1 /*
2    dcraw.c -- Dave Coffin's raw photo decoder
3    Copyright 1997-2011 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.445 $
23    $Date: 2011/10/07 01:00:37 $
24  */
25 
26 #define DCRAW_VERSION "9.11"
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 #ifdef NODEPS
46 #define NO_JASPER
47 #define NO_JPEG
48 #define NO_LCMS
49 #endif
50 #ifndef NO_JASPER
51 #include <jasper/jasper.h>	/* Decode RED camera movies */
52 #endif
53 #ifndef NO_JPEG
54 #include <jpeglib.h>		/* Decode compressed Kodak DC120 photos */
55 #endif
56 #ifndef NO_LCMS
57 #include <lcms.h>		/* Support color profiles */
58 #endif
59 #ifdef LOCALEDIR
60 #include <libintl.h>
61 #define _(String) gettext(String)
62 #else
63 #define _(String) (String)
64 #endif
65 
66 #if defined(DJGPP) || defined(__MINGW32__)
67 #define fseeko fseek
68 #define ftello ftell
69 #else
70 #define fgetc getc_unlocked
71 #endif
72 #ifdef __CYGWIN__
73 #include <io.h>
74 #endif
75 #ifdef WIN32
76 #include <sys/utime.h>
77 #include <winsock2.h>
78 #pragma comment(lib, "ws2_32.lib")
79 #define snprintf _snprintf
80 #define strcasecmp stricmp
81 #define strncasecmp strnicmp
82 typedef __int64 INT64;
83 typedef unsigned __int64 UINT64;
84 #else
85 #include <unistd.h>
86 #include <utime.h>
87 #include <netinet/in.h>
88 typedef long long INT64;
89 typedef unsigned long long UINT64;
90 #endif
91 
92 #ifdef LJPEG_DECODE
93 #error Please compile dcraw.c by itself.
94 #error Do not link it with ljpeg_decode.
95 #endif
96 
97 #ifndef LONG_BIT
98 #define LONG_BIT (8 * sizeof (long))
99 #endif
100 
101 #if !defined(uchar)
102 #define uchar unsigned char
103 #endif
104 #if !defined(ushort)
105 #define ushort unsigned short
106 #endif
107 
108 /*
109    All global variables are defined here, and all functions that
110    access them are prefixed with "CLASS".  Note that a thread-safe
111    C++ class cannot have non-const static local variables.
112  */
113 FILE *ifp, *ofp;
114 short order;
115 const char *ifname;
116 char *meta_data;
117 char cdesc[5], desc[512], make[64], model[64], model2[64], artist[64];
118 float flash_used, canon_ev, iso_speed, shutter, aperture, focal_len;
119 time_t timestamp;
120 unsigned shot_order, kodak_cbpp, filters, exif_cfa, unique_id;
121 off_t    strip_offset, data_offset;
122 off_t    thumb_offset, meta_offset, profile_offset;
123 unsigned thumb_length, meta_length, profile_length;
124 unsigned thumb_misc, *oprof, fuji_layout, shot_select=0, multi_out=0;
125 unsigned tiff_nifds, tiff_samples, tiff_bps, tiff_compress;
126 unsigned black, cblack[8], maximum, mix_green, raw_color, zero_is_bad;
127 unsigned zero_after_ff, is_raw, dng_version, is_foveon, data_error;
128 unsigned tile_width, tile_length, gpsdata[32], load_flags;
129 ushort raw_height, raw_width, height, width, top_margin, left_margin;
130 ushort shrink, iheight, iwidth, fuji_width, thumb_width, thumb_height;
131 int flip, tiff_flip, colors;
132 double pixel_aspect, aber[4]={1,1,1,1}, gamm[6]={ 0.45,4.5,0,0,0,0 };
133 ushort (*image)[4], white[8][8], curve[0x10000], cr2_slice[3], sraw_mul[4];
134 float bright=1, user_mul[4]={0,0,0,0}, threshold=0;
135 int half_size=0, four_color_rgb=0, document_mode=0, highlight=0;
136 int verbose=0, use_auto_wb=0, use_camera_wb=0, use_camera_matrix=-1;
137 int output_color=1, output_bps=8, output_tiff=0, med_passes=0;
138 int no_auto_bright=0;
139 unsigned greybox[4] = { 0, 0, UINT_MAX, UINT_MAX };
140 float cam_mul[4], pre_mul[4], cmatrix[3][4], rgb_cam[3][4];
141 const double xyz_rgb[3][3] = {			/* XYZ from RGB */
142   { 0.412453, 0.357580, 0.180423 },
143   { 0.212671, 0.715160, 0.072169 },
144   { 0.019334, 0.119193, 0.950227 } };
145 const float d65_white[3] = { 0.950456, 1, 1.088754 };
146 int histogram[4][0x2000];
147 void (*write_thumb)(), (*write_fun)();
148 void (*load_raw)(), (*thumb_load_raw)();
149 jmp_buf failure;
150 
151 struct decode {
152   struct decode *branch[2];
153   int leaf;
154 } first_decode[2048], *second_decode, *free_decode;
155 
156 struct tiff_ifd {
157   int width, height, bps, comp, phint, offset, flip, samples, bytes;
158 } tiff_ifd[10];
159 
160 struct ph1 {
161   int format, key_off, black, black_off, split_col, tag_21a;
162   float tag_210;
163 } ph1;
164 
165 #define CLASS
166 
167 #define FORC(cnt) for (c=0; c < cnt; c++)
168 #define FORC3 FORC(3)
169 #define FORC4 FORC(4)
170 #define FORCC FORC(colors)
171 
172 #define SQR(x) ((x)*(x))
173 #define ABS(x) (((int)(x) ^ ((int)(x) >> 31)) - ((int)(x) >> 31))
174 #define MIN(a,b) ((a) < (b) ? (a) : (b))
175 #define MAX(a,b) ((a) > (b) ? (a) : (b))
176 #define LIM(x,min,max) MAX(min,MIN(x,max))
177 #define ULIM(x,y,z) ((y) < (z) ? LIM(x,y,z) : LIM(x,z,y))
178 #define CLIP(x) LIM(x,0,65535)
179 #define SWAP(a,b) { a=a+b; b=a-b; a=a-b; }
180 
181 /*
182    In order to inline this calculation, I make the risky
183    assumption that all filter patterns can be described
184    by a repeating pattern of eight rows and two columns
185 
186    Do not use the FC or BAYER macros with the Leaf CatchLight,
187    because its pattern is 16x16, not 2x8.
188 
189    Return values are either 0/1/2/3 = G/M/C/Y or 0/1/2/3 = R/G1/B/G2
190 
191 	PowerShot 600	PowerShot A50	PowerShot Pro70	Pro90 & G1
192 	0xe1e4e1e4:	0x1b4e4b1e:	0x1e4b4e1b:	0xb4b4b4b4:
193 
194 	  0 1 2 3 4 5	  0 1 2 3 4 5	  0 1 2 3 4 5	  0 1 2 3 4 5
195 	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
196 	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
197 	2 M G M G M G	2 Y C Y C Y C	2 C Y C Y C Y
198 	3 C Y C Y C Y	3 G M G M G M	3 G M G M G M
199 			4 C Y C Y C Y	4 Y C Y C Y C
200 	PowerShot A5	5 G M G M G M	5 G M G M G M
201 	0x1e4e1e4e:	6 Y C Y C Y C	6 C Y C Y C Y
202 			7 M G M G M G	7 M G M G M G
203 	  0 1 2 3 4 5
204 	0 C Y C Y C Y
205 	1 G M G M G M
206 	2 C Y C Y C Y
207 	3 M G M G M G
208 
209    All RGB cameras use one of these Bayer grids:
210 
211 	0x16161616:	0x61616161:	0x49494949:	0x94949494:
212 
213 	  0 1 2 3 4 5	  0 1 2 3 4 5	  0 1 2 3 4 5	  0 1 2 3 4 5
214 	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
215 	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
216 	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
217 	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
218  */
219 
220 #define FC(row,col) \
221 	(filters >> ((((row) << 1 & 14) + ((col) & 1)) << 1) & 3)
222 
223 #define BAYER(row,col) \
224 	image[((row) >> shrink)*iwidth + ((col) >> shrink)][FC(row,col)]
225 
226 #define BAYER2(row,col) \
227 	image[((row) >> shrink)*iwidth + ((col) >> shrink)][fc(row,col)]
228 
fc(int row,int col)229 int CLASS fc (int row, int col)
230 {
231   static const char filter[16][16] =
232   { { 2,1,1,3,2,3,2,0,3,2,3,0,1,2,1,0 },
233     { 0,3,0,2,0,1,3,1,0,1,1,2,0,3,3,2 },
234     { 2,3,3,2,3,1,1,3,3,1,2,1,2,0,0,3 },
235     { 0,1,0,1,0,2,0,2,2,0,3,0,1,3,2,1 },
236     { 3,1,1,2,0,1,0,2,1,3,1,3,0,1,3,0 },
237     { 2,0,0,3,3,2,3,1,2,0,2,0,3,2,2,1 },
238     { 2,3,3,1,2,1,2,1,2,1,1,2,3,0,0,1 },
239     { 1,0,0,2,3,0,0,3,0,3,0,3,2,1,2,3 },
240     { 2,3,3,1,1,2,1,0,3,2,3,0,2,3,1,3 },
241     { 1,0,2,0,3,0,3,2,0,1,1,2,0,1,0,2 },
242     { 0,1,1,3,3,2,2,1,1,3,3,0,2,1,3,2 },
243     { 2,3,2,0,0,1,3,0,2,0,1,2,3,0,1,0 },
244     { 1,3,1,2,3,2,3,2,0,2,0,1,1,0,3,0 },
245     { 0,2,0,3,1,0,0,1,1,3,3,2,3,2,2,1 },
246     { 2,1,3,2,3,1,2,1,0,3,0,2,0,2,0,2 },
247     { 0,3,1,0,0,2,0,3,2,1,3,1,1,3,1,3 } };
248 
249   if (filters != 1) return FC(row,col);
250   return filter[(row+top_margin) & 15][(col+left_margin) & 15];
251 }
252 
253 #ifndef __GLIBC__
my_memmem(char * haystack,size_t haystacklen,char * needle,size_t needlelen)254 char *my_memmem (char *haystack, size_t haystacklen,
255 	      char *needle, size_t needlelen)
256 {
257   char *c;
258   for (c = haystack; c <= haystack + haystacklen - needlelen; c++)
259     if (!memcmp (c, needle, needlelen))
260       return c;
261   return 0;
262 }
263 #define memmem my_memmem
264 #endif
265 
merror(void * ptr,const char * where)266 void CLASS merror (void *ptr, const char *where)
267 {
268   if (ptr) return;
269   fprintf (stderr,_("%s: Out of memory in %s\n"), ifname, where);
270   longjmp (failure, 1);
271 }
272 
derror()273 void CLASS derror()
274 {
275   if (!data_error) {
276     fprintf (stderr, "%s: ", ifname);
277     if (feof(ifp))
278       fprintf (stderr,_("Unexpected end of file\n"));
279     else
280       fprintf (stderr,_("Corrupt data near 0x%llx\n"), (INT64) ftello(ifp));
281   }
282   data_error++;
283 }
284 
sget2(uchar * s)285 ushort CLASS sget2 (uchar *s)
286 {
287   if (order == 0x4949)		/* "II" means little-endian */
288     return s[0] | s[1] << 8;
289   else				/* "MM" means big-endian */
290     return s[0] << 8 | s[1];
291 }
292 
get2()293 ushort CLASS get2()
294 {
295   uchar str[2] = { 0xff,0xff };
296   fread (str, 1, 2, ifp);
297   return sget2(str);
298 }
299 
sget4(uchar * s)300 unsigned CLASS sget4 (uchar *s)
301 {
302   if (order == 0x4949)
303     return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24;
304   else
305     return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3];
306 }
307 #define sget4(s) sget4((uchar *)s)
308 
get4()309 unsigned CLASS get4()
310 {
311   uchar str[4] = { 0xff,0xff,0xff,0xff };
312   fread (str, 1, 4, ifp);
313   return sget4(str);
314 }
315 
getint(int type)316 unsigned CLASS getint (int type)
317 {
318   return type == 3 ? get2() : get4();
319 }
320 
int_to_float(int i)321 float CLASS int_to_float (int i)
322 {
323   union { int i; float f; } u;
324   u.i = i;
325   return u.f;
326 }
327 
getreal(int type)328 double CLASS getreal (int type)
329 {
330   union { char c[8]; double d; } u;
331   int i, rev;
332 
333   switch (type) {
334     case 3: return (unsigned short) get2();
335     case 4: return (unsigned int) get4();
336     case 5:  u.d = (unsigned int) get4();
337       return u.d / (unsigned int) get4();
338     case 8: return (signed short) get2();
339     case 9: return (signed int) get4();
340     case 10: u.d = (signed int) get4();
341       return u.d / (signed int) get4();
342     case 11: return int_to_float (get4());
343     case 12:
344       rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234));
345       for (i=0; i < 8; i++)
346 	u.c[i ^ rev] = fgetc(ifp);
347       return u.d;
348     default: return fgetc(ifp);
349   }
350 }
351 
read_shorts(ushort * pixel,int count)352 void CLASS read_shorts (ushort *pixel, int count)
353 {
354   if (fread (pixel, 2, count, ifp) < count) derror();
355   if ((order == 0x4949) == (ntohs(0x1234) == 0x1234))
356     swab (pixel, pixel, count*2);
357 }
358 
canon_600_fixed_wb(int temp)359 void CLASS canon_600_fixed_wb (int temp)
360 {
361   static const short mul[4][5] = {
362     {  667, 358,397,565,452 },
363     {  731, 390,367,499,517 },
364     { 1119, 396,348,448,537 },
365     { 1399, 485,431,508,688 } };
366   int lo, hi, i;
367   float frac=0;
368 
369   for (lo=4; --lo; )
370     if (*mul[lo] <= temp) break;
371   for (hi=0; hi < 3; hi++)
372     if (*mul[hi] >= temp) break;
373   if (lo != hi)
374     frac = (float) (temp - *mul[lo]) / (*mul[hi] - *mul[lo]);
375   for (i=1; i < 5; i++)
376     pre_mul[i-1] = 1 / (frac * mul[hi][i] + (1-frac) * mul[lo][i]);
377 }
378 
379 /* Return values:  0 = white  1 = near white  2 = not white */
canon_600_color(int ratio[2],int mar)380 int CLASS canon_600_color (int ratio[2], int mar)
381 {
382   int clipped=0, target, miss;
383 
384   if (flash_used) {
385     if (ratio[1] < -104)
386       { ratio[1] = -104; clipped = 1; }
387     if (ratio[1] >   12)
388       { ratio[1] =   12; clipped = 1; }
389   } else {
390     if (ratio[1] < -264 || ratio[1] > 461) return 2;
391     if (ratio[1] < -50)
392       { ratio[1] = -50; clipped = 1; }
393     if (ratio[1] > 307)
394       { ratio[1] = 307; clipped = 1; }
395   }
396   target = flash_used || ratio[1] < 197
397 	? -38 - (398 * ratio[1] >> 10)
398 	: -123 + (48 * ratio[1] >> 10);
399   if (target - mar <= ratio[0] &&
400       target + 20  >= ratio[0] && !clipped) return 0;
401   miss = target - ratio[0];
402   if (abs(miss) >= mar*4) return 2;
403   if (miss < -20) miss = -20;
404   if (miss > mar) miss = mar;
405   ratio[0] = target - miss;
406   return 1;
407 }
408 
canon_600_auto_wb()409 void CLASS canon_600_auto_wb()
410 {
411   int mar, row, col, i, j, st, count[] = { 0,0 };
412   int test[8], total[2][8], ratio[2][2], stat[2];
413 
414   memset (&total, 0, sizeof total);
415   i = canon_ev + 0.5;
416   if      (i < 10) mar = 150;
417   else if (i > 12) mar = 20;
418   else mar = 280 - 20 * i;
419   if (flash_used) mar = 80;
420   for (row=14; row < height-14; row+=4)
421     for (col=10; col < width; col+=2) {
422       for (i=0; i < 8; i++)
423 	test[(i & 4) + FC(row+(i >> 1),col+(i & 1))] =
424 		    BAYER(row+(i >> 1),col+(i & 1));
425       for (i=0; i < 8; i++)
426 	if (test[i] < 150 || test[i] > 1500) goto next;
427       for (i=0; i < 4; i++)
428 	if (abs(test[i] - test[i+4]) > 50) goto next;
429       for (i=0; i < 2; i++) {
430 	for (j=0; j < 4; j+=2)
431 	  ratio[i][j >> 1] = ((test[i*4+j+1]-test[i*4+j]) << 10) / test[i*4+j];
432 	stat[i] = canon_600_color (ratio[i], mar);
433       }
434       if ((st = stat[0] | stat[1]) > 1) goto next;
435       for (i=0; i < 2; i++)
436 	if (stat[i])
437 	  for (j=0; j < 2; j++)
438 	    test[i*4+j*2+1] = test[i*4+j*2] * (0x400 + ratio[i][j]) >> 10;
439       for (i=0; i < 8; i++)
440 	total[st][i] += test[i];
441       count[st]++;
442 next: ;
443     }
444   if (count[0] | count[1]) {
445     st = count[0]*200 < count[1];
446     for (i=0; i < 4; i++)
447       pre_mul[i] = 1.0 / (total[st][i] + total[st][i+4]);
448   }
449 }
450 
canon_600_coeff()451 void CLASS canon_600_coeff()
452 {
453   static const short table[6][12] = {
454     { -190,702,-1878,2390,   1861,-1349,905,-393, -432,944,2617,-2105  },
455     { -1203,1715,-1136,1648, 1388,-876,267,245,  -1641,2153,3921,-3409 },
456     { -615,1127,-1563,2075,  1437,-925,509,3,     -756,1268,2519,-2007 },
457     { -190,702,-1886,2398,   2153,-1641,763,-251, -452,964,3040,-2528  },
458     { -190,702,-1878,2390,   1861,-1349,905,-393, -432,944,2617,-2105  },
459     { -807,1319,-1785,2297,  1388,-876,769,-257,  -230,742,2067,-1555  } };
460   int t=0, i, c;
461   float mc, yc;
462 
463   mc = pre_mul[1] / pre_mul[2];
464   yc = pre_mul[3] / pre_mul[2];
465   if (mc > 1 && mc <= 1.28 && yc < 0.8789) t=1;
466   if (mc > 1.28 && mc <= 2) {
467     if  (yc < 0.8789) t=3;
468     else if (yc <= 2) t=4;
469   }
470   if (flash_used) t=5;
471   for (raw_color = i=0; i < 3; i++)
472     FORCC rgb_cam[i][c] = table[t][i*4 + c] / 1024.0;
473 }
474 
canon_600_load_raw()475 void CLASS canon_600_load_raw()
476 {
477   uchar  data[1120], *dp;
478   ushort pixel[896], *pix;
479   int irow, row, col, val;
480   static const short mul[4][2] =
481   { { 1141,1145 }, { 1128,1109 }, { 1178,1149 }, { 1128,1109 } };
482 
483   for (irow=row=0; irow < height; irow++) {
484     if (fread (data, 1, raw_width*5/4, ifp) < raw_width*5/4) derror();
485     for (dp=data, pix=pixel; dp < data+1120; dp+=10, pix+=8) {
486       pix[0] = (dp[0] << 2) + (dp[1] >> 6    );
487       pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3);
488       pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3);
489       pix[3] = (dp[4] << 2) + (dp[1]      & 3);
490       pix[4] = (dp[5] << 2) + (dp[9]      & 3);
491       pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3);
492       pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3);
493       pix[7] = (dp[8] << 2) + (dp[9] >> 6    );
494     }
495     for (col=0; col < width; col++)
496       BAYER(row,col) = pixel[col];
497     for (col=width; col < raw_width; col++)
498       black += pixel[col];
499     if ((row+=2) > height) row = 1;
500   }
501   if (raw_width > width)
502     black = black / ((raw_width - width) * height) - 4;
503   for (row=0; row < height; row++)
504     for (col=0; col < width; col++) {
505       if ((val = BAYER(row,col) - black) < 0) val = 0;
506       val = val * mul[row & 3][col & 1] >> 9;
507       BAYER(row,col) = val;
508     }
509   canon_600_fixed_wb(1311);
510   canon_600_auto_wb();
511   canon_600_coeff();
512   maximum = (0x3ff - black) * 1109 >> 9;
513   black = 0;
514 }
515 
remove_zeroes()516 void CLASS remove_zeroes()
517 {
518   unsigned row, col, tot, n, r, c;
519 
520   for (row=0; row < height; row++)
521     for (col=0; col < width; col++)
522       if (BAYER(row,col) == 0) {
523 	tot = n = 0;
524 	for (r = row-2; r <= row+2; r++)
525 	  for (c = col-2; c <= col+2; c++)
526 	    if (r < height && c < width &&
527 		FC(r,c) == FC(row,col) && BAYER(r,c))
528 	      tot += (n++,BAYER(r,c));
529 	if (n) BAYER(row,col) = tot/n;
530       }
531 }
532 
canon_s2is()533 int CLASS canon_s2is()
534 {
535   unsigned row;
536 
537   for (row=0; row < 100; row++) {
538     fseek (ifp, row*3340 + 3284, SEEK_SET);
539     if (getc(ifp) > 15) return 1;
540   }
541   return 0;
542 }
543 
544 /*
545    getbits(-1) initializes the buffer
546    getbits(n) where 0 <= n <= 25 returns an n-bit integer
547  */
getbithuff(int nbits,ushort * huff)548 unsigned CLASS getbithuff (int nbits, ushort *huff)
549 {
550   static unsigned bitbuf=0;
551   static int vbits=0, reset=0;
552   unsigned c;
553 
554   if (nbits == -1)
555     return bitbuf = vbits = reset = 0;
556   if (nbits == 0 || vbits < 0) return 0;
557   while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF &&
558     !(reset = zero_after_ff && c == 0xff && fgetc(ifp))) {
559     bitbuf = (bitbuf << 8) + (uchar) c;
560     vbits += 8;
561   }
562   c = bitbuf << (32-vbits) >> (32-nbits);
563   if (huff) {
564     vbits -= huff[c] >> 8;
565     c = (uchar) huff[c];
566   } else
567     vbits -= nbits;
568   if (vbits < 0) derror();
569   return c;
570 }
571 
572 #define getbits(n) getbithuff(n,0)
573 #define gethuff(h) getbithuff(*h,h+1)
574 
575 /*
576    Construct a decode tree according the specification in *source.
577    The first 16 bytes specify how many codes should be 1-bit, 2-bit
578    3-bit, etc.  Bytes after that are the leaf values.
579 
580    For example, if the source is
581 
582     { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
583       0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff  },
584 
585    then the code is
586 
587 	00		0x04
588 	010		0x03
589 	011		0x05
590 	100		0x06
591 	101		0x02
592 	1100		0x07
593 	1101		0x01
594 	11100		0x08
595 	11101		0x09
596 	11110		0x00
597 	111110		0x0a
598 	1111110		0x0b
599 	1111111		0xff
600  */
make_decoder_ref(const uchar ** source)601 ushort * CLASS make_decoder_ref (const uchar **source)
602 {
603   int max, len, h, i, j;
604   const uchar *count;
605   ushort *huff;
606 
607   count = (*source += 16) - 17;
608   for (max=16; max && !count[max]; max--);
609   huff = (ushort *) calloc (1 + (1 << max), sizeof *huff);
610   merror (huff, "make_decoder()");
611   huff[0] = max;
612   for (h=len=1; len <= max; len++)
613     for (i=0; i < count[len]; i++, ++*source)
614       for (j=0; j < 1 << (max-len); j++)
615 	if (h <= 1 << max)
616 	  huff[h++] = len << 8 | **source;
617   return huff;
618 }
619 
make_decoder(const uchar * source)620 ushort * CLASS make_decoder (const uchar *source)
621 {
622   return make_decoder_ref (&source);
623 }
624 
crw_init_tables(unsigned table,ushort * huff[2])625 void CLASS crw_init_tables (unsigned table, ushort *huff[2])
626 {
627   static const uchar first_tree[3][29] = {
628     { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
629       0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff  },
630     { 0,2,2,3,1,1,1,1,2,0,0,0,0,0,0,0,
631       0x03,0x02,0x04,0x01,0x05,0x00,0x06,0x07,0x09,0x08,0x0a,0x0b,0xff  },
632     { 0,0,6,3,1,1,2,0,0,0,0,0,0,0,0,0,
633       0x06,0x05,0x07,0x04,0x08,0x03,0x09,0x02,0x00,0x0a,0x01,0x0b,0xff  },
634   };
635   static const uchar second_tree[3][180] = {
636     { 0,2,2,2,1,4,2,1,2,5,1,1,0,0,0,139,
637       0x03,0x04,0x02,0x05,0x01,0x06,0x07,0x08,
638       0x12,0x13,0x11,0x14,0x09,0x15,0x22,0x00,0x21,0x16,0x0a,0xf0,
639       0x23,0x17,0x24,0x31,0x32,0x18,0x19,0x33,0x25,0x41,0x34,0x42,
640       0x35,0x51,0x36,0x37,0x38,0x29,0x79,0x26,0x1a,0x39,0x56,0x57,
641       0x28,0x27,0x52,0x55,0x58,0x43,0x76,0x59,0x77,0x54,0x61,0xf9,
642       0x71,0x78,0x75,0x96,0x97,0x49,0xb7,0x53,0xd7,0x74,0xb6,0x98,
643       0x47,0x48,0x95,0x69,0x99,0x91,0xfa,0xb8,0x68,0xb5,0xb9,0xd6,
644       0xf7,0xd8,0x67,0x46,0x45,0x94,0x89,0xf8,0x81,0xd5,0xf6,0xb4,
645       0x88,0xb1,0x2a,0x44,0x72,0xd9,0x87,0x66,0xd4,0xf5,0x3a,0xa7,
646       0x73,0xa9,0xa8,0x86,0x62,0xc7,0x65,0xc8,0xc9,0xa1,0xf4,0xd1,
647       0xe9,0x5a,0x92,0x85,0xa6,0xe7,0x93,0xe8,0xc1,0xc6,0x7a,0x64,
648       0xe1,0x4a,0x6a,0xe6,0xb3,0xf1,0xd3,0xa5,0x8a,0xb2,0x9a,0xba,
649       0x84,0xa4,0x63,0xe5,0xc5,0xf3,0xd2,0xc4,0x82,0xaa,0xda,0xe4,
650       0xf2,0xca,0x83,0xa3,0xa2,0xc3,0xea,0xc2,0xe2,0xe3,0xff,0xff  },
651     { 0,2,2,1,4,1,4,1,3,3,1,0,0,0,0,140,
652       0x02,0x03,0x01,0x04,0x05,0x12,0x11,0x06,
653       0x13,0x07,0x08,0x14,0x22,0x09,0x21,0x00,0x23,0x15,0x31,0x32,
654       0x0a,0x16,0xf0,0x24,0x33,0x41,0x42,0x19,0x17,0x25,0x18,0x51,
655       0x34,0x43,0x52,0x29,0x35,0x61,0x39,0x71,0x62,0x36,0x53,0x26,
656       0x38,0x1a,0x37,0x81,0x27,0x91,0x79,0x55,0x45,0x28,0x72,0x59,
657       0xa1,0xb1,0x44,0x69,0x54,0x58,0xd1,0xfa,0x57,0xe1,0xf1,0xb9,
658       0x49,0x47,0x63,0x6a,0xf9,0x56,0x46,0xa8,0x2a,0x4a,0x78,0x99,
659       0x3a,0x75,0x74,0x86,0x65,0xc1,0x76,0xb6,0x96,0xd6,0x89,0x85,
660       0xc9,0xf5,0x95,0xb4,0xc7,0xf7,0x8a,0x97,0xb8,0x73,0xb7,0xd8,
661       0xd9,0x87,0xa7,0x7a,0x48,0x82,0x84,0xea,0xf4,0xa6,0xc5,0x5a,
662       0x94,0xa4,0xc6,0x92,0xc3,0x68,0xb5,0xc8,0xe4,0xe5,0xe6,0xe9,
663       0xa2,0xa3,0xe3,0xc2,0x66,0x67,0x93,0xaa,0xd4,0xd5,0xe7,0xf8,
664       0x88,0x9a,0xd7,0x77,0xc4,0x64,0xe2,0x98,0xa5,0xca,0xda,0xe8,
665       0xf3,0xf6,0xa9,0xb2,0xb3,0xf2,0xd2,0x83,0xba,0xd3,0xff,0xff  },
666     { 0,0,6,2,1,3,3,2,5,1,2,2,8,10,0,117,
667       0x04,0x05,0x03,0x06,0x02,0x07,0x01,0x08,
668       0x09,0x12,0x13,0x14,0x11,0x15,0x0a,0x16,0x17,0xf0,0x00,0x22,
669       0x21,0x18,0x23,0x19,0x24,0x32,0x31,0x25,0x33,0x38,0x37,0x34,
670       0x35,0x36,0x39,0x79,0x57,0x58,0x59,0x28,0x56,0x78,0x27,0x41,
671       0x29,0x77,0x26,0x42,0x76,0x99,0x1a,0x55,0x98,0x97,0xf9,0x48,
672       0x54,0x96,0x89,0x47,0xb7,0x49,0xfa,0x75,0x68,0xb6,0x67,0x69,
673       0xb9,0xb8,0xd8,0x52,0xd7,0x88,0xb5,0x74,0x51,0x46,0xd9,0xf8,
674       0x3a,0xd6,0x87,0x45,0x7a,0x95,0xd5,0xf6,0x86,0xb4,0xa9,0x94,
675       0x53,0x2a,0xa8,0x43,0xf5,0xf7,0xd4,0x66,0xa7,0x5a,0x44,0x8a,
676       0xc9,0xe8,0xc8,0xe7,0x9a,0x6a,0x73,0x4a,0x61,0xc7,0xf4,0xc6,
677       0x65,0xe9,0x72,0xe6,0x71,0x91,0x93,0xa6,0xda,0x92,0x85,0x62,
678       0xf3,0xc5,0xb2,0xa4,0x84,0xba,0x64,0xa5,0xb3,0xd2,0x81,0xe5,
679       0xd3,0xaa,0xc4,0xca,0xf2,0xb1,0xe4,0xd1,0x83,0x63,0xea,0xc3,
680       0xe2,0x82,0xf1,0xa3,0xc2,0xa1,0xc1,0xe3,0xa2,0xe1,0xff,0xff  }
681   };
682   if (table > 2) table = 2;
683   huff[0] = make_decoder ( first_tree[table]);
684   huff[1] = make_decoder (second_tree[table]);
685 }
686 
687 /*
688    Return 0 if the image starts with compressed data,
689    1 if it starts with uncompressed low-order bits.
690 
691    In Canon compressed data, 0xff is always followed by 0x00.
692  */
canon_has_lowbits()693 int CLASS canon_has_lowbits()
694 {
695   uchar test[0x4000];
696   int ret=1, i;
697 
698   fseek (ifp, 0, SEEK_SET);
699   fread (test, 1, sizeof test, ifp);
700   for (i=540; i < sizeof test - 1; i++)
701     if (test[i] == 0xff) {
702       if (test[i+1]) return 1;
703       ret=0;
704     }
705   return ret;
706 }
707 
canon_compressed_load_raw()708 void CLASS canon_compressed_load_raw()
709 {
710   ushort *pixel, *prow, *huff[2];
711   int nblocks, lowbits, i, c, row, r, col, save, val;
712   unsigned irow, icol;
713   int block, diffbuf[64], leaf, len, diff, carry=0, pnum=0, base[2];
714 
715   crw_init_tables (tiff_compress, huff);
716   pixel = (ushort *) calloc (raw_width*8, sizeof *pixel);
717   merror (pixel, "canon_compressed_load_raw()");
718   lowbits = canon_has_lowbits();
719   if (!lowbits) maximum = 0x3ff;
720   fseek (ifp, 540 + lowbits*raw_height*raw_width/4, SEEK_SET);
721   zero_after_ff = 1;
722   getbits(-1);
723   for (row=0; row < raw_height; row+=8) {
724     nblocks = MIN (8, raw_height-row) * raw_width >> 6;
725     for (block=0; block < nblocks; block++) {
726       memset (diffbuf, 0, sizeof diffbuf);
727       for (i=0; i < 64; i++ ) {
728 	leaf = gethuff(huff[i > 0]);
729 	if (leaf == 0 && i) break;
730 	if (leaf == 0xff) continue;
731 	i  += leaf >> 4;
732 	len = leaf & 15;
733 	if (len == 0) continue;
734 	diff = getbits(len);
735 	if ((diff & (1 << (len-1))) == 0)
736 	  diff -= (1 << len) - 1;
737 	if (i < 64) diffbuf[i] = diff;
738       }
739       diffbuf[0] += carry;
740       carry = diffbuf[0];
741       for (i=0; i < 64; i++ ) {
742 	if (pnum++ % raw_width == 0)
743 	  base[0] = base[1] = 512;
744 	if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10)
745 	  derror();
746       }
747     }
748     if (lowbits) {
749       save = ftell(ifp);
750       fseek (ifp, 26 + row*raw_width/4, SEEK_SET);
751       for (prow=pixel, i=0; i < raw_width*2; i++) {
752 	c = fgetc(ifp);
753 	for (r=0; r < 8; r+=2, prow++) {
754 	  val = (*prow << 2) + ((c >> r) & 3);
755 	  if (raw_width == 2672 && val < 512) val += 2;
756 	  *prow = val;
757 	}
758       }
759       fseek (ifp, save, SEEK_SET);
760     }
761     for (r=0; r < 8; r++) {
762       irow = row - top_margin + r;
763       if (irow >= height) continue;
764       for (col=0; col < raw_width; col++) {
765 	icol = col - left_margin;
766 	c = FC(irow,icol);
767 	if (icol < width)
768 	  BAYER(irow,icol) = pixel[r*raw_width+col];
769 	else if (col > 1 && (unsigned) (col-left_margin+2) > width+3)
770 	  cblack[c] += (cblack[4+c]++,pixel[r*raw_width+col]);
771       }
772     }
773   }
774   free (pixel);
775   FORC(2) free (huff[c]);
776   FORC4 if (cblack[4+c]) cblack[c] /= cblack[4+c];
777 }
778 
779 /*
780    Not a full implementation of Lossless JPEG, just
781    enough to decode Canon, Kodak and Adobe DNG images.
782  */
783 struct jhead {
784   int bits, high, wide, clrs, sraw, psv, restart, vpred[6];
785   ushort *huff[6], *free[4], *row;
786 };
787 
ljpeg_start(struct jhead * jh,int info_only)788 int CLASS ljpeg_start (struct jhead *jh, int info_only)
789 {
790   int c, tag, len;
791   uchar data[0x10000];
792   const uchar *dp;
793 
794   memset (jh, 0, sizeof *jh);
795   jh->restart = INT_MAX;
796   fread (data, 2, 1, ifp);
797   if (data[1] != 0xd8) return 0;
798   do {
799     fread (data, 2, 2, ifp);
800     tag =  data[0] << 8 | data[1];
801     len = (data[2] << 8 | data[3]) - 2;
802     if (tag <= 0xff00) return 0;
803     fread (data, 1, len, ifp);
804     switch (tag) {
805       case 0xffc3:
806 	jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3;
807       case 0xffc0:
808 	jh->bits = data[0];
809 	jh->high = data[1] << 8 | data[2];
810 	jh->wide = data[3] << 8 | data[4];
811 	jh->clrs = data[5] + jh->sraw;
812 	if (len == 9 && !dng_version) getc(ifp);
813 	break;
814       case 0xffc4:
815 	if (info_only) break;
816 	for (dp = data; dp < data+len && (c = *dp++) < 4; )
817 	  jh->free[c] = jh->huff[c] = make_decoder_ref (&dp);
818 	break;
819       case 0xffda:
820 	jh->psv = data[1+data[0]*2];
821 	jh->bits -= data[3+data[0]*2] & 15;
822 	break;
823       case 0xffdd:
824 	jh->restart = data[0] << 8 | data[1];
825     }
826   } while (tag != 0xffda);
827   if (info_only) return 1;
828   FORC(5) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c];
829   if (jh->sraw) {
830     FORC(4)        jh->huff[2+c] = jh->huff[1];
831     FORC(jh->sraw) jh->huff[1+c] = jh->huff[0];
832   }
833   jh->row = (ushort *) calloc (jh->wide*jh->clrs, 4);
834   merror (jh->row, "ljpeg_start()");
835   return zero_after_ff = 1;
836 }
837 
ljpeg_end(struct jhead * jh)838 void CLASS ljpeg_end (struct jhead *jh)
839 {
840   int c;
841   FORC4 if (jh->free[c]) free (jh->free[c]);
842   free (jh->row);
843 }
844 
ljpeg_diff(ushort * huff)845 int CLASS ljpeg_diff (ushort *huff)
846 {
847   int len, diff;
848 
849   len = gethuff(huff);
850   if (len == 16 && (!dng_version || dng_version >= 0x1010000))
851     return -32768;
852   diff = getbits(len);
853   if ((diff & (1 << (len-1))) == 0)
854     diff -= (1 << len) - 1;
855   return diff;
856 }
857 
ljpeg_row(int jrow,struct jhead * jh)858 ushort * CLASS ljpeg_row (int jrow, struct jhead *jh)
859 {
860   int col, c, diff, pred, spred=0;
861   ushort mark=0, *row[3];
862 
863   if (jrow * jh->wide % jh->restart == 0) {
864     FORC(6) jh->vpred[c] = 1 << (jh->bits-1);
865     if (jrow) {
866       fseek (ifp, -2, SEEK_CUR);
867       do mark = (mark << 8) + (c = fgetc(ifp));
868       while (c != EOF && mark >> 4 != 0xffd);
869     }
870     getbits(-1);
871   }
872   FORC3 row[c] = jh->row + jh->wide*jh->clrs*((jrow+c) & 1);
873   for (col=0; col < jh->wide; col++)
874     FORC(jh->clrs) {
875       diff = ljpeg_diff (jh->huff[c]);
876       if (jh->sraw && c <= jh->sraw && (col | c))
877 		    pred = spred;
878       else if (col) pred = row[0][-jh->clrs];
879       else	    pred = (jh->vpred[c] += diff) - diff;
880       if (jrow && col) switch (jh->psv) {
881 	case 1:	break;
882 	case 2: pred = row[1][0];					break;
883 	case 3: pred = row[1][-jh->clrs];				break;
884 	case 4: pred = pred +   row[1][0] - row[1][-jh->clrs];		break;
885 	case 5: pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1);	break;
886 	case 6: pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1);	break;
887 	case 7: pred = (pred + row[1][0]) >> 1;				break;
888 	default: pred = 0;
889       }
890       if ((**row = pred + diff) >> jh->bits) derror();
891       if (c <= jh->sraw) spred = **row;
892       row[0]++; row[1]++;
893     }
894   return row[2];
895 }
896 
lossless_jpeg_load_raw()897 void CLASS lossless_jpeg_load_raw()
898 {
899   int jwide, jrow, jcol, val, jidx, c, i, j, row=0, col=0;
900   struct jhead jh;
901   int min=INT_MAX;
902   ushort *rp;
903 
904   if (!ljpeg_start (&jh, 0)) return;
905   jwide = jh.wide * jh.clrs;
906 
907   for (jrow=0; jrow < jh.high; jrow++) {
908     rp = ljpeg_row (jrow, &jh);
909     if (load_flags & 1)
910       row = jrow & 1 ? height-1-jrow/2 : jrow/2;
911     for (jcol=0; jcol < jwide; jcol++) {
912       val = *rp++;
913       if (jh.bits <= 12)
914 	val = curve[val & 0xfff];
915       if (cr2_slice[0]) {
916 	jidx = jrow*jwide + jcol;
917 	i = jidx / (cr2_slice[1]*jh.high);
918 	if ((j = i >= cr2_slice[0]))
919 		 i  = cr2_slice[0];
920 	jidx -= i * (cr2_slice[1]*jh.high);
921 	row = jidx / cr2_slice[1+j];
922 	col = jidx % cr2_slice[1+j] + i*cr2_slice[1];
923       }
924       if (raw_width == 3984 && (col -= 2) < 0)
925 	col += (row--,raw_width);
926       if ((unsigned) (row-top_margin) < height) {
927 	c = FC(row-top_margin,col-left_margin);
928 	if ((unsigned) (col-left_margin) < width) {
929 	  BAYER(row-top_margin,col-left_margin) = val;
930 	  if (min > val) min = val;
931 	} else if (col > 1 && (unsigned) (col-left_margin+2) > width+3)
932 	  cblack[c] += (cblack[4+c]++,val);
933       }
934       if (++col >= raw_width)
935 	col = (row++,0);
936     }
937   }
938   ljpeg_end (&jh);
939   FORC4 if (cblack[4+c]) cblack[c] /= cblack[4+c];
940   if (!strcasecmp(make,"KODAK"))
941     black = min;
942 }
943 
canon_sraw_load_raw()944 void CLASS canon_sraw_load_raw()
945 {
946   struct jhead jh;
947   short *rp=0, (*ip)[4];
948   int jwide, slice, scol, ecol, row, col, jrow=0, jcol=0, pix[3], c;
949   int v[3]={0,0,0}, ver, hue;
950   char *cp;
951 
952   if (!ljpeg_start (&jh, 0)) return;
953   jwide = (jh.wide >>= 1) * jh.clrs;
954 
955   for (ecol=slice=0; slice <= cr2_slice[0]; slice++) {
956     scol = ecol;
957     ecol += cr2_slice[1] * 2 / jh.clrs;
958     if (!cr2_slice[0] || ecol > raw_width-1) ecol = raw_width & -2;
959     for (row=0; row < height; row += (jh.clrs >> 1) - 1) {
960       ip = (short (*)[4]) image + row*width;
961       for (col=scol; col < ecol; col+=2, jcol+=jh.clrs) {
962 	if ((jcol %= jwide) == 0)
963 	  rp = (short *) ljpeg_row (jrow++, &jh);
964 	if (col >= width) continue;
965 	FORC (jh.clrs-2)
966 	  ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c];
967 	ip[col][1] = rp[jcol+jh.clrs-2] - 16384;
968 	ip[col][2] = rp[jcol+jh.clrs-1] - 16384;
969       }
970     }
971   }
972   for (cp=model2; *cp && !isdigit(*cp); cp++);
973   sscanf (cp, "%d.%d.%d", v, v+1, v+2);
974   ver = (v[0]*1000 + v[1])*1000 + v[2];
975   hue = (jh.sraw+1) << 2;
976   if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006))
977     hue = jh.sraw << 1;
978   ip = (short (*)[4]) image;
979   rp = ip[0];
980   for (row=0; row < height; row++, ip+=width) {
981     if (row & (jh.sraw >> 1))
982       for (col=0; col < width; col+=2)
983 	for (c=1; c < 3; c++)
984 	  if (row == height-1)
985 	       ip[col][c] =  ip[col-width][c];
986 	  else ip[col][c] = (ip[col-width][c] + ip[col+width][c] + 1) >> 1;
987     for (col=1; col < width; col+=2)
988       for (c=1; c < 3; c++)
989 	if (col == width-1)
990 	     ip[col][c] =  ip[col-1][c];
991 	else ip[col][c] = (ip[col-1][c] + ip[col+1][c] + 1) >> 1;
992   }
993   for ( ; rp < ip[0]; rp+=4) {
994     if (unique_id < 0x80000218) {
995       pix[0] = rp[0] + rp[2] - 512;
996       pix[2] = rp[0] + rp[1] - 512;
997       pix[1] = rp[0] + ((-778*rp[1] - (rp[2] << 11)) >> 12) - 512;
998     } else {
999       rp[1] = (rp[1] << 2) + hue;
1000       rp[2] = (rp[2] << 2) + hue;
1001       pix[0] = rp[0] + ((   50*rp[1] + 22929*rp[2]) >> 14);
1002       pix[1] = rp[0] + ((-5640*rp[1] - 11751*rp[2]) >> 14);
1003       pix[2] = rp[0] + ((29040*rp[1] -   101*rp[2]) >> 14);
1004     }
1005     FORC3 rp[c] = CLIP(pix[c] * sraw_mul[c] >> 10);
1006   }
1007   ljpeg_end (&jh);
1008   maximum = 0x3fff;
1009 }
1010 
adobe_copy_pixel(int row,int col,ushort ** rp)1011 void CLASS adobe_copy_pixel (int row, int col, ushort **rp)
1012 {
1013   unsigned r, c;
1014 
1015   r = row -= top_margin;
1016   c = col -= left_margin;
1017   if (is_raw == 2 && shot_select) (*rp)++;
1018   if (filters) {
1019     if (fuji_width) {
1020       r = row + fuji_width - 1 - (col >> 1);
1021       c = row + ((col+1) >> 1);
1022     }
1023     if (r < height && c < width)
1024       BAYER(r,c) = **rp < 0x1000 ? curve[**rp] : **rp;
1025     *rp += is_raw;
1026   } else {
1027     if (r < height && c < width)
1028       FORC(tiff_samples)
1029 	image[row*width+col][c] = (*rp)[c] < 0x1000 ? curve[(*rp)[c]]:(*rp)[c];
1030     *rp += tiff_samples;
1031   }
1032   if (is_raw == 2 && shot_select) (*rp)--;
1033 }
1034 
adobe_dng_load_raw_lj()1035 void CLASS adobe_dng_load_raw_lj()
1036 {
1037   unsigned save, trow=0, tcol=0, jwide, jrow, jcol, row, col;
1038   struct jhead jh;
1039   ushort *rp;
1040 
1041   while (trow < raw_height) {
1042     save = ftell(ifp);
1043     if (tile_length < INT_MAX)
1044       fseek (ifp, get4(), SEEK_SET);
1045     if (!ljpeg_start (&jh, 0)) break;
1046     jwide = jh.wide;
1047     if (filters) jwide *= jh.clrs;
1048     jwide /= is_raw;
1049     for (row=col=jrow=0; jrow < jh.high; jrow++) {
1050       rp = ljpeg_row (jrow, &jh);
1051       for (jcol=0; jcol < jwide; jcol++) {
1052 	adobe_copy_pixel (trow+row, tcol+col, &rp);
1053 	if (++col >= tile_width || col >= raw_width)
1054 	  row += 1 + (col = 0);
1055       }
1056     }
1057     fseek (ifp, save+4, SEEK_SET);
1058     if ((tcol += tile_width) >= raw_width)
1059       trow += tile_length + (tcol = 0);
1060     ljpeg_end (&jh);
1061   }
1062 }
1063 
adobe_dng_load_raw_nc()1064 void CLASS adobe_dng_load_raw_nc()
1065 {
1066   ushort *pixel, *rp;
1067   int row, col;
1068 
1069   pixel = (ushort *) calloc (raw_width * tiff_samples, sizeof *pixel);
1070   merror (pixel, "adobe_dng_load_raw_nc()");
1071   for (row=0; row < raw_height; row++) {
1072     if (tiff_bps == 16)
1073       read_shorts (pixel, raw_width * tiff_samples);
1074     else {
1075       getbits(-1);
1076       for (col=0; col < raw_width * tiff_samples; col++)
1077 	pixel[col] = getbits(tiff_bps);
1078     }
1079     for (rp=pixel, col=0; col < raw_width; col++)
1080       adobe_copy_pixel (row, col, &rp);
1081   }
1082   free (pixel);
1083 }
1084 
pentax_load_raw()1085 void CLASS pentax_load_raw()
1086 {
1087   ushort bit[2][15], huff[4097];
1088   int dep, row, col, diff, c, i;
1089   ushort vpred[2][2] = {{0,0},{0,0}}, hpred[2];
1090 
1091   fseek (ifp, meta_offset, SEEK_SET);
1092   dep = (get2() + 12) & 15;
1093   fseek (ifp, 12, SEEK_CUR);
1094   FORC(dep) bit[0][c] = get2();
1095   FORC(dep) bit[1][c] = fgetc(ifp);
1096   FORC(dep)
1097     for (i=bit[0][c]; i <= ((bit[0][c]+(4096 >> bit[1][c])-1) & 4095); )
1098       huff[++i] = bit[1][c] << 8 | c;
1099   huff[0] = 12;
1100   fseek (ifp, data_offset, SEEK_SET);
1101   getbits(-1);
1102   for (row=0; row < raw_height; row++)
1103     for (col=0; col < raw_width; col++) {
1104       diff = ljpeg_diff (huff);
1105       if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
1106       else	   hpred[col & 1] += diff;
1107       if ((unsigned) (row-top_margin) < height &&
1108 	  (unsigned) (col-left_margin) < width)
1109 	BAYER(row-top_margin,col-left_margin) = hpred[col & 1];
1110       if (hpred[col & 1] >> tiff_bps) derror();
1111     }
1112 }
1113 
nikon_compressed_load_raw()1114 void CLASS nikon_compressed_load_raw()
1115 {
1116   static const uchar nikon_tree[][32] = {
1117     { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0,	/* 12-bit lossy */
1118       5,4,3,6,2,7,1,0,8,9,11,10,12 },
1119     { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0,	/* 12-bit lossy after split */
1120       0x39,0x5a,0x38,0x27,0x16,5,4,3,2,1,0,11,12,12 },
1121     { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,  /* 12-bit lossless */
1122       5,4,6,3,7,2,8,1,9,0,10,11,12 },
1123     { 0,1,4,3,1,1,1,1,1,2,0,0,0,0,0,0,	/* 14-bit lossy */
1124       5,6,4,7,8,3,9,2,1,0,10,11,12,13,14 },
1125     { 0,1,5,1,1,1,1,1,1,1,2,0,0,0,0,0,	/* 14-bit lossy after split */
1126       8,0x5c,0x4b,0x3a,0x29,7,6,5,4,3,2,1,0,13,14 },
1127     { 0,1,4,2,2,3,1,2,0,0,0,0,0,0,0,0,	/* 14-bit lossless */
1128       7,6,8,5,9,4,10,3,11,12,2,0,1,13,14 } };
1129   ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize;
1130   int i, min, max, step=0, tree=0, split=0, row, col, len, shl, diff;
1131 
1132   fseek (ifp, meta_offset, SEEK_SET);
1133   ver0 = fgetc(ifp);
1134   ver1 = fgetc(ifp);
1135   if (ver0 == 0x49 || ver1 == 0x58)
1136     fseek (ifp, 2110, SEEK_CUR);
1137   if (ver0 == 0x46) tree = 2;
1138   if (tiff_bps == 14) tree += 3;
1139   read_shorts (vpred[0], 4);
1140   max = 1 << tiff_bps & 0x7fff;
1141   if ((csize = get2()) > 1)
1142     step = max / (csize-1);
1143   if (ver0 == 0x44 && ver1 == 0x20 && step > 0) {
1144     for (i=0; i < csize; i++)
1145       curve[i*step] = get2();
1146     for (i=0; i < max; i++)
1147       curve[i] = ( curve[i-i%step]*(step-i%step) +
1148 		   curve[i-i%step+step]*(i%step) ) / step;
1149     fseek (ifp, meta_offset+562, SEEK_SET);
1150     split = get2();
1151   } else if (ver0 != 0x46 && csize <= 0x4001)
1152     read_shorts (curve, max=csize);
1153   while (curve[max-2] == curve[max-1]) max--;
1154   huff = make_decoder (nikon_tree[tree]);
1155   fseek (ifp, data_offset, SEEK_SET);
1156   getbits(-1);
1157   for (min=row=0; row < height; row++) {
1158     if (split && row == split) {
1159       free (huff);
1160       huff = make_decoder (nikon_tree[tree+1]);
1161       max += (min = 16) << 1;
1162     }
1163     for (col=0; col < raw_width; col++) {
1164       i = gethuff(huff);
1165       len = i & 15;
1166       shl = i >> 4;
1167       diff = ((getbits(len-shl) << 1) + 1) << shl >> 1;
1168       if ((diff & (1 << (len-1))) == 0)
1169 	diff -= (1 << len) - !shl;
1170       if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
1171       else	   hpred[col & 1] += diff;
1172       if ((ushort)(hpred[col & 1] + min) >= max) derror();
1173       if ((unsigned) (col-left_margin) < width)
1174 	BAYER(row,col-left_margin) = curve[LIM((short)hpred[col & 1],0,0x3fff)];
1175     }
1176   }
1177   free (huff);
1178 }
1179 
1180 /*
1181    Figure out if a NEF file is compressed.  These fancy heuristics
1182    are only needed for the D100, thanks to a bug in some cameras
1183    that tags all images as "compressed".
1184  */
nikon_is_compressed()1185 int CLASS nikon_is_compressed()
1186 {
1187   uchar test[256];
1188   int i;
1189 
1190   fseek (ifp, data_offset, SEEK_SET);
1191   fread (test, 1, 256, ifp);
1192   for (i=15; i < 256; i+=16)
1193     if (test[i]) return 1;
1194   return 0;
1195 }
1196 
1197 /*
1198    Returns 1 for a Coolpix 995, 0 for anything else.
1199  */
nikon_e995()1200 int CLASS nikon_e995()
1201 {
1202   int i, histo[256];
1203   const uchar often[] = { 0x00, 0x55, 0xaa, 0xff };
1204 
1205   memset (histo, 0, sizeof histo);
1206   fseek (ifp, -2000, SEEK_END);
1207   for (i=0; i < 2000; i++)
1208     histo[fgetc(ifp)]++;
1209   for (i=0; i < 4; i++)
1210     if (histo[often[i]] < 200)
1211       return 0;
1212   return 1;
1213 }
1214 
1215 /*
1216    Returns 1 for a Coolpix 2100, 0 for anything else.
1217  */
nikon_e2100()1218 int CLASS nikon_e2100()
1219 {
1220   uchar t[12];
1221   int i;
1222 
1223   fseek (ifp, 0, SEEK_SET);
1224   for (i=0; i < 1024; i++) {
1225     fread (t, 1, 12, ifp);
1226     if (((t[2] & t[4] & t[7] & t[9]) >> 4
1227 	& t[1] & t[6] & t[8] & t[11] & 3) != 3)
1228       return 0;
1229   }
1230   return 1;
1231 }
1232 
nikon_3700()1233 void CLASS nikon_3700()
1234 {
1235   int bits, i;
1236   uchar dp[24];
1237   static const struct {
1238     int bits;
1239     char make[12], model[15];
1240   } table[] = {
1241     { 0x00, "PENTAX",  "Optio 33WR" },
1242     { 0x03, "NIKON",   "E3200" },
1243     { 0x32, "NIKON",   "E3700" },
1244     { 0x33, "OLYMPUS", "C740UZ" } };
1245 
1246   fseek (ifp, 3072, SEEK_SET);
1247   fread (dp, 1, 24, ifp);
1248   bits = (dp[8] & 3) << 4 | (dp[20] & 3);
1249   for (i=0; i < sizeof table / sizeof *table; i++)
1250     if (bits == table[i].bits) {
1251       strcpy (make,  table[i].make );
1252       strcpy (model, table[i].model);
1253     }
1254 }
1255 
1256 /*
1257    Separates a Minolta DiMAGE Z2 from a Nikon E4300.
1258  */
minolta_z2()1259 int CLASS minolta_z2()
1260 {
1261   int i, nz;
1262   char tail[424];
1263 
1264   fseek (ifp, -sizeof tail, SEEK_END);
1265   fread (tail, 1, sizeof tail, ifp);
1266   for (nz=i=0; i < sizeof tail; i++)
1267     if (tail[i]) nz++;
1268   return nz > 20;
1269 }
1270 
1271 /*
1272    The Fuji Super CCD is just a Bayer grid rotated 45 degrees.
1273  */
fuji_load_raw()1274 void CLASS fuji_load_raw()
1275 {
1276   ushort *pixel;
1277   int wide, row, col, r, c;
1278 
1279   fseek (ifp, (top_margin*raw_width + left_margin) * 2, SEEK_CUR);
1280   wide = fuji_width << !fuji_layout;
1281   pixel = (ushort *) calloc (wide, sizeof *pixel);
1282   merror (pixel, "fuji_load_raw()");
1283   for (row=0; row < raw_height; row++) {
1284     read_shorts (pixel, wide);
1285     fseek (ifp, 2*(raw_width - wide), SEEK_CUR);
1286     for (col=0; col < wide; col++) {
1287       if (fuji_layout) {
1288 	r = fuji_width - 1 - col + (row >> 1);
1289 	c = col + ((row+1) >> 1);
1290       } else {
1291 	r = fuji_width - 1 + row - (col >> 1);
1292 	c = row + ((col+1) >> 1);
1293       }
1294       BAYER(r,c) = pixel[col];
1295     }
1296   }
1297   free (pixel);
1298 }
1299 
1300 void CLASS jpeg_thumb();
1301 
ppm_thumb()1302 void CLASS ppm_thumb()
1303 {
1304   char *thumb;
1305   thumb_length = thumb_width*thumb_height*3;
1306   thumb = (char *) malloc (thumb_length);
1307   merror (thumb, "ppm_thumb()");
1308   fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
1309   fread  (thumb, 1, thumb_length, ifp);
1310   fwrite (thumb, 1, thumb_length, ofp);
1311   free (thumb);
1312 }
1313 
layer_thumb()1314 void CLASS layer_thumb()
1315 {
1316   int i, c;
1317   char *thumb, map[][4] = { "012","102" };
1318 
1319   colors = thumb_misc >> 5 & 7;
1320   thumb_length = thumb_width*thumb_height;
1321   thumb = (char *) calloc (colors, thumb_length);
1322   merror (thumb, "layer_thumb()");
1323   fprintf (ofp, "P%d\n%d %d\n255\n",
1324 	5 + (colors >> 1), thumb_width, thumb_height);
1325   fread (thumb, thumb_length, colors, ifp);
1326   for (i=0; i < thumb_length; i++)
1327     FORCC putc (thumb[i+thumb_length*(map[thumb_misc >> 8][c]-'0')], ofp);
1328   free (thumb);
1329 }
1330 
rollei_thumb()1331 void CLASS rollei_thumb()
1332 {
1333   unsigned i;
1334   ushort *thumb;
1335 
1336   thumb_length = thumb_width * thumb_height;
1337   thumb = (ushort *) calloc (thumb_length, 2);
1338   merror (thumb, "rollei_thumb()");
1339   fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
1340   read_shorts (thumb, thumb_length);
1341   for (i=0; i < thumb_length; i++) {
1342     putc (thumb[i] << 3, ofp);
1343     putc (thumb[i] >> 5  << 2, ofp);
1344     putc (thumb[i] >> 11 << 3, ofp);
1345   }
1346   free (thumb);
1347 }
1348 
rollei_load_raw()1349 void CLASS rollei_load_raw()
1350 {
1351   uchar pixel[10];
1352   unsigned iten=0, isix, i, buffer=0, row, col, todo[16];
1353 
1354   isix = raw_width * raw_height * 5 / 8;
1355   while (fread (pixel, 1, 10, ifp) == 10) {
1356     for (i=0; i < 10; i+=2) {
1357       todo[i]   = iten++;
1358       todo[i+1] = pixel[i] << 8 | pixel[i+1];
1359       buffer    = pixel[i] >> 2 | buffer << 6;
1360     }
1361     for (   ; i < 16; i+=2) {
1362       todo[i]   = isix++;
1363       todo[i+1] = buffer >> (14-i)*5;
1364     }
1365     for (i=0; i < 16; i+=2) {
1366       row = todo[i] / raw_width - top_margin;
1367       col = todo[i] % raw_width - left_margin;
1368       if (row < height && col < width)
1369 	BAYER(row,col) = (todo[i+1] & 0x3ff);
1370     }
1371   }
1372   maximum = 0x3ff;
1373 }
1374 
bayer(unsigned row,unsigned col)1375 int CLASS bayer (unsigned row, unsigned col)
1376 {
1377   return (row < height && col < width) ? BAYER(row,col) : 0;
1378 }
1379 
phase_one_flat_field(int is_float,int nc)1380 void CLASS phase_one_flat_field (int is_float, int nc)
1381 {
1382   ushort head[8];
1383   unsigned wide, y, x, c, rend, cend, row, col;
1384   float *mrow, num, mult[4];
1385 
1386   read_shorts (head, 8);
1387   wide = head[2] / head[4];
1388   mrow = (float *) calloc (nc*wide, sizeof *mrow);
1389   merror (mrow, "phase_one_flat_field()");
1390   for (y=0; y < head[3] / head[5]; y++) {
1391     for (x=0; x < wide; x++)
1392       for (c=0; c < nc; c+=2) {
1393 	num = is_float ? getreal(11) : get2()/32768.0;
1394 	if (y==0) mrow[c*wide+x] = num;
1395 	else mrow[(c+1)*wide+x] = (num - mrow[c*wide+x]) / head[5];
1396       }
1397     if (y==0) continue;
1398     rend = head[1]-top_margin + y*head[5];
1399     for (row = rend-head[5]; row < height && row < rend; row++) {
1400       for (x=1; x < wide; x++) {
1401 	for (c=0; c < nc; c+=2) {
1402 	  mult[c] = mrow[c*wide+x-1];
1403 	  mult[c+1] = (mrow[c*wide+x] - mult[c]) / head[4];
1404 	}
1405 	cend = head[0]-left_margin + x*head[4];
1406 	for (col = cend-head[4]; col < width && col < cend; col++) {
1407 	  c = nc > 2 ? FC(row,col) : 0;
1408 	  if (!(c & 1)) {
1409 	    c = BAYER(row,col) * mult[c];
1410 	    BAYER(row,col) = LIM(c,0,65535);
1411 	  }
1412 	  for (c=0; c < nc; c+=2)
1413 	    mult[c] += mult[c+1];
1414 	}
1415       }
1416       for (x=0; x < wide; x++)
1417 	for (c=0; c < nc; c+=2)
1418 	  mrow[c*wide+x] += mrow[(c+1)*wide+x];
1419     }
1420   }
1421   free (mrow);
1422 }
1423 
phase_one_correct()1424 void CLASS phase_one_correct()
1425 {
1426   unsigned entries, tag, data, save, col, row, type;
1427   int len, i, j, k, cip, val[4], dev[4], sum, max;
1428   int head[9], diff, mindiff=INT_MAX, off_412=0;
1429   static const signed char dir[12][2] =
1430     { {-1,-1}, {-1,1}, {1,-1}, {1,1}, {-2,0}, {0,-2}, {0,2}, {2,0},
1431       {-2,-2}, {-2,2}, {2,-2}, {2,2} };
1432   float poly[8], num, cfrac, frac, mult[2], *yval[2];
1433   ushort *xval[2];
1434 
1435   if (half_size || !meta_length) return;
1436   if (verbose) fprintf (stderr,_("Phase One correction...\n"));
1437   fseek (ifp, meta_offset, SEEK_SET);
1438   order = get2();
1439   fseek (ifp, 6, SEEK_CUR);
1440   fseek (ifp, meta_offset+get4(), SEEK_SET);
1441   entries = get4();  get4();
1442   while (entries--) {
1443     tag  = get4();
1444     len  = get4();
1445     data = get4();
1446     save = ftell(ifp);
1447     fseek (ifp, meta_offset+data, SEEK_SET);
1448     if (tag == 0x419) {				/* Polynomial curve */
1449       for (get4(), i=0; i < 8; i++)
1450 	poly[i] = getreal(11);
1451       poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1;
1452       for (i=0; i < 0x10000; i++) {
1453 	num = (poly[5]*i + poly[3])*i + poly[1];
1454 	curve[i] = LIM(num,0,65535);
1455       } goto apply;				/* apply to right half */
1456     } else if (tag == 0x41a) {			/* Polynomial curve */
1457       for (i=0; i < 4; i++)
1458 	poly[i] = getreal(11);
1459       for (i=0; i < 0x10000; i++) {
1460 	for (num=0, j=4; j--; )
1461 	  num = num * i + poly[j];
1462 	curve[i] = LIM(num+i,0,65535);
1463       } apply:					/* apply to whole image */
1464       for (row=0; row < height; row++)
1465 	for (col = (tag & 1)*ph1.split_col; col < width; col++)
1466 	  BAYER(row,col) = curve[BAYER(row,col)];
1467     } else if (tag == 0x400) {			/* Sensor defects */
1468       while ((len -= 8) >= 0) {
1469 	col  = get2() - left_margin;
1470 	row  = get2() - top_margin;
1471 	type = get2(); get2();
1472 	if (col >= width) continue;
1473 	if (type == 131)			/* Bad column */
1474 	  for (row=0; row < height; row++)
1475 	    if (FC(row,col) == 1) {
1476 	      for (sum=i=0; i < 4; i++)
1477 		sum += val[i] = bayer (row+dir[i][0], col+dir[i][1]);
1478 	      for (max=i=0; i < 4; i++) {
1479 		dev[i] = abs((val[i] << 2) - sum);
1480 		if (dev[max] < dev[i]) max = i;
1481 	      }
1482 	      BAYER(row,col) = (sum - val[max])/3.0 + 0.5;
1483 	    } else {
1484 	      for (sum=0, i=8; i < 12; i++)
1485 		sum += bayer (row+dir[i][0], col+dir[i][1]);
1486 	      BAYER(row,col) = 0.5 + sum * 0.0732233 +
1487 		(bayer(row,col-2) + bayer(row,col+2)) * 0.3535534;
1488 	    }
1489 	else if (type == 129) {			/* Bad pixel */
1490 	  if (row >= height) continue;
1491 	  j = (FC(row,col) != 1) * 4;
1492 	  for (sum=0, i=j; i < j+8; i++)
1493 	    sum += bayer (row+dir[i][0], col+dir[i][1]);
1494 	  BAYER(row,col) = (sum + 4) >> 3;
1495 	}
1496       }
1497     } else if (tag == 0x401) {			/* All-color flat fields */
1498       phase_one_flat_field (1, 2);
1499     } else if (tag == 0x416 || tag == 0x410) {
1500       phase_one_flat_field (0, 2);
1501     } else if (tag == 0x40b) {			/* Red+blue flat field */
1502       phase_one_flat_field (0, 4);
1503     } else if (tag == 0x412) {
1504       fseek (ifp, 36, SEEK_CUR);
1505       diff = abs (get2() - ph1.tag_21a);
1506       if (mindiff > diff) {
1507 	mindiff = diff;
1508 	off_412 = ftell(ifp) - 38;
1509       }
1510     }
1511     fseek (ifp, save, SEEK_SET);
1512   }
1513   if (off_412) {
1514     fseek (ifp, off_412, SEEK_SET);
1515     for (i=0; i < 9; i++) head[i] = get4() & 0x7fff;
1516     yval[0] = (float *) calloc (head[1]*head[3] + head[2]*head[4], 6);
1517     merror (yval[0], "phase_one_correct()");
1518     yval[1] = (float  *) (yval[0] + head[1]*head[3]);
1519     xval[0] = (ushort *) (yval[1] + head[2]*head[4]);
1520     xval[1] = (ushort *) (xval[0] + head[1]*head[3]);
1521     get2();
1522     for (i=0; i < 2; i++)
1523       for (j=0; j < head[i+1]*head[i+3]; j++)
1524 	yval[i][j] = getreal(11);
1525     for (i=0; i < 2; i++)
1526       for (j=0; j < head[i+1]*head[i+3]; j++)
1527 	xval[i][j] = get2();
1528     for (row=0; row < height; row++)
1529       for (col=0; col < width; col++) {
1530 	cfrac = (float) col * head[3] / raw_width;
1531 	cfrac -= cip = cfrac;
1532 	num = BAYER(row,col) * 0.5;
1533 	for (i=cip; i < cip+2; i++) {
1534 	  for (k=j=0; j < head[1]; j++)
1535 	    if (num < xval[0][k = head[1]*i+j]) break;
1536 	  frac = (j == 0 || j == head[1]) ? 0 :
1537 		(xval[0][k] - num) / (xval[0][k] - xval[0][k-1]);
1538 	  mult[i-cip] = yval[0][k-1] * frac + yval[0][k] * (1-frac);
1539 	}
1540 	i = ((mult[0] * (1-cfrac) + mult[1] * cfrac)
1541 		* (row + top_margin) + num) * 2;
1542 	BAYER(row,col) = LIM(i,0,65535);
1543       }
1544     free (yval[0]);
1545   }
1546 }
1547 
phase_one_load_raw()1548 void CLASS phase_one_load_raw()
1549 {
1550   int row, col, a, b;
1551   ushort *pixel, akey, bkey, mask;
1552 
1553   fseek (ifp, ph1.key_off, SEEK_SET);
1554   akey = get2();
1555   bkey = get2();
1556   mask = ph1.format == 1 ? 0x5555:0x1354;
1557   fseek (ifp, data_offset + top_margin*raw_width*2, SEEK_SET);
1558   pixel = (ushort *) calloc (raw_width, sizeof *pixel);
1559   merror (pixel, "phase_one_load_raw()");
1560   for (row=0; row < height; row++) {
1561     read_shorts (pixel, raw_width);
1562     if (ph1.format)
1563       for (col=0; col < raw_width; col+=2) {
1564 	a = pixel[col+0] ^ akey;
1565 	b = pixel[col+1] ^ bkey;
1566 	pixel[col+0] = (a & mask) | (b & ~mask);
1567 	pixel[col+1] = (b & mask) | (a & ~mask);
1568       }
1569     for (col=0; col < width; col++)
1570       BAYER(row,col) = pixel[col+left_margin];
1571   }
1572   free (pixel);
1573   phase_one_correct();
1574 }
1575 
ph1_bithuff(int nbits,ushort * huff)1576 unsigned CLASS ph1_bithuff (int nbits, ushort *huff)
1577 {
1578   static UINT64 bitbuf=0;
1579   static int vbits=0;
1580   unsigned c;
1581 
1582   if (nbits == -1)
1583     return bitbuf = vbits = 0;
1584   if (nbits == 0) return 0;
1585   if (vbits < nbits) {
1586     bitbuf = bitbuf << 32 | get4();
1587     vbits += 32;
1588   }
1589   c = bitbuf << (64-vbits) >> (64-nbits);
1590   if (huff) {
1591     vbits -= huff[c] >> 8;
1592     return (uchar) huff[c];
1593   }
1594   vbits -= nbits;
1595   return c;
1596 }
1597 #define ph1_bits(n) ph1_bithuff(n,0)
1598 #define ph1_huff(h) ph1_bithuff(*h,h+1)
1599 
phase_one_load_raw_c()1600 void CLASS phase_one_load_raw_c()
1601 {
1602   static const int length[] = { 8,7,6,9,11,10,5,12,14,13 };
1603   int *offset, len[2], pred[2], row, col, i, j;
1604   ushort *pixel;
1605   short (*black)[2];
1606 
1607   pixel = (ushort *) calloc (raw_width + raw_height*4, 2);
1608   merror (pixel, "phase_one_load_raw_c()");
1609   offset = (int *) (pixel + raw_width);
1610   fseek (ifp, strip_offset, SEEK_SET);
1611   for (row=0; row < raw_height; row++)
1612     offset[row] = get4();
1613   black = (short (*)[2]) offset + raw_height;
1614   fseek (ifp, ph1.black_off, SEEK_SET);
1615   if (ph1.black_off)
1616     read_shorts ((ushort *) black[0], raw_height*2);
1617   for (i=0; i < 256; i++)
1618     curve[i] = i*i / 3.969 + 0.5;
1619   for (row=0; row < raw_height; row++) {
1620     fseek (ifp, data_offset + offset[row], SEEK_SET);
1621     ph1_bits(-1);
1622     pred[0] = pred[1] = 0;
1623     for (col=0; col < raw_width; col++) {
1624       if (col >= (raw_width & -8))
1625 	len[0] = len[1] = 14;
1626       else if ((col & 7) == 0)
1627 	for (i=0; i < 2; i++) {
1628 	  for (j=0; j < 5 && !ph1_bits(1); j++);
1629 	  if (j--) len[i] = length[j*2 + ph1_bits(1)];
1630 	}
1631       if ((i = len[col & 1]) == 14)
1632 	pixel[col] = pred[col & 1] = ph1_bits(16);
1633       else
1634 	pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1));
1635       if (pred[col & 1] >> 16) derror();
1636       if (ph1.format == 5 && pixel[col] < 256)
1637 	pixel[col] = curve[pixel[col]];
1638     }
1639     if ((unsigned) (row-top_margin) < height)
1640       for (col=0; col < width; col++) {
1641 	i = (pixel[col+left_margin] << 2)
1642 		- ph1.black + black[row][col >= ph1.split_col];
1643 	if (i > 0) BAYER(row-top_margin,col) = i;
1644       }
1645   }
1646   free (pixel);
1647   phase_one_correct();
1648   maximum = 0xfffc - ph1.black;
1649 }
1650 
hasselblad_load_raw()1651 void CLASS hasselblad_load_raw()
1652 {
1653   struct jhead jh;
1654   int row, col, pred[2], len[2], diff, c;
1655 
1656   if (!ljpeg_start (&jh, 0)) return;
1657   order = 0x4949;
1658   ph1_bits(-1);
1659   for (row=-top_margin; row < height; row++) {
1660     pred[0] = pred[1] = 0x8000 + load_flags;
1661     for (col=-left_margin; col < raw_width-left_margin; col+=2) {
1662       FORC(2) len[c] = ph1_huff(jh.huff[0]);
1663       FORC(2) {
1664 	diff = ph1_bits(len[c]);
1665 	if ((diff & (1 << (len[c]-1))) == 0)
1666 	  diff -= (1 << len[c]) - 1;
1667 	if (diff == 65535) diff = -32768;
1668 	pred[c] += diff;
1669 	if (row >= 0 && (unsigned)(col+c) < width)
1670 	  BAYER(row,col+c) = pred[c];
1671       }
1672     }
1673   }
1674   ljpeg_end (&jh);
1675   maximum = 0xffff;
1676 }
1677 
leaf_hdr_load_raw()1678 void CLASS leaf_hdr_load_raw()
1679 {
1680   ushort *pixel;
1681   unsigned tile=0, r, c, row, col;
1682 
1683   pixel = (ushort *) calloc (raw_width, sizeof *pixel);
1684   merror (pixel, "leaf_hdr_load_raw()");
1685   FORC(tiff_samples)
1686     for (r=0; r < raw_height; r++) {
1687       if (r % tile_length == 0) {
1688 	fseek (ifp, data_offset + 4*tile++, SEEK_SET);
1689 	fseek (ifp, get4() + 2*left_margin, SEEK_SET);
1690       }
1691       if (filters && c != shot_select) continue;
1692       read_shorts (pixel, raw_width);
1693       if ((row = r - top_margin) >= height) continue;
1694       for (col=0; col < width; col++)
1695 	if (filters)  BAYER(row,col) = pixel[col];
1696 	else image[row*width+col][c] = pixel[col];
1697     }
1698   free (pixel);
1699   if (!filters) {
1700     maximum = 0xffff;
1701     raw_color = 1;
1702   }
1703 }
1704 
1705 void CLASS unpacked_load_raw();
1706 
sinar_4shot_load_raw()1707 void CLASS sinar_4shot_load_raw()
1708 {
1709   ushort *pixel;
1710   unsigned shot, row, col, r, c;
1711 
1712   if ((shot = shot_select) || half_size) {
1713     if (shot) shot--;
1714     if (shot > 3) shot = 3;
1715     fseek (ifp, data_offset + shot*4, SEEK_SET);
1716     fseek (ifp, get4(), SEEK_SET);
1717     unpacked_load_raw();
1718     return;
1719   }
1720   free (image);
1721   image = (ushort (*)[4])
1722 	calloc ((iheight=height)*(iwidth=width), sizeof *image);
1723   merror (image, "sinar_4shot_load_raw()");
1724   pixel = (ushort *) calloc (raw_width, sizeof *pixel);
1725   merror (pixel, "sinar_4shot_load_raw()");
1726   for (shot=0; shot < 4; shot++) {
1727     fseek (ifp, data_offset + shot*4, SEEK_SET);
1728     fseek (ifp, get4(), SEEK_SET);
1729     for (row=0; row < raw_height; row++) {
1730       read_shorts (pixel, raw_width);
1731       if ((r = row-top_margin - (shot >> 1 & 1)) >= height) continue;
1732       for (col=0; col < raw_width; col++) {
1733 	if ((c = col-left_margin - (shot & 1)) >= width) continue;
1734 	image[r*width+c][FC(row,col)] = pixel[col];
1735       }
1736     }
1737   }
1738   free (pixel);
1739   shrink = filters = 0;
1740 }
1741 
imacon_full_load_raw()1742 void CLASS imacon_full_load_raw()
1743 {
1744   int row, col;
1745 
1746   for (row=0; row < height; row++)
1747     for (col=0; col < width; col++)
1748       read_shorts (image[row*width+col], 3);
1749 }
1750 
packed_load_raw()1751 void CLASS packed_load_raw()
1752 {
1753   int vbits=0, bwide, pwide, rbits, bite, half, irow, row, col, val, i;
1754   int zero=0;
1755   UINT64 bitbuf=0;
1756 
1757   if (raw_width * 8 >= width * tiff_bps)	/* Is raw_width in bytes? */
1758        pwide = (bwide = raw_width) * 8 / tiff_bps;
1759   else bwide = (pwide = raw_width) * tiff_bps / 8;
1760   rbits = bwide * 8 - pwide * tiff_bps;
1761   if (load_flags & 1) bwide = bwide * 16 / 15;
1762   fseek (ifp, top_margin*bwide, SEEK_CUR);
1763   bite = 8 + (load_flags & 24);
1764   half = (height+1) >> 1;
1765   for (irow=0; irow < height; irow++) {
1766     row = irow;
1767     if (load_flags & 2 &&
1768 	(row = irow % half * 2 + irow / half) == 1 &&
1769 	load_flags & 4) {
1770       if (vbits=0, tiff_compress)
1771 	fseek (ifp, data_offset - (-half*bwide & -2048), SEEK_SET);
1772       else {
1773 	fseek (ifp, 0, SEEK_END);
1774 	fseek (ifp, ftell(ifp) >> 3 << 2, SEEK_SET);
1775       }
1776     }
1777     for (col=0; col < pwide; col++) {
1778       for (vbits -= tiff_bps; vbits < 0; vbits += bite) {
1779 	bitbuf <<= bite;
1780 	for (i=0; i < bite; i+=8)
1781 	  bitbuf |= (unsigned) (fgetc(ifp) << i);
1782       }
1783       val = bitbuf << (64-tiff_bps-vbits) >> (64-tiff_bps);
1784       i = (col ^ (load_flags >> 6)) - left_margin;
1785       if ((unsigned) i < width)
1786 	BAYER(row,i) = val;
1787       else if (load_flags & 32) {
1788 	black += val;
1789 	zero += !val;
1790       }
1791       if (load_flags & 1 && (col % 10) == 9 &&
1792 	fgetc(ifp) && col < width+left_margin) derror();
1793     }
1794     vbits -= rbits;
1795   }
1796   if (load_flags & 32 && pwide > width)
1797     black /= (pwide - width) * height;
1798   if (zero*4 > (pwide - width) * height)
1799     black = 0;
1800 }
1801 
unpacked_load_raw()1802 void CLASS unpacked_load_raw()
1803 {
1804   ushort *pixel;
1805   int row, col, bits=0;
1806 
1807   while (1 << ++bits < maximum);
1808   fseek (ifp, (top_margin*raw_width + left_margin) * 2, SEEK_CUR);
1809   pixel = (ushort *) calloc (width, sizeof *pixel);
1810   merror (pixel, "unpacked_load_raw()");
1811   for (row=0; row < height; row++) {
1812     read_shorts (pixel, width);
1813     fseek (ifp, 2*(raw_width - width), SEEK_CUR);
1814     for (col=0; col < width; col++)
1815       if ((BAYER2(row,col) = pixel[col] >> load_flags) >> bits) derror();
1816   }
1817   free (pixel);
1818 }
1819 
nokia_load_raw()1820 void CLASS nokia_load_raw()
1821 {
1822   uchar  *data,  *dp;
1823   ushort *pixel, *pix;
1824   int rev, dwide, row, c;
1825 
1826   rev = 3 * (order == 0x4949);
1827   dwide = raw_width * 5 / 4;
1828   data = (uchar *) malloc (dwide + raw_width*2);
1829   merror (data, "nokia_load_raw()");
1830   pixel = (ushort *) (data + dwide);
1831   for (row=0; row < raw_height; row++) {
1832     if (fread (data+dwide, 1, dwide, ifp) < dwide) derror();
1833     FORC(dwide) data[c] = data[dwide+(c ^ rev)];
1834     for (dp=data, pix=pixel; pix < pixel+raw_width; dp+=5, pix+=4)
1835       FORC4 pix[c] = (dp[c] << 2) | (dp[4] >> (c << 1) & 3);
1836     if (row < top_margin)
1837       FORC(width) black += pixel[c];
1838     else
1839       FORC(width) BAYER(row-top_margin,c) = pixel[c];
1840   }
1841   free (data);
1842   if (top_margin) black /= top_margin * width;
1843   maximum = 0x3ff;
1844 }
1845 
pana_bits(int nbits)1846 unsigned CLASS pana_bits (int nbits)
1847 {
1848   static uchar buf[0x4000];
1849   static int vbits;
1850   int byte;
1851 
1852   if (!nbits) return vbits=0;
1853   if (!vbits) {
1854     fread (buf+load_flags, 1, 0x4000-load_flags, ifp);
1855     fread (buf, 1, load_flags, ifp);
1856   }
1857   vbits = (vbits - nbits) & 0x1ffff;
1858   byte = vbits >> 3 ^ 0x3ff0;
1859   return (buf[byte] | buf[byte+1] << 8) >> (vbits & 7) & ~(-1 << nbits);
1860 }
1861 
panasonic_load_raw()1862 void CLASS panasonic_load_raw()
1863 {
1864   int row, col, i, j, sh=0, pred[2], nonz[2];
1865 
1866   pana_bits(0);
1867   for (row=0; row < height; row++)
1868     for (col=0; col < raw_width; col++) {
1869       if ((i = col % 14) == 0)
1870 	pred[0] = pred[1] = nonz[0] = nonz[1] = 0;
1871       if (i % 3 == 2) sh = 4 >> (3 - pana_bits(2));
1872       if (nonz[i & 1]) {
1873 	if ((j = pana_bits(8))) {
1874 	  if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4)
1875 	       pred[i & 1] &= ~(-1 << sh);
1876 	  pred[i & 1] += j << sh;
1877 	}
1878       } else if ((nonz[i & 1] = pana_bits(8)) || i > 11)
1879 	pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4);
1880       if (col < width)
1881 	if ((BAYER(row,col) = pred[col & 1]) > 4098) derror();
1882     }
1883 }
1884 
olympus_load_raw()1885 void CLASS olympus_load_raw()
1886 {
1887   ushort huff[4096];
1888   int row, col, nbits, sign, low, high, i, c, w, n, nw;
1889   int acarry[2][3], *carry, pred, diff;
1890 
1891   huff[n=0] = 0xc0c;
1892   for (i=12; i--; )
1893     FORC(2048 >> i) huff[++n] = (i+1) << 8 | i;
1894   fseek (ifp, 7, SEEK_CUR);
1895   getbits(-1);
1896   for (row=0; row < height; row++) {
1897     memset (acarry, 0, sizeof acarry);
1898     for (col=0; col < raw_width; col++) {
1899       carry = acarry[col & 1];
1900       i = 2 * (carry[2] < 3);
1901       for (nbits=2+i; (ushort) carry[0] >> (nbits+i); nbits++);
1902       low = (sign = getbits(3)) & 3;
1903       sign = sign << 29 >> 31;
1904       if ((high = getbithuff(12,huff)) == 12)
1905 	high = getbits(16-nbits) >> 1;
1906       carry[0] = (high << nbits) | getbits(nbits);
1907       diff = (carry[0] ^ sign) + carry[1];
1908       carry[1] = (diff*3 + carry[1]) >> 5;
1909       carry[2] = carry[0] > 16 ? 0 : carry[2]+1;
1910       if (col >= width) continue;
1911       if (row < 2 && col < 2) pred = 0;
1912       else if (row < 2) pred = BAYER(row,col-2);
1913       else if (col < 2) pred = BAYER(row-2,col);
1914       else {
1915 	w  = BAYER(row,col-2);
1916 	n  = BAYER(row-2,col);
1917 	nw = BAYER(row-2,col-2);
1918 	if ((w < nw && nw < n) || (n < nw && nw < w)) {
1919 	  if (ABS(w-nw) > 32 || ABS(n-nw) > 32)
1920 	    pred = w + n - nw;
1921 	  else pred = (w + n) >> 1;
1922 	} else pred = ABS(w-nw) > ABS(n-nw) ? w : n;
1923       }
1924       if ((BAYER(row,col) = pred + ((diff << 2) | low)) >> 12) derror();
1925     }
1926   }
1927 }
1928 
minolta_rd175_load_raw()1929 void CLASS minolta_rd175_load_raw()
1930 {
1931   uchar pixel[768];
1932   unsigned irow, box, row, col;
1933 
1934   for (irow=0; irow < 1481; irow++) {
1935     if (fread (pixel, 1, 768, ifp) < 768) derror();
1936     box = irow / 82;
1937     row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box-12)*2);
1938     switch (irow) {
1939       case 1477: case 1479: continue;
1940       case 1476: row = 984; break;
1941       case 1480: row = 985; break;
1942       case 1478: row = 985; box = 1;
1943     }
1944     if ((box < 12) && (box & 1)) {
1945       for (col=0; col < 1533; col++, row ^= 1)
1946 	if (col != 1) BAYER(row,col) = (col+1) & 2 ?
1947 		   pixel[col/2-1] + pixel[col/2+1] : pixel[col/2] << 1;
1948       BAYER(row,1)    = pixel[1]   << 1;
1949       BAYER(row,1533) = pixel[765] << 1;
1950     } else
1951       for (col=row & 1; col < 1534; col+=2)
1952 	BAYER(row,col) = pixel[col/2] << 1;
1953   }
1954   maximum = 0xff << 1;
1955 }
1956 
quicktake_100_load_raw()1957 void CLASS quicktake_100_load_raw()
1958 {
1959   uchar pixel[484][644];
1960   static const short gstep[16] =
1961   { -89,-60,-44,-32,-22,-15,-8,-2,2,8,15,22,32,44,60,89 };
1962   static const short rstep[6][4] =
1963   { {  -3,-1,1,3  }, {  -5,-1,1,5  }, {  -8,-2,2,8  },
1964     { -13,-3,3,13 }, { -19,-4,4,19 }, { -28,-6,6,28 } };
1965   static const short curve[256] =
1966   { 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,
1967     28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,53,
1968     54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78,
1969     79,80,81,82,83,84,86,88,90,92,94,97,99,101,103,105,107,110,112,114,116,
1970     118,120,123,125,127,129,131,134,136,138,140,142,144,147,149,151,153,155,
1971     158,160,162,164,166,168,171,173,175,177,179,181,184,186,188,190,192,195,
1972     197,199,201,203,205,208,210,212,214,216,218,221,223,226,230,235,239,244,
1973     248,252,257,261,265,270,274,278,283,287,291,296,300,305,309,313,318,322,
1974     326,331,335,339,344,348,352,357,361,365,370,374,379,383,387,392,396,400,
1975     405,409,413,418,422,426,431,435,440,444,448,453,457,461,466,470,474,479,
1976     483,487,492,496,500,508,519,531,542,553,564,575,587,598,609,620,631,643,
1977     654,665,676,687,698,710,721,732,743,754,766,777,788,799,810,822,833,844,
1978     855,866,878,889,900,911,922,933,945,956,967,978,989,1001,1012,1023 };
1979   int rb, row, col, sharp, val=0;
1980 
1981   getbits(-1);
1982   memset (pixel, 0x80, sizeof pixel);
1983   for (row=2; row < height+2; row++) {
1984     for (col=2+(row & 1); col < width+2; col+=2) {
1985       val = ((pixel[row-1][col-1] + 2*pixel[row-1][col+1] +
1986 		pixel[row][col-2]) >> 2) + gstep[getbits(4)];
1987       pixel[row][col] = val = LIM(val,0,255);
1988       if (col < 4)
1989 	pixel[row][col-2] = pixel[row+1][~row & 1] = val;
1990       if (row == 2)
1991 	pixel[row-1][col+1] = pixel[row-1][col+3] = val;
1992     }
1993     pixel[row][col] = val;
1994   }
1995   for (rb=0; rb < 2; rb++)
1996     for (row=2+rb; row < height+2; row+=2)
1997       for (col=3-(row & 1); col < width+2; col+=2) {
1998 	if (row < 4 || col < 4) sharp = 2;
1999 	else {
2000 	  val = ABS(pixel[row-2][col] - pixel[row][col-2])
2001 	      + ABS(pixel[row-2][col] - pixel[row-2][col-2])
2002 	      + ABS(pixel[row][col-2] - pixel[row-2][col-2]);
2003 	  sharp = val <  4 ? 0 : val <  8 ? 1 : val < 16 ? 2 :
2004 		  val < 32 ? 3 : val < 48 ? 4 : 5;
2005 	}
2006 	val = ((pixel[row-2][col] + pixel[row][col-2]) >> 1)
2007 	      + rstep[sharp][getbits(2)];
2008 	pixel[row][col] = val = LIM(val,0,255);
2009 	if (row < 4) pixel[row-2][col+2] = val;
2010 	if (col < 4) pixel[row+2][col-2] = val;
2011       }
2012   for (row=2; row < height+2; row++)
2013     for (col=3-(row & 1); col < width+2; col+=2) {
2014       val = ((pixel[row][col-1] + (pixel[row][col] << 2) +
2015 	      pixel[row][col+1]) >> 1) - 0x100;
2016       pixel[row][col] = LIM(val,0,255);
2017     }
2018   for (row=0; row < height; row++)
2019     for (col=0; col < width; col++)
2020       BAYER(row,col) = curve[pixel[row+2][col+2]];
2021   maximum = 0x3ff;
2022 }
2023 
2024 #define radc_token(tree) ((signed char) getbithuff(8,huff[tree]))
2025 
2026 #define FORYX for (y=1; y < 3; y++) for (x=col+1; x >= col; x--)
2027 
2028 #define PREDICTOR (c ? (buf[c][y-1][x] + buf[c][y][x+1]) / 2 \
2029 : (buf[c][y-1][x+1] + 2*buf[c][y-1][x] + buf[c][y][x+1]) / 4)
2030 
kodak_radc_load_raw()2031 void CLASS kodak_radc_load_raw()
2032 {
2033   static const char src[] = {
2034     1,1, 2,3, 3,4, 4,2, 5,7, 6,5, 7,6, 7,8,
2035     1,0, 2,1, 3,3, 4,4, 5,2, 6,7, 7,6, 8,5, 8,8,
2036     2,1, 2,3, 3,0, 3,2, 3,4, 4,6, 5,5, 6,7, 6,8,
2037     2,0, 2,1, 2,3, 3,2, 4,4, 5,6, 6,7, 7,5, 7,8,
2038     2,1, 2,4, 3,0, 3,2, 3,3, 4,7, 5,5, 6,6, 6,8,
2039     2,3, 3,1, 3,2, 3,4, 3,5, 3,6, 4,7, 5,0, 5,8,
2040     2,3, 2,6, 3,0, 3,1, 4,4, 4,5, 4,7, 5,2, 5,8,
2041     2,4, 2,7, 3,3, 3,6, 4,1, 4,2, 4,5, 5,0, 5,8,
2042     2,6, 3,1, 3,3, 3,5, 3,7, 3,8, 4,0, 5,2, 5,4,
2043     2,0, 2,1, 3,2, 3,3, 4,4, 4,5, 5,6, 5,7, 4,8,
2044     1,0, 2,2, 2,-2,
2045     1,-3, 1,3,
2046     2,-17, 2,-5, 2,5, 2,17,
2047     2,-7, 2,2, 2,9, 2,18,
2048     2,-18, 2,-9, 2,-2, 2,7,
2049     2,-28, 2,28, 3,-49, 3,-9, 3,9, 4,49, 5,-79, 5,79,
2050     2,-1, 2,13, 2,26, 3,39, 4,-16, 5,55, 6,-37, 6,76,
2051     2,-26, 2,-13, 2,1, 3,-39, 4,16, 5,-55, 6,-76, 6,37
2052   };
2053   ushort huff[19][256];
2054   int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val;
2055   short last[3] = { 16,16,16 }, mul[3], buf[3][3][386];
2056   static const ushort pt[] =
2057     { 0,0, 1280,1344, 2320,3616, 3328,8000, 4095,16383, 65535,16383 };
2058 
2059   for (i=2; i < 12; i+=2)
2060     for (c=pt[i-2]; c <= pt[i]; c++)
2061       curve[c] = (float)
2062 	(c-pt[i-2]) / (pt[i]-pt[i-2]) * (pt[i+1]-pt[i-1]) + pt[i-1] + 0.5;
2063   for (s=i=0; i < sizeof src; i+=2)
2064     FORC(256 >> src[i])
2065       huff[0][s++] = src[i] << 8 | (uchar) src[i+1];
2066   s = kodak_cbpp == 243 ? 2 : 3;
2067   FORC(256) huff[18][c] = (8-s) << 8 | c >> s << s | 1 << (s-1);
2068   getbits(-1);
2069   for (i=0; i < sizeof(buf)/sizeof(short); i++)
2070     buf[0][0][i] = 2048;
2071   for (row=0; row < height; row+=4) {
2072     FORC3 mul[c] = getbits(6);
2073     FORC3 {
2074       val = ((0x1000000/last[c] + 0x7ff) >> 12) * mul[c];
2075       s = val > 65564 ? 10:12;
2076       x = ~(-1 << (s-1));
2077       val <<= 12-s;
2078       for (i=0; i < sizeof(buf[0])/sizeof(short); i++)
2079 	buf[c][0][i] = (buf[c][0][i] * val + x) >> s;
2080       last[c] = mul[c];
2081       for (r=0; r <= !c; r++) {
2082 	buf[c][1][width/2] = buf[c][2][width/2] = mul[c] << 7;
2083 	for (tree=1, col=width/2; col > 0; ) {
2084 	  if ((tree = radc_token(tree))) {
2085 	    col -= 2;
2086 	    if (tree == 8)
2087 	      FORYX buf[c][y][x] = (uchar) radc_token(18) * mul[c];
2088 	    else
2089 	      FORYX buf[c][y][x] = radc_token(tree+10) * 16 + PREDICTOR;
2090 	  } else
2091 	    do {
2092 	      nreps = (col > 2) ? radc_token(9) + 1 : 1;
2093 	      for (rep=0; rep < 8 && rep < nreps && col > 0; rep++) {
2094 		col -= 2;
2095 		FORYX buf[c][y][x] = PREDICTOR;
2096 		if (rep & 1) {
2097 		  step = radc_token(10) << 4;
2098 		  FORYX buf[c][y][x] += step;
2099 		}
2100 	      }
2101 	    } while (nreps == 9);
2102 	}
2103 	for (y=0; y < 2; y++)
2104 	  for (x=0; x < width/2; x++) {
2105 	    val = (buf[c][y+1][x] << 4) / mul[c];
2106 	    if (val < 0) val = 0;
2107 	    if (c) BAYER(row+y*2+c-1,x*2+2-c) = val;
2108 	    else   BAYER(row+r*2+y,x*2+y) = val;
2109 	  }
2110 	memcpy (buf[c][0]+!c, buf[c][2], sizeof buf[c][0]-2*!c);
2111       }
2112     }
2113     for (y=row; y < row+4; y++)
2114       for (x=0; x < width; x++)
2115 	if ((x+y) & 1) {
2116 	  r = x ? x-1 : x+1;
2117 	  s = x+1 < width ? x+1 : x-1;
2118 	  val = (BAYER(y,x)-2048)*2 + (BAYER(y,r)+BAYER(y,s))/2;
2119 	  if (val < 0) val = 0;
2120 	  BAYER(y,x) = val;
2121 	}
2122   }
2123   for (i=0; i < iheight*iwidth*4; i++)
2124     image[0][i] = curve[image[0][i]];
2125   maximum = 0x3fff;
2126 }
2127 
2128 #undef FORYX
2129 #undef PREDICTOR
2130 
2131 #ifdef NO_JPEG
kodak_jpeg_load_raw()2132 void CLASS kodak_jpeg_load_raw() {}
2133 #else
2134 
2135 METHODDEF(boolean)
fill_input_buffer(j_decompress_ptr cinfo)2136 fill_input_buffer (j_decompress_ptr cinfo)
2137 {
2138   static uchar jpeg_buffer[4096];
2139   size_t nbytes;
2140 
2141   nbytes = fread (jpeg_buffer, 1, 4096, ifp);
2142   swab (jpeg_buffer, jpeg_buffer, nbytes);
2143   cinfo->src->next_input_byte = jpeg_buffer;
2144   cinfo->src->bytes_in_buffer = nbytes;
2145   return TRUE;
2146 }
2147 
kodak_jpeg_load_raw()2148 void CLASS kodak_jpeg_load_raw()
2149 {
2150   struct jpeg_decompress_struct cinfo;
2151   struct jpeg_error_mgr jerr;
2152   JSAMPARRAY buf;
2153   JSAMPLE (*pixel)[3];
2154   int row, col;
2155 
2156   cinfo.err = jpeg_std_error (&jerr);
2157   jpeg_create_decompress (&cinfo);
2158   jpeg_stdio_src (&cinfo, ifp);
2159   cinfo.src->fill_input_buffer = fill_input_buffer;
2160   jpeg_read_header (&cinfo, TRUE);
2161   jpeg_start_decompress (&cinfo);
2162   if ((cinfo.output_width      != width  ) ||
2163       (cinfo.output_height*2   != height ) ||
2164       (cinfo.output_components != 3      )) {
2165     fprintf (stderr,_("%s: incorrect JPEG dimensions\n"), ifname);
2166     jpeg_destroy_decompress (&cinfo);
2167     longjmp (failure, 3);
2168   }
2169   buf = (*cinfo.mem->alloc_sarray)
2170 		((j_common_ptr) &cinfo, JPOOL_IMAGE, width*3, 1);
2171 
2172   while (cinfo.output_scanline < cinfo.output_height) {
2173     row = cinfo.output_scanline * 2;
2174     jpeg_read_scanlines (&cinfo, buf, 1);
2175     pixel = (JSAMPLE (*)[3]) buf[0];
2176     for (col=0; col < width; col+=2) {
2177       BAYER(row+0,col+0) = pixel[col+0][1] << 1;
2178       BAYER(row+1,col+1) = pixel[col+1][1] << 1;
2179       BAYER(row+0,col+1) = pixel[col][0] + pixel[col+1][0];
2180       BAYER(row+1,col+0) = pixel[col][2] + pixel[col+1][2];
2181     }
2182   }
2183   jpeg_finish_decompress (&cinfo);
2184   jpeg_destroy_decompress (&cinfo);
2185   maximum = 0xff << 1;
2186 }
2187 #endif
2188 
kodak_dc120_load_raw()2189 void CLASS kodak_dc120_load_raw()
2190 {
2191   static const int mul[4] = { 162, 192, 187,  92 };
2192   static const int add[4] = {   0, 636, 424, 212 };
2193   uchar pixel[848];
2194   int row, shift, col;
2195 
2196   for (row=0; row < height; row++) {
2197     if (fread (pixel, 1, 848, ifp) < 848) derror();
2198     shift = row * mul[row & 3] + add[row & 3];
2199     for (col=0; col < width; col++)
2200       BAYER(row,col) = (ushort) pixel[(col + shift) % 848];
2201   }
2202   maximum = 0xff;
2203 }
2204 
eight_bit_load_raw()2205 void CLASS eight_bit_load_raw()
2206 {
2207   uchar *pixel;
2208   unsigned row, col, val, lblack=0;
2209 
2210   pixel = (uchar *) calloc (raw_width, sizeof *pixel);
2211   merror (pixel, "eight_bit_load_raw()");
2212   fseek (ifp, top_margin*raw_width, SEEK_CUR);
2213   for (row=0; row < height; row++) {
2214     if (fread (pixel, 1, raw_width, ifp) < raw_width) derror();
2215     for (col=0; col < raw_width; col++) {
2216       val = curve[pixel[col]];
2217       if ((unsigned) (col-left_margin) < width)
2218 	BAYER(row,col-left_margin) = val;
2219       else lblack += val;
2220     }
2221   }
2222   free (pixel);
2223   if (raw_width > width+1)
2224     black = lblack / ((raw_width - width) * height);
2225   if (!strncmp(model,"DC2",3))
2226     black = 0;
2227   maximum = curve[0xff];
2228 }
2229 
kodak_yrgb_load_raw()2230 void CLASS kodak_yrgb_load_raw()
2231 {
2232   uchar *pixel;
2233   int row, col, y, cb, cr, rgb[3], c;
2234 
2235   pixel = (uchar *) calloc (raw_width, 3*sizeof *pixel);
2236   merror (pixel, "kodak_yrgb_load_raw()");
2237   for (row=0; row < height; row++) {
2238     if (~row & 1)
2239       if (fread (pixel, raw_width, 3, ifp) < 3) derror();
2240     for (col=0; col < raw_width; col++) {
2241       y  = pixel[width*2*(row & 1) + col];
2242       cb = pixel[width + (col & -2)]   - 128;
2243       cr = pixel[width + (col & -2)+1] - 128;
2244       rgb[1] = y-((cb + cr + 2) >> 2);
2245       rgb[2] = rgb[1] + cb;
2246       rgb[0] = rgb[1] + cr;
2247       FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)];
2248     }
2249   }
2250   free (pixel);
2251   maximum = curve[0xff];
2252 }
2253 
kodak_262_load_raw()2254 void CLASS kodak_262_load_raw()
2255 {
2256   static const uchar kodak_tree[2][26] =
2257   { { 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 },
2258     { 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 } };
2259   ushort *huff[2];
2260   uchar *pixel;
2261   int *strip, ns, c, row, col, chess, pi=0, pi1, pi2, pred, val;
2262 
2263   FORC(2) huff[c] = make_decoder (kodak_tree[c]);
2264   ns = (raw_height+63) >> 5;
2265   pixel = (uchar *) malloc (raw_width*32 + ns*4);
2266   merror (pixel, "kodak_262_load_raw()");
2267   strip = (int *) (pixel + raw_width*32);
2268   order = 0x4d4d;
2269   FORC(ns) strip[c] = get4();
2270   for (row=0; row < raw_height; row++) {
2271     if ((row & 31) == 0) {
2272       fseek (ifp, strip[row >> 5], SEEK_SET);
2273       getbits(-1);
2274       pi = 0;
2275     }
2276     for (col=0; col < raw_width; col++) {
2277       chess = (row + col) & 1;
2278       pi1 = chess ? pi-2           : pi-raw_width-1;
2279       pi2 = chess ? pi-2*raw_width : pi-raw_width+1;
2280       if (col <= chess) pi1 = -1;
2281       if (pi1 < 0) pi1 = pi2;
2282       if (pi2 < 0) pi2 = pi1;
2283       if (pi1 < 0 && col > 1) pi1 = pi2 = pi-2;
2284       pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1;
2285       pixel[pi] = val = pred + ljpeg_diff (huff[chess]);
2286       if (val >> 8) derror();
2287       val = curve[pixel[pi++]];
2288       if ((unsigned) (col-left_margin) < width)
2289 	BAYER(row,col-left_margin) = val;
2290       else black += val;
2291     }
2292   }
2293   free (pixel);
2294   FORC(2) free (huff[c]);
2295   if (raw_width > width)
2296     black /= (raw_width - width) * height;
2297 }
2298 
kodak_65000_decode(short * out,int bsize)2299 int CLASS kodak_65000_decode (short *out, int bsize)
2300 {
2301   uchar c, blen[768];
2302   ushort raw[6];
2303   INT64 bitbuf=0;
2304   int save, bits=0, i, j, len, diff;
2305 
2306   save = ftell(ifp);
2307   bsize = (bsize + 3) & -4;
2308   for (i=0; i < bsize; i+=2) {
2309     c = fgetc(ifp);
2310     if ((blen[i  ] = c & 15) > 12 ||
2311 	(blen[i+1] = c >> 4) > 12 ) {
2312       fseek (ifp, save, SEEK_SET);
2313       for (i=0; i < bsize; i+=8) {
2314 	read_shorts (raw, 6);
2315 	out[i  ] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12;
2316 	out[i+1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12;
2317 	for (j=0; j < 6; j++)
2318 	  out[i+2+j] = raw[j] & 0xfff;
2319       }
2320       return 1;
2321     }
2322   }
2323   if ((bsize & 7) == 4) {
2324     bitbuf  = fgetc(ifp) << 8;
2325     bitbuf += fgetc(ifp);
2326     bits = 16;
2327   }
2328   for (i=0; i < bsize; i++) {
2329     len = blen[i];
2330     if (bits < len) {
2331       for (j=0; j < 32; j+=8)
2332 	bitbuf += (INT64) fgetc(ifp) << (bits+(j^8));
2333       bits += 32;
2334     }
2335     diff = bitbuf & (0xffff >> (16-len));
2336     bitbuf >>= len;
2337     bits -= len;
2338     if ((diff & (1 << (len-1))) == 0)
2339       diff -= (1 << len) - 1;
2340     out[i] = diff;
2341   }
2342   return 0;
2343 }
2344 
kodak_65000_load_raw()2345 void CLASS kodak_65000_load_raw()
2346 {
2347   short buf[256];
2348   int row, col, len, pred[2], ret, i;
2349 
2350   for (row=0; row < height; row++)
2351     for (col=0; col < width; col+=256) {
2352       pred[0] = pred[1] = 0;
2353       len = MIN (256, width-col);
2354       ret = kodak_65000_decode (buf, len);
2355       for (i=0; i < len; i++)
2356 	if ((BAYER(row,col+i) =	curve[ret ? buf[i] :
2357 		(pred[i & 1] += buf[i])]) >> 12) derror();
2358     }
2359 }
2360 
kodak_ycbcr_load_raw()2361 void CLASS kodak_ycbcr_load_raw()
2362 {
2363   short buf[384], *bp;
2364   int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3];
2365   ushort *ip;
2366 
2367   for (row=0; row < height; row+=2)
2368     for (col=0; col < width; col+=128) {
2369       len = MIN (128, width-col);
2370       kodak_65000_decode (buf, len*3);
2371       y[0][1] = y[1][1] = cb = cr = 0;
2372       for (bp=buf, i=0; i < len; i+=2, bp+=2) {
2373 	cb += bp[4];
2374 	cr += bp[5];
2375 	rgb[1] = -((cb + cr + 2) >> 2);
2376 	rgb[2] = rgb[1] + cb;
2377 	rgb[0] = rgb[1] + cr;
2378 	for (j=0; j < 2; j++)
2379 	  for (k=0; k < 2; k++) {
2380 	    if ((y[j][k] = y[j][k^1] + *bp++) >> 10) derror();
2381 	    ip = image[(row+j)*width + col+i+k];
2382 	    FORC3 ip[c] = curve[LIM(y[j][k]+rgb[c], 0, 0xfff)];
2383 	  }
2384       }
2385     }
2386 }
2387 
kodak_rgb_load_raw()2388 void CLASS kodak_rgb_load_raw()
2389 {
2390   short buf[768], *bp;
2391   int row, col, len, c, i, rgb[3];
2392   ushort *ip=image[0];
2393 
2394   for (row=0; row < height; row++)
2395     for (col=0; col < width; col+=256) {
2396       len = MIN (256, width-col);
2397       kodak_65000_decode (buf, len*3);
2398       memset (rgb, 0, sizeof rgb);
2399       for (bp=buf, i=0; i < len; i++, ip+=4)
2400 	FORC3 if ((ip[c] = rgb[c] += *bp++) >> 12) derror();
2401     }
2402 }
2403 
kodak_thumb_load_raw()2404 void CLASS kodak_thumb_load_raw()
2405 {
2406   int row, col;
2407   colors = thumb_misc >> 5;
2408   for (row=0; row < height; row++)
2409     for (col=0; col < width; col++)
2410       read_shorts (image[row*width+col], colors);
2411   maximum = (1 << (thumb_misc & 31)) - 1;
2412 }
2413 
sony_decrypt(unsigned * data,int len,int start,int key)2414 void CLASS sony_decrypt (unsigned *data, int len, int start, int key)
2415 {
2416   static unsigned pad[128], p;
2417 
2418   if (start) {
2419     for (p=0; p < 4; p++)
2420       pad[p] = key = key * 48828125 + 1;
2421     pad[3] = pad[3] << 1 | (pad[0]^pad[2]) >> 31;
2422     for (p=4; p < 127; p++)
2423       pad[p] = (pad[p-4]^pad[p-2]) << 1 | (pad[p-3]^pad[p-1]) >> 31;
2424     for (p=0; p < 127; p++)
2425       pad[p] = htonl(pad[p]);
2426   }
2427   while (len--)
2428     *data++ ^= pad[p++ & 127] = pad[(p+1) & 127] ^ pad[(p+65) & 127];
2429 }
2430 
sony_load_raw()2431 void CLASS sony_load_raw()
2432 {
2433   uchar head[40];
2434   ushort *pixel;
2435   unsigned i, key, row, col;
2436 
2437   fseek (ifp, 200896, SEEK_SET);
2438   fseek (ifp, (unsigned) fgetc(ifp)*4 - 1, SEEK_CUR);
2439   order = 0x4d4d;
2440   key = get4();
2441   fseek (ifp, 164600, SEEK_SET);
2442   fread (head, 1, 40, ifp);
2443   sony_decrypt ((unsigned int *) head, 10, 1, key);
2444   for (i=26; i-- > 22; )
2445     key = key << 8 | head[i];
2446   fseek (ifp, data_offset, SEEK_SET);
2447   pixel = (ushort *) calloc (raw_width, sizeof *pixel);
2448   merror (pixel, "sony_load_raw()");
2449   for (row=0; row < height; row++) {
2450     if (fread (pixel, 2, raw_width, ifp) < raw_width) derror();
2451     sony_decrypt ((unsigned int *) pixel, raw_width/2, !row, key);
2452     for (col=9; col < left_margin; col++)
2453       black += ntohs(pixel[col]);
2454     for (col=0; col < width; col++)
2455       if ((BAYER(row,col) = ntohs(pixel[col+left_margin])) >> 14)
2456 	derror();
2457   }
2458   free (pixel);
2459   if (left_margin > 9)
2460     black /= (left_margin-9) * height;
2461   maximum = 0x3ff0;
2462 }
2463 
sony_arw_load_raw()2464 void CLASS sony_arw_load_raw()
2465 {
2466   ushort huff[32768];
2467   static const ushort tab[18] =
2468   { 0xf11,0xf10,0xe0f,0xd0e,0xc0d,0xb0c,0xa0b,0x90a,0x809,
2469     0x708,0x607,0x506,0x405,0x304,0x303,0x300,0x202,0x201 };
2470   int i, c, n, col, row, len, diff, sum=0;
2471 
2472   for (n=i=0; i < 18; i++)
2473     FORC(32768 >> (tab[i] >> 8)) huff[n++] = tab[i];
2474   getbits(-1);
2475   for (col = raw_width; col--; )
2476     for (row=0; row < raw_height+1; row+=2) {
2477       if (row == raw_height) row = 1;
2478       len = getbithuff(15,huff);
2479       diff = getbits(len);
2480       if ((diff & (1 << (len-1))) == 0)
2481 	diff -= (1 << len) - 1;
2482       if ((sum += diff) >> 12) derror();
2483       if (row < height) BAYER(row,col) = sum;
2484     }
2485 }
2486 
sony_arw2_load_raw()2487 void CLASS sony_arw2_load_raw()
2488 {
2489   uchar *data, *dp;
2490   ushort pix[16];
2491   int row, col, val, max, min, imax, imin, sh, bit, i;
2492 
2493   data = (uchar *) malloc (raw_width);
2494   merror (data, "sony_arw2_load_raw()");
2495   for (row=0; row < height; row++) {
2496     fread (data, 1, raw_width, ifp);
2497     for (dp=data, col=0; col < raw_width-30; dp+=16) {
2498       max = 0x7ff & (val = sget4(dp));
2499       min = 0x7ff & val >> 11;
2500       imax = 0x0f & val >> 22;
2501       imin = 0x0f & val >> 26;
2502       for (sh=0; sh < 4 && 0x80 << sh <= max-min; sh++);
2503       for (bit=30, i=0; i < 16; i++)
2504 	if      (i == imax) pix[i] = max;
2505 	else if (i == imin) pix[i] = min;
2506 	else {
2507 	  pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min;
2508 	  if (pix[i] > 0x7ff) pix[i] = 0x7ff;
2509 	  bit += 7;
2510 	}
2511       for (i=0; i < 16; i++, col+=2)
2512 	if (col < width) BAYER(row,col) = curve[pix[i] << 1] >> 2;
2513       col -= col & 1 ? 1:31;
2514     }
2515   }
2516   free (data);
2517 }
2518 
2519 #define HOLE(row) ((holes >> (((row) - raw_height) & 7)) & 1)
2520 
2521 /* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */
smal_decode_segment(unsigned seg[2][2],int holes)2522 void CLASS smal_decode_segment (unsigned seg[2][2], int holes)
2523 {
2524   uchar hist[3][13] = {
2525     { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 },
2526     { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 },
2527     { 3, 3, 0, 0, 63,     47,     31,     15,    0 } };
2528   int low, high=0xff, carry=0, nbits=8;
2529   int s, count, bin, next, i, sym[3];
2530   uchar diff, pred[]={0,0};
2531   ushort data=0, range=0;
2532   unsigned pix, row, col;
2533 
2534   fseek (ifp, seg[0][1]+1, SEEK_SET);
2535   getbits(-1);
2536   for (pix=seg[0][0]; pix < seg[1][0]; pix++) {
2537     for (s=0; s < 3; s++) {
2538       data = data << nbits | getbits(nbits);
2539       if (carry < 0)
2540 	carry = (nbits += carry+1) < 1 ? nbits-1 : 0;
2541       while (--nbits >= 0)
2542 	if ((data >> nbits & 0xff) == 0xff) break;
2543       if (nbits > 0)
2544 	  data = ((data & ((1 << (nbits-1)) - 1)) << 1) |
2545 	((data + (((data & (1 << (nbits-1)))) << 1)) & (-1 << nbits));
2546       if (nbits >= 0) {
2547 	data += getbits(1);
2548 	carry = nbits - 8;
2549       }
2550       count = ((((data-range+1) & 0xffff) << 2) - 1) / (high >> 4);
2551       for (bin=0; hist[s][bin+5] > count; bin++);
2552 		low = hist[s][bin+5] * (high >> 4) >> 2;
2553       if (bin) high = hist[s][bin+4] * (high >> 4) >> 2;
2554       high -= low;
2555       for (nbits=0; high << nbits < 128; nbits++);
2556       range = (range+low) << nbits;
2557       high <<= nbits;
2558       next = hist[s][1];
2559       if (++hist[s][2] > hist[s][3]) {
2560 	next = (next+1) & hist[s][0];
2561 	hist[s][3] = (hist[s][next+4] - hist[s][next+5]) >> 2;
2562 	hist[s][2] = 1;
2563       }
2564       if (hist[s][hist[s][1]+4] - hist[s][hist[s][1]+5] > 1) {
2565 	if (bin < hist[s][1])
2566 	  for (i=bin; i < hist[s][1]; i++) hist[s][i+5]--;
2567 	else if (next <= bin)
2568 	  for (i=hist[s][1]; i < bin; i++) hist[s][i+5]++;
2569       }
2570       hist[s][1] = next;
2571       sym[s] = bin;
2572     }
2573     diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3);
2574     if (sym[0] & 4)
2575       diff = diff ? -diff : 0x80;
2576     if (ftell(ifp) + 12 >= seg[1][1])
2577       diff = 0;
2578     pred[pix & 1] += diff;
2579     row = pix / raw_width - top_margin;
2580     col = pix % raw_width - left_margin;
2581     if (row < height && col < width)
2582       BAYER(row,col) = pred[pix & 1];
2583     if (!(pix & 1) && HOLE(row)) pix += 2;
2584   }
2585   maximum = 0xff;
2586 }
2587 
smal_v6_load_raw()2588 void CLASS smal_v6_load_raw()
2589 {
2590   unsigned seg[2][2];
2591 
2592   fseek (ifp, 16, SEEK_SET);
2593   seg[0][0] = 0;
2594   seg[0][1] = get2();
2595   seg[1][0] = raw_width * raw_height;
2596   seg[1][1] = INT_MAX;
2597   smal_decode_segment (seg, 0);
2598 }
2599 
median4(int * p)2600 int CLASS median4 (int *p)
2601 {
2602   int min, max, sum, i;
2603 
2604   min = max = sum = p[0];
2605   for (i=1; i < 4; i++) {
2606     sum += p[i];
2607     if (min > p[i]) min = p[i];
2608     if (max < p[i]) max = p[i];
2609   }
2610   return (sum - min - max) >> 1;
2611 }
2612 
fill_holes(int holes)2613 void CLASS fill_holes (int holes)
2614 {
2615   int row, col, val[4];
2616 
2617   for (row=2; row < height-2; row++) {
2618     if (!HOLE(row)) continue;
2619     for (col=1; col < width-1; col+=4) {
2620       val[0] = BAYER(row-1,col-1);
2621       val[1] = BAYER(row-1,col+1);
2622       val[2] = BAYER(row+1,col-1);
2623       val[3] = BAYER(row+1,col+1);
2624       BAYER(row,col) = median4(val);
2625     }
2626     for (col=2; col < width-2; col+=4)
2627       if (HOLE(row-2) || HOLE(row+2))
2628 	BAYER(row,col) = (BAYER(row,col-2) + BAYER(row,col+2)) >> 1;
2629       else {
2630 	val[0] = BAYER(row,col-2);
2631 	val[1] = BAYER(row,col+2);
2632 	val[2] = BAYER(row-2,col);
2633 	val[3] = BAYER(row+2,col);
2634 	BAYER(row,col) = median4(val);
2635       }
2636   }
2637 }
2638 
smal_v9_load_raw()2639 void CLASS smal_v9_load_raw()
2640 {
2641   unsigned seg[256][2], offset, nseg, holes, i;
2642 
2643   fseek (ifp, 67, SEEK_SET);
2644   offset = get4();
2645   nseg = fgetc(ifp);
2646   fseek (ifp, offset, SEEK_SET);
2647   for (i=0; i < nseg*2; i++)
2648     seg[0][i] = get4() + data_offset*(i & 1);
2649   fseek (ifp, 78, SEEK_SET);
2650   holes = fgetc(ifp);
2651   fseek (ifp, 88, SEEK_SET);
2652   seg[nseg][0] = raw_height * raw_width;
2653   seg[nseg][1] = get4() + data_offset;
2654   for (i=0; i < nseg; i++)
2655     smal_decode_segment (seg+i, holes);
2656   if (holes) fill_holes (holes);
2657 }
2658 
redcine_load_raw()2659 void CLASS redcine_load_raw()
2660 {
2661 #ifndef NO_JASPER
2662   int c, row, col;
2663   jas_stream_t *in;
2664   jas_image_t *jimg;
2665   jas_matrix_t *jmat;
2666   jas_seqent_t *data;
2667   ushort *img, *pix;
2668 
2669   jas_init();
2670   in = jas_stream_fopen (ifname, "rb");
2671   jas_stream_seek (in, data_offset+20, SEEK_SET);
2672   jimg = jas_image_decode (in, -1, 0);
2673   if (!jimg) longjmp (failure, 3);
2674   jmat = jas_matrix_create (height/2, width/2);
2675   merror (jmat, "redcine_load_raw()");
2676   img = (ushort *) calloc ((height+2)*(width+2), 2);
2677   merror (img, "redcine_load_raw()");
2678   FORC4 {
2679     jas_image_readcmpt (jimg, c, 0, 0, width/2, height/2, jmat);
2680     data = jas_matrix_getref (jmat, 0, 0);
2681     for (row = c >> 1; row < height; row+=2)
2682       for (col = c & 1; col < width; col+=2)
2683 	img[(row+1)*(width+2)+col+1] = data[(row/2)*(width/2)+col/2];
2684   }
2685   for (col=1; col <= width; col++) {
2686     img[col] = img[2*(width+2)+col];
2687     img[(height+1)*(width+2)+col] = img[(height-1)*(width+2)+col];
2688   }
2689   for (row=0; row < height+2; row++) {
2690     img[row*(width+2)] = img[row*(width+2)+2];
2691     img[(row+1)*(width+2)-1] = img[(row+1)*(width+2)-3];
2692   }
2693   for (row=1; row <= height; row++) {
2694     pix = img + row*(width+2) + (col = 1 + (FC(row,1) & 1));
2695     for (   ; col <= width; col+=2, pix+=2) {
2696       c = (((pix[0] - 0x800) << 3) +
2697 	pix[-(width+2)] + pix[width+2] + pix[-1] + pix[1]) >> 2;
2698       pix[0] = LIM(c,0,4095);
2699     }
2700   }
2701   for (row=0; row < height; row++)
2702     for (col=0; col < width; col++)
2703       BAYER(row,col) = curve[img[(row+1)*(width+2)+col+1]];
2704   free (img);
2705   jas_matrix_destroy (jmat);
2706   jas_image_destroy (jimg);
2707   jas_stream_close (in);
2708 #endif
2709 }
2710 
2711 /* RESTRICTED code starts here */
2712 
foveon_decoder(unsigned size,unsigned code)2713 void CLASS foveon_decoder (unsigned size, unsigned code)
2714 {
2715   static unsigned huff[1024];
2716   struct decode *cur;
2717   int i, len;
2718 
2719   if (!code) {
2720     for (i=0; i < size; i++)
2721       huff[i] = get4();
2722     memset (first_decode, 0, sizeof first_decode);
2723     free_decode = first_decode;
2724   }
2725   cur = free_decode++;
2726   if (free_decode > first_decode+2048) {
2727     fprintf (stderr,_("%s: decoder table overflow\n"), ifname);
2728     longjmp (failure, 2);
2729   }
2730   if (code)
2731     for (i=0; i < size; i++)
2732       if (huff[i] == code) {
2733 	cur->leaf = i;
2734 	return;
2735       }
2736   if ((len = code >> 27) > 26) return;
2737   code = (len+1) << 27 | (code & 0x3ffffff) << 1;
2738 
2739   cur->branch[0] = free_decode;
2740   foveon_decoder (size, code);
2741   cur->branch[1] = free_decode;
2742   foveon_decoder (size, code+1);
2743 }
2744 
foveon_thumb()2745 void CLASS foveon_thumb()
2746 {
2747   unsigned bwide, row, col, bitbuf=0, bit=1, c, i;
2748   char *buf;
2749   struct decode *dindex;
2750   short pred[3];
2751 
2752   bwide = get4();
2753   fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
2754   if (bwide > 0) {
2755     if (bwide < thumb_width*3) return;
2756     buf = (char *) malloc (bwide);
2757     merror (buf, "foveon_thumb()");
2758     for (row=0; row < thumb_height; row++) {
2759       fread  (buf, 1, bwide, ifp);
2760       fwrite (buf, 3, thumb_width, ofp);
2761     }
2762     free (buf);
2763     return;
2764   }
2765   foveon_decoder (256, 0);
2766 
2767   for (row=0; row < thumb_height; row++) {
2768     memset (pred, 0, sizeof pred);
2769     if (!bit) get4();
2770     for (bit=col=0; col < thumb_width; col++)
2771       FORC3 {
2772 	for (dindex=first_decode; dindex->branch[0]; ) {
2773 	  if ((bit = (bit-1) & 31) == 31)
2774 	    for (i=0; i < 4; i++)
2775 	      bitbuf = (bitbuf << 8) + fgetc(ifp);
2776 	  dindex = dindex->branch[bitbuf >> bit & 1];
2777 	}
2778 	pred[c] += dindex->leaf;
2779 	fputc (pred[c], ofp);
2780       }
2781   }
2782 }
2783 
foveon_load_camf()2784 void CLASS foveon_load_camf()
2785 {
2786   unsigned key, i, val;
2787 
2788   fseek (ifp, meta_offset, SEEK_SET);
2789   key = get4();
2790   fread (meta_data, 1, meta_length, ifp);
2791   for (i=0; i < meta_length; i++) {
2792     key = (key * 1597 + 51749) % 244944;
2793     val = key * (INT64) 301593171 >> 24;
2794     meta_data[i] ^= ((((key << 8) - val) >> 1) + val) >> 17;
2795   }
2796 }
2797 
foveon_load_raw()2798 void CLASS foveon_load_raw()
2799 {
2800   struct decode *dindex;
2801   short diff[1024];
2802   unsigned bitbuf=0;
2803   int pred[3], fixed, row, col, bit=-1, c, i;
2804 
2805   fixed = get4();
2806   read_shorts ((ushort *) diff, 1024);
2807   if (!fixed) foveon_decoder (1024, 0);
2808 
2809   for (row=0; row < height; row++) {
2810     memset (pred, 0, sizeof pred);
2811     if (!bit && !fixed && atoi(model+2) < 14) get4();
2812     for (col=bit=0; col < width; col++) {
2813       if (fixed) {
2814 	bitbuf = get4();
2815 	FORC3 pred[2-c] += diff[bitbuf >> c*10 & 0x3ff];
2816       }
2817       else FORC3 {
2818 	for (dindex=first_decode; dindex->branch[0]; ) {
2819 	  if ((bit = (bit-1) & 31) == 31)
2820 	    for (i=0; i < 4; i++)
2821 	      bitbuf = (bitbuf << 8) + fgetc(ifp);
2822 	  dindex = dindex->branch[bitbuf >> bit & 1];
2823 	}
2824 	pred[c] += diff[dindex->leaf];
2825 	if (pred[c] >> 16 && ~pred[c] >> 16) derror();
2826       }
2827       FORC3 image[row*width+col][c] = pred[c];
2828     }
2829   }
2830   if (document_mode)
2831     for (i=0; i < height*width*4; i++)
2832       if ((short) image[0][i] < 0) image[0][i] = 0;
2833   foveon_load_camf();
2834 }
2835 
foveon_camf_param(const char * block,const char * param)2836 const char * CLASS foveon_camf_param (const char *block, const char *param)
2837 {
2838   unsigned idx, num;
2839   char *pos, *cp, *dp;
2840 
2841   for (idx=0; idx < meta_length; idx += sget4(pos+8)) {
2842     pos = meta_data + idx;
2843     if (strncmp (pos, "CMb", 3)) break;
2844     if (pos[3] != 'P') continue;
2845     if (strcmp (block, pos+sget4(pos+12))) continue;
2846     cp = pos + sget4(pos+16);
2847     num = sget4(cp);
2848     dp = pos + sget4(cp+4);
2849     while (num--) {
2850       cp += 8;
2851       if (!strcmp (param, dp+sget4(cp)))
2852 	return dp+sget4(cp+4);
2853     }
2854   }
2855   return 0;
2856 }
2857 
foveon_camf_matrix(unsigned dim[3],const char * name)2858 void * CLASS foveon_camf_matrix (unsigned dim[3], const char *name)
2859 {
2860   unsigned i, idx, type, ndim, size, *mat;
2861   char *pos, *cp, *dp;
2862   double dsize;
2863 
2864   for (idx=0; idx < meta_length; idx += sget4(pos+8)) {
2865     pos = meta_data + idx;
2866     if (strncmp (pos, "CMb", 3)) break;
2867     if (pos[3] != 'M') continue;
2868     if (strcmp (name, pos+sget4(pos+12))) continue;
2869     dim[0] = dim[1] = dim[2] = 1;
2870     cp = pos + sget4(pos+16);
2871     type = sget4(cp);
2872     if ((ndim = sget4(cp+4)) > 3) break;
2873     dp = pos + sget4(cp+8);
2874     for (i=ndim; i--; ) {
2875       cp += 12;
2876       dim[i] = sget4(cp);
2877     }
2878     if ((dsize = (double) dim[0]*dim[1]*dim[2]) > meta_length/4) break;
2879     mat = (unsigned *) malloc ((size = dsize) * 4);
2880     merror (mat, "foveon_camf_matrix()");
2881     for (i=0; i < size; i++)
2882       if (type && type != 6)
2883 	mat[i] = sget4(dp + i*4);
2884       else
2885 	mat[i] = sget4(dp + i*2) & 0xffff;
2886     return mat;
2887   }
2888   fprintf (stderr,_("%s: \"%s\" matrix not found!\n"), ifname, name);
2889   return 0;
2890 }
2891 
foveon_fixed(void * ptr,int size,const char * name)2892 int CLASS foveon_fixed (void *ptr, int size, const char *name)
2893 {
2894   void *dp;
2895   unsigned dim[3];
2896 
2897   dp = foveon_camf_matrix (dim, name);
2898   if (!dp) return 0;
2899   memcpy (ptr, dp, size*4);
2900   free (dp);
2901   return 1;
2902 }
2903 
foveon_avg(short * pix,int range[2],float cfilt)2904 float CLASS foveon_avg (short *pix, int range[2], float cfilt)
2905 {
2906   int i;
2907   float val, min=FLT_MAX, max=-FLT_MAX, sum=0;
2908 
2909   for (i=range[0]; i <= range[1]; i++) {
2910     sum += val = pix[i*4] + (pix[i*4]-pix[(i-1)*4]) * cfilt;
2911     if (min > val) min = val;
2912     if (max < val) max = val;
2913   }
2914   if (range[1] - range[0] == 1) return sum/2;
2915   return (sum - min - max) / (range[1] - range[0] - 1);
2916 }
2917 
foveon_make_curve(double max,double mul,double filt)2918 short * CLASS foveon_make_curve (double max, double mul, double filt)
2919 {
2920   short *curve;
2921   unsigned i, size;
2922   double x;
2923 
2924   if (!filt) filt = 0.8;
2925   size = 4*M_PI*max / filt;
2926   if (size == UINT_MAX) size--;
2927   curve = (short *) calloc (size+1, sizeof *curve);
2928   merror (curve, "foveon_make_curve()");
2929   curve[0] = size;
2930   for (i=0; i < size; i++) {
2931     x = i*filt/max/4;
2932     curve[i+1] = (cos(x)+1)/2 * tanh(i*filt/mul) * mul + 0.5;
2933   }
2934   return curve;
2935 }
2936 
foveon_make_curves(short ** curvep,float dq[3],float div[3],float filt)2937 void CLASS foveon_make_curves
2938 	(short **curvep, float dq[3], float div[3], float filt)
2939 {
2940   double mul[3], max=0;
2941   int c;
2942 
2943   FORC3 mul[c] = dq[c]/div[c];
2944   FORC3 if (max < mul[c]) max = mul[c];
2945   FORC3 curvep[c] = foveon_make_curve (max, mul[c], filt);
2946 }
2947 
foveon_apply_curve(short * curve,int i)2948 int CLASS foveon_apply_curve (short *curve, int i)
2949 {
2950   if (abs(i) >= curve[0]) return 0;
2951   return i < 0 ? -curve[1-i] : curve[1+i];
2952 }
2953 
2954 #define image ((short (*)[4]) image)
2955 
foveon_interpolate()2956 void CLASS foveon_interpolate()
2957 {
2958   static const short hood[] = { -1,-1, -1,0, -1,1, 0,-1, 0,1, 1,-1, 1,0, 1,1 };
2959   short *pix, prev[3], *curve[8], (*shrink)[3];
2960   float cfilt=0, ddft[3][3][2], ppm[3][3][3];
2961   float cam_xyz[3][3], correct[3][3], last[3][3], trans[3][3];
2962   float chroma_dq[3], color_dq[3], diag[3][3], div[3];
2963   float (*black)[3], (*sgain)[3], (*sgrow)[3];
2964   float fsum[3], val, frow, num;
2965   int row, col, c, i, j, diff, sgx, irow, sum, min, max, limit;
2966   int dscr[2][2], dstb[4], (*smrow[7])[3], total[4], ipix[3];
2967   int work[3][3], smlast, smred, smred_p=0, dev[3];
2968   int satlev[3], keep[4], active[4];
2969   unsigned dim[3], *badpix;
2970   double dsum=0, trsum[3];
2971   char str[128];
2972   const char* cp;
2973 
2974   if (verbose)
2975     fprintf (stderr,_("Foveon interpolation...\n"));
2976 
2977   foveon_fixed (dscr, 4, "DarkShieldColRange");
2978   foveon_fixed (ppm[0][0], 27, "PostPolyMatrix");
2979   foveon_fixed (satlev, 3, "SaturationLevel");
2980   foveon_fixed (keep, 4, "KeepImageArea");
2981   foveon_fixed (active, 4, "ActiveImageArea");
2982   foveon_fixed (chroma_dq, 3, "ChromaDQ");
2983   foveon_fixed (color_dq, 3,
2984 	foveon_camf_param ("IncludeBlocks", "ColorDQ") ?
2985 		"ColorDQ" : "ColorDQCamRGB");
2986   if (foveon_camf_param ("IncludeBlocks", "ColumnFilter"))
2987   		 foveon_fixed (&cfilt, 1, "ColumnFilter");
2988 
2989   memset (ddft, 0, sizeof ddft);
2990   if (!foveon_camf_param ("IncludeBlocks", "DarkDrift")
2991 	 || !foveon_fixed (ddft[1][0], 12, "DarkDrift"))
2992     for (i=0; i < 2; i++) {
2993       foveon_fixed (dstb, 4, i ? "DarkShieldBottom":"DarkShieldTop");
2994       for (row = dstb[1]; row <= dstb[3]; row++)
2995 	for (col = dstb[0]; col <= dstb[2]; col++)
2996 	  FORC3 ddft[i+1][c][1] += (short) image[row*width+col][c];
2997       FORC3 ddft[i+1][c][1] /= (dstb[3]-dstb[1]+1) * (dstb[2]-dstb[0]+1);
2998     }
2999 
3000   if (!(cp = foveon_camf_param ("WhiteBalanceIlluminants", model2)))
3001   { fprintf (stderr,_("%s: Invalid white balance \"%s\"\n"), ifname, model2);
3002     return; }
3003   foveon_fixed (cam_xyz, 9, cp);
3004   foveon_fixed (correct, 9,
3005 	foveon_camf_param ("WhiteBalanceCorrections", model2));
3006   memset (last, 0, sizeof last);
3007   for (i=0; i < 3; i++)
3008     for (j=0; j < 3; j++)
3009       FORC3 last[i][j] += correct[i][c] * cam_xyz[c][j];
3010 
3011   #define LAST(x,y) last[(i+x)%3][(c+y)%3]
3012   for (i=0; i < 3; i++)
3013     FORC3 diag[c][i] = LAST(1,1)*LAST(2,2) - LAST(1,2)*LAST(2,1);
3014   #undef LAST
3015   FORC3 div[c] = diag[c][0]*0.3127 + diag[c][1]*0.329 + diag[c][2]*0.3583;
3016   sprintf (str, "%sRGBNeutral", model2);
3017   if (foveon_camf_param ("IncludeBlocks", str))
3018     foveon_fixed (div, 3, str);
3019   num = 0;
3020   FORC3 if (num < div[c]) num = div[c];
3021   FORC3 div[c] /= num;
3022 
3023   memset (trans, 0, sizeof trans);
3024   for (i=0; i < 3; i++)
3025     for (j=0; j < 3; j++)
3026       FORC3 trans[i][j] += rgb_cam[i][c] * last[c][j] * div[j];
3027   FORC3 trsum[c] = trans[c][0] + trans[c][1] + trans[c][2];
3028   dsum = (6*trsum[0] + 11*trsum[1] + 3*trsum[2]) / 20;
3029   for (i=0; i < 3; i++)
3030     FORC3 last[i][c] = trans[i][c] * dsum / trsum[i];
3031   memset (trans, 0, sizeof trans);
3032   for (i=0; i < 3; i++)
3033     for (j=0; j < 3; j++)
3034       FORC3 trans[i][j] += (i==c ? 32 : -1) * last[c][j] / 30;
3035 
3036   foveon_make_curves (curve, color_dq, div, cfilt);
3037   FORC3 chroma_dq[c] /= 3;
3038   foveon_make_curves (curve+3, chroma_dq, div, cfilt);
3039   FORC3 dsum += chroma_dq[c] / div[c];
3040   curve[6] = foveon_make_curve (dsum, dsum, cfilt);
3041   curve[7] = foveon_make_curve (dsum*2, dsum*2, cfilt);
3042 
3043   sgain = (float (*)[3]) foveon_camf_matrix (dim, "SpatialGain");
3044   if (!sgain) return;
3045   sgrow = (float (*)[3]) calloc (dim[1], sizeof *sgrow);
3046   sgx = (width + dim[1]-2) / (dim[1]-1);
3047 
3048   black = (float (*)[3]) calloc (height, sizeof *black);
3049   for (row=0; row < height; row++) {
3050     for (i=0; i < 6; i++)
3051       ddft[0][0][i] = ddft[1][0][i] +
3052 	row / (height-1.0) * (ddft[2][0][i] - ddft[1][0][i]);
3053     FORC3 black[row][c] =
3054  	( foveon_avg (image[row*width]+c, dscr[0], cfilt) +
3055 	  foveon_avg (image[row*width]+c, dscr[1], cfilt) * 3
3056 	  - ddft[0][c][0] ) / 4 - ddft[0][c][1];
3057   }
3058   memcpy (black, black+8, sizeof *black*8);
3059   memcpy (black+height-11, black+height-22, 11*sizeof *black);
3060   memcpy (last, black, sizeof last);
3061 
3062   for (row=1; row < height-1; row++) {
3063     FORC3 if (last[1][c] > last[0][c]) {
3064 	if (last[1][c] > last[2][c])
3065 	  black[row][c] = (last[0][c] > last[2][c]) ? last[0][c]:last[2][c];
3066       } else
3067 	if (last[1][c] < last[2][c])
3068 	  black[row][c] = (last[0][c] < last[2][c]) ? last[0][c]:last[2][c];
3069     memmove (last, last+1, 2*sizeof last[0]);
3070     memcpy (last[2], black[row+1], sizeof last[2]);
3071   }
3072   FORC3 black[row][c] = (last[0][c] + last[1][c])/2;
3073   FORC3 black[0][c] = (black[1][c] + black[3][c])/2;
3074 
3075   val = 1 - exp(-1/24.0);
3076   memcpy (fsum, black, sizeof fsum);
3077   for (row=1; row < height; row++)
3078     FORC3 fsum[c] += black[row][c] =
3079 	(black[row][c] - black[row-1][c])*val + black[row-1][c];
3080   memcpy (last[0], black[height-1], sizeof last[0]);
3081   FORC3 fsum[c] /= height;
3082   for (row = height; row--; )
3083     FORC3 last[0][c] = black[row][c] =
3084 	(black[row][c] - fsum[c] - last[0][c])*val + last[0][c];
3085 
3086   memset (total, 0, sizeof total);
3087   for (row=2; row < height; row+=4)
3088     for (col=2; col < width; col+=4) {
3089       FORC3 total[c] += (short) image[row*width+col][c];
3090       total[3]++;
3091     }
3092   for (row=0; row < height; row++)
3093     FORC3 black[row][c] += fsum[c]/2 + total[c]/(total[3]*100.0);
3094 
3095   for (row=0; row < height; row++) {
3096     for (i=0; i < 6; i++)
3097       ddft[0][0][i] = ddft[1][0][i] +
3098 	row / (height-1.0) * (ddft[2][0][i] - ddft[1][0][i]);
3099     pix = image[row*width];
3100     memcpy (prev, pix, sizeof prev);
3101     frow = row / (height-1.0) * (dim[2]-1);
3102     if ((irow = frow) == dim[2]-1) irow--;
3103     frow -= irow;
3104     for (i=0; i < dim[1]; i++)
3105       FORC3 sgrow[i][c] = sgain[ irow   *dim[1]+i][c] * (1-frow) +
3106 			  sgain[(irow+1)*dim[1]+i][c] *    frow;
3107     for (col=0; col < width; col++) {
3108       FORC3 {
3109 	diff = pix[c] - prev[c];
3110 	prev[c] = pix[c];
3111 	ipix[c] = pix[c] + floor ((diff + (diff*diff >> 14)) * cfilt
3112 		- ddft[0][c][1] - ddft[0][c][0] * ((float) col/width - 0.5)
3113 		- black[row][c] );
3114       }
3115       FORC3 {
3116 	work[0][c] = ipix[c] * ipix[c] >> 14;
3117 	work[2][c] = ipix[c] * work[0][c] >> 14;
3118 	work[1][2-c] = ipix[(c+1) % 3] * ipix[(c+2) % 3] >> 14;
3119       }
3120       FORC3 {
3121 	for (val=i=0; i < 3; i++)
3122 	  for (  j=0; j < 3; j++)
3123 	    val += ppm[c][i][j] * work[i][j];
3124 	ipix[c] = floor ((ipix[c] + floor(val)) *
3125 		( sgrow[col/sgx  ][c] * (sgx - col%sgx) +
3126 		  sgrow[col/sgx+1][c] * (col%sgx) ) / sgx / div[c]);
3127 	if (ipix[c] > 32000) ipix[c] = 32000;
3128 	pix[c] = ipix[c];
3129       }
3130       pix += 4;
3131     }
3132   }
3133   free (black);
3134   free (sgrow);
3135   free (sgain);
3136 
3137   if ((badpix = (unsigned int *) foveon_camf_matrix (dim, "BadPixels"))) {
3138     for (i=0; i < dim[0]; i++) {
3139       col = (badpix[i] >> 8 & 0xfff) - keep[0];
3140       row = (badpix[i] >> 20       ) - keep[1];
3141       if ((unsigned)(row-1) > height-3 || (unsigned)(col-1) > width-3)
3142 	continue;
3143       memset (fsum, 0, sizeof fsum);
3144       for (sum=j=0; j < 8; j++)
3145 	if (badpix[i] & (1 << j)) {
3146 	  FORC3 fsum[c] += (short)
3147 		image[(row+hood[j*2])*width+col+hood[j*2+1]][c];
3148 	  sum++;
3149 	}
3150       if (sum) FORC3 image[row*width+col][c] = fsum[c]/sum;
3151     }
3152     free (badpix);
3153   }
3154 
3155   /* Array for 5x5 Gaussian averaging of red values */
3156   smrow[6] = (int (*)[3]) calloc (width*5, sizeof **smrow);
3157   merror (smrow[6], "foveon_interpolate()");
3158   for (i=0; i < 5; i++)
3159     smrow[i] = smrow[6] + i*width;
3160 
3161   /* Sharpen the reds against these Gaussian averages */
3162   for (smlast=-1, row=2; row < height-2; row++) {
3163     while (smlast < row+2) {
3164       for (i=0; i < 6; i++)
3165 	smrow[(i+5) % 6] = smrow[i];
3166       pix = image[++smlast*width+2];
3167       for (col=2; col < width-2; col++) {
3168 	smrow[4][col][0] =
3169 	  (pix[0]*6 + (pix[-4]+pix[4])*4 + pix[-8]+pix[8] + 8) >> 4;
3170 	pix += 4;
3171       }
3172     }
3173     pix = image[row*width+2];
3174     for (col=2; col < width-2; col++) {
3175       smred = ( 6 *  smrow[2][col][0]
3176 	      + 4 * (smrow[1][col][0] + smrow[3][col][0])
3177 	      +      smrow[0][col][0] + smrow[4][col][0] + 8 ) >> 4;
3178       if (col == 2)
3179 	smred_p = smred;
3180       i = pix[0] + ((pix[0] - ((smred*7 + smred_p) >> 3)) >> 3);
3181       if (i > 32000) i = 32000;
3182       pix[0] = i;
3183       smred_p = smred;
3184       pix += 4;
3185     }
3186   }
3187 
3188   /* Adjust the brighter pixels for better linearity */
3189   min = 0xffff;
3190   FORC3 {
3191     i = satlev[c] / div[c];
3192     if (min > i) min = i;
3193   }
3194   limit = min * 9 >> 4;
3195   for (pix=image[0]; pix < image[height*width]; pix+=4) {
3196     if (pix[0] <= limit || pix[1] <= limit || pix[2] <= limit)
3197       continue;
3198     min = max = pix[0];
3199     for (c=1; c < 3; c++) {
3200       if (min > pix[c]) min = pix[c];
3201       if (max < pix[c]) max = pix[c];
3202     }
3203     if (min >= limit*2) {
3204       pix[0] = pix[1] = pix[2] = max;
3205     } else {
3206       i = 0x4000 - ((min - limit) << 14) / limit;
3207       i = 0x4000 - (i*i >> 14);
3208       i = i*i >> 14;
3209       FORC3 pix[c] += (max - pix[c]) * i >> 14;
3210     }
3211   }
3212 /*
3213    Because photons that miss one detector often hit another,
3214    the sum R+G+B is much less noisy than the individual colors.
3215    So smooth the hues without smoothing the total.
3216  */
3217   for (smlast=-1, row=2; row < height-2; row++) {
3218     while (smlast < row+2) {
3219       for (i=0; i < 6; i++)
3220 	smrow[(i+5) % 6] = smrow[i];
3221       pix = image[++smlast*width+2];
3222       for (col=2; col < width-2; col++) {
3223 	FORC3 smrow[4][col][c] = (pix[c-4]+2*pix[c]+pix[c+4]+2) >> 2;
3224 	pix += 4;
3225       }
3226     }
3227     pix = image[row*width+2];
3228     for (col=2; col < width-2; col++) {
3229       FORC3 dev[c] = -foveon_apply_curve (curve[7], pix[c] -
3230 	((smrow[1][col][c] + 2*smrow[2][col][c] + smrow[3][col][c]) >> 2));
3231       sum = (dev[0] + dev[1] + dev[2]) >> 3;
3232       FORC3 pix[c] += dev[c] - sum;
3233       pix += 4;
3234     }
3235   }
3236   for (smlast=-1, row=2; row < height-2; row++) {
3237     while (smlast < row+2) {
3238       for (i=0; i < 6; i++)
3239 	smrow[(i+5) % 6] = smrow[i];
3240       pix = image[++smlast*width+2];
3241       for (col=2; col < width-2; col++) {
3242 	FORC3 smrow[4][col][c] =
3243 		(pix[c-8]+pix[c-4]+pix[c]+pix[c+4]+pix[c+8]+2) >> 2;
3244 	pix += 4;
3245       }
3246     }
3247     pix = image[row*width+2];
3248     for (col=2; col < width-2; col++) {
3249       for (total[3]=375, sum=60, c=0; c < 3; c++) {
3250 	for (total[c]=i=0; i < 5; i++)
3251 	  total[c] += smrow[i][col][c];
3252 	total[3] += total[c];
3253 	sum += pix[c];
3254       }
3255       if (sum < 0) sum = 0;
3256       j = total[3] > 375 ? (sum << 16) / total[3] : sum * 174;
3257       FORC3 pix[c] += foveon_apply_curve (curve[6],
3258 		((j*total[c] + 0x8000) >> 16) - pix[c]);
3259       pix += 4;
3260     }
3261   }
3262 
3263   /* Transform the image to a different colorspace */
3264   for (pix=image[0]; pix < image[height*width]; pix+=4) {
3265     FORC3 pix[c] -= foveon_apply_curve (curve[c], pix[c]);
3266     sum = (pix[0]+pix[1]+pix[1]+pix[2]) >> 2;
3267     FORC3 pix[c] -= foveon_apply_curve (curve[c], pix[c]-sum);
3268     FORC3 {
3269       for (dsum=i=0; i < 3; i++)
3270 	dsum += trans[c][i] * pix[i];
3271       if (dsum < 0)  dsum = 0;
3272       if (dsum > 24000) dsum = 24000;
3273       ipix[c] = dsum + 0.5;
3274     }
3275     FORC3 pix[c] = ipix[c];
3276   }
3277 
3278   /* Smooth the image bottom-to-top and save at 1/4 scale */
3279   shrink = (short (*)[3]) calloc ((width/4) * (height/4), sizeof *shrink);
3280   merror (shrink, "foveon_interpolate()");
3281   for (row = height/4; row--; )
3282     for (col=0; col < width/4; col++) {
3283       ipix[0] = ipix[1] = ipix[2] = 0;
3284       for (i=0; i < 4; i++)
3285 	for (j=0; j < 4; j++)
3286 	  FORC3 ipix[c] += image[(row*4+i)*width+col*4+j][c];
3287       FORC3
3288 	if (row+2 > height/4)
3289 	  shrink[row*(width/4)+col][c] = ipix[c] >> 4;
3290 	else
3291 	  shrink[row*(width/4)+col][c] =
3292 	    (shrink[(row+1)*(width/4)+col][c]*1840 + ipix[c]*141 + 2048) >> 12;
3293     }
3294   /* From the 1/4-scale image, smooth right-to-left */
3295   for (row=0; row < (height & ~3); row++) {
3296     ipix[0] = ipix[1] = ipix[2] = 0;
3297     if ((row & 3) == 0)
3298       for (col = width & ~3 ; col--; )
3299 	FORC3 smrow[0][col][c] = ipix[c] =
3300 	  (shrink[(row/4)*(width/4)+col/4][c]*1485 + ipix[c]*6707 + 4096) >> 13;
3301 
3302   /* Then smooth left-to-right */
3303     ipix[0] = ipix[1] = ipix[2] = 0;
3304     for (col=0; col < (width & ~3); col++)
3305       FORC3 smrow[1][col][c] = ipix[c] =
3306 	(smrow[0][col][c]*1485 + ipix[c]*6707 + 4096) >> 13;
3307 
3308   /* Smooth top-to-bottom */
3309     if (row == 0)
3310       memcpy (smrow[2], smrow[1], sizeof **smrow * width);
3311     else
3312       for (col=0; col < (width & ~3); col++)
3313 	FORC3 smrow[2][col][c] =
3314 	  (smrow[2][col][c]*6707 + smrow[1][col][c]*1485 + 4096) >> 13;
3315 
3316   /* Adjust the chroma toward the smooth values */
3317     for (col=0; col < (width & ~3); col++) {
3318       for (i=j=30, c=0; c < 3; c++) {
3319 	i += smrow[2][col][c];
3320 	j += image[row*width+col][c];
3321       }
3322       j = (j << 16) / i;
3323       for (sum=c=0; c < 3; c++) {
3324 	ipix[c] = foveon_apply_curve (curve[c+3],
3325 	  ((smrow[2][col][c] * j + 0x8000) >> 16) - image[row*width+col][c]);
3326 	sum += ipix[c];
3327       }
3328       sum >>= 3;
3329       FORC3 {
3330 	i = image[row*width+col][c] + ipix[c] - sum;
3331 	if (i < 0) i = 0;
3332 	image[row*width+col][c] = i;
3333       }
3334     }
3335   }
3336   free (shrink);
3337   free (smrow[6]);
3338   for (i=0; i < 8; i++)
3339     free (curve[i]);
3340 
3341   /* Trim off the black border */
3342   active[1] -= keep[1];
3343   active[3] -= 2;
3344   i = active[2] - active[0];
3345   for (row=0; row < active[3]-active[1]; row++)
3346     memcpy (image[row*i], image[(row+active[1])*width+active[0]],
3347 	 i * sizeof *image);
3348   width = i;
3349   height = row;
3350 }
3351 #undef image
3352 
3353 /* RESTRICTED code ends here */
3354 
3355 /*
3356    Seach from the current directory up to the root looking for
3357    a ".badpixels" file, and fix those pixels now.
3358  */
bad_pixels(const char * cfname)3359 void CLASS bad_pixels (const char *cfname)
3360 {
3361   FILE *fp=0;
3362   char *fname, *cp, line[128];
3363   int len, time, row, col, r, c, rad, tot, n, fixed=0;
3364 
3365   if (!filters) return;
3366   if (cfname)
3367     fp = fopen (cfname, "r");
3368   else {
3369     for (len=32 ; ; len *= 2) {
3370       fname = (char *) malloc (len);
3371       if (!fname) return;
3372       if (getcwd (fname, len-16)) break;
3373       free (fname);
3374       if (errno != ERANGE) return;
3375     }
3376 #if defined(WIN32) || defined(DJGPP)
3377     if (fname[1] == ':')
3378       memmove (fname, fname+2, len-2);
3379     for (cp=fname; *cp; cp++)
3380       if (*cp == '\\') *cp = '/';
3381 #endif
3382     cp = fname + strlen(fname);
3383     if (cp[-1] == '/') cp--;
3384     while (*fname == '/') {
3385       strcpy (cp, "/.badpixels");
3386       if ((fp = fopen (fname, "r"))) break;
3387       if (cp == fname) break;
3388       while (*--cp != '/');
3389     }
3390     free (fname);
3391   }
3392   if (!fp) return;
3393   while (fgets (line, 128, fp)) {
3394     cp = strchr (line, '#');
3395     if (cp) *cp = 0;
3396     if (sscanf (line, "%d %d %d", &col, &row, &time) != 3) continue;
3397     if ((unsigned) col >= width || (unsigned) row >= height) continue;
3398     if (time > timestamp) continue;
3399     for (tot=n=0, rad=1; rad < 3 && n==0; rad++)
3400       for (r = row-rad; r <= row+rad; r++)
3401 	for (c = col-rad; c <= col+rad; c++)
3402 	  if ((unsigned) r < height && (unsigned) c < width &&
3403 		(r != row || c != col) && fc(r,c) == fc(row,col)) {
3404 	    tot += BAYER2(r,c);
3405 	    n++;
3406 	  }
3407     BAYER2(row,col) = tot/n;
3408     if (verbose) {
3409       if (!fixed++)
3410 	fprintf (stderr,_("Fixed dead pixels at:"));
3411       fprintf (stderr, " %d,%d", col, row);
3412     }
3413   }
3414   if (fixed) fputc ('\n', stderr);
3415   fclose (fp);
3416 }
3417 
subtract(const char * fname)3418 void CLASS subtract (const char *fname)
3419 {
3420   FILE *fp;
3421   int dim[3]={0,0,0}, comment=0, number=0, error=0, nd=0, c, row, col;
3422   ushort *pixel;
3423 
3424   if (!(fp = fopen (fname, "rb"))) {
3425     perror (fname);  return;
3426   }
3427   if (fgetc(fp) != 'P' || fgetc(fp) != '5') error = 1;
3428   while (!error && nd < 3 && (c = fgetc(fp)) != EOF) {
3429     if (c == '#')  comment = 1;
3430     if (c == '\n') comment = 0;
3431     if (comment) continue;
3432     if (isdigit(c)) number = 1;
3433     if (number) {
3434       if (isdigit(c)) dim[nd] = dim[nd]*10 + c -'0';
3435       else if (isspace(c)) {
3436 	number = 0;  nd++;
3437       } else error = 1;
3438     }
3439   }
3440   if (error || nd < 3) {
3441     fprintf (stderr,_("%s is not a valid PGM file!\n"), fname);
3442     fclose (fp);  return;
3443   } else if (dim[0] != width || dim[1] != height || dim[2] != 65535) {
3444     fprintf (stderr,_("%s has the wrong dimensions!\n"), fname);
3445     fclose (fp);  return;
3446   }
3447   pixel = (ushort *) calloc (width, sizeof *pixel);
3448   merror (pixel, "subtract()");
3449   for (row=0; row < height; row++) {
3450     fread (pixel, 2, width, fp);
3451     for (col=0; col < width; col++)
3452       BAYER(row,col) = MAX (BAYER(row,col) - ntohs(pixel[col]), 0);
3453   }
3454   free (pixel);
3455   fclose (fp);
3456   memset (cblack, 0, sizeof cblack);
3457   black = 0;
3458 }
3459 
gamma_curve(double pwr,double ts,int mode,int imax)3460 void CLASS gamma_curve (double pwr, double ts, int mode, int imax)
3461 {
3462   int i;
3463   double g[6], bnd[2]={0,0}, r;
3464 
3465   g[0] = pwr;
3466   g[1] = ts;
3467   g[2] = g[3] = g[4] = 0;
3468   bnd[g[1] >= 1] = 1;
3469   if (g[1] && (g[1]-1)*(g[0]-1) <= 0) {
3470     for (i=0; i < 48; i++) {
3471       g[2] = (bnd[0] + bnd[1])/2;
3472       if (g[0]) bnd[(pow(g[2]/g[1],-g[0]) - 1)/g[0] - 1/g[2] > -1] = g[2];
3473       else	bnd[g[2]/exp(1-1/g[2]) < g[1]] = g[2];
3474     }
3475     g[3] = g[2] / g[1];
3476     if (g[0]) g[4] = g[2] * (1/g[0] - 1);
3477   }
3478   if (g[0]) g[5] = 1 / (g[1]*SQR(g[3])/2 - g[4]*(1 - g[3]) +
3479 		(1 - pow(g[3],1+g[0]))*(1 + g[4])/(1 + g[0])) - 1;
3480   else      g[5] = 1 / (g[1]*SQR(g[3])/2 + 1
3481 		- g[2] - g[3] -	g[2]*g[3]*(log(g[3]) - 1)) - 1;
3482   if (!mode--) {
3483     memcpy (gamm, g, sizeof gamm);
3484     return;
3485   }
3486   for (i=0; i < 0x10000; i++) {
3487     curve[i] = 0xffff;
3488     if ((r = (double) i / imax) < 1)
3489       curve[i] = 0x10000 * ( mode
3490 	? (r < g[3] ? r*g[1] : (g[0] ? pow( r,g[0])*(1+g[4])-g[4]    : log(r)*g[2]+1))
3491 	: (r < g[2] ? r/g[1] : (g[0] ? pow((r+g[4])/(1+g[4]),1/g[0]) : exp((r-1)/g[2]))));
3492   }
3493 }
3494 
pseudoinverse(double (* in)[3],double (* out)[3],int size)3495 void CLASS pseudoinverse (double (*in)[3], double (*out)[3], int size)
3496 {
3497   double work[3][6], num;
3498   int i, j, k;
3499 
3500   for (i=0; i < 3; i++) {
3501     for (j=0; j < 6; j++)
3502       work[i][j] = j == i+3;
3503     for (j=0; j < 3; j++)
3504       for (k=0; k < size; k++)
3505 	work[i][j] += in[k][i] * in[k][j];
3506   }
3507   for (i=0; i < 3; i++) {
3508     num = work[i][i];
3509     for (j=0; j < 6; j++)
3510       work[i][j] /= num;
3511     for (k=0; k < 3; k++) {
3512       if (k==i) continue;
3513       num = work[k][i];
3514       for (j=0; j < 6; j++)
3515 	work[k][j] -= work[i][j] * num;
3516     }
3517   }
3518   for (i=0; i < size; i++)
3519     for (j=0; j < 3; j++)
3520       for (out[i][j]=k=0; k < 3; k++)
3521 	out[i][j] += work[j][k+3] * in[i][k];
3522 }
3523 
cam_xyz_coeff(double cam_xyz[4][3])3524 void CLASS cam_xyz_coeff (double cam_xyz[4][3])
3525 {
3526   double cam_rgb[4][3], inverse[4][3], num;
3527   int i, j, k;
3528 
3529   for (i=0; i < colors; i++)		/* Multiply out XYZ colorspace */
3530     for (j=0; j < 3; j++)
3531       for (cam_rgb[i][j] = k=0; k < 3; k++)
3532 	cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j];
3533 
3534   for (i=0; i < colors; i++) {		/* Normalize cam_rgb so that */
3535     for (num=j=0; j < 3; j++)		/* cam_rgb * (1,1,1) is (1,1,1,1) */
3536       num += cam_rgb[i][j];
3537     for (j=0; j < 3; j++)
3538       cam_rgb[i][j] /= num;
3539     pre_mul[i] = 1 / num;
3540   }
3541   pseudoinverse (cam_rgb, inverse, colors);
3542   for (raw_color = i=0; i < 3; i++)
3543     for (j=0; j < colors; j++)
3544       rgb_cam[i][j] = inverse[j][i];
3545 }
3546 
3547 #ifdef COLORCHECK
colorcheck()3548 void CLASS colorcheck()
3549 {
3550 #define NSQ 24
3551 // Coordinates of the GretagMacbeth ColorChecker squares
3552 // width, height, 1st_column, 1st_row
3553   int cut[NSQ][4];			// you must set these
3554 // ColorChecker Chart under 6500-kelvin illumination
3555   static const double gmb_xyY[NSQ][3] = {
3556     { 0.400, 0.350, 10.1 },		// Dark Skin
3557     { 0.377, 0.345, 35.8 },		// Light Skin
3558     { 0.247, 0.251, 19.3 },		// Blue Sky
3559     { 0.337, 0.422, 13.3 },		// Foliage
3560     { 0.265, 0.240, 24.3 },		// Blue Flower
3561     { 0.261, 0.343, 43.1 },		// Bluish Green
3562     { 0.506, 0.407, 30.1 },		// Orange
3563     { 0.211, 0.175, 12.0 },		// Purplish Blue
3564     { 0.453, 0.306, 19.8 },		// Moderate Red
3565     { 0.285, 0.202, 6.6 },		// Purple
3566     { 0.380, 0.489, 44.3 },		// Yellow Green
3567     { 0.473, 0.438, 43.1 },		// Orange Yellow
3568     { 0.187, 0.129, 6.1 },		// Blue
3569     { 0.305, 0.478, 23.4 },		// Green
3570     { 0.539, 0.313, 12.0 },		// Red
3571     { 0.448, 0.470, 59.1 },		// Yellow
3572     { 0.364, 0.233, 19.8 },		// Magenta
3573     { 0.196, 0.252, 19.8 },		// Cyan
3574     { 0.310, 0.316, 90.0 },		// White
3575     { 0.310, 0.316, 59.1 },		// Neutral 8
3576     { 0.310, 0.316, 36.2 },		// Neutral 6.5
3577     { 0.310, 0.316, 19.8 },		// Neutral 5
3578     { 0.310, 0.316, 9.0 },		// Neutral 3.5
3579     { 0.310, 0.316, 3.1 } };		// Black
3580   double gmb_cam[NSQ][4], gmb_xyz[NSQ][3];
3581   double inverse[NSQ][3], cam_xyz[4][3], num;
3582   int c, i, j, k, sq, row, col, count[4];
3583 
3584   memset (gmb_cam, 0, sizeof gmb_cam);
3585   for (sq=0; sq < NSQ; sq++) {
3586     FORCC count[c] = 0;
3587     for   (row=cut[sq][3]; row < cut[sq][3]+cut[sq][1]; row++)
3588       for (col=cut[sq][2]; col < cut[sq][2]+cut[sq][0]; col++) {
3589 	c = FC(row,col);
3590 	if (c >= colors) c -= 2;
3591 	gmb_cam[sq][c] += BAYER(row,col);
3592 	count[c]++;
3593       }
3594     FORCC gmb_cam[sq][c] = gmb_cam[sq][c]/count[c] - black;
3595     gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1];
3596     gmb_xyz[sq][1] = gmb_xyY[sq][2];
3597     gmb_xyz[sq][2] = gmb_xyY[sq][2] *
3598 		(1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1];
3599   }
3600   pseudoinverse (gmb_xyz, inverse, NSQ);
3601   for (i=0; i < colors; i++)
3602     for (j=0; j < 3; j++)
3603       for (cam_xyz[i][j] = k=0; k < NSQ; k++)
3604 	cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j];
3605   cam_xyz_coeff (cam_xyz);
3606   if (verbose) {
3607     printf ("    { \"%s %s\", %d,\n\t{", make, model, black);
3608     num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]);
3609     FORCC for (j=0; j < 3; j++)
3610       printf ("%c%d", (c | j) ? ',':' ', (int) (cam_xyz[c][j] * num + 0.5));
3611     puts (" } },");
3612   }
3613 #undef NSQ
3614 }
3615 #endif
3616 
hat_transform(float * temp,float * base,int st,int size,int sc)3617 void CLASS hat_transform (float *temp, float *base, int st, int size, int sc)
3618 {
3619   int i;
3620   for (i=0; i < sc; i++)
3621     temp[i] = 2*base[st*i] + base[st*(sc-i)] + base[st*(i+sc)];
3622   for (; i+sc < size; i++)
3623     temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(i+sc)];
3624   for (; i < size; i++)
3625     temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(2*size-2-(i+sc))];
3626 }
3627 
wavelet_denoise()3628 void CLASS wavelet_denoise()
3629 {
3630   float *fimg=0, *temp, thold, mul[2], avg, diff;
3631   int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2];
3632   ushort *window[4];
3633   static const float noise[] =
3634   { 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 };
3635 
3636   if (verbose) fprintf (stderr,_("Wavelet denoising...\n"));
3637 
3638   while (maximum << scale < 0x10000) scale++;
3639   maximum <<= --scale;
3640   black <<= scale;
3641   FORC4 cblack[c] <<= scale;
3642   if ((size = iheight*iwidth) < 0x15550000)
3643     fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg);
3644   merror (fimg, "wavelet_denoise()");
3645   temp = fimg + size*3;
3646   if ((nc = colors) == 3 && filters) nc++;
3647   FORC(nc) {			/* denoise R,G1,B,G3 individually */
3648     for (i=0; i < size; i++)
3649       fimg[i] = 256 * sqrt(image[i][c] << scale);
3650     for (hpass=lev=0; lev < 5; lev++) {
3651       lpass = size*((lev & 1)+1);
3652       for (row=0; row < iheight; row++) {
3653 	hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev);
3654 	for (col=0; col < iwidth; col++)
3655 	  fimg[lpass + row*iwidth + col] = temp[col] * 0.25;
3656       }
3657       for (col=0; col < iwidth; col++) {
3658 	hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev);
3659 	for (row=0; row < iheight; row++)
3660 	  fimg[lpass + row*iwidth + col] = temp[row] * 0.25;
3661       }
3662       thold = threshold * noise[lev];
3663       for (i=0; i < size; i++) {
3664 	fimg[hpass+i] -= fimg[lpass+i];
3665 	if	(fimg[hpass+i] < -thold) fimg[hpass+i] += thold;
3666 	else if (fimg[hpass+i] >  thold) fimg[hpass+i] -= thold;
3667 	else	 fimg[hpass+i] = 0;
3668 	if (hpass) fimg[i] += fimg[hpass+i];
3669       }
3670       hpass = lpass;
3671     }
3672     for (i=0; i < size; i++)
3673       image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000);
3674   }
3675   if (filters && colors == 3) {  /* pull G1 and G3 closer together */
3676     for (row=0; row < 2; row++) {
3677       mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1];
3678       blk[row] = cblack[FC(row,0) | 1];
3679     }
3680     for (i=0; i < 4; i++)
3681       window[i] = (ushort *) fimg + width*i;
3682     for (wlast=-1, row=1; row < height-1; row++) {
3683       while (wlast < row+1) {
3684 	for (wlast++, i=0; i < 4; i++)
3685 	  window[(i+3) & 3] = window[i];
3686 	for (col = FC(wlast,1) & 1; col < width; col+=2)
3687 	  window[2][col] = BAYER(wlast,col);
3688       }
3689       thold = threshold/512;
3690       for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) {
3691 	avg = ( window[0][col-1] + window[0][col+1] +
3692 		window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 )
3693 	      * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5;
3694 	avg = avg < 0 ? 0 : sqrt(avg);
3695 	diff = sqrt(BAYER(row,col)) - avg;
3696 	if      (diff < -thold) diff += thold;
3697 	else if (diff >  thold) diff -= thold;
3698 	else diff = 0;
3699 	BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5);
3700       }
3701     }
3702   }
3703   free (fimg);
3704 }
3705 
scale_colors()3706 void CLASS scale_colors()
3707 {
3708   unsigned bottom, right, size, row, col, ur, uc, i, x, y, c, sum[8];
3709   int val, dark, sat;
3710   double dsum[8], dmin, dmax;
3711   float scale_mul[4], fr, fc;
3712   ushort *img=0, *pix;
3713 
3714   FORC4 cblack[c] += black;
3715   if (user_mul[0])
3716     memcpy (pre_mul, user_mul, sizeof pre_mul);
3717   if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1)) {
3718     memset (dsum, 0, sizeof dsum);
3719     bottom = MIN (greybox[1]+greybox[3], height);
3720     right  = MIN (greybox[0]+greybox[2], width);
3721     for (row=greybox[1]; row < bottom; row += 8)
3722       for (col=greybox[0]; col < right; col += 8) {
3723 	memset (sum, 0, sizeof sum);
3724 	for (y=row; y < row+8 && y < bottom; y++)
3725 	  for (x=col; x < col+8 && x < right; x++)
3726 	    FORC4 {
3727 	      if (filters) {
3728 		c = FC(y,x);
3729 		val = BAYER(y,x);
3730 	      } else
3731 		val = image[y*width+x][c];
3732 	      if (val > maximum-25) goto skip_block;
3733 	      if ((val -= cblack[c]) < 0) val = 0;
3734 	      sum[c] += val;
3735 	      sum[c+4]++;
3736 	      if (filters) break;
3737 	    }
3738 	FORC(8) dsum[c] += sum[c];
3739 skip_block: ;
3740       }
3741     FORC4 if (dsum[c]) pre_mul[c] = dsum[c+4] / dsum[c];
3742   }
3743   if (use_camera_wb && cam_mul[0] != -1) {
3744     memset (sum, 0, sizeof sum);
3745     for (row=0; row < 8; row++)
3746       for (col=0; col < 8; col++) {
3747 	c = FC(row,col);
3748 	if ((val = white[row][col] - cblack[c]) > 0)
3749 	  sum[c] += val;
3750 	sum[c+4]++;
3751       }
3752     if (sum[0] && sum[1] && sum[2] && sum[3])
3753       FORC4 pre_mul[c] = (float) sum[c+4] / sum[c];
3754     else if (cam_mul[0] && cam_mul[2])
3755       memcpy (pre_mul, cam_mul, sizeof pre_mul);
3756     else
3757       fprintf (stderr,_("%s: Cannot use camera white balance.\n"), ifname);
3758   }
3759   if (pre_mul[3] == 0) pre_mul[3] = colors < 4 ? pre_mul[1] : 1;
3760   dark = black;
3761   sat = maximum;
3762   if (threshold) wavelet_denoise();
3763   maximum -= black;
3764   for (dmin=DBL_MAX, dmax=c=0; c < 4; c++) {
3765     if (dmin > pre_mul[c])
3766 	dmin = pre_mul[c];
3767     if (dmax < pre_mul[c])
3768 	dmax = pre_mul[c];
3769   }
3770   if (!highlight) dmax = dmin;
3771   FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum;
3772   if (verbose) {
3773     fprintf (stderr,
3774       _("Scaling with darkness %d, saturation %d, and\nmultipliers"), dark, sat);
3775     FORC4 fprintf (stderr, " %f", pre_mul[c]);
3776     fputc ('\n', stderr);
3777   }
3778   size = iheight*iwidth;
3779   for (i=0; i < size*4; i++) {
3780     val = image[0][i];
3781     if (!val) continue;
3782     val -= cblack[i & 3];
3783     val *= scale_mul[i & 3];
3784     image[0][i] = CLIP(val);
3785   }
3786   if ((aber[0] != 1 || aber[2] != 1) && colors == 3) {
3787     if (verbose)
3788       fprintf (stderr,_("Correcting chromatic aberration...\n"));
3789     for (c=0; c < 4; c+=2) {
3790       if (aber[c] == 1) continue;
3791       img = (ushort *) malloc (size * sizeof *img);
3792       merror (img, "scale_colors()");
3793       for (i=0; i < size; i++)
3794 	img[i] = image[i][c];
3795       for (row=0; row < iheight; row++) {
3796 	ur = fr = (row - iheight*0.5) * aber[c] + iheight*0.5;
3797 	if (ur > iheight-2) continue;
3798 	fr -= ur;
3799 	for (col=0; col < iwidth; col++) {
3800 	  uc = fc = (col - iwidth*0.5) * aber[c] + iwidth*0.5;
3801 	  if (uc > iwidth-2) continue;
3802 	  fc -= uc;
3803 	  pix = img + ur*iwidth + uc;
3804 	  image[row*iwidth+col][c] =
3805 	    (pix[     0]*(1-fc) + pix[       1]*fc) * (1-fr) +
3806 	    (pix[iwidth]*(1-fc) + pix[iwidth+1]*fc) * fr;
3807 	}
3808       }
3809       free(img);
3810     }
3811   }
3812 }
3813 
pre_interpolate()3814 void CLASS pre_interpolate()
3815 {
3816   ushort (*img)[4];
3817   int row, col, c;
3818 
3819   if (shrink) {
3820     if (half_size) {
3821       height = iheight;
3822       width  = iwidth;
3823     } else {
3824       img = (ushort (*)[4]) calloc (height*width, sizeof *img);
3825       merror (img, "pre_interpolate()");
3826       for (row=0; row < height; row++)
3827 	for (col=0; col < width; col++) {
3828 	  c = fc(row,col);
3829 	  img[row*width+col][c] = image[(row >> 1)*iwidth+(col >> 1)][c];
3830 	}
3831       free (image);
3832       image = img;
3833       shrink = 0;
3834     }
3835   }
3836   if (filters && colors == 3) {
3837     if ((mix_green = four_color_rgb)) colors++;
3838     else {
3839       for (row = FC(1,0) >> 1; row < height; row+=2)
3840 	for (col = FC(row,1) & 1; col < width; col+=2)
3841 	  image[row*width+col][1] = image[row*width+col][3];
3842       filters &= ~((filters & 0x55555555) << 1);
3843     }
3844   }
3845   if (half_size) filters = 0;
3846 }
3847 
border_interpolate(int border)3848 void CLASS border_interpolate (int border)
3849 {
3850   unsigned row, col, y, x, f, c, sum[8];
3851 
3852   for (row=0; row < height; row++)
3853     for (col=0; col < width; col++) {
3854       if (col==border && row >= border && row < height-border)
3855 	col = width-border;
3856       memset (sum, 0, sizeof sum);
3857       for (y=row-1; y != row+2; y++)
3858 	for (x=col-1; x != col+2; x++)
3859 	  if (y < height && x < width) {
3860 	    f = fc(y,x);
3861 	    sum[f] += image[y*width+x][f];
3862 	    sum[f+4]++;
3863 	  }
3864       f = fc(row,col);
3865       FORCC if (c != f && sum[c+4])
3866 	image[row*width+col][c] = sum[c] / sum[c+4];
3867     }
3868 }
3869 
lin_interpolate()3870 void CLASS lin_interpolate()
3871 {
3872   int code[16][16][32], *ip, sum[4];
3873   int c, i, x, y, row, col, shift, color;
3874   ushort *pix;
3875 
3876   if (verbose) fprintf (stderr,_("Bilinear interpolation...\n"));
3877 
3878   border_interpolate(1);
3879   for (row=0; row < 16; row++)
3880     for (col=0; col < 16; col++) {
3881       ip = code[row][col];
3882       memset (sum, 0, sizeof sum);
3883       for (y=-1; y <= 1; y++)
3884 	for (x=-1; x <= 1; x++) {
3885 	  shift = (y==0) + (x==0);
3886 	  if (shift == 2) continue;
3887 	  color = fc(row+y,col+x);
3888 	  *ip++ = (width*y + x)*4 + color;
3889 	  *ip++ = shift;
3890 	  *ip++ = color;
3891 	  sum[color] += 1 << shift;
3892 	}
3893       FORCC
3894 	if (c != fc(row,col)) {
3895 	  *ip++ = c;
3896 	  *ip++ = 256 / sum[c];
3897 	}
3898     }
3899   for (row=1; row < height-1; row++)
3900     for (col=1; col < width-1; col++) {
3901       pix = image[row*width+col];
3902       ip = code[row & 15][col & 15];
3903       memset (sum, 0, sizeof sum);
3904       for (i=8; i--; ip+=3)
3905 	sum[ip[2]] += pix[ip[0]] << ip[1];
3906       for (i=colors; --i; ip+=2)
3907 	pix[ip[0]] = sum[ip[0]] * ip[1] >> 8;
3908     }
3909 }
3910 
3911 /*
3912    This algorithm is officially called:
3913 
3914    "Interpolation using a Threshold-based variable number of gradients"
3915 
3916    described in http://scien.stanford.edu/pages/labsite/1999/psych221/projects/99/tingchen/algodep/vargra.html
3917 
3918    I've extended the basic idea to work with non-Bayer filter arrays.
3919    Gradients are numbered clockwise from NW=0 to W=7.
3920  */
vng_interpolate()3921 void CLASS vng_interpolate()
3922 {
3923   static const signed char *cp, terms[] = {
3924     -2,-2,+0,-1,0,0x01, -2,-2,+0,+0,1,0x01, -2,-1,-1,+0,0,0x01,
3925     -2,-1,+0,-1,0,0x02, -2,-1,+0,+0,0,0x03, -2,-1,+0,+1,1,0x01,
3926     -2,+0,+0,-1,0,0x06, -2,+0,+0,+0,1,0x02, -2,+0,+0,+1,0,0x03,
3927     -2,+1,-1,+0,0,0x04, -2,+1,+0,-1,1,0x04, -2,+1,+0,+0,0,0x06,
3928     -2,+1,+0,+1,0,0x02, -2,+2,+0,+0,1,0x04, -2,+2,+0,+1,0,0x04,
3929     -1,-2,-1,+0,0,0x80, -1,-2,+0,-1,0,0x01, -1,-2,+1,-1,0,0x01,
3930     -1,-2,+1,+0,1,0x01, -1,-1,-1,+1,0,0x88, -1,-1,+1,-2,0,0x40,
3931     -1,-1,+1,-1,0,0x22, -1,-1,+1,+0,0,0x33, -1,-1,+1,+1,1,0x11,
3932     -1,+0,-1,+2,0,0x08, -1,+0,+0,-1,0,0x44, -1,+0,+0,+1,0,0x11,
3933     -1,+0,+1,-2,1,0x40, -1,+0,+1,-1,0,0x66, -1,+0,+1,+0,1,0x22,
3934     -1,+0,+1,+1,0,0x33, -1,+0,+1,+2,1,0x10, -1,+1,+1,-1,1,0x44,
3935     -1,+1,+1,+0,0,0x66, -1,+1,+1,+1,0,0x22, -1,+1,+1,+2,0,0x10,
3936     -1,+2,+0,+1,0,0x04, -1,+2,+1,+0,1,0x04, -1,+2,+1,+1,0,0x04,
3937     +0,-2,+0,+0,1,0x80, +0,-1,+0,+1,1,0x88, +0,-1,+1,-2,0,0x40,
3938     +0,-1,+1,+0,0,0x11, +0,-1,+2,-2,0,0x40, +0,-1,+2,-1,0,0x20,
3939     +0,-1,+2,+0,0,0x30, +0,-1,+2,+1,1,0x10, +0,+0,+0,+2,1,0x08,
3940     +0,+0,+2,-2,1,0x40, +0,+0,+2,-1,0,0x60, +0,+0,+2,+0,1,0x20,
3941     +0,+0,+2,+1,0,0x30, +0,+0,+2,+2,1,0x10, +0,+1,+1,+0,0,0x44,
3942     +0,+1,+1,+2,0,0x10, +0,+1,+2,-1,1,0x40, +0,+1,+2,+0,0,0x60,
3943     +0,+1,+2,+1,0,0x20, +0,+1,+2,+2,0,0x10, +1,-2,+1,+0,0,0x80,
3944     +1,-1,+1,+1,0,0x88, +1,+0,+1,+2,0,0x08, +1,+0,+2,-1,0,0x40,
3945     +1,+0,+2,+1,0,0x10
3946   }, chood[] = { -1,-1, -1,0, -1,+1, 0,+1, +1,+1, +1,0, +1,-1, 0,-1 };
3947   ushort (*brow[5])[4], *pix;
3948   int prow=7, pcol=1, *ip, *code[16][16], gval[8], gmin, gmax, sum[4];
3949   int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag;
3950   int g, diff, thold, num, c;
3951 
3952   lin_interpolate();
3953   if (verbose) fprintf (stderr,_("VNG interpolation...\n"));
3954 
3955   if (filters == 1) prow = pcol = 15;
3956   ip = (int *) calloc ((prow+1)*(pcol+1), 1280);
3957   merror (ip, "vng_interpolate()");
3958   for (row=0; row <= prow; row++)		/* Precalculate for VNG */
3959     for (col=0; col <= pcol; col++) {
3960       code[row][col] = ip;
3961       for (cp=terms, t=0; t < 64; t++) {
3962 	y1 = *cp++;  x1 = *cp++;
3963 	y2 = *cp++;  x2 = *cp++;
3964 	weight = *cp++;
3965 	grads = *cp++;
3966 	color = fc(row+y1,col+x1);
3967 	if (fc(row+y2,col+x2) != color) continue;
3968 	diag = (fc(row,col+1) == color && fc(row+1,col) == color) ? 2:1;
3969 	if (abs(y1-y2) == diag && abs(x1-x2) == diag) continue;
3970 	*ip++ = (y1*width + x1)*4 + color;
3971 	*ip++ = (y2*width + x2)*4 + color;
3972 	*ip++ = weight;
3973 	for (g=0; g < 8; g++)
3974 	  if (grads & 1<<g) *ip++ = g;
3975 	*ip++ = -1;
3976       }
3977       *ip++ = INT_MAX;
3978       for (cp=chood, g=0; g < 8; g++) {
3979 	y = *cp++;  x = *cp++;
3980 	*ip++ = (y*width + x) * 4;
3981 	color = fc(row,col);
3982 	if (fc(row+y,col+x) != color && fc(row+y*2,col+x*2) == color)
3983 	  *ip++ = (y*width + x) * 8 + color;
3984 	else
3985 	  *ip++ = 0;
3986       }
3987     }
3988   brow[4] = (ushort (*)[4]) calloc (width*3, sizeof **brow);
3989   merror (brow[4], "vng_interpolate()");
3990   for (row=0; row < 3; row++)
3991     brow[row] = brow[4] + row*width;
3992   for (row=2; row < height-2; row++) {		/* Do VNG interpolation */
3993     for (col=2; col < width-2; col++) {
3994       pix = image[row*width+col];
3995       ip = code[row & prow][col & pcol];
3996       memset (gval, 0, sizeof gval);
3997       while ((g = ip[0]) != INT_MAX) {		/* Calculate gradients */
3998 	diff = ABS(pix[g] - pix[ip[1]]) << ip[2];
3999 	gval[ip[3]] += diff;
4000 	ip += 5;
4001 	if ((g = ip[-1]) == -1) continue;
4002 	gval[g] += diff;
4003 	while ((g = *ip++) != -1)
4004 	  gval[g] += diff;
4005       }
4006       ip++;
4007       gmin = gmax = gval[0];			/* Choose a threshold */
4008       for (g=1; g < 8; g++) {
4009 	if (gmin > gval[g]) gmin = gval[g];
4010 	if (gmax < gval[g]) gmax = gval[g];
4011       }
4012       if (gmax == 0) {
4013 	memcpy (brow[2][col], pix, sizeof *image);
4014 	continue;
4015       }
4016       thold = gmin + (gmax >> 1);
4017       memset (sum, 0, sizeof sum);
4018       color = fc(row,col);
4019       for (num=g=0; g < 8; g++,ip+=2) {		/* Average the neighbors */
4020 	if (gval[g] <= thold) {
4021 	  FORCC
4022 	    if (c == color && ip[1])
4023 	      sum[c] += (pix[c] + pix[ip[1]]) >> 1;
4024 	    else
4025 	      sum[c] += pix[ip[0] + c];
4026 	  num++;
4027 	}
4028       }
4029       FORCC {					/* Save to buffer */
4030 	t = pix[color];
4031 	if (c != color)
4032 	  t += (sum[c] - sum[color]) / num;
4033 	brow[2][col][c] = CLIP(t);
4034       }
4035     }
4036     if (row > 3)				/* Write buffer to image */
4037       memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image);
4038     for (g=0; g < 4; g++)
4039       brow[(g-1) & 3] = brow[g];
4040   }
4041   memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image);
4042   memcpy (image[(row-1)*width+2], brow[1]+2, (width-4)*sizeof *image);
4043   free (brow[4]);
4044   free (code[0][0]);
4045 }
4046 
4047 /*
4048    Patterned Pixel Grouping Interpolation by Alain Desbiolles
4049 */
ppg_interpolate()4050 void CLASS ppg_interpolate()
4051 {
4052   int dir[5] = { 1, width, -1, -width, 1 };
4053   int row, col, diff[2], guess[2], c, d, i;
4054   ushort (*pix)[4];
4055 
4056   border_interpolate(3);
4057   if (verbose) fprintf (stderr,_("PPG interpolation...\n"));
4058 
4059 /*  Fill in the green layer with gradients and pattern recognition: */
4060   for (row=3; row < height-3; row++)
4061     for (col=3+(FC(row,3) & 1), c=FC(row,col); col < width-3; col+=2) {
4062       pix = image + row*width+col;
4063       for (i=0; (d=dir[i]) > 0; i++) {
4064 	guess[i] = (pix[-d][1] + pix[0][c] + pix[d][1]) * 2
4065 		      - pix[-2*d][c] - pix[2*d][c];
4066 	diff[i] = ( ABS(pix[-2*d][c] - pix[ 0][c]) +
4067 		    ABS(pix[ 2*d][c] - pix[ 0][c]) +
4068 		    ABS(pix[  -d][1] - pix[ d][1]) ) * 3 +
4069 		  ( ABS(pix[ 3*d][1] - pix[ d][1]) +
4070 		    ABS(pix[-3*d][1] - pix[-d][1]) ) * 2;
4071       }
4072       d = dir[i = diff[0] > diff[1]];
4073       pix[0][1] = ULIM(guess[i] >> 2, pix[d][1], pix[-d][1]);
4074     }
4075 /*  Calculate red and blue for each green pixel:		*/
4076   for (row=1; row < height-1; row++)
4077     for (col=1+(FC(row,2) & 1), c=FC(row,col+1); col < width-1; col+=2) {
4078       pix = image + row*width+col;
4079       for (i=0; (d=dir[i]) > 0; c=2-c, i++)
4080 	pix[0][c] = CLIP((pix[-d][c] + pix[d][c] + 2*pix[0][1]
4081 			- pix[-d][1] - pix[d][1]) >> 1);
4082     }
4083 /*  Calculate blue for red pixels and vice versa:		*/
4084   for (row=1; row < height-1; row++)
4085     for (col=1+(FC(row,1) & 1), c=2-FC(row,col); col < width-1; col+=2) {
4086       pix = image + row*width+col;
4087       for (i=0; (d=dir[i]+dir[i+1]) > 0; i++) {
4088 	diff[i] = ABS(pix[-d][c] - pix[d][c]) +
4089 		  ABS(pix[-d][1] - pix[0][1]) +
4090 		  ABS(pix[ d][1] - pix[0][1]);
4091 	guess[i] = pix[-d][c] + pix[d][c] + 2*pix[0][1]
4092 		 - pix[-d][1] - pix[d][1];
4093       }
4094       if (diff[0] != diff[1])
4095 	pix[0][c] = CLIP(guess[diff[0] > diff[1]] >> 1);
4096       else
4097 	pix[0][c] = CLIP((guess[0]+guess[1]) >> 2);
4098     }
4099 }
4100 
4101 /*
4102    Adaptive Homogeneity-Directed interpolation is based on
4103    the work of Keigo Hirakawa, Thomas Parks, and Paul Lee.
4104  */
4105 #define TS 256		/* Tile Size */
4106 
ahd_interpolate()4107 void CLASS ahd_interpolate()
4108 {
4109   int i, j, k, top, left, row, col, tr, tc, c, d, val, hm[2];
4110   ushort (*pix)[4], (*rix)[3];
4111   static const int dir[4] = { -1, 1, -TS, TS };
4112   unsigned ldiff[2][4], abdiff[2][4], leps, abeps;
4113   float r, cbrt[0x10000], xyz[3], xyz_cam[3][4];
4114   ushort (*rgb)[TS][TS][3];
4115    short (*lab)[TS][TS][3], (*lix)[3];
4116    char (*homo)[TS][TS], *buffer;
4117 
4118   if (verbose) fprintf (stderr,_("AHD interpolation...\n"));
4119 
4120   for (i=0; i < 0x10000; i++) {
4121     r = i / 65535.0;
4122     cbrt[i] = r > 0.008856 ? pow(r,1/3.0) : 7.787*r + 16/116.0;
4123   }
4124   for (i=0; i < 3; i++)
4125     for (j=0; j < colors; j++)
4126       for (xyz_cam[i][j] = k=0; k < 3; k++)
4127 	xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i];
4128 
4129   border_interpolate(5);
4130   buffer = (char *) malloc (26*TS*TS);		/* 1664 kB */
4131   merror (buffer, "ahd_interpolate()");
4132   rgb  = (ushort(*)[TS][TS][3]) buffer;
4133   lab  = (short (*)[TS][TS][3])(buffer + 12*TS*TS);
4134   homo = (char  (*)[TS][TS])   (buffer + 24*TS*TS);
4135 
4136   for (top=2; top < height-5; top += TS-6)
4137     for (left=2; left < width-5; left += TS-6) {
4138 
4139 /*  Interpolate green horizontally and vertically:		*/
4140       for (row = top; row < top+TS && row < height-2; row++) {
4141 	col = left + (FC(row,left) & 1);
4142 	for (c = FC(row,col); col < left+TS && col < width-2; col+=2) {
4143 	  pix = image + row*width+col;
4144 	  val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2
4145 		- pix[-2][c] - pix[2][c]) >> 2;
4146 	  rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]);
4147 	  val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2
4148 		- pix[-2*width][c] - pix[2*width][c]) >> 2;
4149 	  rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]);
4150 	}
4151       }
4152 /*  Interpolate red and blue, and convert to CIELab:		*/
4153       for (d=0; d < 2; d++)
4154 	for (row=top+1; row < top+TS-1 && row < height-3; row++)
4155 	  for (col=left+1; col < left+TS-1 && col < width-3; col++) {
4156 	    pix = image + row*width+col;
4157 	    rix = &rgb[d][row-top][col-left];
4158 	    lix = &lab[d][row-top][col-left];
4159 	    if ((c = 2 - FC(row,col)) == 1) {
4160 	      c = FC(row+1,col);
4161 	      val = pix[0][1] + (( pix[-1][2-c] + pix[1][2-c]
4162 				 - rix[-1][1] - rix[1][1] ) >> 1);
4163 	      rix[0][2-c] = CLIP(val);
4164 	      val = pix[0][1] + (( pix[-width][c] + pix[width][c]
4165 				 - rix[-TS][1] - rix[TS][1] ) >> 1);
4166 	    } else
4167 	      val = rix[0][1] + (( pix[-width-1][c] + pix[-width+1][c]
4168 				 + pix[+width-1][c] + pix[+width+1][c]
4169 				 - rix[-TS-1][1] - rix[-TS+1][1]
4170 				 - rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2);
4171 	    rix[0][c] = CLIP(val);
4172 	    c = FC(row,col);
4173 	    rix[0][c] = pix[0][c];
4174 	    xyz[0] = xyz[1] = xyz[2] = 0.5;
4175 	    FORCC {
4176 	      xyz[0] += xyz_cam[0][c] * rix[0][c];
4177 	      xyz[1] += xyz_cam[1][c] * rix[0][c];
4178 	      xyz[2] += xyz_cam[2][c] * rix[0][c];
4179 	    }
4180 	    xyz[0] = cbrt[CLIP((int) xyz[0])];
4181 	    xyz[1] = cbrt[CLIP((int) xyz[1])];
4182 	    xyz[2] = cbrt[CLIP((int) xyz[2])];
4183 	    lix[0][0] = 64 * (116 * xyz[1] - 16);
4184 	    lix[0][1] = 64 * 500 * (xyz[0] - xyz[1]);
4185 	    lix[0][2] = 64 * 200 * (xyz[1] - xyz[2]);
4186 	  }
4187 /*  Build homogeneity maps from the CIELab images:		*/
4188       memset (homo, 0, 2*TS*TS);
4189       for (row=top+2; row < top+TS-2 && row < height-4; row++) {
4190 	tr = row-top;
4191 	for (col=left+2; col < left+TS-2 && col < width-4; col++) {
4192 	  tc = col-left;
4193 	  for (d=0; d < 2; d++) {
4194 	    lix = &lab[d][tr][tc];
4195 	    for (i=0; i < 4; i++) {
4196 	       ldiff[d][i] = ABS(lix[0][0]-lix[dir[i]][0]);
4197 	      abdiff[d][i] = SQR(lix[0][1]-lix[dir[i]][1])
4198 			   + SQR(lix[0][2]-lix[dir[i]][2]);
4199 	    }
4200 	  }
4201 	  leps = MIN(MAX(ldiff[0][0],ldiff[0][1]),
4202 		     MAX(ldiff[1][2],ldiff[1][3]));
4203 	  abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]),
4204 		      MAX(abdiff[1][2],abdiff[1][3]));
4205 	  for (d=0; d < 2; d++)
4206 	    for (i=0; i < 4; i++)
4207 	      if (ldiff[d][i] <= leps && abdiff[d][i] <= abeps)
4208 		homo[d][tr][tc]++;
4209 	}
4210       }
4211 /*  Combine the most homogenous pixels for the final result:	*/
4212       for (row=top+3; row < top+TS-3 && row < height-5; row++) {
4213 	tr = row-top;
4214 	for (col=left+3; col < left+TS-3 && col < width-5; col++) {
4215 	  tc = col-left;
4216 	  for (d=0; d < 2; d++)
4217 	    for (hm[d]=0, i=tr-1; i <= tr+1; i++)
4218 	      for (j=tc-1; j <= tc+1; j++)
4219 		hm[d] += homo[d][i][j];
4220 	  if (hm[0] != hm[1])
4221 	    FORC3 image[row*width+col][c] = rgb[hm[1] > hm[0]][tr][tc][c];
4222 	  else
4223 	    FORC3 image[row*width+col][c] =
4224 		(rgb[0][tr][tc][c] + rgb[1][tr][tc][c]) >> 1;
4225 	}
4226       }
4227     }
4228   free (buffer);
4229 }
4230 #undef TS
4231 
median_filter()4232 void CLASS median_filter()
4233 {
4234   ushort (*pix)[4];
4235   int pass, c, i, j, k, med[9];
4236   static const uchar opt[] =	/* Optimal 9-element median search */
4237   { 1,2, 4,5, 7,8, 0,1, 3,4, 6,7, 1,2, 4,5, 7,8,
4238     0,3, 5,8, 4,7, 3,6, 1,4, 2,5, 4,7, 4,2, 6,4, 4,2 };
4239 
4240   for (pass=1; pass <= med_passes; pass++) {
4241     if (verbose)
4242       fprintf (stderr,_("Median filter pass %d...\n"), pass);
4243     for (c=0; c < 3; c+=2) {
4244       for (pix = image; pix < image+width*height; pix++)
4245 	pix[0][3] = pix[0][c];
4246       for (pix = image+width; pix < image+width*(height-1); pix++) {
4247 	if ((pix-image+1) % width < 2) continue;
4248 	for (k=0, i = -width; i <= width; i += width)
4249 	  for (j = i-1; j <= i+1; j++)
4250 	    med[k++] = pix[j][3] - pix[j][1];
4251 	for (i=0; i < sizeof opt; i+=2)
4252 	  if     (med[opt[i]] > med[opt[i+1]])
4253 	    SWAP (med[opt[i]] , med[opt[i+1]]);
4254 	pix[0][c] = CLIP(med[4] + pix[0][1]);
4255       }
4256     }
4257   }
4258 }
4259 
blend_highlights()4260 void CLASS blend_highlights()
4261 {
4262   int clip=INT_MAX, row, col, c, i, j;
4263   static const float trans[2][4][4] =
4264   { { { 1,1,1 }, { 1.7320508,-1.7320508,0 }, { -1,-1,2 } },
4265     { { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } };
4266   static const float itrans[2][4][4] =
4267   { { { 1,0.8660254,-0.5 }, { 1,-0.8660254,-0.5 }, { 1,0,1 } },
4268     { { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } };
4269   float cam[2][4], lab[2][4], sum[2], chratio;
4270 
4271   if ((unsigned) (colors-3) > 1) return;
4272   if (verbose) fprintf (stderr,_("Blending highlights...\n"));
4273   FORCC if (clip > (i = 65535*pre_mul[c])) clip = i;
4274   for (row=0; row < height; row++)
4275     for (col=0; col < width; col++) {
4276       FORCC if (image[row*width+col][c] > clip) break;
4277       if (c == colors) continue;
4278       FORCC {
4279 	cam[0][c] = image[row*width+col][c];
4280 	cam[1][c] = MIN(cam[0][c],clip);
4281       }
4282       for (i=0; i < 2; i++) {
4283 	FORCC for (lab[i][c]=j=0; j < colors; j++)
4284 	  lab[i][c] += trans[colors-3][c][j] * cam[i][j];
4285 	for (sum[i]=0,c=1; c < colors; c++)
4286 	  sum[i] += SQR(lab[i][c]);
4287       }
4288       chratio = sqrt(sum[1]/sum[0]);
4289       for (c=1; c < colors; c++)
4290 	lab[0][c] *= chratio;
4291       FORCC for (cam[0][c]=j=0; j < colors; j++)
4292 	cam[0][c] += itrans[colors-3][c][j] * lab[0][j];
4293       FORCC image[row*width+col][c] = cam[0][c] / colors;
4294     }
4295 }
4296 
4297 #define SCALE (4 >> shrink)
recover_highlights()4298 void CLASS recover_highlights()
4299 {
4300   float *map, sum, wgt, grow;
4301   int hsat[4], count, spread, change, val, i;
4302   unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x;
4303   ushort *pixel;
4304   static const signed char dir[8][2] =
4305     { {-1,-1}, {-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1} };
4306 
4307   if (verbose) fprintf (stderr,_("Rebuilding highlights...\n"));
4308 
4309   grow = pow (2, 4-highlight);
4310   FORCC hsat[c] = 32000 * pre_mul[c];
4311   for (kc=0, c=1; c < colors; c++)
4312     if (pre_mul[kc] < pre_mul[c]) kc = c;
4313   high = height / SCALE;
4314   wide =  width / SCALE;
4315   map = (float *) calloc (high*wide, sizeof *map);
4316   merror (map, "recover_highlights()");
4317   FORCC if (c != kc) {
4318     memset (map, 0, high*wide*sizeof *map);
4319     for (mrow=0; mrow < high; mrow++)
4320       for (mcol=0; mcol < wide; mcol++) {
4321 	sum = wgt = count = 0;
4322 	for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++)
4323 	  for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) {
4324 	    pixel = image[row*width+col];
4325 	    if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000) {
4326 	      sum += pixel[c];
4327 	      wgt += pixel[kc];
4328 	      count++;
4329 	    }
4330 	  }
4331 	if (count == SCALE*SCALE)
4332 	  map[mrow*wide+mcol] = sum / wgt;
4333       }
4334     for (spread = 32/grow; spread--; ) {
4335       for (mrow=0; mrow < high; mrow++)
4336 	for (mcol=0; mcol < wide; mcol++) {
4337 	  if (map[mrow*wide+mcol]) continue;
4338 	  sum = count = 0;
4339 	  for (d=0; d < 8; d++) {
4340 	    y = mrow + dir[d][0];
4341 	    x = mcol + dir[d][1];
4342 	    if (y < high && x < wide && map[y*wide+x] > 0) {
4343 	      sum  += (1 + (d & 1)) * map[y*wide+x];
4344 	      count += 1 + (d & 1);
4345 	    }
4346 	  }
4347 	  if (count > 3)
4348 	    map[mrow*wide+mcol] = - (sum+grow) / (count+grow);
4349 	}
4350       for (change=i=0; i < high*wide; i++)
4351 	if (map[i] < 0) {
4352 	  map[i] = -map[i];
4353 	  change = 1;
4354 	}
4355       if (!change) break;
4356     }
4357     for (i=0; i < high*wide; i++)
4358       if (map[i] == 0) map[i] = 1;
4359     for (mrow=0; mrow < high; mrow++)
4360       for (mcol=0; mcol < wide; mcol++) {
4361 	for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++)
4362 	  for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) {
4363 	    pixel = image[row*width+col];
4364 	    if (pixel[c] / hsat[c] > 1) {
4365 	      val = pixel[kc] * map[mrow*wide+mcol];
4366 	      if (pixel[c] < val) pixel[c] = CLIP(val);
4367 	    }
4368 	  }
4369       }
4370   }
4371   free (map);
4372 }
4373 #undef SCALE
4374 
tiff_get(unsigned base,unsigned * tag,unsigned * type,unsigned * len,unsigned * save)4375 void CLASS tiff_get (unsigned base,
4376 	unsigned *tag, unsigned *type, unsigned *len, unsigned *save)
4377 {
4378   *tag  = get2();
4379   *type = get2();
4380   *len  = get4();
4381   *save = ftell(ifp) + 4;
4382   if (*len * ("11124811248488"[*type < 14 ? *type:0]-'0') > 4)
4383     fseek (ifp, get4()+base, SEEK_SET);
4384 }
4385 
parse_thumb_note(int base,unsigned toff,unsigned tlen)4386 void CLASS parse_thumb_note (int base, unsigned toff, unsigned tlen)
4387 {
4388   unsigned entries, tag, type, len, save;
4389 
4390   entries = get2();
4391   while (entries--) {
4392     tiff_get (base, &tag, &type, &len, &save);
4393     if (tag == toff) thumb_offset = get4()+base;
4394     if (tag == tlen) thumb_length = get4();
4395     fseek (ifp, save, SEEK_SET);
4396   }
4397 }
4398 
4399 int CLASS parse_tiff_ifd (int base);
4400 
parse_makernote(int base,int uptag)4401 void CLASS parse_makernote (int base, int uptag)
4402 {
4403   static const uchar xlat[2][256] = {
4404   { 0xc1,0xbf,0x6d,0x0d,0x59,0xc5,0x13,0x9d,0x83,0x61,0x6b,0x4f,0xc7,0x7f,0x3d,0x3d,
4405     0x53,0x59,0xe3,0xc7,0xe9,0x2f,0x95,0xa7,0x95,0x1f,0xdf,0x7f,0x2b,0x29,0xc7,0x0d,
4406     0xdf,0x07,0xef,0x71,0x89,0x3d,0x13,0x3d,0x3b,0x13,0xfb,0x0d,0x89,0xc1,0x65,0x1f,
4407     0xb3,0x0d,0x6b,0x29,0xe3,0xfb,0xef,0xa3,0x6b,0x47,0x7f,0x95,0x35,0xa7,0x47,0x4f,
4408     0xc7,0xf1,0x59,0x95,0x35,0x11,0x29,0x61,0xf1,0x3d,0xb3,0x2b,0x0d,0x43,0x89,0xc1,
4409     0x9d,0x9d,0x89,0x65,0xf1,0xe9,0xdf,0xbf,0x3d,0x7f,0x53,0x97,0xe5,0xe9,0x95,0x17,
4410     0x1d,0x3d,0x8b,0xfb,0xc7,0xe3,0x67,0xa7,0x07,0xf1,0x71,0xa7,0x53,0xb5,0x29,0x89,
4411     0xe5,0x2b,0xa7,0x17,0x29,0xe9,0x4f,0xc5,0x65,0x6d,0x6b,0xef,0x0d,0x89,0x49,0x2f,
4412     0xb3,0x43,0x53,0x65,0x1d,0x49,0xa3,0x13,0x89,0x59,0xef,0x6b,0xef,0x65,0x1d,0x0b,
4413     0x59,0x13,0xe3,0x4f,0x9d,0xb3,0x29,0x43,0x2b,0x07,0x1d,0x95,0x59,0x59,0x47,0xfb,
4414     0xe5,0xe9,0x61,0x47,0x2f,0x35,0x7f,0x17,0x7f,0xef,0x7f,0x95,0x95,0x71,0xd3,0xa3,
4415     0x0b,0x71,0xa3,0xad,0x0b,0x3b,0xb5,0xfb,0xa3,0xbf,0x4f,0x83,0x1d,0xad,0xe9,0x2f,
4416     0x71,0x65,0xa3,0xe5,0x07,0x35,0x3d,0x0d,0xb5,0xe9,0xe5,0x47,0x3b,0x9d,0xef,0x35,
4417     0xa3,0xbf,0xb3,0xdf,0x53,0xd3,0x97,0x53,0x49,0x71,0x07,0x35,0x61,0x71,0x2f,0x43,
4418     0x2f,0x11,0xdf,0x17,0x97,0xfb,0x95,0x3b,0x7f,0x6b,0xd3,0x25,0xbf,0xad,0xc7,0xc5,
4419     0xc5,0xb5,0x8b,0xef,0x2f,0xd3,0x07,0x6b,0x25,0x49,0x95,0x25,0x49,0x6d,0x71,0xc7 },
4420   { 0xa7,0xbc,0xc9,0xad,0x91,0xdf,0x85,0xe5,0xd4,0x78,0xd5,0x17,0x46,0x7c,0x29,0x4c,
4421     0x4d,0x03,0xe9,0x25,0x68,0x11,0x86,0xb3,0xbd,0xf7,0x6f,0x61,0x22,0xa2,0x26,0x34,
4422     0x2a,0xbe,0x1e,0x46,0x14,0x68,0x9d,0x44,0x18,0xc2,0x40,0xf4,0x7e,0x5f,0x1b,0xad,
4423     0x0b,0x94,0xb6,0x67,0xb4,0x0b,0xe1,0xea,0x95,0x9c,0x66,0xdc,0xe7,0x5d,0x6c,0x05,
4424     0xda,0xd5,0xdf,0x7a,0xef,0xf6,0xdb,0x1f,0x82,0x4c,0xc0,0x68,0x47,0xa1,0xbd,0xee,
4425     0x39,0x50,0x56,0x4a,0xdd,0xdf,0xa5,0xf8,0xc6,0xda,0xca,0x90,0xca,0x01,0x42,0x9d,
4426     0x8b,0x0c,0x73,0x43,0x75,0x05,0x94,0xde,0x24,0xb3,0x80,0x34,0xe5,0x2c,0xdc,0x9b,
4427     0x3f,0xca,0x33,0x45,0xd0,0xdb,0x5f,0xf5,0x52,0xc3,0x21,0xda,0xe2,0x22,0x72,0x6b,
4428     0x3e,0xd0,0x5b,0xa8,0x87,0x8c,0x06,0x5d,0x0f,0xdd,0x09,0x19,0x93,0xd0,0xb9,0xfc,
4429     0x8b,0x0f,0x84,0x60,0x33,0x1c,0x9b,0x45,0xf1,0xf0,0xa3,0x94,0x3a,0x12,0x77,0x33,
4430     0x4d,0x44,0x78,0x28,0x3c,0x9e,0xfd,0x65,0x57,0x16,0x94,0x6b,0xfb,0x59,0xd0,0xc8,
4431     0x22,0x36,0xdb,0xd2,0x63,0x98,0x43,0xa1,0x04,0x87,0x86,0xf7,0xa6,0x26,0xbb,0xd6,
4432     0x59,0x4d,0xbf,0x6a,0x2e,0xaa,0x2b,0xef,0xe6,0x78,0xb6,0x4e,0xe0,0x2f,0xdc,0x7c,
4433     0xbe,0x57,0x19,0x32,0x7e,0x2a,0xd0,0xb8,0xba,0x29,0x00,0x3c,0x52,0x7d,0xa8,0x49,
4434     0x3b,0x2d,0xeb,0x25,0x49,0xfa,0xa3,0xaa,0x39,0xa7,0xc5,0xa7,0x50,0x11,0x36,0xfb,
4435     0xc6,0x67,0x4a,0xf5,0xa5,0x12,0x65,0x7e,0xb0,0xdf,0xaf,0x4e,0xb3,0x61,0x7f,0x2f } };
4436   unsigned offset=0, entries, tag, type, len, save, c;
4437   unsigned ver97=0, serial=0, i, wbi=0, wb[4]={0,0,0,0};
4438   uchar buf97[324], ci, cj, ck;
4439   short morder, sorder=order;
4440   char buf[10];
4441 /*
4442    The MakerNote might have its own TIFF header (possibly with
4443    its own byte-order!), or it might just be a table.
4444  */
4445   if (!strcmp(make,"Nokia")) return;
4446   fread (buf, 1, 10, ifp);
4447   if (!strncmp (buf,"KDK" ,3) ||	/* these aren't TIFF tables */
4448       !strncmp (buf,"VER" ,3) ||
4449       !strncmp (buf,"IIII",4) ||
4450       !strncmp (buf,"MMMM",4)) return;
4451   if (!strncmp (buf,"KC"  ,2) ||	/* Konica KD-400Z, KD-510Z */
4452       !strncmp (buf,"MLY" ,3)) {	/* Minolta DiMAGE G series */
4453     order = 0x4d4d;
4454     while ((i=ftell(ifp)) < data_offset && i < 16384) {
4455       wb[0] = wb[2];  wb[2] = wb[1];  wb[1] = wb[3];
4456       wb[3] = get2();
4457       if (wb[1] == 256 && wb[3] == 256 &&
4458 	  wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640)
4459 	FORC4 cam_mul[c] = wb[c];
4460     }
4461     goto quit;
4462   }
4463   if (!strcmp (buf,"Nikon")) {
4464     base = ftell(ifp);
4465     order = get2();
4466     if (get2() != 42) goto quit;
4467     offset = get4();
4468     fseek (ifp, offset-8, SEEK_CUR);
4469   } else if (!strcmp (buf,"OLYMPUS")) {
4470     base = ftell(ifp)-10;
4471     fseek (ifp, -2, SEEK_CUR);
4472     order = get2();  get2();
4473   } else if (!strncmp (buf,"SONY",4) ||
4474 	     !strcmp  (buf,"Panasonic")) {
4475     goto nf;
4476   } else if (!strncmp (buf,"FUJIFILM",8)) {
4477     base = ftell(ifp)-10;
4478 nf: order = 0x4949;
4479     fseek (ifp,  2, SEEK_CUR);
4480   } else if (!strcmp (buf,"OLYMP") ||
4481 	     !strcmp (buf,"LEICA") ||
4482 	     !strcmp (buf,"Ricoh") ||
4483 	     !strcmp (buf,"EPSON"))
4484     fseek (ifp, -2, SEEK_CUR);
4485   else if (!strcmp (buf,"AOC") ||
4486 	   !strcmp (buf,"QVC"))
4487     fseek (ifp, -4, SEEK_CUR);
4488   else {
4489     fseek (ifp, -10, SEEK_CUR);
4490     if (!strncmp(make,"SAMSUNG",7))
4491       base = ftell(ifp);
4492   }
4493   entries = get2();
4494   if (entries > 1000) return;
4495   morder = order;
4496   while (entries--) {
4497     order = morder;
4498     tiff_get (base, &tag, &type, &len, &save);
4499     tag |= uptag << 16;
4500     if (tag == 2 && strstr(make,"NIKON") && !iso_speed)
4501       iso_speed = (get2(),get2());
4502     if (tag == 4 && len > 26 && len < 35) {
4503       if ((i=(get4(),get2())) != 0x7fff && !iso_speed)
4504 	iso_speed = 50 * pow (2, i/32.0 - 4);
4505       if ((i=(get2(),get2())) != 0x7fff && !aperture)
4506 	aperture = pow (2, i/64.0);
4507       if ((i=get2()) != 0xffff && !shutter)
4508 	shutter = pow (2, (short) i/-32.0);
4509       wbi = (get2(),get2());
4510       shot_order = (get2(),get2());
4511     }
4512     if ((tag == 4 || tag == 0x114) && !strncmp(make,"KONICA",6)) {
4513       fseek (ifp, tag == 4 ? 140:160, SEEK_CUR);
4514       switch (get2()) {
4515 	case 72:  flip = 0;  break;
4516 	case 76:  flip = 6;  break;
4517 	case 82:  flip = 5;  break;
4518       }
4519     }
4520     if (tag == 7 && type == 2 && len > 20)
4521       fgets (model2, 64, ifp);
4522     if (tag == 8 && type == 4)
4523       shot_order = get4();
4524     if (tag == 9 && !strcmp(make,"Canon"))
4525       fread (artist, 64, 1, ifp);
4526     if (tag == 0xc && len == 4) {
4527       cam_mul[0] = getreal(type);
4528       cam_mul[2] = getreal(type);
4529     }
4530     if (tag == 0xd && type == 7 && get2() == 0xaaaa) {
4531       fread (buf97, 1, sizeof buf97, ifp);
4532       i = (uchar *) memmem (buf97, sizeof buf97,"\xbb\xbb",2) - buf97 + 10;
4533       if (i < 70 && buf97[i] < 3)
4534 	flip = "065"[buf97[i]]-'0';
4535     }
4536     if (tag == 0x10 && type == 4)
4537       unique_id = get4();
4538     if (tag == 0x11 && is_raw && !strncmp(make,"NIKON",5)) {
4539       fseek (ifp, get4()+base, SEEK_SET);
4540       parse_tiff_ifd (base);
4541     }
4542     if (tag == 0x14 && type == 7) {
4543       if (len == 2560) {
4544 	fseek (ifp, 1248, SEEK_CUR);
4545 	goto get2_256;
4546       }
4547       fread (buf, 1, 10, ifp);
4548       if (!strncmp(buf,"NRW ",4)) {
4549 	fseek (ifp, strcmp(buf+4,"0100") ? 46:1546, SEEK_CUR);
4550 	cam_mul[0] = get4() << 2;
4551 	cam_mul[1] = get4() + get4();
4552 	cam_mul[2] = get4() << 2;
4553       }
4554     }
4555     if (tag == 0x15 && type == 2 && is_raw)
4556       fread (model, 64, 1, ifp);
4557     if (strstr(make,"PENTAX")) {
4558       if (tag == 0x1b) tag = 0x1018;
4559       if (tag == 0x1c) tag = 0x1017;
4560     }
4561     if (tag == 0x1d)
4562       while ((c = fgetc(ifp)) && c != EOF)
4563 	serial = serial*10 + (isdigit(c) ? c - '0' : c % 10);
4564     if (tag == 0x81 && type == 4) {
4565       data_offset = get4();
4566       fseek (ifp, data_offset + 41, SEEK_SET);
4567       raw_height = get2() * 2;
4568       raw_width  = get2();
4569       filters = 0x61616161;
4570     }
4571     if (tag == 0x29 && type == 1) {
4572       c = wbi < 18 ? "012347800000005896"[wbi]-'0' : 0;
4573       fseek (ifp, 8 + c*32, SEEK_CUR);
4574       FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4();
4575     }
4576     if ((tag == 0x81  && type == 7) ||
4577 	(tag == 0x100 && type == 7) ||
4578 	(tag == 0x280 && type == 1)) {
4579       thumb_offset = ftell(ifp);
4580       thumb_length = len;
4581     }
4582     if (tag == 0x88 && type == 4 && (thumb_offset = get4()))
4583       thumb_offset += base;
4584     if (tag == 0x89 && type == 4)
4585       thumb_length = get4();
4586     if (tag == 0x8c || tag == 0x96)
4587       meta_offset = ftell(ifp);
4588     if (tag == 0x97) {
4589       for (i=0; i < 4; i++)
4590 	ver97 = ver97 * 10 + fgetc(ifp)-'0';
4591       switch (ver97) {
4592 	case 100:
4593 	  fseek (ifp, 68, SEEK_CUR);
4594 	  FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2();
4595 	  break;
4596 	case 102:
4597 	  fseek (ifp, 6, SEEK_CUR);
4598 	  goto get2_rggb;
4599 	case 103:
4600 	  fseek (ifp, 16, SEEK_CUR);
4601 	  FORC4 cam_mul[c] = get2();
4602       }
4603       if (ver97 >= 200) {
4604 	if (ver97 != 205) fseek (ifp, 280, SEEK_CUR);
4605 	fread (buf97, 324, 1, ifp);
4606       }
4607     }
4608     if (tag == 0xa1 && type == 7) {
4609       order = 0x4949;
4610       fseek (ifp, 140, SEEK_CUR);
4611       FORC3 cam_mul[c] = get4();
4612     }
4613     if (tag == 0xa4 && type == 3) {
4614       fseek (ifp, wbi*48, SEEK_CUR);
4615       FORC3 cam_mul[c] = get2();
4616     }
4617     if (tag == 0xa7 && (unsigned) (ver97-200) < 17) {
4618       ci = xlat[0][serial & 0xff];
4619       cj = xlat[1][fgetc(ifp)^fgetc(ifp)^fgetc(ifp)^fgetc(ifp)];
4620       ck = 0x60;
4621       for (i=0; i < 324; i++)
4622 	buf97[i] ^= (cj += ci * ck++);
4623       i = "66666>666;6A;:;55"[ver97-200] - '0';
4624       FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] =
4625 	sget2 (buf97 + (i & -2) + c*2);
4626     }
4627     if (tag == 0x200 && len == 3)
4628       shot_order = (get4(),get4());
4629     if (tag == 0x200 && len == 4)
4630       FORC4 cblack[c ^ c >> 1] = get2();
4631     if (tag == 0x201 && len == 4)
4632       goto get2_rggb;
4633     if (tag == 0x220 && type == 7)
4634       meta_offset = ftell(ifp);
4635     if (tag == 0x401 && type == 4 && len == 4)
4636       FORC4 cblack[c ^ c >> 1] = get4();
4637     if (tag == 0xe01) {		/* Nikon Capture Note */
4638       order = 0x4949;
4639       fseek (ifp, 22, SEEK_CUR);
4640       for (offset=22; offset+22 < len; offset += 22+i) {
4641 	tag = get4();
4642 	fseek (ifp, 14, SEEK_CUR);
4643 	i = get4()-4;
4644 	if (tag == 0x76a43207) flip = get2();
4645 	else fseek (ifp, i, SEEK_CUR);
4646       }
4647     }
4648     if (tag == 0xe80 && len == 256 && type == 7) {
4649       fseek (ifp, 48, SEEK_CUR);
4650       cam_mul[0] = get2() * 508 * 1.078 / 0x10000;
4651       cam_mul[2] = get2() * 382 * 1.173 / 0x10000;
4652     }
4653     if (tag == 0xf00 && type == 7) {
4654       if (len == 614)
4655 	fseek (ifp, 176, SEEK_CUR);
4656       else if (len == 734 || len == 1502)
4657 	fseek (ifp, 148, SEEK_CUR);
4658       else goto next;
4659       goto get2_256;
4660     }
4661     if ((tag == 0x1011 && len == 9) || tag == 0x20400200)
4662       for (i=0; i < 3; i++)
4663 	FORC3 cmatrix[i][c] = ((short) get2()) / 256.0;
4664     if ((tag == 0x1012 || tag == 0x20400600) && len == 4)
4665       FORC4 cblack[c ^ c >> 1] = get2();
4666     if (tag == 0x1017 || tag == 0x20400100)
4667       cam_mul[0] = get2() / 256.0;
4668     if (tag == 0x1018 || tag == 0x20400100)
4669       cam_mul[2] = get2() / 256.0;
4670     if (tag == 0x2011 && len == 2) {
4671 get2_256:
4672       order = 0x4d4d;
4673       cam_mul[0] = get2() / 256.0;
4674       cam_mul[2] = get2() / 256.0;
4675     }
4676     if ((tag | 0x70) == 0x2070 && type == 4)
4677       fseek (ifp, get4()+base, SEEK_SET);
4678     if (tag == 0x2010 && type != 7)
4679       load_raw = &CLASS olympus_load_raw;
4680     if (tag == 0x2020)
4681       parse_thumb_note (base, 257, 258);
4682     if (tag == 0x2040)
4683       parse_makernote (base, 0x2040);
4684     if (tag == 0xb028) {
4685       fseek (ifp, get4()+base, SEEK_SET);
4686       parse_thumb_note (base, 136, 137);
4687     }
4688     if (tag == 0x4001 && len > 500) {
4689       i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126;
4690       fseek (ifp, i, SEEK_CUR);
4691 get2_rggb:
4692       FORC4 cam_mul[c ^ (c >> 1)] = get2();
4693       fseek (ifp, 22, SEEK_CUR);
4694       FORC4 sraw_mul[c ^ (c >> 1)] = get2();
4695     }
4696     if (tag == 0xa021)
4697       FORC4 cam_mul[c ^ (c >> 1)] = get4();
4698     if (tag == 0xa028)
4699       FORC4 cam_mul[c ^ (c >> 1)] -= get4();
4700 next:
4701     fseek (ifp, save, SEEK_SET);
4702   }
4703 quit:
4704   order = sorder;
4705 }
4706 
4707 /*
4708    Since the TIFF DateTime string has no timezone information,
4709    assume that the camera's clock was set to Universal Time.
4710  */
get_timestamp(int reversed)4711 void CLASS get_timestamp (int reversed)
4712 {
4713   struct tm t;
4714   char str[20];
4715   int i;
4716 
4717   str[19] = 0;
4718   if (reversed)
4719     for (i=19; i--; ) str[i] = fgetc(ifp);
4720   else
4721     fread (str, 19, 1, ifp);
4722   memset (&t, 0, sizeof t);
4723   if (sscanf (str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon,
4724 	&t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6)
4725     return;
4726   t.tm_year -= 1900;
4727   t.tm_mon -= 1;
4728   t.tm_isdst = -1;
4729   if (mktime(&t) > 0)
4730     timestamp = mktime(&t);
4731 }
4732 
parse_exif(int base)4733 void CLASS parse_exif (int base)
4734 {
4735   unsigned kodak, entries, tag, type, len, save, c;
4736   double expo;
4737 
4738   kodak = !strncmp(make,"EASTMAN",7) && tiff_nifds < 3;
4739   entries = get2();
4740   while (entries--) {
4741     tiff_get (base, &tag, &type, &len, &save);
4742     switch (tag) {
4743       case 33434:  shutter = getreal(type);		break;
4744       case 33437:  aperture = getreal(type);		break;
4745       case 34855:  iso_speed = get2();			break;
4746       case 36867:
4747       case 36868:  get_timestamp(0);			break;
4748       case 37377:  if ((expo = -getreal(type)) < 128)
4749 		     shutter = pow (2, expo);		break;
4750       case 37378:  aperture = pow (2, getreal(type)/2);	break;
4751       case 37386:  focal_len = getreal(type);		break;
4752       case 37500:  parse_makernote (base, 0);		break;
4753       case 40962:  if (kodak) raw_width  = get4();	break;
4754       case 40963:  if (kodak) raw_height = get4();	break;
4755       case 41730:
4756 	if (get4() == 0x20002)
4757 	  for (exif_cfa=c=0; c < 8; c+=2)
4758 	    exif_cfa |= fgetc(ifp) * 0x01010101 << c;
4759     }
4760     fseek (ifp, save, SEEK_SET);
4761   }
4762 }
4763 
parse_gps(int base)4764 void CLASS parse_gps (int base)
4765 {
4766   unsigned entries, tag, type, len, save, c;
4767 
4768   entries = get2();
4769   while (entries--) {
4770     tiff_get (base, &tag, &type, &len, &save);
4771     switch (tag) {
4772       case 1: case 3: case 5:
4773 	gpsdata[29+tag/2] = getc(ifp);			break;
4774       case 2: case 4: case 7:
4775 	FORC(6) gpsdata[tag/3*6+c] = get4();		break;
4776       case 6:
4777 	FORC(2) gpsdata[18+c] = get4();			break;
4778       case 18: case 29:
4779 	fgets ((char *) (gpsdata+14+tag/3), MIN(len,12), ifp);
4780     }
4781     fseek (ifp, save, SEEK_SET);
4782   }
4783 }
4784 
romm_coeff(float romm_cam[3][3])4785 void CLASS romm_coeff (float romm_cam[3][3])
4786 {
4787   static const float rgb_romm[3][3] =	/* ROMM == Kodak ProPhoto */
4788   { {  2.034193, -0.727420, -0.306766 },
4789     { -0.228811,  1.231729, -0.002922 },
4790     { -0.008565, -0.153273,  1.161839 } };
4791   int i, j, k;
4792 
4793   for (i=0; i < 3; i++)
4794     for (j=0; j < 3; j++)
4795       for (cmatrix[i][j] = k=0; k < 3; k++)
4796 	cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j];
4797 }
4798 
parse_mos(int offset)4799 void CLASS parse_mos (int offset)
4800 {
4801   char data[40];
4802   int skip, from, i, c, neut[4], planes=0, frot=0;
4803   static const char *mod[] =
4804   { "","DCB2","Volare","Cantare","CMost","Valeo 6","Valeo 11","Valeo 22",
4805     "Valeo 11p","Valeo 17","","Aptus 17","Aptus 22","Aptus 75","Aptus 65",
4806     "Aptus 54S","Aptus 65S","Aptus 75S","AFi 5","AFi 6","AFi 7",
4807     "","","","","","","","","","","","","","","","","","AFi-II 12" };
4808   float romm_cam[3][3];
4809 
4810   fseek (ifp, offset, SEEK_SET);
4811   while (1) {
4812     if (get4() != 0x504b5453) break;
4813     get4();
4814     fread (data, 1, 40, ifp);
4815     skip = get4();
4816     from = ftell(ifp);
4817     if (!strcmp(data,"JPEG_preview_data")) {
4818       thumb_offset = from;
4819       thumb_length = skip;
4820     }
4821     if (!strcmp(data,"icc_camera_profile")) {
4822       profile_offset = from;
4823       profile_length = skip;
4824     }
4825     if (!strcmp(data,"ShootObj_back_type")) {
4826       fscanf (ifp, "%d", &i);
4827       if ((unsigned) i < sizeof mod / sizeof (*mod))
4828 	strcpy (model, mod[i]);
4829     }
4830     if (!strcmp(data,"icc_camera_to_tone_matrix")) {
4831       for (i=0; i < 9; i++)
4832 	romm_cam[0][i] = int_to_float(get4());
4833       romm_coeff (romm_cam);
4834     }
4835     if (!strcmp(data,"CaptProf_color_matrix")) {
4836       for (i=0; i < 9; i++)
4837 	fscanf (ifp, "%f", &romm_cam[0][i]);
4838       romm_coeff (romm_cam);
4839     }
4840     if (!strcmp(data,"CaptProf_number_of_planes"))
4841       fscanf (ifp, "%d", &planes);
4842     if (!strcmp(data,"CaptProf_raw_data_rotation"))
4843       fscanf (ifp, "%d", &flip);
4844     if (!strcmp(data,"CaptProf_mosaic_pattern"))
4845       FORC4 {
4846 	fscanf (ifp, "%d", &i);
4847 	if (i == 1) frot = c ^ (c >> 1);
4848       }
4849     if (!strcmp(data,"ImgProf_rotation_angle")) {
4850       fscanf (ifp, "%d", &i);
4851       flip = i - flip;
4852     }
4853     if (!strcmp(data,"NeutObj_neutrals") && !cam_mul[0]) {
4854       FORC4 fscanf (ifp, "%d", neut+c);
4855       FORC3 cam_mul[c] = (float) neut[0] / neut[c+1];
4856     }
4857     if (!strcmp(data,"Rows_data"))
4858       load_flags = get4();
4859     parse_mos (from);
4860     fseek (ifp, skip+from, SEEK_SET);
4861   }
4862   if (planes)
4863     filters = (planes == 1) * 0x01010101 *
4864 	(uchar) "\x94\x61\x16\x49"[(flip/90 + frot) & 3];
4865 }
4866 
linear_table(unsigned len)4867 void CLASS linear_table (unsigned len)
4868 {
4869   int i;
4870   if (len > 0x1000) len = 0x1000;
4871   read_shorts (curve, len);
4872   for (i=len; i < 0x1000; i++)
4873     curve[i] = curve[i-1];
4874   maximum = curve[0xfff];
4875 }
4876 
parse_kodak_ifd(int base)4877 void CLASS parse_kodak_ifd (int base)
4878 {
4879   unsigned entries, tag, type, len, save;
4880   int i, c, wbi=-2, wbtemp=6500;
4881   float mul[3]={1,1,1}, num;
4882   static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 };
4883 
4884   entries = get2();
4885   if (entries > 1024) return;
4886   while (entries--) {
4887     tiff_get (base, &tag, &type, &len, &save);
4888     if (tag == 1020) wbi = getint(type);
4889     if (tag == 1021 && len == 72) {		/* WB set in software */
4890       fseek (ifp, 40, SEEK_CUR);
4891       FORC3 cam_mul[c] = 2048.0 / get2();
4892       wbi = -2;
4893     }
4894     if (tag == 2118) wbtemp = getint(type);
4895     if (tag == 2130 + wbi)
4896       FORC3 mul[c] = getreal(type);
4897     if (tag == 2140 + wbi && wbi >= 0)
4898       FORC3 {
4899 	for (num=i=0; i < 4; i++)
4900 	  num += getreal(type) * pow (wbtemp/100.0, i);
4901 	cam_mul[c] = 2048 / (num * mul[c]);
4902       }
4903     if (tag == 2317) linear_table (len);
4904     if (tag == 6020) iso_speed = getint(type);
4905     if (tag == 64013) wbi = fgetc(ifp);
4906     if ((unsigned) wbi < 7 && tag == wbtag[wbi])
4907       FORC3 cam_mul[c] = get4();
4908     if (tag == 64019) width = getint(type);
4909     if (tag == 64020) height = (getint(type)+1) & -2;
4910     fseek (ifp, save, SEEK_SET);
4911   }
4912 }
4913 
4914 void CLASS parse_minolta (int base);
4915 int CLASS parse_tiff (int base);
4916 
parse_tiff_ifd(int base)4917 int CLASS parse_tiff_ifd (int base)
4918 {
4919   unsigned entries, tag, type, len, plen=16, save;
4920   int ifd, use_cm=0, cfa, i, j, c, ima_len=0;
4921   int blrr=1, blrc=1, dblack[] = { 0,0,0,0 };
4922   char software[64], *cbuf, *cp;
4923   uchar cfa_pat[16], cfa_pc[] = { 0,1,2,3 }, tab[256];
4924   double cc[4][4], cm[4][3], cam_xyz[4][3], num;
4925   double ab[]={ 1,1,1,1 }, asn[] = { 0,0,0,0 }, xyz[] = { 1,1,1 };
4926   unsigned sony_curve[] = { 0,0,0,0,0,4095 };
4927   unsigned *buf, sony_offset=0, sony_length=0, sony_key=0;
4928   struct jhead jh;
4929   FILE *sfp;
4930 
4931   if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0])
4932     return 1;
4933   ifd = tiff_nifds++;
4934   for (j=0; j < 4; j++)
4935     for (i=0; i < 4; i++)
4936       cc[j][i] = i == j;
4937   entries = get2();
4938   if (entries > 512) return 1;
4939   while (entries--) {
4940     tiff_get (base, &tag, &type, &len, &save);
4941     switch (tag) {
4942       case 5:   width  = get2();  break;
4943       case 6:   height = get2();  break;
4944       case 7:   width += get2();  break;
4945       case 9:  filters = get2();  break;
4946       case 17: case 18:
4947 	if (type == 3 && len == 1)
4948 	  cam_mul[(tag-17)*2] = get2() / 256.0;
4949 	break;
4950       case 23:
4951 	if (type == 3) iso_speed = get2();
4952 	break;
4953       case 36: case 37: case 38:
4954 	cam_mul[tag-0x24] = get2();
4955 	break;
4956       case 39:
4957 	if (len < 50 || cam_mul[0]) break;
4958 	fseek (ifp, 12, SEEK_CUR);
4959 	FORC3 cam_mul[c] = get2();
4960 	break;
4961       case 46:
4962 	if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break;
4963 	thumb_offset = ftell(ifp) - 2;
4964 	thumb_length = len;
4965 	break;
4966       case 61440:			/* Fuji HS10 table */
4967 	parse_tiff_ifd (base);
4968 	break;
4969       case 2: case 256: case 61441:	/* ImageWidth */
4970 	tiff_ifd[ifd].width = getint(type);
4971 	break;
4972       case 3: case 257: case 61442:	/* ImageHeight */
4973 	tiff_ifd[ifd].height = getint(type);
4974 	break;
4975       case 258:				/* BitsPerSample */
4976       case 61443:
4977 	tiff_ifd[ifd].samples = len & 7;
4978 	tiff_ifd[ifd].bps = getint(type);
4979 	break;
4980       case 61446:
4981 	raw_height = 0;
4982 	load_raw = &CLASS packed_load_raw;
4983 	load_flags = get4() && (filters=0x16161616) ? 24:80;
4984 	break;
4985       case 259:				/* Compression */
4986 	tiff_ifd[ifd].comp = get2();
4987 	break;
4988       case 262:				/* PhotometricInterpretation */
4989 	tiff_ifd[ifd].phint = get2();
4990 	break;
4991       case 270:				/* ImageDescription */
4992 	fread (desc, 512, 1, ifp);
4993 	break;
4994       case 271:				/* Make */
4995 	fgets (make, 64, ifp);
4996 	break;
4997       case 272:				/* Model */
4998 	fgets (model, 64, ifp);
4999 	break;
5000       case 280:				/* Panasonic RW2 offset */
5001 	if (type != 4) break;
5002 	load_raw = &CLASS panasonic_load_raw;
5003 	load_flags = 0x2008;
5004       case 273:				/* StripOffset */
5005       case 513:				/* JpegIFOffset */
5006       case 61447:
5007 	tiff_ifd[ifd].offset = get4()+base;
5008 	if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) {
5009 	  fseek (ifp, tiff_ifd[ifd].offset, SEEK_SET);
5010 	  if (ljpeg_start (&jh, 1)) {
5011 	    tiff_ifd[ifd].comp    = 6;
5012 	    tiff_ifd[ifd].width   = jh.wide;
5013 	    tiff_ifd[ifd].height  = jh.high;
5014 	    tiff_ifd[ifd].bps     = jh.bits;
5015 	    tiff_ifd[ifd].samples = jh.clrs;
5016 	    if (!(jh.sraw || (jh.clrs & 1)))
5017 	      tiff_ifd[ifd].width *= jh.clrs;
5018 	    i = order;
5019 	    parse_tiff (tiff_ifd[ifd].offset + 12);
5020 	    order = i;
5021 	  }
5022 	}
5023 	break;
5024       case 274:				/* Orientation */
5025 	tiff_ifd[ifd].flip = "50132467"[get2() & 7]-'0';
5026 	break;
5027       case 277:				/* SamplesPerPixel */
5028 	tiff_ifd[ifd].samples = getint(type) & 7;
5029 	break;
5030       case 279:				/* StripByteCounts */
5031       case 514:
5032       case 61448:
5033 	tiff_ifd[ifd].bytes = get4();
5034 	break;
5035       case 61454:
5036 	FORC3 cam_mul[(4-c) % 3] = getint(type);
5037 	break;
5038       case 305:  case 11:		/* Software */
5039 	fgets (software, 64, ifp);
5040 	if (!strncmp(software,"Adobe",5) ||
5041 	    !strncmp(software,"dcraw",5) ||
5042 	    !strncmp(software,"UFRaw",5) ||
5043 	    !strncmp(software,"Bibble",6) ||
5044 	    !strncmp(software,"Nikon Scan",10) ||
5045 	    !strcmp (software,"Digital Photo Professional"))
5046 	  is_raw = 0;
5047 	break;
5048       case 306:				/* DateTime */
5049 	get_timestamp(0);
5050 	break;
5051       case 315:				/* Artist */
5052 	fread (artist, 64, 1, ifp);
5053 	break;
5054       case 322:				/* TileWidth */
5055 	tile_width = getint(type);
5056 	break;
5057       case 323:				/* TileLength */
5058 	tile_length = getint(type);
5059 	break;
5060       case 324:				/* TileOffsets */
5061 	tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4();
5062 	if (len == 4) {
5063 	  load_raw = &CLASS sinar_4shot_load_raw;
5064 	  is_raw = 5;
5065 	}
5066 	break;
5067       case 330:				/* SubIFDs */
5068 	if (!strcmp(model,"DSLR-A100") && tiff_ifd[ifd].width == 3872) {
5069 	  load_raw = &CLASS sony_arw_load_raw;
5070 	  data_offset = get4()+base;
5071 	  ifd++;  break;
5072 	}
5073 	while (len--) {
5074 	  i = ftell(ifp);
5075 	  fseek (ifp, get4()+base, SEEK_SET);
5076 	  if (parse_tiff_ifd (base)) break;
5077 	  fseek (ifp, i+4, SEEK_SET);
5078 	}
5079 	break;
5080       case 400:
5081 	strcpy (make, "Sarnoff");
5082 	maximum = 0xfff;
5083 	break;
5084       case 28688:
5085 	FORC4 sony_curve[c+1] = get2() >> 2 & 0xfff;
5086 	for (i=0; i < 5; i++)
5087 	  for (j = sony_curve[i]+1; j <= sony_curve[i+1]; j++)
5088 	    curve[j] = curve[j-1] + (1 << i);
5089 	break;
5090       case 29184: sony_offset = get4();  break;
5091       case 29185: sony_length = get4();  break;
5092       case 29217: sony_key    = get4();  break;
5093       case 29264:
5094 	parse_minolta (ftell(ifp));
5095 	raw_width = 0;
5096 	break;
5097       case 29443:
5098 	FORC4 cam_mul[c ^ (c < 2)] = get2();
5099 	break;
5100       case 29459:
5101 	FORC4 cam_mul[c] = get2();
5102 	i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1;
5103 	SWAP (cam_mul[i],cam_mul[i+1])
5104 	break;
5105       case 33405:			/* Model2 */
5106 	fgets (model2, 64, ifp);
5107 	break;
5108       case 33422:			/* CFAPattern */
5109       case 64777:			/* Kodak P-series */
5110 	if ((plen=len) > 16) plen = 16;
5111 	fread (cfa_pat, 1, plen, ifp);
5112 	for (colors=cfa=i=0; i < plen; i++) {
5113 	  colors += !(cfa & (1 << cfa_pat[i]));
5114 	  cfa |= 1 << cfa_pat[i];
5115 	}
5116 	if (cfa == 070) memcpy (cfa_pc,"\003\004\005",3);	/* CMY */
5117 	if (cfa == 072) memcpy (cfa_pc,"\005\003\004\001",4);	/* GMCY */
5118 	goto guess_cfa_pc;
5119       case 33424:
5120       case 65024:
5121 	fseek (ifp, get4()+base, SEEK_SET);
5122 	parse_kodak_ifd (base);
5123 	break;
5124       case 33434:			/* ExposureTime */
5125 	shutter = getreal(type);
5126 	break;
5127       case 33437:			/* FNumber */
5128 	aperture = getreal(type);
5129 	break;
5130       case 34306:			/* Leaf white balance */
5131 	FORC4 cam_mul[c ^ 1] = 4096.0 / get2();
5132 	break;
5133       case 34307:			/* Leaf CatchLight color matrix */
5134 	fread (software, 1, 7, ifp);
5135 	if (strncmp(software,"MATRIX",6)) break;
5136 	colors = 4;
5137 	for (raw_color = i=0; i < 3; i++) {
5138 	  FORC4 fscanf (ifp, "%f", &rgb_cam[i][c^1]);
5139 	  if (!use_camera_wb) continue;
5140 	  num = 0;
5141 	  FORC4 num += rgb_cam[i][c];
5142 	  FORC4 rgb_cam[i][c] /= num;
5143 	}
5144 	break;
5145       case 34310:			/* Leaf metadata */
5146 	parse_mos (ftell(ifp));
5147       case 34303:
5148 	strcpy (make, "Leaf");
5149 	break;
5150       case 34665:			/* EXIF tag */
5151 	fseek (ifp, get4()+base, SEEK_SET);
5152 	parse_exif (base);
5153 	break;
5154       case 34853:			/* GPSInfo tag */
5155 	fseek (ifp, get4()+base, SEEK_SET);
5156 	parse_gps (base);
5157 	break;
5158       case 34675:			/* InterColorProfile */
5159       case 50831:			/* AsShotICCProfile */
5160 	profile_offset = ftell(ifp);
5161 	profile_length = len;
5162 	break;
5163       case 37122:			/* CompressedBitsPerPixel */
5164 	kodak_cbpp = get4();
5165 	break;
5166       case 37386:			/* FocalLength */
5167 	focal_len = getreal(type);
5168 	break;
5169       case 37393:			/* ImageNumber */
5170 	shot_order = getint(type);
5171 	break;
5172       case 37400:			/* old Kodak KDC tag */
5173 	for (raw_color = i=0; i < 3; i++) {
5174 	  getreal(type);
5175 	  FORC3 rgb_cam[i][c] = getreal(type);
5176 	}
5177 	break;
5178       case 46275:			/* Imacon tags */
5179 	strcpy (make, "Imacon");
5180 	data_offset = ftell(ifp);
5181 	ima_len = len;
5182 	break;
5183       case 46279:
5184 	if (!ima_len) break;
5185 	fseek (ifp, 78, SEEK_CUR);
5186 	raw_width  = get4();
5187 	raw_height = get4();
5188 	left_margin = get4() & 7;
5189 	width = raw_width - left_margin - (get4() & 7);
5190 	top_margin = get4() & 7;
5191 	height = raw_height - top_margin - (get4() & 7);
5192 	if (raw_width == 7262) {
5193 	  height = 5444;
5194 	  width  = 7244;
5195 	  left_margin = 7;
5196 	}
5197 	fseek (ifp, 52, SEEK_CUR);
5198 	FORC3 cam_mul[c] = getreal(11);
5199 	fseek (ifp, 114, SEEK_CUR);
5200 	flip = (get2() >> 7) * 90;
5201 	if (width * height * 6 == ima_len) {
5202 	  if (flip % 180 == 90) SWAP(width,height);
5203 	  filters = flip = 0;
5204 	}
5205 	sprintf (model, "Ixpress %d-Mp", height*width/1000000);
5206 	load_raw = &CLASS imacon_full_load_raw;
5207 	if (filters) {
5208 	  if (left_margin & 1) filters = 0x61616161;
5209 	  load_raw = &CLASS unpacked_load_raw;
5210 	}
5211 	maximum = 0xffff;
5212 	break;
5213       case 50454:			/* Sinar tag */
5214       case 50455:
5215 	if (!(cbuf = (char *) malloc(len))) break;
5216 	fread (cbuf, 1, len, ifp);
5217 	for (cp = cbuf-1; cp && cp < cbuf+len; cp = strchr(cp,'\n'))
5218 	  if (!strncmp (++cp,"Neutral ",8))
5219 	    sscanf (cp+8, "%f %f %f", cam_mul, cam_mul+1, cam_mul+2);
5220 	free (cbuf);
5221 	break;
5222       case 50458:
5223 	if (!make[0]) strcpy (make, "Hasselblad");
5224 	break;
5225       case 50459:			/* Hasselblad tag */
5226 	i = order;
5227 	j = ftell(ifp);
5228 	c = tiff_nifds;
5229 	order = get2();
5230 	fseek (ifp, j+(get2(),get4()), SEEK_SET);
5231 	parse_tiff_ifd (j);
5232 	maximum = 0xffff;
5233 	tiff_nifds = c;
5234 	order = i;
5235 	break;
5236       case 50706:			/* DNGVersion */
5237 	FORC4 dng_version = (dng_version << 8) + fgetc(ifp);
5238 	if (!make[0]) strcpy (make, "DNG");
5239 	is_raw = 1;
5240 	break;
5241       case 50710:			/* CFAPlaneColor */
5242 	if (len > 4) len = 4;
5243 	colors = len;
5244 	fread (cfa_pc, 1, colors, ifp);
5245 guess_cfa_pc:
5246 	FORCC tab[cfa_pc[c]] = c;
5247 	cdesc[c] = 0;
5248 	for (i=16; i--; )
5249 	  filters = filters << 2 | tab[cfa_pat[i % plen]];
5250 	break;
5251       case 50711:			/* CFALayout */
5252 	if (get2() == 2) {
5253 	  fuji_width = 1;
5254 	  filters = 0x49494949;
5255 	}
5256 	break;
5257       case 291:
5258       case 50712:			/* LinearizationTable */
5259 	linear_table (len);
5260 	break;
5261       case 50713:			/* BlackLevelRepeatDim */
5262 	blrr = get2();
5263 	blrc = get2();
5264 	break;
5265       case 61450:
5266 	blrr = blrc = 2;
5267       case 50714:			/* BlackLevel */
5268 	black = getreal(type);
5269 	if (!filters || !~filters) break;
5270 	dblack[0] = black;
5271 	dblack[1] = (blrc == 2) ? getreal(type):dblack[0];
5272 	dblack[2] = (blrr == 2) ? getreal(type):dblack[0];
5273 	dblack[3] = (blrc == 2 && blrr == 2) ? getreal(type):dblack[1];
5274 	if (colors == 3)
5275 	  filters |= ((filters >> 2 & 0x22222222) |
5276 		      (filters << 2 & 0x88888888)) & filters << 1;
5277 	FORC4 cblack[filters >> (c << 1) & 3] = dblack[c];
5278 	black = 0;
5279 	break;
5280       case 50715:			/* BlackLevelDeltaH */
5281       case 50716:			/* BlackLevelDeltaV */
5282 	for (num=i=0; i < len; i++)
5283 	  num += getreal(type);
5284 	black += num/len + 0.5;
5285 	break;
5286       case 50717:			/* WhiteLevel */
5287 	maximum = getint(type);
5288 	break;
5289       case 50718:			/* DefaultScale */
5290 	pixel_aspect  = getreal(type);
5291 	pixel_aspect /= getreal(type);
5292 	break;
5293       case 50721:			/* ColorMatrix1 */
5294       case 50722:			/* ColorMatrix2 */
5295 	FORCC for (j=0; j < 3; j++)
5296 	  cm[c][j] = getreal(type);
5297 	use_cm = 1;
5298 	break;
5299       case 50723:			/* CameraCalibration1 */
5300       case 50724:			/* CameraCalibration2 */
5301 	for (i=0; i < colors; i++)
5302 	  FORCC cc[i][c] = getreal(type);
5303 	break;
5304       case 50727:			/* AnalogBalance */
5305 	FORCC ab[c] = getreal(type);
5306 	break;
5307       case 50728:			/* AsShotNeutral */
5308 	FORCC asn[c] = getreal(type);
5309 	break;
5310       case 50729:			/* AsShotWhiteXY */
5311 	xyz[0] = getreal(type);
5312 	xyz[1] = getreal(type);
5313 	xyz[2] = 1 - xyz[0] - xyz[1];
5314 	FORC3 xyz[c] /= d65_white[c];
5315 	break;
5316       case 50740:			/* DNGPrivateData */
5317 	if (dng_version) break;
5318 	parse_minolta (j = get4()+base);
5319 	fseek (ifp, j, SEEK_SET);
5320 	parse_tiff_ifd (base);
5321 	break;
5322       case 50752:
5323 	read_shorts (cr2_slice, 3);
5324 	break;
5325       case 50829:			/* ActiveArea */
5326 	top_margin = getint(type);
5327 	left_margin = getint(type);
5328 	height = getint(type) - top_margin;
5329 	width = getint(type) - left_margin;
5330 	break;
5331       case 64772:			/* Kodak P-series */
5332 	if (len < 13) break;
5333 	fseek (ifp, 16, SEEK_CUR);
5334 	data_offset = get4();
5335 	fseek (ifp, 28, SEEK_CUR);
5336 	data_offset += get4();
5337 	load_raw = &CLASS packed_load_raw;
5338 	break;
5339       case 65026:
5340 	if (type == 2) fgets (model2, 64, ifp);
5341     }
5342     fseek (ifp, save, SEEK_SET);
5343   }
5344   if (sony_length && (buf = (unsigned *) malloc(sony_length))) {
5345     fseek (ifp, sony_offset, SEEK_SET);
5346     fread (buf, sony_length, 1, ifp);
5347     sony_decrypt (buf, sony_length/4, 1, sony_key);
5348     sfp = ifp;
5349     if ((ifp = tmpfile())) {
5350       fwrite (buf, sony_length, 1, ifp);
5351       fseek (ifp, 0, SEEK_SET);
5352       parse_tiff_ifd (-sony_offset);
5353       fclose (ifp);
5354     }
5355     ifp = sfp;
5356     free (buf);
5357   }
5358   for (i=0; i < colors; i++)
5359     FORCC cc[i][c] *= ab[i];
5360   if (use_cm) {
5361     FORCC for (i=0; i < 3; i++)
5362       for (cam_xyz[c][i]=j=0; j < colors; j++)
5363 	cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i];
5364     cam_xyz_coeff (cam_xyz);
5365   }
5366   if (asn[0]) {
5367     cam_mul[3] = 0;
5368     FORCC cam_mul[c] = 1 / asn[c];
5369   }
5370   if (!use_cm)
5371     FORCC pre_mul[c] /= cc[c][c];
5372   return 0;
5373 }
5374 
parse_tiff(int base)5375 int CLASS parse_tiff (int base)
5376 {
5377   int doff;
5378 
5379   fseek (ifp, base, SEEK_SET);
5380   order = get2();
5381   if (order != 0x4949 && order != 0x4d4d) return 0;
5382   get2();
5383   while ((doff = get4())) {
5384     fseek (ifp, doff+base, SEEK_SET);
5385     if (parse_tiff_ifd (base)) break;
5386   }
5387   return 1;
5388 }
5389 
apply_tiff()5390 void CLASS apply_tiff()
5391 {
5392   int max_samp=0, raw=-1, thm=-1, i;
5393   struct jhead jh;
5394 
5395   thumb_misc = 16;
5396   if (thumb_offset) {
5397     fseek (ifp, thumb_offset, SEEK_SET);
5398     if (ljpeg_start (&jh, 1)) {
5399       thumb_misc   = jh.bits;
5400       thumb_width  = jh.wide;
5401       thumb_height = jh.high;
5402     }
5403   }
5404   for (i=0; i < tiff_nifds; i++) {
5405     if (max_samp < tiff_ifd[i].samples)
5406 	max_samp = tiff_ifd[i].samples;
5407     if (max_samp > 3) max_samp = 3;
5408     if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) &&
5409 	(tiff_ifd[i].width | tiff_ifd[i].height) < 0x10000 &&
5410 	tiff_ifd[i].width*tiff_ifd[i].height > raw_width*raw_height) {
5411       raw_width     = tiff_ifd[i].width;
5412       raw_height    = tiff_ifd[i].height;
5413       tiff_bps      = tiff_ifd[i].bps;
5414       tiff_compress = tiff_ifd[i].comp;
5415       data_offset   = tiff_ifd[i].offset;
5416       tiff_flip     = tiff_ifd[i].flip;
5417       tiff_samples  = tiff_ifd[i].samples;
5418       raw = i;
5419     }
5420   }
5421   for (i=tiff_nifds; i--; )
5422     if (tiff_ifd[i].flip) tiff_flip = tiff_ifd[i].flip;
5423   if (raw >= 0 && !load_raw)
5424     switch (tiff_compress) {
5425       case 0:  case 1:
5426 	switch (tiff_bps) {
5427 	  case  8: load_raw = &CLASS eight_bit_load_raw;	break;
5428 	  case 12: load_raw = &CLASS packed_load_raw;
5429 		   if (tiff_ifd[raw].phint == 2)
5430 		     load_flags = 6;
5431 		   if (strncmp(make,"PENTAX",6)) break;
5432 	  case 14:
5433 	  case 16: load_raw = &CLASS unpacked_load_raw;		break;
5434 	}
5435 	if (tiff_ifd[raw].bytes*5 == raw_width*raw_height*8) {
5436 	  tiff_bps = 12;
5437 	  load_raw = &CLASS packed_load_raw;
5438 	  load_flags = 81;
5439 	}
5440 	break;
5441       case 6:  case 7:  case 99:
5442 	load_raw = &CLASS lossless_jpeg_load_raw;		break;
5443       case 262:
5444 	load_raw = &CLASS kodak_262_load_raw;			break;
5445       case 32767:
5446 	if (tiff_ifd[raw].bytes == raw_width*raw_height) {
5447 	  tiff_bps = 12;
5448 	  load_raw = &CLASS sony_arw2_load_raw;			break;
5449 	}
5450 	if (tiff_ifd[raw].bytes*8 != raw_width*raw_height*tiff_bps) {
5451 	  raw_height += 8;
5452 	  load_raw = &CLASS sony_arw_load_raw;			break;
5453 	}
5454 	load_flags = 79;
5455       case 32769:
5456 	load_flags++;
5457       case 32770:
5458       case 32773:
5459 	load_raw = &CLASS packed_load_raw;			break;
5460       case 34713:
5461 	load_raw = &CLASS nikon_compressed_load_raw;		break;
5462       case 65535:
5463 	load_raw = &CLASS pentax_load_raw;			break;
5464       case 65000:
5465 	switch (tiff_ifd[raw].phint) {
5466 	  case 2: load_raw = &CLASS kodak_rgb_load_raw;   filters = 0;  break;
5467 	  case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0;  break;
5468 	  case 32803: load_raw = &CLASS kodak_65000_load_raw;
5469 	}
5470       case 32867: break;
5471       default: is_raw = 0;
5472     }
5473   if (!dng_version)
5474     if ( (tiff_samples == 3 && tiff_ifd[raw].bytes &&
5475 	  tiff_bps != 14 && tiff_bps != 2048)
5476       || (tiff_bps == 8 && !strstr(make,"KODAK") && !strstr(make,"Kodak") &&
5477 	  !strstr(model2,"DEBUG RAW")))
5478       is_raw = 0;
5479   for (i=0; i < tiff_nifds; i++)
5480     if (i != raw && tiff_ifd[i].samples == max_samp &&
5481 	tiff_ifd[i].width * tiff_ifd[i].height / SQR(tiff_ifd[i].bps+1) >
5482 	      thumb_width *       thumb_height / SQR(thumb_misc+1)) {
5483       thumb_width  = tiff_ifd[i].width;
5484       thumb_height = tiff_ifd[i].height;
5485       thumb_offset = tiff_ifd[i].offset;
5486       thumb_length = tiff_ifd[i].bytes;
5487       thumb_misc   = tiff_ifd[i].bps;
5488       thm = i;
5489     }
5490   if (thm >= 0) {
5491     thumb_misc |= tiff_ifd[thm].samples << 5;
5492     switch (tiff_ifd[thm].comp) {
5493       case 0:
5494 	write_thumb = &CLASS layer_thumb;
5495 	break;
5496       case 1:
5497 	if (tiff_ifd[thm].bps > 8)
5498 	  thumb_load_raw = &CLASS kodak_thumb_load_raw;
5499 	else
5500 	  write_thumb = &CLASS ppm_thumb;
5501 	break;
5502       case 65000:
5503 	thumb_load_raw = tiff_ifd[thm].phint == 6 ?
5504 		&CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw;
5505     }
5506   }
5507 }
5508 
parse_minolta(int base)5509 void CLASS parse_minolta (int base)
5510 {
5511   int save, tag, len, offset, high=0, wide=0, i, c;
5512   short sorder=order;
5513 
5514   fseek (ifp, base, SEEK_SET);
5515   if (fgetc(ifp) || fgetc(ifp)-'M' || fgetc(ifp)-'R') return;
5516   order = fgetc(ifp) * 0x101;
5517   offset = base + get4() + 8;
5518   while ((save=ftell(ifp)) < offset) {
5519     for (tag=i=0; i < 4; i++)
5520       tag = tag << 8 | fgetc(ifp);
5521     len = get4();
5522     switch (tag) {
5523       case 0x505244:				/* PRD */
5524 	fseek (ifp, 8, SEEK_CUR);
5525 	high = get2();
5526 	wide = get2();
5527 	break;
5528       case 0x574247:				/* WBG */
5529 	get4();
5530 	i = strcmp(model,"DiMAGE A200") ? 0:3;
5531 	FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2();
5532 	break;
5533       case 0x545457:				/* TTW */
5534 	parse_tiff (ftell(ifp));
5535 	data_offset = offset;
5536     }
5537     fseek (ifp, save+len+8, SEEK_SET);
5538   }
5539   raw_height = high;
5540   raw_width  = wide;
5541   order = sorder;
5542 }
5543 
5544 /*
5545    Many cameras have a "debug mode" that writes JPEG and raw
5546    at the same time.  The raw file has no header, so try to
5547    to open the matching JPEG file and read its metadata.
5548  */
parse_external_jpeg()5549 void CLASS parse_external_jpeg()
5550 {
5551   const char *file, *ext;
5552   char *jname, *jfile, *jext;
5553   FILE *save=ifp;
5554 
5555   ext  = strrchr (ifname, '.');
5556   file = strrchr (ifname, '/');
5557   if (!file) file = strrchr (ifname, '\\');
5558   if (!file) file = ifname-1;
5559   file++;
5560   if (!ext || strlen(ext) != 4 || ext-file != 8) return;
5561   jname = (char *) malloc (strlen(ifname) + 1);
5562   merror (jname, "parse_external_jpeg()");
5563   strcpy (jname, ifname);
5564   jfile = file - ifname + jname;
5565   jext  = ext  - ifname + jname;
5566   if (strcasecmp (ext, ".jpg")) {
5567     strcpy (jext, isupper(ext[1]) ? ".JPG":".jpg");
5568     if (isdigit(*file)) {
5569       memcpy (jfile, file+4, 4);
5570       memcpy (jfile+4, file, 4);
5571     }
5572   } else
5573     while (isdigit(*--jext)) {
5574       if (*jext != '9') {
5575 	(*jext)++;
5576 	break;
5577       }
5578       *jext = '0';
5579     }
5580   if (strcmp (jname, ifname)) {
5581     if ((ifp = fopen (jname, "rb"))) {
5582       if (verbose)
5583 	fprintf (stderr,_("Reading metadata from %s ...\n"), jname);
5584       parse_tiff (12);
5585       thumb_offset = 0;
5586       is_raw = 1;
5587       fclose (ifp);
5588     }
5589   }
5590   if (!timestamp)
5591     fprintf (stderr,_("Failed to read metadata from %s\n"), jname);
5592   free (jname);
5593   ifp = save;
5594 }
5595 
5596 /*
5597    CIFF block 0x1030 contains an 8x8 white sample.
5598    Load this into white[][] for use in scale_colors().
5599  */
ciff_block_1030()5600 void CLASS ciff_block_1030()
5601 {
5602   static const ushort key[] = { 0x410, 0x45f3 };
5603   int i, bpp, row, col, vbits=0;
5604   unsigned long bitbuf=0;
5605 
5606   if ((get2(),get4()) != 0x80008 || !get4()) return;
5607   bpp = get2();
5608   if (bpp != 10 && bpp != 12) return;
5609   for (i=row=0; row < 8; row++)
5610     for (col=0; col < 8; col++) {
5611       if (vbits < bpp) {
5612 	bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]);
5613 	vbits += 16;
5614       }
5615       white[row][col] =
5616 	bitbuf << (LONG_BIT - vbits) >> (LONG_BIT - bpp);
5617       vbits -= bpp;
5618     }
5619 }
5620 
5621 /*
5622    Parse a CIFF file, better known as Canon CRW format.
5623  */
parse_ciff(int offset,int length)5624 void CLASS parse_ciff (int offset, int length)
5625 {
5626   int tboff, nrecs, c, type, len, save, wbi=-1;
5627   ushort key[] = { 0x410, 0x45f3 };
5628 
5629   fseek (ifp, offset+length-4, SEEK_SET);
5630   tboff = get4() + offset;
5631   fseek (ifp, tboff, SEEK_SET);
5632   nrecs = get2();
5633   if (nrecs > 100) return;
5634   while (nrecs--) {
5635     type = get2();
5636     len  = get4();
5637     save = ftell(ifp) + 4;
5638     fseek (ifp, offset+get4(), SEEK_SET);
5639     if ((((type >> 8) + 8) | 8) == 0x38)
5640       parse_ciff (ftell(ifp), len);	/* Parse a sub-table */
5641 
5642     if (type == 0x0810)
5643       fread (artist, 64, 1, ifp);
5644     if (type == 0x080a) {
5645       fread (make, 64, 1, ifp);
5646       fseek (ifp, strlen(make) - 63, SEEK_CUR);
5647       fread (model, 64, 1, ifp);
5648     }
5649     if (type == 0x1810) {
5650       fseek (ifp, 12, SEEK_CUR);
5651       flip = get4();
5652     }
5653     if (type == 0x1835)			/* Get the decoder table */
5654       tiff_compress = get4();
5655     if (type == 0x2007) {
5656       thumb_offset = ftell(ifp);
5657       thumb_length = len;
5658     }
5659     if (type == 0x1818) {
5660       shutter = pow (2, -int_to_float((get4(),get4())));
5661       aperture = pow (2, int_to_float(get4())/2);
5662     }
5663     if (type == 0x102a) {
5664       iso_speed = pow (2, (get4(),get2())/32.0 - 4) * 50;
5665       aperture  = pow (2, (get2(),(short)get2())/64.0);
5666       shutter   = pow (2,-((short)get2())/32.0);
5667       wbi = (get2(),get2());
5668       if (wbi > 17) wbi = 0;
5669       fseek (ifp, 32, SEEK_CUR);
5670       if (shutter > 1e6) shutter = get2()/10.0;
5671     }
5672     if (type == 0x102c) {
5673       if (get2() > 512) {		/* Pro90, G1 */
5674 	fseek (ifp, 118, SEEK_CUR);
5675 	FORC4 cam_mul[c ^ 2] = get2();
5676       } else {				/* G2, S30, S40 */
5677 	fseek (ifp, 98, SEEK_CUR);
5678 	FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2();
5679       }
5680     }
5681     if (type == 0x0032) {
5682       if (len == 768) {			/* EOS D30 */
5683 	fseek (ifp, 72, SEEK_CUR);
5684 	FORC4 cam_mul[c ^ (c >> 1)] = 1024.0 / get2();
5685 	if (!wbi) cam_mul[0] = -1;	/* use my auto white balance */
5686       } else if (!cam_mul[0]) {
5687 	if (get2() == key[0])		/* Pro1, G6, S60, S70 */
5688 	  c = (strstr(model,"Pro1") ?
5689 	      "012346000000000000":"01345:000000006008")[wbi]-'0'+ 2;
5690 	else {				/* G3, G5, S45, S50 */
5691 	  c = "023457000000006000"[wbi]-'0';
5692 	  key[0] = key[1] = 0;
5693 	}
5694 	fseek (ifp, 78 + c*8, SEEK_CUR);
5695 	FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1];
5696 	if (!wbi) cam_mul[0] = -1;
5697       }
5698     }
5699     if (type == 0x10a9) {		/* D60, 10D, 300D, and clones */
5700       if (len > 66) wbi = "0134567028"[wbi]-'0';
5701       fseek (ifp, 2 + wbi*8, SEEK_CUR);
5702       FORC4 cam_mul[c ^ (c >> 1)] = get2();
5703     }
5704     if (type == 0x1030 && (0x18040 >> wbi & 1))
5705       ciff_block_1030();		/* all that don't have 0x10a9 */
5706     if (type == 0x1031) {
5707       raw_width = (get2(),get2());
5708       raw_height = get2();
5709     }
5710     if (type == 0x5029) {
5711       focal_len = len >> 16;
5712       if ((len & 0xffff) == 2) focal_len /= 32;
5713     }
5714     if (type == 0x5813) flash_used = int_to_float(len);
5715     if (type == 0x5814) canon_ev   = int_to_float(len);
5716     if (type == 0x5817) shot_order = len;
5717     if (type == 0x5834) unique_id  = len;
5718     if (type == 0x580e) timestamp  = len;
5719     if (type == 0x180e) timestamp  = get4();
5720 #ifdef LOCALTIME
5721     if ((type | 0x4000) == 0x580e)
5722       timestamp = mktime (gmtime (&timestamp));
5723 #endif
5724     fseek (ifp, save, SEEK_SET);
5725   }
5726 }
5727 
parse_rollei()5728 void CLASS parse_rollei()
5729 {
5730   char line[128], *val;
5731   struct tm t;
5732 
5733   fseek (ifp, 0, SEEK_SET);
5734   memset (&t, 0, sizeof t);
5735   do {
5736     fgets (line, 128, ifp);
5737     if ((val = strchr(line,'=')))
5738       *val++ = 0;
5739     else
5740       val = line + strlen(line);
5741     if (!strcmp(line,"DAT"))
5742       sscanf (val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year);
5743     if (!strcmp(line,"TIM"))
5744       sscanf (val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec);
5745     if (!strcmp(line,"HDR"))
5746       thumb_offset = atoi(val);
5747     if (!strcmp(line,"X  "))
5748       raw_width = atoi(val);
5749     if (!strcmp(line,"Y  "))
5750       raw_height = atoi(val);
5751     if (!strcmp(line,"TX "))
5752       thumb_width = atoi(val);
5753     if (!strcmp(line,"TY "))
5754       thumb_height = atoi(val);
5755   } while (strncmp(line,"EOHD",4));
5756   data_offset = thumb_offset + thumb_width * thumb_height * 2;
5757   t.tm_year -= 1900;
5758   t.tm_mon -= 1;
5759   if (mktime(&t) > 0)
5760     timestamp = mktime(&t);
5761   strcpy (make, "Rollei");
5762   strcpy (model,"d530flex");
5763   write_thumb = &CLASS rollei_thumb;
5764 }
5765 
parse_sinar_ia()5766 void CLASS parse_sinar_ia()
5767 {
5768   int entries, off;
5769   char str[8], *cp;
5770 
5771   order = 0x4949;
5772   fseek (ifp, 4, SEEK_SET);
5773   entries = get4();
5774   fseek (ifp, get4(), SEEK_SET);
5775   while (entries--) {
5776     off = get4(); get4();
5777     fread (str, 8, 1, ifp);
5778     if (!strcmp(str,"META"))   meta_offset = off;
5779     if (!strcmp(str,"THUMB")) thumb_offset = off;
5780     if (!strcmp(str,"RAW0"))   data_offset = off;
5781   }
5782   fseek (ifp, meta_offset+20, SEEK_SET);
5783   fread (make, 64, 1, ifp);
5784   make[63] = 0;
5785   if ((cp = strchr(make,' '))) {
5786     strcpy (model, cp+1);
5787     *cp = 0;
5788   }
5789   raw_width  = get2();
5790   raw_height = get2();
5791   load_raw = &CLASS unpacked_load_raw;
5792   thumb_width = (get4(),get2());
5793   thumb_height = get2();
5794   write_thumb = &CLASS ppm_thumb;
5795   maximum = 0x3fff;
5796 }
5797 
parse_phase_one(int base)5798 void CLASS parse_phase_one (int base)
5799 {
5800   unsigned entries, tag, type, len, data, save, i, c;
5801   float romm_cam[3][3];
5802   char *cp;
5803 
5804   memset (&ph1, 0, sizeof ph1);
5805   fseek (ifp, base, SEEK_SET);
5806   order = get4() & 0xffff;
5807   if (get4() >> 8 != 0x526177) return;		/* "Raw" */
5808   fseek (ifp, get4()+base, SEEK_SET);
5809   entries = get4();
5810   get4();
5811   while (entries--) {
5812     tag  = get4();
5813     type = get4();
5814     len  = get4();
5815     data = get4();
5816     save = ftell(ifp);
5817     fseek (ifp, base+data, SEEK_SET);
5818     switch (tag) {
5819       case 0x100:  flip = "0653"[data & 3]-'0';  break;
5820       case 0x106:
5821 	for (i=0; i < 9; i++)
5822 	  romm_cam[0][i] = getreal(11);
5823 	romm_coeff (romm_cam);
5824 	break;
5825       case 0x107:
5826 	FORC3 cam_mul[c] = getreal(11);
5827 	break;
5828       case 0x108:  raw_width     = data;	break;
5829       case 0x109:  raw_height    = data;	break;
5830       case 0x10a:  left_margin   = data;	break;
5831       case 0x10b:  top_margin    = data;	break;
5832       case 0x10c:  width         = data;	break;
5833       case 0x10d:  height        = data;	break;
5834       case 0x10e:  ph1.format    = data;	break;
5835       case 0x10f:  data_offset   = data+base;	break;
5836       case 0x110:  meta_offset   = data+base;
5837 		   meta_length   = len;			break;
5838       case 0x112:  ph1.key_off   = save - 4;		break;
5839       case 0x210:  ph1.tag_210   = int_to_float(data);	break;
5840       case 0x21a:  ph1.tag_21a   = data;		break;
5841       case 0x21c:  strip_offset  = data+base;		break;
5842       case 0x21d:  ph1.black     = data;		break;
5843       case 0x222:  ph1.split_col = data - left_margin;	break;
5844       case 0x223:  ph1.black_off = data+base;		break;
5845       case 0x301:
5846 	model[63] = 0;
5847 	fread (model, 1, 63, ifp);
5848 	if ((cp = strstr(model," camera"))) *cp = 0;
5849     }
5850     fseek (ifp, save, SEEK_SET);
5851   }
5852   load_raw = ph1.format < 3 ?
5853 	&CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c;
5854   maximum = 0xffff;
5855   strcpy (make, "Phase One");
5856   if (model[0]) return;
5857   switch (raw_height) {
5858     case 2060: strcpy (model,"LightPhase");	break;
5859     case 2682: strcpy (model,"H 10");		break;
5860     case 4128: strcpy (model,"H 20");		break;
5861     case 5488: strcpy (model,"H 25");		break;
5862   }
5863 }
5864 
parse_fuji(int offset)5865 void CLASS parse_fuji (int offset)
5866 {
5867   unsigned entries, tag, len, save, c;
5868 
5869   fseek (ifp, offset, SEEK_SET);
5870   entries = get4();
5871   if (entries > 255) return;
5872   while (entries--) {
5873     tag = get2();
5874     len = get2();
5875     save = ftell(ifp);
5876     if (tag == 0x100) {
5877       raw_height = get2();
5878       raw_width  = get2();
5879     } else if (tag == 0x121) {
5880       height = get2();
5881       if ((width = get2()) == 4284) width += 3;
5882     } else if (tag == 0x130) {
5883       fuji_layout = fgetc(ifp) >> 7;
5884       load_raw = fgetc(ifp) & 8 ?
5885 	&CLASS unpacked_load_raw : &CLASS fuji_load_raw;
5886     } else if (tag == 0x2ff0) {
5887       FORC4 cam_mul[c ^ 1] = get2();
5888     } else if (tag == 0xc000) {
5889       c = order;
5890       order = 0x4949;
5891       width  = get4();
5892       height = get4();
5893       order = c;
5894     }
5895     fseek (ifp, save+len, SEEK_SET);
5896   }
5897   height <<= fuji_layout;
5898   width  >>= fuji_layout;
5899 }
5900 
parse_jpeg(int offset)5901 int CLASS parse_jpeg (int offset)
5902 {
5903   int len, save, hlen, mark;
5904 
5905   fseek (ifp, offset, SEEK_SET);
5906   if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0;
5907 
5908   while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) {
5909     order = 0x4d4d;
5910     len   = get2() - 2;
5911     save  = ftell(ifp);
5912     if (mark == 0xc0 || mark == 0xc3) {
5913       fgetc(ifp);
5914       raw_height = get2();
5915       raw_width  = get2();
5916     }
5917     order = get2();
5918     hlen  = get4();
5919     if (get4() == 0x48454150)		/* "HEAP" */
5920       parse_ciff (save+hlen, len-hlen);
5921     if (parse_tiff (save+6)) apply_tiff();
5922     fseek (ifp, save+len, SEEK_SET);
5923   }
5924   return 1;
5925 }
5926 
parse_riff()5927 void CLASS parse_riff()
5928 {
5929   unsigned i, size, end;
5930   char tag[4], date[64], month[64];
5931   static const char mon[12][4] =
5932   { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" };
5933   struct tm t;
5934 
5935   order = 0x4949;
5936   fread (tag, 4, 1, ifp);
5937   size = get4();
5938   end = ftell(ifp) + size;
5939   if (!memcmp(tag,"RIFF",4) || !memcmp(tag,"LIST",4)) {
5940     get4();
5941     while (ftell(ifp)+7 < end)
5942       parse_riff();
5943   } else if (!memcmp(tag,"nctg",4)) {
5944     while (ftell(ifp)+7 < end) {
5945       i = get2();
5946       size = get2();
5947       if ((i+1) >> 1 == 10 && size == 20)
5948 	get_timestamp(0);
5949       else fseek (ifp, size, SEEK_CUR);
5950     }
5951   } else if (!memcmp(tag,"IDIT",4) && size < 64) {
5952     fread (date, 64, 1, ifp);
5953     date[size] = 0;
5954     memset (&t, 0, sizeof t);
5955     if (sscanf (date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday,
5956 	&t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) {
5957       for (i=0; i < 12 && strcasecmp(mon[i],month); i++);
5958       t.tm_mon = i;
5959       t.tm_year -= 1900;
5960       if (mktime(&t) > 0)
5961 	timestamp = mktime(&t);
5962     }
5963   } else
5964     fseek (ifp, size, SEEK_CUR);
5965 }
5966 
parse_smal(int offset,int fsize)5967 void CLASS parse_smal (int offset, int fsize)
5968 {
5969   int ver;
5970 
5971   fseek (ifp, offset+2, SEEK_SET);
5972   order = 0x4949;
5973   ver = fgetc(ifp);
5974   if (ver == 6)
5975     fseek (ifp, 5, SEEK_CUR);
5976   if (get4() != fsize) return;
5977   if (ver > 6) data_offset = get4();
5978   raw_height = height = get2();
5979   raw_width  = width  = get2();
5980   strcpy (make, "SMaL");
5981   sprintf (model, "v%d %dx%d", ver, width, height);
5982   if (ver == 6) load_raw = &CLASS smal_v6_load_raw;
5983   if (ver == 9) load_raw = &CLASS smal_v9_load_raw;
5984 }
5985 
parse_cine()5986 void CLASS parse_cine()
5987 {
5988   unsigned off_head, off_setup, off_image, i;
5989 
5990   order = 0x4949;
5991   fseek (ifp, 4, SEEK_SET);
5992   is_raw = get2() == 2;
5993   fseek (ifp, 14, SEEK_CUR);
5994   is_raw *= get4();
5995   off_head = get4();
5996   off_setup = get4();
5997   off_image = get4();
5998   timestamp = get4();
5999   if ((i = get4())) timestamp = i;
6000   fseek (ifp, off_head+4, SEEK_SET);
6001   raw_width = get4();
6002   raw_height = get4();
6003   switch (get2(),get2()) {
6004     case  8:  load_raw = &CLASS eight_bit_load_raw;  break;
6005     case 16:  load_raw = &CLASS  unpacked_load_raw;
6006   }
6007   fseek (ifp, off_setup+792, SEEK_SET);
6008   strcpy (make, "CINE");
6009   sprintf (model, "%d", get4());
6010   fseek (ifp, 12, SEEK_CUR);
6011   switch ((i=get4()) & 0xffffff) {
6012     case  3:  filters = 0x94949494;  break;
6013     case  4:  filters = 0x49494949;  break;
6014     default:  is_raw = 0;
6015   }
6016   fseek (ifp, 72, SEEK_CUR);
6017   switch ((get4()+3600) % 360) {
6018     case 270:  flip = 4;  break;
6019     case 180:  flip = 1;  break;
6020     case  90:  flip = 7;  break;
6021     case   0:  flip = 2;
6022   }
6023   cam_mul[0] = getreal(11);
6024   cam_mul[2] = getreal(11);
6025   maximum = ~(-1 << get4());
6026   fseek (ifp, 668, SEEK_CUR);
6027   shutter = get4()/1000000000.0;
6028   fseek (ifp, off_image, SEEK_SET);
6029   if (shot_select < is_raw)
6030     fseek (ifp, shot_select*8, SEEK_CUR);
6031   data_offset  = (INT64) get4() + 8;
6032   data_offset += (INT64) get4() << 32;
6033 }
6034 
parse_redcine()6035 void CLASS parse_redcine()
6036 {
6037   unsigned i, len, rdvo;
6038 
6039   order = 0x4d4d;
6040   is_raw = 0;
6041   fseek (ifp, 52, SEEK_SET);
6042   width  = get4();
6043   height = get4();
6044   fseek (ifp, 0, SEEK_END);
6045   fseek (ifp, -(i = ftello(ifp) & 511), SEEK_CUR);
6046   if (get4() != i || get4() != 0x52454f42) {
6047     fprintf (stderr,_("%s: Tail is missing, parsing from head...\n"), ifname);
6048     fseek (ifp, 0, SEEK_SET);
6049     while ((len = get4()) != EOF) {
6050       if (get4() == 0x52454456)
6051 	if (is_raw++ == shot_select)
6052 	  data_offset = ftello(ifp) - 8;
6053       fseek (ifp, len-8, SEEK_CUR);
6054     }
6055   } else {
6056     rdvo = get4();
6057     fseek (ifp, 12, SEEK_CUR);
6058     is_raw = get4();
6059     fseeko (ifp, rdvo+8 + shot_select*4, SEEK_SET);
6060     data_offset = get4();
6061   }
6062 }
6063 
foveon_gets(int offset,char * str,int len)6064 char * CLASS foveon_gets (int offset, char *str, int len)
6065 {
6066   int i;
6067   fseek (ifp, offset, SEEK_SET);
6068   for (i=0; i < len-1; i++)
6069     if ((str[i] = get2()) == 0) break;
6070   str[i] = 0;
6071   return str;
6072 }
6073 
parse_foveon()6074 void CLASS parse_foveon()
6075 {
6076   int entries, img=0, off, len, tag, save, i, wide, high, pent, poff[256][2];
6077   char name[64], value[64];
6078 
6079   order = 0x4949;			/* Little-endian */
6080   fseek (ifp, 36, SEEK_SET);
6081   flip = get4();
6082   fseek (ifp, -4, SEEK_END);
6083   fseek (ifp, get4(), SEEK_SET);
6084   if (get4() != 0x64434553) return;	/* SECd */
6085   entries = (get4(),get4());
6086   while (entries--) {
6087     off = get4();
6088     len = get4();
6089     tag = get4();
6090     save = ftell(ifp);
6091     fseek (ifp, off, SEEK_SET);
6092     if (get4() != (0x20434553 | (tag << 24))) return;
6093     switch (tag) {
6094       case 0x47414d49:			/* IMAG */
6095       case 0x32414d49:			/* IMA2 */
6096 	fseek (ifp, 12, SEEK_CUR);
6097 	wide = get4();
6098 	high = get4();
6099 	if (wide > raw_width && high > raw_height) {
6100 	  raw_width  = wide;
6101 	  raw_height = high;
6102 	  data_offset = off+24;
6103 	}
6104 	fseek (ifp, off+28, SEEK_SET);
6105 	if (fgetc(ifp) == 0xff && fgetc(ifp) == 0xd8
6106 		&& thumb_length < len-28) {
6107 	  thumb_offset = off+28;
6108 	  thumb_length = len-28;
6109 	  write_thumb = &CLASS jpeg_thumb;
6110 	}
6111 	if (++img == 2 && !thumb_length) {
6112 	  thumb_offset = off+24;
6113 	  thumb_width = wide;
6114 	  thumb_height = high;
6115 	  write_thumb = &CLASS foveon_thumb;
6116 	}
6117 	break;
6118       case 0x464d4143:			/* CAMF */
6119 	meta_offset = off+24;
6120 	meta_length = len-28;
6121 	if (meta_length > 0x20000)
6122 	    meta_length = 0x20000;
6123 	break;
6124       case 0x504f5250:			/* PROP */
6125 	pent = (get4(),get4());
6126 	fseek (ifp, 12, SEEK_CUR);
6127 	off += pent*8 + 24;
6128 	if ((unsigned) pent > 256) pent=256;
6129 	for (i=0; i < pent*2; i++)
6130 	  poff[0][i] = off + get4()*2;
6131 	for (i=0; i < pent; i++) {
6132 	  foveon_gets (poff[i][0], name, 64);
6133 	  foveon_gets (poff[i][1], value, 64);
6134 	  if (!strcmp (name, "ISO"))
6135 	    iso_speed = atoi(value);
6136 	  if (!strcmp (name, "CAMMANUF"))
6137 	    strcpy (make, value);
6138 	  if (!strcmp (name, "CAMMODEL"))
6139 	    strcpy (model, value);
6140 	  if (!strcmp (name, "WB_DESC"))
6141 	    strcpy (model2, value);
6142 	  if (!strcmp (name, "TIME"))
6143 	    timestamp = atoi(value);
6144 	  if (!strcmp (name, "EXPTIME"))
6145 	    shutter = atoi(value) / 1000000.0;
6146 	  if (!strcmp (name, "APERTURE"))
6147 	    aperture = atof(value);
6148 	  if (!strcmp (name, "FLENGTH"))
6149 	    focal_len = atof(value);
6150 	}
6151 #ifdef LOCALTIME
6152 	timestamp = mktime (gmtime (&timestamp));
6153 #endif
6154     }
6155     fseek (ifp, save, SEEK_SET);
6156   }
6157   is_foveon = 1;
6158 }
6159 
6160 /*
6161    All matrices are from Adobe DNG Converter unless otherwise noted.
6162  */
adobe_coeff(const char * make,const char * model)6163 void CLASS adobe_coeff (const char *make, const char *model)
6164 {
6165   static const struct {
6166     const char *prefix;
6167     short black, maximum, trans[12];
6168   } table[] = {
6169     { "AGFAPHOTO DC-833m", 0, 0,	/* DJC */
6170 	{ 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } },
6171     { "Apple QuickTake", 0, 0,		/* DJC */
6172 	{ 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } },
6173     { "Canon EOS D2000", 0, 0,
6174 	{ 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } },
6175     { "Canon EOS D6000", 0, 0,
6176 	{ 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } },
6177     { "Canon EOS D30", 0, 0,
6178 	{ 9805,-2689,-1312,-5803,13064,3068,-2438,3075,8775 } },
6179     { "Canon EOS D60", 0, 0xfa0,
6180 	{ 6188,-1341,-890,-7168,14489,2937,-2640,3228,8483 } },
6181     { "Canon EOS 5D Mark II", 0, 0x3cf0,
6182 	{ 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } },
6183     { "Canon EOS 5D", 0, 0xe6c,
6184 	{ 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } },
6185     { "Canon EOS 7D", 0, 0x3510,
6186 	{ 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } },
6187     { "Canon EOS 10D", 0, 0xfa0,
6188 	{ 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } },
6189     { "Canon EOS 20Da", 0, 0,
6190 	{ 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } },
6191     { "Canon EOS 20D", 0, 0xfff,
6192 	{ 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } },
6193     { "Canon EOS 30D", 0, 0,
6194 	{ 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } },
6195     { "Canon EOS 40D", 0, 0x3f60,
6196 	{ 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } },
6197     { "Canon EOS 50D", 0, 0x3d93,
6198 	{ 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } },
6199     { "Canon EOS 60D", 0, 0x2ff7,
6200 	{ 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } },
6201     { "Canon EOS 300D", 0, 0xfa0,
6202 	{ 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } },
6203     { "Canon EOS 350D", 0, 0xfff,
6204 	{ 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } },
6205     { "Canon EOS 400D", 0, 0xe8e,
6206 	{ 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } },
6207     { "Canon EOS 450D", 0, 0x390d,
6208 	{ 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } },
6209     { "Canon EOS 500D", 0, 0x3479,
6210 	{ 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } },
6211     { "Canon EOS 550D", 0, 0x3dd7,
6212 	{ 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } },
6213     { "Canon EOS 600D", 0, 0x3510,
6214 	{ 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } },
6215     { "Canon EOS 1000D", 0, 0xe43,
6216 	{ 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } },
6217     { "Canon EOS 1100D", 0, 0x3510,
6218 	{ 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } },
6219     { "Canon EOS-1Ds Mark III", 0, 0x3bb0,
6220 	{ 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } },
6221     { "Canon EOS-1Ds Mark II", 0, 0xe80,
6222 	{ 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } },
6223     { "Canon EOS-1D Mark IV", 0, 0x3bb0,
6224 	{ 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } },
6225     { "Canon EOS-1D Mark III", 0, 0x3bb0,
6226 	{ 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } },
6227     { "Canon EOS-1D Mark II N", 0, 0xe80,
6228 	{ 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } },
6229     { "Canon EOS-1D Mark II", 0, 0xe80,
6230 	{ 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } },
6231     { "Canon EOS-1DS", 0, 0xe20,
6232 	{ 4374,3631,-1743,-7520,15212,2472,-2892,3632,8161 } },
6233     { "Canon EOS-1D", 0, 0xe20,
6234 	{ 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } },
6235     { "Canon EOS", 0, 0,
6236 	{ 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } },
6237     { "Canon PowerShot A530", 0, 0,
6238 	{ 0 } },	/* don't want the A5 matrix */
6239     { "Canon PowerShot A50", 0, 0,
6240 	{ -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } },
6241     { "Canon PowerShot A5", 0, 0,
6242 	{ -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } },
6243     { "Canon PowerShot G10", 0, 0,
6244 	{ 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } },
6245     { "Canon PowerShot G11", 0, 0,
6246 	{ 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } },
6247     { "Canon PowerShot G12", 0, 0,
6248 	{ 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } },
6249     { "Canon PowerShot G1", 0, 0,
6250 	{ -4778,9467,2172,4743,-1141,4344,-5146,9908,6077,-1566,11051,557 } },
6251     { "Canon PowerShot G2", 0, 0,
6252 	{ 9087,-2693,-1049,-6715,14382,2537,-2291,2819,7790 } },
6253     { "Canon PowerShot G3", 0, 0,
6254 	{ 9212,-2781,-1073,-6573,14189,2605,-2300,2844,7664 } },
6255     { "Canon PowerShot G5", 0, 0,
6256 	{ 9757,-2872,-933,-5972,13861,2301,-1622,2328,7212 } },
6257     { "Canon PowerShot G6", 0, 0,
6258 	{ 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } },
6259     { "Canon PowerShot G9", 0, 0,
6260 	{ 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } },
6261     { "Canon PowerShot Pro1", 0, 0,
6262 	{ 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } },
6263     { "Canon PowerShot Pro70", 34, 0,
6264 	{ -4155,9818,1529,3939,-25,4522,-5521,9870,6610,-2238,10873,1342 } },
6265     { "Canon PowerShot Pro90", 0, 0,
6266 	{ -4963,9896,2235,4642,-987,4294,-5162,10011,5859,-1770,11230,577 } },
6267     { "Canon PowerShot S30", 0, 0,
6268 	{ 10566,-3652,-1129,-6552,14662,2006,-2197,2581,7670 } },
6269     { "Canon PowerShot S40", 0, 0,
6270 	{ 8510,-2487,-940,-6869,14231,2900,-2318,2829,9013 } },
6271     { "Canon PowerShot S45", 0, 0,
6272 	{ 8163,-2333,-955,-6682,14174,2751,-2077,2597,8041 } },
6273     { "Canon PowerShot S50", 0, 0,
6274 	{ 8882,-2571,-863,-6348,14234,2288,-1516,2172,6569 } },
6275     { "Canon PowerShot S60", 0, 0,
6276 	{ 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } },
6277     { "Canon PowerShot S70", 0, 0,
6278 	{ 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } },
6279     { "Canon PowerShot S90", 0, 0,
6280 	{ 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } },
6281     { "Canon PowerShot S95", 0, 0,
6282 	{ 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } },
6283     { "Canon PowerShot A470", 0, 0,	/* DJC */
6284 	{ 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } },
6285     { "Canon PowerShot A610", 0, 0,	/* DJC */
6286 	{ 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } },
6287     { "Canon PowerShot A620", 0, 0,	/* DJC */
6288 	{ 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } },
6289     { "Canon PowerShot A630", 0, 0,	/* DJC */
6290 	{ 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } },
6291     { "Canon PowerShot A640", 0, 0,	/* DJC */
6292 	{ 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } },
6293     { "Canon PowerShot A650", 0, 0,	/* DJC */
6294 	{ 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } },
6295     { "Canon PowerShot A720", 0, 0,	/* DJC */
6296 	{ 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } },
6297     { "Canon PowerShot S3 IS", 0, 0,	/* DJC */
6298 	{ 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } },
6299     { "Canon PowerShot SX1 IS", 0, 0,
6300 	{ 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } },
6301     { "Canon PowerShot SX110 IS", 0, 0,	/* DJC */
6302 	{ 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } },
6303     { "CASIO EX-S20", 0, 0,		/* DJC */
6304 	{ 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } },
6305     { "CASIO EX-Z750", 0, 0,		/* DJC */
6306 	{ 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } },
6307     { "CASIO EX-Z10", 128, 0xfff,	/* DJC */
6308 	{ 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } },
6309     { "CINE 650", 0, 0,
6310 	{ 3390,480,-500,-800,3610,340,-550,2336,1192 } },
6311     { "CINE 660", 0, 0,
6312 	{ 3390,480,-500,-800,3610,340,-550,2336,1192 } },
6313     { "CINE", 0, 0,
6314 	{ 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } },
6315     { "Contax N Digital", 0, 0xf1e,
6316 	{ 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } },
6317     { "EPSON R-D1", 0, 0,
6318 	{ 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } },
6319     { "FUJIFILM FinePix E550", 0, 0,
6320 	{ 11044,-3888,-1120,-7248,15168,2208,-1531,2277,8069 } },
6321     { "FUJIFILM FinePix E900", 0, 0,
6322 	{ 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } },
6323     { "FUJIFILM FinePix F8", 0, 0,
6324 	{ 11044,-3888,-1120,-7248,15168,2208,-1531,2277,8069 } },
6325     { "FUJIFILM FinePix F7", 0, 0,
6326 	{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
6327     { "FUJIFILM FinePix S100FS", 514, 0,
6328 	{ 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } },
6329     { "FUJIFILM FinePix S200EXR", 512, 0x3fff,
6330 	{ 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } },
6331     { "FUJIFILM FinePix S20Pro", 0, 0,
6332 	{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
6333     { "FUJIFILM FinePix S2Pro", 128, 0,
6334 	{ 12492,-4690,-1402,-7033,15423,1647,-1507,2111,7697 } },
6335     { "FUJIFILM FinePix S3Pro", 0, 0,
6336 	{ 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } },
6337     { "FUJIFILM FinePix S5Pro", 0, 0,
6338 	{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
6339     { "FUJIFILM FinePix S5000", 0, 0,
6340 	{ 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } },
6341     { "FUJIFILM FinePix S5100", 0, 0,
6342 	{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
6343     { "FUJIFILM FinePix S5500", 0, 0,
6344 	{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
6345     { "FUJIFILM FinePix S5200", 0, 0,
6346 	{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
6347     { "FUJIFILM FinePix S5600", 0, 0,
6348 	{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
6349     { "FUJIFILM FinePix S6", 0, 0,
6350 	{ 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } },
6351     { "FUJIFILM FinePix S7000", 0, 0,
6352 	{ 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } },
6353     { "FUJIFILM FinePix S9000", 0, 0,
6354 	{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
6355     { "FUJIFILM FinePix S9500", 0, 0,
6356 	{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
6357     { "FUJIFILM FinePix S9100", 0, 0,
6358 	{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
6359     { "FUJIFILM FinePix S9600", 0, 0,
6360 	{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
6361     { "FUJIFILM IS-1", 0, 0,
6362 	{ 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } },
6363     { "FUJIFILM IS Pro", 0, 0,
6364 	{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
6365     { "FUJIFILM FinePix HS10 HS11", 0, 0xf68,
6366 	{ 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } },
6367     { "FUJIFILM FinePix HS20EXR", 0, 0,
6368 	{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
6369     { "FUJIFILM FinePix F550EXR", 0, 0,
6370 	{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
6371     { "FUJIFILM FinePix F600EXR", 0, 0,
6372 	{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
6373     { "FUJIFILM FinePix X100", 0, 0,
6374 	{ 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } },
6375     { "Imacon Ixpress", 0, 0,		/* DJC */
6376 	{ 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } },
6377     { "KODAK NC2000", 0, 0,
6378 	{ 13891,-6055,-803,-465,9919,642,2121,82,1291 } },
6379     { "Kodak DCS315C", 8, 0,
6380 	{ 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } },
6381     { "Kodak DCS330C", 8, 0,
6382 	{ 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } },
6383     { "KODAK DCS420", 0, 0,
6384 	{ 10868,-1852,-644,-1537,11083,484,2343,628,2216 } },
6385     { "KODAK DCS460", 0, 0,
6386 	{ 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
6387     { "KODAK EOSDCS1", 0, 0,
6388 	{ 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
6389     { "KODAK EOSDCS3B", 0, 0,
6390 	{ 9898,-2700,-940,-2478,12219,206,1985,634,1031 } },
6391     { "Kodak DCS520C", 180, 0,
6392 	{ 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } },
6393     { "Kodak DCS560C", 188, 0,
6394 	{ 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } },
6395     { "Kodak DCS620C", 180, 0,
6396 	{ 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } },
6397     { "Kodak DCS620X", 185, 0,
6398 	{ 13095,-6231,154,12221,-21,-2137,895,4602,2258 } },
6399     { "Kodak DCS660C", 214, 0,
6400 	{ 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } },
6401     { "Kodak DCS720X", 0, 0,
6402 	{ 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } },
6403     { "Kodak DCS760C", 0, 0,
6404 	{ 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } },
6405     { "Kodak DCS Pro SLR", 0, 0,
6406 	{ 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
6407     { "Kodak DCS Pro 14nx", 0, 0,
6408 	{ 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
6409     { "Kodak DCS Pro 14", 0, 0,
6410 	{ 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } },
6411     { "Kodak ProBack645", 0, 0,
6412 	{ 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } },
6413     { "Kodak ProBack", 0, 0,
6414 	{ 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } },
6415     { "KODAK P712", 0, 0,
6416 	{ 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } },
6417     { "KODAK P850", 0, 0xf7c,
6418 	{ 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } },
6419     { "KODAK P880", 0, 0xfff,
6420 	{ 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } },
6421     { "KODAK EasyShare Z980", 0, 0,
6422 	{ 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } },
6423     { "KODAK EasyShare Z981", 0, 0,
6424 	{ 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } },
6425     { "KODAK EasyShare Z990", 0, 0xfed,
6426 	{ 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } },
6427     { "KODAK EASYSHARE Z1015", 0, 0xef1,
6428 	{ 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } },
6429     { "Leaf CMost", 0, 0,
6430 	{ 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
6431     { "Leaf Valeo 6", 0, 0,
6432 	{ 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
6433     { "Leaf Aptus 54S", 0, 0,
6434 	{ 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
6435     { "Leaf Aptus 65", 0, 0,
6436 	{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
6437     { "Leaf Aptus 75", 0, 0,
6438 	{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
6439     { "Leaf", 0, 0,
6440 	{ 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
6441     { "Mamiya ZD", 0, 0,
6442 	{ 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } },
6443     { "Micron 2010", 110, 0,		/* DJC */
6444 	{ 16695,-3761,-2151,155,9682,163,3433,951,4904 } },
6445     { "Minolta DiMAGE 5", 0, 0xf7d,
6446 	{ 8983,-2942,-963,-6556,14476,2237,-2426,2887,8014 } },
6447     { "Minolta DiMAGE 7Hi", 0, 0xf7d,
6448 	{ 11368,-3894,-1242,-6521,14358,2339,-2475,3056,7285 } },
6449     { "Minolta DiMAGE 7", 0, 0xf7d,
6450 	{ 9144,-2777,-998,-6676,14556,2281,-2470,3019,7744 } },
6451     { "Minolta DiMAGE A1", 0, 0xf8b,
6452 	{ 9274,-2547,-1167,-8220,16323,1943,-2273,2720,8340 } },
6453     { "MINOLTA DiMAGE A200", 0, 0,
6454 	{ 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } },
6455     { "Minolta DiMAGE A2", 0, 0xf8f,
6456 	{ 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } },
6457     { "Minolta DiMAGE Z2", 0, 0,	/* DJC */
6458 	{ 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
6459     { "MINOLTA DYNAX 5", 0, 0xffb,
6460 	{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
6461     { "MINOLTA DYNAX 7", 0, 0xffb,
6462 	{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
6463     { "MOTOROLA PIXL", 0, 0,		/* DJC */
6464 	{ 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } },
6465     { "NIKON D100", 0, 0,
6466 	{ 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } },
6467     { "NIKON D1H", 0, 0,
6468 	{ 7577,-2166,-926,-7454,15592,1934,-2377,2808,8606 } },
6469     { "NIKON D1X", 0, 0,
6470 	{ 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } },
6471     { "NIKON D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */
6472 	{ 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } },
6473     { "NIKON D200", 0, 0xfbc,
6474 	{ 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } },
6475     { "NIKON D2H", 0, 0,
6476 	{ 5710,-901,-615,-8594,16617,2024,-2975,4120,6830 } },
6477     { "NIKON D2X", 0, 0,
6478 	{ 10231,-2769,-1255,-8301,15900,2552,-797,680,7148 } },
6479     { "NIKON D3000", 0, 0,
6480 	{ 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } },
6481     { "NIKON D3100", 0, 0,
6482 	{ 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } },
6483     { "NIKON D300", 0, 0,
6484 	{ 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } },
6485     { "NIKON D3X", 0, 0,
6486 	{ 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } },
6487     { "NIKON D3S", 0, 0,
6488 	{ 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } },
6489     { "NIKON D3", 0, 0,
6490 	{ 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } },
6491     { "NIKON D40X", 0, 0,
6492 	{ 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } },
6493     { "NIKON D40", 0, 0,
6494 	{ 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } },
6495     { "NIKON D5000", 0, 0xf00,
6496 	{ 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } },
6497     { "NIKON D5100", 0, 0x3de6,
6498 	{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
6499     { "NIKON D50", 0, 0,
6500 	{ 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
6501     { "NIKON D60", 0, 0,
6502 	{ 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } },
6503     { "NIKON D7000", 0, 0,
6504 	{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
6505     { "NIKON D700", 0, 0,
6506 	{ 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } },
6507     { "NIKON D70", 0, 0,
6508 	{ 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
6509     { "NIKON D80", 0, 0,
6510 	{ 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } },
6511     { "NIKON D90", 0, 0xf00,
6512 	{ 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } },
6513     { "NIKON E950", 0, 0x3dd,		/* DJC */
6514 	{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
6515     { "NIKON E995", 0, 0,	/* copied from E5000 */
6516 	{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
6517     { "NIKON E2100", 0, 0,	/* copied from Z2, new white balance */
6518 	{ 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711} },
6519     { "NIKON E2500", 0, 0,
6520 	{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
6521     { "NIKON E3200", 0, 0,		/* DJC */
6522 	{ 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } },
6523     { "NIKON E4300", 0, 0,	/* copied from Minolta DiMAGE Z2 */
6524 	{ 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
6525     { "NIKON E4500", 0, 0,
6526 	{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
6527     { "NIKON E5000", 0, 0,
6528 	{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
6529     { "NIKON E5400", 0, 0,
6530 	{ 9349,-2987,-1001,-7919,15766,2266,-2098,2680,6839 } },
6531     { "NIKON E5700", 0, 0,
6532 	{ -5368,11478,2368,5537,-113,3148,-4969,10021,5782,778,9028,211 } },
6533     { "NIKON E8400", 0, 0,
6534 	{ 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } },
6535     { "NIKON E8700", 0, 0,
6536 	{ 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
6537     { "NIKON E8800", 0, 0,
6538 	{ 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } },
6539     { "NIKON COOLPIX P6000", 0, 0,
6540 	{ 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } },
6541     { "NIKON COOLPIX P7000", 0, 0,
6542 	{ 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } },
6543     { "NIKON COOLPIX P7100", 0, 0,
6544 	{ 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } },
6545     { "OLYMPUS C5050", 0, 0,
6546 	{ 10508,-3124,-1273,-6079,14294,1901,-1653,2306,6237 } },
6547     { "OLYMPUS C5060", 0, 0,
6548 	{ 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } },
6549     { "OLYMPUS C7070", 0, 0,
6550 	{ 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } },
6551     { "OLYMPUS C70", 0, 0,
6552 	{ 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } },
6553     { "OLYMPUS C80", 0, 0,
6554 	{ 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } },
6555     { "OLYMPUS E-10", 0, 0xffc,
6556 	{ 12745,-4500,-1416,-6062,14542,1580,-1934,2256,6603 } },
6557     { "OLYMPUS E-1", 0, 0,
6558 	{ 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } },
6559     { "OLYMPUS E-20", 0, 0xffc,
6560 	{ 13173,-4732,-1499,-5807,14036,1895,-2045,2452,7142 } },
6561     { "OLYMPUS E-300", 0, 0,
6562 	{ 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } },
6563     { "OLYMPUS E-330", 0, 0,
6564 	{ 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } },
6565     { "OLYMPUS E-30", 0, 0xfbc,
6566 	{ 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } },
6567     { "OLYMPUS E-3", 0, 0xf99,
6568 	{ 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } },
6569     { "OLYMPUS E-400", 0, 0,
6570 	{ 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } },
6571     { "OLYMPUS E-410", 0, 0xf6a,
6572 	{ 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } },
6573     { "OLYMPUS E-420", 0, 0xfd7,
6574 	{ 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } },
6575     { "OLYMPUS E-450", 0, 0xfd2,
6576 	{ 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } },
6577     { "OLYMPUS E-500", 0, 0,
6578 	{ 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } },
6579     { "OLYMPUS E-510", 0, 0xf6a,
6580 	{ 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } },
6581     { "OLYMPUS E-520", 0, 0xfd2,
6582 	{ 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } },
6583     { "OLYMPUS E-5", 0, 0,
6584 	{ 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } },
6585     { "OLYMPUS E-600", 0, 0xfaf,
6586 	{ 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } },
6587     { "OLYMPUS E-620", 0, 0xfaf,
6588 	{ 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } },
6589     { "OLYMPUS E-P1", 0, 0xffd,
6590 	{ 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } },
6591     { "OLYMPUS E-P2", 0, 0xffd,
6592 	{ 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } },
6593     { "OLYMPUS E-P3", 0, 0,
6594 	{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
6595     { "OLYMPUS E-PL1s", 0, 0,
6596 	{ 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } },
6597     { "OLYMPUS E-PL1", 0, 0,
6598 	{ 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } },
6599     { "OLYMPUS E-PL2", 0, 0,
6600 	{ 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } },
6601     { "OLYMPUS E-PL3", 0, 0,
6602 	{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
6603     { "OLYMPUS E-PM1", 0, 0,
6604 	{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
6605     { "OLYMPUS SP350", 0, 0,
6606 	{ 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } },
6607     { "OLYMPUS SP3", 0, 0,
6608 	{ 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } },
6609     { "OLYMPUS SP500UZ", 0, 0xfff,
6610 	{ 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } },
6611     { "OLYMPUS SP510UZ", 0, 0xffe,
6612 	{ 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } },
6613     { "OLYMPUS SP550UZ", 0, 0xffe,
6614 	{ 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } },
6615     { "OLYMPUS SP560UZ", 0, 0xff9,
6616 	{ 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } },
6617     { "OLYMPUS SP570UZ", 0, 0,
6618 	{ 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } },
6619     { "OLYMPUS XZ-1", 0, 0,
6620 	{ 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } },
6621     { "PENTAX *ist DL2", 0, 0,
6622 	{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
6623     { "PENTAX *ist DL", 0, 0,
6624 	{ 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } },
6625     { "PENTAX *ist DS2", 0, 0,
6626 	{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
6627     { "PENTAX *ist DS", 0, 0,
6628 	{ 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } },
6629     { "PENTAX *ist D", 0, 0,
6630 	{ 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } },
6631     { "PENTAX K10D", 0, 0,
6632 	{ 9566,-2863,-803,-7170,15172,2112,-818,803,9705 } },
6633     { "PENTAX K1", 0, 0,
6634 	{ 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } },
6635     { "PENTAX K20D", 0, 0,
6636 	{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
6637     { "PENTAX K200D", 0, 0,
6638 	{ 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } },
6639     { "PENTAX K2000", 0, 0,
6640 	{ 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } },
6641     { "PENTAX K-m", 0, 0,
6642 	{ 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } },
6643     { "PENTAX K-x", 0, 0,
6644 	{ 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } },
6645     { "PENTAX K-r", 0, 0,
6646 	{ 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } },
6647     { "PENTAX K-5", 0, 0,
6648 	{ 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } },
6649     { "PENTAX K-7", 0, 0,
6650 	{ 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } },
6651     { "PENTAX 645D", 0, 0x3e00,
6652 	{ 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } },
6653     { "Panasonic DMC-FZ8", 0, 0xf7f,
6654 	{ 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } },
6655     { "Panasonic DMC-FZ18", 0, 0,
6656 	{ 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } },
6657     { "Panasonic DMC-FZ28", 15, 0xf96,
6658 	{ 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } },
6659     { "Panasonic DMC-FZ30", 0, 0xf94,
6660 	{ 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } },
6661     { "Panasonic DMC-FZ3", 143, 0,
6662 	{ 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } },
6663     { "Panasonic DMC-FZ40", 143, 0,
6664 	{ 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } },
6665     { "Panasonic DMC-FZ50", 0, 0,
6666 	{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
6667     { "LEICA V-LUX1", 0, 0,
6668 	{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
6669     { "Panasonic DMC-L10", 15, 0xf96,
6670 	{ 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } },
6671     { "Panasonic DMC-L1", 0, 0xf7f,
6672 	{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
6673     { "LEICA DIGILUX 3", 0, 0xf7f,
6674 	{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
6675     { "Panasonic DMC-LC1", 0, 0,
6676 	{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
6677     { "LEICA DIGILUX 2", 0, 0,
6678 	{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
6679     { "Panasonic DMC-LX1", 0, 0xf7f,
6680 	{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
6681     { "LEICA D-LUX2", 0, 0xf7f,
6682 	{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
6683     { "Panasonic DMC-LX2", 0, 0,
6684 	{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
6685     { "LEICA D-LUX3", 0, 0,
6686 	{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
6687     { "Panasonic DMC-LX3", 15, 0,
6688 	{ 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } },
6689     { "LEICA D-LUX 4", 15, 0,
6690 	{ 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } },
6691     { "Panasonic DMC-LX5", 143, 0,
6692 	{ 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } },
6693     { "LEICA D-LUX 5", 143, 0,
6694 	{ 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } },
6695     { "Panasonic DMC-FZ100", 143, 0xfff,
6696 	{ 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } },
6697     { "LEICA V-LUX 2", 143, 0xfff,
6698 	{ 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } },
6699     { "Panasonic DMC-FZ150", 143, 0xfff,
6700 	{ 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } },
6701     { "Panasonic DMC-FX150", 15, 0xfff,
6702 	{ 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } },
6703     { "Panasonic DMC-G10", 0, 0,
6704 	{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } },
6705     { "Panasonic DMC-G1", 15, 0xf94,
6706 	{ 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } },
6707     { "Panasonic DMC-G2", 15, 0xf3c,
6708 	{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } },
6709     { "Panasonic DMC-G3", 143, 0xfff,
6710 	{ 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } },
6711     { "Panasonic DMC-GF1", 15, 0xf92,
6712 	{ 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } },
6713     { "Panasonic DMC-GF2", 143, 0xfff,
6714 	{ 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } },
6715     { "Panasonic DMC-GF3", 143, 0xfff,
6716 	{ 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } },
6717     { "Panasonic DMC-GH1", 15, 0xf92,
6718 	{ 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } },
6719     { "Panasonic DMC-GH2", 15, 0xf95,
6720 	{ 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } },
6721     { "Phase One H 20", 0, 0,		/* DJC */
6722 	{ 1313,1855,-109,-6715,15908,808,-327,1840,6020 } },
6723     { "Phase One H 25", 0, 0,
6724 	{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
6725     { "Phase One P 2", 0, 0,
6726 	{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
6727     { "Phase One P 30", 0, 0,
6728 	{ 4516,-245,-37,-7020,14976,2173,-3206,4671,7087 } },
6729     { "Phase One P 45", 0, 0,
6730 	{ 5053,-24,-117,-5684,14076,1702,-2619,4492,5849 } },
6731     { "Phase One P40", 0, 0,
6732 	{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
6733     { "Phase One P65", 0, 0,
6734 	{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
6735     { "RED ONE", 704, 0xffff,		/* DJC */
6736 	{ 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } },
6737     { "SAMSUNG EX1", 0, 0x3e00,
6738 	{ 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } },
6739     { "SAMSUNG NX1", 0, 0,
6740 	{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
6741     { "SAMSUNG WB2000", 0, 0xfff,
6742 	{ 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } },
6743     { "SAMSUNG GX-1", 0, 0,
6744 	{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
6745     { "SAMSUNG S85", 0, 0xffff,		/* DJC */
6746 	{ 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } },
6747     { "Sinar", 0, 0,			/* DJC */
6748 	{ 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } },
6749     { "SONY DSC-F828", 491, 0,
6750 	{ 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } },
6751     { "SONY DSC-R1", 512, 0,
6752 	{ 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } },
6753     { "SONY DSC-V3", 0, 0,
6754 	{ 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } },
6755     { "SONY DSLR-A100", 0, 0xfeb,
6756 	{ 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } },
6757     { "SONY DSLR-A290", 0, 0,
6758 	{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
6759     { "SONY DSLR-A2", 0, 0,
6760 	{ 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } },
6761     { "SONY DSLR-A300", 0, 0,
6762 	{ 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } },
6763     { "SONY DSLR-A330", 0, 0,
6764 	{ 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } },
6765     { "SONY DSLR-A350", 0, 0xffc,
6766 	{ 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } },
6767     { "SONY DSLR-A380", 0, 0,
6768 	{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
6769     { "SONY DSLR-A390", 0, 0,
6770 	{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
6771     { "SONY DSLR-A450", 128, 0xfeb,
6772 	{ 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } },
6773     { "SONY DSLR-A580", 128, 0xfeb,
6774 	{ 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } },
6775     { "SONY DSLR-A5", 128, 0xfeb,
6776 	{ 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } },
6777     { "SONY DSLR-A700", 126, 0,
6778 	{ 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } },
6779     { "SONY DSLR-A850", 128, 0,
6780 	{ 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } },
6781     { "SONY DSLR-A900", 128, 0,
6782 	{ 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } },
6783     { "SONY NEX-5N", 128, 0,
6784 	{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
6785     { "SONY NEX-C3", 128, 0,
6786 	{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
6787     { "SONY NEX-3", 138, 0,		/* DJC */
6788 	{ 6907,-1256,-645,-4940,12621,2320,-1710,2581,6230 } },
6789     { "SONY NEX-5", 116, 0,		/* DJC */
6790 	{ 6807,-1350,-342,-4216,11649,2567,-1089,2001,6420 } },
6791     { "SONY NEX-3", 128, 0,		/* Adobe */
6792 	{ 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } },
6793     { "SONY NEX-5", 128, 0,		/* Adobe */
6794 	{ 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } },
6795     { "SONY SLT-A33", 128, 0,
6796 	{ 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } },
6797     { "SONY SLT-A35", 128, 0,
6798 	{ 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } },
6799     { "SONY SLT-A55", 128, 0,
6800 	{ 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } },
6801     { "SONY SLT-A65", 128, 0,
6802 	{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
6803     { "SONY SLT-A77", 128, 0,
6804 	{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }
6805   };
6806   double cam_xyz[4][3];
6807   char name[130];
6808   int i, j;
6809 
6810   sprintf (name, "%s %s", make, model);
6811   for (i=0; i < sizeof table / sizeof *table; i++)
6812     if (!strncmp (name, table[i].prefix, strlen(table[i].prefix))) {
6813       if (table[i].black)   black   = (ushort) table[i].black;
6814       if (table[i].maximum) maximum = (ushort) table[i].maximum;
6815       if (table[i].trans[0]) {
6816 	for (j=0; j < 12; j++)
6817 	  cam_xyz[0][j] = table[i].trans[j] / 10000.0;
6818 	cam_xyz_coeff (cam_xyz);
6819       }
6820       break;
6821     }
6822 }
6823 
simple_coeff(int index)6824 void CLASS simple_coeff (int index)
6825 {
6826   static const float table[][12] = {
6827   /* index 0 -- all Foveon cameras */
6828   { 1.4032,-0.2231,-0.1016,-0.5263,1.4816,0.017,-0.0112,0.0183,0.9113 },
6829   /* index 1 -- Kodak DC20 and DC25 */
6830   { 2.25,0.75,-1.75,-0.25,-0.25,0.75,0.75,-0.25,-0.25,-1.75,0.75,2.25 },
6831   /* index 2 -- Logitech Fotoman Pixtura */
6832   { 1.893,-0.418,-0.476,-0.495,1.773,-0.278,-1.017,-0.655,2.672 },
6833   /* index 3 -- Nikon E880, E900, and E990 */
6834   { -1.936280,  1.800443, -1.448486,  2.584324,
6835      1.405365, -0.524955, -0.289090,  0.408680,
6836     -1.204965,  1.082304,  2.941367, -1.818705 }
6837   };
6838   int i, c;
6839 
6840   for (raw_color = i=0; i < 3; i++)
6841     FORCC rgb_cam[i][c] = table[index][i*colors+c];
6842 }
6843 
guess_byte_order(int words)6844 short CLASS guess_byte_order (int words)
6845 {
6846   uchar test[4][2];
6847   int t=2, msb;
6848   double diff, sum[2] = {0,0};
6849 
6850   fread (test[0], 2, 2, ifp);
6851   for (words-=2; words--; ) {
6852     fread (test[t], 2, 1, ifp);
6853     for (msb=0; msb < 2; msb++) {
6854       diff = (test[t^2][msb] << 8 | test[t^2][!msb])
6855 	   - (test[t  ][msb] << 8 | test[t  ][!msb]);
6856       sum[msb] += diff*diff;
6857     }
6858     t = (t+1) & 3;
6859   }
6860   return sum[0] < sum[1] ? 0x4d4d : 0x4949;
6861 }
6862 
find_green(int bps,int bite,int off0,int off1)6863 float CLASS find_green (int bps, int bite, int off0, int off1)
6864 {
6865   UINT64 bitbuf=0;
6866   int vbits, col, i, c;
6867   ushort img[2][2064];
6868   double sum[]={0,0};
6869 
6870   FORC(2) {
6871     fseek (ifp, c ? off1:off0, SEEK_SET);
6872     for (vbits=col=0; col < width; col++) {
6873       for (vbits -= bps; vbits < 0; vbits += bite) {
6874 	bitbuf <<= bite;
6875 	for (i=0; i < bite; i+=8)
6876 	  bitbuf |= (unsigned) (fgetc(ifp) << i);
6877       }
6878       img[c][col] = bitbuf << (64-bps-vbits) >> (64-bps);
6879     }
6880   }
6881   FORC(width-1) {
6882     sum[ c & 1] += ABS(img[0][c]-img[1][c+1]);
6883     sum[~c & 1] += ABS(img[1][c]-img[0][c+1]);
6884   }
6885   return 100 * log(sum[0]/sum[1]);
6886 }
6887 
6888 /*
6889    Identify which camera created this file, and set global variables
6890    accordingly.
6891  */
identify()6892 void CLASS identify()
6893 {
6894   char head[32], *cp;
6895   int hlen, flen, fsize, zero_fsize=1, i, c, is_canon;
6896   struct jhead jh;
6897   short pana[][6] = {
6898     { 3130, 1743,  4,  0, -6,  0 },
6899     { 3130, 2055,  4,  0, -6,  0 },
6900     { 3130, 2319,  4,  0, -6,  0 },
6901     { 3170, 2103, 18,  0,-42, 20 },
6902     { 3170, 2367, 18, 13,-42,-21 },
6903     { 3177, 2367,  0,  0, -1,  0 },
6904     { 3304, 2458,  0,  0, -1,  0 },
6905     { 3330, 2463,  9,  0, -5,  0 },
6906     { 3330, 2479,  9,  0,-17,  4 },
6907     { 3370, 1899, 15,  0,-44, 20 },
6908     { 3370, 2235, 15,  0,-44, 20 },
6909     { 3370, 2511, 15, 10,-44,-21 },
6910     { 3690, 2751,  3,  0, -8, -3 },
6911     { 3710, 2751,  0,  0, -3,  0 },
6912     { 3724, 2450,  0,  0,  0, -2 },
6913     { 3770, 2487, 17,  0,-44, 19 },
6914     { 3770, 2799, 17, 15,-44,-19 },
6915     { 3880, 2170,  6,  0, -6,  0 },
6916     { 4060, 3018,  0,  0,  0, -2 },
6917     { 4290, 2391,  3,  0, -8, -1 },
6918     { 4330, 2439, 17, 15,-44,-19 },
6919     { 4508, 2962,  0,  0, -3, -4 },
6920     { 4508, 3330,  0,  0, -3, -6 } };
6921   static const struct {
6922     int fsize;
6923     char make[12], model[19], withjpeg;
6924   } table[] = {
6925     {    62464, "Kodak",    "DC20"            ,0 },
6926     {   124928, "Kodak",    "DC20"            ,0 },
6927     {  1652736, "Kodak",    "DCS200"          ,0 },
6928     {  4159302, "Kodak",    "C330"            ,0 },
6929     {  4162462, "Kodak",    "C330"            ,0 },
6930     {   460800, "Kodak",    "C603v"           ,0 },
6931     {   614400, "Kodak",    "C603v"           ,0 },
6932     {  6163328, "Kodak",    "C603"            ,0 },
6933     {  6166488, "Kodak",    "C603"            ,0 },
6934     {  9116448, "Kodak",    "C603y"           ,0 },
6935     {   311696, "ST Micro", "STV680 VGA"      ,0 },  /* SPYz */
6936     {   787456, "Creative", "PC-CAM 600"      ,0 },
6937     {  1138688, "Minolta",  "RD175"           ,0 },
6938     {  3840000, "Foculus",  "531C"            ,0 },
6939     {   786432, "AVT",      "F-080C"          ,0 },
6940     {  1447680, "AVT",      "F-145C"          ,0 },
6941     {  1920000, "AVT",      "F-201C"          ,0 },
6942     {  5067304, "AVT",      "F-510C"          ,0 },
6943     {  5067316, "AVT",      "F-510C"          ,0 },
6944     { 10134608, "AVT",      "F-510C"          ,0 },
6945     { 10134620, "AVT",      "F-510C"          ,0 },
6946     { 16157136, "AVT",      "F-810C"          ,0 },
6947     {  1409024, "Sony",     "XCD-SX910CR"     ,0 },
6948     {  2818048, "Sony",     "XCD-SX910CR"     ,0 },
6949     {  3884928, "Micron",   "2010"            ,0 },
6950     {  6624000, "Pixelink", "A782"            ,0 },
6951     { 13248000, "Pixelink", "A782"            ,0 },
6952     {  6291456, "RoverShot","3320AF"          ,0 },
6953     {  6553440, "Canon",    "PowerShot A460"  ,0 },
6954     {  6653280, "Canon",    "PowerShot A530"  ,0 },
6955     {  6573120, "Canon",    "PowerShot A610"  ,0 },
6956     {  9219600, "Canon",    "PowerShot A620"  ,0 },
6957     {  9243240, "Canon",    "PowerShot A470"  ,0 },
6958     { 10341600, "Canon",    "PowerShot A720 IS",0 },
6959     { 10383120, "Canon",    "PowerShot A630"  ,0 },
6960     { 12945240, "Canon",    "PowerShot A640"  ,0 },
6961     { 15636240, "Canon",    "PowerShot A650"  ,0 },
6962     {  5298000, "Canon",    "PowerShot SD300" ,0 },
6963     {  7710960, "Canon",    "PowerShot S3 IS" ,0 },
6964     { 15467760, "Canon",    "PowerShot SX110 IS",0 },
6965     { 15534576, "Canon",    "PowerShot SX120 IS",0 },
6966     { 18653760, "Canon",    "PowerShot SX20 IS",0 },
6967     { 21936096, "Canon",    "PowerShot SX30 IS",0 },
6968     {  5939200, "OLYMPUS",  "C770UZ"          ,0 },
6969     {  1581060, "NIKON",    "E900"            ,1 },  /* or E900s,E910 */
6970     {  2465792, "NIKON",    "E950"            ,1 },  /* or E800,E700 */
6971     {  2940928, "NIKON",    "E2100"           ,1 },  /* or E2500 */
6972     {  4771840, "NIKON",    "E990"            ,1 },  /* or E995, Oly C3030Z */
6973     {  4775936, "NIKON",    "E3700"           ,1 },  /* or Optio 33WR */
6974     {  5869568, "NIKON",    "E4300"           ,1 },  /* or DiMAGE Z2 */
6975     {  5865472, "NIKON",    "E4500"           ,1 },
6976     {  7438336, "NIKON",    "E5000"           ,1 },  /* or E5700 */
6977     {  8998912, "NIKON",    "COOLPIX S6"      ,1 },
6978     {  1976352, "CASIO",    "QV-2000UX"       ,1 },
6979     {  3217760, "CASIO",    "QV-3*00EX"       ,1 },
6980     {  6218368, "CASIO",    "QV-5700"         ,1 },
6981     {  6054400, "CASIO",    "QV-R41"          ,1 },
6982     {  7530816, "CASIO",    "QV-R51"          ,1 },
6983     {  7684000, "CASIO",    "QV-4000"         ,1 },
6984     {  2937856, "CASIO",    "EX-S20"          ,1 },
6985     {  4948608, "CASIO",    "EX-S100"         ,1 },
6986     {  7542528, "CASIO",    "EX-Z50"          ,1 },
6987     {  7753344, "CASIO",    "EX-Z55"          ,1 },
6988     {  7816704, "CASIO",    "EX-Z60"          ,1 },
6989     { 10843712, "CASIO",    "EX-Z75"          ,1 },
6990     { 10834368, "CASIO",    "EX-Z750"         ,1 },
6991     { 12310144, "CASIO",    "EX-Z850"         ,1 },
6992     { 15499264, "CASIO",    "EX-Z1050"        ,1 },
6993     {  7426656, "CASIO",    "EX-P505"         ,1 },
6994     {  9313536, "CASIO",    "EX-P600"         ,1 },
6995     { 10979200, "CASIO",    "EX-P700"         ,1 },
6996     {  3178560, "PENTAX",   "Optio S"         ,1 },
6997     {  4841984, "PENTAX",   "Optio S"         ,1 },
6998     {  6114240, "PENTAX",   "Optio S4"        ,1 },  /* or S4i, CASIO EX-Z4 */
6999     { 10702848, "PENTAX",   "Optio 750Z"      ,1 },
7000     { 15980544, "AGFAPHOTO","DC-833m"         ,1 },
7001     { 16098048, "SAMSUNG",  "S85"             ,1 },
7002     { 16215552, "SAMSUNG",  "S85"             ,1 },
7003     { 20487168, "SAMSUNG",  "WB550"           ,1 },
7004     { 24000000, "SAMSUNG",  "WB550"           ,1 },
7005     { 12582980, "Sinar",    ""                ,0 },
7006     { 33292868, "Sinar",    ""                ,0 },
7007     { 44390468, "Sinar",    ""                ,0 } };
7008   static const char *corp[] =
7009     { "Canon", "NIKON", "EPSON", "KODAK", "Kodak", "OLYMPUS", "PENTAX",
7010       "MINOLTA", "Minolta", "Konica", "CASIO", "Sinar", "Phase One",
7011       "SAMSUNG", "Mamiya", "MOTOROLA" };
7012 
7013   tiff_flip = flip = filters = -1;	/* 0 is valid, so -1 is unknown */
7014   raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0;
7015   maximum = height = width = top_margin = left_margin = 0;
7016   cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0;
7017   iso_speed = shutter = aperture = focal_len = unique_id = 0;
7018   tiff_nifds = 0;
7019   memset (tiff_ifd, 0, sizeof tiff_ifd);
7020   memset (gpsdata, 0, sizeof gpsdata);
7021   memset (cblack, 0, sizeof cblack);
7022   memset (white, 0, sizeof white);
7023   thumb_offset = thumb_length = thumb_width = thumb_height = 0;
7024   load_raw = thumb_load_raw = 0;
7025   write_thumb = &CLASS jpeg_thumb;
7026   data_offset = meta_length = tiff_bps = tiff_compress = 0;
7027   kodak_cbpp = zero_after_ff = dng_version = load_flags = 0;
7028   timestamp = shot_order = tiff_samples = black = is_foveon = 0;
7029   mix_green = profile_length = data_error = zero_is_bad = 0;
7030   pixel_aspect = is_raw = raw_color = 1;
7031   tile_width = tile_length = INT_MAX;
7032   for (i=0; i < 4; i++) {
7033     cam_mul[i] = i == 1;
7034     pre_mul[i] = i < 3;
7035     FORC3 cmatrix[c][i] = 0;
7036     FORC3 rgb_cam[c][i] = c == i;
7037   }
7038   colors = 3;
7039   for (i=0; i < 0x4000; i++) curve[i] = i;
7040 
7041   order = get2();
7042   hlen = get4();
7043   fseek (ifp, 0, SEEK_SET);
7044   fread (head, 1, 32, ifp);
7045   fseek (ifp, 0, SEEK_END);
7046   flen = fsize = ftell(ifp);
7047   if ((cp = (char *) memmem (head, 32, "MMMM", 4)) ||
7048       (cp = (char *) memmem (head, 32, "IIII", 4))) {
7049     parse_phase_one (cp-head);
7050     if (cp-head && parse_tiff(0)) apply_tiff();
7051   } else if (order == 0x4949 || order == 0x4d4d) {
7052     if (!memcmp (head+6,"HEAPCCDR",8)) {
7053       data_offset = hlen;
7054       parse_ciff (hlen, flen - hlen);
7055     } else if (parse_tiff(0)) apply_tiff();
7056   } else if (!memcmp (head,"\xff\xd8\xff\xe1",4) &&
7057 	     !memcmp (head+6,"Exif",4)) {
7058     fseek (ifp, 4, SEEK_SET);
7059     data_offset = 4 + get2();
7060     fseek (ifp, data_offset, SEEK_SET);
7061     if (fgetc(ifp) != 0xff)
7062       parse_tiff(12);
7063     thumb_offset = 0;
7064   } else if (!memcmp (head+25,"ARECOYK",7)) {
7065     strcpy (make, "Contax");
7066     strcpy (model,"N Digital");
7067     fseek (ifp, 33, SEEK_SET);
7068     get_timestamp(1);
7069     fseek (ifp, 60, SEEK_SET);
7070     FORC4 cam_mul[c ^ (c >> 1)] = get4();
7071   } else if (!strcmp (head, "PXN")) {
7072     strcpy (make, "Logitech");
7073     strcpy (model,"Fotoman Pixtura");
7074   } else if (!strcmp (head, "qktk")) {
7075     strcpy (make, "Apple");
7076     strcpy (model,"QuickTake 100");
7077     load_raw = &CLASS quicktake_100_load_raw;
7078   } else if (!strcmp (head, "qktn")) {
7079     strcpy (make, "Apple");
7080     strcpy (model,"QuickTake 150");
7081     load_raw = &CLASS kodak_radc_load_raw;
7082   } else if (!memcmp (head,"FUJIFILM",8)) {
7083     fseek (ifp, 84, SEEK_SET);
7084     thumb_offset = get4();
7085     thumb_length = get4();
7086     fseek (ifp, 92, SEEK_SET);
7087     parse_fuji (get4());
7088     if (thumb_offset > 120) {
7089       fseek (ifp, 120, SEEK_SET);
7090       is_raw += (i = get4()) && 1;
7091       if (is_raw == 2 && shot_select)
7092 	parse_fuji (i);
7093     }
7094     fseek (ifp, 100+28*(shot_select > 0), SEEK_SET);
7095     parse_tiff (data_offset = get4());
7096     parse_tiff (thumb_offset+12);
7097     apply_tiff();
7098   } else if (!memcmp (head,"RIFF",4)) {
7099     fseek (ifp, 0, SEEK_SET);
7100     parse_riff();
7101   } else if (!memcmp (head,"\0\001\0\001\0@",6)) {
7102     fseek (ifp, 6, SEEK_SET);
7103     fread (make, 1, 8, ifp);
7104     fread (model, 1, 8, ifp);
7105     fread (model2, 1, 16, ifp);
7106     data_offset = get2();
7107     get2();
7108     raw_width = get2();
7109     raw_height = get2();
7110     load_raw = &CLASS nokia_load_raw;
7111     filters = 0x61616161;
7112   } else if (!memcmp (head,"NOKIARAW",8)) {
7113     strcpy (make, "NOKIA");
7114     strcpy (model, "X2");
7115     order = 0x4949;
7116     fseek (ifp, 300, SEEK_SET);
7117     data_offset = get4();
7118     i = get4();
7119     width = get2();
7120     height = get2();
7121     data_offset += i - width * 5 / 4 * height;
7122     load_raw = &CLASS nokia_load_raw;
7123     filters = 0x61616161;
7124   } else if (!memcmp (head,"ARRI",4)) {
7125     order = 0x4949;
7126     fseek (ifp, 20, SEEK_SET);
7127     width = get4();
7128     height = get4();
7129     strcpy (make, "ARRI");
7130     fseek (ifp, 668, SEEK_SET);
7131     fread (model, 1, 64, ifp);
7132     data_offset = 4096;
7133     load_raw = &CLASS packed_load_raw;
7134     load_flags = 88;
7135     filters = 0x61616161;
7136   } else if (!memcmp (head+4,"RED1",4)) {
7137     strcpy (make, "RED");
7138     strcpy (model,"ONE");
7139     parse_redcine();
7140     load_raw = &CLASS redcine_load_raw;
7141     gamma_curve (1/2.4, 12.92, 1, 4095);
7142     filters = 0x49494949;
7143   } else if (!memcmp (head,"DSC-Image",9))
7144     parse_rollei();
7145   else if (!memcmp (head,"PWAD",4))
7146     parse_sinar_ia();
7147   else if (!memcmp (head,"\0MRM",4))
7148     parse_minolta(0);
7149   else if (!memcmp (head,"FOVb",4))
7150     parse_foveon();
7151   else if (!memcmp (head,"CI",2))
7152     parse_cine();
7153   else
7154     for (zero_fsize=i=0; i < sizeof table / sizeof *table; i++)
7155       if (fsize == table[i].fsize) {
7156 	strcpy (make,  table[i].make );
7157 	strcpy (model, table[i].model);
7158 	if (table[i].withjpeg)
7159 	  parse_external_jpeg();
7160       }
7161   if (zero_fsize) fsize = 0;
7162   if (make[0] == 0) parse_smal (0, flen);
7163   if (make[0] == 0) parse_jpeg (is_raw = 0);
7164 
7165   for (i=0; i < sizeof corp / sizeof *corp; i++)
7166     if (strstr (make, corp[i]))		/* Simplify company names */
7167 	strcpy (make, corp[i]);
7168   if (!strncmp (make,"KODAK",5) &&
7169 	((cp = strstr(model," DIGITAL CAMERA")) ||
7170 	 (cp = strstr(model," Digital Camera")) ||
7171 	 (cp = strstr(model,"FILE VERSION"))))
7172      *cp = 0;
7173   cp = make + strlen(make);		/* Remove trailing spaces */
7174   while (*--cp == ' ') *cp = 0;
7175   cp = model + strlen(model);
7176   while (*--cp == ' ') *cp = 0;
7177   i = strlen(make);			/* Remove make from model */
7178   if (!strncasecmp (model, make, i) && model[i++] == ' ')
7179     memmove (model, model+i, 64-i);
7180   if (!strncmp (model,"Digital Camera ",15))
7181     strcpy (model, model+15);
7182   desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0;
7183   if (!is_raw) goto notraw;
7184 
7185   if (!height) height = raw_height;
7186   if (!width)  width  = raw_width;
7187   if (fuji_width) {
7188     fuji_width = (raw_width+1)/2;
7189     width = height + fuji_width;
7190     height = width - 1;
7191     pixel_aspect = 1;
7192   }
7193   if (height == 2624 && width == 3936)	/* Pentax K10D and Samsung GX10 */
7194     { height  = 2616;   width  = 3896; }
7195   if (height == 3136 && width == 4864)  /* Pentax K20D and Samsung GX20 */
7196     { height  = 3124;   width  = 4688; filters = 0x16161616; }
7197   if (width == 4352 && (!strcmp(model,"K-r") || !strcmp(model,"K-x")))
7198     {			width  = 4309; filters = 0x16161616; }
7199   if (width >= 4960 && !strcmp(model,"K-5"))
7200     { left_margin = 10; width  = 4950; filters = 0x16161616; }
7201   if (width == 4736 && !strcmp(model,"K-7"))
7202     { height  = 3122;   width  = 4684; filters = 0x16161616; top_margin = 2; }
7203   if (width == 7424 && !strcmp(model,"645D"))
7204     { height  = 5502;   width  = 7328; filters = 0x61616161; top_margin = 29;
7205       left_margin = 48; }
7206   if (height == 3014 && width == 4096)	/* Ricoh GX200 */
7207 			width  = 4014;
7208   if (dng_version) {
7209     if (filters == UINT_MAX) filters = 0;
7210     if (filters) is_raw = tiff_samples;
7211     else	 colors = tiff_samples;
7212     if (tiff_compress == 1)
7213       load_raw = &CLASS adobe_dng_load_raw_nc;
7214     if (tiff_compress == 7)
7215       load_raw = &CLASS adobe_dng_load_raw_lj;
7216     goto dng_skip;
7217   }
7218   if ((is_canon = !strcmp(make,"Canon")))
7219     load_raw = memcmp (head+6,"HEAPCCDR",8) ?
7220 	&CLASS lossless_jpeg_load_raw : &CLASS canon_compressed_load_raw;
7221   if (!strcmp(make,"NIKON")) {
7222     if (!load_raw)
7223       load_raw = &CLASS packed_load_raw;
7224     if (model[0] == 'E')
7225       load_flags |= !data_offset << 2 | 2;
7226   }
7227   if (!strcmp(make,"CASIO")) {
7228     load_raw = &CLASS packed_load_raw;
7229     maximum = 0xf7f;
7230   }
7231 
7232 /* Set parameters based on camera name (for non-DNG files). */
7233 
7234   if (is_foveon) {
7235     if (height*2 < width) pixel_aspect = 0.5;
7236     if (height   > width) pixel_aspect = 2;
7237     filters = 0;
7238     load_raw = &CLASS foveon_load_raw;
7239     simple_coeff(0);
7240   } else if (is_canon && tiff_bps == 15) {
7241     switch (width) {
7242       case 3344: width -= 66;
7243       case 3872: width -= 6;
7244     }
7245     filters = 0;
7246     load_raw = &CLASS canon_sraw_load_raw;
7247   } else if (!strcmp(model,"PowerShot 600")) {
7248     height = 613;
7249     width  = 854;
7250     raw_width = 896;
7251     pixel_aspect = 607/628.0;
7252     colors = 4;
7253     filters = 0xe1e4e1e4;
7254     load_raw = &CLASS canon_600_load_raw;
7255   } else if (!strcmp(model,"PowerShot A5") ||
7256 	     !strcmp(model,"PowerShot A5 Zoom")) {
7257     height = 773;
7258     width  = 960;
7259     raw_width = 992;
7260     pixel_aspect = 256/235.0;
7261     colors = 4;
7262     filters = 0x1e4e1e4e;
7263     goto canon_a5;
7264   } else if (!strcmp(model,"PowerShot A50")) {
7265     height =  968;
7266     width  = 1290;
7267     raw_width = 1320;
7268     colors = 4;
7269     filters = 0x1b4e4b1e;
7270     goto canon_a5;
7271   } else if (!strcmp(model,"PowerShot Pro70")) {
7272     height = 1024;
7273     width  = 1552;
7274     colors = 4;
7275     filters = 0x1e4b4e1b;
7276     goto canon_a5;
7277   } else if (!strcmp(model,"PowerShot SD300")) {
7278     height = 1752;
7279     width  = 2344;
7280     raw_height = 1766;
7281     raw_width  = 2400;
7282     top_margin  = 12;
7283     left_margin = 12;
7284     goto canon_a5;
7285   } else if (!strcmp(model,"PowerShot A460")) {
7286     height = 1960;
7287     width  = 2616;
7288     raw_height = 1968;
7289     raw_width  = 2664;
7290     top_margin  = 4;
7291     left_margin = 4;
7292     goto canon_a5;
7293   } else if (!strcmp(model,"PowerShot A530")) {
7294     height = 1984;
7295     width  = 2620;
7296     raw_height = 1992;
7297     raw_width  = 2672;
7298     top_margin  = 6;
7299     left_margin = 10;
7300     goto canon_a5;
7301   } else if (!strcmp(model,"PowerShot A610")) {
7302     if (canon_s2is()) strcpy (model+10, "S2 IS");
7303     height = 1960;
7304     width  = 2616;
7305     raw_height = 1968;
7306     raw_width  = 2672;
7307     top_margin  = 8;
7308     left_margin = 12;
7309     goto canon_a5;
7310   } else if (!strcmp(model,"PowerShot A620")) {
7311     height = 2328;
7312     width  = 3112;
7313     raw_height = 2340;
7314     raw_width  = 3152;
7315     top_margin  = 12;
7316     left_margin = 36;
7317     goto canon_a5;
7318   } else if (!strcmp(model,"PowerShot A470")) {
7319     height = 2328;
7320     width  = 3096;
7321     raw_height = 2346;
7322     raw_width  = 3152;
7323     top_margin  = 6;
7324     left_margin = 12;
7325     goto canon_a5;
7326   } else if (!strcmp(model,"PowerShot A720 IS")) {
7327     height = 2472;
7328     width  = 3298;
7329     raw_height = 2480;
7330     raw_width  = 3336;
7331     top_margin  = 5;
7332     left_margin = 6;
7333     goto canon_a5;
7334   } else if (!strcmp(model,"PowerShot A630")) {
7335     height = 2472;
7336     width  = 3288;
7337     raw_height = 2484;
7338     raw_width  = 3344;
7339     top_margin  = 6;
7340     left_margin = 12;
7341     goto canon_a5;
7342   } else if (!strcmp(model,"PowerShot A640")) {
7343     height = 2760;
7344     width  = 3672;
7345     raw_height = 2772;
7346     raw_width  = 3736;
7347     top_margin  = 6;
7348     left_margin = 12;
7349     goto canon_a5;
7350   } else if (!strcmp(model,"PowerShot A650")) {
7351     height = 3024;
7352     width  = 4032;
7353     raw_height = 3048;
7354     raw_width  = 4104;
7355     top_margin  = 12;
7356     left_margin = 48;
7357     goto canon_a5;
7358   } else if (!strcmp(model,"PowerShot S3 IS")) {
7359     height = 2128;
7360     width  = 2840;
7361     raw_height = 2136;
7362     raw_width  = 2888;
7363     top_margin  = 8;
7364     left_margin = 44;
7365 canon_a5:
7366     tiff_bps = 10;
7367     load_raw = &CLASS packed_load_raw;
7368     load_flags = 40;
7369     if (raw_width > 1600) zero_is_bad = 1;
7370   } else if (!strcmp(model,"PowerShot SX110 IS")) {
7371     height = 2760;
7372     width  = 3684;
7373     raw_height = 2772;
7374     raw_width  = 3720;
7375     top_margin  = 12;
7376     left_margin = 6;
7377     load_raw = &CLASS packed_load_raw;
7378     load_flags = 40;
7379     zero_is_bad = 1;
7380   } else if (!strcmp(model,"PowerShot SX120 IS")) {
7381     height = 2742;
7382     width  = 3664;
7383     raw_height = 2778;
7384     raw_width  = 3728;
7385     top_margin  = 18;
7386     left_margin = 16;
7387     filters = 0x49494949;
7388     load_raw = &CLASS packed_load_raw;
7389     load_flags = 40;
7390     zero_is_bad = 1;
7391   } else if (!strcmp(model,"PowerShot SX20 IS")) {
7392     height = 3024;
7393     width  = 4032;
7394     raw_height = 3048;
7395     raw_width  = 4080;
7396     top_margin  = 12;
7397     left_margin = 24;
7398     load_raw = &CLASS packed_load_raw;
7399     load_flags = 40;
7400     zero_is_bad = 1;
7401   } else if (!strcmp(model,"PowerShot SX30 IS")) {
7402     height = 3254;
7403     width  = 4366;
7404     raw_height = 3276;
7405     raw_width  = 4464;
7406     top_margin  = 10;
7407     left_margin = 25;
7408     filters = 0x16161616;
7409     load_raw = &CLASS packed_load_raw;
7410     load_flags = 40;
7411     zero_is_bad = 1;
7412   } else if (!strcmp(model,"PowerShot Pro90 IS")) {
7413     width  = 1896;
7414     colors = 4;
7415     filters = 0xb4b4b4b4;
7416   } else if (is_canon && raw_width == 2144) {
7417     height = 1550;
7418     width  = 2088;
7419     top_margin  = 8;
7420     left_margin = 4;
7421     if (!strcmp(model,"PowerShot G1")) {
7422       colors = 4;
7423       filters = 0xb4b4b4b4;
7424     }
7425   } else if (is_canon && raw_width == 2224) {
7426     height = 1448;
7427     width  = 2176;
7428     top_margin  = 6;
7429     left_margin = 48;
7430   } else if (is_canon && raw_width == 2376) {
7431     height = 1720;
7432     width  = 2312;
7433     top_margin  = 6;
7434     left_margin = 12;
7435   } else if (is_canon && raw_width == 2672) {
7436     height = 1960;
7437     width  = 2616;
7438     top_margin  = 6;
7439     left_margin = 12;
7440   } else if (is_canon && raw_width == 3152) {
7441     height = 2056;
7442     width  = 3088;
7443     top_margin  = 12;
7444     left_margin = 64;
7445     if (unique_id == 0x80000170)
7446       adobe_coeff ("Canon","EOS 300D");
7447   } else if (is_canon && raw_width == 3160) {
7448     height = 2328;
7449     width  = 3112;
7450     top_margin  = 12;
7451     left_margin = 44;
7452   } else if (is_canon && raw_width == 3344) {
7453     height = 2472;
7454     width  = 3288;
7455     top_margin  = 6;
7456     left_margin = 4;
7457   } else if (!strcmp(model,"EOS D2000C")) {
7458     filters = 0x61616161;
7459     black = curve[200];
7460   } else if (is_canon && raw_width == 3516) {
7461     top_margin  = 14;
7462     left_margin = 42;
7463     if (unique_id == 0x80000189)
7464       adobe_coeff ("Canon","EOS 350D");
7465     goto canon_cr2;
7466   } else if (is_canon && raw_width == 3596) {
7467     top_margin  = 12;
7468     left_margin = 74;
7469     goto canon_cr2;
7470   } else if (is_canon && raw_width == 3744) {
7471     height = 2760;
7472     width  = 3684;
7473     top_margin  = 16;
7474     left_margin = 8;
7475     if (unique_id > 0x2720000) {
7476       top_margin  = 12;
7477       left_margin = 52;
7478     }
7479   } else if (is_canon && raw_width == 3944) {
7480     height = 2602;
7481     width  = 3908;
7482     top_margin  = 18;
7483     left_margin = 30;
7484   } else if (is_canon && raw_width == 3948) {
7485     top_margin  = 18;
7486     left_margin = 42;
7487     height -= 2;
7488     if (unique_id == 0x80000236)
7489       adobe_coeff ("Canon","EOS 400D");
7490     if (unique_id == 0x80000254)
7491       adobe_coeff ("Canon","EOS 1000D");
7492     goto canon_cr2;
7493   } else if (is_canon && raw_width == 3984) {
7494     top_margin  = 20;
7495     left_margin = 76;
7496     height -= 2;
7497     goto canon_cr2;
7498   } else if (is_canon && raw_width == 4104) {
7499     height = 3024;
7500     width  = 4032;
7501     top_margin  = 12;
7502     left_margin = 48;
7503   } else if (is_canon && raw_width == 4152) {
7504     top_margin  = 12;
7505     left_margin = 192;
7506     goto canon_cr2;
7507   } else if (is_canon && raw_width == 4312) {
7508     top_margin  = 18;
7509     left_margin = 22;
7510     height -= 2;
7511     if (unique_id == 0x80000176)
7512       adobe_coeff ("Canon","EOS 450D");
7513     goto canon_cr2;
7514   } else if (is_canon && raw_width == 4352) {
7515     top_margin  = 18;
7516     left_margin = 62;
7517     if (unique_id == 0x80000288)
7518       adobe_coeff ("Canon","EOS 1100D");
7519     goto canon_cr2;
7520   } else if (is_canon && raw_width == 4476) {
7521     top_margin  = 34;
7522     left_margin = 90;
7523     goto canon_cr2;
7524   } else if (is_canon && raw_width == 4480) {
7525     height = 3326;
7526     width  = 4432;
7527     top_margin  = 10;
7528     left_margin = 12;
7529     filters = 0x49494949;
7530   } else if (is_canon && raw_width == 4832) {
7531     top_margin = unique_id == 0x80000261 ? 51:26;
7532     left_margin = 62;
7533     if (unique_id == 0x80000252)
7534       adobe_coeff ("Canon","EOS 500D");
7535     goto canon_cr2;
7536   } else if (is_canon && raw_width == 5120) {
7537     height -= top_margin = 45;
7538     left_margin = 142;
7539     width = 4916;
7540   } else if (is_canon && raw_width == 5344) {
7541     top_margin = 51;
7542     left_margin = 142;
7543     if (unique_id == 0x80000270)
7544       adobe_coeff ("Canon","EOS 550D");
7545     if (unique_id == 0x80000286)
7546       adobe_coeff ("Canon","EOS 600D");
7547     goto canon_cr2;
7548   } else if (is_canon && raw_width == 5360) {
7549     top_margin = 51;
7550     left_margin = 158;
7551     goto canon_cr2;
7552   } else if (is_canon && raw_width == 5792) {
7553     top_margin  = 51;
7554     left_margin = 158;
7555     goto canon_cr2;
7556   } else if (is_canon && raw_width == 5108) {
7557     top_margin  = 13;
7558     left_margin = 98;
7559 canon_cr2:
7560     height -= top_margin;
7561     width  -= left_margin;
7562   } else if (is_canon && raw_width == 5712) {
7563     height = 3752;
7564     width  = 5640;
7565     top_margin  = 20;
7566     left_margin = 62;
7567   } else if (!strcmp(model,"D1")) {
7568     cam_mul[0] *= 256/527.0;
7569     cam_mul[2] *= 256/317.0;
7570   } else if (!strcmp(model,"D1X")) {
7571     width -= 4;
7572     pixel_aspect = 0.5;
7573   } else if (!strcmp(model,"D40X") ||
7574 	     !strcmp(model,"D60")  ||
7575 	     !strcmp(model,"D80")  ||
7576 	     !strcmp(model,"D3000")) {
7577     height -= 3;
7578     width  -= 4;
7579   } else if (!strcmp(model,"D3")   ||
7580 	     !strcmp(model,"D3S")  ||
7581 	     !strcmp(model,"D700")) {
7582     width -= 4;
7583     left_margin = 2;
7584   } else if (!strcmp(model,"D5000")) {
7585     width -= 42;
7586   } else if (!strcmp(model,"D5100") ||
7587 	     !strcmp(model,"D7000")) {
7588     width -= 44;
7589   } else if (!strcmp(model,"D3100")) {
7590     width -= 28;
7591     left_margin = 6;
7592   } else if (!strncmp(model,"D40",3) ||
7593 	     !strncmp(model,"D50",3) ||
7594 	     !strncmp(model,"D70",3)) {
7595     width--;
7596   } else if (!strcmp(model,"D90")) {
7597     width -= 42;
7598   } else if (!strcmp(model,"D100")) {
7599     if (tiff_compress == 34713 && !nikon_is_compressed()) {
7600       load_raw = &CLASS packed_load_raw;
7601       load_flags |= 1;
7602       raw_width = (width += 3) + 3;
7603     }
7604   } else if (!strcmp(model,"D200")) {
7605     left_margin = 1;
7606     width -= 4;
7607     filters = 0x94949494;
7608   } else if (!strncmp(model,"D2H",3)) {
7609     left_margin = 6;
7610     width -= 14;
7611   } else if (!strncmp(model,"D2X",3)) {
7612     if (width == 3264) width -= 32;
7613     else width -= 8;
7614   } else if (!strncmp(model,"D300",4)) {
7615     width -= 32;
7616   } else if (!strncmp(model,"COOLPIX P",9)) {
7617     load_flags = 24;
7618     filters = 0x94949494;
7619     if (model[9] == '7' && iso_speed >= 400)
7620       black = 255;
7621   } else if (fsize == 1581060) {
7622     height = 963;
7623     width = 1287;
7624     raw_width = 1632;
7625     maximum = 0x3f4;
7626     colors = 4;
7627     filters = 0x1e1e1e1e;
7628     simple_coeff(3);
7629     pre_mul[0] = 1.2085;
7630     pre_mul[1] = 1.0943;
7631     pre_mul[3] = 1.1103;
7632     goto e900;
7633   } else if (fsize == 2465792) {
7634     height = 1203;
7635     width  = 1616;
7636     raw_width = 2048;
7637     colors = 4;
7638     filters = 0x4b4b4b4b;
7639     adobe_coeff ("NIKON","E950");
7640 e900:
7641     tiff_bps = 10;
7642     load_raw = &CLASS packed_load_raw;
7643     load_flags = 6;
7644   } else if (fsize == 4771840) {
7645     height = 1540;
7646     width  = 2064;
7647     colors = 4;
7648     filters = 0xe1e1e1e1;
7649     load_raw = &CLASS packed_load_raw;
7650     load_flags = 6;
7651     if (!timestamp && nikon_e995())
7652       strcpy (model, "E995");
7653     if (strcmp(model,"E995")) {
7654       filters = 0xb4b4b4b4;
7655       simple_coeff(3);
7656       pre_mul[0] = 1.196;
7657       pre_mul[1] = 1.246;
7658       pre_mul[2] = 1.018;
7659     }
7660   } else if (!strcmp(model,"E2100")) {
7661     if (!timestamp && !nikon_e2100()) goto cp_e2500;
7662     height = 1206;
7663     width  = 1616;
7664     load_flags = 30;
7665   } else if (!strcmp(model,"E2500")) {
7666 cp_e2500:
7667     strcpy (model, "E2500");
7668     height = 1204;
7669     width  = 1616;
7670     colors = 4;
7671     filters = 0x4b4b4b4b;
7672   } else if (fsize == 4775936) {
7673     height = 1542;
7674     width  = 2064;
7675     load_raw = &CLASS packed_load_raw;
7676     load_flags = 30;
7677     if (!timestamp) nikon_3700();
7678     if (model[0] == 'E' && atoi(model+1) < 3700)
7679       filters = 0x49494949;
7680     if (!strcmp(model,"Optio 33WR")) {
7681       flip = 1;
7682       filters = 0x16161616;
7683     }
7684     if (make[0] == 'O') {
7685       i = find_green (12, 32, 1188864, 3576832);
7686       c = find_green (12, 32, 2383920, 2387016);
7687       if (abs(i) < abs(c)) {
7688 	SWAP(i,c);
7689 	load_flags = 24;
7690       }
7691       if (i < 0) filters = 0x61616161;
7692     }
7693   } else if (fsize == 5869568) {
7694     height = 1710;
7695     width  = 2288;
7696     filters = 0x16161616;
7697     if (!timestamp && minolta_z2()) {
7698       strcpy (make, "Minolta");
7699       strcpy (model,"DiMAGE Z2");
7700     }
7701     load_raw = &CLASS packed_load_raw;
7702     load_flags = 6 + 24*(make[0] == 'M');
7703   } else if (!strcmp(model,"E4500")) {
7704     height = 1708;
7705     width  = 2288;
7706     colors = 4;
7707     filters = 0xb4b4b4b4;
7708   } else if (fsize == 7438336) {
7709     height = 1924;
7710     width  = 2576;
7711     colors = 4;
7712     filters = 0xb4b4b4b4;
7713   } else if (fsize == 8998912) {
7714     height = 2118;
7715     width  = 2832;
7716     maximum = 0xf83;
7717     load_raw = &CLASS packed_load_raw;
7718     load_flags = 30;
7719   } else if (!strcmp(make,"FUJIFILM")) {
7720     if (!strcmp(model+7,"S2Pro")) {
7721       strcpy (model+7," S2Pro");
7722       height = 2144;
7723       width  = 2880;
7724       flip = 6;
7725     } else if (load_raw != &CLASS packed_load_raw)
7726       maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00;
7727     top_margin = (raw_height - height) >> 2 << 1;
7728     left_margin = (raw_width - width ) >> 2 << 1;
7729     if (width == 3328) {
7730       width = 3262;
7731       left_margin = 34;
7732     }
7733     if (fuji_layout) raw_width *= is_raw;
7734     if (load_raw == &CLASS fuji_load_raw) {
7735       fuji_width = width >> !fuji_layout;
7736       width = (height >> fuji_layout) + fuji_width;
7737       raw_height = height;
7738       height = width - 1;
7739       if (~fuji_width & 1) filters = 0x49494949;
7740     }
7741   } else if (!strcmp(model,"RD175")) {
7742     height = 986;
7743     width = 1534;
7744     data_offset = 513;
7745     filters = 0x61616161;
7746     load_raw = &CLASS minolta_rd175_load_raw;
7747   } else if (!strcmp(model,"KD-400Z")) {
7748     height = 1712;
7749     width  = 2312;
7750     raw_width = 2336;
7751     goto konica_400z;
7752   } else if (!strcmp(model,"KD-510Z")) {
7753     goto konica_510z;
7754   } else if (!strcasecmp(make,"MINOLTA")) {
7755     load_raw = &CLASS unpacked_load_raw;
7756     maximum = 0xfff;
7757     if (!strncmp(model,"DiMAGE A",8)) {
7758       if (!strcmp(model,"DiMAGE A200"))
7759 	filters = 0x49494949;
7760       tiff_bps = 12;
7761       load_raw = &CLASS packed_load_raw;
7762     } else if (!strncmp(model,"ALPHA",5) ||
7763 	       !strncmp(model,"DYNAX",5) ||
7764 	       !strncmp(model,"MAXXUM",6)) {
7765       sprintf (model+20, "DYNAX %-10s", model+6+(model[0]=='M'));
7766       adobe_coeff (make, model+20);
7767       load_raw = &CLASS packed_load_raw;
7768     } else if (!strncmp(model,"DiMAGE G",8)) {
7769       if (model[8] == '4') {
7770 	height = 1716;
7771 	width  = 2304;
7772       } else if (model[8] == '5') {
7773 konica_510z:
7774 	height = 1956;
7775 	width  = 2607;
7776 	raw_width = 2624;
7777       } else if (model[8] == '6') {
7778 	height = 2136;
7779 	width  = 2848;
7780       }
7781       data_offset += 14;
7782       filters = 0x61616161;
7783 konica_400z:
7784       load_raw = &CLASS unpacked_load_raw;
7785       maximum = 0x3df;
7786       order = 0x4d4d;
7787     }
7788   } else if (!strcmp(model,"*ist D")) {
7789     data_error = -1;
7790   } else if (!strcmp(model,"*ist DS")) {
7791     height -= 2;
7792   } else if (!strcmp(model,"Optio S")) {
7793     if (fsize == 3178560) {
7794       height = 1540;
7795       width  = 2064;
7796       load_raw = &CLASS eight_bit_load_raw;
7797       cam_mul[0] *= 4;
7798       cam_mul[2] *= 4;
7799     } else {
7800       height = 1544;
7801       width  = 2068;
7802       raw_width = 3136;
7803       load_raw = &CLASS packed_load_raw;
7804       maximum = 0xf7c;
7805     }
7806   } else if (fsize == 6114240) {
7807     height = 1737;
7808     width  = 2324;
7809     raw_width = 3520;
7810     load_raw = &CLASS packed_load_raw;
7811     maximum = 0xf7a;
7812   } else if (!strcmp(model,"Optio 750Z")) {
7813     height = 2302;
7814     width  = 3072;
7815     load_raw = &CLASS packed_load_raw;
7816     load_flags = 30;
7817   } else if (!strcmp(model,"DC-833m")) {
7818     height = 2448;
7819     width  = 3264;
7820     order = 0x4949;
7821     filters = 0x61616161;
7822     load_raw = &CLASS unpacked_load_raw;
7823     maximum = 0xfc00;
7824   } else if (!strncmp(model,"S85",3)) {
7825     height = 2448;
7826     width  = 3264;
7827     raw_width = fsize/height/2;
7828     order = 0x4d4d;
7829     load_raw = &CLASS unpacked_load_raw;
7830   } else if (!strncmp(model,"NX1",3)) {
7831     height -= top_margin = 8;
7832     width -= 2 * (left_margin = 8);
7833     load_flags = 32;
7834   } else if (!strcmp(model,"EX1")) {
7835     order = 0x4949;
7836     height -= 20;
7837     top_margin = 2;
7838     if ((width -= 6) > 3682) {
7839       height -= 10;
7840       width  -= 46;
7841       top_margin = 8;
7842     }
7843   } else if (!strcmp(model,"WB2000")) {
7844     order = 0x4949;
7845     height -= 3;
7846     top_margin = 2;
7847     if ((width -= 10) > 3718) {
7848       height -= 28;
7849       width  -= 56;
7850       top_margin = 8;
7851     }
7852   } else if (fsize == 20487168) {
7853     height = 2808;
7854     width  = 3648;
7855     goto wb550;
7856   } else if (fsize == 24000000) {
7857     height = 3000;
7858     width  = 4000;
7859 wb550:
7860     strcpy (model, "WB550");
7861     order = 0x4d4d;
7862     load_raw = &CLASS unpacked_load_raw;
7863     load_flags = 6;
7864     maximum = 0x3df;
7865   } else if (!strcmp(model,"STV680 VGA")) {
7866     height = 484;
7867     width  = 644;
7868     load_raw = &CLASS eight_bit_load_raw;
7869     flip = 2;
7870     filters = 0x16161616;
7871     black = 16;
7872   } else if (!strcmp(model,"N95")) {
7873     height = raw_height - (top_margin = 2);
7874   } else if (!strcmp(model,"531C")) {
7875     height = 1200;
7876     width  = 1600;
7877     load_raw = &CLASS unpacked_load_raw;
7878     filters = 0x49494949;
7879   } else if (!strcmp(model,"F-080C")) {
7880     height = 768;
7881     width  = 1024;
7882     load_raw = &CLASS eight_bit_load_raw;
7883   } else if (!strcmp(model,"F-145C")) {
7884     height = 1040;
7885     width  = 1392;
7886     load_raw = &CLASS eight_bit_load_raw;
7887   } else if (!strcmp(model,"F-201C")) {
7888     height = 1200;
7889     width  = 1600;
7890     load_raw = &CLASS eight_bit_load_raw;
7891   } else if (!strcmp(model,"F-510C")) {
7892     height = 1958;
7893     width  = 2588;
7894     load_raw = fsize < 7500000 ?
7895 	&CLASS eight_bit_load_raw : &CLASS unpacked_load_raw;
7896     data_offset = fsize - width*height*(fsize >> 22);
7897     maximum = 0xfff0;
7898   } else if (!strcmp(model,"F-810C")) {
7899     height = 2469;
7900     width  = 3272;
7901     load_raw = &CLASS unpacked_load_raw;
7902     maximum = 0xfff0;
7903   } else if (!strcmp(model,"XCD-SX910CR")) {
7904     height = 1024;
7905     width  = 1375;
7906     raw_width = 1376;
7907     filters = 0x49494949;
7908     maximum = 0x3ff;
7909     load_raw = fsize < 2000000 ?
7910 	&CLASS eight_bit_load_raw : &CLASS unpacked_load_raw;
7911   } else if (!strcmp(model,"2010")) {
7912     height = 1207;
7913     width  = 1608;
7914     order = 0x4949;
7915     filters = 0x16161616;
7916     data_offset = 3212;
7917     maximum = 0x3ff;
7918     load_raw = &CLASS unpacked_load_raw;
7919   } else if (!strcmp(model,"A782")) {
7920     height = 3000;
7921     width  = 2208;
7922     filters = 0x61616161;
7923     load_raw = fsize < 10000000 ?
7924 	&CLASS eight_bit_load_raw : &CLASS unpacked_load_raw;
7925     maximum = 0xffc0;
7926   } else if (!strcmp(model,"3320AF")) {
7927     height = 1536;
7928     raw_width = width = 2048;
7929     filters = 0x61616161;
7930     load_raw = &CLASS unpacked_load_raw;
7931     maximum = 0x3ff;
7932     fseek (ifp, 0x300000, SEEK_SET);
7933     if ((order = guess_byte_order(0x10000)) == 0x4d4d) {
7934       height -= (top_margin = 16);
7935       width -= (left_margin = 28);
7936       maximum = 0xf5c0;
7937       strcpy (make, "ISG");
7938       model[0] = 0;
7939     }
7940   } else if (!strcmp(make,"Hasselblad")) {
7941     if (load_raw == &CLASS lossless_jpeg_load_raw)
7942       load_raw = &CLASS hasselblad_load_raw;
7943     if (raw_width == 7262) {
7944       height = 5444;
7945       width  = 7248;
7946       top_margin  = 4;
7947       left_margin = 7;
7948       filters = 0x61616161;
7949     } else if (raw_width == 7410) {
7950       height = 5502;
7951       width  = 7328;
7952       top_margin  = 4;
7953       left_margin = 41;
7954       filters = 0x61616161;
7955     } else if (raw_width == 9044) {
7956       height = 6716;
7957       width  = 8964;
7958       top_margin  = 8;
7959       left_margin = 40;
7960       black += load_flags = 256;
7961       maximum = 0x8101;
7962     } else if (raw_width == 4090) {
7963       strcpy (model, "V96C");
7964       height -= (top_margin = 6);
7965       width -= (left_margin = 3) + 7;
7966       filters = 0x61616161;
7967     }
7968   } else if (!strcmp(make,"Sinar")) {
7969     if (!memcmp(head,"8BPS",4)) {
7970       fseek (ifp, 14, SEEK_SET);
7971       height = get4();
7972       width  = get4();
7973       filters = 0x61616161;
7974       data_offset = 68;
7975     }
7976     if (!load_raw) load_raw = &CLASS unpacked_load_raw;
7977     maximum = 0x3fff;
7978   } else if (!strcmp(make,"Leaf")) {
7979     maximum = 0x3fff;
7980     fseek (ifp, data_offset, SEEK_SET);
7981     if (ljpeg_start (&jh, 1) && jh.bits == 15)
7982       maximum = 0x1fff;
7983     if (tiff_samples > 1) filters = 0;
7984     if (tiff_samples > 1 || tile_length < raw_height) {
7985       load_raw = &CLASS leaf_hdr_load_raw;
7986       raw_width = tile_width;
7987     }
7988     if ((width | height) == 2048) {
7989       if (tiff_samples == 1) {
7990 	filters = 1;
7991 	strcpy (cdesc, "RBTG");
7992 	strcpy (model, "CatchLight");
7993 	top_margin =  8; left_margin = 18; height = 2032; width = 2016;
7994       } else {
7995 	strcpy (model, "DCB2");
7996 	top_margin = 10; left_margin = 16; height = 2028; width = 2022;
7997       }
7998     } else if (width+height == 3144+2060) {
7999       if (!model[0]) strcpy (model, "Cantare");
8000       if (width > height) {
8001 	 top_margin = 6; left_margin = 32; height = 2048;  width = 3072;
8002 	filters = 0x61616161;
8003       } else {
8004 	left_margin = 6;  top_margin = 32;  width = 2048; height = 3072;
8005 	filters = 0x16161616;
8006       }
8007       if (!cam_mul[0] || model[0] == 'V') filters = 0;
8008       else is_raw = tiff_samples;
8009     } else if (width == 2116) {
8010       strcpy (model, "Valeo 6");
8011       height -= 2 * (top_margin = 30);
8012       width -= 2 * (left_margin = 55);
8013       filters = 0x49494949;
8014     } else if (width == 3171) {
8015       strcpy (model, "Valeo 6");
8016       height -= 2 * (top_margin = 24);
8017       width -= 2 * (left_margin = 24);
8018       filters = 0x16161616;
8019     }
8020   } else if (!strcmp(make,"LEICA") || !strcmp(make,"Panasonic")) {
8021     if ((flen - data_offset) / (raw_width*8/7) == raw_height)
8022       load_raw = &CLASS panasonic_load_raw;
8023     if (!load_raw) {
8024       load_raw = &CLASS unpacked_load_raw;
8025       load_flags = 4;
8026     }
8027     zero_is_bad = 1;
8028     if ((height += 12) > raw_height) height = raw_height;
8029     for (i=0; i < sizeof pana / sizeof *pana; i++)
8030       if (raw_width == pana[i][0] && raw_height == pana[i][1]) {
8031 	left_margin = pana[i][2];
8032 	 top_margin = pana[i][3];
8033 	     width += pana[i][4];
8034 	    height += pana[i][5];
8035       }
8036     filters = 0x01010101 * (uchar) "\x94\x61\x49\x16"
8037 	[((filters-1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3];
8038   } else if (!strcmp(model,"C770UZ")) {
8039     height = 1718;
8040     width  = 2304;
8041     filters = 0x16161616;
8042     load_raw = &CLASS packed_load_raw;
8043     load_flags = 30;
8044   } else if (!strcmp(make,"OLYMPUS")) {
8045     height += height & 1;
8046     filters = exif_cfa;
8047     if (width == 4100) width -= 4;
8048     if (width == 4080) width -= 24;
8049     if (load_raw == &CLASS unpacked_load_raw)
8050       load_flags = 4;
8051     tiff_bps = 12;
8052     if (!strcmp(model,"E-300") ||
8053 	!strcmp(model,"E-500")) {
8054       width -= 20;
8055       if (load_raw == &CLASS unpacked_load_raw) {
8056 	maximum = 0xfc3;
8057 	memset (cblack, 0, sizeof cblack);
8058       }
8059     } else if (!strcmp(model,"E-330")) {
8060       width -= 30;
8061       if (load_raw == &CLASS unpacked_load_raw)
8062 	maximum = 0xf79;
8063     } else if (!strcmp(model,"SP550UZ")) {
8064       thumb_length = flen - (thumb_offset = 0xa39800);
8065       thumb_height = 480;
8066       thumb_width  = 640;
8067     }
8068   } else if (!strcmp(model,"N Digital")) {
8069     height = 2047;
8070     width  = 3072;
8071     filters = 0x61616161;
8072     data_offset = 0x1a00;
8073     load_raw = &CLASS packed_load_raw;
8074   } else if (!strcmp(model,"DSC-F828")) {
8075     width = 3288;
8076     left_margin = 5;
8077     data_offset = 862144;
8078     load_raw = &CLASS sony_load_raw;
8079     filters = 0x9c9c9c9c;
8080     colors = 4;
8081     strcpy (cdesc, "RGBE");
8082   } else if (!strcmp(model,"DSC-V3")) {
8083     width = 3109;
8084     left_margin = 59;
8085     data_offset = 787392;
8086     load_raw = &CLASS sony_load_raw;
8087   } else if (!strcmp(make,"SONY") && raw_width == 3984) {
8088     adobe_coeff ("SONY","DSC-R1");
8089     width = 3925;
8090     order = 0x4d4d;
8091   } else if (!strcmp(make,"SONY") && raw_width == 6048) {
8092     width -= 24;
8093   } else if (!strcmp(model,"DSLR-A100")) {
8094     if (width == 3880) {
8095       height--;
8096       width = ++raw_width;
8097     } else {
8098       order = 0x4d4d;
8099       load_flags = 2;
8100     }
8101     filters = 0x61616161;
8102   } else if (!strcmp(model,"DSLR-A350")) {
8103     height -= 4;
8104   } else if (!strcmp(model,"PIXL")) {
8105     height -= top_margin = 4;
8106     width -= left_margin = 32;
8107     gamma_curve (0, 7, 1, 255);
8108   } else if (!strcmp(model,"C603v")) {
8109     height = 480;
8110     width  = 640;
8111     if (fsize < 614400 || find_green (16, 16, 3840, 5120) < 25) goto c603v;
8112     strcpy (model,"KAI-0340");
8113     height -= 3;
8114     data_offset = 3840;
8115     order = 0x4949;
8116     load_raw = &CLASS unpacked_load_raw;
8117   } else if (!strcmp(model,"C603y")) {
8118     height = 2134;
8119     width  = 2848;
8120 c603v:
8121     filters = 0;
8122     load_raw = &CLASS kodak_yrgb_load_raw;
8123     gamma_curve (0, 3.875, 1, 255);
8124   } else if (!strcmp(model,"C603")) {
8125     raw_height = height = 2152;
8126     raw_width  = width  = 2864;
8127     goto c603;
8128   } else if (!strcmp(model,"C330")) {
8129     height = 1744;
8130     width  = 2336;
8131     raw_height = 1779;
8132     raw_width  = 2338;
8133     top_margin = 33;
8134     left_margin = 1;
8135 c603:
8136     order = 0x4949;
8137     if ((data_offset = fsize - raw_height*raw_width)) {
8138       fseek (ifp, 168, SEEK_SET);
8139       read_shorts (curve, 256);
8140     } else gamma_curve (0, 3.875, 1, 255);
8141     load_raw = &CLASS eight_bit_load_raw;
8142   } else if (!strncasecmp(model,"EasyShare",9)) {
8143     data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000;
8144     load_raw = &CLASS packed_load_raw;
8145   } else if (!strcasecmp(make,"KODAK")) {
8146     if (filters == UINT_MAX) filters = 0x61616161;
8147     if (!strncmp(model,"NC2000",6)) {
8148       width -= 4;
8149       left_margin = 2;
8150     } else if (!strcmp(model,"EOSDCS3B")) {
8151       width -= 4;
8152       left_margin = 2;
8153     } else if (!strcmp(model,"EOSDCS1")) {
8154       width -= 4;
8155       left_margin = 2;
8156     } else if (!strcmp(model,"DCS420")) {
8157       width -= 4;
8158       left_margin = 2;
8159     } else if (!strncmp(model,"DCS460 ",7)) {
8160       model[6] = 0;
8161       width -= 4;
8162       left_margin = 2;
8163     } else if (!strcmp(model,"DCS460A")) {
8164       width -= 4;
8165       left_margin = 2;
8166       colors = 1;
8167       filters = 0;
8168     } else if (!strcmp(model,"DCS660M")) {
8169       black = 214;
8170       colors = 1;
8171       filters = 0;
8172     } else if (!strcmp(model,"DCS760M")) {
8173       colors = 1;
8174       filters = 0;
8175     }
8176     if (!strcmp(model+4,"20X"))
8177       strcpy (cdesc, "MYCY");
8178     if (strstr(model,"DC25")) {
8179       strcpy (model, "DC25");
8180       data_offset = 15424;
8181     }
8182     if (!strncmp(model,"DC2",3)) {
8183       height = 242;
8184       if (flen < 100000) {
8185 	raw_width = 256; width = 249;
8186 	pixel_aspect = (4.0*height) / (3.0*width);
8187       } else {
8188 	raw_width = 512; width = 501;
8189 	pixel_aspect = (493.0*height) / (373.0*width);
8190       }
8191       data_offset += raw_width + 1;
8192       colors = 4;
8193       filters = 0x8d8d8d8d;
8194       simple_coeff(1);
8195       pre_mul[1] = 1.179;
8196       pre_mul[2] = 1.209;
8197       pre_mul[3] = 1.036;
8198       load_raw = &CLASS eight_bit_load_raw;
8199     } else if (!strcmp(model,"40")) {
8200       strcpy (model, "DC40");
8201       height = 512;
8202       width  = 768;
8203       data_offset = 1152;
8204       load_raw = &CLASS kodak_radc_load_raw;
8205     } else if (strstr(model,"DC50")) {
8206       strcpy (model, "DC50");
8207       height = 512;
8208       width  = 768;
8209       data_offset = 19712;
8210       load_raw = &CLASS kodak_radc_load_raw;
8211     } else if (strstr(model,"DC120")) {
8212       strcpy (model, "DC120");
8213       height = 976;
8214       width  = 848;
8215       pixel_aspect = height/0.75/width;
8216       load_raw = tiff_compress == 7 ?
8217 	&CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw;
8218     } else if (!strcmp(model,"DCS200")) {
8219       thumb_height = 128;
8220       thumb_width  = 192;
8221       thumb_offset = 6144;
8222       thumb_misc   = 360;
8223       write_thumb = &CLASS layer_thumb;
8224       height = 1024;
8225       width  = 1536;
8226       data_offset = 79872;
8227       load_raw = &CLASS eight_bit_load_raw;
8228       black = 17;
8229     }
8230   } else if (!strcmp(model,"Fotoman Pixtura")) {
8231     height = 512;
8232     width  = 768;
8233     data_offset = 3632;
8234     load_raw = &CLASS kodak_radc_load_raw;
8235     filters = 0x61616161;
8236     simple_coeff(2);
8237   } else if (!strncmp(model,"QuickTake",9)) {
8238     if (head[5]) strcpy (model+10, "200");
8239     fseek (ifp, 544, SEEK_SET);
8240     height = get2();
8241     width  = get2();
8242     data_offset = (get4(),get2()) == 30 ? 738:736;
8243     if (height > width) {
8244       SWAP(height,width);
8245       fseek (ifp, data_offset-6, SEEK_SET);
8246       flip = ~get2() & 3 ? 5:6;
8247     }
8248     filters = 0x61616161;
8249   } else if (!strcmp(make,"Rollei") && !load_raw) {
8250     switch (raw_width) {
8251       case 1316:
8252 	height = 1030;
8253 	width  = 1300;
8254 	top_margin  = 1;
8255 	left_margin = 6;
8256 	break;
8257       case 2568:
8258 	height = 1960;
8259 	width  = 2560;
8260 	top_margin  = 2;
8261 	left_margin = 8;
8262     }
8263     filters = 0x16161616;
8264     load_raw = &CLASS rollei_load_raw;
8265   } else if (!strcmp(model,"PC-CAM 600")) {
8266     height = 768;
8267     data_offset = width = 1024;
8268     filters = 0x49494949;
8269     load_raw = &CLASS eight_bit_load_raw;
8270   } else if (!strcmp(model,"QV-2000UX")) {
8271     height = 1208;
8272     width  = 1632;
8273     data_offset = width * 2;
8274     load_raw = &CLASS eight_bit_load_raw;
8275   } else if (fsize == 3217760) {
8276     height = 1546;
8277     width  = 2070;
8278     raw_width = 2080;
8279     load_raw = &CLASS eight_bit_load_raw;
8280   } else if (!strcmp(model,"QV-4000")) {
8281     height = 1700;
8282     width  = 2260;
8283     load_raw = &CLASS unpacked_load_raw;
8284     maximum = 0xffff;
8285   } else if (!strcmp(model,"QV-5700")) {
8286     height = 1924;
8287     width  = 2576;
8288     raw_width = 3232;
8289     tiff_bps = 10;
8290   } else if (!strcmp(model,"QV-R41")) {
8291     height = 1720;
8292     width  = 2312;
8293     raw_width = 3520;
8294     left_margin = 2;
8295   } else if (!strcmp(model,"QV-R51")) {
8296     height = 1926;
8297     width  = 2580;
8298     raw_width = 3904;
8299   } else if (!strcmp(model,"EX-S20")) {
8300     height = 1208;
8301     width  = 1620;
8302     raw_width = 2432;
8303     flip = 3;
8304   } else if (!strcmp(model,"EX-S100")) {
8305     height = 1544;
8306     width  = 2058;
8307     raw_width = 3136;
8308   } else if (!strcmp(model,"EX-Z50")) {
8309     height = 1931;
8310     width  = 2570;
8311     raw_width = 3904;
8312   } else if (!strcmp(model,"EX-Z55")) {
8313     height = 1960;
8314     width  = 2570;
8315     raw_width = 3904;
8316   } else if (!strcmp(model,"EX-Z60")) {
8317     height = 2145;
8318     width  = 2833;
8319     raw_width = 3584;
8320     filters = 0x16161616;
8321     tiff_bps = 10;
8322   } else if (!strcmp(model,"EX-Z75")) {
8323     height = 2321;
8324     width  = 3089;
8325     raw_width = 4672;
8326     maximum = 0xfff;
8327   } else if (!strcmp(model,"EX-Z750")) {
8328     height = 2319;
8329     width  = 3087;
8330     raw_width = 4672;
8331     maximum = 0xfff;
8332   } else if (!strcmp(model,"EX-Z850")) {
8333     height = 2468;
8334     width  = 3279;
8335     raw_width = 4928;
8336     maximum = 0xfff;
8337   } else if (fsize == 15499264) {	/* EX-Z1050 or EX-Z1080 */
8338     height = 2752;
8339     width  = 3672;
8340     raw_width = 5632;
8341   } else if (!strcmp(model,"EX-P505")) {
8342     height = 1928;
8343     width  = 2568;
8344     raw_width = 3852;
8345     maximum = 0xfff;
8346   } else if (fsize == 9313536) {	/* EX-P600 or QV-R61 */
8347     height = 2142;
8348     width  = 2844;
8349     raw_width = 4288;
8350   } else if (!strcmp(model,"EX-P700")) {
8351     height = 2318;
8352     width  = 3082;
8353     raw_width = 4672;
8354   }
8355   if (!model[0])
8356     sprintf (model, "%dx%d", width, height);
8357   if (filters == UINT_MAX) filters = 0x94949494;
8358   if (raw_color) adobe_coeff (make, model);
8359   if (load_raw == &CLASS kodak_radc_load_raw)
8360     if (raw_color) adobe_coeff ("Apple","Quicktake");
8361   if (thumb_offset && !thumb_height) {
8362     fseek (ifp, thumb_offset, SEEK_SET);
8363     if (ljpeg_start (&jh, 1)) {
8364       thumb_width  = jh.wide;
8365       thumb_height = jh.high;
8366     }
8367   }
8368 dng_skip:
8369   if (!tiff_bps) tiff_bps = 12;
8370   if (!maximum) maximum = (1 << tiff_bps) - 1;
8371   if (!load_raw || height < 22) is_raw = 0;
8372 #ifdef NO_JASPER
8373   if (load_raw == &CLASS redcine_load_raw) {
8374     fprintf (stderr,_("%s: You must link dcraw with %s!!\n"),
8375 	ifname, "libjasper");
8376     is_raw = 0;
8377   }
8378 #endif
8379 #ifdef NO_JPEG
8380   if (load_raw == &CLASS kodak_jpeg_load_raw) {
8381     fprintf (stderr,_("%s: You must link dcraw with %s!!\n"),
8382 	ifname, "libjpeg");
8383     is_raw = 0;
8384   }
8385 #endif
8386   if (!cdesc[0])
8387     strcpy (cdesc, colors == 3 ? "RGBG":"GMCY");
8388   if (!raw_height) raw_height = height;
8389   if (!raw_width ) raw_width  = width;
8390   if (filters && colors == 3)
8391     filters |= ((filters >> 2 & 0x22222222) |
8392 		(filters << 2 & 0x88888888)) & filters << 1;
8393 notraw:
8394   if (flip == -1) flip = tiff_flip;
8395   if (flip == -1) flip = 0;
8396 }
8397 
8398 #ifndef NO_LCMS
apply_profile(const char * input,const char * output)8399 void CLASS apply_profile (const char *input, const char *output)
8400 {
8401   char *prof;
8402   cmsHPROFILE hInProfile=0, hOutProfile=0;
8403   cmsHTRANSFORM hTransform;
8404   FILE *fp;
8405   unsigned size;
8406 
8407   cmsErrorAction (LCMS_ERROR_SHOW);
8408   if (strcmp (input, "embed"))
8409     hInProfile = cmsOpenProfileFromFile (input, "r");
8410   else if (profile_length) {
8411     prof = (char *) malloc (profile_length);
8412     merror (prof, "apply_profile()");
8413     fseek (ifp, profile_offset, SEEK_SET);
8414     fread (prof, 1, profile_length, ifp);
8415     hInProfile = cmsOpenProfileFromMem (prof, profile_length);
8416     free (prof);
8417   } else
8418     fprintf (stderr,_("%s has no embedded profile.\n"), ifname);
8419   if (!hInProfile) return;
8420   if (!output)
8421     hOutProfile = cmsCreate_sRGBProfile();
8422   else if ((fp = fopen (output, "rb"))) {
8423     fread (&size, 4, 1, fp);
8424     fseek (fp, 0, SEEK_SET);
8425     oprof = (unsigned *) malloc (size = ntohl(size));
8426     merror (oprof, "apply_profile()");
8427     fread (oprof, 1, size, fp);
8428     fclose (fp);
8429     if (!(hOutProfile = cmsOpenProfileFromMem (oprof, size))) {
8430       free (oprof);
8431       oprof = 0;
8432     }
8433   } else
8434     fprintf (stderr,_("Cannot open file %s!\n"), output);
8435   if (!hOutProfile) goto quit;
8436   if (verbose)
8437     fprintf (stderr,_("Applying color profile...\n"));
8438   hTransform = cmsCreateTransform (hInProfile, TYPE_RGBA_16,
8439 	hOutProfile, TYPE_RGBA_16, INTENT_PERCEPTUAL, 0);
8440   cmsDoTransform (hTransform, image, image, width*height);
8441   raw_color = 1;		/* Don't use rgb_cam with a profile */
8442   cmsDeleteTransform (hTransform);
8443   cmsCloseProfile (hOutProfile);
8444 quit:
8445   cmsCloseProfile (hInProfile);
8446 }
8447 #endif
8448 
convert_to_rgb()8449 void CLASS convert_to_rgb()
8450 {
8451   int row, col, c, i, j, k;
8452   ushort *img;
8453   float out[3], out_cam[3][4];
8454   double num, inverse[3][3];
8455   static const double xyzd50_srgb[3][3] =
8456   { { 0.436083, 0.385083, 0.143055 },
8457     { 0.222507, 0.716888, 0.060608 },
8458     { 0.013930, 0.097097, 0.714022 } };
8459   static const double rgb_rgb[3][3] =
8460   { { 1,0,0 }, { 0,1,0 }, { 0,0,1 } };
8461   static const double adobe_rgb[3][3] =
8462   { { 0.715146, 0.284856, 0.000000 },
8463     { 0.000000, 1.000000, 0.000000 },
8464     { 0.000000, 0.041166, 0.958839 } };
8465   static const double wide_rgb[3][3] =
8466   { { 0.593087, 0.404710, 0.002206 },
8467     { 0.095413, 0.843149, 0.061439 },
8468     { 0.011621, 0.069091, 0.919288 } };
8469   static const double prophoto_rgb[3][3] =
8470   { { 0.529317, 0.330092, 0.140588 },
8471     { 0.098368, 0.873465, 0.028169 },
8472     { 0.016879, 0.117663, 0.865457 } };
8473   static const double (*out_rgb[])[3] =
8474   { rgb_rgb, adobe_rgb, wide_rgb, prophoto_rgb, xyz_rgb };
8475   static const char *name[] =
8476   { "sRGB", "Adobe RGB (1998)", "WideGamut D65", "ProPhoto D65", "XYZ" };
8477   static const unsigned phead[] =
8478   { 1024, 0, 0x2100000, 0x6d6e7472, 0x52474220, 0x58595a20, 0, 0, 0,
8479     0x61637370, 0, 0, 0x6e6f6e65, 0, 0, 0, 0, 0xf6d6, 0x10000, 0xd32d };
8480   unsigned pbody[] =
8481   { 10, 0x63707274, 0, 36,	/* cprt */
8482 	0x64657363, 0, 40,	/* desc */
8483 	0x77747074, 0, 20,	/* wtpt */
8484 	0x626b7074, 0, 20,	/* bkpt */
8485 	0x72545243, 0, 14,	/* rTRC */
8486 	0x67545243, 0, 14,	/* gTRC */
8487 	0x62545243, 0, 14,	/* bTRC */
8488 	0x7258595a, 0, 20,	/* rXYZ */
8489 	0x6758595a, 0, 20,	/* gXYZ */
8490 	0x6258595a, 0, 20 };	/* bXYZ */
8491   static const unsigned pwhite[] = { 0xf351, 0x10000, 0x116cc };
8492   unsigned pcurve[] = { 0x63757276, 0, 1, 0x1000000 };
8493 
8494   gamma_curve (gamm[0], gamm[1], 0, 0);
8495   memcpy (out_cam, rgb_cam, sizeof out_cam);
8496   raw_color |= colors == 1 || document_mode ||
8497 		output_color < 1 || output_color > 5;
8498   if (!raw_color) {
8499     oprof = (unsigned *) calloc (phead[0], 1);
8500     merror (oprof, "convert_to_rgb()");
8501     memcpy (oprof, phead, sizeof phead);
8502     if (output_color == 5) oprof[4] = oprof[5];
8503     oprof[0] = 132 + 12*pbody[0];
8504     for (i=0; i < pbody[0]; i++) {
8505       oprof[oprof[0]/4] = i ? (i > 1 ? 0x58595a20 : 0x64657363) : 0x74657874;
8506       pbody[i*3+2] = oprof[0];
8507       oprof[0] += (pbody[i*3+3] + 3) & -4;
8508     }
8509     memcpy (oprof+32, pbody, sizeof pbody);
8510     oprof[pbody[5]/4+2] = strlen(name[output_color-1]) + 1;
8511     memcpy ((char *)oprof+pbody[8]+8, pwhite, sizeof pwhite);
8512     pcurve[3] = (short)(256/gamm[5]+0.5) << 16;
8513     for (i=4; i < 7; i++)
8514       memcpy ((char *)oprof+pbody[i*3+2], pcurve, sizeof pcurve);
8515     pseudoinverse ((double (*)[3]) out_rgb[output_color-1], inverse, 3);
8516     for (i=0; i < 3; i++)
8517       for (j=0; j < 3; j++) {
8518 	for (num = k=0; k < 3; k++)
8519 	  num += xyzd50_srgb[i][k] * inverse[j][k];
8520 	oprof[pbody[j*3+23]/4+i+2] = num * 0x10000 + 0.5;
8521       }
8522     for (i=0; i < phead[0]/4; i++)
8523       oprof[i] = htonl(oprof[i]);
8524     strcpy ((char *)oprof+pbody[2]+8, "auto-generated by dcraw");
8525     strcpy ((char *)oprof+pbody[5]+12, name[output_color-1]);
8526     for (i=0; i < 3; i++)
8527       for (j=0; j < colors; j++)
8528 	for (out_cam[i][j] = k=0; k < 3; k++)
8529 	  out_cam[i][j] += out_rgb[output_color-1][i][k] * rgb_cam[k][j];
8530   }
8531   if (verbose)
8532     fprintf (stderr, raw_color ? _("Building histograms...\n") :
8533 	_("Converting to %s colorspace...\n"), name[output_color-1]);
8534 
8535   memset (histogram, 0, sizeof histogram);
8536   for (img=image[0], row=0; row < height; row++)
8537     for (col=0; col < width; col++, img+=4) {
8538       if (!raw_color) {
8539 	out[0] = out[1] = out[2] = 0;
8540 	FORCC {
8541 	  out[0] += out_cam[0][c] * img[c];
8542 	  out[1] += out_cam[1][c] * img[c];
8543 	  out[2] += out_cam[2][c] * img[c];
8544 	}
8545 	FORC3 img[c] = CLIP((int) out[c]);
8546       }
8547       else if (document_mode)
8548 	img[0] = img[FC(row,col)];
8549       FORCC histogram[c][img[c] >> 3]++;
8550     }
8551   if (colors == 4 && output_color) colors = 3;
8552   if (document_mode && filters) colors = 1;
8553 }
8554 
fuji_rotate()8555 void CLASS fuji_rotate()
8556 {
8557   int i, row, col;
8558   double step;
8559   float r, c, fr, fc;
8560   unsigned ur, uc;
8561   ushort wide, high, (*img)[4], (*pix)[4];
8562 
8563   if (!fuji_width) return;
8564   if (verbose)
8565     fprintf (stderr,_("Rotating image 45 degrees...\n"));
8566   fuji_width = (fuji_width - 1 + shrink) >> shrink;
8567   step = sqrt(0.5);
8568   wide = fuji_width / step;
8569   high = (height - fuji_width) / step;
8570   img = (ushort (*)[4]) calloc (wide*high, sizeof *img);
8571   merror (img, "fuji_rotate()");
8572 
8573   for (row=0; row < high; row++)
8574     for (col=0; col < wide; col++) {
8575       ur = r = fuji_width + (row-col)*step;
8576       uc = c = (row+col)*step;
8577       if (ur > height-2 || uc > width-2) continue;
8578       fr = r - ur;
8579       fc = c - uc;
8580       pix = image + ur*width + uc;
8581       for (i=0; i < colors; i++)
8582 	img[row*wide+col][i] =
8583 	  (pix[    0][i]*(1-fc) + pix[      1][i]*fc) * (1-fr) +
8584 	  (pix[width][i]*(1-fc) + pix[width+1][i]*fc) * fr;
8585     }
8586   free (image);
8587   width  = wide;
8588   height = high;
8589   image  = img;
8590   fuji_width = 0;
8591 }
8592 
stretch()8593 void CLASS stretch()
8594 {
8595   ushort newdim, (*img)[4], *pix0, *pix1;
8596   int row, col, c;
8597   double rc, frac;
8598 
8599   if (pixel_aspect == 1) return;
8600   if (verbose) fprintf (stderr,_("Stretching the image...\n"));
8601   if (pixel_aspect < 1) {
8602     newdim = height / pixel_aspect + 0.5;
8603     img = (ushort (*)[4]) calloc (width*newdim, sizeof *img);
8604     merror (img, "stretch()");
8605     for (rc=row=0; row < newdim; row++, rc+=pixel_aspect) {
8606       frac = rc - (c = rc);
8607       pix0 = pix1 = image[c*width];
8608       if (c+1 < height) pix1 += width*4;
8609       for (col=0; col < width; col++, pix0+=4, pix1+=4)
8610 	FORCC img[row*width+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5;
8611     }
8612     height = newdim;
8613   } else {
8614     newdim = width * pixel_aspect + 0.5;
8615     img = (ushort (*)[4]) calloc (height*newdim, sizeof *img);
8616     merror (img, "stretch()");
8617     for (rc=col=0; col < newdim; col++, rc+=1/pixel_aspect) {
8618       frac = rc - (c = rc);
8619       pix0 = pix1 = image[c];
8620       if (c+1 < width) pix1 += 4;
8621       for (row=0; row < height; row++, pix0+=width*4, pix1+=width*4)
8622 	FORCC img[row*newdim+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5;
8623     }
8624     width = newdim;
8625   }
8626   free (image);
8627   image = img;
8628 }
8629 
flip_index(int row,int col)8630 int CLASS flip_index (int row, int col)
8631 {
8632   if (flip & 4) SWAP(row,col);
8633   if (flip & 2) row = iheight - 1 - row;
8634   if (flip & 1) col = iwidth  - 1 - col;
8635   return row * iwidth + col;
8636 }
8637 
8638 struct tiff_tag {
8639   ushort tag, type;
8640   int count;
8641   union { char c[4]; short s[2]; int i; } val;
8642 };
8643 
8644 struct tiff_hdr {
8645   ushort order, magic;
8646   int ifd;
8647   ushort pad, ntag;
8648   struct tiff_tag tag[23];
8649   int nextifd;
8650   ushort pad2, nexif;
8651   struct tiff_tag exif[4];
8652   ushort pad3, ngps;
8653   struct tiff_tag gpst[10];
8654   short bps[4];
8655   int rat[10];
8656   unsigned gps[26];
8657   char desc[512], make[64], model[64], soft[32], date[20], artist[64];
8658 };
8659 
tiff_set(ushort * ntag,ushort tag,ushort type,int count,int val)8660 void CLASS tiff_set (ushort *ntag,
8661 	ushort tag, ushort type, int count, int val)
8662 {
8663   struct tiff_tag *tt;
8664   int c;
8665 
8666   tt = (struct tiff_tag *)(ntag+1) + (*ntag)++;
8667   tt->tag = tag;
8668   tt->type = type;
8669   tt->count = count;
8670   if (type < 3 && count <= 4)
8671     FORC(4) tt->val.c[c] = val >> (c << 3);
8672   else if (type == 3 && count <= 2)
8673     FORC(2) tt->val.s[c] = val >> (c << 4);
8674   else tt->val.i = val;
8675 }
8676 
8677 #define TOFF(ptr) ((char *)(&(ptr)) - (char *)th)
8678 
tiff_head(struct tiff_hdr * th,int full)8679 void CLASS tiff_head (struct tiff_hdr *th, int full)
8680 {
8681   int c, psize=0;
8682   struct tm *t;
8683 
8684   memset (th, 0, sizeof *th);
8685   th->order = htonl(0x4d4d4949) >> 16;
8686   th->magic = 42;
8687   th->ifd = 10;
8688   if (full) {
8689     tiff_set (&th->ntag, 254, 4, 1, 0);
8690     tiff_set (&th->ntag, 256, 4, 1, width);
8691     tiff_set (&th->ntag, 257, 4, 1, height);
8692     tiff_set (&th->ntag, 258, 3, colors, output_bps);
8693     if (colors > 2)
8694       th->tag[th->ntag-1].val.i = TOFF(th->bps);
8695     FORC4 th->bps[c] = output_bps;
8696     tiff_set (&th->ntag, 259, 3, 1, 1);
8697     tiff_set (&th->ntag, 262, 3, 1, 1 + (colors > 1));
8698   }
8699   tiff_set (&th->ntag, 270, 2, 512, TOFF(th->desc));
8700   tiff_set (&th->ntag, 271, 2, 64, TOFF(th->make));
8701   tiff_set (&th->ntag, 272, 2, 64, TOFF(th->model));
8702   if (full) {
8703     if (oprof) psize = ntohl(oprof[0]);
8704     tiff_set (&th->ntag, 273, 4, 1, sizeof *th + psize);
8705     tiff_set (&th->ntag, 277, 3, 1, colors);
8706     tiff_set (&th->ntag, 278, 4, 1, height);
8707     tiff_set (&th->ntag, 279, 4, 1, height*width*colors*output_bps/8);
8708   } else
8709     tiff_set (&th->ntag, 274, 3, 1, "12435867"[flip]-'0');
8710   tiff_set (&th->ntag, 282, 5, 1, TOFF(th->rat[0]));
8711   tiff_set (&th->ntag, 283, 5, 1, TOFF(th->rat[2]));
8712   tiff_set (&th->ntag, 284, 3, 1, 1);
8713   tiff_set (&th->ntag, 296, 3, 1, 2);
8714   tiff_set (&th->ntag, 305, 2, 32, TOFF(th->soft));
8715   tiff_set (&th->ntag, 306, 2, 20, TOFF(th->date));
8716   tiff_set (&th->ntag, 315, 2, 64, TOFF(th->artist));
8717   tiff_set (&th->ntag, 34665, 4, 1, TOFF(th->nexif));
8718   if (psize) tiff_set (&th->ntag, 34675, 7, psize, sizeof *th);
8719   tiff_set (&th->nexif, 33434, 5, 1, TOFF(th->rat[4]));
8720   tiff_set (&th->nexif, 33437, 5, 1, TOFF(th->rat[6]));
8721   tiff_set (&th->nexif, 34855, 3, 1, iso_speed);
8722   tiff_set (&th->nexif, 37386, 5, 1, TOFF(th->rat[8]));
8723   if (gpsdata[1]) {
8724     tiff_set (&th->ntag, 34853, 4, 1, TOFF(th->ngps));
8725     tiff_set (&th->ngps,  0, 1,  4, 0x202);
8726     tiff_set (&th->ngps,  1, 2,  2, gpsdata[29]);
8727     tiff_set (&th->ngps,  2, 5,  3, TOFF(th->gps[0]));
8728     tiff_set (&th->ngps,  3, 2,  2, gpsdata[30]);
8729     tiff_set (&th->ngps,  4, 5,  3, TOFF(th->gps[6]));
8730     tiff_set (&th->ngps,  5, 1,  1, gpsdata[31]);
8731     tiff_set (&th->ngps,  6, 5,  1, TOFF(th->gps[18]));
8732     tiff_set (&th->ngps,  7, 5,  3, TOFF(th->gps[12]));
8733     tiff_set (&th->ngps, 18, 2, 12, TOFF(th->gps[20]));
8734     tiff_set (&th->ngps, 29, 2, 12, TOFF(th->gps[23]));
8735     memcpy (th->gps, gpsdata, sizeof th->gps);
8736   }
8737   th->rat[0] = th->rat[2] = 300;
8738   th->rat[1] = th->rat[3] = 1;
8739   FORC(6) th->rat[4+c] = 1000000;
8740   th->rat[4] *= shutter;
8741   th->rat[6] *= aperture;
8742   th->rat[8] *= focal_len;
8743   strncpy (th->desc, desc, 512);
8744   strncpy (th->make, make, 64);
8745   strncpy (th->model, model, 64);
8746   strcpy (th->soft, "dcraw v"DCRAW_VERSION);
8747   t = localtime (&timestamp);
8748   sprintf (th->date, "%04d:%02d:%02d %02d:%02d:%02d",
8749       t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);
8750   strncpy (th->artist, artist, 64);
8751 }
8752 
jpeg_thumb()8753 void CLASS jpeg_thumb()
8754 {
8755   char *thumb;
8756   ushort exif[5];
8757   struct tiff_hdr th;
8758 
8759   thumb = (char *) malloc (thumb_length);
8760   merror (thumb, "jpeg_thumb()");
8761   fread (thumb, 1, thumb_length, ifp);
8762   fputc (0xff, ofp);
8763   fputc (0xd8, ofp);
8764   if (strcmp (thumb+6, "Exif")) {
8765     memcpy (exif, "\xff\xe1  Exif\0\0", 10);
8766     exif[1] = htons (8 + sizeof th);
8767     fwrite (exif, 1, sizeof exif, ofp);
8768     tiff_head (&th, 0);
8769     fwrite (&th, 1, sizeof th, ofp);
8770   }
8771   fwrite (thumb+2, 1, thumb_length-2, ofp);
8772   free (thumb);
8773 }
8774 
write_ppm_tiff()8775 void CLASS write_ppm_tiff()
8776 {
8777   struct tiff_hdr th;
8778   uchar *ppm;
8779   ushort *ppm2;
8780   int c, row, col, soff, rstep, cstep;
8781   int perc, val, total, white=0x2000;
8782 
8783   perc = width * height * 0.01;		/* 99th percentile white level */
8784   if (fuji_width) perc /= 2;
8785   if (!((highlight & ~2) || no_auto_bright))
8786     for (white=c=0; c < colors; c++) {
8787       for (val=0x2000, total=0; --val > 32; )
8788 	if ((total += histogram[c][val]) > perc) break;
8789       if (white < val) white = val;
8790     }
8791   gamma_curve (gamm[0], gamm[1], 2, (white << 3)/bright);
8792   iheight = height;
8793   iwidth  = width;
8794   if (flip & 4) SWAP(height,width);
8795   ppm = (uchar *) calloc (width, colors*output_bps/8);
8796   ppm2 = (ushort *) ppm;
8797   merror (ppm, "write_ppm_tiff()");
8798   if (output_tiff) {
8799     tiff_head (&th, 1);
8800     fwrite (&th, sizeof th, 1, ofp);
8801     if (oprof)
8802       fwrite (oprof, ntohl(oprof[0]), 1, ofp);
8803   } else if (colors > 3)
8804     fprintf (ofp,
8805       "P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n",
8806 	width, height, colors, (1 << output_bps)-1, cdesc);
8807   else
8808     fprintf (ofp, "P%d\n%d %d\n%d\n",
8809 	colors/2+5, width, height, (1 << output_bps)-1);
8810   soff  = flip_index (0, 0);
8811   cstep = flip_index (0, 1) - soff;
8812   rstep = flip_index (1, 0) - flip_index (0, width);
8813   for (row=0; row < height; row++, soff += rstep) {
8814     for (col=0; col < width; col++, soff += cstep)
8815       if (output_bps == 8)
8816 	   FORCC ppm [col*colors+c] = curve[image[soff][c]] >> 8;
8817       else FORCC ppm2[col*colors+c] = curve[image[soff][c]];
8818     if (output_bps == 16 && !output_tiff && htons(0x55aa) != 0x55aa)
8819       swab (ppm2, ppm2, width*colors*2);
8820     fwrite (ppm, colors*output_bps/8, width, ofp);
8821   }
8822   free (ppm);
8823 }
8824 
main(int argc,const char ** argv)8825 int CLASS main (int argc, const char **argv)
8826 {
8827   int arg, status=0;
8828   int timestamp_only=0, thumbnail_only=0, identify_only=0;
8829   int user_qual=-1, user_black=-1, user_sat=-1, user_flip=-1;
8830   int use_fuji_rotate=1, write_to_stdout=0, quality, i, c;
8831   const char *sp, *bpfile=0, *dark_frame=0, *write_ext;
8832   char opm, opt, *ofname, *cp;
8833   struct utimbuf ut;
8834 #ifndef NO_LCMS
8835   const char *cam_profile=0, *out_profile=0;
8836 #endif
8837 
8838 #ifndef LOCALTIME
8839   putenv ((char *) "TZ=UTC");
8840 #endif
8841 #ifdef LOCALEDIR
8842   setlocale (LC_CTYPE, "");
8843   setlocale (LC_MESSAGES, "");
8844   bindtextdomain ("dcraw", LOCALEDIR);
8845   textdomain ("dcraw");
8846 #endif
8847 
8848   if (argc == 1) {
8849     printf(_("\nRaw photo decoder \"dcraw\" v%s"), DCRAW_VERSION);
8850     printf(_("\nby Dave Coffin, dcoffin a cybercom o net\n"));
8851     printf(_("\nUsage:  %s [OPTION]... [FILE]...\n\n"), argv[0]);
8852     puts(_("-v        Print verbose messages"));
8853     puts(_("-c        Write image data to standard output"));
8854     puts(_("-e        Extract embedded thumbnail image"));
8855     puts(_("-i        Identify files without decoding them"));
8856     puts(_("-i -v     Identify files and show metadata"));
8857     puts(_("-z        Change file dates to camera timestamp"));
8858     puts(_("-w        Use camera white balance, if possible"));
8859     puts(_("-a        Average the whole image for white balance"));
8860     puts(_("-A <x y w h> Average a grey box for white balance"));
8861     puts(_("-r <r g b g> Set custom white balance"));
8862     puts(_("+M/-M     Use/don't use an embedded color matrix"));
8863     puts(_("-C <r b>  Correct chromatic aberration"));
8864     puts(_("-P <file> Fix the dead pixels listed in this file"));
8865     puts(_("-K <file> Subtract dark frame (16-bit raw PGM)"));
8866     puts(_("-k <num>  Set the darkness level"));
8867     puts(_("-S <num>  Set the saturation level"));
8868     puts(_("-n <num>  Set threshold for wavelet denoising"));
8869     puts(_("-H [0-9]  Highlight mode (0=clip, 1=unclip, 2=blend, 3+=rebuild)"));
8870     puts(_("-t [0-7]  Flip image (0=none, 3=180, 5=90CCW, 6=90CW)"));
8871     puts(_("-o [0-5]  Output colorspace (raw,sRGB,Adobe,Wide,ProPhoto,XYZ)"));
8872 #ifndef NO_LCMS
8873     puts(_("-o <file> Apply output ICC profile from file"));
8874     puts(_("-p <file> Apply camera ICC profile from file or \"embed\""));
8875 #endif
8876     puts(_("-d        Document mode (no color, no interpolation)"));
8877     puts(_("-D        Document mode without scaling (totally raw)"));
8878     puts(_("-j        Don't stretch or rotate raw pixels"));
8879     puts(_("-W        Don't automatically brighten the image"));
8880     puts(_("-b <num>  Adjust brightness (default = 1.0)"));
8881     puts(_("-g <p ts> Set custom gamma curve (default = 2.222 4.5)"));
8882     puts(_("-q [0-3]  Set the interpolation quality"));
8883     puts(_("-h        Half-size color image (twice as fast as \"-q 0\")"));
8884     puts(_("-f        Interpolate RGGB as four colors"));
8885     puts(_("-m <num>  Apply a 3x3 median filter to R-G and B-G"));
8886     puts(_("-s [0..N-1] Select one raw image or \"all\" from each file"));
8887     puts(_("-6        Write 16-bit instead of 8-bit"));
8888     puts(_("-4        Linear 16-bit, same as \"-6 -W -g 1 1\""));
8889     puts(_("-T        Write TIFF instead of PPM"));
8890     puts("");
8891     return 1;
8892   }
8893   argv[argc] = "";
8894   for (arg=1; (((opm = argv[arg][0]) - 2) | 2) == '+'; ) {
8895     opt = argv[arg++][1];
8896     if ((cp = (char *) strchr (sp="nbrkStqmHACg", opt)))
8897       for (i=0; i < "114111111422"[cp-sp]-'0'; i++)
8898 	if (!isdigit(argv[arg+i][0])) {
8899 	  fprintf (stderr,_("Non-numeric argument to \"-%c\"\n"), opt);
8900 	  return 1;
8901 	}
8902     switch (opt) {
8903       case 'n':  threshold   = atof(argv[arg++]);  break;
8904       case 'b':  bright      = atof(argv[arg++]);  break;
8905       case 'r':
8906 	   FORC4 user_mul[c] = atof(argv[arg++]);  break;
8907       case 'C':  aber[0] = 1 / atof(argv[arg++]);
8908 		 aber[2] = 1 / atof(argv[arg++]);  break;
8909       case 'g':  gamm[0] =     atof(argv[arg++]);
8910 		 gamm[1] =     atof(argv[arg++]);
8911 		 if (gamm[0]) gamm[0] = 1/gamm[0]; break;
8912       case 'k':  user_black  = atoi(argv[arg++]);  break;
8913       case 'S':  user_sat    = atoi(argv[arg++]);  break;
8914       case 't':  user_flip   = atoi(argv[arg++]);  break;
8915       case 'q':  user_qual   = atoi(argv[arg++]);  break;
8916       case 'm':  med_passes  = atoi(argv[arg++]);  break;
8917       case 'H':  highlight   = atoi(argv[arg++]);  break;
8918       case 's':
8919 	shot_select = abs(atoi(argv[arg]));
8920 	multi_out = !strcmp(argv[arg++],"all");
8921 	break;
8922       case 'o':
8923 	if (isdigit(argv[arg][0]) && !argv[arg][1])
8924 	  output_color = atoi(argv[arg++]);
8925 #ifndef NO_LCMS
8926 	else     out_profile = argv[arg++];
8927 	break;
8928       case 'p':  cam_profile = argv[arg++];
8929 #endif
8930 	break;
8931       case 'P':  bpfile     = argv[arg++];  break;
8932       case 'K':  dark_frame = argv[arg++];  break;
8933       case 'z':  timestamp_only    = 1;  break;
8934       case 'e':  thumbnail_only    = 1;  break;
8935       case 'i':  identify_only     = 1;  break;
8936       case 'c':  write_to_stdout   = 1;  break;
8937       case 'v':  verbose           = 1;  break;
8938       case 'h':  half_size         = 1;		/* "-h" implies "-f" */
8939       case 'f':  four_color_rgb    = 1;  break;
8940       case 'A':  FORC4 greybox[c]  = atoi(argv[arg++]);
8941       case 'a':  use_auto_wb       = 1;  break;
8942       case 'w':  use_camera_wb     = 1;  break;
8943       case 'M':  use_camera_matrix = (opm == '+');  break;
8944       case 'D':
8945       case 'd':  document_mode = 1 + (opt == 'D');
8946       case 'j':  use_fuji_rotate   = 0;  break;
8947       case 'W':  no_auto_bright    = 1;  break;
8948       case 'T':  output_tiff       = 1;  break;
8949       case '4':  gamm[0] = gamm[1] =
8950 		 no_auto_bright    = 1;
8951       case '6':  output_bps       = 16;  break;
8952       default:
8953 	fprintf (stderr,_("Unknown option \"-%c\".\n"), opt);
8954 	return 1;
8955     }
8956   }
8957   if (use_camera_matrix < 0)
8958       use_camera_matrix = use_camera_wb;
8959   if (arg == argc) {
8960     fprintf (stderr,_("No files to process.\n"));
8961     return 1;
8962   }
8963   if (write_to_stdout) {
8964     if (isatty(1)) {
8965       fprintf (stderr,_("Will not write an image to the terminal!\n"));
8966       return 1;
8967     }
8968 #if defined(WIN32) || defined(DJGPP) || defined(__CYGWIN__)
8969     if (setmode(1,O_BINARY) < 0) {
8970       perror ("setmode()");
8971       return 1;
8972     }
8973 #endif
8974   }
8975   for ( ; arg < argc; arg++) {
8976     status = 1;
8977     image = 0;
8978     oprof = 0;
8979     meta_data = ofname = 0;
8980     ofp = stdout;
8981     if (setjmp (failure)) {
8982       if (fileno(ifp) > 2) fclose(ifp);
8983       if (fileno(ofp) > 2) fclose(ofp);
8984       status = 1;
8985       goto cleanup;
8986     }
8987     ifname = argv[arg];
8988     if (!(ifp = fopen (ifname, "rb"))) {
8989       perror (ifname);
8990       continue;
8991     }
8992     status = (identify(),!is_raw);
8993     if (user_flip >= 0)
8994       flip = user_flip;
8995     switch ((flip+3600) % 360) {
8996       case 270:  flip = 5;  break;
8997       case 180:  flip = 3;  break;
8998       case  90:  flip = 6;
8999     }
9000     if (timestamp_only) {
9001       if ((status = !timestamp))
9002 	fprintf (stderr,_("%s has no timestamp.\n"), ifname);
9003       else if (identify_only)
9004 	printf ("%10ld%10d %s\n", (long) timestamp, shot_order, ifname);
9005       else {
9006 	if (verbose)
9007 	  fprintf (stderr,_("%s time set to %d.\n"), ifname, (int) timestamp);
9008 	ut.actime = ut.modtime = timestamp;
9009 	utime (ifname, &ut);
9010       }
9011       goto next;
9012     }
9013     write_fun = &CLASS write_ppm_tiff;
9014     if (thumbnail_only) {
9015       if ((status = !thumb_offset)) {
9016 	fprintf (stderr,_("%s has no thumbnail.\n"), ifname);
9017 	goto next;
9018       } else if (thumb_load_raw) {
9019 	load_raw = thumb_load_raw;
9020 	data_offset = thumb_offset;
9021 	height = thumb_height;
9022 	width  = thumb_width;
9023 	filters = 0;
9024       } else {
9025 	fseek (ifp, thumb_offset, SEEK_SET);
9026 	write_fun = write_thumb;
9027 	goto thumbnail;
9028       }
9029     }
9030     if (load_raw == &CLASS kodak_ycbcr_load_raw) {
9031       height += height & 1;
9032       width  += width  & 1;
9033     }
9034     if (identify_only && verbose && make[0]) {
9035       printf (_("\nFilename: %s\n"), ifname);
9036       printf (_("Timestamp: %s"), ctime(&timestamp));
9037       printf (_("Camera: %s %s\n"), make, model);
9038       if (artist[0])
9039 	printf (_("Owner: %s\n"), artist);
9040       if (dng_version) {
9041 	printf (_("DNG Version: "));
9042 	for (i=24; i >= 0; i -= 8)
9043 	  printf ("%d%c", dng_version >> i & 255, i ? '.':'\n');
9044       }
9045       printf (_("ISO speed: %d\n"), (int) iso_speed);
9046       printf (_("Shutter: "));
9047       if (shutter > 0 && shutter < 1)
9048 	shutter = (printf ("1/"), 1 / shutter);
9049       printf (_("%0.1f sec\n"), shutter);
9050       printf (_("Aperture: f/%0.1f\n"), aperture);
9051       printf (_("Focal length: %0.1f mm\n"), focal_len);
9052       printf (_("Embedded ICC profile: %s\n"), profile_length ? _("yes"):_("no"));
9053       printf (_("Number of raw images: %d\n"), is_raw);
9054       if (pixel_aspect != 1)
9055 	printf (_("Pixel Aspect Ratio: %0.6f\n"), pixel_aspect);
9056       if (thumb_offset)
9057 	printf (_("Thumb size:  %4d x %d\n"), thumb_width, thumb_height);
9058       printf (_("Full size:   %4d x %d\n"), raw_width, raw_height);
9059     } else if (!is_raw)
9060       fprintf (stderr,_("Cannot decode file %s\n"), ifname);
9061     if (!is_raw) goto next;
9062     shrink = filters && (half_size || (!identify_only &&
9063 	(threshold || aber[0] != 1 || aber[2] != 1)));
9064     iheight = (height + shrink) >> shrink;
9065     iwidth  = (width  + shrink) >> shrink;
9066     if (identify_only) {
9067       if (verbose) {
9068 	if (use_fuji_rotate) {
9069 	  if (fuji_width) {
9070 	    fuji_width = (fuji_width - 1 + shrink) >> shrink;
9071 	    iwidth = fuji_width / sqrt(0.5);
9072 	    iheight = (iheight - fuji_width) / sqrt(0.5);
9073 	  } else {
9074 	    if (pixel_aspect < 1) iheight = iheight / pixel_aspect + 0.5;
9075 	    if (pixel_aspect > 1) iwidth  = iwidth  * pixel_aspect + 0.5;
9076 	  }
9077 	}
9078 	if (flip & 4)
9079 	  SWAP(iheight,iwidth);
9080 	printf (_("Image size:  %4d x %d\n"), width, height);
9081 	printf (_("Output size: %4d x %d\n"), iwidth, iheight);
9082 	printf (_("Raw colors: %d"), colors);
9083 	if (filters) {
9084 	  printf (_("\nFilter pattern: "));
9085 	  for (i=0; i < 16; i++)
9086 	    putchar (cdesc[fc(i >> 1,i & 1)]);
9087 	}
9088 	printf (_("\nDaylight multipliers:"));
9089 	FORCC printf (" %f", pre_mul[c]);
9090 	if (cam_mul[0] > 0) {
9091 	  printf (_("\nCamera multipliers:"));
9092 	  FORC4 printf (" %f", cam_mul[c]);
9093 	}
9094 	putchar ('\n');
9095       } else
9096 	printf (_("%s is a %s %s image.\n"), ifname, make, model);
9097 next:
9098       fclose(ifp);
9099       continue;
9100     }
9101     if (use_camera_matrix && cmatrix[0][0] > 0.25) {
9102       memcpy (rgb_cam, cmatrix, sizeof cmatrix);
9103       raw_color = 0;
9104     }
9105     image = (ushort (*)[4]) calloc (iheight*iwidth, sizeof *image);
9106     merror (image, "main()");
9107     if (meta_length) {
9108       meta_data = (char *) malloc (meta_length);
9109       merror (meta_data, "main()");
9110     }
9111     if (verbose)
9112       fprintf (stderr,_("Loading %s %s image from %s ...\n"),
9113 	make, model, ifname);
9114     if (shot_select >= is_raw)
9115       fprintf (stderr,_("%s: \"-s %d\" requests a nonexistent image!\n"),
9116 	ifname, shot_select);
9117     fseeko (ifp, data_offset, SEEK_SET);
9118     (*load_raw)();
9119     if (zero_is_bad) remove_zeroes();
9120     bad_pixels (bpfile);
9121     if (dark_frame) subtract (dark_frame);
9122     quality = 2 + !fuji_width;
9123     if (user_qual >= 0) quality = user_qual;
9124     i = cblack[3];
9125     FORC3 if (i > cblack[c]) i = cblack[c];
9126     FORC4 cblack[c] -= i;
9127     black += i;
9128     if (user_black >= 0) black = user_black;
9129     if (user_sat > 0) maximum = user_sat;
9130 #ifdef COLORCHECK
9131     colorcheck();
9132 #endif
9133     if (is_foveon && !document_mode) foveon_interpolate();
9134     if (!is_foveon && document_mode < 2) scale_colors();
9135     pre_interpolate();
9136     if (filters && !document_mode) {
9137       if (quality == 0)
9138 	lin_interpolate();
9139       else if (quality == 1 || colors > 3)
9140 	vng_interpolate();
9141       else if (quality == 2)
9142 	ppg_interpolate();
9143       else ahd_interpolate();
9144     }
9145     if (mix_green)
9146       for (colors=3, i=0; i < height*width; i++)
9147 	image[i][1] = (image[i][1] + image[i][3]) >> 1;
9148     if (!is_foveon && colors == 3) median_filter();
9149     if (!is_foveon && highlight == 2) blend_highlights();
9150     if (!is_foveon && highlight > 2) recover_highlights();
9151     if (use_fuji_rotate) fuji_rotate();
9152 #ifndef NO_LCMS
9153     if (cam_profile) apply_profile (cam_profile, out_profile);
9154 #endif
9155     convert_to_rgb();
9156     if (use_fuji_rotate) stretch();
9157 thumbnail:
9158     if (write_fun == &CLASS jpeg_thumb)
9159       write_ext = ".jpg";
9160     else if (output_tiff && write_fun == &CLASS write_ppm_tiff)
9161       write_ext = ".tiff";
9162     else
9163       write_ext = ".pgm\0.ppm\0.ppm\0.pam" + colors*5-5;
9164     ofname = (char *) malloc (strlen(ifname) + 64);
9165     merror (ofname, "main()");
9166     if (write_to_stdout)
9167       strcpy (ofname,_("standard output"));
9168     else {
9169       strcpy (ofname, ifname);
9170       if ((cp = strrchr (ofname, '.'))) *cp = 0;
9171       if (multi_out)
9172 	sprintf (ofname+strlen(ofname), "_%0*d",
9173 		snprintf(0,0,"%d",is_raw-1), shot_select);
9174       if (thumbnail_only)
9175 	strcat (ofname, ".thumb");
9176       strcat (ofname, write_ext);
9177       ofp = fopen (ofname, "wb");
9178       if (!ofp) {
9179 	status = 1;
9180 	perror (ofname);
9181 	goto cleanup;
9182       }
9183     }
9184     if (verbose)
9185       fprintf (stderr,_("Writing data to %s ...\n"), ofname);
9186     (*write_fun)();
9187     fclose(ifp);
9188     if (ofp != stdout) fclose(ofp);
9189 cleanup:
9190     if (meta_data) free (meta_data);
9191     if (ofname) free (ofname);
9192     if (oprof) free (oprof);
9193     if (image) free (image);
9194     if (multi_out) {
9195       if (++shot_select < is_raw) arg--;
9196       else shot_select = 0;
9197     }
9198   }
9199   return status;
9200 }
9201