tesseract  3.05.02
imagedata.cpp
Go to the documentation of this file.
1 // File: imagedata.h
3 // Description: Class to hold information about a single multi-page tiff
4 // training file and its corresponding boxes or text file.
5 // Author: Ray Smith
6 // Created: Tue May 28 08:56:06 PST 2013
7 //
8 // (C) Copyright 2013, Google Inc.
9 // Licensed under the Apache License, Version 2.0 (the "License");
10 // you may not use this file except in compliance with the License.
11 // You may obtain a copy of the License at
12 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 
20 // Include automatically generated configuration file if running autoconf.
21 #ifdef HAVE_CONFIG_H
22 #include "config_auto.h"
23 #endif
24 
25 #include "imagedata.h"
26 
27 #include "allheaders.h"
28 #include "boxread.h"
29 #include "callcpp.h"
30 #include "helpers.h"
31 #include "tprintf.h"
32 
33 #if defined(__MINGW32__)
34 # include <unistd.h>
35 #elif __cplusplus > 199711L // in C++11
36 # include <thread>
37 #endif
38 
39 // Number of documents to read ahead while training. Doesn't need to be very
40 // large.
41 const int kMaxReadAhead = 8;
42 
43 namespace tesseract {
44 
45 WordFeature::WordFeature() : x_(0), y_(0), dir_(0) {
46 }
47 
49  : x_(IntCastRounded(fcoord.x())),
50  y_(ClipToRange(IntCastRounded(fcoord.y()), 0, MAX_UINT8)),
51  dir_(dir) {
52 }
53 
54 // Computes the maximum x and y value in the features.
56  int* max_x, int* max_y) {
57  *max_x = 0;
58  *max_y = 0;
59  for (int f = 0; f < features.size(); ++f) {
60  if (features[f].x_ > *max_x) *max_x = features[f].x_;
61  if (features[f].y_ > *max_y) *max_y = features[f].y_;
62  }
63 }
64 
65 // Draws the features in the given window.
67  ScrollView* window) {
68 #ifndef GRAPHICS_DISABLED
69  for (int f = 0; f < features.size(); ++f) {
70  FCOORD pos(features[f].x_, features[f].y_);
71  FCOORD dir;
72  dir.from_direction(features[f].dir_);
73  dir *= 8.0f;
74  window->SetCursor(IntCastRounded(pos.x() - dir.x()),
75  IntCastRounded(pos.y() - dir.y()));
76  window->DrawTo(IntCastRounded(pos.x() + dir.x()),
77  IntCastRounded(pos.y() + dir.y()));
78  }
79 #endif
80 }
81 
82 // Writes to the given file. Returns false in case of error.
83 bool WordFeature::Serialize(FILE* fp) const {
84  if (fwrite(&x_, sizeof(x_), 1, fp) != 1) return false;
85  if (fwrite(&y_, sizeof(y_), 1, fp) != 1) return false;
86  if (fwrite(&dir_, sizeof(dir_), 1, fp) != 1) return false;
87  return true;
88 }
89 // Reads from the given file. Returns false in case of error.
90 // If swap is true, assumes a big/little-endian swap is needed.
91 bool WordFeature::DeSerialize(bool swap, FILE* fp) {
92  if (fread(&x_, sizeof(x_), 1, fp) != 1) return false;
93  if (swap) ReverseN(&x_, sizeof(x_));
94  if (fread(&y_, sizeof(y_), 1, fp) != 1) return false;
95  if (fread(&dir_, sizeof(dir_), 1, fp) != 1) return false;
96  return true;
97 }
98 
100  const GenericVector<WordFeature>& word_features,
101  GenericVector<FloatWordFeature>* float_features) {
102  for (int i = 0; i < word_features.size(); ++i) {
104  f.x = word_features[i].x();
105  f.y = word_features[i].y();
106  f.dir = word_features[i].dir();
107  f.x_bucket = 0; // Will set it later.
108  float_features->push_back(f);
109  }
110 }
111 
112 // Sort function to sort first by x-bucket, then by y.
113 /* static */
114 int FloatWordFeature::SortByXBucket(const void* v1, const void* v2) {
115  const FloatWordFeature* f1 = reinterpret_cast<const FloatWordFeature*>(v1);
116  const FloatWordFeature* f2 = reinterpret_cast<const FloatWordFeature*>(v2);
117  int x_diff = f1->x_bucket - f2->x_bucket;
118  if (x_diff == 0) return f1->y - f2->y;
119  return x_diff;
120 }
121 
122 ImageData::ImageData() : page_number_(-1), vertical_text_(false) {
123 }
124 // Takes ownership of the pix and destroys it.
125 ImageData::ImageData(bool vertical, Pix* pix)
126  : page_number_(0), vertical_text_(vertical) {
127  SetPix(pix);
128 }
130 }
131 
132 // Builds and returns an ImageData from the basic data. Note that imagedata,
133 // truth_text, and box_text are all the actual file data, NOT filenames.
134 ImageData* ImageData::Build(const char* name, int page_number, const char* lang,
135  const char* imagedata, int imagedatasize,
136  const char* truth_text, const char* box_text) {
137  ImageData* image_data = new ImageData();
138  image_data->imagefilename_ = name;
139  image_data->page_number_ = page_number;
140  image_data->language_ = lang;
141  // Save the imagedata.
142  image_data->image_data_.resize_no_init(imagedatasize);
143  memcpy(&image_data->image_data_[0], imagedata, imagedatasize);
144  if (!image_data->AddBoxes(box_text)) {
145  if (truth_text == NULL || truth_text[0] == '\0') {
146  tprintf("Error: No text corresponding to page %d from image %s!\n",
147  page_number, name);
148  delete image_data;
149  return NULL;
150  }
151  image_data->transcription_ = truth_text;
152  // If we have no boxes, the transcription is in the 0th box_texts_.
153  image_data->box_texts_.push_back(truth_text);
154  // We will create a box for the whole image on PreScale, to save unpacking
155  // the image now.
156  } else if (truth_text != NULL && truth_text[0] != '\0' &&
157  image_data->transcription_ != truth_text) {
158  // Save the truth text as it is present and disagrees with the box text.
159  image_data->transcription_ = truth_text;
160  }
161  return image_data;
162 }
163 
164 // Writes to the given file. Returns false in case of error.
165 bool ImageData::Serialize(TFile* fp) const {
166  if (!imagefilename_.Serialize(fp)) return false;
167  if (fp->FWrite(&page_number_, sizeof(page_number_), 1) != 1) return false;
168  if (!image_data_.Serialize(fp)) return false;
169  if (!transcription_.Serialize(fp)) return false;
170  // WARNING: Will not work across different endian machines.
171  if (!boxes_.Serialize(fp)) return false;
172  if (!box_texts_.SerializeClasses(fp)) return false;
173  inT8 vertical = vertical_text_;
174  if (fp->FWrite(&vertical, sizeof(vertical), 1) != 1) return false;
175  return true;
176 }
177 
178 // Reads from the given file. Returns false in case of error.
179 // If swap is true, assumes a big/little-endian swap is needed.
180 bool ImageData::DeSerialize(bool swap, TFile* fp) {
181  if (!imagefilename_.DeSerialize(swap, fp)) return false;
182  if (fp->FRead(&page_number_, sizeof(page_number_), 1) != 1) return false;
183  if (swap) ReverseN(&page_number_, sizeof(page_number_));
184  if (!image_data_.DeSerialize(swap, fp)) return false;
185  if (!transcription_.DeSerialize(swap, fp)) return false;
186  // WARNING: Will not work across different endian machines.
187  if (!boxes_.DeSerialize(swap, fp)) return false;
188  if (!box_texts_.DeSerializeClasses(swap, fp)) return false;
189  inT8 vertical = 0;
190  if (fp->FRead(&vertical, sizeof(vertical), 1) != 1) return false;
191  vertical_text_ = vertical != 0;
192  return true;
193 }
194 
195 // As DeSerialize, but only seeks past the data - hence a static method.
196 bool ImageData::SkipDeSerialize(bool swap, TFile* fp) {
197  if (!STRING::SkipDeSerialize(swap, fp)) return false;
199  if (fp->FRead(&page_number, sizeof(page_number), 1) != 1) return false;
200  if (!GenericVector<char>::SkipDeSerialize(swap, fp)) return false;
201  if (!STRING::SkipDeSerialize(swap, fp)) return false;
202  if (!GenericVector<TBOX>::SkipDeSerialize(swap, fp)) return false;
203  if (!GenericVector<STRING>::SkipDeSerializeClasses(swap, fp)) return false;
204  inT8 vertical = 0;
205  return fp->FRead(&vertical, sizeof(vertical), 1) == 1;
206 }
207 
208 // Saves the given Pix as a PNG-encoded string and destroys it.
209 void ImageData::SetPix(Pix* pix) {
210  SetPixInternal(pix, &image_data_);
211 }
212 
213 // Returns the Pix image for *this. Must be pixDestroyed after use.
214 Pix* ImageData::GetPix() const {
215  return GetPixInternal(image_data_);
216 }
217 
218 // Gets anything and everything with a non-NULL pointer, prescaled to a
219 // given target_height (if 0, then the original image height), and aligned.
220 // Also returns (if not NULL) the width and height of the scaled image.
221 // The return value is the scaled Pix, which must be pixDestroyed after use,
222 // and scale_factor (if not NULL) is set to the scale factor that was applied
223 // to the image to achieve the target_height.
224 Pix* ImageData::PreScale(int target_height, int max_height, float* scale_factor,
225  int* scaled_width, int* scaled_height,
226  GenericVector<TBOX>* boxes) const {
227  int input_width = 0;
228  int input_height = 0;
229  Pix* src_pix = GetPix();
230  ASSERT_HOST(src_pix != NULL);
231  input_width = pixGetWidth(src_pix);
232  input_height = pixGetHeight(src_pix);
233  if (target_height == 0) {
234  target_height = MIN(input_height, max_height);
235  }
236  float im_factor = static_cast<float>(target_height) / input_height;
237  if (scaled_width != NULL)
238  *scaled_width = IntCastRounded(im_factor * input_width);
239  if (scaled_height != NULL)
240  *scaled_height = target_height;
241  // Get the scaled image.
242  Pix* pix = pixScale(src_pix, im_factor, im_factor);
243  if (pix == NULL) {
244  tprintf("Scaling pix of size %d, %d by factor %g made null pix!!\n",
245  input_width, input_height, im_factor);
246  }
247  if (scaled_width != NULL) *scaled_width = pixGetWidth(pix);
248  if (scaled_height != NULL) *scaled_height = pixGetHeight(pix);
249  pixDestroy(&src_pix);
250  if (boxes != NULL) {
251  // Get the boxes.
252  boxes->truncate(0);
253  for (int b = 0; b < boxes_.size(); ++b) {
254  TBOX box = boxes_[b];
255  box.scale(im_factor);
256  boxes->push_back(box);
257  }
258  if (boxes->empty()) {
259  // Make a single box for the whole image.
260  TBOX box(0, 0, im_factor * input_width, target_height);
261  boxes->push_back(box);
262  }
263  }
264  if (scale_factor != NULL) *scale_factor = im_factor;
265  return pix;
266 }
267 
269  return image_data_.size();
270 }
271 
272 // Draws the data in a new window.
273 void ImageData::Display() const {
274 #ifndef GRAPHICS_DISABLED
275  const int kTextSize = 64;
276  // Draw the image.
277  Pix* pix = GetPix();
278  if (pix == NULL) return;
279  int width = pixGetWidth(pix);
280  int height = pixGetHeight(pix);
281  ScrollView* win = new ScrollView("Imagedata", 100, 100,
282  2 * (width + 2 * kTextSize),
283  2 * (height + 4 * kTextSize),
284  width + 10, height + 3 * kTextSize, true);
285  win->Image(pix, 0, height - 1);
286  pixDestroy(&pix);
287  // Draw the boxes.
288  win->Pen(ScrollView::RED);
289  win->Brush(ScrollView::NONE);
290  int text_size = kTextSize;
291  if (!boxes_.empty() && boxes_[0].height() * 2 < text_size)
292  text_size = boxes_[0].height() * 2;
293  win->TextAttributes("Arial", text_size, false, false, false);
294  if (!boxes_.empty()) {
295  for (int b = 0; b < boxes_.size(); ++b) {
296  boxes_[b].plot(win);
297  win->Text(boxes_[b].left(), height + kTextSize, box_texts_[b].string());
298  }
299  } else {
300  // The full transcription.
301  win->Pen(ScrollView::CYAN);
302  win->Text(0, height + kTextSize * 2, transcription_.string());
303  }
304  win->Update();
305  window_wait(win);
306 #endif
307 }
308 
309 // Adds the supplied boxes and transcriptions that correspond to the correct
310 // page number.
312  const GenericVector<STRING>& texts,
313  const GenericVector<int>& box_pages) {
314  // Copy the boxes and make the transcription.
315  for (int i = 0; i < box_pages.size(); ++i) {
316  if (page_number_ >= 0 && box_pages[i] != page_number_) continue;
317  transcription_ += texts[i];
318  boxes_.push_back(boxes[i]);
319  box_texts_.push_back(texts[i]);
320  }
321 }
322 
323 // Saves the given Pix as a PNG-encoded string and destroys it.
324 void ImageData::SetPixInternal(Pix* pix, GenericVector<char>* image_data) {
325  l_uint8* data;
326  size_t size;
327  pixWriteMem(&data, &size, pix, IFF_PNG);
328  pixDestroy(&pix);
329  image_data->resize_no_init(size);
330  memcpy(&(*image_data)[0], data, size);
331  free(data);
332 }
333 
334 // Returns the Pix image for the image_data. Must be pixDestroyed after use.
335 Pix* ImageData::GetPixInternal(const GenericVector<char>& image_data) {
336  Pix* pix = NULL;
337  if (!image_data.empty()) {
338  // Convert the array to an image.
339  const unsigned char* u_data =
340  reinterpret_cast<const unsigned char*>(&image_data[0]);
341  pix = pixReadMem(u_data, image_data.size());
342  }
343  return pix;
344 }
345 
346 // Parses the text string as a box file and adds any discovered boxes that
347 // match the page number. Returns false on error.
348 bool ImageData::AddBoxes(const char* box_text) {
349  if (box_text != NULL && box_text[0] != '\0') {
351  GenericVector<STRING> texts;
352  GenericVector<int> box_pages;
353  if (ReadMemBoxes(page_number_, false, box_text, &boxes,
354  &texts, NULL, &box_pages)) {
355  AddBoxes(boxes, texts, box_pages);
356  return true;
357  } else {
358  tprintf("Error: No boxes for page %d from image %s!\n",
359  page_number_, imagefilename_.string());
360  }
361  }
362  return false;
363 }
364 
365 // Thread function to call ReCachePages.
366 void* ReCachePagesFunc(void* data) {
367  DocumentData* document_data = reinterpret_cast<DocumentData*>(data);
368  document_data->ReCachePages();
369  return NULL;
370 }
371 
373  : document_name_(name),
374  pages_offset_(-1),
375  total_pages_(-1),
376  memory_used_(0),
377  max_memory_(0),
378  reader_(NULL) {}
379 
381  SVAutoLock lock_p(&pages_mutex_);
382  SVAutoLock lock_g(&general_mutex_);
383 }
384 
385 // Reads all the pages in the given lstmf filename to the cache. The reader
386 // is used to read the file.
387 bool DocumentData::LoadDocument(const char* filename, const char* lang,
388  int start_page, inT64 max_memory,
389  FileReader reader) {
390  SetDocument(filename, lang, max_memory, reader);
391  pages_offset_ = start_page;
392  return ReCachePages();
393 }
394 
395 // Sets up the document, without actually loading it.
396 void DocumentData::SetDocument(const char* filename, const char* lang,
397  inT64 max_memory, FileReader reader) {
398  SVAutoLock lock_p(&pages_mutex_);
399  SVAutoLock lock(&general_mutex_);
400  document_name_ = filename;
401  lang_ = lang;
402  pages_offset_ = -1;
403  max_memory_ = max_memory;
404  reader_ = reader;
405 }
406 
407 // Writes all the pages to the given filename. Returns false on error.
408 bool DocumentData::SaveDocument(const char* filename, FileWriter writer) {
409  SVAutoLock lock(&pages_mutex_);
410  TFile fp;
411  fp.OpenWrite(NULL);
412  if (!pages_.Serialize(&fp) || !fp.CloseWrite(filename, writer)) {
413  tprintf("Serialize failed: %s\n", filename);
414  return false;
415  }
416  return true;
417 }
419  SVAutoLock lock(&pages_mutex_);
420  TFile fp;
421  fp.OpenWrite(buffer);
422  return pages_.Serialize(&fp);
423 }
424 
425 // Adds the given page data to this document, counting up memory.
427  SVAutoLock lock(&pages_mutex_);
428  pages_.push_back(page);
429  set_memory_used(memory_used() + page->MemoryUsed());
430 }
431 
432 // If the given index is not currently loaded, loads it using a separate
433 // thread.
435  ImageData* page = NULL;
436  if (IsPageAvailable(index, &page)) return;
437  SVAutoLock lock(&pages_mutex_);
438  if (pages_offset_ == index) return;
439  pages_offset_ = index;
440  pages_.clear();
441  #ifndef GRAPHICS_DISABLED
443  #endif // GRAPHICS_DISABLED
444 }
445 
446 // Returns a pointer to the page with the given index, modulo the total
447 // number of pages. Blocks until the background load is completed.
448 const ImageData* DocumentData::GetPage(int index) {
449  ImageData* page = NULL;
450  while (!IsPageAvailable(index, &page)) {
451  // If there is no background load scheduled, schedule one now.
452  pages_mutex_.Lock();
453  bool needs_loading = pages_offset_ != index;
454  pages_mutex_.Unlock();
455  if (needs_loading) LoadPageInBackground(index);
456  // We can't directly load the page, or the background load will delete it
457  // while the caller is using it, so give it a chance to work.
458 #if __cplusplus > 199711L && !defined(__MINGW32__)
459  std::this_thread::sleep_for(std::chrono::seconds(1));
460 #elif _WIN32 // MSVS
461  Sleep(1000);
462 #else
463  sleep(1);
464 #endif
465  }
466  return page;
467 }
468 
469 // Returns true if the requested page is available, and provides a pointer,
470 // which may be NULL if the document is empty. May block, even though it
471 // doesn't guarantee to return true.
472 bool DocumentData::IsPageAvailable(int index, ImageData** page) {
473  SVAutoLock lock(&pages_mutex_);
474  int num_pages = NumPages();
475  if (num_pages == 0 || index < 0) {
476  *page = NULL; // Empty Document.
477  return true;
478  }
479  if (num_pages > 0) {
480  index = Modulo(index, num_pages);
481  if (pages_offset_ <= index && index < pages_offset_ + pages_.size()) {
482  *page = pages_[index - pages_offset_]; // Page is available already.
483  return true;
484  }
485  }
486  return false;
487 }
488 
489 // Removes all pages from memory and frees the memory, but does not forget
490 // the document metadata.
492  SVAutoLock lock(&pages_mutex_);
493  inT64 memory_saved = memory_used();
494  pages_.clear();
495  pages_offset_ = -1;
496  set_total_pages(-1);
497  set_memory_used(0);
498  tprintf("Unloaded document %s, saving %d memory\n", document_name_.string(),
499  memory_saved);
500  return memory_saved;
501 }
502 
503 // Locks the pages_mutex_ and Loads as many pages can fit in max_memory_
504 // starting at index pages_offset_.
505 bool DocumentData::ReCachePages() {
506  SVAutoLock lock(&pages_mutex_);
507  // Read the file.
508  set_total_pages(0);
509  set_memory_used(0);
510  int loaded_pages = 0;
511  pages_.truncate(0);
512  TFile fp;
513  if (!fp.Open(document_name_, reader_) ||
514  !PointerVector<ImageData>::DeSerializeSize(false, &fp, &loaded_pages) ||
515  loaded_pages <= 0) {
516  tprintf("Deserialize header failed: %s\n", document_name_.string());
517  return false;
518  }
519  pages_offset_ %= loaded_pages;
520  // Skip pages before the first one we want, and load the rest until max
521  // memory and skip the rest after that.
522  int page;
523  for (page = 0; page < loaded_pages; ++page) {
524  if (page < pages_offset_ ||
525  (max_memory_ > 0 && memory_used() > max_memory_)) {
526  if (!PointerVector<ImageData>::DeSerializeSkip(false, &fp)) break;
527  } else {
528  if (!pages_.DeSerializeElement(false, &fp)) break;
529  ImageData* image_data = pages_.back();
530  if (image_data->imagefilename().length() == 0) {
531  image_data->set_imagefilename(document_name_);
532  image_data->set_page_number(page);
533  }
534  image_data->set_language(lang_);
535  set_memory_used(memory_used() + image_data->MemoryUsed());
536  }
537  }
538  if (page < loaded_pages) {
539  tprintf("Deserialize failed: %s read %d/%d pages\n",
540  document_name_.string(), page, loaded_pages);
541  pages_.truncate(0);
542  } else {
543  tprintf("Loaded %d/%d pages (%d-%d) of document %s\n", pages_.size(),
544  loaded_pages, pages_offset_, pages_offset_ + pages_.size(),
545  document_name_.string());
546  }
547  set_total_pages(loaded_pages);
548  return !pages_.empty();
549 }
550 
551 // A collection of DocumentData that knows roughly how much memory it is using.
553  : num_pages_per_doc_(0), max_memory_(max_memory) {}
555 
556 // Adds all the documents in the list of filenames, counting memory.
557 // The reader is used to read the files.
559  const char* lang,
560  CachingStrategy cache_strategy,
561  FileReader reader) {
562  cache_strategy_ = cache_strategy;
563  inT64 fair_share_memory = 0;
564  // In the round-robin case, each DocumentData handles restricting its content
565  // to its fair share of memory. In the sequential case, DocumentCache
566  // determines which DocumentDatas are held entirely in memory.
567  if (cache_strategy_ == CS_ROUND_ROBIN)
568  fair_share_memory = max_memory_ / filenames.size();
569  for (int arg = 0; arg < filenames.size(); ++arg) {
570  STRING filename = filenames[arg];
571  DocumentData* document = new DocumentData(filename);
572  document->SetDocument(filename.string(), lang, fair_share_memory, reader);
573  AddToCache(document);
574  }
575  if (!documents_.empty()) {
576  // Try to get the first page now to verify the list of filenames.
577  if (GetPageBySerial(0) != NULL) return true;
578  tprintf("Load of page 0 failed!\n");
579  }
580  return false;
581 }
582 
583 // Adds document to the cache.
585  inT64 new_memory = data->memory_used();
586  documents_.push_back(data);
587  return true;
588 }
589 
590 // Finds and returns a document by name.
591 DocumentData* DocumentCache::FindDocument(const STRING& document_name) const {
592  for (int i = 0; i < documents_.size(); ++i) {
593  if (documents_[i]->document_name() == document_name)
594  return documents_[i];
595  }
596  return NULL;
597 }
598 
599 // Returns the total number of pages in an epoch. For CS_ROUND_ROBIN cache
600 // strategy, could take a long time.
602  if (cache_strategy_ == CS_SEQUENTIAL) {
603  // In sequential mode, we assume each doc has the same number of pages
604  // whether it is true or not.
605  if (num_pages_per_doc_ == 0) GetPageSequential(0);
606  return num_pages_per_doc_ * documents_.size();
607  }
608  int total_pages = 0;
609  int num_docs = documents_.size();
610  for (int d = 0; d < num_docs; ++d) {
611  // We have to load a page to make NumPages() valid.
612  documents_[d]->GetPage(0);
613  total_pages += documents_[d]->NumPages();
614  }
615  return total_pages;
616 }
617 
618 // Returns a page by serial number, selecting them in a round-robin fashion
619 // from all the documents. Highly disk-intensive, but doesn't need samples
620 // to be shuffled between files to begin with.
621 const ImageData* DocumentCache::GetPageRoundRobin(int serial) {
622  int num_docs = documents_.size();
623  int doc_index = serial % num_docs;
624  const ImageData* doc = documents_[doc_index]->GetPage(serial / num_docs);
625  for (int offset = 1; offset <= kMaxReadAhead && offset < num_docs; ++offset) {
626  doc_index = (serial + offset) % num_docs;
627  int page = (serial + offset) / num_docs;
628  documents_[doc_index]->LoadPageInBackground(page);
629  }
630  return doc;
631 }
632 
633 // Returns a page by serial number, selecting them in sequence from each file.
634 // Requires the samples to be shuffled between the files to give a random or
635 // uniform distribution of data. Less disk-intensive than GetPageRoundRobin.
636 const ImageData* DocumentCache::GetPageSequential(int serial) {
637  int num_docs = documents_.size();
638  ASSERT_HOST(num_docs > 0);
639  if (num_pages_per_doc_ == 0) {
640  // Use the pages in the first doc as the number of pages in each doc.
641  documents_[0]->GetPage(0);
642  num_pages_per_doc_ = documents_[0]->NumPages();
643  if (num_pages_per_doc_ == 0) {
644  tprintf("First document cannot be empty!!\n");
645  ASSERT_HOST(num_pages_per_doc_ > 0);
646  }
647  // Get rid of zero now if we don't need it.
648  if (serial / num_pages_per_doc_ % num_docs > 0) documents_[0]->UnCache();
649  }
650  int doc_index = serial / num_pages_per_doc_ % num_docs;
651  const ImageData* doc =
652  documents_[doc_index]->GetPage(serial % num_pages_per_doc_);
653  // Count up total memory. Background loading makes it more complicated to
654  // keep a running count.
655  inT64 total_memory = 0;
656  for (int d = 0; d < num_docs; ++d) {
657  total_memory += documents_[d]->memory_used();
658  }
659  if (total_memory >= max_memory_) {
660  // Find something to un-cache.
661  // If there are more than 3 in front, then serial is from the back reader
662  // of a pair of readers. If we un-cache from in-front-2 to 2-ahead, then
663  // we create a hole between them and then un-caching the backmost occupied
664  // will work for both.
665  int num_in_front = CountNeighbourDocs(doc_index, 1);
666  for (int offset = num_in_front - 2;
667  offset > 1 && total_memory >= max_memory_; --offset) {
668  int next_index = (doc_index + offset) % num_docs;
669  total_memory -= documents_[next_index]->UnCache();
670  }
671  // If that didn't work, the best solution is to un-cache from the back. If
672  // we take away the document that a 2nd reader is using, it will put it
673  // back and make a hole between.
674  int num_behind = CountNeighbourDocs(doc_index, -1);
675  for (int offset = num_behind; offset < 0 && total_memory >= max_memory_;
676  ++offset) {
677  int next_index = (doc_index + offset + num_docs) % num_docs;
678  total_memory -= documents_[next_index]->UnCache();
679  }
680  }
681  int next_index = (doc_index + 1) % num_docs;
682  if (!documents_[next_index]->IsCached() && total_memory < max_memory_) {
683  documents_[next_index]->LoadPageInBackground(0);
684  }
685  return doc;
686 }
687 
688 // Helper counts the number of adjacent cached neighbours of index looking in
689 // direction dir, ie index+dir, index+2*dir etc.
690 int DocumentCache::CountNeighbourDocs(int index, int dir) {
691  int num_docs = documents_.size();
692  for (int offset = dir; abs(offset) < num_docs; offset += dir) {
693  int offset_index = (index + offset + num_docs) % num_docs;
694  if (!documents_[offset_index]->IsCached()) return offset - dir;
695  }
696  return num_docs;
697 }
698 
699 } // namespace tesseract.
const ImageData * GetPageBySerial(int serial)
Definition: imagedata.h:337
void SetPix(Pix *pix)
Definition: imagedata.cpp:209
void DrawTo(int x, int y)
Definition: scrollview.cpp:531
void Image(struct Pix *image, int x_pos, int y_pos)
Definition: scrollview.cpp:773
static void ComputeSize(const GenericVector< WordFeature > &features, int *max_x, int *max_y)
Definition: imagedata.cpp:55
Pix * GetPix() const
Definition: imagedata.cpp:214
bool LoadDocument(const char *filename, const char *lang, int start_page, inT64 max_memory, FileReader reader)
Definition: imagedata.cpp:387
void scale(const float f)
Definition: rect.h:171
int IntCastRounded(double x)
Definition: helpers.h:172
bool SaveDocument(const char *filename, FileWriter writer)
Definition: imagedata.cpp:408
void resize_no_init(int size)
Definition: genericvector.h:66
static bool DeSerializeSkip(bool swap, TFile *fp)
static void Update()
Definition: scrollview.cpp:715
bool SaveToBuffer(GenericVector< char > *buffer)
Definition: imagedata.cpp:418
static void Draw(const GenericVector< WordFeature > &features, ScrollView *window)
Definition: imagedata.cpp:66
int FWrite(const void *buffer, int size, int count)
Definition: serialis.cpp:131
void SetCursor(int x, int y)
Definition: scrollview.cpp:525
friend void * ReCachePagesFunc(void *data)
Definition: imagedata.cpp:366
int NumPages() const
Definition: imagedata.h:229
void SetDocument(const char *filename, const char *lang, inT64 max_memory, FileReader reader)
Definition: imagedata.cpp:396
const int kMaxReadAhead
Definition: imagedata.cpp:41
bool Open(const STRING &filename, FileReader reader)
Definition: serialis.cpp:35
const GenericVector< TBOX > & boxes() const
Definition: imagedata.h:149
#define MIN(x, y)
Definition: ndminx.h:28
static bool SkipDeSerialize(bool swap, tesseract::TFile *fp)
Definition: strngs.cpp:185
bool DeSerialize(bool swap, FILE *fp)
Definition: imagedata.cpp:91
T ClipToRange(const T &x, const T &lower_bound, const T &upper_bound)
Definition: helpers.h:115
unsigned char uinT8
Definition: host.h:32
void TextAttributes(const char *font, int pixel_size, bool bold, bool italic, bool underlined)
Definition: scrollview.cpp:641
void Brush(Color color)
Definition: scrollview.cpp:732
bool DeSerializeClasses(bool swap, FILE *fp)
bool DeSerialize(bool swap, FILE *fp)
Definition: strngs.cpp:163
const GenericVector< char > & image_data() const
Definition: imagedata.h:137
bool Serialize(FILE *fp) const
int push_back(T object)
bool Serialize(TFile *fp) const
Definition: imagedata.cpp:165
void * ReCachePagesFunc(void *data)
Definition: imagedata.cpp:366
void Text(int x, int y, const char *mystring)
Definition: scrollview.cpp:658
const ImageData * GetPage(int index)
Definition: imagedata.cpp:448
bool LoadDocuments(const GenericVector< STRING > &filenames, const char *lang, CachingStrategy cache_strategy, FileReader reader)
Definition: imagedata.cpp:558
const char * string() const
Definition: strngs.cpp:201
#define MAX_UINT8
Definition: host.h:54
bool CloseWrite(const STRING &filename, FileWriter writer)
Definition: serialis.cpp:123
DocumentCache(inT64 max_memory)
Definition: imagedata.cpp:552
static ImageData * Build(const char *name, int page_number, const char *lang, const char *imagedata, int imagedatasize, const char *truth_text, const char *box_text)
Definition: imagedata.cpp:134
bool AddToCache(DocumentData *data)
Definition: imagedata.cpp:584
void LoadPageInBackground(int index)
Definition: imagedata.cpp:434
int FRead(void *buffer, int size, int count)
Definition: serialis.cpp:91
CachingStrategy
Definition: imagedata.h:40
bool IsPageAvailable(int index, ImageData **page)
Definition: imagedata.cpp:472
SIGNED char inT8
Definition: host.h:31
long long int inT64
Definition: host.h:41
void Pen(Color color)
Definition: scrollview.cpp:726
float y() const
Definition: points.h:212
void Display() const
Definition: imagedata.cpp:273
void truncate(int size)
int page_number() const
Definition: imagedata.h:131
void Lock()
Locks on a mutex.
Definition: svutil.cpp:70
bool Serialize(FILE *fp) const
Definition: imagedata.cpp:83
DocumentData(const STRING &name)
Definition: imagedata.cpp:372
int inT32
Definition: host.h:35
#define tprintf(...)
Definition: tprintf.h:31
static int SortByXBucket(const void *, const void *)
Definition: imagedata.cpp:114
Definition: strngs.h:44
int size() const
Definition: genericvector.h:72
Definition: points.h:189
bool ReadMemBoxes(int target_page, bool skip_blanks, const char *box_data, GenericVector< TBOX > *boxes, GenericVector< STRING > *texts, GenericVector< STRING > *box_texts, GenericVector< int > *pages)
Definition: boxread.cpp:65
const STRING & box_text(int index) const
Definition: imagedata.h:155
bool DeSerialize(bool swap, TFile *fp)
Definition: imagedata.cpp:180
bool Serialize(FILE *fp) const
Definition: strngs.cpp:148
void OpenWrite(GenericVector< char > *data)
Definition: serialis.cpp:109
Pix * PreScale(int target_height, int max_height, float *scale_factor, int *scaled_width, int *scaled_height, GenericVector< TBOX > *boxes) const
Definition: imagedata.cpp:224
void AddBoxes(const GenericVector< TBOX > &boxes, const GenericVector< STRING > &texts, const GenericVector< int > &box_pages)
Definition: imagedata.cpp:311
int Modulo(int a, int b)
Definition: helpers.h:157
inT64 memory_used() const
Definition: imagedata.h:233
float x() const
Definition: points.h:209
static bool DeSerializeSize(bool swap, TFile *fp, inT32 *size)
bool SerializeClasses(FILE *fp) const
void Unlock()
Unlocks on a mutex.
Definition: svutil.cpp:78
void AddPageToDocument(ImageData *page)
Definition: imagedata.cpp:426
Definition: rect.h:30
static void FromWordFeatures(const GenericVector< WordFeature > &word_features, GenericVector< FloatWordFeature > *float_features)
Definition: imagedata.cpp:99
int MemoryUsed() const
Definition: imagedata.cpp:268
bool(* FileReader)(const STRING &filename, GenericVector< char > *data)
char window_wait(ScrollView *win)
Definition: callcpp.cpp:111
bool empty() const
Definition: genericvector.h:84
void ReverseN(void *ptr, int num_bytes)
Definition: helpers.h:177
#define ASSERT_HOST(x)
Definition: errcode.h:84
static bool SkipDeSerialize(bool swap, tesseract::TFile *fp)
Definition: imagedata.cpp:196
DocumentData * FindDocument(const STRING &document_name) const
Definition: imagedata.cpp:591
static void StartThread(void *(*func)(void *), void *arg)
Create new thread.
Definition: svutil.cpp:192
bool(* FileWriter)(const GenericVector< char > &data, const STRING &filename)
bool DeSerialize(bool swap, FILE *fp)