-
Notifications
You must be signed in to change notification settings - Fork 18
/
imgdb.cpp
2070 lines (1736 loc) · 64.9 KB
/
imgdb.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************\
imgdb.cpp - iqdb library implementation
Copyright (C) 2008 [email protected]
Originally based on imgSeek code, these portions
Copyright (C) 2003 Ricardo Niederberger Cabral.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
\**************************************************************************/
/* System includes */
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <ctime>
#include <limits>
/* STL includes */
#include <algorithm>
#include <vector>
/* iqdb includes */
#include "imgdb.h"
#include "imglib.h"
#include "debug.h"
extern int debug_level;
namespace imgdb {
// Globals
//keywordsMapType globalKwdsMap;
Score weights[2][6][3];
/* Fixed weight mask for pixel positions (i,j).
Each entry x = i*NUM_PIXELS + j, gets value max(i,j) saturated at 5.
To be treated as a constant.
*/
unsigned char imgBin[NUM_PIXELS*NUM_PIXELS];
int imgBinInited = 0;
unsigned int random_bloom_seed = 0;
const static bool is_disk_db = true;
static size_t pageSize = 0;
static size_t pageMask = 0;
static size_t pageImgs = 0;
static size_t pageImgMask = 0;
/* Endianness */
#if CONV_LE && (__BIG_ENDIAN__ || _BIG_ENDIAN || BIG_ENDIAN)
#define CONV_ENDIAN 1
#else
#define CONV_ENDIAN 0
#endif
#if CONV_ENDIAN
#define FLIP(x) flip_endian(x)
#define FLIPPED(x) flipped_endian(x)
#else
#define FLIP(x)
#define FLIPPED(x) (x)
#endif
template<typename T>
void flip_endian(T& v) {
//if (sizeof(T) != 4) throw fatal_error("Can't flip this endian.");
union { T _v; char _c[sizeof(T)]; } c; c._v = v;
for (char* one = c._c, * two = c._c + sizeof(T) - 1; one < two; one++, two--) {
char t = *one; *one = *two; *two = t;
}
v = c._v;
};
template<typename T>
T flipped_endian(T& v) {
T f = v;
flip_endian(f);
return f;
}
//typedef std::priority_queue < KwdFrequencyStruct > kwdFreqPriorityQueue;
mapped_file::mapped_file(const char* fname, bool writable) {
int fd = open(fname, writable ? O_RDWR : O_RDONLY);
struct stat st;
if (fd == -1 || fstat(fd, &st) || (m_base = (unsigned char*) mmap(NULL, m_length = st.st_size, writable ? PROT_READ | PROT_WRITE : PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED)
throw image_error("Can't open/stat/map file.");
close(fd);
}
inline void mapped_file::unmap() {
if (!m_base) return;
if (munmap(m_base, m_length))
DEBUG(errors)("WARNING: Could not unmap %zd bytes of memory.\n", m_length);
}
int tempfile() {
char tempnam[] = "/tmp/imgdb_cache.XXXXXXX";
int fd = mkstemp(tempnam);
if (fd == -1) throw io_error(std::string("Can't open cache file ")+tempnam+": "+strerror(errno));
if (unlink(tempnam))
DEBUG(errors)("WARNING: Can't unlink cache file %s: %s.", tempnam, strerror(errno));
return fd;
}
template<bool is_simple>
int imageIdIndex_list<is_simple, false>::m_fd = -1;
template<>
template<bool is_simple>
void imageIdIndex_list<is_simple, false>::resize(size_t s) {
if (!is_simple) s = (s + pageImgMask) & ~pageImgMask;
if (s <= m_capacity) return;
if (m_fd == -1) m_fd = tempfile();
size_t toadd = s - m_capacity;
off_t page = lseek(m_fd, 0, SEEK_CUR);
//fprintf(stderr, "%zd/%zd entries at %llx=", toadd, s, page);
m_baseofs = page & pageMask;
size_t len = toadd * sizeof(imageId);
m_capacity += len / sizeof(imageId);
if (m_baseofs & (sizeof(imageId) - 1)) throw internal_error("Mis-aligned file position.");
if (!is_simple && m_baseofs) throw internal_error("Base offset in write mode.");
page &= ~pageMask;
//fprintf(stderr, "%llx:%zx, %zd bytes=%zd.\n", page, m_baseofs, len, m_capacity);
if (ftruncate(m_fd, lseek(m_fd, len, SEEK_CUR))) throw io_error("Failed to resize bucket map file.");
m_pages.push_back(imageIdPage(page, len));
}
template<>
imageIdIndex_map<true> imageIdIndex_list<true, false>::map_all(bool writable) {
//fprintf(stderr, "Mapping... write=%d size=%zd+%zd=%zd/%zd. %zd pages. ", writable, m_size, m_tail.size(), size(), m_capacity, m_pages.size());
if (!writable && !size()) return imageIdIndex_map<true>();
if (!writable && m_pages.empty()) {
//fprintf(stderr, "Using fake map of tail data.\n");
return imageIdIndex_map<true>();
}
imageIdPage& page = m_pages.front();
size_t length = page.second + m_baseofs;
//fprintf(stderr, "Directly mapping %zd bytes. ", length);
void* base = mmap(NULL, length, PROT_READ|PROT_WRITE, MAP_SHARED, m_fd, page.first);
if (base == MAP_FAILED) throw memory_error("Failed to mmap bucket.");
return imageIdIndex_map<true>(base, (size_t*)(((char*)base)+m_baseofs), (size_t*)(((char*)base)+m_baseofs)+m_size, length);
}
template<>
imageIdIndex_map<false> imageIdIndex_list<false, false>::map_all(bool writable) {
if (!writable && !size()) return imageIdIndex_map<false>();
if (!writable && m_pages.empty()) {
//fprintf(stderr, "Using fake map of tail data.\n");
return imageIdIndex_map<false>();
}
while (writable && !m_tail.empty()) page_out();
if (m_baseofs) throw internal_error("Base offset in write mode.");
size_t len = m_capacity * sizeof(imageId);
len = (len + pageMask) & ~pageMask;
//fprintf(stderr, "Making full map of %zd bytes. ", len);
void* base = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
if (base == MAP_FAILED) throw memory_error("Failed to mmap bucket.");
imageIdIndex_map<false> mapret(base, (image_id_index*)base, (image_id_index*)base+m_capacity, len);
char* chunk = (char*) base;
for (page_list::iterator itr = m_pages.begin(); itr != m_pages.end(); ++itr) {
//fprintf(stderr, "Using %zd bytes from ofs %llx. ", itr->second, (long long int) itr->first);
void* map = mmap(chunk, itr->second, PROT_READ|PROT_WRITE, MAP_FIXED|MAP_SHARED, m_fd, itr->first);
if (map == MAP_FAILED) { mapret.unmap(); throw memory_error("Failed to mmap bucket chunk."); }
chunk += itr->second;
}
return mapret;
}
template<bool is_simple>
void imageIdIndex_list<is_simple, false>::page_out() {
//fprintf(stderr, "Tail has %zd/%zd values. Capacity %zd. Paging out. ", m_tail.size(), size(), m_capacity);
size_t last = m_size & pageImgMask;
//fprintf(stderr, "Last page has %zd/%zd(%zd), ", last, m_size, m_capacity);
if (!last) resize(size());
imageIdPage page = m_pages.back();
if (((size() + pageImgMask) & ~pageImgMask) != m_capacity) {
//fprintf(stderr, "Need middle page for %zd(%zd)/%zd.", m_size, (size() + pageImgMask) & ~pageImgMask, m_capacity);
size_t ofs = last;
for (page_list::iterator itr = m_pages.begin(); itr != m_pages.end(); ++itr) {
page = *itr;
//fprintf(stderr, " %zd@%llx", page.second / sizeof(imageId), (long long int) page.first);
while (page.second && m_size > ofs) {
ofs += pageImgs;
page.first += pageSize;
page.second -= pageSize;
}
if (ofs >= m_size) break;
}
//fprintf(stderr, " -> %llx = %zd. ", (long long int) page.first, ofs);
if (ofs != m_size) throw internal_error("Counted pages badly.");
} else {
//fprintf(stderr, "map @%llx/%zd. ", (long long int) page.first + page.second - pageSize, page.second);
page.first += page.second - pageSize;
}
image_id_index* ptr = (image_id_index*) mmap(NULL, pageSize, PROT_READ|PROT_WRITE, MAP_SHARED, m_fd, page.first);
if (ptr == MAP_FAILED) throw memory_error("Failed to map tail page.");
size_t copy = std::min(m_tail.size(), pageImgs - last);
//fprintf(stderr, "Fits %zd, ", copy);
memcpy(ptr + last, &m_tail.front(), copy * sizeof(imageId));
m_size += copy;
if (copy == m_tail.size()) {
m_tail.clear();
//fprintf(stderr, "has all. Now %zd.\n", size());
} else {
m_tail.erase(m_tail.begin(), m_tail.begin() + copy);
//fprintf(stderr, "Only fits %zd, %zd left = %zd.\n", copy, m_tail.size(), size());
}
if (munmap(ptr, pageSize))
DEBUG(errors)("WARNING: Failed to munmap tail page.\n");
}
template<>
void imageIdIndex_list<false, false>::remove(image_id_index i) {
if (!size()) return;
//fprintf(stderr, "Removing %lx from %zd/%zd(%zd). ", i.id, m_tail.size(), m_size, m_capacity);
IdIndex_list::iterator itr = std::find_if(m_tail.begin(), m_tail.end(), std::bind2nd(std::equal_to<image_id_index>(), i));
if (itr != m_tail.end()) {
//fprintf(stderr, "Found in tail at %d/%zd.\n", itr - m_tail.begin(), m_tail.size());
*itr = m_tail.back();
m_tail.pop_back();
return;
}
AutoImageIdIndex_map<false> map(map_all(false));
imageIdIndex_map<false>::iterator mItr = map.begin();
while (mItr != map.end() && *mItr != i) ++mItr;
if (mItr != map.end()) {
if (*mItr != i) throw internal_error("Huh???");
//fprintf(stderr, "Found at %zd/%zd.\n", ofs, m_size);
if (!m_tail.empty()) {
*mItr = m_tail.back();
m_tail.pop_back();
} else {
imageIdIndex_map<false>::iterator last = map.end();
--last;
*mItr = *last;
m_size--;
}
}
//else fprintf(stderr, "NOT FOUND!!!\n");
}
//template<>
void imageIdIndex_list<true, true>::set_base() {
if (!m_base.empty()) return;
#ifdef USE_DELTA_QUEUE
if (m_tail.base_size() * 17 / 16 + 16 < m_tail.base_capacity()) {
container copy;
copy.reserve(m_tail.base_size(), true);
for (container::iterator itr = m_tail.begin(); itr != m_tail.end(); ++itr)
copy.push_back(*itr);
m_base.swap(copy);
copy = container();
m_tail.swap(copy);
} else {
m_base.swap(m_tail);
}
#else
m_base.swap(m_tail);
#endif
}
int dbSpace::mode_from_name(const char* mode_name) {
if (!strcmp(mode_name, "normal"))
return imgdb::dbSpace::mode_normal;
else if (!strcmp(mode_name, "readonly"))
return imgdb::dbSpace::mode_readonly;
else if (!strcmp(mode_name, "simple"))
return imgdb::dbSpace::mode_simple;
else if (!strcmp(mode_name, "alter"))
return imgdb::dbSpace::mode_alter;
else if (!strcmp(mode_name, "imgdata"))
return imgdb::dbSpace::mode_imgdata;
else
throw param_error("Unknown mode name.");
}
// Specializations accessing images as SigStruct* or size_t map, and imageIdIndex_map as imageId or index map.
template<> inline dbSpaceImpl<false>::imageIterator dbSpaceImpl<false>::image_begin() { return imageIterator(m_images.begin(), *this); }
template<> inline dbSpaceImpl<false>::imageIterator dbSpaceImpl<false>::image_end() { return imageIterator(m_images.end(), *this); }
template<> inline dbSpaceImpl<true>::imageIterator dbSpaceImpl<true>::image_begin() { return imageIterator(m_info.begin(), *this); }
template<> inline dbSpaceImpl<true>::imageIterator dbSpaceImpl<true>::image_end() { return imageIterator(m_info.end(), *this); }
template<bool is_simple>
inline typename dbSpaceImpl<is_simple>::imageIterator dbSpaceImpl<is_simple>::find(imageId i) {
map_iterator itr = m_images.find(i);
if (itr == m_images.end()) throw invalid_id("Invalid image ID.");
return imageIterator(itr, *this);
}
inline dbSpaceAlter::ImageMap::iterator dbSpaceAlter::find(imageId i) {
ImageMap::iterator itr = m_images.find(i);
if (itr == m_images.end()) throw invalid_id("Invalid image ID.");
return itr;
}
static const size_t no_cacheOfs = ~size_t();
void initImgBin()
{
imgBinInited = 1;
srand((unsigned)time(0));
pageSize = sysconf(_SC_PAGESIZE);
pageMask = pageSize - 1;
pageImgs = pageSize / sizeof(imageId);
pageImgMask = pageMask / sizeof(imageId);
//fprintf(stderr, "page size = %zx, page mask = %zx.\n", pageSize, pageMask);
/* setup initial fixed weights that each coefficient represents */
int i, j;
/*
0 1 2 3 4 5 6 i
0 0 1 2 3 4 5 5
1 1 1 2 3 4 5 5
2 2 2 2 3 4 5 5
3 3 3 3 3 4 5 5
4 4 4 4 4 4 5 5
5 5 5 5 5 5 5 5
5 5 5 5 5 5 5 5
j
*/
/* Every position has value 5, */
memset(imgBin, 5, NUM_PIXELS_SQUARED);
/* Except for the 5 by 5 upper-left quadrant: */
for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++)
imgBin[i * NUM_PIXELS + j] = std::max(i, j);
// Note: imgBin[0] == 0
/* Integer weights. */
for (i = 0; i < 2; i++)
for (j = 0; j < 6; j++)
for (int c = 0; c < 3; c++)
weights[i][j][c] = lrint(weightsf[i][j][c] * ScoreMax);
}
template<bool is_simple>
bool dbSpaceImpl<is_simple>::hasImage(imageId id) {
return m_images.find(id) != m_images.end();
}
bool dbSpaceAlter::hasImage(imageId id) {
return m_images.find(id) != m_images.end();
}
template<bool is_simple>
inline ImgData dbSpaceImpl<is_simple>::get_sig_from_cache(imageId id) {
if (is_simple && m_sigFile == -1) throw usage_error("Not supported in simple mode.");
ImgData sig;
read_sig_cache(find(id).cOfs(), &sig);
return sig;
}
inline ImgData dbSpaceAlter::get_sig(size_t ind) {
ImgData sig;
m_f->seekg(m_sigOff + ind * sizeof(ImgData));
m_f->read(&sig);
return sig;
}
template<bool is_simple>
int dbSpaceImpl<is_simple>::getImageWidth(imageId id) {
return find(id).width();
}
template<bool is_simple>
int dbSpaceImpl<is_simple>::getImageHeight(imageId id) {
return find(id).height();
}
int dbSpaceAlter::getImageWidth(imageId id) {
return get_sig(find(id)->second).width;
}
int dbSpaceAlter::getImageHeight(imageId id) {
return get_sig(find(id)->second).height;
}
inline bool dbSpaceCommon::is_grayscale(const lumin_int& avgl) {
return abs(avgl[1]) + abs(avgl[2]) < ScoreMax * 6 / 1000;
}
bool dbSpaceCommon::isImageGrayscale(imageId id) {
lumin_int avgl;
getImgAvgl(id, avgl);
return is_grayscale(avgl);
}
void dbSpaceCommon::sigFromImage(Image* image, imageId id, ImgData* sig) {
AutoCleanArray<unsigned char> rchan(NUM_PIXELS*NUM_PIXELS);
AutoCleanArray<unsigned char> gchan(NUM_PIXELS*NUM_PIXELS);
AutoCleanArray<unsigned char> bchan(NUM_PIXELS*NUM_PIXELS);
#if LIB_ImageMagick
AutoExceptionInfo exception;
/*
Initialize the image info structure and read an image.
*/
sig->id = id;
sig->width = image->columns;
sig->height = image->rows;
//resize_image = SampleImage(image, NUM_PIXELS, NUM_PIXELS, &exception);
Image* resize_image = NULL;
if (image->columns != NUM_PIXELS || image->rows != NUM_PIXELS) {
resize_image = ResizeImage(image, NUM_PIXELS, NUM_PIXELS, TriangleFilter, 1.0, &exception);
if (!resize_image)
throw image_error("Unable to resize image.");
image = resize_image;
}
// To clean up resize_image on return or exceptions.
AutoImage resize_image_auto(resize_image);
const PixelPacket *pixel_cache = AcquireImagePixels(image, 0, 0, NUM_PIXELS, NUM_PIXELS, &exception);
for (int idx = 0; idx < NUM_PIXELS*NUM_PIXELS; idx++) {
rchan[idx] = pixel_cache->red >> (QuantumDepth - 8);
gchan[idx] = pixel_cache->green >> (QuantumDepth - 8);
bchan[idx] = pixel_cache->blue >> (QuantumDepth - 8);
pixel_cache++;
}
#elif LIB_GD
sig->id = id;
sig->width = image->sx;
sig->height = image->sy;
AutoGDImage resized;
if (image->sx != NUM_PIXELS || image->sy != NUM_PIXELS || !gdImageTrueColor(image)) {
resized.set(gdImageCreateTrueColor(NUM_PIXELS, NUM_PIXELS));
gdImageFilledRectangle(resized, 0, 0, NUM_PIXELS, NUM_PIXELS, gdTrueColor(255, 255, 255));
gdImageCopyResampled(resized, image, 0, 0, 0, 0, NUM_PIXELS, NUM_PIXELS, image->sx, image->sy);
image = resized;
}
unsigned char* red = rchan.ptr(), *green = gchan.ptr(), *blue = bchan.ptr();
for (int** row = image->tpixels; row < image->tpixels + NUM_PIXELS; row++)
for (int* col = *row, *end = *row + NUM_PIXELS; col < end; col++) {
*red++ = gdTrueColorGetRed(*col);
*green++ = gdTrueColorGetGreen(*col);
*blue++ = gdTrueColorGetBlue(*col);
}
#else
# error Unsupported image library.
#endif
AutoCleanArray<Unit> cdata1(NUM_PIXELS*NUM_PIXELS);
AutoCleanArray<Unit> cdata2(NUM_PIXELS*NUM_PIXELS);
AutoCleanArray<Unit> cdata3(NUM_PIXELS*NUM_PIXELS);
transformChar(rchan.ptr(), gchan.ptr(), bchan.ptr(), cdata1.ptr(), cdata2.ptr(), cdata3.ptr());
calcHaar(cdata1.ptr(), cdata2.ptr(), cdata3.ptr(), sig->sig1, sig->sig2, sig->sig3, sig->avglf);
}
template<typename B>
inline void dbSpaceCommon::bucket_set<B>::add(const ImgData& nsig, count_t index) {
lumin_int avgl;
SigStruct::avglf2i(nsig.avglf, avgl);
for (int i = 0; i < NUM_COEFS; i++) { // populate buckets
#ifdef FAST_POW_GEERT
int x, t;
// sig[i] never 0
int x, t;
x = nsig.sig1[i];
t = (x < 0); /* t = 1 if x neg else 0 */
/* x - 0 ^ 0 = x; i - 1 ^ 0b111..1111 = 2-compl(x) = -x */
x = (x - t) ^ -t;
buckets[0][t][x].add(nsig.id, index);
if (is_grayscale(avg))
continue; // ignore I/Q coeff's if chrominance too low
x = nsig.sig2[i];
t = (x < 0);
x = (x - t) ^ -t;
buckets[1][t][x].add(nsig.id, index);
x = nsig.sig3[i];
t = (x < 0);
x = (x - t) ^ -t;
buckets[2][t][x].add(nsig.id, index);
should not fail
#else //FAST_POW_GEERT
//imageId_array3 (imgbuckets = dbSpace[dbId]->(imgbuckets;
if (nsig.sig1[i]>0) buckets[0][0][nsig.sig1[i]].add(nsig.id, index);
if (nsig.sig1[i]<0) buckets[0][1][-nsig.sig1[i]].add(nsig.id, index);
if (is_grayscale(avgl))
continue; // ignore I/Q coeff's if chrominance too low
if (nsig.sig2[i]>0) buckets[1][0][nsig.sig2[i]].add(nsig.id, index);
if (nsig.sig2[i]<0) buckets[1][1][-nsig.sig2[i]].add(nsig.id, index);
if (nsig.sig3[i]>0) buckets[2][0][nsig.sig3[i]].add(nsig.id, index);
if (nsig.sig3[i]<0) buckets[2][1][-nsig.sig3[i]].add(nsig.id, index);
#endif //FAST_POW_GEERT
}
}
template<typename B>
inline B& dbSpaceCommon::bucket_set<B>::at(int col, int coeff, int* idxret) {
int pn, idx;
//TODO see if FAST_POW_GEERT gives the same results
#ifdef FAST_POW_GEERT
pn = coeff < 0;
idx = (coeff - pn) ^ -pn;
#else
pn = 0;
if (coeff>0) {
pn = 0;
idx = coeff;
} else {
pn = 1;
idx = -coeff;
}
#endif
if (idxret) *idxret = idx;
return buckets[col][pn][idx];
}
template<>
void dbSpaceImpl<false>::addImageData(const ImgData* img) {
if (hasImage(img->id)) // image already in db
throw duplicate_id("Image already in database.");
SigStruct *nsig = new SigStruct(get_sig_cache());
nsig->init(img);
write_sig_cache(nsig->cacheOfs, img);
// insert into sigmap
m_images.add_sig(img->id, nsig);
// insert into ids bloom filter
//imgIdsFilter->insert(id);
imgbuckets.add(*img, m_nextIndex++);
}
template<>
void dbSpaceImpl<true>::addImageData(const ImgData* img) {
if (hasImage(img->id)) // image already in db
throw duplicate_id("Image already in database.");
size_t ind = m_nextIndex++;
if (ind > m_info.size())
throw internal_error("Index incremented too much!");
if (ind == m_info.size()) {
if (ind >= m_info.capacity()) m_info.reserve(10 + ind + ind / 40);
m_info.resize(ind+1);
}
m_info.at(ind).id = img->id;
SigStruct::avglf2i(img->avglf, m_info[ind].avgl);
m_info[ind].width = img->width;
m_info[ind].height = img->height;
m_images.add_index(img->id, ind);
if (m_sigFile != -1) {
size_t ofs = get_sig_cache();
if (ofs != ind * sizeof(ImgData)) throw internal_error("Index and cache out of sync!");
write_sig_cache(ofs, img);
}
imgbuckets.add(*img, ind);
}
void dbSpaceAlter::addImageData(const ImgData* img) {
if (m_readonly)
throw usage_error("Not possible in imgdata mode.");
if (hasImage(img->id)) // image already in db
throw duplicate_id("Image already in database.");
size_t ind;
if (!m_deleted.empty()) {
ind = m_deleted.back();
m_deleted.pop_back();
} else {
ind = m_images.size();
if (m_imgOff + ((off_t)ind + 1) * (off_t)sizeof(imageId) >= m_sigOff) {
resize_header();
if (m_imgOff + ((off_t)ind + 1) * (off_t)sizeof(imageId) >= m_sigOff)
throw internal_error("resize_header failed!");
}
}
if (!m_rewriteIDs) {
m_f->seekp(m_imgOff + ind * sizeof(imageId));
m_f->write(img->id);
}
m_f->seekp(m_sigOff + ind * sizeof(ImgData));
m_f->write(*img);
m_buckets.add(*img, ind);
m_images[img->id] = ind;
}
#if LIB_ImageMagick
inline void check_image(Image* image) {
if (!image) // unable to read image
throw image_error("Unable to read image data.");
if (image->colorspace != RGBColorspace)
throw image_error("Invalid color space.");
if (image->storage_class != DirectClass) {
SyncImage(image);
SetImageType(image, TrueColorType);
SyncImage(image);
}
}
void dbSpaceCommon::addImageBlob(imageId id, const void *blob, size_t length) {
if (hasImage(id)) // image already in db
throw duplicate_id("Image already in database.");
AutoExceptionInfo exception;
AutoImageInfo image_info;
AutoImage image(BlobToImage(image_info, blob, length, &exception));
if (exception.severity != UndefinedException) CatchException(&exception);
check_image(image);
ImgData sig;
sigFromImage(image, id, &sig);
return addImageData(&sig);
}
void dbSpaceCommon::imgDataFromFile(const char* filename, imageId id, ImgData* img) {
AutoExceptionInfo exception;
AutoImageInfo image_info;
strcpy(image_info->filename, filename);
AutoImage image(ReadImage(image_info, &exception));
if (exception.severity != UndefinedException) CatchException(&exception);
check_image(image);
sigFromImage(image, id, img);
}
void dbSpaceCommon::imgDataFromBlob(const void* data, size_t data_size, imageId id, ImgData* img) {
AutoExceptionInfo exception;
AutoImageInfo image_info;
AutoImage image(BlobToImage(image_info, data, data_size, &exception));
if (exception.severity != UndefinedException) CatchException(&exception);
check_image(image);
sigFromImage(image, id, img);
}
#elif LIB_GD
void dbSpaceCommon::addImageBlob(imageId id, const void *blob, size_t length) {
if (hasImage(id)) // image already in db
throw duplicate_id("Image already in database.");
::image_info info;
get_image_info((const unsigned char*) blob, length, &info);
AutoGDImage image(resize_image_data((const unsigned char*) blob, length, NUM_PIXELS, NUM_PIXELS, true));
ImgData sig;
sigFromImage(image, id, &sig);
return addImageData(&sig);
}
void dbSpaceCommon::imgDataFromFile(const char* filename, imageId id, ImgData* img) {
AutoClean<mapped_file, &mapped_file::unmap> map(mapped_file(filename, false));
AutoGDImage image(resize_image_data((const unsigned char*) map.m_base, map.m_length, NUM_PIXELS, NUM_PIXELS, true));
sigFromImage(image, id, img);
}
void dbSpaceCommon::imgDataFromBlob(const void* data, size_t data_size, imageId id, ImgData* img) {
::image_info info;
get_image_info((const unsigned char*) data, data_size, &info);
AutoGDImage image(resize_image_data((const unsigned char*) data, data_size, NUM_PIXELS, NUM_PIXELS, true));
sigFromImage(image, id, img);
}
#endif
void dbSpaceCommon::addImage(imageId id, const char *filename) {
if (hasImage(id)) // image already in db
throw duplicate_id("Image already in database.");
ImgData sig;
imgDataFromFile(filename, id, &sig);
return addImageData(&sig);
}
void dbSpace::imgDataFromFile(const char* filename, imageId id, ImgData* img) {
return dbSpaceCommon::imgDataFromFile(filename, id, img);
}
void dbSpace::imgDataFromBlob(const void* data, size_t data_size, imageId id, ImgData* img) {
return dbSpaceCommon::imgDataFromBlob(data, data_size, id, img);
}
template<>
void dbSpaceImpl<false>::setImageRes(imageId id, int width, int height) {
imageIterator itr = find(id);
ImgData sig;
read_sig_cache(itr.cOfs(), &sig);
sig.width = width;
sig.height = height;
write_sig_cache(itr.cOfs(), &sig);
}
template<> void dbSpaceImpl<true>::setImageRes(imageId id, int width, int height) {
imageIterator itr = find(id);
itr->width = width;
itr->height = height;
}
void dbSpaceAlter::setImageRes(imageId id, int width, int height) {
if (m_readonly)
throw usage_error("Not possible in imgdata mode.");
size_t ind = find(id)->second;
ImgData sig = get_sig(ind);
m_f->seekg(m_sigOff + ind * sizeof(ImgData));
m_f->read(&sig);
sig.width = width;
sig.height = height;
m_f->seekp(m_sigOff + ind * sizeof(ImgData));
m_f->write(sig);
}
template<bool is_simple>
void dbSpaceImpl<is_simple>::load(const char* filename) {
db_ifstream f(filename);
if (!f.is_open()) {
DEBUG(warnings)("Unable to open file %s for read ops: %s.\n", filename, strerror(errno));
return;
}
uint32_t v_code = FLIPPED(f.read<uint32_t>());
uint version;
uint32_t intsizes = v_code >> 8;
if (intsizes == 0) {
DEBUG(warnings)("Old database version.\n");
}
version = v_code & 0xff;
// Old version... skip its useless metadata.
if (version == 1) {
version = FLIPPED(f.read<int>());
f.read<int>(); f.read<int>(); f.read<int>();
}
if (version > SRZ_V0_9_0) {
throw data_error("Database from a version after 0.9.0");
} else if (version < SRZ_V0_7_0) {
return load_stream_old(f, version);
} else if (intsizes != SRZ_V_SZ) {
if (CONV_ENDIAN)
throw data_error("Cannot load database with both wrong endianness AND data sizes");
DEBUG(imgdb)("Loading db (converting data sizes)... ");
} else if (version == SRZ_V0_9_0) {
DEBUG(imgdb)("Loading db (cur ver)... ");
} else {
DEBUG(imgdb)("Loading db (old but compatible ver)... ");
}
int size_res = (intsizes >> 0) & 31;
int size_count = (intsizes >> 5) & 31;
int size_offset = (intsizes >> 10) & 31;
int size_imageId = (intsizes >> 15) & 31;
count_t numImg = FLIPPED(f.read_size<count_t>(size_count));
offset_t firstOff = FLIPPED(f.read_size<offset_t>(size_offset));
DEBUG_CONT(imgdb)(DEBUG_OUT, "has %"FMT_count_t" images at %llx. ", numImg, (long long)firstOff);
// read bucket sizes and reserve space so that buckets do not
// waste memory due to exponential growth of std::vector
for (typename buckets_t::iterator itr = imgbuckets.begin(); itr != imgbuckets.end(); ++itr)
itr->reserve(FLIPPED(f.read_size<count_t>(size_count)));
DEBUG_CONT(imgdb)(DEBUG_OUT, "bucket sizes done at %llx... ", (long long)firstOff);
// read IDs (for verification only)
AutoCleanArray<imageId> ids(numImg);
if (sizeof(imageId) == size_imageId) {
f.read(ids.ptr(), numImg);
} else {
for (typename image_map::size_type k = 0; k < numImg; k++)
ids[k] = f.read_size<imageId>(size_imageId);
}
for (typename image_map::size_type k = 0; k < numImg; k++)
FLIP(ids[k]);
// read sigs
f.seekg(firstOff);
if (is_simple) m_info.resize(numImg);
for (typename image_map::size_type k = 0; k < numImg; k++) {
ImgData sig;
if (intsizes == SRZ_V_SZ) {
f.read(&sig);
} else {
memset(&sig, 0, sizeof(sig));
sig.id = f.read_size<imageId>(size_imageId);
f.read(&sig.sig1);
f.read(&sig.sig2);
f.read(&sig.sig3);
f.read(&sig.avglf);
sig.width = f.read_size<res_t>(size_res);
sig.height = f.read_size<res_t>(size_res);
}
FLIP(sig.id); FLIP(sig.width); FLIP(sig.height); FLIP(sig.avglf[0]); FLIP(sig.avglf[1]); FLIP(sig.avglf[2]);
size_t ind = m_nextIndex++;
imgbuckets.add(sig, ind);
if (ids[ind] != sig.id) {
if (is_simple) {
DEBUG_CONT(imgdb)(DEBUG_OUT, "\n");
DEBUG(warnings)("WARNING: index %zd DB header ID %08llx mismatch with sig ID %08llx.", ind, (long long)ids[ind], (long long) sig.id);
} else {
throw data_error("DB header ID mismatch with sig ID.");
}
}
if (is_simple) {
m_info[ind].id = sig.id;
SigStruct::avglf2i(sig.avglf, m_info[ind].avgl);
m_info[ind].width = sig.width;
m_info[ind].height = sig.height;
m_images.add_index(sig.id, ind);
if (m_sigFile != -1) {
size_t ofs = get_sig_cache();
if (ofs != ind * sizeof(ImgData)) throw internal_error("Index and cache out of sync!");
write_sig_cache(ofs, &sig);
}
} else {
SigStruct* nsig = new SigStruct(get_sig_cache());
nsig->init(&sig);
nsig->index = ind;
write_sig_cache(nsig->cacheOfs, &sig);
// insert new sig
m_images.add_sig(sig.id, nsig);
}
}
if (is_simple && is_disk_db)
DEBUG_CONT(imgdb)(DEBUG_OUT, "map size: %lld... ", (long long int) lseek(imgbuckets[0][0][0].fd(), 0, SEEK_CUR));
for (typename buckets_t::iterator itr = imgbuckets.begin(); itr != imgbuckets.end(); ++itr)
itr->set_base();
m_bucketsValid = true;
DEBUG_CONT(imgdb)(DEBUG_OUT, "complete!\n");
f.close();
}
void dbSpaceAlter::load(const char* filename) {
m_f = new db_fstream(filename);
m_fname = filename;
try {
if (!m_f->is_open()) {
// Instead of replicating code here to create the basic file structure, we'll just make a dummy DB.
AutoCleanPtr<dbSpace> dummy(load_file(filename, mode_normal));
dummy->save_file(filename);
dummy.set(NULL);
m_f->open(filename);
if (!m_f->is_open())
throw io_error("Could not create DB structure.");
}
m_f->exceptions(std::fstream::badbit | std::fstream::failbit);
uint32_t v_code = FLIPPED(m_f->read<uint32_t>());
uint version = v_code & 0xff;
if ((v_code >> 8) == 0) {
DEBUG(warnings)("Old database version.\n");
} else if ((v_code >> 8) != SRZ_V_SZ) {
throw data_error("Database incompatible with this system");
}
if (version != SRZ_V0_7_0 && version != SRZ_V0_9_0)
throw data_error("Only current version is supported in alter mode, upgrade first using normal mode.");
DEBUG(imgdb)("Loading db header (cur ver)... ");
m_hdrOff = m_f->tellg();
count_t numImg = FLIPPED(m_f->read<count_t>());
m_sigOff = FLIPPED(m_f->read<offset_t>());
DEBUG_CONT(imgdb)(DEBUG_OUT, "has %"FMT_count_t" images. ", numImg);
// read bucket sizes
for (buckets_t::iterator itr = m_buckets.begin(); itr != m_buckets.end(); ++itr)
itr->size = FLIPPED(m_f->read<count_t>());
// read IDs
m_imgOff = m_f->tellg();
for (size_t k = 0; k < numImg; k++)
m_images[FLIPPED(m_f->read<count_t>())] = k;
m_rewriteIDs = false;
DEBUG_CONT(imgdb)(DEBUG_OUT, "complete!\n");
} catch (const base_error& e) {
if (m_f) {
if (m_f->is_open()) m_f->close();
delete m_f;
m_fname.clear();
}
DEBUG_CONT(imgdb)(DEBUG_OUT, "failed!\n");
throw;
}
}
template<>
void dbSpaceImpl<true>::load_stream_old(db_ifstream& f, uint version) {
throw usage_error("Not supported in read-only mode.");
}
template<>
void dbSpaceImpl<false>::load_stream_old(db_ifstream& f, uint version) {
#ifdef NO_SUPPORT_OLD_VER
throw data_error("Cannot load old database version: NO_SUPPORT_OLD_VER was set.");
#else
static const bool is_simple = false;
DEBUG(imgdb)("Loading db (old ver)... ");
imageId id;
uint sz;
if (version < SRZ_V0_6_0) {
throw data_error("Database from a version prior to 0.6");
} else if (version > SRZ_V0_6_1) {
throw data_error("Database from a version after 0.6.1");
}
// fast-forward to image count
db_ifstream::pos_type old_pos = f.tellg();
m_bucketsValid = true;
for (buckets_t::iterator itr = imgbuckets.begin(); itr != imgbuckets.end(); ++itr) {
sz = FLIPPED(f.read<int>());
if (sz == ~uint()) {
if (itr != imgbuckets.begin()) throw data_error("No-bucket indicator too late.");
m_bucketsValid = false;
DEBUG_CONT(imgdb)(DEBUG_OUT, "NO BUCKETS VERSION! ");
sz = FLIPPED(f.read<int>());
}
if (m_bucketsValid)
f.seekg(sz * sizeof(imageId), f.cur);
}
image_map::size_type szt;
f.read((char *) &(szt), sizeof(szt));
FLIP(szt);
f.seekg(old_pos);
DEBUG_CONT(imgdb)(DEBUG_OUT, "has %zd images. ", szt);
//To discard most common buckets: szt /= 10;
// read buckets
if (!m_bucketsValid)
f.read((char *) &(sz), sizeof(int));
for (buckets_t::iterator itr = imgbuckets.begin(); itr != imgbuckets.end(); ++itr) {
f.read((char *) &(sz), sizeof(int));
FLIP(sz);
if (!sz) continue;
if (!m_bucketsValid) {
itr->reserve(sz);
continue;
}
if (is_simple && sz > szt) {
//fprintf(stderr, "Bucket %d:%d:%d has %d/%zd, ignoring.\n", c, pn, i, sz, szt*10);