1 /*
2    dcraw.c -- Dave Coffin's raw photo decoder
3    Copyright 1997-2010 by Dave Coffin, dcoffin a cybercom o net
4 
5    This is a command-line ANSI C program to convert raw photos from
6    any digital camera on any computer running any operating system.
7 
8    No license is required to download and use dcraw.c.  However,
9    to lawfully redistribute dcraw, you must either (a) offer, at
10    no extra charge, full source code* for all executable files
11    containing RESTRICTED functions, (b) distribute this code under
12    the GPL Version 2 or later, (c) remove all RESTRICTED functions,
13    re-implement them, or copy them from an earlier, unrestricted
14    Revision of dcraw.c, or (d) purchase a license from the author.
15 
16    The functions that process Foveon images have been RESTRICTED
17    since Revision 1.237.  All other code remains free for all uses.
18 
19    *If you have not modified dcraw.c in any way, a link to my
20    homepage qualifies as "full source code".
21 
22    $Revision: 1.440 $
23    $Date: 2011/01/29 07:43:38 $
24  */
25 
26 #define VERSION "9.06"
27 
28 #ifndef _GNU_SOURCE
29 #define _GNU_SOURCE
30 #endif
31 #define _USE_MATH_DEFINES
32 #include <ctype.h>
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <float.h>
36 #include <limits.h>
37 #include <math.h>
38 #include <setjmp.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <time.h>
43 #include <sys/types.h>
44 /*
45    NO_JPEG disables decoding of compressed Kodak DC120 files.
46    NO_LCMS disables the "-p" option.
47  */
48 #ifndef NO_JPEG
49 #include <jpeglib.h>
50 #endif
51 #ifndef NO_LCMS
52 #include <lcms.h>
53 #endif
54 #ifdef LOCALEDIR
55 #include <libintl.h>
56 #define _(String) gettext(String)
57 #else
58 #define _(String) (String)
59 #endif
60 #if defined(DJGPP) || defined(__MINGW32__)
61 #define fseeko fseek
62 #define ftello ftell
63 #else
64 #define fgetc getc_unlocked
65 #endif
66 #ifdef __CYGWIN__
67 #include <io.h>
68 #endif
69 #ifdef WIN32
70 #include <sys/utime.h>
71 #include <winsock2.h>
72 #pragma comment(lib, "ws2_32.lib")
73 #define snprintf _snprintf
74 #define strcasecmp stricmp
75 #define strncasecmp strnicmp
76 typedef __int64 INT64;
77 typedef unsigned __int64 UINT64;
78 #else
79 #include <unistd.h>
80 #include <utime.h>
81 #include <netinet/in.h>
82 typedef long long INT64;
83 typedef unsigned long long UINT64;
84 #endif
85 
86 #ifdef LJPEG_DECODE
87 #error Please compile dcraw.c by itself.
88 #error Do not link it with ljpeg_decode.
89 #endif
90 
91 #ifndef LONG_BIT
92 #define LONG_BIT (8 * sizeof (long))
93 #endif
94 
95 #define ushort UshORt
96 typedef unsigned char uchar;
97 typedef unsigned short ushort;
98 
99 /*
100    All global variables are defined here, and all functions that
101    access them are prefixed with "CLASS".  Note that a thread-safe
102    C++ class cannot have non-const static local variables.
103  */
104 FILE *ifp, *ofp;
105 short order;
106 const char *ifname;
107 char *meta_data;
108 char cdesc[5], desc[512], make[64], model[64], model2[64], artist[64];
109 float flash_used, canon_ev, iso_speed, shutter, aperture, focal_len;
110 time_t timestamp;
111 unsigned shot_order, kodak_cbpp, filters, exif_cfa, unique_id;
112 off_t    strip_offset, data_offset;
113 off_t    thumb_offset, meta_offset, profile_offset;
114 unsigned thumb_length, meta_length, profile_length;
115 unsigned thumb_misc, *oprof, fuji_layout, shot_select=0, multi_out=0;
116 unsigned tiff_nifds, tiff_samples, tiff_bps, tiff_compress;
117 unsigned black, cblack[8], maximum, mix_green, raw_color, zero_is_bad;
118 unsigned zero_after_ff, is_raw, dng_version, is_foveon, data_error;
119 unsigned tile_width, tile_length, gpsdata[32], load_flags;
120 ushort raw_height, raw_width, height, width, top_margin, left_margin;
121 ushort shrink, iheight, iwidth, fuji_width, thumb_width, thumb_height;
122 int flip, tiff_flip, colors;
123 double pixel_aspect, aber[4]={1,1,1,1}, gamm[6]={ 0.45,4.5,0,0,0,0 };
124 ushort (*image)[4], white[8][8], curve[0x10000], cr2_slice[3], sraw_mul[4];
125 float bright=1, user_mul[4]={0,0,0,0}, threshold=0;
126 int half_size=0, four_color_rgb=0, document_mode=0, highlight=0;
127 int verbose=0, use_auto_wb=0, use_camera_wb=0, use_camera_matrix=-1;
128 int output_color=1, output_bps=8, output_tiff=0, med_passes=0;
129 int no_auto_bright=0;
130 unsigned greybox[4] = { 0, 0, UINT_MAX, UINT_MAX };
131 float cam_mul[4], pre_mul[4], cmatrix[3][4], rgb_cam[3][4];
132 const double xyz_rgb[3][3] = {			/* XYZ from RGB */
133   { 0.412453, 0.357580, 0.180423 },
134   { 0.212671, 0.715160, 0.072169 },
135   { 0.019334, 0.119193, 0.950227 } };
136 const float d65_white[3] = { 0.950456, 1, 1.088754 };
137 int histogram[4][0x2000];
138 void (*write_thumb)(), (*write_fun)();
139 void (*load_raw)(), (*thumb_load_raw)();
140 jmp_buf failure;
141 
142 struct decode {
143   struct decode *branch[2];
144   int leaf;
145 } first_decode[2048], *second_decode, *free_decode;
146 
147 struct tiff_ifd {
148   int width, height, bps, comp, phint, offset, flip, samples, bytes;
149 } tiff_ifd[10];
150 
151 struct ph1 {
152   int format, key_off, black, black_off, split_col, tag_21a;
153   float tag_210;
154 } ph1;
155 
156 #define CLASS
157 
158 #define FORC(cnt) for (c=0; c < cnt; c++)
159 #define FORC3 FORC(3)
160 #define FORC4 FORC(4)
161 #define FORCC FORC(colors)
162 
163 #define SQR(x) ((x)*(x))
164 #define ABS(x) (((int)(x) ^ ((int)(x) >> 31)) - ((int)(x) >> 31))
165 #define MIN(a,b) ((a) < (b) ? (a) : (b))
166 #define MAX(a,b) ((a) > (b) ? (a) : (b))
167 #define LIM(x,min,max) MAX(min,MIN(x,max))
168 #define ULIM(x,y,z) ((y) < (z) ? LIM(x,y,z) : LIM(x,z,y))
169 #define CLIP(x) LIM(x,0,65535)
170 #define SWAP(a,b) { a=a+b; b=a-b; a=a-b; }
171 
172 /*
173    In order to inline this calculation, I make the risky
174    assumption that all filter patterns can be described
175    by a repeating pattern of eight rows and two columns
176 
177    Do not use the FC or BAYER macros with the Leaf CatchLight,
178    because its pattern is 16x16, not 2x8.
179 
180    Return values are either 0/1/2/3 = G/M/C/Y or 0/1/2/3 = R/G1/B/G2
181 
182 	PowerShot 600	PowerShot A50	PowerShot Pro70	Pro90 & G1
183 	0xe1e4e1e4:	0x1b4e4b1e:	0x1e4b4e1b:	0xb4b4b4b4:
184 
185 	  0 1 2 3 4 5	  0 1 2 3 4 5	  0 1 2 3 4 5	  0 1 2 3 4 5
186 	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
187 	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
188 	2 M G M G M G	2 Y C Y C Y C	2 C Y C Y C Y
189 	3 C Y C Y C Y	3 G M G M G M	3 G M G M G M
190 			4 C Y C Y C Y	4 Y C Y C Y C
191 	PowerShot A5	5 G M G M G M	5 G M G M G M
192 	0x1e4e1e4e:	6 Y C Y C Y C	6 C Y C Y C Y
193 			7 M G M G M G	7 M G M G M G
194 	  0 1 2 3 4 5
195 	0 C Y C Y C Y
196 	1 G M G M G M
197 	2 C Y C Y C Y
198 	3 M G M G M G
199 
200    All RGB cameras use one of these Bayer grids:
201 
202 	0x16161616:	0x61616161:	0x49494949:	0x94949494:
203 
204 	  0 1 2 3 4 5	  0 1 2 3 4 5	  0 1 2 3 4 5	  0 1 2 3 4 5
205 	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
206 	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
207 	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
208 	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
209  */
210 
211 #define FC(row,col) \
212 	(filters >> ((((row) << 1 & 14) + ((col) & 1)) << 1) & 3)
213 
214 #define BAYER(row,col) \
215 	image[((row) >> shrink)*iwidth + ((col) >> shrink)][FC(row,col)]
216 
217 #define BAYER2(row,col) \
218 	image[((row) >> shrink)*iwidth + ((col) >> shrink)][fc(row,col)]
219 
fc(int row,int col)220 int CLASS fc (int row, int col)
221 {
222   static const char filter[16][16] =
223   { { 2,1,1,3,2,3,2,0,3,2,3,0,1,2,1,0 },
224     { 0,3,0,2,0,1,3,1,0,1,1,2,0,3,3,2 },
225     { 2,3,3,2,3,1,1,3,3,1,2,1,2,0,0,3 },
226     { 0,1,0,1,0,2,0,2,2,0,3,0,1,3,2,1 },
227     { 3,1,1,2,0,1,0,2,1,3,1,3,0,1,3,0 },
228     { 2,0,0,3,3,2,3,1,2,0,2,0,3,2,2,1 },
229     { 2,3,3,1,2,1,2,1,2,1,1,2,3,0,0,1 },
230     { 1,0,0,2,3,0,0,3,0,3,0,3,2,1,2,3 },
231     { 2,3,3,1,1,2,1,0,3,2,3,0,2,3,1,3 },
232     { 1,0,2,0,3,0,3,2,0,1,1,2,0,1,0,2 },
233     { 0,1,1,3,3,2,2,1,1,3,3,0,2,1,3,2 },
234     { 2,3,2,0,0,1,3,0,2,0,1,2,3,0,1,0 },
235     { 1,3,1,2,3,2,3,2,0,2,0,1,1,0,3,0 },
236     { 0,2,0,3,1,0,0,1,1,3,3,2,3,2,2,1 },
237     { 2,1,3,2,3,1,2,1,0,3,0,2,0,2,0,2 },
238     { 0,3,1,0,0,2,0,3,2,1,3,1,1,3,1,3 } };
239 
240   if (filters != 1) return FC(row,col);
241   return filter[(row+top_margin) & 15][(col+left_margin) & 15];
242 }
243 
244 #ifndef __GLIBC__
my_memmem(char * haystack,size_t haystacklen,char * needle,size_t needlelen)245 char *my_memmem (char *haystack, size_t haystacklen,
246 	      char *needle, size_t needlelen)
247 {
248   char *c;
249   for (c = haystack; c <= haystack + haystacklen - needlelen; c++)
250     if (!memcmp (c, needle, needlelen))
251       return c;
252   return 0;
253 }
254 #define memmem my_memmem
255 #endif
256 
merror(void * ptr,const char * where)257 void CLASS merror (void *ptr, const char *where)
258 {
259   if (ptr) return;
260   fprintf (stderr,_("%s: Out of memory in %s\n"), ifname, where);
261   longjmp (failure, 1);
262 }
263 
derror()264 void CLASS derror()
265 {
266   if (!data_error) {
267     fprintf (stderr, "%s: ", ifname);
268     if (feof(ifp))
269       fprintf (stderr,_("Unexpected end of file\n"));
270     else
271       fprintf (stderr,_("Corrupt data near 0x%llx\n"), (INT64) ftello(ifp));
272   }
273   data_error++;
274 }
275 
sget2(uchar * s)276 ushort CLASS sget2 (uchar *s)
277 {
278   if (order == 0x4949)		/* "II" means little-endian */
279     return s[0] | s[1] << 8;
280   else				/* "MM" means big-endian */
281     return s[0] << 8 | s[1];
282 }
283 
get2()284 ushort CLASS get2()
285 {
286   uchar str[2] = { 0xff,0xff };
287   fread (str, 1, 2, ifp);
288   return sget2(str);
289 }
290 
sget4(uchar * s)291 unsigned CLASS sget4 (uchar *s)
292 {
293   if (order == 0x4949)
294     return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24;
295   else
296     return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3];
297 }
298 #define sget4(s) sget4((uchar *)s)
299 
get4()300 unsigned CLASS get4()
301 {
302   uchar str[4] = { 0xff,0xff,0xff,0xff };
303   fread (str, 1, 4, ifp);
304   return sget4(str);
305 }
306 
getint(int type)307 unsigned CLASS getint (int type)
308 {
309   return type == 3 ? get2() : get4();
310 }
311 
int_to_float(int i)312 float CLASS int_to_float (int i)
313 {
314   union { int i; float f; } u;
315   u.i = i;
316   return u.f;
317 }
318 
getreal(int type)319 double CLASS getreal (int type)
320 {
321   union { char c[8]; double d; } u;
322   int i, rev;
323 
324   switch (type) {
325     case 3: return (unsigned short) get2();
326     case 4: return (unsigned int) get4();
327     case 5:  u.d = (unsigned int) get4();
328       return u.d / (unsigned int) get4();
329     case 8: return (signed short) get2();
330     case 9: return (signed int) get4();
331     case 10: u.d = (signed int) get4();
332       return u.d / (signed int) get4();
333     case 11: return int_to_float (get4());
334     case 12:
335       rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234));
336       for (i=0; i < 8; i++)
337 	u.c[i ^ rev] = fgetc(ifp);
338       return u.d;
339     default: return fgetc(ifp);
340   }
341 }
342 
read_shorts(ushort * pixel,int count)343 void CLASS read_shorts (ushort *pixel, int count)
344 {
345   if (fread (pixel, 2, count, ifp) < count) derror();
346   if ((order == 0x4949) == (ntohs(0x1234) == 0x1234))
347     swab (pixel, pixel, count*2);
348 }
349 
canon_600_fixed_wb(int temp)350 void CLASS canon_600_fixed_wb (int temp)
351 {
352   static const short mul[4][5] = {
353     {  667, 358,397,565,452 },
354     {  731, 390,367,499,517 },
355     { 1119, 396,348,448,537 },
356     { 1399, 485,431,508,688 } };
357   int lo, hi, i;
358   float frac=0;
359 
360   for (lo=4; --lo; )
361     if (*mul[lo] <= temp) break;
362   for (hi=0; hi < 3; hi++)
363     if (*mul[hi] >= temp) break;
364   if (lo != hi)
365     frac = (float) (temp - *mul[lo]) / (*mul[hi] - *mul[lo]);
366   for (i=1; i < 5; i++)
367     pre_mul[i-1] = 1 / (frac * mul[hi][i] + (1-frac) * mul[lo][i]);
368 }
369 
370 /* Return values:  0 = white  1 = near white  2 = not white */
canon_600_color(int ratio[2],int mar)371 int CLASS canon_600_color (int ratio[2], int mar)
372 {
373   int clipped=0, target, miss;
374 
375   if (flash_used) {
376     if (ratio[1] < -104)
377       { ratio[1] = -104; clipped = 1; }
378     if (ratio[1] >   12)
379       { ratio[1] =   12; clipped = 1; }
380   } else {
381     if (ratio[1] < -264 || ratio[1] > 461) return 2;
382     if (ratio[1] < -50)
383       { ratio[1] = -50; clipped = 1; }
384     if (ratio[1] > 307)
385       { ratio[1] = 307; clipped = 1; }
386   }
387   target = flash_used || ratio[1] < 197
388 	? -38 - (398 * ratio[1] >> 10)
389 	: -123 + (48 * ratio[1] >> 10);
390   if (target - mar <= ratio[0] &&
391       target + 20  >= ratio[0] && !clipped) return 0;
392   miss = target - ratio[0];
393   if (abs(miss) >= mar*4) return 2;
394   if (miss < -20) miss = -20;
395   if (miss > mar) miss = mar;
396   ratio[0] = target - miss;
397   return 1;
398 }
399 
canon_600_auto_wb()400 void CLASS canon_600_auto_wb()
401 {
402   int mar, row, col, i, j, st, count[] = { 0,0 };
403   int test[8], total[2][8], ratio[2][2], stat[2];
404 
405   memset (&total, 0, sizeof total);
406   i = canon_ev + 0.5;
407   if      (i < 10) mar = 150;
408   else if (i > 12) mar = 20;
409   else mar = 280 - 20 * i;
410   if (flash_used) mar = 80;
411   for (row=14; row < height-14; row+=4)
412     for (col=10; col < width; col+=2) {
413       for (i=0; i < 8; i++)
414 	test[(i & 4) + FC(row+(i >> 1),col+(i & 1))] =
415 		    BAYER(row+(i >> 1),col+(i & 1));
416       for (i=0; i < 8; i++)
417 	if (test[i] < 150 || test[i] > 1500) goto next;
418       for (i=0; i < 4; i++)
419 	if (abs(test[i] - test[i+4]) > 50) goto next;
420       for (i=0; i < 2; i++) {
421 	for (j=0; j < 4; j+=2)
422 	  ratio[i][j >> 1] = ((test[i*4+j+1]-test[i*4+j]) << 10) / test[i*4+j];
423 	stat[i] = canon_600_color (ratio[i], mar);
424       }
425       if ((st = stat[0] | stat[1]) > 1) goto next;
426       for (i=0; i < 2; i++)
427 	if (stat[i])
428 	  for (j=0; j < 2; j++)
429 	    test[i*4+j*2+1] = test[i*4+j*2] * (0x400 + ratio[i][j]) >> 10;
430       for (i=0; i < 8; i++)
431 	total[st][i] += test[i];
432       count[st]++;
433 next: ;
434     }
435   if (count[0] | count[1]) {
436     st = count[0]*200 < count[1];
437     for (i=0; i < 4; i++)
438       pre_mul[i] = 1.0 / (total[st][i] + total[st][i+4]);
439   }
440 }
441 
canon_600_coeff()442 void CLASS canon_600_coeff()
443 {
444   static const short table[6][12] = {
445     { -190,702,-1878,2390,   1861,-1349,905,-393, -432,944,2617,-2105  },
446     { -1203,1715,-1136,1648, 1388,-876,267,245,  -1641,2153,3921,-3409 },
447     { -615,1127,-1563,2075,  1437,-925,509,3,     -756,1268,2519,-2007 },
448     { -190,702,-1886,2398,   2153,-1641,763,-251, -452,964,3040,-2528  },
449     { -190,702,-1878,2390,   1861,-1349,905,-393, -432,944,2617,-2105  },
450     { -807,1319,-1785,2297,  1388,-876,769,-257,  -230,742,2067,-1555  } };
451   int t=0, i, c;
452   float mc, yc;
453 
454   mc = pre_mul[1] / pre_mul[2];
455   yc = pre_mul[3] / pre_mul[2];
456   if (mc > 1 && mc <= 1.28 && yc < 0.8789) t=1;
457   if (mc > 1.28 && mc <= 2) {
458     if  (yc < 0.8789) t=3;
459     else if (yc <= 2) t=4;
460   }
461   if (flash_used) t=5;
462   for (raw_color = i=0; i < 3; i++)
463     FORCC rgb_cam[i][c] = table[t][i*4 + c] / 1024.0;
464 }
465 
canon_600_load_raw()466 void CLASS canon_600_load_raw()
467 {
468   uchar  data[1120], *dp;
469   ushort pixel[896], *pix;
470   int irow, row, col, val;
471   static const short mul[4][2] =
472   { { 1141,1145 }, { 1128,1109 }, { 1178,1149 }, { 1128,1109 } };
473 
474   for (irow=row=0; irow < height; irow++) {
475     if (fread (data, 1, raw_width*5/4, ifp) < raw_width*5/4) derror();
476     for (dp=data, pix=pixel; dp < data+1120; dp+=10, pix+=8) {
477       pix[0] = (dp[0] << 2) + (dp[1] >> 6    );
478       pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3);
479       pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3);
480       pix[3] = (dp[4] << 2) + (dp[1]      & 3);
481       pix[4] = (dp[5] << 2) + (dp[9]      & 3);
482       pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3);
483       pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3);
484       pix[7] = (dp[8] << 2) + (dp[9] >> 6    );
485     }
486     for (col=0; col < width; col++)
487       BAYER(row,col) = pixel[col];
488     for (col=width; col < raw_width; col++)
489       black += pixel[col];
490     if ((row+=2) > height) row = 1;
491   }
492   if (raw_width > width)
493     black = black / ((raw_width - width) * height) - 4;
494   for (row=0; row < height; row++)
495     for (col=0; col < width; col++) {
496       if ((val = BAYER(row,col) - black) < 0) val = 0;
497       val = val * mul[row & 3][col & 1] >> 9;
498       BAYER(row,col) = val;
499     }
500   canon_600_fixed_wb(1311);
501   canon_600_auto_wb();
502   canon_600_coeff();
503   maximum = (0x3ff - black) * 1109 >> 9;
504   black = 0;
505 }
506 
remove_zeroes()507 void CLASS remove_zeroes()
508 {
509   unsigned row, col, tot, n, r, c;
510 
511   for (row=0; row < height; row++)
512     for (col=0; col < width; col++)
513       if (BAYER(row,col) == 0) {
514 	tot = n = 0;
515 	for (r = row-2; r <= row+2; r++)
516 	  for (c = col-2; c <= col+2; c++)
517 	    if (r < height && c < width &&
518 		FC(r,c) == FC(row,col) && BAYER(r,c))
519 	      tot += (n++,BAYER(r,c));
520 	if (n) BAYER(row,col) = tot/n;
521       }
522 }
523 
canon_s2is()524 int CLASS canon_s2is()
525 {
526   unsigned row;
527 
528   for (row=0; row < 100; row++) {
529     fseek (ifp, row*3340 + 3284, SEEK_SET);
530     if (getc(ifp) > 15) return 1;
531   }
532   return 0;
533 }
534 
535 /*
536    getbits(-1) initializes the buffer
537    getbits(n) where 0 <= n <= 25 returns an n-bit integer
538  */
getbithuff(int nbits,ushort * huff)539 unsigned CLASS getbithuff (int nbits, ushort *huff)
540 {
541   static unsigned bitbuf=0;
542   static int vbits=0, reset=0;
543   unsigned c;
544 
545   if (nbits == -1)
546     return bitbuf = vbits = reset = 0;
547   if (nbits == 0 || vbits < 0) return 0;
548   while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF &&
549     !(reset = zero_after_ff && c == 0xff && fgetc(ifp))) {
550     bitbuf = (bitbuf << 8) + (uchar) c;
551     vbits += 8;
552   }
553   c = bitbuf << (32-vbits) >> (32-nbits);
554   if (huff) {
555     vbits -= huff[c] >> 8;
556     c = (uchar) huff[c];
557   } else
558     vbits -= nbits;
559   if (vbits < 0) derror();
560   return c;
561 }
562 
563 #define getbits(n) getbithuff(n,0)
564 #define gethuff(h) getbithuff(*h,h+1)
565 
566 /*
567    Construct a decode tree according the specification in *source.
568    The first 16 bytes specify how many codes should be 1-bit, 2-bit
569    3-bit, etc.  Bytes after that are the leaf values.
570 
571    For example, if the source is
572 
573     { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
574       0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff  },
575 
576    then the code is
577 
578 	00		0x04
579 	010		0x03
580 	011		0x05
581 	100		0x06
582 	101		0x02
583 	1100		0x07
584 	1101		0x01
585 	11100		0x08
586 	11101		0x09
587 	11110		0x00
588 	111110		0x0a
589 	1111110		0x0b
590 	1111111		0xff
591  */
make_decoder_ref(const uchar ** source)592 ushort * CLASS make_decoder_ref (const uchar **source)
593 {
594   int max, len, h, i, j;
595   const uchar *count;
596   ushort *huff;
597 
598   count = (*source += 16) - 17;
599   for (max=16; max && !count[max]; max--);
600   huff = (ushort *) calloc (1 + (1 << max), sizeof *huff);
601   merror (huff, "make_decoder()");
602   huff[0] = max;
603   for (h=len=1; len <= max; len++)
604     for (i=0; i < count[len]; i++, ++*source)
605       for (j=0; j < 1 << (max-len); j++)
606 	if (h <= 1 << max)
607 	  huff[h++] = len << 8 | **source;
608   return huff;
609 }
610 
make_decoder(const uchar * source)611 ushort * CLASS make_decoder (const uchar *source)
612 {
613   return make_decoder_ref (&source);
614 }
615 
crw_init_tables(unsigned table,ushort * huff[2])616 void CLASS crw_init_tables (unsigned table, ushort *huff[2])
617 {
618   static const uchar first_tree[3][29] = {
619     { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
620       0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff  },
621     { 0,2,2,3,1,1,1,1,2,0,0,0,0,0,0,0,
622       0x03,0x02,0x04,0x01,0x05,0x00,0x06,0x07,0x09,0x08,0x0a,0x0b,0xff  },
623     { 0,0,6,3,1,1,2,0,0,0,0,0,0,0,0,0,
624       0x06,0x05,0x07,0x04,0x08,0x03,0x09,0x02,0x00,0x0a,0x01,0x0b,0xff  },
625   };
626   static const uchar second_tree[3][180] = {
627     { 0,2,2,2,1,4,2,1,2,5,1,1,0,0,0,139,
628       0x03,0x04,0x02,0x05,0x01,0x06,0x07,0x08,
629       0x12,0x13,0x11,0x14,0x09,0x15,0x22,0x00,0x21,0x16,0x0a,0xf0,
630       0x23,0x17,0x24,0x31,0x32,0x18,0x19,0x33,0x25,0x41,0x34,0x42,
631       0x35,0x51,0x36,0x37,0x38,0x29,0x79,0x26,0x1a,0x39,0x56,0x57,
632       0x28,0x27,0x52,0x55,0x58,0x43,0x76,0x59,0x77,0x54,0x61,0xf9,
633       0x71,0x78,0x75,0x96,0x97,0x49,0xb7,0x53,0xd7,0x74,0xb6,0x98,
634       0x47,0x48,0x95,0x69,0x99,0x91,0xfa,0xb8,0x68,0xb5,0xb9,0xd6,
635       0xf7,0xd8,0x67,0x46,0x45,0x94,0x89,0xf8,0x81,0xd5,0xf6,0xb4,
636       0x88,0xb1,0x2a,0x44,0x72,0xd9,0x87,0x66,0xd4,0xf5,0x3a,0xa7,
637       0x73,0xa9,0xa8,0x86,0x62,0xc7,0x65,0xc8,0xc9,0xa1,0xf4,0xd1,
638       0xe9,0x5a,0x92,0x85,0xa6,0xe7,0x93,0xe8,0xc1,0xc6,0x7a,0x64,
639       0xe1,0x4a,0x6a,0xe6,0xb3,0xf1,0xd3,0xa5,0x8a,0xb2,0x9a,0xba,
640       0x84,0xa4,0x63,0xe5,0xc5,0xf3,0xd2,0xc4,0x82,0xaa,0xda,0xe4,
641       0xf2,0xca,0x83,0xa3,0xa2,0xc3,0xea,0xc2,0xe2,0xe3,0xff,0xff  },
642     { 0,2,2,1,4,1,4,1,3,3,1,0,0,0,0,140,
643       0x02,0x03,0x01,0x04,0x05,0x12,0x11,0x06,
644       0x13,0x07,0x08,0x14,0x22,0x09,0x21,0x00,0x23,0x15,0x31,0x32,
645       0x0a,0x16,0xf0,0x24,0x33,0x41,0x42,0x19,0x17,0x25,0x18,0x51,
646       0x34,0x43,0x52,0x29,0x35,0x61,0x39,0x71,0x62,0x36,0x53,0x26,
647       0x38,0x1a,0x37,0x81,0x27,0x91,0x79,0x55,0x45,0x28,0x72,0x59,
648       0xa1,0xb1,0x44,0x69,0x54,0x58,0xd1,0xfa,0x57,0xe1,0xf1,0xb9,
649       0x49,0x47,0x63,0x6a,0xf9,0x56,0x46,0xa8,0x2a,0x4a,0x78,0x99,
650       0x3a,0x75,0x74,0x86,0x65,0xc1,0x76,0xb6,0x96,0xd6,0x89,0x85,
651       0xc9,0xf5,0x95,0xb4,0xc7,0xf7,0x8a,0x97,0xb8,0x73,0xb7,0xd8,
652       0xd9,0x87,0xa7,0x7a,0x48,0x82,0x84,0xea,0xf4,0xa6,0xc5,0x5a,
653       0x94,0xa4,0xc6,0x92,0xc3,0x68,0xb5,0xc8,0xe4,0xe5,0xe6,0xe9,
654       0xa2,0xa3,0xe3,0xc2,0x66,0x67,0x93,0xaa,0xd4,0xd5,0xe7,0xf8,
655       0x88,0x9a,0xd7,0x77,0xc4,0x64,0xe2,0x98,0xa5,0xca,0xda,0xe8,
656       0xf3,0xf6,0xa9,0xb2,0xb3,0xf2,0xd2,0x83,0xba,0xd3,0xff,0xff  },
657     { 0,0,6,2,1,3,3,2,5,1,2,2,8,10,0,117,
658       0x04,0x05,0x03,0x06,0x02,0x07,0x01,0x08,
659       0x09,0x12,0x13,0x14,0x11,0x15,0x0a,0x16,0x17,0xf0,0x00,0x22,
660       0x21,0x18,0x23,0x19,0x24,0x32,0x31,0x25,0x33,0x38,0x37,0x34,
661       0x35,0x36,0x39,0x79,0x57,0x58,0x59,0x28,0x56,0x78,0x27,0x41,
662       0x29,0x77,0x26,0x42,0x76,0x99,0x1a,0x55,0x98,0x97,0xf9,0x48,
663       0x54,0x96,0x89,0x47,0xb7,0x49,0xfa,0x75,0x68,0xb6,0x67,0x69,
664       0xb9,0xb8,0xd8,0x52,0xd7,0x88,0xb5,0x74,0x51,0x46,0xd9,0xf8,
665       0x3a,0xd6,0x87,0x45,0x7a,0x95,0xd5,0xf6,0x86,0xb4,0xa9,0x94,
666       0x53,0x2a,0xa8,0x43,0xf5,0xf7,0xd4,0x66,0xa7,0x5a,0x44,0x8a,
667       0xc9,0xe8,0xc8,0xe7,0x9a,0x6a,0x73,0x4a,0x61,0xc7,0xf4,0xc6,
668       0x65,0xe9,0x72,0xe6,0x71,0x91,0x93,0xa6,0xda,0x92,0x85,0x62,
669       0xf3,0xc5,0xb2,0xa4,0x84,0xba,0x64,0xa5,0xb3,0xd2,0x81,0xe5,
670       0xd3,0xaa,0xc4,0xca,0xf2,0xb1,0xe4,0xd1,0x83,0x63,0xea,0xc3,
671       0xe2,0x82,0xf1,0xa3,0xc2,0xa1,0xc1,0xe3,0xa2,0xe1,0xff,0xff  }
672   };
673   if (table > 2) table = 2;
674   huff[0] = make_decoder ( first_tree[table]);
675   huff[1] = make_decoder (second_tree[table]);
676 }
677 
678 /*
679    Return 0 if the image starts with compressed data,
680    1 if it starts with uncompressed low-order bits.
681 
682    In Canon compressed data, 0xff is always followed by 0x00.
683  */
canon_has_lowbits()684 int CLASS canon_has_lowbits()
685 {
686   uchar test[0x4000];
687   int ret=1, i;
688 
689   fseek (ifp, 0, SEEK_SET);
690   fread (test, 1, sizeof test, ifp);
691   for (i=540; i < sizeof test - 1; i++)
692     if (test[i] == 0xff) {
693       if (test[i+1]) return 1;
694       ret=0;
695     }
696   return ret;
697 }
698 
canon_compressed_load_raw()699 void CLASS canon_compressed_load_raw()
700 {
701   ushort *pixel, *prow, *huff[2];
702   int nblocks, lowbits, i, c, row, r, col, save, val;
703   unsigned irow, icol;
704   int block, diffbuf[64], leaf, len, diff, carry=0, pnum=0, base[2];
705 
706   crw_init_tables (tiff_compress, huff);
707   pixel = (ushort *) calloc (raw_width*8, sizeof *pixel);
708   merror (pixel, "canon_compressed_load_raw()");
709   lowbits = canon_has_lowbits();
710   if (!lowbits) maximum = 0x3ff;
711   fseek (ifp, 540 + lowbits*raw_height*raw_width/4, SEEK_SET);
712   zero_after_ff = 1;
713   getbits(-1);
714   for (row=0; row < raw_height; row+=8) {
715     nblocks = MIN (8, raw_height-row) * raw_width >> 6;
716     for (block=0; block < nblocks; block++) {
717       memset (diffbuf, 0, sizeof diffbuf);
718       for (i=0; i < 64; i++ ) {
719 	leaf = gethuff(huff[i > 0]);
720 	if (leaf == 0 && i) break;
721 	if (leaf == 0xff) continue;
722 	i  += leaf >> 4;
723 	len = leaf & 15;
724 	if (len == 0) continue;
725 	diff = getbits(len);
726 	if ((diff & (1 << (len-1))) == 0)
727 	  diff -= (1 << len) - 1;
728 	if (i < 64) diffbuf[i] = diff;
729       }
730       diffbuf[0] += carry;
731       carry = diffbuf[0];
732       for (i=0; i < 64; i++ ) {
733 	if (pnum++ % raw_width == 0)
734 	  base[0] = base[1] = 512;
735 	if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10)
736 	  derror();
737       }
738     }
739     if (lowbits) {
740       save = ftell(ifp);
741       fseek (ifp, 26 + row*raw_width/4, SEEK_SET);
742       for (prow=pixel, i=0; i < raw_width*2; i++) {
743 	c = fgetc(ifp);
744 	for (r=0; r < 8; r+=2, prow++) {
745 	  val = (*prow << 2) + ((c >> r) & 3);
746 	  if (raw_width == 2672 && val < 512) val += 2;
747 	  *prow = val;
748 	}
749       }
750       fseek (ifp, save, SEEK_SET);
751     }
752     for (r=0; r < 8; r++) {
753       irow = row - top_margin + r;
754       if (irow >= height) continue;
755       for (col=0; col < raw_width; col++) {
756 	icol = col - left_margin;
757 	c = FC(irow,icol);
758 	if (icol < width)
759 	  BAYER(irow,icol) = pixel[r*raw_width+col];
760 	else if (col > 1 && (unsigned) (col-left_margin+2) > width+3)
761 	  cblack[c] += (cblack[4+c]++,pixel[r*raw_width+col]);
762       }
763     }
764   }
765   free (pixel);
766   FORC(2) free (huff[c]);
767   FORC4 if (cblack[4+c]) cblack[c] /= cblack[4+c];
768 }
769 
770 /*
771    Not a full implementation of Lossless JPEG, just
772    enough to decode Canon, Kodak and Adobe DNG images.
773  */
774 struct jhead {
775   int bits, high, wide, clrs, sraw, psv, restart, vpred[6];
776   ushort *huff[6], *free[4], *row;
777 };
778 
ljpeg_start(struct jhead * jh,int info_only)779 int CLASS ljpeg_start (struct jhead *jh, int info_only)
780 {
781   int c, tag, len;
782   uchar data[0x10000];
783   const uchar *dp;
784 
785   memset (jh, 0, sizeof *jh);
786   jh->restart = INT_MAX;
787   fread (data, 2, 1, ifp);
788   if (data[1] != 0xd8) return 0;
789   do {
790     fread (data, 2, 2, ifp);
791     tag =  data[0] << 8 | data[1];
792     len = (data[2] << 8 | data[3]) - 2;
793     if (tag <= 0xff00) return 0;
794     fread (data, 1, len, ifp);
795     switch (tag) {
796       case 0xffc3:
797 	jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3;
798       case 0xffc0:
799 	jh->bits = data[0];
800 	jh->high = data[1] << 8 | data[2];
801 	jh->wide = data[3] << 8 | data[4];
802 	jh->clrs = data[5] + jh->sraw;
803 	if (len == 9 && !dng_version) getc(ifp);
804 	break;
805       case 0xffc4:
806 	if (info_only) break;
807 	for (dp = data; dp < data+len && (c = *dp++) < 4; )
808 	  jh->free[c] = jh->huff[c] = make_decoder_ref (&dp);
809 	break;
810       case 0xffda:
811 	jh->psv = data[1+data[0]*2];
812 	jh->bits -= data[3+data[0]*2] & 15;
813 	break;
814       case 0xffdd:
815 	jh->restart = data[0] << 8 | data[1];
816     }
817   } while (tag != 0xffda);
818   if (info_only) return 1;
819   FORC(5) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c];
820   if (jh->sraw) {
821     FORC(4)        jh->huff[2+c] = jh->huff[1];
822     FORC(jh->sraw) jh->huff[1+c] = jh->huff[0];
823   }
824   jh->row = (ushort *) calloc (jh->wide*jh->clrs, 4);
825   merror (jh->row, "ljpeg_start()");
826   return zero_after_ff = 1;
827 }
828 
ljpeg_end(struct jhead * jh)829 void CLASS ljpeg_end (struct jhead *jh)
830 {
831   int c;
832   FORC4 if (jh->free[c]) free (jh->free[c]);
833   free (jh->row);
834 }
835 
ljpeg_diff(ushort * huff)836 int CLASS ljpeg_diff (ushort *huff)
837 {
838   int len, diff;
839 
840   len = gethuff(huff);
841   if (len == 16 && (!dng_version || dng_version >= 0x1010000))
842     return -32768;
843   diff = getbits(len);
844   if ((diff & (1 << (len-1))) == 0)
845     diff -= (1 << len) - 1;
846   return diff;
847 }
848 
ljpeg_row(int jrow,struct jhead * jh)849 ushort * CLASS ljpeg_row (int jrow, struct jhead *jh)
850 {
851   int col, c, diff, pred, spred=0;
852   ushort mark=0, *row[3];
853 
854   if (jrow * jh->wide % jh->restart == 0) {
855     FORC(6) jh->vpred[c] = 1 << (jh->bits-1);
856     if (jrow) {
857       fseek (ifp, -2, SEEK_CUR);
858       do mark = (mark << 8) + (c = fgetc(ifp));
859       while (c != EOF && mark >> 4 != 0xffd);
860     }
861     getbits(-1);
862   }
863   FORC3 row[c] = jh->row + jh->wide*jh->clrs*((jrow+c) & 1);
864   for (col=0; col < jh->wide; col++)
865     FORC(jh->clrs) {
866       diff = ljpeg_diff (jh->huff[c]);
867       if (jh->sraw && c <= jh->sraw && (col | c))
868 		    pred = spred;
869       else if (col) pred = row[0][-jh->clrs];
870       else	    pred = (jh->vpred[c] += diff) - diff;
871       if (jrow && col) switch (jh->psv) {
872 	case 1:	break;
873 	case 2: pred = row[1][0];					break;
874 	case 3: pred = row[1][-jh->clrs];				break;
875 	case 4: pred = pred +   row[1][0] - row[1][-jh->clrs];		break;
876 	case 5: pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1);	break;
877 	case 6: pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1);	break;
878 	case 7: pred = (pred + row[1][0]) >> 1;				break;
879 	default: pred = 0;
880       }
881       if ((**row = pred + diff) >> jh->bits) derror();
882       if (c <= jh->sraw) spred = **row;
883       row[0]++; row[1]++;
884     }
885   return row[2];
886 }
887 
lossless_jpeg_load_raw()888 void CLASS lossless_jpeg_load_raw()
889 {
890   int jwide, jrow, jcol, val, jidx, c, i, j, row=0, col=0;
891   struct jhead jh;
892   int min=INT_MAX;
893   ushort *rp;
894 
895   if (!ljpeg_start (&jh, 0)) return;
896   jwide = jh.wide * jh.clrs;
897 
898   for (jrow=0; jrow < jh.high; jrow++) {
899     rp = ljpeg_row (jrow, &jh);
900     for (jcol=0; jcol < jwide; jcol++) {
901       val = *rp++;
902       if (jh.bits <= 12)
903 	val = curve[val & 0xfff];
904       if (cr2_slice[0]) {
905 	jidx = jrow*jwide + jcol;
906 	i = jidx / (cr2_slice[1]*jh.high);
907 	if ((j = i >= cr2_slice[0]))
908 		 i  = cr2_slice[0];
909 	jidx -= i * (cr2_slice[1]*jh.high);
910 	row = jidx / cr2_slice[1+j];
911 	col = jidx % cr2_slice[1+j] + i*cr2_slice[1];
912       }
913       if (raw_width == 3984 && (col -= 2) < 0)
914 	col += (row--,raw_width);
915       if ((unsigned) (row-top_margin) < height) {
916 	c = FC(row-top_margin,col-left_margin);
917 	if ((unsigned) (col-left_margin) < width) {
918 	  BAYER(row-top_margin,col-left_margin) = val;
919 	  if (min > val) min = val;
920 	} else if (col > 1 && (unsigned) (col-left_margin+2) > width+3)
921 	  cblack[c] += (cblack[4+c]++,val);
922       }
923       if (++col >= raw_width)
924 	col = (row++,0);
925     }
926   }
927   ljpeg_end (&jh);
928   FORC4 if (cblack[4+c]) cblack[c] /= cblack[4+c];
929   if (!strcasecmp(make,"KODAK"))
930     black = min;
931 }
932 
canon_sraw_load_raw()933 void CLASS canon_sraw_load_raw()
934 {
935   struct jhead jh;
936   short *rp=0, (*ip)[4];
937   int jwide, slice, scol, ecol, row, col, jrow=0, jcol=0, pix[3], c;
938   int v[3]={0,0,0}, ver, hue;
939   char *cp;
940 
941   if (!ljpeg_start (&jh, 0)) return;
942   jwide = (jh.wide >>= 1) * jh.clrs;
943 
944   for (ecol=slice=0; slice <= cr2_slice[0]; slice++) {
945     scol = ecol;
946     ecol += cr2_slice[1] * 2 / jh.clrs;
947     if (!cr2_slice[0] || ecol > raw_width-1) ecol = raw_width & -2;
948     for (row=0; row < height; row += (jh.clrs >> 1) - 1) {
949       ip = (short (*)[4]) image + row*width;
950       for (col=scol; col < ecol; col+=2, jcol+=jh.clrs) {
951 	if ((jcol %= jwide) == 0)
952 	  rp = (short *) ljpeg_row (jrow++, &jh);
953 	if (col >= width) continue;
954 	FORC (jh.clrs-2)
955 	  ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c];
956 	ip[col][1] = rp[jcol+jh.clrs-2] - 16384;
957 	ip[col][2] = rp[jcol+jh.clrs-1] - 16384;
958       }
959     }
960   }
961   for (cp=model2; *cp && !isdigit(*cp); cp++);
962   sscanf (cp, "%d.%d.%d", v, v+1, v+2);
963   ver = (v[0]*1000 + v[1])*1000 + v[2];
964   hue = (jh.sraw+1) << 2;
965   if (unique_id == 0x80000218 && ver > 1000006 && ver < 3000000)
966     hue = jh.sraw << 1;
967   ip = (short (*)[4]) image;
968   rp = ip[0];
969   for (row=0; row < height; row++, ip+=width) {
970     if (row & (jh.sraw >> 1))
971       for (col=0; col < width; col+=2)
972 	for (c=1; c < 3; c++)
973 	  if (row == height-1)
974 	       ip[col][c] =  ip[col-width][c];
975 	  else ip[col][c] = (ip[col-width][c] + ip[col+width][c] + 1) >> 1;
976     for (col=1; col < width; col+=2)
977       for (c=1; c < 3; c++)
978 	if (col == width-1)
979 	     ip[col][c] =  ip[col-1][c];
980 	else ip[col][c] = (ip[col-1][c] + ip[col+1][c] + 1) >> 1;
981   }
982   for ( ; rp < ip[0]; rp+=4) {
983     if (unique_id < 0x80000218) {
984       pix[0] = rp[0] + rp[2] - 512;
985       pix[2] = rp[0] + rp[1] - 512;
986       pix[1] = rp[0] + ((-778*rp[1] - (rp[2] << 11)) >> 12) - 512;
987     } else {
988       rp[1] = (rp[1] << 2) + hue;
989       rp[2] = (rp[2] << 2) + hue;
990       pix[0] = rp[0] + ((  200*rp[1] + 22929*rp[2]) >> 14);
991       pix[1] = rp[0] + ((-5640*rp[1] - 11751*rp[2]) >> 14);
992       pix[2] = rp[0] + ((29040*rp[1] -   101*rp[2]) >> 14);
993     }
994     FORC3 rp[c] = CLIP(pix[c] * sraw_mul[c] >> 10);
995   }
996   ljpeg_end (&jh);
997   maximum = 0x3fff;
998 }
999 
adobe_copy_pixel(int row,int col,ushort ** rp)1000 void CLASS adobe_copy_pixel (int row, int col, ushort **rp)
1001 {
1002   unsigned r, c;
1003 
1004   r = row -= top_margin;
1005   c = col -= left_margin;
1006   if (is_raw == 2 && shot_select) (*rp)++;
1007   if (filters) {
1008     if (fuji_width) {
1009       r = row + fuji_width - 1 - (col >> 1);
1010       c = row + ((col+1) >> 1);
1011     }
1012     if (r < height && c < width)
1013       BAYER(r,c) = **rp < 0x1000 ? curve[**rp] : **rp;
1014     *rp += is_raw;
1015   } else {
1016     if (r < height && c < width)
1017       FORC(tiff_samples)
1018 	image[row*width+col][c] = (*rp)[c] < 0x1000 ? curve[(*rp)[c]]:(*rp)[c];
1019     *rp += tiff_samples;
1020   }
1021   if (is_raw == 2 && shot_select) (*rp)--;
1022 }
1023 
adobe_dng_load_raw_lj()1024 void CLASS adobe_dng_load_raw_lj()
1025 {
1026   unsigned save, trow=0, tcol=0, jwide, jrow, jcol, row, col;
1027   struct jhead jh;
1028   ushort *rp;
1029 
1030   while (trow < raw_height) {
1031     save = ftell(ifp);
1032     if (tile_length < INT_MAX)
1033       fseek (ifp, get4(), SEEK_SET);
1034     if (!ljpeg_start (&jh, 0)) break;
1035     jwide = jh.wide;
1036     if (filters) jwide *= jh.clrs;
1037     jwide /= is_raw;
1038     for (row=col=jrow=0; jrow < jh.high; jrow++) {
1039       rp = ljpeg_row (jrow, &jh);
1040       for (jcol=0; jcol < jwide; jcol++) {
1041 	adobe_copy_pixel (trow+row, tcol+col, &rp);
1042 	if (++col >= tile_width || col >= raw_width)
1043 	  row += 1 + (col = 0);
1044       }
1045     }
1046     fseek (ifp, save+4, SEEK_SET);
1047     if ((tcol += tile_width) >= raw_width)
1048       trow += tile_length + (tcol = 0);
1049     ljpeg_end (&jh);
1050   }
1051 }
1052 
adobe_dng_load_raw_nc()1053 void CLASS adobe_dng_load_raw_nc()
1054 {
1055   ushort *pixel, *rp;
1056   int row, col;
1057 
1058   pixel = (ushort *) calloc (raw_width * tiff_samples, sizeof *pixel);
1059   merror (pixel, "adobe_dng_load_raw_nc()");
1060   for (row=0; row < raw_height; row++) {
1061     if (tiff_bps == 16)
1062       read_shorts (pixel, raw_width * tiff_samples);
1063     else {
1064       getbits(-1);
1065       for (col=0; col < raw_width * tiff_samples; col++)
1066 	pixel[col] = getbits(tiff_bps);
1067     }
1068     for (rp=pixel, col=0; col < raw_width; col++)
1069       adobe_copy_pixel (row, col, &rp);
1070   }
1071   free (pixel);
1072 }
1073 
pentax_load_raw()1074 void CLASS pentax_load_raw()
1075 {
1076   ushort bit[2][15], huff[4097];
1077   int dep, row, col, diff, c, i;
1078   ushort vpred[2][2] = {{0,0},{0,0}}, hpred[2];
1079 
1080   fseek (ifp, meta_offset, SEEK_SET);
1081   dep = (get2() + 12) & 15;
1082   fseek (ifp, 12, SEEK_CUR);
1083   FORC(dep) bit[0][c] = get2();
1084   FORC(dep) bit[1][c] = fgetc(ifp);
1085   FORC(dep)
1086     for (i=bit[0][c]; i <= ((bit[0][c]+(4096 >> bit[1][c])-1) & 4095); )
1087       huff[++i] = bit[1][c] << 8 | c;
1088   huff[0] = 12;
1089   fseek (ifp, data_offset, SEEK_SET);
1090   getbits(-1);
1091   for (row=0; row < raw_height; row++)
1092     for (col=0; col < raw_width; col++) {
1093       diff = ljpeg_diff (huff);
1094       if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
1095       else	   hpred[col & 1] += diff;
1096       if ((unsigned) (row-top_margin) < height &&
1097 	  (unsigned) (col-left_margin) < width)
1098 	BAYER(row-top_margin,col-left_margin) = hpred[col & 1];
1099       if (hpred[col & 1] >> tiff_bps) derror();
1100     }
1101 }
1102 
nikon_compressed_load_raw()1103 void CLASS nikon_compressed_load_raw()
1104 {
1105   static const uchar nikon_tree[][32] = {
1106     { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0,	/* 12-bit lossy */
1107       5,4,3,6,2,7,1,0,8,9,11,10,12 },
1108     { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0,	/* 12-bit lossy after split */
1109       0x39,0x5a,0x38,0x27,0x16,5,4,3,2,1,0,11,12,12 },
1110     { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,  /* 12-bit lossless */
1111       5,4,6,3,7,2,8,1,9,0,10,11,12 },
1112     { 0,1,4,3,1,1,1,1,1,2,0,0,0,0,0,0,	/* 14-bit lossy */
1113       5,6,4,7,8,3,9,2,1,0,10,11,12,13,14 },
1114     { 0,1,5,1,1,1,1,1,1,1,2,0,0,0,0,0,	/* 14-bit lossy after split */
1115       8,0x5c,0x4b,0x3a,0x29,7,6,5,4,3,2,1,0,13,14 },
1116     { 0,1,4,2,2,3,1,2,0,0,0,0,0,0,0,0,	/* 14-bit lossless */
1117       7,6,8,5,9,4,10,3,11,12,2,0,1,13,14 } };
1118   ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize;
1119   int i, min, max, step=0, tree=0, split=0, row, col, len, shl, diff;
1120 
1121   fseek (ifp, meta_offset, SEEK_SET);
1122   ver0 = fgetc(ifp);
1123   ver1 = fgetc(ifp);
1124   if (ver0 == 0x49 || ver1 == 0x58)
1125     fseek (ifp, 2110, SEEK_CUR);
1126   if (ver0 == 0x46) tree = 2;
1127   if (tiff_bps == 14) tree += 3;
1128   read_shorts (vpred[0], 4);
1129   max = 1 << tiff_bps & 0x7fff;
1130   if ((csize = get2()) > 1)
1131     step = max / (csize-1);
1132   if (ver0 == 0x44 && ver1 == 0x20 && step > 0) {
1133     for (i=0; i < csize; i++)
1134       curve[i*step] = get2();
1135     for (i=0; i < max; i++)
1136       curve[i] = ( curve[i-i%step]*(step-i%step) +
1137 		   curve[i-i%step+step]*(i%step) ) / step;
1138     fseek (ifp, meta_offset+562, SEEK_SET);
1139     split = get2();
1140   } else if (ver0 != 0x46 && csize <= 0x4001)
1141     read_shorts (curve, max=csize);
1142   while (curve[max-2] == curve[max-1]) max--;
1143   huff = make_decoder (nikon_tree[tree]);
1144   fseek (ifp, data_offset, SEEK_SET);
1145   getbits(-1);
1146   for (min=row=0; row < height; row++) {
1147     if (split && row == split) {
1148       free (huff);
1149       huff = make_decoder (nikon_tree[tree+1]);
1150       max += (min = 16) << 1;
1151     }
1152     for (col=0; col < raw_width; col++) {
1153       i = gethuff(huff);
1154       len = i & 15;
1155       shl = i >> 4;
1156       diff = ((getbits(len-shl) << 1) + 1) << shl >> 1;
1157       if ((diff & (1 << (len-1))) == 0)
1158 	diff -= (1 << len) - !shl;
1159       if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
1160       else	   hpred[col & 1] += diff;
1161       if ((ushort)(hpred[col & 1] + min) >= max) derror();
1162       if ((unsigned) (col-left_margin) < width)
1163 	BAYER(row,col-left_margin) = curve[LIM((short)hpred[col & 1],0,0x3fff)];
1164     }
1165   }
1166   free (huff);
1167 }
1168 
1169 /*
1170    Figure out if a NEF file is compressed.  These fancy heuristics
1171    are only needed for the D100, thanks to a bug in some cameras
1172    that tags all images as "compressed".
1173  */
nikon_is_compressed()1174 int CLASS nikon_is_compressed()
1175 {
1176   uchar test[256];
1177   int i;
1178 
1179   fseek (ifp, data_offset, SEEK_SET);
1180   fread (test, 1, 256, ifp);
1181   for (i=15; i < 256; i+=16)
1182     if (test[i]) return 1;
1183   return 0;
1184 }
1185 
1186 /*
1187    Returns 1 for a Coolpix 995, 0 for anything else.
1188  */
nikon_e995()1189 int CLASS nikon_e995()
1190 {
1191   int i, histo[256];
1192   const uchar often[] = { 0x00, 0x55, 0xaa, 0xff };
1193 
1194   memset (histo, 0, sizeof histo);
1195   fseek (ifp, -2000, SEEK_END);
1196   for (i=0; i < 2000; i++)
1197     histo[fgetc(ifp)]++;
1198   for (i=0; i < 4; i++)
1199     if (histo[often[i]] < 200)
1200       return 0;
1201   return 1;
1202 }
1203 
1204 /*
1205    Returns 1 for a Coolpix 2100, 0 for anything else.
1206  */
nikon_e2100()1207 int CLASS nikon_e2100()
1208 {
1209   uchar t[12];
1210   int i;
1211 
1212   fseek (ifp, 0, SEEK_SET);
1213   for (i=0; i < 1024; i++) {
1214     fread (t, 1, 12, ifp);
1215     if (((t[2] & t[4] & t[7] & t[9]) >> 4
1216 	& t[1] & t[6] & t[8] & t[11] & 3) != 3)
1217       return 0;
1218   }
1219   return 1;
1220 }
1221 
nikon_3700()1222 void CLASS nikon_3700()
1223 {
1224   int bits, i;
1225   uchar dp[24];
1226   static const struct {
1227     int bits;
1228     char make[12], model[15];
1229   } table[] = {
1230     { 0x00, "PENTAX",  "Optio 33WR" },
1231     { 0x03, "NIKON",   "E3200" },
1232     { 0x32, "NIKON",   "E3700" },
1233     { 0x33, "OLYMPUS", "C740UZ" } };
1234 
1235   fseek (ifp, 3072, SEEK_SET);
1236   fread (dp, 1, 24, ifp);
1237   bits = (dp[8] & 3) << 4 | (dp[20] & 3);
1238   for (i=0; i < sizeof table / sizeof *table; i++)
1239     if (bits == table[i].bits) {
1240       strcpy (make,  table[i].make );
1241       strcpy (model, table[i].model);
1242     }
1243 }
1244 
1245 /*
1246    Separates a Minolta DiMAGE Z2 from a Nikon E4300.
1247  */
minolta_z2()1248 int CLASS minolta_z2()
1249 {
1250   int i, nz;
1251   char tail[424];
1252 
1253   fseek (ifp, -sizeof tail, SEEK_END);
1254   fread (tail, 1, sizeof tail, ifp);
1255   for (nz=i=0; i < sizeof tail; i++)
1256     if (tail[i]) nz++;
1257   return nz > 20;
1258 }
1259 
1260 /*
1261    The Fuji Super CCD is just a Bayer grid rotated 45 degrees.
1262  */
fuji_load_raw()1263 void CLASS fuji_load_raw()
1264 {
1265   ushort *pixel;
1266   int wide, row, col, r, c;
1267 
1268   fseek (ifp, (top_margin*raw_width + left_margin) * 2, SEEK_CUR);
1269   wide = fuji_width << !fuji_layout;
1270   pixel = (ushort *) calloc (wide, sizeof *pixel);
1271   merror (pixel, "fuji_load_raw()");
1272   for (row=0; row < raw_height; row++) {
1273     read_shorts (pixel, wide);
1274     fseek (ifp, 2*(raw_width - wide), SEEK_CUR);
1275     for (col=0; col < wide; col++) {
1276       if (fuji_layout) {
1277 	r = fuji_width - 1 - col + (row >> 1);
1278 	c = col + ((row+1) >> 1);
1279       } else {
1280 	r = fuji_width - 1 + row - (col >> 1);
1281 	c = row + ((col+1) >> 1);
1282       }
1283       BAYER(r,c) = pixel[col];
1284     }
1285   }
1286   free (pixel);
1287 }
1288 
1289 void CLASS jpeg_thumb();
1290 
ppm_thumb()1291 void CLASS ppm_thumb()
1292 {
1293   char *thumb;
1294   thumb_length = thumb_width*thumb_height*3;
1295   thumb = (char *) malloc (thumb_length);
1296   merror (thumb, "ppm_thumb()");
1297   fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
1298   fread  (thumb, 1, thumb_length, ifp);
1299   fwrite (thumb, 1, thumb_length, ofp);
1300   free (thumb);
1301 }
1302 
layer_thumb()1303 void CLASS layer_thumb()
1304 {
1305   int i, c;
1306   char *thumb, map[][4] = { "012","102" };
1307 
1308   colors = thumb_misc >> 5 & 7;
1309   thumb_length = thumb_width*thumb_height;
1310   thumb = (char *) calloc (colors, thumb_length);
1311   merror (thumb, "layer_thumb()");
1312   fprintf (ofp, "P%d\n%d %d\n255\n",
1313 	5 + (colors >> 1), thumb_width, thumb_height);
1314   fread (thumb, thumb_length, colors, ifp);
1315   for (i=0; i < thumb_length; i++)
1316     FORCC putc (thumb[i+thumb_length*(map[thumb_misc >> 8][c]-'0')], ofp);
1317   free (thumb);
1318 }
1319 
rollei_thumb()1320 void CLASS rollei_thumb()
1321 {
1322   unsigned i;
1323   ushort *thumb;
1324 
1325   thumb_length = thumb_width * thumb_height;
1326   thumb = (ushort *) calloc (thumb_length, 2);
1327   merror (thumb, "rollei_thumb()");
1328   fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
1329   read_shorts (thumb, thumb_length);
1330   for (i=0; i < thumb_length; i++) {
1331     putc (thumb[i] << 3, ofp);
1332     putc (thumb[i] >> 5  << 2, ofp);
1333     putc (thumb[i] >> 11 << 3, ofp);
1334   }
1335   free (thumb);
1336 }
1337 
rollei_load_raw()1338 void CLASS rollei_load_raw()
1339 {
1340   uchar pixel[10];
1341   unsigned iten=0, isix, i, buffer=0, row, col, todo[16];
1342 
1343   isix = raw_width * raw_height * 5 / 8;
1344   while (fread (pixel, 1, 10, ifp) == 10) {
1345     for (i=0; i < 10; i+=2) {
1346       todo[i]   = iten++;
1347       todo[i+1] = pixel[i] << 8 | pixel[i+1];
1348       buffer    = pixel[i] >> 2 | buffer << 6;
1349     }
1350     for (   ; i < 16; i+=2) {
1351       todo[i]   = isix++;
1352       todo[i+1] = buffer >> (14-i)*5;
1353     }
1354     for (i=0; i < 16; i+=2) {
1355       row = todo[i] / raw_width - top_margin;
1356       col = todo[i] % raw_width - left_margin;
1357       if (row < height && col < width)
1358 	BAYER(row,col) = (todo[i+1] & 0x3ff);
1359     }
1360   }
1361   maximum = 0x3ff;
1362 }
1363 
bayer(unsigned row,unsigned col)1364 int CLASS bayer (unsigned row, unsigned col)
1365 {
1366   return (row < height && col < width) ? BAYER(row,col) : 0;
1367 }
1368 
phase_one_flat_field(int is_float,int nc)1369 void CLASS phase_one_flat_field (int is_float, int nc)
1370 {
1371   ushort head[8];
1372   unsigned wide, y, x, c, rend, cend, row, col;
1373   float *mrow, num, mult[4];
1374 
1375   read_shorts (head, 8);
1376   wide = head[2] / head[4];
1377   mrow = (float *) calloc (nc*wide, sizeof *mrow);
1378   merror (mrow, "phase_one_flat_field()");
1379   for (y=0; y < head[3] / head[5]; y++) {
1380     for (x=0; x < wide; x++)
1381       for (c=0; c < nc; c+=2) {
1382 	num = is_float ? getreal(11) : get2()/32768.0;
1383 	if (y==0) mrow[c*wide+x] = num;
1384 	else mrow[(c+1)*wide+x] = (num - mrow[c*wide+x]) / head[5];
1385       }
1386     if (y==0) continue;
1387     rend = head[1]-top_margin + y*head[5];
1388     for (row = rend-head[5]; row < height && row < rend; row++) {
1389       for (x=1; x < wide; x++) {
1390 	for (c=0; c < nc; c+=2) {
1391 	  mult[c] = mrow[c*wide+x-1];
1392 	  mult[c+1] = (mrow[c*wide+x] - mult[c]) / head[4];
1393 	}
1394 	cend = head[0]-left_margin + x*head[4];
1395 	for (col = cend-head[4]; col < width && col < cend; col++) {
1396 	  c = nc > 2 ? FC(row,col) : 0;
1397 	  if (!(c & 1)) {
1398 	    c = BAYER(row,col) * mult[c];
1399 	    BAYER(row,col) = LIM(c,0,65535);
1400 	  }
1401 	  for (c=0; c < nc; c+=2)
1402 	    mult[c] += mult[c+1];
1403 	}
1404       }
1405       for (x=0; x < wide; x++)
1406 	for (c=0; c < nc; c+=2)
1407 	  mrow[c*wide+x] += mrow[(c+1)*wide+x];
1408     }
1409   }
1410   free (mrow);
1411 }
1412 
phase_one_correct()1413 void CLASS phase_one_correct()
1414 {
1415   unsigned entries, tag, data, save, col, row, type;
1416   int len, i, j, k, cip, val[4], dev[4], sum, max;
1417   int head[9], diff, mindiff=INT_MAX, off_412=0;
1418   static const signed char dir[12][2] =
1419     { {-1,-1}, {-1,1}, {1,-1}, {1,1}, {-2,0}, {0,-2}, {0,2}, {2,0},
1420       {-2,-2}, {-2,2}, {2,-2}, {2,2} };
1421   float poly[8], num, cfrac, frac, mult[2], *yval[2];
1422   ushort *xval[2];
1423 
1424   if (half_size || !meta_length) return;
1425   if (verbose) fprintf (stderr,_("Phase One correction...\n"));
1426   fseek (ifp, meta_offset, SEEK_SET);
1427   order = get2();
1428   fseek (ifp, 6, SEEK_CUR);
1429   fseek (ifp, meta_offset+get4(), SEEK_SET);
1430   entries = get4();  get4();
1431   while (entries--) {
1432     tag  = get4();
1433     len  = get4();
1434     data = get4();
1435     save = ftell(ifp);
1436     fseek (ifp, meta_offset+data, SEEK_SET);
1437     if (tag == 0x419) {				/* Polynomial curve */
1438       for (get4(), i=0; i < 8; i++)
1439 	poly[i] = getreal(11);
1440       poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1;
1441       for (i=0; i < 0x10000; i++) {
1442 	num = (poly[5]*i + poly[3])*i + poly[1];
1443 	curve[i] = LIM(num,0,65535);
1444       } goto apply;				/* apply to right half */
1445     } else if (tag == 0x41a) {			/* Polynomial curve */
1446       for (i=0; i < 4; i++)
1447 	poly[i] = getreal(11);
1448       for (i=0; i < 0x10000; i++) {
1449 	for (num=0, j=4; j--; )
1450 	  num = num * i + poly[j];
1451 	curve[i] = LIM(num+i,0,65535);
1452       } apply:					/* apply to whole image */
1453       for (row=0; row < height; row++)
1454 	for (col = (tag & 1)*ph1.split_col; col < width; col++)
1455 	  BAYER(row,col) = curve[BAYER(row,col)];
1456     } else if (tag == 0x400) {			/* Sensor defects */
1457       while ((len -= 8) >= 0) {
1458 	col  = get2() - left_margin;
1459 	row  = get2() - top_margin;
1460 	type = get2(); get2();
1461 	if (col >= width) continue;
1462 	if (type == 131)			/* Bad column */
1463 	  for (row=0; row < height; row++)
1464 	    if (FC(row,col) == 1) {
1465 	      for (sum=i=0; i < 4; i++)
1466 		sum += val[i] = bayer (row+dir[i][0], col+dir[i][1]);
1467 	      for (max=i=0; i < 4; i++) {
1468 		dev[i] = abs((val[i] << 2) - sum);
1469 		if (dev[max] < dev[i]) max = i;
1470 	      }
1471 	      BAYER(row,col) = (sum - val[max])/3.0 + 0.5;
1472 	    } else {
1473 	      for (sum=0, i=8; i < 12; i++)
1474 		sum += bayer (row+dir[i][0], col+dir[i][1]);
1475 	      BAYER(row,col) = 0.5 + sum * 0.0732233 +
1476 		(bayer(row,col-2) + bayer(row,col+2)) * 0.3535534;
1477 	    }
1478 	else if (type == 129) {			/* Bad pixel */
1479 	  if (row >= height) continue;
1480 	  j = (FC(row,col) != 1) * 4;
1481 	  for (sum=0, i=j; i < j+8; i++)
1482 	    sum += bayer (row+dir[i][0], col+dir[i][1]);
1483 	  BAYER(row,col) = (sum + 4) >> 3;
1484 	}
1485       }
1486     } else if (tag == 0x401) {			/* All-color flat fields */
1487       phase_one_flat_field (1, 2);
1488     } else if (tag == 0x416 || tag == 0x410) {
1489       phase_one_flat_field (0, 2);
1490     } else if (tag == 0x40b) {			/* Red+blue flat field */
1491       phase_one_flat_field (0, 4);
1492     } else if (tag == 0x412) {
1493       fseek (ifp, 36, SEEK_CUR);
1494       diff = abs (get2() - ph1.tag_21a);
1495       if (mindiff > diff) {
1496 	mindiff = diff;
1497 	off_412 = ftell(ifp) - 38;
1498       }
1499     }
1500     fseek (ifp, save, SEEK_SET);
1501   }
1502   if (off_412) {
1503     fseek (ifp, off_412, SEEK_SET);
1504     for (i=0; i < 9; i++) head[i] = get4() & 0x7fff;
1505     yval[0] = (float *) calloc (head[1]*head[3] + head[2]*head[4], 6);
1506     merror (yval[0], "phase_one_correct()");
1507     yval[1] = (float  *) (yval[0] + head[1]*head[3]);
1508     xval[0] = (ushort *) (yval[1] + head[2]*head[4]);
1509     xval[1] = (ushort *) (xval[0] + head[1]*head[3]);
1510     get2();
1511     for (i=0; i < 2; i++)
1512       for (j=0; j < head[i+1]*head[i+3]; j++)
1513 	yval[i][j] = getreal(11);
1514     for (i=0; i < 2; i++)
1515       for (j=0; j < head[i+1]*head[i+3]; j++)
1516 	xval[i][j] = get2();
1517     for (row=0; row < height; row++)
1518       for (col=0; col < width; col++) {
1519 	cfrac = (float) col * head[3] / raw_width;
1520 	cfrac -= cip = cfrac;
1521 	num = BAYER(row,col) * 0.5;
1522 	for (i=cip; i < cip+2; i++) {
1523 	  for (k=j=0; j < head[1]; j++)
1524 	    if (num < xval[0][k = head[1]*i+j]) break;
1525 	  frac = (j == 0 || j == head[1]) ? 0 :
1526 		(xval[0][k] - num) / (xval[0][k] - xval[0][k-1]);
1527 	  mult[i-cip] = yval[0][k-1] * frac + yval[0][k] * (1-frac);
1528 	}
1529 	i = ((mult[0] * (1-cfrac) + mult[1] * cfrac)
1530 		* (row + top_margin) + num) * 2;
1531 	BAYER(row,col) = LIM(i,0,65535);
1532       }
1533     free (yval[0]);
1534   }
1535 }
1536 
phase_one_load_raw()1537 void CLASS phase_one_load_raw()
1538 {
1539   int row, col, a, b;
1540   ushort *pixel, akey, bkey, mask;
1541 
1542   fseek (ifp, ph1.key_off, SEEK_SET);
1543   akey = get2();
1544   bkey = get2();
1545   mask = ph1.format == 1 ? 0x5555:0x1354;
1546   fseek (ifp, data_offset + top_margin*raw_width*2, SEEK_SET);
1547   pixel = (ushort *) calloc (raw_width, sizeof *pixel);
1548   merror (pixel, "phase_one_load_raw()");
1549   for (row=0; row < height; row++) {
1550     read_shorts (pixel, raw_width);
1551     if (ph1.format)
1552       for (col=0; col < raw_width; col+=2) {
1553 	a = pixel[col+0] ^ akey;
1554 	b = pixel[col+1] ^ bkey;
1555 	pixel[col+0] = (a & mask) | (b & ~mask);
1556 	pixel[col+1] = (b & mask) | (a & ~mask);
1557       }
1558     for (col=0; col < width; col++)
1559       BAYER(row,col) = pixel[col+left_margin];
1560   }
1561   free (pixel);
1562   phase_one_correct();
1563 }
1564 
ph1_bithuff(int nbits,ushort * huff)1565 unsigned CLASS ph1_bithuff (int nbits, ushort *huff)
1566 {
1567   static UINT64 bitbuf=0;
1568   static int vbits=0;
1569   unsigned c;
1570 
1571   if (nbits == -1)
1572     return bitbuf = vbits = 0;
1573   if (nbits == 0) return 0;
1574   if (vbits < nbits) {
1575     bitbuf = bitbuf << 32 | get4();
1576     vbits += 32;
1577   }
1578   c = bitbuf << (64-vbits) >> (64-nbits);
1579   if (huff) {
1580     vbits -= huff[c] >> 8;
1581     return (uchar) huff[c];
1582   }
1583   vbits -= nbits;
1584   return c;
1585 }
1586 #define ph1_bits(n) ph1_bithuff(n,0)
1587 #define ph1_huff(h) ph1_bithuff(*h,h+1)
1588 
phase_one_load_raw_c()1589 void CLASS phase_one_load_raw_c()
1590 {
1591   static const int length[] = { 8,7,6,9,11,10,5,12,14,13 };
1592   int *offset, len[2], pred[2], row, col, i, j;
1593   ushort *pixel;
1594   short (*black)[2];
1595 
1596   pixel = (ushort *) calloc (raw_width + raw_height*4, 2);
1597   merror (pixel, "phase_one_load_raw_c()");
1598   offset = (int *) (pixel + raw_width);
1599   fseek (ifp, strip_offset, SEEK_SET);
1600   for (row=0; row < raw_height; row++)
1601     offset[row] = get4();
1602   black = (short (*)[2]) offset + raw_height;
1603   fseek (ifp, ph1.black_off, SEEK_SET);
1604   if (ph1.black_off)
1605     read_shorts ((ushort *) black[0], raw_height*2);
1606   for (i=0; i < 256; i++)
1607     curve[i] = i*i / 3.969 + 0.5;
1608   for (row=0; row < raw_height; row++) {
1609     fseek (ifp, data_offset + offset[row], SEEK_SET);
1610     ph1_bits(-1);
1611     pred[0] = pred[1] = 0;
1612     for (col=0; col < raw_width; col++) {
1613       if (col >= (raw_width & -8))
1614 	len[0] = len[1] = 14;
1615       else if ((col & 7) == 0)
1616 	for (i=0; i < 2; i++) {
1617 	  for (j=0; j < 5 && !ph1_bits(1); j++);
1618 	  if (j--) len[i] = length[j*2 + ph1_bits(1)];
1619 	}
1620       if ((i = len[col & 1]) == 14)
1621 	pixel[col] = pred[col & 1] = ph1_bits(16);
1622       else
1623 	pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1));
1624       if (pred[col & 1] >> 16) derror();
1625       if (ph1.format == 5 && pixel[col] < 256)
1626 	pixel[col] = curve[pixel[col]];
1627     }
1628     if ((unsigned) (row-top_margin) < height)
1629       for (col=0; col < width; col++) {
1630 	i = (pixel[col+left_margin] << 2)
1631 		- ph1.black + black[row][col >= ph1.split_col];
1632 	if (i > 0) BAYER(row-top_margin,col) = i;
1633       }
1634   }
1635   free (pixel);
1636   phase_one_correct();
1637   maximum = 0xfffc - ph1.black;
1638 }
1639 
hasselblad_load_raw()1640 void CLASS hasselblad_load_raw()
1641 {
1642   struct jhead jh;
1643   int row, col, pred[2], len[2], diff, c;
1644 
1645   if (!ljpeg_start (&jh, 0)) return;
1646   order = 0x4949;
1647   ph1_bits(-1);
1648   for (row=-top_margin; row < height; row++) {
1649     pred[0] = pred[1] = 0x8000;
1650     for (col=-left_margin; col < raw_width-left_margin; col+=2) {
1651       FORC(2) len[c] = ph1_huff(jh.huff[0]);
1652       FORC(2) {
1653 	diff = ph1_bits(len[c]);
1654 	if ((diff & (1 << (len[c]-1))) == 0)
1655 	  diff -= (1 << len[c]) - 1;
1656 	if (diff == 65535) diff = -32768;
1657 	pred[c] += diff;
1658 	if (row >= 0 && (unsigned)(col+c) < width)
1659 	  BAYER(row,col+c) = pred[c];
1660       }
1661     }
1662   }
1663   ljpeg_end (&jh);
1664   maximum = 0xffff;
1665 }
1666 
leaf_hdr_load_raw()1667 void CLASS leaf_hdr_load_raw()
1668 {
1669   ushort *pixel;
1670   unsigned tile=0, r, c, row, col;
1671 
1672   pixel = (ushort *) calloc (raw_width, sizeof *pixel);
1673   merror (pixel, "leaf_hdr_load_raw()");
1674   FORC(tiff_samples)
1675     for (r=0; r < raw_height; r++) {
1676       if (r % tile_length == 0) {
1677 	fseek (ifp, data_offset + 4*tile++, SEEK_SET);
1678 	fseek (ifp, get4() + 2*left_margin, SEEK_SET);
1679       }
1680       if (filters && c != shot_select) continue;
1681       read_shorts (pixel, raw_width);
1682       if ((row = r - top_margin) >= height) continue;
1683       for (col=0; col < width; col++)
1684 	if (filters)  BAYER(row,col) = pixel[col];
1685 	else image[row*width+col][c] = pixel[col];
1686     }
1687   free (pixel);
1688   if (!filters) {
1689     maximum = 0xffff;
1690     raw_color = 1;
1691   }
1692 }
1693 
1694 void CLASS unpacked_load_raw();
1695 
sinar_4shot_load_raw()1696 void CLASS sinar_4shot_load_raw()
1697 {
1698   ushort *pixel;
1699   unsigned shot, row, col, r, c;
1700 
1701   if ((shot = shot_select) || half_size) {
1702     if (shot) shot--;
1703     if (shot > 3) shot = 3;
1704     fseek (ifp, data_offset + shot*4, SEEK_SET);
1705     fseek (ifp, get4(), SEEK_SET);
1706     unpacked_load_raw();
1707     return;
1708   }
1709   free (image);
1710   image = (ushort (*)[4])
1711 	calloc ((iheight=height)*(iwidth=width), sizeof *image);
1712   merror (image, "sinar_4shot_load_raw()");
1713   pixel = (ushort *) calloc (raw_width, sizeof *pixel);
1714   merror (pixel, "sinar_4shot_load_raw()");
1715   for (shot=0; shot < 4; shot++) {
1716     fseek (ifp, data_offset + shot*4, SEEK_SET);
1717     fseek (ifp, get4(), SEEK_SET);
1718     for (row=0; row < raw_height; row++) {
1719       read_shorts (pixel, raw_width);
1720       if ((r = row-top_margin - (shot >> 1 & 1)) >= height) continue;
1721       for (col=0; col < raw_width; col++) {
1722 	if ((c = col-left_margin - (shot & 1)) >= width) continue;
1723         image[r*width+c][FC(row,col)] = pixel[col];
1724       }
1725     }
1726   }
1727   free (pixel);
1728   shrink = filters = 0;
1729 }
1730 
imacon_full_load_raw()1731 void CLASS imacon_full_load_raw()
1732 {
1733   int row, col;
1734 
1735   for (row=0; row < height; row++)
1736     for (col=0; col < width; col++)
1737       read_shorts (image[row*width+col], 3);
1738 }
1739 
packed_load_raw()1740 void CLASS packed_load_raw()
1741 {
1742   int vbits=0, bwide, pwide, rbits, bite, half, irow, row, col, val, i;
1743   int zero=0;
1744   UINT64 bitbuf=0;
1745 
1746   if (raw_width * 8 >= width * tiff_bps)	/* Is raw_width in bytes? */
1747        pwide = (bwide = raw_width) * 8 / tiff_bps;
1748   else bwide = (pwide = raw_width) * tiff_bps / 8;
1749   rbits = bwide * 8 - pwide * tiff_bps;
1750   if (load_flags & 1) bwide = bwide * 16 / 15;
1751   fseek (ifp, top_margin*bwide, SEEK_CUR);
1752   bite = 8 + (load_flags & 24);
1753   half = (height+1) >> 1;
1754   for (irow=0; irow < height; irow++) {
1755     row = irow;
1756     if (load_flags & 2 &&
1757 	(row = irow % half * 2 + irow / half) == 1 &&
1758 	load_flags & 4) {
1759       if (vbits=0, tiff_compress)
1760 	fseek (ifp, data_offset - (-half*bwide & -2048), SEEK_SET);
1761       else {
1762 	fseek (ifp, 0, SEEK_END);
1763 	fseek (ifp, ftell(ifp) >> 3 << 2, SEEK_SET);
1764       }
1765     }
1766     for (col=0; col < pwide; col++) {
1767       for (vbits -= tiff_bps; vbits < 0; vbits += bite) {
1768 	bitbuf <<= bite;
1769 	for (i=0; i < bite; i+=8)
1770 	  bitbuf |= (unsigned) (fgetc(ifp) << i);
1771       }
1772       val = bitbuf << (64-tiff_bps-vbits) >> (64-tiff_bps);
1773       i = (col ^ (bite == 24)) - left_margin;
1774       if ((unsigned) i < width)
1775 	BAYER(row,i) = val;
1776       else if (load_flags & 32) {
1777 	black += val;
1778 	zero += !val;
1779       }
1780       if (load_flags & 1 && (col % 10) == 9 &&
1781 	fgetc(ifp) && col < width+left_margin) derror();
1782     }
1783     vbits -= rbits;
1784   }
1785   if (load_flags & 32 && pwide > width)
1786     black /= (pwide - width) * height;
1787   if (zero*4 > (pwide - width) * height)
1788     black = 0;
1789 }
1790 
unpacked_load_raw()1791 void CLASS unpacked_load_raw()
1792 {
1793   ushort *pixel;
1794   int row, col, bits=0;
1795 
1796   while (1 << ++bits < maximum);
1797   fseek (ifp, (top_margin*raw_width + left_margin) * 2, SEEK_CUR);
1798   pixel = (ushort *) calloc (width, sizeof *pixel);
1799   merror (pixel, "unpacked_load_raw()");
1800   for (row=0; row < height; row++) {
1801     read_shorts (pixel, width);
1802     fseek (ifp, 2*(raw_width - width), SEEK_CUR);
1803     for (col=0; col < width; col++)
1804       if ((BAYER2(row,col) = pixel[col] >> load_flags) >> bits) derror();
1805   }
1806   free (pixel);
1807 }
1808 
nokia_load_raw()1809 void CLASS nokia_load_raw()
1810 {
1811   uchar  *data,  *dp;
1812   ushort *pixel, *pix;
1813   int rev, dwide, row, c;
1814 
1815   rev = 3 * (order == 0x4949);
1816   dwide = raw_width * 5 / 4;
1817   data = (uchar *) malloc (dwide + raw_width*2);
1818   merror (data, "nokia_load_raw()");
1819   pixel = (ushort *) (data + dwide);
1820   for (row=0; row < raw_height; row++) {
1821     if (fread (data+dwide, 1, dwide, ifp) < dwide) derror();
1822     FORC(dwide) data[c] = data[dwide+(c ^ rev)];
1823     for (dp=data, pix=pixel; pix < pixel+raw_width; dp+=5, pix+=4)
1824       FORC4 pix[c] = (dp[c] << 2) | (dp[4] >> (c << 1) & 3);
1825     if (row < top_margin)
1826       FORC(width) black += pixel[c];
1827     else
1828       FORC(width) BAYER(row-top_margin,c) = pixel[c];
1829   }
1830   free (data);
1831   if (top_margin) black /= top_margin * width;
1832   maximum = 0x3ff;
1833 }
1834 
pana_bits(int nbits)1835 unsigned CLASS pana_bits (int nbits)
1836 {
1837   static uchar buf[0x4000];
1838   static int vbits;
1839   int byte;
1840 
1841   if (!nbits) return vbits=0;
1842   if (!vbits) {
1843     fread (buf+load_flags, 1, 0x4000-load_flags, ifp);
1844     fread (buf, 1, load_flags, ifp);
1845   }
1846   vbits = (vbits - nbits) & 0x1ffff;
1847   byte = vbits >> 3 ^ 0x3ff0;
1848   return (buf[byte] | buf[byte+1] << 8) >> (vbits & 7) & ~(-1 << nbits);
1849 }
1850 
panasonic_load_raw()1851 void CLASS panasonic_load_raw()
1852 {
1853   int row, col, i, j, sh=0, pred[2], nonz[2];
1854 
1855   pana_bits(0);
1856   for (row=0; row < height; row++)
1857     for (col=0; col < raw_width; col++) {
1858       if ((i = col % 14) == 0)
1859 	pred[0] = pred[1] = nonz[0] = nonz[1] = 0;
1860       if (i % 3 == 2) sh = 4 >> (3 - pana_bits(2));
1861       if (nonz[i & 1]) {
1862 	if ((j = pana_bits(8))) {
1863 	  if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4)
1864 	       pred[i & 1] &= ~(-1 << sh);
1865 	  pred[i & 1] += j << sh;
1866 	}
1867       } else if ((nonz[i & 1] = pana_bits(8)) || i > 11)
1868 	pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4);
1869       if (col < width)
1870 	if ((BAYER(row,col) = pred[col & 1]) > 4098) derror();
1871     }
1872 }
1873 
olympus_load_raw()1874 void CLASS olympus_load_raw()
1875 {
1876   ushort huff[4096];
1877   int row, col, nbits, sign, low, high, i, c, w, n, nw;
1878   int acarry[2][3], *carry, pred, diff;
1879 
1880   huff[n=0] = 0xc0c;
1881   for (i=12; i--; )
1882     FORC(2048 >> i) huff[++n] = (i+1) << 8 | i;
1883   fseek (ifp, 7, SEEK_CUR);
1884   getbits(-1);
1885   for (row=0; row < height; row++) {
1886     memset (acarry, 0, sizeof acarry);
1887     for (col=0; col < raw_width; col++) {
1888       carry = acarry[col & 1];
1889       i = 2 * (carry[2] < 3);
1890       for (nbits=2+i; (ushort) carry[0] >> (nbits+i); nbits++);
1891       low = (sign = getbits(3)) & 3;
1892       sign = sign << 29 >> 31;
1893       if ((high = getbithuff(12,huff)) == 12)
1894 	high = getbits(16-nbits) >> 1;
1895       carry[0] = (high << nbits) | getbits(nbits);
1896       diff = (carry[0] ^ sign) + carry[1];
1897       carry[1] = (diff*3 + carry[1]) >> 5;
1898       carry[2] = carry[0] > 16 ? 0 : carry[2]+1;
1899       if (col >= width) continue;
1900       if (row < 2 && col < 2) pred = 0;
1901       else if (row < 2) pred = BAYER(row,col-2);
1902       else if (col < 2) pred = BAYER(row-2,col);
1903       else {
1904 	w  = BAYER(row,col-2);
1905 	n  = BAYER(row-2,col);
1906 	nw = BAYER(row-2,col-2);
1907 	if ((w < nw && nw < n) || (n < nw && nw < w)) {
1908 	  if (ABS(w-nw) > 32 || ABS(n-nw) > 32)
1909 	    pred = w + n - nw;
1910 	  else pred = (w + n) >> 1;
1911 	} else pred = ABS(w-nw) > ABS(n-nw) ? w : n;
1912       }
1913       if ((BAYER(row,col) = pred + ((diff << 2) | low)) >> 12) derror();
1914     }
1915   }
1916 }
1917 
minolta_rd175_load_raw()1918 void CLASS minolta_rd175_load_raw()
1919 {
1920   uchar pixel[768];
1921   unsigned irow, box, row, col;
1922 
1923   for (irow=0; irow < 1481; irow++) {
1924     if (fread (pixel, 1, 768, ifp) < 768) derror();
1925     box = irow / 82;
1926     row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box-12)*2);
1927     switch (irow) {
1928       case 1477: case 1479: continue;
1929       case 1476: row = 984; break;
1930       case 1480: row = 985; break;
1931       case 1478: row = 985; box = 1;
1932     }
1933     if ((box < 12) && (box & 1)) {
1934       for (col=0; col < 1533; col++, row ^= 1)
1935 	if (col != 1) BAYER(row,col) = (col+1) & 2 ?
1936 		   pixel[col/2-1] + pixel[col/2+1] : pixel[col/2] << 1;
1937       BAYER(row,1)    = pixel[1]   << 1;
1938       BAYER(row,1533) = pixel[765] << 1;
1939     } else
1940       for (col=row & 1; col < 1534; col+=2)
1941 	BAYER(row,col) = pixel[col/2] << 1;
1942   }
1943   maximum = 0xff << 1;
1944 }
1945 
quicktake_100_load_raw()1946 void CLASS quicktake_100_load_raw()
1947 {
1948   uchar pixel[484][644];
1949   static const short gstep[16] =
1950   { -89,-60,-44,-32,-22,-15,-8,-2,2,8,15,22,32,44,60,89 };
1951   static const short rstep[6][4] =
1952   { {  -3,-1,1,3  }, {  -5,-1,1,5  }, {  -8,-2,2,8  },
1953     { -13,-3,3,13 }, { -19,-4,4,19 }, { -28,-6,6,28 } };
1954   static const short curve[256] =
1955   { 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,
1956     28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,53,
1957     54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78,
1958     79,80,81,82,83,84,86,88,90,92,94,97,99,101,103,105,107,110,112,114,116,
1959     118,120,123,125,127,129,131,134,136,138,140,142,144,147,149,151,153,155,
1960     158,160,162,164,166,168,171,173,175,177,179,181,184,186,188,190,192,195,
1961     197,199,201,203,205,208,210,212,214,216,218,221,223,226,230,235,239,244,
1962     248,252,257,261,265,270,274,278,283,287,291,296,300,305,309,313,318,322,
1963     326,331,335,339,344,348,352,357,361,365,370,374,379,383,387,392,396,400,
1964     405,409,413,418,422,426,431,435,440,444,448,453,457,461,466,470,474,479,
1965     483,487,492,496,500,508,519,531,542,553,564,575,587,598,609,620,631,643,
1966     654,665,676,687,698,710,721,732,743,754,766,777,788,799,810,822,833,844,
1967     855,866,878,889,900,911,922,933,945,956,967,978,989,1001,1012,1023 };
1968   int rb, row, col, sharp, val=0;
1969 
1970   getbits(-1);
1971   memset (pixel, 0x80, sizeof pixel);
1972   for (row=2; row < height+2; row++) {
1973     for (col=2+(row & 1); col < width+2; col+=2) {
1974       val = ((pixel[row-1][col-1] + 2*pixel[row-1][col+1] +
1975 		pixel[row][col-2]) >> 2) + gstep[getbits(4)];
1976       pixel[row][col] = val = LIM(val,0,255);
1977       if (col < 4)
1978 	pixel[row][col-2] = pixel[row+1][~row & 1] = val;
1979       if (row == 2)
1980 	pixel[row-1][col+1] = pixel[row-1][col+3] = val;
1981     }
1982     pixel[row][col] = val;
1983   }
1984   for (rb=0; rb < 2; rb++)
1985     for (row=2+rb; row < height+2; row+=2)
1986       for (col=3-(row & 1); col < width+2; col+=2) {
1987 	if (row < 4 || col < 4) sharp = 2;
1988 	else {
1989 	  val = ABS(pixel[row-2][col] - pixel[row][col-2])
1990 	      + ABS(pixel[row-2][col] - pixel[row-2][col-2])
1991 	      + ABS(pixel[row][col-2] - pixel[row-2][col-2]);
1992 	  sharp = val <  4 ? 0 : val <  8 ? 1 : val < 16 ? 2 :
1993 		  val < 32 ? 3 : val < 48 ? 4 : 5;
1994 	}
1995 	val = ((pixel[row-2][col] + pixel[row][col-2]) >> 1)
1996 	      + rstep[sharp][getbits(2)];
1997 	pixel[row][col] = val = LIM(val,0,255);
1998 	if (row < 4) pixel[row-2][col+2] = val;
1999 	if (col < 4) pixel[row+2][col-2] = val;
2000       }
2001   for (row=2; row < height+2; row++)
2002     for (col=3-(row & 1); col < width+2; col+=2) {
2003       val = ((pixel[row][col-1] + (pixel[row][col] << 2) +
2004 	      pixel[row][col+1]) >> 1) - 0x100;
2005       pixel[row][col] = LIM(val,0,255);
2006     }
2007   for (row=0; row < height; row++)
2008     for (col=0; col < width; col++)
2009       BAYER(row,col) = curve[pixel[row+2][col+2]];
2010   maximum = 0x3ff;
2011 }
2012 
2013 #define radc_token(tree) ((signed char) getbithuff(8,huff[tree]))
2014 
2015 #define FORYX for (y=1; y < 3; y++) for (x=col+1; x >= col; x--)
2016 
2017 #define PREDICTOR (c ? (buf[c][y-1][x] + buf[c][y][x+1]) / 2 \
2018 : (buf[c][y-1][x+1] + 2*buf[c][y-1][x] + buf[c][y][x+1]) / 4)
2019 
kodak_radc_load_raw()2020 void CLASS kodak_radc_load_raw()
2021 {
2022   static const char src[] = {
2023     1,1, 2,3, 3,4, 4,2, 5,7, 6,5, 7,6, 7,8,
2024     1,0, 2,1, 3,3, 4,4, 5,2, 6,7, 7,6, 8,5, 8,8,
2025     2,1, 2,3, 3,0, 3,2, 3,4, 4,6, 5,5, 6,7, 6,8,
2026     2,0, 2,1, 2,3, 3,2, 4,4, 5,6, 6,7, 7,5, 7,8,
2027     2,1, 2,4, 3,0, 3,2, 3,3, 4,7, 5,5, 6,6, 6,8,
2028     2,3, 3,1, 3,2, 3,4, 3,5, 3,6, 4,7, 5,0, 5,8,
2029     2,3, 2,6, 3,0, 3,1, 4,4, 4,5, 4,7, 5,2, 5,8,
2030     2,4, 2,7, 3,3, 3,6, 4,1, 4,2, 4,5, 5,0, 5,8,
2031     2,6, 3,1, 3,3, 3,5, 3,7, 3,8, 4,0, 5,2, 5,4,
2032     2,0, 2,1, 3,2, 3,3, 4,4, 4,5, 5,6, 5,7, 4,8,
2033     1,0, 2,2, 2,-2,
2034     1,-3, 1,3,
2035     2,-17, 2,-5, 2,5, 2,17,
2036     2,-7, 2,2, 2,9, 2,18,
2037     2,-18, 2,-9, 2,-2, 2,7,
2038     2,-28, 2,28, 3,-49, 3,-9, 3,9, 4,49, 5,-79, 5,79,
2039     2,-1, 2,13, 2,26, 3,39, 4,-16, 5,55, 6,-37, 6,76,
2040     2,-26, 2,-13, 2,1, 3,-39, 4,16, 5,-55, 6,-76, 6,37
2041   };
2042   ushort huff[19][256];
2043   int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val;
2044   short last[3] = { 16,16,16 }, mul[3], buf[3][3][386];
2045   static const ushort pt[] =
2046     { 0,0, 1280,1344, 2320,3616, 3328,8000, 4095,16383, 65535,16383 };
2047 
2048   for (i=2; i < 12; i+=2)
2049     for (c=pt[i-2]; c <= pt[i]; c++)
2050       curve[c] = (float)
2051 	(c-pt[i-2]) / (pt[i]-pt[i-2]) * (pt[i+1]-pt[i-1]) + pt[i-1] + 0.5;
2052   for (s=i=0; i < sizeof src; i+=2)
2053     FORC(256 >> src[i])
2054       huff[0][s++] = src[i] << 8 | (uchar) src[i+1];
2055   s = kodak_cbpp == 243 ? 2 : 3;
2056   FORC(256) huff[18][c] = (8-s) << 8 | c >> s << s | 1 << (s-1);
2057   getbits(-1);
2058   for (i=0; i < sizeof(buf)/sizeof(short); i++)
2059     buf[0][0][i] = 2048;
2060   for (row=0; row < height; row+=4) {
2061     FORC3 mul[c] = getbits(6);
2062     FORC3 {
2063       val = ((0x1000000/last[c] + 0x7ff) >> 12) * mul[c];
2064       s = val > 65564 ? 10:12;
2065       x = ~(-1 << (s-1));
2066       val <<= 12-s;
2067       for (i=0; i < sizeof(buf[0])/sizeof(short); i++)
2068 	buf[c][0][i] = (buf[c][0][i] * val + x) >> s;
2069       last[c] = mul[c];
2070       for (r=0; r <= !c; r++) {
2071 	buf[c][1][width/2] = buf[c][2][width/2] = mul[c] << 7;
2072 	for (tree=1, col=width/2; col > 0; ) {
2073 	  if ((tree = radc_token(tree))) {
2074 	    col -= 2;
2075 	    if (tree == 8)
2076 	      FORYX buf[c][y][x] = (uchar) radc_token(18) * mul[c];
2077 	    else
2078 	      FORYX buf[c][y][x] = radc_token(tree+10) * 16 + PREDICTOR;
2079 	  } else
2080 	    do {
2081 	      nreps = (col > 2) ? radc_token(9) + 1 : 1;
2082 	      for (rep=0; rep < 8 && rep < nreps && col > 0; rep++) {
2083 		col -= 2;
2084 		FORYX buf[c][y][x] = PREDICTOR;
2085 		if (rep & 1) {
2086 		  step = radc_token(10) << 4;
2087 		  FORYX buf[c][y][x] += step;
2088 		}
2089 	      }
2090 	    } while (nreps == 9);
2091 	}
2092 	for (y=0; y < 2; y++)
2093 	  for (x=0; x < width/2; x++) {
2094 	    val = (buf[c][y+1][x] << 4) / mul[c];
2095 	    if (val < 0) val = 0;
2096 	    if (c) BAYER(row+y*2+c-1,x*2+2-c) = val;
2097 	    else   BAYER(row+r*2+y,x*2+y) = val;
2098 	  }
2099 	memcpy (buf[c][0]+!c, buf[c][2], sizeof buf[c][0]-2*!c);
2100       }
2101     }
2102     for (y=row; y < row+4; y++)
2103       for (x=0; x < width; x++)
2104 	if ((x+y) & 1) {
2105 	  r = x ? x-1 : x+1;
2106 	  s = x+1 < width ? x+1 : x-1;
2107 	  val = (BAYER(y,x)-2048)*2 + (BAYER(y,r)+BAYER(y,s))/2;
2108 	  if (val < 0) val = 0;
2109 	  BAYER(y,x) = val;
2110 	}
2111   }
2112   for (i=0; i < iheight*iwidth*4; i++)
2113     image[0][i] = curve[image[0][i]];
2114   maximum = 0x3fff;
2115 }
2116 
2117 #undef FORYX
2118 #undef PREDICTOR
2119 
2120 #ifdef NO_JPEG
kodak_jpeg_load_raw()2121 void CLASS kodak_jpeg_load_raw() {}
2122 #else
2123 
2124 METHODDEF(boolean)
fill_input_buffer(j_decompress_ptr cinfo)2125 fill_input_buffer (j_decompress_ptr cinfo)
2126 {
2127   static uchar jpeg_buffer[4096];
2128   size_t nbytes;
2129 
2130   nbytes = fread (jpeg_buffer, 1, 4096, ifp);
2131   swab (jpeg_buffer, jpeg_buffer, nbytes);
2132   cinfo->src->next_input_byte = jpeg_buffer;
2133   cinfo->src->bytes_in_buffer = nbytes;
2134   return TRUE;
2135 }
2136 
kodak_jpeg_load_raw()2137 void CLASS kodak_jpeg_load_raw()
2138 {
2139   struct jpeg_decompress_struct cinfo;
2140   struct jpeg_error_mgr jerr;
2141   JSAMPARRAY buf;
2142   JSAMPLE (*pixel)[3];
2143   int row, col;
2144 
2145   cinfo.err = jpeg_std_error (&jerr);
2146   jpeg_create_decompress (&cinfo);
2147   jpeg_stdio_src (&cinfo, ifp);
2148   cinfo.src->fill_input_buffer = fill_input_buffer;
2149   jpeg_read_header (&cinfo, TRUE);
2150   jpeg_start_decompress (&cinfo);
2151   if ((cinfo.output_width      != width  ) ||
2152       (cinfo.output_height*2   != height ) ||
2153       (cinfo.output_components != 3      )) {
2154     fprintf (stderr,_("%s: incorrect JPEG dimensions\n"), ifname);
2155     jpeg_destroy_decompress (&cinfo);
2156     longjmp (failure, 3);
2157   }
2158   buf = (*cinfo.mem->alloc_sarray)
2159 		((j_common_ptr) &cinfo, JPOOL_IMAGE, width*3, 1);
2160 
2161   while (cinfo.output_scanline < cinfo.output_height) {
2162     row = cinfo.output_scanline * 2;
2163     jpeg_read_scanlines (&cinfo, buf, 1);
2164     pixel = (JSAMPLE (*)[3]) buf[0];
2165     for (col=0; col < width; col+=2) {
2166       BAYER(row+0,col+0) = pixel[col+0][1] << 1;
2167       BAYER(row+1,col+1) = pixel[col+1][1] << 1;
2168       BAYER(row+0,col+1) = pixel[col][0] + pixel[col+1][0];
2169       BAYER(row+1,col+0) = pixel[col][2] + pixel[col+1][2];
2170     }
2171   }
2172   jpeg_finish_decompress (&cinfo);
2173   jpeg_destroy_decompress (&cinfo);
2174   maximum = 0xff << 1;
2175 }
2176 #endif
2177 
kodak_dc120_load_raw()2178 void CLASS kodak_dc120_load_raw()
2179 {
2180   static const int mul[4] = { 162, 192, 187,  92 };
2181   static const int add[4] = {   0, 636, 424, 212 };
2182   uchar pixel[848];
2183   int row, shift, col;
2184 
2185   for (row=0; row < height; row++) {
2186     if (fread (pixel, 1, 848, ifp) < 848) derror();
2187     shift = row * mul[row & 3] + add[row & 3];
2188     for (col=0; col < width; col++)
2189       BAYER(row,col) = (ushort) pixel[(col + shift) % 848];
2190   }
2191   maximum = 0xff;
2192 }
2193 
eight_bit_load_raw()2194 void CLASS eight_bit_load_raw()
2195 {
2196   uchar *pixel;
2197   unsigned row, col, val, lblack=0;
2198 
2199   pixel = (uchar *) calloc (raw_width, sizeof *pixel);
2200   merror (pixel, "eight_bit_load_raw()");
2201   fseek (ifp, top_margin*raw_width, SEEK_CUR);
2202   for (row=0; row < height; row++) {
2203     if (fread (pixel, 1, raw_width, ifp) < raw_width) derror();
2204     for (col=0; col < raw_width; col++) {
2205       val = curve[pixel[col]];
2206       if ((unsigned) (col-left_margin) < width)
2207         BAYER(row,col-left_margin) = val;
2208       else lblack += val;
2209     }
2210   }
2211   free (pixel);
2212   if (raw_width > width+1)
2213     black = lblack / ((raw_width - width) * height);
2214   if (!strncmp(model,"DC2",3))
2215     black = 0;
2216   maximum = curve[0xff];
2217 }
2218 
kodak_yrgb_load_raw()2219 void CLASS kodak_yrgb_load_raw()
2220 {
2221   uchar *pixel;
2222   int row, col, y, cb, cr, rgb[3], c;
2223 
2224   pixel = (uchar *) calloc (raw_width, 3*sizeof *pixel);
2225   merror (pixel, "kodak_yrgb_load_raw()");
2226   for (row=0; row < height; row++) {
2227     if (~row & 1)
2228       if (fread (pixel, raw_width, 3, ifp) < 3) derror();
2229     for (col=0; col < raw_width; col++) {
2230       y  = pixel[width*2*(row & 1) + col];
2231       cb = pixel[width + (col & -2)]   - 128;
2232       cr = pixel[width + (col & -2)+1] - 128;
2233       rgb[1] = y-((cb + cr + 2) >> 2);
2234       rgb[2] = rgb[1] + cb;
2235       rgb[0] = rgb[1] + cr;
2236       FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)];
2237     }
2238   }
2239   free (pixel);
2240   maximum = curve[0xff];
2241 }
2242 
kodak_262_load_raw()2243 void CLASS kodak_262_load_raw()
2244 {
2245   static const uchar kodak_tree[2][26] =
2246   { { 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 },
2247     { 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 } };
2248   ushort *huff[2];
2249   uchar *pixel;
2250   int *strip, ns, c, row, col, chess, pi=0, pi1, pi2, pred, val;
2251 
2252   FORC(2) huff[c] = make_decoder (kodak_tree[c]);
2253   ns = (raw_height+63) >> 5;
2254   pixel = (uchar *) malloc (raw_width*32 + ns*4);
2255   merror (pixel, "kodak_262_load_raw()");
2256   strip = (int *) (pixel + raw_width*32);
2257   order = 0x4d4d;
2258   FORC(ns) strip[c] = get4();
2259   for (row=0; row < raw_height; row++) {
2260     if ((row & 31) == 0) {
2261       fseek (ifp, strip[row >> 5], SEEK_SET);
2262       getbits(-1);
2263       pi = 0;
2264     }
2265     for (col=0; col < raw_width; col++) {
2266       chess = (row + col) & 1;
2267       pi1 = chess ? pi-2           : pi-raw_width-1;
2268       pi2 = chess ? pi-2*raw_width : pi-raw_width+1;
2269       if (col <= chess) pi1 = -1;
2270       if (pi1 < 0) pi1 = pi2;
2271       if (pi2 < 0) pi2 = pi1;
2272       if (pi1 < 0 && col > 1) pi1 = pi2 = pi-2;
2273       pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1;
2274       pixel[pi] = val = pred + ljpeg_diff (huff[chess]);
2275       if (val >> 8) derror();
2276       val = curve[pixel[pi++]];
2277       if ((unsigned) (col-left_margin) < width)
2278 	BAYER(row,col-left_margin) = val;
2279       else black += val;
2280     }
2281   }
2282   free (pixel);
2283   FORC(2) free (huff[c]);
2284   if (raw_width > width)
2285     black /= (raw_width - width) * height;
2286 }
2287 
kodak_65000_decode(short * out,int bsize)2288 int CLASS kodak_65000_decode (short *out, int bsize)
2289 {
2290   uchar c, blen[768];
2291   ushort raw[6];
2292   INT64 bitbuf=0;
2293   int save, bits=0, i, j, len, diff;
2294 
2295   save = ftell(ifp);
2296   bsize = (bsize + 3) & -4;
2297   for (i=0; i < bsize; i+=2) {
2298     c = fgetc(ifp);
2299     if ((blen[i  ] = c & 15) > 12 ||
2300 	(blen[i+1] = c >> 4) > 12 ) {
2301       fseek (ifp, save, SEEK_SET);
2302       for (i=0; i < bsize; i+=8) {
2303 	read_shorts (raw, 6);
2304 	out[i  ] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12;
2305 	out[i+1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12;
2306 	for (j=0; j < 6; j++)
2307 	  out[i+2+j] = raw[j] & 0xfff;
2308       }
2309       return 1;
2310     }
2311   }
2312   if ((bsize & 7) == 4) {
2313     bitbuf  = fgetc(ifp) << 8;
2314     bitbuf += fgetc(ifp);
2315     bits = 16;
2316   }
2317   for (i=0; i < bsize; i++) {
2318     len = blen[i];
2319     if (bits < len) {
2320       for (j=0; j < 32; j+=8)
2321 	bitbuf += (INT64) fgetc(ifp) << (bits+(j^8));
2322       bits += 32;
2323     }
2324     diff = bitbuf & (0xffff >> (16-len));
2325     bitbuf >>= len;
2326     bits -= len;
2327     if ((diff & (1 << (len-1))) == 0)
2328       diff -= (1 << len) - 1;
2329     out[i] = diff;
2330   }
2331   return 0;
2332 }
2333 
kodak_65000_load_raw()2334 void CLASS kodak_65000_load_raw()
2335 {
2336   short buf[256];
2337   int row, col, len, pred[2], ret, i;
2338 
2339   for (row=0; row < height; row++)
2340     for (col=0; col < width; col+=256) {
2341       pred[0] = pred[1] = 0;
2342       len = MIN (256, width-col);
2343       ret = kodak_65000_decode (buf, len);
2344       for (i=0; i < len; i++)
2345 	if ((BAYER(row,col+i) =	curve[ret ? buf[i] :
2346 		(pred[i & 1] += buf[i])]) >> 12) derror();
2347     }
2348 }
2349 
kodak_ycbcr_load_raw()2350 void CLASS kodak_ycbcr_load_raw()
2351 {
2352   short buf[384], *bp;
2353   int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3];
2354   ushort *ip;
2355 
2356   for (row=0; row < height; row+=2)
2357     for (col=0; col < width; col+=128) {
2358       len = MIN (128, width-col);
2359       kodak_65000_decode (buf, len*3);
2360       y[0][1] = y[1][1] = cb = cr = 0;
2361       for (bp=buf, i=0; i < len; i+=2, bp+=2) {
2362 	cb += bp[4];
2363 	cr += bp[5];
2364 	rgb[1] = -((cb + cr + 2) >> 2);
2365 	rgb[2] = rgb[1] + cb;
2366 	rgb[0] = rgb[1] + cr;
2367 	for (j=0; j < 2; j++)
2368 	  for (k=0; k < 2; k++) {
2369 	    if ((y[j][k] = y[j][k^1] + *bp++) >> 10) derror();
2370 	    ip = image[(row+j)*width + col+i+k];
2371 	    FORC3 ip[c] = curve[LIM(y[j][k]+rgb[c], 0, 0xfff)];
2372 	  }
2373       }
2374     }
2375 }
2376 
kodak_rgb_load_raw()2377 void CLASS kodak_rgb_load_raw()
2378 {
2379   short buf[768], *bp;
2380   int row, col, len, c, i, rgb[3];
2381   ushort *ip=image[0];
2382 
2383   for (row=0; row < height; row++)
2384     for (col=0; col < width; col+=256) {
2385       len = MIN (256, width-col);
2386       kodak_65000_decode (buf, len*3);
2387       memset (rgb, 0, sizeof rgb);
2388       for (bp=buf, i=0; i < len; i++, ip+=4)
2389 	FORC3 if ((ip[c] = rgb[c] += *bp++) >> 12) derror();
2390     }
2391 }
2392 
kodak_thumb_load_raw()2393 void CLASS kodak_thumb_load_raw()
2394 {
2395   int row, col;
2396   colors = thumb_misc >> 5;
2397   for (row=0; row < height; row++)
2398     for (col=0; col < width; col++)
2399       read_shorts (image[row*width+col], colors);
2400   maximum = (1 << (thumb_misc & 31)) - 1;
2401 }
2402 
sony_decrypt(unsigned * data,int len,int start,int key)2403 void CLASS sony_decrypt (unsigned *data, int len, int start, int key)
2404 {
2405   static unsigned pad[128], p;
2406 
2407   if (start) {
2408     for (p=0; p < 4; p++)
2409       pad[p] = key = key * 48828125 + 1;
2410     pad[3] = pad[3] << 1 | (pad[0]^pad[2]) >> 31;
2411     for (p=4; p < 127; p++)
2412       pad[p] = (pad[p-4]^pad[p-2]) << 1 | (pad[p-3]^pad[p-1]) >> 31;
2413     for (p=0; p < 127; p++)
2414       pad[p] = htonl(pad[p]);
2415   }
2416   while (len--)
2417     *data++ ^= pad[p++ & 127] = pad[(p+1) & 127] ^ pad[(p+65) & 127];
2418 }
2419 
sony_load_raw()2420 void CLASS sony_load_raw()
2421 {
2422   uchar head[40];
2423   ushort *pixel;
2424   unsigned i, key, row, col;
2425 
2426   fseek (ifp, 200896, SEEK_SET);
2427   fseek (ifp, (unsigned) fgetc(ifp)*4 - 1, SEEK_CUR);
2428   order = 0x4d4d;
2429   key = get4();
2430   fseek (ifp, 164600, SEEK_SET);
2431   fread (head, 1, 40, ifp);
2432   sony_decrypt ((unsigned int *) head, 10, 1, key);
2433   for (i=26; i-- > 22; )
2434     key = key << 8 | head[i];
2435   fseek (ifp, data_offset, SEEK_SET);
2436   pixel = (ushort *) calloc (raw_width, sizeof *pixel);
2437   merror (pixel, "sony_load_raw()");
2438   for (row=0; row < height; row++) {
2439     if (fread (pixel, 2, raw_width, ifp) < raw_width) derror();
2440     sony_decrypt ((unsigned int *) pixel, raw_width/2, !row, key);
2441     for (col=9; col < left_margin; col++)
2442       black += ntohs(pixel[col]);
2443     for (col=0; col < width; col++)
2444       if ((BAYER(row,col) = ntohs(pixel[col+left_margin])) >> 14)
2445 	derror();
2446   }
2447   free (pixel);
2448   if (left_margin > 9)
2449     black /= (left_margin-9) * height;
2450   maximum = 0x3ff0;
2451 }
2452 
sony_arw_load_raw()2453 void CLASS sony_arw_load_raw()
2454 {
2455   ushort huff[32768];
2456   static const ushort tab[18] =
2457   { 0xf11,0xf10,0xe0f,0xd0e,0xc0d,0xb0c,0xa0b,0x90a,0x809,
2458     0x708,0x607,0x506,0x405,0x304,0x303,0x300,0x202,0x201 };
2459   int i, c, n, col, row, len, diff, sum=0;
2460 
2461   for (n=i=0; i < 18; i++)
2462     FORC(32768 >> (tab[i] >> 8)) huff[n++] = tab[i];
2463   getbits(-1);
2464   for (col = raw_width; col--; )
2465     for (row=0; row < raw_height+1; row+=2) {
2466       if (row == raw_height) row = 1;
2467       len = getbithuff(15,huff);
2468       diff = getbits(len);
2469       if ((diff & (1 << (len-1))) == 0)
2470 	diff -= (1 << len) - 1;
2471       if ((sum += diff) >> 12) derror();
2472       if (row < height) BAYER(row,col) = sum;
2473     }
2474 }
2475 
sony_arw2_load_raw()2476 void CLASS sony_arw2_load_raw()
2477 {
2478   uchar *data, *dp;
2479   ushort pix[16];
2480   int row, col, val, max, min, imax, imin, sh, bit, i;
2481 
2482   data = (uchar *) malloc (raw_width);
2483   merror (data, "sony_arw2_load_raw()");
2484   for (row=0; row < height; row++) {
2485     fread (data, 1, raw_width, ifp);
2486     for (dp=data, col=0; col < width-30; dp+=16) {
2487       max = 0x7ff & (val = sget4(dp));
2488       min = 0x7ff & val >> 11;
2489       imax = 0x0f & val >> 22;
2490       imin = 0x0f & val >> 26;
2491       for (sh=0; sh < 4 && 0x80 << sh <= max-min; sh++);
2492       for (bit=30, i=0; i < 16; i++)
2493 	if      (i == imax) pix[i] = max;
2494 	else if (i == imin) pix[i] = min;
2495 	else {
2496 	  pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min;
2497 	  if (pix[i] > 0x7ff) pix[i] = 0x7ff;
2498 	  bit += 7;
2499 	}
2500       for (i=0; i < 16; i++, col+=2)
2501 	BAYER(row,col) = curve[pix[i] << 1] >> 2;
2502       col -= col & 1 ? 1:31;
2503     }
2504   }
2505   free (data);
2506 }
2507 
2508 #define HOLE(row) ((holes >> (((row) - raw_height) & 7)) & 1)
2509 
2510 /* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */
smal_decode_segment(unsigned seg[2][2],int holes)2511 void CLASS smal_decode_segment (unsigned seg[2][2], int holes)
2512 {
2513   uchar hist[3][13] = {
2514     { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 },
2515     { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 },
2516     { 3, 3, 0, 0, 63,     47,     31,     15,    0 } };
2517   int low, high=0xff, carry=0, nbits=8;
2518   int s, count, bin, next, i, sym[3];
2519   uchar diff, pred[]={0,0};
2520   ushort data=0, range=0;
2521   unsigned pix, row, col;
2522 
2523   fseek (ifp, seg[0][1]+1, SEEK_SET);
2524   getbits(-1);
2525   for (pix=seg[0][0]; pix < seg[1][0]; pix++) {
2526     for (s=0; s < 3; s++) {
2527       data = data << nbits | getbits(nbits);
2528       if (carry < 0)
2529 	carry = (nbits += carry+1) < 1 ? nbits-1 : 0;
2530       while (--nbits >= 0)
2531 	if ((data >> nbits & 0xff) == 0xff) break;
2532       if (nbits > 0)
2533 	  data = ((data & ((1 << (nbits-1)) - 1)) << 1) |
2534 	((data + (((data & (1 << (nbits-1)))) << 1)) & (-1 << nbits));
2535       if (nbits >= 0) {
2536 	data += getbits(1);
2537 	carry = nbits - 8;
2538       }
2539       count = ((((data-range+1) & 0xffff) << 2) - 1) / (high >> 4);
2540       for (bin=0; hist[s][bin+5] > count; bin++);
2541 		low = hist[s][bin+5] * (high >> 4) >> 2;
2542       if (bin) high = hist[s][bin+4] * (high >> 4) >> 2;
2543       high -= low;
2544       for (nbits=0; high << nbits < 128; nbits++);
2545       range = (range+low) << nbits;
2546       high <<= nbits;
2547       next = hist[s][1];
2548       if (++hist[s][2] > hist[s][3]) {
2549 	next = (next+1) & hist[s][0];
2550 	hist[s][3] = (hist[s][next+4] - hist[s][next+5]) >> 2;
2551 	hist[s][2] = 1;
2552       }
2553       if (hist[s][hist[s][1]+4] - hist[s][hist[s][1]+5] > 1) {
2554 	if (bin < hist[s][1])
2555 	  for (i=bin; i < hist[s][1]; i++) hist[s][i+5]--;
2556 	else if (next <= bin)
2557 	  for (i=hist[s][1]; i < bin; i++) hist[s][i+5]++;
2558       }
2559       hist[s][1] = next;
2560       sym[s] = bin;
2561     }
2562     diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3);
2563     if (sym[0] & 4)
2564       diff = diff ? -diff : 0x80;
2565     if (ftell(ifp) + 12 >= seg[1][1])
2566       diff = 0;
2567     pred[pix & 1] += diff;
2568     row = pix / raw_width - top_margin;
2569     col = pix % raw_width - left_margin;
2570     if (row < height && col < width)
2571       BAYER(row,col) = pred[pix & 1];
2572     if (!(pix & 1) && HOLE(row)) pix += 2;
2573   }
2574   maximum = 0xff;
2575 }
2576 
smal_v6_load_raw()2577 void CLASS smal_v6_load_raw()
2578 {
2579   unsigned seg[2][2];
2580 
2581   fseek (ifp, 16, SEEK_SET);
2582   seg[0][0] = 0;
2583   seg[0][1] = get2();
2584   seg[1][0] = raw_width * raw_height;
2585   seg[1][1] = INT_MAX;
2586   smal_decode_segment (seg, 0);
2587 }
2588 
median4(int * p)2589 int CLASS median4 (int *p)
2590 {
2591   int min, max, sum, i;
2592 
2593   min = max = sum = p[0];
2594   for (i=1; i < 4; i++) {
2595     sum += p[i];
2596     if (min > p[i]) min = p[i];
2597     if (max < p[i]) max = p[i];
2598   }
2599   return (sum - min - max) >> 1;
2600 }
2601 
fill_holes(int holes)2602 void CLASS fill_holes (int holes)
2603 {
2604   int row, col, val[4];
2605 
2606   for (row=2; row < height-2; row++) {
2607     if (!HOLE(row)) continue;
2608     for (col=1; col < width-1; col+=4) {
2609       val[0] = BAYER(row-1,col-1);
2610       val[1] = BAYER(row-1,col+1);
2611       val[2] = BAYER(row+1,col-1);
2612       val[3] = BAYER(row+1,col+1);
2613       BAYER(row,col) = median4(val);
2614     }
2615     for (col=2; col < width-2; col+=4)
2616       if (HOLE(row-2) || HOLE(row+2))
2617 	BAYER(row,col) = (BAYER(row,col-2) + BAYER(row,col+2)) >> 1;
2618       else {
2619 	val[0] = BAYER(row,col-2);
2620 	val[1] = BAYER(row,col+2);
2621 	val[2] = BAYER(row-2,col);
2622 	val[3] = BAYER(row+2,col);
2623 	BAYER(row,col) = median4(val);
2624       }
2625   }
2626 }
2627 
smal_v9_load_raw()2628 void CLASS smal_v9_load_raw()
2629 {
2630   unsigned seg[256][2], offset, nseg, holes, i;
2631 
2632   fseek (ifp, 67, SEEK_SET);
2633   offset = get4();
2634   nseg = fgetc(ifp);
2635   fseek (ifp, offset, SEEK_SET);
2636   for (i=0; i < nseg*2; i++)
2637     seg[0][i] = get4() + data_offset*(i & 1);
2638   fseek (ifp, 78, SEEK_SET);
2639   holes = fgetc(ifp);
2640   fseek (ifp, 88, SEEK_SET);
2641   seg[nseg][0] = raw_height * raw_width;
2642   seg[nseg][1] = get4() + data_offset;
2643   for (i=0; i < nseg; i++)
2644     smal_decode_segment (seg+i, holes);
2645   if (holes) fill_holes (holes);
2646 }
2647 
2648 /* RESTRICTED code starts here */
2649 
foveon_decoder(unsigned size,unsigned code)2650 void CLASS foveon_decoder (unsigned size, unsigned code)
2651 {
2652   static unsigned huff[1024];
2653   struct decode *cur;
2654   int i, len;
2655 
2656   if (!code) {
2657     for (i=0; i < size; i++)
2658       huff[i] = get4();
2659     memset (first_decode, 0, sizeof first_decode);
2660     free_decode = first_decode;
2661   }
2662   cur = free_decode++;
2663   if (free_decode > first_decode+2048) {
2664     fprintf (stderr,_("%s: decoder table overflow\n"), ifname);
2665     longjmp (failure, 2);
2666   }
2667   if (code)
2668     for (i=0; i < size; i++)
2669       if (huff[i] == code) {
2670 	cur->leaf = i;
2671 	return;
2672       }
2673   if ((len = code >> 27) > 26) return;
2674   code = (len+1) << 27 | (code & 0x3ffffff) << 1;
2675 
2676   cur->branch[0] = free_decode;
2677   foveon_decoder (size, code);
2678   cur->branch[1] = free_decode;
2679   foveon_decoder (size, code+1);
2680 }
2681 
foveon_thumb()2682 void CLASS foveon_thumb()
2683 {
2684   unsigned bwide, row, col, bitbuf=0, bit=1, c, i;
2685   char *buf;
2686   struct decode *dindex;
2687   short pred[3];
2688 
2689   bwide = get4();
2690   fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
2691   if (bwide > 0) {
2692     if (bwide < thumb_width*3) return;
2693     buf = (char *) malloc (bwide);
2694     merror (buf, "foveon_thumb()");
2695     for (row=0; row < thumb_height; row++) {
2696       fread  (buf, 1, bwide, ifp);
2697       fwrite (buf, 3, thumb_width, ofp);
2698     }
2699     free (buf);
2700     return;
2701   }
2702   foveon_decoder (256, 0);
2703 
2704   for (row=0; row < thumb_height; row++) {
2705     memset (pred, 0, sizeof pred);
2706     if (!bit) get4();
2707     for (bit=col=0; col < thumb_width; col++)
2708       FORC3 {
2709 	for (dindex=first_decode; dindex->branch[0]; ) {
2710 	  if ((bit = (bit-1) & 31) == 31)
2711 	    for (i=0; i < 4; i++)
2712 	      bitbuf = (bitbuf << 8) + fgetc(ifp);
2713 	  dindex = dindex->branch[bitbuf >> bit & 1];
2714 	}
2715 	pred[c] += dindex->leaf;
2716 	fputc (pred[c], ofp);
2717       }
2718   }
2719 }
2720 
foveon_load_camf()2721 void CLASS foveon_load_camf()
2722 {
2723   unsigned key, i, val;
2724 
2725   fseek (ifp, meta_offset, SEEK_SET);
2726   key = get4();
2727   fread (meta_data, 1, meta_length, ifp);
2728   for (i=0; i < meta_length; i++) {
2729     key = (key * 1597 + 51749) % 244944;
2730     val = key * (INT64) 301593171 >> 24;
2731     meta_data[i] ^= ((((key << 8) - val) >> 1) + val) >> 17;
2732   }
2733 }
2734 
foveon_load_raw()2735 void CLASS foveon_load_raw()
2736 {
2737   struct decode *dindex;
2738   short diff[1024];
2739   unsigned bitbuf=0;
2740   int pred[3], fixed, row, col, bit=-1, c, i;
2741 
2742   fixed = get4();
2743   read_shorts ((ushort *) diff, 1024);
2744   if (!fixed) foveon_decoder (1024, 0);
2745 
2746   for (row=0; row < height; row++) {
2747     memset (pred, 0, sizeof pred);
2748     if (!bit && !fixed && atoi(model+2) < 14) get4();
2749     for (col=bit=0; col < width; col++) {
2750       if (fixed) {
2751 	bitbuf = get4();
2752 	FORC3 pred[2-c] += diff[bitbuf >> c*10 & 0x3ff];
2753       }
2754       else FORC3 {
2755 	for (dindex=first_decode; dindex->branch[0]; ) {
2756 	  if ((bit = (bit-1) & 31) == 31)
2757 	    for (i=0; i < 4; i++)
2758 	      bitbuf = (bitbuf << 8) + fgetc(ifp);
2759 	  dindex = dindex->branch[bitbuf >> bit & 1];
2760 	}
2761 	pred[c] += diff[dindex->leaf];
2762 	if (pred[c] >> 16 && ~pred[c] >> 16) derror();
2763       }
2764       FORC3 image[row*width+col][c] = pred[c];
2765     }
2766   }
2767   if (document_mode)
2768     for (i=0; i < height*width*4; i++)
2769       if ((short) image[0][i] < 0) image[0][i] = 0;
2770   foveon_load_camf();
2771 }
2772 
foveon_camf_param(const char * block,const char * param)2773 const char * CLASS foveon_camf_param (const char *block, const char *param)
2774 {
2775   unsigned idx, num;
2776   char *pos, *cp, *dp;
2777 
2778   for (idx=0; idx < meta_length; idx += sget4(pos+8)) {
2779     pos = meta_data + idx;
2780     if (strncmp (pos, "CMb", 3)) break;
2781     if (pos[3] != 'P') continue;
2782     if (strcmp (block, pos+sget4(pos+12))) continue;
2783     cp = pos + sget4(pos+16);
2784     num = sget4(cp);
2785     dp = pos + sget4(cp+4);
2786     while (num--) {
2787       cp += 8;
2788       if (!strcmp (param, dp+sget4(cp)))
2789 	return dp+sget4(cp+4);
2790     }
2791   }
2792   return 0;
2793 }
2794 
foveon_camf_matrix(unsigned dim[3],const char * name)2795 void * CLASS foveon_camf_matrix (unsigned dim[3], const char *name)
2796 {
2797   unsigned i, idx, type, ndim, size, *mat;
2798   char *pos, *cp, *dp;
2799   double dsize;
2800 
2801   for (idx=0; idx < meta_length; idx += sget4(pos+8)) {
2802     pos = meta_data + idx;
2803     if (strncmp (pos, "CMb", 3)) break;
2804     if (pos[3] != 'M') continue;
2805     if (strcmp (name, pos+sget4(pos+12))) continue;
2806     dim[0] = dim[1] = dim[2] = 1;
2807     cp = pos + sget4(pos+16);
2808     type = sget4(cp);
2809     if ((ndim = sget4(cp+4)) > 3) break;
2810     dp = pos + sget4(cp+8);
2811     for (i=ndim; i--; ) {
2812       cp += 12;
2813       dim[i] = sget4(cp);
2814     }
2815     if ((dsize = (double) dim[0]*dim[1]*dim[2]) > meta_length/4) break;
2816     mat = (unsigned *) malloc ((size = dsize) * 4);
2817     merror (mat, "foveon_camf_matrix()");
2818     for (i=0; i < size; i++)
2819       if (type && type != 6)
2820 	mat[i] = sget4(dp + i*4);
2821       else
2822 	mat[i] = sget4(dp + i*2) & 0xffff;
2823     return mat;
2824   }
2825   fprintf (stderr,_("%s: \"%s\" matrix not found!\n"), ifname, name);
2826   return 0;
2827 }
2828 
foveon_fixed(void * ptr,int size,const char * name)2829 int CLASS foveon_fixed (void *ptr, int size, const char *name)
2830 {
2831   void *dp;
2832   unsigned dim[3];
2833 
2834   dp = foveon_camf_matrix (dim, name);
2835   if (!dp) return 0;
2836   memcpy (ptr, dp, size*4);
2837   free (dp);
2838   return 1;
2839 }
2840 
foveon_avg(short * pix,int range[2],float cfilt)2841 float CLASS foveon_avg (short *pix, int range[2], float cfilt)
2842 {
2843   int i;
2844   float val, min=FLT_MAX, max=-FLT_MAX, sum=0;
2845 
2846   for (i=range[0]; i <= range[1]; i++) {
2847     sum += val = pix[i*4] + (pix[i*4]-pix[(i-1)*4]) * cfilt;
2848     if (min > val) min = val;
2849     if (max < val) max = val;
2850   }
2851   if (range[1] - range[0] == 1) return sum/2;
2852   return (sum - min - max) / (range[1] - range[0] - 1);
2853 }
2854 
foveon_make_curve(double max,double mul,double filt)2855 short * CLASS foveon_make_curve (double max, double mul, double filt)
2856 {
2857   short *curve;
2858   unsigned i, size;
2859   double x;
2860 
2861   if (!filt) filt = 0.8;
2862   size = 4*M_PI*max / filt;
2863   if (size == UINT_MAX) size--;
2864   curve = (short *) calloc (size+1, sizeof *curve);
2865   merror (curve, "foveon_make_curve()");
2866   curve[0] = size;
2867   for (i=0; i < size; i++) {
2868     x = i*filt/max/4;
2869     curve[i+1] = (cos(x)+1)/2 * tanh(i*filt/mul) * mul + 0.5;
2870   }
2871   return curve;
2872 }
2873 
foveon_make_curves(short ** curvep,float dq[3],float div[3],float filt)2874 void CLASS foveon_make_curves
2875 	(short **curvep, float dq[3], float div[3], float filt)
2876 {
2877   double mul[3], max=0;
2878   int c;
2879 
2880   FORC3 mul[c] = dq[c]/div[c];
2881   FORC3 if (max < mul[c]) max = mul[c];
2882   FORC3 curvep[c] = foveon_make_curve (max, mul[c], filt);
2883 }
2884 
foveon_apply_curve(short * curve,int i)2885 int CLASS foveon_apply_curve (short *curve, int i)
2886 {
2887   if (abs(i) >= curve[0]) return 0;
2888   return i < 0 ? -curve[1-i] : curve[1+i];
2889 }
2890 
2891 #define image ((short (*)[4]) image)
2892 
foveon_interpolate()2893 void CLASS foveon_interpolate()
2894 {
2895   static const short hood[] = { -1,-1, -1,0, -1,1, 0,-1, 0,1, 1,-1, 1,0, 1,1 };
2896   short *pix, prev[3], *curve[8], (*shrink)[3];
2897   float cfilt=0, ddft[3][3][2], ppm[3][3][3];
2898   float cam_xyz[3][3], correct[3][3], last[3][3], trans[3][3];
2899   float chroma_dq[3], color_dq[3], diag[3][3], div[3];
2900   float (*black)[3], (*sgain)[3], (*sgrow)[3];
2901   float fsum[3], val, frow, num;
2902   int row, col, c, i, j, diff, sgx, irow, sum, min, max, limit;
2903   int dscr[2][2], dstb[4], (*smrow[7])[3], total[4], ipix[3];
2904   int work[3][3], smlast, smred, smred_p=0, dev[3];
2905   int satlev[3], keep[4], active[4];
2906   unsigned dim[3], *badpix;
2907   double dsum=0, trsum[3];
2908   char str[128];
2909   const char* cp;
2910 
2911   if (verbose)
2912     fprintf (stderr,_("Foveon interpolation...\n"));
2913 
2914   foveon_fixed (dscr, 4, "DarkShieldColRange");
2915   foveon_fixed (ppm[0][0], 27, "PostPolyMatrix");
2916   foveon_fixed (satlev, 3, "SaturationLevel");
2917   foveon_fixed (keep, 4, "KeepImageArea");
2918   foveon_fixed (active, 4, "ActiveImageArea");
2919   foveon_fixed (chroma_dq, 3, "ChromaDQ");
2920   foveon_fixed (color_dq, 3,
2921 	foveon_camf_param ("IncludeBlocks", "ColorDQ") ?
2922 		"ColorDQ" : "ColorDQCamRGB");
2923   if (foveon_camf_param ("IncludeBlocks", "ColumnFilter"))
2924   		 foveon_fixed (&cfilt, 1, "ColumnFilter");
2925 
2926   memset (ddft, 0, sizeof ddft);
2927   if (!foveon_camf_param ("IncludeBlocks", "DarkDrift")
2928 	 || !foveon_fixed (ddft[1][0], 12, "DarkDrift"))
2929     for (i=0; i < 2; i++) {
2930       foveon_fixed (dstb, 4, i ? "DarkShieldBottom":"DarkShieldTop");
2931       for (row = dstb[1]; row <= dstb[3]; row++)
2932 	for (col = dstb[0]; col <= dstb[2]; col++)
2933 	  FORC3 ddft[i+1][c][1] += (short) image[row*width+col][c];
2934       FORC3 ddft[i+1][c][1] /= (dstb[3]-dstb[1]+1) * (dstb[2]-dstb[0]+1);
2935     }
2936 
2937   if (!(cp = foveon_camf_param ("WhiteBalanceIlluminants", model2)))
2938   { fprintf (stderr,_("%s: Invalid white balance \"%s\"\n"), ifname, model2);
2939     return; }
2940   foveon_fixed (cam_xyz, 9, cp);
2941   foveon_fixed (correct, 9,
2942 	foveon_camf_param ("WhiteBalanceCorrections", model2));
2943   memset (last, 0, sizeof last);
2944   for (i=0; i < 3; i++)
2945     for (j=0; j < 3; j++)
2946       FORC3 last[i][j] += correct[i][c] * cam_xyz[c][j];
2947 
2948   #define LAST(x,y) last[(i+x)%3][(c+y)%3]
2949   for (i=0; i < 3; i++)
2950     FORC3 diag[c][i] = LAST(1,1)*LAST(2,2) - LAST(1,2)*LAST(2,1);
2951   #undef LAST
2952   FORC3 div[c] = diag[c][0]*0.3127 + diag[c][1]*0.329 + diag[c][2]*0.3583;
2953   sprintf (str, "%sRGBNeutral", model2);
2954   if (foveon_camf_param ("IncludeBlocks", str))
2955     foveon_fixed (div, 3, str);
2956   num = 0;
2957   FORC3 if (num < div[c]) num = div[c];
2958   FORC3 div[c] /= num;
2959 
2960   memset (trans, 0, sizeof trans);
2961   for (i=0; i < 3; i++)
2962     for (j=0; j < 3; j++)
2963       FORC3 trans[i][j] += rgb_cam[i][c] * last[c][j] * div[j];
2964   FORC3 trsum[c] = trans[c][0] + trans[c][1] + trans[c][2];
2965   dsum = (6*trsum[0] + 11*trsum[1] + 3*trsum[2]) / 20;
2966   for (i=0; i < 3; i++)
2967     FORC3 last[i][c] = trans[i][c] * dsum / trsum[i];
2968   memset (trans, 0, sizeof trans);
2969   for (i=0; i < 3; i++)
2970     for (j=0; j < 3; j++)
2971       FORC3 trans[i][j] += (i==c ? 32 : -1) * last[c][j] / 30;
2972 
2973   foveon_make_curves (curve, color_dq, div, cfilt);
2974   FORC3 chroma_dq[c] /= 3;
2975   foveon_make_curves (curve+3, chroma_dq, div, cfilt);
2976   FORC3 dsum += chroma_dq[c] / div[c];
2977   curve[6] = foveon_make_curve (dsum, dsum, cfilt);
2978   curve[7] = foveon_make_curve (dsum*2, dsum*2, cfilt);
2979 
2980   sgain = (float (*)[3]) foveon_camf_matrix (dim, "SpatialGain");
2981   if (!sgain) return;
2982   sgrow = (float (*)[3]) calloc (dim[1], sizeof *sgrow);
2983   sgx = (width + dim[1]-2) / (dim[1]-1);
2984 
2985   black = (float (*)[3]) calloc (height, sizeof *black);
2986   for (row=0; row < height; row++) {
2987     for (i=0; i < 6; i++)
2988       ddft[0][0][i] = ddft[1][0][i] +
2989 	row / (height-1.0) * (ddft[2][0][i] - ddft[1][0][i]);
2990     FORC3 black[row][c] =
2991  	( foveon_avg (image[row*width]+c, dscr[0], cfilt) +
2992 	  foveon_avg (image[row*width]+c, dscr[1], cfilt) * 3
2993 	  - ddft[0][c][0] ) / 4 - ddft[0][c][1];
2994   }
2995   memcpy (black, black+8, sizeof *black*8);
2996   memcpy (black+height-11, black+height-22, 11*sizeof *black);
2997   memcpy (last, black, sizeof last);
2998 
2999   for (row=1; row < height-1; row++) {
3000     FORC3 if (last[1][c] > last[0][c]) {
3001 	if (last[1][c] > last[2][c])
3002 	  black[row][c] = (last[0][c] > last[2][c]) ? last[0][c]:last[2][c];
3003       } else
3004 	if (last[1][c] < last[2][c])
3005 	  black[row][c] = (last[0][c] < last[2][c]) ? last[0][c]:last[2][c];
3006     memmove (last, last+1, 2*sizeof last[0]);
3007     memcpy (last[2], black[row+1], sizeof last[2]);
3008   }
3009   FORC3 black[row][c] = (last[0][c] + last[1][c])/2;
3010   FORC3 black[0][c] = (black[1][c] + black[3][c])/2;
3011 
3012   val = 1 - exp(-1/24.0);
3013   memcpy (fsum, black, sizeof fsum);
3014   for (row=1; row < height; row++)
3015     FORC3 fsum[c] += black[row][c] =
3016 	(black[row][c] - black[row-1][c])*val + black[row-1][c];
3017   memcpy (last[0], black[height-1], sizeof last[0]);
3018   FORC3 fsum[c] /= height;
3019   for (row = height; row--; )
3020     FORC3 last[0][c] = black[row][c] =
3021 	(black[row][c] - fsum[c] - last[0][c])*val + last[0][c];
3022 
3023   memset (total, 0, sizeof total);
3024   for (row=2; row < height; row+=4)
3025     for (col=2; col < width; col+=4) {
3026       FORC3 total[c] += (short) image[row*width+col][c];
3027       total[3]++;
3028     }
3029   for (row=0; row < height; row++)
3030     FORC3 black[row][c] += fsum[c]/2 + total[c]/(total[3]*100.0);
3031 
3032   for (row=0; row < height; row++) {
3033     for (i=0; i < 6; i++)
3034       ddft[0][0][i] = ddft[1][0][i] +
3035 	row / (height-1.0) * (ddft[2][0][i] - ddft[1][0][i]);
3036     pix = image[row*width];
3037     memcpy (prev, pix, sizeof prev);
3038     frow = row / (height-1.0) * (dim[2]-1);
3039     if ((irow = frow) == dim[2]-1) irow--;
3040     frow -= irow;
3041     for (i=0; i < dim[1]; i++)
3042       FORC3 sgrow[i][c] = sgain[ irow   *dim[1]+i][c] * (1-frow) +
3043 			  sgain[(irow+1)*dim[1]+i][c] *    frow;
3044     for (col=0; col < width; col++) {
3045       FORC3 {
3046 	diff = pix[c] - prev[c];
3047 	prev[c] = pix[c];
3048 	ipix[c] = pix[c] + floor ((diff + (diff*diff >> 14)) * cfilt
3049 		- ddft[0][c][1] - ddft[0][c][0] * ((float) col/width - 0.5)
3050 		- black[row][c] );
3051       }
3052       FORC3 {
3053 	work[0][c] = ipix[c] * ipix[c] >> 14;
3054 	work[2][c] = ipix[c] * work[0][c] >> 14;
3055 	work[1][2-c] = ipix[(c+1) % 3] * ipix[(c+2) % 3] >> 14;
3056       }
3057       FORC3 {
3058 	for (val=i=0; i < 3; i++)
3059 	  for (  j=0; j < 3; j++)
3060 	    val += ppm[c][i][j] * work[i][j];
3061 	ipix[c] = floor ((ipix[c] + floor(val)) *
3062 		( sgrow[col/sgx  ][c] * (sgx - col%sgx) +
3063 		  sgrow[col/sgx+1][c] * (col%sgx) ) / sgx / div[c]);
3064 	if (ipix[c] > 32000) ipix[c] = 32000;
3065 	pix[c] = ipix[c];
3066       }
3067       pix += 4;
3068     }
3069   }
3070   free (black);
3071   free (sgrow);
3072   free (sgain);
3073 
3074   if ((badpix = (unsigned int *) foveon_camf_matrix (dim, "BadPixels"))) {
3075     for (i=0; i < dim[0]; i++) {
3076       col = (badpix[i] >> 8 & 0xfff) - keep[0];
3077       row = (badpix[i] >> 20       ) - keep[1];
3078       if ((unsigned)(row-1) > height-3 || (unsigned)(col-1) > width-3)
3079 	continue;
3080       memset (fsum, 0, sizeof fsum);
3081       for (sum=j=0; j < 8; j++)
3082 	if (badpix[i] & (1 << j)) {
3083 	  FORC3 fsum[c] += (short)
3084 		image[(row+hood[j*2])*width+col+hood[j*2+1]][c];
3085 	  sum++;
3086 	}
3087       if (sum) FORC3 image[row*width+col][c] = fsum[c]/sum;
3088     }
3089     free (badpix);
3090   }
3091 
3092   /* Array for 5x5 Gaussian averaging of red values */
3093   smrow[6] = (int (*)[3]) calloc (width*5, sizeof **smrow);
3094   merror (smrow[6], "foveon_interpolate()");
3095   for (i=0; i < 5; i++)
3096     smrow[i] = smrow[6] + i*width;
3097 
3098   /* Sharpen the reds against these Gaussian averages */
3099   for (smlast=-1, row=2; row < height-2; row++) {
3100     while (smlast < row+2) {
3101       for (i=0; i < 6; i++)
3102 	smrow[(i+5) % 6] = smrow[i];
3103       pix = image[++smlast*width+2];
3104       for (col=2; col < width-2; col++) {
3105 	smrow[4][col][0] =
3106 	  (pix[0]*6 + (pix[-4]+pix[4])*4 + pix[-8]+pix[8] + 8) >> 4;
3107 	pix += 4;
3108       }
3109     }
3110     pix = image[row*width+2];
3111     for (col=2; col < width-2; col++) {
3112       smred = ( 6 *  smrow[2][col][0]
3113 	      + 4 * (smrow[1][col][0] + smrow[3][col][0])
3114 	      +      smrow[0][col][0] + smrow[4][col][0] + 8 ) >> 4;
3115       if (col == 2)
3116 	smred_p = smred;
3117       i = pix[0] + ((pix[0] - ((smred*7 + smred_p) >> 3)) >> 3);
3118       if (i > 32000) i = 32000;
3119       pix[0] = i;
3120       smred_p = smred;
3121       pix += 4;
3122     }
3123   }
3124 
3125   /* Adjust the brighter pixels for better linearity */
3126   min = 0xffff;
3127   FORC3 {
3128     i = satlev[c] / div[c];
3129     if (min > i) min = i;
3130   }
3131   limit = min * 9 >> 4;
3132   for (pix=image[0]; pix < image[height*width]; pix+=4) {
3133     if (pix[0] <= limit || pix[1] <= limit || pix[2] <= limit)
3134       continue;
3135     min = max = pix[0];
3136     for (c=1; c < 3; c++) {
3137       if (min > pix[c]) min = pix[c];
3138       if (max < pix[c]) max = pix[c];
3139     }
3140     if (min >= limit*2) {
3141       pix[0] = pix[1] = pix[2] = max;
3142     } else {
3143       i = 0x4000 - ((min - limit) << 14) / limit;
3144       i = 0x4000 - (i*i >> 14);
3145       i = i*i >> 14;
3146       FORC3 pix[c] += (max - pix[c]) * i >> 14;
3147     }
3148   }
3149 /*
3150    Because photons that miss one detector often hit another,
3151    the sum R+G+B is much less noisy than the individual colors.
3152    So smooth the hues without smoothing the total.
3153  */
3154   for (smlast=-1, row=2; row < height-2; row++) {
3155     while (smlast < row+2) {
3156       for (i=0; i < 6; i++)
3157 	smrow[(i+5) % 6] = smrow[i];
3158       pix = image[++smlast*width+2];
3159       for (col=2; col < width-2; col++) {
3160 	FORC3 smrow[4][col][c] = (pix[c-4]+2*pix[c]+pix[c+4]+2) >> 2;
3161 	pix += 4;
3162       }
3163     }
3164     pix = image[row*width+2];
3165     for (col=2; col < width-2; col++) {
3166       FORC3 dev[c] = -foveon_apply_curve (curve[7], pix[c] -
3167 	((smrow[1][col][c] + 2*smrow[2][col][c] + smrow[3][col][c]) >> 2));
3168       sum = (dev[0] + dev[1] + dev[2]) >> 3;
3169       FORC3 pix[c] += dev[c] - sum;
3170       pix += 4;
3171     }
3172   }
3173   for (smlast=-1, row=2; row < height-2; row++) {
3174     while (smlast < row+2) {
3175       for (i=0; i < 6; i++)
3176 	smrow[(i+5) % 6] = smrow[i];
3177       pix = image[++smlast*width+2];
3178       for (col=2; col < width-2; col++) {
3179 	FORC3 smrow[4][col][c] =
3180 		(pix[c-8]+pix[c-4]+pix[c]+pix[c+4]+pix[c+8]+2) >> 2;
3181 	pix += 4;
3182       }
3183     }
3184     pix = image[row*width+2];
3185     for (col=2; col < width-2; col++) {
3186       for (total[3]=375, sum=60, c=0; c < 3; c++) {
3187 	for (total[c]=i=0; i < 5; i++)
3188 	  total[c] += smrow[i][col][c];
3189 	total[3] += total[c];
3190 	sum += pix[c];
3191       }
3192       if (sum < 0) sum = 0;
3193       j = total[3] > 375 ? (sum << 16) / total[3] : sum * 174;
3194       FORC3 pix[c] += foveon_apply_curve (curve[6],
3195 		((j*total[c] + 0x8000) >> 16) - pix[c]);
3196       pix += 4;
3197     }
3198   }
3199 
3200   /* Transform the image to a different colorspace */
3201   for (pix=image[0]; pix < image[height*width]; pix+=4) {
3202     FORC3 pix[c] -= foveon_apply_curve (curve[c], pix[c]);
3203     sum = (pix[0]+pix[1]+pix[1]+pix[2]) >> 2;
3204     FORC3 pix[c] -= foveon_apply_curve (curve[c], pix[c]-sum);
3205     FORC3 {
3206       for (dsum=i=0; i < 3; i++)
3207 	dsum += trans[c][i] * pix[i];
3208       if (dsum < 0)  dsum = 0;
3209       if (dsum > 24000) dsum = 24000;
3210       ipix[c] = dsum + 0.5;
3211     }
3212     FORC3 pix[c] = ipix[c];
3213   }
3214 
3215   /* Smooth the image bottom-to-top and save at 1/4 scale */
3216   shrink = (short (*)[3]) calloc ((width/4) * (height/4), sizeof *shrink);
3217   merror (shrink, "foveon_interpolate()");
3218   for (row = height/4; row--; )
3219     for (col=0; col < width/4; col++) {
3220       ipix[0] = ipix[1] = ipix[2] = 0;
3221       for (i=0; i < 4; i++)
3222 	for (j=0; j < 4; j++)
3223 	  FORC3 ipix[c] += image[(row*4+i)*width+col*4+j][c];
3224       FORC3
3225 	if (row+2 > height/4)
3226 	  shrink[row*(width/4)+col][c] = ipix[c] >> 4;
3227 	else
3228 	  shrink[row*(width/4)+col][c] =
3229 	    (shrink[(row+1)*(width/4)+col][c]*1840 + ipix[c]*141 + 2048) >> 12;
3230     }
3231   /* From the 1/4-scale image, smooth right-to-left */
3232   for (row=0; row < (height & ~3); row++) {
3233     ipix[0] = ipix[1] = ipix[2] = 0;
3234     if ((row & 3) == 0)
3235       for (col = width & ~3 ; col--; )
3236 	FORC3 smrow[0][col][c] = ipix[c] =
3237 	  (shrink[(row/4)*(width/4)+col/4][c]*1485 + ipix[c]*6707 + 4096) >> 13;
3238 
3239   /* Then smooth left-to-right */
3240     ipix[0] = ipix[1] = ipix[2] = 0;
3241     for (col=0; col < (width & ~3); col++)
3242       FORC3 smrow[1][col][c] = ipix[c] =
3243 	(smrow[0][col][c]*1485 + ipix[c]*6707 + 4096) >> 13;
3244 
3245   /* Smooth top-to-bottom */
3246     if (row == 0)
3247       memcpy (smrow[2], smrow[1], sizeof **smrow * width);
3248     else
3249       for (col=0; col < (width & ~3); col++)
3250 	FORC3 smrow[2][col][c] =
3251 	  (smrow[2][col][c]*6707 + smrow[1][col][c]*1485 + 4096) >> 13;
3252 
3253   /* Adjust the chroma toward the smooth values */
3254     for (col=0; col < (width & ~3); col++) {
3255       for (i=j=30, c=0; c < 3; c++) {
3256 	i += smrow[2][col][c];
3257 	j += image[row*width+col][c];
3258       }
3259       j = (j << 16) / i;
3260       for (sum=c=0; c < 3; c++) {
3261 	ipix[c] = foveon_apply_curve (curve[c+3],
3262 	  ((smrow[2][col][c] * j + 0x8000) >> 16) - image[row*width+col][c]);
3263 	sum += ipix[c];
3264       }
3265       sum >>= 3;
3266       FORC3 {
3267 	i = image[row*width+col][c] + ipix[c] - sum;
3268 	if (i < 0) i = 0;
3269 	image[row*width+col][c] = i;
3270       }
3271     }
3272   }
3273   free (shrink);
3274   free (smrow[6]);
3275   for (i=0; i < 8; i++)
3276     free (curve[i]);
3277 
3278   /* Trim off the black border */
3279   active[1] -= keep[1];
3280   active[3] -= 2;
3281   i = active[2] - active[0];
3282   for (row=0; row < active[3]-active[1]; row++)
3283     memcpy (image[row*i], image[(row+active[1])*width+active[0]],
3284 	 i * sizeof *image);
3285   width = i;
3286   height = row;
3287 }
3288 #undef image
3289 
3290 /* RESTRICTED code ends here */
3291 
3292 /*
3293    Seach from the current directory up to the root looking for
3294    a ".badpixels" file, and fix those pixels now.
3295  */
bad_pixels(const char * cfname)3296 void CLASS bad_pixels (const char *cfname)
3297 {
3298   FILE *fp=0;
3299   char *fname, *cp, line[128];
3300   int len, time, row, col, r, c, rad, tot, n, fixed=0;
3301 
3302   if (!filters) return;
3303   if (cfname)
3304     fp = fopen (cfname, "r");
3305   else {
3306     for (len=32 ; ; len *= 2) {
3307       fname = (char *) malloc (len);
3308       if (!fname) return;
3309       if (getcwd (fname, len-16)) break;
3310       free (fname);
3311       if (errno != ERANGE) return;
3312     }
3313 #if defined(WIN32) || defined(DJGPP)
3314     if (fname[1] == ':')
3315       memmove (fname, fname+2, len-2);
3316     for (cp=fname; *cp; cp++)
3317       if (*cp == '\\') *cp = '/';
3318 #endif
3319     cp = fname + strlen(fname);
3320     if (cp[-1] == '/') cp--;
3321     while (*fname == '/') {
3322       strcpy (cp, "/.badpixels");
3323       if ((fp = fopen (fname, "r"))) break;
3324       if (cp == fname) break;
3325       while (*--cp != '/');
3326     }
3327     free (fname);
3328   }
3329   if (!fp) return;
3330   while (fgets (line, 128, fp)) {
3331     cp = strchr (line, '#');
3332     if (cp) *cp = 0;
3333     if (sscanf (line, "%d %d %d", &col, &row, &time) != 3) continue;
3334     if ((unsigned) col >= width || (unsigned) row >= height) continue;
3335     if (time > timestamp) continue;
3336     for (tot=n=0, rad=1; rad < 3 && n==0; rad++)
3337       for (r = row-rad; r <= row+rad; r++)
3338 	for (c = col-rad; c <= col+rad; c++)
3339 	  if ((unsigned) r < height && (unsigned) c < width &&
3340 		(r != row || c != col) && fc(r,c) == fc(row,col)) {
3341 	    tot += BAYER2(r,c);
3342 	    n++;
3343 	  }
3344     BAYER2(row,col) = tot/n;
3345     if (verbose) {
3346       if (!fixed++)
3347 	fprintf (stderr,_("Fixed dead pixels at:"));
3348       fprintf (stderr, " %d,%d", col, row);
3349     }
3350   }
3351   if (fixed) fputc ('\n', stderr);
3352   fclose (fp);
3353 }
3354 
subtract(const char * fname)3355 void CLASS subtract (const char *fname)
3356 {
3357   FILE *fp;
3358   int dim[3]={0,0,0}, comment=0, number=0, error=0, nd=0, c, row, col;
3359   ushort *pixel;
3360 
3361   if (!(fp = fopen (fname, "rb"))) {
3362     perror (fname);  return;
3363   }
3364   if (fgetc(fp) != 'P' || fgetc(fp) != '5') error = 1;
3365   while (!error && nd < 3 && (c = fgetc(fp)) != EOF) {
3366     if (c == '#')  comment = 1;
3367     if (c == '\n') comment = 0;
3368     if (comment) continue;
3369     if (isdigit(c)) number = 1;
3370     if (number) {
3371       if (isdigit(c)) dim[nd] = dim[nd]*10 + c -'0';
3372       else if (isspace(c)) {
3373 	number = 0;  nd++;
3374       } else error = 1;
3375     }
3376   }
3377   if (error || nd < 3) {
3378     fprintf (stderr,_("%s is not a valid PGM file!\n"), fname);
3379     fclose (fp);  return;
3380   } else if (dim[0] != width || dim[1] != height || dim[2] != 65535) {
3381     fprintf (stderr,_("%s has the wrong dimensions!\n"), fname);
3382     fclose (fp);  return;
3383   }
3384   pixel = (ushort *) calloc (width, sizeof *pixel);
3385   merror (pixel, "subtract()");
3386   for (row=0; row < height; row++) {
3387     fread (pixel, 2, width, fp);
3388     for (col=0; col < width; col++)
3389       BAYER(row,col) = MAX (BAYER(row,col) - ntohs(pixel[col]), 0);
3390   }
3391   free (pixel);
3392   fclose (fp);
3393   memset (cblack, 0, sizeof cblack);
3394   black = 0;
3395 }
3396 
gamma_curve(double pwr,double ts,int mode,int imax)3397 void CLASS gamma_curve (double pwr, double ts, int mode, int imax)
3398 {
3399   int i;
3400   double g[6], bnd[2]={0,0}, r;
3401 
3402   g[0] = pwr;
3403   g[1] = ts;
3404   g[2] = g[3] = g[4] = 0;
3405   bnd[g[1] >= 1] = 1;
3406   if (g[1] && (g[1]-1)*(g[0]-1) <= 0) {
3407     for (i=0; i < 48; i++) {
3408       g[2] = (bnd[0] + bnd[1])/2;
3409       if (g[0]) bnd[(pow(g[2]/g[1],-g[0]) - 1)/g[0] - 1/g[2] > -1] = g[2];
3410       else	bnd[g[2]/exp(1-1/g[2]) < g[1]] = g[2];
3411     }
3412     g[3] = g[2] / g[1];
3413     if (g[0]) g[4] = g[2] * (1/g[0] - 1);
3414   }
3415   if (g[0]) g[5] = 1 / (g[1]*SQR(g[3])/2 - g[4]*(1 - g[3]) +
3416 		(1 - pow(g[3],1+g[0]))*(1 + g[4])/(1 + g[0])) - 1;
3417   else      g[5] = 1 / (g[1]*SQR(g[3])/2 + 1
3418 		- g[2] - g[3] -	g[2]*g[3]*(log(g[3]) - 1)) - 1;
3419   if (!mode--) {
3420     memcpy (gamm, g, sizeof gamm);
3421     return;
3422   }
3423   for (i=0; i < 0x10000; i++) {
3424     curve[i] = 0xffff;
3425     if ((r = (double) i / imax) < 1)
3426       curve[i] = 0x10000 * ( mode
3427 	? (r < g[3] ? r*g[1] : (g[0] ? pow( r,g[0])*(1+g[4])-g[4]    : log(r)*g[2]+1))
3428 	: (r < g[2] ? r/g[1] : (g[0] ? pow((r+g[4])/(1+g[4]),1/g[0]) : exp((r-1)/g[2]))));
3429   }
3430 }
3431 
pseudoinverse(double (* in)[3],double (* out)[3],int size)3432 void CLASS pseudoinverse (double (*in)[3], double (*out)[3], int size)
3433 {
3434   double work[3][6], num;
3435   int i, j, k;
3436 
3437   for (i=0; i < 3; i++) {
3438     for (j=0; j < 6; j++)
3439       work[i][j] = j == i+3;
3440     for (j=0; j < 3; j++)
3441       for (k=0; k < size; k++)
3442 	work[i][j] += in[k][i] * in[k][j];
3443   }
3444   for (i=0; i < 3; i++) {
3445     num = work[i][i];
3446     for (j=0; j < 6; j++)
3447       work[i][j] /= num;
3448     for (k=0; k < 3; k++) {
3449       if (k==i) continue;
3450       num = work[k][i];
3451       for (j=0; j < 6; j++)
3452 	work[k][j] -= work[i][j] * num;
3453     }
3454   }
3455   for (i=0; i < size; i++)
3456     for (j=0; j < 3; j++)
3457       for (out[i][j]=k=0; k < 3; k++)
3458 	out[i][j] += work[j][k+3] * in[i][k];
3459 }
3460 
cam_xyz_coeff(double cam_xyz[4][3])3461 void CLASS cam_xyz_coeff (double cam_xyz[4][3])
3462 {
3463   double cam_rgb[4][3], inverse[4][3], num;
3464   int i, j, k;
3465 
3466   for (i=0; i < colors; i++)		/* Multiply out XYZ colorspace */
3467     for (j=0; j < 3; j++)
3468       for (cam_rgb[i][j] = k=0; k < 3; k++)
3469 	cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j];
3470 
3471   for (i=0; i < colors; i++) {		/* Normalize cam_rgb so that */
3472     for (num=j=0; j < 3; j++)		/* cam_rgb * (1,1,1) is (1,1,1,1) */
3473       num += cam_rgb[i][j];
3474     for (j=0; j < 3; j++)
3475       cam_rgb[i][j] /= num;
3476     pre_mul[i] = 1 / num;
3477   }
3478   pseudoinverse (cam_rgb, inverse, colors);
3479   for (raw_color = i=0; i < 3; i++)
3480     for (j=0; j < colors; j++)
3481       rgb_cam[i][j] = inverse[j][i];
3482 }
3483 
3484 #ifdef COLORCHECK
colorcheck()3485 void CLASS colorcheck()
3486 {
3487 #define NSQ 24
3488 // Coordinates of the GretagMacbeth ColorChecker squares
3489 // width, height, 1st_column, 1st_row
3490   int cut[NSQ][4];			// you must set these
3491 // ColorChecker Chart under 6500-kelvin illumination
3492   static const double gmb_xyY[NSQ][3] = {
3493     { 0.400, 0.350, 10.1 },		// Dark Skin
3494     { 0.377, 0.345, 35.8 },		// Light Skin
3495     { 0.247, 0.251, 19.3 },		// Blue Sky
3496     { 0.337, 0.422, 13.3 },		// Foliage
3497     { 0.265, 0.240, 24.3 },		// Blue Flower
3498     { 0.261, 0.343, 43.1 },		// Bluish Green
3499     { 0.506, 0.407, 30.1 },		// Orange
3500     { 0.211, 0.175, 12.0 },		// Purplish Blue
3501     { 0.453, 0.306, 19.8 },		// Moderate Red
3502     { 0.285, 0.202, 6.6 },		// Purple
3503     { 0.380, 0.489, 44.3 },		// Yellow Green
3504     { 0.473, 0.438, 43.1 },		// Orange Yellow
3505     { 0.187, 0.129, 6.1 },		// Blue
3506     { 0.305, 0.478, 23.4 },		// Green
3507     { 0.539, 0.313, 12.0 },		// Red
3508     { 0.448, 0.470, 59.1 },		// Yellow
3509     { 0.364, 0.233, 19.8 },		// Magenta
3510     { 0.196, 0.252, 19.8 },		// Cyan
3511     { 0.310, 0.316, 90.0 },		// White
3512     { 0.310, 0.316, 59.1 },		// Neutral 8
3513     { 0.310, 0.316, 36.2 },		// Neutral 6.5
3514     { 0.310, 0.316, 19.8 },		// Neutral 5
3515     { 0.310, 0.316, 9.0 },		// Neutral 3.5
3516     { 0.310, 0.316, 3.1 } };		// Black
3517   double gmb_cam[NSQ][4], gmb_xyz[NSQ][3];
3518   double inverse[NSQ][3], cam_xyz[4][3], num;
3519   int c, i, j, k, sq, row, col, count[4];
3520 
3521   memset (gmb_cam, 0, sizeof gmb_cam);
3522   for (sq=0; sq < NSQ; sq++) {
3523     FORCC count[c] = 0;
3524     for   (row=cut[sq][3]; row < cut[sq][3]+cut[sq][1]; row++)
3525       for (col=cut[sq][2]; col < cut[sq][2]+cut[sq][0]; col++) {
3526 	c = FC(row,col);
3527 	if (c >= colors) c -= 2;
3528 	gmb_cam[sq][c] += BAYER(row,col);
3529 	count[c]++;
3530       }
3531     FORCC gmb_cam[sq][c] = gmb_cam[sq][c]/count[c] - black;
3532     gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1];
3533     gmb_xyz[sq][1] = gmb_xyY[sq][2];
3534     gmb_xyz[sq][2] = gmb_xyY[sq][2] *
3535 		(1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1];
3536   }
3537   pseudoinverse (gmb_xyz, inverse, NSQ);
3538   for (i=0; i < colors; i++)
3539     for (j=0; j < 3; j++)
3540       for (cam_xyz[i][j] = k=0; k < NSQ; k++)
3541 	cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j];
3542   cam_xyz_coeff (cam_xyz);
3543   if (verbose) {
3544     printf ("    { \"%s %s\", %d,\n\t{", make, model, black);
3545     num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]);
3546     FORCC for (j=0; j < 3; j++)
3547       printf ("%c%d", (c | j) ? ',':' ', (int) (cam_xyz[c][j] * num + 0.5));
3548     puts (" } },");
3549   }
3550 #undef NSQ
3551 }
3552 #endif
3553 
hat_transform(float * temp,float * base,int st,int size,int sc)3554 void CLASS hat_transform (float *temp, float *base, int st, int size, int sc)
3555 {
3556   int i;
3557   for (i=0; i < sc; i++)
3558     temp[i] = 2*base[st*i] + base[st*(sc-i)] + base[st*(i+sc)];
3559   for (; i+sc < size; i++)
3560     temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(i+sc)];
3561   for (; i < size; i++)
3562     temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(2*size-2-(i+sc))];
3563 }
3564 
wavelet_denoise()3565 void CLASS wavelet_denoise()
3566 {
3567   float *fimg=0, *temp, thold, mul[2], avg, diff;
3568   int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2];
3569   ushort *window[4];
3570   static const float noise[] =
3571   { 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 };
3572 
3573   if (verbose) fprintf (stderr,_("Wavelet denoising...\n"));
3574 
3575   while (maximum << scale < 0x10000) scale++;
3576   maximum <<= --scale;
3577   black <<= scale;
3578   FORC4 cblack[c] <<= scale;
3579   if ((size = iheight*iwidth) < 0x15550000)
3580     fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg);
3581   merror (fimg, "wavelet_denoise()");
3582   temp = fimg + size*3;
3583   if ((nc = colors) == 3 && filters) nc++;
3584   FORC(nc) {			/* denoise R,G1,B,G3 individually */
3585     for (i=0; i < size; i++)
3586       fimg[i] = 256 * sqrt(image[i][c] << scale);
3587     for (hpass=lev=0; lev < 5; lev++) {
3588       lpass = size*((lev & 1)+1);
3589       for (row=0; row < iheight; row++) {
3590 	hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev);
3591         for (col=0; col < iwidth; col++)
3592 	  fimg[lpass + row*iwidth + col] = temp[col] * 0.25;
3593       }
3594       for (col=0; col < iwidth; col++) {
3595 	hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev);
3596 	for (row=0; row < iheight; row++)
3597 	  fimg[lpass + row*iwidth + col] = temp[row] * 0.25;
3598       }
3599       thold = threshold * noise[lev];
3600       for (i=0; i < size; i++) {
3601 	fimg[hpass+i] -= fimg[lpass+i];
3602 	if	(fimg[hpass+i] < -thold) fimg[hpass+i] += thold;
3603 	else if (fimg[hpass+i] >  thold) fimg[hpass+i] -= thold;
3604 	else	 fimg[hpass+i] = 0;
3605 	if (hpass) fimg[i] += fimg[hpass+i];
3606       }
3607       hpass = lpass;
3608     }
3609     for (i=0; i < size; i++)
3610       image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000);
3611   }
3612   if (filters && colors == 3) {  /* pull G1 and G3 closer together */
3613     for (row=0; row < 2; row++) {
3614       mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1];
3615       blk[row] = cblack[FC(row,0) | 1];
3616     }
3617     for (i=0; i < 4; i++)
3618       window[i] = (ushort *) fimg + width*i;
3619     for (wlast=-1, row=1; row < height-1; row++) {
3620       while (wlast < row+1) {
3621 	for (wlast++, i=0; i < 4; i++)
3622 	  window[(i+3) & 3] = window[i];
3623 	for (col = FC(wlast,1) & 1; col < width; col+=2)
3624 	  window[2][col] = BAYER(wlast,col);
3625       }
3626       thold = threshold/512;
3627       for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) {
3628 	avg = ( window[0][col-1] + window[0][col+1] +
3629 		window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 )
3630 	      * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5;
3631 	avg = avg < 0 ? 0 : sqrt(avg);
3632 	diff = sqrt(BAYER(row,col)) - avg;
3633 	if      (diff < -thold) diff += thold;
3634 	else if (diff >  thold) diff -= thold;
3635 	else diff = 0;
3636 	BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5);
3637       }
3638     }
3639   }
3640   free (fimg);
3641 }
3642 
scale_colors()3643 void CLASS scale_colors()
3644 {
3645   unsigned bottom, right, size, row, col, ur, uc, i, x, y, c, sum[8];
3646   int val, dark, sat;
3647   double dsum[8], dmin, dmax;
3648   float scale_mul[4], fr, fc;
3649   ushort *img=0, *pix;
3650 
3651   FORC4 cblack[c] += black;
3652   if (user_mul[0])
3653     memcpy (pre_mul, user_mul, sizeof pre_mul);
3654   if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1)) {
3655     memset (dsum, 0, sizeof dsum);
3656     bottom = MIN (greybox[1]+greybox[3], height);
3657     right  = MIN (greybox[0]+greybox[2], width);
3658     for (row=greybox[1]; row < bottom; row += 8)
3659       for (col=greybox[0]; col < right; col += 8) {
3660 	memset (sum, 0, sizeof sum);
3661 	for (y=row; y < row+8 && y < bottom; y++)
3662 	  for (x=col; x < col+8 && x < right; x++)
3663 	    FORC4 {
3664 	      if (filters) {
3665 		c = FC(y,x);
3666 		val = BAYER(y,x);
3667 	      } else
3668 		val = image[y*width+x][c];
3669 	      if (val > maximum-25) goto skip_block;
3670 	      if ((val -= cblack[c]) < 0) val = 0;
3671 	      sum[c] += val;
3672 	      sum[c+4]++;
3673 	      if (filters) break;
3674 	    }
3675 	FORC(8) dsum[c] += sum[c];
3676 skip_block: ;
3677       }
3678     FORC4 if (dsum[c]) pre_mul[c] = dsum[c+4] / dsum[c];
3679   }
3680   if (use_camera_wb && cam_mul[0] != -1) {
3681     memset (sum, 0, sizeof sum);
3682     for (row=0; row < 8; row++)
3683       for (col=0; col < 8; col++) {
3684 	c = FC(row,col);
3685 	if ((val = white[row][col] - cblack[c]) > 0)
3686 	  sum[c] += val;
3687 	sum[c+4]++;
3688       }
3689     if (sum[0] && sum[1] && sum[2] && sum[3])
3690       FORC4 pre_mul[c] = (float) sum[c+4] / sum[c];
3691     else if (cam_mul[0] && cam_mul[2])
3692       memcpy (pre_mul, cam_mul, sizeof pre_mul);
3693     else
3694       fprintf (stderr,_("%s: Cannot use camera white balance.\n"), ifname);
3695   }
3696   if (pre_mul[3] == 0) pre_mul[3] = colors < 4 ? pre_mul[1] : 1;
3697   dark = black;
3698   sat = maximum;
3699   if (threshold) wavelet_denoise();
3700   maximum -= black;
3701   for (dmin=DBL_MAX, dmax=c=0; c < 4; c++) {
3702     if (dmin > pre_mul[c])
3703 	dmin = pre_mul[c];
3704     if (dmax < pre_mul[c])
3705 	dmax = pre_mul[c];
3706   }
3707   if (!highlight) dmax = dmin;
3708   FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum;
3709   if (verbose) {
3710     fprintf (stderr,
3711       _("Scaling with darkness %d, saturation %d, and\nmultipliers"), dark, sat);
3712     FORC4 fprintf (stderr, " %f", pre_mul[c]);
3713     fputc ('\n', stderr);
3714   }
3715   size = iheight*iwidth;
3716   for (i=0; i < size*4; i++) {
3717     val = image[0][i];
3718     if (!val) continue;
3719     val -= cblack[i & 3];
3720     val *= scale_mul[i & 3];
3721     image[0][i] = CLIP(val);
3722   }
3723   if ((aber[0] != 1 || aber[2] != 1) && colors == 3) {
3724     if (verbose)
3725       fprintf (stderr,_("Correcting chromatic aberration...\n"));
3726     for (c=0; c < 4; c+=2) {
3727       if (aber[c] == 1) continue;
3728       img = (ushort *) malloc (size * sizeof *img);
3729       merror (img, "scale_colors()");
3730       for (i=0; i < size; i++)
3731 	img[i] = image[i][c];
3732       for (row=0; row < iheight; row++) {
3733 	ur = fr = (row - iheight*0.5) * aber[c] + iheight*0.5;
3734 	if (ur > iheight-2) continue;
3735 	fr -= ur;
3736 	for (col=0; col < iwidth; col++) {
3737 	  uc = fc = (col - iwidth*0.5) * aber[c] + iwidth*0.5;
3738 	  if (uc > iwidth-2) continue;
3739 	  fc -= uc;
3740 	  pix = img + ur*iwidth + uc;
3741 	  image[row*iwidth+col][c] =
3742 	    (pix[     0]*(1-fc) + pix[       1]*fc) * (1-fr) +
3743 	    (pix[iwidth]*(1-fc) + pix[iwidth+1]*fc) * fr;
3744 	}
3745       }
3746       free(img);
3747     }
3748   }
3749 }
3750 
pre_interpolate()3751 void CLASS pre_interpolate()
3752 {
3753   ushort (*img)[4];
3754   int row, col, c;
3755 
3756   if (shrink) {
3757     if (half_size) {
3758       height = iheight;
3759       width  = iwidth;
3760     } else {
3761       img = (ushort (*)[4]) calloc (height*width, sizeof *img);
3762       merror (img, "pre_interpolate()");
3763       for (row=0; row < height; row++)
3764 	for (col=0; col < width; col++) {
3765 	  c = fc(row,col);
3766 	  img[row*width+col][c] = image[(row >> 1)*iwidth+(col >> 1)][c];
3767 	}
3768       free (image);
3769       image = img;
3770       shrink = 0;
3771     }
3772   }
3773   if (filters && colors == 3) {
3774     if ((mix_green = four_color_rgb)) colors++;
3775     else {
3776       for (row = FC(1,0) >> 1; row < height; row+=2)
3777 	for (col = FC(row,1) & 1; col < width; col+=2)
3778 	  image[row*width+col][1] = image[row*width+col][3];
3779       filters &= ~((filters & 0x55555555) << 1);
3780     }
3781   }
3782   if (half_size) filters = 0;
3783 }
3784 
border_interpolate(int border)3785 void CLASS border_interpolate (int border)
3786 {
3787   unsigned row, col, y, x, f, c, sum[8];
3788 
3789   for (row=0; row < height; row++)
3790     for (col=0; col < width; col++) {
3791       if (col==border && row >= border && row < height-border)
3792 	col = width-border;
3793       memset (sum, 0, sizeof sum);
3794       for (y=row-1; y != row+2; y++)
3795 	for (x=col-1; x != col+2; x++)
3796 	  if (y < height && x < width) {
3797 	    f = fc(y,x);
3798 	    sum[f] += image[y*width+x][f];
3799 	    sum[f+4]++;
3800 	  }
3801       f = fc(row,col);
3802       FORCC if (c != f && sum[c+4])
3803 	image[row*width+col][c] = sum[c] / sum[c+4];
3804     }
3805 }
3806 
lin_interpolate()3807 void CLASS lin_interpolate()
3808 {
3809   int code[16][16][32], *ip, sum[4];
3810   int c, i, x, y, row, col, shift, color;
3811   ushort *pix;
3812 
3813   if (verbose) fprintf (stderr,_("Bilinear interpolation...\n"));
3814 
3815   border_interpolate(1);
3816   for (row=0; row < 16; row++)
3817     for (col=0; col < 16; col++) {
3818       ip = code[row][col];
3819       memset (sum, 0, sizeof sum);
3820       for (y=-1; y <= 1; y++)
3821 	for (x=-1; x <= 1; x++) {
3822 	  shift = (y==0) + (x==0);
3823 	  if (shift == 2) continue;
3824 	  color = fc(row+y,col+x);
3825 	  *ip++ = (width*y + x)*4 + color;
3826 	  *ip++ = shift;
3827 	  *ip++ = color;
3828 	  sum[color] += 1 << shift;
3829 	}
3830       FORCC
3831 	if (c != fc(row,col)) {
3832 	  *ip++ = c;
3833 	  *ip++ = 256 / sum[c];
3834 	}
3835     }
3836   for (row=1; row < height-1; row++)
3837     for (col=1; col < width-1; col++) {
3838       pix = image[row*width+col];
3839       ip = code[row & 15][col & 15];
3840       memset (sum, 0, sizeof sum);
3841       for (i=8; i--; ip+=3)
3842 	sum[ip[2]] += pix[ip[0]] << ip[1];
3843       for (i=colors; --i; ip+=2)
3844 	pix[ip[0]] = sum[ip[0]] * ip[1] >> 8;
3845     }
3846 }
3847 
3848 /*
3849    This algorithm is officially called:
3850 
3851    "Interpolation using a Threshold-based variable number of gradients"
3852 
3853    described in http://scien.stanford.edu/pages/labsite/1999/psych221/projects/99/tingchen/algodep/vargra.html
3854 
3855    I've extended the basic idea to work with non-Bayer filter arrays.
3856    Gradients are numbered clockwise from NW=0 to W=7.
3857  */
vng_interpolate()3858 void CLASS vng_interpolate()
3859 {
3860   static const signed char *cp, terms[] = {
3861     -2,-2,+0,-1,0,0x01, -2,-2,+0,+0,1,0x01, -2,-1,-1,+0,0,0x01,
3862     -2,-1,+0,-1,0,0x02, -2,-1,+0,+0,0,0x03, -2,-1,+0,+1,1,0x01,
3863     -2,+0,+0,-1,0,0x06, -2,+0,+0,+0,1,0x02, -2,+0,+0,+1,0,0x03,
3864     -2,+1,-1,+0,0,0x04, -2,+1,+0,-1,1,0x04, -2,+1,+0,+0,0,0x06,
3865     -2,+1,+0,+1,0,0x02, -2,+2,+0,+0,1,0x04, -2,+2,+0,+1,0,0x04,
3866     -1,-2,-1,+0,0,0x80, -1,-2,+0,-1,0,0x01, -1,-2,+1,-1,0,0x01,
3867     -1,-2,+1,+0,1,0x01, -1,-1,-1,+1,0,0x88, -1,-1,+1,-2,0,0x40,
3868     -1,-1,+1,-1,0,0x22, -1,-1,+1,+0,0,0x33, -1,-1,+1,+1,1,0x11,
3869     -1,+0,-1,+2,0,0x08, -1,+0,+0,-1,0,0x44, -1,+0,+0,+1,0,0x11,
3870     -1,+0,+1,-2,1,0x40, -1,+0,+1,-1,0,0x66, -1,+0,+1,+0,1,0x22,
3871     -1,+0,+1,+1,0,0x33, -1,+0,+1,+2,1,0x10, -1,+1,+1,-1,1,0x44,
3872     -1,+1,+1,+0,0,0x66, -1,+1,+1,+1,0,0x22, -1,+1,+1,+2,0,0x10,
3873     -1,+2,+0,+1,0,0x04, -1,+2,+1,+0,1,0x04, -1,+2,+1,+1,0,0x04,
3874     +0,-2,+0,+0,1,0x80, +0,-1,+0,+1,1,0x88, +0,-1,+1,-2,0,0x40,
3875     +0,-1,+1,+0,0,0x11, +0,-1,+2,-2,0,0x40, +0,-1,+2,-1,0,0x20,
3876     +0,-1,+2,+0,0,0x30, +0,-1,+2,+1,1,0x10, +0,+0,+0,+2,1,0x08,
3877     +0,+0,+2,-2,1,0x40, +0,+0,+2,-1,0,0x60, +0,+0,+2,+0,1,0x20,
3878     +0,+0,+2,+1,0,0x30, +0,+0,+2,+2,1,0x10, +0,+1,+1,+0,0,0x44,
3879     +0,+1,+1,+2,0,0x10, +0,+1,+2,-1,1,0x40, +0,+1,+2,+0,0,0x60,
3880     +0,+1,+2,+1,0,0x20, +0,+1,+2,+2,0,0x10, +1,-2,+1,+0,0,0x80,
3881     +1,-1,+1,+1,0,0x88, +1,+0,+1,+2,0,0x08, +1,+0,+2,-1,0,0x40,
3882     +1,+0,+2,+1,0,0x10
3883   }, chood[] = { -1,-1, -1,0, -1,+1, 0,+1, +1,+1, +1,0, +1,-1, 0,-1 };
3884   ushort (*brow[5])[4], *pix;
3885   int prow=7, pcol=1, *ip, *code[16][16], gval[8], gmin, gmax, sum[4];
3886   int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag;
3887   int g, diff, thold, num, c;
3888 
3889   lin_interpolate();
3890   if (verbose) fprintf (stderr,_("VNG interpolation...\n"));
3891 
3892   if (filters == 1) prow = pcol = 15;
3893   ip = (int *) calloc ((prow+1)*(pcol+1), 1280);
3894   merror (ip, "vng_interpolate()");
3895   for (row=0; row <= prow; row++)		/* Precalculate for VNG */
3896     for (col=0; col <= pcol; col++) {
3897       code[row][col] = ip;
3898       for (cp=terms, t=0; t < 64; t++) {
3899 	y1 = *cp++;  x1 = *cp++;
3900 	y2 = *cp++;  x2 = *cp++;
3901 	weight = *cp++;
3902 	grads = *cp++;
3903 	color = fc(row+y1,col+x1);
3904 	if (fc(row+y2,col+x2) != color) continue;
3905 	diag = (fc(row,col+1) == color && fc(row+1,col) == color) ? 2:1;
3906 	if (abs(y1-y2) == diag && abs(x1-x2) == diag) continue;
3907 	*ip++ = (y1*width + x1)*4 + color;
3908 	*ip++ = (y2*width + x2)*4 + color;
3909 	*ip++ = weight;
3910 	for (g=0; g < 8; g++)
3911 	  if (grads & 1<<g) *ip++ = g;
3912 	*ip++ = -1;
3913       }
3914       *ip++ = INT_MAX;
3915       for (cp=chood, g=0; g < 8; g++) {
3916 	y = *cp++;  x = *cp++;
3917 	*ip++ = (y*width + x) * 4;
3918 	color = fc(row,col);
3919 	if (fc(row+y,col+x) != color && fc(row+y*2,col+x*2) == color)
3920 	  *ip++ = (y*width + x) * 8 + color;
3921 	else
3922 	  *ip++ = 0;
3923       }
3924     }
3925   brow[4] = (ushort (*)[4]) calloc (width*3, sizeof **brow);
3926   merror (brow[4], "vng_interpolate()");
3927   for (row=0; row < 3; row++)
3928     brow[row] = brow[4] + row*width;
3929   for (row=2; row < height-2; row++) {		/* Do VNG interpolation */
3930     for (col=2; col < width-2; col++) {
3931       pix = image[row*width+col];
3932       ip = code[row & prow][col & pcol];
3933       memset (gval, 0, sizeof gval);
3934       while ((g = ip[0]) != INT_MAX) {		/* Calculate gradients */
3935 	diff = ABS(pix[g] - pix[ip[1]]) << ip[2];
3936 	gval[ip[3]] += diff;
3937 	ip += 5;
3938 	if ((g = ip[-1]) == -1) continue;
3939 	gval[g] += diff;
3940 	while ((g = *ip++) != -1)
3941 	  gval[g] += diff;
3942       }
3943       ip++;
3944       gmin = gmax = gval[0];			/* Choose a threshold */
3945       for (g=1; g < 8; g++) {
3946 	if (gmin > gval[g]) gmin = gval[g];
3947 	if (gmax < gval[g]) gmax = gval[g];
3948       }
3949       if (gmax == 0) {
3950 	memcpy (brow[2][col], pix, sizeof *image);
3951 	continue;
3952       }
3953       thold = gmin + (gmax >> 1);
3954       memset (sum, 0, sizeof sum);
3955       color = fc(row,col);
3956       for (num=g=0; g < 8; g++,ip+=2) {		/* Average the neighbors */
3957 	if (gval[g] <= thold) {
3958 	  FORCC
3959 	    if (c == color && ip[1])
3960 	      sum[c] += (pix[c] + pix[ip[1]]) >> 1;
3961 	    else
3962 	      sum[c] += pix[ip[0] + c];
3963 	  num++;
3964 	}
3965       }
3966       FORCC {					/* Save to buffer */
3967 	t = pix[color];
3968 	if (c != color)
3969 	  t += (sum[c] - sum[color]) / num;
3970 	brow[2][col][c] = CLIP(t);
3971       }
3972     }
3973     if (row > 3)				/* Write buffer to image */
3974       memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image);
3975     for (g=0; g < 4; g++)
3976       brow[(g-1) & 3] = brow[g];
3977   }
3978   memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image);
3979   memcpy (image[(row-1)*width+2], brow[1]+2, (width-4)*sizeof *image);
3980   free (brow[4]);
3981   free (code[0][0]);
3982 }
3983 
3984 /*
3985    Patterned Pixel Grouping Interpolation by Alain Desbiolles
3986 */
ppg_interpolate()3987 void CLASS ppg_interpolate()
3988 {
3989   int dir[5] = { 1, width, -1, -width, 1 };
3990   int row, col, diff[2], guess[2], c, d, i;
3991   ushort (*pix)[4];
3992 
3993   border_interpolate(3);
3994   if (verbose) fprintf (stderr,_("PPG interpolation...\n"));
3995 
3996 /*  Fill in the green layer with gradients and pattern recognition: */
3997   for (row=3; row < height-3; row++)
3998     for (col=3+(FC(row,3) & 1), c=FC(row,col); col < width-3; col+=2) {
3999       pix = image + row*width+col;
4000       for (i=0; (d=dir[i]) > 0; i++) {
4001 	guess[i] = (pix[-d][1] + pix[0][c] + pix[d][1]) * 2
4002 		      - pix[-2*d][c] - pix[2*d][c];
4003 	diff[i] = ( ABS(pix[-2*d][c] - pix[ 0][c]) +
4004 		    ABS(pix[ 2*d][c] - pix[ 0][c]) +
4005 		    ABS(pix[  -d][1] - pix[ d][1]) ) * 3 +
4006 		  ( ABS(pix[ 3*d][1] - pix[ d][1]) +
4007 		    ABS(pix[-3*d][1] - pix[-d][1]) ) * 2;
4008       }
4009       d = dir[i = diff[0] > diff[1]];
4010       pix[0][1] = ULIM(guess[i] >> 2, pix[d][1], pix[-d][1]);
4011     }
4012 /*  Calculate red and blue for each green pixel:		*/
4013   for (row=1; row < height-1; row++)
4014     for (col=1+(FC(row,2) & 1), c=FC(row,col+1); col < width-1; col+=2) {
4015       pix = image + row*width+col;
4016       for (i=0; (d=dir[i]) > 0; c=2-c, i++)
4017 	pix[0][c] = CLIP((pix[-d][c] + pix[d][c] + 2*pix[0][1]
4018 			- pix[-d][1] - pix[d][1]) >> 1);
4019     }
4020 /*  Calculate blue for red pixels and vice versa:		*/
4021   for (row=1; row < height-1; row++)
4022     for (col=1+(FC(row,1) & 1), c=2-FC(row,col); col < width-1; col+=2) {
4023       pix = image + row*width+col;
4024       for (i=0; (d=dir[i]+dir[i+1]) > 0; i++) {
4025 	diff[i] = ABS(pix[-d][c] - pix[d][c]) +
4026 		  ABS(pix[-d][1] - pix[0][1]) +
4027 		  ABS(pix[ d][1] - pix[0][1]);
4028 	guess[i] = pix[-d][c] + pix[d][c] + 2*pix[0][1]
4029 		 - pix[-d][1] - pix[d][1];
4030       }
4031       if (diff[0] != diff[1])
4032 	pix[0][c] = CLIP(guess[diff[0] > diff[1]] >> 1);
4033       else
4034 	pix[0][c] = CLIP((guess[0]+guess[1]) >> 2);
4035     }
4036 }
4037 
4038 /*
4039    Adaptive Homogeneity-Directed interpolation is based on
4040    the work of Keigo Hirakawa, Thomas Parks, and Paul Lee.
4041  */
4042 #define TS 256		/* Tile Size */
4043 
ahd_interpolate()4044 void CLASS ahd_interpolate()
4045 {
4046   int i, j, k, top, left, row, col, tr, tc, c, d, val, hm[2];
4047   ushort (*pix)[4], (*rix)[3];
4048   static const int dir[4] = { -1, 1, -TS, TS };
4049   unsigned ldiff[2][4], abdiff[2][4], leps, abeps;
4050   float r, cbrt[0x10000], xyz[3], xyz_cam[3][4];
4051   ushort (*rgb)[TS][TS][3];
4052    short (*lab)[TS][TS][3], (*lix)[3];
4053    char (*homo)[TS][TS], *buffer;
4054 
4055   if (verbose) fprintf (stderr,_("AHD interpolation...\n"));
4056 
4057   for (i=0; i < 0x10000; i++) {
4058     r = i / 65535.0;
4059     cbrt[i] = r > 0.008856 ? pow(r,1/3.0) : 7.787*r + 16/116.0;
4060   }
4061   for (i=0; i < 3; i++)
4062     for (j=0; j < colors; j++)
4063       for (xyz_cam[i][j] = k=0; k < 3; k++)
4064 	xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i];
4065 
4066   border_interpolate(5);
4067   buffer = (char *) malloc (26*TS*TS);		/* 1664 kB */
4068   merror (buffer, "ahd_interpolate()");
4069   rgb  = (ushort(*)[TS][TS][3]) buffer;
4070   lab  = (short (*)[TS][TS][3])(buffer + 12*TS*TS);
4071   homo = (char  (*)[TS][TS])   (buffer + 24*TS*TS);
4072 
4073   for (top=2; top < height-5; top += TS-6)
4074     for (left=2; left < width-5; left += TS-6) {
4075 
4076 /*  Interpolate green horizontally and vertically:		*/
4077       for (row = top; row < top+TS && row < height-2; row++) {
4078 	col = left + (FC(row,left) & 1);
4079 	for (c = FC(row,col); col < left+TS && col < width-2; col+=2) {
4080 	  pix = image + row*width+col;
4081 	  val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2
4082 		- pix[-2][c] - pix[2][c]) >> 2;
4083 	  rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]);
4084 	  val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2
4085 		- pix[-2*width][c] - pix[2*width][c]) >> 2;
4086 	  rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]);
4087 	}
4088       }
4089 /*  Interpolate red and blue, and convert to CIELab:		*/
4090       for (d=0; d < 2; d++)
4091 	for (row=top+1; row < top+TS-1 && row < height-3; row++)
4092 	  for (col=left+1; col < left+TS-1 && col < width-3; col++) {
4093 	    pix = image + row*width+col;
4094 	    rix = &rgb[d][row-top][col-left];
4095 	    lix = &lab[d][row-top][col-left];
4096 	    if ((c = 2 - FC(row,col)) == 1) {
4097 	      c = FC(row+1,col);
4098 	      val = pix[0][1] + (( pix[-1][2-c] + pix[1][2-c]
4099 				 - rix[-1][1] - rix[1][1] ) >> 1);
4100 	      rix[0][2-c] = CLIP(val);
4101 	      val = pix[0][1] + (( pix[-width][c] + pix[width][c]
4102 				 - rix[-TS][1] - rix[TS][1] ) >> 1);
4103 	    } else
4104 	      val = rix[0][1] + (( pix[-width-1][c] + pix[-width+1][c]
4105 				 + pix[+width-1][c] + pix[+width+1][c]
4106 				 - rix[-TS-1][1] - rix[-TS+1][1]
4107 				 - rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2);
4108 	    rix[0][c] = CLIP(val);
4109 	    c = FC(row,col);
4110 	    rix[0][c] = pix[0][c];
4111 	    xyz[0] = xyz[1] = xyz[2] = 0.5;
4112 	    FORCC {
4113 	      xyz[0] += xyz_cam[0][c] * rix[0][c];
4114 	      xyz[1] += xyz_cam[1][c] * rix[0][c];
4115 	      xyz[2] += xyz_cam[2][c] * rix[0][c];
4116 	    }
4117 	    xyz[0] = cbrt[CLIP((int) xyz[0])];
4118 	    xyz[1] = cbrt[CLIP((int) xyz[1])];
4119 	    xyz[2] = cbrt[CLIP((int) xyz[2])];
4120 	    lix[0][0] = 64 * (116 * xyz[1] - 16);
4121 	    lix[0][1] = 64 * 500 * (xyz[0] - xyz[1]);
4122 	    lix[0][2] = 64 * 200 * (xyz[1] - xyz[2]);
4123 	  }
4124 /*  Build homogeneity maps from the CIELab images:		*/
4125       memset (homo, 0, 2*TS*TS);
4126       for (row=top+2; row < top+TS-2 && row < height-4; row++) {
4127 	tr = row-top;
4128 	for (col=left+2; col < left+TS-2 && col < width-4; col++) {
4129 	  tc = col-left;
4130 	  for (d=0; d < 2; d++) {
4131 	    lix = &lab[d][tr][tc];
4132 	    for (i=0; i < 4; i++) {
4133 	       ldiff[d][i] = ABS(lix[0][0]-lix[dir[i]][0]);
4134 	      abdiff[d][i] = SQR(lix[0][1]-lix[dir[i]][1])
4135 			   + SQR(lix[0][2]-lix[dir[i]][2]);
4136 	    }
4137 	  }
4138 	  leps = MIN(MAX(ldiff[0][0],ldiff[0][1]),
4139 		     MAX(ldiff[1][2],ldiff[1][3]));
4140 	  abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]),
4141 		      MAX(abdiff[1][2],abdiff[1][3]));
4142 	  for (d=0; d < 2; d++)
4143 	    for (i=0; i < 4; i++)
4144 	      if (ldiff[d][i] <= leps && abdiff[d][i] <= abeps)
4145 		homo[d][tr][tc]++;
4146 	}
4147       }
4148 /*  Combine the most homogenous pixels for the final result:	*/
4149       for (row=top+3; row < top+TS-3 && row < height-5; row++) {
4150 	tr = row-top;
4151 	for (col=left+3; col < left+TS-3 && col < width-5; col++) {
4152 	  tc = col-left;
4153 	  for (d=0; d < 2; d++)
4154 	    for (hm[d]=0, i=tr-1; i <= tr+1; i++)
4155 	      for (j=tc-1; j <= tc+1; j++)
4156 		hm[d] += homo[d][i][j];
4157 	  if (hm[0] != hm[1])
4158 	    FORC3 image[row*width+col][c] = rgb[hm[1] > hm[0]][tr][tc][c];
4159 	  else
4160 	    FORC3 image[row*width+col][c] =
4161 		(rgb[0][tr][tc][c] + rgb[1][tr][tc][c]) >> 1;
4162 	}
4163       }
4164     }
4165   free (buffer);
4166 }
4167 #undef TS
4168 
median_filter()4169 void CLASS median_filter()
4170 {
4171   ushort (*pix)[4];
4172   int pass, c, i, j, k, med[9];
4173   static const uchar opt[] =	/* Optimal 9-element median search */
4174   { 1,2, 4,5, 7,8, 0,1, 3,4, 6,7, 1,2, 4,5, 7,8,
4175     0,3, 5,8, 4,7, 3,6, 1,4, 2,5, 4,7, 4,2, 6,4, 4,2 };
4176 
4177   for (pass=1; pass <= med_passes; pass++) {
4178     if (verbose)
4179       fprintf (stderr,_("Median filter pass %d...\n"), pass);
4180     for (c=0; c < 3; c+=2) {
4181       for (pix = image; pix < image+width*height; pix++)
4182 	pix[0][3] = pix[0][c];
4183       for (pix = image+width; pix < image+width*(height-1); pix++) {
4184 	if ((pix-image+1) % width < 2) continue;
4185 	for (k=0, i = -width; i <= width; i += width)
4186 	  for (j = i-1; j <= i+1; j++)
4187 	    med[k++] = pix[j][3] - pix[j][1];
4188 	for (i=0; i < sizeof opt; i+=2)
4189 	  if     (med[opt[i]] > med[opt[i+1]])
4190 	    SWAP (med[opt[i]] , med[opt[i+1]]);
4191 	pix[0][c] = CLIP(med[4] + pix[0][1]);
4192       }
4193     }
4194   }
4195 }
4196 
blend_highlights()4197 void CLASS blend_highlights()
4198 {
4199   int clip=INT_MAX, row, col, c, i, j;
4200   static const float trans[2][4][4] =
4201   { { { 1,1,1 }, { 1.7320508,-1.7320508,0 }, { -1,-1,2 } },
4202     { { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } };
4203   static const float itrans[2][4][4] =
4204   { { { 1,0.8660254,-0.5 }, { 1,-0.8660254,-0.5 }, { 1,0,1 } },
4205     { { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } };
4206   float cam[2][4], lab[2][4], sum[2], chratio;
4207 
4208   if ((unsigned) (colors-3) > 1) return;
4209   if (verbose) fprintf (stderr,_("Blending highlights...\n"));
4210   FORCC if (clip > (i = 65535*pre_mul[c])) clip = i;
4211   for (row=0; row < height; row++)
4212     for (col=0; col < width; col++) {
4213       FORCC if (image[row*width+col][c] > clip) break;
4214       if (c == colors) continue;
4215       FORCC {
4216 	cam[0][c] = image[row*width+col][c];
4217 	cam[1][c] = MIN(cam[0][c],clip);
4218       }
4219       for (i=0; i < 2; i++) {
4220 	FORCC for (lab[i][c]=j=0; j < colors; j++)
4221 	  lab[i][c] += trans[colors-3][c][j] * cam[i][j];
4222 	for (sum[i]=0,c=1; c < colors; c++)
4223 	  sum[i] += SQR(lab[i][c]);
4224       }
4225       chratio = sqrt(sum[1]/sum[0]);
4226       for (c=1; c < colors; c++)
4227 	lab[0][c] *= chratio;
4228       FORCC for (cam[0][c]=j=0; j < colors; j++)
4229 	cam[0][c] += itrans[colors-3][c][j] * lab[0][j];
4230       FORCC image[row*width+col][c] = cam[0][c] / colors;
4231     }
4232 }
4233 
4234 #define SCALE (4 >> shrink)
recover_highlights()4235 void CLASS recover_highlights()
4236 {
4237   float *map, sum, wgt, grow;
4238   int hsat[4], count, spread, change, val, i;
4239   unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x;
4240   ushort *pixel;
4241   static const signed char dir[8][2] =
4242     { {-1,-1}, {-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1} };
4243 
4244   if (verbose) fprintf (stderr,_("Rebuilding highlights...\n"));
4245 
4246   grow = pow (2, 4-highlight);
4247   FORCC hsat[c] = 32000 * pre_mul[c];
4248   for (kc=0, c=1; c < colors; c++)
4249     if (pre_mul[kc] < pre_mul[c]) kc = c;
4250   high = height / SCALE;
4251   wide =  width / SCALE;
4252   map = (float *) calloc (high*wide, sizeof *map);
4253   merror (map, "recover_highlights()");
4254   FORCC if (c != kc) {
4255     memset (map, 0, high*wide*sizeof *map);
4256     for (mrow=0; mrow < high; mrow++)
4257       for (mcol=0; mcol < wide; mcol++) {
4258 	sum = wgt = count = 0;
4259 	for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++)
4260 	  for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) {
4261 	    pixel = image[row*width+col];
4262 	    if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000) {
4263 	      sum += pixel[c];
4264 	      wgt += pixel[kc];
4265 	      count++;
4266 	    }
4267 	  }
4268 	if (count == SCALE*SCALE)
4269 	  map[mrow*wide+mcol] = sum / wgt;
4270       }
4271     for (spread = 32/grow; spread--; ) {
4272       for (mrow=0; mrow < high; mrow++)
4273 	for (mcol=0; mcol < wide; mcol++) {
4274 	  if (map[mrow*wide+mcol]) continue;
4275 	  sum = count = 0;
4276 	  for (d=0; d < 8; d++) {
4277 	    y = mrow + dir[d][0];
4278 	    x = mcol + dir[d][1];
4279 	    if (y < high && x < wide && map[y*wide+x] > 0) {
4280 	      sum  += (1 + (d & 1)) * map[y*wide+x];
4281 	      count += 1 + (d & 1);
4282 	    }
4283 	  }
4284 	  if (count > 3)
4285 	    map[mrow*wide+mcol] = - (sum+grow) / (count+grow);
4286 	}
4287       for (change=i=0; i < high*wide; i++)
4288 	if (map[i] < 0) {
4289 	  map[i] = -map[i];
4290 	  change = 1;
4291 	}
4292       if (!change) break;
4293     }
4294     for (i=0; i < high*wide; i++)
4295       if (map[i] == 0) map[i] = 1;
4296     for (mrow=0; mrow < high; mrow++)
4297       for (mcol=0; mcol < wide; mcol++) {
4298 	for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++)
4299 	  for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) {
4300 	    pixel = image[row*width+col];
4301 	    if (pixel[c] / hsat[c] > 1) {
4302 	      val = pixel[kc] * map[mrow*wide+mcol];
4303 	      if (pixel[c] < val) pixel[c] = CLIP(val);
4304 	    }
4305 	  }
4306       }
4307   }
4308   free (map);
4309 }
4310 #undef SCALE
4311 
tiff_get(unsigned base,unsigned * tag,unsigned * type,unsigned * len,unsigned * save)4312 void CLASS tiff_get (unsigned base,
4313 	unsigned *tag, unsigned *type, unsigned *len, unsigned *save)
4314 {
4315   *tag  = get2();
4316   *type = get2();
4317   *len  = get4();
4318   *save = ftell(ifp) + 4;
4319   if (*len * ("11124811248488"[*type < 14 ? *type:0]-'0') > 4)
4320     fseek (ifp, get4()+base, SEEK_SET);
4321 }
4322 
parse_thumb_note(int base,unsigned toff,unsigned tlen)4323 void CLASS parse_thumb_note (int base, unsigned toff, unsigned tlen)
4324 {
4325   unsigned entries, tag, type, len, save;
4326 
4327   entries = get2();
4328   while (entries--) {
4329     tiff_get (base, &tag, &type, &len, &save);
4330     if (tag == toff) thumb_offset = get4()+base;
4331     if (tag == tlen) thumb_length = get4();
4332     fseek (ifp, save, SEEK_SET);
4333   }
4334 }
4335 
4336 int CLASS parse_tiff_ifd (int base);
4337 
parse_makernote(int base,int uptag)4338 void CLASS parse_makernote (int base, int uptag)
4339 {
4340   static const uchar xlat[2][256] = {
4341   { 0xc1,0xbf,0x6d,0x0d,0x59,0xc5,0x13,0x9d,0x83,0x61,0x6b,0x4f,0xc7,0x7f,0x3d,0x3d,
4342     0x53,0x59,0xe3,0xc7,0xe9,0x2f,0x95,0xa7,0x95,0x1f,0xdf,0x7f,0x2b,0x29,0xc7,0x0d,
4343     0xdf,0x07,0xef,0x71,0x89,0x3d,0x13,0x3d,0x3b,0x13,0xfb,0x0d,0x89,0xc1,0x65,0x1f,
4344     0xb3,0x0d,0x6b,0x29,0xe3,0xfb,0xef,0xa3,0x6b,0x47,0x7f,0x95,0x35,0xa7,0x47,0x4f,
4345     0xc7,0xf1,0x59,0x95,0x35,0x11,0x29,0x61,0xf1,0x3d,0xb3,0x2b,0x0d,0x43,0x89,0xc1,
4346     0x9d,0x9d,0x89,0x65,0xf1,0xe9,0xdf,0xbf,0x3d,0x7f,0x53,0x97,0xe5,0xe9,0x95,0x17,
4347     0x1d,0x3d,0x8b,0xfb,0xc7,0xe3,0x67,0xa7,0x07,0xf1,0x71,0xa7,0x53,0xb5,0x29,0x89,
4348     0xe5,0x2b,0xa7,0x17,0x29,0xe9,0x4f,0xc5,0x65,0x6d,0x6b,0xef,0x0d,0x89,0x49,0x2f,
4349     0xb3,0x43,0x53,0x65,0x1d,0x49,0xa3,0x13,0x89,0x59,0xef,0x6b,0xef,0x65,0x1d,0x0b,
4350     0x59,0x13,0xe3,0x4f,0x9d,0xb3,0x29,0x43,0x2b,0x07,0x1d,0x95,0x59,0x59,0x47,0xfb,
4351     0xe5,0xe9,0x61,0x47,0x2f,0x35,0x7f,0x17,0x7f,0xef,0x7f,0x95,0x95,0x71,0xd3,0xa3,
4352     0x0b,0x71,0xa3,0xad,0x0b,0x3b,0xb5,0xfb,0xa3,0xbf,0x4f,0x83,0x1d,0xad,0xe9,0x2f,
4353     0x71,0x65,0xa3,0xe5,0x07,0x35,0x3d,0x0d,0xb5,0xe9,0xe5,0x47,0x3b,0x9d,0xef,0x35,
4354     0xa3,0xbf,0xb3,0xdf,0x53,0xd3,0x97,0x53,0x49,0x71,0x07,0x35,0x61,0x71,0x2f,0x43,
4355     0x2f,0x11,0xdf,0x17,0x97,0xfb,0x95,0x3b,0x7f,0x6b,0xd3,0x25,0xbf,0xad,0xc7,0xc5,
4356     0xc5,0xb5,0x8b,0xef,0x2f,0xd3,0x07,0x6b,0x25,0x49,0x95,0x25,0x49,0x6d,0x71,0xc7 },
4357   { 0xa7,0xbc,0xc9,0xad,0x91,0xdf,0x85,0xe5,0xd4,0x78,0xd5,0x17,0x46,0x7c,0x29,0x4c,
4358     0x4d,0x03,0xe9,0x25,0x68,0x11,0x86,0xb3,0xbd,0xf7,0x6f,0x61,0x22,0xa2,0x26,0x34,
4359     0x2a,0xbe,0x1e,0x46,0x14,0x68,0x9d,0x44,0x18,0xc2,0x40,0xf4,0x7e,0x5f,0x1b,0xad,
4360     0x0b,0x94,0xb6,0x67,0xb4,0x0b,0xe1,0xea,0x95,0x9c,0x66,0xdc,0xe7,0x5d,0x6c,0x05,
4361     0xda,0xd5,0xdf,0x7a,0xef,0xf6,0xdb,0x1f,0x82,0x4c,0xc0,0x68,0x47,0xa1,0xbd,0xee,
4362     0x39,0x50,0x56,0x4a,0xdd,0xdf,0xa5,0xf8,0xc6,0xda,0xca,0x90,0xca,0x01,0x42,0x9d,
4363     0x8b,0x0c,0x73,0x43,0x75,0x05,0x94,0xde,0x24,0xb3,0x80,0x34,0xe5,0x2c,0xdc,0x9b,
4364     0x3f,0xca,0x33,0x45,0xd0,0xdb,0x5f,0xf5,0x52,0xc3,0x21,0xda,0xe2,0x22,0x72,0x6b,
4365     0x3e,0xd0,0x5b,0xa8,0x87,0x8c,0x06,0x5d,0x0f,0xdd,0x09,0x19,0x93,0xd0,0xb9,0xfc,
4366     0x8b,0x0f,0x84,0x60,0x33,0x1c,0x9b,0x45,0xf1,0xf0,0xa3,0x94,0x3a,0x12,0x77,0x33,
4367     0x4d,0x44,0x78,0x28,0x3c,0x9e,0xfd,0x65,0x57,0x16,0x94,0x6b,0xfb,0x59,0xd0,0xc8,
4368     0x22,0x36,0xdb,0xd2,0x63,0x98,0x43,0xa1,0x04,0x87,0x86,0xf7,0xa6,0x26,0xbb,0xd6,
4369     0x59,0x4d,0xbf,0x6a,0x2e,0xaa,0x2b,0xef,0xe6,0x78,0xb6,0x4e,0xe0,0x2f,0xdc,0x7c,
4370     0xbe,0x57,0x19,0x32,0x7e,0x2a,0xd0,0xb8,0xba,0x29,0x00,0x3c,0x52,0x7d,0xa8,0x49,
4371     0x3b,0x2d,0xeb,0x25,0x49,0xfa,0xa3,0xaa,0x39,0xa7,0xc5,0xa7,0x50,0x11,0x36,0xfb,
4372     0xc6,0x67,0x4a,0xf5,0xa5,0x12,0x65,0x7e,0xb0,0xdf,0xaf,0x4e,0xb3,0x61,0x7f,0x2f } };
4373   unsigned offset=0, entries, tag, type, len, save, c;
4374   unsigned ver97=0, serial=0, i, wbi=0, wb[4]={0,0,0,0};
4375   uchar buf97[324], ci, cj, ck;
4376   short sorder=order;
4377   char buf[10];
4378 /*
4379    The MakerNote might have its own TIFF header (possibly with
4380    its own byte-order!), or it might just be a table.
4381  */
4382   fread (buf, 1, 10, ifp);
4383   if (!strncmp (buf,"KDK" ,3) ||	/* these aren't TIFF tables */
4384       !strncmp (buf,"VER" ,3) ||
4385       !strncmp (buf,"IIII",4) ||
4386       !strncmp (buf,"MMMM",4)) return;
4387   if (!strncmp (buf,"KC"  ,2) ||	/* Konica KD-400Z, KD-510Z */
4388       !strncmp (buf,"MLY" ,3)) {	/* Minolta DiMAGE G series */
4389     order = 0x4d4d;
4390     while ((i=ftell(ifp)) < data_offset && i < 16384) {
4391       wb[0] = wb[2];  wb[2] = wb[1];  wb[1] = wb[3];
4392       wb[3] = get2();
4393       if (wb[1] == 256 && wb[3] == 256 &&
4394 	  wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640)
4395 	FORC4 cam_mul[c] = wb[c];
4396     }
4397     goto quit;
4398   }
4399   if (!strcmp (buf,"Nikon")) {
4400     base = ftell(ifp);
4401     order = get2();
4402     if (get2() != 42) goto quit;
4403     offset = get4();
4404     fseek (ifp, offset-8, SEEK_CUR);
4405   } else if (!strcmp (buf,"OLYMPUS")) {
4406     base = ftell(ifp)-10;
4407     fseek (ifp, -2, SEEK_CUR);
4408     order = get2();  get2();
4409   } else if (!strncmp (buf,"FUJIFILM",8) ||
4410 	     !strncmp (buf,"SONY",4) ||
4411 	     !strcmp  (buf,"Panasonic")) {
4412     order = 0x4949;
4413     fseek (ifp,  2, SEEK_CUR);
4414   } else if (!strcmp (buf,"OLYMP") ||
4415 	     !strcmp (buf,"LEICA") ||
4416 	     !strcmp (buf,"Ricoh") ||
4417 	     !strcmp (buf,"EPSON"))
4418     fseek (ifp, -2, SEEK_CUR);
4419   else if (!strcmp (buf,"AOC") ||
4420 	   !strcmp (buf,"QVC"))
4421     fseek (ifp, -4, SEEK_CUR);
4422   else {
4423     fseek (ifp, -10, SEEK_CUR);
4424     if (!strncmp(make,"SAMSUNG",7))
4425       base = ftell(ifp);
4426   }
4427   entries = get2();
4428   if (entries > 1000) return;
4429   while (entries--) {
4430     tiff_get (base, &tag, &type, &len, &save);
4431     tag |= uptag << 16;
4432     if (tag == 2 && strstr(make,"NIKON"))
4433       iso_speed = (get2(),get2());
4434     if (tag == 4 && len > 26 && len < 35) {
4435       if ((i=(get4(),get2())) != 0x7fff && !iso_speed)
4436 	iso_speed = 50 * pow (2, i/32.0 - 4);
4437       if ((i=(get2(),get2())) != 0x7fff && !aperture)
4438 	aperture = pow (2, i/64.0);
4439       if ((i=get2()) != 0xffff && !shutter)
4440 	shutter = pow (2, (short) i/-32.0);
4441       wbi = (get2(),get2());
4442       shot_order = (get2(),get2());
4443     }
4444     if ((tag == 4 || tag == 0x114) && !strncmp(make,"KONICA",6)) {
4445       fseek (ifp, tag == 4 ? 140:160, SEEK_CUR);
4446       switch (get2()) {
4447 	case 72:  flip = 0;  break;
4448 	case 76:  flip = 6;  break;
4449 	case 82:  flip = 5;  break;
4450       }
4451     }
4452     if (tag == 7 && type == 2 && len > 20)
4453       fgets (model2, 64, ifp);
4454     if (tag == 8 && type == 4)
4455       shot_order = get4();
4456     if (tag == 9 && !strcmp(make,"Canon"))
4457       fread (artist, 64, 1, ifp);
4458     if (tag == 0xc && len == 4) {
4459       cam_mul[0] = getreal(type);
4460       cam_mul[2] = getreal(type);
4461     }
4462     if (tag == 0xd && type == 7 && get2() == 0xaaaa) {
4463       fread (buf97, 1, sizeof buf97, ifp);
4464       i = (uchar *) memmem (buf97, sizeof buf97,"\xbb\xbb",2) - buf97 + 10;
4465       if (i < 70 && buf97[i] < 3)
4466 	flip = "065"[buf97[i]]-'0';
4467     }
4468     if (tag == 0x10 && type == 4)
4469       unique_id = get4();
4470     if (tag == 0x11 && is_raw && !strncmp(make,"NIKON",5)) {
4471       fseek (ifp, get4()+base, SEEK_SET);
4472       parse_tiff_ifd (base);
4473     }
4474     if (tag == 0x14 && type == 7) {
4475       if (len == 2560) {
4476 	fseek (ifp, 1248, SEEK_CUR);
4477 	goto get2_256;
4478       }
4479       fread (buf, 1, 10, ifp);
4480       if (!strncmp(buf,"NRW ",4)) {
4481 	fseek (ifp, strcmp(buf+4,"0100") ? 46:1546, SEEK_CUR);
4482 	cam_mul[0] = get4() << 2;
4483 	cam_mul[1] = get4() + get4();
4484 	cam_mul[2] = get4() << 2;
4485       }
4486     }
4487     if (tag == 0x15 && type == 2 && is_raw)
4488       fread (model, 64, 1, ifp);
4489     if (strstr(make,"PENTAX")) {
4490       if (tag == 0x1b) tag = 0x1018;
4491       if (tag == 0x1c) tag = 0x1017;
4492     }
4493     if (tag == 0x1d)
4494       while ((c = fgetc(ifp)) && c != EOF)
4495 	serial = serial*10 + (isdigit(c) ? c - '0' : c % 10);
4496     if (tag == 0x81 && type == 4) {
4497       data_offset = get4();
4498       fseek (ifp, data_offset + 41, SEEK_SET);
4499       raw_height = get2() * 2;
4500       raw_width  = get2();
4501       filters = 0x61616161;
4502     }
4503     if (tag == 0x29 && type == 1) {
4504       c = wbi < 18 ? "012347800000005896"[wbi]-'0' : 0;
4505       fseek (ifp, 8 + c*32, SEEK_CUR);
4506       FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4();
4507     }
4508     if ((tag == 0x81  && type == 7) ||
4509 	(tag == 0x100 && type == 7) ||
4510 	(tag == 0x280 && type == 1)) {
4511       thumb_offset = ftell(ifp);
4512       thumb_length = len;
4513     }
4514     if (tag == 0x88 && type == 4 && (thumb_offset = get4()))
4515       thumb_offset += base;
4516     if (tag == 0x89 && type == 4)
4517       thumb_length = get4();
4518     if (tag == 0x8c || tag == 0x96)
4519       meta_offset = ftell(ifp);
4520     if (tag == 0x97) {
4521       for (i=0; i < 4; i++)
4522 	ver97 = ver97 * 10 + fgetc(ifp)-'0';
4523       switch (ver97) {
4524 	case 100:
4525 	  fseek (ifp, 68, SEEK_CUR);
4526 	  FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2();
4527 	  break;
4528 	case 102:
4529 	  fseek (ifp, 6, SEEK_CUR);
4530 	  goto get2_rggb;
4531 	case 103:
4532 	  fseek (ifp, 16, SEEK_CUR);
4533 	  FORC4 cam_mul[c] = get2();
4534       }
4535       if (ver97 >= 200) {
4536 	if (ver97 != 205) fseek (ifp, 280, SEEK_CUR);
4537 	fread (buf97, 324, 1, ifp);
4538       }
4539     }
4540     if (tag == 0xa1 && type == 7) {
4541       type = order;
4542       order = 0x4949;
4543       fseek (ifp, 140, SEEK_CUR);
4544       FORC3 cam_mul[c] = get4();
4545       order = type;
4546     }
4547     if (tag == 0xa4 && type == 3) {
4548       fseek (ifp, wbi*48, SEEK_CUR);
4549       FORC3 cam_mul[c] = get2();
4550     }
4551     if (tag == 0xa7 && (unsigned) (ver97-200) < 12 && !cam_mul[0]) {
4552       ci = xlat[0][serial & 0xff];
4553       cj = xlat[1][fgetc(ifp)^fgetc(ifp)^fgetc(ifp)^fgetc(ifp)];
4554       ck = 0x60;
4555       for (i=0; i < 324; i++)
4556 	buf97[i] ^= (cj += ci * ck++);
4557       i = "66666>666;6A"[ver97-200] - '0';
4558       FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] =
4559 	sget2 (buf97 + (i & -2) + c*2);
4560     }
4561     if (tag == 0x200 && len == 3)
4562       shot_order = (get4(),get4());
4563     if (tag == 0x200 && len == 4)
4564       FORC4 cblack[c ^ c >> 1] = get2();
4565     if (tag == 0x201 && len == 4)
4566       goto get2_rggb;
4567     if (tag == 0x220 && type == 7)
4568       meta_offset = ftell(ifp);
4569     if (tag == 0x401 && type == 4 && len == 4)
4570       FORC4 cblack[c ^ c >> 1] = get4();
4571     if (tag == 0xe01) {		/* Nikon Capture Note */
4572       type = order;
4573       order = 0x4949;
4574       fseek (ifp, 22, SEEK_CUR);
4575       for (offset=22; offset+22 < len; offset += 22+i) {
4576 	tag = get4();
4577 	fseek (ifp, 14, SEEK_CUR);
4578 	i = get4()-4;
4579 	if (tag == 0x76a43207) flip = get2();
4580 	else fseek (ifp, i, SEEK_CUR);
4581       }
4582       order = type;
4583     }
4584     if (tag == 0xe80 && len == 256 && type == 7) {
4585       fseek (ifp, 48, SEEK_CUR);
4586       cam_mul[0] = get2() * 508 * 1.078 / 0x10000;
4587       cam_mul[2] = get2() * 382 * 1.173 / 0x10000;
4588     }
4589     if (tag == 0xf00 && type == 7) {
4590       if (len == 614)
4591 	fseek (ifp, 176, SEEK_CUR);
4592       else if (len == 734 || len == 1502)
4593 	fseek (ifp, 148, SEEK_CUR);
4594       else goto next;
4595       goto get2_256;
4596     }
4597     if ((tag == 0x1011 && len == 9) || tag == 0x20400200)
4598       for (i=0; i < 3; i++)
4599 	FORC3 cmatrix[i][c] = ((short) get2()) / 256.0;
4600     if ((tag == 0x1012 || tag == 0x20400600) && len == 4)
4601       FORC4 cblack[c ^ c >> 1] = get2();
4602     if (tag == 0x1017 || tag == 0x20400100)
4603       cam_mul[0] = get2() / 256.0;
4604     if (tag == 0x1018 || tag == 0x20400100)
4605       cam_mul[2] = get2() / 256.0;
4606     if (tag == 0x2011 && len == 2) {
4607 get2_256:
4608       order = 0x4d4d;
4609       cam_mul[0] = get2() / 256.0;
4610       cam_mul[2] = get2() / 256.0;
4611     }
4612     if ((tag | 0x70) == 0x2070 && type == 4)
4613       fseek (ifp, get4()+base, SEEK_SET);
4614     if (tag == 0x2010 && type != 7)
4615       load_raw = &CLASS olympus_load_raw;
4616     if (tag == 0x2020)
4617       parse_thumb_note (base, 257, 258);
4618     if (tag == 0x2040)
4619       parse_makernote (base, 0x2040);
4620     if (tag == 0xb028) {
4621       fseek (ifp, get4()+base, SEEK_SET);
4622       parse_thumb_note (base, 136, 137);
4623     }
4624     if (tag == 0x4001 && len > 500) {
4625       i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126;
4626       fseek (ifp, i, SEEK_CUR);
4627 get2_rggb:
4628       FORC4 cam_mul[c ^ (c >> 1)] = get2();
4629       fseek (ifp, 22, SEEK_CUR);
4630       FORC4 sraw_mul[c ^ (c >> 1)] = get2();
4631     }
4632     if (tag == 0xa021)
4633       FORC4 cam_mul[c ^ (c >> 1)] = get4();
4634     if (tag == 0xa028)
4635       FORC4 cam_mul[c ^ (c >> 1)] -= get4();
4636 next:
4637     fseek (ifp, save, SEEK_SET);
4638   }
4639 quit:
4640   order = sorder;
4641 }
4642 
4643 /*
4644    Since the TIFF DateTime string has no timezone information,
4645    assume that the camera's clock was set to Universal Time.
4646  */
get_timestamp(int reversed)4647 void CLASS get_timestamp (int reversed)
4648 {
4649   struct tm t;
4650   char str[20];
4651   int i;
4652 
4653   str[19] = 0;
4654   if (reversed)
4655     for (i=19; i--; ) str[i] = fgetc(ifp);
4656   else
4657     fread (str, 19, 1, ifp);
4658   memset (&t, 0, sizeof t);
4659   if (sscanf (str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon,
4660 	&t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6)
4661     return;
4662   t.tm_year -= 1900;
4663   t.tm_mon -= 1;
4664   t.tm_isdst = -1;
4665   if (mktime(&t) > 0)
4666     timestamp = mktime(&t);
4667 }
4668 
parse_exif(int base)4669 void CLASS parse_exif (int base)
4670 {
4671   unsigned kodak, entries, tag, type, len, save, c;
4672   double expo;
4673 
4674   kodak = !strncmp(make,"EASTMAN",7) && tiff_nifds < 3;
4675   entries = get2();
4676   while (entries--) {
4677     tiff_get (base, &tag, &type, &len, &save);
4678     switch (tag) {
4679       case 33434:  shutter = getreal(type);		break;
4680       case 33437:  aperture = getreal(type);		break;
4681       case 34855:  iso_speed = get2();			break;
4682       case 36867:
4683       case 36868:  get_timestamp(0);			break;
4684       case 37377:  if ((expo = -getreal(type)) < 128)
4685 		     shutter = pow (2, expo);		break;
4686       case 37378:  aperture = pow (2, getreal(type)/2);	break;
4687       case 37386:  focal_len = getreal(type);		break;
4688       case 37500:  parse_makernote (base, 0);		break;
4689       case 40962:  if (kodak) raw_width  = get4();	break;
4690       case 40963:  if (kodak) raw_height = get4();	break;
4691       case 41730:
4692 	if (get4() == 0x20002)
4693 	  for (exif_cfa=c=0; c < 8; c+=2)
4694 	    exif_cfa |= fgetc(ifp) * 0x01010101 << c;
4695     }
4696     fseek (ifp, save, SEEK_SET);
4697   }
4698 }
4699 
parse_gps(int base)4700 void CLASS parse_gps (int base)
4701 {
4702   unsigned entries, tag, type, len, save, c;
4703 
4704   entries = get2();
4705   while (entries--) {
4706     tiff_get (base, &tag, &type, &len, &save);
4707     switch (tag) {
4708       case 1: case 3: case 5:
4709 	gpsdata[29+tag/2] = getc(ifp);			break;
4710       case 2: case 4: case 7:
4711 	FORC(6) gpsdata[tag/3*6+c] = get4();		break;
4712       case 6:
4713 	FORC(2) gpsdata[18+c] = get4();			break;
4714       case 18: case 29:
4715 	fgets ((char *) (gpsdata+14+tag/3), MIN(len,12), ifp);
4716     }
4717     fseek (ifp, save, SEEK_SET);
4718   }
4719 }
4720 
romm_coeff(float romm_cam[3][3])4721 void CLASS romm_coeff (float romm_cam[3][3])
4722 {
4723   static const float rgb_romm[3][3] =	/* ROMM == Kodak ProPhoto */
4724   { {  2.034193, -0.727420, -0.306766 },
4725     { -0.228811,  1.231729, -0.002922 },
4726     { -0.008565, -0.153273,  1.161839 } };
4727   int i, j, k;
4728 
4729   for (i=0; i < 3; i++)
4730     for (j=0; j < 3; j++)
4731       for (cmatrix[i][j] = k=0; k < 3; k++)
4732 	cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j];
4733 }
4734 
parse_mos(int offset)4735 void CLASS parse_mos (int offset)
4736 {
4737   char data[40];
4738   int skip, from, i, c, neut[4], planes=0, frot=0;
4739   static const char *mod[] =
4740   { "","DCB2","Volare","Cantare","CMost","Valeo 6","Valeo 11","Valeo 22",
4741     "Valeo 11p","Valeo 17","","Aptus 17","Aptus 22","Aptus 75","Aptus 65",
4742     "Aptus 54S","Aptus 65S","Aptus 75S","AFi 5","AFi 6","AFi 7" };
4743   float romm_cam[3][3];
4744 
4745   fseek (ifp, offset, SEEK_SET);
4746   while (1) {
4747     if (get4() != 0x504b5453) break;
4748     get4();
4749     fread (data, 1, 40, ifp);
4750     skip = get4();
4751     from = ftell(ifp);
4752     if (!strcmp(data,"JPEG_preview_data")) {
4753       thumb_offset = from;
4754       thumb_length = skip;
4755     }
4756     if (!strcmp(data,"icc_camera_profile")) {
4757       profile_offset = from;
4758       profile_length = skip;
4759     }
4760     if (!strcmp(data,"ShootObj_back_type")) {
4761       fscanf (ifp, "%d", &i);
4762       if ((unsigned) i < sizeof mod / sizeof (*mod))
4763 	strcpy (model, mod[i]);
4764     }
4765     if (!strcmp(data,"icc_camera_to_tone_matrix")) {
4766       for (i=0; i < 9; i++)
4767 	romm_cam[0][i] = int_to_float(get4());
4768       romm_coeff (romm_cam);
4769     }
4770     if (!strcmp(data,"CaptProf_color_matrix")) {
4771       for (i=0; i < 9; i++)
4772 	fscanf (ifp, "%f", &romm_cam[0][i]);
4773       romm_coeff (romm_cam);
4774     }
4775     if (!strcmp(data,"CaptProf_number_of_planes"))
4776       fscanf (ifp, "%d", &planes);
4777     if (!strcmp(data,"CaptProf_raw_data_rotation"))
4778       fscanf (ifp, "%d", &flip);
4779     if (!strcmp(data,"CaptProf_mosaic_pattern"))
4780       FORC4 {
4781 	fscanf (ifp, "%d", &i);
4782 	if (i == 1) frot = c ^ (c >> 1);
4783       }
4784     if (!strcmp(data,"ImgProf_rotation_angle")) {
4785       fscanf (ifp, "%d", &i);
4786       flip = i - flip;
4787     }
4788     if (!strcmp(data,"NeutObj_neutrals") && !cam_mul[0]) {
4789       FORC4 fscanf (ifp, "%d", neut+c);
4790       FORC3 cam_mul[c] = (float) neut[0] / neut[c+1];
4791     }
4792     parse_mos (from);
4793     fseek (ifp, skip+from, SEEK_SET);
4794   }
4795   if (planes)
4796     filters = (planes == 1) * 0x01010101 *
4797 	(uchar) "\x94\x61\x16\x49"[(flip/90 + frot) & 3];
4798 }
4799 
linear_table(unsigned len)4800 void CLASS linear_table (unsigned len)
4801 {
4802   int i;
4803   if (len > 0x1000) len = 0x1000;
4804   read_shorts (curve, len);
4805   for (i=len; i < 0x1000; i++)
4806     curve[i] = curve[i-1];
4807   maximum = curve[0xfff];
4808 }
4809 
parse_kodak_ifd(int base)4810 void CLASS parse_kodak_ifd (int base)
4811 {
4812   unsigned entries, tag, type, len, save;
4813   int i, c, wbi=-2, wbtemp=6500;
4814   float mul[3]={1,1,1}, num;
4815   static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 };
4816 
4817   entries = get2();
4818   if (entries > 1024) return;
4819   while (entries--) {
4820     tiff_get (base, &tag, &type, &len, &save);
4821     if (tag == 1020) wbi = getint(type);
4822     if (tag == 1021 && len == 72) {		/* WB set in software */
4823       fseek (ifp, 40, SEEK_CUR);
4824       FORC3 cam_mul[c] = 2048.0 / get2();
4825       wbi = -2;
4826     }
4827     if (tag == 2118) wbtemp = getint(type);
4828     if (tag == 2130 + wbi)
4829       FORC3 mul[c] = getreal(type);
4830     if (tag == 2140 + wbi && wbi >= 0)
4831       FORC3 {
4832 	for (num=i=0; i < 4; i++)
4833 	  num += getreal(type) * pow (wbtemp/100.0, i);
4834 	cam_mul[c] = 2048 / (num * mul[c]);
4835       }
4836     if (tag == 2317) linear_table (len);
4837     if (tag == 6020) iso_speed = getint(type);
4838     if (tag == 64013) wbi = fgetc(ifp);
4839     if ((unsigned) wbi < 7 && tag == wbtag[wbi])
4840       FORC3 cam_mul[c] = get4();
4841     if (tag == 64019) width = getint(type);
4842     if (tag == 64020) height = (getint(type)+1) & -2;
4843     fseek (ifp, save, SEEK_SET);
4844   }
4845 }
4846 
4847 void CLASS parse_minolta (int base);
4848 int CLASS parse_tiff (int base);
4849 
parse_tiff_ifd(int base)4850 int CLASS parse_tiff_ifd (int base)
4851 {
4852   unsigned entries, tag, type, len, plen=16, save;
4853   int ifd, use_cm=0, cfa, i, j, c, ima_len=0;
4854   int blrr=1, blrc=1, dblack[] = { 0,0,0,0 };
4855   char software[64], *cbuf, *cp;
4856   uchar cfa_pat[16], cfa_pc[] = { 0,1,2,3 }, tab[256];
4857   double cc[4][4], cm[4][3], cam_xyz[4][3], num;
4858   double ab[]={ 1,1,1,1 }, asn[] = { 0,0,0,0 }, xyz[] = { 1,1,1 };
4859   unsigned sony_curve[] = { 0,0,0,0,0,4095 };
4860   unsigned *buf, sony_offset=0, sony_length=0, sony_key=0;
4861   struct jhead jh;
4862   FILE *sfp;
4863 
4864   if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0])
4865     return 1;
4866   ifd = tiff_nifds++;
4867   for (j=0; j < 4; j++)
4868     for (i=0; i < 4; i++)
4869       cc[j][i] = i == j;
4870   entries = get2();
4871   if (entries > 512) return 1;
4872   while (entries--) {
4873     tiff_get (base, &tag, &type, &len, &save);
4874     switch (tag) {
4875       case 5:   width  = get2();  break;
4876       case 6:   height = get2();  break;
4877       case 7:   width += get2();  break;
4878       case 9:  filters = get2();  break;
4879       case 17: case 18:
4880 	if (type == 3 && len == 1)
4881 	  cam_mul[(tag-17)*2] = get2() / 256.0;
4882 	break;
4883       case 23:
4884 	if (type == 3) iso_speed = get2();
4885 	break;
4886       case 36: case 37: case 38:
4887 	cam_mul[tag-0x24] = get2();
4888 	break;
4889       case 39:
4890 	if (len < 50 || cam_mul[0]) break;
4891 	fseek (ifp, 12, SEEK_CUR);
4892 	FORC3 cam_mul[c] = get2();
4893 	break;
4894       case 46:
4895 	if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break;
4896 	thumb_offset = ftell(ifp) - 2;
4897 	thumb_length = len;
4898 	break;
4899       case 61440:			/* Fuji HS10 table */
4900 	parse_tiff_ifd (base);
4901 	break;
4902       case 2: case 256: case 61441:	/* ImageWidth */
4903 	tiff_ifd[ifd].width = getint(type);
4904 	break;
4905       case 3: case 257: case 61442:	/* ImageHeight */
4906 	tiff_ifd[ifd].height = getint(type);
4907 	break;
4908       case 258:				/* BitsPerSample */
4909       case 61443:
4910 	tiff_ifd[ifd].samples = len & 7;
4911 	tiff_ifd[ifd].bps = getint(type);
4912 	break;
4913       case 259:				/* Compression */
4914 	tiff_ifd[ifd].comp = get2();
4915 	break;
4916       case 262:				/* PhotometricInterpretation */
4917 	tiff_ifd[ifd].phint = get2();
4918 	break;
4919       case 270:				/* ImageDescription */
4920 	fread (desc, 512, 1, ifp);
4921 	break;
4922       case 271:				/* Make */
4923 	fgets (make, 64, ifp);
4924 	break;
4925       case 272:				/* Model */
4926 	fgets (model, 64, ifp);
4927 	break;
4928       case 280:				/* Panasonic RW2 offset */
4929 	if (type != 4) break;
4930 	load_raw = &CLASS panasonic_load_raw;
4931 	load_flags = 0x2008;
4932       case 273:				/* StripOffset */
4933       case 513:				/* JpegIFOffset */
4934       case 61447:
4935 	tiff_ifd[ifd].offset = get4()+base;
4936 	if (!tiff_ifd[ifd].bps) {
4937 	  fseek (ifp, tiff_ifd[ifd].offset, SEEK_SET);
4938 	  if (ljpeg_start (&jh, 1)) {
4939 	    tiff_ifd[ifd].comp    = 6;
4940 	    tiff_ifd[ifd].width   = jh.wide;
4941 	    tiff_ifd[ifd].height  = jh.high;
4942 	    tiff_ifd[ifd].bps     = jh.bits;
4943 	    tiff_ifd[ifd].samples = jh.clrs;
4944 	    if (!(jh.sraw || (jh.clrs & 1)))
4945 	      tiff_ifd[ifd].width *= jh.clrs;
4946 	    i = order;
4947 	    parse_tiff (tiff_ifd[ifd].offset + 12);
4948 	    order = i;
4949 	  }
4950 	}
4951 	break;
4952       case 274:				/* Orientation */
4953 	tiff_ifd[ifd].flip = "50132467"[get2() & 7]-'0';
4954 	break;
4955       case 277:				/* SamplesPerPixel */
4956 	tiff_ifd[ifd].samples = getint(type) & 7;
4957 	break;
4958       case 279:				/* StripByteCounts */
4959       case 514:
4960       case 61448:
4961 	tiff_ifd[ifd].bytes = get4();
4962 	break;
4963       case 61454:
4964 	FORC3 cam_mul[(4-c) % 3] = getint(type);
4965 	break;
4966       case 305:  case 11:		/* Software */
4967 	fgets (software, 64, ifp);
4968 	if (!strncmp(software,"Adobe",5) ||
4969 	    !strncmp(software,"dcraw",5) ||
4970 	    !strncmp(software,"UFRaw",5) ||
4971 	    !strncmp(software,"Bibble",6) ||
4972 	    !strncmp(software,"Nikon Scan",10) ||
4973 	    !strcmp (software,"Digital Photo Professional"))
4974 	  is_raw = 0;
4975 	break;
4976       case 306:				/* DateTime */
4977 	get_timestamp(0);
4978 	break;
4979       case 315:				/* Artist */
4980 	fread (artist, 64, 1, ifp);
4981 	break;
4982       case 322:				/* TileWidth */
4983 	tile_width = getint(type);
4984 	break;
4985       case 323:				/* TileLength */
4986 	tile_length = getint(type);
4987 	break;
4988       case 324:				/* TileOffsets */
4989 	tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4();
4990 	if (len == 4) {
4991 	  load_raw = &CLASS sinar_4shot_load_raw;
4992 	  is_raw = 5;
4993 	}
4994 	break;
4995       case 330:				/* SubIFDs */
4996 	if (!strcmp(model,"DSLR-A100") && tiff_ifd[ifd].width == 3872) {
4997 	  load_raw = &CLASS sony_arw_load_raw;
4998 	  data_offset = get4()+base;
4999 	  ifd++;  break;
5000 	}
5001 	while (len--) {
5002 	  i = ftell(ifp);
5003 	  fseek (ifp, get4()+base, SEEK_SET);
5004 	  if (parse_tiff_ifd (base)) break;
5005 	  fseek (ifp, i+4, SEEK_SET);
5006 	}
5007 	break;
5008       case 400:
5009 	strcpy (make, "Sarnoff");
5010 	maximum = 0xfff;
5011 	break;
5012       case 28688:
5013 	FORC4 sony_curve[c+1] = get2() >> 2 & 0xfff;
5014 	for (i=0; i < 5; i++)
5015 	  for (j = sony_curve[i]+1; j <= sony_curve[i+1]; j++)
5016 	    curve[j] = curve[j-1] + (1 << i);
5017 	break;
5018       case 29184: sony_offset = get4();  break;
5019       case 29185: sony_length = get4();  break;
5020       case 29217: sony_key    = get4();  break;
5021       case 29264:
5022 	parse_minolta (ftell(ifp));
5023 	raw_width = 0;
5024 	break;
5025       case 29443:
5026 	FORC4 cam_mul[c ^ (c < 2)] = get2();
5027 	break;
5028       case 29459:
5029 	FORC4 cam_mul[c] = get2();
5030 	i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1;
5031 	SWAP (cam_mul[i],cam_mul[i+1])
5032 	break;
5033       case 33405:			/* Model2 */
5034 	fgets (model2, 64, ifp);
5035 	break;
5036       case 33422:			/* CFAPattern */
5037       case 64777:			/* Kodak P-series */
5038 	if ((plen=len) > 16) plen = 16;
5039 	fread (cfa_pat, 1, plen, ifp);
5040 	for (colors=cfa=i=0; i < plen; i++) {
5041 	  colors += !(cfa & (1 << cfa_pat[i]));
5042 	  cfa |= 1 << cfa_pat[i];
5043 	}
5044 	if (cfa == 070) memcpy (cfa_pc,"\003\004\005",3);	/* CMY */
5045 	if (cfa == 072) memcpy (cfa_pc,"\005\003\004\001",4);	/* GMCY */
5046 	goto guess_cfa_pc;
5047       case 33424:
5048       case 65024:
5049 	fseek (ifp, get4()+base, SEEK_SET);
5050 	parse_kodak_ifd (base);
5051 	break;
5052       case 33434:			/* ExposureTime */
5053 	shutter = getreal(type);
5054 	break;
5055       case 33437:			/* FNumber */
5056 	aperture = getreal(type);
5057 	break;
5058       case 34306:			/* Leaf white balance */
5059 	FORC4 cam_mul[c ^ 1] = 4096.0 / get2();
5060 	break;
5061       case 34307:			/* Leaf CatchLight color matrix */
5062 	fread (software, 1, 7, ifp);
5063 	if (strncmp(software,"MATRIX",6)) break;
5064 	colors = 4;
5065 	for (raw_color = i=0; i < 3; i++) {
5066 	  FORC4 fscanf (ifp, "%f", &rgb_cam[i][c^1]);
5067 	  if (!use_camera_wb) continue;
5068 	  num = 0;
5069 	  FORC4 num += rgb_cam[i][c];
5070 	  FORC4 rgb_cam[i][c] /= num;
5071 	}
5072 	break;
5073       case 34310:			/* Leaf metadata */
5074 	parse_mos (ftell(ifp));
5075       case 34303:
5076 	strcpy (make, "Leaf");
5077 	break;
5078       case 34665:			/* EXIF tag */
5079 	fseek (ifp, get4()+base, SEEK_SET);
5080 	parse_exif (base);
5081 	break;
5082       case 34853:			/* GPSInfo tag */
5083 	fseek (ifp, get4()+base, SEEK_SET);
5084 	parse_gps (base);
5085 	break;
5086       case 34675:			/* InterColorProfile */
5087       case 50831:			/* AsShotICCProfile */
5088 	profile_offset = ftell(ifp);
5089 	profile_length = len;
5090 	break;
5091       case 37122:			/* CompressedBitsPerPixel */
5092 	kodak_cbpp = get4();
5093 	break;
5094       case 37386:			/* FocalLength */
5095 	focal_len = getreal(type);
5096 	break;
5097       case 37393:			/* ImageNumber */
5098 	shot_order = getint(type);
5099 	break;
5100       case 37400:			/* old Kodak KDC tag */
5101 	for (raw_color = i=0; i < 3; i++) {
5102 	  getreal(type);
5103 	  FORC3 rgb_cam[i][c] = getreal(type);
5104 	}
5105 	break;
5106       case 46275:			/* Imacon tags */
5107 	strcpy (make, "Imacon");
5108 	data_offset = ftell(ifp);
5109 	ima_len = len;
5110 	break;
5111       case 46279:
5112 	if (!ima_len) break;
5113 	fseek (ifp, 78, SEEK_CUR);
5114 	raw_width  = get4();
5115 	raw_height = get4();
5116 	left_margin = get4() & 7;
5117 	width = raw_width - left_margin - (get4() & 7);
5118 	top_margin = get4() & 7;
5119 	height = raw_height - top_margin - (get4() & 7);
5120 	if (raw_width == 7262) {
5121 	  height = 5444;
5122 	  width  = 7244;
5123 	  left_margin = 7;
5124 	}
5125 	fseek (ifp, 52, SEEK_CUR);
5126 	FORC3 cam_mul[c] = getreal(11);
5127 	fseek (ifp, 114, SEEK_CUR);
5128 	flip = (get2() >> 7) * 90;
5129 	if (width * height * 6 == ima_len) {
5130 	  if (flip % 180 == 90) SWAP(width,height);
5131 	  filters = flip = 0;
5132 	}
5133 	sprintf (model, "Ixpress %d-Mp", height*width/1000000);
5134 	load_raw = &CLASS imacon_full_load_raw;
5135 	if (filters) {
5136 	  if (left_margin & 1) filters = 0x61616161;
5137 	  load_raw = &CLASS unpacked_load_raw;
5138 	}
5139 	maximum = 0xffff;
5140 	break;
5141       case 50454:			/* Sinar tag */
5142       case 50455:
5143 	if (!(cbuf = (char *) malloc(len))) break;
5144 	fread (cbuf, 1, len, ifp);
5145 	for (cp = cbuf-1; cp && cp < cbuf+len; cp = strchr(cp,'\n'))
5146 	  if (!strncmp (++cp,"Neutral ",8))
5147 	    sscanf (cp+8, "%f %f %f", cam_mul, cam_mul+1, cam_mul+2);
5148 	free (cbuf);
5149 	break;
5150       case 50458:
5151 	if (!make[0]) strcpy (make, "Hasselblad");
5152 	break;
5153       case 50459:			/* Hasselblad tag */
5154 	i = order;
5155 	j = ftell(ifp);
5156 	c = tiff_nifds;
5157 	order = get2();
5158 	fseek (ifp, j+(get2(),get4()), SEEK_SET);
5159 	parse_tiff_ifd (j);
5160 	maximum = 0xffff;
5161 	tiff_nifds = c;
5162 	order = i;
5163 	break;
5164       case 50706:			/* DNGVersion */
5165 	FORC4 dng_version = (dng_version << 8) + fgetc(ifp);
5166 	if (!make[0]) strcpy (make, "DNG");
5167 	is_raw = 1;
5168 	break;
5169       case 50710:			/* CFAPlaneColor */
5170 	if (len > 4) len = 4;
5171 	colors = len;
5172 	fread (cfa_pc, 1, colors, ifp);
5173 guess_cfa_pc:
5174 	FORCC tab[cfa_pc[c]] = c;
5175 	cdesc[c] = 0;
5176 	for (i=16; i--; )
5177 	  filters = filters << 2 | tab[cfa_pat[i % plen]];
5178 	break;
5179       case 50711:			/* CFALayout */
5180 	if (get2() == 2) {
5181 	  fuji_width = 1;
5182 	  filters = 0x49494949;
5183 	}
5184 	break;
5185       case 291:
5186       case 50712:			/* LinearizationTable */
5187 	linear_table (len);
5188 	break;
5189       case 50713:			/* BlackLevelRepeatDim */
5190 	blrr = get2();
5191 	blrc = get2();
5192 	break;
5193       case 61450:
5194 	blrr = blrc = 2;
5195       case 50714:			/* BlackLevel */
5196 	black = getreal(type);
5197 	if (!filters || !~filters) break;
5198 	dblack[0] = black;
5199 	dblack[1] = (blrc == 2) ? getreal(type):dblack[0];
5200 	dblack[2] = (blrr == 2) ? getreal(type):dblack[0];
5201 	dblack[3] = (blrc == 2 && blrr == 2) ? getreal(type):dblack[1];
5202 	if (colors == 3)
5203 	  filters |= ((filters >> 2 & 0x22222222) |
5204 		      (filters << 2 & 0x88888888)) & filters << 1;
5205 	FORC4 cblack[filters >> (c << 1) & 3] = dblack[c];
5206 	black = 0;
5207 	break;
5208       case 50715:			/* BlackLevelDeltaH */
5209       case 50716:			/* BlackLevelDeltaV */
5210 	for (num=i=0; i < len; i++)
5211 	  num += getreal(type);
5212 	black += num/len + 0.5;
5213 	break;
5214       case 50717:			/* WhiteLevel */
5215 	maximum = getint(type);
5216 	break;
5217       case 50718:			/* DefaultScale */
5218 	pixel_aspect  = getreal(type);
5219 	pixel_aspect /= getreal(type);
5220 	break;
5221       case 50721:			/* ColorMatrix1 */
5222       case 50722:			/* ColorMatrix2 */
5223 	FORCC for (j=0; j < 3; j++)
5224 	  cm[c][j] = getreal(type);
5225 	use_cm = 1;
5226 	break;
5227       case 50723:			/* CameraCalibration1 */
5228       case 50724:			/* CameraCalibration2 */
5229 	for (i=0; i < colors; i++)
5230 	  FORCC cc[i][c] = getreal(type);
5231 	break;
5232       case 50727:			/* AnalogBalance */
5233 	FORCC ab[c] = getreal(type);
5234 	break;
5235       case 50728:			/* AsShotNeutral */
5236 	FORCC asn[c] = getreal(type);
5237 	break;
5238       case 50729:			/* AsShotWhiteXY */
5239 	xyz[0] = getreal(type);
5240 	xyz[1] = getreal(type);
5241 	xyz[2] = 1 - xyz[0] - xyz[1];
5242 	FORC3 xyz[c] /= d65_white[c];
5243 	break;
5244       case 50740:			/* DNGPrivateData */
5245 	if (dng_version) break;
5246 	parse_minolta (j = get4()+base);
5247 	fseek (ifp, j, SEEK_SET);
5248 	parse_tiff_ifd (base);
5249 	break;
5250       case 50752:
5251 	read_shorts (cr2_slice, 3);
5252 	break;
5253       case 50829:			/* ActiveArea */
5254 	top_margin = getint(type);
5255 	left_margin = getint(type);
5256 	height = getint(type) - top_margin;
5257 	width = getint(type) - left_margin;
5258 	break;
5259       case 64772:			/* Kodak P-series */
5260 	if (len < 13) break;
5261 	fseek (ifp, 16, SEEK_CUR);
5262 	data_offset = get4();
5263 	fseek (ifp, 28, SEEK_CUR);
5264 	data_offset += get4();
5265 	load_raw = &CLASS packed_load_raw;
5266 	break;
5267       case 65026:
5268 	if (type == 2) fgets (model2, 64, ifp);
5269     }
5270     fseek (ifp, save, SEEK_SET);
5271   }
5272   if (sony_length && (buf = (unsigned *) malloc(sony_length))) {
5273     fseek (ifp, sony_offset, SEEK_SET);
5274     fread (buf, sony_length, 1, ifp);
5275     sony_decrypt (buf, sony_length/4, 1, sony_key);
5276     sfp = ifp;
5277     if ((ifp = tmpfile())) {
5278       fwrite (buf, sony_length, 1, ifp);
5279       fseek (ifp, 0, SEEK_SET);
5280       parse_tiff_ifd (-sony_offset);
5281       fclose (ifp);
5282     }
5283     ifp = sfp;
5284     free (buf);
5285   }
5286   for (i=0; i < colors; i++)
5287     FORCC cc[i][c] *= ab[i];
5288   if (use_cm) {
5289     FORCC for (i=0; i < 3; i++)
5290       for (cam_xyz[c][i]=j=0; j < colors; j++)
5291 	cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i];
5292     cam_xyz_coeff (cam_xyz);
5293   }
5294   if (asn[0]) {
5295     cam_mul[3] = 0;
5296     FORCC cam_mul[c] = 1 / asn[c];
5297   }
5298   if (!use_cm)
5299     FORCC pre_mul[c] /= cc[c][c];
5300   return 0;
5301 }
5302 
parse_tiff(int base)5303 int CLASS parse_tiff (int base)
5304 {
5305   int doff;
5306 
5307   fseek (ifp, base, SEEK_SET);
5308   order = get2();
5309   if (order != 0x4949 && order != 0x4d4d) return 0;
5310   get2();
5311   while ((doff = get4())) {
5312     fseek (ifp, doff+base, SEEK_SET);
5313     if (parse_tiff_ifd (base)) break;
5314   }
5315   return 1;
5316 }
5317 
apply_tiff()5318 void CLASS apply_tiff()
5319 {
5320   int max_samp=0, raw=-1, thm=-1, i;
5321   struct jhead jh;
5322 
5323   thumb_misc = 16;
5324   if (thumb_offset) {
5325     fseek (ifp, thumb_offset, SEEK_SET);
5326     if (ljpeg_start (&jh, 1)) {
5327       thumb_misc   = jh.bits;
5328       thumb_width  = jh.wide;
5329       thumb_height = jh.high;
5330     }
5331   }
5332   for (i=0; i < tiff_nifds; i++) {
5333     if (max_samp < tiff_ifd[i].samples)
5334 	max_samp = tiff_ifd[i].samples;
5335     if (max_samp > 3) max_samp = 3;
5336     if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) &&
5337 	(tiff_ifd[i].width | tiff_ifd[i].height) < 0x10000 &&
5338 	tiff_ifd[i].width*tiff_ifd[i].height > raw_width*raw_height) {
5339       raw_width     = tiff_ifd[i].width;
5340       raw_height    = tiff_ifd[i].height;
5341       tiff_bps      = tiff_ifd[i].bps;
5342       tiff_compress = tiff_ifd[i].comp;
5343       data_offset   = tiff_ifd[i].offset;
5344       tiff_flip     = tiff_ifd[i].flip;
5345       tiff_samples  = tiff_ifd[i].samples;
5346       raw = i;
5347     }
5348   }
5349   for (i=tiff_nifds; i--; )
5350     if (tiff_ifd[i].flip) tiff_flip = tiff_ifd[i].flip;
5351   if (raw >= 0 && !load_raw)
5352     switch (tiff_compress) {
5353       case 0:  case 1:
5354 	switch (tiff_bps) {
5355 	  case  8: load_raw = &CLASS eight_bit_load_raw;	break;
5356 	  case 12: load_raw = &CLASS packed_load_raw;
5357 		   if (tiff_ifd[raw].phint == 2)
5358 		     load_flags = 6;
5359 		   if (strncmp(make,"PENTAX",6)) break;
5360 	  case 14:
5361 	  case 16: load_raw = &CLASS unpacked_load_raw;		break;
5362 	}
5363 	if (tiff_ifd[raw].bytes*5 == raw_width*raw_height*8) {
5364 	  tiff_bps = 12;
5365 	  load_raw = &CLASS packed_load_raw;
5366 	  load_flags = 17;
5367 	}
5368 	break;
5369       case 6:  case 7:  case 99:
5370 	load_raw = &CLASS lossless_jpeg_load_raw;		break;
5371       case 262:
5372 	load_raw = &CLASS kodak_262_load_raw;			break;
5373       case 32767:
5374 	if (tiff_ifd[raw].bytes == raw_width*raw_height) {
5375 	  tiff_bps = 12;
5376 	  load_raw = &CLASS sony_arw2_load_raw;			break;
5377 	}
5378 	if (tiff_ifd[raw].bytes*8 != raw_width*raw_height*tiff_bps) {
5379 	  raw_height += 8;
5380 	  load_raw = &CLASS sony_arw_load_raw;			break;
5381 	}
5382 	load_flags = 15;
5383       case 32769:
5384 	load_flags++;
5385       case 32770:
5386       case 32773:
5387 	load_raw = &CLASS packed_load_raw;			break;
5388       case 34713:
5389 	load_raw = &CLASS nikon_compressed_load_raw;		break;
5390       case 65535:
5391 	load_raw = &CLASS pentax_load_raw;			break;
5392       case 65000:
5393 	switch (tiff_ifd[raw].phint) {
5394 	  case 2: load_raw = &CLASS kodak_rgb_load_raw;   filters = 0;  break;
5395 	  case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0;  break;
5396 	  case 32803: load_raw = &CLASS kodak_65000_load_raw;
5397 	}
5398       case 32867: break;
5399       default: is_raw = 0;
5400     }
5401   if (!dng_version)
5402     if ( (tiff_samples == 3 && tiff_ifd[raw].bytes &&
5403 	  tiff_bps != 14 && tiff_bps != 2048)
5404       || (tiff_bps == 8 && !strstr(make,"KODAK") && !strstr(make,"Kodak") &&
5405 	  !strstr(model2,"DEBUG RAW")))
5406       is_raw = 0;
5407   for (i=0; i < tiff_nifds; i++)
5408     if (i != raw && tiff_ifd[i].samples == max_samp &&
5409 	tiff_ifd[i].width * tiff_ifd[i].height / SQR(tiff_ifd[i].bps+1) >
5410 	      thumb_width *       thumb_height / SQR(thumb_misc+1)) {
5411       thumb_width  = tiff_ifd[i].width;
5412       thumb_height = tiff_ifd[i].height;
5413       thumb_offset = tiff_ifd[i].offset;
5414       thumb_length = tiff_ifd[i].bytes;
5415       thumb_misc   = tiff_ifd[i].bps;
5416       thm = i;
5417     }
5418   if (thm >= 0) {
5419     thumb_misc |= tiff_ifd[thm].samples << 5;
5420     switch (tiff_ifd[thm].comp) {
5421       case 0:
5422 	write_thumb = &CLASS layer_thumb;
5423 	break;
5424       case 1:
5425 	if (tiff_ifd[thm].bps > 8)
5426 	  thumb_load_raw = &CLASS kodak_thumb_load_raw;
5427 	else
5428 	  write_thumb = &CLASS ppm_thumb;
5429 	break;
5430       case 65000:
5431 	thumb_load_raw = tiff_ifd[thm].phint == 6 ?
5432 		&CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw;
5433     }
5434   }
5435 }
5436 
parse_minolta(int base)5437 void CLASS parse_minolta (int base)
5438 {
5439   int save, tag, len, offset, high=0, wide=0, i, c;
5440   short sorder=order;
5441 
5442   fseek (ifp, base, SEEK_SET);
5443   if (fgetc(ifp) || fgetc(ifp)-'M' || fgetc(ifp)-'R') return;
5444   order = fgetc(ifp) * 0x101;
5445   offset = base + get4() + 8;
5446   while ((save=ftell(ifp)) < offset) {
5447     for (tag=i=0; i < 4; i++)
5448       tag = tag << 8 | fgetc(ifp);
5449     len = get4();
5450     switch (tag) {
5451       case 0x505244:				/* PRD */
5452 	fseek (ifp, 8, SEEK_CUR);
5453 	high = get2();
5454 	wide = get2();
5455 	break;
5456       case 0x574247:				/* WBG */
5457 	get4();
5458 	i = strcmp(model,"DiMAGE A200") ? 0:3;
5459 	FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2();
5460 	break;
5461       case 0x545457:				/* TTW */
5462 	parse_tiff (ftell(ifp));
5463 	data_offset = offset;
5464     }
5465     fseek (ifp, save+len+8, SEEK_SET);
5466   }
5467   raw_height = high;
5468   raw_width  = wide;
5469   order = sorder;
5470 }
5471 
5472 /*
5473    Many cameras have a "debug mode" that writes JPEG and raw
5474    at the same time.  The raw file has no header, so try to
5475    to open the matching JPEG file and read its metadata.
5476  */
parse_external_jpeg()5477 void CLASS parse_external_jpeg()
5478 {
5479   const char *file, *ext;
5480   char *jname, *jfile, *jext;
5481   FILE *save=ifp;
5482 
5483   ext  = strrchr (ifname, '.');
5484   file = strrchr (ifname, '/');
5485   if (!file) file = strrchr (ifname, '\\');
5486   if (!file) file = ifname-1;
5487   file++;
5488   if (!ext || strlen(ext) != 4 || ext-file != 8) return;
5489   jname = (char *) malloc (strlen(ifname) + 1);
5490   merror (jname, "parse_external_jpeg()");
5491   strcpy (jname, ifname);
5492   jfile = file - ifname + jname;
5493   jext  = ext  - ifname + jname;
5494   if (strcasecmp (ext, ".jpg")) {
5495     strcpy (jext, isupper(ext[1]) ? ".JPG":".jpg");
5496     if (isdigit(*file)) {
5497       memcpy (jfile, file+4, 4);
5498       memcpy (jfile+4, file, 4);
5499     }
5500   } else
5501     while (isdigit(*--jext)) {
5502       if (*jext != '9') {
5503         (*jext)++;
5504 	break;
5505       }
5506       *jext = '0';
5507     }
5508   if (strcmp (jname, ifname)) {
5509     if ((ifp = fopen (jname, "rb"))) {
5510       if (verbose)
5511 	fprintf (stderr,_("Reading metadata from %s ...\n"), jname);
5512       parse_tiff (12);
5513       thumb_offset = 0;
5514       is_raw = 1;
5515       fclose (ifp);
5516     }
5517   }
5518   if (!timestamp)
5519     fprintf (stderr,_("Failed to read metadata from %s\n"), jname);
5520   free (jname);
5521   ifp = save;
5522 }
5523 
5524 /*
5525    CIFF block 0x1030 contains an 8x8 white sample.
5526    Load this into white[][] for use in scale_colors().
5527  */
ciff_block_1030()5528 void CLASS ciff_block_1030()
5529 {
5530   static const ushort key[] = { 0x410, 0x45f3 };
5531   int i, bpp, row, col, vbits=0;
5532   unsigned long bitbuf=0;
5533 
5534   if ((get2(),get4()) != 0x80008 || !get4()) return;
5535   bpp = get2();
5536   if (bpp != 10 && bpp != 12) return;
5537   for (i=row=0; row < 8; row++)
5538     for (col=0; col < 8; col++) {
5539       if (vbits < bpp) {
5540 	bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]);
5541 	vbits += 16;
5542       }
5543       white[row][col] =
5544 	bitbuf << (LONG_BIT - vbits) >> (LONG_BIT - bpp);
5545       vbits -= bpp;
5546     }
5547 }
5548 
5549 /*
5550    Parse a CIFF file, better known as Canon CRW format.
5551  */
parse_ciff(int offset,int length)5552 void CLASS parse_ciff (int offset, int length)
5553 {
5554   int tboff, nrecs, c, type, len, save, wbi=-1;
5555   ushort key[] = { 0x410, 0x45f3 };
5556 
5557   fseek (ifp, offset+length-4, SEEK_SET);
5558   tboff = get4() + offset;
5559   fseek (ifp, tboff, SEEK_SET);
5560   nrecs = get2();
5561   if (nrecs > 100) return;
5562   while (nrecs--) {
5563     type = get2();
5564     len  = get4();
5565     save = ftell(ifp) + 4;
5566     fseek (ifp, offset+get4(), SEEK_SET);
5567     if ((((type >> 8) + 8) | 8) == 0x38)
5568       parse_ciff (ftell(ifp), len);	/* Parse a sub-table */
5569 
5570     if (type == 0x0810)
5571       fread (artist, 64, 1, ifp);
5572     if (type == 0x080a) {
5573       fread (make, 64, 1, ifp);
5574       fseek (ifp, strlen(make) - 63, SEEK_CUR);
5575       fread (model, 64, 1, ifp);
5576     }
5577     if (type == 0x1810) {
5578       fseek (ifp, 12, SEEK_CUR);
5579       flip = get4();
5580     }
5581     if (type == 0x1835)			/* Get the decoder table */
5582       tiff_compress = get4();
5583     if (type == 0x2007) {
5584       thumb_offset = ftell(ifp);
5585       thumb_length = len;
5586     }
5587     if (type == 0x1818) {
5588       shutter = pow (2, -int_to_float((get4(),get4())));
5589       aperture = pow (2, int_to_float(get4())/2);
5590     }
5591     if (type == 0x102a) {
5592       iso_speed = pow (2, (get4(),get2())/32.0 - 4) * 50;
5593       aperture  = pow (2, (get2(),(short)get2())/64.0);
5594       shutter   = pow (2,-((short)get2())/32.0);
5595       wbi = (get2(),get2());
5596       if (wbi > 17) wbi = 0;
5597       fseek (ifp, 32, SEEK_CUR);
5598       if (shutter > 1e6) shutter = get2()/10.0;
5599     }
5600     if (type == 0x102c) {
5601       if (get2() > 512) {		/* Pro90, G1 */
5602 	fseek (ifp, 118, SEEK_CUR);
5603 	FORC4 cam_mul[c ^ 2] = get2();
5604       } else {				/* G2, S30, S40 */
5605 	fseek (ifp, 98, SEEK_CUR);
5606 	FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2();
5607       }
5608     }
5609     if (type == 0x0032) {
5610       if (len == 768) {			/* EOS D30 */
5611 	fseek (ifp, 72, SEEK_CUR);
5612 	FORC4 cam_mul[c ^ (c >> 1)] = 1024.0 / get2();
5613 	if (!wbi) cam_mul[0] = -1;	/* use my auto white balance */
5614       } else if (!cam_mul[0]) {
5615 	if (get2() == key[0])		/* Pro1, G6, S60, S70 */
5616 	  c = (strstr(model,"Pro1") ?
5617 	      "012346000000000000":"01345:000000006008")[wbi]-'0'+ 2;
5618 	else {				/* G3, G5, S45, S50 */
5619 	  c = "023457000000006000"[wbi]-'0';
5620 	  key[0] = key[1] = 0;
5621 	}
5622 	fseek (ifp, 78 + c*8, SEEK_CUR);
5623 	FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1];
5624 	if (!wbi) cam_mul[0] = -1;
5625       }
5626     }
5627     if (type == 0x10a9) {		/* D60, 10D, 300D, and clones */
5628       if (len > 66) wbi = "0134567028"[wbi]-'0';
5629       fseek (ifp, 2 + wbi*8, SEEK_CUR);
5630       FORC4 cam_mul[c ^ (c >> 1)] = get2();
5631     }
5632     if (type == 0x1030 && (0x18040 >> wbi & 1))
5633       ciff_block_1030();		/* all that don't have 0x10a9 */
5634     if (type == 0x1031) {
5635       raw_width = (get2(),get2());
5636       raw_height = get2();
5637     }
5638     if (type == 0x5029) {
5639       focal_len = len >> 16;
5640       if ((len & 0xffff) == 2) focal_len /= 32;
5641     }
5642     if (type == 0x5813) flash_used = int_to_float(len);
5643     if (type == 0x5814) canon_ev   = int_to_float(len);
5644     if (type == 0x5817) shot_order = len;
5645     if (type == 0x5834) unique_id  = len;
5646     if (type == 0x580e) timestamp  = len;
5647     if (type == 0x180e) timestamp  = get4();
5648 #ifdef LOCALTIME
5649     if ((type | 0x4000) == 0x580e)
5650       timestamp = mktime (gmtime (&timestamp));
5651 #endif
5652     fseek (ifp, save, SEEK_SET);
5653   }
5654 }
5655 
parse_rollei()5656 void CLASS parse_rollei()
5657 {
5658   char line[128], *val;
5659   struct tm t;
5660 
5661   fseek (ifp, 0, SEEK_SET);
5662   memset (&t, 0, sizeof t);
5663   do {
5664     fgets (line, 128, ifp);
5665     if ((val = strchr(line,'=')))
5666       *val++ = 0;
5667     else
5668       val = line + strlen(line);
5669     if (!strcmp(line,"DAT"))
5670       sscanf (val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year);
5671     if (!strcmp(line,"TIM"))
5672       sscanf (val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec);
5673     if (!strcmp(line,"HDR"))
5674       thumb_offset = atoi(val);
5675     if (!strcmp(line,"X  "))
5676       raw_width = atoi(val);
5677     if (!strcmp(line,"Y  "))
5678       raw_height = atoi(val);
5679     if (!strcmp(line,"TX "))
5680       thumb_width = atoi(val);
5681     if (!strcmp(line,"TY "))
5682       thumb_height = atoi(val);
5683   } while (strncmp(line,"EOHD",4));
5684   data_offset = thumb_offset + thumb_width * thumb_height * 2;
5685   t.tm_year -= 1900;
5686   t.tm_mon -= 1;
5687   if (mktime(&t) > 0)
5688     timestamp = mktime(&t);
5689   strcpy (make, "Rollei");
5690   strcpy (model,"d530flex");
5691   write_thumb = &CLASS rollei_thumb;
5692 }
5693 
parse_sinar_ia()5694 void CLASS parse_sinar_ia()
5695 {
5696   int entries, off;
5697   char str[8], *cp;
5698 
5699   order = 0x4949;
5700   fseek (ifp, 4, SEEK_SET);
5701   entries = get4();
5702   fseek (ifp, get4(), SEEK_SET);
5703   while (entries--) {
5704     off = get4(); get4();
5705     fread (str, 8, 1, ifp);
5706     if (!strcmp(str,"META"))   meta_offset = off;
5707     if (!strcmp(str,"THUMB")) thumb_offset = off;
5708     if (!strcmp(str,"RAW0"))   data_offset = off;
5709   }
5710   fseek (ifp, meta_offset+20, SEEK_SET);
5711   fread (make, 64, 1, ifp);
5712   make[63] = 0;
5713   if ((cp = strchr(make,' '))) {
5714     strcpy (model, cp+1);
5715     *cp = 0;
5716   }
5717   raw_width  = get2();
5718   raw_height = get2();
5719   load_raw = &CLASS unpacked_load_raw;
5720   thumb_width = (get4(),get2());
5721   thumb_height = get2();
5722   write_thumb = &CLASS ppm_thumb;
5723   maximum = 0x3fff;
5724 }
5725 
parse_phase_one(int base)5726 void CLASS parse_phase_one (int base)
5727 {
5728   unsigned entries, tag, type, len, data, save, i, c;
5729   float romm_cam[3][3];
5730   char *cp;
5731 
5732   memset (&ph1, 0, sizeof ph1);
5733   fseek (ifp, base, SEEK_SET);
5734   order = get4() & 0xffff;
5735   if (get4() >> 8 != 0x526177) return;		/* "Raw" */
5736   fseek (ifp, get4()+base, SEEK_SET);
5737   entries = get4();
5738   get4();
5739   while (entries--) {
5740     tag  = get4();
5741     type = get4();
5742     len  = get4();
5743     data = get4();
5744     save = ftell(ifp);
5745     fseek (ifp, base+data, SEEK_SET);
5746     switch (tag) {
5747       case 0x100:  flip = "0653"[data & 3]-'0';  break;
5748       case 0x106:
5749 	for (i=0; i < 9; i++)
5750 	  romm_cam[0][i] = getreal(11);
5751 	romm_coeff (romm_cam);
5752 	break;
5753       case 0x107:
5754 	FORC3 cam_mul[c] = getreal(11);
5755 	break;
5756       case 0x108:  raw_width     = data;	break;
5757       case 0x109:  raw_height    = data;	break;
5758       case 0x10a:  left_margin   = data;	break;
5759       case 0x10b:  top_margin    = data;	break;
5760       case 0x10c:  width         = data;	break;
5761       case 0x10d:  height        = data;	break;
5762       case 0x10e:  ph1.format    = data;	break;
5763       case 0x10f:  data_offset   = data+base;	break;
5764       case 0x110:  meta_offset   = data+base;
5765 		   meta_length   = len;			break;
5766       case 0x112:  ph1.key_off   = save - 4;		break;
5767       case 0x210:  ph1.tag_210   = int_to_float(data);	break;
5768       case 0x21a:  ph1.tag_21a   = data;		break;
5769       case 0x21c:  strip_offset  = data+base;		break;
5770       case 0x21d:  ph1.black     = data;		break;
5771       case 0x222:  ph1.split_col = data - left_margin;	break;
5772       case 0x223:  ph1.black_off = data+base;		break;
5773       case 0x301:
5774 	model[63] = 0;
5775 	fread (model, 1, 63, ifp);
5776 	if ((cp = strstr(model," camera"))) *cp = 0;
5777     }
5778     fseek (ifp, save, SEEK_SET);
5779   }
5780   load_raw = ph1.format < 3 ?
5781 	&CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c;
5782   maximum = 0xffff;
5783   strcpy (make, "Phase One");
5784   if (model[0]) return;
5785   switch (raw_height) {
5786     case 2060: strcpy (model,"LightPhase");	break;
5787     case 2682: strcpy (model,"H 10");		break;
5788     case 4128: strcpy (model,"H 20");		break;
5789     case 5488: strcpy (model,"H 25");		break;
5790   }
5791 }
5792 
parse_fuji(int offset)5793 void CLASS parse_fuji (int offset)
5794 {
5795   unsigned entries, tag, len, save, c;
5796 
5797   fseek (ifp, offset, SEEK_SET);
5798   entries = get4();
5799   if (entries > 255) return;
5800   while (entries--) {
5801     tag = get2();
5802     len = get2();
5803     save = ftell(ifp);
5804     if (tag == 0x100) {
5805       raw_height = get2();
5806       raw_width  = get2();
5807     } else if (tag == 0x121) {
5808       height = get2();
5809       if ((width = get2()) == 4284) width += 3;
5810     } else if (tag == 0x130) {
5811       fuji_layout = fgetc(ifp) >> 7;
5812       load_raw = fgetc(ifp) & 8 ?
5813 	&CLASS unpacked_load_raw : &CLASS fuji_load_raw;
5814     }
5815     if (tag == 0x2ff0)
5816       FORC4 cam_mul[c ^ 1] = get2();
5817     fseek (ifp, save+len, SEEK_SET);
5818   }
5819   if (!raw_height) {
5820     filters = 0x16161616;
5821     load_raw = &CLASS packed_load_raw;
5822     load_flags = 24;
5823   }
5824   height <<= fuji_layout;
5825   width  >>= fuji_layout;
5826 }
5827 
parse_jpeg(int offset)5828 int CLASS parse_jpeg (int offset)
5829 {
5830   int len, save, hlen, mark;
5831 
5832   fseek (ifp, offset, SEEK_SET);
5833   if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0;
5834 
5835   while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) {
5836     order = 0x4d4d;
5837     len   = get2() - 2;
5838     save  = ftell(ifp);
5839     if (mark == 0xc0 || mark == 0xc3) {
5840       fgetc(ifp);
5841       raw_height = get2();
5842       raw_width  = get2();
5843     }
5844     order = get2();
5845     hlen  = get4();
5846     if (get4() == 0x48454150)		/* "HEAP" */
5847       parse_ciff (save+hlen, len-hlen);
5848     if (parse_tiff (save+6)) apply_tiff();
5849     fseek (ifp, save+len, SEEK_SET);
5850   }
5851   return 1;
5852 }
5853 
parse_riff()5854 void CLASS parse_riff()
5855 {
5856   unsigned i, size, end;
5857   char tag[4], date[64], month[64];
5858   static const char mon[12][4] =
5859   { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" };
5860   struct tm t;
5861 
5862   order = 0x4949;
5863   fread (tag, 4, 1, ifp);
5864   size = get4();
5865   end = ftell(ifp) + size;
5866   if (!memcmp(tag,"RIFF",4) || !memcmp(tag,"LIST",4)) {
5867     get4();
5868     while (ftell(ifp)+7 < end)
5869       parse_riff();
5870   } else if (!memcmp(tag,"nctg",4)) {
5871     while (ftell(ifp)+7 < end) {
5872       i = get2();
5873       size = get2();
5874       if ((i+1) >> 1 == 10 && size == 20)
5875 	get_timestamp(0);
5876       else fseek (ifp, size, SEEK_CUR);
5877     }
5878   } else if (!memcmp(tag,"IDIT",4) && size < 64) {
5879     fread (date, 64, 1, ifp);
5880     date[size] = 0;
5881     memset (&t, 0, sizeof t);
5882     if (sscanf (date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday,
5883 	&t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) {
5884       for (i=0; i < 12 && strcasecmp(mon[i],month); i++);
5885       t.tm_mon = i;
5886       t.tm_year -= 1900;
5887       if (mktime(&t) > 0)
5888 	timestamp = mktime(&t);
5889     }
5890   } else
5891     fseek (ifp, size, SEEK_CUR);
5892 }
5893 
parse_smal(int offset,int fsize)5894 void CLASS parse_smal (int offset, int fsize)
5895 {
5896   int ver;
5897 
5898   fseek (ifp, offset+2, SEEK_SET);
5899   order = 0x4949;
5900   ver = fgetc(ifp);
5901   if (ver == 6)
5902     fseek (ifp, 5, SEEK_CUR);
5903   if (get4() != fsize) return;
5904   if (ver > 6) data_offset = get4();
5905   raw_height = height = get2();
5906   raw_width  = width  = get2();
5907   strcpy (make, "SMaL");
5908   sprintf (model, "v%d %dx%d", ver, width, height);
5909   if (ver == 6) load_raw = &CLASS smal_v6_load_raw;
5910   if (ver == 9) load_raw = &CLASS smal_v9_load_raw;
5911 }
5912 
parse_cine()5913 void CLASS parse_cine()
5914 {
5915   unsigned off_head, off_setup, off_image, i;
5916 
5917   order = 0x4949;
5918   fseek (ifp, 4, SEEK_SET);
5919   is_raw = get2() == 2;
5920   fseek (ifp, 14, SEEK_CUR);
5921   is_raw *= get4();
5922   off_head = get4();
5923   off_setup = get4();
5924   off_image = get4();
5925   timestamp = get4();
5926   if ((i = get4())) timestamp = i;
5927   fseek (ifp, off_head+4, SEEK_SET);
5928   raw_width = get4();
5929   raw_height = get4();
5930   switch (get2(),get2()) {
5931     case  8:  load_raw = &CLASS eight_bit_load_raw;  break;
5932     case 16:  load_raw = &CLASS  unpacked_load_raw;
5933   }
5934   fseek (ifp, off_setup+792, SEEK_SET);
5935   strcpy (make, "CINE");
5936   sprintf (model, "%d", get4());
5937   fseek (ifp, 12, SEEK_CUR);
5938   switch ((i=get4()) & 0xffffff) {
5939     case  3:  filters = 0x94949494;  break;
5940     case  4:  filters = 0x49494949;  break;
5941     default:  is_raw = 0;
5942   }
5943   fseek (ifp, 72, SEEK_CUR);
5944   switch ((get4()+3600) % 360) {
5945     case 270:  flip = 4;  break;
5946     case 180:  flip = 1;  break;
5947     case  90:  flip = 7;  break;
5948     case   0:  flip = 2;
5949   }
5950   cam_mul[0] = getreal(11);
5951   cam_mul[2] = getreal(11);
5952   maximum = ~(-1 << get4());
5953   fseek (ifp, 668, SEEK_CUR);
5954   shutter = get4()/1000000000.0;
5955   fseek (ifp, off_image, SEEK_SET);
5956   if (shot_select < is_raw)
5957     fseek (ifp, shot_select*8, SEEK_CUR);
5958   data_offset  = (INT64) get4() + 8;
5959   data_offset += (INT64) get4() << 32;
5960 }
5961 
foveon_gets(int offset,char * str,int len)5962 char * CLASS foveon_gets (int offset, char *str, int len)
5963 {
5964   int i;
5965   fseek (ifp, offset, SEEK_SET);
5966   for (i=0; i < len-1; i++)
5967     if ((str[i] = get2()) == 0) break;
5968   str[i] = 0;
5969   return str;
5970 }
5971 
parse_foveon()5972 void CLASS parse_foveon()
5973 {
5974   int entries, img=0, off, len, tag, save, i, wide, high, pent, poff[256][2];
5975   char name[64], value[64];
5976 
5977   order = 0x4949;			/* Little-endian */
5978   fseek (ifp, 36, SEEK_SET);
5979   flip = get4();
5980   fseek (ifp, -4, SEEK_END);
5981   fseek (ifp, get4(), SEEK_SET);
5982   if (get4() != 0x64434553) return;	/* SECd */
5983   entries = (get4(),get4());
5984   while (entries--) {
5985     off = get4();
5986     len = get4();
5987     tag = get4();
5988     save = ftell(ifp);
5989     fseek (ifp, off, SEEK_SET);
5990     if (get4() != (0x20434553 | (tag << 24))) return;
5991     switch (tag) {
5992       case 0x47414d49:			/* IMAG */
5993       case 0x32414d49:			/* IMA2 */
5994 	fseek (ifp, 12, SEEK_CUR);
5995 	wide = get4();
5996 	high = get4();
5997 	if (wide > raw_width && high > raw_height) {
5998 	  raw_width  = wide;
5999 	  raw_height = high;
6000 	  data_offset = off+24;
6001 	}
6002 	fseek (ifp, off+28, SEEK_SET);
6003 	if (fgetc(ifp) == 0xff && fgetc(ifp) == 0xd8
6004 		&& thumb_length < len-28) {
6005 	  thumb_offset = off+28;
6006 	  thumb_length = len-28;
6007 	  write_thumb = &CLASS jpeg_thumb;
6008 	}
6009 	if (++img == 2 && !thumb_length) {
6010 	  thumb_offset = off+24;
6011 	  thumb_width = wide;
6012 	  thumb_height = high;
6013 	  write_thumb = &CLASS foveon_thumb;
6014 	}
6015 	break;
6016       case 0x464d4143:			/* CAMF */
6017 	meta_offset = off+24;
6018 	meta_length = len-28;
6019 	if (meta_length > 0x20000)
6020 	    meta_length = 0x20000;
6021 	break;
6022       case 0x504f5250:			/* PROP */
6023 	pent = (get4(),get4());
6024 	fseek (ifp, 12, SEEK_CUR);
6025 	off += pent*8 + 24;
6026 	if ((unsigned) pent > 256) pent=256;
6027 	for (i=0; i < pent*2; i++)
6028 	  poff[0][i] = off + get4()*2;
6029 	for (i=0; i < pent; i++) {
6030 	  foveon_gets (poff[i][0], name, 64);
6031 	  foveon_gets (poff[i][1], value, 64);
6032 	  if (!strcmp (name, "ISO"))
6033 	    iso_speed = atoi(value);
6034 	  if (!strcmp (name, "CAMMANUF"))
6035 	    strcpy (make, value);
6036 	  if (!strcmp (name, "CAMMODEL"))
6037 	    strcpy (model, value);
6038 	  if (!strcmp (name, "WB_DESC"))
6039 	    strcpy (model2, value);
6040 	  if (!strcmp (name, "TIME"))
6041 	    timestamp = atoi(value);
6042 	  if (!strcmp (name, "EXPTIME"))
6043 	    shutter = atoi(value) / 1000000.0;
6044 	  if (!strcmp (name, "APERTURE"))
6045 	    aperture = atof(value);
6046 	  if (!strcmp (name, "FLENGTH"))
6047 	    focal_len = atof(value);
6048 	}
6049 #ifdef LOCALTIME
6050 	timestamp = mktime (gmtime (&timestamp));
6051 #endif
6052     }
6053     fseek (ifp, save, SEEK_SET);
6054   }
6055   is_foveon = 1;
6056 }
6057 
6058 /*
6059    All matrices are from Adobe DNG Converter unless otherwise noted.
6060  */
adobe_coeff(const char * make,const char * model)6061 void CLASS adobe_coeff (const char *make, const char *model)
6062 {
6063   static const struct {
6064     const char *prefix;
6065     short black, maximum, trans[12];
6066   } table[] = {
6067     { "AGFAPHOTO DC-833m", 0, 0,	/* DJC */
6068 	{ 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } },
6069     { "Apple QuickTake", 0, 0,		/* DJC */
6070 	{ 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } },
6071     { "Canon EOS D2000", 0, 0,
6072 	{ 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } },
6073     { "Canon EOS D6000", 0, 0,
6074 	{ 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } },
6075     { "Canon EOS D30", 0, 0,
6076 	{ 9805,-2689,-1312,-5803,13064,3068,-2438,3075,8775 } },
6077     { "Canon EOS D60", 0, 0xfa0,
6078 	{ 6188,-1341,-890,-7168,14489,2937,-2640,3228,8483 } },
6079     { "Canon EOS 5D Mark II", 0, 0x3cf0,
6080 	{ 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } },
6081     { "Canon EOS 5D", 0, 0xe6c,
6082 	{ 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } },
6083     { "Canon EOS 7D", 0, 0x3510,
6084 	{ 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } },
6085     { "Canon EOS 10D", 0, 0xfa0,
6086 	{ 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } },
6087     { "Canon EOS 20Da", 0, 0,
6088 	{ 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } },
6089     { "Canon EOS 20D", 0, 0xfff,
6090 	{ 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } },
6091     { "Canon EOS 30D", 0, 0,
6092 	{ 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } },
6093     { "Canon EOS 40D", 0, 0x3f60,
6094 	{ 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } },
6095     { "Canon EOS 50D", 0, 0x3d93,
6096 	{ 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } },
6097     { "Canon EOS 60D", 0, 0x2ff7,
6098 	{ 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } },
6099     { "Canon EOS 300D", 0, 0xfa0,
6100 	{ 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } },
6101     { "Canon EOS 350D", 0, 0xfff,
6102 	{ 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } },
6103     { "Canon EOS 400D", 0, 0xe8e,
6104 	{ 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } },
6105     { "Canon EOS 450D", 0, 0x390d,
6106 	{ 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } },
6107     { "Canon EOS 500D", 0, 0x3479,
6108 	{ 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } },
6109     { "Canon EOS 550D", 0, 0x3dd7,
6110 	{ 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } },
6111     { "Canon EOS 1000D", 0, 0xe43,
6112 	{ 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } },
6113     { "Canon EOS-1Ds Mark III", 0, 0x3bb0,
6114 	{ 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } },
6115     { "Canon EOS-1Ds Mark II", 0, 0xe80,
6116 	{ 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } },
6117     { "Canon EOS-1D Mark IV", 0, 0x3bb0,
6118 	{ 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } },
6119     { "Canon EOS-1D Mark III", 0, 0x3bb0,
6120 	{ 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } },
6121     { "Canon EOS-1D Mark II N", 0, 0xe80,
6122 	{ 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } },
6123     { "Canon EOS-1D Mark II", 0, 0xe80,
6124 	{ 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } },
6125     { "Canon EOS-1DS", 0, 0xe20,
6126 	{ 4374,3631,-1743,-7520,15212,2472,-2892,3632,8161 } },
6127     { "Canon EOS-1D", 0, 0xe20,
6128 	{ 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } },
6129     { "Canon EOS", 0, 0,
6130 	{ 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } },
6131     { "Canon PowerShot A530", 0, 0,
6132 	{ 0 } },	/* don't want the A5 matrix */
6133     { "Canon PowerShot A50", 0, 0,
6134 	{ -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } },
6135     { "Canon PowerShot A5", 0, 0,
6136 	{ -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } },
6137     { "Canon PowerShot G10", 0, 0,
6138 	{ 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } },
6139     { "Canon PowerShot G11", 0, 0,
6140 	{ 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } },
6141     { "Canon PowerShot G12", 0, 0,
6142 	{ 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } },
6143     { "Canon PowerShot G1", 0, 0,
6144 	{ -4778,9467,2172,4743,-1141,4344,-5146,9908,6077,-1566,11051,557 } },
6145     { "Canon PowerShot G2", 0, 0,
6146 	{ 9087,-2693,-1049,-6715,14382,2537,-2291,2819,7790 } },
6147     { "Canon PowerShot G3", 0, 0,
6148 	{ 9212,-2781,-1073,-6573,14189,2605,-2300,2844,7664 } },
6149     { "Canon PowerShot G5", 0, 0,
6150 	{ 9757,-2872,-933,-5972,13861,2301,-1622,2328,7212 } },
6151     { "Canon PowerShot G6", 0, 0,
6152 	{ 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } },
6153     { "Canon PowerShot G9", 0, 0,
6154 	{ 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } },
6155     { "Canon PowerShot Pro1", 0, 0,
6156 	{ 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } },
6157     { "Canon PowerShot Pro70", 34, 0,
6158 	{ -4155,9818,1529,3939,-25,4522,-5521,9870,6610,-2238,10873,1342 } },
6159     { "Canon PowerShot Pro90", 0, 0,
6160 	{ -4963,9896,2235,4642,-987,4294,-5162,10011,5859,-1770,11230,577 } },
6161     { "Canon PowerShot S30", 0, 0,
6162 	{ 10566,-3652,-1129,-6552,14662,2006,-2197,2581,7670 } },
6163     { "Canon PowerShot S40", 0, 0,
6164 	{ 8510,-2487,-940,-6869,14231,2900,-2318,2829,9013 } },
6165     { "Canon PowerShot S45", 0, 0,
6166 	{ 8163,-2333,-955,-6682,14174,2751,-2077,2597,8041 } },
6167     { "Canon PowerShot S50", 0, 0,
6168 	{ 8882,-2571,-863,-6348,14234,2288,-1516,2172,6569 } },
6169     { "Canon PowerShot S60", 0, 0,
6170 	{ 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } },
6171     { "Canon PowerShot S70", 0, 0,
6172 	{ 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } },
6173     { "Canon PowerShot S90", 0, 0,
6174 	{ 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } },
6175     { "Canon PowerShot S95", 0, 0,
6176 	{ 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } },
6177     { "Canon PowerShot A470", 0, 0,	/* DJC */
6178 	{ 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } },
6179     { "Canon PowerShot A610", 0, 0,	/* DJC */
6180 	{ 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } },
6181     { "Canon PowerShot A620", 0, 0,	/* DJC */
6182 	{ 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } },
6183     { "Canon PowerShot A630", 0, 0,	/* DJC */
6184 	{ 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } },
6185     { "Canon PowerShot A640", 0, 0,	/* DJC */
6186 	{ 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } },
6187     { "Canon PowerShot A650", 0, 0,	/* DJC */
6188 	{ 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } },
6189     { "Canon PowerShot A720", 0, 0,	/* DJC */
6190 	{ 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } },
6191     { "Canon PowerShot S3 IS", 0, 0,	/* DJC */
6192 	{ 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } },
6193     { "Canon PowerShot SX1 IS", 0, 0,
6194 	{ 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } },
6195     { "Canon PowerShot SX110 IS", 0, 0,	/* DJC */
6196         { 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } },
6197     { "CASIO EX-S20", 0, 0,		/* DJC */
6198 	{ 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } },
6199     { "CASIO EX-Z750", 0, 0,		/* DJC */
6200 	{ 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } },
6201     { "CASIO EX-Z10", 128, 0xfff,	/* DJC */
6202 	{ 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } },
6203     { "CINE 650", 0, 0,
6204 	{ 3390,480,-500,-800,3610,340,-550,2336,1192 } },
6205     { "CINE 660", 0, 0,
6206 	{ 3390,480,-500,-800,3610,340,-550,2336,1192 } },
6207     { "CINE", 0, 0,
6208 	{ 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } },
6209     { "Contax N Digital", 0, 0xf1e,
6210 	{ 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } },
6211     { "EPSON R-D1", 0, 0,
6212 	{ 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } },
6213     { "FUJIFILM FinePix E550", 0, 0,
6214 	{ 11044,-3888,-1120,-7248,15168,2208,-1531,2277,8069 } },
6215     { "FUJIFILM FinePix E900", 0, 0,
6216 	{ 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } },
6217     { "FUJIFILM FinePix F8", 0, 0,
6218 	{ 11044,-3888,-1120,-7248,15168,2208,-1531,2277,8069 } },
6219     { "FUJIFILM FinePix F7", 0, 0,
6220 	{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
6221     { "FUJIFILM FinePix S100FS", 514, 0,
6222 	{ 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } },
6223     { "FUJIFILM FinePix S200EXR", 512, 0x3fff,
6224 	{ 0 } },
6225     { "FUJIFILM FinePix S20Pro", 0, 0,
6226 	{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
6227     { "FUJIFILM FinePix S2Pro", 128, 0,
6228 	{ 12492,-4690,-1402,-7033,15423,1647,-1507,2111,7697 } },
6229     { "FUJIFILM FinePix S3Pro", 0, 0,
6230 	{ 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } },
6231     { "FUJIFILM FinePix S5Pro", 0, 0,
6232 	{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
6233     { "FUJIFILM FinePix S5000", 0, 0,
6234 	{ 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } },
6235     { "FUJIFILM FinePix S5100", 0, 0,
6236 	{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
6237     { "FUJIFILM FinePix S5500", 0, 0,
6238 	{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
6239     { "FUJIFILM FinePix S5200", 0, 0,
6240 	{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
6241     { "FUJIFILM FinePix S5600", 0, 0,
6242 	{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
6243     { "FUJIFILM FinePix S6", 0, 0,
6244 	{ 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } },
6245     { "FUJIFILM FinePix S7000", 0, 0,
6246 	{ 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } },
6247     { "FUJIFILM FinePix S9000", 0, 0,
6248 	{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
6249     { "FUJIFILM FinePix S9500", 0, 0,
6250 	{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
6251     { "FUJIFILM FinePix S9100", 0, 0,
6252 	{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
6253     { "FUJIFILM FinePix S9600", 0, 0,
6254 	{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
6255     { "FUJIFILM IS-1", 0, 0,
6256 	{ 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } },
6257     { "FUJIFILM IS Pro", 0, 0,
6258 	{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
6259     { "FUJIFILM FinePix HS10 HS11", 0, 0xf68,
6260 	{ 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } },
6261     { "Imacon Ixpress", 0, 0,		/* DJC */
6262 	{ 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } },
6263     { "KODAK NC2000", 0, 0,
6264 	{ 13891,-6055,-803,-465,9919,642,2121,82,1291 } },
6265     { "Kodak DCS315C", 8, 0,
6266 	{ 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } },
6267     { "Kodak DCS330C", 8, 0,
6268 	{ 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } },
6269     { "KODAK DCS420", 0, 0,
6270 	{ 10868,-1852,-644,-1537,11083,484,2343,628,2216 } },
6271     { "KODAK DCS460", 0, 0,
6272 	{ 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
6273     { "KODAK EOSDCS1", 0, 0,
6274 	{ 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
6275     { "KODAK EOSDCS3B", 0, 0,
6276 	{ 9898,-2700,-940,-2478,12219,206,1985,634,1031 } },
6277     { "Kodak DCS520C", 180, 0,
6278 	{ 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } },
6279     { "Kodak DCS560C", 188, 0,
6280 	{ 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } },
6281     { "Kodak DCS620C", 180, 0,
6282 	{ 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } },
6283     { "Kodak DCS620X", 185, 0,
6284 	{ 13095,-6231,154,12221,-21,-2137,895,4602,2258 } },
6285     { "Kodak DCS660C", 214, 0,
6286 	{ 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } },
6287     { "Kodak DCS720X", 0, 0,
6288 	{ 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } },
6289     { "Kodak DCS760C", 0, 0,
6290 	{ 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } },
6291     { "Kodak DCS Pro SLR", 0, 0,
6292 	{ 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
6293     { "Kodak DCS Pro 14nx", 0, 0,
6294 	{ 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
6295     { "Kodak DCS Pro 14", 0, 0,
6296 	{ 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } },
6297     { "Kodak ProBack645", 0, 0,
6298 	{ 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } },
6299     { "Kodak ProBack", 0, 0,
6300 	{ 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } },
6301     { "KODAK P712", 0, 0,
6302 	{ 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } },
6303     { "KODAK P850", 0, 0xf7c,
6304 	{ 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } },
6305     { "KODAK P880", 0, 0xfff,
6306 	{ 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } },
6307     { "KODAK EasyShare Z980", 0, 0,
6308 	{ 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } },
6309     { "KODAK EasyShare Z981", 0, 0,
6310 	{ 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } },
6311     { "KODAK EASYSHARE Z1015", 0, 0xef1,
6312 	{ 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } },
6313     { "Leaf CMost", 0, 0,
6314 	{ 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
6315     { "Leaf Valeo 6", 0, 0,
6316 	{ 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
6317     { "Leaf Aptus 54S", 0, 0,
6318 	{ 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
6319     { "Leaf Aptus 65", 0, 0,
6320 	{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
6321     { "Leaf Aptus 75", 0, 0,
6322 	{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
6323     { "Leaf", 0, 0,
6324 	{ 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
6325     { "Mamiya ZD", 0, 0,
6326 	{ 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } },
6327     { "Micron 2010", 110, 0,		/* DJC */
6328 	{ 16695,-3761,-2151,155,9682,163,3433,951,4904 } },
6329     { "Minolta DiMAGE 5", 0, 0xf7d,
6330 	{ 8983,-2942,-963,-6556,14476,2237,-2426,2887,8014 } },
6331     { "Minolta DiMAGE 7Hi", 0, 0xf7d,
6332 	{ 11368,-3894,-1242,-6521,14358,2339,-2475,3056,7285 } },
6333     { "Minolta DiMAGE 7", 0, 0xf7d,
6334 	{ 9144,-2777,-998,-6676,14556,2281,-2470,3019,7744 } },
6335     { "Minolta DiMAGE A1", 0, 0xf8b,
6336 	{ 9274,-2547,-1167,-8220,16323,1943,-2273,2720,8340 } },
6337     { "MINOLTA DiMAGE A200", 0, 0,
6338 	{ 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } },
6339     { "Minolta DiMAGE A2", 0, 0xf8f,
6340 	{ 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } },
6341     { "Minolta DiMAGE Z2", 0, 0,	/* DJC */
6342 	{ 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
6343     { "MINOLTA DYNAX 5", 0, 0xffb,
6344 	{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
6345     { "MINOLTA DYNAX 7", 0, 0xffb,
6346 	{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
6347     { "MOTOROLA PIXL", 0, 0,		/* DJC */
6348 	{ 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } },
6349     { "NIKON D100", 0, 0,
6350 	{ 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } },
6351     { "NIKON D1H", 0, 0,
6352 	{ 7577,-2166,-926,-7454,15592,1934,-2377,2808,8606 } },
6353     { "NIKON D1X", 0, 0,
6354 	{ 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } },
6355     { "NIKON D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */
6356 	{ 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } },
6357     { "NIKON D200", 0, 0xfbc,
6358 	{ 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } },
6359     { "NIKON D2H", 0, 0,
6360 	{ 5710,-901,-615,-8594,16617,2024,-2975,4120,6830 } },
6361     { "NIKON D2X", 0, 0,
6362 	{ 10231,-2769,-1255,-8301,15900,2552,-797,680,7148 } },
6363     { "NIKON D3000", 0, 0,
6364 	{ 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } },
6365     { "NIKON D3100", 0, 0,
6366 	{ 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } },
6367     { "NIKON D300", 0, 0,
6368 	{ 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } },
6369     { "NIKON D3X", 0, 0,
6370 	{ 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } },
6371     { "NIKON D3S", 0, 0,
6372 	{ 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } },
6373     { "NIKON D3", 0, 0,
6374 	{ 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } },
6375     { "NIKON D40X", 0, 0,
6376 	{ 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } },
6377     { "NIKON D40", 0, 0,
6378 	{ 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } },
6379     { "NIKON D5000", 0, 0xf00,
6380 	{ 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } },
6381     { "NIKON D50", 0, 0,
6382 	{ 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
6383     { "NIKON D60", 0, 0,
6384 	{ 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } },
6385     { "NIKON D7000", 0, 0,
6386 	{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
6387     { "NIKON D700", 0, 0,
6388 	{ 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } },
6389     { "NIKON D70", 0, 0,
6390 	{ 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
6391     { "NIKON D80", 0, 0,
6392 	{ 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } },
6393     { "NIKON D90", 0, 0xf00,
6394 	{ 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } },
6395     { "NIKON E950", 0, 0x3dd,		/* DJC */
6396 	{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
6397     { "NIKON E995", 0, 0,	/* copied from E5000 */
6398 	{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
6399     { "NIKON E2100", 0, 0,	/* copied from Z2, new white balance */
6400 	{ 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711} },
6401     { "NIKON E2500", 0, 0,
6402 	{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
6403     { "NIKON E3200", 0, 0,		/* DJC */
6404 	{ 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } },
6405     { "NIKON E4300", 0, 0,	/* copied from Minolta DiMAGE Z2 */
6406 	{ 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
6407     { "NIKON E4500", 0, 0,
6408 	{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
6409     { "NIKON E5000", 0, 0,
6410 	{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
6411     { "NIKON E5400", 0, 0,
6412 	{ 9349,-2987,-1001,-7919,15766,2266,-2098,2680,6839 } },
6413     { "NIKON E5700", 0, 0,
6414 	{ -5368,11478,2368,5537,-113,3148,-4969,10021,5782,778,9028,211 } },
6415     { "NIKON E8400", 0, 0,
6416 	{ 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } },
6417     { "NIKON E8700", 0, 0,
6418 	{ 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
6419     { "NIKON E8800", 0, 0,
6420 	{ 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } },
6421     { "NIKON COOLPIX P6000", 0, 0,
6422 	{ 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } },
6423     { "NIKON COOLPIX P7000", 0, 0,
6424 	{ 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } },
6425     { "OLYMPUS C5050", 0, 0,
6426 	{ 10508,-3124,-1273,-6079,14294,1901,-1653,2306,6237 } },
6427     { "OLYMPUS C5060", 0, 0,
6428 	{ 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } },
6429     { "OLYMPUS C7070", 0, 0,
6430 	{ 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } },
6431     { "OLYMPUS C70", 0, 0,
6432 	{ 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } },
6433     { "OLYMPUS C80", 0, 0,
6434 	{ 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } },
6435     { "OLYMPUS E-10", 0, 0xffc,
6436 	{ 12745,-4500,-1416,-6062,14542,1580,-1934,2256,6603 } },
6437     { "OLYMPUS E-1", 0, 0,
6438 	{ 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } },
6439     { "OLYMPUS E-20", 0, 0xffc,
6440 	{ 13173,-4732,-1499,-5807,14036,1895,-2045,2452,7142 } },
6441     { "OLYMPUS E-300", 0, 0,
6442 	{ 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } },
6443     { "OLYMPUS E-330", 0, 0,
6444 	{ 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } },
6445     { "OLYMPUS E-30", 0, 0xfbc,
6446 	{ 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } },
6447     { "OLYMPUS E-3", 0, 0xf99,
6448 	{ 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } },
6449     { "OLYMPUS E-400", 0, 0,
6450 	{ 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } },
6451     { "OLYMPUS E-410", 0, 0xf6a,
6452 	{ 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } },
6453     { "OLYMPUS E-420", 0, 0xfd7,
6454 	{ 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } },
6455     { "OLYMPUS E-450", 0, 0xfd2,
6456 	{ 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } },
6457     { "OLYMPUS E-500", 0, 0,
6458 	{ 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } },
6459     { "OLYMPUS E-510", 0, 0xf6a,
6460 	{ 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } },
6461     { "OLYMPUS E-520", 0, 0xfd2,
6462 	{ 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } },
6463     { "OLYMPUS E-5", 0, 0,
6464 	{ 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } },
6465     { "OLYMPUS E-600", 0, 0xfaf,
6466 	{ 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } },
6467     { "OLYMPUS E-620", 0, 0xfaf,
6468 	{ 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } },
6469     { "OLYMPUS E-P1", 0, 0xffd,
6470 	{ 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } },
6471     { "OLYMPUS E-P2", 0, 0xffd,
6472 	{ 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } },
6473     { "OLYMPUS E-PL1", 0, 0,
6474 	{ 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } },
6475     { "OLYMPUS SP350", 0, 0,
6476 	{ 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } },
6477     { "OLYMPUS SP3", 0, 0,
6478 	{ 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } },
6479     { "OLYMPUS SP500UZ", 0, 0xfff,
6480 	{ 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } },
6481     { "OLYMPUS SP510UZ", 0, 0xffe,
6482 	{ 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } },
6483     { "OLYMPUS SP550UZ", 0, 0xffe,
6484 	{ 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } },
6485     { "OLYMPUS SP560UZ", 0, 0xff9,
6486 	{ 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } },
6487     { "OLYMPUS SP570UZ", 0, 0,
6488 	{ 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } },
6489     { "PENTAX *ist DL2", 0, 0,
6490 	{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
6491     { "PENTAX *ist DL", 0, 0,
6492 	{ 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } },
6493     { "PENTAX *ist DS2", 0, 0,
6494 	{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
6495     { "PENTAX *ist DS", 0, 0,
6496 	{ 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } },
6497     { "PENTAX *ist D", 0, 0,
6498 	{ 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } },
6499     { "PENTAX K10D", 0, 0,
6500 	{ 9566,-2863,-803,-7170,15172,2112,-818,803,9705 } },
6501     { "PENTAX K1", 0, 0,
6502 	{ 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } },
6503     { "PENTAX K20D", 0, 0,
6504 	{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
6505     { "PENTAX K200D", 0, 0,
6506 	{ 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } },
6507     { "PENTAX K2000", 0, 0,
6508 	{ 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } },
6509     { "PENTAX K-m", 0, 0,
6510 	{ 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } },
6511     { "PENTAX K-x", 0, 0,
6512 	{ 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } },
6513     { "PENTAX K-r", 0, 0,
6514 	{ 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } },
6515     { "PENTAX K-5", 0, 0,
6516 	{ 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } },
6517     { "PENTAX K-7", 0, 0,
6518 	{ 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } },
6519     { "PENTAX 645D", 0, 0x3e00,
6520 	{ 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } },
6521     { "Panasonic DMC-FZ8", 0, 0xf7f,
6522 	{ 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } },
6523     { "Panasonic DMC-FZ18", 0, 0,
6524 	{ 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } },
6525     { "Panasonic DMC-FZ28", 15, 0xf96,
6526 	{ 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } },
6527     { "Panasonic DMC-FZ30", 0, 0xf94,
6528 	{ 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } },
6529     { "Panasonic DMC-FZ3", 143, 0,
6530 	{ 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } },
6531     { "Panasonic DMC-FZ40", 143, 0,
6532 	{ 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } },
6533     { "Panasonic DMC-FZ50", 0, 0,
6534 	{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
6535     { "LEICA V-LUX1", 0, 0,
6536 	{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
6537     { "Panasonic DMC-L10", 15, 0xf96,
6538 	{ 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } },
6539     { "Panasonic DMC-L1", 0, 0xf7f,
6540 	{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
6541     { "LEICA DIGILUX 3", 0, 0xf7f,
6542 	{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
6543     { "Panasonic DMC-LC1", 0, 0,
6544 	{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
6545     { "LEICA DIGILUX 2", 0, 0,
6546 	{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
6547     { "Panasonic DMC-LX1", 0, 0xf7f,
6548 	{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
6549     { "LEICA D-LUX2", 0, 0xf7f,
6550 	{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
6551     { "Panasonic DMC-LX2", 0, 0,
6552 	{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
6553     { "LEICA D-LUX3", 0, 0,
6554 	{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
6555     { "Panasonic DMC-LX3", 15, 0,
6556 	{ 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } },
6557     { "LEICA D-LUX4", 15, 0,
6558 	{ 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } },
6559     { "Panasonic DMC-LX5", 143, 0,
6560 	{ 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } },
6561     { "Panasonic DMC-FZ100", 143, 0xfff,
6562 	{ 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } },
6563     { "Panasonic DMC-FX150", 15, 0xfff,
6564 	{ 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } },
6565     { "Panasonic DMC-G10", 0, 0,
6566 	{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } },
6567     { "Panasonic DMC-G1", 15, 0xf94,
6568 	{ 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } },
6569     { "Panasonic DMC-G2", 15, 0xf3c,
6570 	{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } },
6571     { "Panasonic DMC-GF1", 15, 0xf92,
6572 	{ 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } },
6573     { "Panasonic DMC-GF2", 143, 0xfff,
6574 	{ 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } },
6575     { "Panasonic DMC-GH1", 15, 0xf92,
6576 	{ 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } },
6577     { "Panasonic DMC-GH2", 15, 0xf95,
6578 	{ 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } },
6579     { "Phase One H 20", 0, 0,		/* DJC */
6580 	{ 1313,1855,-109,-6715,15908,808,-327,1840,6020 } },
6581     { "Phase One P 2", 0, 0,
6582 	{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
6583     { "Phase One P 30", 0, 0,
6584 	{ 4516,-245,-37,-7020,14976,2173,-3206,4671,7087 } },
6585     { "Phase One P 45", 0, 0,
6586 	{ 5053,-24,-117,-5684,14076,1702,-2619,4492,5849 } },
6587     { "Phase One P65", 0, 0,
6588 	{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
6589     { "SAMSUNG EX1", 0, 0x3e00,
6590 	{ 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } },
6591     { "SAMSUNG NX10", 0, 0,
6592 	{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
6593     { "SAMSUNG WB2000", 0, 0xfff,
6594 	{ 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } },
6595     { "SAMSUNG GX-1", 0, 0,
6596 	{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
6597     { "SAMSUNG S85", 0, 0xffff,		/* DJC */
6598 	{ 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } },
6599     { "Sinar", 0, 0,			/* DJC */
6600 	{ 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } },
6601     { "SONY DSC-F828", 491, 0,
6602 	{ 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } },
6603     { "SONY DSC-R1", 512, 0,
6604 	{ 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } },
6605     { "SONY DSC-V3", 0, 0,
6606 	{ 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } },
6607     { "SONY DSLR-A100", 0, 0xfeb,
6608 	{ 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } },
6609     { "SONY DSLR-A2", 0, 0,
6610 	{ 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } },
6611     { "SONY DSLR-A300", 0, 0,
6612 	{ 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } },
6613     { "SONY DSLR-A330", 0, 0,
6614 	{ 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } },
6615     { "SONY DSLR-A350", 0, 0xffc,
6616 	{ 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } },
6617     { "SONY DSLR-A380", 0, 0,
6618 	{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
6619     { "SONY DSLR-A450", 128, 0xfeb,
6620 	{ 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } },
6621     { "SONY DSLR-A580", 128, 0xfeb,
6622 	{ 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } },
6623     { "SONY DSLR-A5", 128, 0xfeb,
6624 	{ 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } },
6625     { "SONY DSLR-A700", 126, 0,
6626 	{ 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } },
6627     { "SONY DSLR-A850", 128, 0,
6628 	{ 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } },
6629     { "SONY DSLR-A900", 128, 0,
6630 	{ 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } },
6631     { "SONY NEX-3", 138, 0,		/* DJC */
6632 	{ 6907,-1256,-645,-4940,12621,2320,-1710,2581,6230 } },
6633     { "SONY NEX-5", 116, 0,		/* DJC */
6634 	{ 6807,-1350,-342,-4216,11649,2567,-1089,2001,6420 } },
6635     { "SONY NEX", 128, 0,		/* Adobe's matrix */
6636 	{ 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } },
6637     { "SONY SLT-A33", 128, 0,
6638 	{ 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } },
6639     { "SONY SLT-A55", 128, 0,
6640 	{ 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }
6641   };
6642   double cam_xyz[4][3];
6643   char name[130];
6644   int i, j;
6645 
6646   sprintf (name, "%s %s", make, model);
6647   for (i=0; i < sizeof table / sizeof *table; i++)
6648     if (!strncmp (name, table[i].prefix, strlen(table[i].prefix))) {
6649       if (table[i].black)   black   = (ushort) table[i].black;
6650       if (table[i].maximum) maximum = (ushort) table[i].maximum;
6651       if (table[i].trans[0]) {
6652 	for (j=0; j < 12; j++)
6653 	  cam_xyz[0][j] = table[i].trans[j] / 10000.0;
6654 	cam_xyz_coeff (cam_xyz);
6655       }
6656       break;
6657     }
6658 }
6659 
simple_coeff(int index)6660 void CLASS simple_coeff (int index)
6661 {
6662   static const float table[][12] = {
6663   /* index 0 -- all Foveon cameras */
6664   { 1.4032,-0.2231,-0.1016,-0.5263,1.4816,0.017,-0.0112,0.0183,0.9113 },
6665   /* index 1 -- Kodak DC20 and DC25 */
6666   { 2.25,0.75,-1.75,-0.25,-0.25,0.75,0.75,-0.25,-0.25,-1.75,0.75,2.25 },
6667   /* index 2 -- Logitech Fotoman Pixtura */
6668   { 1.893,-0.418,-0.476,-0.495,1.773,-0.278,-1.017,-0.655,2.672 },
6669   /* index 3 -- Nikon E880, E900, and E990 */
6670   { -1.936280,  1.800443, -1.448486,  2.584324,
6671      1.405365, -0.524955, -0.289090,  0.408680,
6672     -1.204965,  1.082304,  2.941367, -1.818705 }
6673   };
6674   int i, c;
6675 
6676   for (raw_color = i=0; i < 3; i++)
6677     FORCC rgb_cam[i][c] = table[index][i*colors+c];
6678 }
6679 
guess_byte_order(int words)6680 short CLASS guess_byte_order (int words)
6681 {
6682   uchar test[4][2];
6683   int t=2, msb;
6684   double diff, sum[2] = {0,0};
6685 
6686   fread (test[0], 2, 2, ifp);
6687   for (words-=2; words--; ) {
6688     fread (test[t], 2, 1, ifp);
6689     for (msb=0; msb < 2; msb++) {
6690       diff = (test[t^2][msb] << 8 | test[t^2][!msb])
6691 	   - (test[t  ][msb] << 8 | test[t  ][!msb]);
6692       sum[msb] += diff*diff;
6693     }
6694     t = (t+1) & 3;
6695   }
6696   return sum[0] < sum[1] ? 0x4d4d : 0x4949;
6697 }
6698 
find_green(int bps,int bite,int off0,int off1)6699 float CLASS find_green (int bps, int bite, int off0, int off1)
6700 {
6701   UINT64 bitbuf=0;
6702   int vbits, col, i, c;
6703   ushort img[2][2064];
6704   double sum[]={0,0};
6705 
6706   FORC(2) {
6707     fseek (ifp, c ? off1:off0, SEEK_SET);
6708     for (vbits=col=0; col < width; col++) {
6709       for (vbits -= bps; vbits < 0; vbits += bite) {
6710 	bitbuf <<= bite;
6711 	for (i=0; i < bite; i+=8)
6712 	  bitbuf |= (unsigned) (fgetc(ifp) << i);
6713       }
6714       img[c][col] = bitbuf << (64-bps-vbits) >> (64-bps);
6715     }
6716   }
6717   FORC(width-1) {
6718     sum[ c & 1] += ABS(img[0][c]-img[1][c+1]);
6719     sum[~c & 1] += ABS(img[1][c]-img[0][c+1]);
6720   }
6721   return 100 * log(sum[0]/sum[1]);
6722 }
6723 
6724 /*
6725    Identify which camera created this file, and set global variables
6726    accordingly.
6727  */
identify()6728 void CLASS identify()
6729 {
6730   char head[32], *cp;
6731   int hlen, flen, fsize, zero_fsize=1, i, c, is_canon;
6732   struct jhead jh;
6733   short pana[][6] = {
6734     { 3130, 1743,  4,  0, -6,  0 },
6735     { 3130, 2055,  4,  0, -6,  0 },
6736     { 3130, 2319,  4,  0, -6,  0 },
6737     { 3170, 2103, 18,  0,-42, 20 },
6738     { 3170, 2367, 18, 13,-42,-21 },
6739     { 3177, 2367,  0,  0, -1,  0 },
6740     { 3304, 2458,  0,  0, -1,  0 },
6741     { 3330, 2463,  9,  0, -5,  0 },
6742     { 3330, 2479,  9,  0,-17,  4 },
6743     { 3370, 1899, 15,  0,-44, 20 },
6744     { 3370, 2235, 15,  0,-44, 20 },
6745     { 3370, 2511, 15, 10,-44,-21 },
6746     { 3690, 2751,  3,  0, -8, -3 },
6747     { 3710, 2751,  0,  0, -3,  0 },
6748     { 3724, 2450,  0,  0,  0, -2 },
6749     { 3770, 2487, 17,  0,-44, 19 },
6750     { 3770, 2799, 17, 15,-44,-19 },
6751     { 3880, 2170,  6,  0, -6,  0 },
6752     { 4060, 3018,  0,  0,  0, -2 },
6753     { 4290, 2391,  3,  0, -8, -1 },
6754     { 4330, 2439, 17, 15,-44,-19 },
6755     { 4508, 2962,  0,  0, -3, -4 },
6756     { 4508, 3330,  0,  0, -3, -6 } };
6757   static const struct {
6758     int fsize;
6759     char make[12], model[19], withjpeg;
6760   } table[] = {
6761     {    62464, "Kodak",    "DC20"            ,0 },
6762     {   124928, "Kodak",    "DC20"            ,0 },
6763     {  1652736, "Kodak",    "DCS200"          ,0 },
6764     {  4159302, "Kodak",    "C330"            ,0 },
6765     {  4162462, "Kodak",    "C330"            ,0 },
6766     {   460800, "Kodak",    "C603v"           ,0 },
6767     {   614400, "Kodak",    "C603v"           ,0 },
6768     {  6163328, "Kodak",    "C603"            ,0 },
6769     {  6166488, "Kodak",    "C603"            ,0 },
6770     {  9116448, "Kodak",    "C603y"           ,0 },
6771     {   311696, "ST Micro", "STV680 VGA"      ,0 },  /* SPYz */
6772     {   787456, "Creative", "PC-CAM 600"      ,0 },
6773     {  1138688, "Minolta",  "RD175"           ,0 },
6774     {  3840000, "Foculus",  "531C"            ,0 },
6775     {   786432, "AVT",      "F-080C"          ,0 },
6776     {  1447680, "AVT",      "F-145C"          ,0 },
6777     {  1920000, "AVT",      "F-201C"          ,0 },
6778     {  5067304, "AVT",      "F-510C"          ,0 },
6779     {  5067316, "AVT",      "F-510C"          ,0 },
6780     { 10134608, "AVT",      "F-510C"          ,0 },
6781     { 10134620, "AVT",      "F-510C"          ,0 },
6782     { 16157136, "AVT",      "F-810C"          ,0 },
6783     {  1409024, "Sony",     "XCD-SX910CR"     ,0 },
6784     {  2818048, "Sony",     "XCD-SX910CR"     ,0 },
6785     {  3884928, "Micron",   "2010"            ,0 },
6786     {  6624000, "Pixelink", "A782"            ,0 },
6787     { 13248000, "Pixelink", "A782"            ,0 },
6788     {  6291456, "RoverShot","3320AF"          ,0 },
6789     {  6553440, "Canon",    "PowerShot A460"  ,0 },
6790     {  6653280, "Canon",    "PowerShot A530"  ,0 },
6791     {  6573120, "Canon",    "PowerShot A610"  ,0 },
6792     {  9219600, "Canon",    "PowerShot A620"  ,0 },
6793     {  9243240, "Canon",    "PowerShot A470"  ,0 },
6794     { 10341600, "Canon",    "PowerShot A720 IS",0 },
6795     { 10383120, "Canon",    "PowerShot A630"  ,0 },
6796     { 12945240, "Canon",    "PowerShot A640"  ,0 },
6797     { 15636240, "Canon",    "PowerShot A650"  ,0 },
6798     {  5298000, "Canon",    "PowerShot SD300" ,0 },
6799     {  7710960, "Canon",    "PowerShot S3 IS" ,0 },
6800     { 15467760, "Canon",    "PowerShot SX110 IS",0 },
6801     { 15534576, "Canon",    "PowerShot SX120 IS",0 },
6802     { 18653760, "Canon",    "PowerShot SX20 IS",0 },
6803     {  5939200, "OLYMPUS",  "C770UZ"          ,0 },
6804     {  1581060, "NIKON",    "E900"            ,1 },  /* or E900s,E910 */
6805     {  2465792, "NIKON",    "E950"            ,1 },  /* or E800,E700 */
6806     {  2940928, "NIKON",    "E2100"           ,1 },  /* or E2500 */
6807     {  4771840, "NIKON",    "E990"            ,1 },  /* or E995, Oly C3030Z */
6808     {  4775936, "NIKON",    "E3700"           ,1 },  /* or Optio 33WR */
6809     {  5869568, "NIKON",    "E4300"           ,1 },  /* or DiMAGE Z2 */
6810     {  5865472, "NIKON",    "E4500"           ,1 },
6811     {  7438336, "NIKON",    "E5000"           ,1 },  /* or E5700 */
6812     {  8998912, "NIKON",    "COOLPIX S6"      ,1 },
6813     {  1976352, "CASIO",    "QV-2000UX"       ,1 },
6814     {  3217760, "CASIO",    "QV-3*00EX"       ,1 },
6815     {  6218368, "CASIO",    "QV-5700"         ,1 },
6816     {  6054400, "CASIO",    "QV-R41"          ,1 },
6817     {  7530816, "CASIO",    "QV-R51"          ,1 },
6818     {  7684000, "CASIO",    "QV-4000"         ,1 },
6819     {  2937856, "CASIO",    "EX-S20"          ,1 },
6820     {  4948608, "CASIO",    "EX-S100"         ,1 },
6821     {  7542528, "CASIO",    "EX-Z50"          ,1 },
6822     {  7753344, "CASIO",    "EX-Z55"          ,1 },
6823     {  7816704, "CASIO",    "EX-Z60"          ,1 },
6824     { 10843712, "CASIO",    "EX-Z75"          ,1 },
6825     { 10834368, "CASIO",    "EX-Z750"         ,1 },
6826     { 12310144, "CASIO",    "EX-Z850"         ,1 },
6827     { 15499264, "CASIO",    "EX-Z1050"        ,1 },
6828     {  7426656, "CASIO",    "EX-P505"         ,1 },
6829     {  9313536, "CASIO",    "EX-P600"         ,1 },
6830     { 10979200, "CASIO",    "EX-P700"         ,1 },
6831     {  3178560, "PENTAX",   "Optio S"         ,1 },
6832     {  4841984, "PENTAX",   "Optio S"         ,1 },
6833     {  6114240, "PENTAX",   "Optio S4"        ,1 },  /* or S4i, CASIO EX-Z4 */
6834     { 10702848, "PENTAX",   "Optio 750Z"      ,1 },
6835     { 15980544, "AGFAPHOTO","DC-833m"         ,1 },
6836     { 16098048, "SAMSUNG",  "S85"             ,1 },
6837     { 16215552, "SAMSUNG",  "S85"             ,1 },
6838     { 20487168, "SAMSUNG",  "WB550"           ,1 },
6839     { 24000000, "SAMSUNG",  "WB550"           ,1 },
6840     { 12582980, "Sinar",    ""                ,0 },
6841     { 33292868, "Sinar",    ""                ,0 },
6842     { 44390468, "Sinar",    ""                ,0 } };
6843   static const char *corp[] =
6844     { "Canon", "NIKON", "EPSON", "KODAK", "Kodak", "OLYMPUS", "PENTAX",
6845       "MINOLTA", "Minolta", "Konica", "CASIO", "Sinar", "Phase One",
6846       "SAMSUNG", "Mamiya", "MOTOROLA" };
6847 
6848   tiff_flip = flip = filters = -1;	/* 0 is valid, so -1 is unknown */
6849   raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0;
6850   maximum = height = width = top_margin = left_margin = 0;
6851   cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0;
6852   iso_speed = shutter = aperture = focal_len = unique_id = 0;
6853   tiff_nifds = 0;
6854   memset (tiff_ifd, 0, sizeof tiff_ifd);
6855   memset (gpsdata, 0, sizeof gpsdata);
6856   memset (cblack, 0, sizeof cblack);
6857   memset (white, 0, sizeof white);
6858   thumb_offset = thumb_length = thumb_width = thumb_height = 0;
6859   load_raw = thumb_load_raw = 0;
6860   write_thumb = &CLASS jpeg_thumb;
6861   data_offset = meta_length = tiff_bps = tiff_compress = 0;
6862   kodak_cbpp = zero_after_ff = dng_version = load_flags = 0;
6863   timestamp = shot_order = tiff_samples = black = is_foveon = 0;
6864   mix_green = profile_length = data_error = zero_is_bad = 0;
6865   pixel_aspect = is_raw = raw_color = 1;
6866   tile_width = tile_length = INT_MAX;
6867   for (i=0; i < 4; i++) {
6868     cam_mul[i] = i == 1;
6869     pre_mul[i] = i < 3;
6870     FORC3 cmatrix[c][i] = 0;
6871     FORC3 rgb_cam[c][i] = c == i;
6872   }
6873   colors = 3;
6874   for (i=0; i < 0x4000; i++) curve[i] = i;
6875 
6876   order = get2();
6877   hlen = get4();
6878   fseek (ifp, 0, SEEK_SET);
6879   fread (head, 1, 32, ifp);
6880   fseek (ifp, 0, SEEK_END);
6881   flen = fsize = ftell(ifp);
6882   if ((cp = (char *) memmem (head, 32, "MMMM", 4)) ||
6883       (cp = (char *) memmem (head, 32, "IIII", 4))) {
6884     parse_phase_one (cp-head);
6885     if (cp-head && parse_tiff(0)) apply_tiff();
6886   } else if (order == 0x4949 || order == 0x4d4d) {
6887     if (!memcmp (head+6,"HEAPCCDR",8)) {
6888       data_offset = hlen;
6889       parse_ciff (hlen, flen - hlen);
6890     } else if (parse_tiff(0)) apply_tiff();
6891   } else if (!memcmp (head,"\xff\xd8\xff\xe1",4) &&
6892 	     !memcmp (head+6,"Exif",4)) {
6893     fseek (ifp, 4, SEEK_SET);
6894     data_offset = 4 + get2();
6895     fseek (ifp, data_offset, SEEK_SET);
6896     if (fgetc(ifp) != 0xff)
6897       parse_tiff(12);
6898     thumb_offset = 0;
6899   } else if (!memcmp (head+25,"ARECOYK",7)) {
6900     strcpy (make, "Contax");
6901     strcpy (model,"N Digital");
6902     fseek (ifp, 33, SEEK_SET);
6903     get_timestamp(1);
6904     fseek (ifp, 60, SEEK_SET);
6905     FORC4 cam_mul[c ^ (c >> 1)] = get4();
6906   } else if (!strcmp (head, "PXN")) {
6907     strcpy (make, "Logitech");
6908     strcpy (model,"Fotoman Pixtura");
6909   } else if (!strcmp (head, "qktk")) {
6910     strcpy (make, "Apple");
6911     strcpy (model,"QuickTake 100");
6912   } else if (!strcmp (head, "qktn")) {
6913     strcpy (make, "Apple");
6914     strcpy (model,"QuickTake 150");
6915   } else if (!memcmp (head,"FUJIFILM",8)) {
6916     fseek (ifp, 84, SEEK_SET);
6917     thumb_offset = get4();
6918     thumb_length = get4();
6919     fseek (ifp, 92, SEEK_SET);
6920     parse_fuji (get4());
6921     if (thumb_offset > 120) {
6922       fseek (ifp, 120, SEEK_SET);
6923       is_raw += (i = get4()) && 1;
6924       if (is_raw == 2 && shot_select)
6925 	parse_fuji (i);
6926     }
6927     fseek (ifp, 100, SEEK_SET);
6928     parse_tiff (data_offset = get4());
6929     parse_tiff (thumb_offset+12);
6930     apply_tiff();
6931   } else if (!memcmp (head,"RIFF",4)) {
6932     fseek (ifp, 0, SEEK_SET);
6933     parse_riff();
6934   } else if (!memcmp (head,"\0\001\0\001\0@",6)) {
6935     fseek (ifp, 6, SEEK_SET);
6936     fread (make, 1, 8, ifp);
6937     fread (model, 1, 8, ifp);
6938     fread (model2, 1, 16, ifp);
6939     data_offset = get2();
6940     get2();
6941     raw_width = get2();
6942     raw_height = get2();
6943     load_raw = &CLASS nokia_load_raw;
6944     filters = 0x61616161;
6945   } else if (!memcmp (head,"NOKIARAW",8)) {
6946     strcpy (make, "NOKIA");
6947     strcpy (model, "X2");
6948     order = 0x4949;
6949     fseek (ifp, 300, SEEK_SET);
6950     data_offset = get4();
6951     i = get4();
6952     width = get2();
6953     height = get2();
6954     data_offset += i - width * 5 / 4 * height;
6955     load_raw = &CLASS nokia_load_raw;
6956     filters = 0x61616161;
6957   } else if (!memcmp (head,"DSC-Image",9))
6958     parse_rollei();
6959   else if (!memcmp (head,"PWAD",4))
6960     parse_sinar_ia();
6961   else if (!memcmp (head,"\0MRM",4))
6962     parse_minolta(0);
6963   else if (!memcmp (head,"FOVb",4))
6964     parse_foveon();
6965   else if (!memcmp (head,"CI",2))
6966     parse_cine();
6967   else
6968     for (zero_fsize=i=0; i < sizeof table / sizeof *table; i++)
6969       if (fsize == table[i].fsize) {
6970 	strcpy (make,  table[i].make );
6971 	strcpy (model, table[i].model);
6972 	if (table[i].withjpeg)
6973 	  parse_external_jpeg();
6974       }
6975   if (zero_fsize) fsize = 0;
6976   if (make[0] == 0) parse_smal (0, flen);
6977   if (make[0] == 0) parse_jpeg (is_raw = 0);
6978 
6979   for (i=0; i < sizeof corp / sizeof *corp; i++)
6980     if (strstr (make, corp[i]))		/* Simplify company names */
6981 	strcpy (make, corp[i]);
6982   if (!strncmp (make,"KODAK",5) &&
6983 	((cp = strstr(model," DIGITAL CAMERA")) ||
6984 	 (cp = strstr(model," Digital Camera")) ||
6985 	 (cp = strstr(model,"FILE VERSION"))))
6986      *cp = 0;
6987   cp = make + strlen(make);		/* Remove trailing spaces */
6988   while (*--cp == ' ') *cp = 0;
6989   cp = model + strlen(model);
6990   while (*--cp == ' ') *cp = 0;
6991   i = strlen(make);			/* Remove make from model */
6992   if (!strncasecmp (model, make, i) && model[i++] == ' ')
6993     memmove (model, model+i, 64-i);
6994   if (!strncmp (model,"Digital Camera ",15))
6995     strcpy (model, model+15);
6996   desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0;
6997   if (!is_raw) goto notraw;
6998 
6999   if (!height) height = raw_height;
7000   if (!width)  width  = raw_width;
7001   if (fuji_width) {
7002     fuji_width = (raw_width+1)/2;
7003     width = height + fuji_width;
7004     height = width - 1;
7005     pixel_aspect = 1;
7006   }
7007   if (height == 2624 && width == 3936)	/* Pentax K10D and Samsung GX10 */
7008     { height  = 2616;   width  = 3896; }
7009   if (height == 3136 && width == 4864)  /* Pentax K20D and Samsung GX20 */
7010     { height  = 3124;   width  = 4688; filters = 0x16161616; }
7011   if (!strcmp(model,"K-r") || !strcmp(model,"K-x"))
7012     {			width  = 4309; filters = 0x16161616; }
7013   if (!strcmp(model,"K-5"))
7014     { left_margin = 10; width  = 4950; filters = 0x16161616; }
7015   if (!strcmp(model,"K-7"))
7016     { height  = 3122;   width  = 4684; filters = 0x16161616; top_margin = 2; }
7017   if (!strcmp(model,"645D"))
7018     { height  = 5502;   width  = 7328; filters = 0x61616161; top_margin = 29;
7019       left_margin = 48; }
7020   if (height == 3014 && width == 4096)	/* Ricoh GX200 */
7021 			width  = 4014;
7022   if (dng_version) {
7023     if (filters == UINT_MAX) filters = 0;
7024     if (filters) is_raw = tiff_samples;
7025     else	 colors = tiff_samples;
7026     if (tiff_compress == 1)
7027       load_raw = &CLASS adobe_dng_load_raw_nc;
7028     if (tiff_compress == 7)
7029       load_raw = &CLASS adobe_dng_load_raw_lj;
7030     goto dng_skip;
7031   }
7032   if ((is_canon = !strcmp(make,"Canon")))
7033     load_raw = memcmp (head+6,"HEAPCCDR",8) ?
7034 	&CLASS lossless_jpeg_load_raw : &CLASS canon_compressed_load_raw;
7035   if (!strcmp(make,"NIKON")) {
7036     if (!load_raw)
7037       load_raw = &CLASS packed_load_raw;
7038     if (model[0] == 'E')
7039       load_flags |= !data_offset << 2 | 2;
7040   }
7041   if (!strcmp(make,"CASIO")) {
7042     load_raw = &CLASS packed_load_raw;
7043     maximum = 0xf7f;
7044   }
7045 
7046 /* Set parameters based on camera name (for non-DNG files). */
7047 
7048   if (is_foveon) {
7049     if (height*2 < width) pixel_aspect = 0.5;
7050     if (height   > width) pixel_aspect = 2;
7051     filters = 0;
7052     load_raw = &CLASS foveon_load_raw;
7053     simple_coeff(0);
7054   } else if (is_canon && tiff_bps == 15) {
7055     switch (width) {
7056       case 3344: width -= 66;
7057       case 3872: width -= 6;
7058     }
7059     filters = 0;
7060     load_raw = &CLASS canon_sraw_load_raw;
7061   } else if (!strcmp(model,"PowerShot 600")) {
7062     height = 613;
7063     width  = 854;
7064     raw_width = 896;
7065     pixel_aspect = 607/628.0;
7066     colors = 4;
7067     filters = 0xe1e4e1e4;
7068     load_raw = &CLASS canon_600_load_raw;
7069   } else if (!strcmp(model,"PowerShot A5") ||
7070 	     !strcmp(model,"PowerShot A5 Zoom")) {
7071     height = 773;
7072     width  = 960;
7073     raw_width = 992;
7074     pixel_aspect = 256/235.0;
7075     colors = 4;
7076     filters = 0x1e4e1e4e;
7077     goto canon_a5;
7078   } else if (!strcmp(model,"PowerShot A50")) {
7079     height =  968;
7080     width  = 1290;
7081     raw_width = 1320;
7082     colors = 4;
7083     filters = 0x1b4e4b1e;
7084     goto canon_a5;
7085   } else if (!strcmp(model,"PowerShot Pro70")) {
7086     height = 1024;
7087     width  = 1552;
7088     colors = 4;
7089     filters = 0x1e4b4e1b;
7090     goto canon_a5;
7091   } else if (!strcmp(model,"PowerShot SD300")) {
7092     height = 1752;
7093     width  = 2344;
7094     raw_height = 1766;
7095     raw_width  = 2400;
7096     top_margin  = 12;
7097     left_margin = 12;
7098     goto canon_a5;
7099   } else if (!strcmp(model,"PowerShot A460")) {
7100     height = 1960;
7101     width  = 2616;
7102     raw_height = 1968;
7103     raw_width  = 2664;
7104     top_margin  = 4;
7105     left_margin = 4;
7106     goto canon_a5;
7107   } else if (!strcmp(model,"PowerShot A530")) {
7108     height = 1984;
7109     width  = 2620;
7110     raw_height = 1992;
7111     raw_width  = 2672;
7112     top_margin  = 6;
7113     left_margin = 10;
7114     goto canon_a5;
7115   } else if (!strcmp(model,"PowerShot A610")) {
7116     if (canon_s2is()) strcpy (model+10, "S2 IS");
7117     height = 1960;
7118     width  = 2616;
7119     raw_height = 1968;
7120     raw_width  = 2672;
7121     top_margin  = 8;
7122     left_margin = 12;
7123     goto canon_a5;
7124   } else if (!strcmp(model,"PowerShot A620")) {
7125     height = 2328;
7126     width  = 3112;
7127     raw_height = 2340;
7128     raw_width  = 3152;
7129     top_margin  = 12;
7130     left_margin = 36;
7131     goto canon_a5;
7132   } else if (!strcmp(model,"PowerShot A470")) {
7133     height = 2328;
7134     width  = 3096;
7135     raw_height = 2346;
7136     raw_width  = 3152;
7137     top_margin  = 6;
7138     left_margin = 12;
7139     goto canon_a5;
7140   } else if (!strcmp(model,"PowerShot A720 IS")) {
7141     height = 2472;
7142     width  = 3298;
7143     raw_height = 2480;
7144     raw_width  = 3336;
7145     top_margin  = 5;
7146     left_margin = 6;
7147     goto canon_a5;
7148   } else if (!strcmp(model,"PowerShot A630")) {
7149     height = 2472;
7150     width  = 3288;
7151     raw_height = 2484;
7152     raw_width  = 3344;
7153     top_margin  = 6;
7154     left_margin = 12;
7155     goto canon_a5;
7156   } else if (!strcmp(model,"PowerShot A640")) {
7157     height = 2760;
7158     width  = 3672;
7159     raw_height = 2772;
7160     raw_width  = 3736;
7161     top_margin  = 6;
7162     left_margin = 12;
7163     goto canon_a5;
7164   } else if (!strcmp(model,"PowerShot A650")) {
7165     height = 3024;
7166     width  = 4032;
7167     raw_height = 3048;
7168     raw_width  = 4104;
7169     top_margin  = 12;
7170     left_margin = 48;
7171     goto canon_a5;
7172   } else if (!strcmp(model,"PowerShot S3 IS")) {
7173     height = 2128;
7174     width  = 2840;
7175     raw_height = 2136;
7176     raw_width  = 2888;
7177     top_margin  = 8;
7178     left_margin = 44;
7179 canon_a5:
7180     tiff_bps = 10;
7181     load_raw = &CLASS packed_load_raw;
7182     load_flags = 40;
7183     if (raw_width > 1600) zero_is_bad = 1;
7184   } else if (!strcmp(model,"PowerShot SX110 IS")) {
7185     height = 2760;
7186     width  = 3684;
7187     raw_height = 2772;
7188     raw_width  = 3720;
7189     top_margin  = 12;
7190     left_margin = 6;
7191     load_raw = &CLASS packed_load_raw;
7192     load_flags = 40;
7193     zero_is_bad = 1;
7194   } else if (!strcmp(model,"PowerShot SX120 IS")) {
7195     height = 2742;
7196     width  = 3664;
7197     raw_height = 2778;
7198     raw_width  = 3728;
7199     top_margin  = 18;
7200     left_margin = 16;
7201     filters = 0x49494949;
7202     load_raw = &CLASS packed_load_raw;
7203     load_flags = 40;
7204     zero_is_bad = 1;
7205   } else if (!strcmp(model,"PowerShot SX20 IS")) {
7206     height = 3024;
7207     width  = 4032;
7208     raw_height = 3048;
7209     raw_width  = 4080;
7210     top_margin  = 12;
7211     left_margin = 24;
7212     load_raw = &CLASS packed_load_raw;
7213     load_flags = 40;
7214     zero_is_bad = 1;
7215   } else if (!strcmp(model,"PowerShot Pro90 IS")) {
7216     width  = 1896;
7217     colors = 4;
7218     filters = 0xb4b4b4b4;
7219   } else if (is_canon && raw_width == 2144) {
7220     height = 1550;
7221     width  = 2088;
7222     top_margin  = 8;
7223     left_margin = 4;
7224     if (!strcmp(model,"PowerShot G1")) {
7225       colors = 4;
7226       filters = 0xb4b4b4b4;
7227     }
7228   } else if (is_canon && raw_width == 2224) {
7229     height = 1448;
7230     width  = 2176;
7231     top_margin  = 6;
7232     left_margin = 48;
7233   } else if (is_canon && raw_width == 2376) {
7234     height = 1720;
7235     width  = 2312;
7236     top_margin  = 6;
7237     left_margin = 12;
7238   } else if (is_canon && raw_width == 2672) {
7239     height = 1960;
7240     width  = 2616;
7241     top_margin  = 6;
7242     left_margin = 12;
7243   } else if (is_canon && raw_width == 3152) {
7244     height = 2056;
7245     width  = 3088;
7246     top_margin  = 12;
7247     left_margin = 64;
7248     if (unique_id == 0x80000170)
7249       adobe_coeff ("Canon","EOS 300D");
7250   } else if (is_canon && raw_width == 3160) {
7251     height = 2328;
7252     width  = 3112;
7253     top_margin  = 12;
7254     left_margin = 44;
7255   } else if (is_canon && raw_width == 3344) {
7256     height = 2472;
7257     width  = 3288;
7258     top_margin  = 6;
7259     left_margin = 4;
7260   } else if (!strcmp(model,"EOS D2000C")) {
7261     filters = 0x61616161;
7262     black = curve[200];
7263   } else if (is_canon && raw_width == 3516) {
7264     top_margin  = 14;
7265     left_margin = 42;
7266     if (unique_id == 0x80000189)
7267       adobe_coeff ("Canon","EOS 350D");
7268     goto canon_cr2;
7269   } else if (is_canon && raw_width == 3596) {
7270     top_margin  = 12;
7271     left_margin = 74;
7272     goto canon_cr2;
7273   } else if (is_canon && raw_width == 3744) {
7274     height = 2760;
7275     width  = 3684;
7276     top_margin  = 16;
7277     left_margin = 8;
7278     if (unique_id > 0x2720000) {
7279       top_margin  = 12;
7280       left_margin = 52;
7281     }
7282   } else if (is_canon && raw_width == 3944) {
7283     height = 2602;
7284     width  = 3908;
7285     top_margin  = 18;
7286     left_margin = 30;
7287   } else if (is_canon && raw_width == 3948) {
7288     top_margin  = 18;
7289     left_margin = 42;
7290     height -= 2;
7291     if (unique_id == 0x80000236)
7292       adobe_coeff ("Canon","EOS 400D");
7293     if (unique_id == 0x80000254)
7294       adobe_coeff ("Canon","EOS 1000D");
7295     goto canon_cr2;
7296   } else if (is_canon && raw_width == 3984) {
7297     top_margin  = 20;
7298     left_margin = 76;
7299     height -= 2;
7300     goto canon_cr2;
7301   } else if (is_canon && raw_width == 4104) {
7302     height = 3024;
7303     width  = 4032;
7304     top_margin  = 12;
7305     left_margin = 48;
7306   } else if (is_canon && raw_width == 4152) {
7307     top_margin  = 12;
7308     left_margin = 192;
7309     goto canon_cr2;
7310   } else if (is_canon && raw_width == 4312) {
7311     top_margin  = 18;
7312     left_margin = 22;
7313     height -= 2;
7314     if (unique_id == 0x80000176)
7315       adobe_coeff ("Canon","EOS 450D");
7316     goto canon_cr2;
7317   } else if (is_canon && raw_width == 4476) {
7318     top_margin  = 34;
7319     left_margin = 90;
7320     goto canon_cr2;
7321   } else if (is_canon && raw_width == 4480) {
7322     height = 3326;
7323     width  = 4432;
7324     top_margin  = 10;
7325     left_margin = 12;
7326     filters = 0x49494949;
7327   } else if (is_canon && raw_width == 4832) {
7328     top_margin = unique_id == 0x80000261 ? 51:26;
7329     left_margin = 62;
7330     if (unique_id == 0x80000252)
7331       adobe_coeff ("Canon","EOS 500D");
7332     goto canon_cr2;
7333   } else if (is_canon && raw_width == 5120) {
7334     height -= top_margin = 45;
7335     left_margin = 142;
7336     width = 4916;
7337   } else if (is_canon && raw_width == 5344) {
7338     top_margin = 51;
7339     left_margin = 142;
7340     if (unique_id == 0x80000270)
7341       adobe_coeff ("Canon","EOS 550D");
7342     goto canon_cr2;
7343   } else if (is_canon && raw_width == 5360) {
7344     top_margin = 51;
7345     left_margin = 158;
7346     goto canon_cr2;
7347   } else if (is_canon && raw_width == 5792) {
7348     top_margin  = 51;
7349     left_margin = 158;
7350     goto canon_cr2;
7351   } else if (is_canon && raw_width == 5108) {
7352     top_margin  = 13;
7353     left_margin = 98;
7354 canon_cr2:
7355     height -= top_margin;
7356     width  -= left_margin;
7357   } else if (is_canon && raw_width == 5712) {
7358     height = 3752;
7359     width  = 5640;
7360     top_margin  = 20;
7361     left_margin = 62;
7362   } else if (!strcmp(model,"D1")) {
7363     cam_mul[0] *= 256/527.0;
7364     cam_mul[2] *= 256/317.0;
7365   } else if (!strcmp(model,"D1X")) {
7366     width -= 4;
7367     pixel_aspect = 0.5;
7368   } else if (!strcmp(model,"D40X") ||
7369 	     !strcmp(model,"D60")  ||
7370 	     !strcmp(model,"D80")  ||
7371 	     !strcmp(model,"D3000")) {
7372     height -= 3;
7373     width  -= 4;
7374   } else if (!strcmp(model,"D3")   ||
7375 	     !strcmp(model,"D3S")  ||
7376 	     !strcmp(model,"D700")) {
7377     width -= 4;
7378     left_margin = 2;
7379   } else if (!strcmp(model,"D5000")) {
7380     width -= 42;
7381   } else if (!strcmp(model,"D7000")) {
7382     width -= 44;
7383   } else if (!strcmp(model,"D3100")) {
7384     width -= 28;
7385     left_margin = 6;
7386   } else if (!strncmp(model,"D40",3) ||
7387 	     !strncmp(model,"D50",3) ||
7388 	     !strncmp(model,"D70",3)) {
7389     width--;
7390   } else if (!strcmp(model,"D90")) {
7391     width -= 42;
7392   } else if (!strcmp(model,"D100")) {
7393     if (tiff_compress == 34713 && !nikon_is_compressed()) {
7394       load_raw = &CLASS packed_load_raw;
7395       load_flags |= 1;
7396       raw_width = (width += 3) + 3;
7397     }
7398   } else if (!strcmp(model,"D200")) {
7399     left_margin = 1;
7400     width -= 4;
7401     filters = 0x94949494;
7402   } else if (!strncmp(model,"D2H",3)) {
7403     left_margin = 6;
7404     width -= 14;
7405   } else if (!strncmp(model,"D2X",3)) {
7406     if (width == 3264) width -= 32;
7407     else width -= 8;
7408   } else if (!strncmp(model,"D300",4)) {
7409     width -= 32;
7410   } else if (!strncmp(model,"COOLPIX P",9)) {
7411     load_flags = 24;
7412     filters = 0x94949494;
7413   } else if (fsize == 1581060) {
7414     height = 963;
7415     width = 1287;
7416     raw_width = 1632;
7417     maximum = 0x3f4;
7418     colors = 4;
7419     filters = 0x1e1e1e1e;
7420     simple_coeff(3);
7421     pre_mul[0] = 1.2085;
7422     pre_mul[1] = 1.0943;
7423     pre_mul[3] = 1.1103;
7424     goto e900;
7425   } else if (fsize == 2465792) {
7426     height = 1203;
7427     width  = 1616;
7428     raw_width = 2048;
7429     colors = 4;
7430     filters = 0x4b4b4b4b;
7431     adobe_coeff ("NIKON","E950");
7432 e900:
7433     tiff_bps = 10;
7434     load_raw = &CLASS packed_load_raw;
7435     load_flags = 6;
7436   } else if (fsize == 4771840) {
7437     height = 1540;
7438     width  = 2064;
7439     colors = 4;
7440     filters = 0xe1e1e1e1;
7441     load_raw = &CLASS packed_load_raw;
7442     load_flags = 6;
7443     if (!timestamp && nikon_e995())
7444       strcpy (model, "E995");
7445     if (strcmp(model,"E995")) {
7446       filters = 0xb4b4b4b4;
7447       simple_coeff(3);
7448       pre_mul[0] = 1.196;
7449       pre_mul[1] = 1.246;
7450       pre_mul[2] = 1.018;
7451     }
7452   } else if (!strcmp(model,"E2100")) {
7453     if (!timestamp && !nikon_e2100()) goto cp_e2500;
7454     height = 1206;
7455     width  = 1616;
7456     load_flags = 30;
7457   } else if (!strcmp(model,"E2500")) {
7458 cp_e2500:
7459     strcpy (model, "E2500");
7460     height = 1204;
7461     width  = 1616;
7462     colors = 4;
7463     filters = 0x4b4b4b4b;
7464   } else if (fsize == 4775936) {
7465     height = 1542;
7466     width  = 2064;
7467     load_raw = &CLASS packed_load_raw;
7468     load_flags = 30;
7469     if (!timestamp) nikon_3700();
7470     if (model[0] == 'E' && atoi(model+1) < 3700)
7471       filters = 0x49494949;
7472     if (!strcmp(model,"Optio 33WR")) {
7473       flip = 1;
7474       filters = 0x16161616;
7475     }
7476     if (make[0] == 'O') {
7477       i = find_green (12, 32, 1188864, 3576832);
7478       c = find_green (12, 32, 2383920, 2387016);
7479       if (abs(i) < abs(c)) {
7480 	SWAP(i,c);
7481 	load_flags = 24;
7482       }
7483       if (i < 0) filters = 0x61616161;
7484     }
7485   } else if (fsize == 5869568) {
7486     height = 1710;
7487     width  = 2288;
7488     filters = 0x16161616;
7489     if (!timestamp && minolta_z2()) {
7490       strcpy (make, "Minolta");
7491       strcpy (model,"DiMAGE Z2");
7492     }
7493     load_raw = &CLASS packed_load_raw;
7494     load_flags = 6 + 24*(make[0] == 'M');
7495   } else if (!strcmp(model,"E4500")) {
7496     height = 1708;
7497     width  = 2288;
7498     colors = 4;
7499     filters = 0xb4b4b4b4;
7500   } else if (fsize == 7438336) {
7501     height = 1924;
7502     width  = 2576;
7503     colors = 4;
7504     filters = 0xb4b4b4b4;
7505   } else if (fsize == 8998912) {
7506     height = 2118;
7507     width  = 2832;
7508     maximum = 0xf83;
7509     load_raw = &CLASS packed_load_raw;
7510     load_flags = 30;
7511   } else if (!strcmp(make,"FUJIFILM")) {
7512     if (!strcmp(model+7,"S2Pro")) {
7513       strcpy (model+7," S2Pro");
7514       height = 2144;
7515       width  = 2880;
7516       flip = 6;
7517     } else if (load_raw != &CLASS packed_load_raw)
7518       maximum = 0x3e00;
7519     if (is_raw == 2 && shot_select)
7520       maximum = 0x2f00;
7521     top_margin = (raw_height - height)/2;
7522     left_margin = (raw_width - width )/2;
7523     if (is_raw == 2)
7524       data_offset += (shot_select > 0) * ( fuji_layout ?
7525 		(raw_width *= 2) : raw_height*raw_width*2 );
7526     if (load_raw == &CLASS fuji_load_raw) {
7527       fuji_width = width >> !fuji_layout;
7528       width = (height >> fuji_layout) + fuji_width;
7529       raw_height = height;
7530       height = width - 1;
7531       if (~fuji_width & 1) filters = 0x49494949;
7532     }
7533   } else if (!strcmp(model,"RD175")) {
7534     height = 986;
7535     width = 1534;
7536     data_offset = 513;
7537     filters = 0x61616161;
7538     load_raw = &CLASS minolta_rd175_load_raw;
7539   } else if (!strcmp(model,"KD-400Z")) {
7540     height = 1712;
7541     width  = 2312;
7542     raw_width = 2336;
7543     goto konica_400z;
7544   } else if (!strcmp(model,"KD-510Z")) {
7545     goto konica_510z;
7546   } else if (!strcasecmp(make,"MINOLTA")) {
7547     load_raw = &CLASS unpacked_load_raw;
7548     maximum = 0xfff;
7549     if (!strncmp(model,"DiMAGE A",8)) {
7550       if (!strcmp(model,"DiMAGE A200"))
7551 	filters = 0x49494949;
7552       tiff_bps = 12;
7553       load_raw = &CLASS packed_load_raw;
7554     } else if (!strncmp(model,"ALPHA",5) ||
7555 	       !strncmp(model,"DYNAX",5) ||
7556 	       !strncmp(model,"MAXXUM",6)) {
7557       sprintf (model+20, "DYNAX %-10s", model+6+(model[0]=='M'));
7558       adobe_coeff (make, model+20);
7559       load_raw = &CLASS packed_load_raw;
7560     } else if (!strncmp(model,"DiMAGE G",8)) {
7561       if (model[8] == '4') {
7562 	height = 1716;
7563 	width  = 2304;
7564       } else if (model[8] == '5') {
7565 konica_510z:
7566 	height = 1956;
7567 	width  = 2607;
7568 	raw_width = 2624;
7569       } else if (model[8] == '6') {
7570 	height = 2136;
7571 	width  = 2848;
7572       }
7573       data_offset += 14;
7574       filters = 0x61616161;
7575 konica_400z:
7576       load_raw = &CLASS unpacked_load_raw;
7577       maximum = 0x3df;
7578       order = 0x4d4d;
7579     }
7580   } else if (!strcmp(model,"*ist D")) {
7581     data_error = -1;
7582   } else if (!strcmp(model,"*ist DS")) {
7583     height -= 2;
7584   } else if (!strcmp(model,"Optio S")) {
7585     if (fsize == 3178560) {
7586       height = 1540;
7587       width  = 2064;
7588       load_raw = &CLASS eight_bit_load_raw;
7589       cam_mul[0] *= 4;
7590       cam_mul[2] *= 4;
7591     } else {
7592       height = 1544;
7593       width  = 2068;
7594       raw_width = 3136;
7595       load_raw = &CLASS packed_load_raw;
7596       maximum = 0xf7c;
7597     }
7598   } else if (fsize == 6114240) {
7599     height = 1737;
7600     width  = 2324;
7601     raw_width = 3520;
7602     load_raw = &CLASS packed_load_raw;
7603     maximum = 0xf7a;
7604   } else if (!strcmp(model,"Optio 750Z")) {
7605     height = 2302;
7606     width  = 3072;
7607     load_raw = &CLASS packed_load_raw;
7608     load_flags = 30;
7609   } else if (!strcmp(model,"DC-833m")) {
7610     height = 2448;
7611     width  = 3264;
7612     order = 0x4949;
7613     filters = 0x61616161;
7614     load_raw = &CLASS unpacked_load_raw;
7615     maximum = 0xfc00;
7616   } else if (!strncmp(model,"S85",3)) {
7617     height = 2448;
7618     width  = 3264;
7619     raw_width = fsize/height/2;
7620     order = 0x4d4d;
7621     load_raw = &CLASS unpacked_load_raw;
7622   } else if (!strcmp(model,"NX10")) {
7623     height -= top_margin = 4;
7624     width -= 2 * (left_margin = 8);
7625     load_flags = 32;
7626   } else if (!strcmp(model,"EX1")) {
7627     order = 0x4949;
7628     height = 2760;
7629     top_margin = 2;
7630     if ((width -= 6) > 3682) {
7631       height = 2750;
7632       width  = 3668;
7633       top_margin = 8;
7634     }
7635   } else if (!strcmp(model,"WB2000")) {
7636     order = 0x4949;
7637     height -= 3;
7638     width -= 10;
7639     top_margin = 2;
7640   } else if (fsize == 20487168) {
7641     height = 2808;
7642     width  = 3648;
7643     goto wb550;
7644   } else if (fsize == 24000000) {
7645     height = 3000;
7646     width  = 4000;
7647 wb550:
7648     strcpy (model, "WB550");
7649     order = 0x4d4d;
7650     load_raw = &CLASS unpacked_load_raw;
7651     load_flags = 6;
7652     maximum = 0x3df;
7653   } else if (!strcmp(model,"STV680 VGA")) {
7654     height = 484;
7655     width  = 644;
7656     load_raw = &CLASS eight_bit_load_raw;
7657     flip = 2;
7658     filters = 0x16161616;
7659     black = 16;
7660   } else if (!strcmp(model,"N95")) {
7661     height = raw_height - (top_margin = 2);
7662   } else if (!strcmp(model,"531C")) {
7663     height = 1200;
7664     width  = 1600;
7665     load_raw = &CLASS unpacked_load_raw;
7666     filters = 0x49494949;
7667   } else if (!strcmp(model,"F-080C")) {
7668     height = 768;
7669     width  = 1024;
7670     load_raw = &CLASS eight_bit_load_raw;
7671   } else if (!strcmp(model,"F-145C")) {
7672     height = 1040;
7673     width  = 1392;
7674     load_raw = &CLASS eight_bit_load_raw;
7675   } else if (!strcmp(model,"F-201C")) {
7676     height = 1200;
7677     width  = 1600;
7678     load_raw = &CLASS eight_bit_load_raw;
7679   } else if (!strcmp(model,"F-510C")) {
7680     height = 1958;
7681     width  = 2588;
7682     load_raw = fsize < 7500000 ?
7683 	&CLASS eight_bit_load_raw : &CLASS unpacked_load_raw;
7684     data_offset = fsize - width*height*(fsize >> 22);
7685     maximum = 0xfff0;
7686   } else if (!strcmp(model,"F-810C")) {
7687     height = 2469;
7688     width  = 3272;
7689     load_raw = &CLASS unpacked_load_raw;
7690     maximum = 0xfff0;
7691   } else if (!strcmp(model,"XCD-SX910CR")) {
7692     height = 1024;
7693     width  = 1375;
7694     raw_width = 1376;
7695     filters = 0x49494949;
7696     maximum = 0x3ff;
7697     load_raw = fsize < 2000000 ?
7698 	&CLASS eight_bit_load_raw : &CLASS unpacked_load_raw;
7699   } else if (!strcmp(model,"2010")) {
7700     height = 1207;
7701     width  = 1608;
7702     order = 0x4949;
7703     filters = 0x16161616;
7704     data_offset = 3212;
7705     maximum = 0x3ff;
7706     load_raw = &CLASS unpacked_load_raw;
7707   } else if (!strcmp(model,"A782")) {
7708     height = 3000;
7709     width  = 2208;
7710     filters = 0x61616161;
7711     load_raw = fsize < 10000000 ?
7712 	&CLASS eight_bit_load_raw : &CLASS unpacked_load_raw;
7713     maximum = 0xffc0;
7714   } else if (!strcmp(model,"3320AF")) {
7715     height = 1536;
7716     raw_width = width = 2048;
7717     filters = 0x61616161;
7718     load_raw = &CLASS unpacked_load_raw;
7719     maximum = 0x3ff;
7720     fseek (ifp, 0x300000, SEEK_SET);
7721     if ((order = guess_byte_order(0x10000)) == 0x4d4d) {
7722       height -= (top_margin = 16);
7723       width -= (left_margin = 28);
7724       maximum = 0xf5c0;
7725       strcpy (make, "ISG");
7726       model[0] = 0;
7727     }
7728   } else if (!strcmp(make,"Hasselblad")) {
7729     if (load_raw == &CLASS lossless_jpeg_load_raw)
7730       load_raw = &CLASS hasselblad_load_raw;
7731     if (raw_width == 7262) {
7732       height = 5444;
7733       width  = 7248;
7734       top_margin  = 4;
7735       left_margin = 7;
7736       filters = 0x61616161;
7737     } else if (raw_width == 7410) {
7738       height = 5502;
7739       width  = 7328;
7740       top_margin  = 4;
7741       left_margin = 41;
7742       filters = 0x61616161;
7743     } else if (raw_width == 4090) {
7744       strcpy (model, "V96C");
7745       height -= (top_margin = 6);
7746       width -= (left_margin = 3) + 7;
7747       filters = 0x61616161;
7748     }
7749   } else if (!strcmp(make,"Sinar")) {
7750     if (!memcmp(head,"8BPS",4)) {
7751       fseek (ifp, 14, SEEK_SET);
7752       height = get4();
7753       width  = get4();
7754       filters = 0x61616161;
7755       data_offset = 68;
7756     }
7757     if (!load_raw) load_raw = &CLASS unpacked_load_raw;
7758     maximum = 0x3fff;
7759   } else if (!strcmp(make,"Leaf")) {
7760     maximum = 0x3fff;
7761     fseek (ifp, data_offset, SEEK_SET);
7762     if (ljpeg_start (&jh, 1) && jh.bits == 15)
7763       maximum = 0x1fff;
7764     if (tiff_samples > 1) filters = 0;
7765     if (tiff_samples > 1 || tile_length < raw_height)
7766       load_raw = &CLASS leaf_hdr_load_raw;
7767     if ((width | height) == 2048) {
7768       if (tiff_samples == 1) {
7769 	filters = 1;
7770 	strcpy (cdesc, "RBTG");
7771 	strcpy (model, "CatchLight");
7772 	top_margin =  8; left_margin = 18; height = 2032; width = 2016;
7773       } else {
7774 	strcpy (model, "DCB2");
7775 	top_margin = 10; left_margin = 16; height = 2028; width = 2022;
7776       }
7777     } else if (width+height == 3144+2060) {
7778       if (!model[0]) strcpy (model, "Cantare");
7779       if (width > height) {
7780 	 top_margin = 6; left_margin = 32; height = 2048;  width = 3072;
7781 	filters = 0x61616161;
7782       } else {
7783 	left_margin = 6;  top_margin = 32;  width = 2048; height = 3072;
7784 	filters = 0x16161616;
7785       }
7786       if (!cam_mul[0] || model[0] == 'V') filters = 0;
7787       else is_raw = tiff_samples;
7788     } else if (width == 2116) {
7789       strcpy (model, "Valeo 6");
7790       height -= 2 * (top_margin = 30);
7791       width -= 2 * (left_margin = 55);
7792       filters = 0x49494949;
7793     } else if (width == 3171) {
7794       strcpy (model, "Valeo 6");
7795       height -= 2 * (top_margin = 24);
7796       width -= 2 * (left_margin = 24);
7797       filters = 0x16161616;
7798     }
7799   } else if (!strcmp(make,"LEICA") || !strcmp(make,"Panasonic")) {
7800     if ((flen - data_offset) / (raw_width*8/7) == raw_height)
7801       load_raw = &CLASS panasonic_load_raw;
7802     if (!load_raw) {
7803       load_raw = &CLASS unpacked_load_raw;
7804       load_flags = 4;
7805     }
7806     zero_is_bad = 1;
7807     if ((height += 12) > raw_height) height = raw_height;
7808     for (i=0; i < sizeof pana / sizeof *pana; i++)
7809       if (raw_width == pana[i][0] && raw_height == pana[i][1]) {
7810 	left_margin = pana[i][2];
7811 	 top_margin = pana[i][3];
7812 	     width += pana[i][4];
7813 	    height += pana[i][5];
7814       }
7815     filters = 0x01010101 * (uchar) "\x94\x61\x49\x16"
7816 	[((filters-1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3];
7817   } else if (!strcmp(model,"C770UZ")) {
7818     height = 1718;
7819     width  = 2304;
7820     filters = 0x16161616;
7821     load_raw = &CLASS packed_load_raw;
7822     load_flags = 30;
7823   } else if (!strcmp(make,"OLYMPUS")) {
7824     height += height & 1;
7825     filters = exif_cfa;
7826     if (width == 4100) width -= 4;
7827     if (load_raw == &CLASS unpacked_load_raw)
7828       load_flags = 4;
7829     tiff_bps = 12;
7830     if (!strcmp(model,"E-300") ||
7831 	!strcmp(model,"E-500")) {
7832       width -= 20;
7833       if (load_raw == &CLASS unpacked_load_raw) {
7834 	maximum = 0xfc3;
7835 	memset (cblack, 0, sizeof cblack);
7836       }
7837     } else if (!strcmp(model,"E-330")) {
7838       width -= 30;
7839       if (load_raw == &CLASS unpacked_load_raw)
7840 	maximum = 0xf79;
7841     } else if (!strcmp(model,"SP550UZ")) {
7842       thumb_length = flen - (thumb_offset = 0xa39800);
7843       thumb_height = 480;
7844       thumb_width  = 640;
7845     }
7846   } else if (!strcmp(model,"N Digital")) {
7847     height = 2047;
7848     width  = 3072;
7849     filters = 0x61616161;
7850     data_offset = 0x1a00;
7851     load_raw = &CLASS packed_load_raw;
7852   } else if (!strcmp(model,"DSC-F828")) {
7853     width = 3288;
7854     left_margin = 5;
7855     data_offset = 862144;
7856     load_raw = &CLASS sony_load_raw;
7857     filters = 0x9c9c9c9c;
7858     colors = 4;
7859     strcpy (cdesc, "RGBE");
7860   } else if (!strcmp(model,"DSC-V3")) {
7861     width = 3109;
7862     left_margin = 59;
7863     data_offset = 787392;
7864     load_raw = &CLASS sony_load_raw;
7865   } else if (!strcmp(make,"SONY") && raw_width == 3984) {
7866     adobe_coeff ("SONY","DSC-R1");
7867     width = 3925;
7868     order = 0x4d4d;
7869   } else if (!strcmp(model,"DSLR-A100")) {
7870     if (width == 3880) {
7871       height--;
7872       width = ++raw_width;
7873     } else {
7874       order = 0x4d4d;
7875       load_flags = 2;
7876     }
7877     filters = 0x61616161;
7878   } else if (!strcmp(model,"DSLR-A350")) {
7879     height -= 4;
7880   } else if (!strcmp(model,"PIXL")) {
7881     height -= top_margin = 4;
7882     width -= left_margin = 32;
7883     gamma_curve (0, 7, 1, 255);
7884   } else if (!strcmp(model,"C603v")) {
7885     height = 480;
7886     width  = 640;
7887     if (fsize < 614400 || find_green (16, 16, 3840, 5120) < 25) goto c603v;
7888     strcpy (model,"KAI-0340");
7889     height -= 3;
7890     data_offset = 3840;
7891     order = 0x4949;
7892     load_raw = &CLASS unpacked_load_raw;
7893   } else if (!strcmp(model,"C603y")) {
7894     height = 2134;
7895     width  = 2848;
7896 c603v:
7897     filters = 0;
7898     load_raw = &CLASS kodak_yrgb_load_raw;
7899     gamma_curve (0, 3.875, 1, 255);
7900   } else if (!strcmp(model,"C603")) {
7901     raw_height = height = 2152;
7902     raw_width  = width  = 2864;
7903     goto c603;
7904   } else if (!strcmp(model,"C330")) {
7905     height = 1744;
7906     width  = 2336;
7907     raw_height = 1779;
7908     raw_width  = 2338;
7909     top_margin = 33;
7910     left_margin = 1;
7911 c603:
7912     order = 0x4949;
7913     if ((data_offset = fsize - raw_height*raw_width)) {
7914       fseek (ifp, 168, SEEK_SET);
7915       read_shorts (curve, 256);
7916     } else gamma_curve (0, 3.875, 1, 255);
7917     load_raw = &CLASS eight_bit_load_raw;
7918   } else if (!strncasecmp(model,"EasyShare",9)) {
7919     data_offset = 0x15000;
7920     load_raw = &CLASS packed_load_raw;
7921   } else if (!strcasecmp(make,"KODAK")) {
7922     if (filters == UINT_MAX) filters = 0x61616161;
7923     if (!strncmp(model,"NC2000",6)) {
7924       width -= 4;
7925       left_margin = 2;
7926     } else if (!strcmp(model,"EOSDCS3B")) {
7927       width -= 4;
7928       left_margin = 2;
7929     } else if (!strcmp(model,"EOSDCS1")) {
7930       width -= 4;
7931       left_margin = 2;
7932     } else if (!strcmp(model,"DCS420")) {
7933       width -= 4;
7934       left_margin = 2;
7935     } else if (!strncmp(model,"DCS460 ",7)) {
7936       model[6] = 0;
7937       width -= 4;
7938       left_margin = 2;
7939     } else if (!strcmp(model,"DCS460A")) {
7940       width -= 4;
7941       left_margin = 2;
7942       colors = 1;
7943       filters = 0;
7944     } else if (!strcmp(model,"DCS660M")) {
7945       black = 214;
7946       colors = 1;
7947       filters = 0;
7948     } else if (!strcmp(model,"DCS760M")) {
7949       colors = 1;
7950       filters = 0;
7951     }
7952     if (!strcmp(model+4,"20X"))
7953       strcpy (cdesc, "MYCY");
7954     if (strstr(model,"DC25")) {
7955       strcpy (model, "DC25");
7956       data_offset = 15424;
7957     }
7958     if (!strncmp(model,"DC2",3)) {
7959       height = 242;
7960       if (flen < 100000) {
7961 	raw_width = 256; width = 249;
7962 	pixel_aspect = (4.0*height) / (3.0*width);
7963       } else {
7964 	raw_width = 512; width = 501;
7965 	pixel_aspect = (493.0*height) / (373.0*width);
7966       }
7967       data_offset += raw_width + 1;
7968       colors = 4;
7969       filters = 0x8d8d8d8d;
7970       simple_coeff(1);
7971       pre_mul[1] = 1.179;
7972       pre_mul[2] = 1.209;
7973       pre_mul[3] = 1.036;
7974       load_raw = &CLASS eight_bit_load_raw;
7975     } else if (!strcmp(model,"40")) {
7976       strcpy (model, "DC40");
7977       height = 512;
7978       width  = 768;
7979       data_offset = 1152;
7980       load_raw = &CLASS kodak_radc_load_raw;
7981     } else if (strstr(model,"DC50")) {
7982       strcpy (model, "DC50");
7983       height = 512;
7984       width  = 768;
7985       data_offset = 19712;
7986       load_raw = &CLASS kodak_radc_load_raw;
7987     } else if (strstr(model,"DC120")) {
7988       strcpy (model, "DC120");
7989       height = 976;
7990       width  = 848;
7991       pixel_aspect = height/0.75/width;
7992       load_raw = tiff_compress == 7 ?
7993 	&CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw;
7994     } else if (!strcmp(model,"DCS200")) {
7995       thumb_height = 128;
7996       thumb_width  = 192;
7997       thumb_offset = 6144;
7998       thumb_misc   = 360;
7999       write_thumb = &CLASS layer_thumb;
8000       height = 1024;
8001       width  = 1536;
8002       data_offset = 79872;
8003       load_raw = &CLASS eight_bit_load_raw;
8004       black = 17;
8005     }
8006   } else if (!strcmp(model,"Fotoman Pixtura")) {
8007     height = 512;
8008     width  = 768;
8009     data_offset = 3632;
8010     load_raw = &CLASS kodak_radc_load_raw;
8011     filters = 0x61616161;
8012     simple_coeff(2);
8013   } else if (!strcmp(model,"QuickTake 100")) {
8014     fseek (ifp, 544, SEEK_SET);
8015     height = get2();
8016     width  = get2();
8017     data_offset = (get4(),get2()) == 30 ? 738:736;
8018     if (height > width) {
8019       SWAP(height,width);
8020       fseek (ifp, data_offset-6, SEEK_SET);
8021       flip = ~get2() & 3 ? 5:6;
8022     }
8023     load_raw = &CLASS quicktake_100_load_raw;
8024     filters = 0x61616161;
8025   } else if (!strcmp(model,"QuickTake 150")) {
8026     data_offset = 738 - head[5];
8027     if (head[5]) strcpy (model+10, "200");
8028     load_raw = &CLASS kodak_radc_load_raw;
8029     height = 480;
8030     width  = 640;
8031     filters = 0x61616161;
8032   } else if (!strcmp(make,"Rollei") && !load_raw) {
8033     switch (raw_width) {
8034       case 1316:
8035 	height = 1030;
8036 	width  = 1300;
8037 	top_margin  = 1;
8038 	left_margin = 6;
8039 	break;
8040       case 2568:
8041 	height = 1960;
8042 	width  = 2560;
8043 	top_margin  = 2;
8044 	left_margin = 8;
8045     }
8046     filters = 0x16161616;
8047     load_raw = &CLASS rollei_load_raw;
8048   } else if (!strcmp(model,"PC-CAM 600")) {
8049     height = 768;
8050     data_offset = width = 1024;
8051     filters = 0x49494949;
8052     load_raw = &CLASS eight_bit_load_raw;
8053   } else if (!strcmp(model,"QV-2000UX")) {
8054     height = 1208;
8055     width  = 1632;
8056     data_offset = width * 2;
8057     load_raw = &CLASS eight_bit_load_raw;
8058   } else if (fsize == 3217760) {
8059     height = 1546;
8060     width  = 2070;
8061     raw_width = 2080;
8062     load_raw = &CLASS eight_bit_load_raw;
8063   } else if (!strcmp(model,"QV-4000")) {
8064     height = 1700;
8065     width  = 2260;
8066     load_raw = &CLASS unpacked_load_raw;
8067     maximum = 0xffff;
8068   } else if (!strcmp(model,"QV-5700")) {
8069     height = 1924;
8070     width  = 2576;
8071     raw_width = 3232;
8072     tiff_bps = 10;
8073   } else if (!strcmp(model,"QV-R41")) {
8074     height = 1720;
8075     width  = 2312;
8076     raw_width = 3520;
8077     left_margin = 2;
8078   } else if (!strcmp(model,"QV-R51")) {
8079     height = 1926;
8080     width  = 2580;
8081     raw_width = 3904;
8082   } else if (!strcmp(model,"EX-S20")) {
8083     height = 1208;
8084     width  = 1620;
8085     raw_width = 2432;
8086     flip = 3;
8087   } else if (!strcmp(model,"EX-S100")) {
8088     height = 1544;
8089     width  = 2058;
8090     raw_width = 3136;
8091   } else if (!strcmp(model,"EX-Z50")) {
8092     height = 1931;
8093     width  = 2570;
8094     raw_width = 3904;
8095   } else if (!strcmp(model,"EX-Z55")) {
8096     height = 1960;
8097     width  = 2570;
8098     raw_width = 3904;
8099   } else if (!strcmp(model,"EX-Z60")) {
8100     height = 2145;
8101     width  = 2833;
8102     raw_width = 3584;
8103     filters = 0x16161616;
8104     tiff_bps = 10;
8105   } else if (!strcmp(model,"EX-Z75")) {
8106     height = 2321;
8107     width  = 3089;
8108     raw_width = 4672;
8109     maximum = 0xfff;
8110   } else if (!strcmp(model,"EX-Z750")) {
8111     height = 2319;
8112     width  = 3087;
8113     raw_width = 4672;
8114     maximum = 0xfff;
8115   } else if (!strcmp(model,"EX-Z850")) {
8116     height = 2468;
8117     width  = 3279;
8118     raw_width = 4928;
8119     maximum = 0xfff;
8120   } else if (fsize == 15499264) {	/* EX-Z1050 or EX-Z1080 */
8121     height = 2752;
8122     width  = 3672;
8123     raw_width = 5632;
8124   } else if (!strcmp(model,"EX-P505")) {
8125     height = 1928;
8126     width  = 2568;
8127     raw_width = 3852;
8128     maximum = 0xfff;
8129   } else if (fsize == 9313536) {	/* EX-P600 or QV-R61 */
8130     height = 2142;
8131     width  = 2844;
8132     raw_width = 4288;
8133   } else if (!strcmp(model,"EX-P700")) {
8134     height = 2318;
8135     width  = 3082;
8136     raw_width = 4672;
8137   }
8138   if (!model[0])
8139     sprintf (model, "%dx%d", width, height);
8140   if (filters == UINT_MAX) filters = 0x94949494;
8141   if (raw_color) adobe_coeff (make, model);
8142   if (load_raw == &CLASS kodak_radc_load_raw)
8143     if (raw_color) adobe_coeff ("Apple","Quicktake");
8144   if (thumb_offset && !thumb_height) {
8145     fseek (ifp, thumb_offset, SEEK_SET);
8146     if (ljpeg_start (&jh, 1)) {
8147       thumb_width  = jh.wide;
8148       thumb_height = jh.high;
8149     }
8150   }
8151 dng_skip:
8152   if (!tiff_bps) tiff_bps = 12;
8153   if (!maximum) maximum = (1 << tiff_bps) - 1;
8154   if (!load_raw || height < 22) is_raw = 0;
8155 #ifdef NO_JPEG
8156   if (load_raw == &CLASS kodak_jpeg_load_raw) {
8157     fprintf (stderr,_("%s: You must link dcraw with libjpeg!!\n"), ifname);
8158     is_raw = 0;
8159   }
8160 #endif
8161   if (!cdesc[0])
8162     strcpy (cdesc, colors == 3 ? "RGBG":"GMCY");
8163   if (!raw_height) raw_height = height;
8164   if (!raw_width ) raw_width  = width;
8165   if (filters && colors == 3)
8166     filters |= ((filters >> 2 & 0x22222222) |
8167 		(filters << 2 & 0x88888888)) & filters << 1;
8168 notraw:
8169   if (flip == -1) flip = tiff_flip;
8170   if (flip == -1) flip = 0;
8171 }
8172 
8173 #ifndef NO_LCMS
apply_profile(const char * input,const char * output)8174 void CLASS apply_profile (const char *input, const char *output)
8175 {
8176   char *prof;
8177   cmsHPROFILE hInProfile=0, hOutProfile=0;
8178   cmsHTRANSFORM hTransform;
8179   FILE *fp;
8180   unsigned size;
8181 
8182   cmsErrorAction (LCMS_ERROR_SHOW);
8183   if (strcmp (input, "embed"))
8184     hInProfile = cmsOpenProfileFromFile (input, "r");
8185   else if (profile_length) {
8186     prof = (char *) malloc (profile_length);
8187     merror (prof, "apply_profile()");
8188     fseek (ifp, profile_offset, SEEK_SET);
8189     fread (prof, 1, profile_length, ifp);
8190     hInProfile = cmsOpenProfileFromMem (prof, profile_length);
8191     free (prof);
8192   } else
8193     fprintf (stderr,_("%s has no embedded profile.\n"), ifname);
8194   if (!hInProfile) return;
8195   if (!output)
8196     hOutProfile = cmsCreate_sRGBProfile();
8197   else if ((fp = fopen (output, "rb"))) {
8198     fread (&size, 4, 1, fp);
8199     fseek (fp, 0, SEEK_SET);
8200     oprof = (unsigned *) malloc (size = ntohl(size));
8201     merror (oprof, "apply_profile()");
8202     fread (oprof, 1, size, fp);
8203     fclose (fp);
8204     if (!(hOutProfile = cmsOpenProfileFromMem (oprof, size))) {
8205       free (oprof);
8206       oprof = 0;
8207     }
8208   } else
8209     fprintf (stderr,_("Cannot open file %s!\n"), output);
8210   if (!hOutProfile) goto quit;
8211   if (verbose)
8212     fprintf (stderr,_("Applying color profile...\n"));
8213   hTransform = cmsCreateTransform (hInProfile, TYPE_RGBA_16,
8214 	hOutProfile, TYPE_RGBA_16, INTENT_PERCEPTUAL, 0);
8215   cmsDoTransform (hTransform, image, image, width*height);
8216   raw_color = 1;		/* Don't use rgb_cam with a profile */
8217   cmsDeleteTransform (hTransform);
8218   cmsCloseProfile (hOutProfile);
8219 quit:
8220   cmsCloseProfile (hInProfile);
8221 }
8222 #endif
8223 
convert_to_rgb()8224 void CLASS convert_to_rgb()
8225 {
8226   int row, col, c, i, j, k;
8227   ushort *img;
8228   float out[3], out_cam[3][4];
8229   double num, inverse[3][3];
8230   static const double xyzd50_srgb[3][3] =
8231   { { 0.436083, 0.385083, 0.143055 },
8232     { 0.222507, 0.716888, 0.060608 },
8233     { 0.013930, 0.097097, 0.714022 } };
8234   static const double rgb_rgb[3][3] =
8235   { { 1,0,0 }, { 0,1,0 }, { 0,0,1 } };
8236   static const double adobe_rgb[3][3] =
8237   { { 0.715146, 0.284856, 0.000000 },
8238     { 0.000000, 1.000000, 0.000000 },
8239     { 0.000000, 0.041166, 0.958839 } };
8240   static const double wide_rgb[3][3] =
8241   { { 0.593087, 0.404710, 0.002206 },
8242     { 0.095413, 0.843149, 0.061439 },
8243     { 0.011621, 0.069091, 0.919288 } };
8244   static const double prophoto_rgb[3][3] =
8245   { { 0.529317, 0.330092, 0.140588 },
8246     { 0.098368, 0.873465, 0.028169 },
8247     { 0.016879, 0.117663, 0.865457 } };
8248   static const double (*out_rgb[])[3] =
8249   { rgb_rgb, adobe_rgb, wide_rgb, prophoto_rgb, xyz_rgb };
8250   static const char *name[] =
8251   { "sRGB", "Adobe RGB (1998)", "WideGamut D65", "ProPhoto D65", "XYZ" };
8252   static const unsigned phead[] =
8253   { 1024, 0, 0x2100000, 0x6d6e7472, 0x52474220, 0x58595a20, 0, 0, 0,
8254     0x61637370, 0, 0, 0x6e6f6e65, 0, 0, 0, 0, 0xf6d6, 0x10000, 0xd32d };
8255   unsigned pbody[] =
8256   { 10, 0x63707274, 0, 36,	/* cprt */
8257 	0x64657363, 0, 40,	/* desc */
8258 	0x77747074, 0, 20,	/* wtpt */
8259 	0x626b7074, 0, 20,	/* bkpt */
8260 	0x72545243, 0, 14,	/* rTRC */
8261 	0x67545243, 0, 14,	/* gTRC */
8262 	0x62545243, 0, 14,	/* bTRC */
8263 	0x7258595a, 0, 20,	/* rXYZ */
8264 	0x6758595a, 0, 20,	/* gXYZ */
8265 	0x6258595a, 0, 20 };	/* bXYZ */
8266   static const unsigned pwhite[] = { 0xf351, 0x10000, 0x116cc };
8267   unsigned pcurve[] = { 0x63757276, 0, 1, 0x1000000 };
8268 
8269   gamma_curve (gamm[0], gamm[1], 0, 0);
8270   memcpy (out_cam, rgb_cam, sizeof out_cam);
8271   raw_color |= colors == 1 || document_mode ||
8272 		output_color < 1 || output_color > 5;
8273   if (!raw_color) {
8274     oprof = (unsigned *) calloc (phead[0], 1);
8275     merror (oprof, "convert_to_rgb()");
8276     memcpy (oprof, phead, sizeof phead);
8277     if (output_color == 5) oprof[4] = oprof[5];
8278     oprof[0] = 132 + 12*pbody[0];
8279     for (i=0; i < pbody[0]; i++) {
8280       oprof[oprof[0]/4] = i ? (i > 1 ? 0x58595a20 : 0x64657363) : 0x74657874;
8281       pbody[i*3+2] = oprof[0];
8282       oprof[0] += (pbody[i*3+3] + 3) & -4;
8283     }
8284     memcpy (oprof+32, pbody, sizeof pbody);
8285     oprof[pbody[5]/4+2] = strlen(name[output_color-1]) + 1;
8286     memcpy ((char *)oprof+pbody[8]+8, pwhite, sizeof pwhite);
8287     pcurve[3] = (short)(256/gamm[5]+0.5) << 16;
8288     for (i=4; i < 7; i++)
8289       memcpy ((char *)oprof+pbody[i*3+2], pcurve, sizeof pcurve);
8290     pseudoinverse ((double (*)[3]) out_rgb[output_color-1], inverse, 3);
8291     for (i=0; i < 3; i++)
8292       for (j=0; j < 3; j++) {
8293 	for (num = k=0; k < 3; k++)
8294 	  num += xyzd50_srgb[i][k] * inverse[j][k];
8295         oprof[pbody[j*3+23]/4+i+2] = num * 0x10000 + 0.5;
8296       }
8297     for (i=0; i < phead[0]/4; i++)
8298       oprof[i] = htonl(oprof[i]);
8299     strcpy ((char *)oprof+pbody[2]+8, "auto-generated by dcraw");
8300     strcpy ((char *)oprof+pbody[5]+12, name[output_color-1]);
8301     for (i=0; i < 3; i++)
8302       for (j=0; j < colors; j++)
8303 	for (out_cam[i][j] = k=0; k < 3; k++)
8304 	  out_cam[i][j] += out_rgb[output_color-1][i][k] * rgb_cam[k][j];
8305   }
8306   if (verbose)
8307     fprintf (stderr, raw_color ? _("Building histograms...\n") :
8308 	_("Converting to %s colorspace...\n"), name[output_color-1]);
8309 
8310   memset (histogram, 0, sizeof histogram);
8311   for (img=image[0], row=0; row < height; row++)
8312     for (col=0; col < width; col++, img+=4) {
8313       if (!raw_color) {
8314 	out[0] = out[1] = out[2] = 0;
8315 	FORCC {
8316 	  out[0] += out_cam[0][c] * img[c];
8317 	  out[1] += out_cam[1][c] * img[c];
8318 	  out[2] += out_cam[2][c] * img[c];
8319 	}
8320 	FORC3 img[c] = CLIP((int) out[c]);
8321       }
8322       else if (document_mode)
8323 	img[0] = img[FC(row,col)];
8324       FORCC histogram[c][img[c] >> 3]++;
8325     }
8326   if (colors == 4 && output_color) colors = 3;
8327   if (document_mode && filters) colors = 1;
8328 }
8329 
fuji_rotate()8330 void CLASS fuji_rotate()
8331 {
8332   int i, row, col;
8333   double step;
8334   float r, c, fr, fc;
8335   unsigned ur, uc;
8336   ushort wide, high, (*img)[4], (*pix)[4];
8337 
8338   if (!fuji_width) return;
8339   if (verbose)
8340     fprintf (stderr,_("Rotating image 45 degrees...\n"));
8341   fuji_width = (fuji_width - 1 + shrink) >> shrink;
8342   step = sqrt(0.5);
8343   wide = fuji_width / step;
8344   high = (height - fuji_width) / step;
8345   img = (ushort (*)[4]) calloc (wide*high, sizeof *img);
8346   merror (img, "fuji_rotate()");
8347 
8348   for (row=0; row < high; row++)
8349     for (col=0; col < wide; col++) {
8350       ur = r = fuji_width + (row-col)*step;
8351       uc = c = (row+col)*step;
8352       if (ur > height-2 || uc > width-2) continue;
8353       fr = r - ur;
8354       fc = c - uc;
8355       pix = image + ur*width + uc;
8356       for (i=0; i < colors; i++)
8357 	img[row*wide+col][i] =
8358 	  (pix[    0][i]*(1-fc) + pix[      1][i]*fc) * (1-fr) +
8359 	  (pix[width][i]*(1-fc) + pix[width+1][i]*fc) * fr;
8360     }
8361   free (image);
8362   width  = wide;
8363   height = high;
8364   image  = img;
8365   fuji_width = 0;
8366 }
8367 
stretch()8368 void CLASS stretch()
8369 {
8370   ushort newdim, (*img)[4], *pix0, *pix1;
8371   int row, col, c;
8372   double rc, frac;
8373 
8374   if (pixel_aspect == 1) return;
8375   if (verbose) fprintf (stderr,_("Stretching the image...\n"));
8376   if (pixel_aspect < 1) {
8377     newdim = height / pixel_aspect + 0.5;
8378     img = (ushort (*)[4]) calloc (width*newdim, sizeof *img);
8379     merror (img, "stretch()");
8380     for (rc=row=0; row < newdim; row++, rc+=pixel_aspect) {
8381       frac = rc - (c = rc);
8382       pix0 = pix1 = image[c*width];
8383       if (c+1 < height) pix1 += width*4;
8384       for (col=0; col < width; col++, pix0+=4, pix1+=4)
8385 	FORCC img[row*width+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5;
8386     }
8387     height = newdim;
8388   } else {
8389     newdim = width * pixel_aspect + 0.5;
8390     img = (ushort (*)[4]) calloc (height*newdim, sizeof *img);
8391     merror (img, "stretch()");
8392     for (rc=col=0; col < newdim; col++, rc+=1/pixel_aspect) {
8393       frac = rc - (c = rc);
8394       pix0 = pix1 = image[c];
8395       if (c+1 < width) pix1 += 4;
8396       for (row=0; row < height; row++, pix0+=width*4, pix1+=width*4)
8397 	FORCC img[row*newdim+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5;
8398     }
8399     width = newdim;
8400   }
8401   free (image);
8402   image = img;
8403 }
8404 
flip_index(int row,int col)8405 int CLASS flip_index (int row, int col)
8406 {
8407   if (flip & 4) SWAP(row,col);
8408   if (flip & 2) row = iheight - 1 - row;
8409   if (flip & 1) col = iwidth  - 1 - col;
8410   return row * iwidth + col;
8411 }
8412 
8413 struct tiff_tag {
8414   ushort tag, type;
8415   int count;
8416   union { char c[4]; short s[2]; int i; } val;
8417 };
8418 
8419 struct tiff_hdr {
8420   ushort order, magic;
8421   int ifd;
8422   ushort pad, ntag;
8423   struct tiff_tag tag[23];
8424   int nextifd;
8425   ushort pad2, nexif;
8426   struct tiff_tag exif[4];
8427   ushort pad3, ngps;
8428   struct tiff_tag gpst[10];
8429   short bps[4];
8430   int rat[10];
8431   unsigned gps[26];
8432   char desc[512], make[64], model[64], soft[32], date[20], artist[64];
8433 };
8434 
tiff_set(ushort * ntag,ushort tag,ushort type,int count,int val)8435 void CLASS tiff_set (ushort *ntag,
8436 	ushort tag, ushort type, int count, int val)
8437 {
8438   struct tiff_tag *tt;
8439   int c;
8440 
8441   tt = (struct tiff_tag *)(ntag+1) + (*ntag)++;
8442   tt->tag = tag;
8443   tt->type = type;
8444   tt->count = count;
8445   if (type < 3 && count <= 4)
8446     FORC(4) tt->val.c[c] = val >> (c << 3);
8447   else if (type == 3 && count <= 2)
8448     FORC(2) tt->val.s[c] = val >> (c << 4);
8449   else tt->val.i = val;
8450 }
8451 
8452 #define TOFF(ptr) ((char *)(&(ptr)) - (char *)th)
8453 
tiff_head(struct tiff_hdr * th,int full)8454 void CLASS tiff_head (struct tiff_hdr *th, int full)
8455 {
8456   int c, psize=0;
8457   struct tm *t;
8458 
8459   memset (th, 0, sizeof *th);
8460   th->order = htonl(0x4d4d4949) >> 16;
8461   th->magic = 42;
8462   th->ifd = 10;
8463   if (full) {
8464     tiff_set (&th->ntag, 254, 4, 1, 0);
8465     tiff_set (&th->ntag, 256, 4, 1, width);
8466     tiff_set (&th->ntag, 257, 4, 1, height);
8467     tiff_set (&th->ntag, 258, 3, colors, output_bps);
8468     if (colors > 2)
8469       th->tag[th->ntag-1].val.i = TOFF(th->bps);
8470     FORC4 th->bps[c] = output_bps;
8471     tiff_set (&th->ntag, 259, 3, 1, 1);
8472     tiff_set (&th->ntag, 262, 3, 1, 1 + (colors > 1));
8473   }
8474   tiff_set (&th->ntag, 270, 2, 512, TOFF(th->desc));
8475   tiff_set (&th->ntag, 271, 2, 64, TOFF(th->make));
8476   tiff_set (&th->ntag, 272, 2, 64, TOFF(th->model));
8477   if (full) {
8478     if (oprof) psize = ntohl(oprof[0]);
8479     tiff_set (&th->ntag, 273, 4, 1, sizeof *th + psize);
8480     tiff_set (&th->ntag, 277, 3, 1, colors);
8481     tiff_set (&th->ntag, 278, 4, 1, height);
8482     tiff_set (&th->ntag, 279, 4, 1, height*width*colors*output_bps/8);
8483   } else
8484     tiff_set (&th->ntag, 274, 3, 1, "12435867"[flip]-'0');
8485   tiff_set (&th->ntag, 282, 5, 1, TOFF(th->rat[0]));
8486   tiff_set (&th->ntag, 283, 5, 1, TOFF(th->rat[2]));
8487   tiff_set (&th->ntag, 284, 3, 1, 1);
8488   tiff_set (&th->ntag, 296, 3, 1, 2);
8489   tiff_set (&th->ntag, 305, 2, 32, TOFF(th->soft));
8490   tiff_set (&th->ntag, 306, 2, 20, TOFF(th->date));
8491   tiff_set (&th->ntag, 315, 2, 64, TOFF(th->artist));
8492   tiff_set (&th->ntag, 34665, 4, 1, TOFF(th->nexif));
8493   if (psize) tiff_set (&th->ntag, 34675, 7, psize, sizeof *th);
8494   tiff_set (&th->nexif, 33434, 5, 1, TOFF(th->rat[4]));
8495   tiff_set (&th->nexif, 33437, 5, 1, TOFF(th->rat[6]));
8496   tiff_set (&th->nexif, 34855, 3, 1, iso_speed);
8497   tiff_set (&th->nexif, 37386, 5, 1, TOFF(th->rat[8]));
8498   if (gpsdata[1]) {
8499     tiff_set (&th->ntag, 34853, 4, 1, TOFF(th->ngps));
8500     tiff_set (&th->ngps,  0, 1,  4, 0x202);
8501     tiff_set (&th->ngps,  1, 2,  2, gpsdata[29]);
8502     tiff_set (&th->ngps,  2, 5,  3, TOFF(th->gps[0]));
8503     tiff_set (&th->ngps,  3, 2,  2, gpsdata[30]);
8504     tiff_set (&th->ngps,  4, 5,  3, TOFF(th->gps[6]));
8505     tiff_set (&th->ngps,  5, 1,  1, gpsdata[31]);
8506     tiff_set (&th->ngps,  6, 5,  1, TOFF(th->gps[18]));
8507     tiff_set (&th->ngps,  7, 5,  3, TOFF(th->gps[12]));
8508     tiff_set (&th->ngps, 18, 2, 12, TOFF(th->gps[20]));
8509     tiff_set (&th->ngps, 29, 2, 12, TOFF(th->gps[23]));
8510     memcpy (th->gps, gpsdata, sizeof th->gps);
8511   }
8512   th->rat[0] = th->rat[2] = 300;
8513   th->rat[1] = th->rat[3] = 1;
8514   FORC(6) th->rat[4+c] = 1000000;
8515   th->rat[4] *= shutter;
8516   th->rat[6] *= aperture;
8517   th->rat[8] *= focal_len;
8518   strncpy (th->desc, desc, 512);
8519   strncpy (th->make, make, 64);
8520   strncpy (th->model, model, 64);
8521   strcpy (th->soft, "dcraw v"VERSION);
8522   t = localtime (&timestamp);
8523   sprintf (th->date, "%04d:%02d:%02d %02d:%02d:%02d",
8524       t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);
8525   strncpy (th->artist, artist, 64);
8526 }
8527 
jpeg_thumb()8528 void CLASS jpeg_thumb()
8529 {
8530   char *thumb;
8531   ushort exif[5];
8532   struct tiff_hdr th;
8533 
8534   thumb = (char *) malloc (thumb_length);
8535   merror (thumb, "jpeg_thumb()");
8536   fread (thumb, 1, thumb_length, ifp);
8537   fputc (0xff, ofp);
8538   fputc (0xd8, ofp);
8539   if (strcmp (thumb+6, "Exif")) {
8540     memcpy (exif, "\xff\xe1  Exif\0\0", 10);
8541     exif[1] = htons (8 + sizeof th);
8542     fwrite (exif, 1, sizeof exif, ofp);
8543     tiff_head (&th, 0);
8544     fwrite (&th, 1, sizeof th, ofp);
8545   }
8546   fwrite (thumb+2, 1, thumb_length-2, ofp);
8547   free (thumb);
8548 }
8549 
write_ppm_tiff()8550 void CLASS write_ppm_tiff()
8551 {
8552   struct tiff_hdr th;
8553   uchar *ppm;
8554   ushort *ppm2;
8555   int c, row, col, soff, rstep, cstep;
8556   int perc, val, total, white=0x2000;
8557 
8558   perc = width * height * 0.01;		/* 99th percentile white level */
8559   if (fuji_width) perc /= 2;
8560   if (!((highlight & ~2) || no_auto_bright))
8561     for (white=c=0; c < colors; c++) {
8562       for (val=0x2000, total=0; --val > 32; )
8563 	if ((total += histogram[c][val]) > perc) break;
8564       if (white < val) white = val;
8565     }
8566   gamma_curve (gamm[0], gamm[1], 2, (white << 3)/bright);
8567   iheight = height;
8568   iwidth  = width;
8569   if (flip & 4) SWAP(height,width);
8570   ppm = (uchar *) calloc (width, colors*output_bps/8);
8571   ppm2 = (ushort *) ppm;
8572   merror (ppm, "write_ppm_tiff()");
8573   if (output_tiff) {
8574     tiff_head (&th, 1);
8575     fwrite (&th, sizeof th, 1, ofp);
8576     if (oprof)
8577       fwrite (oprof, ntohl(oprof[0]), 1, ofp);
8578   } else if (colors > 3)
8579     fprintf (ofp,
8580       "P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n",
8581 	width, height, colors, (1 << output_bps)-1, cdesc);
8582   else
8583     fprintf (ofp, "P%d\n%d %d\n%d\n",
8584 	colors/2+5, width, height, (1 << output_bps)-1);
8585   soff  = flip_index (0, 0);
8586   cstep = flip_index (0, 1) - soff;
8587   rstep = flip_index (1, 0) - flip_index (0, width);
8588   for (row=0; row < height; row++, soff += rstep) {
8589     for (col=0; col < width; col++, soff += cstep)
8590       if (output_bps == 8)
8591 	   FORCC ppm [col*colors+c] = curve[image[soff][c]] >> 8;
8592       else FORCC ppm2[col*colors+c] = curve[image[soff][c]];
8593     if (output_bps == 16 && !output_tiff && htons(0x55aa) != 0x55aa)
8594       swab (ppm2, ppm2, width*colors*2);
8595     fwrite (ppm, colors*output_bps/8, width, ofp);
8596   }
8597   free (ppm);
8598 }
8599 
main(int argc,const char ** argv)8600 int CLASS main (int argc, const char **argv)
8601 {
8602   int arg, status=0;
8603   int timestamp_only=0, thumbnail_only=0, identify_only=0;
8604   int user_qual=-1, user_black=-1, user_sat=-1, user_flip=-1;
8605   int use_fuji_rotate=1, write_to_stdout=0, quality, i, c;
8606   const char *sp, *bpfile=0, *dark_frame=0, *write_ext;
8607   char opm, opt, *ofname, *cp;
8608   struct utimbuf ut;
8609 #ifndef NO_LCMS
8610   const char *cam_profile=0, *out_profile=0;
8611 #endif
8612 
8613 #ifndef LOCALTIME
8614   putenv ((char *) "TZ=UTC");
8615 #endif
8616 #ifdef LOCALEDIR
8617   setlocale (LC_CTYPE, "");
8618   setlocale (LC_MESSAGES, "");
8619   bindtextdomain ("dcraw", LOCALEDIR);
8620   textdomain ("dcraw");
8621 #endif
8622 
8623   if (argc == 1) {
8624     printf(_("\nRaw photo decoder \"dcraw\" v%s"), VERSION);
8625     printf(_("\nby Dave Coffin, dcoffin a cybercom o net\n"));
8626     printf(_("\nUsage:  %s [OPTION]... [FILE]...\n\n"), argv[0]);
8627     puts(_("-v        Print verbose messages"));
8628     puts(_("-c        Write image data to standard output"));
8629     puts(_("-e        Extract embedded thumbnail image"));
8630     puts(_("-i        Identify files without decoding them"));
8631     puts(_("-i -v     Identify files and show metadata"));
8632     puts(_("-z        Change file dates to camera timestamp"));
8633     puts(_("-w        Use camera white balance, if possible"));
8634     puts(_("-a        Average the whole image for white balance"));
8635     puts(_("-A <x y w h> Average a grey box for white balance"));
8636     puts(_("-r <r g b g> Set custom white balance"));
8637     puts(_("+M/-M     Use/don't use an embedded color matrix"));
8638     puts(_("-C <r b>  Correct chromatic aberration"));
8639     puts(_("-P <file> Fix the dead pixels listed in this file"));
8640     puts(_("-K <file> Subtract dark frame (16-bit raw PGM)"));
8641     puts(_("-k <num>  Set the darkness level"));
8642     puts(_("-S <num>  Set the saturation level"));
8643     puts(_("-n <num>  Set threshold for wavelet denoising"));
8644     puts(_("-H [0-9]  Highlight mode (0=clip, 1=unclip, 2=blend, 3+=rebuild)"));
8645     puts(_("-t [0-7]  Flip image (0=none, 3=180, 5=90CCW, 6=90CW)"));
8646     puts(_("-o [0-5]  Output colorspace (raw,sRGB,Adobe,Wide,ProPhoto,XYZ)"));
8647 #ifndef NO_LCMS
8648     puts(_("-o <file> Apply output ICC profile from file"));
8649     puts(_("-p <file> Apply camera ICC profile from file or \"embed\""));
8650 #endif
8651     puts(_("-d        Document mode (no color, no interpolation)"));
8652     puts(_("-D        Document mode without scaling (totally raw)"));
8653     puts(_("-j        Don't stretch or rotate raw pixels"));
8654     puts(_("-W        Don't automatically brighten the image"));
8655     puts(_("-b <num>  Adjust brightness (default = 1.0)"));
8656     puts(_("-g <p ts> Set custom gamma curve (default = 2.222 4.5)"));
8657     puts(_("-q [0-3]  Set the interpolation quality"));
8658     puts(_("-h        Half-size color image (twice as fast as \"-q 0\")"));
8659     puts(_("-f        Interpolate RGGB as four colors"));
8660     puts(_("-m <num>  Apply a 3x3 median filter to R-G and B-G"));
8661     puts(_("-s [0..N-1] Select one raw image or \"all\" from each file"));
8662     puts(_("-6        Write 16-bit instead of 8-bit"));
8663     puts(_("-4        Linear 16-bit, same as \"-6 -W -g 1 1\""));
8664     puts(_("-T        Write TIFF instead of PPM"));
8665     puts("");
8666     return 1;
8667   }
8668   argv[argc] = "";
8669   for (arg=1; (((opm = argv[arg][0]) - 2) | 2) == '+'; ) {
8670     opt = argv[arg++][1];
8671     if ((cp = (char *) strchr (sp="nbrkStqmHACg", opt)))
8672       for (i=0; i < "114111111422"[cp-sp]-'0'; i++)
8673 	if (!isdigit(argv[arg+i][0])) {
8674 	  fprintf (stderr,_("Non-numeric argument to \"-%c\"\n"), opt);
8675 	  return 1;
8676 	}
8677     switch (opt) {
8678       case 'n':  threshold   = atof(argv[arg++]);  break;
8679       case 'b':  bright      = atof(argv[arg++]);  break;
8680       case 'r':
8681 	   FORC4 user_mul[c] = atof(argv[arg++]);  break;
8682       case 'C':  aber[0] = 1 / atof(argv[arg++]);
8683 		 aber[2] = 1 / atof(argv[arg++]);  break;
8684       case 'g':  gamm[0] =     atof(argv[arg++]);
8685 		 gamm[1] =     atof(argv[arg++]);
8686 		 if (gamm[0]) gamm[0] = 1/gamm[0]; break;
8687       case 'k':  user_black  = atoi(argv[arg++]);  break;
8688       case 'S':  user_sat    = atoi(argv[arg++]);  break;
8689       case 't':  user_flip   = atoi(argv[arg++]);  break;
8690       case 'q':  user_qual   = atoi(argv[arg++]);  break;
8691       case 'm':  med_passes  = atoi(argv[arg++]);  break;
8692       case 'H':  highlight   = atoi(argv[arg++]);  break;
8693       case 's':
8694 	shot_select = abs(atoi(argv[arg]));
8695 	multi_out = !strcmp(argv[arg++],"all");
8696 	break;
8697       case 'o':
8698 	if (isdigit(argv[arg][0]) && !argv[arg][1])
8699 	  output_color = atoi(argv[arg++]);
8700 #ifndef NO_LCMS
8701 	else     out_profile = argv[arg++];
8702 	break;
8703       case 'p':  cam_profile = argv[arg++];
8704 #endif
8705 	break;
8706       case 'P':  bpfile     = argv[arg++];  break;
8707       case 'K':  dark_frame = argv[arg++];  break;
8708       case 'z':  timestamp_only    = 1;  break;
8709       case 'e':  thumbnail_only    = 1;  break;
8710       case 'i':  identify_only     = 1;  break;
8711       case 'c':  write_to_stdout   = 1;  break;
8712       case 'v':  verbose           = 1;  break;
8713       case 'h':  half_size         = 1;		/* "-h" implies "-f" */
8714       case 'f':  four_color_rgb    = 1;  break;
8715       case 'A':  FORC4 greybox[c]  = atoi(argv[arg++]);
8716       case 'a':  use_auto_wb       = 1;  break;
8717       case 'w':  use_camera_wb     = 1;  break;
8718       case 'M':  use_camera_matrix = (opm == '+');  break;
8719       case 'D':
8720       case 'd':  document_mode = 1 + (opt == 'D');
8721       case 'j':  use_fuji_rotate   = 0;  break;
8722       case 'W':  no_auto_bright    = 1;  break;
8723       case 'T':  output_tiff       = 1;  break;
8724       case '4':  gamm[0] = gamm[1] =
8725 		 no_auto_bright    = 1;
8726       case '6':  output_bps       = 16;  break;
8727       default:
8728 	fprintf (stderr,_("Unknown option \"-%c\".\n"), opt);
8729 	return 1;
8730     }
8731   }
8732   if (use_camera_matrix < 0)
8733       use_camera_matrix = use_camera_wb;
8734   if (arg == argc) {
8735     fprintf (stderr,_("No files to process.\n"));
8736     return 1;
8737   }
8738   if (write_to_stdout) {
8739     if (isatty(1)) {
8740       fprintf (stderr,_("Will not write an image to the terminal!\n"));
8741       return 1;
8742     }
8743 #if defined(WIN32) || defined(DJGPP) || defined(__CYGWIN__)
8744     if (setmode(1,O_BINARY) < 0) {
8745       perror ("setmode()");
8746       return 1;
8747     }
8748 #endif
8749   }
8750   for ( ; arg < argc; arg++) {
8751     status = 1;
8752     image = 0;
8753     oprof = 0;
8754     meta_data = ofname = 0;
8755     ofp = stdout;
8756     if (setjmp (failure)) {
8757       if (fileno(ifp) > 2) fclose(ifp);
8758       if (fileno(ofp) > 2) fclose(ofp);
8759       status = 1;
8760       goto cleanup;
8761     }
8762     ifname = argv[arg];
8763     if (!(ifp = fopen (ifname, "rb"))) {
8764       perror (ifname);
8765       continue;
8766     }
8767     status = (identify(),!is_raw);
8768     if (user_flip >= 0)
8769       flip = user_flip;
8770     switch ((flip+3600) % 360) {
8771       case 270:  flip = 5;  break;
8772       case 180:  flip = 3;  break;
8773       case  90:  flip = 6;
8774     }
8775     if (timestamp_only) {
8776       if ((status = !timestamp))
8777 	fprintf (stderr,_("%s has no timestamp.\n"), ifname);
8778       else if (identify_only)
8779 	printf ("%10ld%10d %s\n", (long) timestamp, shot_order, ifname);
8780       else {
8781 	if (verbose)
8782 	  fprintf (stderr,_("%s time set to %d.\n"), ifname, (int) timestamp);
8783 	ut.actime = ut.modtime = timestamp;
8784 	utime (ifname, &ut);
8785       }
8786       goto next;
8787     }
8788     write_fun = &CLASS write_ppm_tiff;
8789     if (thumbnail_only) {
8790       if ((status = !thumb_offset)) {
8791 	fprintf (stderr,_("%s has no thumbnail.\n"), ifname);
8792 	goto next;
8793       } else if (thumb_load_raw) {
8794 	load_raw = thumb_load_raw;
8795 	data_offset = thumb_offset;
8796 	height = thumb_height;
8797 	width  = thumb_width;
8798 	filters = 0;
8799       } else {
8800 	fseek (ifp, thumb_offset, SEEK_SET);
8801 	write_fun = write_thumb;
8802 	goto thumbnail;
8803       }
8804     }
8805     if (load_raw == &CLASS kodak_ycbcr_load_raw) {
8806       height += height & 1;
8807       width  += width  & 1;
8808     }
8809     if (identify_only && verbose && make[0]) {
8810       printf (_("\nFilename: %s\n"), ifname);
8811       printf (_("Timestamp: %s"), ctime(&timestamp));
8812       printf (_("Camera: %s %s\n"), make, model);
8813       if (artist[0])
8814 	printf (_("Owner: %s\n"), artist);
8815       if (dng_version) {
8816 	printf (_("DNG Version: "));
8817 	for (i=24; i >= 0; i -= 8)
8818 	  printf ("%d%c", dng_version >> i & 255, i ? '.':'\n');
8819       }
8820       printf (_("ISO speed: %d\n"), (int) iso_speed);
8821       printf (_("Shutter: "));
8822       if (shutter > 0 && shutter < 1)
8823 	shutter = (printf ("1/"), 1 / shutter);
8824       printf (_("%0.1f sec\n"), shutter);
8825       printf (_("Aperture: f/%0.1f\n"), aperture);
8826       printf (_("Focal length: %0.1f mm\n"), focal_len);
8827       printf (_("Embedded ICC profile: %s\n"), profile_length ? _("yes"):_("no"));
8828       printf (_("Number of raw images: %d\n"), is_raw);
8829       if (pixel_aspect != 1)
8830 	printf (_("Pixel Aspect Ratio: %0.6f\n"), pixel_aspect);
8831       if (thumb_offset)
8832 	printf (_("Thumb size:  %4d x %d\n"), thumb_width, thumb_height);
8833       printf (_("Full size:   %4d x %d\n"), raw_width, raw_height);
8834     } else if (!is_raw)
8835       fprintf (stderr,_("Cannot decode file %s\n"), ifname);
8836     if (!is_raw) goto next;
8837     shrink = filters && (half_size ||
8838 	((threshold || aber[0] != 1 || aber[2] != 1) && !identify_only));
8839     iheight = (height + shrink) >> shrink;
8840     iwidth  = (width  + shrink) >> shrink;
8841     if (identify_only) {
8842       if (verbose) {
8843 	if (use_fuji_rotate) {
8844 	  if (fuji_width) {
8845 	    fuji_width = (fuji_width - 1 + shrink) >> shrink;
8846 	    iwidth = fuji_width / sqrt(0.5);
8847 	    iheight = (iheight - fuji_width) / sqrt(0.5);
8848 	  } else {
8849 	    if (pixel_aspect < 1) iheight = iheight / pixel_aspect + 0.5;
8850 	    if (pixel_aspect > 1) iwidth  = iwidth  * pixel_aspect + 0.5;
8851 	  }
8852 	}
8853 	if (flip & 4)
8854 	  SWAP(iheight,iwidth);
8855 	printf (_("Image size:  %4d x %d\n"), width, height);
8856 	printf (_("Output size: %4d x %d\n"), iwidth, iheight);
8857 	printf (_("Raw colors: %d"), colors);
8858 	if (filters) {
8859 	  printf (_("\nFilter pattern: "));
8860 	  for (i=0; i < 16; i++)
8861 	    putchar (cdesc[fc(i >> 1,i & 1)]);
8862 	}
8863 	printf (_("\nDaylight multipliers:"));
8864 	FORCC printf (" %f", pre_mul[c]);
8865 	if (cam_mul[0] > 0) {
8866 	  printf (_("\nCamera multipliers:"));
8867 	  FORC4 printf (" %f", cam_mul[c]);
8868 	}
8869 	putchar ('\n');
8870       } else
8871 	printf (_("%s is a %s %s image.\n"), ifname, make, model);
8872 next:
8873       fclose(ifp);
8874       continue;
8875     }
8876     if (use_camera_matrix && cmatrix[0][0] > 0.25) {
8877       memcpy (rgb_cam, cmatrix, sizeof cmatrix);
8878       raw_color = 0;
8879     }
8880     image = (ushort (*)[4]) calloc (iheight*iwidth, sizeof *image);
8881     merror (image, "main()");
8882     if (meta_length) {
8883       meta_data = (char *) malloc (meta_length);
8884       merror (meta_data, "main()");
8885     }
8886     if (verbose)
8887       fprintf (stderr,_("Loading %s %s image from %s ...\n"),
8888 	make, model, ifname);
8889     if (shot_select >= is_raw)
8890       fprintf (stderr,_("%s: \"-s %d\" requests a nonexistent image!\n"),
8891 	ifname, shot_select);
8892     fseeko (ifp, data_offset, SEEK_SET);
8893     (*load_raw)();
8894     if (zero_is_bad) remove_zeroes();
8895     bad_pixels (bpfile);
8896     if (dark_frame) subtract (dark_frame);
8897     quality = 2 + !fuji_width;
8898     if (user_qual >= 0) quality = user_qual;
8899     i = cblack[3];
8900     FORC3 if (i > cblack[c]) i = cblack[c];
8901     FORC4 cblack[c] -= i;
8902     black += i;
8903     if (user_black >= 0) black = user_black;
8904     if (user_sat > 0) maximum = user_sat;
8905 #ifdef COLORCHECK
8906     colorcheck();
8907 #endif
8908     if (is_foveon && !document_mode) foveon_interpolate();
8909     if (!is_foveon && document_mode < 2) scale_colors();
8910     pre_interpolate();
8911     if (filters && !document_mode) {
8912       if (quality == 0)
8913 	lin_interpolate();
8914       else if (quality == 1 || colors > 3)
8915 	vng_interpolate();
8916       else if (quality == 2)
8917 	ppg_interpolate();
8918       else ahd_interpolate();
8919     }
8920     if (mix_green)
8921       for (colors=3, i=0; i < height*width; i++)
8922 	image[i][1] = (image[i][1] + image[i][3]) >> 1;
8923     if (!is_foveon && colors == 3) median_filter();
8924     if (!is_foveon && highlight == 2) blend_highlights();
8925     if (!is_foveon && highlight > 2) recover_highlights();
8926     if (use_fuji_rotate) fuji_rotate();
8927 #ifndef NO_LCMS
8928     if (cam_profile) apply_profile (cam_profile, out_profile);
8929 #endif
8930     convert_to_rgb();
8931     if (use_fuji_rotate) stretch();
8932 thumbnail:
8933     if (write_fun == &CLASS jpeg_thumb)
8934       write_ext = ".jpg";
8935     else if (output_tiff && write_fun == &CLASS write_ppm_tiff)
8936       write_ext = ".tiff";
8937     else
8938       write_ext = ".pgm\0.ppm\0.ppm\0.pam" + colors*5-5;
8939     ofname = (char *) malloc (strlen(ifname) + 64);
8940     merror (ofname, "main()");
8941     if (write_to_stdout)
8942       strcpy (ofname,_("standard output"));
8943     else {
8944       strcpy (ofname, ifname);
8945       if ((cp = strrchr (ofname, '.'))) *cp = 0;
8946       if (multi_out)
8947 	sprintf (ofname+strlen(ofname), "_%0*d",
8948 		snprintf(0,0,"%d",is_raw-1), shot_select);
8949       if (thumbnail_only)
8950 	strcat (ofname, ".thumb");
8951       strcat (ofname, write_ext);
8952       ofp = fopen (ofname, "wb");
8953       if (!ofp) {
8954 	status = 1;
8955 	perror (ofname);
8956 	goto cleanup;
8957       }
8958     }
8959     if (verbose)
8960       fprintf (stderr,_("Writing data to %s ...\n"), ofname);
8961     (*write_fun)();
8962     fclose(ifp);
8963     if (ofp != stdout) fclose(ofp);
8964 cleanup:
8965     if (meta_data) free (meta_data);
8966     if (ofname) free (ofname);
8967     if (oprof) free (oprof);
8968     if (image) free (image);
8969     if (multi_out) {
8970       if (++shot_select < is_raw) arg--;
8971       else shot_select = 0;
8972     }
8973   }
8974   return status;
8975 }
8976