1 #ifdef __GNUC__
2 #pragma GCC diagnostic push
3 #pragma GCC diagnostic ignored "-Wsign-compare"
4 #if (__GNUC__ >= 6)
5 #pragma GCC diagnostic ignored "-Wmisleading-indentation"
6 #endif
7 #if (__GNUC__ >= 9)
8 #pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
9 #endif
10 #endif
11 
12 /*RT*/#include <glib.h>
13 /*RT*/#include <glib/gstdio.h>
14 /*RT*/#undef MAX
15 /*RT*/#undef MIN
16 /*RT*/#undef ABS
17 /*RT*/#include "rt_math.h"
18 /*RT*/#define NO_LCMS
19 /*RT*/#define NO_JPEG
20 /*RT*/#define NO_JASPER
21 /*RT*/#define LOCALTIME
22 /*RT*/#define DJGPP
23 /*RT*/#include "jpeg.h"
24 /*RT*/#include "lj92.h"
25 /*RT*/#ifdef _OPENMP
26 /*RT*/#include <omp.h>
27 /*RT*/#endif
28 
29 #include <memory>
30 #include <utility>
31 #include <vector>
32 #include "opthelper.h"
33 //#define BENCHMARK
34 #include "StopWatch.h"
35 #include "utils.h"
36 #include <zlib.h>
37 #include <stdint.h>
38 
39 
40 /*
41    dcraw.c -- Dave Coffin's raw photo decoder
42    Copyright 1997-2018 by Dave Coffin, dcoffin a cybercom o net
43 
44    This is a command-line ANSI C program to convert raw photos from
45    any digital camera on any computer running any operating system.
46 
47    No license is required to download and use dcraw.c.  However,
48    to lawfully redistribute dcraw, you must either (a) offer, at
49    no extra charge, full source code* for all executable files
50    containing RESTRICTED functions, (b) distribute this code under
51    the GPL Version 2 or later, (c) remove all RESTRICTED functions,
52    re-implement them, or copy them from an earlier, unrestricted
53    Revision of dcraw.c, or (d) purchase a license from the author.
54 
55    The functions that process Foveon images have been RESTRICTED
56    since Revision 1.237.  All other code remains free for all uses.
57 
58    *If you have not modified dcraw.c in any way, a link to my
59    homepage qualifies as "full source code".
60 
61    $Revision: 1.478 $
62    $Date: 2018/06/01 20:36:25 $
63  */
64 
65 #define DCRAW_VERSION "9.28"
66 
67 #ifndef _GNU_SOURCE
68 #define _GNU_SOURCE
69 #endif
70 #define _USE_MATH_DEFINES
71 #include <cctype>
72 #include <cerrno>
73 #include <fcntl.h>
74 #include <cfloat>
75 #include <climits>
76 #include <cmath>
77 #include <csetjmp>
78 #include <cstdio>
79 #include <cstdlib>
80 #include <cstring>
81 #include <ctime>
82 #include <strings.h>
83 #include <sys/types.h>
84 
85 #if defined(DJGPP) || defined(__MINGW32__)
86 #define fseeko fseek
87 #define ftello ftell
88 #else
89 #define fgetc getc_unlocked
90 #endif
91 #ifdef __CYGWIN__
92 #include <io.h>
93 #endif
94 #ifdef WIN32
95 #include <sys/utime.h>
96 #include <winsock2.h>
97 #define snprintf _snprintf
98 #define strcasecmp stricmp
99 #define strncasecmp strnicmp
100 typedef __int64 INT64;
101 typedef unsigned __int64 UINT64;
102 #else
103 #include <unistd.h>
104 #include <utime.h>
105 #include <netinet/in.h>
106 typedef long long INT64;
107 typedef unsigned long long UINT64;
108 #endif
109 
110 #ifdef NODEPS
111 #define NO_JASPER
112 #define NO_JPEG
113 #define NO_LCMS
114 #endif
115 #ifndef NO_JASPER
116 #include <jasper/jasper.h>	/* Decode Red camera movies */
117 #endif
118 #ifndef NO_JPEG
119 #include <jpeglib.h>		/* Decode compressed Kodak DC120 photos */
120 #endif				/* and Adobe Lossy DNGs */
121 #ifndef NO_LCMS
122 #include <lcms2.h>		/* Support color profiles */
123 #endif
124 #ifdef LOCALEDIR
125 #include <libintl.h>
126 #define _(String) gettext(String)
127 #else
128 #define _(String) (String)
129 #endif
130 
131 #define ushort UshORt
132 typedef unsigned char uchar;
133 typedef unsigned short ushort;
134 
135 #include "dcraw.h"
136 /*
137    RT All global variables are defined here, and all functions that
138    access them are prefixed with "CLASS".  Note that a thread-safe
139    C++ class cannot have non-const static local variables.
140  */
141 
142 const double xyz_rgb[3][3] = {			// XYZ from RGB
143   { 0.412453, 0.357580, 0.180423 },
144   { 0.212671, 0.715160, 0.072169 },
145   { 0.019334, 0.119193, 0.950227 } };
146 const float d65_white[3] = { 0.950456, 1, 1.088754 };
147 
148 /* RT: Removed unused structs */
149 #define CLASS DCraw::
150 
151 #define FORC(cnt) for (c=0; c < cnt; c++)
152 #define FORC3 FORC(3)
153 #define FORC4 FORC(4)
154 #define FORCC FORC(colors)
155 
156 #define SQR(x) rtengine::SQR(x)
157 #define ABS(x) (((int)(x) ^ ((int)(x) >> 31)) - ((int)(x) >> 31))
158 #define MIN(a,b) rtengine::min(a,static_cast<__typeof__(a)>(b))
159 #define MAX(a,b) rtengine::max(a,static_cast<__typeof__(a)>(b))
160 #define LIM(x,min,max) rtengine::LIM(x,static_cast<__typeof__(x)>(min),static_cast<__typeof__(x)>(max))
161 #define ULIM(x,y,z) rtengine::median(x,static_cast<__typeof__(x)>(y),static_cast<__typeof__(x)>(z))
162 #define CLIP(x) rtengine::CLIP(x)
163 #define SWAP(a,b) { a=a+b; b=a-b; a=a-b; }
164 
165 /*
166    In order to inline this calculation, I make the risky
167    assumption that all filter patterns can be described
168    by a repeating pattern of eight rows and two columns
169 
170    Do not use the FC or BAYER macros with the Leaf CatchLight,
171    because its pattern is 16x16, not 2x8.
172 
173    Return values are either 0/1/2/3 = G/M/C/Y or 0/1/2/3 = R/G1/B/G2
174 
175 	PowerShot 600	PowerShot A50	PowerShot Pro70	Pro90 & G1
176 	0xe1e4e1e4:	0x1b4e4b1e:	0x1e4b4e1b:	0xb4b4b4b4:
177 
178 	  0 1 2 3 4 5	  0 1 2 3 4 5	  0 1 2 3 4 5	  0 1 2 3 4 5
179 	0 G M G M G M	0 C Y C Y C Y	0 Y C Y C Y C	0 G M G M G M
180 	1 C Y C Y C Y	1 M G M G M G	1 M G M G M G	1 Y C Y C Y C
181 	2 M G M G M G	2 Y C Y C Y C	2 C Y C Y C Y
182 	3 C Y C Y C Y	3 G M G M G M	3 G M G M G M
183 			4 C Y C Y C Y	4 Y C Y C Y C
184 	PowerShot A5	5 G M G M G M	5 G M G M G M
185 	0x1e4e1e4e:	6 Y C Y C Y C	6 C Y C Y C Y
186 			7 M G M G M G	7 M G M G M G
187 	  0 1 2 3 4 5
188 	0 C Y C Y C Y
189 	1 G M G M G M
190 	2 C Y C Y C Y
191 	3 M G M G M G
192 
193    All RGB cameras use one of these Bayer grids:
194 
195 	0x16161616:	0x61616161:	0x49494949:	0x94949494:
196 
197 	  0 1 2 3 4 5	  0 1 2 3 4 5	  0 1 2 3 4 5	  0 1 2 3 4 5
198 	0 B G B G B G	0 G R G R G R	0 G B G B G B	0 R G R G R G
199 	1 G R G R G R	1 B G B G B G	1 R G R G R G	1 G B G B G B
200 	2 B G B G B G	2 G R G R G R	2 G B G B G B	2 R G R G R G
201 	3 G R G R G R	3 B G B G B G	3 R G R G R G	3 G B G B G B
202  */
203 
204 #define RAW(row,col) \
205 	raw_image[(row)*raw_width+(col)]
206 
207 #define FC(row,col) \
208 	(filters >> ((((row) << 1 & 14) + ((col) & 1)) << 1) & 3)
209 
210 #define BAYER(row,col) \
211 	image[((row) >> shrink)*iwidth + ((col) >> shrink)][FC(row,col)]
212 
213 #define BAYER2(row,col) \
214 	image[((row) >> shrink)*iwidth + ((col) >> shrink)][fcol(row,col)]
215 
fcol(int row,int col)216 int CLASS fcol (int row, int col)
217 {
218   static const char filter[16][16] =
219   { { 2,1,1,3,2,3,2,0,3,2,3,0,1,2,1,0 },
220     { 0,3,0,2,0,1,3,1,0,1,1,2,0,3,3,2 },
221     { 2,3,3,2,3,1,1,3,3,1,2,1,2,0,0,3 },
222     { 0,1,0,1,0,2,0,2,2,0,3,0,1,3,2,1 },
223     { 3,1,1,2,0,1,0,2,1,3,1,3,0,1,3,0 },
224     { 2,0,0,3,3,2,3,1,2,0,2,0,3,2,2,1 },
225     { 2,3,3,1,2,1,2,1,2,1,1,2,3,0,0,1 },
226     { 1,0,0,2,3,0,0,3,0,3,0,3,2,1,2,3 },
227     { 2,3,3,1,1,2,1,0,3,2,3,0,2,3,1,3 },
228     { 1,0,2,0,3,0,3,2,0,1,1,2,0,1,0,2 },
229     { 0,1,1,3,3,2,2,1,1,3,3,0,2,1,3,2 },
230     { 2,3,2,0,0,1,3,0,2,0,1,2,3,0,1,0 },
231     { 1,3,1,2,3,2,3,2,0,2,0,1,1,0,3,0 },
232     { 0,2,0,3,1,0,0,1,1,3,3,2,3,2,2,1 },
233     { 2,1,3,2,3,1,2,1,0,3,0,2,0,2,0,2 },
234     { 0,3,1,0,0,2,0,3,2,1,3,1,1,3,1,3 } };
235 
236   if (filters == 1) return filter[(row+top_margin)&15][(col+left_margin)&15];
237   if (filters == 9) return xtrans[(row+6) % 6][(col+6) % 6];
238 
239   return FC(row,col);
240 }
241 
242 #ifndef __GLIBC__
my_memmem(char * haystack,size_t haystacklen,const char * needle,size_t needlelen)243 char *my_memmem (char *haystack, size_t haystacklen,
244 	      const char *needle, size_t needlelen)
245 {
246   char *c;
247   for (c = haystack; c <= haystack + haystacklen - needlelen; c++)
248     if (!memcmp (c, needle, needlelen))
249       return c;
250   return 0;
251 }
252 #define memmem my_memmem
my_strcasestr(char * haystack,const char * needle)253 char *my_strcasestr (char *haystack, const char *needle)
254 {
255   char *c;
256   for (c = haystack; *c; c++)
257     if (!strncasecmp(c, needle, strlen(needle)))
258       return c;
259   return 0;
260 }
261 #define strcasestr my_strcasestr
262 #endif
263 
merror(void * ptr,const char * where)264 void CLASS merror (void *ptr, const char *where)
265 {
266   if (ptr) return;
267   fprintf (stderr,_("%s: Out of memory in %s\n"), ifname, where);
268   longjmp (failure, 1);
269 }
270 
derror()271 void CLASS derror()
272 {
273   if (!data_error) {
274     fprintf (stderr, "%s: ", ifname);
275     if (feof(ifp))
276       fprintf (stderr,_("Unexpected end of file\n"));
277     else
278 #ifdef WIN32
279       fprintf (stderr,_("Corrupt data near 0x%I64x\n"), (INT64) ftello(ifp));
280 #else
281       fprintf (stderr,_("Corrupt data near 0x%llx\n"), (INT64) ftello(ifp));
282 #endif
283   }
284   data_error++;
285 /*RT Issue 2467  longjmp (failure, 1);*/
286 }
287 
sget2(uchar * s)288 ushort CLASS sget2 (uchar *s)
289 {
290   if (order == 0x4949)		/* "II" means little-endian */
291     return s[0] | s[1] << 8;
292   else				/* "MM" means big-endian */
293     return s[0] << 8 | s[1];
294 }
295 
get2()296 ushort CLASS get2()
297 {
298   uchar str[2] = { 0xff,0xff };
299   fread (str, 1, 2, ifp);
300   return sget2(str);
301 }
302 
sget4(uchar * s)303 unsigned CLASS sget4 (uchar *s)
304 {
305   if (order == 0x4949)
306     return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24;
307   else
308     return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3];
309 }
310 #define sget4(s) sget4((uchar *)s)
311 
get4()312 unsigned CLASS get4()
313 {
314   uchar str[4] = { 0xff,0xff,0xff,0xff };
315   fread (str, 1, 4, ifp);
316   return sget4(str);
317 }
318 
getint(int type)319 unsigned CLASS getint (int type)
320 {
321   return type == 3 ? get2() : get4();
322 }
323 
int_to_float(int i)324 float CLASS int_to_float (int i)
325 {
326   union { int i; float f; } u;
327   u.i = i;
328   return u.f;
329 }
330 
getreal(int type)331 double CLASS getreal (int type)
332 {
333   union { char c[8]; double d; } u;
334   int i, rev;
335 
336   switch (type) {
337     case 3: return (unsigned short) get2();
338     case 4: return (unsigned int) get4();
339     case 5:  u.d = (unsigned int) get4();
340       return u.d / (unsigned int) get4();
341     case 8: return (signed short) get2();
342     case 9: return (signed int) get4();
343     case 10: u.d = (signed int) get4();
344       return u.d / (signed int) get4();
345     case 11: return int_to_float (get4());
346     case 12:
347       rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234));
348       for (i=0; i < 8; i++)
349 	u.c[i ^ rev] = fgetc(ifp);
350       return u.d;
351     default: return fgetc(ifp);
352   }
353 }
354 
read_shorts(ushort * pixel,int count)355 void CLASS read_shorts (ushort *pixel, int count)
356 {
357   if (fread (pixel, 2, count, ifp) < count) derror();
358   if ((order == 0x4949) == (ntohs(0x1234) == 0x1234))
359 	  rtengine::swab ((char*)pixel, (char*)pixel, count*2);
360 }
361 
cubic_spline(const int * x_,const int * y_,const int len)362 void CLASS cubic_spline (const int *x_, const int *y_, const int len)
363 {
364   float **A, *b, *c, *d, *x, *y;
365   int i, j;
366 
367   A = (float **) calloc (((2*len + 4)*sizeof **A + sizeof *A), 2*len);
368   if (!A) return;
369   A[0] = (float *) (A + 2*len);
370   for (i = 1; i < 2*len; i++)
371     A[i] = A[0] + 2*len*i;
372   y = len + (x = i + (d = i + (c = i + (b = A[0] + i*i))));
373   for (i = 0; i < len; i++) {
374     x[i] = x_[i] / 65535.0;
375     y[i] = y_[i] / 65535.0;
376   }
377   for (i = len-1; i > 0; i--) {
378     b[i] = (y[i] - y[i-1]) / (x[i] - x[i-1]);
379     d[i-1] = x[i] - x[i-1];
380   }
381   for (i = 1; i < len-1; i++) {
382     A[i][i] = 2 * (d[i-1] + d[i]);
383     if (i > 1) {
384       A[i][i-1] = d[i-1];
385       A[i-1][i] = d[i-1];
386     }
387     A[i][len-1] = 6 * (b[i+1] - b[i]);
388   }
389   for(i = 1; i < len-2; i++) {
390     float v = A[i+1][i] / A[i][i];
391     for(j = 1; j <= len-1; j++)
392       A[i+1][j] -= v * A[i][j];
393   }
394   for(i = len-2; i > 0; i--) {
395     float acc = 0;
396     for(j = i; j <= len-2; j++)
397       acc += A[i][j]*c[j];
398     c[i] = (A[i][len-1] - acc) / A[i][i];
399   }
400   for (i = 0; i < 0x10000; i++) {
401     float x_out = (float)(i / 65535.0);
402     float y_out = 0;
403     for (j = 0; j < len-1; j++) {
404       if (x[j] <= x_out && x_out <= x[j+1]) {
405 	float v = x_out - x[j];
406 	y_out = y[j] +
407 	  ((y[j+1] - y[j]) / d[j] - (2 * d[j] * c[j] + c[j+1] * d[j])/6) * v
408 	   + (c[j] * 0.5) * v*v + ((c[j+1] - c[j]) / (6 * d[j])) * v*v*v;
409       }
410     }
411     curve[i] = y_out < 0.0 ? 0 : (y_out >= 1.0 ? 65535 :
412 		(ushort)(y_out * 65535.0 + 0.5));
413   }
414   free (A);
415 }
416 
canon_600_fixed_wb(int temp)417 void CLASS canon_600_fixed_wb (int temp)
418 {
419   static const short mul[4][5] = {
420     {  667, 358,397,565,452 },
421     {  731, 390,367,499,517 },
422     { 1119, 396,348,448,537 },
423     { 1399, 485,431,508,688 } };
424   int lo, hi, i;
425   float frac=0;
426 
427   for (lo=4; --lo; )
428     if (*mul[lo] <= temp) break;
429   for (hi=0; hi < 3; hi++)
430     if (*mul[hi] >= temp) break;
431   if (lo != hi)
432     frac = (float) (temp - *mul[lo]) / (*mul[hi] - *mul[lo]);
433   for (i=1; i < 5; i++)
434     pre_mul[i-1] = 1 / (frac * mul[hi][i] + (1-frac) * mul[lo][i]);
435 }
436 
437 /* Return values:  0 = white  1 = near white  2 = not white */
canon_600_color(int ratio[2],int mar)438 int CLASS canon_600_color (int ratio[2], int mar)
439 {
440   int clipped=0, target, miss;
441 
442   if (flash_used) {
443     if (ratio[1] < -104)
444       { ratio[1] = -104; clipped = 1; }
445     if (ratio[1] >   12)
446       { ratio[1] =   12; clipped = 1; }
447   } else {
448     if (ratio[1] < -264 || ratio[1] > 461) return 2;
449     if (ratio[1] < -50)
450       { ratio[1] = -50; clipped = 1; }
451     if (ratio[1] > 307)
452       { ratio[1] = 307; clipped = 1; }
453   }
454   target = flash_used || ratio[1] < 197
455 	? -38 - (398 * ratio[1] >> 10)
456 	: -123 + (48 * ratio[1] >> 10);
457   if (target - mar <= ratio[0] &&
458       target + 20  >= ratio[0] && !clipped) return 0;
459   miss = target - ratio[0];
460   if (abs(miss) >= mar*4) return 2;
461   if (miss < -20) miss = -20;
462   if (miss > mar) miss = mar;
463   ratio[0] = target - miss;
464   return 1;
465 }
466 
canon_600_auto_wb()467 void CLASS canon_600_auto_wb()
468 {
469   int mar, row, col, i, j, st, count[] = { 0,0 };
470   int test[8], total[2][8], ratio[2][2], stat[2];
471 
472   memset (&total, 0, sizeof total);
473   i = canon_ev + 0.5;
474   if      (i < 10) mar = 150;
475   else if (i > 12) mar = 20;
476   else mar = 280 - 20 * i;
477   if (flash_used) mar = 80;
478   for (row=14; row < height-14; row+=4)
479     for (col=10; col < width; col+=2) {
480       for (i=0; i < 8; i++)
481 	test[(i & 4) + FC(row+(i >> 1),col+(i & 1))] =
482 		    BAYER(row+(i >> 1),col+(i & 1));
483       for (i=0; i < 8; i++)
484 	if (test[i] < 150 || test[i] > 1500) goto next;
485       for (i=0; i < 4; i++)
486 	if (abs(test[i] - test[i+4]) > 50) goto next;
487       for (i=0; i < 2; i++) {
488 	for (j=0; j < 4; j+=2)
489 	  ratio[i][j >> 1] = ((test[i*4+j+1]-test[i*4+j]) << 10) / test[i*4+j];
490 	stat[i] = canon_600_color (ratio[i], mar);
491       }
492       if ((st = stat[0] | stat[1]) > 1) goto next;
493       for (i=0; i < 2; i++)
494 	if (stat[i])
495 	  for (j=0; j < 2; j++)
496 	    test[i*4+j*2+1] = test[i*4+j*2] * (0x400 + ratio[i][j]) >> 10;
497       for (i=0; i < 8; i++)
498 	total[st][i] += test[i];
499       count[st]++;
500 next: ;
501     }
502   if (count[0] | count[1]) {
503     st = count[0]*200 < count[1];
504     for (i=0; i < 4; i++)
505       pre_mul[i] = 1.0 / (total[st][i] + total[st][i+4]);
506   }
507 }
508 
canon_600_coeff()509 void CLASS canon_600_coeff()
510 {
511   static const short table[6][12] = {
512     { -190,702,-1878,2390,   1861,-1349,905,-393, -432,944,2617,-2105  },
513     { -1203,1715,-1136,1648, 1388,-876,267,245,  -1641,2153,3921,-3409 },
514     { -615,1127,-1563,2075,  1437,-925,509,3,     -756,1268,2519,-2007 },
515     { -190,702,-1886,2398,   2153,-1641,763,-251, -452,964,3040,-2528  },
516     { -190,702,-1878,2390,   1861,-1349,905,-393, -432,944,2617,-2105  },
517     { -807,1319,-1785,2297,  1388,-876,769,-257,  -230,742,2067,-1555  } };
518   int t=0, i, c;
519   float mc, yc;
520 
521   mc = pre_mul[1] / pre_mul[2];
522   yc = pre_mul[3] / pre_mul[2];
523   if (mc > 1 && mc <= 1.28 && yc < 0.8789) t=1;
524   if (mc > 1.28 && mc <= 2) {
525     if  (yc < 0.8789) t=3;
526     else if (yc <= 2) t=4;
527   }
528   if (flash_used) t=5;
529   for (raw_color = i=0; i < 3; i++)
530     FORCC rgb_cam[i][c] = table[t][i*4 + c] / 1024.0;
531 }
532 
canon_600_load_raw()533 void CLASS canon_600_load_raw()
534 {
535   uchar  data[1120], *dp;
536   ushort *pix;
537   int irow, row;
538 
539   for (irow=row=0; irow < height; irow++) {
540     if (fread (data, 1, 1120, ifp) < 1120) derror();
541     pix = raw_image + row*raw_width;
542     for (dp=data; dp < data+1120;  dp+=10, pix+=8) {
543       pix[0] = (dp[0] << 2) + (dp[1] >> 6    );
544       pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3);
545       pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3);
546       pix[3] = (dp[4] << 2) + (dp[1]      & 3);
547       pix[4] = (dp[5] << 2) + (dp[9]      & 3);
548       pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3);
549       pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3);
550       pix[7] = (dp[8] << 2) + (dp[9] >> 6    );
551     }
552     if ((row+=2) > height) row = 1;
553   }
554 }
555 
canon_600_correct()556 void CLASS canon_600_correct()
557 {
558   int row, col, val;
559   static const short mul[4][2] =
560   { { 1141,1145 }, { 1128,1109 }, { 1178,1149 }, { 1128,1109 } };
561 
562   for (row=0; row < height; row++)
563     for (col=0; col < width; col++) {
564       if ((val = BAYER(row,col) - black) < 0) val = 0;
565       val = val * mul[row & 3][col & 1] >> 9;
566       BAYER(row,col) = val;
567     }
568   canon_600_fixed_wb(1311);
569   canon_600_auto_wb();
570   canon_600_coeff();
571   maximum = (0x3ff - black) * 1109 >> 9;
572   black = 0;
573 }
574 
canon_s2is()575 int CLASS canon_s2is()
576 {
577   unsigned row;
578 
579   for (row=0; row < 100; row++) {
580     fseek (ifp, row*3340 + 3284, SEEK_SET);
581     if (getc(ifp) > 15) return 1;
582   }
583   return 0;
584 }
585 
operator ()(int nbits,ushort * huff)586 inline unsigned CLASS getbithuff_t::operator() (int nbits, ushort *huff)
587 {
588 /*RT static unsigned bitbuf=0; */
589 /*RT static int vbits=0, reset=0; */
590   unsigned c;
591 
592   if (UNLIKELY(nbits > 25)) return 0;
593   if (nbits < 0)
594     return bitbuf = vbits = reset = 0;
595   if (nbits == 0 || vbits < 0) return 0;
596   while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF &&
597     !(reset = zero_after_ff && c == 0xff && fgetc(ifp))) {
598     bitbuf = (bitbuf << 8) + (uchar) c;
599     vbits += 8;
600   }
601   c = bitbuf << (32-vbits) >> (32-nbits);
602   if (huff) {
603     vbits -= huff[c] >> 8;
604     c = (uchar) huff[c];
605   } else
606     vbits -= nbits;
607   if (vbits < 0) derror();
608   return c;
609 }
610 
611 #define getbits(n) getbithuff(n,0)
612 #define gethuff(h) getbithuff(*h,h+1)
613 
operator ()(int nbits,ushort * huff)614 inline unsigned CLASS nikbithuff_t::operator() (int nbits, ushort *huff)
615 {
616     unsigned c;
617 
618     if (UNLIKELY(nbits == 0)) {
619         return 0;
620     }
621     if (vbits < nbits && LIKELY((c = fgetc(ifp)) != EOF)) {
622         bitbuf = (bitbuf << 8) | c;
623         vbits += 8;
624         if (vbits < nbits && LIKELY((c = fgetc(ifp)) != EOF)) {
625             bitbuf = (bitbuf << 8) | c;
626             vbits += 8;
627         }
628     }
629     c = bitbuf << (32-vbits) >> (32-nbits);
630     if (huff) {
631         vbits -= huff[c] >> 8;
632         c = (uchar) huff[c];
633         derror(vbits < 0);
634     } else {
635         vbits -= nbits;
636     }
637     return c;
638 }
639 
640 #define nikinit(n) nikbithuff()
641 #define nikbits(n) nikbithuff(n,0)
642 #define nikhuff(h) nikbithuff(*h,h+1)
643 
644 /*
645    Construct a decode tree according the specification in *source.
646    The first 16 bytes specify how many codes should be 1-bit, 2-bit
647    3-bit, etc.  Bytes after that are the leaf values.
648 
649    For example, if the source is
650 
651     { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
652       0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff  },
653 
654    then the code is
655 
656 	00		0x04
657 	010		0x03
658 	011		0x05
659 	100		0x06
660 	101		0x02
661 	1100		0x07
662 	1101		0x01
663 	11100		0x08
664 	11101		0x09
665 	11110		0x00
666 	111110		0x0a
667 	1111110		0x0b
668 	1111111		0xff
669  */
make_decoder_ref(const uchar ** source)670 ushort * CLASS make_decoder_ref (const uchar **source)
671 {
672   int max, len, h, i, j;
673   const uchar *count;
674   ushort *huff;
675 
676   count = (*source += 16) - 17;
677   for (max=16; max && !count[max]; max--);
678   huff = (ushort *) calloc (1 + (1 << max), sizeof *huff);
679   merror (huff, "make_decoder()");
680   huff[0] = max;
681   for (h=len=1; len <= max; len++)
682     for (i=0; i < count[len]; i++, ++*source)
683       for (j=0; j < 1 << (max-len); j++)
684 	if (h <= 1 << max)
685 	  huff[h++] = len << 8 | **source;
686   return huff;
687 }
688 
make_decoder(const uchar * source)689 ushort * CLASS make_decoder (const uchar *source)
690 {
691   return make_decoder_ref (&source);
692 }
693 
crw_init_tables(unsigned table,ushort * huff[2])694 void CLASS crw_init_tables (unsigned table, ushort *huff[2])
695 {
696   static const uchar first_tree[3][29] = {
697     { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
698       0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff  },
699     { 0,2,2,3,1,1,1,1,2,0,0,0,0,0,0,0,
700       0x03,0x02,0x04,0x01,0x05,0x00,0x06,0x07,0x09,0x08,0x0a,0x0b,0xff  },
701     { 0,0,6,3,1,1,2,0,0,0,0,0,0,0,0,0,
702       0x06,0x05,0x07,0x04,0x08,0x03,0x09,0x02,0x00,0x0a,0x01,0x0b,0xff  },
703   };
704   static const uchar second_tree[3][180] = {
705     { 0,2,2,2,1,4,2,1,2,5,1,1,0,0,0,139,
706       0x03,0x04,0x02,0x05,0x01,0x06,0x07,0x08,
707       0x12,0x13,0x11,0x14,0x09,0x15,0x22,0x00,0x21,0x16,0x0a,0xf0,
708       0x23,0x17,0x24,0x31,0x32,0x18,0x19,0x33,0x25,0x41,0x34,0x42,
709       0x35,0x51,0x36,0x37,0x38,0x29,0x79,0x26,0x1a,0x39,0x56,0x57,
710       0x28,0x27,0x52,0x55,0x58,0x43,0x76,0x59,0x77,0x54,0x61,0xf9,
711       0x71,0x78,0x75,0x96,0x97,0x49,0xb7,0x53,0xd7,0x74,0xb6,0x98,
712       0x47,0x48,0x95,0x69,0x99,0x91,0xfa,0xb8,0x68,0xb5,0xb9,0xd6,
713       0xf7,0xd8,0x67,0x46,0x45,0x94,0x89,0xf8,0x81,0xd5,0xf6,0xb4,
714       0x88,0xb1,0x2a,0x44,0x72,0xd9,0x87,0x66,0xd4,0xf5,0x3a,0xa7,
715       0x73,0xa9,0xa8,0x86,0x62,0xc7,0x65,0xc8,0xc9,0xa1,0xf4,0xd1,
716       0xe9,0x5a,0x92,0x85,0xa6,0xe7,0x93,0xe8,0xc1,0xc6,0x7a,0x64,
717       0xe1,0x4a,0x6a,0xe6,0xb3,0xf1,0xd3,0xa5,0x8a,0xb2,0x9a,0xba,
718       0x84,0xa4,0x63,0xe5,0xc5,0xf3,0xd2,0xc4,0x82,0xaa,0xda,0xe4,
719       0xf2,0xca,0x83,0xa3,0xa2,0xc3,0xea,0xc2,0xe2,0xe3,0xff,0xff  },
720     { 0,2,2,1,4,1,4,1,3,3,1,0,0,0,0,140,
721       0x02,0x03,0x01,0x04,0x05,0x12,0x11,0x06,
722       0x13,0x07,0x08,0x14,0x22,0x09,0x21,0x00,0x23,0x15,0x31,0x32,
723       0x0a,0x16,0xf0,0x24,0x33,0x41,0x42,0x19,0x17,0x25,0x18,0x51,
724       0x34,0x43,0x52,0x29,0x35,0x61,0x39,0x71,0x62,0x36,0x53,0x26,
725       0x38,0x1a,0x37,0x81,0x27,0x91,0x79,0x55,0x45,0x28,0x72,0x59,
726       0xa1,0xb1,0x44,0x69,0x54,0x58,0xd1,0xfa,0x57,0xe1,0xf1,0xb9,
727       0x49,0x47,0x63,0x6a,0xf9,0x56,0x46,0xa8,0x2a,0x4a,0x78,0x99,
728       0x3a,0x75,0x74,0x86,0x65,0xc1,0x76,0xb6,0x96,0xd6,0x89,0x85,
729       0xc9,0xf5,0x95,0xb4,0xc7,0xf7,0x8a,0x97,0xb8,0x73,0xb7,0xd8,
730       0xd9,0x87,0xa7,0x7a,0x48,0x82,0x84,0xea,0xf4,0xa6,0xc5,0x5a,
731       0x94,0xa4,0xc6,0x92,0xc3,0x68,0xb5,0xc8,0xe4,0xe5,0xe6,0xe9,
732       0xa2,0xa3,0xe3,0xc2,0x66,0x67,0x93,0xaa,0xd4,0xd5,0xe7,0xf8,
733       0x88,0x9a,0xd7,0x77,0xc4,0x64,0xe2,0x98,0xa5,0xca,0xda,0xe8,
734       0xf3,0xf6,0xa9,0xb2,0xb3,0xf2,0xd2,0x83,0xba,0xd3,0xff,0xff  },
735     { 0,0,6,2,1,3,3,2,5,1,2,2,8,10,0,117,
736       0x04,0x05,0x03,0x06,0x02,0x07,0x01,0x08,
737       0x09,0x12,0x13,0x14,0x11,0x15,0x0a,0x16,0x17,0xf0,0x00,0x22,
738       0x21,0x18,0x23,0x19,0x24,0x32,0x31,0x25,0x33,0x38,0x37,0x34,
739       0x35,0x36,0x39,0x79,0x57,0x58,0x59,0x28,0x56,0x78,0x27,0x41,
740       0x29,0x77,0x26,0x42,0x76,0x99,0x1a,0x55,0x98,0x97,0xf9,0x48,
741       0x54,0x96,0x89,0x47,0xb7,0x49,0xfa,0x75,0x68,0xb6,0x67,0x69,
742       0xb9,0xb8,0xd8,0x52,0xd7,0x88,0xb5,0x74,0x51,0x46,0xd9,0xf8,
743       0x3a,0xd6,0x87,0x45,0x7a,0x95,0xd5,0xf6,0x86,0xb4,0xa9,0x94,
744       0x53,0x2a,0xa8,0x43,0xf5,0xf7,0xd4,0x66,0xa7,0x5a,0x44,0x8a,
745       0xc9,0xe8,0xc8,0xe7,0x9a,0x6a,0x73,0x4a,0x61,0xc7,0xf4,0xc6,
746       0x65,0xe9,0x72,0xe6,0x71,0x91,0x93,0xa6,0xda,0x92,0x85,0x62,
747       0xf3,0xc5,0xb2,0xa4,0x84,0xba,0x64,0xa5,0xb3,0xd2,0x81,0xe5,
748       0xd3,0xaa,0xc4,0xca,0xf2,0xb1,0xe4,0xd1,0x83,0x63,0xea,0xc3,
749       0xe2,0x82,0xf1,0xa3,0xc2,0xa1,0xc1,0xe3,0xa2,0xe1,0xff,0xff  }
750   };
751   if (table > 2) table = 2;
752   huff[0] = make_decoder ( first_tree[table]);
753   huff[1] = make_decoder (second_tree[table]);
754 }
755 
756 /*
757    Return 0 if the image starts with compressed data,
758    1 if it starts with uncompressed low-order bits.
759 
760    In Canon compressed data, 0xff is always followed by 0x00.
761  */
canon_has_lowbits()762 int CLASS canon_has_lowbits()
763 {
764   uchar test[0x4000];
765   int ret=1, i;
766 
767   fseek (ifp, 0, SEEK_SET);
768   fread (test, 1, sizeof test, ifp);
769   for (i=540; i < sizeof test - 1; i++)
770     if (test[i] == 0xff) {
771       if (test[i+1]) return 1;
772       ret=0;
773     }
774   return ret;
775 }
776 
canon_load_raw()777 void CLASS canon_load_raw()
778 {
779   ushort *pixel, *prow, *huff[2];
780   int nblocks, lowbits, i, c, row, r, save, val;
781   int block, diffbuf[64], leaf, len, diff, carry=0, pnum=0, base[2];
782 
783   crw_init_tables (tiff_compress, huff);
784   lowbits = canon_has_lowbits();
785   if (!lowbits) maximum = 0x3ff;
786   fseek (ifp, 540 + lowbits*raw_height*raw_width/4, SEEK_SET);
787   zero_after_ff = 1;
788   getbits(-1);
789   for (row=0; row < raw_height; row+=8) {
790     pixel = raw_image + row*raw_width;
791     nblocks = MIN (8, raw_height-row) * raw_width >> 6;
792     for (block=0; block < nblocks; block++) {
793       memset (diffbuf, 0, sizeof diffbuf);
794       for (i=0; i < 64; i++ ) {
795 	leaf = gethuff(huff[i > 0]);
796 	if (leaf == 0 && i) break;
797 	if (leaf == 0xff) continue;
798 	i  += leaf >> 4;
799 	len = leaf & 15;
800 	if (len == 0) continue;
801 	diff = getbits(len);
802 	if ((diff & (1 << (len-1))) == 0)
803 	  diff -= (1 << len) - 1;
804 	if (i < 64) diffbuf[i] = diff;
805       }
806       diffbuf[0] += carry;
807       carry = diffbuf[0];
808       for (i=0; i < 64; i++ ) {
809 	if (pnum++ % raw_width == 0)
810 	  base[0] = base[1] = 512;
811 	if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10)
812 	  derror();
813       }
814     }
815     if (lowbits) {
816       save = ftell(ifp);
817       fseek (ifp, 26 + row*raw_width/4, SEEK_SET);
818       for (prow=pixel, i=0; i < raw_width*2; i++) {
819 	c = fgetc(ifp);
820 	for (r=0; r < 8; r+=2, prow++) {
821 	  val = (*prow << 2) + ((c >> r) & 3);
822 	  if (raw_width == 2672 && val < 512) val += 2;
823 	  *prow = val;
824 	}
825       }
826       fseek (ifp, save, SEEK_SET);
827     }
828   }
829   FORC(2) free (huff[c]);
830 }
831 
832 /*
833    Not a full implementation of Lossless JPEG, just
834    enough to decode Canon, Kodak and Adobe DNG images.
835  */
836 struct jhead {
837   int bits, high, wide, clrs, sraw, psv, restart, vpred[6];
838   ushort *huff[6], *free[4], *row;
839 };
840 
ljpeg_start(struct jhead * jh,int info_only)841 int CLASS ljpeg_start (struct jhead *jh, int info_only)
842 {
843   ushort c, tag, len;
844   uchar data[0x10000];
845   const uchar *dp;
846 
847   memset (jh, 0, sizeof *jh);
848   jh->restart = INT_MAX;
849   if ((fgetc(ifp),fgetc(ifp)) != 0xd8) return 0;
850   do {
851     if (!fread (data, 2, 2, ifp)) return 0;
852     tag =  data[0] << 8 | data[1];
853     len = (data[2] << 8 | data[3]) - 2;
854     if (tag <= 0xff00) return 0;
855     fread (data, 1, len, ifp);
856     switch (tag) {
857       case 0xffc3:
858 	jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3;
859 	  case 0xffc1:
860       case 0xffc0:
861     jh->algo = tag & 0xff;
862 	jh->bits = data[0];
863 	jh->high = data[1] << 8 | data[2];
864 	jh->wide = data[3] << 8 | data[4];
865 	jh->clrs = data[5] + jh->sraw;
866 	if (len == 9 && !dng_version) getc(ifp);
867 	break;
868       case 0xffc4:
869 	if (info_only) break;
870 	for (dp = data; dp < data+len && !((c = *dp++) & -20); )
871 	  jh->free[c] = jh->huff[c] = make_decoder_ref (&dp);
872 	break;
873       case 0xffda:
874 	jh->psv = data[1+data[0]*2];
875 	jh->bits -= data[3+data[0]*2] & 15;
876 	break;
877       case 0xffdb:
878 	FORC(64) jh->quant[c] = data[c*2+1] << 8 | data[c*2+2];
879 	break;
880       case 0xffdd:
881 	jh->restart = data[0] << 8 | data[1];
882     }
883   } while (tag != 0xffda);
884   if (jh->bits > 16 || jh->clrs > 6 ||
885      !jh->bits || !jh->high || !jh->wide || !jh->clrs) return 0;
886   if (info_only) return 1;
887   if (!jh->huff[0]) return 0;
888   FORC(19) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c];
889   if (jh->sraw) {
890     FORC(4)        jh->huff[2+c] = jh->huff[1];
891     FORC(jh->sraw) jh->huff[1+c] = jh->huff[0];
892   }
893   jh->row = (ushort *) calloc (2 * jh->wide*jh->clrs, 4);
894   merror (jh->row, "ljpeg_start()");
895   return zero_after_ff = 1;
896 }
897 
ljpeg_end(struct jhead * jh)898 void CLASS ljpeg_end (struct jhead *jh)
899 {
900   int c;
901   FORC4 if (jh->free[c]) free (jh->free[c]);
902   free (jh->row);
903 }
904 
ljpeg_diff(ushort * huff)905 inline int CLASS ljpeg_diff (ushort *huff)
906 {
907   int len, diff;
908 
909   len = gethuff(huff);
910   if (len == 16 && (!dng_version || dng_version >= 0x1010000))
911     return -32768;
912   diff = getbits(len);
913   if ((diff & (1 << (len-1))) == 0)
914     diff -= (1 << len) - 1;
915   return diff;
916 }
917 
ljpeg_row(int jrow,struct jhead * jh)918 ushort * CLASS ljpeg_row (int jrow, struct jhead *jh)
919 {
920   int col, c, diff, pred, spred=0;
921   ushort mark=0, *row[3];
922 
923   if (jrow * jh->wide % jh->restart == 0) {
924     FORC(6) jh->vpred[c] = 1 << (jh->bits-1);
925     if (jrow) {
926       fseek (ifp, -2, SEEK_CUR);
927       do mark = (mark << 8) + (c = fgetc(ifp));
928       while (c != EOF && mark >> 4 != 0xffd);
929     }
930     getbits(-1);
931   }
932   FORC3 row[c] = (jh->row + ((jrow & 1) + 1) * (jh->wide*jh->clrs*((jrow+c) & 1)));
933   for (col=0; col < jh->wide; col++)
934     FORC(jh->clrs) {
935       diff = ljpeg_diff (jh->huff[c]);
936       if (jh->sraw && c <= jh->sraw && (col | c))
937 		    pred = spred;
938       else if (col) pred = row[0][-jh->clrs];
939       else	    pred = (jh->vpred[c] += diff) - diff;
940       if (jh->psv != 1 && jrow && col) switch (jh->psv) {
941 	case 2: pred = row[1][0];					break;
942 	case 3: pred = row[1][-jh->clrs];				break;
943 	case 4: pred = pred +   row[1][0] - row[1][-jh->clrs];		break;
944 	case 5: pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1);	break;
945 	case 6: pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1);	break;
946 	case 7: pred = (pred + row[1][0]) >> 1;				break;
947 	default: pred = 0;
948       }
949       if (UNLIKELY((**row = pred + diff) >> jh->bits)) derror();
950       if (c <= jh->sraw) spred = **row;
951       row[0]++; row[1]++;
952     }
953   return row[2];
954 }
955 
lossless_jpeg_load_raw()956 void CLASS lossless_jpeg_load_raw()
957 {
958   struct jhead jh;
959   int row=0, col=0;
960 
961   if (!ljpeg_start (&jh, 0)) return;
962   int jwide = jh.wide * jh.clrs;
963   ushort *rp[2];
964   rp[0] = ljpeg_row (0, &jh);
965 
966   for (int jrow=0; jrow < jh.high; jrow++) {
967 #ifdef _OPENMP
968 #pragma omp parallel sections
969 #endif
970 {
971 #ifdef _OPENMP
972     #pragma omp section
973 #endif
974     {
975         if(jrow < jh.high - 1)
976             rp[(jrow + 1)&1] = ljpeg_row (jrow + 1, &jh);
977     }
978 #ifdef _OPENMP
979      #pragma omp section
980 #endif
981     {
982     if (load_flags & 1)
983       row = jrow & 1 ? height-1-jrow/2 : jrow/2;
984     for (int jcol=0; jcol < jwide; jcol++) {
985       int val = curve[*rp[jrow&1]++];
986       if (cr2_slice[0]) {
987 	int jidx = jrow*jwide + jcol;
988 	int i = jidx / (cr2_slice[1]*raw_height);
989 	int j;
990 	if ((j = i >= cr2_slice[0]))
991 		 i  = cr2_slice[0];
992 	jidx -= i * (cr2_slice[1]*raw_height);
993 	row = jidx / cr2_slice[1+j];
994 	col = jidx % cr2_slice[1+j] + i*cr2_slice[1];
995       }
996       if (raw_width == 3984 && (col -= 2) < 0)
997 	col += (row--,raw_width);
998       if ((unsigned) row < raw_height) RAW(row,col) = val;
999       if (++col >= raw_width)
1000 	col = (row++,0);
1001     }
1002     }
1003 }
1004   }
1005   ljpeg_end (&jh);
1006 }
1007 
canon_sraw_load_raw()1008 void CLASS canon_sraw_load_raw()
1009 {
1010   struct jhead jh;
1011   short *rp=0, (*ip)[4];
1012   int jwide, slice, scol, ecol, row, col, jrow=0, jcol=0, pix[3], c;
1013   int v[3]={0,0,0}, ver, hue;
1014   char *cp;
1015 
1016   if (!ljpeg_start (&jh, 0) || jh.clrs < 4) return;
1017   jwide = (jh.wide >>= 1) * jh.clrs;
1018 
1019   for (ecol=slice=0; slice <= cr2_slice[0]; slice++) {
1020     scol = ecol;
1021     ecol += cr2_slice[1] * 2 / jh.clrs;
1022     if (!cr2_slice[0] || ecol > raw_width-1) ecol = raw_width & -2;
1023     for (row=0; row < height; row += (jh.clrs >> 1) - 1) {
1024       ip = (short (*)[4]) image + row*width;
1025       for (col=scol; col < ecol; col+=2, jcol+=jh.clrs) {
1026 	if ((jcol %= jwide) == 0)
1027 	  rp = (short *) ljpeg_row (jrow++, &jh);
1028 	if (col >= width) continue;
1029 	FORC (jh.clrs-2)
1030 	  ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c];
1031 	ip[col][1] = rp[jcol+jh.clrs-2] - 16384;
1032 	ip[col][2] = rp[jcol+jh.clrs-1] - 16384;
1033       }
1034     }
1035   }
1036   for (cp=model2; *cp && !isdigit(*cp); cp++);
1037   sscanf (cp, "%d.%d.%d", v, v+1, v+2);
1038   ver = (v[0]*1000 + v[1])*1000 + v[2];
1039   hue = (jh.sraw+1) << 2;
1040   if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006))
1041     hue = jh.sraw << 1;
1042   ip = (short (*)[4]) image;
1043   rp = ip[0];
1044   for (row=0; row < height; row++, ip+=width) {
1045     if (row & (jh.sraw >> 1))
1046       for (col=0; col < width; col+=2)
1047 	for (c=1; c < 3; c++) {
1048 	  if (row == height-1)
1049 	       ip[col][c] =  ip[col-width][c];
1050 	  else ip[col][c] = (ip[col-width][c] + ip[col+width][c] + 1) >> 1;
1051 	}
1052     for (col=1; col < width; col+=2)
1053       for (c=1; c < 3; c++)
1054 	if (col == width-1)
1055 	     ip[col][c] =  ip[col-1][c];
1056 	else ip[col][c] = (ip[col-1][c] + ip[col+1][c] + 1) >> 1;
1057   }
1058   for ( ; rp < ip[0]; rp+=4) {
1059     if (unique_id == 0x80000218 ||
1060 	unique_id == 0x80000250 ||
1061 	unique_id == 0x80000261 ||
1062 	unique_id == 0x80000281 ||
1063 	unique_id == 0x80000287) {
1064       rp[1] = (rp[1] << 2) + hue;
1065       rp[2] = (rp[2] << 2) + hue;
1066       pix[0] = rp[0] + ((   50*rp[1] + 22929*rp[2]) >> 14);
1067       pix[1] = rp[0] + ((-5640*rp[1] - 11751*rp[2]) >> 14);
1068       pix[2] = rp[0] + ((29040*rp[1] -   101*rp[2]) >> 14);
1069     } else {
1070       if (unique_id < 0x80000218) rp[0] -= 512;
1071       pix[0] = rp[0] + rp[2];
1072       pix[2] = rp[0] + rp[1];
1073       pix[1] = rp[0] + ((-778*rp[1] - (rp[2] << 11)) >> 12);
1074     }
1075     FORC3 rp[c] = CLIP(pix[c] * sraw_mul[c] >> 10);
1076   }
1077   ljpeg_end (&jh);
1078   maximum = 0x3fff;
1079 }
1080 
adobe_copy_pixel(unsigned row,unsigned col,ushort ** rp)1081 void CLASS adobe_copy_pixel (unsigned row, unsigned col, ushort **rp)
1082 {
1083   int c;
1084 
1085   if (tiff_samples == 2 && shot_select) (*rp)++;
1086   if (raw_image) {
1087     if (row < raw_height && col < raw_width)
1088       RAW(row,col) = curve[**rp];
1089     *rp += tiff_samples;
1090   } else {
1091     if (row < height && col < width)
1092       FORC(tiff_samples)
1093 	image[row*width+col][c] = curve[(*rp)[c]];
1094     *rp += tiff_samples;
1095   }
1096   if (tiff_samples == 2 && shot_select) (*rp)--;
1097 }
1098 
ljpeg_idct(struct jhead * jh)1099 void CLASS ljpeg_idct (struct jhead *jh)
1100 {
1101   int c, i, j, len, skip, coef;
1102   float work[3][8][8];
1103   static float cs[106] = { 0 };
1104   static const uchar zigzag[80] =
1105   {  0, 1, 8,16, 9, 2, 3,10,17,24,32,25,18,11, 4, 5,12,19,26,33,
1106     40,48,41,34,27,20,13, 6, 7,14,21,28,35,42,49,56,57,50,43,36,
1107     29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,
1108     47,55,62,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63 };
1109 
1110   if (!cs[0])
1111     FORC(106) cs[c] = cos((c & 31)*rtengine::RT_PI/16)/2;
1112   memset (work, 0, sizeof work);
1113   work[0][0][0] = jh->vpred[0] += ljpeg_diff (jh->huff[0]) * jh->quant[0];
1114   for (i=1; i < 64; i++ ) {
1115     len = gethuff (jh->huff[16]);
1116     i += skip = len >> 4;
1117     if (!(len &= 15) && skip < 15) break;
1118     coef = getbits(len);
1119     if ((coef & (1 << (len-1))) == 0)
1120       coef -= (1 << len) - 1;
1121     ((float *)work)[zigzag[i]] = coef * jh->quant[i];
1122   }
1123   FORC(8) work[0][0][c] *= rtengine::RT_SQRT1_2;
1124   FORC(8) work[0][c][0] *= rtengine::RT_SQRT1_2;
1125   for (i=0; i < 8; i++)
1126     for (j=0; j < 8; j++)
1127       FORC(8) work[1][i][j] += work[0][i][c] * cs[(j*2+1)*c];
1128   for (i=0; i < 8; i++)
1129     for (j=0; j < 8; j++)
1130       FORC(8) work[2][i][j] += work[1][c][j] * cs[(i*2+1)*c];
1131 
1132   FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c]+0.5);
1133 }
1134 
lossless_dnglj92_load_raw()1135 void CLASS lossless_dnglj92_load_raw()
1136 {
1137     BENCHFUN
1138 
1139     tiff_bps = 16;
1140 
1141     int save = ifp->pos;
1142     uint16_t *lincurve = !strncmp(make,"Blackmagic",10) ? curve : nullptr;
1143     tile_width = tile_length < INT_MAX ? tile_width : raw_width;
1144     size_t tileCount = raw_width / tile_width;
1145 
1146     size_t dataOffset[tileCount];
1147     if(tile_length < INT_MAX) {
1148         for (size_t t = 0; t < tileCount; ++t) {
1149             dataOffset[t] = get4();
1150         }
1151     } else {
1152         dataOffset[0] = ifp->pos;
1153     }
1154     const int data_length = ifp->size;
1155     const std::unique_ptr<uint8_t[]> data(new uint8_t[data_length]);
1156     fseek(ifp, 0, SEEK_SET);
1157     // read whole file
1158     fread(data.get(), 1, data_length, ifp);
1159     lj92 lj;
1160     int newwidth, newheight, newbps;
1161     lj92_open(&lj, &data[dataOffset[0]], data_length, &newwidth, &newheight, &newbps);
1162     lj92_close(lj);
1163     if (newwidth * newheight * tileCount != raw_width * raw_height) {
1164         // not a lj92 file
1165         fseek(ifp, save, SEEK_SET);
1166         lossless_dng_load_raw();
1167         return;
1168     }
1169 
1170 #ifdef _OPENMP
1171     #pragma omp parallel for num_threads(std::min<int>(tileCount, omp_get_max_threads()))
1172 #endif
1173     for (size_t t = 0; t < tileCount; ++t) {
1174         size_t tcol = t * tile_width;
1175         lj92 lj;
1176         int newwidth, newheight, newbps;
1177         lj92_open(&lj, &data[dataOffset[t]], data_length, &newwidth, &newheight, &newbps);
1178 
1179         const std::unique_ptr<uint16_t[]> target(new uint16_t[newwidth * newheight]);
1180         lj92_decode(lj, target.get(), tile_width, 0, lincurve, 0x1000);
1181         for (int y = 0; y < height; ++y) {
1182             for(int x = 0; x < tile_width; ++x) {
1183                 RAW(y, x + tcol) = target[y * tile_width + x];
1184             }
1185         }
1186         lj92_close(lj);
1187     }
1188 }
1189 
lossless_dng_load_raw()1190 void CLASS lossless_dng_load_raw()
1191 {
1192   unsigned save, trow=0, tcol=0, jwide, jrow, jcol, row, col, i, j;
1193   struct jhead jh;
1194   ushort *rp;
1195 
1196   while (trow < raw_height) {
1197     save = ftell(ifp);
1198     if (tile_length < INT_MAX)
1199       fseek (ifp, get4(), SEEK_SET);
1200     if (!ljpeg_start (&jh, 0)) break;
1201     jwide = jh.wide;
1202     if (filters || (colors == 1 && jh.clrs > 1)) jwide *= jh.clrs;
1203     jwide /= MIN (is_raw, tiff_samples);
1204     switch (jh.algo) {
1205       case 0xc1:
1206 	jh.vpred[0] = 16384;
1207 	getbits(-1);
1208 	for (jrow=0; jrow+7 < jh.high; jrow += 8) {
1209 	  for (jcol=0; jcol+7 < jh.wide; jcol += 8) {
1210 	    ljpeg_idct (&jh);
1211 	    rp = jh.idct;
1212 	    row = trow + jcol/tile_width + jrow*2;
1213 	    col = tcol + jcol%tile_width;
1214 	    for (i=0; i < 16; i+=2)
1215 	      for (j=0; j < 8; j++)
1216 		adobe_copy_pixel (row+i, col+j, &rp);
1217 	  }
1218 	}
1219 	break;
1220       case 0xc3:
1221 	for (row=col=jrow=0; jrow < jh.high; jrow++) {
1222 	  rp = ljpeg_row (jrow, &jh);
1223 	  for (jcol=0; jcol < jwide; jcol++) {
1224 	    adobe_copy_pixel (trow+row, tcol+col, &rp);
1225 	    if (++col >= tile_width || col >= raw_width)
1226 	      row += 1 + (col = 0);
1227 	  }
1228 	}    }
1229     fseek (ifp, save+4, SEEK_SET);
1230     if ((tcol += tile_width) >= raw_width)
1231       trow += tile_length + (tcol = 0);
1232     ljpeg_end (&jh);
1233   }
1234 }
1235 
1236 static uint32_t DNG_HalfToFloat(uint16_t halfValue);
1237 
packed_dng_load_raw()1238 void CLASS packed_dng_load_raw()
1239 {
1240   ushort *pixel, *rp;
1241   int row, col;
1242   int isfloat = (tiff_nifds == 1 && tiff_ifd[0].sample_format == 3 && (tiff_bps == 16 || tiff_bps == 32));
1243   if (isfloat) {
1244     float_raw_image = new float[raw_width * raw_height];
1245   }
1246 
1247   pixel = (ushort *) calloc (raw_width, tiff_samples*sizeof *pixel);
1248   merror (pixel, "packed_dng_load_raw()");
1249   for (row=0; row < raw_height; row++) {
1250     if (tiff_bps == 16) {
1251       read_shorts (pixel, raw_width * tiff_samples);
1252       if (isfloat) {
1253           uint32_t *dst = reinterpret_cast<uint32_t *>(&float_raw_image[row*raw_width]);
1254           for (col = 0; col < raw_width; col++) {
1255               uint32_t f = DNG_HalfToFloat(pixel[col]);
1256               dst[col] = f;
1257           }
1258       }
1259     } else if (isfloat) {
1260       if (fread(&float_raw_image[row*raw_width], sizeof(float), raw_width, ifp) != raw_width) {
1261         derror();
1262       }
1263       if ((order == 0x4949) == (ntohs(0x1234) == 0x1234)) {
1264         char *d = reinterpret_cast<char *>(float_raw_image);
1265         rtengine::swab(d, d, sizeof(float)*raw_width);
1266       }
1267     } else {
1268       getbits(-1);
1269       for (col=0; col < raw_width * tiff_samples; col++)
1270 	pixel[col] = getbits(tiff_bps);
1271     }
1272     if (!isfloat) {
1273         for (rp=pixel, col=0; col < raw_width; col++)
1274             adobe_copy_pixel (row, col, &rp);
1275     }
1276   }
1277   free (pixel);
1278 }
1279 
pentax_load_raw()1280 void CLASS pentax_load_raw()
1281 {
1282   ushort bit[2][15], huff[4097];
1283   int dep, row, col, diff, c, i;
1284   ushort vpred[2][2] = {{0,0},{0,0}}, hpred[2];
1285 
1286   fseek (ifp, meta_offset, SEEK_SET);
1287   dep = (get2() + 12) & 15;
1288   fseek (ifp, 12, SEEK_CUR);
1289   FORC(dep) bit[0][c] = get2();
1290   FORC(dep) bit[1][c] = fgetc(ifp);
1291   FORC(dep)
1292     for (i=bit[0][c]; i <= ((bit[0][c]+(4096 >> bit[1][c])-1) & 4095); )
1293       huff[++i] = bit[1][c] << 8 | c;
1294   huff[0] = 12;
1295   fseek (ifp, data_offset, SEEK_SET);
1296   getbits(-1);
1297   for (row=0; row < raw_height; row++)
1298     for (col=0; col < raw_width; col++) {
1299       diff = ljpeg_diff (huff);
1300       if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
1301       else	   hpred[col & 1] += diff;
1302       RAW(row,col) = hpred[col & 1];
1303       if (hpred[col & 1] >> tiff_bps) derror();
1304     }
1305 }
1306 
nikon_load_raw()1307 void CLASS nikon_load_raw()
1308 {
1309     static const uchar nikon_tree[][32] = {
1310       { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0,	/* 12-bit lossy */
1311         5,4,3,6,2,7,1,0,8,9,11,10,12 },
1312       { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0,	/* 12-bit lossy after split */
1313         0x39,0x5a,0x38,0x27,0x16,5,4,3,2,1,0,11,12,12 },
1314       { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,  /* 12-bit lossless */
1315         5,4,6,3,7,2,8,1,9,0,10,11,12 },
1316       { 0,1,4,3,1,1,1,1,1,2,0,0,0,0,0,0,	/* 14-bit lossy */
1317         5,6,4,7,8,3,9,2,1,0,10,11,12,13,14 },
1318       { 0,1,5,1,1,1,1,1,1,1,2,0,0,0,0,0,	/* 14-bit lossy after split */
1319         8,0x5c,0x4b,0x3a,0x29,7,6,5,4,3,2,1,0,13,14 },
1320       { 0,1,4,2,2,3,1,2,0,0,0,0,0,0,0,0,	/* 14-bit lossless */
1321         7,6,8,5,9,4,10,3,11,12,2,0,1,13,14 } };
1322     ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize;
1323     int max, step=0, tree=0, split=0;
1324 
1325     fseek (ifp, meta_offset, SEEK_SET);
1326     ver0 = fgetc(ifp);
1327     ver1 = fgetc(ifp);
1328     if (ver0 == 0x49 || ver1 == 0x58)
1329         fseek (ifp, 2110, SEEK_CUR);
1330     if (ver0 == 0x46) tree = 2;
1331     if (tiff_bps == 14) tree += 3;
1332     read_shorts (vpred[0], 4);
1333     max = 1 << (tiff_bps - (ver0 == 0x44 && ver1 == 0x40 ? 2 : 0)) & 0x7fff;
1334     if ((csize = get2()) > 1)
1335         step = max / (csize-1);
1336     if (ver0 == 0x44 && (ver1 == 0x20 || ver1 == 0x40) && step > 0) {
1337         for (int i=0; i < csize; i++)
1338             curve[i*step] = get2();
1339         for (int i=0; i < max; i++)
1340             curve[i] = ( curve[i-i%step]*(step-i%step) +
1341 		    curve[i-i%step+step]*(i%step) ) / step;
1342         fseek (ifp, meta_offset+562, SEEK_SET);
1343         split = get2();
1344     } else if (ver0 != 0x46 && csize <= 0x4001)
1345         read_shorts (curve, max=csize);
1346     while (curve[max-2] == curve[max-1]) max--;
1347 
1348     // instead of accessing curve[LIM((short)hpred[col & 1],0,0x3fff)] in the inner loop, we just fill the curve with the correct values and access curve[hpred[col & 1]]
1349     for(int i = 0x4000; i < 0x8000; ++i)
1350         curve[i] = curve[0x3fff];
1351     for(int i = 0x8000; i < 0x10000; ++i)
1352         curve[i] = curve[0];
1353 
1354     huff = make_decoder (nikon_tree[tree]);
1355     fseek (ifp, data_offset, SEEK_SET);
1356     nikinit();
1357     if (split) {
1358         for (int min = 0, row = 0; row < height; row++) {
1359             if (row == split) {
1360                 free (huff);
1361                 huff = make_decoder (nikon_tree[tree+1]);
1362                 max += (min = 16) << 1;
1363             }
1364             for (int col=0; col < raw_width; col++) {
1365                 int i = nikhuff(huff);
1366                 int len = i & 15;
1367                 int shl = i >> 4;
1368                 int diff = ((nikbits(len-shl) << 1) + 1) << shl >> 1;
1369                 if ((diff & (1 << (len-1))) == 0)
1370                     diff -= (1 << len) - !shl;
1371                 if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
1372                 else	     hpred[col & 1] += diff;
1373                 derror((ushort)(hpred[col & 1] + min) >= max);
1374                 RAW(row,col) = curve[hpred[col & 1]];
1375             }
1376         }
1377     } else {
1378         for (int row=0; row < height; row++) {
1379             for (int col=0; col < 2; col++) {
1380                 int len = nikhuff(huff);
1381                 int diff = nikbits(len);
1382                 if ((diff & (1 << (len-1))) == 0)
1383                     diff -= (1 << len) - 1;
1384                 hpred[col] = vpred[row & 1][col] += diff;
1385                 derror(hpred[col] >= max);
1386                 RAW(row,col) = curve[hpred[col]];
1387             }
1388             for (int col=2; col < raw_width; col++) {
1389                 int len = nikhuff(huff);
1390                 int diff = nikbits(len);
1391                 if ((diff & (1 << (len-1))) == 0)
1392                     diff -= (1 << len) - 1;
1393                 hpred[col & 1] += diff;
1394                 derror(hpred[col & 1] >= max);
1395                 RAW(row,col) = curve[hpred[col & 1]];
1396             }
1397         }
1398     }
1399     free (huff);
1400     data_error += nikbithuff.errorCount();
1401     if(data_error) {
1402         std::cerr << ifname << " decoded with " << data_error << " errors. File possibly corrupted." << std::endl;
1403     }
1404 }
1405 
nikon_yuv_load_raw()1406 void CLASS nikon_yuv_load_raw()
1407 {
1408   int row, col, yuv[4], rgb[3], b, c;
1409   UINT64 bitbuf=0;
1410 
1411   for (row=0; row < raw_height; row++)
1412     for (col=0; col < raw_width; col++) {
1413       if (!(b = col & 1)) {
1414 	bitbuf = 0;
1415 	FORC(6) bitbuf |= (UINT64) fgetc(ifp) << c*8;
1416 	FORC(4) yuv[c] = (bitbuf >> c*12 & 0xfff) - (c >> 1 << 11);
1417       }
1418       rgb[0] = yuv[b] + 1.370705*yuv[3];
1419       rgb[1] = yuv[b] - 0.337633*yuv[2] - 0.698001*yuv[3];
1420       rgb[2] = yuv[b] + 1.732446*yuv[2];
1421       FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,0xfff)] / cam_mul[c];
1422     }
1423 }
1424 
1425 /*
1426    Returns 1 for a Coolpix 995, 0 for anything else.
1427  */
nikon_e995()1428 int CLASS nikon_e995()
1429 {
1430   int i, histo[256];
1431   const uchar often[] = { 0x00, 0x55, 0xaa, 0xff };
1432 
1433   memset (histo, 0, sizeof histo);
1434   fseek (ifp, -2000, SEEK_END);
1435   for (i=0; i < 2000; i++)
1436     histo[fgetc(ifp)]++;
1437   for (i=0; i < 4; i++)
1438     if (histo[often[i]] < 200)
1439       return 0;
1440   return 1;
1441 }
1442 
1443 /*
1444    Returns 1 for a Coolpix 2100, 0 for anything else.
1445  */
nikon_e2100()1446 int CLASS nikon_e2100()
1447 {
1448   uchar t[12];
1449   int i;
1450 
1451   fseek (ifp, 0, SEEK_SET);
1452   for (i=0; i < 1024; i++) {
1453     fread (t, 1, 12, ifp);
1454     if (((t[2] & t[4] & t[7] & t[9]) >> 4
1455 	& t[1] & t[6] & t[8] & t[11] & 3) != 3)
1456       return 0;
1457   }
1458   return 1;
1459 }
1460 
nikon_3700()1461 void CLASS nikon_3700()
1462 {
1463   int bits, i;
1464   uchar dp[24];
1465   static const struct {
1466     int bits;
1467     char make[12], model[15];
1468   } table[] = {
1469     { 0x00, "Pentax",  "Optio 33WR" },
1470     { 0x03, "Nikon",   "E3200" },
1471     { 0x32, "Nikon",   "E3700" },
1472     { 0x33, "Olympus", "C740UZ" } };
1473 
1474   fseek (ifp, 3072, SEEK_SET);
1475   fread (dp, 1, 24, ifp);
1476   bits = (dp[8] & 3) << 4 | (dp[20] & 3);
1477   for (i=0; i < sizeof table / sizeof *table; i++)
1478     if (bits == table[i].bits) {
1479       strcpy (make,  table[i].make );
1480       strcpy (model, table[i].model);
1481     }
1482 }
1483 
1484 /*
1485    Separates a Minolta DiMAGE Z2 from a Nikon E4300.
1486  */
minolta_z2()1487 int CLASS minolta_z2()
1488 {
1489   int i, nz;
1490   char tail[424];
1491 
1492   fseek (ifp, -(int)sizeof tail, SEEK_END);
1493   fread (tail, 1, sizeof tail, ifp);
1494   for (nz=i=0; i < sizeof tail; i++)
1495     if (tail[i]) nz++;
1496   return nz > 20;
1497 }
1498 
1499 /*RT  void CLASS jpeg_thumb(); */
1500 
ppm_thumb()1501 void CLASS ppm_thumb()
1502 {
1503   char *thumb;
1504   thumb_length = thumb_width*thumb_height*3;
1505   thumb = (char *) malloc (thumb_length);
1506   merror (thumb, "ppm_thumb()");
1507   fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
1508   fread  (thumb, 1, thumb_length, ifp);
1509   fwrite (thumb, 1, thumb_length, ofp);
1510   free (thumb);
1511 }
1512 
ppm16_thumb()1513 void CLASS ppm16_thumb()
1514 {
1515   int i;
1516   char *thumb;
1517   thumb_length = thumb_width*thumb_height*3;
1518   thumb = (char *) calloc (thumb_length, 2);
1519   merror (thumb, "ppm16_thumb()");
1520   read_shorts ((ushort *) thumb, thumb_length);
1521   for (i=0; i < thumb_length; i++)
1522     thumb[i] = ((ushort *) thumb)[i] >> 8;
1523   fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
1524   fwrite (thumb, 1, thumb_length, ofp);
1525   free (thumb);
1526 }
1527 
layer_thumb()1528 void CLASS layer_thumb()
1529 {
1530   int i, c;
1531   char *thumb, map[][4] = { "012","102" };
1532 
1533   colors = thumb_misc >> 5 & 7;
1534   thumb_length = thumb_width*thumb_height;
1535   thumb = (char *) calloc (colors, thumb_length);
1536   merror (thumb, "layer_thumb()");
1537   fprintf (ofp, "P%d\n%d %d\n255\n",
1538 	5 + (colors >> 1), thumb_width, thumb_height);
1539   fread (thumb, thumb_length, colors, ifp);
1540   for (i=0; i < thumb_length; i++)
1541     FORCC putc (thumb[i+thumb_length*(map[thumb_misc >> 8][c]-'0')], ofp);
1542   free (thumb);
1543 }
1544 
rollei_thumb()1545 void CLASS rollei_thumb()
1546 {
1547   unsigned i;
1548   ushort *thumb;
1549 
1550   thumb_length = thumb_width * thumb_height;
1551   thumb = (ushort *) calloc (thumb_length, 2);
1552   merror (thumb, "rollei_thumb()");
1553   fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
1554   read_shorts (thumb, thumb_length);
1555   for (i=0; i < thumb_length; i++) {
1556     putc (thumb[i] << 3, ofp);
1557     putc (thumb[i] >> 5  << 2, ofp);
1558     putc (thumb[i] >> 11 << 3, ofp);
1559   }
1560   free (thumb);
1561 }
1562 
rollei_load_raw()1563 void CLASS rollei_load_raw()
1564 {
1565   uchar pixel[10];
1566   unsigned iten=0, isix, i, buffer=0, todo[16];
1567 
1568   isix = raw_width * raw_height * 5 / 8;
1569   while (fread (pixel, 1, 10, ifp) == 10) {
1570     for (i=0; i < 10; i+=2) {
1571       todo[i]   = iten++;
1572       todo[i+1] = pixel[i] << 8 | pixel[i+1];
1573       buffer    = pixel[i] >> 2 | buffer << 6;
1574     }
1575     for (   ; i < 16; i+=2) {
1576       todo[i]   = isix++;
1577       todo[i+1] = buffer >> (14-i)*5;
1578     }
1579     for (i=0; i < 16; i+=2)
1580       raw_image[todo[i]] = (todo[i+1] & 0x3ff);
1581   }
1582   maximum = 0x3ff;
1583 }
1584 
raw(unsigned row,unsigned col)1585 int CLASS raw (unsigned row, unsigned col)
1586 {
1587   return (row < raw_height && col < raw_width) ? RAW(row,col) : 0;
1588 }
1589 
phase_one_flat_field(int is_float,int nc)1590 void CLASS phase_one_flat_field (int is_float, int nc)
1591 {
1592     ushort uhead[8];
1593 
1594     read_shorts (uhead, 8);
1595     if (uhead[2] * uhead[3] * uhead[4] * uhead[5] == 0) {
1596         return;
1597     }
1598     const unsigned wide = uhead[2] / uhead[4] + (uhead[2] % uhead[4] != 0);
1599     const unsigned high = uhead[3] / uhead[5] + (uhead[3] % uhead[5] != 0);
1600     const unsigned colLimit = std::min(uhead[0] + uhead[2] - uhead[4], (int)raw_width);
1601 
1602     const float head4 = 1.0 / uhead[4];
1603     const float head5 = 1.0 / uhead[5];
1604 
1605     float* mrow = (float *) calloc(nc * wide, sizeof *mrow);
1606     merror(mrow, "phase_one_flat_field()");
1607     for (unsigned x=0; x < wide; x++) {
1608         for (unsigned c=0; c < nc; c+=2) {
1609             float num = is_float ? getreal(11) : get2() / 32768.f;
1610             mrow[c * wide + x] = num;
1611         }
1612     }
1613     for (unsigned y=1; y < high; y++) {
1614         for (unsigned x=0; x < wide; x++) {
1615             for (unsigned c=0; c < nc; c+=2) {
1616                 float num = is_float ? getreal(11) : get2() / 32768.f;
1617                 mrow[(c + 1) * wide + x] = (num - mrow[c * wide + x]) * head5;
1618            }
1619         }
1620         const unsigned rend = uhead[1] + y * uhead[5];
1621         for (unsigned row = rend - uhead[5]; row < raw_height && row < rend && row < uhead[1] + uhead[3] - uhead[5]; row++) {
1622             unsigned cend = uhead[0] + uhead[4];
1623             const unsigned c0 = FC(row - top_margin, cend - uhead[4] - left_margin);
1624             const unsigned c = nc > 2 ? (c0 & 1) ? FC(row - top_margin, cend - uhead[4] - left_margin + 1) : c0 : 0;
1625             for (unsigned x=1; x < wide; x++, cend += uhead[4]) {
1626                 float mult0 = mrow[c * wide + x - 1];
1627                 float mult1 = (mrow[c * wide + x] - mult0) * head4;
1628                 if (nc > 2) {
1629                     mult0 += (c0 & 1) ? mult1 : 0;
1630                     for (unsigned col = cend - uhead[4] + (c0 & 1); col < std::min(colLimit, cend); col += 2) {
1631                         unsigned val = RAW(row, col) * mult0;
1632                         RAW(row, col) = rtengine::min(val, 65535u);
1633                         mult0 += mult1;
1634                         mult0 += mult1; // <= this could be reduced to one addition inside the loop, but then the result is not exactly the same as with old code, though it should be even more accurate then
1635                     }
1636                 } else {
1637                     for (unsigned col = cend - uhead[4]; col < std::min(colLimit, cend); col++) {
1638                         unsigned val = RAW(row, col) * mult0;
1639                         RAW(row, col) = rtengine::min(val, 65535u);
1640                         mult0 += mult1;
1641                     }
1642                 }
1643             }
1644             for (unsigned x = 0; x < wide; x++) {
1645                 for (unsigned c = 0; c < nc; c += 2) {
1646                     mrow[c * wide + x] += mrow[(c + 1) * wide + x];
1647                 }
1648             }
1649         }
1650     }
1651   free(mrow);
1652 }
1653 
phase_one_correct()1654 void CLASS phase_one_correct()
1655 {
1656     unsigned entries, tag, data, save, col, row, type;
1657     int len, i, j, k, cip, val[4], dev[4], sum, max;
1658     int head[9], diff, mindiff=INT_MAX, off_412=0;
1659     static const signed char dir[12][2] = { {-1,-1}, {-1,1}, {1,-1}, {1,1}, {-2,0}, {0,-2}, {0,2}, {2,0}, {-2,-2}, {-2,2}, {2,-2}, {2,2} };
1660     float poly[8], num, cfrac, frac, mult[2], *yval[2];
1661     ushort *xval[2];
1662     int qmult_applied = 0, qlin_applied = 0;
1663 
1664     if (half_size || !meta_length) {
1665         return;
1666     }
1667     if (verbose) {
1668         fprintf (stderr,_("Phase One correction...\n"));
1669     }
1670     fseek (ifp, meta_offset, SEEK_SET);
1671     order = get2();
1672     fseek (ifp, 6, SEEK_CUR);
1673     fseek (ifp, meta_offset+get4(), SEEK_SET);
1674     entries = get4();  get4();
1675     while (entries--) {
1676         tag  = get4();
1677         len  = get4();
1678         data = get4();
1679         save = ftell(ifp);
1680         fseek (ifp, meta_offset+data, SEEK_SET);
1681         if (tag == 0x419) {				/* Polynomial curve */
1682             for (get4(), i=0; i < 8; i++) {
1683                 poly[i] = getreal(11);
1684             }
1685             poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1;
1686             for (i=0; i < 0x10000; i++) {
1687                 num = (poly[5]*i + poly[3])*i + poly[1];
1688                 curve[i] = LIM(num,0,65535);
1689             }
1690             goto apply;				/* apply to right half */
1691         } else if (tag == 0x41a) {			/* Polynomial curve */
1692             for (i=0; i < 4; i++) {
1693                 poly[i] = getreal(11);
1694             }
1695             for (i=0; i < 0x10000; i++) {
1696                 for (num=0, j=4; j--;) {
1697                     num = num * i + poly[j];
1698                 }
1699             curve[i] = LIM(num+i,0,65535);
1700             }
1701             apply:					/* apply to whole image */
1702 #ifdef _OPENMP
1703             #pragma omp parallel for schedule(dynamic,16)
1704 #endif
1705             for (int row=0; row < raw_height; row++) {
1706                 for (int col = (tag & 1)*ph1.split_col; col < raw_width; col++) {
1707                     RAW(row,col) = curve[RAW(row,col)];
1708                 }
1709             }
1710         } else if (tag == 0x400) {			/* Sensor defects */
1711             while ((len -= 8) >= 0) {
1712 	            col  = get2();
1713 	            row  = get2();
1714 	            type = get2();
1715 	            get2();
1716 	            if (col >= raw_width) continue;
1717 	            if (type == 131 || type == 137) {		/* Bad column */
1718                     for (row=0; row < raw_height; row++) {
1719                         if (FC(row-top_margin,col-left_margin) == 1) {
1720                             for (sum=i=0; i < 4; i++)
1721                                 sum += val[i] = raw (row+dir[i][0], col+dir[i][1]);
1722                             for (max=i=0; i < 4; i++) {
1723                                 dev[i] = abs((val[i] << 2) - sum);
1724                                 if (dev[max] < dev[i]) max = i;
1725                             }
1726                             RAW(row,col) = (sum - val[max])/3.0 + 0.5;
1727                         } else {
1728                             for (sum=0, i=8; i < 12; i++)
1729                                 sum += raw (row+dir[i][0], col+dir[i][1]);
1730                             RAW(row,col) = 0.5 + sum * 0.0732233 + (raw(row,col-2) + raw(row,col+2)) * 0.3535534;
1731                         }
1732                     }
1733 	            } else if (type == 129) {			/* Bad pixel */
1734                     if (row >= raw_height) continue;
1735                     j = (FC(row-top_margin,col-left_margin) != 1) * 4;
1736                     for (sum=0, i=j; i < j+8; i++)
1737 	                    sum += raw (row+dir[i][0], col+dir[i][1]);
1738                     RAW(row,col) = (sum + 4) >> 3;
1739 	            }
1740             }
1741         } else if (tag == 0x401) {			/* All-color flat fields */
1742             phase_one_flat_field (1, 2);
1743         } else if (tag == 0x416 || tag == 0x410) {
1744             phase_one_flat_field (0, 2);
1745         } else if (tag == 0x40b) {			/* Red+blue flat field */
1746             phase_one_flat_field (0, 4);
1747         } else if (tag == 0x412) {
1748             fseek (ifp, 36, SEEK_CUR);
1749             diff = abs (get2() - ph1.tag_21a);
1750             if (mindiff > diff) {
1751 	            mindiff = diff;
1752 	            off_412 = ftell(ifp) - 38;
1753             }
1754         } else if (tag == 0x41f && !qlin_applied) { /* Quadrant linearization */
1755             ushort lc[2][2][16], ref[16];
1756             int qr, qc;
1757             for (qr = 0; qr < 2; qr++)
1758 	            for (qc = 0; qc < 2; qc++)
1759 	                for (i = 0; i < 16; i++)
1760 	                    lc[qr][qc][i] = get4();
1761             for (i = 0; i < 16; i++) {
1762 	            int v = 0;
1763 	            for (qr = 0; qr < 2; qr++)
1764 	                for (qc = 0; qc < 2; qc++)
1765 	                    v += lc[qr][qc][i];
1766 	            ref[i] = (v + 2) >> 2;
1767             }
1768             for (qr = 0; qr < 2; qr++) {
1769 	            for (qc = 0; qc < 2; qc++) {
1770 	                int cx[19], cf[19];
1771 	                for (i = 0; i < 16; i++) {
1772 	                    cx[1+i] = lc[qr][qc][i];
1773 	                    cf[1+i] = ref[i];
1774 	                }
1775 	                cx[0] = cf[0] = 0;
1776 	                cx[17] = cf[17] = ((unsigned) ref[15] * 65535) / lc[qr][qc][15];
1777 	                cx[18] = cf[18] = 65535;
1778 	                cubic_spline(cx, cf, 19);
1779 #ifdef _OPENMP
1780 	                #pragma omp parallel for schedule(dynamic,16)
1781 #endif
1782 	                for (int row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++)
1783                         for (int col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++)
1784                             RAW(row,col) = curve[RAW(row,col)];
1785 	            }
1786             }
1787             qlin_applied = 1;
1788         } else if (tag == 0x41e && !qmult_applied) { /* Quadrant multipliers */
1789             float qmult[2][2] = { { 1, 1 }, { 1, 1 } };
1790             get4(); get4(); get4(); get4();
1791             qmult[0][0] = 1.0 + getreal(11);
1792             get4(); get4(); get4(); get4(); get4();
1793             qmult[0][1] = 1.0 + getreal(11);
1794             get4(); get4(); get4();
1795             qmult[1][0] = 1.0 + getreal(11);
1796             get4(); get4(); get4();
1797             qmult[1][1] = 1.0 + getreal(11);
1798 #ifdef _OPENMP
1799             #pragma omp parallel for schedule(dynamic,16)
1800 #endif
1801             for (int row=0; row < raw_height; row++) {
1802                 for (int col=0; col < raw_width; col++) {
1803                     int i = qmult[row >= ph1.split_row][col >= ph1.split_col] * RAW(row,col);
1804                     RAW(row,col) = LIM(i,0,65535);
1805                 }
1806             }
1807             qmult_applied = 1;
1808         } else if (tag == 0x431 && !qmult_applied) { /* Quadrant combined */
1809             ushort lc[2][2][7], ref[7];
1810             int qr, qc;
1811             for (i = 0; i < 7; i++)
1812                 ref[i] = get4();
1813             for (qr = 0; qr < 2; qr++)
1814                 for (qc = 0; qc < 2; qc++)
1815                     for (i = 0; i < 7; i++)
1816                         lc[qr][qc][i] = get4();
1817             for (qr = 0; qr < 2; qr++) {
1818                 for (qc = 0; qc < 2; qc++) {
1819                     int cx[9], cf[9];
1820                     for (i = 0; i < 7; i++) {
1821                         cx[1+i] = ref[i];
1822                         cf[1+i] = ((unsigned) ref[i] * lc[qr][qc][i]) / 10000;
1823 	                }
1824 	                cx[0] = cf[0] = 0;
1825 	                cx[8] = cf[8] = 65535;
1826 	                cubic_spline(cx, cf, 9);
1827 	                for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++)
1828 	                    for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++)
1829 	                        RAW(row,col) = curve[RAW(row,col)];
1830                 }
1831             }
1832             qmult_applied = 1;
1833             qlin_applied = 1;
1834         }
1835         fseek (ifp, save, SEEK_SET);
1836     }
1837     if (off_412) {
1838         fseek (ifp, off_412, SEEK_SET);
1839         for (i=0; i < 9; i++)
1840             head[i] = get4() & 0x7fff;
1841         yval[0] = (float *) calloc (head[1]*head[3] + head[2]*head[4], 6);
1842         merror (yval[0], "phase_one_correct()");
1843         yval[1] = (float  *) (yval[0] + head[1]*head[3]);
1844         xval[0] = (ushort *) (yval[1] + head[2]*head[4]);
1845         xval[1] = (ushort *) (xval[0] + head[1]*head[3]);
1846         get2();
1847         for (i=0; i < 2; i++)
1848             for (j=0; j < head[i+1]*head[i+3]; j++)
1849 	            yval[i][j] = getreal(11);
1850         for (i=0; i < 2; i++)
1851             for (j=0; j < head[i+1]*head[i+3]; j++)
1852 	            xval[i][j] = get2();
1853         for (row=0; row < raw_height; row++)
1854             for (col=0; col < raw_width; col++) {
1855 	            cfrac = (float) col * head[3] / raw_width;
1856 	            cfrac -= cip = cfrac;
1857 	            num = RAW(row,col) * 0.5;
1858 	            for (i=cip; i < cip+2; i++) {
1859 	                for (k=j=0; j < head[1]; j++)
1860 	                    if (num < xval[0][k = head[1]*i+j])
1861 	                        break;
1862 	                frac = (j == 0 || j == head[1]) ? 0 : (xval[0][k] - num) / (xval[0][k] - xval[0][k-1]);
1863 	                mult[i-cip] = yval[0][k-1] * frac + yval[0][k] * (1-frac);
1864 	            }
1865 	            i = ((mult[0] * (1-cfrac) + mult[1] * cfrac) * row + num) * 2;
1866 	            RAW(row,col) = LIM(i,0,65535);
1867         }
1868         free (yval[0]);
1869     }
1870 }
1871 
phase_one_load_raw()1872 void CLASS phase_one_load_raw()
1873 {
1874   int a, b, i;
1875   ushort akey, bkey, mask;
1876 
1877   fseek (ifp, ph1.key_off, SEEK_SET);
1878   akey = get2();
1879   bkey = get2();
1880   mask = ph1.format == 1 ? 0x5555:0x1354;
1881   fseek (ifp, data_offset, SEEK_SET);
1882   read_shorts (raw_image, raw_width*raw_height);
1883   if (ph1.format)
1884     for (i=0; i < raw_width*raw_height; i+=2) {
1885       a = raw_image[i+0] ^ akey;
1886       b = raw_image[i+1] ^ bkey;
1887       raw_image[i+0] = (a & mask) | (b & ~mask);
1888       raw_image[i+1] = (b & mask) | (a & ~mask);
1889     }
1890 }
1891 
operator ()(int nbits,ushort * huff)1892 unsigned CLASS ph1_bithuff_t::operator() (int nbits, ushort *huff)
1893 {
1894 /*RT  static UINT64 bitbuf=0; */
1895 /*RT  static int vbits=0; */
1896   unsigned c;
1897 
1898   if (nbits == -1)
1899     return bitbuf = vbits = 0;
1900   if (nbits == 0) return 0;
1901   if (vbits < nbits) {
1902     bitbuf = bitbuf << 32 | get4();
1903     vbits += 32;
1904   }
1905   c = bitbuf << (64-vbits) >> (64-nbits);
1906   if (huff) {
1907     vbits -= huff[c] >> 8;
1908     return (uchar) huff[c];
1909   }
1910   vbits -= nbits;
1911   return c;
1912 }
1913 
operator ()(int nbits)1914 inline unsigned CLASS ph1_bithuff_t::operator() (int nbits)
1915 {
1916 /*RT  static UINT64 bitbuf=0; */
1917 /*RT  static int vbits=0; */
1918 
1919   if (vbits < nbits) {
1920     bitbuf = bitbuf << 32 | get4();
1921     vbits += 32;
1922   }
1923   unsigned c = bitbuf << (64-vbits) >> (64-nbits);
1924   vbits -= nbits;
1925   return c;
1926 }
1927 
operator ()()1928 inline unsigned CLASS ph1_bithuff_t::operator() ()
1929 {
1930 /*RT  static UINT64 bitbuf=0; */
1931 /*RT  static int vbits=0; */
1932   return bitbuf = vbits = 0;
1933 }
1934 
1935 
1936 #define ph1_init() ph1_bithuff()
1937 #define ph1_bits(n) ph1_bithuff(n)
1938 #define hb_bits(n) ph1_bithuff(n,0)
1939 #define ph1_huff(h) ph1_bithuff(*h,h+1)
1940 
1941 #ifndef MYFILE_MMAP
phase_one_load_raw_c()1942 void CLASS phase_one_load_raw_c()
1943 {
1944   static const int length[] = { 8,7,6,9,11,10,5,12,14,13 };
1945   int *offset, len[2], pred[2], row, col, i, j;
1946   ushort *pixel;
1947   short (*cblack)[2], (*rblack)[2];
1948 
1949   pixel = (ushort *) calloc (raw_width*3 + raw_height*4, 2);
1950   merror (pixel, "phase_one_load_raw_c()");
1951   offset = (int *) (pixel + raw_width);
1952   fseek (ifp, strip_offset, SEEK_SET);
1953   for (row=0; row < raw_height; row++)
1954     offset[row] = get4();
1955   cblack = (short (*)[2]) (offset + raw_height);
1956   fseek (ifp, ph1.black_col, SEEK_SET);
1957   if (ph1.black_col)
1958     read_shorts ((ushort *) cblack[0], raw_height*2);
1959   rblack = cblack + raw_height;
1960   fseek (ifp, ph1.black_row, SEEK_SET);
1961   if (ph1.black_row)
1962     read_shorts ((ushort *) rblack[0], raw_width*2);
1963   for (i=0; i < 256; i++)
1964     curve[i] = i*i / 3.969 + 0.5;
1965   ph1_bithuff_t ph1_bithuff(this, ifp, order);
1966   for (row=0; row < raw_height; row++) {
1967     fseek (ifp, data_offset + offset[row], SEEK_SET);
1968     ph1_init();
1969     pred[0] = pred[1] = 0;
1970     for (col=0; col < raw_width; col++) {
1971       if (col >= (raw_width & -8))
1972 	len[0] = len[1] = 14;
1973       else if ((col & 7) == 0)
1974 	for (i=0; i < 2; i++) {
1975 	  for (j=0; j < 5 && !ph1_bits(1); j++);
1976 	  if (j--) len[i] = length[j*2 + ph1_bits(1)];
1977 	}
1978       if ((i = len[col & 1]) == 14)
1979 	pixel[col] = pred[col & 1] = ph1_bits(16);
1980       else
1981 	pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1));
1982       if (pred[col & 1] >> 16) derror();
1983       if (ph1.format == 5 && pixel[col] < 256)
1984 	pixel[col] = curve[pixel[col]];
1985     }
1986     for (col=0; col < raw_width; col++) {
1987       i = (pixel[col] << 2*(ph1.format != 8)) - ph1.black
1988 	+ cblack[row][col >= ph1.split_col]
1989 	+ rblack[col][row >= ph1.split_row];
1990       if (i > 0) RAW(row,col) = i;
1991     }
1992   }
1993   free (pixel);
1994   maximum = 0xfffc - ph1.black;
1995 }
1996 #else
phase_one_load_raw_c()1997 void CLASS phase_one_load_raw_c()
1998 {
1999     static const int length[] = { 8,7,6,9,11,10,5,12,14,13 };
2000 
2001     int *offset = (int *)calloc(raw_width * 2 + raw_height * 4, 2);
2002     fseek(ifp, strip_offset, SEEK_SET);
2003     for (int row = 0; row < raw_height; row++) {
2004         offset[row] = get4();
2005     }
2006 
2007     short (*cblack)[2] = (short (*)[2]) (offset + raw_height);
2008     fseek(ifp, ph1.black_col, SEEK_SET);
2009     if (ph1.black_col) {
2010         read_shorts ((ushort *) cblack[0], raw_height * 2);
2011     }
2012 
2013     short (*rblack)[2] = cblack + raw_height;
2014     fseek(ifp, ph1.black_row, SEEK_SET);
2015     if (ph1.black_row) {
2016         read_shorts ((ushort *) rblack[0], raw_width * 2);
2017     }
2018 
2019     for (int i = 0; i < 256; i++) {
2020         curve[i] = i * i / 3.969 + 0.5;
2021     }
2022 
2023 #ifdef _OPENMP
2024 #pragma omp parallel
2025 #endif
2026 {
2027     int len[2], pred[2];
2028     IMFILE ifpthr = *ifp;
2029     ifpthr.plistener = nullptr;
2030 
2031 #ifdef _OPENMP
2032 #pragma omp master
2033 #endif
2034 {
2035     ifpthr.plistener = ifp->plistener;
2036 }
2037 
2038     ph1_bithuff_t ph1_bithuff(this, &ifpthr, order);
2039 
2040 #ifdef _OPENMP
2041     #pragma omp for schedule(dynamic,16)
2042 #endif
2043 
2044     for (int row = 0; row < raw_height; row++) {
2045         const int shift = 2 * (ph1.format != 8);
2046         fseek(&ifpthr, data_offset + offset[row], SEEK_SET);
2047         ph1_init();
2048         pred[0] = pred[1] = 0;
2049         for (int col = 0; col < raw_width; col++) {
2050             if (col >= (raw_width & -8)) {
2051 	            len[0] = len[1] = 14;
2052             } else if ((col & 7) == 0) {
2053                 for (int i = 0; i < 2; i++) {
2054                     int j;
2055                     for (j = 0; j < 5 && !ph1_bits(1); j++)
2056                         ;
2057 	                if (j--) {
2058                         len[i] = length[j * 2 + ph1_bits(1)];
2059 	                }
2060 	            }
2061             }
2062 
2063             int i = len[col & 1];
2064             ushort pixel;
2065             if (i == 14) {
2066 	            pixel = pred[col & 1] = ph1_bits(16);
2067             } else {
2068 	            pixel = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1));
2069             }
2070             if (ph1.format == 5 && pixel < 256) {
2071 	            pixel = curve[pixel];
2072             }
2073             int rawVal = (pixel << shift) - ph1.black + cblack[row][col >= ph1.split_col] + rblack[col][row >= ph1.split_row];
2074             RAW(row,col) = std::max(rawVal, 0);
2075         }
2076     }
2077 }
2078   free(offset);
2079   maximum = 0xfffc - ph1.black;
2080 }
2081 #endif
parse_hasselblad_gain()2082 void CLASS parse_hasselblad_gain()
2083 {
2084     /*
2085       Reverse-engineer's notes:
2086 
2087       The Hasselblad gain tag (0x19 in makernotes) is only available in the 3FR format and
2088       is applied and removed when Hasselblad Phocus converts it to the FFF format. It's
2089       always 0x300000 bytes large regardless of (tested) model, not all space in it is
2090       used though.
2091 
2092       It contains individual calibration information from the factory to tune the sensor
2093       performance.
2094 
2095       There is more calibration data in the tag than what is applied in conversion to FFF,
2096       I've only cared to figure out the data which is actually used, but have some leads on
2097       remaining info.
2098 
2099       The format is not equal between all models. Due to lack of 3FR files (harder to get
2100       than FFF) only a subset of the models have been reverse-engineered.
2101 
2102       The header space is 512 bytes and is a mix of 16 and 32 bit values. Offset to blocks
2103       are 32 bit values, but all information seems to be encoded in 16 bit values. Many
2104       values in the header can be zeroed with no effect on FFF conversion, and their
2105       meaning, if any, have not been further investigated.
2106 
2107       Formats:
2108       hdr16[22] = raw width
2109       hdr16[23] = raw height
2110       hdr32[24] = offset to level corr block
2111          Data block format. Seems to differ depending on sensor type. For tested H4D-50
2112          and H3D-31: 10 16 bit signed values per row
2113          value 0: a correction factor (k) used on even columns, where the new pixel value is
2114          calculated as follows:
2115          new_value = old_value + (2 * ((k * (old_value_on_row_above-256)) / 32767) - 2)
2116          note the connection to the value on the row above, seems to be some sort of signal
2117          leakage correction.
2118          value 1: same as value 0 but using old value on row below instead of above
2119          value 2-3: same as value 0-1 but for odd columns
2120          value 4-9: has some effect if non-zero (probably similar to the others) but not
2121          investigated which, as it's seems to be always zero for the tested cameras.
2122 
2123       hdr32[25] = probably offset to "bad/unreliable pixels" info, always 512 as it starts
2124                   directly after the header. Not applied in FFF conversion (at least
2125                   typically).
2126                   Data block format guess: raw_height packets of
2127                     <type?><number of coords><coords...>
2128 
2129       hdr32[27] = offset to unknown data (bad colulmns?), of the form:
2130                   <packet count><packets><0>
2131                   packet: <column><?><?><?>.
2132 
2133       hdr32[34] = curves offset, seems to be A/D curves (one per channel) on newer models
2134                   and some sort of a film curve on older. Not applied in FFF conversion.
2135 
2136       hdr32[36] = flatfield correction, not available in older models. Data format:
2137                   <1><block width><block height><rows><cols><11 * 2 pad><packets>
2138                   packet: <R><G1><G2><B>
2139 
2140                   The header pad is not zeroed and might seem to contain some sort of
2141                   information, but it makes no difference if set to zero. See
2142                   hasselblad_correct() how the flatfield is applied.
2143 
2144       Applied in FFF conversion is levels, flatfield correction, and the bad columns(?)
2145       data. A/D curves are surprisingly not applied, maybe pre-applied in hardware and
2146       only available as information? Levels are applied before flatfield, further
2147       ordering has not been investigated.
2148 
2149       Not all combinations/models have been tested so there may be gaps.
2150 
2151       Most clipped pixels in a 3FR is at 65535, but there's also some at 65534. Both
2152       are set to 65535 when calibrated, while 65533 is treated as a normal value. In
2153       the calibration process smaller values can be scaled to 65534 (which should
2154       not be seen as clipped).
2155     */
2156 
2157     int offset;
2158     off_t base;
2159 
2160     base = ftell(ifp);
2161     fseek(ifp, 2 * 23, SEEK_CUR);
2162     get2();
2163     fseek(ifp, 48, SEEK_CUR);
2164     offset = get4();
2165     hbd.levels = offset ? base + offset : 0;
2166     fseek(ifp, 8, SEEK_CUR);
2167     offset = get4();
2168     hbd.unknown1 = offset ? base + offset : 0;
2169     fseek(ifp, 32, SEEK_CUR);
2170     offset = get4();
2171     hbd.flatfield = (offset && (base + offset < ifp->size)) ? base + offset : 0;
2172 }
2173 
hasselblad_correct()2174 void CLASS hasselblad_correct()
2175 {
2176     unsigned col, row;
2177 
2178     /*
2179 
2180       This function applies 3FR calibration data. At the time of writing it supports a
2181       subset, so here's a todo list:
2182 
2183       TODO:
2184        - Support all gain tag formats
2185           - The 0x19 tag varies a bit between models. We don't have parsers for all models.
2186           - The reference model used was during initial reverse-engineering was a H4D-50,
2187             we probably support the Hasselblads with Kodak 31, 39, 40 and 50 megapixels
2188             well, but more work is needed for Kodak 16 and 22, Dalsa 60 and Sony 50.
2189        - Apply bad column(?) data (hbd.unknown1)
2190           - It was left out in this initial release since the effect is very small.
2191        - Apply black(?) data, tag 0x1a and 0x1b is not parsed, it has however marginal
2192          effect (at least for shorter exposures) so it's not too important.
2193 
2194       While there are things to do, the current implementation supports the most
2195       important aspects, the faltfield and levels calibrations applied can have strong
2196       visible effects.
2197 
2198      */
2199 
2200     if (hbd.levels) {
2201         int i;
2202         fseek(ifp, hbd.levels, SEEK_SET);
2203         /* skip the first set (not used as we don't apply on first/last row), we look at it though to see if
2204            the levels format is one that we support (there are other formats on some models which is not
2205            supported here) */
2206         short test[10];
2207         for (i = 0; i < 10; i++) test[i] = (short)get2();
2208         if (test[5] == 0 && test[6] == 0 && test[7] == 0 && test[8] == 0 && test[9] == 0) {
2209             int corr[4];
2210             ushort *row_above = (ushort *)malloc(sizeof(ushort) * raw_width); // we need to cache row above as we write new values as we go
2211             for (col = 0; col < raw_width; col++) row_above[col] = RAW(0,col);
2212             for (row = 1; row < raw_height-1; row++) {
2213                 for (i = 0; i < 4; i++) corr[i] = (short)get2();
2214                 fseek(ifp, 6 * 2, SEEK_CUR);
2215                 for (col = 0; col < raw_width; col++) {
2216                     unsigned v = RAW(row,col);
2217 		    if (v >= 65534) {
2218 		        v = 65535;
2219 		    } else {
2220 		        if (corr[((col & 1)<<1)+0] && row_above[col] > black) v += 2 * ((corr[((col & 1)<<1)+0] * (row_above[col]-(int)black)) / 32767) - 2;
2221 			if (corr[((col & 1)<<1)+1] && RAW(row+1,col) > black) v += 2 * ((corr[((col & 1)<<1)+1] * (RAW(row+1,col)-(int)black)) / 32767) - 2;
2222 		    }
2223                     row_above[col] = RAW(row,col);
2224                     RAW(row,col) = CLIP(v);
2225                 }
2226             }
2227             free(row_above);
2228         }
2229     }
2230 
2231     if (hbd.flatfield) {
2232         int bw, bh, ffrows, ffcols, i, c;
2233         ushort ref[4], ref_max;
2234         fseek(ifp, hbd.flatfield, SEEK_SET);
2235         get2();
2236         bw = get2();
2237         bh = get2();
2238         ffcols = get2();
2239         ffrows = get2();
2240         fseek(ifp, hbd.flatfield + 16 * 2, SEEK_SET);
2241         unsigned toRead = sizeof(ushort) * 4 * ffcols * ffrows;
2242         if (toRead > ifp->size) { // there must be something wrong, see Issue #4748
2243             return;
2244         }
2245 
2246         ushort *ffmap = (ushort *)malloc(toRead);
2247         for (i = 0; i < 4 * ffcols * ffrows; i++) ffmap[i] = get2();
2248 
2249         /* Get reference values from center of field. This seems to be what Phocus does too,
2250            but haven't cared to figure out exactly at which coordinate */
2251         i = 4 * (ffcols * ffrows / 2 + ffcols / 2);
2252         ref[0] = ffmap[i+0];
2253         ref[1] = ffmap[i+1];
2254         ref[3] = ffmap[i+2]; // G2 = index 3 in dcraw, 2 in 3FR
2255         ref[2] = ffmap[i+3];
2256         ref_max = 0;
2257         FORC4 if (ref[c] > ref_max) ref_max = ref[c];
2258         if (ref_max == 0) ref[0] = ref[1] = ref[2] = ref[3] = ref_max = 10000;
2259 
2260         /* Convert measured flatfield values to actual multipliers. The measured flatfield
2261            can have vignetting which should be normalized, only color cast should be corrected. */
2262         for (i = 0; i < 4 * ffcols * ffrows; i += 4) {
2263             double base, min = 65535.0, max = 0;
2264             double cur[4];
2265             cur[0] = (double)ffmap[i+0] / ref[0];
2266             cur[1] = (double)ffmap[i+1] / ref[1];
2267             cur[3] = (double)ffmap[i+2] / ref[3]; // G2 index differs in dcraw and 3FR
2268             cur[2] = (double)ffmap[i+3] / ref[2];
2269             FORC4 {
2270                 if (cur[c] < min) min = cur[c];
2271                 if (cur[c] > max) max = cur[c];
2272             }
2273             if (max == 0) max = 1.0;
2274             base = (cur[0]+cur[1]+cur[2]+cur[3])/(max*4);
2275             FORC4 cur[c] = cur[c] == 0 ? 1.0 : (base * max) / cur[c];
2276             /* convert to integer multiplier and store back to ffmap, we limit
2277                range to 4 (16384*4) which should be fine for flatfield */
2278             FORC4 {
2279                 cur[c] *= 16384.0;
2280                 if (cur[c] > 65535.0) cur[c] = 65535.0;
2281                 ffmap[i+c] = (ushort)cur[c];
2282             }
2283         }
2284 
2285         // of the cameras we've tested we know the exact placement of the flatfield map
2286         int row_offset, col_offset;
2287         switch (raw_width) {
2288         case 8282: // 50 megapixel Kodak
2289             row_offset = 21;
2290             col_offset = 71;
2291             break;
2292         default:
2293             /* Default case for camera models we've not tested. We center the map, which may
2294                not be exactly where it should be but close enough for the smooth flatfield */
2295             row_offset = (raw_height - bh * ffrows) / 2;
2296             col_offset = (raw_width - bw * ffcols) / 2;
2297             break;
2298         }
2299 
2300         /*
2301           Concerning smoothing between blocks in the map Phocus makes it only vertically,
2302           probably because it's simpler and faster. Looking at actual flatfield data it seems
2303           like it's better to smooth in both directions. Possibly flatfield could be used for
2304           correcting tiling on Dalsa sensors (H4D-60) like partly done in Phase One IIQ format,
2305           and then sharp edges may be beneficial at least at the tiling seams, but at the time
2306           of writing I've had no H4D-60 3FR files to test with to verify that.
2307 
2308           Meanwhile we do both vertical and horizontal smoothing/blurring.
2309         */
2310 
2311         /* pre-calculate constants for blurring. We probably should make a more efficient
2312            blur than this, but this does not need any buffer and makes nice-looking
2313            radial gradients */
2314         ushort *corners_weight = (ushort *)malloc(bw*bh*9*sizeof(*corners_weight));
2315         const int corners_mix[9][4][2] = { { {0,0}, {0,1}, {1,0}, {1,1} },
2316                                             { {0,1}, {1,1}, {-1,-1}, {-1,-1} },
2317                                             { {0,1}, {0,2}, {1,1}, {1,2} },
2318                                             { {1,0}, {1,1}, {-1,-1}, {-1,-1} },
2319                                             { {1,1}, {-1,-1}, {-1,-1}, {-1,-1} },
2320                                             { {1,1}, {1,2}, {-1,-1}, {-1,-1} },
2321                                             { {1,0}, {1,1}, {2,0}, {2,1} },
2322                                             { {1,1}, {2,1}, {-1,-1}, {-1,-1} },
2323                                             { {1,1}, {1,2}, {2,1}, {2,2} } };
2324         const ushort corners_shift[9] = { 2, 1, 2, 1, 0, 1, 2, 1, 2 };
2325         for (row = 0; row < bh; row++) {
2326             const ushort maxdist = bw < bh ? bw/2-1 : bh/2-1;
2327             const unsigned bwu = (unsigned)bw;
2328             const unsigned bhu = (unsigned)bh;
2329             const unsigned corners[9][2] = {{0,0},    {0,bwu/2},    {0,bwu-1},
2330                                             {bhu/2,0},{bhu/2,bwu/2},{bhu/2,bwu-1},
2331                                             {bhu-1,0},{bhu-1,bwu/2},{bhu-1,bwu-1}};
2332             for (col = 0; col < bw; col++) {
2333                 for (i = 0; i < 9; i++) {
2334                     ushort dist = (ushort)sqrt(abs((int)(corners[i][0] - row)) * abs((int)(corners[i][0] - row)) + abs((int)(corners[i][1] - col)) * abs((int)(corners[i][1] - col)));
2335                     ushort weight = dist > maxdist ? 0 : maxdist - dist;
2336                     corners_weight[9*(row*bw+col)+i] = weight;
2337                 }
2338             }
2339         }
2340 
2341         // apply flatfield
2342 #ifdef _OPENMP
2343 #pragma omp parallel for
2344 #endif
2345         for (int row = 0; row < raw_height; row++) {
2346             int ffs, cur_ffr, i, c;
2347             if (row < row_offset) {
2348                 cur_ffr = row_offset;
2349                 ffs = 0;
2350             } else if (row >= row_offset + ffrows * bh) {
2351                 cur_ffr = row_offset + (ffrows-1) * bh;
2352                 ffs = 4 * ffcols * (ffrows-1);
2353             } else {
2354                 cur_ffr = row_offset + bh * ((row - row_offset) / bh);
2355                 ffs = 4 * ffcols * ((row - row_offset) / bh);
2356             }
2357             int next_ffc = 0, cur_ffc = col_offset;
2358             int ffc = ffs;
2359             ushort *cur[3][3]; // points to local ffmap entries with center at cur[1][1]
2360             for (int col = 0; col < raw_width; col++) {
2361                 if (col == next_ffc) {
2362                     int rowsub = ffs == 0 ? 0 : ffcols*4;
2363                     int rowadd = ffs == 4 * ffcols * (ffrows-1) ? 0 : ffcols * 4;
2364                     int colsub = ffc == ffs ? 0 : 4;
2365                     int coladd = ffc == ffs + 4 * (ffcols-1) ? 0 : 4;
2366                     if (col != 0) cur_ffc = next_ffc;
2367                     else next_ffc += col_offset;
2368                     next_ffc += bw;
2369 
2370                     cur[0][0] = &ffmap[ffc-rowsub-colsub];
2371                     cur[0][1] = &ffmap[ffc-rowsub];
2372                     cur[0][2] = &ffmap[ffc-rowsub+coladd];
2373 
2374                     cur[1][0] = &ffmap[ffc-colsub];
2375                     cur[1][1] = &ffmap[ffc];
2376                     cur[1][2] = &ffmap[ffc+coladd];
2377 
2378                     cur[2][0] = &ffmap[ffc+rowadd-colsub];
2379                     cur[2][1] = &ffmap[ffc+rowadd];
2380                     cur[2][2] = &ffmap[ffc+rowadd+coladd];
2381 
2382                     ffc += 4;
2383                     if (ffc == ffs + 4 * ffcols) next_ffc += raw_width; // last col in map, avoid stepping further
2384                 }
2385                 unsigned v = RAW(row,col);
2386                 if (v > black && v < 65535) {
2387                     c = FC(row,col);
2388                     unsigned x = col < cur_ffc ? 0 : col - cur_ffc;
2389                     unsigned y = row < cur_ffr ? 0 : row - cur_ffr;
2390                     if (x >= bw) x = bw-1;
2391                     if (y >= bh) y = bh-1;
2392                     unsigned wsum = 0;
2393                     unsigned mul = 0;
2394                     for (i = 0; i < 9; i++) {
2395                         ushort cw = corners_weight[9*(y*bw+x)+i];
2396                         if (cw) {
2397                             unsigned m = 0;
2398                             int j;
2399                             for (j = 0; j < 1 << corners_shift[i]; j++) {
2400                                 int cr = corners_mix[i][j][0], cc = corners_mix[i][j][1];
2401                                 m += cur[cr][cc][c];
2402                             }
2403                             m >>= corners_shift[i];
2404                             mul += m * cw;
2405                             wsum += cw;
2406                         }
2407                     }
2408                     mul /= wsum;
2409                     v = black + ((v-black) * mul) / 16384;
2410                     RAW(row,col) = v > 65535 ? 65535 : v;
2411                 }
2412             }
2413         }
2414         free(ffmap);
2415         free(corners_weight);
2416     }
2417 }
2418 
hasselblad_load_raw()2419 void CLASS hasselblad_load_raw()
2420 {
2421     struct jhead jh;
2422     int diff[12];
2423 
2424     if (!ljpeg_start (&jh, 0)) {
2425         return;
2426     }
2427     order = 0x4949;
2428     ph1_bithuff_t ph1_bithuff(this, ifp, order);
2429     hb_bits(-1);
2430     const int shot = LIM(shot_select, 1, tiff_samples) - 1;
2431     const int predictor_init = static_cast<int>(0x8000 + load_flags);
2432     for (int row = 0; row < raw_height; ++row) {
2433         int stashed_predictors[2] = {predictor_init, predictor_init};
2434         for (int col = 0; col < raw_width; col += 2) {
2435             for (int s = 0; s < tiff_samples * 2; s += 2) {
2436                 const int len[2]= {
2437                     static_cast<int>(ph1_huff(jh.huff[0])),
2438                     static_cast<int>(ph1_huff(jh.huff[0]))
2439                 };
2440                 for (int c = 0; c < 2; ++c) {
2441                     diff[s + c] = hb_bits(len[c]);
2442                     if ((diff[s + c] & (1 << (len[c] - 1))) == 0) {
2443                         diff[s + c] -= (1 << len[c]) - 1;
2444                     }
2445                     if (diff[s + c] == 65535) {
2446                         diff[s + c] = -32768;
2447                     }
2448                 }
2449             }
2450             for (int s = col; s < col + 2; ++s) {
2451                 int pred = stashed_predictors[s & 1];
2452                 for (int c = 0; c < tiff_samples; ++c) {
2453                     pred += diff[(s & 1) * tiff_samples + c];
2454                     const unsigned upix = pred & 0xffff;
2455                     if (raw_image && c == shot) {
2456                         RAW(row, s) = upix;
2457                     }
2458                     if (image) {
2459                         const int f = (row & 1) * 3 ^ ((col + s) & 1);
2460                         const unsigned urow = row - top_margin  + (c & 1);
2461                         const unsigned ucol = col - left_margin - ((c >> 1) & 1);
2462                         ushort* const ip = &image[urow * width + ucol][f];
2463                         if (urow < height && ucol < width) {
2464                             *ip = c < 4 ? upix : (*ip + upix) >> 1;
2465                         }
2466                     }
2467                     if (c == (tiff_samples-1)) {
2468                       stashed_predictors[s & 1] = pred;
2469                     }
2470                 }
2471             }
2472         }
2473     }
2474     ljpeg_end(&jh);
2475     if (image) {
2476         mix_green = 1;
2477     }
2478 }
2479 
leaf_hdr_load_raw()2480 void CLASS leaf_hdr_load_raw()
2481 {
2482   ushort *pixel=0;
2483   unsigned tile=0, r, c, row, col;
2484 
2485   if (!filters) {
2486     pixel = (ushort *) calloc (raw_width, sizeof *pixel);
2487     merror (pixel, "leaf_hdr_load_raw()");
2488   }
2489   FORC(tiff_samples)
2490     for (r=0; r < raw_height; r++) {
2491       if (r % tile_length == 0) {
2492 	fseek (ifp, data_offset + 4*tile++, SEEK_SET);
2493 	fseek (ifp, get4(), SEEK_SET);
2494       }
2495       if (filters && c != shot_select) continue;
2496       if (filters) pixel = raw_image + r*raw_width;
2497       read_shorts (pixel, raw_width);
2498       if (!filters && (row = r - top_margin) < height)
2499 	for (col=0; col < width; col++)
2500 	  image[row*width+col][c] = pixel[col+left_margin];
2501     }
2502   if (!filters) {
2503     maximum = 0xffff;
2504     raw_color = 1;
2505     free (pixel);
2506   }
2507 }
2508 
unpacked_load_raw()2509 void CLASS unpacked_load_raw()
2510 {
2511   int row, col, bits=0;
2512 
2513   while (1 << ++bits < maximum);
2514   read_shorts (raw_image, raw_width*raw_height);
2515   if (load_flags) {
2516       for (row=0; row < raw_height; row++)
2517         for (col=0; col < raw_width; col++)
2518           if ((RAW(row,col) >>= load_flags) >> bits
2519         && (unsigned) (row-top_margin) < height
2520         && (unsigned) (col-left_margin) < width) derror();
2521   } else if (bits < 16) {
2522       for (row=0; row < raw_height; row++)
2523         for (col=0; col < raw_width; col++)
2524           if (RAW(row,col) >> bits
2525         && (unsigned) (row-top_margin) < height
2526         && (unsigned) (col-left_margin) < width) derror();
2527   }
2528 }
2529 
2530 
2531 // RT
sony_arq_load_raw()2532 void CLASS sony_arq_load_raw()
2533 {
2534     constexpr unsigned frame2pos[] = { 0, 1, 3, 2 };
2535     const unsigned frame = frame2pos[shot_select];
2536 
2537     // allocate memory for a row of pixels
2538     ushort *samples = new ushort[4 * raw_width];
2539 
2540     int bits = 0;
2541     while (1 << ++bits < maximum)
2542         ;
2543     bits = (1 << bits) - 1;
2544 
2545     for (int row = 0; row < ((frame < 2) ? 1 : raw_height); row++) {
2546         for (int col = 0; col < ((row == 0) ? raw_width : 1); col++) {
2547             RAW(row, col) = 0;
2548         }
2549     }
2550 
2551     for (int row = 0; row < raw_height; ++row) {
2552         int r = row + (frame & 1);
2553         read_shorts(samples, 4 * raw_width);
2554         if (r < raw_height) {
2555             int offset = 2 * (r & 1);
2556             for (int c = (frame >> 1) & 1; c < raw_width; ++c, offset += 4) {
2557                 RAW(r, c) = samples[offset + (c & 1)] & bits;
2558             }
2559         }
2560     }
2561     delete [] samples;
2562 }
2563 
2564 
sinar_4shot_load_raw()2565 void CLASS sinar_4shot_load_raw()
2566 {
2567   ushort *pixel;
2568   unsigned shot, row, col, r, c;
2569 
2570   if (raw_image) {
2571     shot = LIM (shot_select, 1, 4) - 1;
2572     fseek (ifp, data_offset + shot*4, SEEK_SET);
2573     fseek (ifp, get4(), SEEK_SET);
2574     unpacked_load_raw();
2575     return;
2576   }
2577   pixel = (ushort *) calloc (raw_width, sizeof *pixel);
2578   merror (pixel, "sinar_4shot_load_raw()");
2579   for (shot=0; shot < 4; shot++) {
2580     fseek (ifp, data_offset + shot*4, SEEK_SET);
2581     fseek (ifp, get4(), SEEK_SET);
2582     for (row=0; row < raw_height; row++) {
2583       read_shorts (pixel, raw_width);
2584       if ((r = row-top_margin - (shot >> 1 & 1)) >= height) continue;
2585       for (col=0; col < raw_width; col++) {
2586 	if ((c = col-left_margin - (shot & 1)) >= width) continue;
2587 	image[r*width+c][(row & 1)*3 ^ (~col & 1)] = pixel[col];
2588       }
2589     }
2590   }
2591   free (pixel);
2592   mix_green = 1;
2593 }
2594 
imacon_full_load_raw()2595 void CLASS imacon_full_load_raw()
2596 {
2597   int row, col;
2598 
2599   if (!image) return;
2600   for (row=0; row < height; row++)
2601     for (col=0; col < width; col++)
2602       read_shorts (image[row*width+col], 3);
2603 }
2604 
packed_load_raw()2605 void CLASS packed_load_raw()
2606 {
2607   int vbits=0, bwide, rbits, bite, half, irow, row, col, val, i;
2608   UINT64 bitbuf=0;
2609 
2610   bwide = raw_width * tiff_bps / 8;
2611   bwide += bwide & load_flags >> 9;
2612   bwide += row_padding;
2613   rbits = bwide * 8 - raw_width * tiff_bps;
2614   if (load_flags & 1) bwide = bwide * 16 / 15;
2615   bite = 8 + (load_flags & 56);
2616   half = (raw_height+1) >> 1;
2617   for (irow=0; irow < raw_height; irow++) {
2618     row = irow;
2619     if (load_flags & 2 &&
2620 	(row = irow % half * 2 + irow / half) == 1 &&
2621 	load_flags & 4) {
2622       if (vbits=0, tiff_compress)
2623 	fseek (ifp, data_offset - (-half*bwide & -2048), SEEK_SET);
2624       else {
2625 	fseek (ifp, 0, SEEK_END);
2626 	fseek (ifp, ftell(ifp) >> 3 << 2, SEEK_SET);
2627       }
2628     }
2629     for (col=0; col < raw_width; col++) {
2630       for (vbits -= tiff_bps; vbits < 0; vbits += bite) {
2631 	bitbuf <<= bite;
2632 	for (i=0; i < bite; i+=8)
2633 	  bitbuf |= ((UINT64) fgetc(ifp) << i);
2634       }
2635       val = bitbuf << (64-tiff_bps-vbits) >> (64-tiff_bps);
2636       RAW(row,col ^ (load_flags >> 6 & 3)) = val;
2637       if (load_flags & 1 && (col % 10) == 9 && fgetc(ifp) &&
2638 	row < height+top_margin && col < width+left_margin) derror();
2639     }
2640     vbits -= rbits;
2641   }
2642 }
2643 
nokia_load_raw()2644 void CLASS nokia_load_raw()
2645 {
2646   uchar  *data,  *dp;
2647   int rev, dwide, row, col, c;
2648   double sum[]={0,0};
2649 
2650   rev = 3 * (order == 0x4949);
2651   dwide = (raw_width * 5 + 1) / 4;
2652   data = (uchar *) malloc (dwide*2);
2653   merror (data, "nokia_load_raw()");
2654   for (row=0; row < raw_height; row++) {
2655     if (fread (data+dwide, 1, dwide, ifp) < dwide) derror();
2656     FORC(dwide) data[c] = data[dwide+(c ^ rev)];
2657     for (dp=data, col=0; col < raw_width; dp+=5, col+=4)
2658       FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3);
2659   }
2660   free (data);
2661   maximum = 0x3ff;
2662   if (strcmp(make,"OmniVision")) return;
2663   row = raw_height/2;
2664   FORC(width-1) {
2665     sum[ c & 1] += SQR(RAW(row,c)-RAW(row+1,c+1));
2666     sum[~c & 1] += SQR(RAW(row+1,c)-RAW(row,c+1));
2667   }
2668   if (sum[1] > sum[0]) filters = 0x4b4b4b4b;
2669 }
2670 
canon_rmf_load_raw()2671 void CLASS canon_rmf_load_raw()
2672 {
2673   int row, col, bits, orow, ocol, c;
2674 
2675   for (row=0; row < raw_height; row++)
2676     for (col=0; col < raw_width-2; col+=3) {
2677       bits = get4();
2678       FORC3 {
2679 	orow = row;
2680 	if ((ocol = col+c-4) < 0) {
2681 	  ocol += raw_width;
2682 	  if ((orow -= 2) < 0)
2683 	    orow += raw_height;
2684 	}
2685 	RAW(orow,ocol) = curve[bits >> (10*c+2) & 0x3ff];
2686       }
2687     }
2688   maximum = curve[0x3ff];
2689 }
2690 
2691 
olympus_load_raw()2692 void CLASS olympus_load_raw()
2693 {
2694   ushort huff[4096];
2695   int row, col, nbits, sign, low, high, i, c, w, n, nw;
2696   int acarry[2][3], *carry, pred, diff;
2697 
2698   huff[n=0] = 0xc0c;
2699   for (i=12; i--; )
2700     FORC(2048 >> i) huff[++n] = (i+1) << 8 | i;
2701   fseek (ifp, 7, SEEK_CUR);
2702   getbits(-1);
2703   for (row=0; row < height; row++) {
2704     memset (acarry, 0, sizeof acarry);
2705     for (col=0; col < raw_width; col++) {
2706       carry = acarry[col & 1];
2707       i = 2 * (carry[2] < 3);
2708       for (nbits=2+i; (ushort) carry[0] >> (nbits+i); nbits++);
2709       low = (sign = getbits(3)) & 3;
2710       sign = sign << 29 >> 31;
2711       if ((high = getbithuff(12,huff)) == 12)
2712 	high = getbits(16-nbits) >> 1;
2713       carry[0] = (high << nbits) | getbits(nbits);
2714       diff = (carry[0] ^ sign) + carry[1];
2715       carry[1] = (diff*3 + carry[1]) >> 5;
2716       carry[2] = carry[0] > 16 ? 0 : carry[2]+1;
2717       if (col >= width) continue;
2718       if (row < 2 && col < 2) pred = 0;
2719       else if (row < 2) pred = RAW(row,col-2);
2720       else if (col < 2) pred = RAW(row-2,col);
2721       else {
2722 	w  = RAW(row,col-2);
2723 	n  = RAW(row-2,col);
2724 	nw = RAW(row-2,col-2);
2725 	if ((w < nw && nw < n) || (n < nw && nw < w)) {
2726 	  if (ABS(w-nw) > 32 || ABS(n-nw) > 32)
2727 	    pred = w + n - nw;
2728 	  else pred = (w + n) >> 1;
2729 	} else pred = ABS(w-nw) > ABS(n-nw) ? w : n;
2730       }
2731       if ((RAW(row,col) = pred + ((diff << 2) | low)) >> 12) derror();
2732     }
2733   }
2734 }
2735 
minolta_rd175_load_raw()2736 void CLASS minolta_rd175_load_raw()
2737 {
2738   uchar pixel[768];
2739   unsigned irow, box, row, col;
2740 
2741   for (irow=0; irow < 1481; irow++) {
2742     if (fread (pixel, 1, 768, ifp) < 768) derror();
2743     box = irow / 82;
2744     row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box-12)*2);
2745     switch (irow) {
2746       case 1477: case 1479: continue;
2747       case 1476: row = 984; break;
2748       case 1480: row = 985; break;
2749       case 1478: row = 985; box = 1;
2750     }
2751     if ((box < 12) && (box & 1)) {
2752       for (col=0; col < 1533; col++, row ^= 1)
2753 	if (col != 1) RAW(row,col) = (col+1) & 2 ?
2754 		   pixel[col/2-1] + pixel[col/2+1] : pixel[col/2] << 1;
2755       RAW(row,1)    = pixel[1]   << 1;
2756       RAW(row,1533) = pixel[765] << 1;
2757     } else
2758       for (col=row & 1; col < 1534; col+=2)
2759 	RAW(row,col) = pixel[col/2] << 1;
2760   }
2761   maximum = 0xff << 1;
2762 }
2763 
quicktake_100_load_raw()2764 void CLASS quicktake_100_load_raw()
2765 {
2766   uchar pixel[484][644];
2767   static const short gstep[16] =
2768   { -89,-60,-44,-32,-22,-15,-8,-2,2,8,15,22,32,44,60,89 };
2769   static const short rstep[6][4] =
2770   { {  -3,-1,1,3  }, {  -5,-1,1,5  }, {  -8,-2,2,8  },
2771     { -13,-3,3,13 }, { -19,-4,4,19 }, { -28,-6,6,28 } };
2772   static const short curve[256] =
2773   { 0,1,2,3,4,5,6,7,8,9,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,
2774     28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,53,
2775     54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78,
2776     79,80,81,82,83,84,86,88,90,92,94,97,99,101,103,105,107,110,112,114,116,
2777     118,120,123,125,127,129,131,134,136,138,140,142,144,147,149,151,153,155,
2778     158,160,162,164,166,168,171,173,175,177,179,181,184,186,188,190,192,195,
2779     197,199,201,203,205,208,210,212,214,216,218,221,223,226,230,235,239,244,
2780     248,252,257,261,265,270,274,278,283,287,291,296,300,305,309,313,318,322,
2781     326,331,335,339,344,348,352,357,361,365,370,374,379,383,387,392,396,400,
2782     405,409,413,418,422,426,431,435,440,444,448,453,457,461,466,470,474,479,
2783     483,487,492,496,500,508,519,531,542,553,564,575,587,598,609,620,631,643,
2784     654,665,676,687,698,710,721,732,743,754,766,777,788,799,810,822,833,844,
2785     855,866,878,889,900,911,922,933,945,956,967,978,989,1001,1012,1023 };
2786   int rb, row, col, sharp, val=0;
2787 
2788   getbits(-1);
2789   memset (pixel, 0x80, sizeof pixel);
2790   for (row=2; row < height+2; row++) {
2791     for (col=2+(row & 1); col < width+2; col+=2) {
2792       val = ((pixel[row-1][col-1] + 2*pixel[row-1][col+1] +
2793 		pixel[row][col-2]) >> 2) + gstep[getbits(4)];
2794       pixel[row][col] = val = LIM(val,0,255);
2795       if (col < 4)
2796 	pixel[row][col-2] = pixel[row+1][~row & 1] = val;
2797       if (row == 2)
2798 	pixel[row-1][col+1] = pixel[row-1][col+3] = val;
2799     }
2800     pixel[row][col] = val;
2801   }
2802   for (rb=0; rb < 2; rb++)
2803     for (row=2+rb; row < height+2; row+=2)
2804       for (col=3-(row & 1); col < width+2; col+=2) {
2805 	if (row < 4 || col < 4) sharp = 2;
2806 	else {
2807 	  val = ABS(pixel[row-2][col] - pixel[row][col-2])
2808 	      + ABS(pixel[row-2][col] - pixel[row-2][col-2])
2809 	      + ABS(pixel[row][col-2] - pixel[row-2][col-2]);
2810 	  sharp = val <  4 ? 0 : val <  8 ? 1 : val < 16 ? 2 :
2811 		  val < 32 ? 3 : val < 48 ? 4 : 5;
2812 	}
2813 	val = ((pixel[row-2][col] + pixel[row][col-2]) >> 1)
2814 	      + rstep[sharp][getbits(2)];
2815 	pixel[row][col] = val = LIM(val,0,255);
2816 	if (row < 4) pixel[row-2][col+2] = val;
2817 	if (col < 4) pixel[row+2][col-2] = val;
2818       }
2819   for (row=2; row < height+2; row++)
2820     for (col=3-(row & 1); col < width+2; col+=2) {
2821       val = ((pixel[row][col-1] + (pixel[row][col] << 2) +
2822 	      pixel[row][col+1]) >> 1) - 0x100;
2823       pixel[row][col] = LIM(val,0,255);
2824     }
2825   for (row=0; row < height; row++)
2826     for (col=0; col < width; col++)
2827       RAW(row,col) = curve[pixel[row+2][col+2]];
2828   maximum = 0x3ff;
2829 }
2830 
2831 #define radc_token(tree) ((signed char) getbithuff(8,huff[tree]))
2832 
2833 #define FORYX for (y=1; y < 3; y++) for (x=col+1; x >= col; x--)
2834 
2835 #define PREDICTOR (c ? (buf[c][y-1][x] + buf[c][y][x+1]) / 2 \
2836 : (buf[c][y-1][x+1] + 2*buf[c][y-1][x] + buf[c][y][x+1]) / 4)
2837 
kodak_radc_load_raw()2838 void CLASS kodak_radc_load_raw()
2839 {
2840   static const signed char src[] = {
2841     1,1, 2,3, 3,4, 4,2, 5,7, 6,5, 7,6, 7,8,
2842     1,0, 2,1, 3,3, 4,4, 5,2, 6,7, 7,6, 8,5, 8,8,
2843     2,1, 2,3, 3,0, 3,2, 3,4, 4,6, 5,5, 6,7, 6,8,
2844     2,0, 2,1, 2,3, 3,2, 4,4, 5,6, 6,7, 7,5, 7,8,
2845     2,1, 2,4, 3,0, 3,2, 3,3, 4,7, 5,5, 6,6, 6,8,
2846     2,3, 3,1, 3,2, 3,4, 3,5, 3,6, 4,7, 5,0, 5,8,
2847     2,3, 2,6, 3,0, 3,1, 4,4, 4,5, 4,7, 5,2, 5,8,
2848     2,4, 2,7, 3,3, 3,6, 4,1, 4,2, 4,5, 5,0, 5,8,
2849     2,6, 3,1, 3,3, 3,5, 3,7, 3,8, 4,0, 5,2, 5,4,
2850     2,0, 2,1, 3,2, 3,3, 4,4, 4,5, 5,6, 5,7, 4,8,
2851     1,0, 2,2, 2,-2,
2852     1,-3, 1,3,
2853     2,-17, 2,-5, 2,5, 2,17,
2854     2,-7, 2,2, 2,9, 2,18,
2855     2,-18, 2,-9, 2,-2, 2,7,
2856     2,-28, 2,28, 3,-49, 3,-9, 3,9, 4,49, 5,-79, 5,79,
2857     2,-1, 2,13, 2,26, 3,39, 4,-16, 5,55, 6,-37, 6,76,
2858     2,-26, 2,-13, 2,1, 3,-39, 4,16, 5,-55, 6,-76, 6,37
2859   };
2860   ushort huff[19][256];
2861   int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val;
2862   short last[3] = { 16,16,16 }, mul[3], buf[3][3][386];
2863   static const ushort pt[] =
2864     { 0,0, 1280,1344, 2320,3616, 3328,8000, 4095,16383, 65535,16383 };
2865 
2866   for (i=2; i < 12; i+=2)
2867     for (c=pt[i-2]; c <= pt[i]; c++)
2868       curve[c] = (float)
2869 	(c-pt[i-2]) / (pt[i]-pt[i-2]) * (pt[i+1]-pt[i-1]) + pt[i-1] + 0.5;
2870   for (s=i=0; i < sizeof src; i+=2)
2871     FORC(256 >> src[i])
2872       ((ushort *)huff)[s++] = src[i] << 8 | (uchar) src[i+1];
2873   s = kodak_cbpp == 243 ? 2 : 3;
2874   FORC(256) huff[18][c] = (8-s) << 8 | c >> s << s | 1 << (s-1);
2875   getbits(-1);
2876   for (i=0; i < sizeof(buf)/sizeof(short); i++)
2877     ((short *)buf)[i] = 2048;
2878   for (row=0; row < height; row+=4) {
2879     FORC3 mul[c] = getbits(6);
2880     FORC3 {
2881         if (!mul[c]) {
2882             mul[c] = 1;
2883             derror();
2884         }
2885     }
2886     FORC3 {
2887       val = ((0x1000000/last[c] + 0x7ff) >> 12) * mul[c];
2888       s = val > 65564 ? 10:12;
2889       x = ~(-1 << (s-1));
2890       val <<= 12-s;
2891       for (i=0; i < sizeof(buf[0])/sizeof(short); i++)
2892 	((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s;
2893       last[c] = mul[c];
2894       for (r=0; r <= !c; r++) {
2895 	buf[c][1][width/2] = buf[c][2][width/2] = mul[c] << 7;
2896 	for (tree=1, col=width/2; col > 0; ) {
2897 	  if ((tree = radc_token(tree))) {
2898 	    col -= 2;
2899 	    if (tree == 8)
2900 	      FORYX buf[c][y][x] = (uchar) radc_token(18) * mul[c];
2901 	    else
2902 	      FORYX buf[c][y][x] = radc_token(tree+10) * 16 + PREDICTOR;
2903 	  } else
2904 	    do {
2905 	      nreps = (col > 2) ? radc_token(9) + 1 : 1;
2906 	      for (rep=0; rep < 8 && rep < nreps && col > 0; rep++) {
2907 		col -= 2;
2908 		FORYX buf[c][y][x] = PREDICTOR;
2909 		if (rep & 1) {
2910 		  step = radc_token(10) << 4;
2911 		  FORYX buf[c][y][x] += step;
2912 		}
2913 	      }
2914 	    } while (nreps == 9);
2915 	}
2916 	for (y=0; y < 2; y++)
2917 	  for (x=0; x < width/2; x++) {
2918 	    val = (buf[c][y+1][x] << 4) / mul[c];
2919 	    if (val < 0) val = 0;
2920 	    if (c) RAW(row+y*2+c-1,x*2+2-c) = val;
2921 	    else   RAW(row+r*2+y,x*2+y) = val;
2922 	  }
2923 	memcpy (buf[c][0]+!c, buf[c][2], sizeof buf[c][0]-2*!c);
2924       }
2925     }
2926     for (y=row; y < row+4; y++)
2927       for (x=0; x < width; x++)
2928 	if ((x+y) & 1) {
2929 	  r = x ? x-1 : x+1;
2930 	  s = x+1 < width ? x+1 : x-1;
2931 	  val = (RAW(y,x)-2048)*2 + (RAW(y,r)+RAW(y,s))/2;
2932 	  if (val < 0) val = 0;
2933 	  RAW(y,x) = val;
2934 	}
2935   }
2936   for (i=0; i < height*width; i++)
2937     raw_image[i] = curve[raw_image[i]];
2938   maximum = 0x3fff;
2939 }
2940 
2941 #undef FORYX
2942 #undef PREDICTOR
2943 
2944 #ifdef NO_JPEG
kodak_jpeg_load_raw()2945 void CLASS kodak_jpeg_load_raw() {}
2946 // RT void CLASS lossy_dng_load_raw() {}
2947 #else
2948 
2949 METHODDEF(boolean)
fill_input_buffer(j_decompress_ptr cinfo)2950 fill_input_buffer (j_decompress_ptr cinfo)
2951 {
2952 /*RT  static uchar jpeg_buffer[4096]; */
2953   size_t nbytes;
2954 
2955   nbytes = fread (jpeg_buffer, 1, 4096, ifp);
2956   rtengine::swab ((char*)jpeg_buffer, (char*)jpeg_buffer, nbytes);
2957   cinfo->src->next_input_byte = jpeg_buffer;
2958   cinfo->src->bytes_in_buffer = nbytes;
2959   return TRUE;
2960 }
2961 
kodak_jpeg_load_raw()2962 void CLASS kodak_jpeg_load_raw()
2963 {
2964   struct jpeg_decompress_struct cinfo;
2965   struct jpeg_error_mgr jerr;
2966   JSAMPARRAY buf;
2967   JSAMPLE (*pixel)[3];
2968   int row, col;
2969 
2970   cinfo.err = jpeg_std_error (&jerr);
2971   jpeg_create_decompress (&cinfo);
2972   jpeg_stdio_src (&cinfo, ifp);
2973   cinfo.src->fill_input_buffer = fill_input_buffer;
2974   jpeg_read_header (&cinfo, TRUE);
2975   jpeg_start_decompress (&cinfo);
2976   if ((cinfo.output_width      != width  ) ||
2977       (cinfo.output_height*2   != height ) ||
2978       (cinfo.output_components != 3      )) {
2979     fprintf (stderr,_("%s: incorrect JPEG dimensions\n"), ifname);
2980     jpeg_destroy_decompress (&cinfo);
2981     longjmp (failure, 3);
2982   }
2983   buf = (*cinfo.mem->alloc_sarray)
2984 		((j_common_ptr) &cinfo, JPOOL_IMAGE, width*3, 1);
2985 
2986   while (cinfo.output_scanline < cinfo.output_height) {
2987     row = cinfo.output_scanline * 2;
2988     jpeg_read_scanlines (&cinfo, buf, 1);
2989     pixel = (JSAMPLE (*)[3]) buf[0];
2990     for (col=0; col < width; col+=2) {
2991       RAW(row+0,col+0) = pixel[col+0][1] << 1;
2992       RAW(row+1,col+1) = pixel[col+1][1] << 1;
2993       RAW(row+0,col+1) = pixel[col][0] + pixel[col+1][0];
2994       RAW(row+1,col+0) = pixel[col][2] + pixel[col+1][2];
2995     }
2996   }
2997   jpeg_finish_decompress (&cinfo);
2998   jpeg_destroy_decompress (&cinfo);
2999   maximum = 0xff << 1;
3000 }
3001 
3002 void CLASS gamma_curve (double pwr, double ts, int mode, int imax);
3003 /*RT*/#endif
3004 
lossy_dng_load_raw()3005 void CLASS lossy_dng_load_raw()
3006 {
3007   struct jpeg_decompress_struct cinfo;
3008   struct jpeg_error_mgr jerr;
3009   JSAMPARRAY buf;
3010   JSAMPLE (*pixel)[3];
3011   unsigned sorder=order, ntags, opcode, deg, i, j, c;
3012   unsigned save=data_offset-4, trow=0, tcol=0, row, col;
3013   ushort cur[3][256];
3014   double coeff[9], tot;
3015 
3016   if (meta_offset) {
3017     fseek (ifp, meta_offset, SEEK_SET);
3018     order = 0x4d4d;
3019     ntags = get4();
3020     while (ntags--) {
3021       opcode = get4(); get4(); get4();
3022       if (opcode != 8)
3023       { fseek (ifp, get4(), SEEK_CUR); continue; }
3024       fseek (ifp, 20, SEEK_CUR);
3025       if ((c = get4()) > 2) break;
3026       fseek (ifp, 12, SEEK_CUR);
3027       if ((deg = get4()) > 8) break;
3028       for (i=0; i <= deg && i < 9; i++)
3029 	coeff[i] = getreal(12);
3030       for (i=0; i < 256; i++) {
3031 	for (tot=j=0; j <= deg; j++)
3032 	  tot += coeff[j] * pow(i/255.0, j);
3033 	cur[c][i] = tot*0xffff;
3034       }
3035     }
3036     order = sorder;
3037   } else {
3038     gamma_curve (1/2.4, 12.92310, 1, 255);
3039     FORC3 memcpy (cur[c], curve, sizeof cur[0]);
3040   }
3041   cinfo.err = jpeg_std_error (&jerr);
3042   jpeg_create_decompress (&cinfo);
3043   while (trow < raw_height) {
3044     fseek (ifp, save+=4, SEEK_SET);
3045     if (tile_length < INT_MAX)
3046       fseek (ifp, get4(), SEEK_SET);
3047     /*RT jpeg_stdio_src (&cinfo, ifp); */
3048     /*RT*/jpeg_memory_src(&cinfo, fdata(ftell(ifp), ifp), ifp->size - ftell(ifp));
3049     jpeg_read_header (&cinfo, TRUE);
3050     jpeg_start_decompress (&cinfo);
3051     buf = (*cinfo.mem->alloc_sarray)
3052 	((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.output_width*3, 1);
3053     while (cinfo.output_scanline < cinfo.output_height &&
3054 	(row = trow + cinfo.output_scanline) < height) {
3055       jpeg_read_scanlines (&cinfo, buf, 1);
3056       pixel = (JSAMPLE (*)[3]) buf[0];
3057       for (col=0; col < cinfo.output_width && tcol+col < width; col++) {
3058 	FORC3 image[row*width+tcol+col][c] = cur[c][pixel[col][c]];
3059       }
3060     }
3061     jpeg_abort_decompress (&cinfo);
3062     if ((tcol += tile_width) >= raw_width)
3063       trow += tile_length + (tcol = 0);
3064   }
3065   jpeg_destroy_decompress (&cinfo);
3066   maximum = 0xffff;
3067 }
3068 /*RT #endif */
3069 
kodak_dc120_load_raw()3070 void CLASS kodak_dc120_load_raw()
3071 {
3072   static const int mul[4] = { 162, 192, 187,  92 };
3073   static const int add[4] = {   0, 636, 424, 212 };
3074   uchar pixel[848];
3075   int row, shift, col;
3076 
3077   for (row=0; row < height; row++) {
3078     if (fread (pixel, 1, 848, ifp) < 848) derror();
3079     shift = row * mul[row & 3] + add[row & 3];
3080     for (col=0; col < width; col++)
3081       RAW(row,col) = (ushort) pixel[(col + shift) % 848];
3082   }
3083   maximum = 0xff;
3084 }
3085 
eight_bit_load_raw()3086 void CLASS eight_bit_load_raw()
3087 {
3088   uchar *pixel;
3089   unsigned row, col;
3090 
3091   pixel = (uchar *) calloc (raw_width, sizeof *pixel);
3092   merror (pixel, "eight_bit_load_raw()");
3093   for (row=0; row < raw_height; row++) {
3094     if (fread (pixel, 1, raw_width, ifp) < raw_width) derror();
3095     for (col=0; col < raw_width; col++)
3096       RAW(row,col) = curve[pixel[col]];
3097   }
3098   free (pixel);
3099   maximum = curve[0xff];
3100 }
3101 
kodak_c330_load_raw()3102 void CLASS kodak_c330_load_raw()
3103 {
3104   uchar *pixel;
3105   int row, col, y, cb, cr, rgb[3], c;
3106 
3107   pixel = (uchar *) calloc (raw_width, 2*sizeof *pixel);
3108   merror (pixel, "kodak_c330_load_raw()");
3109   for (row=0; row < height; row++) {
3110     if (fread (pixel, raw_width, 2, ifp) < 2) derror();
3111     if (load_flags && (row & 31) == 31)
3112       fseek (ifp, raw_width*32, SEEK_CUR);
3113     for (col=0; col < width; col++) {
3114       y  = pixel[col*2];
3115       cb = pixel[(col*2 & -4) | 1] - 128;
3116       cr = pixel[(col*2 & -4) | 3] - 128;
3117       rgb[1] = y - ((cb + cr + 2) >> 2);
3118       rgb[2] = rgb[1] + cb;
3119       rgb[0] = rgb[1] + cr;
3120       FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)];
3121     }
3122   }
3123   free (pixel);
3124   maximum = curve[0xff];
3125 }
3126 
kodak_c603_load_raw()3127 void CLASS kodak_c603_load_raw()
3128 {
3129   uchar *pixel;
3130   int row, col, y, cb, cr, rgb[3], c;
3131 
3132   pixel = (uchar *) calloc (raw_width, 3*sizeof *pixel);
3133   merror (pixel, "kodak_c603_load_raw()");
3134   for (row=0; row < height; row++) {
3135     if (~row & 1)
3136       if (fread (pixel, raw_width, 3, ifp) < 3) derror();
3137     for (col=0; col < width; col++) {
3138       y  = pixel[width*2*(row & 1) + col];
3139       cb = pixel[width + (col & -2)]   - 128;
3140       cr = pixel[width + (col & -2)+1] - 128;
3141       rgb[1] = y - ((cb + cr + 2) >> 2);
3142       rgb[2] = rgb[1] + cb;
3143       rgb[0] = rgb[1] + cr;
3144       FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)];
3145     }
3146   }
3147   free (pixel);
3148   maximum = curve[0xff];
3149 }
3150 
kodak_262_load_raw()3151 void CLASS kodak_262_load_raw()
3152 {
3153   static const uchar kodak_tree[2][26] =
3154   { { 0,1,5,1,1,2,0,0,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 },
3155     { 0,3,1,1,1,1,1,2,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 } };
3156   ushort *huff[2];
3157   uchar *pixel;
3158   int *strip, ns, c, row, col, chess, pi=0, pi1, pi2, pred, val;
3159 
3160   FORC(2) huff[c] = make_decoder (kodak_tree[c]);
3161   ns = (raw_height+63) >> 5;
3162   pixel = (uchar *) malloc (raw_width*32 + ns*4);
3163   merror (pixel, "kodak_262_load_raw()");
3164   strip = (int *) (pixel + raw_width*32);
3165   order = 0x4d4d;
3166   FORC(ns) strip[c] = get4();
3167   for (row=0; row < raw_height; row++) {
3168     if ((row & 31) == 0) {
3169       fseek (ifp, strip[row >> 5], SEEK_SET);
3170       getbits(-1);
3171       pi = 0;
3172     }
3173     for (col=0; col < raw_width; col++) {
3174       chess = (row + col) & 1;
3175       pi1 = chess ? pi-2           : pi-raw_width-1;
3176       pi2 = chess ? pi-2*raw_width : pi-raw_width+1;
3177       if (col <= chess) pi1 = -1;
3178       if (pi1 < 0) pi1 = pi2;
3179       if (pi2 < 0) pi2 = pi1;
3180       if (pi1 < 0 && col > 1) pi1 = pi2 = pi-2;
3181       pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1;
3182       pixel[pi] = val = pred + ljpeg_diff (huff[chess]);
3183       if (val >> 8) derror();
3184       val = curve[pixel[pi++]];
3185       RAW(row,col) = val;
3186     }
3187   }
3188   free (pixel);
3189   FORC(2) free (huff[c]);
3190 }
3191 
kodak_65000_decode(short * out,int bsize)3192 int CLASS kodak_65000_decode (short *out, int bsize)
3193 {
3194   uchar c, blen[768];
3195   ushort raw[6];
3196   INT64 bitbuf=0;
3197   int save, bits=0, i, j, len, diff;
3198 
3199   save = ftell(ifp);
3200   bsize = (bsize + 3) & -4;
3201   for (i=0; i < bsize; i+=2) {
3202     c = fgetc(ifp);
3203     if ((blen[i  ] = c & 15) > 12 ||
3204 	(blen[i+1] = c >> 4) > 12 ) {
3205       fseek (ifp, save, SEEK_SET);
3206       for (i=0; i < bsize; i+=8) {
3207 	read_shorts (raw, 6);
3208 	out[i  ] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12;
3209 	out[i+1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12;
3210 	for (j=0; j < 6; j++)
3211 	  out[i+2+j] = raw[j] & 0xfff;
3212       }
3213       return 1;
3214     }
3215   }
3216   if ((bsize & 7) == 4) {
3217     bitbuf  = fgetc(ifp) << 8;
3218     bitbuf += fgetc(ifp);
3219     bits = 16;
3220   }
3221   for (i=0; i < bsize; i++) {
3222     len = blen[i];
3223     if (bits < len) {
3224       for (j=0; j < 32; j+=8)
3225 	bitbuf += (INT64) fgetc(ifp) << (bits+(j^8));
3226       bits += 32;
3227     }
3228     diff = bitbuf & (0xffff >> (16-len));
3229     bitbuf >>= len;
3230     bits -= len;
3231     if ((diff & (1 << (len-1))) == 0)
3232       diff -= (1 << len) - 1;
3233     out[i] = diff;
3234   }
3235   return 0;
3236 }
3237 
kodak_65000_load_raw()3238 void CLASS kodak_65000_load_raw()
3239 {
3240   short buf[256];
3241   int row, col, len, pred[2], ret, i;
3242 
3243   for (row=0; row < height; row++)
3244     for (col=0; col < width; col+=256) {
3245       pred[0] = pred[1] = 0;
3246       len = MIN (256, width-col);
3247       ret = kodak_65000_decode (buf, len);
3248       for (i=0; i < len; i++) {
3249 	    int idx = ret ? buf[i] : (pred[i & 1] += buf[i]);
3250         if(idx >=0 && idx <= 0xffff) {
3251           if ((RAW(row,col+i) = curve[idx]) >> 12) derror();
3252         } else
3253           derror();
3254       }
3255     }
3256 }
3257 
kodak_ycbcr_load_raw()3258 void CLASS kodak_ycbcr_load_raw()
3259 {
3260   short buf[384], *bp;
3261   int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3];
3262   ushort *ip;
3263 
3264   if (!image) return;
3265   for (row=0; row < height; row+=2)
3266     for (col=0; col < width; col+=128) {
3267       len = MIN (128, width-col);
3268       kodak_65000_decode (buf, len*3);
3269       y[0][1] = y[1][1] = cb = cr = 0;
3270       for (bp=buf, i=0; i < len; i+=2, bp+=2) {
3271 	cb += bp[4];
3272 	cr += bp[5];
3273 	rgb[1] = -((cb + cr + 2) >> 2);
3274 	rgb[2] = rgb[1] + cb;
3275 	rgb[0] = rgb[1] + cr;
3276 	for (j=0; j < 2; j++)
3277 	  for (k=0; k < 2; k++) {
3278 	    if ((y[j][k] = y[j][k^1] + *bp++) >> 10) derror();
3279 	    ip = image[(row+j)*width + col+i+k];
3280 	    FORC3 ip[c] = curve[LIM(y[j][k]+rgb[c], 0, 0xfff)];
3281 	  }
3282       }
3283     }
3284 }
3285 
kodak_rgb_load_raw()3286 void CLASS kodak_rgb_load_raw()
3287 {
3288   short buf[768], *bp;
3289   int row, col, len, c, i, rgb[3];
3290   ushort *ip=image[0];
3291 
3292   for (row=0; row < height; row++)
3293     for (col=0; col < width; col+=256) {
3294       len = MIN (256, width-col);
3295       kodak_65000_decode (buf, len*3);
3296       memset (rgb, 0, sizeof rgb);
3297       for (bp=buf, i=0; i < len; i++, ip+=4)
3298 	FORC3 if ((ip[c] = rgb[c] += *bp++) >> 12) derror();
3299     }
3300 }
3301 
kodak_thumb_load_raw()3302 void CLASS kodak_thumb_load_raw()
3303 {
3304   int row, col;
3305   colors = thumb_misc >> 5;
3306   for (row=0; row < height; row++)
3307     for (col=0; col < width; col++)
3308       read_shorts (image[row*width+col], colors);
3309   maximum = (1 << (thumb_misc & 31)) - 1;
3310 }
3311 
operator ()(unsigned * data,int len,int start,int key)3312 void CLASS sony_decrypt_t::operator()(unsigned *data, int len, int start, int key)
3313 {
3314 /*RT  static unsigned pad[128], p;*/
3315   if (start) {
3316     for (p=0; p < 4; p++)
3317       pad[p] = key = key * 48828125 + 1;
3318     pad[3] = pad[3] << 1 | (pad[0]^pad[2]) >> 31;
3319     for (p=4; p < 127; p++)
3320       pad[p] = (pad[p-4]^pad[p-2]) << 1 | (pad[p-3]^pad[p-1]) >> 31;
3321     for (p=0; p < 127; p++)
3322       pad[p] = htonl(pad[p]);
3323   }
3324   while (len-- && p++)
3325     *data++ ^= pad[(p-1) & 127] = pad[p & 127] ^ pad[(p+64) & 127];
3326 }
3327 
sony_load_raw()3328 void CLASS sony_load_raw()
3329 {
3330   uchar head[40];
3331   ushort *pixel;
3332   unsigned i, key, row, col;
3333 
3334   fseek (ifp, 200896, SEEK_SET);
3335   fseek (ifp, (unsigned) fgetc(ifp)*4 - 1, SEEK_CUR);
3336   order = 0x4d4d;
3337   key = get4();
3338   fseek (ifp, 164600, SEEK_SET);
3339   fread (head, 1, 40, ifp);
3340   sony_decrypt ((unsigned *) head, 10, 1, key);
3341   for (i=26; i-- > 22; )
3342     key = key << 8 | head[i];
3343   fseek (ifp, data_offset, SEEK_SET);
3344   for (row=0; row < raw_height; row++) {
3345     pixel = raw_image + row*raw_width;
3346     if (fread (pixel, 2, raw_width, ifp) < raw_width) derror();
3347     sony_decrypt ((unsigned *) pixel, raw_width/2, !row, key);
3348     for (col=0; col < raw_width; col++)
3349       if ((pixel[col] = ntohs(pixel[col])) >> 14) derror();
3350   }
3351   maximum = 0x3ff0;
3352 }
3353 
sony_arw_load_raw()3354 void CLASS sony_arw_load_raw()
3355 {
3356   ushort huff[32770];
3357   static const ushort tab[18] =
3358   { 0xf11,0xf10,0xe0f,0xd0e,0xc0d,0xb0c,0xa0b,0x90a,0x809,
3359     0x708,0x607,0x506,0x405,0x304,0x303,0x300,0x202,0x201 };
3360   int i, c, n, col, row, sum=0;
3361 
3362   huff[0] = 15;
3363   for (n=i=0; i < 18; i++)
3364     FORC(32768 >> (tab[i] >> 8)) huff[++n] = tab[i];
3365   getbits(-1);
3366   for (col = raw_width; col--; )
3367     for (row=0; row < raw_height+1; row+=2) {
3368       if (row == raw_height) row = 1;
3369       if ((sum += ljpeg_diff(huff)) >> 12) derror();
3370       if (row < height) RAW(row,col) = sum;
3371     }
3372 }
3373 
sony_arw2_load_raw()3374 void CLASS sony_arw2_load_raw()
3375 {
3376 
3377 #if defined( _OPENMP ) && defined( MYFILE_MMAP )
3378 #pragma omp parallel
3379 #endif
3380 {
3381     uchar *data = new (std::nothrow) uchar[raw_width + 1];
3382     merror(data, "sony_arw2_load_raw()");
3383     IMFILE ifpthr = *ifp;
3384     int pos = ifpthr.pos;
3385     ushort pix[16];
3386 
3387 #if defined( _OPENMP ) && defined( MYFILE_MMAP )
3388     // only master thread will update the progress bar
3389     ifpthr.plistener = nullptr;
3390     #pragma omp master
3391     {
3392     ifpthr.plistener = ifp->plistener;
3393     }
3394     #pragma omp for schedule(dynamic,16) nowait
3395 #endif
3396 
3397     for (int row = 0; row < height; row++) {
3398         fseek(&ifpthr, pos + row * raw_width, SEEK_SET);
3399         fread(data, 1, raw_width, &ifpthr);
3400         uchar *dp = data;
3401         for (int col = 0; col < raw_width - 30; dp += 16) {
3402             int val = sget4(dp);
3403             int max = 0x7ff & val;
3404             int min = 0x7ff & val >> 11;
3405             int imax = 0x0f & val >> 22;
3406             int imin = 0x0f & val >> 26;
3407             int bit = 30;
3408             for (int i = 0; i < 16; i++) {
3409                 if (i == imax) {
3410                     pix[i] = max;
3411                 } else if (i == imin) {
3412                     pix[i] = min;
3413                 } else {
3414                     int sh;
3415                     for (sh = 0; sh < 4 && 0x80 << sh <= max - min; sh++)
3416                         ;
3417                     pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min;
3418                     pix[i] = std::min(pix[i], (ushort)0x7ff);
3419                     bit += 7;
3420                 }
3421             }
3422             for (int i = 0; i < 16; i++, col += 2) {
3423                 RAW(row,col) = curve[pix[i] << 1]; // >> 2; RT: disabled shifting to avoid precision loss
3424             }
3425             col -= col & 1 ? 1:31;
3426         }
3427     }
3428   delete [] data;
3429 }
3430   maximum = curve[0x7ff << 1]; // RT: fix maximum.
3431   maximum = 16300; // RT: conservative white level tested on various ARW2 cameras. This constant was set in 2013-12-17, may need re-evaluation in the future.
3432 }
3433 
samsung_load_raw()3434 void CLASS samsung_load_raw()
3435 {
3436   int row, col, c, i, dir, op[4], len[4];
3437 
3438   order = 0x4949;
3439   ph1_bithuff_t ph1_bithuff(this, ifp, order);
3440   for (row=0; row < raw_height; row++) {
3441     fseek (ifp, strip_offset+row*4, SEEK_SET);
3442     fseek (ifp, data_offset+get4(), SEEK_SET);
3443     hb_bits(-1);
3444     FORC4 len[c] = row < 2 ? 7:4;
3445     for (col=0; col < raw_width; col+=16) {
3446       dir = hb_bits(1);
3447       FORC4 op[c] = hb_bits(2);
3448       FORC4 switch (op[c]) {
3449 	case 3: len[c] = hb_bits(4);	break;
3450 	case 2: len[c]--;		break;
3451 	case 1: len[c]++;
3452       }
3453       for (c=0; c < 16; c+=2) {
3454 	i = len[((c & 1) << 1) | (c >> 3)];
3455         RAW(row,col+c) = ((signed) hb_bits(i) << (32-i) >> (32-i)) +
3456 	  (dir ? RAW(row+(~c | -2),col+c) : col ? RAW(row,col+(c | -2)) : 128);
3457 	if (c == 14) c = -1;
3458       }
3459     }
3460   }
3461   for (row=0; row < raw_height-1; row+=2)
3462     for (col=0; col < raw_width-1; col+=2)
3463       SWAP (RAW(row,col+1), RAW(row+1,col));
3464 }
3465 
samsung2_load_raw()3466 void CLASS samsung2_load_raw()
3467 {
3468   static const ushort tab[14] =
3469   { 0x304,0x307,0x206,0x205,0x403,0x600,0x709,
3470     0x80a,0x90b,0xa0c,0xa0d,0x501,0x408,0x402 };
3471   ushort huff[1026], vpred[2][2] = {{0,0},{0,0}}, hpred[2];
3472   int i, c, n, row, col, diff;
3473 
3474   huff[0] = 10;
3475   for (n=i=0; i < 14; i++)
3476     FORC(1024 >> (tab[i] >> 8)) huff[++n] = tab[i];
3477   getbits(-1);
3478   for (row=0; row < raw_height; row++)
3479     for (col=0; col < raw_width; col++) {
3480       diff = ljpeg_diff (huff);
3481       if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
3482       else	   hpred[col & 1] += diff;
3483       RAW(row,col) = hpred[col & 1];
3484       if (hpred[col & 1] >> tiff_bps) derror();
3485     }
3486 }
3487 
samsung3_load_raw()3488 void CLASS samsung3_load_raw()
3489 {
3490   int opt, init, mag, pmode, row, tab, col, pred, diff, i, c;
3491   ushort lent[3][2], len[4], *prow[2];
3492 
3493   order = 0x4949;
3494   fseek (ifp, 9, SEEK_CUR);
3495   opt = fgetc(ifp);
3496   init = (get2(),get2());
3497   ph1_bithuff_t ph1_bithuff(this, ifp, order);
3498   for (row=0; row < raw_height; row++) {
3499     fseek (ifp, (data_offset-ftell(ifp)) & 15, SEEK_CUR);
3500     hb_bits(-1);
3501     mag = 0; pmode = 7;
3502     FORC(6) ((ushort *)lent)[c] = row < 2 ? 7:4;
3503     prow[ row & 1] = &RAW(row-1,1-((row & 1) << 1));	// green
3504     prow[~row & 1] = &RAW(row-2,0);			// red and blue
3505     for (tab=0; tab+15 < raw_width; tab+=16) {
3506       if (~opt & 4 && !(tab & 63)) {
3507 	i = hb_bits(2);
3508 	mag = i < 3 ? mag-'2'+"204"[i] : hb_bits(12);
3509       }
3510       if (opt & 2)
3511 	pmode = 7 - 4*hb_bits(1);
3512       else if (!hb_bits(1))
3513 	pmode = hb_bits(3);
3514       if (opt & 1 || !hb_bits(1)) {
3515 	FORC4 len[c] = hb_bits(2);
3516 	FORC4 {
3517 	  i = ((row & 1) << 1 | (c & 1)) % 3;
3518 	  len[c] = len[c] < 3 ? lent[i][0]-'1'+"120"[len[c]] : hb_bits(4);
3519 	  lent[i][0] = lent[i][1];
3520 	  lent[i][1] = len[c];
3521 	}
3522       }
3523       FORC(16) {
3524 	col = tab + (((c & 7) << 1)^(c >> 3)^(row & 1));
3525 	pred = (pmode == 7 || row < 2)
3526 	     ? (tab ? RAW(row,tab-2+(col & 1)) : init)
3527 	     : (prow[col & 1][col-'4'+"0224468"[pmode]] +
3528 		prow[col & 1][col-'4'+"0244668"[pmode]] + 1) >> 1;
3529 	diff = hb_bits (i = len[c >> 2]);
3530 	if (diff >> (i-1)) diff -= 1 << i;
3531 	diff = diff * (mag*2+1) + mag;
3532 	RAW(row,col) = pred + diff;
3533       }
3534     }
3535   }
3536 }
3537 
3538 #define HOLE(row) ((holes >> (((row) - raw_height) & 7)) & 1)
3539 
3540 /* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */
smal_decode_segment(unsigned seg[2][2],int holes)3541 void CLASS smal_decode_segment (unsigned seg[2][2], int holes)
3542 {
3543   uchar hist[3][13] = {
3544     { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 },
3545     { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 },
3546     { 3, 3, 0, 0, 63,     47,     31,     15,    0 } };
3547   int low, high=0xff, carry=0, nbits=8;
3548   int pix, s, count, bin, next, i, sym[3];
3549   uchar diff, pred[]={0,0};
3550   ushort data=0, range=0;
3551 
3552   fseek (ifp, seg[0][1]+1, SEEK_SET);
3553   getbits(-1);
3554   if (seg[1][0] > raw_width*raw_height)
3555       seg[1][0] = raw_width*raw_height;
3556   for (pix=seg[0][0]; pix < seg[1][0]; pix++) {
3557     for (s=0; s < 3; s++) {
3558       data = data << nbits | getbits(nbits);
3559       if (carry < 0)
3560 	carry = (nbits += carry+1) < 1 ? nbits-1 : 0;
3561       while (--nbits >= 0)
3562 	if ((data >> nbits & 0xff) == 0xff) break;
3563       if (nbits > 0)
3564 	  data = ((data & ((1 << (nbits-1)) - 1)) << 1) |
3565 	((data + (((data & (1 << (nbits-1)))) << 1)) & (-1 << nbits));
3566       if (nbits >= 0) {
3567 	data += getbits(1);
3568 	carry = nbits - 8;
3569       }
3570       count = ((((data-range+1) & 0xffff) << 2) - 1) / (high >> 4);
3571       for (bin=0; hist[s][bin+5] > count; bin++);
3572 		low = hist[s][bin+5] * (high >> 4) >> 2;
3573       if (bin) high = hist[s][bin+4] * (high >> 4) >> 2;
3574       high -= low;
3575       for (nbits=0; high << nbits < 128; nbits++);
3576       range = (range+low) << nbits;
3577       high <<= nbits;
3578       next = hist[s][1];
3579       if (++hist[s][2] > hist[s][3]) {
3580 	next = (next+1) & hist[s][0];
3581 	hist[s][3] = (hist[s][next+4] - hist[s][next+5]) >> 2;
3582 	hist[s][2] = 1;
3583       }
3584       if (hist[s][hist[s][1]+4] - hist[s][hist[s][1]+5] > 1) {
3585 	if (bin < hist[s][1])
3586 	  for (i=bin; i < hist[s][1]; i++) hist[s][i+5]--;
3587 	else if (next <= bin)
3588 	  for (i=hist[s][1]; i < bin; i++) hist[s][i+5]++;
3589       }
3590       hist[s][1] = next;
3591       sym[s] = bin;
3592     }
3593     diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3);
3594     if (sym[0] & 4)
3595       diff = diff ? -diff : 0x80;
3596     if (ftell(ifp) + 12 >= seg[1][1])
3597       diff = 0;
3598     if(pix>=raw_width*raw_height)
3599       derror();
3600     else
3601       raw_image[pix] = pred[pix & 1] += diff;
3602     if (!(pix & 1) && HOLE(pix / raw_width)) pix += 2;
3603   }
3604   maximum = 0xff;
3605 }
3606 
smal_v6_load_raw()3607 void CLASS smal_v6_load_raw()
3608 {
3609   unsigned seg[2][2];
3610 
3611   fseek (ifp, 16, SEEK_SET);
3612   seg[0][0] = 0;
3613   seg[0][1] = get2();
3614   seg[1][0] = raw_width * raw_height;
3615   seg[1][1] = INT_MAX;
3616   smal_decode_segment (seg, 0);
3617 }
3618 
median4(int * p)3619 int CLASS median4 (int *p)
3620 {
3621   int min, max, sum, i;
3622 
3623   min = max = sum = p[0];
3624   for (i=1; i < 4; i++) {
3625     sum += p[i];
3626     if (min > p[i]) min = p[i];
3627     if (max < p[i]) max = p[i];
3628   }
3629   return (sum - min - max) >> 1;
3630 }
3631 
fill_holes(int holes)3632 void CLASS fill_holes (int holes)
3633 {
3634   int row, col, val[4];
3635 
3636   for (row=2; row < height-2; row++) {
3637     if (!HOLE(row)) continue;
3638     for (col=1; col < width-1; col+=4) {
3639       val[0] = RAW(row-1,col-1);
3640       val[1] = RAW(row-1,col+1);
3641       val[2] = RAW(row+1,col-1);
3642       val[3] = RAW(row+1,col+1);
3643       RAW(row,col) = median4(val);
3644     }
3645     for (col=2; col < width-2; col+=4)
3646       if (HOLE(row-2) || HOLE(row+2))
3647 	RAW(row,col) = (RAW(row,col-2) + RAW(row,col+2)) >> 1;
3648       else {
3649 	val[0] = RAW(row,col-2);
3650 	val[1] = RAW(row,col+2);
3651 	val[2] = RAW(row-2,col);
3652 	val[3] = RAW(row+2,col);
3653 	RAW(row,col) = median4(val);
3654       }
3655   }
3656 }
3657 
smal_v9_load_raw()3658 void CLASS smal_v9_load_raw()
3659 {
3660   unsigned seg[256][2], offset, nseg, holes, i;
3661 
3662   fseek (ifp, 67, SEEK_SET);
3663   offset = get4();
3664   nseg = (uchar) fgetc(ifp);
3665   fseek (ifp, offset, SEEK_SET);
3666   for (i=0; i < nseg*2; i++)
3667     ((unsigned *)seg)[i] = get4() + data_offset*(i & 1);
3668   fseek (ifp, 78, SEEK_SET);
3669   holes = fgetc(ifp);
3670   fseek (ifp, 88, SEEK_SET);
3671   seg[nseg][0] = raw_height * raw_width;
3672   seg[nseg][1] = get4() + data_offset;
3673   for (i=0; i < nseg; i++)
3674     smal_decode_segment (seg+i, holes);
3675   if (holes) fill_holes (holes);
3676 }
3677 
redcine_load_raw()3678 void CLASS redcine_load_raw()
3679 {
3680 #ifndef NO_JASPER
3681   int c, row, col;
3682   jas_stream_t *in;
3683   jas_image_t *jimg;
3684   jas_matrix_t *jmat;
3685   jas_seqent_t *data;
3686   ushort *img, *pix;
3687 
3688   jas_init();
3689   in = jas_stream_fopen (ifname, "rb");
3690   jas_stream_seek (in, data_offset+20, SEEK_SET);
3691   jimg = jas_image_decode (in, -1, 0);
3692   if (!jimg) longjmp (failure, 3);
3693   jmat = jas_matrix_create (height/2, width/2);
3694   merror (jmat, "redcine_load_raw()");
3695   img = (ushort *) calloc ((height+2), (width+2)*2);
3696   merror (img, "redcine_load_raw()");
3697   FORC4 {
3698     jas_image_readcmpt (jimg, c, 0, 0, width/2, height/2, jmat);
3699     data = jas_matrix_getref (jmat, 0, 0);
3700     for (row = c >> 1; row < height; row+=2)
3701       for (col = c & 1; col < width; col+=2)
3702 	img[(row+1)*(width+2)+col+1] = data[(row/2)*(width/2)+col/2];
3703   }
3704   for (col=1; col <= width; col++) {
3705     img[col] = img[2*(width+2)+col];
3706     img[(height+1)*(width+2)+col] = img[(height-1)*(width+2)+col];
3707   }
3708   for (row=0; row < height+2; row++) {
3709     img[row*(width+2)] = img[row*(width+2)+2];
3710     img[(row+1)*(width+2)-1] = img[(row+1)*(width+2)-3];
3711   }
3712   for (row=1; row <= height; row++) {
3713     pix = img + row*(width+2) + (col = 1 + (FC(row,1) & 1));
3714     for (   ; col <= width; col+=2, pix+=2) {
3715       c = (((pix[0] - 0x800) << 3) +
3716 	pix[-(width+2)] + pix[width+2] + pix[-1] + pix[1]) >> 2;
3717       pix[0] = LIM(c,0,4095);
3718     }
3719   }
3720   for (row=0; row < height; row++)
3721     for (col=0; col < width; col++)
3722       RAW(row,col) = curve[img[(row+1)*(width+2)+col+1]];
3723   free (img);
3724   jas_matrix_destroy (jmat);
3725   jas_image_destroy (jimg);
3726   jas_stream_close (in);
3727 #endif
3728 }
3729 
3730 /* RESTRICTED code starts here */
3731 
foveon_decoder(unsigned size,unsigned code)3732 void CLASS foveon_decoder (unsigned size, unsigned code)
3733 {
3734 /*RT  static unsigned huff[1024];*/
3735   struct decode *cur;
3736   int i, len;
3737 
3738   if (!code) {
3739     for (i=0; i < size; i++)
3740       huff[i] = get4();
3741     memset (first_decode, 0, sizeof first_decode);
3742     free_decode = first_decode;
3743   }
3744   cur = free_decode++;
3745   if (free_decode > first_decode+2048) {
3746     fprintf (stderr,_("%s: decoder table overflow\n"), ifname);
3747     longjmp (failure, 2);
3748   }
3749   if (code)
3750     for (i=0; i < size; i++)
3751       if (huff[i] == code) {
3752 	cur->leaf = i;
3753 	return;
3754       }
3755   if ((len = code >> 27) > 26) return;
3756   code = (len+1) << 27 | (code & 0x3ffffff) << 1;
3757 
3758   cur->branch[0] = free_decode;
3759   foveon_decoder (size, code);
3760   cur->branch[1] = free_decode;
3761   foveon_decoder (size, code+1);
3762 }
3763 
foveon_thumb()3764 void CLASS foveon_thumb()
3765 {
3766   unsigned bwide, row, col, bitbuf=0, bit=1, c, i;
3767   char *buf;
3768   struct decode *dindex;
3769   short pred[3];
3770 
3771   bwide = get4();
3772   fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
3773   if (bwide > 0) {
3774     if (bwide < thumb_width*3) return;
3775     buf = (char *) malloc (bwide);
3776     merror (buf, "foveon_thumb()");
3777     for (row=0; row < thumb_height; row++) {
3778       fread  (buf, 1, bwide, ifp);
3779       fwrite (buf, 3, thumb_width, ofp);
3780     }
3781     free (buf);
3782     return;
3783   }
3784   foveon_decoder (256, 0);
3785 
3786   for (row=0; row < thumb_height; row++) {
3787     memset (pred, 0, sizeof pred);
3788     if (!bit) get4();
3789     for (bit=col=0; col < thumb_width; col++)
3790       FORC3 {
3791 	for (dindex=first_decode; dindex->branch[0]; ) {
3792 	  if ((bit = (bit-1) & 31) == 31)
3793 	    for (i=0; i < 4; i++)
3794 	      bitbuf = (bitbuf << 8) + fgetc(ifp);
3795 	  dindex = dindex->branch[bitbuf >> bit & 1];
3796 	}
3797 	pred[c] += dindex->leaf;
3798 	fputc (pred[c], ofp);
3799       }
3800   }
3801 }
3802 
foveon_sd_load_raw()3803 void CLASS foveon_sd_load_raw()
3804 {
3805   struct decode *dindex;
3806   short diff[1024];
3807   unsigned bitbuf=0;
3808   int pred[3], row, col, bit=-1, c, i;
3809 
3810   read_shorts ((ushort *) diff, 1024);
3811   if (!load_flags) foveon_decoder (1024, 0);
3812 
3813   for (row=0; row < height; row++) {
3814     memset (pred, 0, sizeof pred);
3815     if (!bit && !load_flags && atoi(model+2) < 14) get4();
3816     for (col=bit=0; col < width; col++) {
3817       if (load_flags) {
3818 	bitbuf = get4();
3819 	FORC3 pred[2-c] += diff[bitbuf >> c*10 & 0x3ff];
3820       }
3821       else FORC3 {
3822 	for (dindex=first_decode; dindex->branch[0]; ) {
3823 	  if ((bit = (bit-1) & 31) == 31)
3824 	    for (i=0; i < 4; i++)
3825 	      bitbuf = (bitbuf << 8) + fgetc(ifp);
3826 	  dindex = dindex->branch[bitbuf >> bit & 1];
3827 	}
3828 	pred[c] += diff[dindex->leaf];
3829 	if (pred[c] >> 16 && ~pred[c] >> 16) derror();
3830       }
3831       FORC3 image[row*width+col][c] = pred[c] < 0 ? 0 : pred[c];
3832     }
3833   }
3834 }
3835 
foveon_huff(ushort * huff)3836 void CLASS foveon_huff (ushort *huff)
3837 {
3838   int i, j, clen, code;
3839 
3840   huff[0] = 8;
3841   for (i=0; i < 13; i++) {
3842     clen = getc(ifp);
3843     code = getc(ifp);
3844     for (j=0; j < 256 >> clen; )
3845       huff[code+ ++j] = clen << 8 | i;
3846   }
3847   get2();
3848 }
3849 
foveon_dp_load_raw()3850 void CLASS foveon_dp_load_raw()
3851 {
3852   unsigned c, roff[4], row, col, diff;
3853   ushort huff[512], vpred[2][2], hpred[2];
3854 
3855   fseek (ifp, 8, SEEK_CUR);
3856   foveon_huff (huff);
3857   roff[0] = 48;
3858   FORC3 roff[c+1] = -(-(roff[c] + get4()) & -16);
3859   FORC3 {
3860     fseek (ifp, data_offset+roff[c], SEEK_SET);
3861     getbits(-1);
3862     vpred[0][0] = vpred[0][1] = vpred[1][0] = vpred[1][1] = 512;
3863     for (row=0; row < height; row++) {
3864       for (col=0; col < width; col++) {
3865 	diff = ljpeg_diff(huff);
3866 	if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
3867 	else hpred[col & 1] += diff;
3868 	image[row*width+col][c] = hpred[col & 1];
3869       }
3870     }
3871   }
3872 }
3873 
foveon_load_camf()3874 void CLASS foveon_load_camf()
3875 {
3876   unsigned type, wide, high, i, j, row, col, diff;
3877   ushort huff[258], vpred[2][2] = {{512,512},{512,512}}, hpred[2];
3878 
3879   fseek (ifp, meta_offset, SEEK_SET);
3880   type = get4();  get4();  get4();
3881   wide = get4();
3882   high = get4();
3883   if (type == 2) {
3884     fread (meta_data, 1, meta_length, ifp);
3885     for (i=0; i < meta_length; i++) {
3886       high = (high * 1597 + 51749) % 244944;
3887       wide = high * (INT64) 301593171 >> 24;
3888       meta_data[i] ^= ((((high << 8) - wide) >> 1) + wide) >> 17;
3889     }
3890   } else if (type == 4) {
3891     free (meta_data);
3892     meta_data = (char *) malloc (meta_length = wide*high*3/2);
3893     merror (meta_data, "foveon_load_camf()");
3894     foveon_huff (huff);
3895     get4();
3896     getbits(-1);
3897     for (j=row=0; row < high; row++) {
3898       for (col=0; col < wide; col++) {
3899 	diff = ljpeg_diff(huff);
3900 	if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
3901 	else         hpred[col & 1] += diff;
3902 	if (col & 1) {
3903 	  meta_data[j++] = hpred[0] >> 4;
3904 	  meta_data[j++] = hpred[0] << 4 | hpred[1] >> 8;
3905 	  meta_data[j++] = hpred[1];
3906 	}
3907       }
3908     }
3909   } else
3910     fprintf (stderr,_("%s has unknown CAMF type %d.\n"), ifname, type);
3911 }
3912 
foveon_camf_param(const char * block,const char * param)3913 const char * CLASS foveon_camf_param (const char *block, const char *param)
3914 {
3915   unsigned idx, num;
3916   char *pos, *cp, *dp;
3917 
3918   for (idx=0; idx < meta_length; idx += sget4(pos+8)) {
3919     pos = meta_data + idx;
3920     if (strncmp (pos, "CMb", 3)) break;
3921     if (pos[3] != 'P') continue;
3922     if (strcmp (block, pos+sget4(pos+12))) continue;
3923     cp = pos + sget4(pos+16);
3924     num = sget4(cp);
3925     dp = pos + sget4(cp+4);
3926     while (num--) {
3927       cp += 8;
3928       if (!strcmp (param, dp+sget4(cp)))
3929 	return dp+sget4(cp+4);
3930     }
3931   }
3932   return 0;
3933 }
3934 
foveon_camf_matrix(unsigned dim[3],const char * name)3935 void * CLASS foveon_camf_matrix (unsigned dim[3], const char *name)
3936 {
3937   unsigned i, idx, type, ndim, size, *mat;
3938   char *pos, *cp, *dp;
3939   double dsize;
3940 
3941   for (idx=0; idx < meta_length; idx += sget4(pos+8)) {
3942     pos = meta_data + idx;
3943     if (strncmp (pos, "CMb", 3)) break;
3944     if (pos[3] != 'M') continue;
3945     if (strcmp (name, pos+sget4(pos+12))) continue;
3946     dim[0] = dim[1] = dim[2] = 1;
3947     cp = pos + sget4(pos+16);
3948     type = sget4(cp);
3949     if ((ndim = sget4(cp+4)) > 3) break;
3950     dp = pos + sget4(cp+8);
3951     for (i=ndim; i--; ) {
3952       cp += 12;
3953       dim[i] = sget4(cp);
3954     }
3955     if ((dsize = (double) dim[0]*dim[1]*dim[2]) > meta_length/4) break;
3956     mat = (unsigned *) malloc ((size = dsize) * 4);
3957     merror (mat, "foveon_camf_matrix()");
3958     for (i=0; i < size; i++)
3959       if (type && type != 6)
3960 	mat[i] = sget4(dp + i*4);
3961       else
3962 	mat[i] = sget4(dp + i*2) & 0xffff;
3963     return mat;
3964   }
3965   fprintf (stderr,_("%s: \"%s\" matrix not found!\n"), ifname, name);
3966   return 0;
3967 }
3968 
foveon_fixed(void * ptr,int size,const char * name)3969 int CLASS foveon_fixed (void *ptr, int size, const char *name)
3970 {
3971   void *dp;
3972   unsigned dim[3];
3973 
3974   if (!name) return 0;
3975   dp = foveon_camf_matrix (dim, name);
3976   if (!dp) return 0;
3977   memcpy (ptr, dp, size*4);
3978   free (dp);
3979   return 1;
3980 }
3981 
foveon_avg(short * pix,int range[2],float cfilt)3982 float CLASS foveon_avg (short *pix, int range[2], float cfilt)
3983 {
3984   int i;
3985   float val, min=FLT_MAX, max=-FLT_MAX, sum=0;
3986 
3987   for (i=range[0]; i <= range[1]; i++) {
3988     sum += val = pix[i*4] + (pix[i*4]-pix[(i-1)*4]) * cfilt;
3989     if (min > val) min = val;
3990     if (max < val) max = val;
3991   }
3992   if (range[1] - range[0] == 1) return sum/2;
3993   return (sum - min - max) / (range[1] - range[0] - 1);
3994 }
3995 
foveon_make_curve(double max,double mul,double filt)3996 short * CLASS foveon_make_curve (double max, double mul, double filt)
3997 {
3998   short *curve;
3999   size_t i, size;
4000   double x;
4001 
4002   if (!filt) filt = 0.8;
4003   size = 4*rtengine::RT_PI*max / filt;
4004   if (size == UINT_MAX) size--;
4005   curve = (short *) calloc (size+1, sizeof *curve);
4006   merror (curve, "foveon_make_curve()");
4007   curve[0] = size;
4008   for (i=0; i < size; i++) {
4009     x = i*filt/max/4;
4010     curve[i+1] = (cos(x)+1)/2 * tanh(i*filt/mul) * mul + 0.5;
4011   }
4012   return curve;
4013 }
4014 
foveon_make_curves(short ** curvep,float dq[3],float div[3],float filt)4015 void CLASS foveon_make_curves
4016 	(short **curvep, float dq[3], float div[3], float filt)
4017 {
4018   double mul[3], max=0;
4019   int c;
4020 
4021   FORC3 mul[c] = dq[c]/div[c];
4022   FORC3 if (max < mul[c]) max = mul[c];
4023   FORC3 curvep[c] = foveon_make_curve (max, mul[c], filt);
4024 }
4025 
foveon_apply_curve(short * curve,int i)4026 int CLASS foveon_apply_curve (short *curve, int i)
4027 {
4028   if (abs(i) >= curve[0]) return 0;
4029   return i < 0 ? -curve[1-i] : curve[1+i];
4030 }
4031 
4032 #define image ((short (*)[4]) image)
4033 
foveon_interpolate()4034 void CLASS foveon_interpolate()
4035 {
4036   static const short hood[] = { -1,-1, -1,0, -1,1, 0,-1, 0,1, 1,-1, 1,0, 1,1 };
4037   short *pix, prev[3], *curve[8], (*shrink)[3];
4038   float cfilt=0, ddft[3][3][2], ppm[3][3][3];
4039   float cam_xyz[3][3], correct[3][3], last[3][3], trans[3][3];
4040   float chroma_dq[3], color_dq[3], diag[3][3], div[3];
4041   float (*black)[3], (*sgain)[3], (*sgrow)[3];
4042   float fsum[3], val, frow, num;
4043   int row, col, c, i, j, diff, sgx, irow, sum, min, max, limit;
4044   int dscr[2][2], dstb[4], (*smrow[7])[3], total[4], ipix[3];
4045   int work[3][3], smlast, smred, smred_p=0, dev[3];
4046   int satlev[3], keep[4], active[4];
4047   unsigned dim[3], *badpix;
4048   double dsum=0, trsum[3];
4049   char str[128];
4050   const char* cp;
4051 
4052   if (verbose)
4053     fprintf (stderr,_("Foveon interpolation...\n"));
4054 
4055   foveon_load_camf();
4056   foveon_fixed (dscr, 4, "DarkShieldColRange");
4057   foveon_fixed (ppm[0][0], 27, "PostPolyMatrix");
4058   foveon_fixed (satlev, 3, "SaturationLevel");
4059   foveon_fixed (keep, 4, "KeepImageArea");
4060   foveon_fixed (active, 4, "ActiveImageArea");
4061   foveon_fixed (chroma_dq, 3, "ChromaDQ");
4062   foveon_fixed (color_dq, 3,
4063 	foveon_camf_param ("IncludeBlocks", "ColorDQ") ?
4064 		"ColorDQ" : "ColorDQCamRGB");
4065   if (foveon_camf_param ("IncludeBlocks", "ColumnFilter"))
4066 		 foveon_fixed (&cfilt, 1, "ColumnFilter");
4067 
4068   memset (ddft, 0, sizeof ddft);
4069   if (!foveon_camf_param ("IncludeBlocks", "DarkDrift")
4070 	 || !foveon_fixed (ddft[1][0], 12, "DarkDrift"))
4071     for (i=0; i < 2; i++) {
4072       foveon_fixed (dstb, 4, i ? "DarkShieldBottom":"DarkShieldTop");
4073       for (row = dstb[1]; row <= dstb[3]; row++)
4074 	for (col = dstb[0]; col <= dstb[2]; col++)
4075 	  FORC3 ddft[i+1][c][1] += (short) image[row*width+col][c];
4076       FORC3 ddft[i+1][c][1] /= (dstb[3]-dstb[1]+1) * (dstb[2]-dstb[0]+1);
4077     }
4078 
4079   if (!(cp = foveon_camf_param ("WhiteBalanceIlluminants", model2)))
4080   { fprintf (stderr,_("%s: Invalid white balance \"%s\"\n"), ifname, model2);
4081     return; }
4082   foveon_fixed (cam_xyz, 9, cp);
4083   foveon_fixed (correct, 9,
4084 	foveon_camf_param ("WhiteBalanceCorrections", model2));
4085   memset (last, 0, sizeof last);
4086   for (i=0; i < 3; i++)
4087     for (j=0; j < 3; j++)
4088       FORC3 last[i][j] += correct[i][c] * cam_xyz[c][j];
4089 
4090   #define LAST(x,y) last[(i+x)%3][(c+y)%3]
4091   for (i=0; i < 3; i++)
4092     FORC3 diag[c][i] = LAST(1,1)*LAST(2,2) - LAST(1,2)*LAST(2,1);
4093   #undef LAST
4094   FORC3 div[c] = diag[c][0]*0.3127 + diag[c][1]*0.329 + diag[c][2]*0.3583;
4095   sprintf (str, "%sRGBNeutral", model2);
4096   if (foveon_camf_param ("IncludeBlocks", str))
4097     foveon_fixed (div, 3, str);
4098   num = 0;
4099   FORC3 if (num < div[c]) num = div[c];
4100   FORC3 div[c] /= num;
4101 
4102   memset (trans, 0, sizeof trans);
4103   for (i=0; i < 3; i++)
4104     for (j=0; j < 3; j++)
4105       FORC3 trans[i][j] += rgb_cam[i][c] * last[c][j] * div[j];
4106   FORC3 trsum[c] = trans[c][0] + trans[c][1] + trans[c][2];
4107   dsum = (6*trsum[0] + 11*trsum[1] + 3*trsum[2]) / 20;
4108   for (i=0; i < 3; i++)
4109     FORC3 last[i][c] = trans[i][c] * dsum / trsum[i];
4110   memset (trans, 0, sizeof trans);
4111   for (i=0; i < 3; i++)
4112     for (j=0; j < 3; j++)
4113       FORC3 trans[i][j] += (i==c ? 32 : -1) * last[c][j] / 30;
4114 
4115   foveon_make_curves (curve, color_dq, div, cfilt);
4116   FORC3 chroma_dq[c] /= 3;
4117   foveon_make_curves (curve+3, chroma_dq, div, cfilt);
4118   FORC3 dsum += chroma_dq[c] / div[c];
4119   curve[6] = foveon_make_curve (dsum, dsum, cfilt);
4120   curve[7] = foveon_make_curve (dsum*2, dsum*2, cfilt);
4121 
4122   sgain = (float (*)[3]) foveon_camf_matrix (dim, "SpatialGain");
4123   if (!sgain) return;
4124   sgrow = (float (*)[3]) calloc (dim[1], sizeof *sgrow);
4125   sgx = (width + dim[1]-2) / (dim[1]-1);
4126 
4127   black = (float (*)[3]) calloc (height, sizeof *black);
4128   for (row=0; row < height; row++) {
4129     for (i=0; i < 6; i++)
4130       ((float *)ddft[0])[i] = ((float *)ddft[1])[i] +
4131 	row / (height-1.0) * (((float *)ddft[2])[i] - ((float *)ddft[1])[i]);
4132     FORC3 black[row][c] =
4133 	( foveon_avg (image[row*width]+c, dscr[0], cfilt) +
4134 	  foveon_avg (image[row*width]+c, dscr[1], cfilt) * 3
4135 	  - ddft[0][c][0] ) / 4 - ddft[0][c][1];
4136   }
4137   memmove (black, black+8, sizeof *black*8);
4138   memmove (black+height-11, black+height-22, 11*sizeof *black);
4139   memcpy (last, black, sizeof last);
4140 
4141   for (row=1; row < height-1; row++) {
4142     FORC3 if (last[1][c] > last[0][c]) {
4143 	if (last[1][c] > last[2][c])
4144 	  black[row][c] = (last[0][c] > last[2][c]) ? last[0][c]:last[2][c];
4145       } else
4146 	if (last[1][c] < last[2][c])
4147 	  black[row][c] = (last[0][c] < last[2][c]) ? last[0][c]:last[2][c];
4148     memmove (last, last+1, 2*sizeof last[0]);
4149     memcpy (last[2], black[row+1], sizeof last[2]);
4150   }
4151   FORC3 black[row][c] = (last[0][c] + last[1][c])/2;
4152   FORC3 black[0][c] = (black[1][c] + black[3][c])/2;
4153 
4154   val = 1 - exp(-1/24.0);
4155   memcpy (fsum, black, sizeof fsum);
4156   for (row=1; row < height; row++)
4157     FORC3 fsum[c] += black[row][c] =
4158 	(black[row][c] - black[row-1][c])*val + black[row-1][c];
4159   memcpy (last[0], black[height-1], sizeof last[0]);
4160   FORC3 fsum[c] /= height;
4161   for (row = height; row--; )
4162     FORC3 last[0][c] = black[row][c] =
4163 	(black[row][c] - fsum[c] - last[0][c])*val + last[0][c];
4164 
4165   memset (total, 0, sizeof total);
4166   for (row=2; row < height; row+=4)
4167     for (col=2; col < width; col+=4) {
4168       FORC3 total[c] += (short) image[row*width+col][c];
4169       total[3]++;
4170     }
4171   for (row=0; row < height; row++)
4172     FORC3 black[row][c] += fsum[c]/2 + total[c]/(total[3]*100.0);
4173 
4174   for (row=0; row < height; row++) {
4175     for (i=0; i < 6; i++)
4176       ((float *)ddft[0])[i] = ((float *)ddft[1])[i] +
4177 	row / (height-1.0) * (((float *)ddft[2])[i] - ((float *)ddft[1])[i]);
4178     pix = image[row*width];
4179     memcpy (prev, pix, sizeof prev);
4180     frow = row / (height-1.0) * (dim[2]-1);
4181     if ((irow = frow) == dim[2]-1) irow--;
4182     frow -= irow;
4183     for (i=0; i < dim[1]; i++)
4184       FORC3 sgrow[i][c] = sgain[ irow   *dim[1]+i][c] * (1-frow) +
4185 			  sgain[(irow+1)*dim[1]+i][c] *    frow;
4186     for (col=0; col < width; col++) {
4187       FORC3 {
4188 	diff = pix[c] - prev[c];
4189 	prev[c] = pix[c];
4190 	ipix[c] = pix[c] + floor ((diff + (diff*diff >> 14)) * cfilt
4191 		- ddft[0][c][1] - ddft[0][c][0] * ((float) col/width - 0.5)
4192 		- black[row][c] );
4193       }
4194       FORC3 {
4195 	work[0][c] = ipix[c] * ipix[c] >> 14;
4196 	work[2][c] = ipix[c] * work[0][c] >> 14;
4197 	work[1][2-c] = ipix[(c+1) % 3] * ipix[(c+2) % 3] >> 14;
4198       }
4199       FORC3 {
4200 	for (val=i=0; i < 3; i++)
4201 	  for (  j=0; j < 3; j++)
4202 	    val += ppm[c][i][j] * work[i][j];
4203 	ipix[c] = floor ((ipix[c] + floor(val)) *
4204 		( sgrow[col/sgx  ][c] * (sgx - col%sgx) +
4205 		  sgrow[col/sgx+1][c] * (col%sgx) ) / sgx / div[c]);
4206 	if (ipix[c] > 32000) ipix[c] = 32000;
4207 	pix[c] = ipix[c];
4208       }
4209       pix += 4;
4210     }
4211   }
4212   free (black);
4213   free (sgrow);
4214   free (sgain);
4215 
4216   if ((badpix = (unsigned *) foveon_camf_matrix (dim, "BadPixels"))) {
4217     for (i=0; i < dim[0]; i++) {
4218       col = (badpix[i] >> 8 & 0xfff) - keep[0];
4219       row = (badpix[i] >> 20       ) - keep[1];
4220       if ((unsigned)(row-1) > height-3 || (unsigned)(col-1) > width-3)
4221 	continue;
4222       memset (fsum, 0, sizeof fsum);
4223       for (sum=j=0; j < 8; j++)
4224 	if (badpix[i] & (1 << j)) {
4225 	  FORC3 fsum[c] += (short)
4226 		image[(row+hood[j*2])*width+col+hood[j*2+1]][c];
4227 	  sum++;
4228 	}
4229       if (sum) FORC3 image[row*width+col][c] = fsum[c]/sum;
4230     }
4231     free (badpix);
4232   }
4233 
4234   /* Array for 5x5 Gaussian averaging of red values */
4235   smrow[6] = (int (*)[3]) calloc (width*5, sizeof **smrow);
4236   merror (smrow[6], "foveon_interpolate()");
4237   for (i=0; i < 5; i++)
4238     smrow[i] = smrow[6] + i*width;
4239 
4240   /* Sharpen the reds against these Gaussian averages */
4241   for (smlast=-1, row=2; row < height-2; row++) {
4242     while (smlast < row+2) {
4243       for (i=0; i < 6; i++)
4244 	smrow[(i+5) % 6] = smrow[i];
4245       pix = image[++smlast*width+2];
4246       for (col=2; col < width-2; col++) {
4247 	smrow[4][col][0] =
4248 	  (pix[0]*6 + (pix[-4]+pix[4])*4 + pix[-8]+pix[8] + 8) >> 4;
4249 	pix += 4;
4250       }
4251     }
4252     pix = image[row*width+2];
4253     for (col=2; col < width-2; col++) {
4254       smred = ( 6 *  smrow[2][col][0]
4255 	      + 4 * (smrow[1][col][0] + smrow[3][col][0])
4256 	      +      smrow[0][col][0] + smrow[4][col][0] + 8 ) >> 4;
4257       if (col == 2)
4258 	smred_p = smred;
4259       i = pix[0] + ((pix[0] - ((smred*7 + smred_p) >> 3)) >> 3);
4260       if (i > 32000) i = 32000;
4261       pix[0] = i;
4262       smred_p = smred;
4263       pix += 4;
4264     }
4265   }
4266 
4267   /* Adjust the brighter pixels for better linearity */
4268   min = 0xffff;
4269   FORC3 {
4270     i = satlev[c] / div[c];
4271     if (min > i) min = i;
4272   }
4273   limit = min * 9 >> 4;
4274   for (pix=image[0]; pix < image[height*width]; pix+=4) {
4275     if (pix[0] <= limit || pix[1] <= limit || pix[2] <= limit)
4276       continue;
4277     min = max = pix[0];
4278     for (c=1; c < 3; c++) {
4279       if (min > pix[c]) min = pix[c];
4280       if (max < pix[c]) max = pix[c];
4281     }
4282     if (min >= limit*2) {
4283       pix[0] = pix[1] = pix[2] = max;
4284     } else {
4285       i = 0x4000 - ((min - limit) << 14) / limit;
4286       i = 0x4000 - (i*i >> 14);
4287       i = i*i >> 14;
4288       FORC3 pix[c] += (max - pix[c]) * i >> 14;
4289     }
4290   }
4291 /*
4292    Because photons that miss one detector often hit another,
4293    the sum R+G+B is much less noisy than the individual colors.
4294    So smooth the hues without smoothing the total.
4295  */
4296   for (smlast=-1, row=2; row < height-2; row++) {
4297     while (smlast < row+2) {
4298       for (i=0; i < 6; i++)
4299 	smrow[(i+5) % 6] = smrow[i];
4300       pix = image[++smlast*width+2];
4301       for (col=2; col < width-2; col++) {
4302 	FORC3 smrow[4][col][c] = (pix[c-4]+2*pix[c]+pix[c+4]+2) >> 2;
4303 	pix += 4;
4304       }
4305     }
4306     pix = image[row*width+2];
4307     for (col=2; col < width-2; col++) {
4308       FORC3 dev[c] = -foveon_apply_curve (curve[7], pix[c] -
4309 	((smrow[1][col][c] + 2*smrow[2][col][c] + smrow[3][col][c]) >> 2));
4310       sum = (dev[0] + dev[1] + dev[2]) >> 3;
4311       FORC3 pix[c] += dev[c] - sum;
4312       pix += 4;
4313     }
4314   }
4315   for (smlast=-1, row=2; row < height-2; row++) {
4316     while (smlast < row+2) {
4317       for (i=0; i < 6; i++)
4318 	smrow[(i+5) % 6] = smrow[i];
4319       pix = image[++smlast*width+2];
4320       for (col=2; col < width-2; col++) {
4321 	FORC3 smrow[4][col][c] =
4322 		(pix[c-8]+pix[c-4]+pix[c]+pix[c+4]+pix[c+8]+2) >> 2;
4323 	pix += 4;
4324       }
4325     }
4326     pix = image[row*width+2];
4327     for (col=2; col < width-2; col++) {
4328       for (total[3]=375, sum=60, c=0; c < 3; c++) {
4329 	for (total[c]=i=0; i < 5; i++)
4330 	  total[c] += smrow[i][col][c];
4331 	total[3] += total[c];
4332 	sum += pix[c];
4333       }
4334       if (sum < 0) sum = 0;
4335       j = total[3] > 375 ? (sum << 16) / total[3] : sum * 174;
4336       FORC3 pix[c] += foveon_apply_curve (curve[6],
4337 		((j*total[c] + 0x8000) >> 16) - pix[c]);
4338       pix += 4;
4339     }
4340   }
4341 
4342   /* Transform the image to a different colorspace */
4343   for (pix=image[0]; pix < image[height*width]; pix+=4) {
4344     FORC3 pix[c] -= foveon_apply_curve (curve[c], pix[c]);
4345     sum = (pix[0]+pix[1]+pix[1]+pix[2]) >> 2;
4346     FORC3 pix[c] -= foveon_apply_curve (curve[c], pix[c]-sum);
4347     FORC3 {
4348       for (dsum=i=0; i < 3; i++)
4349 	dsum += trans[c][i] * pix[i];
4350       if (dsum < 0)  dsum = 0;
4351       if (dsum > 24000) dsum = 24000;
4352       ipix[c] = dsum + 0.5;
4353     }
4354     FORC3 pix[c] = ipix[c];
4355   }
4356 
4357   /* Smooth the image bottom-to-top and save at 1/4 scale */
4358   shrink = (short (*)[3]) calloc ((height/4), (width/4)*sizeof *shrink);
4359   merror (shrink, "foveon_interpolate()");
4360   for (row = height/4; row--; )
4361     for (col=0; col < width/4; col++) {
4362       ipix[0] = ipix[1] = ipix[2] = 0;
4363       for (i=0; i < 4; i++)
4364 	for (j=0; j < 4; j++)
4365 	  FORC3 ipix[c] += image[(row*4+i)*width+col*4+j][c];
4366       FORC3
4367 	if (row+2 > height/4)
4368 	  shrink[row*(width/4)+col][c] = ipix[c] >> 4;
4369 	else
4370 	  shrink[row*(width/4)+col][c] =
4371 	    (shrink[(row+1)*(width/4)+col][c]*1840 + ipix[c]*141 + 2048) >> 12;
4372     }
4373   /* From the 1/4-scale image, smooth right-to-left */
4374   for (row=0; row < (height & ~3); row++) {
4375     ipix[0] = ipix[1] = ipix[2] = 0;
4376     if ((row & 3) == 0)
4377       for (col = width & ~3 ; col--; )
4378 	FORC3 smrow[0][col][c] = ipix[c] =
4379 	  (shrink[(row/4)*(width/4)+col/4][c]*1485 + ipix[c]*6707 + 4096) >> 13;
4380 
4381   /* Then smooth left-to-right */
4382     ipix[0] = ipix[1] = ipix[2] = 0;
4383     for (col=0; col < (width & ~3); col++)
4384       FORC3 smrow[1][col][c] = ipix[c] =
4385 	(smrow[0][col][c]*1485 + ipix[c]*6707 + 4096) >> 13;
4386 
4387   /* Smooth top-to-bottom */
4388     if (row == 0)
4389       memcpy (smrow[2], smrow[1], sizeof **smrow * width);
4390     else
4391       for (col=0; col < (width & ~3); col++)
4392 	FORC3 smrow[2][col][c] =
4393 	  (smrow[2][col][c]*6707 + smrow[1][col][c]*1485 + 4096) >> 13;
4394 
4395   /* Adjust the chroma toward the smooth values */
4396     for (col=0; col < (width & ~3); col++) {
4397       for (i=j=30, c=0; c < 3; c++) {
4398 	i += smrow[2][col][c];
4399 	j += image[row*width+col][c];
4400       }
4401       j = (j << 16) / i;
4402       for (sum=c=0; c < 3; c++) {
4403 	ipix[c] = foveon_apply_curve (curve[c+3],
4404 	  ((smrow[2][col][c] * j + 0x8000) >> 16) - image[row*width+col][c]);
4405 	sum += ipix[c];
4406       }
4407       sum >>= 3;
4408       FORC3 {
4409 	i = image[row*width+col][c] + ipix[c] - sum;
4410 	if (i < 0) i = 0;
4411 	image[row*width+col][c] = i;
4412       }
4413     }
4414   }
4415   free (shrink);
4416   free (smrow[6]);
4417   for (i=0; i < 8; i++)
4418     free (curve[i]);
4419 
4420   /* Trim off the black border */
4421   active[1] -= keep[1];
4422   active[3] -= 2;
4423   i = active[2] - active[0];
4424   for (row=0; row < active[3]-active[1]; row++)
4425     memcpy (image[row*i], image[(row+active[1])*width+active[0]],
4426 	 i * sizeof *image);
4427   width = i;
4428   height = row;
4429 }
4430 #undef image
4431 
4432 /* RESTRICTED code ends here */
4433 
crop_masked_pixels()4434 void CLASS crop_masked_pixels()
4435 {
4436   if (data_error) {
4437     return;
4438   }
4439 
4440   int row, col;
4441   unsigned r, c, m, mblack[8], zero, val;
4442 
4443   if (load_raw == &CLASS phase_one_load_raw ||
4444       load_raw == &CLASS phase_one_load_raw_c)
4445     phase_one_correct();
4446   if (load_raw == &CLASS hasselblad_load_raw) // RT
4447       hasselblad_correct();                   // RT
4448   if (fuji_width) {
4449     for (row=0; row < raw_height-top_margin*2; row++) {
4450       for (col=0; col < fuji_width << !fuji_layout; col++) {
4451 	if (fuji_layout) {
4452 	  r = fuji_width - 1 - col + (row >> 1);
4453 	  c = col + ((row+1) >> 1);
4454 	} else {
4455 	  r = fuji_width - 1 + row - (col >> 1);
4456 	  c = row + ((col+1) >> 1);
4457 	}
4458 	if (r < height && c < width)
4459 	  BAYER(r,c) = RAW(row+top_margin,col+left_margin);
4460       }
4461     }
4462   } else {
4463 #ifdef _OPENMP
4464 #pragma omp parallel for
4465 #endif
4466     for (int row=0; row < height; row++)
4467       for (int col=0; col < width; col++)
4468 	BAYER2(row,col) = RAW(row+top_margin,col+left_margin);
4469   }
4470 
4471   if (mask[0][3] > 0) goto mask_set;
4472   if (load_raw == &CLASS canon_load_raw ||
4473       load_raw == &CLASS lossless_jpeg_load_raw) {
4474     mask[0][1] = mask[1][1] += 2;
4475     mask[0][3] -= 2;
4476     goto sides;
4477   }
4478   if (load_raw == &CLASS canon_600_load_raw ||
4479       load_raw == &CLASS sony_load_raw ||
4480      (load_raw == &CLASS eight_bit_load_raw && strncmp(model,"DC2",3)) ||
4481       load_raw == &CLASS kodak_262_load_raw ||
4482      (load_raw == &CLASS packed_load_raw && (load_flags & 256))) {
4483 sides:
4484     mask[0][0] = mask[1][0] = top_margin;
4485     mask[0][2] = mask[1][2] = top_margin+height;
4486     mask[0][3] += left_margin;
4487     mask[1][1] += left_margin+width;
4488     mask[1][3] += raw_width;
4489   }
4490   if (load_raw == &CLASS nokia_load_raw) {
4491     mask[0][2] = top_margin;
4492     mask[0][3] = width;
4493   }
4494 mask_set:
4495   memset (mblack, 0, sizeof mblack);
4496   for (zero=m=0; m < 8; m++)
4497     for (row=MAX(mask[m][0],0); row < MIN(mask[m][2],raw_height); row++)
4498       for (col=MAX(mask[m][1],0); col < MIN(mask[m][3],raw_width); col++) {
4499 	c = FC(row-top_margin,col-left_margin);
4500 	mblack[c] += val = RAW(row,col);
4501 	mblack[4+c]++;
4502 	zero += !val;
4503       }
4504   if (load_raw == &CLASS canon_600_load_raw && width < raw_width) {
4505     black = (mblack[0]+mblack[1]+mblack[2]+mblack[3]) /
4506 	    (mblack[4]+mblack[5]+mblack[6]+mblack[7]) - 4;
4507     canon_600_correct();
4508   } else if (zero < mblack[4] && mblack[5] && mblack[6] && mblack[7]) {
4509     FORC4 cblack[c] = mblack[c] / mblack[4+c];
4510     cblack[4] = cblack[5] = cblack[6] = 0;
4511   }
4512 }
4513 
4514 //void CLASS remove_zeroes()
4515 //{
4516 //  unsigned row, col, tot, n, r, c;
4517 //
4518 //  for (row=0; row < height; row++)
4519 //    for (col=0; col < width; col++)
4520 //      if (BAYER(row,col) == 0) {
4521 //	tot = n = 0;
4522 //	for (r = row-2; r <= row+2; r++)
4523 //	  for (c = col-2; c <= col+2; c++)
4524 //	    if (r < height && c < width &&
4525 //		FC(r,c) == FC(row,col) && BAYER(r,c))
4526 //	      tot += (n++,BAYER(r,c));
4527 //	if (n) BAYER(row,col) = tot/n;
4528 //      }
4529 //}
4530 
4531 /*
4532    Search from the current directory up to the root looking for
4533    a ".badpixels" file, and fix those pixels now.
4534  */
4535 //void CLASS bad_pixels (const char *cfname)
4536 //{
4537 //  FILE *fp=0;
4538 //  char *fname, *cp, line[128];
4539 //  int len, time, row, col, r, c, rad, tot, n, fixed=0;
4540 //
4541 //  if (!filters) return;
4542 //  if (cfname)
4543 //    fp = fopen (cfname, "r");
4544 //  else {
4545 //    for (len=32 ; ; len *= 2) {
4546 //      fname = (char *) malloc (len);
4547 //      if (!fname) return;
4548 //      if (getcwd (fname, len-16)) break;
4549 //      free (fname);
4550 //      if (errno != ERANGE) return;
4551 //    }
4552 //#if defined(WIN32) || defined(DJGPP)
4553 //    if (fname[1] == ':')
4554 //      memmove (fname, fname+2, len-2);
4555 //    for (cp=fname; *cp; cp++)
4556 //      if (*cp == '\\') *cp = '/';
4557 //#endif
4558 //    cp = fname + strlen(fname);
4559 //    if (cp[-1] == '/') cp--;
4560 //    while (*fname == '/') {
4561 //      strcpy (cp, "/.badpixels");
4562 //      if ((fp = fopen (fname, "r"))) break;
4563 //      if (cp == fname) break;
4564 //      while (*--cp != '/');
4565 //    }
4566 //    free (fname);
4567 //  }
4568 //  if (!fp) return;
4569 //  while (fgets (line, 128, fp)) {
4570 //    cp = strchr (line, '#');
4571 //    if (cp) *cp = 0;
4572 //    if (sscanf (line, "%d %d %d", &col, &row, &time) != 3) continue;
4573 //    if ((unsigned) col >= width || (unsigned) row >= height) continue;
4574 //    if (time > timestamp) continue;
4575 //    for (tot=n=0, rad=1; rad < 3 && n==0; rad++)
4576 //      for (r = row-rad; r <= row+rad; r++)
4577 //	for (c = col-rad; c <= col+rad; c++)
4578 //	  if ((unsigned) r < height && (unsigned) c < width &&
4579 //		(r != row || c != col) && fcol(r,c) == fcol(row,col)) {
4580 //	    tot += BAYER2(r,c);
4581 //	    n++;
4582 //	  }
4583 //    BAYER2(row,col) = tot/n;
4584 //    if (verbose) {
4585 //      if (!fixed++)
4586 //	fprintf (stderr,_("Fixed dead pixels at:"));
4587 //      fprintf (stderr, " %d,%d", col, row);
4588 //    }
4589 //  }
4590 //  if (fixed) fputc ('\n', stderr);
4591 //  fclose (fp);
4592 //}
4593 
4594 //void CLASS subtract (const char *fname)
4595 //{
4596 //  FILE *fp;
4597 //  int dim[3]={0,0,0}, comment=0, number=0, error=0, nd=0, c, row, col;
4598 //  ushort *pixel;
4599 //
4600 //  if (!(fp = fopen (fname, "rb"))) {
4601 //    perror (fname);  return;
4602 //  }
4603 //  if (fgetc(fp) != 'P' || fgetc(fp) != '5') error = 1;
4604 //  while (!error && nd < 3 && (c = fgetc(fp)) != EOF) {
4605 //    if (c == '#')  comment = 1;
4606 //    if (c == '\n') comment = 0;
4607 //    if (comment) continue;
4608 //    if (isdigit(c)) number = 1;
4609 //    if (number) {
4610 //      if (isdigit(c)) dim[nd] = dim[nd]*10 + c -'0';
4611 //      else if (isspace(c)) {
4612 //	number = 0;  nd++;
4613 //      } else error = 1;
4614 //    }
4615 //  }
4616 //  if (error || nd < 3) {
4617 //    fprintf (stderr,_("%s is not a valid PGM file!\n"), fname);
4618 //    fclose (fp);  return;
4619 //  } else if (dim[0] != width || dim[1] != height || dim[2] != 65535) {
4620 //    fprintf (stderr,_("%s has the wrong dimensions!\n"), fname);
4621 //    fclose (fp);  return;
4622 //  }
4623 //  pixel = (ushort *) calloc (width, sizeof *pixel);
4624 //  merror (pixel, "subtract()");
4625 //  for (row=0; row < height; row++) {
4626 //    fread (pixel, 2, width, fp);
4627 //    for (col=0; col < width; col++)
4628 //      BAYER(row,col) = MAX (BAYER(row,col) - ntohs(pixel[col]), 0);
4629 //  }
4630 //  free (pixel);
4631 //  fclose (fp);
4632 //  memset (cblack, 0, sizeof cblack);
4633 //  black = 0;
4634 //}
4635 
gamma_curve(double pwr,double ts,int mode,int imax)4636 void CLASS gamma_curve (double pwr, double ts, int mode, int imax)
4637 {
4638   int i;
4639   double g[6], bnd[2]={0,0}, r;
4640 
4641   g[0] = pwr;
4642   g[1] = ts;
4643   g[2] = g[3] = g[4] = 0;
4644   bnd[g[1] >= 1] = 1;
4645   if (g[1] && (g[1]-1)*(g[0]-1) <= 0) {
4646     for (i=0; i < 48; i++) {
4647       g[2] = (bnd[0] + bnd[1])/2;
4648       if (g[0]) bnd[(pow(g[2]/g[1],-g[0]) - 1)/g[0] - 1/g[2] > -1] = g[2];
4649       else	bnd[g[2]/exp(1-1/g[2]) < g[1]] = g[2];
4650     }
4651     g[3] = g[2] / g[1];
4652     if (g[0]) g[4] = g[2] * (1/g[0] - 1);
4653   }
4654   if (g[0]) g[5] = 1 / (g[1]*SQR(g[3])/2 - g[4]*(1 - g[3]) +
4655 		(1 - pow(g[3],1+g[0]))*(1 + g[4])/(1 + g[0])) - 1;
4656   else      g[5] = 1 / (g[1]*SQR(g[3])/2 + 1
4657 		- g[2] - g[3] -	g[2]*g[3]*(log(g[3]) - 1)) - 1;
4658   if (!mode--) {
4659     memcpy (gamm, g, sizeof gamm);
4660     return;
4661   }
4662   for (i=0; i < 0x10000; i++) {
4663     curve[i] = 0xffff;
4664     if ((r = (double) i / imax) < 1)
4665       curve[i] = 0x10000 * ( mode
4666 	? (r < g[3] ? r*g[1] : (g[0] ? pow( r,g[0])*(1+g[4])-g[4]    : log(r)*g[2]+1))
4667 	: (r < g[2] ? r/g[1] : (g[0] ? pow((r+g[4])/(1+g[4]),1/g[0]) : exp((r-1)/g[2]))));
4668   }
4669 }
4670 
pseudoinverse(double (* in)[3],double (* out)[3],int size)4671 void CLASS pseudoinverse (double (*in)[3], double (*out)[3], int size)
4672 {
4673   double work[3][6], num;
4674   int i, j, k;
4675 
4676   for (i=0; i < 3; i++) {
4677     for (j=0; j < 6; j++)
4678       work[i][j] = j == i+3;
4679     for (j=0; j < 3; j++)
4680       for (k=0; k < size; k++)
4681 	work[i][j] += in[k][i] * in[k][j];
4682   }
4683   for (i=0; i < 3; i++) {
4684     num = work[i][i];
4685     for (j=0; j < 6; j++)
4686       work[i][j] /= num;
4687     for (k=0; k < 3; k++) {
4688       if (k==i) continue;
4689       num = work[k][i];
4690       for (j=0; j < 6; j++)
4691 	work[k][j] -= work[i][j] * num;
4692     }
4693   }
4694   for (i=0; i < size; i++)
4695     for (j=0; j < 3; j++)
4696       for (out[i][j]=k=0; k < 3; k++)
4697 	out[i][j] += work[j][k+3] * in[i][k];
4698 }
4699 
cam_xyz_coeff(float rgb_cam[3][4],double cam_xyz[4][3])4700 void CLASS cam_xyz_coeff (float rgb_cam[3][4], double cam_xyz[4][3])
4701 {
4702   double cam_rgb[4][3], inverse[4][3], num;
4703   int i, j, k;
4704 
4705   for (i=0; i < colors; i++)		/* Multiply out XYZ colorspace */
4706     for (j=0; j < 3; j++)
4707       for (cam_rgb[i][j] = k=0; k < 3; k++)
4708 	cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j];
4709 
4710   for (i=0; i < colors; i++) {		/* Normalize cam_rgb so that */
4711     for (num=j=0; j < 3; j++)		/* cam_rgb * (1,1,1) is (1,1,1,1) */
4712       num += cam_rgb[i][j];
4713     for (j=0; j < 3; j++)
4714       cam_rgb[i][j] /= num;
4715     pre_mul[i] = 1 / num;
4716   }
4717   pseudoinverse (cam_rgb, inverse, colors);
4718   for (i=0; i < 3; i++)
4719     for (j=0; j < colors; j++)
4720       rgb_cam[i][j] = inverse[j][i];
4721 }
4722 
4723 #ifdef COLORCHECK
colorcheck()4724 void CLASS colorcheck()
4725 {
4726 #define NSQ 24
4727 // Coordinates of the GretagMacbeth ColorChecker squares
4728 // width, height, 1st_column, 1st_row
4729   int cut[NSQ][4];			// you must set these
4730 // ColorChecker Chart under 6500-kelvin illumination
4731   static const double gmb_xyY[NSQ][3] = {
4732     { 0.400, 0.350, 10.1 },		// Dark Skin
4733     { 0.377, 0.345, 35.8 },		// Light Skin
4734     { 0.247, 0.251, 19.3 },		// Blue Sky
4735     { 0.337, 0.422, 13.3 },		// Foliage
4736     { 0.265, 0.240, 24.3 },		// Blue Flower
4737     { 0.261, 0.343, 43.1 },		// Bluish Green
4738     { 0.506, 0.407, 30.1 },		// Orange
4739     { 0.211, 0.175, 12.0 },		// Purplish Blue
4740     { 0.453, 0.306, 19.8 },		// Moderate Red
4741     { 0.285, 0.202, 6.6 },		// Purple
4742     { 0.380, 0.489, 44.3 },		// Yellow Green
4743     { 0.473, 0.438, 43.1 },		// Orange Yellow
4744     { 0.187, 0.129, 6.1 },		// Blue
4745     { 0.305, 0.478, 23.4 },		// Green
4746     { 0.539, 0.313, 12.0 },		// Red
4747     { 0.448, 0.470, 59.1 },		// Yellow
4748     { 0.364, 0.233, 19.8 },		// Magenta
4749     { 0.196, 0.252, 19.8 },		// Cyan
4750     { 0.310, 0.316, 90.0 },		// White
4751     { 0.310, 0.316, 59.1 },		// Neutral 8
4752     { 0.310, 0.316, 36.2 },		// Neutral 6.5
4753     { 0.310, 0.316, 19.8 },		// Neutral 5
4754     { 0.310, 0.316, 9.0 },		// Neutral 3.5
4755     { 0.310, 0.316, 3.1 } };		// Black
4756   double gmb_cam[NSQ][4], gmb_xyz[NSQ][3];
4757   double inverse[NSQ][3], cam_xyz[4][3], balance[4], num;
4758   int c, i, j, k, sq, row, col, pass, count[4];
4759 
4760   memset (gmb_cam, 0, sizeof gmb_cam);
4761   for (sq=0; sq < NSQ; sq++) {
4762     FORCC count[c] = 0;
4763     for   (row=cut[sq][3]; row < cut[sq][3]+cut[sq][1]; row++)
4764       for (col=cut[sq][2]; col < cut[sq][2]+cut[sq][0]; col++) {
4765 	c = FC(row,col);
4766 	if (c >= colors) c -= 2;
4767 	gmb_cam[sq][c] += BAYER2(row,col);
4768 	BAYER2(row,col) = black + (BAYER2(row,col)-black)/2;
4769 	count[c]++;
4770       }
4771     FORCC gmb_cam[sq][c] = gmb_cam[sq][c]/count[c] - black;
4772     gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1];
4773     gmb_xyz[sq][1] = gmb_xyY[sq][2];
4774     gmb_xyz[sq][2] = gmb_xyY[sq][2] *
4775 		(1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1];
4776   }
4777   pseudoinverse (gmb_xyz, inverse, NSQ);
4778   for (pass=0; pass < 2; pass++) {
4779     for (raw_color = i=0; i < colors; i++)
4780       for (j=0; j < 3; j++)
4781 	for (cam_xyz[i][j] = k=0; k < NSQ; k++)
4782 	  cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j];
4783     cam_xyz_coeff (rgb_cam, cam_xyz);
4784     FORCC balance[c] = pre_mul[c] * gmb_cam[20][c];
4785     for (sq=0; sq < NSQ; sq++)
4786       FORCC gmb_cam[sq][c] *= balance[c];
4787   }
4788   if (verbose) {
4789     printf ("    { \"%s %s\", %d,\n\t{", make, model, black);
4790     num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]);
4791     FORCC for (j=0; j < 3; j++)
4792       printf ("%c%d", (c | j) ? ',':' ', (int) (cam_xyz[c][j] * num + 0.5));
4793     puts (" } },");
4794   }
4795 #undef NSQ
4796 }
4797 #endif
4798 
4799 //void CLASS hat_transform (float *temp, float *base, int st, int size, int sc)
4800 //{
4801 //  int i;
4802 //  for (i=0; i < sc; i++)
4803 //    temp[i] = 2*base[st*i] + base[st*(sc-i)] + base[st*(i+sc)];
4804 //  for (; i+sc < size; i++)
4805 //    temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(i+sc)];
4806 //  for (; i < size; i++)
4807 //    temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(2*size-2-(i+sc))];
4808 //}
4809 
4810 //void CLASS wavelet_denoise()
4811 //{
4812 //  float *fimg=0, *temp, thold, mul[2], avg, diff;
4813 //  int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2];
4814 //  ushort *window[4];
4815 //  static const float noise[] =
4816 //  { 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 };
4817 //
4818 //  if (verbose) fprintf (stderr,_("Wavelet denoising...\n"));
4819 //
4820 //  while (maximum << scale < 0x10000) scale++;
4821 //  maximum <<= --scale;
4822 //  black <<= scale;
4823 //  FORC4 cblack[c] <<= scale;
4824 //  if ((size = iheight*iwidth) < 0x15550000)
4825 //    fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg);
4826 //  merror (fimg, "wavelet_denoise()");
4827 //  temp = fimg + size*3;
4828 //  if ((nc = colors) == 3 && filters) nc++;
4829 //  FORC(nc) {			/* denoise R,G1,B,G3 individually */
4830 //    for (i=0; i < size; i++)
4831 //      fimg[i] = 256 * sqrt(image[i][c] << scale);
4832 //    for (hpass=lev=0; lev < 5; lev++) {
4833 //      lpass = size*((lev & 1)+1);
4834 //      for (row=0; row < iheight; row++) {
4835 //	hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev);
4836 //	for (col=0; col < iwidth; col++)
4837 //	  fimg[lpass + row*iwidth + col] = temp[col] * 0.25;
4838 //      }
4839 //      for (col=0; col < iwidth; col++) {
4840 //	hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev);
4841 //	for (row=0; row < iheight; row++)
4842 //	  fimg[lpass + row*iwidth + col] = temp[row] * 0.25;
4843 //      }
4844 //      thold = threshold * noise[lev];
4845 //      for (i=0; i < size; i++) {
4846 //	fimg[hpass+i] -= fimg[lpass+i];
4847 //	if	(fimg[hpass+i] < -thold) fimg[hpass+i] += thold;
4848 //	else if (fimg[hpass+i] >  thold) fimg[hpass+i] -= thold;
4849 //	else	 fimg[hpass+i] = 0;
4850 //	if (hpass) fimg[i] += fimg[hpass+i];
4851 //      }
4852 //      hpass = lpass;
4853 //    }
4854 //    for (i=0; i < size; i++)
4855 //      image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000);
4856 //  }
4857 //  if (filters && colors == 3) {  /* pull G1 and G3 closer together */
4858 //    for (row=0; row < 2; row++) {
4859 //      mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1];
4860 //      blk[row] = cblack[FC(row,0) | 1];
4861 //    }
4862 //    for (i=0; i < 4; i++)
4863 //      window[i] = (ushort *) fimg + width*i;
4864 //    for (wlast=-1, row=1; row < height-1; row++) {
4865 //      while (wlast < row+1) {
4866 //	for (wlast++, i=0; i < 4; i++)
4867 //	  window[(i+3) & 3] = window[i];
4868 //	for (col = FC(wlast,1) & 1; col < width; col+=2)
4869 //	  window[2][col] = BAYER(wlast,col);
4870 //      }
4871 //      thold = threshold/512;
4872 //      for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) {
4873 //	avg = ( window[0][col-1] + window[0][col+1] +
4874 //		window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 )
4875 //	      * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5;
4876 //	avg = avg < 0 ? 0 : sqrt(avg);
4877 //	diff = sqrt(BAYER(row,col)) - avg;
4878 //	if      (diff < -thold) diff += thold;
4879 //	else if (diff >  thold) diff -= thold;
4880 //	else diff = 0;
4881 //	BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5);
4882 //      }
4883 //    }
4884 //  }
4885 //  free (fimg);
4886 //}
4887 
4888 /*
4889 void CLASS scale_colors()
4890 {
4891   unsigned bottom, right, size, row, col, ur, uc, i, x, y, c, sum[8];
4892   int val, dark, sat;
4893   double dsum[8], dmin, dmax;
4894   float scale_mul[4], fr, fc;
4895   ushort *img=0, *pix;
4896 
4897   if (user_mul[0])
4898     memcpy (pre_mul, user_mul, sizeof pre_mul);
4899   if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1)) {
4900     memset (dsum, 0, sizeof dsum);
4901     bottom = MIN (greybox[1]+greybox[3], height);
4902     right  = MIN (greybox[0]+greybox[2], width);
4903     for (row=greybox[1]; row < bottom; row += 8)
4904       for (col=greybox[0]; col < right; col += 8) {
4905 	memset (sum, 0, sizeof sum);
4906 	for (y=row; y < row+8 && y < bottom; y++)
4907 	  for (x=col; x < col+8 && x < right; x++)
4908 	    FORC4 {
4909 	      if (filters) {
4910 		c = fcol(y,x);
4911 		val = BAYER2(y,x);
4912 	      } else
4913 		val = image[y*width+x][c];
4914 	      if (val > maximum-25) goto skip_block;
4915 	      if ((val -= cblack[c]) < 0) val = 0;
4916 	      sum[c] += val;
4917 	      sum[c+4]++;
4918 	      if (filters) break;
4919 	    }
4920 	FORC(8) dsum[c] += sum[c];
4921 skip_block: ;
4922       }
4923     FORC4 if (dsum[c]) pre_mul[c] = dsum[c+4] / dsum[c];
4924   }
4925   if (use_camera_wb && cam_mul[0] != -1) {
4926     memset (sum, 0, sizeof sum);
4927     for (row=0; row < 8; row++)
4928       for (col=0; col < 8; col++) {
4929 	c = FC(row,col);
4930 	if ((val = white[row][col] - cblack[c]) > 0)
4931 	  sum[c] += val;
4932 	sum[c+4]++;
4933       }
4934     if (sum[0] && sum[1] && sum[2] && sum[3])
4935       FORC4 pre_mul[c] = (float) sum[c+4] / sum[c];
4936     else if (cam_mul[0] && cam_mul[2])
4937       memcpy (pre_mul, cam_mul, sizeof pre_mul);
4938     else
4939       fprintf (stderr,_("%s: Cannot use camera white balance.\n"), ifname);
4940   }
4941   if (pre_mul[1] == 0) pre_mul[1] = 1;
4942   if (pre_mul[3] == 0) pre_mul[3] = colors < 4 ? pre_mul[1] : 1;
4943   dark = black;
4944   sat = maximum;
4945 //  if (threshold) wavelet_denoise();
4946   maximum -= black;
4947   for (dmin=DBL_MAX, dmax=c=0; c < 4; c++) {
4948     if (dmin > pre_mul[c])
4949 	dmin = pre_mul[c];
4950     if (dmax < pre_mul[c])
4951 	dmax = pre_mul[c];
4952   }
4953   if (!highlight) dmax = dmin;
4954   FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum;
4955   if (verbose) {
4956     fprintf (stderr,
4957       _("Scaling with darkness %d, saturation %d, and\nmultipliers"), dark, sat);
4958     FORC4 fprintf (stderr, " %f", pre_mul[c]);
4959     fputc ('\n', stderr);
4960   }
4961   if (filters > 1000 && (cblack[4]+1)/2 == 1 && (cblack[5]+1)/2 == 1) {
4962     FORC4 cblack[FC(c/2,c%2)] +=
4963 	cblack[6 + c/2 % cblack[4] * cblack[5] + c%2 % cblack[5]];
4964     cblack[4] = cblack[5] = 0;
4965   }
4966   size = iheight*iwidth;
4967   for (i=0; i < size*4; i++) {
4968     if (!(val = ((ushort *)image)[i])) continue;
4969     if (cblack[4] && cblack[5])
4970       val -= cblack[6 + i/4 / iwidth % cblack[4] * cblack[5] +
4971 			i/4 % iwidth % cblack[5]];
4972     val -= cblack[i & 3];
4973     val *= scale_mul[i & 3];
4974     ((ushort *)image)[i] = CLIP(val);
4975   }
4976   if ((aber[0] != 1 || aber[2] != 1) && colors == 3) {
4977     if (verbose)
4978       fprintf (stderr,_("Correcting chromatic aberration...\n"));
4979     for (c=0; c < 4; c+=2) {
4980       if (aber[c] == 1) continue;
4981       img = (ushort *) malloc (size * sizeof *img);
4982       merror (img, "scale_colors()");
4983       for (i=0; i < size; i++)
4984 	img[i] = image[i][c];
4985       for (row=0; row < iheight; row++) {
4986 	ur = fr = (row - iheight*0.5) * aber[c] + iheight*0.5;
4987 	if (ur > iheight-2) continue;
4988 	fr -= ur;
4989 	for (col=0; col < iwidth; col++) {
4990 	  uc = fc = (col - iwidth*0.5) * aber[c] + iwidth*0.5;
4991 	  if (uc > iwidth-2) continue;
4992 	  fc -= uc;
4993 	  pix = img + ur*iwidth + uc;
4994 	  image[row*iwidth+col][c] =
4995 	    (pix[     0]*(1-fc) + pix[       1]*fc) * (1-fr) +
4996 	    (pix[iwidth]*(1-fc) + pix[iwidth+1]*fc) * fr;
4997 	}
4998       }
4999       free(img);
5000     }
5001   }
5002 }
5003 
5004 */
pre_interpolate()5005 void CLASS pre_interpolate()
5006 {
5007   ushort (*img)[4];
5008   int row, col, c;
5009 
5010   if (shrink) {
5011     if (half_size) {
5012       height = iheight;
5013       width  = iwidth;
5014       if (filters == 9) {
5015 	for (row=0; row < 3; row++)
5016 	  for (col=1; col < 4; col++)
5017 	    if (!(image[row*width+col][0] | image[row*width+col][2]))
5018 	      goto break2;  break2:
5019 	for ( ; row < height; row+=3)
5020 	  for (col=(col-1)%3+1; col < width-1; col+=3) {
5021 	    img = image + row*width+col;
5022 	    for (c=0; c < 3; c+=2)
5023 	      img[0][c] = (img[-1][c] + img[1][c]) >> 1;
5024 	  }
5025       }
5026     } else {
5027       img = (ushort (*)[4]) calloc (height, width*sizeof *img);
5028       merror (img, "pre_interpolate()");
5029       for (row=0; row < height; row++)
5030 	for (col=0; col < width; col++) {
5031 	  c = fcol(row,col);
5032 	  img[row*width+col][c] = image[(row >> 1)*iwidth+(col >> 1)][c];
5033 	}
5034       free (image);
5035       image = img;
5036       shrink = 0;
5037     }
5038   }
5039   if (filters > 1000 && colors == 3) {
5040     mix_green = four_color_rgb ^ half_size;
5041     if (four_color_rgb | half_size) colors++;
5042     else {
5043       for (row = FC(1,0) >> 1; row < height; row+=2)
5044 	for (col = FC(row,1) & 1; col < width; col+=2)
5045 	  image[row*width+col][1] = image[row*width+col][3];
5046       filters &= ~((filters & 0x55555555) << 1);
5047     }
5048   }
5049   if (half_size) filters = 0;
5050 }
5051 
5052 //void CLASS border_interpolate (int border)
5053 //{
5054 //  unsigned row, col, y, x, f, c, sum[8];
5055 //
5056 //  for (row=0; row < height; row++)
5057 //    for (col=0; col < width; col++) {
5058 //      if (col==border && row >= border && row < height-border)
5059 //	col = width-border;
5060 //      memset (sum, 0, sizeof sum);
5061 //      for (y=row-1; y != row+2; y++)
5062 //	for (x=col-1; x != col+2; x++)
5063 //	  if (y < height && x < width) {
5064 //	    f = fcol(y,x);
5065 //	    sum[f] += image[y*width+x][f];
5066 //	    sum[f+4]++;
5067 //	  }
5068 //      f = fcol(row,col);
5069 //      FORCC if (c != f && sum[c+4])
5070 //	image[row*width+col][c] = sum[c] / sum[c+4];
5071 //    }
5072 //}
5073 
5074 /* RT: delete interpolation functions */
5075 
5076 
5077 //void CLASS cielab (ushort rgb[3], short lab[3])
5078 //{
5079 //  int c, i, j, k;
5080 //  float r, xyz[3];
5081 //  static float cbrt[0x10000], xyz_cam[3][4];
5082 //
5083 //  if (!rgb) {
5084 //    for (i=0; i < 0x10000; i++) {
5085 //      r = i / 65535.0;
5086 //      cbrt[i] = r > 0.008856 ? pow(r,1/3.0) : 7.787*r + 16/116.0;
5087 //    }
5088 //    for (i=0; i < 3; i++)
5089 //      for (j=0; j < colors; j++)
5090 //	for (xyz_cam[i][j] = k=0; k < 3; k++)
5091 //	  xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i];
5092 //    return;
5093 //  }
5094 //  xyz[0] = xyz[1] = xyz[2] = 0.5;
5095 //  FORCC {
5096 //    xyz[0] += xyz_cam[0][c] * rgb[c];
5097 //    xyz[1] += xyz_cam[1][c] * rgb[c];
5098 //    xyz[2] += xyz_cam[2][c] * rgb[c];
5099 //  }
5100 //  xyz[0] = cbrt[CLIP((int) xyz[0])];
5101 //  xyz[1] = cbrt[CLIP((int) xyz[1])];
5102 //  xyz[2] = cbrt[CLIP((int) xyz[2])];
5103 //  lab[0] = 64 * (116 * xyz[1] - 16);
5104 //  lab[1] = 64 * 500 * (xyz[0] - xyz[1]);
5105 //  lab[2] = 64 * 200 * (xyz[1] - xyz[2]);
5106 //}
5107 //
5108 //#define TS 512		/* Tile Size */
5109 //#define fcol(row,col) xtrans[(row+6) % 6][(col+6) % 6]
5110 //
5111 ///*
5112 //   Frank Markesteijn's algorithm for Fuji X-Trans sensors
5113 // */
5114 //void CLASS xtrans_interpolate (int passes)
5115 //{
5116 //  int c, d, f, g, h, i, v, ng, row, col, top, left, mrow, mcol;
5117 //  int val, ndir, pass, hm[8], avg[4], color[3][8];
5118 //  static const short orth[12] = { 1,0,0,1,-1,0,0,-1,1,0,0,1 },
5119 //	patt[2][16] = { { 0,1,0,-1,2,0,-1,0,1,1,1,-1,0,0,0,0 },
5120 //			{ 0,1,0,-2,1,0,-2,0,1,1,-2,-2,1,-1,-1,1 } },
5121 //	dir[4] = { 1,TS,TS+1,TS-1 };
5122 //  short allhex[3][3][2][8], *hex;
5123 //  ushort min, max, sgrow, sgcol;
5124 //  ushort (*rgb)[TS][TS][3], (*rix)[3], (*pix)[4];
5125 //   short (*lab)    [TS][3], (*lix)[3];
5126 //   float (*drv)[TS][TS], diff[6], tr;
5127 //   char (*homo)[TS][TS], *buffer;
5128 //
5129 //  if (verbose)
5130 //    fprintf (stderr,_("%d-pass X-Trans interpolation...\n"), passes);
5131 //
5132 //  cielab (0,0);
5133 //  ndir = 4 << (passes > 1);
5134 //  buffer = (char *) malloc (TS*TS*(ndir*11+6));
5135 //  merror (buffer, "xtrans_interpolate()");
5136 //  rgb  = (ushort(*)[TS][TS][3]) buffer;
5137 //  lab  = (short (*)    [TS][3])(buffer + TS*TS*(ndir*6));
5138 //  drv  = (float (*)[TS][TS])   (buffer + TS*TS*(ndir*6+6));
5139 //  homo = (char  (*)[TS][TS])   (buffer + TS*TS*(ndir*10+6));
5140 //
5141 ///* Map a green hexagon around each non-green pixel and vice versa:	*/
5142 //  for (row=0; row < 3; row++)
5143 //    for (col=0; col < 3; col++)
5144 //      for (ng=d=0; d < 10; d+=2) {
5145 //	g = fcol(row,col) == 1;
5146 //	if (fcol(row+orth[d],col+orth[d+2]) == 1) ng=0; else ng++;
5147 //	if (ng == 4) { sgrow = row; sgcol = col; }
5148 //	if (ng == g+1) FORC(8) {
5149 //	  v = orth[d  ]*patt[g][c*2] + orth[d+1]*patt[g][c*2+1];
5150 //	  h = orth[d+2]*patt[g][c*2] + orth[d+3]*patt[g][c*2+1];
5151 //	  allhex[row][col][0][c^(g*2 & d)] = h + v*width;
5152 //	  allhex[row][col][1][c^(g*2 & d)] = h + v*TS;
5153 //	}
5154 //      }
5155 //
5156 ///* Set green1 and green3 to the minimum and maximum allowed values:	*/
5157 //  for (row=2; row < height-2; row++)
5158 //    for (min=~(max=0), col=2; col < width-2; col++) {
5159 //      if (fcol(row,col) == 1 && (min=~(max=0))) continue;
5160 //      pix = image + row*width + col;
5161 //      hex = allhex[row % 3][col % 3][0];
5162 //      if (!max) FORC(6) {
5163 //	val = pix[hex[c]][1];
5164 //	if (min > val) min = val;
5165 //	if (max < val) max = val;
5166 //      }
5167 //      pix[0][1] = min;
5168 //      pix[0][3] = max;
5169 //      switch ((row-sgrow) % 3) {
5170 //	case 1: if (row < height-3) { row++; col--; } break;
5171 //	case 2: if ((min=~(max=0)) && (col+=2) < width-3 && row > 2) row--;
5172 //      }
5173 //    }
5174 //
5175 //  for (top=3; top < height-19; top += TS-16)
5176 //    for (left=3; left < width-19; left += TS-16) {
5177 //      mrow = MIN (top+TS, height-3);
5178 //      mcol = MIN (left+TS, width-3);
5179 //      for (row=top; row < mrow; row++)
5180 //	for (col=left; col < mcol; col++)
5181 //	  memcpy (rgb[0][row-top][col-left], image[row*width+col], 6);
5182 //      FORC3 memcpy (rgb[c+1], rgb[0], sizeof *rgb);
5183 //
5184 ///* Interpolate green horizontally, vertically, and along both diagonals: */
5185 //      for (row=top; row < mrow; row++)
5186 //	for (col=left; col < mcol; col++) {
5187 //	  if ((f = fcol(row,col)) == 1) continue;
5188 //	  pix = image + row*width + col;
5189 //	  hex = allhex[row % 3][col % 3][0];
5190 //	  color[1][0] = 174 * (pix[  hex[1]][1] + pix[  hex[0]][1]) -
5191 //			 46 * (pix[2*hex[1]][1] + pix[2*hex[0]][1]);
5192 //	  color[1][1] = 223 *  pix[  hex[3]][1] + pix[  hex[2]][1] * 33 +
5193 //			 92 * (pix[      0 ][f] - pix[ -hex[2]][f]);
5194 //	  FORC(2) color[1][2+c] =
5195 //		164 * pix[hex[4+c]][1] + 92 * pix[-2*hex[4+c]][1] + 33 *
5196 //		(2*pix[0][f] - pix[3*hex[4+c]][f] - pix[-3*hex[4+c]][f]);
5197 //	  FORC4 rgb[c^!((row-sgrow) % 3)][row-top][col-left][1] =
5198 //		LIM(color[1][c] >> 8,pix[0][1],pix[0][3]);
5199 //	}
5200 //
5201 //      for (pass=0; pass < passes; pass++) {
5202 //	if (pass == 1)
5203 //	  memcpy (rgb+=4, buffer, 4*sizeof *rgb);
5204 //
5205 ///* Recalculate green from interpolated values of closer pixels:	*/
5206 //	if (pass) {
5207 //	  for (row=top+2; row < mrow-2; row++)
5208 //	    for (col=left+2; col < mcol-2; col++) {
5209 //	      if ((f = fcol(row,col)) == 1) continue;
5210 //	      pix = image + row*width + col;
5211 //	      hex = allhex[row % 3][col % 3][1];
5212 //	      for (d=3; d < 6; d++) {
5213 //		rix = &rgb[(d-2)^!((row-sgrow) % 3)][row-top][col-left];
5214 //		val = rix[-2*hex[d]][1] + 2*rix[hex[d]][1]
5215 //		    - rix[-2*hex[d]][f] - 2*rix[hex[d]][f] + 3*rix[0][f];
5216 //		rix[0][1] = LIM(val/3,pix[0][1],pix[0][3]);
5217 //	      }
5218 //	    }
5219 //	}
5220 //
5221 ///* Interpolate red and blue values for solitary green pixels:	*/
5222 //	for (row=(top-sgrow+4)/3*3+sgrow; row < mrow-2; row+=3)
5223 //	  for (col=(left-sgcol+4)/3*3+sgcol; col < mcol-2; col+=3) {
5224 //	    rix = &rgb[0][row-top][col-left];
5225 //	    h = fcol(row,col+1);
5226 //	    memset (diff, 0, sizeof diff);
5227 //	    for (i=1, d=0; d < 6; d++, i^=TS^1, h^=2) {
5228 //	      for (c=0; c < 2; c++, h^=2) {
5229 //		g = 2*rix[0][1] - rix[i<<c][1] - rix[-i<<c][1];
5230 //		color[h][d] = g + rix[i<<c][h] + rix[-i<<c][h];
5231 //		if (d > 1)
5232 //		  diff[d] += SQR (rix[i<<c][1] - rix[-i<<c][1]
5233 //				- rix[i<<c][h] + rix[-i<<c][h]) + SQR(g);
5234 //	      }
5235 //	      if (d > 1 && (d & 1))
5236 //		if (diff[d-1] < diff[d])
5237 //		  FORC(2) color[c*2][d] = color[c*2][d-1];
5238 //	      if (d < 2 || (d & 1)) {
5239 //		FORC(2) rix[0][c*2] = CLIP(color[c*2][d]/2);
5240 //		rix += TS*TS;
5241 //	      }
5242 //	    }
5243 //	  }
5244 //
5245 ///* Interpolate red for blue pixels and vice versa:		*/
5246 //	for (row=top+3; row < mrow-3; row++)
5247 //	  for (col=left+3; col < mcol-3; col++) {
5248 //	    if ((f = 2-fcol(row,col)) == 1) continue;
5249 //	    rix = &rgb[0][row-top][col-left];
5250 //	    c = (row-sgrow) % 3 ? TS:1;
5251 //	    h = 3 * (c ^ TS ^ 1);
5252 //	    for (d=0; d < 4; d++, rix += TS*TS) {
5253 //	      i = d > 1 || ((d ^ c) & 1) ||
5254 //		 ((ABS(rix[0][1]-rix[c][1])+ABS(rix[0][1]-rix[-c][1])) <
5255 //		2*(ABS(rix[0][1]-rix[h][1])+ABS(rix[0][1]-rix[-h][1]))) ? c:h;
5256 //	      rix[0][f] = CLIP((rix[i][f] + rix[-i][f] +
5257 //		  2*rix[0][1] - rix[i][1] - rix[-i][1])/2);
5258 //	    }
5259 //	  }
5260 //
5261 ///* Fill in red and blue for 2x2 blocks of green:		*/
5262 //	for (row=top+2; row < mrow-2; row++) if ((row-sgrow) % 3)
5263 //	  for (col=left+2; col < mcol-2; col++) if ((col-sgcol) % 3) {
5264 //	    rix = &rgb[0][row-top][col-left];
5265 //	    hex = allhex[row % 3][col % 3][1];
5266 //	    for (d=0; d < ndir; d+=2, rix += TS*TS)
5267 //	      if (hex[d] + hex[d+1]) {
5268 //		g = 3*rix[0][1] - 2*rix[hex[d]][1] - rix[hex[d+1]][1];
5269 //		for (c=0; c < 4; c+=2) rix[0][c] =
5270 //			CLIP((g + 2*rix[hex[d]][c] + rix[hex[d+1]][c])/3);
5271 //	      } else {
5272 //		g = 2*rix[0][1] - rix[hex[d]][1] - rix[hex[d+1]][1];
5273 //		for (c=0; c < 4; c+=2) rix[0][c] =
5274 //			CLIP((g + rix[hex[d]][c] + rix[hex[d+1]][c])/2);
5275 //	      }
5276 //	  }
5277 //      }
5278 //      rgb = (ushort(*)[TS][TS][3]) buffer;
5279 //      mrow -= top;
5280 //      mcol -= left;
5281 //
5282 ///* Convert to CIELab and differentiate in all directions:	*/
5283 //      for (d=0; d < ndir; d++) {
5284 //	for (row=2; row < mrow-2; row++)
5285 //	  for (col=2; col < mcol-2; col++)
5286 //	    cielab (rgb[d][row][col], lab[row][col]);
5287 //	for (f=dir[d & 3],row=3; row < mrow-3; row++)
5288 //	  for (col=3; col < mcol-3; col++) {
5289 //	    lix = &lab[row][col];
5290 //	    g = 2*lix[0][0] - lix[f][0] - lix[-f][0];
5291 //	    drv[d][row][col] = SQR(g)
5292 //	      + SQR((2*lix[0][1] - lix[f][1] - lix[-f][1] + g*500/232))
5293 //	      + SQR((2*lix[0][2] - lix[f][2] - lix[-f][2] - g*500/580));
5294 //	  }
5295 //      }
5296 //
5297 ///* Build homogeneity maps from the derivatives:			*/
5298 //      memset(homo, 0, ndir*TS*TS);
5299 //      for (row=4; row < mrow-4; row++)
5300 //	for (col=4; col < mcol-4; col++) {
5301 //	  for (tr=FLT_MAX, d=0; d < ndir; d++)
5302 //	    if (tr > drv[d][row][col])
5303 //		tr = drv[d][row][col];
5304 //	  tr *= 8;
5305 //	  for (d=0; d < ndir; d++)
5306 //	    for (v=-1; v <= 1; v++)
5307 //	      for (h=-1; h <= 1; h++)
5308 //		if (drv[d][row+v][col+h] <= tr)
5309 //		  homo[d][row][col]++;
5310 //	}
5311 //
5312 ///* Average the most homogeneous pixels for the final result:	*/
5313 //      if (height-top < TS+4) mrow = height-top+2;
5314 //      if (width-left < TS+4) mcol = width-left+2;
5315 //      for (row = MIN(top,8); row < mrow-8; row++)
5316 //	for (col = MIN(left,8); col < mcol-8; col++) {
5317 //	  for (d=0; d < ndir; d++)
5318 //	    for (hm[d]=0, v=-2; v <= 2; v++)
5319 //	      for (h=-2; h <= 2; h++)
5320 //		hm[d] += homo[d][row+v][col+h];
5321 //	  for (d=0; d < ndir-4; d++)
5322 //	    if (hm[d] < hm[d+4]) hm[d  ] = 0; else
5323 //	    if (hm[d] > hm[d+4]) hm[d+4] = 0;
5324 //	  for (max=hm[0],d=1; d < ndir; d++)
5325 //	    if (max < hm[d]) max = hm[d];
5326 //	  max -= max >> 3;
5327 //	  memset (avg, 0, sizeof avg);
5328 //	  for (d=0; d < ndir; d++)
5329 //	    if (hm[d] >= max) {
5330 //	      FORC3 avg[c] += rgb[d][row][col][c];
5331 //	      avg[3]++;
5332 //	    }
5333 //	  FORC3 image[(row+top)*width+col+left][c] = avg[c]/avg[3];
5334 //	}
5335 //    }
5336 //  free(buffer);
5337 //  border_interpolate(8);
5338 //}
5339 //#undef fcol
5340 //
5341 //
5342 //#undef TS
5343 
5344 //void CLASS median_filter()
5345 //{
5346 //  ushort (*pix)[4];
5347 //  int pass, c, i, j, k, med[9];
5348 //  static const uchar opt[] =	/* Optimal 9-element median search */
5349 //  { 1,2, 4,5, 7,8, 0,1, 3,4, 6,7, 1,2, 4,5, 7,8,
5350 //    0,3, 5,8, 4,7, 3,6, 1,4, 2,5, 4,7, 4,2, 6,4, 4,2 };
5351 //
5352 //  for (pass=1; pass <= med_passes; pass++) {
5353 //    if (verbose)
5354 //      fprintf (stderr,_("Median filter pass %d...\n"), pass);
5355 //    for (c=0; c < 3; c+=2) {
5356 //      for (pix = image; pix < image+width*height; pix++)
5357 //	pix[0][3] = pix[0][c];
5358 //      for (pix = image+width; pix < image+width*(height-1); pix++) {
5359 //	if ((pix-image+1) % width < 2) continue;
5360 //	for (k=0, i = -width; i <= width; i += width)
5361 //	  for (j = i-1; j <= i+1; j++)
5362 //	    med[k++] = pix[j][3] - pix[j][1];
5363 //	for (i=0; i < sizeof opt; i+=2)
5364 //	  if     (med[opt[i]] > med[opt[i+1]])
5365 //	    SWAP (med[opt[i]] , med[opt[i+1]]);
5366 //	pix[0][c] = CLIP(med[4] + pix[0][1]);
5367 //      }
5368 //    }
5369 //  }
5370 //}
5371 //
5372 //void CLASS blend_highlights()
5373 //{
5374 //  int clip=INT_MAX, row, col, c, i, j;
5375 //  static const float trans[2][4][4] =
5376 //  { { { 1,1,1 }, { 1.7320508,-1.7320508,0 }, { -1,-1,2 } },
5377 //    { { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } };
5378 //  static const float itrans[2][4][4] =
5379 //  { { { 1,0.8660254,-0.5 }, { 1,-0.8660254,-0.5 }, { 1,0,1 } },
5380 //    { { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } };
5381 //  float cam[2][4], lab[2][4], sum[2], chratio;
5382 //
5383 //  if ((unsigned) (colors-3) > 1) return;
5384 //  if (verbose) fprintf (stderr,_("Blending highlights...\n"));
5385 //  FORCC if (clip > (i = 65535*pre_mul[c])) clip = i;
5386 //  for (row=0; row < height; row++)
5387 //    for (col=0; col < width; col++) {
5388 //      FORCC if (image[row*width+col][c] > clip) break;
5389 //      if (c == colors) continue;
5390 //      FORCC {
5391 //	cam[0][c] = image[row*width+col][c];
5392 //	cam[1][c] = MIN(cam[0][c],clip);
5393 //      }
5394 //      for (i=0; i < 2; i++) {
5395 //	FORCC for (lab[i][c]=j=0; j < colors; j++)
5396 //	  lab[i][c] += trans[colors-3][c][j] * cam[i][j];
5397 //	for (sum[i]=0,c=1; c < colors; c++)
5398 //	  sum[i] += SQR(lab[i][c]);
5399 //      }
5400 //      chratio = sqrt(sum[1]/sum[0]);
5401 //      for (c=1; c < colors; c++)
5402 //	lab[0][c] *= chratio;
5403 //      FORCC for (cam[0][c]=j=0; j < colors; j++)
5404 //	cam[0][c] += itrans[colors-3][c][j] * lab[0][j];
5405 //      FORCC image[row*width+col][c] = cam[0][c] / colors;
5406 //    }
5407 //}
5408 //
5409 //#define SCALE (4 >> shrink)
5410 //void CLASS recover_highlights()
5411 //{
5412 //  float *map, sum, wgt, grow;
5413 //  int hsat[4], count, spread, change, val, i;
5414 //  unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x;
5415 //  ushort *pixel;
5416 //  static const signed char dir[8][2] =
5417 //    { {-1,-1}, {-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1} };
5418 //
5419 //  if (verbose) fprintf (stderr,_("Rebuilding highlights...\n"));
5420 //
5421 //  grow = pow (2, 4-highlight);
5422 //  FORCC hsat[c] = 32000 * pre_mul[c];
5423 //  for (kc=0, c=1; c < colors; c++)
5424 //    if (pre_mul[kc] < pre_mul[c]) kc = c;
5425 //  high = height / SCALE;
5426 //  wide =  width / SCALE;
5427 //  map = (float *) calloc (high, wide*sizeof *map);
5428 //  merror (map, "recover_highlights()");
5429 //  FORCC if (c != kc) {
5430 //    memset (map, 0, high*wide*sizeof *map);
5431 //    for (mrow=0; mrow < high; mrow++)
5432 //      for (mcol=0; mcol < wide; mcol++) {
5433 //	sum = wgt = count = 0;
5434 //	for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++)
5435 //	  for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) {
5436 //	    pixel = image[row*width+col];
5437 //	    if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000) {
5438 //	      sum += pixel[c];
5439 //	      wgt += pixel[kc];
5440 //	      count++;
5441 //	    }
5442 //	  }
5443 //	if (count == SCALE*SCALE)
5444 //	  map[mrow*wide+mcol] = sum / wgt;
5445 //      }
5446 //    for (spread = 32/grow; spread--; ) {
5447 //      for (mrow=0; mrow < high; mrow++)
5448 //	for (mcol=0; mcol < wide; mcol++) {
5449 //	  if (map[mrow*wide+mcol]) continue;
5450 //	  sum = count = 0;
5451 //	  for (d=0; d < 8; d++) {
5452 //	    y = mrow + dir[d][0];
5453 //	    x = mcol + dir[d][1];
5454 //	    if (y < high && x < wide && map[y*wide+x] > 0) {
5455 //	      sum  += (1 + (d & 1)) * map[y*wide+x];
5456 //	      count += 1 + (d & 1);
5457 //	    }
5458 //	  }
5459 //	  if (count > 3)
5460 //	    map[mrow*wide+mcol] = - (sum+grow) / (count+grow);
5461 //	}
5462 //      for (change=i=0; i < high*wide; i++)
5463 //	if (map[i] < 0) {
5464 //	  map[i] = -map[i];
5465 //	  change = 1;
5466 //	}
5467 //      if (!change) break;
5468 //    }
5469 //    for (i=0; i < high*wide; i++)
5470 //      if (map[i] == 0) map[i] = 1;
5471 //    for (mrow=0; mrow < high; mrow++)
5472 //      for (mcol=0; mcol < wide; mcol++) {
5473 //	for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++)
5474 //	  for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) {
5475 //	    pixel = image[row*width+col];
5476 //	    if (pixel[c] / hsat[c] > 1) {
5477 //	      val = pixel[kc] * map[mrow*wide+mcol];
5478 //	      if (pixel[c] < val) pixel[c] = CLIP(val);
5479 //	    }
5480 //	  }
5481 //      }
5482 //  }
5483 //  free (map);
5484 //}
5485 //#undef SCALE
5486 
tiff_get(unsigned base,unsigned * tag,unsigned * type,unsigned * len,unsigned * save)5487 void CLASS tiff_get (unsigned base,
5488 	unsigned *tag, unsigned *type, unsigned *len, unsigned *save)
5489 {
5490   *tag  = get2();
5491   *type = get2();
5492   *len  = get4();
5493   *save = ftell(ifp) + 4;
5494   if (*len * ("11124811248484"[*type < 14 ? *type:0]-'0') > 4)
5495     fseek (ifp, get4()+base, SEEK_SET);
5496 }
5497 
parse_thumb_note(int base,unsigned toff,unsigned tlen)5498 void CLASS parse_thumb_note (int base, unsigned toff, unsigned tlen)
5499 {
5500   unsigned entries, tag, type, len, save;
5501 
5502   entries = get2();
5503   while (entries--) {
5504     tiff_get (base, &tag, &type, &len, &save);
5505     if (tag == toff) thumb_offset = get4()+base;
5506     if (tag == tlen) thumb_length = get4();
5507     fseek (ifp, save, SEEK_SET);
5508   }
5509 }
5510 
5511 /*RT int CLASS parse_tiff_ifd (int base);*/
5512 
parse_makernote(int base,int uptag)5513 void CLASS parse_makernote (int base, int uptag)
5514 {
5515   static const uchar xlat[2][256] = {
5516   { 0xc1,0xbf,0x6d,0x0d,0x59,0xc5,0x13,0x9d,0x83,0x61,0x6b,0x4f,0xc7,0x7f,0x3d,0x3d,
5517     0x53,0x59,0xe3,0xc7,0xe9,0x2f,0x95,0xa7,0x95,0x1f,0xdf,0x7f,0x2b,0x29,0xc7,0x0d,
5518     0xdf,0x07,0xef,0x71,0x89,0x3d,0x13,0x3d,0x3b,0x13,0xfb,0x0d,0x89,0xc1,0x65,0x1f,
5519     0xb3,0x0d,0x6b,0x29,0xe3,0xfb,0xef,0xa3,0x6b,0x47,0x7f,0x95,0x35,0xa7,0x47,0x4f,
5520     0xc7,0xf1,0x59,0x95,0x35,0x11,0x29,0x61,0xf1,0x3d,0xb3,0x2b,0x0d,0x43,0x89,0xc1,
5521     0x9d,0x9d,0x89,0x65,0xf1,0xe9,0xdf,0xbf,0x3d,0x7f,0x53,0x97,0xe5,0xe9,0x95,0x17,
5522     0x1d,0x3d,0x8b,0xfb,0xc7,0xe3,0x67,0xa7,0x07,0xf1,0x71,0xa7,0x53,0xb5,0x29,0x89,
5523     0xe5,0x2b,0xa7,0x17,0x29,0xe9,0x4f,0xc5,0x65,0x6d,0x6b,0xef,0x0d,0x89,0x49,0x2f,
5524     0xb3,0x43,0x53,0x65,0x1d,0x49,0xa3,0x13,0x89,0x59,0xef,0x6b,0xef,0x65,0x1d,0x0b,
5525     0x59,0x13,0xe3,0x4f,0x9d,0xb3,0x29,0x43,0x2b,0x07,0x1d,0x95,0x59,0x59,0x47,0xfb,
5526     0xe5,0xe9,0x61,0x47,0x2f,0x35,0x7f,0x17,0x7f,0xef,0x7f,0x95,0x95,0x71,0xd3,0xa3,
5527     0x0b,0x71,0xa3,0xad,0x0b,0x3b,0xb5,0xfb,0xa3,0xbf,0x4f,0x83,0x1d,0xad,0xe9,0x2f,
5528     0x71,0x65,0xa3,0xe5,0x07,0x35,0x3d,0x0d,0xb5,0xe9,0xe5,0x47,0x3b,0x9d,0xef,0x35,
5529     0xa3,0xbf,0xb3,0xdf,0x53,0xd3,0x97,0x53,0x49,0x71,0x07,0x35,0x61,0x71,0x2f,0x43,
5530     0x2f,0x11,0xdf,0x17,0x97,0xfb,0x95,0x3b,0x7f,0x6b,0xd3,0x25,0xbf,0xad,0xc7,0xc5,
5531     0xc5,0xb5,0x8b,0xef,0x2f,0xd3,0x07,0x6b,0x25,0x49,0x95,0x25,0x49,0x6d,0x71,0xc7 },
5532   { 0xa7,0xbc,0xc9,0xad,0x91,0xdf,0x85,0xe5,0xd4,0x78,0xd5,0x17,0x46,0x7c,0x29,0x4c,
5533     0x4d,0x03,0xe9,0x25,0x68,0x11,0x86,0xb3,0xbd,0xf7,0x6f,0x61,0x22,0xa2,0x26,0x34,
5534     0x2a,0xbe,0x1e,0x46,0x14,0x68,0x9d,0x44,0x18,0xc2,0x40,0xf4,0x7e,0x5f,0x1b,0xad,
5535     0x0b,0x94,0xb6,0x67,0xb4,0x0b,0xe1,0xea,0x95,0x9c,0x66,0xdc,0xe7,0x5d,0x6c,0x05,
5536     0xda,0xd5,0xdf,0x7a,0xef,0xf6,0xdb,0x1f,0x82,0x4c,0xc0,0x68,0x47,0xa1,0xbd,0xee,
5537     0x39,0x50,0x56,0x4a,0xdd,0xdf,0xa5,0xf8,0xc6,0xda,0xca,0x90,0xca,0x01,0x42,0x9d,
5538     0x8b,0x0c,0x73,0x43,0x75,0x05,0x94,0xde,0x24,0xb3,0x80,0x34,0xe5,0x2c,0xdc,0x9b,
5539     0x3f,0xca,0x33,0x45,0xd0,0xdb,0x5f,0xf5,0x52,0xc3,0x21,0xda,0xe2,0x22,0x72,0x6b,
5540     0x3e,0xd0,0x5b,0xa8,0x87,0x8c,0x06,0x5d,0x0f,0xdd,0x09,0x19,0x93,0xd0,0xb9,0xfc,
5541     0x8b,0x0f,0x84,0x60,0x33,0x1c,0x9b,0x45,0xf1,0xf0,0xa3,0x94,0x3a,0x12,0x77,0x33,
5542     0x4d,0x44,0x78,0x28,0x3c,0x9e,0xfd,0x65,0x57,0x16,0x94,0x6b,0xfb,0x59,0xd0,0xc8,
5543     0x22,0x36,0xdb,0xd2,0x63,0x98,0x43,0xa1,0x04,0x87,0x86,0xf7,0xa6,0x26,0xbb,0xd6,
5544     0x59,0x4d,0xbf,0x6a,0x2e,0xaa,0x2b,0xef,0xe6,0x78,0xb6,0x4e,0xe0,0x2f,0xdc,0x7c,
5545     0xbe,0x57,0x19,0x32,0x7e,0x2a,0xd0,0xb8,0xba,0x29,0x00,0x3c,0x52,0x7d,0xa8,0x49,
5546     0x3b,0x2d,0xeb,0x25,0x49,0xfa,0xa3,0xaa,0x39,0xa7,0xc5,0xa7,0x50,0x11,0x36,0xfb,
5547     0xc6,0x67,0x4a,0xf5,0xa5,0x12,0x65,0x7e,0xb0,0xdf,0xaf,0x4e,0xb3,0x61,0x7f,0x2f } };
5548   unsigned offset=0, entries, tag, type, len, save, c;
5549   unsigned ver97=0, serial=0, i, wbi=0, wb[4]={0,0,0,0};
5550   uchar buf97[324], ci, cj, ck;
5551   short morder, sorder=order;
5552   char buf[10];
5553 /*
5554    The MakerNote might have its own TIFF header (possibly with
5555    its own byte-order!), or it might just be a table.
5556  */
5557   if (!strcmp(make,"Nokia")) return;
5558   fread (buf, 1, 10, ifp);
5559   if (!strncmp (buf,"KDK" ,3) ||	/* these aren't TIFF tables */
5560       !strncmp (buf,"VER" ,3) ||
5561       !strncmp (buf,"IIII",4) ||
5562       !strncmp (buf,"MMMM",4)) return;
5563   if (!strncmp (buf,"KC"  ,2) ||	/* Konica KD-400Z, KD-510Z */
5564       !strncmp (buf,"MLY" ,3)) {	/* Minolta DiMAGE G series */
5565     order = 0x4d4d;
5566     while ((i=ftell(ifp)) < data_offset && i < 16384) {
5567       wb[0] = wb[2];  wb[2] = wb[1];  wb[1] = wb[3];
5568       wb[3] = get2();
5569       if (wb[1] == 256 && wb[3] == 256 &&
5570 	  wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640)
5571 	FORC4 cam_mul[c] = wb[c];
5572     }
5573     goto quit;
5574   }
5575   if (!strcmp (buf,"Nikon")) {
5576     base = ftell(ifp);
5577     order = get2();
5578     if (get2() != 42) goto quit;
5579     offset = get4();
5580     fseek (ifp, offset-8, SEEK_CUR);
5581   } else if (!strcmp (buf,"OLYMPUS") ||
5582              !strcmp (buf,"PENTAX ")) {
5583     base = ftell(ifp)-10;
5584     fseek (ifp, -2, SEEK_CUR);
5585     order = get2();
5586     if (buf[0] == 'O') get2();
5587   } else if (!strncmp (buf,"SONY",4) ||
5588 	     !strcmp  (buf,"Panasonic")) {
5589     goto nf;
5590   } else if (!strncmp (buf,"FUJIFILM",8)) {
5591     base = ftell(ifp)-10;
5592 nf: order = 0x4949;
5593     fseek (ifp,  2, SEEK_CUR);
5594   } else if (!strcmp (buf,"OLYMP") ||
5595 	     !strcmp (buf,"LEICA") ||
5596 	     !strcmp (buf,"Ricoh") ||
5597 	     !strcmp (buf,"EPSON"))
5598     fseek (ifp, -2, SEEK_CUR);
5599   else if (!strcmp (buf,"AOC") ||
5600 	   !strcmp (buf,"QVC"))
5601     fseek (ifp, -4, SEEK_CUR);
5602   // ALB -- taken from LibRaw ------------------------------------------------
5603   else if (!strncmp(buf, "CMT3", 4))
5604   {
5605     order = sget2((uchar *)(buf + 4));
5606     fseek(ifp, 2L, SEEK_CUR);
5607   }
5608   else if (RT_canon_CR3_data.CR3_CTMDtag)
5609   {
5610     order = sget2((uchar *)buf);
5611     fseek(ifp, -2L, SEEK_CUR);
5612   }
5613   // -------------------------------------------------------------------------
5614 
5615   else {
5616     fseek (ifp, -10, SEEK_CUR);
5617     if (!strncmp(make,"SAMSUNG",7))
5618       base = ftell(ifp);
5619   }
5620   entries = get2();
5621   if (entries > 2000) return;
5622   morder = order;
5623   while (entries--) {
5624     order = morder;
5625     tiff_get (base, &tag, &type, &len, &save);
5626     tag |= uptag << 16;
5627     if (tag == 2 && strstr(make,"NIKON") && !iso_speed)
5628       iso_speed = (get2(),get2());
5629     if ((tag == 0x25 || tag == 0x28) && strstr(make,"NIKON") && !iso_speed) { // Nikon ISOInfo Tags/ISO & ISO2
5630       uchar iso[1];
5631       fread (iso, 1, 1, ifp);
5632       iso_speed = 100 * pow(2,(float)iso[0]/12.0-5);
5633     }
5634     if (tag == 4 && len > 26 && len < 35) {
5635       if ((i=(get4(),get2())) != 0x7fff && !iso_speed)
5636 	iso_speed = 50 * pow (2, i/32.0 - 4);
5637       if ((i=(get2(),get2())) != 0x7fff && !aperture)
5638 	aperture = pow (2, i/64.0);
5639       if ((i=get2()) != 0xffff && !shutter)
5640 	shutter = pow (2, (short) i/-32.0);
5641       wbi = (get2(),get2());
5642       shot_order = (get2(),get2());
5643     }
5644     if ((tag == 4 || tag == 0x114) && !strncmp(make,"KONICA",6)) {
5645       fseek (ifp, tag == 4 ? 140:160, SEEK_CUR);
5646       switch (get2()) {
5647 	case 72:  flip = 0;  break;
5648 	case 76:  flip = 6;  break;
5649 	case 82:  flip = 5;  break;
5650       }
5651     }
5652     if (tag == 7 && type == 2 && len > 20)
5653       fgets (model2, 64, ifp);
5654     if (tag == 8 && type == 4)
5655       shot_order = get4();
5656     if (tag == 9 && !strcmp(make,"Canon"))
5657       fread (artist, 64, 1, ifp);
5658     if (tag == 0xc && len == 4)
5659       FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type);
5660     if (tag == 0xd && type == 7 && get2() == 0xaaaa) {
5661       for (c=i=2; (ushort) c != 0xbbbb && i < len; i++)
5662 	c = c << 8 | fgetc(ifp);
5663       while ((i+=4) < len-5)
5664     if (get4() == 257 && (i=len) && (c = (get4(),fgetc(ifp))) < 3 && strcmp(make,"Canon"))
5665       // don't use this tag for Canon cameras as it's known to give wrong orientation some times
5666 	  flip = "065"[c]-'0';
5667     }
5668     if (tag == 0x10 && type == 4)
5669       unique_id = get4();
5670     if (tag == 0x11 && is_raw && !strncmp(make,"NIKON",5)) {
5671       fseek (ifp, get4()+base, SEEK_SET);
5672       parse_tiff_ifd (base);
5673     }
5674     if (tag == 0x14 && type == 7) {
5675       if (len == 2560) {
5676 	fseek (ifp, 1248, SEEK_CUR);
5677 	goto get2_256;
5678       }
5679       fread (buf, 1, 10, ifp);
5680       if (!strncmp(buf,"NRW ",4)) {
5681 	fseek (ifp, strcmp(buf+4,"0100") ? 46:1546, SEEK_CUR);
5682 	cam_mul[0] = get4() << 2;
5683 	cam_mul[1] = get4() + get4();
5684 	cam_mul[2] = get4() << 2;
5685       }
5686     }
5687     //if (tag == 0x15 && type == 2 && is_raw)
5688     if (tag == 0x15 && type == 2 && is_raw && strstr(model, "Hasselblad ") != model) // RT: don't overwrite already parsed Hasselblad model
5689       fread (model, 64, 1, ifp);
5690     if (strstr(make,"PENTAX")) {
5691       if (tag == 0x1b) tag = 0x1018;
5692       if (tag == 0x1c) tag = 0x1017;
5693     }
5694     if (tag == 0x19 && !strcmp(make,"Hasselblad") && len == 0x300000) { // RT
5695         parse_hasselblad_gain();                                        // RT
5696     }                                                                   // RT
5697     if (tag == 0x1d)
5698       while ((c = fgetc(ifp)) && c != EOF)
5699 	serial = serial*10 + (isdigit(c) ? c - '0' : c % 10);
5700     if (tag == 0x29 && type == 1) {
5701       c = wbi < 18 ? "012347800000005896"[wbi]-'0' : 0;
5702       fseek (ifp, 8 + c*32, SEEK_CUR);
5703       FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4();
5704     }
5705     if (tag == 0x3d && type == 3 && len == 4)
5706       FORC4 cblack[c ^ c >> 1] = get2() >> (14-tiff_bps);
5707     if (tag == 0x81 && type == 4) {
5708       data_offset = get4();
5709       fseek (ifp, data_offset + 41, SEEK_SET);
5710       raw_height = get2() * 2;
5711       raw_width  = get2();
5712       filters = 0x61616161;
5713     }
5714     if ((tag == 0x81  && type == 7) ||
5715 	(tag == 0x100 && type == 7) ||
5716 	(tag == 0x280 && type == 1)) {
5717       thumb_offset = ftell(ifp);
5718       thumb_length = len;
5719     }
5720     if (tag == 0x88 && type == 4 && (thumb_offset = get4()))
5721       thumb_offset += base;
5722     if (tag == 0x89 && type == 4)
5723       thumb_length = get4();
5724     if (tag == 0x8c || tag == 0x96)
5725       meta_offset = ftell(ifp);
5726     if (tag == 0x97) {
5727       for (i=0; i < 4; i++)
5728 	ver97 = ver97 * 10 + fgetc(ifp)-'0';
5729       switch (ver97) {
5730 	case 100:
5731 	  fseek (ifp, 68, SEEK_CUR);
5732 	  FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2();
5733 	  break;
5734 	case 102:
5735 	  fseek (ifp, 6, SEEK_CUR);
5736 	  FORC4 cam_mul[c ^ (c >> 1)] = get2();
5737 	  break;
5738 	case 103:
5739 	  fseek (ifp, 16, SEEK_CUR);
5740 	  FORC4 cam_mul[c] = get2();
5741       }
5742       if (ver97 >= 200) {
5743 	if (ver97 != 205) fseek (ifp, 280, SEEK_CUR);
5744 	fread (buf97, 324, 1, ifp);
5745       }
5746     }
5747     if (tag == 0xa1 && type == 7) {
5748       order = 0x4949;
5749       fseek (ifp, 140, SEEK_CUR);
5750       FORC3 cam_mul[c] = get4();
5751     }
5752     if (tag == 0xa4 && type == 3) {
5753       fseek (ifp, wbi*48, SEEK_CUR);
5754       FORC3 cam_mul[c] = get2();
5755     }
5756     if (tag == 0xa7 && (unsigned) (ver97-200) < 17) {
5757       ci = xlat[0][serial & 0xff];
5758       cj = xlat[1][fgetc(ifp)^fgetc(ifp)^fgetc(ifp)^fgetc(ifp)];
5759       ck = 0x60;
5760       for (i=0; i < 324; i++)
5761 	buf97[i] ^= (cj += ci * ck++);
5762       i = "66666>666;6A;:;55"[ver97-200] - '0';
5763       FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] =
5764 	sget2 (buf97 + (i & -2) + c*2);
5765     }
5766     if (tag == 0x200 && len == 3)
5767       shot_order = (get4(),get4());
5768     if (tag == 0x200 && len == 4)
5769       FORC4 cblack[c ^ c >> 1] = get2();
5770     if (tag == 0x201 && len == 4)
5771       FORC4 cam_mul[c ^ (c >> 1)] = get2();
5772     if (tag == 0x220 && type == 7)
5773       meta_offset = ftell(ifp);
5774     if (tag == 0x401 && type == 4 && len == 4)
5775       FORC4 cblack[c ^ c >> 1] = get4();
5776     if (tag == 0xe01) {		/* Nikon Capture Note */
5777       order = 0x4949;
5778       fseek (ifp, 22, SEEK_CUR);
5779       for (offset=22; offset+22 < len; offset += 22+i) {
5780 	tag = get4();
5781 	fseek (ifp, 14, SEEK_CUR);
5782 	i = get4()-4;
5783 	if (tag == 0x76a43207) flip = get2();
5784 	else fseek (ifp, i, SEEK_CUR);
5785       }
5786     }
5787     if (tag == 0xe80 && len == 256 && type == 7) {
5788       fseek (ifp, 48, SEEK_CUR);
5789       cam_mul[0] = get2() * 508 * 1.078 / 0x10000;
5790       cam_mul[2] = get2() * 382 * 1.173 / 0x10000;
5791     }
5792     if (tag == 0xf00 && type == 7) {
5793       if (len == 614)
5794 	fseek (ifp, 176, SEEK_CUR);
5795       else if (len == 734 || len == 1502)
5796 	fseek (ifp, 148, SEEK_CUR);
5797       else goto next;
5798       goto get2_256;
5799     }
5800     if ((tag == 0x1011 && len == 9) || tag == 0x20400200)
5801       for (i=0; i < 3; i++)
5802 	FORC3 cmatrix[i][c] = ((short) get2()) / 256.0;
5803     if ((tag == 0x1012 || tag == 0x20400600) && len == 4)
5804       FORC4 cblack[c ^ c >> 1] = get2();
5805     if (tag == 0x1017 || tag == 0x20400100)
5806       cam_mul[0] = get2() / 256.0;
5807     if (tag == 0x1018 || tag == 0x20400100)
5808       cam_mul[2] = get2() / 256.0;
5809     if (tag == 0x2011 && len == 2) {
5810 get2_256:
5811       order = 0x4d4d;
5812       cam_mul[0] = get2() / 256.0;
5813       cam_mul[2] = get2() / 256.0;
5814     }
5815     if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13))
5816       fseek (ifp, get4()+base, SEEK_SET);
5817     if (tag == 0x2020 && !strncmp(buf,"OLYMP",5))
5818       parse_thumb_note (base, 257, 258);
5819     if (tag == 0x2040)
5820       parse_makernote (base, 0x2040);
5821     if (tag == 0xb028) {
5822       fseek (ifp, get4()+base, SEEK_SET);
5823       parse_thumb_note (base, 136, 137);
5824     }
5825     if (tag == 0x4001 && len > 500) {
5826       // i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126;
5827       // fseek (ifp, i, SEEK_CUR);
5828       // FORC4 cam_mul[c ^ (c >> 1)] = get2();
5829       // for (i+=18; i <= len; i+=10) {
5830       //   get2();
5831       //   FORC4 sraw_mul[c ^ (c >> 1)] = get2();
5832       //   if (sraw_mul[1] == 1170) break;
5833       // }
5834         // -- ALB -- adapted from LibRaw --------------------------------------
5835     int bls = 0;
5836     long int offsetChannelBlackLevel = 0L;
5837     long int offsetChannelBlackLevel2 = 0L;
5838     long int offsetWhiteLevels = 0L;
5839     struct {
5840         int AverageBlackLevel;
5841         int ColorDataSubVer;
5842         int NormalWhiteLevel;
5843         int SpecularWhiteLevel;
5844     } imCanon = { 0, 0, 0, 0 };
5845     long int save1 = ftell(ifp);
5846 
5847     switch (len)
5848     {
5849 
5850     case 582:
5851       // imCanon.ColorDataVer = 1; // 20D / 350D
5852 
5853       fseek(ifp, save1 + (0x0019 << 1), SEEK_SET);
5854       FORC4 cam_mul[c ^ (c >> 1)] = (float)get2();
5855       // fseek(ifp, save1 + (0x001e << 1), SEEK_SET);
5856       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
5857       // fseek(ifp, save1 + (0x0041 << 1), SEEK_SET);
5858       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2();
5859       // fseek(ifp, save1 + (0x0046 << 1), SEEK_SET);
5860       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2();
5861 
5862       // fseek(ifp, save1 + (0x0023 << 1), SEEK_SET);
5863       // Canon_WBpresets(2, 2);
5864       // fseek(ifp, save1 + (0x004b << 1), SEEK_SET);
5865       // Canon_WBCTpresets(1); // ABCT
5866       offsetChannelBlackLevel = save1 + (0x00a6 << 1);
5867       break;
5868 
5869     case 653:
5870       // imCanon.ColorDataVer = 2; // 1Dmk2 / 1DsMK2
5871 
5872       // fseek(ifp, save1 + (0x0018 << 1), SEEK_SET);
5873       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
5874       fseek(ifp, save1 + (0x0022 << 1), SEEK_SET);
5875       FORC4 cam_mul[c ^ (c >> 1)] = (float)get2();
5876       // fseek(ifp, save1 + (0x0090 << 1), SEEK_SET);
5877       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2();
5878       // fseek(ifp, save1 + (0x0095 << 1), SEEK_SET);
5879       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2();
5880       // fseek(ifp, save1 + (0x009a << 1), SEEK_SET);
5881       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom3][c ^ (c >> 1)] = get2();
5882 
5883       // fseek(ifp, save1 + (0x0027 << 1), SEEK_SET);
5884       // Canon_WBpresets(2, 12);
5885       // fseek(ifp, save1 + (0x00a4 << 1), SEEK_SET);
5886       // Canon_WBCTpresets(1); // ABCT
5887       offsetChannelBlackLevel = save1 + (0x011e << 1);
5888       break;
5889 
5890     case 796:
5891       // imCanon.ColorDataVer = 3; // 1DmkIIN / 5D / 30D / 400D
5892       // imCanon.ColorDataSubVer = get2();
5893 
5894       fseek(ifp, save1 + (0x003f << 1), SEEK_SET);
5895       FORC4 cam_mul[c ^ (c >> 1)] = (float)get2();
5896       // fseek(ifp, save1 + (0x0044 << 1), SEEK_SET);
5897       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
5898       // fseek(ifp, save1 + (0x0049 << 1), SEEK_SET);
5899       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
5900       // fseek(ifp, save1 + (0x0071 << 1), SEEK_SET);
5901       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2();
5902       // fseek(ifp, save1 + (0x0076 << 1), SEEK_SET);
5903       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2();
5904       // fseek(ifp, save1 + (0x007b << 1), SEEK_SET);
5905       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom3][c ^ (c >> 1)] = get2();
5906       // fseek(ifp, save1 + (0x0080 << 1), SEEK_SET);
5907       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom][c ^ (c >> 1)] = get2();
5908 
5909       // fseek(ifp, save1 + (0x004e << 1), SEEK_SET);
5910       // Canon_WBpresets(2, 12);
5911       // fseek(ifp, save1 + (0x0085 << 1), SEEK_SET);
5912       // Canon_WBCTpresets(0); // BCAT
5913       offsetChannelBlackLevel = save1 + (0x00c4 << 1);
5914       break;
5915 
5916     // 1DmkIII / 1DSmkIII / 1DmkIV / 5DmkII
5917     // 7D / 40D / 50D / 60D / 450D / 500D
5918     // 550D / 1000D / 1100D
5919     case 674:
5920     case 692:
5921     case 702:
5922     case 1227:
5923     case 1250:
5924     case 1251:
5925     case 1337:
5926     case 1338:
5927     case 1346:
5928       // imCanon.ColorDataVer = 4;
5929       imCanon.ColorDataSubVer = get2();
5930 
5931       fseek(ifp, save1 + (0x003f << 1), SEEK_SET);
5932       FORC4 cam_mul[c ^ (c >> 1)] = (float)get2();
5933       // fseek(ifp, save1 + (0x0044 << 1), SEEK_SET);
5934       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
5935       // fseek(ifp, save1 + (0x0049 << 1), SEEK_SET);
5936       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
5937 
5938       fseek(ifp, save1 + (0x004e << 1), SEEK_SET);
5939       FORC4 sraw_mul[c ^ (c >> 1)] = get2();
5940       // fseek(ifp, save1 + (0x0053 << 1), SEEK_SET);
5941       // Canon_WBpresets(2, 12);
5942       // fseek(ifp, save1 + (0x00a8 << 1), SEEK_SET);
5943       // Canon_WBCTpresets(0); // BCAT
5944 
5945       if ((imCanon.ColorDataSubVer == 4) ||
5946           (imCanon.ColorDataSubVer == 5))
5947       {
5948         offsetChannelBlackLevel = save1 + (0x02b4 << 1);
5949         offsetWhiteLevels = save1 + (0x02b8 << 1);
5950       }
5951       else if ((imCanon.ColorDataSubVer == 6) ||
5952                (imCanon.ColorDataSubVer == 7))
5953       {
5954         offsetChannelBlackLevel = save1 + (0x02cb << 1);
5955         offsetWhiteLevels = save1 + (0x02cf << 1);
5956       }
5957       else if (imCanon.ColorDataSubVer == 9)
5958       {
5959         offsetChannelBlackLevel = save1 + (0x02cf << 1);
5960         offsetWhiteLevels = save1 + (0x02d3 << 1);
5961       }
5962       else
5963         offsetChannelBlackLevel = save1 + (0x00e7 << 1);
5964       break;
5965 
5966     case 5120:  // PowerShot G10, G12, G5 X, G7 X, G9 X, EOS M3, EOS M5, EOS M6
5967       // imCanon.ColorDataVer = 5;
5968       imCanon.ColorDataSubVer = get2();
5969 
5970       fseek(ifp, save1 + (0x0047 << 1), SEEK_SET);
5971       FORC4 cam_mul[c ^ (c >> 1)] = (float)get2();
5972 
5973       if (imCanon.ColorDataSubVer == 0xfffc)
5974       { // -4: G7 X Mark II, G9 X Mark II, G1 X Mark III, M5, M100, M6
5975         // fseek(ifp, save1 + (0x004f << 1), SEEK_SET);
5976         // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
5977         // fseek(ifp, 8, SEEK_CUR);
5978         // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] =
5979         //     get2();
5980         // fseek(ifp, 8, SEEK_CUR);
5981         // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2();
5982         // fseek(ifp, 8, SEEK_CUR);
5983         // Canon_WBpresets(8, 24);
5984         // fseek(ifp, 168, SEEK_CUR);
5985         // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2();
5986         // fseek(ifp, 24, SEEK_CUR);
5987         // Canon_WBCTpresets(2); // BCADT
5988         offsetChannelBlackLevel = save1 + (0x014d << 1);
5989         offsetWhiteLevels = save1 + (0x0569 << 1);
5990       }
5991       else if (imCanon.ColorDataSubVer == 0xfffd)
5992       { // -3: M10/M3/G1 X/G1 X II/G10/G11/G12/G15/G16/G3 X/G5 X/G7 X/G9
5993         // X/S100/S110/S120/S90/S95/SX1 IX/SX50 HS/SX60 HS
5994         // fseek(ifp, save1 + (0x004c << 1), SEEK_SET);
5995         // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
5996         // get2();
5997         // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] =
5998         //     get2();
5999         // get2();
6000         // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2();
6001         // get2();
6002         // Canon_WBpresets(2, 12);
6003         // fseek(ifp, save1 + (0x00ba << 1), SEEK_SET);
6004         // Canon_WBCTpresets(2); // BCADT
6005         offsetChannelBlackLevel = save1 + (0x0108 << 1);
6006       }
6007       break;
6008 
6009     case 1273:
6010     case 1275:
6011       // imCanon.ColorDataVer = 6; // 600D / 1200D
6012       imCanon.ColorDataSubVer = get2();
6013 
6014       fseek(ifp, save1 + (0x003f << 1), SEEK_SET);
6015       FORC4 cam_mul[c ^ (c >> 1)] = (float)get2();
6016       // fseek(ifp, save1 + (0x0044 << 1), SEEK_SET);
6017       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
6018       // fseek(ifp, save1 + (0x0049 << 1), SEEK_SET);
6019       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
6020 
6021       fseek(ifp, save1 + (0x0062 << 1), SEEK_SET);
6022       FORC4 sraw_mul[c ^ (c >> 1)] = get2();
6023       // fseek(ifp, save1 + (0x0067 << 1), SEEK_SET);
6024       // Canon_WBpresets(2, 12);
6025       // fseek(ifp, save1 + (0x00bc << 1), SEEK_SET);
6026       // Canon_WBCTpresets(0); // BCAT
6027       offsetChannelBlackLevel = save1 + (0x01df << 1);
6028       offsetWhiteLevels = save1 + (0x01e3 << 1);
6029       break;
6030 
6031     // 1DX / 5DmkIII / 6D / 100D / 650D / 700D / EOS M / 7DmkII / 750D / 760D
6032     case 1312:
6033     case 1313:
6034     case 1316:
6035     case 1506:
6036       // imCanon.ColorDataVer = 7;
6037       imCanon.ColorDataSubVer = get2();
6038 
6039       fseek(ifp, save1 + (0x003f << 1), SEEK_SET);
6040       FORC4 cam_mul[c ^ (c >> 1)] = (float)get2();
6041       // fseek(ifp, save1 + (0x0044 << 1), SEEK_SET);
6042       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
6043       // fseek(ifp, save1 + (0x0049 << 1), SEEK_SET);
6044       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
6045 
6046       fseek(ifp, save1 + (0x007b << 1), SEEK_SET);
6047       FORC4 sraw_mul[c ^ (c >> 1)] = get2();
6048       // fseek(ifp, save1 + (0x0080 << 1), SEEK_SET);
6049       // Canon_WBpresets(2, 12);
6050       // fseek(ifp, save1 + (0x00d5 << 1), SEEK_SET);
6051       // Canon_WBCTpresets(0); // BCAT
6052 
6053       if (imCanon.ColorDataSubVer == 10)
6054       {
6055         offsetChannelBlackLevel = save1 + (0x01f8 << 1);
6056         offsetWhiteLevels = save1 + (0x01fc << 1);
6057       }
6058       else if (imCanon.ColorDataSubVer == 11)
6059       {
6060         offsetChannelBlackLevel = save1 + (0x02d8 << 1);
6061         offsetWhiteLevels = save1 + (0x02dc << 1);
6062       }
6063       break;
6064 
6065     // 5DS / 5DS R / 80D / 1300D / 1500D / 3000D / 5D4 / 800D / 77D / 6D II /
6066     // 200D
6067     case 1560:
6068     case 1592:
6069     case 1353:
6070     case 1602:
6071       // imCanon.ColorDataVer = 8;
6072       imCanon.ColorDataSubVer = get2();
6073 
6074       fseek(ifp, save1 + (0x003f << 1), SEEK_SET);
6075       FORC4 cam_mul[c ^ (c >> 1)] = (float)get2();
6076       // fseek(ifp, save1 + (0x0044 << 1), SEEK_SET);
6077       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
6078       // fseek(ifp, save1 + (0x0049 << 1), SEEK_SET);
6079       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
6080 
6081       fseek(ifp, save1 + (0x0080 << 1), SEEK_SET);
6082       FORC4 sraw_mul[c ^ (c >> 1)] = get2();
6083       // fseek(ifp, save1 + (0x0085 << 1), SEEK_SET);
6084       // Canon_WBpresets(2, 12);
6085       // fseek(ifp, save1 + (0x0107 << 1), SEEK_SET);
6086       // Canon_WBCTpresets(0); // BCAT
6087 
6088       if (imCanon.ColorDataSubVer == 14)
6089       { // 1300D / 1500D / 3000D
6090         offsetChannelBlackLevel = save1 + (0x022c << 1);
6091         offsetWhiteLevels = save1 + (0x0230 << 1);
6092       }
6093       else
6094       {
6095         offsetChannelBlackLevel = save1 + (0x030a << 1);
6096         offsetWhiteLevels = save1 + (0x030e << 1);
6097       }
6098       break;
6099 
6100     case 1820: // M50, ColorDataSubVer 16
6101     case 1824: // EOS R, SX740HS, ColorDataSubVer 17
6102     case 1816: // EOS RP, SX70HS, ColorDataSubVer 18;
6103                // EOS M6 Mark II, EOS 90D, G7XmkIII, ColorDataSubVer 19
6104       // imCanon.ColorDataVer = 9;
6105       imCanon.ColorDataSubVer = get2();
6106 
6107       fseek(ifp, save1 + (0x0047 << 1), SEEK_SET);
6108       FORC4 cam_mul[c ^ (c >> 1)] = (float)get2();
6109       // get2();
6110       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
6111       // get2();
6112       // FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
6113       // fseek(ifp, save1 + (0x0088 << 1), SEEK_SET);
6114       // Canon_WBpresets(2, 12);
6115       // fseek(ifp, save1 + (0x010a << 1), SEEK_SET);
6116       // Canon_WBCTpresets(0);
6117       offsetChannelBlackLevel = save1 + (0x0318 << 1);
6118       offsetChannelBlackLevel2 = save1 + (0x0149 << 1);
6119       offsetWhiteLevels = save1 + (0x031c << 1);
6120       break;
6121     }
6122 
6123     if (offsetChannelBlackLevel)
6124     {
6125       fseek(ifp, offsetChannelBlackLevel, SEEK_SET);
6126       FORC4
6127           bls += (cblack/*imCanon.ChannelBlackLevel*/[c ^ (c >> 1)] = get2());
6128       imCanon.AverageBlackLevel = bls / 4;
6129       // RT_blacklevel_from_constant = ThreeValBool::F;
6130     }
6131     if (offsetWhiteLevels)
6132     {
6133       if ((offsetWhiteLevels - offsetChannelBlackLevel) != 8L)
6134         fseek(ifp, offsetWhiteLevels, SEEK_SET);
6135       imCanon.NormalWhiteLevel = get2();
6136       imCanon.SpecularWhiteLevel = get2();
6137       // FORC4
6138       //   imgdata.color.linear_max[c] = imCanon.SpecularWhiteLevel;
6139       maximum = imCanon.SpecularWhiteLevel;
6140       // RT_whitelevel_from_constant = ThreeValBool::F;
6141     }
6142 
6143     if(!imCanon.AverageBlackLevel && offsetChannelBlackLevel2)
6144     {
6145         fseek(ifp, offsetChannelBlackLevel2, SEEK_SET);
6146         FORC4
6147             bls += (cblack/*imCanon.ChannelBlackLevel*/[c ^ (c >> 1)] = get2());
6148         imCanon.AverageBlackLevel = bls / 4;
6149         // RT_blacklevel_from_constant = ThreeValBool::F;
6150     }
6151     fseek(ifp, save1, SEEK_SET);
6152 
6153     //---------------------------------------------------------------------
6154     }    if (tag == 0x4021 && get4() && get4())
6155       FORC4 cam_mul[c] = 1024;
6156     if (tag == 0xa021)
6157       FORC4 cam_mul[c ^ (c >> 1)] = get4();
6158     if (tag == 0xa028)
6159       FORC4 cam_mul[c ^ (c >> 1)] -= get4();
6160     if (tag == 0xb001)
6161       unique_id = get2();
6162 next:
6163     fseek (ifp, save, SEEK_SET);
6164   }
6165 quit:
6166   order = sorder;
6167 }
6168 
6169 /*
6170    Since the TIFF DateTime string has no timezone information,
6171    assume that the camera's clock was set to Universal Time.
6172  */
get_timestamp(int reversed)6173 void CLASS get_timestamp (int reversed)
6174 {
6175   struct tm t;
6176   char str[20];
6177   int i;
6178 
6179   str[19] = 0;
6180   if (reversed)
6181     for (i=19; i--; ) str[i] = fgetc(ifp);
6182   else
6183     fread (str, 19, 1, ifp);
6184   memset (&t, 0, sizeof t);
6185   if (sscanf (str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon,
6186 	&t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6)
6187     return;
6188   t.tm_year -= 1900;
6189   t.tm_mon -= 1;
6190   t.tm_isdst = -1;
6191   if (mktime(&t) > 0)
6192     timestamp = mktime(&t);
6193 }
6194 
parse_exif(int base)6195 void CLASS parse_exif (int base)
6196 {
6197   unsigned kodak, entries, tag, type, len, save, c;
6198   double expo;
6199 
6200   kodak = !strncmp(make,"EASTMAN",7) && tiff_nifds < 3;
6201   entries = get2();
6202   while (entries--) {
6203     tiff_get (base, &tag, &type, &len, &save);
6204     switch (tag) {
6205       case 33434:  tiff_ifd[tiff_nifds-1].shutter = shutter = getreal(type);		break;
6206       case 33437:  aperture = getreal(type);		break;
6207       case 34855:  iso_speed = get2();			break;
6208       case 34866:  if((!iso_speed) || iso_speed == 65535) iso_speed = get4();break;
6209       case 36867:
6210       case 36868:  get_timestamp(0);			break;
6211       case 37377:  if ((expo = -getreal(type)) < 128)
6212              tiff_ifd[tiff_nifds-1].shutter =
6213 		     shutter = pow (2, expo);		break;
6214       case 37378:  aperture = pow (2, getreal(type)/2);	break;
6215       case 37386:  focal_len = getreal(type);		break;
6216       case 37500:  parse_makernote (base, 0);		break;
6217       case 40962:  if (kodak) raw_width  = get4();	break;
6218       case 40963:  if (kodak) raw_height = get4();	break;
6219       case 41730:
6220 	if (get4() == 0x20002)
6221 	  for (exif_cfa=c=0; c < 8; c+=2)
6222 	    exif_cfa |= fgetc(ifp) * 0x01010101 << c;
6223     }
6224     fseek (ifp, save, SEEK_SET);
6225   }
6226 }
6227 
parse_gps(int base)6228 void CLASS parse_gps (int base)
6229 {
6230   unsigned entries, tag, type, len, save, c;
6231 
6232   entries = get2();
6233   while (entries--) {
6234     tiff_get (base, &tag, &type, &len, &save);
6235     switch (tag) {
6236       case 1: case 3: case 5:
6237 	gpsdata[29+tag/2] = getc(ifp);			break;
6238       case 2: case 4: case 7:
6239 	FORC(6) gpsdata[tag/3*6+c] = get4();		break;
6240       case 6:
6241 	FORC(2) gpsdata[18+c] = get4();			break;
6242       case 18: case 29:
6243 	fgets ((char *) (gpsdata+14+tag/3), MIN(len,12), ifp);
6244     }
6245     fseek (ifp, save, SEEK_SET);
6246   }
6247 }
6248 
romm_coeff(float romm_cam[3][3])6249 void CLASS romm_coeff (float romm_cam[3][3])
6250 {
6251   static const float rgb_romm[3][3] =	/* ROMM == Kodak ProPhoto */
6252   { {  2.034193, -0.727420, -0.306766 },
6253     { -0.228811,  1.231729, -0.002922 },
6254     { -0.008565, -0.153273,  1.161839 } };
6255   int i, j, k;
6256 
6257   for (i=0; i < 3; i++)
6258     for (j=0; j < 3; j++)
6259       for (cmatrix[i][j] = k=0; k < 3; k++)
6260 	cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j];
6261 }
6262 
parse_mos(int offset)6263 void CLASS parse_mos (int offset)
6264 {
6265   char data[40];
6266   int skip, from, i, c, neut[4], planes=0, frot=0;
6267   static const char *mod[] =
6268   { "","DCB2","Volare","Cantare","CMost","Valeo 6","Valeo 11","Valeo 22",
6269     "Valeo 11p","Valeo 17","","Aptus 17","Aptus 22","Aptus 75","Aptus 65",
6270     "Aptus 54S","Aptus 65S","Aptus 75S","AFi 5","AFi 6","AFi 7",
6271     "AFi-II 7","Aptus-II 7","","Aptus-II 6","","","Aptus-II 10","Aptus-II 5",
6272     "","","","","Aptus-II 10R","Aptus-II 8","","Aptus-II 12","","AFi-II 12" };
6273   float romm_cam[3][3];
6274 
6275   fseek (ifp, offset, SEEK_SET);
6276   while (1) {
6277     if (get4() != 0x504b5453) break;
6278     get4();
6279     fread (data, 1, 40, ifp);
6280     skip = get4();
6281     from = ftell(ifp);
6282     if (!strcmp(data,"JPEG_preview_data")) {
6283       thumb_offset = from;
6284       thumb_length = skip;
6285     }
6286     if (!strcmp(data,"icc_camera_profile")) {
6287       profile_offset = from;
6288       profile_length = skip;
6289     }
6290     if (!strcmp(data,"ShootObj_back_type")) {
6291       fscanf (ifp, "%d", &i);
6292       if ((unsigned) i < sizeof mod / sizeof (*mod))
6293 	strcpy (model, mod[i]);
6294     }
6295     if (!strcmp(data,"icc_camera_to_tone_matrix")) {
6296       for (i=0; i < 9; i++)
6297 	((float *)romm_cam)[i] = int_to_float(get4());
6298       romm_coeff (romm_cam);
6299     }
6300     if (!strcmp(data,"CaptProf_color_matrix")) {
6301       for (i=0; i < 9; i++)
6302 	fscanf (ifp, "%f", (float *)romm_cam + i);
6303       romm_coeff (romm_cam);
6304     }
6305     if (!strcmp(data,"CaptProf_number_of_planes"))
6306       fscanf (ifp, "%d", &planes);
6307     if (!strcmp(data,"CaptProf_raw_data_rotation"))
6308       fscanf (ifp, "%d", &flip);
6309     if (!strcmp(data,"CaptProf_mosaic_pattern"))
6310       FORC4 {
6311 	fscanf (ifp, "%d", &i);
6312 	if (i == 1) frot = c ^ (c >> 1);
6313       }
6314     if (!strcmp(data,"ImgProf_rotation_angle")) {
6315       fscanf (ifp, "%d", &i);
6316       flip = i - flip;
6317     }
6318     if (!strcmp(data,"NeutObj_neutrals") && !cam_mul[0]) {
6319       FORC4 fscanf (ifp, "%d", neut+c);
6320       FORC3 cam_mul[c] = (float) neut[0] / neut[c+1];
6321     }
6322     if (!strcmp(data,"Rows_data"))
6323       load_flags = get4();
6324     parse_mos (from);
6325     fseek (ifp, skip+from, SEEK_SET);
6326   }
6327   if (planes)
6328     filters = (planes == 1) * 0x01010101 *
6329 	(uchar) "\x94\x61\x16\x49"[(flip/90 + frot) & 3];
6330 }
6331 
linear_table(unsigned len)6332 void CLASS linear_table (unsigned len)
6333 {
6334   int i;
6335   if (len > 0x1000) len = 0x1000;
6336   read_shorts (curve, len);
6337   for (i=len; i < 0x1000; i++)
6338     curve[i] = curve[i-1];
6339   maximum = curve[0xfff];
6340 }
6341 
parse_kodak_ifd(int base)6342 void CLASS parse_kodak_ifd (int base)
6343 {
6344   unsigned entries, tag, type, len, save;
6345   int i, c, wbi=-2, wbtemp=6500;
6346   float mul[3]={1,1,1}, num;
6347   static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 };
6348 
6349   entries = get2();
6350   if (entries > 1024) return;
6351   while (entries--) {
6352     tiff_get (base, &tag, &type, &len, &save);
6353     if (tag == 1020) wbi = getint(type);
6354     if (tag == 1021 && len == 72) {		/* WB set in software */
6355       fseek (ifp, 40, SEEK_CUR);
6356       FORC3 cam_mul[c] = 2048.0 / get2();
6357       wbi = -2;
6358     }
6359     if (tag == 2118) wbtemp = getint(type);
6360     if (tag == 2120 + wbi && wbi >= 0)
6361       FORC3 cam_mul[c] = 2048.0 / getreal(type);
6362     if (tag == 2130 + wbi)
6363       FORC3 mul[c] = getreal(type);
6364     if (tag == 2140 + wbi && wbi >= 0)
6365       FORC3 {
6366 	for (num=i=0; i < 4; i++)
6367 	  num += getreal(type) * pow (wbtemp/100.0, i);
6368 	cam_mul[c] = 2048 / (num * mul[c]);
6369       }
6370     if (tag == 2317) linear_table (len);
6371     if (tag == 6020) iso_speed = getint(type);
6372     if (tag == 64013) wbi = fgetc(ifp);
6373     if ((unsigned) wbi < 7 && tag == wbtag[wbi])
6374       FORC3 cam_mul[c] = get4();
6375     if (tag == 64019) width = getint(type);
6376     if (tag == 64020) height = (getint(type)+1) & -2;
6377     fseek (ifp, save, SEEK_SET);
6378   }
6379 }
6380 
6381 /*RT void CLASS parse_minolta (int base); */
6382 /*RT int CLASS parse_tiff (int base);*/
6383 
parse_tiff_ifd(int base)6384 int CLASS parse_tiff_ifd (int base)
6385 {
6386   unsigned entries, tag, type, len, plen=16, save;
6387   int ifd, use_cm=0, cfa, i, j, c, ima_len=0,cm_D65=0;
6388   char software[64], *cbuf, *cp;
6389   uchar cfa_pat[16], cfa_pc[] = { 0,1,2,3 }, tab[256];
6390   double cc[2][4][4];
6391   double cm[2][4][3] = {{{NAN,NAN,NAN},{NAN,NAN,NAN},{NAN,NAN,NAN},{NAN,NAN,NAN}},{{NAN,NAN,NAN},{NAN,NAN,NAN},{NAN,NAN,NAN},{NAN,NAN,NAN}}};
6392   double cam_xyz[4][3], num;
6393   double ab[]={ 1,1,1,1 }, asn[] = { 0,0,0,0 }, xyz[] = { 1,1,1 };
6394   unsigned sony_curve[] = { 0,0,0,0,0,4095 };
6395   unsigned *buf, sony_offset=0, sony_length=0, sony_key=0;
6396   struct jhead jh;
6397 /*RT*/  IMFILE *sfp;
6398 /*RT*/  int pana_raw = 0;
6399 
6400   if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0])
6401     return 1;
6402   ifd = tiff_nifds++;
6403   for (j=0; j < 4; j++)
6404     for (i=0; i < 4; i++)
6405     {
6406       cc[0][j][i] = i == j;
6407       cc[1][j][i] = i == j;
6408     }
6409   entries = get2();
6410   if (entries > 512) return 1;
6411   while (entries--) {
6412     tiff_get (base, &tag, &type, &len, &save);
6413     switch (tag) {
6414       case 1: if (len == 4) pana_raw = get4(); break;
6415       case 5:   width  = get2();  break;
6416       case 6:   height = get2();  break;
6417       case 7:   width += get2();  break;
6418       case 9:   if ((i = get2())) filters = i;  break;
6419       case 10:
6420           if (pana_raw && len == 1 && type == 3) {
6421               RT_pana_info.bpp = get2();
6422           }
6423           break;
6424       case 17: case 18:
6425 	if (type == 3 && len == 1)
6426 	  cam_mul[(tag-17)*2] = get2() / 256.0;
6427 	break;
6428       case 23:
6429 	if (type == 3) iso_speed = get2();
6430 	break;
6431       case 28: case 29: case 30:
6432 	cblack[tag-28] = get2();
6433 	cblack[3] = cblack[1];
6434 	break;
6435       case 36: case 37: case 38:
6436 	cam_mul[tag-36] = get2();
6437 	break;
6438       case 39:
6439 	if (len < 50 || cam_mul[0]) break;
6440 	fseek (ifp, 12, SEEK_CUR);
6441 	FORC3 cam_mul[c] = get2();
6442 	break;
6443       case 45:
6444           if (pana_raw && len == 1 && type == 3)
6445           {
6446               RT_pana_info.encoding = get2();
6447           }
6448           break;
6449       case 46:
6450 	if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break;
6451 	thumb_offset = ftell(ifp) - 2;
6452 	thumb_length = len;
6453 	break;
6454       case 61440:			/* Fuji HS10 table */
6455 	fseek (ifp, get4()+base, SEEK_SET);
6456 	parse_tiff_ifd (base);
6457 	break;
6458       case 2: case 256: case 61441:	/* ImageWidth */
6459 	tiff_ifd[ifd].width = getint(type);
6460 	break;
6461       case 3: case 257: case 61442:	/* ImageHeight */
6462 	tiff_ifd[ifd].height = getint(type);
6463 	break;
6464       case 258:				/* BitsPerSample */
6465       case 61443:
6466 	tiff_ifd[ifd].samples = len & 7;
6467 	if ((tiff_ifd[ifd].bps = getint(type)) > 32)
6468         tiff_ifd[ifd].bps = 8;
6469 	if (tiff_bps < tiff_ifd[ifd].bps)
6470 	    tiff_bps = tiff_ifd[ifd].bps;
6471 	break;
6472       case 61446:
6473 	raw_height = 0;
6474 	load_flags = get4() ? 24:80;
6475 	break;
6476       case 259:				/* Compression */
6477 	tiff_ifd[ifd].comp = getint(type);
6478 	break;
6479       case 262:				/* PhotometricInterpretation */
6480 	tiff_ifd[ifd].phint = get2();
6481 	break;
6482       case 270:				/* ImageDescription */
6483 	fread (desc, 512, 1, ifp);
6484 	break;
6485       case 271:				/* Make */
6486 	fgets (make, 64, ifp);
6487 	break;
6488       case 272:				/* Model */
6489         if (strstr(model, "Hasselblad ") != model) // RT: if Hasselblad, only parse the first model name (otherwise it can change from say Hasselblad CFV-50 to Hasselblad CW (ie the camera body model, not the back model which we are interested in)
6490 	  fgets (model, 64, ifp);
6491 	break;
6492       case 280:				/* Panasonic RW2 offset */
6493 	if (type != 4) break;
6494 	load_raw = &CLASS panasonic_load_raw;
6495 	load_flags = 0x2008;
6496       case 273:				/* StripOffset */
6497       case 513:				/* JpegIFOffset */
6498       case 61447:
6499 	tiff_ifd[ifd].offset = get4()+base;
6500 	if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) {
6501 	  fseek (ifp, tiff_ifd[ifd].offset, SEEK_SET);
6502 	  if (ljpeg_start (&jh, 1)) {
6503 	    tiff_ifd[ifd].comp    = 6;
6504 	    tiff_ifd[ifd].width   = jh.wide;
6505 	    tiff_ifd[ifd].height  = jh.high;
6506 	    tiff_ifd[ifd].bps     = jh.bits;
6507 	    tiff_ifd[ifd].samples = jh.clrs;
6508 	    if (!(jh.sraw || (jh.clrs & 1)))
6509 	      tiff_ifd[ifd].width *= jh.clrs;
6510 	    if ((tiff_ifd[ifd].width > 4*tiff_ifd[ifd].height) & ~jh.clrs) {
6511 	      tiff_ifd[ifd].width  /= 2;
6512 	      tiff_ifd[ifd].height *= 2;
6513 	    }
6514 	    i = order;
6515 	    parse_tiff (tiff_ifd[ifd].offset + 12);
6516 	    order = i;
6517 	  }
6518 	}
6519 	break;
6520       case 274:				/* Orientation */
6521 	tiff_ifd[ifd].flip = "50132467"[get2() & 7]-'0';
6522 	break;
6523       case 277:				/* SamplesPerPixel */
6524 	tiff_ifd[ifd].samples = getint(type) & 7;
6525 	break;
6526       case 279:				/* StripByteCounts */
6527       case 514:
6528       case 61448:
6529 	tiff_ifd[ifd].bytes = get4();
6530 	break;
6531       case 61454:
6532 	FORC3 cam_mul[(4-c) % 3] = getint(type);
6533 	break;
6534       case 305:  case 11:		/* Software */
6535 	fgets (software, 64, ifp);
6536         RT_software = software;
6537 	if (!strncmp(software,"Adobe",5) ||
6538 	    !strncmp(software,"dcraw",5) ||
6539 	    !strncmp(software,"UFRaw",5) ||
6540 	    !strncmp(software,"Bibble",6) ||
6541 	    !strncmp(software,"Nikon Scan",10) ||
6542 	    !strcmp (software,"Digital Photo Professional"))
6543 	  is_raw = 0;
6544 	break;
6545       case 306:				/* DateTime */
6546 	get_timestamp(0);
6547 	break;
6548       case 315:				/* Artist */
6549 	fread (artist, 64, 1, ifp);
6550 	break;
6551       case 317:				/* Predictor */
6552 	tiff_ifd[ifd].predictor = getint(type);
6553 	break;
6554       case 322:				/* TileWidth */
6555 	tiff_ifd[ifd].tile_width = getint(type);
6556 	break;
6557       case 323:				/* TileLength */
6558 	tiff_ifd[ifd].tile_length = getint(type);
6559 	break;
6560       case 324:				/* TileOffsets */
6561 	tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4();
6562 	if (len == 1)
6563 	  tiff_ifd[ifd].tile_width = tiff_ifd[ifd].tile_length = 0;
6564 	if (len == 4) {
6565 	  load_raw = &CLASS sinar_4shot_load_raw;
6566 	  is_raw = 5;
6567 	}
6568 	break;
6569       case 325:                         /* TileByteCounts */
6570         tiff_ifd[ifd].bytes = len > 1 ? ftell(ifp) : get4();
6571         break;
6572       case 330:				/* SubIFDs */
6573 	if (!strcmp(model,"DSLR-A100") && tiff_ifd[ifd].width == 3872) {
6574 	  load_raw = &CLASS sony_arw_load_raw;
6575 	  data_offset = get4()+base;
6576 	  ifd++;  break;
6577 	}
6578 	while (len--) {
6579 	  i = ftell(ifp);
6580 	  fseek (ifp, get4()+base, SEEK_SET);
6581 	  if (parse_tiff_ifd (base)) break;
6582 	  fseek (ifp, i+4, SEEK_SET);
6583 	}
6584 	break;
6585       case 339:
6586         tiff_ifd[ifd].sample_format = getint(type);
6587         break;
6588       case 400:
6589 	strcpy (make, "Sarnoff");
6590 	maximum = 0xfff;
6591 	break;
6592       case 28688:
6593 	FORC4 sony_curve[c+1] = get2() >> 2 & 0xfff;
6594 	for (i=0; i < 5; i++)
6595 	  for (j = sony_curve[i]+1; j <= sony_curve[i+1]; j++)
6596 	    curve[j] = curve[j-1] + (1 << i);
6597 	break;
6598       case 29184: sony_offset = get4();  break;
6599       case 29185: sony_length = get4();  break;
6600       case 29217: sony_key    = get4();  break;
6601       case 29264:
6602 	parse_minolta (ftell(ifp));
6603 	raw_width = 0;
6604 	break;
6605       case 29443:
6606 	FORC4 cam_mul[c ^ (c < 2)] = get2();
6607 	break;
6608       case 29459:
6609 	FORC4 cam_mul[c] = get2();
6610 	i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1;
6611 	SWAP (cam_mul[i],cam_mul[i+1])
6612 	break;
6613       case 33405:			/* Model2 */
6614 	fgets (model2, 64, ifp);
6615 	break;
6616       case 33421:			/* CFARepeatPatternDim */
6617 	if (get2() == 6 && get2() == 6)
6618 	  filters = 9;
6619 	break;
6620       case 33422:			/* CFAPattern */
6621 	if (filters == 9) {
6622 	  FORC(36) ((int *)xtrans)[c] = fgetc(ifp) & 3;
6623 	  break;
6624 	}
6625       case 64777:			/* Kodak P-series */
6626 	if ((plen=len) > 16) plen = 16;
6627 	fread (cfa_pat, 1, plen, ifp);
6628 	for (colors=cfa=i=0; i < plen && colors < 4; i++) {
6629 	  colors += !(cfa & (1 << cfa_pat[i]));
6630 	  cfa |= 1 << cfa_pat[i];
6631 	}
6632 	if (cfa == 070) memcpy (cfa_pc,"\003\004\005",3);	/* CMY */
6633 	if (cfa == 072) memcpy (cfa_pc,"\005\003\004\001",4);	/* GMCY */
6634 	goto guess_cfa_pc;
6635       case 33424:
6636       case 65024:
6637 	fseek (ifp, get4()+base, SEEK_SET);
6638 	parse_kodak_ifd (base);
6639 	break;
6640       case 33434:			/* ExposureTime */
6641 	tiff_ifd[ifd].shutter = shutter = getreal(type);
6642 	break;
6643       case 33437:			/* FNumber */
6644 	aperture = getreal(type);
6645 	break;
6646       case 34306:			/* Leaf white balance */
6647 	FORC4 cam_mul[c ^ 1] = 4096.0 / get2();
6648 	break;
6649       case 34307:			/* Leaf CatchLight color matrix */
6650 	fread (software, 1, 7, ifp);
6651 	if (strncmp(software,"MATRIX",6)) break;
6652 	colors = 4;
6653 	for (raw_color = i=0; i < 3; i++) {
6654 	  FORC4 fscanf (ifp, "%f", &rgb_cam[i][c^1]);
6655 	  if (!use_camera_wb) continue;
6656 	  num = 0;
6657 	  FORC4 num += rgb_cam[i][c];
6658 	  FORC4 rgb_cam[i][c] /= num;
6659 	}
6660 	break;
6661       case 34310:			/* Leaf metadata */
6662 	parse_mos (ftell(ifp));
6663       case 34303:
6664 	strcpy (make, "Leaf");
6665 	break;
6666       case 34665:			/* EXIF tag */
6667 	fseek (ifp, get4()+base, SEEK_SET);
6668 	parse_exif (base);
6669 	break;
6670       case 34853:			/* GPSInfo tag */
6671 	fseek (ifp, get4()+base, SEEK_SET);
6672 	parse_gps (base);
6673 	break;
6674       case 34675:			/* InterColorProfile */
6675       case 50831:			/* AsShotICCProfile */
6676 	profile_offset = ftell(ifp);
6677 	profile_length = len;
6678 	break;
6679       case 37122:			/* CompressedBitsPerPixel */
6680 	kodak_cbpp = get4();
6681 	break;
6682       case 37386:			/* FocalLength */
6683 	focal_len = getreal(type);
6684 	break;
6685       case 37393:			/* ImageNumber */
6686 	shot_order = getint(type);
6687 	break;
6688       case 37400:			/* old Kodak KDC tag */
6689 	for (raw_color = i=0; i < 3; i++) {
6690 	  getreal(type);
6691 	  FORC3 rgb_cam[i][c] = getreal(type);
6692 	}
6693 	break;
6694       case 40976:
6695 	strip_offset = get4();
6696 	switch (tiff_ifd[ifd].comp) {
6697 	  case 32770: load_raw = &CLASS samsung_load_raw;   break;
6698 	  case 32772: load_raw = &CLASS samsung2_load_raw;  break;
6699 	  case 32773: load_raw = &CLASS samsung3_load_raw;  break;
6700 	}
6701 	break;
6702       case 46275:			/* Imacon tags */
6703 	strcpy (make, "Imacon");
6704 	data_offset = ftell(ifp);
6705 	ima_len = len;
6706 	break;
6707       case 46279:
6708 	if (!ima_len) break;
6709 	fseek (ifp, 38, SEEK_CUR);
6710       case 46274:
6711 	fseek (ifp, 40, SEEK_CUR);
6712 	raw_width  = get4();
6713 	raw_height = get4();
6714 	left_margin = get4() & 7;
6715 	width = raw_width - left_margin - (get4() & 7);
6716 	top_margin = get4() & 7;
6717 	height = raw_height - top_margin - (get4() & 7);
6718 	if (raw_width == 7262) {
6719 	  height = 5444;
6720 	  width  = 7244;
6721 	  left_margin = 7;
6722 	}
6723 	fseek (ifp, 52, SEEK_CUR);
6724 	FORC3 cam_mul[c] = getreal(11);
6725 	fseek (ifp, 114, SEEK_CUR);
6726 	flip = (get2() >> 7) * 90;
6727 	if (width * height * 6 == ima_len) {
6728 	  if (flip % 180 == 90) SWAP(width,height);
6729 	  raw_width = width;
6730 	  raw_height = height;
6731 	  left_margin = top_margin = filters = flip = 0;
6732 	}
6733 	sprintf (model, "Ixpress %d-Mp", height*width/1000000);
6734 	load_raw = &CLASS imacon_full_load_raw;
6735 	if (filters) {
6736 	  if (left_margin & 1) filters = 0x61616161;
6737 	  load_raw = &CLASS unpacked_load_raw;
6738 	}
6739 	maximum = 0xffff;
6740 	break;
6741       case 50454:			/* Sinar tag */
6742       case 50455:
6743 	if (!(cbuf = (char *) malloc(len))) break;
6744 	fread (cbuf, 1, len, ifp);
6745 	for (cp = cbuf-1; cp && cp < cbuf+len; cp = strchr(cp,'\n'))
6746 	  if (!strncmp (++cp,"Neutral ",8))
6747 	    sscanf (cp+8, "%f %f %f", cam_mul, cam_mul+1, cam_mul+2);
6748 	free (cbuf);
6749 	break;
6750       case 50458:
6751 	if (!make[0]) strcpy (make, "Hasselblad");
6752 	break;
6753       case 50459:			/* Hasselblad tag */
6754 	i = order;
6755 	j = ftell(ifp);
6756 	c = tiff_nifds;
6757 	order = get2();
6758 	fseek (ifp, j+(get2(),get4()), SEEK_SET);
6759 	parse_tiff_ifd (j);
6760 	maximum = 0xffff;
6761 	tiff_nifds = c;
6762 	order = i;
6763 	break;
6764       case 50706:			/* DNGVersion */
6765 	FORC4 dng_version = (dng_version << 8) + fgetc(ifp);
6766 	if (!make[0]) strcpy (make, "DNG");
6767 	is_raw = 1;
6768 	break;
6769       case 50708:			/* UniqueCameraModel */
6770 	if (model[0]) break;
6771 	fgets (make, 64, ifp);
6772         if ((cp = strchr(make,' '))) {
6773 	  strcpy(model,cp+1);
6774 	  *cp = 0;
6775 	}
6776 	break;
6777       case 50710:			/* CFAPlaneColor */
6778 	if (filters == 9) break;
6779 	if (len > 4) len = 4;
6780 	colors = len;
6781 	fread (cfa_pc, 1, colors, ifp);
6782 guess_cfa_pc:
6783 	FORCC tab[cfa_pc[c]] = c;
6784 	cdesc[c] = 0;
6785 	for (i=16; i--; )
6786 	  filters = filters << 2 | tab[cfa_pat[i % plen]];
6787 	filters -= !filters;
6788 	break;
6789       case 50711:			/* CFALayout */
6790 	if (get2() == 2) fuji_width = 1;
6791 	break;
6792       case 291:
6793       case 50712:			/* LinearizationTable */
6794 	linear_table (len);
6795 	break;
6796       case 50713:			/* BlackLevelRepeatDim */
6797 	cblack[4] = get2();
6798 	cblack[5] = get2();
6799 	if (cblack[4] * cblack[5] > sizeof cblack / sizeof *cblack - 6)
6800 	    cblack[4] = cblack[5] = 1;
6801 	break;
6802       case 61450:
6803 	cblack[4] = cblack[5] = MIN(sqrt(len),64);
6804       case 50714:			/* BlackLevel */
6805                 RT_blacklevel_from_constant = ThreeValBool::F;
6806 //-----------------------------------------------------------------------------
6807 // taken from LibRaw.
6808 /*
6809   Copyright 2008-2019 LibRaw LLC (info@libraw.org)
6810 
6811 LibRaw is free software; you can redistribute it and/or modify
6812 it under the terms of the one of two licenses as you choose:
6813 
6814 1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1
6815    (See file LICENSE.LGPL provided in LibRaw distribution archive for details).
6816 
6817 2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
6818    (See file LICENSE.CDDL provided in LibRaw distribution archive for details).
6819 */
6820                 if (tiff_ifd[ifd].samples > 1 && tiff_ifd[ifd].samples == len) // LinearDNG, per-channel black
6821                 {
6822                     for (i = 0; i < 4 && i < len; i++)
6823                     {
6824                         double b = getreal(type);
6825                         cblack[i] = b+0.5;
6826                     }
6827 
6828                     black = 0;
6829                 } else
6830 //-----------------------------------------------------------------------------
6831 		if(cblack[4] * cblack[5] == 0) {
6832 			int dblack[] = { 0,0,0,0 };
6833 			black = getreal(type);
6834 			if ((unsigned)(filters+1) < 1000) break;
6835 			dblack[0] = dblack[1] = dblack[2] = dblack[3] = black;
6836 			if (colors == 3)
6837 			  filters |= ((filters >> 2 & 0x22222222) |
6838 					  (filters << 2 & 0x88888888)) & filters << 1;
6839 			FORC4 cblack[filters >> (c << 1) & 3] = dblack[c];
6840 		} else {
6841 			FORC (cblack[4] * cblack[5])
6842 			  cblack[6+c] = getreal(type);
6843 		}
6844 		black = 0;
6845 		break;
6846       case 50715:			/* BlackLevelDeltaH */
6847       case 50716:			/* BlackLevelDeltaV */
6848 	for (num=i=0; i < (len & 0xffff); i++)
6849 	  num += getreal(type);
6850 	black += num/len + 0.5;
6851         RT_blacklevel_from_constant = ThreeValBool::F;
6852 	break;
6853       case 50717:			/* WhiteLevel */
6854 	maximum = getint(type);
6855         RT_whitelevel_from_constant = ThreeValBool::F;
6856 	break;
6857       case 50718:			/* DefaultScale */
6858 	pixel_aspect  = getreal(type);
6859 	pixel_aspect /= getreal(type);
6860 	break;
6861       case 50721:			/* ColorMatrix1 */
6862       case 50722:			/* ColorMatrix2 */
6863 	FORCC for (j=0; j < 3; j++)
6864 	  cm[tag-50721][c][j] = getreal(type);
6865 	use_cm = 1;
6866 	break;
6867       case 50723:			/* CameraCalibration1 */
6868       case 50724:			/* CameraCalibration2 */
6869 	for (i=0; i < colors; i++)
6870 	  FORCC cc[tag-50723][i][c] = getreal(type);
6871 	break;
6872       case 50727:			/* AnalogBalance */
6873 	FORCC ab[c] = getreal(type);
6874 	break;
6875       case 50728:			/* AsShotNeutral */
6876 	FORCC asn[c] = getreal(type);
6877 	break;
6878       case 50729:			/* AsShotWhiteXY */
6879 	xyz[0] = getreal(type);
6880 	xyz[1] = getreal(type);
6881 	xyz[2] = 1 - xyz[0] - xyz[1];
6882 	FORC3 xyz[c] /= d65_white[c];
6883 	break;
6884       case 50730:                       /* BaselineExposure */
6885         if (dng_version) {
6886             double be = getreal(type);
6887             if (!std::isnan(be)) {
6888                 RT_baseline_exposure = be;
6889             }
6890         }
6891         break;
6892       case 50740:			/* DNGPrivateData */
6893 	if (dng_version) break;
6894 	parse_minolta (j = get4()+base);
6895 	fseek (ifp, j, SEEK_SET);
6896 	parse_tiff_ifd (base);
6897 	break;
6898       case 50752:
6899 	read_shorts (cr2_slice, 3);
6900 	break;
6901       case 50778:
6902       case 50779:
6903          if( get2() == 21 )
6904             cm_D65 = (tag-50778);
6905          break;
6906       case 50829:			/* ActiveArea */
6907 	top_margin = getint(type);
6908 	left_margin = getint(type);
6909 	height = getint(type) - top_margin;
6910 	width = getint(type) - left_margin;
6911 	break;
6912       case 50830:			/* MaskedAreas */
6913         for (i=0; i < len && i < 32; i++)
6914 	  ((int *)mask)[i] = getint(type);
6915 	black = 0;
6916 	break;
6917       case 51008:           /* OpcodeList1 */
6918         {
6919             unsigned oldOrder = order;
6920             order = 0x4d4d; // always big endian per definition in https://www.adobe.com/content/dam/acom/en/products/photoshop/pdfs/dng_spec_1.4.0.0.pdf chapter 7
6921             unsigned ntags = get4(); // read the number of opcodes
6922 
6923             if (ntags < ifp->size / 12) { // rough check for wrong value (happens for example with DNG files from DJI FC6310)
6924                 while (ntags-- && !ifp->eof) {
6925                   unsigned opcode = get4();
6926                   fseek (ifp, 8, SEEK_CUR); // skip 8 bytes as they don't interest us currently
6927                   if (opcode == 4) { // FixBadPixelsConstant
6928                     fseek (ifp, 4, SEEK_CUR); // skip 4 bytes as we know that the opcode 4 takes 4 byte
6929                     if(get4() == 0) { // if raw 0 values should be treated as bad pixels, set zero_is_bad to true (1). That's the only value currently supported by rt
6930                         zero_is_bad = 1;
6931                     }
6932                   } else {
6933                     fseek (ifp, get4(), SEEK_CUR);
6934                   }
6935                 }
6936             }
6937             order = oldOrder;
6938           break;
6939         }
6940       case 51009:			/* OpcodeList2 */
6941 	meta_offset = ftell(ifp);
6942 	break;
6943       case 64772:			/* Kodak P-series */
6944 	if (len < 13) break;
6945 	fseek (ifp, 16, SEEK_CUR);
6946 	data_offset = get4();
6947 	fseek (ifp, 28, SEEK_CUR);
6948 	data_offset += get4();
6949 	load_raw = &CLASS packed_load_raw;
6950 	break;
6951       case 65026:
6952 	if (type == 2) fgets (model2, 64, ifp);
6953     }
6954     fseek (ifp, save, SEEK_SET);
6955   }
6956   if (sony_length && (buf = (unsigned *) malloc(sony_length))) {
6957     fseek (ifp, sony_offset, SEEK_SET);
6958     fread (buf, sony_length, 1, ifp);
6959     sony_decrypt (buf, sony_length/4, 1, sony_key);
6960     sfp = ifp;
6961 /*RT*/ ifp = fopen (buf, sony_length);
6962 // if ((ifp = tmpfile())) {
6963 // fwrite (buf, sony_length, 1, ifp);
6964 // fseek (ifp, 0, SEEK_SET);
6965     parse_tiff_ifd (-sony_offset);
6966 // fclose (ifp);
6967 // }
6968 	if(ifp)
6969 		fclose(ifp);
6970     ifp = sfp;
6971     free (buf);
6972   }
6973 
6974   /* RT -- do not use CameraCalibration matrices for DNGs - see #4129 */
6975   for (j=0; j < 4; j++) {
6976       ab[j] = 1;
6977       for (i=0; i < 4; i++) {
6978           cc[0][j][i] = i == j;
6979           cc[1][j][i] = i == j;
6980       }
6981   }
6982   /* RT end */
6983 
6984   for (i=0; i < colors; i++)
6985     FORCC cc[cm_D65][i][c] *= ab[i];
6986   if (use_cm) {
6987     if(cm_D65 == 1 && std::isnan(cm[1][0][0]))
6988         cm_D65 = 0;
6989     FORCC for (i=0; i < 3; i++)
6990       for (cam_xyz[c][i]=j=0; j < colors; j++)
6991 	cam_xyz[c][i] += cc[cm_D65][c][j] * cm[cm_D65][j][i] * xyz[i];
6992     cam_xyz_coeff (cmatrix, cam_xyz);
6993   }
6994   if (asn[0]) {
6995     cam_mul[3] = 0;
6996     FORCC cam_mul[c] = 1 / asn[c];
6997   }
6998   if (!use_cm)
6999     FORCC pre_mul[c] /= cc[cm_D65][c][c];
7000 
7001   return 0;
7002 }
7003 
parse_tiff(int base)7004 int CLASS parse_tiff (int base)
7005 {
7006   int doff;
7007   /*RT*/  if (exif_base == -1) exif_base = base;
7008 
7009   fseek (ifp, base, SEEK_SET);
7010   order = get2();
7011   if (order != 0x4949 && order != 0x4d4d) return 0;
7012   get2();
7013   while ((doff = get4())) {
7014     fseek (ifp, doff+base, SEEK_SET);
7015     if (parse_tiff_ifd (base)) break;
7016   }
7017   return 1;
7018 }
7019 
apply_tiff()7020 void CLASS apply_tiff()
7021 {
7022   int max_samp=0, ties=0, /*os, ns,*/ raw=-1, thm=-1, i;
7023   uint64_t os, ns; // RT
7024   struct jhead jh;
7025 
7026   thumb_misc = 16;
7027   if (thumb_offset) {
7028     fseek (ifp, thumb_offset, SEEK_SET);
7029     if (ljpeg_start (&jh, 1)) {
7030       thumb_misc   = jh.bits;
7031       thumb_width  = jh.wide;
7032       thumb_height = jh.high;
7033     }
7034   }
7035   for (i=tiff_nifds; i--; ) {
7036     if (tiff_ifd[i].shutter)
7037       shutter = tiff_ifd[i].shutter;
7038     tiff_ifd[i].shutter = shutter;
7039   }
7040 
7041   for (i=0; i < tiff_nifds; i++) {
7042     if (max_samp < tiff_ifd[i].samples)
7043 	max_samp = tiff_ifd[i].samples;
7044     if (max_samp > 3) max_samp = 3;
7045     os = raw_width*raw_height;
7046     ns = tiff_ifd[i].width*tiff_ifd[i].height;
7047     if (tiff_bps) {
7048       os *= tiff_bps;
7049       ns *= tiff_ifd[i].bps;
7050     }
7051     if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) &&
7052 	(tiff_ifd[i].width | tiff_ifd[i].height) < 0x10000 &&
7053     (unsigned)tiff_ifd[i].bps < 33 && (unsigned)tiff_ifd[i].samples < 13 && // RT
7054 	 ns && ((ns > os && (ties = 1)) ||
7055 		(ns == os && shot_select == ties++))) {
7056       raw_width     = tiff_ifd[i].width;
7057       raw_height    = tiff_ifd[i].height;
7058       tiff_bps      = tiff_ifd[i].bps;
7059       tiff_compress = tiff_ifd[i].comp;
7060       data_offset   = tiff_ifd[i].offset;
7061       tiff_flip     = tiff_ifd[i].flip;
7062       tiff_samples  = tiff_ifd[i].samples;
7063       tile_width    = tiff_ifd[i].tile_width;
7064       tile_length   = tiff_ifd[i].tile_length;
7065       shutter       = tiff_ifd[i].shutter;
7066       raw_size      = tiff_ifd[i].bytes;
7067       raw = i;
7068     }
7069   }
7070   if (is_raw == 1 && ties) is_raw = ties;
7071   if (!tile_width ) tile_width  = INT_MAX;
7072   if (!tile_length) tile_length = INT_MAX;
7073   for (i=tiff_nifds; i--; )
7074     if (tiff_ifd[i].flip) tiff_flip = tiff_ifd[i].flip;
7075   if (raw >= 0 && !load_raw)
7076     switch (tiff_compress) {
7077       case 32767:
7078 	if (tiff_ifd[raw].bytes == raw_width*raw_height) {
7079 	  tiff_bps = 12;
7080 	  maximum = 4095;
7081 	  load_raw = &CLASS sony_arw2_load_raw;			break;
7082 	}
7083 	if (tiff_ifd[raw].bytes*8 != raw_width*raw_height*tiff_bps) {
7084 	  raw_height += 8;
7085 	  load_raw = &CLASS sony_arw_load_raw;			break;
7086 	}
7087 	load_flags = 79;
7088       case 32769:
7089 	load_flags++;
7090       case 32770:
7091       case 32773: goto slr;
7092       case 0:  case 1:
7093 	if (!strncmp(make,"OLYMPUS",7) &&
7094 		tiff_ifd[raw].bytes*2 == raw_width*raw_height*3)
7095 	  load_flags = 24;
7096 	if (!strcmp(make,"SONY") && tiff_bps < 14 &&
7097 		tiff_ifd[raw].bytes == raw_width*raw_height*2)
7098 	    tiff_bps = 14;	if (tiff_ifd[raw].bytes*5 == raw_width*raw_height*8) {
7099 	  load_flags = 81;
7100 	  tiff_bps = 12;
7101 	} slr:
7102 	switch (tiff_bps) {
7103 	  case  8: load_raw = &CLASS eight_bit_load_raw;	break;
7104 	  case 12: if (tiff_ifd[raw].phint == 2)
7105 		     load_flags = 6;
7106              if(!strncmp(make,"SONY",4) && tiff_ifd[raw].comp == 1) { // hack for some sony cameras which report as 12 bit uncompressed but in fact are 14 bit uncompressed
7107                  tiff_bps = 14;
7108              } else {
7109                load_raw = &CLASS packed_load_raw;
7110                break;
7111              }
7112 	  case 14: load_raw = &CLASS packed_load_raw;
7113 		   if (tiff_ifd[raw].bytes*4 == raw_width*raw_height*7) break;
7114 		   load_flags = 0;
7115 	  case 16: load_raw = &CLASS unpacked_load_raw;
7116 		   if (!strncmp(make,"OLYMPUS",7) &&
7117 			tiff_ifd[raw].bytes*7 > raw_width*raw_height)
7118 		     load_raw = &CLASS olympus_load_raw;
7119                    // ------- RT -------
7120                    if (!strncmp(make,"SONY",4) &&
7121                        (!strncmp(model,"ILCE-7RM3",9) || !strncmp(model,"ILCE-7RM4",9)) &&
7122                        tiff_samples == 4 &&
7123                        tiff_ifd[raw].bytes == raw_width*raw_height*tiff_samples*2) {
7124                        load_raw = &CLASS sony_arq_load_raw;
7125                        colors = 3;
7126                        is_raw = 4;
7127                        filters = 0x94949494;
7128                    }
7129                    // ------------------
7130 	}
7131 //	if (filters == 9 && tiff_ifd[raw].bytes*8 < raw_width*raw_height*tiff_bps)
7132 //	  load_raw = &CLASS fuji_xtrans_load_raw;
7133 
7134 	break;
7135       case 6:  case 7:  case 99:
7136 	load_raw = &CLASS lossless_jpeg_load_raw;		break;
7137       case 262:
7138 	load_raw = &CLASS kodak_262_load_raw;			break;
7139       case 34713:
7140 	if ((raw_width+9)/10*16*raw_height == tiff_ifd[raw].bytes) {
7141 	  load_raw = &CLASS packed_load_raw;
7142 	  load_flags = 1;
7143 	} else if (raw_width*raw_height*3 == tiff_ifd[raw].bytes*2) {
7144 	  load_raw = &CLASS packed_load_raw;
7145 	  if (model[0] == 'N') load_flags = 80;
7146 	} else if (raw_width*raw_height*3 == tiff_ifd[raw].bytes) {
7147 	  load_raw = &CLASS nikon_yuv_load_raw;
7148 	  gamma_curve (1/2.4, 12.92310, 1, 4095);
7149 	  memset (cblack, 0, sizeof cblack);
7150 	  filters = 0;
7151 	} else if (raw_width*raw_height*2 == tiff_ifd[raw].bytes) {
7152 	  load_raw = &CLASS unpacked_load_raw;
7153 	  load_flags = 4;
7154 	  order = 0x4d4d;
7155 	} else if ((raw_width * raw_height * 2 * tiff_bps) / 16 == tiff_ifd[raw].bytes) {
7156 	    // 12 bit uncompressed from Nikon Z7
7157 	    load_raw = &CLASS packed_load_raw;
7158 	} else if ((raw_width * 2 * tiff_bps / 16 + 8) * raw_height == tiff_ifd[raw].bytes) {
7159 	    // 14 bit uncompressed from Nikon Z7, still wrong
7160 	    // each line has 8 padding byte.
7161 	    //row_padding = 8;
7162 	    //load_raw = &CLASS packed_load_raw;
7163             load_raw = &CLASS nikon_14bit_load_raw;
7164 	} else if ((raw_width * 2 * tiff_bps / 16 + 12) * raw_height == tiff_ifd[raw].bytes) {
7165 	    // 14 bit uncompressed from Nikon Z6, still wrong
7166 	    // each line has 12 padding byte.
7167 	    // row_padding = 12;
7168 	    // load_raw = &CLASS packed_load_raw;
7169             load_raw = &CLASS nikon_14bit_load_raw;
7170 	} else
7171 	  load_raw = &CLASS nikon_load_raw;			break;
7172       case 65535:
7173 	load_raw = &CLASS pentax_load_raw;			break;
7174       case 65000:
7175 	switch (tiff_ifd[raw].phint) {
7176 	  case 2: load_raw = &CLASS kodak_rgb_load_raw;   filters = 0;  break;
7177 	  case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0;  break;
7178 	  case 32803: load_raw = &CLASS kodak_65000_load_raw;
7179 	}
7180       case 32867: case 34892: break;
7181       case 8: break;
7182       default: is_raw = 0;
7183     }
7184   if (!dng_version)
7185     if ( (tiff_samples == 3 && tiff_ifd[raw].bytes && tiff_bps != 14 &&
7186 	  (tiff_compress & -16) != 32768)
7187       || (tiff_bps == 8 && strncmp(make,"Phase",5) &&
7188 	  !strcasestr(make,"Kodak") && !strstr(model2,"DEBUG RAW")))
7189       is_raw = 0;
7190   for (i=0; i < tiff_nifds; i++)
7191     if (i != raw && tiff_ifd[i].samples == max_samp &&
7192 	tiff_ifd[i].width * tiff_ifd[i].height / (SQR(tiff_ifd[i].bps)+1) >
7193 	      thumb_width *       thumb_height / (SQR(thumb_misc)+1)
7194 	&& tiff_ifd[i].comp != 34892) {
7195       thumb_width  = tiff_ifd[i].width;
7196       thumb_height = tiff_ifd[i].height;
7197       thumb_offset = tiff_ifd[i].offset;
7198       thumb_length = tiff_ifd[i].bytes;
7199       thumb_misc   = tiff_ifd[i].bps;
7200       thm = i;
7201     }
7202   if (thm >= 0) {
7203     thumb_misc |= tiff_ifd[thm].samples << 5;
7204     switch (tiff_ifd[thm].comp) {
7205       case 0:
7206 	write_thumb = &CLASS layer_thumb;
7207 	break;
7208       case 1:
7209 	if (tiff_ifd[thm].bps <= 8)
7210 	  write_thumb = &CLASS ppm_thumb;
7211 	else if (!strcmp(make,"Imacon"))
7212 	  write_thumb = &CLASS ppm16_thumb;
7213 	else
7214 	  thumb_load_raw = &CLASS kodak_thumb_load_raw;
7215 	break;
7216       case 65000:
7217 	thumb_load_raw = tiff_ifd[thm].phint == 6 ?
7218 		&CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw;
7219     }
7220   }
7221 }
7222 
parse_minolta(int base)7223 void CLASS parse_minolta (int base)
7224 {
7225   int save, tag, len, offset, high=0, wide=0, i, c;
7226   short sorder=order;
7227 
7228   fseek (ifp, base, SEEK_SET);
7229   if (fgetc(ifp) || fgetc(ifp)-'M' || fgetc(ifp)-'R') return;
7230   order = fgetc(ifp) * 0x101;
7231   offset = base + get4() + 8;
7232   while ((save=ftell(ifp)) < offset) {
7233     for (tag=i=0; i < 4; i++)
7234       tag = tag << 8 | fgetc(ifp);
7235     len = get4();
7236     switch (tag) {
7237       case 0x505244:				/* PRD */
7238 	fseek (ifp, 8, SEEK_CUR);
7239 	high = get2();
7240 	wide = get2();
7241 	break;
7242       case 0x574247:				/* WBG */
7243 	get4();
7244 	i = strcmp(model,"DiMAGE A200") ? 0:3;
7245 	FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2();
7246 	break;
7247       case 0x545457:				/* TTW */
7248 	parse_tiff (ftell(ifp));
7249 	data_offset = offset;
7250     }
7251     fseek (ifp, save+len+8, SEEK_SET);
7252   }
7253   raw_height = high;
7254   raw_width  = wide;
7255   order = sorder;
7256 }
7257 
7258 /*
7259    Many cameras have a "debug mode" that writes JPEG and raw
7260    at the same time.  The raw file has no header, so try to
7261    to open the matching JPEG file and read its metadata.
7262  */
parse_external_jpeg()7263 void CLASS parse_external_jpeg()
7264 {
7265   const char *file, *ext;
7266   char *jname, *jfile, *jext;
7267 /*RT*/  IMFILE *save=ifp;
7268 
7269   ext  = strrchr (ifname, '.');
7270   file = strrchr (ifname, '/');
7271   if (!file) file = strrchr (ifname, '\\');
7272   if (!file) file = ifname-1;
7273   file++;
7274   if (!ext || strlen(ext) != 4 || ext-file != 8) return;
7275   jname = (char *) malloc (strlen(ifname) + 1);
7276   merror (jname, "parse_external_jpeg()");
7277   strcpy (jname, ifname);
7278   jfile = file - ifname + jname;
7279   jext  = ext  - ifname + jname;
7280   if (strcasecmp (ext, ".jpg")) {
7281     strcpy (jext, isupper(ext[1]) ? ".JPG":".jpg");
7282     if (isdigit(*file)) {
7283       memcpy (jfile, file+4, 4);
7284       memcpy (jfile+4, file, 4);
7285     }
7286   } else
7287     while (isdigit(*--jext)) {
7288       if (*jext != '9') {
7289       (*jext)++;
7290 	break;
7291       }
7292       *jext = '0';
7293     }
7294   if (strcmp (jname, ifname)) {
7295 /*RT*/    if ((ifp = fopen (jname))) {
7296 //    if ((ifp = fopen (jname, "rb"))) {
7297       if (verbose)
7298 	fprintf (stderr,_("Reading metadata from %s ...\n"), jname);
7299       parse_tiff (12);
7300       thumb_offset = 0;
7301       is_raw = 1;
7302       fclose (ifp);
7303     }
7304   }
7305   if (!timestamp)
7306     fprintf (stderr,_("Failed to read metadata from %s\n"), jname);
7307   free (jname);
7308   ifp = save;
7309 }
7310 
7311 /*
7312    CIFF block 0x1030 contains an 8x8 white sample.
7313    Load this into white[][] for use in scale_colors().
7314  */
ciff_block_1030()7315 void CLASS ciff_block_1030()
7316 {
7317   static const ushort key[] = { 0x410, 0x45f3 };
7318   int i, bpp, row, col, vbits=0;
7319   unsigned long bitbuf=0;
7320 
7321   if ((get2(),get4()) != 0x80008 || !get4()) return;
7322   bpp = get2();
7323   if (bpp != 10 && bpp != 12) return;
7324   for (i=row=0; row < 8; row++)
7325     for (col=0; col < 8; col++) {
7326       if (vbits < bpp) {
7327 	bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]);
7328 	vbits += 16;
7329       }
7330       white[row][col] = bitbuf >> (vbits -= bpp) & ~(-1 << bpp);
7331     }
7332 }
7333 
7334 /*
7335    Parse a CIFF file, better known as Canon CRW format.
7336  */
parse_ciff(int offset,int length,int depth)7337 void CLASS parse_ciff (int offset, int length, int depth)
7338 {
7339   int tboff, nrecs, c, type, len, save, wbi=-1;
7340   ushort key[] = { 0x410, 0x45f3 };
7341 
7342   fseek (ifp, offset+length-4, SEEK_SET);
7343   tboff = get4() + offset;
7344   fseek (ifp, tboff, SEEK_SET);
7345   nrecs = get2();
7346   if ((nrecs | depth) > 127) return;
7347   while (nrecs--) {
7348     type = get2();
7349     len  = get4();
7350     save = ftell(ifp) + 4;
7351     fseek (ifp, offset+get4(), SEEK_SET);
7352     if ((((type >> 8) + 8) | 8) == 0x38)
7353       parse_ciff (ftell(ifp), len, depth+1); /* Parse a sub-table */
7354     if (type == 0x0810)
7355       fread (artist, 64, 1, ifp);
7356     if (type == 0x080a) {
7357       fread (make, 64, 1, ifp);
7358       fseek (ifp, strlen(make) - 63, SEEK_CUR);
7359       fread (model, 64, 1, ifp);
7360     }
7361     if (type == 0x1810) {
7362       width = get4();
7363       height = get4();
7364       pixel_aspect = int_to_float(get4());
7365       flip = get4();
7366     }
7367     if (type == 0x1835)			/* Get the decoder table */
7368       tiff_compress = get4();
7369     if (type == 0x2007) {
7370       thumb_offset = ftell(ifp);
7371       thumb_length = len;
7372     }
7373     if (type == 0x1818) {
7374       shutter = pow (2, -int_to_float((get4(),get4())));
7375       aperture = pow (2, int_to_float(get4())/2);
7376     }
7377     if (type == 0x102a) {
7378       iso_speed = pow (2, (get4(),get2())/32.0 - 4) * 50;
7379       aperture  = pow (2, (get2(),(short)get2())/64.0);
7380       shutter   = pow (2,-((short)get2())/32.0);
7381       wbi = (get2(),get2());
7382       if (wbi > 17) wbi = 0;
7383       fseek (ifp, 32, SEEK_CUR);
7384       if (shutter > 1e6) shutter = get2()/10.0;
7385     }
7386     if (type == 0x102c) {
7387       if (get2() > 512) {		/* Pro90, G1 */
7388 	fseek (ifp, 118, SEEK_CUR);
7389 	FORC4 cam_mul[c ^ 2] = get2();
7390       } else {				/* G2, S30, S40 */
7391 	fseek (ifp, 98, SEEK_CUR);
7392 	FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2();
7393       }
7394     }
7395     if (type == 0x0032) {
7396       if (len == 768) {			/* EOS D30 */
7397 	fseek (ifp, 72, SEEK_CUR);
7398 	FORC4 cam_mul[c ^ (c >> 1)] = 1024.0 / get2();
7399 	if (!wbi) cam_mul[0] = -1;	/* use my auto white balance */
7400       } else if (!cam_mul[0]) {
7401 	if (get2() == key[0])		/* Pro1, G6, S60, S70 */
7402 	  c = (strstr(model,"Pro1") ?
7403 	      "012346000000000000":"01345:000000006008")[wbi]-'0'+ 2;
7404 	else {				/* G3, G5, S45, S50 */
7405 	  c = "023457000000006000"[wbi]-'0';
7406 	  key[0] = key[1] = 0;
7407 	}
7408 	fseek (ifp, 78 + c*8, SEEK_CUR);
7409 	FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1];
7410 	if (!wbi) cam_mul[0] = -1;
7411       }
7412     }
7413     if (type == 0x10a9) {		/* D60, 10D, 300D, and clones */
7414       if (len > 66) wbi = "0134567028"[wbi]-'0';
7415       fseek (ifp, 2 + wbi*8, SEEK_CUR);
7416       FORC4 cam_mul[c ^ (c >> 1)] = get2();
7417     }
7418     if (type == 0x1030 && (0x18040 >> wbi & 1))
7419       ciff_block_1030();		/* all that don't have 0x10a9 */
7420     if (type == 0x1031) {
7421       raw_width = (get2(),get2());
7422       raw_height = get2();
7423     }
7424     if (type == 0x5029) {
7425       focal_len = len >> 16;
7426       if ((len & 0xffff) == 2) focal_len /= 32;
7427     }
7428     if (type == 0x5813) flash_used = int_to_float(len);
7429     if (type == 0x5814) canon_ev   = int_to_float(len);
7430     if (type == 0x5817) shot_order = len;
7431     if (type == 0x5834) unique_id  = len;
7432     if (type == 0x580e) timestamp  = len;
7433     if (type == 0x180e) timestamp  = get4();
7434 #ifdef LOCALTIME
7435     if ((type | 0x4000) == 0x580e)
7436       timestamp = mktime (gmtime (&timestamp));
7437 #endif
7438     fseek (ifp, save, SEEK_SET);
7439   }
7440 }
7441 
parse_rollei()7442 void CLASS parse_rollei()
7443 {
7444   char line[128], *val;
7445   struct tm t;
7446 
7447   fseek (ifp, 0, SEEK_SET);
7448   memset (&t, 0, sizeof t);
7449   do {
7450     fgets (line, 128, ifp);
7451     if ((val = strchr(line,'=')))
7452       *val++ = 0;
7453     else
7454       val = line + strlen(line);
7455     if (!strcmp(line,"DAT"))
7456       sscanf (val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year);
7457     if (!strcmp(line,"TIM"))
7458       sscanf (val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec);
7459     if (!strcmp(line,"HDR"))
7460       thumb_offset = atoi(val);
7461     if (!strcmp(line,"X  "))
7462       raw_width = atoi(val);
7463     if (!strcmp(line,"Y  "))
7464       raw_height = atoi(val);
7465     if (!strcmp(line,"TX "))
7466       thumb_width = atoi(val);
7467     if (!strcmp(line,"TY "))
7468       thumb_height = atoi(val);
7469   } while (strncmp(line,"EOHD",4));
7470   data_offset = thumb_offset + thumb_width * thumb_height * 2;
7471   t.tm_year -= 1900;
7472   t.tm_mon -= 1;
7473   if (mktime(&t) > 0)
7474     timestamp = mktime(&t);
7475   strcpy (make, "Rollei");
7476   strcpy (model,"d530flex");
7477   write_thumb = &CLASS rollei_thumb;
7478 }
7479 
parse_sinar_ia()7480 void CLASS parse_sinar_ia()
7481 {
7482   int entries, off;
7483   char str[8], *cp;
7484 
7485   order = 0x4949;
7486   fseek (ifp, 4, SEEK_SET);
7487   entries = get4();
7488   fseek (ifp, get4(), SEEK_SET);
7489   while (entries--) {
7490     off = get4(); get4();
7491     fread (str, 8, 1, ifp);
7492     if (!strcmp(str,"META"))   meta_offset = off;
7493     if (!strcmp(str,"THUMB")) thumb_offset = off;
7494     if (!strcmp(str,"RAW0"))   data_offset = off;
7495   }
7496   fseek (ifp, meta_offset+20, SEEK_SET);
7497   fread (make, 64, 1, ifp);
7498   make[63] = 0;
7499   if ((cp = strchr(make,' '))) {
7500     strcpy (model, cp+1);
7501     *cp = 0;
7502   }
7503   raw_width  = get2();
7504   raw_height = get2();
7505   load_raw = &CLASS unpacked_load_raw;
7506   thumb_width = (get4(),get2());
7507   thumb_height = get2();
7508   write_thumb = &CLASS ppm_thumb;
7509   maximum = 0x3fff;
7510 }
7511 
parse_phase_one(int base)7512 void CLASS parse_phase_one (int base)
7513 {
7514   unsigned entries, tag, len, data, save, i, c;
7515   float romm_cam[3][3];
7516   char *cp;
7517 
7518   memset (&ph1, 0, sizeof ph1);
7519   fseek (ifp, base, SEEK_SET);
7520   order = get4() & 0xffff;
7521   if (get4() >> 8 != 0x526177) return;		/* "Raw" */
7522   fseek (ifp, get4()+base, SEEK_SET);
7523   entries = get4();
7524   get4();
7525   while (entries--) {
7526     tag  = get4();
7527     get4();
7528     len  = get4();
7529     data = get4();
7530     save = ftell(ifp);
7531     fseek (ifp, base+data, SEEK_SET);
7532     switch (tag) {
7533       case 0x100:  flip = "0653"[data & 3]-'0';  break;
7534       case 0x106:
7535 	for (i=0; i < 9; i++)
7536 	  ((float *)romm_cam)[i] = getreal(11);
7537 	romm_coeff (romm_cam);
7538 	break;
7539       case 0x107:
7540 	FORC3 cam_mul[c] = getreal(11);
7541 	break;
7542       case 0x108:  raw_width     = data;	break;
7543       case 0x109:  raw_height    = data;	break;
7544       case 0x10a:  left_margin   = data;	break;
7545       case 0x10b:  top_margin    = data;	break;
7546       case 0x10c:  width         = data;	break;
7547       case 0x10d:  height        = data;	break;
7548       case 0x10e:  ph1.format    = data;	break;
7549       case 0x10f:  data_offset   = data+base;	break;
7550       case 0x110:  meta_offset   = data+base;
7551 		   meta_length   = len;			break;
7552       case 0x112:  ph1.key_off   = save - 4;		break;
7553       case 0x210:  ph1.tag_210   = int_to_float(data);	break;
7554       case 0x21a:  ph1.tag_21a   = data;		break;
7555       case 0x21c:  strip_offset  = data+base;		break;
7556       case 0x21d:  ph1.black     = data;		break;
7557       case 0x222:  ph1.split_col = data;		break;
7558       case 0x223:  ph1.black_col = data+base;		break;
7559       case 0x224:  ph1.split_row = data;		break;
7560       case 0x225:  ph1.black_row = data+base;		break;
7561       case 0x301:
7562 	model[63] = 0;
7563 	fread (model, 1, 63, ifp);
7564 	if ((cp = strstr(model," camera"))) *cp = 0;
7565     }
7566     fseek (ifp, save, SEEK_SET);
7567   }
7568   load_raw = ph1.format < 3 ?
7569 	&CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c;
7570   maximum = 0xffff;
7571   tiff_bps = 16;
7572   strcpy (make, "Phase One");
7573   if (model[0]) return;
7574   switch (raw_height) {
7575     case 2060: strcpy (model,"LightPhase");	break;
7576     case 2682: strcpy (model,"H 10");		break;
7577     case 4128: strcpy (model,"H 20");		break;
7578     case 5488: strcpy (model,"H 25");		break;
7579   }
7580 }
7581 
parse_fuji(int offset)7582 void CLASS parse_fuji (int offset)
7583 {
7584   unsigned entries, tag, len, save, c;
7585 
7586   fseek (ifp, offset, SEEK_SET);
7587   entries = get4();
7588   if (entries > 255) return;
7589   while (entries--) {
7590     tag = get2();
7591     len = get2();
7592     save = ftell(ifp);
7593     if (tag == 0x100) {
7594       raw_height = get2();
7595       raw_width  = get2();
7596     } else if (tag == 0x121) {
7597       height = get2();
7598       if ((width = get2()) == 4284) width += 3;
7599     } else if (tag == 0x130) {
7600       fuji_layout = fgetc(ifp) >> 7;
7601       fuji_width = !(fgetc(ifp) & 8);
7602     } else if (tag == 0x131) {
7603       filters = 9;
7604       FORC(36) xtrans_abs[0][35-c] = fgetc(ifp) & 3;
7605     } else if (tag == 0x2ff0) {
7606       FORC4 cam_mul[c ^ 1] = get2();
7607     } else if (tag == 0xc000 && len > 20000) {
7608       c = order;
7609       order = 0x4949;
7610       while ((tag = get4()) > raw_width);
7611       width = tag;
7612       height = get4();
7613       order = c;
7614     }
7615     fseek (ifp, save+len, SEEK_SET);
7616   }
7617   height <<= fuji_layout;
7618   width  >>= fuji_layout;
7619 }
7620 
parse_jpeg(int offset)7621 int CLASS parse_jpeg (int offset)
7622 {
7623   int len, save, hlen, mark;
7624 
7625   fseek (ifp, offset, SEEK_SET);
7626   if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0;
7627 
7628   while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) {
7629     order = 0x4d4d;
7630     len   = get2() - 2;
7631     save  = ftell(ifp);
7632     if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9) {
7633       fgetc(ifp);
7634       raw_height = get2();
7635       raw_width  = get2();
7636     }
7637     order = get2();
7638     hlen  = get4();
7639     if (get4() == 0x48454150)		/* "HEAP" */
7640 /*RT*/    {
7641 /*RT*/      ciff_base = save+hlen;
7642 /*RT*/      ciff_len = len-hlen;
7643       parse_ciff (save+hlen, len-hlen, 0);
7644 /*RT*/    }
7645     if (parse_tiff (save+6)) apply_tiff();
7646     fseek (ifp, save+len, SEEK_SET);
7647   }
7648   return 1;
7649 }
7650 
parse_riff()7651 void CLASS parse_riff()
7652 {
7653   unsigned i, size, end;
7654   char tag[4], date[64], month[64];
7655   static const char mon[12][4] =
7656   { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" };
7657   struct tm t;
7658 
7659   order = 0x4949;
7660   fread (tag, 4, 1, ifp);
7661   size = get4();
7662   end = ftell(ifp) + size;
7663   if (!memcmp(tag,"RIFF",4) || !memcmp(tag,"LIST",4)) {
7664     get4();
7665     while (ftell(ifp)+7 < end && !feof(ifp))
7666       parse_riff();
7667   } else if (!memcmp(tag,"nctg",4)) {
7668     while (ftell(ifp)+7 < end) {
7669       i = get2();
7670       size = get2();
7671       if ((i+1) >> 1 == 10 && size == 20)
7672 	get_timestamp(0);
7673       else fseek (ifp, size, SEEK_CUR);
7674     }
7675   } else if (!memcmp(tag,"IDIT",4) && size < 64) {
7676     fread (date, 64, 1, ifp);
7677     date[size] = 0;
7678     memset (&t, 0, sizeof t);
7679     if (sscanf (date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday,
7680 	&t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) {
7681       for (i=0; i < 12 && strcasecmp(mon[i],month); i++);
7682       t.tm_mon = i;
7683       t.tm_year -= 1900;
7684       if (mktime(&t) > 0)
7685 	timestamp = mktime(&t);
7686     }
7687   } else
7688     fseek (ifp, size, SEEK_CUR);
7689 }
7690 
parse_qt(int end)7691 void CLASS parse_qt (int end)
7692 {
7693   unsigned save, size;
7694   char tag[4];
7695 
7696   order = 0x4d4d;
7697   while (ftell(ifp)+7 < end) {
7698     save = ftell(ifp);
7699     if ((size = get4()) < 8) return;
7700     fread (tag, 4, 1, ifp);
7701     if (!memcmp(tag,"moov",4) ||
7702 	!memcmp(tag,"udta",4) ||
7703 	!memcmp(tag,"CNTH",4))
7704       parse_qt (save+size);
7705     if (!memcmp(tag,"CNDA",4))
7706       parse_jpeg (ftell(ifp));
7707     fseek (ifp, save+size, SEEK_SET);
7708   }
7709 }
7710 
parse_smal(int offset,int fsize)7711 void CLASS parse_smal (int offset, int fsize)
7712 {
7713   int ver;
7714 
7715   fseek (ifp, offset+2, SEEK_SET);
7716   order = 0x4949;
7717   ver = fgetc(ifp);
7718   if (ver == 6)
7719     fseek (ifp, 5, SEEK_CUR);
7720   if (get4() != fsize) return;
7721   if (ver > 6) data_offset = get4();
7722   raw_height = height = get2();
7723   raw_width  = width  = get2();
7724   strcpy (make, "SMaL");
7725   sprintf (model, "v%d %dx%d", ver, width, height);
7726   if (ver == 6) load_raw = &CLASS smal_v6_load_raw;
7727   if (ver == 9) load_raw = &CLASS smal_v9_load_raw;
7728 }
7729 
parse_cine()7730 void CLASS parse_cine()
7731 {
7732   unsigned off_head, off_setup, off_image, i;
7733 
7734   order = 0x4949;
7735   fseek (ifp, 4, SEEK_SET);
7736   is_raw = get2() == 2;
7737   fseek (ifp, 14, SEEK_CUR);
7738   is_raw *= get4();
7739   off_head = get4();
7740   off_setup = get4();
7741   off_image = get4();
7742   timestamp = get4();
7743   if ((i = get4())) timestamp = i;
7744   fseek (ifp, off_head+4, SEEK_SET);
7745   raw_width = get4();
7746   raw_height = get4();
7747   switch (get2(),get2()) {
7748     case  8:  load_raw = &CLASS eight_bit_load_raw;  break;
7749     case 16:  load_raw = &CLASS  unpacked_load_raw;
7750   }
7751   fseek (ifp, off_setup+792, SEEK_SET);
7752   strcpy (make, "CINE");
7753   sprintf (model, "%d", get4());
7754   fseek (ifp, 12, SEEK_CUR);
7755   switch ((i=get4()) & 0xffffff) {
7756     case  3:  filters = 0x94949494;  break;
7757     case  4:  filters = 0x49494949;  break;
7758     default:  is_raw = 0;
7759   }
7760   fseek (ifp, 72, SEEK_CUR);
7761   switch ((get4()+3600) % 360) {
7762     case 270:  flip = 4;  break;
7763     case 180:  flip = 1;  break;
7764     case  90:  flip = 7;  break;
7765     case   0:  flip = 2;
7766   }
7767   cam_mul[0] = getreal(11);
7768   cam_mul[2] = getreal(11);
7769   maximum = ~(-1 << get4());
7770   fseek (ifp, 668, SEEK_CUR);
7771   shutter = get4()/1000000000.0;
7772   fseek (ifp, off_image, SEEK_SET);
7773   if (shot_select < is_raw)
7774     fseek (ifp, shot_select*8, SEEK_CUR);
7775   data_offset  = (INT64) get4() + 8;
7776   data_offset += (INT64) get4() << 32;
7777 }
7778 
parse_redcine()7779 void CLASS parse_redcine()
7780 {
7781   unsigned i, len, rdvo;
7782 
7783   order = 0x4d4d;
7784   is_raw = 0;
7785   fseek (ifp, 52, SEEK_SET);
7786   width  = get4();
7787   height = get4();
7788   fseek (ifp, 0, SEEK_END);
7789   fseek (ifp, -(i = ftello(ifp) & 511), SEEK_CUR);
7790   if (get4() != i || get4() != 0x52454f42) {
7791     fprintf (stderr,_("%s: Tail is missing, parsing from head...\n"), ifname);
7792     fseek (ifp, 0, SEEK_SET);
7793     while ((len = get4()) != EOF) {
7794       if (get4() == 0x52454456)
7795 	if (is_raw++ == shot_select)
7796 	  data_offset = ftello(ifp) - 8;
7797       fseek (ifp, len-8, SEEK_CUR);
7798     }
7799   } else {
7800     rdvo = get4();
7801     fseek (ifp, 12, SEEK_CUR);
7802     is_raw = get4();
7803     fseeko (ifp, rdvo+8 + shot_select*4, SEEK_SET);
7804     data_offset = get4();
7805   }
7806 }
7807 
foveon_gets(int offset,char * str,int len)7808 char * CLASS foveon_gets (int offset, char *str, int len)
7809 {
7810   int i;
7811   fseek (ifp, offset, SEEK_SET);
7812   for (i=0; i < len-1; i++)
7813     if ((str[i] = get2()) == 0) break;
7814   str[i] = 0;
7815   return str;
7816 }
7817 
parse_foveon()7818 void CLASS parse_foveon()
7819 {
7820   int entries, img=0, off, len, tag, save, i, wide, high, pent, poff[256][2];
7821   char name[64], value[64];
7822 
7823   order = 0x4949;			/* Little-endian */
7824   fseek (ifp, 36, SEEK_SET);
7825   flip = get4();
7826   fseek (ifp, -4, SEEK_END);
7827   fseek (ifp, get4(), SEEK_SET);
7828   if (get4() != 0x64434553) return;	/* SECd */
7829   entries = (get4(),get4());
7830   while (entries--) {
7831     off = get4();
7832     len = get4();
7833     tag = get4();
7834     save = ftell(ifp);
7835     fseek (ifp, off, SEEK_SET);
7836     if (get4() != (0x20434553 | (tag << 24))) return;
7837     switch (tag) {
7838       case 0x47414d49:			/* IMAG */
7839       case 0x32414d49:			/* IMA2 */
7840 	fseek (ifp, 8, SEEK_CUR);
7841 	pent = get4();
7842 	wide = get4();
7843 	high = get4();
7844 	if (wide > raw_width && high > raw_height) {
7845 	  switch (pent) {
7846 	    case  5:  load_flags = 1;
7847 	    case  6:  load_raw = &CLASS foveon_sd_load_raw;  break;
7848 	    case 30:  load_raw = &CLASS foveon_dp_load_raw;  break;
7849 	    default:  load_raw = 0;
7850 	  }
7851 	  raw_width  = wide;
7852 	  raw_height = high;
7853 	  data_offset = off+28;
7854 	  is_foveon = 1;
7855 	}
7856 	fseek (ifp, off+28, SEEK_SET);
7857 	if (fgetc(ifp) == 0xff && fgetc(ifp) == 0xd8
7858 		&& thumb_length < len-28) {
7859 	  thumb_offset = off+28;
7860 	  thumb_length = len-28;
7861 	  write_thumb = &CLASS jpeg_thumb;
7862 	}
7863 	if (++img == 2 && !thumb_length) {
7864 	  thumb_offset = off+24;
7865 	  thumb_width = wide;
7866 	  thumb_height = high;
7867 	  write_thumb = &CLASS foveon_thumb;
7868 	}
7869 	break;
7870       case 0x464d4143:			/* CAMF */
7871 	meta_offset = off+8;
7872 	meta_length = len-28;
7873 	break;
7874       case 0x504f5250:			/* PROP */
7875 	pent = (get4(),get4());
7876 	fseek (ifp, 12, SEEK_CUR);
7877 	off += pent*8 + 24;
7878 	if ((unsigned) pent > 256) pent=256;
7879 	for (i=0; i < pent*2; i++)
7880 	  ((int *)poff)[i] = off + get4()*2;
7881 	for (i=0; i < pent; i++) {
7882 	  foveon_gets (poff[i][0], name, 64);
7883 	  foveon_gets (poff[i][1], value, 64);
7884 	  if (!strcmp (name, "ISO"))
7885 	    iso_speed = atoi(value);
7886 	  if (!strcmp (name, "CAMMANUF"))
7887 	    strcpy (make, value);
7888 	  if (!strcmp (name, "CAMMODEL"))
7889 	    strcpy (model, value);
7890 	  if (!strcmp (name, "WB_DESC"))
7891 	    strcpy (model2, value);
7892 	  if (!strcmp (name, "TIME"))
7893 	    timestamp = atoi(value);
7894 	  if (!strcmp (name, "EXPTIME"))
7895 	    shutter = atoi(value) / 1000000.0;
7896 	  if (!strcmp (name, "APERTURE"))
7897 	    aperture = atof(value);
7898 	  if (!strcmp (name, "FLENGTH"))
7899 	    focal_len = atof(value);
7900 	}
7901 #ifdef LOCALTIME
7902 	timestamp = mktime (gmtime (&timestamp));
7903 #endif
7904     }
7905     fseek (ifp, save, SEEK_SET);
7906   }
7907 }
7908 
7909 /*
7910    All matrices are from Adobe DNG Converter unless otherwise noted.
7911  */
adobe_coeff(const char * make,const char * model)7912 void CLASS adobe_coeff (const char *make, const char *model)
7913 {
7914   static const struct {
7915     const char *prefix;
7916     unsigned short black, maximum;  // RT: Change to UShort
7917     short trans[12];
7918   } table[] = {
7919     { "AgfaPhoto DC-833m", 0, 0,	/* DJC */
7920 	{ 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } },
7921     { "Apple QuickTake", 0, 0,		/* DJC */
7922 	{ 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } },
7923     { "Canon EOS D2000", 0, 0,
7924 	{ 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } },
7925     { "Canon EOS D6000", 0, 0,
7926 	{ 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } },
7927     { "Canon EOS D30", 0, 0,
7928 	{ 9805,-2689,-1312,-5803,13064,3068,-2438,3075,8775 } },
7929     { "Canon EOS D60", 0, 0xfa0,
7930 	{ 6188,-1341,-890,-7168,14489,2937,-2640,3228,8483 } },
7931     { "Canon EOS 5DS", 0, 0x3c96,
7932 	{ 6250,-711,-808,-5153,12794,2636,-1249,2198,5610 } },
7933     { "Canon EOS 5D Mark IV", 0, 0,
7934 	{ 6446,-366,-864,-4436,12204,2513,-952,2496,6348 } },
7935     { "Canon EOS 5D Mark III", 0, 0x3c80,
7936 	{ 6722,-635,-963,-4287,12460,2028,-908,2162,5668 } },
7937     { "Canon EOS 5D Mark II", 0, 0x3cf0,
7938 	{ 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } },
7939     { "Canon EOS 5D", 0, 0xe6c,
7940 	{ 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } },
7941     { "Canon EOS 6D Mark II", 0, 0,
7942 	{ 6875,-970,-932,-4691,12459,2501,-874,1953,5809 } },
7943     { "Canon EOS 6D", 0, 0x3c82,
7944 	{ 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } },
7945     { "Canon EOS 7D Mark II", 0, 0x3510,
7946 	{ 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } },
7947     { "Canon EOS 7D", 0, 0x3510,
7948 	{ 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } },
7949     { "Canon EOS 10D", 0, 0xfa0,
7950 	{ 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } },
7951     { "Canon EOS 20Da", 0, 0,
7952 	{ 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } },
7953     { "Canon EOS 20D", 0, 0xfff,
7954 	{ 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } },
7955     { "Canon EOS 30D", 0, 0,
7956 	{ 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } },
7957     { "Canon EOS 40D", 0, 0x3f60,
7958 	{ 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } },
7959     { "Canon EOS 50D", 0, 0x3d93,
7960 	{ 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } },
7961     { "Canon EOS 60D", 0, 0x2ff7,
7962 	{ 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } },
7963     { "Canon EOS 70D", 0, 0x3bc7,
7964 	{ 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } },
7965     { "Canon EOS 77D", 0, 0,
7966 	{ 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } },
7967     { "Canon EOS 80D", 0, 0,
7968 	{ 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } },
7969     { "Canon EOS 100D", 0, 0x350f,
7970 	{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
7971     { "Canon EOS 200D", 0, 0,
7972 	{ 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } },
7973     { "Canon EOS 300D", 0, 0xfa0,
7974 	{ 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } },
7975     { "Canon EOS 350D", 0, 0xfff,
7976 	{ 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } },
7977     { "Canon EOS 400D", 0, 0xe8e,
7978 	{ 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } },
7979     { "Canon EOS 450D", 0, 0x390d,
7980 	{ 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } },
7981     { "Canon EOS 500D", 0, 0x3479,
7982 	{ 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } },
7983     { "Canon EOS 550D", 0, 0x3dd7,
7984 	{ 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } },
7985     { "Canon EOS 600D", 0, 0x3510,
7986 	{ 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } },
7987     { "Canon EOS 650D", 0, 0x354d,
7988 	{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
7989     { "Canon EOS 700D", 0, 0x3c00,
7990 	{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
7991     { "Canon EOS 750D", 0, 0x368e,
7992 	{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
7993     { "Canon EOS 760D", 0, 0x350f,
7994 	{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
7995     { "Canon EOS 800D", 0, 0,
7996 	{ 6970,-512,-968,-4425,12161,2553,-739,1982,5601 } },
7997     { "Canon EOS 1000D", 0, 0xe43,
7998 	{ 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } },
7999     { "Canon EOS 1100D", 0, 0x3510,
8000 	{ 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } },
8001     { "Canon EOS 1200D", 0, 0x37c2,
8002 	{ 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } },
8003     { "Canon EOS 1300D", 0, 0x3510,
8004 	{ 6939,-1016,-866,-4428,12473,2177,-1175,2178,6162 } },
8005     { "Canon EOS 1500D", 0, 0,
8006 	{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
8007     { "Canon EOS 3000D", 0, 0,
8008 	{ 6939,-1016,-866,-4428,12473,2177,-1175,2178,6162 } },
8009     { "Canon EOS M6", 0, 0,
8010 	{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
8011     { "Canon EOS M5", 0, 0,	/* also M50 */
8012 	{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
8013     { "Canon EOS M3", 0, 0,
8014 	{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
8015     { "Canon EOS M100", 0, 0,
8016 	{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
8017     { "Canon EOS M10", 0, 0,
8018 	{ 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } },
8019     { "Canon EOS M", 0, 0,
8020 	{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
8021     { "Canon EOS-1Ds Mark III", 0, 0x3bb0,
8022 	{ 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } },
8023     { "Canon EOS-1Ds Mark II", 0, 0xe80,
8024 	{ 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } },
8025     { "Canon EOS-1D Mark IV", 0, 0x3bb0,
8026 	{ 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } },
8027     { "Canon EOS-1D Mark III", 0, 0x3bb0,
8028 	{ 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } },
8029     { "Canon EOS-1D Mark II N", 0, 0xe80,
8030 	{ 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } },
8031     { "Canon EOS-1D Mark II", 0, 0xe80,
8032 	{ 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } },
8033     { "Canon EOS-1DS", 0, 0xe20,
8034 	{ 4374,3631,-1743,-7520,15212,2472,-2892,3632,8161 } },
8035     { "Canon EOS-1D C", 0, 0x3c4e,
8036 	{ 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } },
8037     { "Canon EOS-1D X Mark II", 0, 0,
8038 	{ 7596,-978,-967,-4808,12571,2503,-1398,2567,5752 } },
8039     { "Canon EOS-1D X", 0, 0x3c4e,
8040 	{ 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } },
8041     { "Canon EOS-1D", 0, 0xe20,
8042 	{ 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } },
8043     { "Canon EOS C500", 853, 0,		/* DJC */
8044 	{ 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } },
8045     { "Canon PowerShot A530", 0, 0,
8046 	{ 0 } },	/* don't want the A5 matrix */
8047     { "Canon PowerShot A50", 0, 0,
8048 	{ -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } },
8049     { "Canon PowerShot A5", 0, 0,
8050 	{ -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } },
8051     { "Canon PowerShot G10", 0, 0,
8052 	{ 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } },
8053     { "Canon PowerShot G11", 0, 0,
8054 	{ 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } },
8055     { "Canon PowerShot G12", 0, 0,
8056 	{ 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } },
8057     { "Canon PowerShot G15", 0, 0,
8058 	{ 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } },
8059     { "Canon PowerShot G16", 0, 0,
8060 	{ 8020,-2687,-682,-3704,11879,2052,-965,1921,5556 } },
8061     { "Canon PowerShot G1 X Mark III", 0, 0,
8062 	{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
8063     { "Canon PowerShot G1 X", 0, 0,
8064 	{ 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } },
8065     { "Canon PowerShot G1", 0, 0,
8066 	{ -4778,9467,2172,4743,-1141,4344,-5146,9908,6077,-1566,11051,557 } },
8067     { "Canon PowerShot G2", 0, 0,
8068 	{ 9087,-2693,-1049,-6715,14382,2537,-2291,2819,7790 } },
8069     { "Canon PowerShot G3 X", 0, 0,
8070 	{ 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } },
8071     { "Canon PowerShot G3", 0, 0,
8072 	{ 9212,-2781,-1073,-6573,14189,2605,-2300,2844,7664 } },
8073     { "Canon PowerShot G5 X", 0, 0,
8074 	{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
8075     { "Canon PowerShot G5", 0, 0,
8076 	{ 9757,-2872,-933,-5972,13861,2301,-1622,2328,7212 } },
8077     { "Canon PowerShot G6", 0, 0,
8078 	{ 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } },
8079     { "Canon PowerShot G7 X", 0, 0,
8080 	{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
8081     { "Canon PowerShot G9 X Mark II", 0, 0,
8082 	{ 10056,-4131,-944,-2576,11143,1625,-238,1294,5179 } },
8083     { "Canon PowerShot G9 X", 0, 0,
8084 	{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
8085     { "Canon PowerShot G9", 0, 0,
8086 	{ 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } },
8087     { "Canon PowerShot Pro1", 0, 0,
8088 	{ 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } },
8089     { "Canon PowerShot Pro70", 34, 0,
8090 	{ -4155,9818,1529,3939,-25,4522,-5521,9870,6610,-2238,10873,1342 } },
8091     { "Canon PowerShot Pro90", 0, 0,
8092 	{ -4963,9896,2235,4642,-987,4294,-5162,10011,5859,-1770,11230,577 } },
8093     { "Canon PowerShot S30", 0, 0,
8094 	{ 10566,-3652,-1129,-6552,14662,2006,-2197,2581,7670 } },
8095     { "Canon PowerShot S40", 0, 0,
8096 	{ 8510,-2487,-940,-6869,14231,2900,-2318,2829,9013 } },
8097     { "Canon PowerShot S45", 0, 0,
8098 	{ 8163,-2333,-955,-6682,14174,2751,-2077,2597,8041 } },
8099     { "Canon PowerShot S50", 0, 0,
8100 	{ 8882,-2571,-863,-6348,14234,2288,-1516,2172,6569 } },
8101     { "Canon PowerShot S60", 0, 0,
8102 	{ 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } },
8103     { "Canon PowerShot S70", 0, 0,
8104 	{ 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } },
8105     { "Canon PowerShot S90", 0, 0,
8106 	{ 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } },
8107     { "Canon PowerShot S95", 0, 0,
8108 	{ 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } },
8109     { "Canon PowerShot S100", 0, 0,
8110 	{ 7968,-2565,-636,-2873,10697,2513,180,667,4211 } },
8111     { "Canon PowerShot S110", 0, 0,
8112 	{ 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } },
8113     { "Canon PowerShot S120", 0, 0,
8114 	{ 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } },
8115     { "Canon PowerShot SX1 IS", 0, 0,
8116 	{ 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } },
8117     { "Canon PowerShot SX50 HS", 0, 0,
8118 	{ 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } },
8119     { "Canon PowerShot SX60 HS", 0, 0,
8120 	{ 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } },
8121     { "Canon PowerShot A3300", 0, 0,	/* DJC */
8122 	{ 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } },
8123     { "Canon PowerShot A470", 0, 0,	/* DJC */
8124 	{ 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } },
8125     { "Canon PowerShot A610", 0, 0,	/* DJC */
8126 	{ 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } },
8127     { "Canon PowerShot A620", 0, 0,	/* DJC */
8128 	{ 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } },
8129     { "Canon PowerShot A630", 0, 0,	/* DJC */
8130 	{ 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } },
8131     { "Canon PowerShot A640", 0, 0,	/* DJC */
8132 	{ 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } },
8133     { "Canon PowerShot A650", 0, 0,	/* DJC */
8134 	{ 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } },
8135     { "Canon PowerShot A720", 0, 0,	/* DJC */
8136 	{ 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } },
8137     { "Canon PowerShot S3 IS", 0, 0,	/* DJC */
8138 	{ 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } },
8139     { "Canon PowerShot SX110 IS", 0, 0,	/* DJC */
8140 	{ 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } },
8141     { "Canon PowerShot SX220", 0, 0,	/* DJC */
8142 	{ 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } },
8143     { "Canon IXUS 160", 0, 0,		/* DJC */
8144 	{ 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } },
8145     { "Casio EX-S20", 0, 0,		/* DJC */
8146 	{ 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } },
8147     { "Casio EX-Z750", 0, 0,		/* DJC */
8148 	{ 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } },
8149     { "Casio EX-Z10", 128, 0xfff,	/* DJC */
8150 	{ 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } },
8151     { "CINE 650", 0, 0,
8152 	{ 3390,480,-500,-800,3610,340,-550,2336,1192 } },
8153     { "CINE 660", 0, 0,
8154 	{ 3390,480,-500,-800,3610,340,-550,2336,1192 } },
8155     { "CINE", 0, 0,
8156 	{ 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } },
8157     { "Contax N Digital", 0, 0xf1e,
8158 	{ 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } },
8159     { "DXO ONE", 0, 0,
8160 	{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
8161     { "Epson R-D1", 0, 0,
8162 	{ 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } },
8163     { "Fujifilm E550", 0, 0,
8164 	{ 11044,-3888,-1120,-7248,15168,2208,-1531,2277,8069 } },
8165     { "Fujifilm E900", 0, 0,
8166 	{ 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } },
8167     { "Fujifilm F5", 0, 0,
8168 	{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
8169     { "Fujifilm F6", 0, 0,
8170 	{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
8171     { "Fujifilm F77", 0, 0xfe9,
8172 	{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
8173     { "Fujifilm F7", 0, 0,
8174 	{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
8175     { "Fujifilm F8", 0, 0,
8176 	{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
8177     { "Fujifilm GFX 50S", 0, 0,
8178 	{ 11756,-4754,-874,-3056,11045,2305,-381,1457,6006 } },
8179     { "Fujifilm S100FS", 514, 0,
8180 	{ 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } },
8181     { "Fujifilm S1", 0, 0,
8182 	{ 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } },
8183     { "Fujifilm S20Pro", 0, 0,
8184 	{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
8185     { "Fujifilm S20", 512, 0x3fff,
8186 	{ 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } },
8187     { "Fujifilm S2Pro", 128, 0xf15,
8188 	{ 12492,-4690,-1402,-7033,15423,1647,-1507,2111,7697 } },
8189     { "Fujifilm S3Pro", 0, 0x3dff,
8190 	{ 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } },
8191     { "Fujifilm S5Pro", 0, 0,
8192 	{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
8193     { "Fujifilm S5000", 0, 0,
8194 	{ 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } },
8195     { "Fujifilm S5100", 0, 0,
8196 	{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
8197     { "Fujifilm S5500", 0, 0,
8198 	{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
8199     { "Fujifilm S5200", 0, 0,
8200 	{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
8201     { "Fujifilm S5600", 0, 0,
8202 	{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
8203     { "Fujifilm S6", 0, 0,
8204 	{ 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } },
8205     { "Fujifilm S7000", 0, 0,
8206 	{ 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } },
8207     { "Fujifilm S9000", 0, 0,
8208 	{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
8209     { "Fujifilm S9500", 0, 0,
8210 	{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
8211     { "Fujifilm S9100", 0, 0,
8212 	{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
8213     { "Fujifilm S9600", 0, 0,
8214 	{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
8215     { "Fujifilm SL1000", 0, 0,
8216 	{ 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } },
8217     { "Fujifilm IS-1", 0, 0,
8218 	{ 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } },
8219     { "Fujifilm IS Pro", 0, 0,
8220 	{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
8221     { "Fujifilm HS10 HS11", 0, 0xf68,
8222 	{ 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } },
8223     { "Fujifilm HS2", 0, 0xfef,
8224 	{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
8225     { "Fujifilm HS3", 0, 0,
8226 	{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
8227     { "Fujifilm HS50EXR", 0, 0,
8228 	{ 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } },
8229     { "Fujifilm F900EXR", 0, 0,
8230 	{ 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } },
8231     { "Fujifilm X100F", 0, 0,
8232 	{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
8233     { "Fujifilm X100S", 0, 0,
8234 	{ 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } },
8235     { "Fujifilm X100T", 0, 0,
8236 	{ 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } },
8237     { "Fujifilm X100", 0, 0,
8238 	{ 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } },
8239     { "Fujifilm X10", 0, 0,
8240 	{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
8241     { "Fujifilm X20", 0, 0,
8242 	{ 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } },
8243     { "Fujifilm X30", 0, 0,
8244 	{ 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } },
8245     { "Fujifilm X70", 0, 0,
8246 	{ 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } },
8247     { "Fujifilm X-Pro1", 0, 0,
8248 	{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
8249     { "Fujifilm X-Pro2", 0, 0,
8250 	{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
8251     { "Fujifilm X-A10", 0, 0,
8252 	{ 11540,-4999,-991,-2949,10963,2278,-382,1049,5605 } },
8253     { "Fujifilm X-A20", 0, 0,
8254 	{ 11540,-4999,-991,-2949,10963,2278,-382,1049,5605 } },
8255     { "Fujifilm X-A1", 0, 0,
8256 	{ 11086,-4555,-839,-3512,11310,2517,-815,1341,5940 } },
8257     { "Fujifilm X-A2", 0, 0,
8258 	{ 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } },
8259     { "Fujifilm X-A3", 0, 0,
8260 	{ 12407,-5222,-1086,-2971,11116,2120,-294,1029,5284 } },
8261     { "Fujifilm X-A5", 0, 0,
8262 	{ 11673,-4760,-1041,-3988,12058,2166,-771,1417,5569 } },
8263     { "Fujifilm X-E1", 0, 0,
8264 	{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
8265     { "Fujifilm X-E2S", 0, 0,
8266 	{ 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } },
8267     { "Fujifilm X-E2", 0, 0,
8268 	{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
8269     { "Fujifilm X-E3", 0, 0,
8270 	{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
8271     { "Fujifilm X-H1", 0, 0,
8272 	{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
8273     { "Fujifilm X-M1", 0, 0,
8274 	{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
8275     { "Fujifilm X-S1", 0, 0,
8276 	{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
8277     { "Fujifilm X-T1", 0, 0,	/* also X-T10 */
8278 	{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
8279     { "Fujifilm X-T2", 0, 0,	/* also X-T20 */
8280 	{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
8281     { "Fujifilm XF1", 0, 0,
8282 	{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
8283     { "Fujifilm XQ", 0, 0,	/* XQ1 and XQ2 */
8284 	{ 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } },
8285     { "GoPro HERO5 Black", 0, 0,
8286 	{ 10344,-4210,-620,-2315,10625,1948,93,1058,5541 } },
8287     { "Imacon Ixpress", 0, 0,		/* DJC */
8288 	{ 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } },
8289     { "Kodak NC2000", 0, 0,
8290 	{ 13891,-6055,-803,-465,9919,642,2121,82,1291 } },
8291     { "Kodak DCS315C", 8, 0,
8292 	{ 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } },
8293     { "Kodak DCS330C", 8, 0,
8294 	{ 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } },
8295     { "Kodak DCS420", 0, 0,
8296 	{ 10868,-1852,-644,-1537,11083,484,2343,628,2216 } },
8297     { "Kodak DCS460", 0, 0,
8298 	{ 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
8299     { "Kodak EOSDCS1", 0, 0,
8300 	{ 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
8301     { "Kodak EOSDCS3B", 0, 0,
8302 	{ 9898,-2700,-940,-2478,12219,206,1985,634,1031 } },
8303     { "Kodak DCS520C", 178, 0,
8304 	{ 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } },
8305     { "Kodak DCS560C", 177, 0,
8306 	{ 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } },
8307     { "Kodak DCS620C", 177, 0,
8308 	{ 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } },
8309     { "Kodak DCS620X", 176, 0,
8310 	{ 13095,-6231,154,12221,-21,-2137,895,4602,2258 } },
8311     { "Kodak DCS660C", 173, 0,
8312 	{ 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } },
8313     { "Kodak DCS720X", 0, 0,
8314 	{ 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } },
8315     { "Kodak DCS760C", 0, 0,
8316 	{ 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } },
8317     { "Kodak DCS Pro SLR", 0, 0,
8318 	{ 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
8319     { "Kodak DCS Pro 14nx", 0, 0,
8320 	{ 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
8321     { "Kodak DCS Pro 14", 0, 0,
8322 	{ 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } },
8323     { "Kodak ProBack645", 0, 0,
8324 	{ 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } },
8325     { "Kodak ProBack", 0, 0,
8326 	{ 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } },
8327     { "Kodak P712", 0, 0,
8328 	{ 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } },
8329     { "Kodak P850", 0, 0xf7c,
8330 	{ 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } },
8331     { "Kodak P880", 0, 0xfff,
8332 	{ 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } },
8333     { "Kodak EasyShare Z980", 0, 0,
8334 	{ 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } },
8335     { "Kodak EasyShare Z981", 0, 0,
8336 	{ 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } },
8337     { "Kodak EasyShare Z990", 0, 0xfed,
8338 	{ 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } },
8339     { "Kodak EASYSHARE Z1015", 0, 0xef1,
8340 	{ 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } },
8341     { "Leaf CMost", 0, 0,
8342 	{ 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
8343     { "Leaf Valeo 6", 0, 0,
8344 	{ 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
8345     { "Leaf Aptus 54S", 0, 0,
8346 	{ 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
8347     { "Leaf Aptus 65", 0, 0,
8348 	{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
8349     { "Leaf Aptus 75", 0, 0,
8350 	{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
8351     { "Leaf", 0, 0,
8352 	{ 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
8353     { "Mamiya ZD", 0, 0,
8354 	{ 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } },
8355     { "Micron 2010", 110, 0,		/* DJC */
8356 	{ 16695,-3761,-2151,155,9682,163,3433,951,4904 } },
8357     { "Minolta DiMAGE 5", 0, 0xf7d,
8358 	{ 8983,-2942,-963,-6556,14476,2237,-2426,2887,8014 } },
8359     { "Minolta DiMAGE 7Hi", 0, 0xf7d,
8360 	{ 11368,-3894,-1242,-6521,14358,2339,-2475,3056,7285 } },
8361     { "Minolta DiMAGE 7", 0, 0xf7d,
8362 	{ 9144,-2777,-998,-6676,14556,2281,-2470,3019,7744 } },
8363     { "Minolta DiMAGE A1", 0, 0xf8b,
8364 	{ 9274,-2547,-1167,-8220,16323,1943,-2273,2720,8340 } },
8365     { "Minolta DiMAGE A200", 0, 0,
8366 	{ 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } },
8367     { "Minolta DiMAGE A2", 0, 0xf8f,
8368 	{ 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } },
8369     { "Minolta DiMAGE Z2", 0, 0,	/* DJC */
8370 	{ 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
8371     { "Minolta DYNAX 5", 0, 0xffb,
8372 	{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
8373     { "Minolta DYNAX 7", 0, 0xffb,
8374 	{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
8375     { "Motorola PIXL", 0, 0,		/* DJC */
8376 	{ 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } },
8377     { "Nikon D100", 0, 0,
8378 	{ 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } },
8379     { "Nikon D1H", 0, 0,
8380 	{ 7577,-2166,-926,-7454,15592,1934,-2377,2808,8606 } },
8381     { "Nikon D1X", 0, 0,
8382 	{ 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } },
8383     { "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */
8384 	{ 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } },
8385     { "Nikon D200", 0, 0xfbc,
8386 	{ 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } },
8387     { "Nikon D2H", 0, 0,
8388 	{ 5710,-901,-615,-8594,16617,2024,-2975,4120,6830 } },
8389     { "Nikon D2X", 0, 0,
8390 	{ 10231,-2769,-1255,-8301,15900,2552,-797,680,7148 } },
8391     { "Nikon D3000", 0, 0,
8392 	{ 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } },
8393     { "Nikon D3100", 0, 0,
8394 	{ 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } },
8395     { "Nikon D3200", 0, 0xfb9,
8396 	{ 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } },
8397     { "Nikon D3300", 0, 0,
8398 	{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
8399     { "Nikon D3400", 0, 0,
8400 	{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
8401     { "Nikon D300", 0, 0,
8402 	{ 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } },
8403     { "Nikon D3X", 0, 0,
8404 	{ 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } },
8405     { "Nikon D3S", 0, 0,
8406 	{ 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } },
8407     { "Nikon D3", 0, 0,
8408 	{ 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } },
8409     { "Nikon D40X", 0, 0,
8410 	{ 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } },
8411     { "Nikon D40", 0, 0,
8412 	{ 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } },
8413     { "Nikon D4S", 0, 0,
8414 	{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
8415     { "Nikon D4", 0, 0,
8416 	{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
8417     { "Nikon Df", 0, 0,
8418 	{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
8419     { "Nikon D5000", 0, 0xf00,
8420 	{ 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } },
8421     { "Nikon D5100", 0, 0x3de6,
8422 	{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
8423     { "Nikon D5200", 0, 0,
8424 	{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
8425     { "Nikon D5300", 0, 0,
8426 	{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
8427     { "Nikon D5500", 0, 0,
8428 	{ 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } },
8429     { "Nikon D5600", 0, 0,
8430 	{ 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } },
8431     { "Nikon D500", 0, 0,
8432 	{ 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } },
8433     { "Nikon D50", 0, 0,
8434 	{ 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
8435     { "Nikon D5", 0, 0,
8436 	{ 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } },
8437     { "Nikon D600", 0, 0x3e07,
8438 	{ 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } },
8439     { "Nikon D610", 0, 0,
8440 	{ 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } },
8441     { "Nikon D60", 0, 0,
8442 	{ 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } },
8443     { "Nikon D7000", 0, 0,
8444 	{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
8445     { "Nikon D7100", 0, 0,
8446 	{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
8447     { "Nikon D7200", 0, 0,
8448 	{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
8449     { "Nikon D7500", 0, 0,
8450 	{ 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } },
8451     { "Nikon D750", 0, 0,
8452 	{ 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } },
8453     { "Nikon D700", 0, 0,
8454 	{ 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } },
8455     { "Nikon D70", 0, 0,
8456 	{ 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
8457     { "Nikon D850", 0, 0,
8458 	{ 10405,-3755,-1270,-5461,13787,1793,-1040,2015,6785 } },
8459     { "Nikon D810", 0, 0,
8460 	{ 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } },
8461     { "Nikon D800", 0, 0,
8462 	{ 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } },
8463     { "Nikon D80", 0, 0,
8464 	{ 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } },
8465     { "Nikon D90", 0, 0xf00,
8466 	{ 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } },
8467     { "Nikon E700", 0, 0x3dd,		/* DJC */
8468 	{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
8469     { "Nikon E800", 0, 0x3dd,		/* DJC */
8470 	{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
8471     { "Nikon E950", 0, 0x3dd,		/* DJC */
8472 	{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
8473     { "Nikon E995", 0, 0,	/* copied from E5000 */
8474 	{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
8475     { "Nikon E2100", 0, 0,	/* copied from Z2, new white balance */
8476 	{ 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711} },
8477     { "Nikon E2500", 0, 0,
8478 	{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
8479     { "Nikon E3200", 0, 0,		/* DJC */
8480 	{ 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } },
8481     { "Nikon E4300", 0, 0,	/* copied from Minolta DiMAGE Z2 */
8482 	{ 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
8483     { "Nikon E4500", 0, 0,
8484 	{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
8485     { "Nikon E5000", 0, 0,
8486 	{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
8487     { "Nikon E5400", 0, 0,
8488 	{ 9349,-2987,-1001,-7919,15766,2266,-2098,2680,6839 } },
8489     { "Nikon E5700", 0, 0,
8490 	{ -5368,11478,2368,5537,-113,3148,-4969,10021,5782,778,9028,211 } },
8491     { "Nikon E8400", 0, 0,
8492 	{ 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } },
8493     { "Nikon E8700", 0, 0,
8494 	{ 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
8495     { "Nikon E8800", 0, 0,
8496 	{ 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } },
8497     { "Nikon COOLPIX A", 0, 0,
8498 	{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
8499     { "Nikon COOLPIX B700", 200, 0,
8500 	{ 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } },
8501     { "Nikon COOLPIX P330", 200, 0,
8502 	{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
8503     { "Nikon COOLPIX P340", 200, 0,
8504 	{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
8505     { "Nikon COOLPIX P6000", 0, 0,
8506 	{ 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } },
8507     { "Nikon COOLPIX P7000", 0, 0,
8508 	{ 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } },
8509     { "Nikon COOLPIX P7100", 0, 0,
8510 	{ 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } },
8511     { "Nikon COOLPIX P7700", 200, 0,
8512 	{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
8513     { "Nikon COOLPIX P7800", 200, 0,
8514 	{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
8515     { "Nikon 1 V3", 0, 0,
8516 	{ 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } },
8517     { "Nikon 1 J4", 0, 0,
8518 	{ 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } },
8519     { "Nikon 1 J5", 0, 0,
8520 	{ 7520,-2518,-645,-3844,12102,1945,-913,2249,6835 } },
8521     { "Nikon 1 S2", 200, 0,
8522 	{ 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } },
8523     { "Nikon 1 V2", 0, 0,
8524 	{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
8525     { "Nikon 1 J3", 0, 0,
8526 	{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
8527     { "Nikon 1 AW1", 0, 0,
8528 	{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
8529     { "Nikon 1 ", 0, 0,		/* J1, J2, S1, V1 */
8530 	{ 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } },
8531     { "Olympus AIR A01", 0, 0,
8532 	{ 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } },
8533     { "Olympus C5050", 0, 0,
8534 	{ 10508,-3124,-1273,-6079,14294,1901,-1653,2306,6237 } },
8535     { "Olympus C5060", 0, 0,
8536 	{ 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } },
8537     { "Olympus C7070", 0, 0,
8538 	{ 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } },
8539     { "Olympus C70", 0, 0,
8540 	{ 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } },
8541     { "Olympus C80", 0, 0,
8542 	{ 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } },
8543     { "Olympus E-10", 0, 0xffc,
8544 	{ 12745,-4500,-1416,-6062,14542,1580,-1934,2256,6603 } },
8545     { "Olympus E-1", 0, 0,
8546 	{ 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } },
8547     { "Olympus E-20", 0, 0xffc,
8548 	{ 13173,-4732,-1499,-5807,14036,1895,-2045,2452,7142 } },
8549     { "Olympus E-300", 0, 0,
8550 	{ 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } },
8551     { "Olympus E-330", 0, 0,
8552 	{ 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } },
8553     { "Olympus E-30", 0, 0xfbc,
8554 	{ 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } },
8555     { "Olympus E-3", 0, 0xf99,
8556 	{ 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } },
8557     { "Olympus E-400", 0, 0,
8558 	{ 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } },
8559     { "Olympus E-410", 0, 0xf6a,
8560 	{ 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } },
8561     { "Olympus E-420", 0, 0xfd7,
8562 	{ 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } },
8563     { "Olympus E-450", 0, 0xfd2,
8564 	{ 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } },
8565     { "Olympus E-500", 0, 0,
8566 	{ 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } },
8567     { "Olympus E-510", 0, 0xf6a,
8568 	{ 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } },
8569     { "Olympus E-520", 0, 0xfd2,
8570 	{ 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } },
8571     { "Olympus E-5", 0, 0xeec,
8572 	{ 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } },
8573     { "Olympus E-600", 0, 0xfaf,
8574 	{ 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } },
8575     { "Olympus E-620", 0, 0xfaf,
8576 	{ 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } },
8577     { "Olympus E-P1", 0, 0xffd,
8578 	{ 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } },
8579     { "Olympus E-P2", 0, 0xffd,
8580 	{ 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } },
8581     { "Olympus E-P3", 0, 0,
8582 	{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
8583     { "Olympus E-P5", 0, 0,
8584 	{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
8585     { "Olympus E-PL1s", 0, 0,
8586 	{ 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } },
8587     { "Olympus E-PL1", 0, 0,
8588 	{ 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } },
8589     { "Olympus E-PL2", 0, 0xcf3,
8590 	{ 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } },
8591     { "Olympus E-PL3", 0, 0,
8592 	{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
8593     { "Olympus E-PL5", 0, 0xfcb,
8594 	{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
8595     { "Olympus E-PL6", 0, 0,
8596 	{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
8597     { "Olympus E-PL7", 0, 0,
8598 	{ 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } },
8599     { "Olympus E-PL8", 0, 0,
8600 	{ 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } },
8601     { "Olympus E-PL9", 0, 0,
8602 	{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
8603     { "Olympus E-PM1", 0, 0,
8604 	{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
8605     { "Olympus E-PM2", 0, 0,
8606 	{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
8607     { "Olympus E-M10", 0, 0,	/* also E-M10 Mark II & III */
8608 	{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
8609     { "Olympus E-M1Mark II", 0, 0,
8610 	{ 9383,-3170,-763,-2457,10702,2020,-384,1236,5552 } },
8611     { "Olympus E-M1", 0, 0,
8612 	{ 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } },
8613     { "Olympus E-M5MarkII", 0, 0,
8614 	{ 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } },
8615     { "Olympus E-M5", 0, 0xfe1,
8616 	{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
8617     { "Olympus PEN-F", 0, 0,
8618 	{ 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } },
8619     { "Olympus SH-2", 0, 0,
8620 	{ 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } },
8621     { "Olympus SP350", 0, 0,
8622 	{ 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } },
8623     { "Olympus SP3", 0, 0,
8624 	{ 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } },
8625     { "Olympus SP500UZ", 0, 0xfff,
8626 	{ 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } },
8627     { "Olympus SP510UZ", 0, 0xffe,
8628 	{ 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } },
8629     { "Olympus SP550UZ", 0, 0xffe,
8630 	{ 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } },
8631     { "Olympus SP560UZ", 0, 0xff9,
8632 	{ 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } },
8633     { "Olympus SP570UZ", 0, 0,
8634 	{ 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } },
8635     { "Olympus STYLUS1", 0, 0,
8636 	{ 8360,-2420,-880,-3928,12353,1739,-1381,2416,5173 } },
8637     { "Olympus TG-4", 0, 0,
8638 	{ 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } },
8639     { "Olympus TG-5", 0, 0,
8640 	{ 10899,-3833,-1082,-2112,10736,1575,-267,1452,5269 } },
8641     { "Olympus XZ-10", 0, 0,
8642 	{ 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } },
8643     { "Olympus XZ-1", 0, 0,
8644 	{ 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } },
8645     { "Olympus XZ-2", 0, 0,
8646 	{ 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } },
8647     { "OmniVision", 0, 0,		/* DJC */
8648 	{ 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } },
8649     { "Pentax *ist DL2", 0, 0,
8650 	{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
8651     { "Pentax *ist DL", 0, 0,
8652 	{ 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } },
8653     { "Pentax *ist DS2", 0, 0,
8654 	{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
8655     { "Pentax *ist DS", 0, 0,
8656 	{ 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } },
8657     { "Pentax *ist D", 0, 0,
8658 	{ 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } },
8659     { "Pentax K10D", 0, 0,
8660 	{ 9566,-2863,-803,-7170,15172,2112,-818,803,9705 } },
8661     { "Pentax K1", 0, 0,
8662 	{ 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } },
8663     { "Pentax K20D", 0, 0,
8664 	{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
8665     { "Pentax K200D", 0, 0,
8666 	{ 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } },
8667     { "Pentax K2000", 0, 0,
8668 	{ 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } },
8669     { "Pentax K-m", 0, 0,
8670 	{ 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } },
8671     { "Pentax K-x", 0, 0,
8672 	{ 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } },
8673     { "Pentax K-r", 0, 0,
8674 	{ 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } },
8675     { "Pentax K-1", 0, 0,
8676 	{ 8596,-2981,-639,-4202,12046,2431,-685,1424,6122 } },
8677     { "Pentax K-30", 0, 0,
8678 	{ 8710,-2632,-1167,-3995,12301,1881,-981,1719,6535 } },
8679     { "Pentax K-3 II", 0, 0,
8680 	{ 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } },
8681     { "Pentax K-3", 0, 0,
8682 	{ 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } },
8683     { "Pentax K-5 II", 0, 0,
8684 	{ 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } },
8685     { "Pentax K-5", 0, 0,
8686 	{ 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } },
8687     { "Pentax K-70", 0, 0,
8688 	{ 8270,-2117,-1299,-4359,12953,1515,-1078,1933,5975 } },
8689     { "Pentax K-7", 0, 0,
8690 	{ 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } },
8691     { "Pentax K-S1", 0, 0,
8692 	{ 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } },
8693     { "Pentax K-S2", 0, 0,
8694 	{ 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } },
8695     { "Pentax KP", 0, 0,
8696 	{ 8617,-3228,-1034,-4674,12821,2044,-803,1577,5728 } },
8697     { "Pentax Q-S1", 0, 0,
8698 	{ 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } },
8699     { "Pentax 645D", 0, 0x3e00,
8700 	{ 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } },
8701     { "Panasonic DMC-CM1", 15, 0,
8702 	{ 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } },
8703     { "Panasonic DC-FZ80", 0, 0,
8704 	{ 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } },
8705     { "Panasonic DMC-FZ8", 0, 0xf7f,
8706 	{ 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } },
8707     { "Panasonic DMC-FZ18", 0, 0,
8708 	{ 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } },
8709     { "Panasonic DMC-FZ28", 15, 0xf96,
8710 	{ 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } },
8711     { "Panasonic DMC-FZ2500", 15, 0,
8712 	{ 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } },
8713     { "Panasonic DMC-FZ330", 15, 0,
8714 	{ 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } },
8715     { "Panasonic DMC-FZ300", 15, 0,
8716 	{ 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } },
8717     { "Panasonic DMC-FZ30", 0, 0xf94,
8718 	{ 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } },
8719     { "Panasonic DMC-FZ3", 15, 0,	/* FZ35, FZ38 */
8720 	{ 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } },
8721     { "Panasonic DMC-FZ4", 15, 0,	/* FZ40, FZ45 */
8722 	{ 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } },
8723     { "Panasonic DMC-FZ50", 0, 0,
8724 	{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
8725     { "Panasonic DMC-FZ7", 15, 0,	/* FZ70, FZ72 */
8726 	{ 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } },
8727     { "Leica V-LUX1", 0, 0,
8728 	{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
8729     { "Panasonic DMC-L10", 15, 0xf96,
8730 	{ 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } },
8731     { "Panasonic DMC-L1", 0, 0xf7f,
8732 	{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
8733     { "Leica DIGILUX 3", 0, 0xf7f,
8734 	{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
8735     { "Panasonic DMC-LC1", 0, 0,
8736 	{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
8737     { "Leica DIGILUX 2", 0, 0,
8738 	{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
8739     { "Panasonic DMC-LX100", 15, 0,
8740 	{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
8741     { "Leica D-LUX (Typ 109)", 15, 0,
8742 	{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
8743     { "Panasonic DMC-LF1", 15, 0,
8744 	{ 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } },
8745     { "Leica C (Typ 112)", 15, 0,
8746 	{ 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } },
8747     { "Panasonic DMC-LX1", 0, 0xf7f,
8748 	{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
8749     { "Leica D-LUX2", 0, 0xf7f,
8750 	{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
8751     { "Panasonic DMC-LX2", 0, 0,
8752 	{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
8753     { "Leica D-LUX3", 0, 0,
8754 	{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
8755     { "Panasonic DMC-LX3", 15, 0,
8756 	{ 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } },
8757     { "Leica D-LUX 4", 15, 0,
8758 	{ 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } },
8759     { "Panasonic DMC-LX5", 15, 0,
8760 	{ 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } },
8761     { "Leica D-LUX 5", 15, 0,
8762 	{ 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } },
8763     { "Panasonic DMC-LX7", 15, 0,
8764 	{ 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } },
8765     { "Leica D-LUX 6", 15, 0,
8766 	{ 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } },
8767     { "Panasonic DMC-LX9", 15, 0,
8768 	{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
8769     { "Panasonic DMC-FZ1000", 15, 0,
8770 	{ 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } },
8771     { "Leica V-LUX (Typ 114)", 15, 0,
8772 	{ 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } },
8773     { "Panasonic DMC-FZ100", 15, 0xfff,
8774 	{ 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } },
8775     { "Leica V-LUX 2", 15, 0xfff,
8776 	{ 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } },
8777     { "Panasonic DMC-FZ150", 15, 0xfff,
8778 	{ 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } },
8779     { "Leica V-LUX 3", 15, 0xfff,
8780 	{ 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } },
8781     { "Panasonic DMC-FZ200", 15, 0xfff,
8782 	{ 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } },
8783     { "Leica V-LUX 4", 15, 0xfff,
8784 	{ 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } },
8785     { "Panasonic DMC-FX150", 15, 0xfff,
8786 	{ 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } },
8787     { "Panasonic DMC-G10", 0, 0,
8788 	{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } },
8789     { "Panasonic DMC-G1", 15, 0xf94,
8790 	{ 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } },
8791     { "Panasonic DMC-G2", 15, 0xf3c,
8792 	{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } },
8793     { "Panasonic DMC-G3", 15, 0xfff,
8794 	{ 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } },
8795     { "Panasonic DMC-G5", 15, 0xfff,
8796 	{ 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } },
8797     { "Panasonic DMC-G6", 15, 0xfff,
8798 	{ 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } },
8799     { "Panasonic DMC-G7", 15, 0xfff,
8800 	{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
8801     { "Panasonic DMC-G8", 15, 0xfff,	/* G8, G80, G81, G85 */
8802 	{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
8803     { "Panasonic DC-G9", 15, 0xfff,
8804 	{ 7685,-2375,-634,-3687,11700,2249,-748,1546,5111 } },
8805     { "Panasonic DMC-GF1", 15, 0xf92,
8806 	{ 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } },
8807     { "Panasonic DMC-GF2", 15, 0xfff,
8808 	{ 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } },
8809     { "Panasonic DMC-GF3", 15, 0xfff,
8810 	{ 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } },
8811     { "Panasonic DMC-GF5", 15, 0xfff,
8812 	{ 8228,-2945,-660,-3938,11792,2430,-1094,2278,5793 } },
8813     { "Panasonic DMC-GF6", 15, 0,
8814 	{ 8130,-2801,-946,-3520,11289,2552,-1314,2511,5791 } },
8815     { "Panasonic DMC-GF7", 15, 0,
8816 	{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
8817     { "Panasonic DMC-GF8", 15, 0,
8818 	{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
8819     { "Panasonic DC-GF9", 15, 0,
8820 	{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
8821     { "Panasonic DMC-GH1", 15, 0xf92,
8822 	{ 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } },
8823     { "Panasonic DMC-GH2", 15, 0xf95,
8824 	{ 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } },
8825     { "Panasonic DMC-GH3", 15, 0,
8826 	{ 6559,-1752,-491,-3672,11407,2586,-962,1875,5130 } },
8827     { "Panasonic DMC-GH4", 15, 0,
8828 	{ 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } },
8829     { "Panasonic DC-GH5S", 15, 0,
8830 	{ 6929,-2355,-708,-4192,12534,1828,-1097,1989,5195 } },
8831     { "Panasonic DC-GH5", 15, 0,
8832 	{ 7641,-2336,-605,-3218,11299,2187,-485,1338,5121 } },
8833     { "Panasonic DMC-GM1", 15, 0,
8834 	{ 6770,-1895,-744,-5232,13145,2303,-1664,2691,5703 } },
8835     { "Panasonic DMC-GM5", 15, 0,
8836 	{ 8238,-3244,-679,-3921,11814,2384,-836,2022,5852 } },
8837     { "Panasonic DMC-GX1", 15, 0,
8838 	{ 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } },
8839     { "Panasonic DMC-GX7", 15, 0,
8840 	{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
8841     { "Panasonic DMC-GX85", 15, 0,
8842 	{ 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } },
8843     { "Panasonic DMC-GX8", 15, 0,
8844 	{ 7564,-2263,-606,-3148,11239,2177,-540,1435,4853 } },
8845     { "Panasonic DC-GX9", 15, 0,
8846 	{ 7564,-2263,-606,-3148,11239,2177,-540,1435,4853 } },
8847     { "Panasonic DMC-ZS100", 15, 0,
8848 	{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
8849     { "Panasonic DC-ZS200", 15, 0,
8850 	{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
8851     { "Panasonic DMC-ZS40", 15, 0,
8852 	{ 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } },
8853     { "Panasonic DMC-ZS50", 15, 0,
8854 	{ 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } },
8855     { "Panasonic DMC-TZ82", 15, 0,
8856 	{ 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } },
8857     { "Panasonic DMC-ZS6", 15, 0,
8858 	{ 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } },
8859     { "Panasonic DMC-ZS70", 15, 0,
8860 	{ 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } },
8861     { "Leica S (Typ 007)", 0, 0,
8862 	{ 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } },
8863     { "Leica X", 0, 0,		/* X and X-U, both (Typ 113) */
8864 	{ 7712,-2059,-653,-3882,11494,2726,-710,1332,5958 } },
8865     { "Leica Q (Typ 116)", 0, 0,
8866 	{ 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830 } },
8867     { "Leica M (Typ 262)", 0, 0,
8868 	{ 6653,-1486,-611,-4221,13303,929,-881,2416,7226 } },
8869     { "Leica SL (Typ 601)", 0, 0,
8870 	{ 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830 } },
8871     { "Leica TL2", 0, 0,
8872 	{ 5836,-1626,-647,-5384,13326,2261,-1207,2129,5861 } },
8873     { "Leica TL", 0, 0,
8874 	{ 5463,-988,-364,-4634,12036,2946,-766,1389,6522 } },
8875     { "Leica CL", 0, 0,
8876 	{ 7414,-2393,-840,-5127,13180,2138,-1585,2468,5064 } },
8877     { "Leica M10", 0, 0,
8878 	{ 8249,-2849,-620,-5415,14756,565,-957,3074,6517 } },
8879     { "Phase One H 20", 0, 0,		/* DJC */
8880 	{ 1313,1855,-109,-6715,15908,808,-327,1840,6020 } },
8881     { "Phase One H 25", 0, 0,
8882 	{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
8883     { "Phase One P 2", 0, 0,
8884 	{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
8885     { "Phase One P 30", 0, 0,
8886 	{ 4516,-245,-37,-7020,14976,2173,-3206,4671,7087 } },
8887     { "Phase One P 45", 0, 0,
8888 	{ 5053,-24,-117,-5684,14076,1702,-2619,4492,5849 } },
8889     { "Phase One P40", 0, 0,
8890 	{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
8891     { "Phase One P65", 0, 0,
8892 	{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
8893     { "Photron BC2-HD", 0, 0,		/* DJC */
8894 	{ 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } },
8895     { "Red One", 704, 0xffff,		/* DJC */
8896 	{ 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } },
8897     { "Ricoh GR II", 0, 0,
8898 	{ 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } },
8899     { "Ricoh GR", 0, 0,
8900 	{ 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } },
8901     { "Samsung EX1", 0, 0x3e00,
8902 	{ 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } },
8903     { "Samsung EX2F", 0, 0x7ff,
8904 	{ 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } },
8905     { "Samsung EK-GN120", 0, 0,
8906 	{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
8907     { "Samsung NX mini", 0, 0,
8908 	{ 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } },
8909     { "Samsung NX3300", 0, 0,
8910 	{ 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } },
8911     { "Samsung NX3000", 0, 0,
8912 	{ 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } },
8913     { "Samsung NX30", 0, 0,	/* NX30, NX300, NX300M */
8914 	{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
8915     { "Samsung NX2000", 0, 0,
8916 	{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
8917     { "Samsung NX2", 0, 0xfff,	/* NX20, NX200, NX210 */
8918 	{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
8919     { "Samsung NX1000", 0, 0,
8920 	{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
8921     { "Samsung NX1100", 0, 0,
8922 	{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
8923     { "Samsung NX11", 0, 0,
8924 	{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
8925     { "Samsung NX10", 0, 0,	/* also NX100 */
8926 	{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
8927     { "Samsung NX500", 0, 0,
8928 	{ 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } },
8929     { "Samsung NX5", 0, 0,
8930 	{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
8931     { "Samsung NX1", 0, 0,
8932 	{ 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } },
8933     { "Samsung WB2000", 0, 0xfff,
8934 	{ 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } },
8935     { "Samsung GX-1", 0, 0,
8936 	{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
8937     { "Samsung GX20", 0, 0,	/* copied from Pentax K20D */
8938 	{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
8939     { "Samsung S85", 0, 0,		/* DJC */
8940 	{ 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } },
8941     { "Sinar", 0, 0,			/* DJC */
8942 	{ 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } },
8943     { "Sony DSC-F828", 0, 0,
8944 	{ 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } },
8945     { "Sony DSC-R1", 0, 0,
8946 	{ 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } },
8947     { "Sony DSC-V3", 0, 0,
8948 	{ 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } },
8949     { "Sony DSC-RX100M", 0, 0,		/* M2, M3, M4, and M5 */
8950 	{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
8951     { "Sony DSC-RX100", 0, 0,
8952 	{ 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } },
8953     { "Sony DSC-RX10M4", 0, 0,
8954 	{ 7699,-2566,-629,-2967,11270,1928,-378,1286,4807 } },
8955     { "Sony DSC-RX10", 0, 0,		/* also RX10M2, RX10M3 */
8956 	{ 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } },
8957     { "Sony DSC-RX1RM2", 0, 0,
8958 	{ 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } },
8959     { "Sony DSC-RX1", 0, 0,
8960     { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } },
8961     { "Sony DSC-RX0", 200, 0,
8962 	{ 9396,-3507,-843,-2497,11111,1572,-343,1355,5089 } },
8963     { "Sony DSLR-A100", 0, 0xfeb,
8964 	{ 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } },
8965     { "Sony DSLR-A290", 0, 0,
8966 	{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
8967     { "Sony DSLR-A2", 0, 0,
8968 	{ 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } },
8969     { "Sony DSLR-A300", 0, 0,
8970 	{ 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } },
8971     { "Sony DSLR-A330", 0, 0,
8972 	{ 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } },
8973     { "Sony DSLR-A350", 0, 0xffc,
8974 	{ 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } },
8975     { "Sony DSLR-A380", 0, 0,
8976 	{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
8977     { "Sony DSLR-A390", 0, 0,
8978 	{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
8979     { "Sony DSLR-A450", 0, 0,
8980 	{ 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } },
8981     { "Sony DSLR-A580", 0, 0,
8982 	{ 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } },
8983     { "Sony DSLR-A500", 0, 0,
8984 	{ 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } },
8985     { "Sony DSLR-A5", 0, 0,
8986 	{ 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } },
8987     { "Sony DSLR-A700", 0, 0,
8988 	{ 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } },
8989     { "Sony DSLR-A850", 0, 0,
8990 	{ 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } },
8991     { "Sony DSLR-A900", 0, 0,
8992 	{ 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } },
8993     { "Sony ILCA-68", 0, 0,
8994 	{ 6435,-1903,-536,-4722,12449,2550,-663,1363,6517 } },
8995     { "Sony ILCA-77M2", 0, 0,
8996 	{ 5991,-1732,-443,-4100,11989,2381,-704,1467,5992 } },
8997     { "Sony ILCA-99M2", 0, 0,
8998 	{ 6660,-1918,-471,-4613,12398,2485,-649,1433,6447 } },
8999     { "Sony ILCE-6", 0, 0,		/* 6300, 6500 */
9000 	{ 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } },
9001     { "Sony ILCE-7M2", 0, 0,
9002 	{ 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } },
9003     { "Sony ILCE-7M3", 0, 0,
9004 	{ 7374,-2389,-551,-5435,13162,2519,-1006,1795,6552 } },
9005     { "Sony ILCE-7S", 0, 0,	/* also ILCE-7SM2 */
9006 	{ 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } },
9007     { "Sony ILCE-7RM3", 0, 0,
9008 	{ 6640,-1847,-503,-5238,13010,2474,-993,1673,6527 } },
9009     { "Sony ILCE-7RM2", 0, 0,
9010 	{ 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } },
9011     { "Sony ILCE-7R", 0, 0,
9012 	{ 4913,-541,-202,-6130,13513,2906,-1564,2151,7183 } },
9013     { "Sony ILCE-7", 0, 0,
9014 	{ 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } },
9015     { "Sony ILCE-9", 0, 0,
9016 	{ 6389,-1703,-378,-4562,12265,2587,-670,1489,6550 } },
9017     { "Sony ILCE", 0, 0,	/* 3000, 5000, 5100, 6000, and QX1 */
9018 	{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
9019     { "Sony NEX-5N", 0, 0,
9020 	{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
9021     { "Sony NEX-5R", 0, 0,
9022 	{ 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } },
9023     { "Sony NEX-5T", 0, 0,
9024 	{ 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } },
9025     { "Sony NEX-3N", 0, 0,
9026 	{ 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } },
9027     { "Sony NEX-3", 138, 0,		/* DJC */
9028 	{ 6907,-1256,-645,-4940,12621,2320,-1710,2581,6230 } },
9029     { "Sony NEX-5", 116, 0,		/* DJC */
9030 	{ 6807,-1350,-342,-4216,11649,2567,-1089,2001,6420 } },
9031     { "Sony NEX-3", 0, 0,		/* Adobe */
9032 	{ 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } },
9033     { "Sony NEX-5", 0, 0,		/* Adobe */
9034 	{ 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } },
9035     { "Sony NEX-6", 0, 0,
9036 	{ 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } },
9037     { "Sony NEX-7", 0, 0,
9038 	{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
9039     { "Sony NEX", 0, 0,	/* NEX-C3, NEX-F3 */
9040 	{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
9041     { "Sony SLT-A33", 0, 0,
9042 	{ 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } },
9043     { "Sony SLT-A35", 0, 0,
9044 	{ 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } },
9045     { "Sony SLT-A37", 0, 0,
9046 	{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
9047     { "Sony SLT-A55", 0, 0,
9048 	{ 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } },
9049     { "Sony SLT-A57", 0, 0,
9050 	{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
9051     { "Sony SLT-A58", 0, 0,
9052 	{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
9053     { "Sony SLT-A65", 0, 0,
9054 	{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
9055     { "Sony SLT-A77", 0, 0,
9056 	{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
9057     { "Sony SLT-A99", 0, 0,
9058 	{ 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } },
9059     { "YI M1", 0, 0,
9060 	{ 7712,-2059,-653,-3882,11494,2726,-710,1332,5958 } },
9061   };
9062   double cam_xyz[4][3];
9063   char name[130];
9064   int i, j;
9065 
9066   sprintf (name, "%s %s", make, model);
9067 
9068 
9069   // -- RT --------------------------------------------------------------------
9070   const bool is_pentax_dng = dng_version && !strncmp(RT_software.c_str(), "PENTAX", 6);
9071   // indicate that DCRAW wants these from constants (rather than having loaded these from RAW file
9072   // note: this is simplified so far, in some cases dcraw calls this when it has say the black level
9073   // from file, but then we will not provide any black level in the tables. This case is mainly just
9074   // to avoid loading table values if we have loaded a DNG conversion of a raw file (which already
9075   // have constants stored in the file).
9076   if (RT_whitelevel_from_constant == ThreeValBool::X || is_pentax_dng) {
9077     RT_whitelevel_from_constant = ThreeValBool::T;
9078   }
9079   if (RT_blacklevel_from_constant == ThreeValBool::X || is_pentax_dng) {
9080     RT_blacklevel_from_constant = ThreeValBool::T;
9081   }
9082   if (RT_matrix_from_constant == ThreeValBool::X) {
9083     RT_matrix_from_constant = ThreeValBool::T;
9084   }
9085   // -- RT --------------------------------------------------------------------
9086 
9087   for (i=0; i < sizeof table / sizeof *table; i++)
9088     if (!strncmp (name, table[i].prefix, strlen(table[i].prefix))) {
9089       if (RT_blacklevel_from_constant == ThreeValBool::T && table[i].black)   black   = (ushort) table[i].black;
9090       if (RT_whitelevel_from_constant == ThreeValBool::T && table[i].maximum) maximum = (ushort) table[i].maximum;
9091       if (RT_matrix_from_constant == ThreeValBool::T && table[i].trans[0]) {
9092 	for (raw_color = j=0; j < 12; j++)
9093 	  ((double *)cam_xyz)[j] = table[i].trans[j] / 10000.0;
9094 	cam_xyz_coeff (rgb_cam, cam_xyz);
9095       }
9096       break;
9097     }
9098   if (load_raw == &CLASS sony_arw2_load_raw) { // RT: arw2 scale fix
9099       black <<= 2;
9100       tiff_bps += 2;
9101   }
9102   { /* Check for RawTherapee table overrides and extensions */
9103       int black_level, white_level;
9104       short trans[12];
9105       if (dcraw_coeff_overrides(make, model, iso_speed, trans, &black_level, &white_level)) {
9106           if (black_level > -1) {
9107               black = (ushort)black_level;
9108           }
9109           if (white_level > -1) {
9110               maximum = (ushort)white_level;
9111               if(tiff_bps > 0) {
9112                 unsigned compare = ((uint64_t)1 << tiff_bps) - 1; // use uint64_t to avoid overflow if tiff_bps == 32
9113                 while(maximum > compare)
9114                     maximum >>= 1;
9115               }
9116           }
9117           if (trans[0]) {
9118               for (j=0; j < 12; j++) {
9119                   ((double *)cam_xyz)[j] = trans[j] / 10000.0;
9120               }
9121               cam_xyz_coeff (rgb_cam,cam_xyz);
9122           }
9123       }
9124   }
9125 }
9126 
simple_coeff(int index)9127 void CLASS simple_coeff (int index)
9128 {
9129   static const float table[][12] = {
9130   /* index 0 -- all Foveon cameras */
9131   { 1.4032,-0.2231,-0.1016,-0.5263,1.4816,0.017,-0.0112,0.0183,0.9113 },
9132   /* index 1 -- Kodak DC20 and DC25 */
9133   { 2.25,0.75,-1.75,-0.25,-0.25,0.75,0.75,-0.25,-0.25,-1.75,0.75,2.25 },
9134   /* index 2 -- Logitech Fotoman Pixtura */
9135   { 1.893,-0.418,-0.476,-0.495,1.773,-0.278,-1.017,-0.655,2.672 },
9136   /* index 3 -- Nikon E880, E900, and E990 */
9137   { -1.936280,  1.800443, -1.448486,  2.584324,
9138      1.405365, -0.524955, -0.289090,  0.408680,
9139     -1.204965,  1.082304,  2.941367, -1.818705 }
9140   };
9141   int i, c;
9142 
9143   for (raw_color = i=0; i < 3; i++)
9144     FORCC rgb_cam[i][c] = table[index][i*colors+c];
9145 }
9146 
guess_byte_order(int words)9147 short CLASS guess_byte_order (int words)
9148 {
9149   uchar test[4][2];
9150   int t=2, msb;
9151   double diff, sum[2] = {0,0};
9152 
9153   fread (test[0], 2, 2, ifp);
9154   for (words-=2; words--; ) {
9155     fread (test[t], 2, 1, ifp);
9156     for (msb=0; msb < 2; msb++) {
9157       diff = (test[t^2][msb] << 8 | test[t^2][!msb])
9158 	   - (test[t  ][msb] << 8 | test[t  ][!msb]);
9159       sum[msb] += diff*diff;
9160     }
9161     t = (t+1) & 3;
9162   }
9163   return sum[0] < sum[1] ? 0x4d4d : 0x4949;
9164 }
9165 
find_green(int bps,int bite,int off0,int off1)9166 float CLASS find_green (int bps, int bite, int off0, int off1)
9167 {
9168   UINT64 bitbuf=0;
9169   int vbits, col, i, c;
9170   ushort img[2][2064];
9171   double sum[]={0,0};
9172 
9173   FORC(2) {
9174     fseek (ifp, c ? off1:off0, SEEK_SET);
9175     for (vbits=col=0; col < width; col++) {
9176       for (vbits -= bps; vbits < 0; vbits += bite) {
9177 	bitbuf <<= bite;
9178 	for (i=0; i < bite; i+=8)
9179 	  bitbuf |= (unsigned) (fgetc(ifp) << i);
9180       }
9181       img[c][col] = bitbuf << (64-bps-vbits) >> (64-bps);
9182     }
9183   }
9184   FORC(width-1) {
9185     sum[ c & 1] += ABS(img[0][c]-img[1][c+1]);
9186     sum[~c & 1] += ABS(img[1][c]-img[0][c+1]);
9187   }
9188   return 100 * log(sum[0]/sum[1]);
9189 }
9190 
9191 /*
9192    Identify which camera created this file, and set global variables
9193    accordingly.
9194  */
identify()9195 void CLASS identify()
9196 {
9197   static const short pana[][6] = {
9198     { 3130, 1743,  4,  0, -6,  0 },
9199     { 3130, 2055,  4,  0, -6,  0 },
9200     { 3130, 2319,  4,  0, -6,  0 },
9201     { 3170, 2103, 18,  0,-42, 20 },
9202     { 3170, 2367, 18, 13,-42,-21 },
9203     { 3177, 2367,  0,  0, -1,  0 },
9204     { 3304, 2458,  0,  0, -1,  0 },
9205     { 3330, 2463,  9,  0, -5,  0 },
9206     { 3330, 2479,  9,  0,-17,  4 },
9207     { 3370, 1899, 15,  0,-44, 20 },
9208     { 3370, 2235, 15,  0,-44, 20 },
9209     { 3370, 2511, 15, 10,-44,-21 },
9210     { 3690, 2751,  3,  0, -8, -3 },
9211     { 3710, 2751,  0,  0, -3,  0 },
9212     { 3724, 2450,  0,  0,  0, -2 },
9213     { 3770, 2487, 17,  0,-44, 19 },
9214     { 3770, 2799, 17, 15,-44,-19 },
9215     { 3880, 2170,  6,  0, -6,  0 },
9216     { 4060, 3018,  0,  0,  0, -2 },
9217     { 4290, 2391,  3,  0, -8, -1 },
9218     { 4330, 2439, 17, 15,-44,-19 },
9219     { 4508, 2962,  0,  0, -3, -4 },
9220     { 4508, 3330,  0,  0, -3, -6 },
9221   };
9222   static const ushort canon[][11] = {
9223     { 1944, 1416,   0,  0, 48,  0 },
9224     { 2144, 1560,   4,  8, 52,  2, 0, 0, 0, 25 },
9225     { 2224, 1456,  48,  6,  0,  2 },
9226     { 2376, 1728,  12,  6, 52,  2 },
9227     { 2672, 1968,  12,  6, 44,  2 },
9228     { 3152, 2068,  64, 12,  0,  0, 16 },
9229     { 3160, 2344,  44, 12,  4,  4 },
9230     { 3344, 2484,   4,  6, 52,  6 },
9231     { 3516, 2328,  42, 14,  0,  0 },
9232     { 3596, 2360,  74, 12,  0,  0 },
9233     { 3744, 2784,  52, 12,  8, 12 },
9234     { 3944, 2622,  30, 18,  6,  2 },
9235     { 3948, 2622,  42, 18,  0,  2 },
9236     { 3984, 2622,  76, 20,  0,  2, 14 },
9237     { 4104, 3048,  48, 12, 24, 12 },
9238     { 4116, 2178,   4,  2,  0,  0 },
9239     { 4152, 2772, 192, 12,  0,  0 },
9240     { 4160, 3124, 104, 11,  8, 65 },
9241     { 4176, 3062,  96, 17,  8,  0, 0, 16, 0, 7, 0x49 },
9242     { 4192, 3062,  96, 17, 24,  0, 0, 16, 0, 0, 0x49 },
9243     { 4312, 2876,  22, 18,  0,  2 },
9244     { 4352, 2874,  62, 18,  0,  0 },
9245     { 4476, 2954,  90, 34,  0,  0 },
9246     { 4480, 3348,  12, 10, 36, 12, 0, 0, 0, 18, 0x49 },
9247     { 4480, 3366,  80, 50,  0,  0 },
9248     { 4496, 3366,  80, 50, 12,  0 },
9249     { 4768, 3516,  96, 16,  0,  0, 0, 16 },
9250     { 4832, 3204,  62, 26,  0,  0 },
9251     { 4832, 3228,  62, 51,  0,  0 },
9252     { 5108, 3349,  98, 13,  0,  0 },
9253     { 5120, 3318, 142, 45, 62,  0 },
9254     { 5280, 3528,  72, 52,  0,  0 },
9255     { 5344, 3516, 142, 51,  0,  0 },
9256     { 5344, 3584, 126,100,  0,  2 },
9257     { 5360, 3516, 158, 51,  0,  0 },
9258     { 5568, 3708,  72, 38,  0,  0 },
9259     { 5632, 3710,  96, 17,  0,  0, 0, 16, 0, 0, 0x49 },
9260     { 5712, 3774,  62, 20, 10,  2 },
9261     { 5792, 3804, 158, 51,  0,  0 },
9262     { 5920, 3950, 122, 80,  2,  0 },
9263     { 6096, 4051,  76, 35,  0,  0 },
9264     { 6096, 4056,  72, 34,  0,  0 },
9265     { 6288, 4056, 264, 36,  0,  0 },
9266     { 6384, 4224, 120, 44,  0,  0 },
9267     { 6880, 4544, 136, 42,  0,  0 },
9268     { 8896, 5920, 160, 64,  0,  0 },
9269   };
9270   static const struct {
9271     ushort id;
9272     char model[20];
9273   } unique[] = {
9274     { 0x168, "EOS 10D" },    { 0x001, "EOS-1D" },
9275     { 0x175, "EOS 20D" },    { 0x174, "EOS-1D Mark II" },
9276     { 0x234, "EOS 30D" },    { 0x232, "EOS-1D Mark II N" },
9277     { 0x190, "EOS 40D" },    { 0x169, "EOS-1D Mark III" },
9278     { 0x261, "EOS 50D" },    { 0x281, "EOS-1D Mark IV" },
9279     { 0x287, "EOS 60D" },    { 0x167, "EOS-1DS" },
9280     { 0x325, "EOS 70D" },
9281     { 0x408, "EOS 77D" },    { 0x331, "EOS M" },
9282     { 0x350, "EOS 80D" },    { 0x328, "EOS-1D X Mark II" },
9283     { 0x346, "EOS 100D" },
9284     { 0x417, "EOS 200D" },
9285     { 0x170, "EOS 300D" },   { 0x188, "EOS-1Ds Mark II" },
9286     { 0x176, "EOS 450D" },   { 0x215, "EOS-1Ds Mark III" },
9287     { 0x189, "EOS 350D" },   { 0x324, "EOS-1D C" },
9288     { 0x236, "EOS 400D" },   { 0x269, "EOS-1D X" },
9289     { 0x252, "EOS 500D" },   { 0x213, "EOS 5D" },
9290     { 0x270, "EOS 550D" },   { 0x218, "EOS 5D Mark II" },
9291     { 0x286, "EOS 600D" },   { 0x285, "EOS 5D Mark III" },
9292     { 0x301, "EOS 650D" },   { 0x302, "EOS 6D" },
9293     { 0x326, "EOS 700D" },   { 0x250, "EOS 7D" },
9294     { 0x393, "EOS 750D" },   { 0x289, "EOS 7D Mark II" },
9295     { 0x347, "EOS 760D" },   { 0x406, "EOS 6D Mark II" },
9296     { 0x405, "EOS 800D" },   { 0x349, "EOS 5D Mark IV" },
9297     { 0x254, "EOS 1000D" },
9298     { 0x288, "EOS 1100D" },
9299     { 0x327, "EOS 1200D" },  { 0x382, "EOS 5DS" },
9300     { 0x404, "EOS 1300D" },  { 0x401, "EOS 5DS R" },
9301     { 0x422, "EOS 1500D" },
9302     { 0x432, "EOS 3000D" },
9303   }, sonique[] = {
9304     { 0x002, "DSC-R1" },     { 0x100, "DSLR-A100" },
9305     { 0x101, "DSLR-A900" },  { 0x102, "DSLR-A700" },
9306     { 0x103, "DSLR-A200" },  { 0x104, "DSLR-A350" },
9307     { 0x105, "DSLR-A300" },  { 0x108, "DSLR-A330" },
9308     { 0x109, "DSLR-A230" },  { 0x10a, "DSLR-A290" },
9309     { 0x10d, "DSLR-A850" },  { 0x111, "DSLR-A550" },
9310     { 0x112, "DSLR-A500" },  { 0x113, "DSLR-A450" },
9311     { 0x116, "NEX-5" },      { 0x117, "NEX-3" },
9312     { 0x118, "SLT-A33" },    { 0x119, "SLT-A55V" },
9313     { 0x11a, "DSLR-A560" },  { 0x11b, "DSLR-A580" },
9314     { 0x11c, "NEX-C3" },     { 0x11d, "SLT-A35" },
9315     { 0x11e, "SLT-A65V" },   { 0x11f, "SLT-A77V" },
9316     { 0x120, "NEX-5N" },     { 0x121, "NEX-7" },
9317     { 0x123, "SLT-A37" },    { 0x124, "SLT-A57" },
9318     { 0x125, "NEX-F3" },     { 0x126, "SLT-A99V" },
9319     { 0x127, "NEX-6" },      { 0x128, "NEX-5R" },
9320     { 0x129, "DSC-RX100" },  { 0x12a, "DSC-RX1" },
9321     { 0x12e, "ILCE-3000" },  { 0x12f, "SLT-A58" },
9322     { 0x131, "NEX-3N" },     { 0x132, "ILCE-7" },
9323     { 0x133, "NEX-5T" },     { 0x134, "DSC-RX100M2" },
9324     { 0x135, "DSC-RX10" },   { 0x136, "DSC-RX1R" },
9325     { 0x137, "ILCE-7R" },    { 0x138, "ILCE-6000" },
9326     { 0x139, "ILCE-5000" },  { 0x13d, "DSC-RX100M3" },
9327     { 0x13e, "ILCE-7S" },    { 0x13f, "ILCA-77M2" },
9328     { 0x153, "ILCE-5100" },  { 0x154, "ILCE-7M2" },
9329     { 0x155, "DSC-RX100M4" },{ 0x156, "DSC-RX10M2" },
9330     { 0x158, "DSC-RX1RM2" }, { 0x15a, "ILCE-QX1" },
9331     { 0x15b, "ILCE-7RM2" },  { 0x15e, "ILCE-7SM2" },
9332     { 0x161, "ILCA-68" },    { 0x162, "ILCA-99M2" },
9333     { 0x163, "DSC-RX10M3" }, { 0x164, "DSC-RX100M5" },
9334     { 0x165, "ILCE-6300" },  { 0x166, "ILCE-9" },
9335     { 0x168, "ILCE-6500" },  { 0x16a, "ILCE-7RM3" },
9336     { 0x16b, "ILCE-7M3" },   { 0x16c, "DSC-RX0" },
9337     { 0x16d, "DSC-RX10M4" },
9338   };
9339   static const char *orig, panalias[][12] = {
9340     "@DC-FZ80", "DC-FZ82", "DC-FZ85",
9341     "@DC-FZ81", "DC-FZ83",
9342     "@DC-GF9", "DC-GX800", "DC-GX850",
9343     "@DC-GF10", "DC-GF90",
9344     "@DC-GX9", "DC-GX7MK3",
9345     "@DC-ZS70", "DC-TZ90", "DC-TZ91", "DC-TZ92", "DC-TZ93",
9346     "@DMC-FZ40", "DMC-FZ45",
9347     "@DMC-FZ2500", "DMC-FZ2000", "DMC-FZH1",
9348     "@DMC-G8", "DMC-G80", "DMC-G81", "DMC-G85",
9349     "@DMC-GX85", "DMC-GX80", "DMC-GX7MK2",
9350     "@DMC-LX9", "DMC-LX10", "DMC-LX15",
9351     "@DMC-ZS40", "DMC-TZ60", "DMC-TZ61",
9352     "@DMC-ZS50", "DMC-TZ70", "DMC-TZ71",
9353     "@DMC-ZS60", "DMC-TZ80", "DMC-TZ81", "DMC-TZ85",
9354     "@DMC-ZS100", "DMC-ZS110", "DMC-TZ100", "DMC-TZ101", "DMC-TZ110", "DMC-TX1",
9355     "@DC-ZS200", "DC-TX2", "DC-TZ200", "DC-TZ202", "DC-TZ220", "DC-ZS220",
9356   };
9357   static const struct {
9358     unsigned fsize;
9359     ushort rw, rh;
9360     uchar lm, tm, rm, bm, lf, cf, max, flags;
9361     char make[10], model[20];
9362     ushort offset;
9363   } table[] = {
9364     {   786432,1024, 768, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-080C" },
9365     {  1447680,1392,1040, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-145C" },
9366     {  1920000,1600,1200, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-201C" },
9367     {  5067304,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-510C" },
9368     {  5067316,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-510C",12 },
9369     { 10134608,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-510C" },
9370     { 10134620,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-510C",12 },
9371     { 16157136,3272,2469, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-810C" },
9372     { 15980544,3264,2448, 0, 0, 0, 0, 8,0x61,0,1,"AgfaPhoto","DC-833m" },
9373     {  9631728,2532,1902, 0, 0, 0, 0,96,0x61,0,0,"Alcatel","5035D" },
9374     {  2868726,1384,1036, 0, 0, 0, 0,64,0x49,0,8,"Baumer","TXG14",1078 },
9375     {  5298000,2400,1766,12,12,44, 2, 8,0x94,0,2,"Canon","PowerShot SD300" },
9376     {  6553440,2664,1968, 4, 4,44, 4, 8,0x94,0,2,"Canon","PowerShot A460" },
9377     {  6573120,2672,1968,12, 8,44, 0, 8,0x94,0,2,"Canon","PowerShot A610" },
9378     {  6653280,2672,1992,10, 6,42, 2, 8,0x94,0,2,"Canon","PowerShot A530" },
9379     {  7710960,2888,2136,44, 8, 4, 0, 8,0x94,0,2,"Canon","PowerShot S3 IS" },
9380     {  9219600,3152,2340,36,12, 4, 0, 8,0x94,0,2,"Canon","PowerShot A620" },
9381     {  9243240,3152,2346,12, 7,44,13, 8,0x49,0,2,"Canon","PowerShot A470" },
9382     { 10341600,3336,2480, 6, 5,32, 3, 8,0x94,0,2,"Canon","PowerShot A720 IS" },
9383     { 10383120,3344,2484,12, 6,44, 6, 8,0x94,0,2,"Canon","PowerShot A630" },
9384     { 12945240,3736,2772,12, 6,52, 6, 8,0x94,0,2,"Canon","PowerShot A640" },
9385     { 15636240,4104,3048,48,12,24,12, 8,0x94,0,2,"Canon","PowerShot A650" },
9386     { 15467760,3720,2772, 6,12,30, 0, 8,0x94,0,2,"Canon","PowerShot SX110 IS" },
9387     { 15534576,3728,2778,12, 9,44, 9, 8,0x94,0,2,"Canon","PowerShot SX120 IS" },
9388     { 18653760,4080,3048,24,12,24,12, 8,0x94,0,2,"Canon","PowerShot SX20 IS" },
9389     { 19131120,4168,3060,92,16, 4, 1, 8,0x94,0,2,"Canon","PowerShot SX220 HS" },
9390     { 21936096,4464,3276,25,10,73,12, 8,0x16,0,2,"Canon","PowerShot SX30 IS" },
9391     { 24724224,4704,3504, 8,16,56, 8, 8,0x94,0,2,"Canon","PowerShot A3300 IS" },
9392     { 30858240,5248,3920, 8,16,56,16, 8,0x94,0,2,"Canon","IXUS 160" },    {  1976352,1632,1211, 0, 2, 0, 1, 0,0x94,0,1,"Casio","QV-2000UX" },
9393     {  3217760,2080,1547, 0, 0,10, 1, 0,0x94,0,1,"Casio","QV-3*00EX" },
9394     {  6218368,2585,1924, 0, 0, 9, 0, 0,0x94,0,1,"Casio","QV-5700" },
9395     {  7816704,2867,2181, 0, 0,34,36, 0,0x16,0,1,"Casio","EX-Z60" },
9396     {  2937856,1621,1208, 0, 0, 1, 0, 0,0x94,7,13,"Casio","EX-S20" },
9397     {  4948608,2090,1578, 0, 0,32,34, 0,0x94,7,1,"Casio","EX-S100" },
9398     {  6054400,2346,1720, 2, 0,32, 0, 0,0x94,7,1,"Casio","QV-R41" },
9399     {  7426656,2568,1928, 0, 0, 0, 0, 0,0x94,0,1,"Casio","EX-P505" },
9400     {  7530816,2602,1929, 0, 0,22, 0, 0,0x94,7,1,"Casio","QV-R51" },
9401     {  7542528,2602,1932, 0, 0,32, 0, 0,0x94,7,1,"Casio","EX-Z50" },
9402     {  7562048,2602,1937, 0, 0,25, 0, 0,0x16,7,1,"Casio","EX-Z500" },
9403     {  7753344,2602,1986, 0, 0,32,26, 0,0x94,7,1,"Casio","EX-Z55" },
9404     {  9313536,2858,2172, 0, 0,14,30, 0,0x94,7,1,"Casio","EX-P600" },
9405     { 10834368,3114,2319, 0, 0,27, 0, 0,0x94,0,1,"Casio","EX-Z750" },
9406     { 10843712,3114,2321, 0, 0,25, 0, 0,0x94,0,1,"Casio","EX-Z75" },
9407     { 10979200,3114,2350, 0, 0,32,32, 0,0x94,7,1,"Casio","EX-P700" },
9408     { 12310144,3285,2498, 0, 0, 6,30, 0,0x94,0,1,"Casio","EX-Z850" },
9409     { 12489984,3328,2502, 0, 0,47,35, 0,0x94,0,1,"Casio","EX-Z8" },
9410     { 15499264,3754,2752, 0, 0,82, 0, 0,0x94,0,1,"Casio","EX-Z1050" },
9411     { 18702336,4096,3044, 0, 0,24, 0,80,0x94,7,1,"Casio","EX-ZR100" },
9412     {  7684000,2260,1700, 0, 0, 0, 0,13,0x94,0,1,"Casio","QV-4000" },
9413     {   787456,1024, 769, 0, 1, 0, 0, 0,0x49,0,0,"Creative","PC-CAM 600" },
9414     { 28829184,4384,3288, 0, 0, 0, 0,36,0x61,0,0,"DJI" },
9415     { 15151104,4608,3288, 0, 0, 0, 0, 0,0x94,0,0,"Matrix" },
9416     {  3840000,1600,1200, 0, 0, 0, 0,65,0x49,0,0,"Foculus","531C" },
9417     {   307200, 640, 480, 0, 0, 0, 0, 0,0x94,0,0,"Generic" },
9418     {    62464, 256, 244, 1, 1, 6, 1, 0,0x8d,0,0,"Kodak","DC20" },
9419     {   124928, 512, 244, 1, 1,10, 1, 0,0x8d,0,0,"Kodak","DC20" },
9420     {  1652736,1536,1076, 0,52, 0, 0, 0,0x61,0,0,"Kodak","DCS200" },
9421     {  4159302,2338,1779, 1,33, 1, 2, 0,0x94,0,0,"Kodak","C330" },
9422     {  4162462,2338,1779, 1,33, 1, 2, 0,0x94,0,0,"Kodak","C330",3160 },
9423     {  2247168,1232, 912, 0, 0,16, 0, 0,0x00,0,0,"Kodak","C330" },
9424     {  3370752,1232, 912, 0, 0,16, 0, 0,0x00,0,0,"Kodak","C330" },
9425     {  6163328,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,"Kodak","C603" },
9426     {  6166488,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,"Kodak","C603",3160 },
9427     {   460800, 640, 480, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","C603" },
9428     {  9116448,2848,2134, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","C603" },
9429     { 12241200,4040,3030, 2, 0, 0,13, 0,0x49,0,0,"Kodak","12MP" },
9430     { 12272756,4040,3030, 2, 0, 0,13, 0,0x49,0,0,"Kodak","12MP",31556 },
9431     { 18000000,4000,3000, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","12MP" },
9432     {   614400, 640, 480, 0, 3, 0, 0,64,0x94,0,0,"Kodak","KAI-0340" },
9433     { 15360000,3200,2400, 0, 0, 0, 0,96,0x16,0,0,"Lenovo","A820" },
9434     {  3884928,1608,1207, 0, 0, 0, 0,96,0x16,0,0,"Micron","2010",3212 },
9435     {  1138688,1534, 986, 0, 0, 0, 0, 0,0x61,0,0,"Minolta","RD175",513 },
9436     {  1581060,1305, 969, 0, 0,18, 6, 6,0x1e,4,1,"Nikon","E900" },
9437     {  2465792,1638,1204, 0, 0,22, 1, 6,0x4b,5,1,"Nikon","E950" },
9438     {  2940928,1616,1213, 0, 0, 0, 7,30,0x94,0,1,"Nikon","E2100" },
9439     {  4771840,2064,1541, 0, 0, 0, 1, 6,0xe1,0,1,"Nikon","E990" },
9440     {  4775936,2064,1542, 0, 0, 0, 0,30,0x94,0,1,"Nikon","E3700" },
9441     {  5865472,2288,1709, 0, 0, 0, 1, 6,0xb4,0,1,"Nikon","E4500" },
9442     {  5869568,2288,1710, 0, 0, 0, 0, 6,0x16,0,1,"Nikon","E4300" },
9443     {  7438336,2576,1925, 0, 0, 0, 1, 6,0xb4,0,1,"Nikon","E5000" },
9444     {  8998912,2832,2118, 0, 0, 0, 0,30,0x94,7,1,"Nikon","COOLPIX S6" },
9445     {  5939200,2304,1718, 0, 0, 0, 0,30,0x16,0,0,"Olympus","C770UZ" },
9446     {  3178560,2064,1540, 0, 0, 0, 0, 0,0x94,0,1,"Pentax","Optio S" },
9447     {  4841984,2090,1544, 0, 0,22, 0, 0,0x94,7,1,"Pentax","Optio S" },
9448     {  6114240,2346,1737, 0, 0,22, 0, 0,0x94,7,1,"Pentax","Optio S4" },
9449     { 10702848,3072,2322, 0, 0, 0,21,30,0x94,0,1,"Pentax","Optio 750Z" },
9450     {  4147200,1920,1080, 0, 0, 0, 0, 0,0x49,0,0,"Photron","BC2-HD" },
9451     {  4151666,1920,1080, 0, 0, 0, 0, 0,0x49,0,0,"Photron","BC2-HD",8 },
9452     { 13248000,2208,3000, 0, 0, 0, 0,13,0x61,0,0,"Pixelink","A782" },
9453     {  6291456,2048,1536, 0, 0, 0, 0,96,0x61,0,0,"RoverShot","3320AF" },
9454     {   311696, 644, 484, 0, 0, 0, 0, 0,0x16,0,8,"ST Micro","STV680 VGA" },
9455     { 16098048,3288,2448, 0, 0,24, 0, 9,0x94,0,1,"Samsung","S85" },
9456     { 16215552,3312,2448, 0, 0,48, 0, 9,0x94,0,1,"Samsung","S85" },
9457     { 20487168,3648,2808, 0, 0, 0, 0,13,0x94,5,1,"Samsung","WB550" },
9458     { 24000000,4000,3000, 0, 0, 0, 0,13,0x94,5,1,"Samsung","WB550" },
9459     { 12582980,3072,2048, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 },
9460     { 33292868,4080,4080, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 },
9461     { 44390468,4080,5440, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 },
9462     {  1409024,1376,1024, 0, 0, 1, 0, 0,0x49,0,0,"Sony","XCD-SX910CR" },
9463     {  2818048,1376,1024, 0, 0, 1, 0,97,0x49,0,0,"Sony","XCD-SX910CR" },
9464     { 17496000,4320,3240, 0, 0, 0,0,224,0x94,0,0,"Xiro","Xplorer V" },
9465   };
9466   static const char *corp[] =
9467     { "AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm",
9468       "Mamiya", "Minolta", "Motorola", "Kodak", "Konica", "Leica",
9469       "Nikon", "Nokia", "Olympus", "Ricoh", "Pentax", "Phase One",
9470       "Samsung", "Sigma", "Sinar", "Sony", "YI" };
9471   char head[32], *cp;
9472   int hlen, flen, fsize, zero_fsize=1, i, c;
9473   struct jhead jh;
9474 
9475   tiff_flip = flip = filters = UINT_MAX;	/* unknown */
9476   raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0;
9477   maximum = height = width = top_margin = left_margin = 0;
9478   cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = model3[0] = 0;
9479   iso_speed = shutter = aperture = focal_len = unique_id = 0;
9480   tiff_nifds = 0;
9481   memset (tiff_ifd, 0, sizeof tiff_ifd);
9482   memset (gpsdata, 0, sizeof gpsdata);
9483   memset (cblack, 0, sizeof cblack);
9484   memset (white, 0, sizeof white);
9485   memset (mask, 0, sizeof mask);
9486   thumb_offset = thumb_length = thumb_width = thumb_height = 0;
9487   load_raw = thumb_load_raw = 0;
9488   write_thumb = &CLASS jpeg_thumb;
9489   data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0;
9490   kodak_cbpp = zero_after_ff = dng_version = load_flags = 0;
9491   timestamp = shot_order = tiff_samples = black = is_foveon = 0;
9492   mix_green = profile_length = data_error = zero_is_bad = 0;
9493   pixel_aspect = is_raw = raw_color = 1;
9494   tile_width = tile_length = 0;
9495   for (i=0; i < 4; i++) {
9496     cam_mul[i] = i == 1;
9497     pre_mul[i] = i < 3;
9498     FORC3 cmatrix[c][i] = 0;
9499     FORC3 rgb_cam[c][i] = c == i;
9500   }
9501   colors = 3;
9502   for (i=0; i < 0x10000; i++) curve[i] = i;
9503 
9504   flen = fsize = ifp->size;
9505 
9506   // currently fsize is of type signed int which means for files larger than 0x7fffffff byte fsize will be < 0. We need to check for large files if we change the type to unsigned int
9507   /*RT*/ if (fsize<100000) {
9508         is_raw = 0;
9509         return;
9510   }
9511 
9512   order = get2();
9513   hlen = get4();
9514   fseek (ifp, 0, SEEK_SET);
9515   fread (head, 1, 32, ifp);
9516   /* RT: changed string constant */
9517   if ((cp = (char *) memmem (head, 32, "MMMM", 4)) ||
9518     (cp = (char *) memmem (head, 32, "IIII", 4))) {
9519     parse_phase_one (cp-head);
9520     if (cp-head && parse_tiff(0)) apply_tiff();
9521   } else if (order == 0x4949 || order == 0x4d4d) {
9522     if (!memcmp (head+6,"HEAPCCDR",8)) {
9523       data_offset = hlen;
9524 /*RT*/      ciff_base = hlen;
9525 /*RT*/      ciff_len = fsize - hlen;
9526       parse_ciff (hlen, flen-hlen, 0);
9527       load_raw = &CLASS canon_load_raw;
9528     } else if (parse_tiff(0)) apply_tiff();
9529   } else if (!memcmp (head,"\xff\xd8\xff\xe1",4) &&
9530 	     !memcmp (head+6,"Exif",4)) {
9531     fseek (ifp, 4, SEEK_SET);
9532     data_offset = 4 + get2();
9533     fseek (ifp, data_offset, SEEK_SET);
9534     if (fgetc(ifp) != 0xff)
9535       parse_tiff(12);
9536     thumb_offset = 0;
9537   } else if (!memcmp (head+25,"ARECOYK",7)) {
9538     strcpy (make, "Contax");
9539     strcpy (model,"N Digital");
9540     fseek (ifp, 33, SEEK_SET);
9541     get_timestamp(1);
9542     fseek (ifp, 60, SEEK_SET);
9543     FORC4 cam_mul[c ^ (c >> 1)] = get4();
9544   } else if (!strcmp (head, "PXN")) {
9545     strcpy (make, "Logitech");
9546     strcpy (model,"Fotoman Pixtura");
9547   } else if (!strcmp (head, "qktk")) {
9548     strcpy (make, "Apple");
9549     strcpy (model,"QuickTake 100");
9550     load_raw = &CLASS quicktake_100_load_raw;
9551   } else if (!strcmp (head, "qktn")) {
9552     strcpy (make, "Apple");
9553     strcpy (model,"QuickTake 150");
9554     load_raw = &CLASS kodak_radc_load_raw;
9555   } else if (!memcmp (head,"FUJIFILM",8)) {
9556     fseek (ifp, 84, SEEK_SET);
9557     thumb_offset = get4();
9558     thumb_length = get4();
9559     fseek (ifp, 92, SEEK_SET);
9560     parse_fuji (get4());
9561     if (thumb_offset > 120) {
9562       fseek (ifp, 120, SEEK_SET);
9563       is_raw += (i = get4()) != 0 ? 1 : 0;
9564       if (is_raw == 2 && shot_select)
9565 	parse_fuji (i);
9566     }
9567     fseek (ifp, 100+28*(shot_select > 0 && shot_select < is_raw), SEEK_SET);
9568     parse_tiff (data_offset = get4());
9569     parse_tiff (thumb_offset+12);
9570 /*RT*/    exif_base = thumb_offset+12;
9571     apply_tiff();
9572     if (!strcmp(model, "X-T3")) {
9573         height = raw_height - 2;
9574     } else if (!strcmp(model, "GFX 100")) {
9575         load_flags = 0;
9576     }
9577     if (!load_raw) {
9578       load_raw = &CLASS unpacked_load_raw;
9579       tiff_bps = 14;
9580     }
9581   } else if (!memcmp (head,"RIFF",4)) {
9582     fseek (ifp, 0, SEEK_SET);
9583     parse_riff();
9584   } else if (!memcmp (head+4,"ftypqt   ",9)) {
9585     fseek (ifp, 0, SEEK_SET);
9586     parse_qt (fsize);
9587     is_raw = 0;
9588   } else if (!memcmp (head,"\0\001\0\001\0@",6)) {
9589     fseek (ifp, 6, SEEK_SET);
9590     fread (make, 1, 8, ifp);
9591     fread (model, 1, 8, ifp);
9592     fread (model2, 1, 16, ifp);
9593     data_offset = get2();
9594     get2();
9595     raw_width = get2();
9596     raw_height = get2();
9597     load_raw = &CLASS nokia_load_raw;
9598     filters = 0x61616161;
9599   } else if (!memcmp (head,"NOKIARAW",8)) {
9600     strcpy (make, "NOKIA");
9601     order = 0x4949;
9602     fseek (ifp, 300, SEEK_SET);
9603     data_offset = get4();
9604     i = get4();
9605     width = get2();
9606     height = get2();
9607     switch (tiff_bps = i*8 / (width * height)) {
9608       case  8: load_raw = &CLASS eight_bit_load_raw;  break;
9609       case 10: load_raw = &CLASS nokia_load_raw;
9610     }
9611     raw_height = height + (top_margin = i / (width * tiff_bps/8) - height);
9612     mask[0][3] = 1;
9613     filters = 0x61616161;
9614   } else if (!memcmp (head,"ARRI",4)) {
9615     order = 0x4949;
9616     fseek (ifp, 20, SEEK_SET);
9617     width = get4();
9618     height = get4();
9619     strcpy (make, "ARRI");
9620     fseek (ifp, 668, SEEK_SET);
9621     fread (model, 1, 64, ifp);
9622     data_offset = 4096;
9623     load_raw = &CLASS packed_load_raw;
9624     load_flags = 88;
9625     filters = 0x61616161;
9626   } else if (!memcmp (head,"XPDS",4)) {
9627     order = 0x4949;
9628     fseek (ifp, 0x800, SEEK_SET);
9629     fread (make, 1, 41, ifp);
9630     raw_height = get2();
9631     raw_width  = get2();
9632     fseek (ifp, 56, SEEK_CUR);
9633     fread (model, 1, 30, ifp);
9634     data_offset = 0x10000;
9635     load_raw = &CLASS canon_rmf_load_raw;
9636     gamma_curve (0, 12.25, 1, 1023);
9637   } else if (!memcmp (head+4,"RED1",4)) {
9638     strcpy (make, "Red");
9639     strcpy (model,"One");
9640     parse_redcine();
9641     load_raw = &CLASS redcine_load_raw;
9642     gamma_curve (1/2.4, 12.92310, 1, 4095);
9643     filters = 0x49494949;
9644   } else if (!memcmp (head,"DSC-Image",9))
9645     parse_rollei();
9646   else if (!memcmp (head,"PWAD",4))
9647     parse_sinar_ia();
9648   else if (!memcmp (head,"\0MRM",4))
9649     parse_minolta(0);
9650   else if (!memcmp (head,"FOVb",4))
9651     parse_foveon();
9652   else if (!memcmp (head,"CI",2))
9653     parse_cine();
9654   //---  RT  ----------------------------------------------------------------
9655   else if (!memcmp(head + 4, "ftypcrx ", 8)) {
9656     parse_canon_cr3();
9657   }
9658   //-------------------------------------------------------------------------
9659   if (make[0] == 0)
9660     for (zero_fsize=i=0; i < sizeof table / sizeof *table; i++)
9661       if (fsize == table[i].fsize) {
9662 	strcpy (make,  table[i].make );
9663 	strcpy (model, table[i].model);
9664 	flip = table[i].flags >> 2;
9665 	zero_is_bad = table[i].flags & 2;
9666 	if (table[i].flags & 1)
9667 	  parse_external_jpeg();
9668 	data_offset = table[i].offset;
9669 	raw_width   = table[i].rw;
9670 	raw_height  = table[i].rh;
9671 	left_margin = table[i].lm;
9672 	 top_margin = table[i].tm;
9673 	width  = raw_width - left_margin - table[i].rm;
9674 	height = raw_height - top_margin - table[i].bm;
9675 	filters = 0x1010101 * table[i].cf;
9676 	colors = 4 - !((filters & filters >> 1) & 0x5555);
9677 	load_flags = table[i].lf;
9678 	switch (tiff_bps = (fsize-data_offset)*8 / (raw_width*raw_height)) {
9679 	  case 6:
9680 	    load_raw = &CLASS minolta_rd175_load_raw;  break;
9681 	  case 8:
9682 	    load_raw = &CLASS eight_bit_load_raw;  break;
9683 	  case 10: case 12:
9684 	    load_flags |= 512;
9685 	    if (!strcmp(make,"Canon")) load_flags |= 256;
9686 	    load_raw = &CLASS packed_load_raw;     break;
9687 	  case 16:
9688 	    order = 0x4949 | 0x404 * (load_flags & 1);
9689 	    tiff_bps -= load_flags >> 4;
9690 	    tiff_bps -= load_flags = load_flags >> 1 & 7;
9691 	    load_raw = &CLASS unpacked_load_raw;
9692 	}
9693 	maximum = (1 << tiff_bps) - (1 << table[i].max);
9694       }
9695   if (zero_fsize) fsize = 0;
9696   if (make[0] == 0) parse_smal (0, flen);
9697   if (make[0] == 0) {
9698     parse_jpeg(0);
9699     //RT fix for the use of fseek below
9700     if (!(strncmp(model,"ov",2) && strncmp(model,"RP_OV",5))) {
9701       fseek (ifp, -6404096, SEEK_END);
9702       if (fread (head, 1, 32, ifp) && !strcmp(head,"BRCMn")) {
9703       strcpy (make, "OmniVision");
9704       data_offset = ftell(ifp) + 0x8000-32;
9705       width = raw_width;
9706       raw_width = 2611;
9707       load_raw = &CLASS nokia_load_raw;
9708       filters = 0x16161616;
9709     } else is_raw = 0;
9710   }
9711   }
9712 
9713   for (i=0; i < sizeof corp / sizeof *corp; i++)
9714     if (strcasestr (make, corp[i]))	/* Simplify company names */
9715 	    strcpy (make, corp[i]);
9716   if ((!strcmp(make,"Kodak") || !strcmp(make,"Leica")) &&
9717 	((cp = strcasestr(model," DIGITAL CAMERA")) ||
9718 	 (cp = strstr(model,"FILE VERSION"))))
9719      *cp = 0;
9720   if (!strncasecmp(model,"PENTAX",6))
9721     strcpy (make, "Pentax");
9722   cp = make + strlen(make);		/* Remove trailing spaces */
9723   while (*--cp == ' ') *cp = 0;
9724   cp = model + strlen(model);
9725   while (*--cp == ' ') *cp = 0;
9726   i = strlen(make);			/* Remove make from model */
9727   if (!strncasecmp (model, make, i) && model[i++] == ' ')
9728     memmove (model, model+i, 64-i);
9729   if (!strncmp (model,"FinePix ",8))
9730     strcpy (model, model+8);
9731   if (!strncmp (model,"Digital Camera ",15))
9732     strcpy (model, model+15);
9733   desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0;
9734   if (!is_raw) goto notraw;
9735 
9736   if (!height) height = raw_height;
9737   if (!width)  width  = raw_width;
9738   if (height == 2624 && width == 3936)	/* Pentax K10D and Samsung GX10 */
9739     { height  = 2616;   width  = 3896; }
9740   if (height == 3136 && width == 4864)  /* Pentax K20D and Samsung GX20 */
9741     { height  = 3124;   width  = 4688; filters = 0x16161616; }
9742   if (raw_height == 2868 && (!strcmp(model,"K-r") || !strcmp(model,"K-x")))
9743 /*RT*/   {			width  = 4308; filters = 0x16161616; }
9744   if (raw_height == 3136 && !strcmp(model,"K-7"))
9745     { height  = 3122;   width  = 4684; filters = 0x16161616; top_margin = 2; }
9746   if (raw_height == 3284 && !strncmp(model,"K-5",3))
9747     { left_margin = 10; width  = 4950; filters = 0x16161616; }
9748   if (raw_height == 3300 && !strncmp(model,"K-50",4))
9749     { height  = 3288,   width  = 4952;  left_margin = 0;  top_margin = 12; }
9750   if (raw_height == 3664 && !strncmp(model,"K-S",3))
9751     {			width  = 5492;  left_margin = 0; }
9752   if (raw_height == 4032 && !strcmp(model,"K-3"))
9753     { height  = 4032;   width  = 6040;  left_margin = 4; }
9754   if (raw_height == 4060 && !strcmp(model,"KP"))
9755     { height  = 4032;   width  = 6032;  left_margin = 52; top_margin = 28; }
9756   if (raw_height == 4950 && !strcmp(model,"K-1"))
9757     { height  = 4932;   width  = 7380;  left_margin = 4;  top_margin = 18; }
9758   if (raw_height == 5552 && !strcmp(model,"645D"))
9759     { height  = 5502;   width  = 7328;  left_margin = 48; top_margin = 29;
9760       filters = 0x61616161; }
9761   if (width == 7392 && !strncmp(model,"K-1",3))
9762     { left_margin = 6; width  = 7376; if(!dng_version) {top_margin = 18; height -= top_margin; }}
9763   if (width == 4832 && !strncmp(model,"K-1",3)) // K-1 APS-C format
9764      if(!dng_version) {top_margin = 18; height -= top_margin; }
9765   if (height == 3014 && width == 4096)	/* Ricoh GX200 */
9766 			width  = 4014;
9767   if (dng_version) {
9768     if (filters == UINT_MAX) filters = 0;
9769     if (filters) is_raw *= tiff_samples;
9770     else	 colors  = tiff_samples;
9771     switch (tiff_compress) {
9772       case 0:
9773       case 1:     load_raw = &CLASS   packed_dng_load_raw;  break;
9774       case 7:     load_raw = (!strncmp(make,"Blackmagic",10) || !strncmp(make,"Canon",5)) ? &CLASS lossless_dnglj92_load_raw : &CLASS lossless_dng_load_raw;  break;
9775       case 8:     load_raw = &CLASS  deflate_dng_load_raw;  break;
9776       case 34892: load_raw = &CLASS    lossy_dng_load_raw;  break;
9777       default:    load_raw = 0;
9778     }
9779     goto dng_skip;
9780   }
9781   if (!strcmp(make,"Canon") && !fsize && tiff_bps != 15) {
9782     if (!load_raw)
9783       load_raw = &CLASS lossless_jpeg_load_raw;
9784     for (i=0; i < sizeof canon / sizeof *canon; i++)
9785       if (raw_width == canon[i][0] && raw_height == canon[i][1]) {
9786 	width  = raw_width - (left_margin = canon[i][2]);
9787 	height = raw_height - (top_margin = canon[i][3]);
9788 	width  -= canon[i][4];
9789 	height -= canon[i][5];
9790 	mask[0][1] =  canon[i][6];
9791 	mask[0][3] = -canon[i][7];
9792 	mask[1][1] =  canon[i][8];
9793 	mask[1][3] = -canon[i][9];
9794 	if (canon[i][10]) filters = canon[i][10] * 0x01010101;
9795       }
9796     if ((unique_id | 0x20000) == 0x2720000) {
9797       left_margin = 8;
9798       top_margin = 16;
9799     }
9800   }
9801   for (i=0; i < sizeof unique / sizeof *unique; i++)
9802     if (unique_id == 0x80000000 + unique[i].id) {
9803       adobe_coeff ("Canon", unique[i].model);
9804       if (model[4] == 'K' && strlen(model) == 8)
9805 	strcpy (model, unique[i].model);
9806     }
9807   for (i=0; i < sizeof sonique / sizeof *sonique; i++)
9808     if (unique_id == sonique[i].id)
9809       strcpy (model, sonique[i].model);
9810   for (i=0; i < sizeof panalias / sizeof *panalias; i++)
9811     if (panalias[i][0] == '@') orig = panalias[i]+1;
9812     else if (!strcmp(model,panalias[i]))
9813       adobe_coeff ("Panasonic", orig);
9814   if (!strcmp(make,"Nikon")) {
9815     if (!load_raw)
9816       load_raw = &CLASS packed_load_raw;
9817     if (model[0] == 'E')
9818       load_flags |= !data_offset << 2 | 2;
9819   }
9820 
9821 /* Set parameters based on camera name (for non-DNG files). */
9822 
9823   if (!strcmp(model,"KAI-0340")
9824 	&& find_green (16, 16, 3840, 5120) < 25) {
9825     height = 480;
9826     top_margin = filters = 0;
9827     strcpy (model,"C603");
9828   }
9829   if (!strcmp(make,"Sony") && raw_width > 3888)
9830     black = 128 << (tiff_bps - 12);
9831   if (is_foveon) {
9832     if (height*2 < width) pixel_aspect = 0.5;
9833     if (height   > width) pixel_aspect = 2;
9834     filters = 0;
9835     simple_coeff(0);
9836    	adobe_coeff (make, model);
9837   } else if (!strcmp(make,"Canon") && tiff_bps == 15) { // Canon mRaw/sRaw
9838     switch (width) {
9839       case 3344: width -= 66;
9840       case 3872: width -= 6;
9841     }
9842     if (height > width) {
9843       SWAP(height,width);
9844       SWAP(raw_height,raw_width);
9845     }
9846 
9847     if(std::fabs(static_cast<float>(width) / height - 1.5f) > 0.02f) {
9848         // wrong image dimensions. Calculate correct dimensions. width / height should be close to 1.5
9849         std::vector<std::pair<float, int>> dimensions;
9850 
9851         int size = width * height;
9852         int newHeight = sqrt(size / 1.48f);
9853         while (--newHeight && std::fabs(static_cast<float>(size) / (newHeight * newHeight) - 1.5f) <= 0.02f) {
9854             if(size % newHeight == 0) {
9855                 dimensions.emplace_back(std::fabs(static_cast<float>(size) / (newHeight * newHeight) - 1.5f), newHeight);
9856             }
9857         }
9858         // find ratio closest to 1.5
9859         float val = 1.f;
9860         while(!dimensions.empty()) {
9861             if(dimensions.back().first < val) {
9862                 raw_height = height = dimensions.back().second;
9863                 raw_width = width = size / raw_height;
9864             }
9865             dimensions.pop_back();
9866         }
9867     }
9868     filters = 0;
9869     tiff_samples = colors = 3;
9870     load_raw = &CLASS canon_sraw_load_raw;
9871     FORC4 cblack[c] = 0; // ALB
9872   } else if (!strcmp(model,"PowerShot 600")) {
9873     height = 613;
9874     width  = 854;
9875     raw_width = 896;
9876     colors = 4;
9877     filters = 0xe1e4e1e4;
9878     load_raw = &CLASS canon_600_load_raw;
9879   } else if (!strcmp(model,"PowerShot A5") ||
9880 	     !strcmp(model,"PowerShot A5 Zoom")) {
9881     height = 773;
9882     width  = 960;
9883     raw_width = 992;
9884     pixel_aspect = 256/235.0;
9885     filters = 0x1e4e1e4e;
9886     goto canon_a5;
9887   } else if (!strcmp(model,"PowerShot A50")) {
9888     height =  968;
9889     width  = 1290;
9890     raw_width = 1320;
9891     filters = 0x1b4e4b1e;
9892     goto canon_a5;
9893   } else if (!strcmp(model,"PowerShot Pro70")) {
9894     height = 1024;
9895     width  = 1552;
9896     filters = 0x1e4b4e1b;
9897 canon_a5:
9898     colors = 4;
9899     tiff_bps = 10;
9900     load_raw = &CLASS packed_load_raw;
9901     load_flags = 264;
9902   } else if (!strcmp(model,"PowerShot Pro90 IS") ||
9903 	     !strcmp(model,"PowerShot G1")) {
9904     colors = 4;
9905     filters = 0xb4b4b4b4;
9906   } else if (!strcmp(model,"PowerShot A610")) {
9907     if (canon_s2is()) strcpy (model+10, "S2 IS");
9908   } else if (!strcmp(model,"PowerShot SX220 HS")) {
9909     mask[1][3] = -4;
9910   } else if (!strcmp(model,"EOS D2000C")) {
9911     filters = 0x61616161;
9912     black = curve[200];
9913   } else if (!strcmp(model,"EOS 80D")) {
9914     top_margin -= 2;
9915     height += 2;
9916   } else if (!strcmp(model,"D1")) {
9917     cam_mul[0] *= 256/527.0;
9918     cam_mul[2] *= 256/317.0;
9919   } else if (!strcmp(model,"D1X")) {
9920     width -= 4;
9921     pixel_aspect = 0.5;
9922   } else if (!strcmp(model,"D40X") ||
9923 	     !strcmp(model,"D60")  ||
9924 	     !strcmp(model,"D80")  ||
9925 	     !strcmp(model,"D3000")) {
9926     height -= 3;
9927     width  -= 4;
9928   } else if (!strcmp(model,"D3")   ||
9929 	     !strcmp(model,"D3S")  ||
9930 	     !strcmp(model,"D700")) {
9931     width -= 4;
9932     left_margin = 2;
9933   } else if (!strcmp(model,"D3100")) {
9934     width -= 28;
9935     left_margin = 6;
9936   } else if (!strcmp(model,"D5000") ||
9937 	     !strcmp(model,"D90")) {
9938     width -= 42;
9939   } else if (!strcmp(model,"D5100") ||
9940 	     !strcmp(model,"D7000") ||
9941 	     !strcmp(model,"COOLPIX A")) {
9942     width -= 44;
9943   } else if (!strcmp(model,"D3200") ||
9944 	    !strncmp(model,"D6",2)  ||
9945 	    !strncmp(model,"D800",4)) {
9946     width -= 46;
9947   } else if (!strcmp(model,"D4") ||
9948 	     !strcmp(model,"Df")) {
9949     width -= 52;
9950     left_margin = 2;
9951   } else if (!strncmp(model,"D40",3) ||
9952 	     !strncmp(model,"D50",3) ||
9953 	     !strncmp(model,"D70",3)) {
9954     width--;
9955   } else if (!strcmp(model,"D100")) {
9956     if (load_flags)
9957       raw_width = (width += 3) + 3;
9958   } else if (!strcmp(model,"D200")) {
9959     left_margin = 1;
9960     width -= 4;
9961     filters = 0x94949494;
9962   } else if (!strncmp(model,"D2H",3)) {
9963     left_margin = 6;
9964     width -= 14;
9965   } else if (!strncmp(model,"D2X",3)) {
9966     if (width == 3264) width -= 32;
9967     else width -= 8;
9968   } else if (!strncmp(model,"D300",4)) {
9969     width -= 32;
9970   } else if (!strncmp(model,"COOLPIX B",9)) {
9971     load_flags = 24;
9972   } else if (!strncmp(model,"COOLPIX P",9) && raw_width != 4032) {
9973     load_flags = 24;
9974     filters = 0x94949494;
9975     if (model[9] == '7' && iso_speed >= 400)
9976       black = 255;
9977   } else if (!strncmp(model,"1 ",2)) {
9978     height -= 2;
9979   } else if (fsize == 1581060) {
9980     simple_coeff(3);
9981     pre_mul[0] = 1.2085;
9982     pre_mul[1] = 1.0943;
9983     pre_mul[3] = 1.1103;
9984   } else if (fsize == 3178560) {
9985     cam_mul[0] *= 4;
9986     cam_mul[2] *= 4;
9987   } else if (fsize == 4771840) {
9988     if (!timestamp && nikon_e995())
9989       strcpy (model, "E995");
9990     if (strcmp(model,"E995")) {
9991       filters = 0xb4b4b4b4;
9992       simple_coeff(3);
9993       pre_mul[0] = 1.196;
9994       pre_mul[1] = 1.246;
9995       pre_mul[2] = 1.018;
9996     }
9997   } else if (fsize == 2940928) {
9998     if (!timestamp && !nikon_e2100())
9999       strcpy (model,"E2500");
10000     if (!strcmp(model,"E2500")) {
10001       height -= 2;
10002       load_flags = 6;
10003       colors = 4;
10004       filters = 0x4b4b4b4b;
10005     }
10006   } else if (fsize == 4775936) {
10007     if (!timestamp) nikon_3700();
10008     if (model[0] == 'E' && atoi(model+1) < 3700)
10009       filters = 0x49494949;
10010     if (!strcmp(model,"Optio 33WR")) {
10011       flip = 1;
10012       filters = 0x16161616;
10013     }
10014     if (make[0] == 'O') {
10015       i = find_green (12, 32, 1188864, 3576832);
10016       c = find_green (12, 32, 2383920, 2387016);
10017       if (abs(i) < abs(c)) {
10018 	SWAP(i,c);
10019 	load_flags = 24;
10020       }
10021       if (i < 0) filters = 0x61616161;
10022     }
10023   } else if (fsize == 5869568) {
10024     if (!timestamp && minolta_z2()) {
10025       strcpy (make, "Minolta");
10026       strcpy (model,"DiMAGE Z2");
10027     }
10028     load_flags = 6 + 24*(make[0] == 'M');
10029   } else if (fsize == 6291456) {
10030     fseek (ifp, 0x300000, SEEK_SET);
10031     if ((order = guess_byte_order(0x10000)) == 0x4d4d) {
10032       height -= (top_margin = 16);
10033       width -= (left_margin = 28);
10034       maximum = 0xf5c0;
10035       strcpy (make, "ISG");
10036       model[0] = 0;
10037     }
10038   } else if (!strcmp(make,"Fujifilm")) {
10039     if (!strcmp(model+7,"S2Pro")) {
10040       strcpy (model,"S2Pro");
10041       height = 2144;
10042       width  = 2880;
10043       flip = 6;
10044     }
10045     if (!strncmp(model,"X-A10",5)) {
10046         width = raw_width = 4912;
10047         height = raw_height = 3278;
10048     } else if (!strncmp(model, "X-A3", 4) || !strncmp(model, "X-A5", 4)) {
10049         width = raw_width = 6016;
10050         height = raw_height = 4014;
10051     }
10052     top_margin = (raw_height - height) >> 2 << 1;
10053     left_margin = (raw_width - width ) >> 2 << 1;
10054     if (width == 2848 || width == 3664) filters = 0x16161616;
10055     if (width == 4032 || width == 4952 || width == 6032 || width == 8280) left_margin = 0;
10056     if (width == 3328 && (width -= 66)) left_margin = 34;
10057     if (width == 4936) left_margin = 4;
10058     if (!strcmp(model,"HS50EXR") ||
10059 	!strcmp(model,"F900EXR")) {
10060       width += 2;
10061       left_margin = 0;
10062       filters = 0x16161616;
10063     }
10064     if (fuji_layout) raw_width *= is_raw;
10065     if (filters == 9)
10066       FORC(36) ((int *)xtrans)[c] =
10067 	xtrans_abs[(c/6+top_margin) % 6][(c+left_margin) % 6];
10068   } else if (!strcmp(model,"KD-400Z")) {
10069     height = 1712;
10070     width  = 2312;
10071     raw_width = 2336;
10072     goto konica_400z;
10073   } else if (!strcmp(model,"KD-510Z")) {
10074     goto konica_510z;
10075   } else if (!strcasecmp(make,"Minolta")) {
10076     if (!load_raw && (maximum = 0xfff))
10077       load_raw = &CLASS unpacked_load_raw;
10078     if (!strncmp(model,"DiMAGE A",8)) {
10079       if (!strcmp(model,"DiMAGE A200"))
10080 	filters = 0x49494949;
10081       tiff_bps = 12;
10082       load_raw = &CLASS packed_load_raw;
10083     } else if (!strncmp(model,"ALPHA",5) ||
10084 	       !strncmp(model,"DYNAX",5) ||
10085 	       !strncmp(model,"MAXXUM",6)) {
10086       sprintf (model+20, "DYNAX %-10s", model+6+(model[0]=='M'));
10087       adobe_coeff (make, model+20);
10088       load_raw = &CLASS packed_load_raw;
10089     } else if (!strncmp(model,"DiMAGE G",8)) {
10090       if (model[8] == '4') {
10091 	height = 1716;
10092 	width  = 2304;
10093       } else if (model[8] == '5') {
10094 konica_510z:
10095 	height = 1956;
10096 	width  = 2607;
10097 	raw_width = 2624;
10098       } else if (model[8] == '6') {
10099 	height = 2136;
10100 	width  = 2848;
10101       }
10102       data_offset += 14;
10103       filters = 0x61616161;
10104 konica_400z:
10105       load_raw = &CLASS unpacked_load_raw;
10106       maximum = 0x3df;
10107       order = 0x4d4d;
10108     }
10109   } else if (!strcmp(model,"*ist D")) {
10110     load_raw = &CLASS unpacked_load_raw;
10111     data_error = -1;
10112   } else if (!strcmp(model,"*ist DS")) {
10113     height -= 2;
10114   } else if (!strcmp(make,"Samsung") && raw_width == 4704) {
10115     height -= top_margin = 8;
10116     width -= 2 * (left_margin = 8);
10117     load_flags = 256;
10118   } else if (!strcmp(make,"Samsung") && raw_height == 3714) {
10119     height -= top_margin = 18;
10120     left_margin = raw_width - (width = 5536);
10121     if (raw_width != 5600)
10122       left_margin = top_margin = 0;
10123     filters = 0x61616161;
10124     colors = 3;
10125   } else if (!strcmp(make,"Samsung") && raw_width == 5632) {
10126     order = 0x4949;
10127     height = 3694;
10128     top_margin = 2;
10129     width  = 5574 - (left_margin = 32 + tiff_bps);
10130     if (tiff_bps == 12) load_flags = 80;
10131   } else if (!strcmp(make,"Samsung") && raw_width == 5664) {
10132     height -= top_margin = 17;
10133     left_margin = 96;
10134     width = 5544;
10135     filters = 0x49494949;
10136   } else if (!strcmp(make,"Samsung") && raw_width == 6496) {
10137     filters = 0x61616161;
10138     black = 1 << (tiff_bps - 7);
10139   } else if (!strcmp(model,"EX1")) {
10140     order = 0x4949;
10141     height -= 20;
10142     top_margin = 2;
10143     if ((width -= 6) > 3682) {
10144       height -= 10;
10145       width  -= 46;
10146       top_margin = 8;
10147     }
10148   } else if (!strcmp(model,"WB2000")) {
10149     order = 0x4949;
10150     height -= 3;
10151     top_margin = 2;
10152     if ((width -= 10) > 3718) {
10153       height -= 28;
10154       width  -= 56;
10155       top_margin = 8;
10156     }
10157   } else if (strstr(model,"WB550")) {
10158     strcpy (model, "WB550");
10159   } else if (!strcmp(model,"EX2F")) {
10160     height = 3045;
10161     width  = 4070;
10162     top_margin = 3;
10163     order = 0x4949;
10164     filters = 0x49494949;
10165     load_raw = &CLASS unpacked_load_raw;
10166   } else if (!strcmp(model,"STV680 VGA")) {
10167     black = 16;
10168   } else if (!strcmp(model,"N95")) {
10169     height = raw_height - (top_margin = 2);
10170   } else if (!strcmp(model,"640x480")) {
10171     gamma_curve (0.45, 4.5, 1, 255);
10172   } else if (!strcmp(make,"Hasselblad")) {
10173     if (load_raw == &CLASS lossless_jpeg_load_raw)
10174       load_raw = &CLASS hasselblad_load_raw;
10175     if (raw_width == 7262) {
10176       if (!strcmp(model, "H3D")) strcpy(model, "H3D-39"); // RT
10177       height = 5444;
10178       width  = 7248;
10179       top_margin  = 4;
10180       left_margin = 7;
10181       filters = 0x61616161;
10182     } else if (raw_width == 7410) {
10183       if (!strcmp(model, "H4D")) strcpy(model, "H4D-40"); // RT
10184       height = 5502;
10185       width  = 7328;
10186       top_margin  = 4;
10187       left_margin = 41;
10188       filters = 0x61616161;
10189     } else if (raw_width == 8384) {
10190       height = 6208;
10191       width  = 8280;
10192       top_margin  = 96;
10193       left_margin = 46;
10194     } else if (raw_width == 6542) { // RT, H3D-31, H3DII-31, H4D-31
10195       if (!strcmp(model, "H3D")) strcpy(model, "H3D-31");
10196       if (!strcmp(model, "H4D")) strcpy(model, "H4D-31");
10197       height = 4904;
10198       width = 6524;
10199       top_margin = 4;
10200       left_margin = 8;
10201     } else if (raw_width == 8282) { // RT, H3DII-50, H3DII-50MS, CFV-50, H4D-50
10202       if (!strcmp(model, "H3D")) strcpy(model, "H3DII-50");
10203       if (!strcmp(model, "H4D")) strcpy(model, "H4D-50");
10204       height = 6152;
10205       width = 8196;
10206       top_margin = 4;
10207       left_margin = 44;
10208     } else if (raw_width == 8374) { // RT, CFV-50c, H5D-50c, "H5D-50c MS", "H5D-200c MS"
10209       if (!strcmp(model, "H5D")) strcpy(model, "H5D-50c");
10210       if (!strcmp(model, "CFV-2")) strcpy(model, "CFV-50c");
10211       height = 6208;
10212       width = 8280;
10213       top_margin = 96;
10214       left_margin = 48;
10215     } else if (raw_width == 9044) {
10216       height = 6716;
10217       width  = 8964;
10218       top_margin  = 8;
10219       left_margin = 40;
10220       // RT: removed black level / maximum adjustment, as it does not seem to be correct when there are clipped highlights. Tested with Hasselblad H4D-60.
10221       //black += load_flags = 256;
10222       //maximum = 0x8101;
10223     } else if (raw_width == 4096) { // RT: CF-22 etc
10224       if (!strcmp(model, "H3D")) strcpy(model, "H3D-22");
10225       else if (strstr(model3, "Hasselblad ") == model3) strcpy(model, &model3[11]);
10226       if (strstr(model3, "ixpressCF132")) strcpy(model, "CF-22"); // ixpressCF132 / CF132 is same as CF-22, we use the simpler name
10227       else if (strstr(model3, "Hasselblad96")) strcpy(model, "CFV"); // popularly called CFV-16
10228     } else if (raw_width == 4090) {
10229       strcpy (model, "V96C");
10230       height -= (top_margin = 6);
10231       width -= (left_margin = 3) + 7;
10232       filters = 0x61616161;
10233     }
10234     if (tiff_samples > 1) {
10235       is_raw = tiff_samples+1;
10236       if (!shot_select && !half_size) filters = 0;
10237     }
10238   } else if (!strcmp(make,"Sinar")) {
10239     if (!load_raw) load_raw = &CLASS unpacked_load_raw;
10240     if (is_raw > 1 && !shot_select && !half_size) filters = 0;
10241     maximum = 0x3fff;
10242   } else if (!strcmp(make,"Leaf")) {
10243     maximum = 0x3fff;
10244     fseek (ifp, data_offset, SEEK_SET);
10245     if (ljpeg_start (&jh, 1) && jh.bits == 15)
10246       maximum = 0x1fff;
10247     if (tiff_samples > 1) filters = 0;
10248     if (tiff_samples > 1 || tile_length < raw_height) {
10249       load_raw = &CLASS leaf_hdr_load_raw;
10250       raw_width = tile_width;
10251     }
10252     if ((width | height) == 2048) {
10253       if (tiff_samples == 1) {
10254 	filters = 1;
10255 	strcpy (cdesc, "RBTG");
10256 	strcpy (model, "CatchLight");
10257 	top_margin =  8; left_margin = 18; height = 2032; width = 2016;
10258       } else {
10259 	strcpy (model, "DCB2");
10260 	top_margin = 10; left_margin = 16; height = 2028; width = 2022;
10261       }
10262     } else if (width+height == 3144+2060) {
10263       if (!model[0]) strcpy (model, "Cantare");
10264       if (width > height) {
10265 	 top_margin = 6; left_margin = 32; height = 2048;  width = 3072;
10266 	filters = 0x61616161;
10267       } else {
10268 	left_margin = 6;  top_margin = 32;  width = 2048; height = 3072;
10269 	filters = 0x16161616;
10270       }
10271       if (!cam_mul[0] || model[0] == 'V') filters = 0;
10272       else is_raw = tiff_samples;
10273     } else if (width == 2116) {
10274       strcpy (model, "Valeo 6");
10275       height -= 2 * (top_margin = 30);
10276       width -= 2 * (left_margin = 55);
10277       filters = 0x49494949;
10278     } else if (width == 3171) {
10279       strcpy (model, "Valeo 6");
10280       height -= 2 * (top_margin = 24);
10281       width -= 2 * (left_margin = 24);
10282       filters = 0x16161616;
10283     }
10284   } else if (!strcmp(make,"Leica") || !strcmp(make,"Panasonic")) {
10285 	if(raw_width > 0) { // avoid divide by zero
10286     if ((flen - data_offset) / (raw_width*8/7) == raw_height)
10287       load_raw = &CLASS panasonic_load_raw;
10288     if (!load_raw) {
10289       load_raw = &CLASS unpacked_load_raw;
10290       load_flags = 4;
10291     }
10292     zero_is_bad = 1;
10293     if ((height += 12) > raw_height) height = raw_height;
10294     for (i=0; i < sizeof pana / sizeof *pana; i++)
10295       if (raw_width == pana[i][0] && raw_height == pana[i][1]) {
10296 	left_margin = pana[i][2];
10297 	 top_margin = pana[i][3];
10298 	     width += pana[i][4];
10299 	    height += pana[i][5];
10300       }
10301     filters = 0x01010101 * (uchar) "\x94\x61\x49\x16"
10302 	[((filters-1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3];
10303 	}
10304   } else if (!strcmp(model,"C770UZ")) {
10305     height = 1718;
10306     width  = 2304;
10307     filters = 0x16161616;
10308     load_raw = &CLASS packed_load_raw;
10309     load_flags = 30;
10310   } else if (!strcmp(make,"Olympus")) {
10311     height += height & 1;
10312     if (exif_cfa) filters = exif_cfa;
10313     if (width == 4100) width -= 4;
10314     if (width == 4080) width -= 24;
10315     if (width == 9280) { width -= 6; height -= 6; }
10316     if (load_raw == &CLASS unpacked_load_raw)
10317       load_flags = 4;
10318     tiff_bps = 12;
10319     if (!strcmp(model,"E-300") ||
10320 	!strcmp(model,"E-500")) {
10321       width -= 20;
10322       if (load_raw == &CLASS unpacked_load_raw) {
10323 	maximum = 0xfc3;
10324 	memset (cblack, 0, sizeof cblack);
10325       }
10326     } else if (!strcmp(model,"E-330")) {
10327       width -= 30;
10328       if (load_raw == &CLASS unpacked_load_raw)
10329 	maximum = 0xf79;
10330     } else if (!strcmp(model,"SP550UZ")) {
10331       thumb_length = flen - (thumb_offset = 0xa39800);
10332       thumb_height = 480;
10333       thumb_width  = 640;
10334     } else if (!strcmp(model,"TG-4")) {
10335       width -= 16;
10336     } else if (!strcmp(model,"TG-5")) {
10337       width -= 6;
10338     }
10339   } else if (!strcmp(model,"N Digital")) {
10340     height = 2047;
10341     width  = 3072;
10342     filters = 0x61616161;
10343     data_offset = 0x1a00;
10344     load_raw = &CLASS packed_load_raw;
10345   } else if (!strcmp(model,"DSC-F828")) {
10346     width = 3288;
10347     left_margin = 5;
10348     mask[1][3] = -17;
10349     data_offset = 862144;
10350     load_raw = &CLASS sony_load_raw;
10351     filters = 0x9c9c9c9c;
10352     colors = 4;
10353     strcpy (cdesc, "RGBE");
10354   } else if (!strcmp(model,"DSC-V3")) {
10355     width = 3109;
10356     left_margin = 59;
10357     mask[0][1] = 9;
10358     data_offset = 787392;
10359     load_raw = &CLASS sony_load_raw;
10360   } else if (!strcmp(make,"Sony") && raw_width == 3984) {
10361     width = 3925;
10362     order = 0x4d4d;
10363   } else if (!strcmp(make,"Sony") && raw_width == 4288) {
10364     width -= 32;
10365   } else if (!strcmp(make,"Sony") && raw_width == 4600) {
10366     if (!strcmp(model,"DSLR-A350"))
10367       height -= 4;
10368     black = 0;
10369   } else if (!strcmp(make,"Sony") && raw_width == 4928) {
10370     if (height < 3280) width -= 8;
10371   } else if (!strcmp(make,"Sony") && raw_width == 5504) {
10372     width -= height > 3664 ? 8 : 32;
10373     if (!strncmp(model,"DSC",3))
10374       black = 200 << (tiff_bps - 12);
10375   } else if (!strcmp(make,"Sony") && strcmp(model,"ILCE-7M2") && raw_width == 6048) {
10376     // for Sony ILCE-7M2 the raw crop is defined in camconst.json
10377     width -= 24;
10378     if (strstr(model,"RX1") || strstr(model,"A99"))
10379       width -= 6;
10380   } else if (!strcmp(make,"Sony") && raw_width == 7392) {
10381     width -= 30;
10382 // this was introduced with update to dcraw 9.27
10383 // but led to broken decode for compressed files from Sony DSC-RX1RM2
10384 //  } else if (!strcmp(make,"Sony") && raw_width == 8000) {
10385 //    width -= 32;
10386 //    if (!strncmp(model,"DSC",3)) {
10387 //      tiff_bps = 14;
10388 //      load_raw = &CLASS unpacked_load_raw;
10389 //      black = 512;
10390 //    }
10391   } else if (!strcmp(model,"DSLR-A100")) {
10392     if (width == 3880) {
10393       height--;
10394       width = ++raw_width;
10395     } else {
10396       height -= 4;
10397       width  -= 4;
10398       order = 0x4d4d;
10399       load_flags = 2;
10400     }
10401     filters = 0x61616161;
10402   } else if (!strcmp(model,"PIXL")) {
10403     height -= top_margin = 4;
10404     width -= left_margin = 32;
10405     gamma_curve (0, 7, 1, 255);
10406   } else if (!strcmp(model,"C603") || !strcmp(model,"C330")
10407 	|| !strcmp(model,"12MP")) {
10408     order = 0x4949;
10409     if (filters && data_offset) {
10410       fseek (ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET);
10411       read_shorts (curve, 256);
10412     } else gamma_curve (0, 3.875, 1, 255);
10413     load_raw  =  filters   ? &CLASS eight_bit_load_raw :
10414       strcmp(model,"C330") ? &CLASS kodak_c603_load_raw :
10415 			     &CLASS kodak_c330_load_raw;
10416     load_flags = tiff_bps > 16;
10417     tiff_bps = 8;
10418   } else if (!strncasecmp(model,"EasyShare",9)) {
10419     data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000;
10420     load_raw = &CLASS packed_load_raw;
10421   } else if (!strcasecmp(make,"Kodak")) {
10422     if (filters == UINT_MAX) filters = 0x61616161;
10423     if (!strncmp(model,"NC2000",6) ||
10424 	!strncmp(model,"EOSDCS",6) ||
10425 	!strncmp(model,"DCS4",4)) {
10426       width -= 4;
10427       left_margin = 2;
10428       if (model[6] == ' ') model[6] = 0;
10429       if (!strcmp(model,"DCS460A")) goto bw;
10430     } else if (!strcmp(model,"DCS660M")) {
10431       black = 214;
10432       goto bw;
10433     } else if (!strcmp(model,"DCS760M")) {
10434 bw:   colors = 1;
10435       filters = 0;
10436     }
10437     if (!strcmp(model+4,"20X"))
10438       strcpy (cdesc, "MYCY");
10439     if (strstr(model,"DC25")) {
10440       strcpy (model, "DC25");
10441       data_offset = 15424;
10442     }
10443     if (!strncmp(model,"DC2",3)) {
10444       raw_height = 2 + (height = 242);
10445       if (flen < 100000) {
10446 	raw_width = 256; width = 249;
10447 	pixel_aspect = (4.0*height) / (3.0*width);
10448       } else {
10449 	raw_width = 512; width = 501;
10450 	pixel_aspect = (493.0*height) / (373.0*width);
10451       }
10452       top_margin = left_margin = 1;
10453       colors = 4;
10454       filters = 0x8d8d8d8d;
10455       simple_coeff(1);
10456       pre_mul[1] = 1.179;
10457       pre_mul[2] = 1.209;
10458       pre_mul[3] = 1.036;
10459       load_raw = &CLASS eight_bit_load_raw;
10460     } else if (!strcmp(model,"40")) {
10461       strcpy (model, "DC40");
10462       height = 512;
10463       width  = 768;
10464       data_offset = 1152;
10465       load_raw = &CLASS kodak_radc_load_raw;
10466       tiff_bps = 12;
10467     } else if (strstr(model,"DC50")) {
10468       strcpy (model, "DC50");
10469       height = 512;
10470       width  = 768;
10471       data_offset = 19712;
10472       load_raw = &CLASS kodak_radc_load_raw;
10473     } else if (strstr(model,"DC120")) {
10474       strcpy (model, "DC120");
10475       height = 976;
10476       width  = 848;
10477       pixel_aspect = height/0.75/width;
10478       load_raw = tiff_compress == 7 ?
10479 	&CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw;
10480     } else if (!strcmp(model,"DCS200")) {
10481       thumb_height = 128;
10482       thumb_width  = 192;
10483       thumb_offset = 6144;
10484       thumb_misc   = 360;
10485       write_thumb = &CLASS layer_thumb;
10486       black = 17;
10487     }
10488   } else if (!strcmp(model,"Fotoman Pixtura")) {
10489     height = 512;
10490     width  = 768;
10491     data_offset = 3632;
10492     load_raw = &CLASS kodak_radc_load_raw;
10493     filters = 0x61616161;
10494     simple_coeff(2);
10495   } else if (!strncmp(model,"QuickTake",9)) {
10496     if (head[5]) strcpy (model+10, "200");
10497     fseek (ifp, 544, SEEK_SET);
10498     height = get2();
10499     width  = get2();
10500     data_offset = (get4(),get2()) == 30 ? 738:736;
10501     if (height > width) {
10502       SWAP(height,width);
10503       fseek (ifp, data_offset-6, SEEK_SET);
10504       flip = ~get2() & 3 ? 5:6;
10505     }
10506     filters = 0x61616161;
10507   } else if (!strcmp(make,"Rollei") && !load_raw) {
10508     switch (raw_width) {
10509       case 1316:
10510 	height = 1030;
10511 	width  = 1300;
10512 	top_margin  = 1;
10513 	left_margin = 6;
10514 	break;
10515       case 2568:
10516 	height = 1960;
10517 	width  = 2560;
10518 	top_margin  = 2;
10519 	left_margin = 8;
10520     }
10521     filters = 0x16161616;
10522     load_raw = &CLASS rollei_load_raw;
10523   }
10524   if (!model[0])
10525     sprintf (model, "%dx%d", width, height);
10526   if (filters == UINT_MAX) filters = 0x94949494;
10527   if (thumb_offset && !thumb_height) {
10528     fseek (ifp, thumb_offset, SEEK_SET);
10529     if (ljpeg_start (&jh, 1)) {
10530       thumb_width  = jh.wide;
10531       thumb_height = jh.high;
10532     }
10533   }
10534 dng_skip:
10535   if ((use_camera_matrix & (use_camera_wb || dng_version))
10536         && cmatrix[0][0] > 0.125
10537         && strncmp(RT_software.c_str(), "Adobe DNG Converter", 19) != 0
10538       /* RT -- do not use the embedded
10539        * matrices for DNGs coming from the
10540        * Adobe DNG Converter, to ensure
10541        * consistency of WB values between
10542        * DNG-converted and original raw
10543        * files. See #4129 */) {
10544     memcpy (rgb_cam, cmatrix, sizeof cmatrix);
10545 //    raw_color = 0;
10546     RT_matrix_from_constant = ThreeValBool::F;
10547   }
10548   if(!strncmp(make, "Panasonic", 9) && !strncmp(model, "DMC-LX100",9))
10549 	adobe_coeff (make, model);
10550   if(!strncmp(make, "Samsung", 7) && !strncmp(model, "GX20",4))
10551 	adobe_coeff (make, model);
10552   if(!strncmp(make, "Samsung", 7) && !strncmp(model, "NX1",3))
10553 	adobe_coeff (make, model);
10554   if((!strncmp(make, "Pentax", 6) && (!strncmp(model, "K10D",4) || !strncmp(model, "K-70",4) || !strncmp(model, "K-1",3) || !strncmp(model, "KP",2))) && filters != 0)
10555 	adobe_coeff (make, model);
10556   if(!strncmp(make, "Leica", 5) && !strncmp(model, "Q",1))
10557     adobe_coeff (make, model);
10558   if(!strncmp(make, "Leica", 5) && !strncmp(model, "SL",2))
10559     adobe_coeff (make, model);
10560   if((!strncmp(make, "XIAOYI", 6) || !strncmp(make, "YI", 2)) && !strncmp(model, "M1",2))
10561 	adobe_coeff (make, model);
10562   if(!strncmp(make, "DJI", 3) && !strncmp(model, "FC6310", 6)) // DNG files from this camera have wrong (too high) white level
10563     adobe_coeff (make, model);
10564   if (!strncmp(make, "LG", 2) && (!strncmp(model, "LG-H850",7) || !strncmp(model, "LG-H815",7)))
10565     adobe_coeff (make, model);
10566   if (raw_color) adobe_coeff (make, model);
10567   if (load_raw == &CLASS kodak_radc_load_raw)
10568     if (raw_color) adobe_coeff ("Apple","Quicktake");
10569   if (fuji_width) {
10570     fuji_width = width >> !fuji_layout;
10571     filters = fuji_width & 1 ? 0x94949494 : 0x49494949;
10572     width = (height >> fuji_layout) + fuji_width;
10573     height = width - 1;
10574     pixel_aspect = 1;
10575   } else {
10576     if (raw_height < height) raw_height = height;
10577     if (raw_width  < width ) raw_width  = width;
10578   }
10579   if (!tiff_bps) tiff_bps = 12;
10580   if (!maximum) {
10581       if (tiff_nifds == 1 && tiff_ifd[0].sample_format == 3) {
10582           // float DNG, default white level is 1.0
10583           maximum = 1;
10584       } else {
10585           maximum = ((uint64_t)1 << tiff_bps) - 1; // use uint64_t to avoid overflow if tiff_bps == 32
10586       }
10587   }
10588   if (!load_raw || height < 22 || width < 22 ||
10589 	tiff_samples > 6 || colors > 4)
10590     is_raw = 0;
10591 #ifdef NO_JASPER
10592   if (load_raw == &CLASS redcine_load_raw) {
10593     fprintf (stderr,_("%s: You must link dcraw with %s!!\n"),
10594 	ifname, "libjasper");
10595     is_raw = 0;
10596   }
10597 #endif
10598 #ifdef NO_JPEG
10599   if (load_raw == &CLASS kodak_jpeg_load_raw /* RT ||
10600       load_raw == &CLASS lossy_dng_load_raw*/) {
10601     fprintf (stderr,_("%s: You must link dcraw with %s!!\n"),
10602 	ifname, "libjpeg");
10603     is_raw = 0;
10604   }
10605 #endif
10606   if (!cdesc[0])
10607     strcpy (cdesc, colors == 3 ? "RGBG":"GMCY");
10608   if (!raw_height) raw_height = height;
10609   if (!raw_width ) raw_width  = width;
10610   if (filters > 999 && colors == 3)
10611     filters |= ((filters >> 2 & 0x22222222) |
10612 		(filters << 2 & 0x88888888)) & filters << 1;
10613 notraw:
10614   if (flip == UINT_MAX) flip = tiff_flip;
10615   if (flip == UINT_MAX) flip = 0;
10616 }
10617 
10618 //#ifndef NO_LCMS
10619 //void CLASS apply_profile (const char *input, const char *output)
10620 //{
10621 //  char *prof;
10622 //  cmsHPROFILE hInProfile=0, hOutProfile=0;
10623 //  cmsHTRANSFORM hTransform;
10624 //  FILE *fp;
10625 //  unsigned size;
10626 //
10627 //  if (strcmp (input, "embed"))
10628 //    hInProfile = cmsOpenProfileFromFile (input, "r");
10629 //  else if (profile_length) {
10630 //    prof = (char *) malloc (profile_length);
10631 //    merror (prof, "apply_profile()");
10632 //    fseek (ifp, profile_offset, SEEK_SET);
10633 //    fread (prof, 1, profile_length, ifp);
10634 //    hInProfile = cmsOpenProfileFromMem (prof, profile_length);
10635 //    free (prof);
10636 //  } else
10637 //    fprintf (stderr,_("%s has no embedded profile.\n"), ifname);
10638 //  if (!hInProfile) return;
10639 //  if (!output)
10640 //    hOutProfile = cmsCreate_sRGBProfile();
10641 //  else if ((fp = fopen (output, "rb"))) {
10642 //    fread (&size, 4, 1, fp);
10643 //    fseek (fp, 0, SEEK_SET);
10644 //    oprof = (unsigned *) malloc (size = ntohl(size));
10645 //    merror (oprof, "apply_profile()");
10646 //    fread (oprof, 1, size, fp);
10647 //    fclose (fp);
10648 //    if (!(hOutProfile = cmsOpenProfileFromMem (oprof, size))) {
10649 //      free (oprof);
10650 //      oprof = 0;
10651 //    }
10652 //  } else
10653 //    fprintf (stderr,_("Cannot open file %s!\n"), output);
10654 //  if (!hOutProfile) goto quit;
10655 //  if (verbose)
10656 //    fprintf (stderr,_("Applying color profile...\n"));
10657 //  hTransform = cmsCreateTransform (hInProfile, TYPE_RGBA_16,
10658 //	hOutProfile, TYPE_RGBA_16, INTENT_PERCEPTUAL, 0);
10659 //  cmsDoTransform (hTransform, image, image, width*height);
10660 //  raw_color = 1;		/* Don't use rgb_cam with a profile */
10661 //  cmsDeleteTransform (hTransform);
10662 //  cmsCloseProfile (hOutProfile);
10663 //quit:
10664 //  cmsCloseProfile (hInProfile);
10665 //}
10666 //#endif
10667 
10668 /* RT: DNG Float */
10669 
10670 // #include <zlib.h>
10671 // #include <stdint.h>
10672 
decodeFPDeltaRow(Bytef * src,Bytef * dst,size_t tileWidth,size_t realTileWidth,int bytesps,int factor)10673 static void decodeFPDeltaRow(Bytef * src, Bytef * dst, size_t tileWidth, size_t realTileWidth, int bytesps, int factor) {
10674   // DecodeDeltaBytes
10675   for (size_t col = factor; col < realTileWidth*bytesps; ++col) {
10676     src[col] += src[col - factor];
10677   }
10678   // Reorder bytes into the image
10679   // 16 and 32-bit versions depend on local architecture, 24-bit does not
10680   if (bytesps == 3) {
10681     for (size_t col = 0; col < tileWidth; ++col) {
10682       dst[col*3] = src[col];
10683       dst[col*3 + 1] = src[col + realTileWidth];
10684       dst[col*3 + 2] = src[col + realTileWidth*2];
10685     }
10686   } else {
10687     union X { uint32_t x; uint8_t c; };
10688     if (((union X){1}).c) {
10689 		for (size_t col = 0; col < tileWidth; ++col) {
10690 			for (size_t byte = 0; byte < bytesps; ++byte)
10691 				dst[col*bytesps + byte] = src[col + realTileWidth*(bytesps-byte-1)];  // Little endian
10692 		}
10693     } else {
10694 		for (size_t col = 0; col < tileWidth; ++col) {
10695 			for (size_t byte = 0; byte < bytesps; ++byte)
10696 				dst[col*bytesps + byte] = src[col + realTileWidth*byte];
10697         }
10698       }
10699     }
10700 
10701 }
10702 
10703 #if 1 //ndef __F16C__
10704 // From DNG SDK dng_utils.h
10705 static //inline
DNG_HalfToFloat(uint16_t halfValue)10706 uint32_t DNG_HalfToFloat(uint16_t halfValue) {
10707   int32_t sign     = (halfValue >> 15) & 0x00000001;
10708   int32_t exponent = (halfValue >> 10) & 0x0000001f;
10709   int32_t mantissa =  halfValue        & 0x000003ff;
10710   if (exponent == 0) {
10711     if (mantissa == 0) {
10712       // Plus or minus zero
10713       return (uint32_t) (sign << 31);
10714     } else {
10715       // Denormalized number -- renormalize it
10716       while (!(mantissa & 0x00000400)) {
10717         mantissa <<= 1;
10718         exponent -=  1;
10719       }
10720       exponent += 1;
10721       mantissa &= ~0x00000400;
10722     }
10723   } else if (exponent == 31) {
10724     if (mantissa == 0) {
10725       // Positive or negative infinity, convert to maximum (16 bit) values.
10726       return (uint32_t) ((sign << 31) | ((0x1eL + 127 - 15) << 23) |  (0x3ffL << 13));
10727     } else {
10728       // Nan -- Just set to zero.
10729       return 0;
10730     }
10731   }
10732   // Normalized number
10733   exponent += (127 - 15);
10734   mantissa <<= 13;
10735   // Assemble sign, exponent and mantissa.
10736   return (uint32_t) ((sign << 31) | (exponent << 23) | mantissa);
10737 }
10738 #endif
10739 
DNG_FP24ToFloat(const uint8_t * input)10740 static inline uint32_t DNG_FP24ToFloat(const uint8_t * input) {
10741   int32_t sign     = (input [0] >> 7) & 0x01;
10742   int32_t exponent = (input [0]     ) & 0x7F;
10743   int32_t mantissa = (((int32_t) input [1]) << 8) | input[2];
10744   if (exponent == 0) {
10745     if (mantissa == 0) {
10746       // Plus or minus zero
10747       return (uint32_t) (sign << 31);
10748     } else {
10749       // Denormalized number -- renormalize it
10750       while (!(mantissa & 0x00010000)) {
10751         mantissa <<= 1;
10752         exponent -=  1;
10753       }
10754       exponent += 1;
10755       mantissa &= ~0x00010000;
10756     }
10757   } else if (exponent == 127) {
10758     if (mantissa == 0) {
10759       // Positive or negative infinity, convert to maximum (24 bit) values.
10760       return (uint32_t) ((sign << 31) | ((0x7eL + 128 - 64) << 23) |  (0xffffL << 7));
10761     } else {
10762       // Nan -- Just set to zero.
10763       return 0;
10764     }
10765   }
10766   // Normalized number
10767   exponent += (128 - 64);
10768   mantissa <<= 7;
10769   // Assemble sign, exponent and mantissa.
10770   return (uint32_t) ((sign << 31) | (exponent << 23) | mantissa);
10771 }
10772 
expandFloats(Bytef * dst,int tileWidth,int bytesps)10773 static void expandFloats(Bytef * dst, int tileWidth, int bytesps) {
10774   if (bytesps == 2) {
10775     uint16_t* const dst16 = reinterpret_cast<uint16_t*>(dst);
10776 #ifndef __F16C__
10777     uint32_t* const dst32 = reinterpret_cast<uint32_t*>(dst);
10778     for (int index = tileWidth - 1; index >= 0; --index) {
10779         dst32[index] = DNG_HalfToFloat(dst16[index]);
10780     }
10781 #else
10782     float* const dst32 = reinterpret_cast<float*>(dst);
10783     int index = tileWidth - 8;
10784     for (; index >= 0; index -= 8) {
10785         __m128i halfFloatv = _mm_loadu_si128((__m128i*)&dst16[index]);
10786         STVFU(dst32[index], _mm_cvtph_ps(halfFloatv));
10787         STVFU(dst32[index + 4], _mm_cvtph_ps(_mm_shuffle_epi32(halfFloatv, _MM_SHUFFLE(0,0,3,2))));
10788     }
10789     index += 4;
10790     if(index >= 0) {
10791         __m128i halfFloatv = _mm_loadu_si128((__m128i*)&dst16[index]);
10792         STVFU(dst32[index], _mm_cvtph_ps(halfFloatv));
10793         index--;
10794     } else {
10795         index += 3;
10796     }
10797     for (; index >= 0; --index) {
10798         dst32[index] = _cvtsh_ss(dst16[index]);
10799     }
10800 #endif
10801   } else if (bytesps == 3) {
10802     uint8_t  * dst8  = ((uint8_t *) dst) + (tileWidth - 1) * 3;
10803     uint32_t * dst32 = (uint32_t *) dst;
10804     for (int index = tileWidth - 1; index >= 0; --index, dst8 -= 3) {
10805       dst32[index] = DNG_FP24ToFloat(dst8);
10806     }
10807   }
10808 }
10809 
decompress(size_t srcLen,size_t dstLen,unsigned char * in,unsigned char * out)10810 static int decompress(size_t srcLen, size_t dstLen, unsigned char *in, unsigned char *out) {
10811     // At least in zlib 1.2.11 the uncompress function is not thread save while it is thread save in zlib 1.2.8
10812     // This simple replacement is thread save. Used example code from https://zlib.net/zlib_how.html
10813 
10814     int ret;
10815     z_stream strm;
10816     /* allocate inflate state */
10817     strm.zalloc = Z_NULL;
10818     strm.zfree = Z_NULL;
10819     strm.opaque = Z_NULL;
10820     strm.avail_in = 0;
10821     strm.next_in = Z_NULL;
10822     ret = inflateInit(&strm);
10823     if (ret != Z_OK) {
10824         return ret;
10825     }
10826     strm.avail_out = dstLen;
10827     strm.next_out = out;
10828     strm.avail_in = srcLen;
10829     strm.next_in = in;
10830     ret = inflate(&strm, Z_NO_FLUSH);
10831     switch (ret) {
10832     case Z_NEED_DICT:
10833         ret = Z_DATA_ERROR;     /* and fall through */
10834     case Z_DATA_ERROR:
10835     case Z_MEM_ERROR:
10836         (void)inflateEnd(&strm);
10837         return ret;
10838     }
10839     /* clean up and return */
10840     (void)inflateEnd(&strm);
10841     return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
10842 }
10843 
deflate_dng_load_raw()10844 void CLASS deflate_dng_load_raw() {
10845     float_raw_image = new float[raw_width * raw_height];
10846 
10847 #ifdef _OPENMP
10848     #pragma omp parallel for
10849 #endif
10850     for (size_t i = 0; i < raw_width * raw_height; ++i)
10851       float_raw_image[i] = 0.0f;
10852 
10853   if(tiff_samples != 1) {
10854     fprintf(stderr, "deflate_dng_load_raw %s: demosaiced float dng files are not supported\n",ifname);
10855     return;
10856   }
10857 
10858   struct tiff_ifd * ifd = &tiff_ifd[0];
10859   while (ifd < &tiff_ifd[tiff_nifds] && ifd->offset != data_offset) ++ifd;
10860   if (ifd == &tiff_ifd[tiff_nifds]) {
10861     fprintf(stderr, "deflate_dng_load_raw %s: Raw image not found???\n",ifname);
10862     return;
10863   }
10864 
10865   if (ifd->sample_format != 3) {  // no floating point data
10866     fprintf(stderr, "deflate_dng_load_raw %s: Only float format is supported for deflate compressed dng files\n",ifname);
10867     return;
10868   }
10869 
10870   int predFactor;
10871   switch(ifd->predictor) {
10872     case 3: predFactor = 1; break;
10873     case 34894: predFactor = 2; break;
10874     case 34895: predFactor = 4; break;
10875 	default: predFactor = 0; break;
10876   }
10877 
10878   // NOTE: This reader is based on the official DNG SDK from Adobe.
10879   // It assumes tiles without subtiles, but the standard does not say that
10880   // subtiles or strips couldn't be used.
10881   if (tile_length < INT_MAX) {
10882     size_t tilesWide = (raw_width + tile_width - 1) / tile_width;
10883     size_t tilesHigh = (raw_height + tile_length - 1) / tile_length;
10884     size_t tileCount = tilesWide * tilesHigh;
10885     //fprintf(stderr, "%dx%d tiles, %d total\n", tilesWide, tilesHigh, tileCount);
10886     size_t tileOffsets[tileCount];
10887     for (size_t t = 0; t < tileCount; ++t) {
10888       tileOffsets[t] = get4();
10889     }
10890     size_t tileBytes[tileCount];
10891     uLongf maxCompressed = 0;
10892     if (tileCount == 1) {
10893       tileBytes[0] = maxCompressed = ifd->bytes;
10894     } else {
10895       fseek(ifp, ifd->bytes, SEEK_SET);
10896       for (size_t t = 0; t < tileCount; ++t) {
10897         tileBytes[t] = get4();
10898         //fprintf(stderr, "Tile %d at %d, size %d\n", t, tileOffsets[t], tileBytes[t]);
10899         if (maxCompressed < tileBytes[t])
10900           maxCompressed = tileBytes[t];
10901       }
10902     }
10903     uLongf dstLen = tile_width * tile_length * 4;
10904 
10905 #ifdef _OPENMP
10906 #pragma omp parallel
10907 #endif
10908 {
10909     Bytef * cBuffer = new Bytef[maxCompressed];
10910     Bytef * uBuffer = new Bytef[dstLen];
10911 
10912 #ifdef _OPENMP
10913     #pragma omp for collapse(2) schedule(dynamic) nowait
10914 #endif
10915     for (size_t y = 0; y < raw_height; y += tile_length) {
10916         for (size_t x = 0; x < raw_width; x += tile_width) {
10917             size_t t = (y / tile_length) * tilesWide + (x / tile_width);
10918 #ifdef _OPENMP
10919             #pragma omp critical
10920 #endif
10921             {
10922                 fseek(ifp, tileOffsets[t], SEEK_SET);
10923                 fread(cBuffer, 1, tileBytes[t], ifp);
10924             }
10925             int err = decompress(tileBytes[t], dstLen, cBuffer, uBuffer);
10926             if (err != Z_OK) {
10927                 fprintf(stderr, "DNG Deflate: Failed uncompressing tile %d, with error %d\n", (int)t, err);
10928             } else if (ifd->sample_format == 3) {  // Floating point data
10929                 int bytesps = ifd->bps >> 3;
10930                 size_t thisTileLength = y + tile_length > raw_height ? raw_height - y : tile_length;
10931                 size_t thisTileWidth = x + tile_width > raw_width ? raw_width - x : tile_width;
10932                 for (size_t row = 0; row < thisTileLength; ++row) {
10933                     Bytef * src = uBuffer + row*tile_width*bytesps;
10934                     Bytef * dst = (Bytef *)&float_raw_image[(y+row)*raw_width + x];
10935                     if (predFactor) {
10936                         decodeFPDeltaRow(src, dst, thisTileWidth, tile_width, bytesps, predFactor);
10937                     }
10938                     expandFloats(dst, thisTileWidth, bytesps);
10939                 }
10940             } else {  // 32-bit Integer data
10941                 // TODO
10942             }
10943         }
10944     }
10945 
10946     delete [] cBuffer;
10947     delete [] uBuffer;
10948 }
10949   }
10950 
10951 }
10952 
10953 /* RT: removed unused functions */
10954 
10955 struct tiff_tag {
10956   ushort tag, type;
10957   int count;
10958   union { char c[4]; short s[2]; int i; } val;
10959 };
10960 
10961 struct tiff_hdr {
10962   ushort order, magic;
10963   int ifd;
10964   ushort pad, ntag;
10965   struct tiff_tag tag[23];
10966   int nextifd;
10967   ushort pad2, nexif;
10968   struct tiff_tag exif[4];
10969   ushort pad3, ngps;
10970   struct tiff_tag gpst[10];
10971   short bps[4];
10972   int rat[10];
10973   unsigned gps[26];
10974   char desc[512], make[64], model[64], soft[32], date[20], artist[64];
10975 };
10976 
10977 #include "fujicompressed.cc"
10978 
10979 //-----------------------------------------------------------------------------
10980 /* Taken from LibRaw
10981 
10982 LibRaw is free software; you can redistribute it and/or modify
10983 it under the terms of the one of two licenses as you choose:
10984 1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1
10985    (See file LICENSE.LGPL provided in LibRaw distribution archive for details).
10986 2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
10987    (See file LICENSE.CDDL provided in LibRaw distribution archive for details).
10988  */
10989 
10990 namespace {
10991 
unpack7bytesto4x16_nikon(unsigned char * src,unsigned short * dest)10992 inline void unpack7bytesto4x16_nikon(unsigned char *src, unsigned short *dest)
10993 {
10994     dest[3] = (src[6] << 6) | (src[5] >> 2);
10995     dest[2] = ((src[5] & 0x3) << 12) | (src[4] << 4) | (src[3] >> 4);
10996     dest[1] = (src[3] & 0xf) << 10 | (src[2] << 2) | (src[1] >> 6);
10997     dest[0] = ((src[1] & 0x3f) << 8) | src[0];
10998 }
10999 
11000 } // namespace
11001 
nikon_14bit_load_raw()11002 void CLASS nikon_14bit_load_raw()
11003 {
11004     const unsigned linelen = (unsigned)(ceilf((float)(raw_width * 7 / 4) / 16.0)) * 16; // 14512; // S.raw_width * 7 / 4;
11005     const unsigned pitch = raw_width; //S.raw_pitch ? S.raw_pitch / 2 : S.raw_width;
11006     unsigned char *buf = (unsigned char *)malloc(linelen);
11007     merror(buf, "nikon_14bit_load_raw()");
11008     for (int row = 0; row < raw_height; row++)
11009     {
11010         unsigned bytesread = fread(buf, 1, linelen, ifp);
11011         unsigned short *dest = &raw_image[pitch * row];
11012         //swab32arr((unsigned *)buf, bytesread / 4);
11013         for (int sp = 0, dp = 0; dp < pitch - 3 && sp < linelen - 6 && sp < bytesread - 6; sp += 7, dp += 4)
11014             unpack7bytesto4x16_nikon(buf + sp, dest + dp);
11015     }
11016     free(buf);
11017 }
11018 
11019 /* RT: Delete from here */
11020 /*RT*/#undef SQR
11021 /*RT*/#undef MAX
11022 /*RT*/#undef MIN
11023 /*RT*/#undef ABS
11024 /*RT*/#undef LIM
11025 /*RT*/#undef ULIM
11026 /*RT*/#undef CLIP
11027 #ifdef __GNUC__
11028 #pragma GCC diagnostic pop
11029 #endif
11030