dcraw.c

00001 /*
00002    dcraw.c -- Dave Coffin's raw photo decoder
00003    Copyright 1997-2006 by Dave Coffin, dcoffin a cybercom o net
00004 
00005    This is a command-line ANSI C program to convert raw photos from
00006    any digital camera on any computer running any operating system.
00007 
00008    Attention!  Some parts of this program are restricted under the
00009    terms of the GNU General Public License.  Such code is enclosed
00010    in "BEGIN GPL BLOCK" and "END GPL BLOCK" declarations.
00011    Any code not declared GPL is free for all uses.
00012 
00013    Starting in Revision 1.237, the code to support Foveon cameras
00014    is under GPL.
00015 
00016    To lawfully redistribute dcraw.c, you must either (a) include
00017    full source code for all executable files containing restricted
00018    functions, (b) remove these functions, re-implement them, or
00019    copy them from an earlier, non-GPL Revision of dcraw.c, or (c)
00020    purchase a license from the author.
00021 
00022    $Revision: 1.359 $
00023    $Date: 2006/12/14 15:40:47 $
00024  */
00025 
00026 #define VERSION "8.46"
00027 
00028 #define _GNU_SOURCE
00029 #define _USE_MATH_DEFINES
00030 #include <ctype.h>
00031 #include <errno.h>
00032 #include <fcntl.h>
00033 #include <float.h>
00034 #include <limits.h>
00035 #include <math.h>
00036 #include <setjmp.h>
00037 #include <stdio.h>
00038 #include <stdlib.h>
00039 #include <string.h>
00040 #include <time.h>
00041 /*
00042    NO_JPEG disables decoding of compressed Kodak DC120 files.
00043    NO_LCMS disables the "-p" option.
00044  */
00045 #ifndef NO_JPEG
00046 #include <jpeglib.h>
00047 #endif
00048 #ifndef NO_LCMS
00049 #include <lcms.h>
00050 #endif
00051 
00052 #ifdef __CYGWIN__
00053 #include <io.h>
00054 #endif
00055 #ifdef WIN32
00056 #include <sys/utime.h>
00057 #include <winsock2.h>
00058 #pragma comment(lib, "ws2_32.lib")
00059 #define strcasecmp stricmp
00060 typedef __int64 INT64;
00061 typedef unsigned __int64 UINT64;
00062 #else
00063 #include <unistd.h>
00064 #include <utime.h>
00065 #include <netinet/in.h>
00066 typedef long long INT64;
00067 typedef unsigned long long UINT64;
00068 #endif
00069 
00070 #ifdef LJPEG_DECODE
00071 #error Please compile dcraw.c by itself.
00072 #error Do not link it with ljpeg_decode.
00073 #endif
00074 
00075 #ifndef LONG_BIT
00076 #define LONG_BIT (8 * sizeof (long))
00077 #endif
00078 
00079 #define ushort UshORt
00080 typedef unsigned char uchar;
00081 typedef unsigned short ushort;
00082 
00083 /*
00084    All global variables are defined here, and all functions that
00085    access them are prefixed with "CLASS".  Note that a thread-safe
00086    C++ class cannot have non-const static local variables.
00087  */
00088 FILE *ifp;
00089 short order;
00090 char *ifname, make[64], model[72], model2[64], *meta_data, cdesc[5];
00091 float flash_used, canon_ev, iso_speed, shutter, aperture, focal_len;
00092 time_t timestamp;
00093 unsigned shot_order, kodak_cbpp, filters, unique_id, *oprof;
00094 int profile_offset, profile_length;
00095 int thumb_offset, thumb_length, thumb_width, thumb_height, thumb_misc;
00096 int data_offset, strip_offset, curve_offset, meta_offset, meta_length;
00097 int tiff_nifds, tiff_flip, tiff_bps, tiff_compress, tile_length;
00098 int raw_height, raw_width, top_margin, left_margin;
00099 int height, width, fuji_width, colors, tiff_samples;
00100 int black, maximum, raw_color, use_gamma;
00101 int iheight, iwidth, shrink, flip, xmag, ymag;
00102 int zero_after_ff, is_raw, dng_version, is_foveon;
00103 ushort (*image)[4], white[8][8], curve[0x1000], cr2_slice[3];
00104 float bright=1, user_mul[4]={0,0,0,0}, sigma_d=0, sigma_r=0;
00105 int four_color_rgb=0, document_mode=0, highlight=0;
00106 int verbose=0, use_auto_wb=0, use_camera_wb=0;
00107 int output_color=1, output_bps=8, output_tiff=0;
00108 int fuji_layout, fuji_secondary, shot_select=0;
00109 float cam_mul[4], pre_mul[4], rgb_cam[3][4];    /* RGB from camera color */
00110 const double xyz_rgb[3][3] = {          /* XYZ from RGB */
00111   { 0.412453, 0.357580, 0.180423 },
00112   { 0.212671, 0.715160, 0.072169 },
00113   { 0.019334, 0.119193, 0.950227 } };
00114 const float d65_white[3] = { 0.950456, 1, 1.088754 };
00115 int histogram[4][0x2000];
00116 void (*write_thumb)(FILE *), (*write_fun)(FILE *);
00117 void (*load_raw)(), (*thumb_load_raw)();
00118 jmp_buf failure;
00119 
00120 struct decode {
00121   struct decode *branch[2];
00122   int leaf;
00123 } first_decode[2048], *second_decode, *free_decode;
00124 
00125 struct {
00126   int width, height, bps, comp, phint, offset, flip, samples, bytes;
00127 } tiff_ifd[10];
00128 
00129 struct {
00130   int format, key_off, black, black_off, split_col, tag_21a;
00131   float tag_210;
00132 } ph1;
00133 
00134 #define CLASS
00135 #define fgetc getc_unlocked
00136 
00137 #define FORC3 for (c=0; c < 3; c++)
00138 #define FORC4 for (c=0; c < 4; c++)
00139 #define FORCC for (c=0; c < colors; c++)
00140 
00141 #define SQR(x) ((x)*(x))
00142 #define ABS(x) (((int)(x) ^ ((int)(x) >> 31)) - ((int)(x) >> 31))
00143 #define MIN(a,b) ((a) < (b) ? (a) : (b))
00144 #define MAX(a,b) ((a) > (b) ? (a) : (b))
00145 #define LIM(x,min,max) MAX(min,MIN(x,max))
00146 #define ULIM(x,y,z) ((y) < (z) ? LIM(x,y,z) : LIM(x,z,y))
00147 #define CLIP(x) LIM(x,0,65535)
00148 #define SWAP(a,b) { a ^= b; a ^= (b ^= a); }
00149 
00150 /*
00151    In order to inline this calculation, I make the risky
00152    assumption that all filter patterns can be described
00153    by a repeating pattern of eight rows and two columns
00154 
00155    Do not use the FC or BAYER macros with the Leaf CatchLight,
00156    because its pattern is 16x16, not 2x8.
00157 
00158    Return values are either 0/1/2/3 = G/M/C/Y or 0/1/2/3 = R/G1/B/G2
00159 
00160     PowerShot 600   PowerShot A50   PowerShot Pro70 Pro90 & G1
00161     0xe1e4e1e4: 0x1b4e4b1e: 0x1e4b4e1b: 0xb4b4b4b4:
00162 
00163       0 1 2 3 4 5     0 1 2 3 4 5     0 1 2 3 4 5     0 1 2 3 4 5
00164     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
00165     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
00166     2 M G M G M G   2 Y C Y C Y C   2 C Y C Y C Y
00167     3 C Y C Y C Y   3 G M G M G M   3 G M G M G M
00168             4 C Y C Y C Y   4 Y C Y C Y C
00169     PowerShot A5    5 G M G M G M   5 G M G M G M
00170     0x1e4e1e4e: 6 Y C Y C Y C   6 C Y C Y C Y
00171             7 M G M G M G   7 M G M G M G
00172       0 1 2 3 4 5
00173     0 C Y C Y C Y
00174     1 G M G M G M
00175     2 C Y C Y C Y
00176     3 M G M G M G
00177 
00178    All RGB cameras use one of these Bayer grids:
00179 
00180     0x16161616: 0x61616161: 0x49494949: 0x94949494:
00181 
00182       0 1 2 3 4 5     0 1 2 3 4 5     0 1 2 3 4 5     0 1 2 3 4 5
00183     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
00184     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
00185     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
00186     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
00187  */
00188 
00189 #define FC(row,col) \
00190     (filters >> ((((row) << 1 & 14) + ((col) & 1)) << 1) & 3)
00191 
00192 #define BAYER(row,col) \
00193     image[((row) >> shrink)*iwidth + ((col) >> shrink)][FC(row,col)]
00194 
00195 #define BAYER2(row,col) \
00196     image[((row) >> shrink)*iwidth + ((col) >> shrink)][fc(row,col)]
00197 
00198 int CLASS fc (int row, int col)
00199 {
00200   static const char filter[16][16] =
00201   { { 2,1,1,3,2,3,2,0,3,2,3,0,1,2,1,0 },
00202     { 0,3,0,2,0,1,3,1,0,1,1,2,0,3,3,2 },
00203     { 2,3,3,2,3,1,1,3,3,1,2,1,2,0,0,3 },
00204     { 0,1,0,1,0,2,0,2,2,0,3,0,1,3,2,1 },
00205     { 3,1,1,2,0,1,0,2,1,3,1,3,0,1,3,0 },
00206     { 2,0,0,3,3,2,3,1,2,0,2,0,3,2,2,1 },
00207     { 2,3,3,1,2,1,2,1,2,1,1,2,3,0,0,1 },
00208     { 1,0,0,2,3,0,0,3,0,3,0,3,2,1,2,3 },
00209     { 2,3,3,1,1,2,1,0,3,2,3,0,2,3,1,3 },
00210     { 1,0,2,0,3,0,3,2,0,1,1,2,0,1,0,2 },
00211     { 0,1,1,3,3,2,2,1,1,3,3,0,2,1,3,2 },
00212     { 2,3,2,0,0,1,3,0,2,0,1,2,3,0,1,0 },
00213     { 1,3,1,2,3,2,3,2,0,2,0,1,1,0,3,0 },
00214     { 0,2,0,3,1,0,0,1,1,3,3,2,3,2,2,1 },
00215     { 2,1,3,2,3,1,2,1,0,3,0,2,0,2,0,2 },
00216     { 0,3,1,0,0,2,0,3,2,1,3,1,1,3,1,3 } };
00217 
00218   if (filters != 1) return FC(row,col);
00219   return filter[(row+top_margin) & 15][(col+left_margin) & 15];
00220 }
00221 
00222 #ifndef __GLIBC__
00223 char *my_memmem (char *haystack, size_t haystacklen,
00224           char *needle, size_t needlelen)
00225 {
00226   char *c;
00227   for (c = haystack; c <= haystack + haystacklen - needlelen; c++)
00228     if (!memcmp (c, needle, needlelen))
00229       return c;
00230   return NULL;
00231 }
00232 #define memmem my_memmem
00233 #endif
00234 
00235 void CLASS merror (void *ptr, char *where)
00236 {
00237   if (ptr) return;
00238   fprintf (stderr, "%s: Out of memory in %s\n", ifname, where);
00239   longjmp (failure, 1);
00240 }
00241 
00242 ushort CLASS sget2 (uchar *s)
00243 {
00244   if (order == 0x4949)      /* "II" means little-endian */
00245     return s[0] | s[1] << 8;
00246   else              /* "MM" means big-endian */
00247     return s[0] << 8 | s[1];
00248 }
00249 
00250 ushort CLASS get2()
00251 {
00252   uchar str[2] = { 0xff,0xff };
00253   fread (str, 1, 2, ifp);
00254   return sget2(str);
00255 }
00256 
00257 int CLASS sget4 (uchar *s)
00258 {
00259   if (order == 0x4949)
00260     return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24;
00261   else
00262     return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3];
00263 }
00264 #define sget4(s) sget4((uchar *)s)
00265 
00266 int CLASS get4()
00267 {
00268   uchar str[4] = { 0xff,0xff,0xff,0xff };
00269   fread (str, 1, 4, ifp);
00270   return sget4(str);
00271 }
00272 
00273 int CLASS getint (int type)
00274 {
00275   return type == 3 ? get2() : get4();
00276 }
00277 
00278 float CLASS int_to_float (int i)
00279 {
00280   union { int i; float f; } u;
00281   u.i = i;
00282   return u.f;
00283 }
00284 
00285 double CLASS getreal (int type)
00286 {
00287   union { char c[8]; double d; } u;
00288   int i, rev;
00289 
00290   switch (type) {
00291     case 3: return (unsigned short) get2();
00292     case 4: return (unsigned int) get4();
00293     case 5:  u.d = (unsigned int) get4();
00294       return u.d / (unsigned int) get4();
00295     case 8: return (signed short) get2();
00296     case 9: return (signed int) get4();
00297     case 10: u.d = (signed int) get4();
00298       return u.d / (signed int) get4();
00299     case 11: return int_to_float (get4());
00300     case 12:
00301       rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234));
00302       for (i=0; i < 8; i++)
00303     u.c[i ^ rev] = fgetc(ifp);
00304       return u.d;
00305     default: return fgetc(ifp);
00306   }
00307 }
00308 #define getrat() getreal(10)
00309 
00310 void CLASS read_shorts (ushort *pixel, int count)
00311 {
00312   fread (pixel, 2, count, ifp);
00313   if ((order == 0x4949) == (ntohs(0x1234) == 0x1234))
00314     swab (pixel, pixel, count*2);
00315 }
00316 
00317 void CLASS canon_600_fixed_wb (int temp)
00318 {
00319   static const short mul[4][5] = {
00320     {  667, 358,397,565,452 },
00321     {  731, 390,367,499,517 },
00322     { 1119, 396,348,448,537 },
00323     { 1399, 485,431,508,688 } };
00324   int lo, hi, i;
00325   float frac=0;
00326 
00327   for (lo=4; --lo; )
00328     if (*mul[lo] <= temp) break;
00329   for (hi=0; hi < 3; hi++)
00330     if (*mul[hi] >= temp) break;
00331   if (lo != hi)
00332     frac = (float) (temp - *mul[lo]) / (*mul[hi] - *mul[lo]);
00333   for (i=1; i < 5; i++)
00334     pre_mul[i-1] = 1 / (frac * mul[hi][i] + (1-frac) * mul[lo][i]);
00335 }
00336 
00337 /* Return values:  0 = white  1 = near white  2 = not white */
00338 int CLASS canon_600_color (int ratio[2], int mar)
00339 {
00340   int clipped=0, target, miss;
00341 
00342   if (flash_used) {
00343     if (ratio[1] < -104)
00344       { ratio[1] = -104; clipped = 1; }
00345     if (ratio[1] >   12)
00346       { ratio[1] =   12; clipped = 1; }
00347   } else {
00348     if (ratio[1] < -264 || ratio[1] > 461) return 2;
00349     if (ratio[1] < -50)
00350       { ratio[1] = -50; clipped = 1; }
00351     if (ratio[1] > 307)
00352       { ratio[1] = 307; clipped = 1; }
00353   }
00354   target = flash_used || ratio[1] < 197
00355     ? -38 - (398 * ratio[1] >> 10)
00356     : -123 + (48 * ratio[1] >> 10);
00357   if (target - mar <= ratio[0] &&
00358       target + 20  >= ratio[0] && !clipped) return 0;
00359   miss = target - ratio[0];
00360   if (abs(miss) >= mar*4) return 2;
00361   if (miss < -20) miss = -20;
00362   if (miss > mar) miss = mar;
00363   ratio[0] = target - miss;
00364   return 1;
00365 }
00366 
00367 void CLASS canon_600_auto_wb()
00368 {
00369   int mar, row, col, i, j, st, count[] = { 0,0 };
00370   int test[8], total[2][8], ratio[2][2], stat[2];
00371 
00372   memset (&total, 0, sizeof total);
00373   i = canon_ev + 0.5;
00374   if      (i < 10) mar = 150;
00375   else if (i > 12) mar = 20;
00376   else mar = 280 - 20 * i;
00377   if (flash_used) mar = 80;
00378   for (row=14; row < height-14; row+=4)
00379     for (col=10; col < width; col+=2) {
00380       for (i=0; i < 8; i++)
00381     test[(i & 4) + FC(row+(i >> 1),col+(i & 1))] =
00382             BAYER(row+(i >> 1),col+(i & 1));
00383       for (i=0; i < 8; i++)
00384     if (test[i] < 150 || test[i] > 1500) goto next;
00385       for (i=0; i < 4; i++)
00386     if (abs(test[i] - test[i+4]) > 50) goto next;
00387       for (i=0; i < 2; i++) {
00388     for (j=0; j < 4; j+=2)
00389       ratio[i][j >> 1] = ((test[i*4+j+1]-test[i*4+j]) << 10) / test[i*4+j];
00390     stat[i] = canon_600_color (ratio[i], mar);
00391       }
00392       if ((st = stat[0] | stat[1]) > 1) goto next;
00393       for (i=0; i < 2; i++)
00394     if (stat[i])
00395       for (j=0; j < 2; j++)
00396         test[i*4+j*2+1] = test[i*4+j*2] * (0x400 + ratio[i][j]) >> 10;
00397       for (i=0; i < 8; i++)
00398     total[st][i] += test[i];
00399       count[st]++;
00400 next: continue;
00401     }
00402   if (count[0] | count[1]) {
00403     st = count[0]*200 < count[1];
00404     for (i=0; i < 4; i++)
00405       pre_mul[i] = 1.0 / (total[st][i] + total[st][i+4]);
00406   }
00407 }
00408 
00409 void CLASS canon_600_coeff()
00410 {
00411   static const short table[6][12] = {
00412     { -190,702,-1878,2390,   1861,-1349,905,-393, -432,944,2617,-2105  },
00413     { -1203,1715,-1136,1648, 1388,-876,267,245,  -1641,2153,3921,-3409 },
00414     { -615,1127,-1563,2075,  1437,-925,509,3,     -756,1268,2519,-2007 },
00415     { -190,702,-1886,2398,   2153,-1641,763,-251, -452,964,3040,-2528  },
00416     { -190,702,-1878,2390,   1861,-1349,905,-393, -432,944,2617,-2105  },
00417     { -807,1319,-1785,2297,  1388,-876,769,-257,  -230,742,2067,-1555  } };
00418   int t=0, i, c;
00419   float mc, yc;
00420 
00421   mc = pre_mul[1] / pre_mul[2];
00422   yc = pre_mul[3] / pre_mul[2];
00423   if (mc > 1 && mc <= 1.28 && yc < 0.8789) t=1;
00424   if (mc > 1.28 && mc <= 2) {
00425     if  (yc < 0.8789) t=3;
00426     else if (yc <= 2) t=4;
00427   }
00428   if (flash_used) t=5;
00429   for (raw_color = i=0; i < 3; i++)
00430     FORCC rgb_cam[i][c] = table[t][i*4 + c] / 1024.0;
00431 }
00432 
00433 void CLASS canon_600_load_raw()
00434 {
00435   uchar  data[1120], *dp;
00436   ushort pixel[896], *pix;
00437   int irow, row, col, val;
00438   static const short mul[4][2] =
00439   { { 1141,1145 }, { 1128,1109 }, { 1178,1149 }, { 1128,1109 } };
00440 
00441   for (irow=row=0; irow < height; irow++) {
00442     fread (data, raw_width * 10 / 8, 1, ifp);
00443     for (dp=data, pix=pixel; dp < data+1120; dp+=10, pix+=8) {
00444       pix[0] = (dp[0] << 2) + (dp[1] >> 6    );
00445       pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3);
00446       pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3);
00447       pix[3] = (dp[4] << 2) + (dp[1]      & 3);
00448       pix[4] = (dp[5] << 2) + (dp[9]      & 3);
00449       pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3);
00450       pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3);
00451       pix[7] = (dp[8] << 2) + (dp[9] >> 6    );
00452     }
00453     for (col=0; col < width; col++)
00454       BAYER(row,col) = pixel[col];
00455     for (col=width; col < raw_width; col++)
00456       black += pixel[col];
00457     if ((row+=2) > height) row = 1;
00458   }
00459   if (raw_width > width)
00460     black = black / ((raw_width - width) * height) - 4;
00461   for (row=0; row < height; row++)
00462     for (col=0; col < width; col++) {
00463       val = (BAYER(row,col) - black) * mul[row & 3][col & 1] >> 9;
00464       if (val < 0) val = 0;
00465       BAYER(row,col) = val;
00466     }
00467   canon_600_fixed_wb(1311);
00468   canon_600_auto_wb();
00469   canon_600_coeff();
00470   maximum = (0x3ff - black) * 1109 >> 9;
00471   black = 0;
00472 }
00473 
00474 void CLASS remove_zeroes()
00475 {
00476   unsigned row, col, tot, n, r, c;
00477 
00478   for (row=0; row < height; row++)
00479     for (col=0; col < width; col++)
00480       if (BAYER(row,col) == 0) {
00481     tot = n = 0;
00482     for (r = row-2; r <= row+2; r++)
00483       for (c = col-2; c <= col+2; c++)
00484         if (r < height && c < width &&
00485         FC(r,c) == FC(row,col) && BAYER(r,c))
00486           tot += (n++,BAYER(r,c));
00487     if (n) BAYER(row,col) = tot/n;
00488       }
00489 }
00490 
00491 void CLASS canon_a5_load_raw()
00492 {
00493   ushort data[1970], *dp, pixel;
00494   int vbits=0, buf=0, row, col, bc=0;
00495 
00496   order = 0x4949;
00497   for (row=-top_margin; row < raw_height-top_margin; row++) {
00498     read_shorts (dp=data, raw_width * 10 / 16);
00499     for (col=-left_margin; col < raw_width-left_margin; col++) {
00500       if (vbits < 10)
00501     buf = (vbits += 16, (buf << 16) + *dp++);
00502       pixel = buf >> (vbits -= 10) & 0x3ff;
00503       if ((unsigned) row < height && (unsigned) col < width)
00504     BAYER(row,col) = pixel;
00505       else black += (bc++,pixel);
00506     }
00507   }
00508   if (bc) black /= bc;
00509   maximum = 0x3ff;
00510   if (raw_width > 1600) remove_zeroes();
00511 }
00512 
00513 /*
00514    getbits(-1) initializes the buffer
00515    getbits(n) where 0 <= n <= 25 returns an n-bit integer
00516  */
00517 unsigned CLASS getbits (int nbits)
00518 {
00519   static unsigned bitbuf=0;
00520   static int vbits=0, reset=0;
00521   unsigned c;
00522 
00523   if (nbits == -1)
00524     return bitbuf = vbits = reset = 0;
00525   if (nbits == 0 || reset) return 0;
00526   while (vbits < nbits) {
00527     c = fgetc(ifp);
00528     if ((reset = zero_after_ff && c == 0xff && fgetc(ifp))) return 0;
00529     bitbuf = (bitbuf << 8) + c;
00530     vbits += 8;
00531   }
00532   vbits -= nbits;
00533   return bitbuf << (32-nbits-vbits) >> (32-nbits);
00534 }
00535 
00536 void CLASS init_decoder()
00537 {
00538   memset (first_decode, 0, sizeof first_decode);
00539   free_decode = first_decode;
00540 }
00541 
00542 /*
00543    Construct a decode tree according the specification in *source.
00544    The first 16 bytes specify how many codes should be 1-bit, 2-bit
00545    3-bit, etc.  Bytes after that are the leaf values.
00546 
00547    For example, if the source is
00548 
00549     { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
00550       0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff  },
00551 
00552    then the code is
00553 
00554     00      0x04
00555     010     0x03
00556     011     0x05
00557     100     0x06
00558     101     0x02
00559     1100        0x07
00560     1101        0x01
00561     11100       0x08
00562     11101       0x09
00563     11110       0x00
00564     111110      0x0a
00565     1111110     0x0b
00566     1111111     0xff
00567  */
00568 uchar * CLASS make_decoder (const uchar *source, int level)
00569 {
00570   struct decode *cur;
00571   static int leaf;
00572   int i, next;
00573 
00574   if (level==0) leaf=0;
00575   cur = free_decode++;
00576   if (free_decode > first_decode+2048) {
00577     fprintf (stderr, "%s: decoder table overflow\n", ifname);
00578     longjmp (failure, 2);
00579   }
00580   for (i=next=0; i <= leaf && next < 16; )
00581     i += source[next++];
00582   if (i > leaf) {
00583     if (level < next) {
00584       cur->branch[0] = free_decode;
00585       make_decoder (source, level+1);
00586       cur->branch[1] = free_decode;
00587       make_decoder (source, level+1);
00588     } else
00589       cur->leaf = source[16 + leaf++];
00590   }
00591   return (uchar *) source + 16 + leaf;
00592 }
00593 
00594 void CLASS crw_init_tables (unsigned table)
00595 {
00596   static const uchar first_tree[3][29] = {
00597     { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
00598       0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff  },
00599     { 0,2,2,3,1,1,1,1,2,0,0,0,0,0,0,0,
00600       0x03,0x02,0x04,0x01,0x05,0x00,0x06,0x07,0x09,0x08,0x0a,0x0b,0xff  },
00601     { 0,0,6,3,1,1,2,0,0,0,0,0,0,0,0,0,
00602       0x06,0x05,0x07,0x04,0x08,0x03,0x09,0x02,0x00,0x0a,0x01,0x0b,0xff  },
00603   };
00604   static const uchar second_tree[3][180] = {
00605     { 0,2,2,2,1,4,2,1,2,5,1,1,0,0,0,139,
00606       0x03,0x04,0x02,0x05,0x01,0x06,0x07,0x08,
00607       0x12,0x13,0x11,0x14,0x09,0x15,0x22,0x00,0x21,0x16,0x0a,0xf0,
00608       0x23,0x17,0x24,0x31,0x32,0x18,0x19,0x33,0x25,0x41,0x34,0x42,
00609       0x35,0x51,0x36,0x37,0x38,0x29,0x79,0x26,0x1a,0x39,0x56,0x57,
00610       0x28,0x27,0x52,0x55,0x58,0x43,0x76,0x59,0x77,0x54,0x61,0xf9,
00611       0x71,0x78,0x75,0x96,0x97,0x49,0xb7,0x53,0xd7,0x74,0xb6,0x98,
00612       0x47,0x48,0x95,0x69,0x99,0x91,0xfa,0xb8,0x68,0xb5,0xb9,0xd6,
00613       0xf7,0xd8,0x67,0x46,0x45,0x94,0x89,0xf8,0x81,0xd5,0xf6,0xb4,
00614       0x88,0xb1,0x2a,0x44,0x72,0xd9,0x87,0x66,0xd4,0xf5,0x3a,0xa7,
00615       0x73,0xa9,0xa8,0x86,0x62,0xc7,0x65,0xc8,0xc9,0xa1,0xf4,0xd1,
00616       0xe9,0x5a,0x92,0x85,0xa6,0xe7,0x93,0xe8,0xc1,0xc6,0x7a,0x64,
00617       0xe1,0x4a,0x6a,0xe6,0xb3,0xf1,0xd3,0xa5,0x8a,0xb2,0x9a,0xba,
00618       0x84,0xa4,0x63,0xe5,0xc5,0xf3,0xd2,0xc4,0x82,0xaa,0xda,0xe4,
00619       0xf2,0xca,0x83,0xa3,0xa2,0xc3,0xea,0xc2,0xe2,0xe3,0xff,0xff  },
00620     { 0,2,2,1,4,1,4,1,3,3,1,0,0,0,0,140,
00621       0x02,0x03,0x01,0x04,0x05,0x12,0x11,0x06,
00622       0x13,0x07,0x08,0x14,0x22,0x09,0x21,0x00,0x23,0x15,0x31,0x32,
00623       0x0a,0x16,0xf0,0x24,0x33,0x41,0x42,0x19,0x17,0x25,0x18,0x51,
00624       0x34,0x43,0x52,0x29,0x35,0x61,0x39,0x71,0x62,0x36,0x53,0x26,
00625       0x38,0x1a,0x37,0x81,0x27,0x91,0x79,0x55,0x45,0x28,0x72,0x59,
00626       0xa1,0xb1,0x44,0x69,0x54,0x58,0xd1,0xfa,0x57,0xe1,0xf1,0xb9,
00627       0x49,0x47,0x63,0x6a,0xf9,0x56,0x46,0xa8,0x2a,0x4a,0x78,0x99,
00628       0x3a,0x75,0x74,0x86,0x65,0xc1,0x76,0xb6,0x96,0xd6,0x89,0x85,
00629       0xc9,0xf5,0x95,0xb4,0xc7,0xf7,0x8a,0x97,0xb8,0x73,0xb7,0xd8,
00630       0xd9,0x87,0xa7,0x7a,0x48,0x82,0x84,0xea,0xf4,0xa6,0xc5,0x5a,
00631       0x94,0xa4,0xc6,0x92,0xc3,0x68,0xb5,0xc8,0xe4,0xe5,0xe6,0xe9,
00632       0xa2,0xa3,0xe3,0xc2,0x66,0x67,0x93,0xaa,0xd4,0xd5,0xe7,0xf8,
00633       0x88,0x9a,0xd7,0x77,0xc4,0x64,0xe2,0x98,0xa5,0xca,0xda,0xe8,
00634       0xf3,0xf6,0xa9,0xb2,0xb3,0xf2,0xd2,0x83,0xba,0xd3,0xff,0xff  },
00635     { 0,0,6,2,1,3,3,2,5,1,2,2,8,10,0,117,
00636       0x04,0x05,0x03,0x06,0x02,0x07,0x01,0x08,
00637       0x09,0x12,0x13,0x14,0x11,0x15,0x0a,0x16,0x17,0xf0,0x00,0x22,
00638       0x21,0x18,0x23,0x19,0x24,0x32,0x31,0x25,0x33,0x38,0x37,0x34,
00639       0x35,0x36,0x39,0x79,0x57,0x58,0x59,0x28,0x56,0x78,0x27,0x41,
00640       0x29,0x77,0x26,0x42,0x76,0x99,0x1a,0x55,0x98,0x97,0xf9,0x48,
00641       0x54,0x96,0x89,0x47,0xb7,0x49,0xfa,0x75,0x68,0xb6,0x67,0x69,
00642       0xb9,0xb8,0xd8,0x52,0xd7,0x88,0xb5,0x74,0x51,0x46,0xd9,0xf8,
00643       0x3a,0xd6,0x87,0x45,0x7a,0x95,0xd5,0xf6,0x86,0xb4,0xa9,0x94,
00644       0x53,0x2a,0xa8,0x43,0xf5,0xf7,0xd4,0x66,0xa7,0x5a,0x44,0x8a,
00645       0xc9,0xe8,0xc8,0xe7,0x9a,0x6a,0x73,0x4a,0x61,0xc7,0xf4,0xc6,
00646       0x65,0xe9,0x72,0xe6,0x71,0x91,0x93,0xa6,0xda,0x92,0x85,0x62,
00647       0xf3,0xc5,0xb2,0xa4,0x84,0xba,0x64,0xa5,0xb3,0xd2,0x81,0xe5,
00648       0xd3,0xaa,0xc4,0xca,0xf2,0xb1,0xe4,0xd1,0x83,0x63,0xea,0xc3,
00649       0xe2,0x82,0xf1,0xa3,0xc2,0xa1,0xc1,0xe3,0xa2,0xe1,0xff,0xff  }
00650   };
00651   if (table > 2) table = 2;
00652   init_decoder();
00653   make_decoder ( first_tree[table], 0);
00654   second_decode = free_decode;
00655   make_decoder (second_tree[table], 0);
00656 }
00657 
00658 /*
00659    Return 0 if the image starts with compressed data,
00660    1 if it starts with uncompressed low-order bits.
00661 
00662    In Canon compressed data, 0xff is always followed by 0x00.
00663  */
00664 int CLASS canon_has_lowbits()
00665 {
00666   uchar test[0x4000];
00667   int ret=1, i;
00668 
00669   fseek (ifp, 0, SEEK_SET);
00670   fread (test, 1, sizeof test, ifp);
00671   for (i=540; i < sizeof test - 1; i++)
00672     if (test[i] == 0xff) {
00673       if (test[i+1]) return 1;
00674       ret=0;
00675     }
00676   return ret;
00677 }
00678 
00679 void CLASS canon_compressed_load_raw()
00680 {
00681   ushort *pixel, *prow;
00682   int lowbits, i, row, r, col, save, val;
00683   unsigned irow, icol;
00684   struct decode *decode, *dindex;
00685   int block, diffbuf[64], leaf, len, diff, carry=0, pnum=0, base[2];
00686   uchar c;
00687 
00688   crw_init_tables (tiff_compress);
00689   pixel = (ushort *) calloc (raw_width*8, sizeof *pixel);
00690   merror (pixel, "canon_compressed_load_raw()");
00691   lowbits = canon_has_lowbits();
00692   if (!lowbits) maximum = 0x3ff;
00693   fseek (ifp, 540 + lowbits*raw_height*raw_width/4, SEEK_SET);
00694   zero_after_ff = 1;
00695   getbits(-1);
00696   for (row=0; row < raw_height; row+=8) {
00697     for (block=0; block < raw_width >> 3; block++) {
00698       memset (diffbuf, 0, sizeof diffbuf);
00699       decode = first_decode;
00700       for (i=0; i < 64; i++ ) {
00701     for (dindex=decode; dindex->branch[0]; )
00702       dindex = dindex->branch[getbits(1)];
00703     leaf = dindex->leaf;
00704     decode = second_decode;
00705     if (leaf == 0 && i) break;
00706     if (leaf == 0xff) continue;
00707     i  += leaf >> 4;
00708     len = leaf & 15;
00709     if (len == 0) continue;
00710     diff = getbits(len);
00711     if ((diff & (1 << (len-1))) == 0)
00712       diff -= (1 << len) - 1;
00713     if (i < 64) diffbuf[i] = diff;
00714       }
00715       diffbuf[0] += carry;
00716       carry = diffbuf[0];
00717       for (i=0; i < 64; i++ ) {
00718     if (pnum++ % raw_width == 0)
00719       base[0] = base[1] = 512;
00720     pixel[(block << 6) + i] = ( base[i & 1] += diffbuf[i] );
00721       }
00722     }
00723     if (lowbits) {
00724       save = ftell(ifp);
00725       fseek (ifp, 26 + row*raw_width/4, SEEK_SET);
00726       for (prow=pixel, i=0; i < raw_width*2; i++) {
00727     c = fgetc(ifp);
00728     for (r=0; r < 8; r+=2, prow++) {
00729       val = (*prow << 2) + ((c >> r) & 3);
00730       if (raw_width == 2672 && val < 512) val += 2;
00731       *prow = val;
00732     }
00733       }
00734       fseek (ifp, save, SEEK_SET);
00735     }
00736     for (r=0; r < 8; r++) {
00737       irow = row - top_margin + r;
00738       if (irow >= height) continue;
00739       for (col=0; col < raw_width; col++) {
00740     icol = col - left_margin;
00741     if (icol < width)
00742       BAYER(irow,icol) = pixel[r*raw_width+col];
00743     else
00744       black += pixel[r*raw_width+col];
00745       }
00746     }
00747   }
00748   free (pixel);
00749   if (raw_width > width)
00750     black /= (raw_width - width) * height;
00751 }
00752 
00753 /*
00754    Not a full implementation of Lossless JPEG, just
00755    enough to decode Canon, Kodak and Adobe DNG images.
00756  */
00757 struct jhead {
00758   int bits, high, wide, clrs, restart, vpred[4];
00759   struct decode *huff[4];
00760   ushort *row;
00761 };
00762 
00763 int CLASS ljpeg_start (struct jhead *jh, int info_only)
00764 {
00765   int i, tag, len;
00766   uchar data[0x10000], *dp;
00767 
00768   init_decoder();
00769   for (i=0; i < 4; i++)
00770     jh->huff[i] = free_decode;
00771   jh->restart = INT_MAX;
00772   fread (data, 2, 1, ifp);
00773   if (data[1] != 0xd8) return 0;
00774   do {
00775     fread (data, 2, 2, ifp);
00776     tag =  data[0] << 8 | data[1];
00777     len = (data[2] << 8 | data[3]) - 2;
00778     if (tag <= 0xff00) return 0;
00779     fread (data, 1, len, ifp);
00780     switch (tag) {
00781       case 0xffc0:
00782       case 0xffc3:
00783     jh->bits = data[0];
00784     jh->high = data[1] << 8 | data[2];
00785     jh->wide = data[3] << 8 | data[4];
00786     jh->clrs = data[5];
00787     break;
00788       case 0xffc4:
00789     if (info_only) break;
00790     for (dp = data; dp < data+len && *dp < 4; ) {
00791       jh->huff[*dp] = free_decode;
00792       dp = make_decoder (++dp, 0);
00793     }
00794     break;
00795       case 0xffdd:
00796     jh->restart = data[0] << 8 | data[1];
00797     }
00798   } while (tag != 0xffda);
00799   if (info_only) return 1;
00800   jh->row = (ushort *) calloc (jh->wide*jh->clrs, 2);
00801   merror (jh->row, " jpeg_start()");
00802   return zero_after_ff = 1;
00803 }
00804 
00805 int CLASS ljpeg_diff (struct decode *dindex)
00806 {
00807   int len, diff;
00808 
00809   while (dindex->branch[0])
00810     dindex = dindex->branch[getbits(1)];
00811   len = dindex->leaf;
00812   if (len == 16 && (!dng_version || dng_version >= 0x1010000))
00813     return -32768;
00814   diff = getbits(len);
00815   if ((diff & (1 << (len-1))) == 0)
00816     diff -= (1 << len) - 1;
00817   return diff;
00818 }
00819 
00820 void CLASS ljpeg_row (int jrow, struct jhead *jh)
00821 {
00822   int col, c, diff;
00823   ushort mark=0, *outp=jh->row;
00824 
00825   if (jrow * jh->wide % jh->restart == 0) {
00826     FORC4 jh->vpred[c] = 1 << (jh->bits-1);
00827     if (jrow)
00828       do mark = (mark << 8) + (c = fgetc(ifp));
00829       while (c != EOF && mark >> 4 != 0xffd);
00830     getbits(-1);
00831   }
00832   for (col=0; col < jh->wide; col++)
00833     for (c=0; c < jh->clrs; c++) {
00834       diff = ljpeg_diff (jh->huff[c]);
00835       *outp = col ? outp[-jh->clrs]+diff : (jh->vpred[c] += diff);
00836       outp++;
00837     }
00838 }
00839 
00840 void CLASS lossless_jpeg_load_raw()
00841 {
00842   int jwide, jrow, jcol, val, jidx, i, j, row=0, col=0;
00843   struct jhead jh;
00844   int min=INT_MAX;
00845 
00846   if (!ljpeg_start (&jh, 0)) return;
00847   jwide = jh.wide * jh.clrs;
00848 
00849   for (jrow=0; jrow < jh.high; jrow++) {
00850     ljpeg_row (jrow, &jh);
00851     for (jcol=0; jcol < jwide; jcol++) {
00852       val = jh.row[jcol];
00853       if (jh.bits <= 12)
00854     val = curve[val];
00855       if (cr2_slice[0]) {
00856     jidx = jrow*jwide + jcol;
00857     i = jidx / (cr2_slice[1]*jh.high);
00858     if ((j = i >= cr2_slice[0]))
00859          i  = cr2_slice[0];
00860     jidx -= i * (cr2_slice[1]*jh.high);
00861     row = jidx / cr2_slice[1+j];
00862     col = jidx % cr2_slice[1+j] + i*cr2_slice[1];
00863       }
00864       if ((unsigned) (row-top_margin) < height) {
00865     if ((unsigned) (col-left_margin) < width) {
00866       BAYER(row-top_margin,col-left_margin) = val;
00867       if (min > val) min = val;
00868     } else black += val;
00869       }
00870       if (++col >= raw_width)
00871     col = (row++,0);
00872     }
00873   }
00874   free (jh.row);
00875   if (raw_width > width)
00876     black /= (raw_width - width) * height;
00877   if (!strcasecmp(make,"KODAK"))
00878     black = min;
00879 }
00880 
00881 void CLASS adobe_copy_pixel (int row, int col, ushort **rp)
00882 {
00883   unsigned r, c;
00884 
00885   r = row -= top_margin;
00886   c = col -= left_margin;
00887   if (fuji_secondary && shot_select) (*rp)++;
00888   if (filters) {
00889     if (fuji_width) {
00890       r = row + fuji_width - 1 - (col >> 1);
00891       c = row + ((col+1) >> 1);
00892     }
00893     if (r < height && c < width)
00894       BAYER(r,c) = **rp < 0x1000 ? curve[**rp] : **rp;
00895     *rp += 1 + fuji_secondary;
00896   } else {
00897     if (r < height && c < width)
00898       for (c=0; c < tiff_samples; c++)
00899     image[row*width+col][c] = (*rp)[c] < 0x1000 ? curve[(*rp)[c]]:(*rp)[c];
00900     *rp += tiff_samples;
00901   }
00902   if (fuji_secondary && shot_select) (*rp)--;
00903 }
00904 
00905 void CLASS adobe_dng_load_raw_lj()
00906 {
00907   int save, twide, trow=0, tcol=0, jrow, jcol;
00908   struct jhead jh;
00909   ushort *rp;
00910 
00911   while (1) {
00912     save = ftell(ifp);
00913     fseek (ifp, get4(), SEEK_SET);
00914     if (!ljpeg_start (&jh, 0)) break;
00915     if (trow >= raw_height) break;
00916     if (jh.high > raw_height-trow)
00917     jh.high = raw_height-trow;
00918     twide = jh.wide;
00919     if (filters) twide *= jh.clrs;
00920     else         colors = jh.clrs;
00921     if (fuji_secondary) twide /= 2;
00922     if (twide > raw_width-tcol)
00923     twide = raw_width-tcol;
00924 
00925     for (jrow=0; jrow < jh.high; jrow++) {
00926       ljpeg_row (jrow, &jh);
00927       for (rp=jh.row, jcol=0; jcol < twide; jcol++)
00928     adobe_copy_pixel (trow+jrow, tcol+jcol, &rp);
00929     }
00930     fseek (ifp, save+4, SEEK_SET);
00931     if ((tcol += twide) >= raw_width) {
00932       tcol = 0;
00933       trow += jh.high;
00934     }
00935     free (jh.row);
00936   }
00937 }
00938 
00939 void CLASS adobe_dng_load_raw_nc()
00940 {
00941   ushort *pixel, *rp;
00942   int row, col;
00943 
00944   pixel = (ushort *) calloc (raw_width * tiff_samples, sizeof *pixel);
00945   merror (pixel, "adobe_dng_load_raw_nc()");
00946   for (row=0; row < raw_height; row++) {
00947     if (tiff_bps == 16)
00948       read_shorts (pixel, raw_width * tiff_samples);
00949     else {
00950       getbits(-1);
00951       for (col=0; col < raw_width * tiff_samples; col++)
00952     pixel[col] = getbits(tiff_bps);
00953     }
00954     for (rp=pixel, col=0; col < raw_width; col++)
00955       adobe_copy_pixel (row, col, &rp);
00956   }
00957   free (pixel);
00958 }
00959 
00960 void CLASS pentax_k10_load_raw()
00961 {
00962   static const uchar pentax_tree[] =
00963   { 0,2,3,1,1,1,1,1,1,2,0,0,0,0,0,0,
00964     3,4,2,5,1,6,0,7,8,9,10,11,12 };
00965   int row, col, diff, i;
00966   ushort vpred[4] = {0,0,0,0}, hpred[2];
00967 
00968   init_decoder();
00969   make_decoder (pentax_tree, 0);
00970   getbits(-1);
00971   for (row=0; row < height; row++)
00972     for (col=0; col < raw_width; col++) {
00973       diff = ljpeg_diff (first_decode);
00974       if (col < 2) {
00975     i = 2*(row & 1) + (col & 1);
00976     vpred[i] += diff;
00977     hpred[col] = vpred[i];
00978       } else
00979     hpred[col & 1] += diff;
00980       if (col < width)
00981     BAYER(row,col) = hpred[col & 1];
00982     }
00983 }
00984 
00985 void CLASS nikon_compressed_load_raw()
00986 {
00987   static const uchar nikon_tree[] =
00988   { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0,
00989     5,4,3,6,2,7,1,0,8,9,11,10,12 };
00990   int csize, row, col, diff, i;
00991   ushort vpred[4], hpred[2], *curve;
00992 
00993   init_decoder();
00994   make_decoder (nikon_tree, 0);
00995 
00996   fseek (ifp, curve_offset, SEEK_SET);
00997   read_shorts (vpred, 4);
00998   csize = get2();
00999   curve = (ushort *) calloc (csize, sizeof *curve);
01000   merror (curve, "nikon_compressed_load_raw()");
01001   read_shorts (curve, csize);
01002 
01003   fseek (ifp, data_offset, SEEK_SET);
01004   getbits(-1);
01005   for (row=0; row < height; row++)
01006     for (col=0; col < raw_width; col++) {
01007       diff = ljpeg_diff (first_decode);
01008       if (col < 2) {
01009     i = 2*(row & 1) + (col & 1);
01010     vpred[i] += diff;
01011     hpred[col] = vpred[i];
01012       } else
01013     hpred[col & 1] += diff;
01014       if ((unsigned) (col-left_margin) >= width) continue;
01015       diff = hpred[col & 1];
01016       if (diff >= csize) diff = csize-1;
01017       BAYER(row,col-left_margin) = curve[diff];
01018     }
01019   free (curve);
01020 }
01021 
01022 void CLASS nikon_load_raw()
01023 {
01024   int irow, row, col, i;
01025 
01026   getbits(-1);
01027   for (irow=0; irow < height; irow++) {
01028     row = irow;
01029     if (make[0] == 'O' || model[0] == 'E') {
01030       row = irow * 2 % height + irow / (height/2);
01031       if (row == 1 && data_offset == 0) {
01032     fseek (ifp, 0, SEEK_END);
01033     fseek (ifp, ftell(ifp)/2, SEEK_SET);
01034     getbits(-1);
01035       }
01036     }
01037     for (col=0; col < raw_width; col++) {
01038       i = getbits(12);
01039       if ((unsigned) (col-left_margin) < width)
01040     BAYER(row,col-left_margin) = i;
01041       if (tiff_compress == 34713 && (col % 10) == 9)
01042     getbits(8);
01043     }
01044   }
01045 }
01046 
01047 /*
01048    Figure out if a NEF file is compressed.  These fancy heuristics
01049    are only needed for the D100, thanks to a bug in some cameras
01050    that tags all images as "compressed".
01051  */
01052 int CLASS nikon_is_compressed()
01053 {
01054   uchar test[256];
01055   int i;
01056 
01057   if (tiff_compress != 34713)
01058     return 0;
01059   if (strcmp(model,"D100"))
01060     return 1;
01061   fseek (ifp, data_offset, SEEK_SET);
01062   fread (test, 1, 256, ifp);
01063   for (i=15; i < 256; i+=16)
01064     if (test[i]) return 1;
01065   return 0;
01066 }
01067 
01068 /*
01069    Returns 1 for a Coolpix 995, 0 for anything else.
01070  */
01071 int CLASS nikon_e995()
01072 {
01073   int i, histo[256];
01074   const uchar often[] = { 0x00, 0x55, 0xaa, 0xff };
01075 
01076   memset (histo, 0, sizeof histo);
01077   fseek (ifp, -2000, SEEK_END);
01078   for (i=0; i < 2000; i++)
01079     histo[fgetc(ifp)]++;
01080   for (i=0; i < 4; i++)
01081     if (histo[often[i]] < 200)
01082       return 0;
01083   return 1;
01084 }
01085 
01086 /*
01087    Returns 1 for a Coolpix 2100, 0 for anything else.
01088  */
01089 int CLASS nikon_e2100()
01090 {
01091   uchar t[12];
01092   int i;
01093 
01094   fseek (ifp, 0, SEEK_SET);
01095   for (i=0; i < 1024; i++) {
01096     fread (t, 1, 12, ifp);
01097     if (((t[2] & t[4] & t[7] & t[9]) >> 4
01098     & t[1] & t[6] & t[8] & t[11] & 3) != 3)
01099       return 0;
01100   }
01101   return 1;
01102 }
01103 
01104 void CLASS nikon_3700()
01105 {
01106   int bits, i;
01107   uchar dp[24];
01108   static const struct {
01109     int bits;
01110     char make[12], model[15];
01111   } table[] = {
01112     { 0x00, "PENTAX",  "Optio 33WR" },
01113     { 0x03, "NIKON",   "E3200" },
01114     { 0x32, "NIKON",   "E3700" },
01115     { 0x33, "OLYMPUS", "C740UZ" } };
01116 
01117   fseek (ifp, 3072, SEEK_SET);
01118   fread (dp, 1, 24, ifp);
01119   bits = (dp[8] & 3) << 4 | (dp[20] & 3);
01120   for (i=0; i < sizeof table / sizeof *table; i++)
01121     if (bits == table[i].bits) {
01122       strcpy (make,  table[i].make );
01123       strcpy (model, table[i].model);
01124     }
01125 }
01126 
01127 /*
01128    Separates a Minolta DiMAGE Z2 from a Nikon E4300.
01129  */
01130 int CLASS minolta_z2()
01131 {
01132   int i;
01133   char tail[424];
01134 
01135   fseek (ifp, -sizeof tail, SEEK_END);
01136   fread (tail, 1, sizeof tail, ifp);
01137   for (i=0; i < sizeof tail; i++)
01138     if (tail[i]) return 1;
01139   return 0;
01140 }
01141 
01142 /* Here raw_width is in bytes, not pixels. */
01143 void CLASS nikon_e900_load_raw()
01144 {
01145   int offset=0, irow, row, col;
01146 
01147   for (irow=0; irow < height; irow++) {
01148     row = irow * 2 % height;
01149     if (row == 1)
01150       offset = - (-offset & -4096);
01151     fseek (ifp, offset, SEEK_SET);
01152     offset += raw_width;
01153     getbits(-1);
01154     for (col=0; col < width; col++)
01155       BAYER(row,col) = getbits(10);
01156   }
01157 }
01158 
01159 void CLASS nikon_e2100_load_raw()
01160 {
01161   uchar   data[3456], *dp;
01162   ushort pixel[2304], *pix;
01163   int row, col;
01164 
01165   for (row=0; row <= height; row+=2) {
01166     if (row == height) {
01167       fseek (ifp, ((width==1616) << 13) - (-ftell(ifp) & -2048), SEEK_SET);
01168       row = 1;
01169     }
01170     fread (data, 1, width*3/2, ifp);
01171     for (dp=data, pix=pixel; pix < pixel+width; dp+=12, pix+=8) {
01172       pix[0] = (dp[2] >> 4) + (dp[ 3] << 4);
01173       pix[1] = (dp[2] << 8) +  dp[ 1];
01174       pix[2] = (dp[7] >> 4) + (dp[ 0] << 4);
01175       pix[3] = (dp[7] << 8) +  dp[ 6];
01176       pix[4] = (dp[4] >> 4) + (dp[ 5] << 4);
01177       pix[5] = (dp[4] << 8) +  dp[11];
01178       pix[6] = (dp[9] >> 4) + (dp[10] << 4);
01179       pix[7] = (dp[9] << 8) +  dp[ 8];
01180     }
01181     for (col=0; col < width; col++)
01182       BAYER(row,col) = (pixel[col] & 0xfff);
01183   }
01184 }
01185 
01186 /*
01187    The Fuji Super CCD is just a Bayer grid rotated 45 degrees.
01188  */
01189 void CLASS fuji_load_raw()
01190 {
01191   ushort *pixel;
01192   int row, col, r, c;
01193 
01194   fseek (ifp, (top_margin*raw_width + left_margin) * 2, SEEK_CUR);
01195   pixel = (ushort *) calloc (raw_width, sizeof *pixel);
01196   merror (pixel, "fuji_load_raw()");
01197   for (row=0; row < raw_height; row++) {
01198     read_shorts (pixel, raw_width);
01199     for (col=0; col < fuji_width << !fuji_layout; col++) {
01200       if (fuji_layout) {
01201     r = fuji_width - 1 - col + (row >> 1);
01202     c = col + ((row+1) >> 1);
01203       } else {
01204     r = fuji_width - 1 + row - (col >> 1);
01205     c = row + ((col+1) >> 1);
01206       }
01207       BAYER(r,c) = pixel[col];
01208     }
01209   }
01210   free (pixel);
01211 }
01212 
01213 void CLASS jpeg_thumb (FILE *tfp)
01214 {
01215   char *thumb = (char *) malloc (thumb_length);
01216   merror (thumb, "jpeg_thumb()");
01217   fread  (thumb, 1, thumb_length, ifp);
01218   thumb[0] = 0xff;
01219   fwrite (thumb, 1, thumb_length, tfp);
01220   free (thumb);
01221 }
01222 
01223 void CLASS ppm_thumb (FILE *tfp)
01224 {
01225   char *thumb;
01226   thumb_length = thumb_width*thumb_height*3;
01227   thumb = (char *) malloc (thumb_length);
01228   merror (thumb, "ppm_thumb()");
01229   fprintf (tfp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
01230   fread  (thumb, 1, thumb_length, ifp);
01231   fwrite (thumb, 1, thumb_length, tfp);
01232   free (thumb);
01233 }
01234 
01235 void CLASS layer_thumb (FILE *tfp)
01236 {
01237   int i, c;
01238   char *thumb, map[][4] = { "012","102" };
01239 
01240   colors = thumb_misc >> 5 & 7;
01241   thumb_length = thumb_width*thumb_height;
01242   thumb = (char *) malloc (thumb_length*colors);
01243   merror (thumb, "layer_thumb()");
01244   fprintf (tfp, "P%d\n%d %d\n255\n",
01245     5 + (colors >> 1), thumb_width, thumb_height);
01246   fread (thumb, thumb_length, colors, ifp);
01247   for (i=0; i < thumb_length; i++)
01248     FORCC putc (thumb[i+thumb_length*(map[thumb_misc >> 8][c]-'0')], tfp);
01249   free (thumb);
01250 }
01251 
01252 void CLASS rollei_thumb (FILE *tfp)
01253 {
01254   int i, size = thumb_width * thumb_height;
01255   ushort *thumb = (ushort *) calloc (size, 2);
01256   merror (thumb, "rollei_thumb()");
01257   fprintf (tfp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
01258   read_shorts (thumb, size);
01259   for (i=0; i < size; i++) {
01260     putc (thumb[i] << 3, tfp);
01261     putc (thumb[i] >> 5  << 2, tfp);
01262     putc (thumb[i] >> 11 << 3, tfp);
01263   }
01264   free (thumb);
01265 }
01266 
01267 void CLASS rollei_load_raw()
01268 {
01269   uchar pixel[10];
01270   unsigned iten=0, isix, i, buffer=0, row, col, todo[16];
01271 
01272   isix = raw_width * raw_height * 5 / 8;
01273   while (fread (pixel, 1, 10, ifp) == 10) {
01274     for (i=0; i < 10; i+=2) {
01275       todo[i]   = iten++;
01276       todo[i+1] = pixel[i] << 8 | pixel[i+1];
01277       buffer    = pixel[i] >> 2 | buffer << 6;
01278     }
01279     for (   ; i < 16; i+=2) {
01280       todo[i]   = isix++;
01281       todo[i+1] = buffer >> (14-i)*5;
01282     }
01283     for (i=0; i < 16; i+=2) {
01284       row = todo[i] / raw_width - top_margin;
01285       col = todo[i] % raw_width - left_margin;
01286       if (row < height && col < width)
01287     BAYER(row,col) = (todo[i+1] & 0x3ff);
01288     }
01289   }
01290   maximum = 0x3ff;
01291 }
01292 
01293 int CLASS bayer (unsigned row, unsigned col)
01294 {
01295   return (row < height && col < width) ? BAYER(row,col) : 0;
01296 }
01297 
01298 void CLASS phase_one_flat_field (int is_float, int nc)
01299 {
01300   ushort head[8];
01301   unsigned wide, y, x, c, rend, cend, row, col;
01302   float *mrow, num, mult[4];
01303 
01304   read_shorts (head, 8);
01305   wide = head[2] / head[4];
01306   mrow = (float *) calloc (nc*wide, sizeof *mrow);
01307   merror (mrow, "phase_one_flat_field()");
01308   for (y=0; y < head[3] / head[5]; y++) {
01309     for (x=0; x < wide; x++)
01310       for (c=0; c < nc; c+=2) {
01311     num = is_float ? getreal(11) : get2()/32768.0;
01312     if (y==0) mrow[c*wide+x] = num;
01313     else mrow[(c+1)*wide+x] = (num - mrow[c*wide+x]) / head[5];
01314       }
01315     if (y==0) continue;
01316     rend = head[1]-top_margin + y*head[5];
01317     for (row = rend-head[5]; row < height && row < rend; row++) {
01318       for (x=1; x < wide; x++) {
01319     for (c=0; c < nc; c+=2) {
01320       mult[c] = mrow[c*wide+x-1];
01321       mult[c+1] = (mrow[c*wide+x] - mult[c]) / head[4];
01322     }
01323     cend = head[0]-left_margin + x*head[4];
01324     for (col = cend-head[4]; col < width && col < cend; col++) {
01325       c = nc > 2 ? FC(row,col) : 0;
01326       if (!(c & 1)) {
01327         c = BAYER(row,col) * mult[c];
01328         BAYER(row,col) = LIM(c,0,65535);
01329       }
01330       for (c=0; c < nc; c+=2)
01331         mult[c] += mult[c+1];
01332     }
01333       }
01334       for (x=0; x < wide; x++)
01335     for (c=0; c < nc; c+=2)
01336       mrow[c*wide+x] += mrow[(c+1)*wide+x];
01337     }
01338   }
01339   free (mrow);
01340 }
01341 
01342 void CLASS phase_one_correct()
01343 {
01344   unsigned entries, tag, data, save, col, row, type;
01345   int len, i, j, k, cip, val[4], dev[4], sum, max;
01346   int head[9], diff, mindiff=INT_MAX, off_412=0;
01347   static const signed char dir[12][2] =
01348     { {-1,-1}, {-1,1}, {1,-1}, {1,1}, {-2,0}, {0,-2}, {0,2}, {2,0},
01349       {-2,-2}, {-2,2}, {2,-2}, {2,2} };
01350   float poly[8], num, cfrac, frac, mult[2], *yval[2];
01351   ushort curve[0x10000], *xval[2];
01352 
01353   if (shrink || !meta_length) return;
01354   if (verbose) fprintf (stderr, "Phase One correction...\n");
01355   fseek (ifp, meta_offset, SEEK_SET);
01356   order = get2();
01357   fseek (ifp, 6, SEEK_CUR);
01358   fseek (ifp, meta_offset+get4(), SEEK_SET);
01359   entries = get4();  get4();
01360   while (entries--) {
01361     tag  = get4();
01362     len  = get4();
01363     data = get4();
01364     save = ftell(ifp);
01365     fseek (ifp, meta_offset+data, SEEK_SET);
01366     if (tag == 0x419) {             /* Polynomial curve */
01367       for (get4(), i=0; i < 8; i++)
01368     poly[i] = getreal(11);
01369       poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1;
01370       for (i=0; i < 0x10000; i++) {
01371     num = (poly[5]*i + poly[3])*i + poly[1];
01372     curve[i] = LIM(num,0,65535);
01373       } goto apply;             /* apply to right half */
01374     } else if (tag == 0x41a) {          /* Polynomial curve */
01375       for (i=0; i < 4; i++)
01376     poly[i] = getreal(11);
01377       for (i=0; i < 0x10000; i++) {
01378     for (num=0, j=4; j--; )
01379       num = num * i + poly[j];
01380     curve[i] = LIM(num+i,0,65535);
01381       } apply:                  /* apply to whole image */
01382       for (row=0; row < height; row++)
01383     for (col = (tag & 1)*ph1.split_col; col < width; col++)
01384       BAYER(row,col) = curve[BAYER(row,col)];
01385     } else if (tag == 0x400) {          /* Sensor defects */
01386       while ((len -= 8) >= 0) {
01387     col  = get2() - left_margin;
01388     row  = get2() - top_margin;
01389     type = get2(); get2();
01390     if (col >= width) continue;
01391     if (type == 131)            /* Bad column */
01392       for (row=0; row < height; row++)
01393         if (FC(row,col) == 1) {
01394           for (sum=i=0; i < 4; i++)
01395         sum += val[i] = bayer (row+dir[i][0], col+dir[i][1]);
01396           for (max=i=0; i < 4; i++) {
01397         dev[i] = abs((val[i] << 2) - sum);
01398         if (dev[max] < dev[i]) max = i;
01399           }
01400           BAYER(row,col) = (sum - val[max])/3.0 + 0.5;
01401         } else {
01402           for (sum=0, i=8; i < 12; i++)
01403         sum += bayer (row+dir[i][0], col+dir[i][1]);
01404           BAYER(row,col) = 0.5 + sum * 0.0732233 +
01405         (bayer(row,col-2) + bayer(row,col+2)) * 0.3535534;
01406         }
01407     else if (type == 129) {         /* Bad pixel */
01408       if (row >= height) continue;
01409       j = (FC(row,col) != 1) * 4;
01410       for (sum=0, i=j; i < j+8; i++)
01411         sum += bayer (row+dir[i][0], col+dir[i][1]);
01412       BAYER(row,col) = (sum + 4) >> 3;
01413     }
01414       }
01415     } else if (tag == 0x401) {          /* All-color flat fields */
01416       phase_one_flat_field (1, 2);
01417     } else if (tag == 0x416 || tag == 0x410) {
01418       phase_one_flat_field (0, 2);
01419     } else if (tag == 0x40b) {          /* Red+blue flat field */
01420       phase_one_flat_field (0, 4);
01421     } else if (tag == 0x412) {
01422       fseek (ifp, 36, SEEK_CUR);
01423       diff = abs (get2() - ph1.tag_21a);
01424       if (mindiff > diff) {
01425     mindiff = diff;
01426     off_412 = ftell(ifp) - 38;
01427       }
01428     }
01429     fseek (ifp, save, SEEK_SET);
01430   }
01431   if (off_412) {
01432     fseek (ifp, off_412, SEEK_SET);
01433     for (i=0; i < 9; i++) head[i] = get4();
01434     yval[0] = (float *) calloc (head[1]*head[3] + head[2]*head[4], 6);
01435     merror (yval[0], "phase_one_correct()");
01436     yval[1] = (float  *) (yval[0] + head[1]*head[3]);
01437     xval[0] = (ushort *) (yval[1] + head[2]*head[4]);
01438     xval[1] = (ushort *) (xval[0] + head[1]*head[3]);
01439     get2();
01440     for (i=0; i < 2; i++)
01441       for (j=0; j < head[i+1]*head[i+3]; j++)
01442     yval[i][j] = getreal(11);
01443     for (i=0; i < 2; i++)
01444       for (j=0; j < head[i+1]*head[i+3]; j++)
01445     xval[i][j] = get2();
01446     for (row=0; row < height; row++)
01447       for (col=0; col < width; col++) {
01448     cfrac = (float) col * head[3] / raw_width;
01449     cfrac -= cip = cfrac;
01450     num = BAYER(row,col) * 0.5;
01451     for (i=cip; i < cip+2; i++) {
01452       for (k=j=0; j < head[1]; j++)
01453         if (num < xval[0][k = head[1]*i+j]) break;
01454       frac = (j == 0 || j == head[1]) ? 0 :
01455         (xval[0][k] - num) / (xval[0][k] - xval[0][k-1]);
01456       mult[i-cip] = yval[0][k-1] * frac + yval[0][k] * (1-frac);
01457     }
01458     i = ((mult[0] * (1-cfrac) + mult[1] * cfrac)
01459         * (row + top_margin) + num) * 2;
01460     BAYER(row,col) = LIM(i,0,65535);
01461       }
01462     free (yval[0]);
01463   }
01464 }
01465 
01466 void CLASS phase_one_load_raw()
01467 {
01468   int row, col, a, b;
01469   ushort *pixel, akey, bkey, mask;
01470 
01471   fseek (ifp, ph1.key_off, SEEK_SET);
01472   akey = get2();
01473   bkey = get2();
01474   mask = ph1.format == 1 ? 0x5555:0x1354;
01475   fseek (ifp, data_offset + top_margin*raw_width*2, SEEK_SET);
01476   pixel = (ushort *) calloc (raw_width, sizeof *pixel);
01477   merror (pixel, "phase_one_load_raw()");
01478   for (row=0; row < height; row++) {
01479     read_shorts (pixel, raw_width);
01480     for (col=0; col < raw_width; col+=2) {
01481       a = pixel[col+0] ^ akey;
01482       b = pixel[col+1] ^ bkey;
01483       pixel[col+0] = (a & mask) | (b & ~mask);
01484       pixel[col+1] = (b & mask) | (a & ~mask);
01485     }
01486     for (col=0; col < width; col++)
01487       BAYER(row,col) = pixel[col+left_margin];
01488   }
01489   free (pixel);
01490   phase_one_correct();
01491 }
01492 
01493 unsigned CLASS ph1_bits (int nbits)
01494 {
01495   static UINT64 bitbuf=0;
01496   static int vbits=0;
01497 
01498   if (nbits == 0)
01499     return bitbuf = vbits = 0;
01500   if (vbits < nbits) {
01501     bitbuf = bitbuf << 32 | (unsigned) get4();
01502     vbits += 32;
01503   }
01504   vbits -= nbits;
01505   return bitbuf << (64 - nbits - vbits) >> (64 - nbits);
01506 }
01507 
01508 void CLASS phase_one_load_raw_c()
01509 {
01510   static const int length[] = { 8,7,6,9,11,10,5,12,14,13 };
01511   int *offset, len[2], pred[2], row, col, i, j;
01512   ushort *pixel;
01513   short (*black)[2];
01514 
01515   pixel = (ushort *) calloc (raw_width + raw_height*4, 2);
01516   merror (pixel, "phase_one_load_raw_c()");
01517   offset = (int *) (pixel + raw_width);
01518   fseek (ifp, strip_offset, SEEK_SET);
01519   for (row=0; row < raw_height; row++)
01520     offset[row] = get4();
01521   black = (short (*)[2]) offset + raw_height;
01522   fseek (ifp, ph1.black_off, SEEK_SET);
01523   if (ph1.black_off)
01524     read_shorts ((ushort *) black[0], raw_height*2);
01525   for (i=0; i < 256; i++)
01526     curve[i] = i*i / 3.969 + 0.5;
01527   for (row=0; row < raw_height; row++) {
01528     fseek (ifp, data_offset + offset[row], SEEK_SET);
01529     ph1_bits(0);
01530     pred[0] = pred[1] = 0;
01531     for (col=0; col < raw_width; col++) {
01532       if (col >= (raw_width & -8))
01533     len[0] = len[1] = 14;
01534       else if ((col & 7) == 0)
01535     for (i=0; i < 2; i++) {
01536       for (j=0; j < 5 && !ph1_bits(1); j++);
01537       if (j--) len[i] = length[j*2 + ph1_bits(1)];
01538     }
01539       if ((i = len[col & 1]) == 14)
01540     pixel[col] = pred[col & 1] = ph1_bits(16);
01541       else
01542     pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1));
01543       if (ph1.format == 5 && pixel[col] < 256)
01544     pixel[col] = curve[pixel[col]];
01545     }
01546     if ((unsigned) (row-top_margin) < height)
01547       for (col=0; col < width; col++) {
01548     i = (pixel[col+left_margin] << 2)
01549         - ph1.black + black[row][col >= ph1.split_col];
01550     if (i > 0) BAYER(row-top_margin,col) = i;
01551       }
01552   }
01553   free (pixel);
01554   phase_one_correct();
01555   maximum = 0xfffc - ph1.black;
01556 }
01557 
01558 void CLASS leaf_hdr_load_raw()
01559 {
01560   ushort *pixel;
01561   unsigned tile=0, r, c, row, col;
01562 
01563   pixel = (ushort *) calloc (raw_width, sizeof *pixel);
01564   merror (pixel, "leaf_hdr_load_raw()");
01565   for (c=0; c < tiff_samples; c++) {
01566     for (r=0; r < raw_height; r++) {
01567       if (r % tile_length == 0) {
01568     fseek (ifp, data_offset + 4*tile++, SEEK_SET);
01569     fseek (ifp, get4() + 2*left_margin, SEEK_SET);
01570       }
01571       if (filters && c != shot_select) continue;
01572       read_shorts (pixel, raw_width);
01573       if ((row = r - top_margin) >= height) continue;
01574       for (col=0; col < width; col++)
01575     if (filters)  BAYER(row,col) = pixel[col];
01576     else image[row*width+col][c] = pixel[col];
01577     }
01578   }
01579   free (pixel);
01580   if (!filters) {
01581     maximum = 0xffff;
01582     raw_color = 1;
01583   }
01584 }
01585 
01586 void CLASS sinar_4shot_load_raw()
01587 {
01588   ushort *pixel;
01589   unsigned shot, row, col, r, c;
01590 
01591   pixel = (ushort *) calloc (raw_width, sizeof *pixel);
01592   merror (pixel, "sinar_4shot_load_raw()");
01593   for (shot=0; shot < 4; shot++) {
01594     fseek (ifp, data_offset + shot*4, SEEK_SET);
01595     fseek (ifp, get4(), SEEK_SET);
01596     for (row=0; row < raw_height; row++) {
01597       read_shorts (pixel, raw_width);
01598       if ((r = row-top_margin - (shot >> 1 & 1)) >= height) continue;
01599       for (col=0; col < raw_width; col++) {
01600     if ((c = col-left_margin - (shot & 1)) >= width) continue;
01601         image[r*width+c][FC(row,col)] = pixel[col];
01602       }
01603     }
01604   }
01605   free (pixel);
01606   filters = 0;
01607 }
01608 
01609 void CLASS imacon_full_load_raw()
01610 {
01611   int row, col;
01612 
01613   for (row=0; row < height; row++)
01614     for (col=0; col < width; col++)
01615       read_shorts (image[row*width+col], 3);
01616 }
01617 
01618 /* Here raw_width is in bytes, not pixels. */
01619 void CLASS packed_12_load_raw()
01620 {
01621   int row, col;
01622 
01623   getbits(-1);
01624   for (row=0; row < height; row++) {
01625     for (col=0; col < width; col++)
01626       BAYER(row,col) = getbits(12);
01627     for (col = width*3/2; col < raw_width; col++)
01628       getbits(8);
01629   }
01630 }
01631 
01632 void CLASS unpacked_load_raw()
01633 {
01634   ushort *pixel;
01635   int row, col;
01636 
01637   fseek (ifp, (top_margin*raw_width + left_margin) * 2, SEEK_CUR);
01638   pixel = (ushort *) calloc (raw_width, sizeof *pixel);
01639   merror (pixel, "unpacked_load_raw()");
01640   for (row=0; row < height; row++) {
01641     read_shorts (pixel, raw_width);
01642     for (col=0; col < width; col++)
01643       BAYER2(row,col) = pixel[col];
01644   }
01645   free (pixel);
01646 }
01647 
01648 void CLASS olympus_e300_load_raw()
01649 {
01650   uchar  *data,  *dp;
01651   ushort *pixel, *pix;
01652   int dwide, row, col;
01653 
01654   dwide = raw_width * 16 / 10;
01655   data = (uchar *) malloc (dwide + raw_width*2);
01656   merror (data, "olympus_e300_load_raw()");
01657   pixel = (ushort *) (data + dwide);
01658   for (row=0; row < height; row++) {
01659     fread (data, 1, dwide, ifp);
01660     for (dp=data, pix=pixel; pix < pixel+raw_width; dp+=3, pix+=2) {
01661       if (((dp-data) & 15) == 15) dp++;
01662       pix[0] = dp[1] << 8 | dp[0];
01663       pix[1] = dp[2] << 4 | dp[1] >> 4;
01664     }
01665     for (col=0; col < width; col++)
01666       BAYER(row,col) = (pixel[col] & 0xfff);
01667   }
01668   free (data);
01669   maximum = 0xfff;
01670   black >>= 4;
01671 }
01672 
01673 void CLASS olympus_cseries_load_raw()
01674 {
01675   int irow, row, col;
01676 
01677   for (irow=0; irow < height; irow++) {
01678     row = irow * 2 % height + irow / (height/2);
01679     if (row < 2) {
01680       fseek (ifp, data_offset - row*(-width*height*3/4 & -2048), SEEK_SET);
01681       getbits(-1);
01682     }
01683     for (col=0; col < width; col++)
01684       BAYER(row,col) = getbits(12);
01685   }
01686   black >>= 4;
01687 }
01688 
01689 void CLASS minolta_rd175_load_raw()
01690 {
01691   uchar pixel[768];
01692   unsigned irow, box, row, col;
01693 
01694   for (irow=0; irow < 1481; irow++) {
01695     fread (pixel, 1, 768, ifp);
01696     box = irow / 82;
01697     row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box-12)*2);
01698     switch (irow) {
01699       case 1477: case 1479: continue;
01700       case 1476: row = 984; break;
01701       case 1480: row = 985; break;
01702       case 1478: row = 985; box = 1;
01703     }
01704     if ((box < 12) && (box & 1)) {
01705       for (col=0; col < 1533; col++, row ^= 1)
01706     if (col != 1) BAYER(row,col) = (col+1) & 2 ?
01707            pixel[col/2-1] + pixel[col/2+1] : pixel[col/2] << 1;
01708       BAYER(row,1)    = pixel[1]   << 1;
01709       BAYER(row,1533) = pixel[765] << 1;
01710     } else
01711       for (col=row & 1; col < 1534; col+=2)
01712     BAYER(row,col) = pixel[col/2] << 1;
01713   }
01714   maximum = 0xff << 1;
01715 }
01716 
01717 void CLASS eight_bit_load_raw()
01718 {
01719   uchar *pixel;
01720   int row, col;
01721 
01722   pixel = (uchar *) calloc (raw_width, sizeof *pixel);
01723   merror (pixel, "eight_bit_load_raw()");
01724   for (row=0; row < height; row++) {
01725     fread (pixel, 1, raw_width, ifp);
01726     for (col=0; col < width; col++)
01727       BAYER(row,col) = pixel[col];
01728   }
01729   free (pixel);
01730   maximum = 0xff;
01731 }
01732 
01733 void CLASS casio_qv5700_load_raw()
01734 {
01735   uchar  data[3232],  *dp;
01736   ushort pixel[2576], *pix;
01737   int row, col;
01738 
01739   for (row=0; row < height; row++) {
01740     fread (data, 1, 3232, ifp);
01741     for (dp=data, pix=pixel; dp < data+3220; dp+=5, pix+=4) {
01742       pix[0] = (dp[0] << 2) + (dp[1] >> 6);
01743       pix[1] = (dp[1] << 4) + (dp[2] >> 4);
01744       pix[2] = (dp[2] << 6) + (dp[3] >> 2);
01745       pix[3] = (dp[3] << 8) + (dp[4]     );
01746     }
01747     for (col=0; col < width; col++)
01748       BAYER(row,col) = (pixel[col] & 0x3ff);
01749   }
01750   maximum = 0x3fc;
01751 }
01752 
01753 void CLASS nucore_load_raw()
01754 {
01755   ushort *pixel;
01756   int irow, row, col;
01757 
01758   pixel = (ushort *) calloc (width, 2);
01759   merror (pixel, "nucore_load_raw()");
01760   for (irow=0; irow < height; irow++) {
01761     read_shorts (pixel, width);
01762     row = irow/2 + height/2 * (irow & 1);
01763     for (col=0; col < width; col++)
01764       BAYER(row,col) = pixel[col];
01765   }
01766   free (pixel);
01767 }
01768 
01769 const int * CLASS make_decoder_int (const int *source, int level)
01770 {
01771   struct decode *cur;
01772 
01773   cur = free_decode++;
01774   if (level < source[0]) {
01775     cur->branch[0] = free_decode;
01776     source = make_decoder_int (source, level+1);
01777     cur->branch[1] = free_decode;
01778     source = make_decoder_int (source, level+1);
01779   } else {
01780     cur->leaf = source[1];
01781     source += 2;
01782   }
01783   return source;
01784 }
01785 
01786 int CLASS radc_token (int tree)
01787 {
01788   int t;
01789   static struct decode *dstart[18], *dindex;
01790   static const int *s, source[] = {
01791     1,1, 2,3, 3,4, 4,2, 5,7, 6,5, 7,6, 7,8,
01792     1,0, 2,1, 3,3, 4,4, 5,2, 6,7, 7,6, 8,5, 8,8,
01793     2,1, 2,3, 3,0, 3,2, 3,4, 4,6, 5,5, 6,7, 6,8,
01794     2,0, 2,1, 2,3, 3,2, 4,4, 5,6, 6,7, 7,5, 7,8,
01795     2,1, 2,4, 3,0, 3,2, 3,3, 4,7, 5,5, 6,6, 6,8,
01796     2,3, 3,1, 3,2, 3,4, 3,5, 3,6, 4,7, 5,0, 5,8,
01797     2,3, 2,6, 3,0, 3,1, 4,4, 4,5, 4,7, 5,2, 5,8,
01798     2,4, 2,7, 3,3, 3,6, 4,1, 4,2, 4,5, 5,0, 5,8,
01799     2,6, 3,1, 3,3, 3,5, 3,7, 3,8, 4,0, 5,2, 5,4,
01800     2,0, 2,1, 3,2, 3,3, 4,4, 4,5, 5,6, 5,7, 4,8,
01801     1,0, 2,2, 2,-2,
01802     1,-3, 1,3,
01803     2,-17, 2,-5, 2,5, 2,17,
01804     2,-7, 2,2, 2,9, 2,18,
01805     2,-18, 2,-9, 2,-2, 2,7,
01806     2,-28, 2,28, 3,-49, 3,-9, 3,9, 4,49, 5,-79, 5,79,
01807     2,-1, 2,13, 2,26, 3,39, 4,-16, 5,55, 6,-37, 6,76,
01808     2,-26, 2,-13, 2,1, 3,-39, 4,16, 5,-55, 6,-76, 6,37
01809   };
01810 
01811   if (free_decode == first_decode)
01812     for (s=source, t=0; t < 18; t++) {
01813       dstart[t] = free_decode;
01814       s = make_decoder_int (s, 0);
01815     }
01816   if (tree == 18) {
01817     if (kodak_cbpp == 243)
01818       return (getbits(6) << 2) + 2; /* most DC50 photos */
01819     else
01820       return (getbits(5) << 3) + 4; /* DC40, Fotoman Pixtura */
01821   }
01822   for (dindex = dstart[tree]; dindex->branch[0]; )
01823     dindex = dindex->branch[getbits(1)];
01824   return dindex->leaf;
01825 }
01826 
01827 #define FORYX for (y=1; y < 3; y++) for (x=col+1; x >= col; x--)
01828 
01829 #define PREDICTOR (c ? (buf[c][y-1][x] + buf[c][y][x+1]) / 2 \
01830 : (buf[c][y-1][x+1] + 2*buf[c][y-1][x] + buf[c][y][x+1]) / 4)
01831 
01832 void CLASS kodak_radc_load_raw()
01833 {
01834   int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val;
01835   short last[3] = { 16,16,16 }, mul[3], buf[3][3][386];
01836 
01837   init_decoder();
01838   getbits(-1);
01839   for (i=0; i < sizeof(buf)/sizeof(short); i++)
01840     buf[0][0][i] = 2048;
01841   for (row=0; row < height; row+=4) {
01842     FORC3 mul[c] = getbits(6);
01843     FORC3 {
01844       val = ((0x1000000/last[c] + 0x7ff) >> 12) * mul[c];
01845       s = val > 65564 ? 10:12;
01846       x = ~(-1 << (s-1));
01847       val <<= 12-s;
01848       for (i=0; i < sizeof(buf[0])/sizeof(short); i++)
01849     buf[c][0][i] = (buf[c][0][i] * val + x) >> s;
01850       last[c] = mul[c];
01851       for (r=0; r <= !c; r++) {
01852     buf[c][1][width/2] = buf[c][2][width/2] = mul[c] << 7;
01853     for (tree=1, col=width/2; col > 0; ) {
01854       if ((tree = radc_token(tree))) {
01855         col -= 2;
01856         if (tree == 8)
01857           FORYX buf[c][y][x] = radc_token(tree+10) * mul[c];
01858         else
01859           FORYX buf[c][y][x] = radc_token(tree+10) * 16 + PREDICTOR;
01860       } else
01861         do {
01862           nreps = (col > 2) ? radc_token(9) + 1 : 1;
01863           for (rep=0; rep < 8 && rep < nreps && col > 0; rep++) {
01864         col -= 2;
01865         FORYX buf[c][y][x] = PREDICTOR;
01866         if (rep & 1) {
01867           step = radc_token(10) << 4;
01868           FORYX buf[c][y][x] += step;
01869         }
01870           }
01871         } while (nreps == 9);
01872     }
01873     for (y=0; y < 2; y++)
01874       for (x=0; x < width/2; x++) {
01875         val = (buf[c][y+1][x] << 4) / mul[c];
01876         if (val < 0) val = 0;
01877         if (c)
01878           BAYER(row+y*2+c-1,x*2+2-c) = val;
01879         else
01880           BAYER(row+r*2+y,x*2+y) = val;
01881       }
01882     memcpy (buf[c][0]+!c, buf[c][2], sizeof buf[c][0]-2*!c);
01883       }
01884     }
01885     for (y=row; y < row+4; y++)
01886       for (x=0; x < width; x++)
01887     if ((x+y) & 1) {
01888       val = (BAYER(y,x)-2048)*2 + (BAYER(y,x-1)+BAYER(y,x+1))/2;
01889       if (val < 0) val = 0;
01890       BAYER(y,x) = val;
01891     }
01892   }
01893   maximum = 10000;
01894 }
01895 
01896 #undef FORYX
01897 #undef PREDICTOR
01898 
01899 #ifdef NO_JPEG
01900 void CLASS kodak_jpeg_load_raw() {}
01901 #else
01902 
01903 METHODDEF(boolean)
01904 fill_input_buffer (j_decompress_ptr cinfo)
01905 {
01906   static uchar jpeg_buffer[4096];
01907   size_t nbytes;
01908 
01909   nbytes = fread (jpeg_buffer, 1, 4096, ifp);
01910   swab (jpeg_buffer, jpeg_buffer, nbytes);
01911   cinfo->src->next_input_byte = jpeg_buffer;
01912   cinfo->src->bytes_in_buffer = nbytes;
01913   return TRUE;
01914 }
01915 
01916 void CLASS kodak_jpeg_load_raw()
01917 {
01918   struct jpeg_decompress_struct cinfo;
01919   struct jpeg_error_mgr jerr;
01920   JSAMPARRAY buf;
01921   JSAMPLE (*pixel)[3];
01922   int row, col;
01923 
01924   cinfo.err = jpeg_std_error (&jerr);
01925   jpeg_create_decompress (&cinfo);
01926   jpeg_stdio_src (&cinfo, ifp);
01927   cinfo.src->fill_input_buffer = fill_input_buffer;
01928   jpeg_read_header (&cinfo, TRUE);
01929   jpeg_start_decompress (&cinfo);
01930   if ((cinfo.output_width      != width  ) ||
01931       (cinfo.output_height*2   != height ) ||
01932       (cinfo.output_components != 3      )) {
01933     fprintf (stderr, "%s: incorrect JPEG dimensions\n", ifname);
01934     jpeg_destroy_decompress (&cinfo);
01935     longjmp (failure, 3);
01936   }
01937   buf = (*cinfo.mem->alloc_sarray)
01938         ((j_common_ptr) &cinfo, JPOOL_IMAGE, width*3, 1);
01939 
01940   while (cinfo.output_scanline < cinfo.output_height) {
01941     row = cinfo.output_scanline * 2;
01942     jpeg_read_scanlines (&cinfo, buf, 1);
01943     pixel = (JSAMPLE (*)[3]) buf[0];
01944     for (col=0; col < width; col+=2) {
01945       BAYER(row+0,col+0) = pixel[col+0][1] << 1;
01946       BAYER(row+1,col+1) = pixel[col+1][1] << 1;
01947       BAYER(row+0,col+1) = pixel[col][0] + pixel[col+1][0];
01948       BAYER(row+1,col+0) = pixel[col][2] + pixel[col+1][2];
01949     }
01950   }
01951   jpeg_finish_decompress (&cinfo);
01952   jpeg_destroy_decompress (&cinfo);
01953   maximum = 0xff << 1;
01954 }
01955 #endif
01956 
01957 void CLASS kodak_dc120_load_raw()
01958 {
01959   static const int mul[4] = { 162, 192, 187,  92 };
01960   static const int add[4] = {   0, 636, 424, 212 };
01961   uchar pixel[848];
01962   int row, shift, col;
01963 
01964   for (row=0; row < height; row++) {
01965     fread (pixel, 848, 1, ifp);
01966     shift = row * mul[row & 3] + add[row & 3];
01967     for (col=0; col < width; col++)
01968       BAYER(row,col) = (ushort) pixel[(col + shift) % 848];
01969   }
01970   maximum = 0xff;
01971 }
01972 
01973 void CLASS kodak_easy_load_raw()
01974 {
01975   uchar *pixel;
01976   unsigned row, col, val;
01977 
01978   if (raw_width > width)
01979     black = 0;
01980   pixel = (uchar *) calloc (raw_width, sizeof *pixel);
01981   merror (pixel, "kodak_easy_load_raw()");
01982   for (row=0; row < height; row++) {
01983     fread (pixel, 1, raw_width, ifp);
01984     for (col=0; col < raw_width; col++) {
01985       val = curve[pixel[col]];
01986       if ((unsigned) (col-left_margin) < width)
01987         BAYER(row,col-left_margin) = val;
01988       else black += val;
01989     }
01990   }
01991   free (pixel);
01992   if (raw_width > width)
01993     black /= (raw_width - width) * height;
01994   if (!strncmp(model,"DC2",3))
01995     black = 0;
01996   maximum = curve[0xff];
01997 }
01998 
01999 void CLASS kodak_262_load_raw()
02000 {
02001   static const uchar kodak_tree[2][26] =
02002   { { 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 },
02003     { 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 } };
02004   struct decode *decode[2];
02005   uchar *pixel;
02006   int *strip, ns, i, row, col, chess, pi=0, pi1, pi2, pred, val;
02007 
02008   init_decoder();
02009   for (i=0; i < 2; i++) {
02010     decode[i] = free_decode;
02011     make_decoder (kodak_tree[i], 0);
02012   }
02013   ns = (raw_height+63) >> 5;
02014   pixel = (uchar *) malloc (raw_width*32 + ns*4);
02015   merror (pixel, "kodak_262_load_raw()");
02016   strip = (int *) (pixel + raw_width*32);
02017   order = 0x4d4d;
02018   for (i=0; i < ns; i++)
02019     strip[i] = get4();
02020   for (row=0; row < raw_height; row++) {
02021     if ((row & 31) == 0) {
02022       fseek (ifp, strip[row >> 5], SEEK_SET);
02023       getbits(-1);
02024       pi = 0;
02025     }
02026     for (col=0; col < raw_width; col++) {
02027       chess = (row + col) & 1;
02028       pi1 = chess ? pi-2           : pi-raw_width-1;
02029       pi2 = chess ? pi-2*raw_width : pi-raw_width+1;
02030       if (col <= chess) pi1 = -1;
02031       if (pi1 < 0) pi1 = pi2;
02032       if (pi2 < 0) pi2 = pi1;
02033       if (pi1 < 0 && col > 1) pi1 = pi2 = pi-2;
02034       pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1;
02035       pixel[pi] = pred + ljpeg_diff (decode[chess]);
02036       val = curve[pixel[pi++]];
02037       if ((unsigned) (col-left_margin) < width)
02038     BAYER(row,col-left_margin) = val;
02039       else black += val;
02040     }
02041   }
02042   free (pixel);
02043   if (raw_width > width)
02044     black /= (raw_width - width) * height;
02045 }
02046 
02047 int CLASS kodak_65000_decode (short *out, int bsize)
02048 {
02049   uchar c, blen[768];
02050   ushort raw[6];
02051   INT64 bitbuf=0;
02052   int save, bits=0, i, j, len, diff;
02053 
02054   save = ftell(ifp);
02055   bsize = (bsize + 3) & -4;
02056   for (i=0; i < bsize; i+=2) {
02057     c = fgetc(ifp);
02058     if ((blen[i  ] = c & 15) > 12 ||
02059     (blen[i+1] = c >> 4) > 12 ) {
02060       fseek (ifp, save, SEEK_SET);
02061       for (i=0; i < bsize; i+=8) {
02062     read_shorts (raw, 6);
02063     out[i  ] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12;
02064     out[i+1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12;
02065     for (j=0; j < 6; j++)
02066       out[i+2+j] = raw[j] & 0xfff;
02067       }
02068       return 1;
02069     }
02070   }
02071   if ((bsize & 7) == 4) {
02072     bitbuf  = fgetc(ifp) << 8;
02073     bitbuf += fgetc(ifp);
02074     bits = 16;
02075   }
02076   for (i=0; i < bsize; i++) {
02077     len = blen[i];
02078     if (bits < len) {
02079       for (j=0; j < 32; j+=8)
02080     bitbuf += (INT64) fgetc(ifp) << (bits+(j^8));
02081       bits += 32;
02082     }
02083     diff = bitbuf & (0xffff >> (16-len));
02084     bitbuf >>= len;
02085     bits -= len;
02086     if ((diff & (1 << (len-1))) == 0)
02087       diff -= (1 << len) - 1;
02088     out[i] = diff;
02089   }
02090   return 0;
02091 }
02092 
02093 void CLASS kodak_65000_load_raw()
02094 {
02095   short buf[256];
02096   int row, col, len, pred[2], ret, i;
02097 
02098   for (row=0; row < height; row++)
02099     for (col=0; col < width; col+=256) {
02100       pred[0] = pred[1] = 0;
02101       len = MIN (256, width-col);
02102       ret = kodak_65000_decode (buf, len);
02103       for (i=0; i < len; i++)
02104     BAYER(row,col+i) = curve[ret ? buf[i] : (pred[i & 1] += buf[i])];
02105     }
02106 }
02107 
02108 void CLASS kodak_ycbcr_load_raw()
02109 {
02110   short buf[384], *bp;
02111   int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3];
02112   ushort *ip;
02113 
02114   for (row=0; row < height; row+=2)
02115     for (col=0; col < width; col+=128) {
02116       len = MIN (128, width-col);
02117       kodak_65000_decode (buf, len*3);
02118       y[0][1] = y[1][1] = cb = cr = 0;
02119       for (bp=buf, i=0; i < len; i+=2, bp+=2) {
02120     cb += bp[4];
02121     cr += bp[5];
02122     rgb[1] = -((cb + cr + 2) >> 2);
02123     rgb[2] = rgb[1] + cb;
02124     rgb[0] = rgb[1] + cr;
02125     for (j=0; j < 2; j++)
02126       for (k=0; k < 2; k++) {
02127         y[j][k] = y[j][k^1] + *bp++;
02128         ip = image[(row+j)*width + col+i+k];
02129         FORC3 ip[c] = curve[LIM(y[j][k]+rgb[c], 0, 0xfff)];
02130       }
02131       }
02132     }
02133 }
02134 
02135 void CLASS kodak_rgb_load_raw()
02136 {
02137   short buf[768], *bp;
02138   int row, col, len, c, i, rgb[3];
02139   ushort *ip=image[0];
02140 
02141   for (row=0; row < height; row++)
02142     for (col=0; col < width; col+=256) {
02143       len = MIN (256, width-col);
02144       kodak_65000_decode (buf, len*3);
02145       memset (rgb, 0, sizeof rgb);
02146       for (bp=buf, i=0; i < len; i++, ip+=4)
02147     FORC3 ip[c] = (rgb[c] += *bp++) & 0xfff;
02148     }
02149 }
02150 
02151 void CLASS kodak_thumb_load_raw()
02152 {
02153   int row, col;
02154   colors = thumb_misc >> 5;
02155   for (row=0; row < height; row++)
02156     for (col=0; col < width; col++)
02157       read_shorts (image[row*width+col], colors);
02158   maximum = (1 << (thumb_misc & 31)) - 1;
02159 }
02160 
02161 void CLASS sony_decrypt (unsigned *data, int len, int start, int key)
02162 {
02163   static unsigned pad[128], p;
02164 
02165   if (start) {
02166     for (p=0; p < 4; p++)
02167       pad[p] = key = key * 48828125 + 1;
02168     pad[3] = pad[3] << 1 | (pad[0]^pad[2]) >> 31;
02169     for (p=4; p < 127; p++)
02170       pad[p] = (pad[p-4]^pad[p-2]) << 1 | (pad[p-3]^pad[p-1]) >> 31;
02171     for (p=0; p < 127; p++)
02172       pad[p] = htonl(pad[p]);
02173   }
02174   while (len--)
02175     *data++ ^= pad[p++ & 127] = pad[(p+1) & 127] ^ pad[(p+65) & 127];
02176 }
02177 
02178 void CLASS sony_load_raw()
02179 {
02180   uchar head[40];
02181   ushort *pixel;
02182   unsigned i, key, row, col;
02183 
02184   fseek (ifp, 200896, SEEK_SET);
02185   fseek (ifp, (unsigned) fgetc(ifp)*4 - 1, SEEK_CUR);
02186   order = 0x4d4d;
02187   key = get4();
02188   fseek (ifp, 164600, SEEK_SET);
02189   fread (head, 1, 40, ifp);
02190   sony_decrypt ((unsigned int *) head, 10, 1, key);
02191   for (i=26; i-- > 22; )
02192     key = key << 8 | head[i];
02193   fseek (ifp, data_offset, SEEK_SET);
02194   pixel = (ushort *) calloc (raw_width, sizeof *pixel);
02195   merror (pixel, "sony_load_raw()");
02196   for (row=0; row < height; row++) {
02197     fread (pixel, 2, raw_width, ifp);
02198     sony_decrypt ((unsigned int *) pixel, raw_width/2, !row, key);
02199     for (col=9; col < left_margin; col++)
02200       black += ntohs(pixel[col]);
02201     for (col=0; col < width; col++)
02202       BAYER(row,col) = ntohs(pixel[col+left_margin]);
02203   }
02204   free (pixel);
02205   if (left_margin > 9)
02206     black /= (left_margin-9) * height;
02207   maximum = 0x3ff0;
02208 }
02209 
02210 void CLASS sony_arw_load_raw()
02211 {
02212   int col, row, len, diff, sum=0;
02213 
02214   getbits(-1);
02215   for (col = raw_width; col--; )
02216     for (row=0; row < raw_height+1; row+=2) {
02217       if (row == raw_height) row = 1;
02218       len = 4 - getbits(2);
02219       if (len == 3 && getbits(1)) len = 0;
02220       if (len == 4)
02221     while (len < 17 && !getbits(1)) len++;
02222       diff = getbits(len);
02223       if ((diff & (1 << (len-1))) == 0)
02224     diff -= (1 << len) - 1;
02225       sum += diff;
02226       if (row < height) BAYER(row,col) = sum;
02227     }
02228 }
02229 
02230 #define HOLE(row) ((holes >> (((row) - raw_height) & 7)) & 1)
02231 
02232 /* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */
02233 void CLASS smal_decode_segment (unsigned seg[2][2], int holes)
02234 {
02235   uchar hist[3][13] = {
02236     { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 },
02237     { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 },
02238     { 3, 3, 0, 0, 63,     47,     31,     15,    0 } };
02239   int low, high=0xff, carry=0, nbits=8;
02240   int s, count, bin, next, i, sym[3];
02241   uchar diff, pred[]={0,0};
02242   ushort data=0, range=0;
02243   unsigned pix, row, col;
02244 
02245   fseek (ifp, seg[0][1]+1, SEEK_SET);
02246   getbits(-1);
02247   for (pix=seg[0][0]; pix < seg[1][0]; pix++) {
02248     for (s=0; s < 3; s++) {
02249       data = data << nbits | getbits(nbits);
02250       if (carry < 0)
02251     carry = (nbits += carry+1) < 1 ? nbits-1 : 0;
02252       while (--nbits >= 0)
02253     if ((data >> nbits & 0xff) == 0xff) break;
02254       if (nbits > 0)
02255       data = ((data & ((1 << (nbits-1)) - 1)) << 1) |
02256     ((data + (((data & (1 << (nbits-1)))) << 1)) & (-1 << nbits));
02257       if (nbits >= 0) {
02258     data += getbits(1);
02259     carry = nbits - 8;
02260       }
02261       count = ((((data-range+1) & 0xffff) << 2) - 1) / (high >> 4);
02262       for (bin=0; hist[s][bin+5] > count; bin++);
02263         low = hist[s][bin+5] * (high >> 4) >> 2;
02264       if (bin) high = hist[s][bin+4] * (high >> 4) >> 2;
02265       high -= low;
02266       for (nbits=0; high << nbits < 128; nbits++);
02267       range = (range+low) << nbits;
02268       high <<= nbits;
02269       next = hist[s][1];
02270       if (++hist[s][2] > hist[s][3]) {
02271     next = (next+1) & hist[s][0];
02272     hist[s][3] = (hist[s][next+4] - hist[s][next+5]) >> 2;
02273     hist[s][2] = 1;
02274       }
02275       if (hist[s][hist[s][1]+4] - hist[s][hist[s][1]+5] > 1) {
02276     if (bin < hist[s][1])
02277       for (i=bin; i < hist[s][1]; i++) hist[s][i+5]--;
02278     else if (next <= bin)
02279       for (i=hist[s][1]; i < bin; i++) hist[s][i+5]++;
02280       }
02281       hist[s][1] = next;
02282       sym[s] = bin;
02283     }
02284     diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3);
02285     if (sym[0] & 4)
02286       diff = diff ? -diff : 0x80;
02287     if (ftell(ifp) + 12 >= seg[1][1])
02288       diff = 0;
02289     pred[pix & 1] += diff;
02290     row = pix / raw_width - top_margin;
02291     col = pix % raw_width - left_margin;
02292     if (row < height && col < width)
02293       BAYER(row,col) = pred[pix & 1];
02294     if (!(pix & 1) && HOLE(row)) pix += 2;
02295   }
02296   maximum = 0xff;
02297 }
02298 
02299 void CLASS smal_v6_load_raw()
02300 {
02301   unsigned seg[2][2];
02302 
02303   fseek (ifp, 16, SEEK_SET);
02304   seg[0][0] = 0;
02305   seg[0][1] = get2();
02306   seg[1][0] = raw_width * raw_height;
02307   seg[1][1] = INT_MAX;
02308   smal_decode_segment (seg, 0);
02309   use_gamma = 0;
02310 }
02311 
02312 int CLASS median4 (int *p)
02313 {
02314   int min, max, sum, i;
02315 
02316   min = max = sum = p[0];
02317   for (i=1; i < 4; i++) {
02318     sum += p[i];
02319     if (min > p[i]) min = p[i];
02320     if (max < p[i]) max = p[i];
02321   }
02322   return (sum - min - max) >> 1;
02323 }
02324 
02325 void CLASS fill_holes (int holes)
02326 {
02327   int row, col, val[4];
02328 
02329   for (row=2; row < height-2; row++) {
02330     if (!HOLE(row)) continue;
02331     for (col=1; col < width-1; col+=4) {
02332       val[0] = BAYER(row-1,col-1);
02333       val[1] = BAYER(row-1,col+1);
02334       val[2] = BAYER(row+1,col-1);
02335       val[3] = BAYER(row+1,col+1);
02336       BAYER(row,col) = median4(val);
02337     }
02338     for (col=2; col < width-2; col+=4)
02339       if (HOLE(row-2) || HOLE(row+2))
02340     BAYER(row,col) = (BAYER(row,col-2) + BAYER(row,col+2)) >> 1;
02341       else {
02342     val[0] = BAYER(row,col-2);
02343     val[1] = BAYER(row,col+2);
02344     val[2] = BAYER(row-2,col);
02345     val[3] = BAYER(row+2,col);
02346     BAYER(row,col) = median4(val);
02347       }
02348   }
02349 }
02350 
02351 void CLASS smal_v9_load_raw()
02352 {
02353   unsigned seg[256][2], offset, nseg, holes, i;
02354 
02355   fseek (ifp, 67, SEEK_SET);
02356   offset = get4();
02357   nseg = fgetc(ifp);
02358   fseek (ifp, offset, SEEK_SET);
02359   for (i=0; i < nseg*2; i++)
02360     seg[0][i] = get4() + data_offset*(i & 1);
02361   fseek (ifp, 78, SEEK_SET);
02362   holes = fgetc(ifp);
02363   fseek (ifp, 88, SEEK_SET);
02364   seg[nseg][0] = raw_height * raw_width;
02365   seg[nseg][1] = get4() + data_offset;
02366   for (i=0; i < nseg; i++)
02367     smal_decode_segment (seg+i, holes);
02368   if (holes) fill_holes (holes);
02369 }
02370 
02371 /* BEGIN GPL BLOCK */
02372 
02373 void CLASS foveon_decoder (unsigned size, unsigned code)
02374 {
02375   static unsigned huff[1024];
02376   struct decode *cur;
02377   int i, len;
02378 
02379   if (!code) {
02380     for (i=0; i < size; i++)
02381       huff[i] = get4();
02382     init_decoder();
02383   }
02384   cur = free_decode++;
02385   if (free_decode > first_decode+2048) {
02386     fprintf (stderr, "%s: decoder table overflow\n", ifname);
02387     longjmp (failure, 2);
02388   }
02389   if (code)
02390     for (i=0; i < size; i++)
02391       if (huff[i] == code) {
02392     cur->leaf = i;
02393     return;
02394       }
02395   if ((len = code >> 27) > 26) return;
02396   code = (len+1) << 27 | (code & 0x3ffffff) << 1;
02397 
02398   cur->branch[0] = free_decode;
02399   foveon_decoder (size, code);
02400   cur->branch[1] = free_decode;
02401   foveon_decoder (size, code+1);
02402 }
02403 
02404 void CLASS foveon_thumb (FILE *tfp)
02405 {
02406   int bwide, row, col, bit=-1, c, i;
02407   char *buf;
02408   struct decode *dindex;
02409   short pred[3];
02410   unsigned bitbuf=0;
02411 
02412   bwide = get4();
02413   fprintf (tfp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
02414   if (bwide > 0) {
02415     buf = (char *) malloc (bwide);
02416     merror (buf, "foveon_thumb()");
02417     for (row=0; row < thumb_height; row++) {
02418       fread  (buf, 1, bwide, ifp);
02419       fwrite (buf, 3, thumb_width, tfp);
02420     }
02421     free (buf);
02422     return;
02423   }
02424   foveon_decoder (256, 0);
02425 
02426   for (row=0; row < thumb_height; row++) {
02427     memset (pred, 0, sizeof pred);
02428     if (!bit) get4();
02429     for (col=bit=0; col < thumb_width; col++)
02430       FORC3 {
02431     for (dindex=first_decode; dindex->branch[0]; ) {
02432       if ((bit = (bit-1) & 31) == 31)
02433         for (i=0; i < 4; i++)
02434           bitbuf = (bitbuf << 8) + fgetc(ifp);
02435       dindex = dindex->branch[bitbuf >> bit & 1];
02436     }
02437     pred[c] += dindex->leaf;
02438     fputc (pred[c], tfp);
02439       }
02440   }
02441 }
02442 
02443 void CLASS foveon_load_camf()
02444 {
02445   unsigned key, i, val;
02446 
02447   fseek (ifp, meta_offset, SEEK_SET);
02448   key = get4();
02449   fread (meta_data, 1, meta_length, ifp);
02450   for (i=0; i < meta_length; i++) {
02451     key = (key * 1597 + 51749) % 244944;
02452     val = key * (INT64) 301593171 >> 24;
02453     meta_data[i] ^= ((((key << 8) - val) >> 1) + val) >> 17;
02454   }
02455 }
02456 
02457 void CLASS foveon_load_raw()
02458 {
02459   struct decode *dindex;
02460   short diff[1024], pred[3];
02461   unsigned bitbuf=0;
02462   int fixed, row, col, bit=-1, c, i;
02463 
02464   fixed = get4();
02465   read_shorts ((ushort *) diff, 1024);
02466   if (!fixed) foveon_decoder (1024, 0);
02467 
02468   for (row=0; row < height; row++) {
02469     memset (pred, 0, sizeof pred);
02470     if (!bit && !fixed) get4();
02471     for (col=bit=0; col < width; col++) {
02472       if (fixed) {
02473     bitbuf = get4();
02474     FORC3 pred[2-c] += diff[bitbuf >> c*10 & 0x3ff];
02475       }
02476       else FORC3 {
02477     for (dindex=first_decode; dindex->branch[0]; ) {
02478       if ((bit = (bit-1) & 31) == 31)
02479         for (i=0; i < 4; i++)
02480           bitbuf = (bitbuf << 8) + fgetc(ifp);
02481       dindex = dindex->branch[bitbuf >> bit & 1];
02482     }
02483     pred[c] += diff[dindex->leaf];
02484       }
02485       FORC3 image[row*width+col][c] = pred[c];
02486     }
02487   }
02488   if (document_mode)
02489     for (i=0; i < height*width*4; i++)
02490       if ((short) image[0][i] < 0) image[0][i] = 0;
02491   foveon_load_camf();
02492 }
02493 
02494 const char * CLASS foveon_camf_param (const char *block, const char *param)
02495 {
02496   unsigned idx, num;
02497   char *pos, *cp, *dp;
02498 
02499   for (idx=0; idx < meta_length; idx += sget4(pos+8)) {
02500     pos = meta_data + idx;
02501     if (strncmp (pos, "CMb", 3)) break;
02502     if (pos[3] != 'P') continue;
02503     if (strcmp (block, pos+sget4(pos+12))) continue;
02504     cp = pos + sget4(pos+16);
02505     num = sget4(cp);
02506     dp = pos + sget4(cp+4);
02507     while (num--) {
02508       cp += 8;
02509       if (!strcmp (param, dp+sget4(cp)))
02510     return dp+sget4(cp+4);
02511     }
02512   }
02513   return NULL;
02514 }
02515 
02516 void * CLASS foveon_camf_matrix (int dim[3], const char *name)
02517 {
02518   unsigned i, idx, type, ndim, size, *mat;
02519   char *pos, *cp, *dp;
02520 
02521   for (idx=0; idx < meta_length; idx += sget4(pos+8)) {
02522     pos = meta_data + idx;
02523     if (strncmp (pos, "CMb", 3)) break;
02524     if (pos[3] != 'M') continue;
02525     if (strcmp (name, pos+sget4(pos+12))) continue;
02526     dim[0] = dim[1] = dim[2] = 1;
02527     cp = pos + sget4(pos+16);
02528     type = sget4(cp);
02529     if ((ndim = sget4(cp+4)) > 3) break;
02530     dp = pos + sget4(cp+8);
02531     for (i=ndim; i--; ) {
02532       cp += 12;
02533       dim[i] = sget4(cp);
02534     }
02535     if ((size = dim[0]*dim[1]*dim[2]) > meta_length/4) break;
02536     mat = (unsigned *) malloc (size * 4);
02537     merror (mat, "foveon_camf_matrix()");
02538     for (i=0; i < size; i++)
02539       if (type && type != 6)
02540     mat[i] = sget4(dp + i*4);
02541       else
02542     mat[i] = sget4(dp + i*2) & 0xffff;
02543     return mat;
02544   }
02545   fprintf (stderr, "%s: \"%s\" matrix not found!\n", ifname, name);
02546   return NULL;
02547 }
02548 
02549 int CLASS foveon_fixed (void *ptr, int size, const char *name)
02550 {
02551   void *dp;
02552   int dim[3];
02553 
02554   dp = foveon_camf_matrix (dim, name);
02555   if (!dp) return 0;
02556   memcpy (ptr, dp, size*4);
02557   free (dp);
02558   return 1;
02559 }
02560 
02561 float CLASS foveon_avg (short *pix, int range[2], float cfilt)
02562 {
02563   int i;
02564   float val, min=FLT_MAX, max=-FLT_MAX, sum=0;
02565 
02566   for (i=range[0]; i <= range[1]; i++) {
02567     sum += val = pix[i*4] + (pix[i*4]-pix[(i-1)*4]) * cfilt;
02568     if (min > val) min = val;
02569     if (max < val) max = val;
02570   }
02571   return (sum - min - max) / (range[1] - range[0] - 1);
02572 }
02573 
02574 short * CLASS foveon_make_curve (double max, double mul, double filt)
02575 {
02576   short *curve;
02577   int i, size;
02578   double x;
02579 
02580   if (!filt) filt = 0.8;
02581   size = 4*M_PI*max / filt;
02582   curve = (short *) calloc (size+1, sizeof *curve);
02583   merror (curve, "foveon_make_curve()");
02584   curve[0] = size;
02585   for (i=0; i < size; i++) {
02586     x = i*filt/max/4;
02587     curve[i+1] = (cos(x)+1)/2 * tanh(i*filt/mul) * mul + 0.5;
02588   }
02589   return curve;
02590 }
02591 
02592 void CLASS foveon_make_curves
02593     (short **curvep, float dq[3], float div[3], float filt)
02594 {
02595   double mul[3], max=0;
02596   int c;
02597 
02598   FORC3 mul[c] = dq[c]/div[c];
02599   FORC3 if (max < mul[c]) max = mul[c];
02600   FORC3 curvep[c] = foveon_make_curve (max, mul[c], filt);
02601 }
02602 
02603 int CLASS foveon_apply_curve (short *curve, int i)
02604 {
02605   if (abs(i) >= curve[0]) return 0;
02606   return i < 0 ? -curve[1-i] : curve[1+i];
02607 }
02608 
02609 #define image ((short (*)[4]) image)
02610 
02611 void CLASS foveon_interpolate()
02612 {
02613   static const short hood[] = { -1,-1, -1,0, -1,1, 0,-1, 0,1, 1,-1, 1,0, 1,1 };
02614   short *pix, prev[3], *curve[8], (*shrink)[3];
02615   float cfilt=0, ddft[3][3][2], ppm[3][3][3];
02616   float cam_xyz[3][3], correct[3][3], last[3][3], trans[3][3];
02617   float chroma_dq[3], color_dq[3], diag[3][3], div[3];
02618   float (*black)[3], (*sgain)[3], (*sgrow)[3];
02619   float fsum[3], val, frow, num;
02620   int row, col, c, i, j, diff, sgx, irow, sum, min, max, limit;
02621   int dim[3], dscr[2][2], dstb[4], (*smrow[7])[3], total[4], ipix[3];
02622   int work[3][3], smlast, smred, smred_p=0, dev[3];
02623   int satlev[3], keep[4], active[4];
02624   unsigned *badpix;
02625   double dsum=0, trsum[3];
02626   char str[128];
02627   const char* cp;
02628 
02629   if (verbose)
02630     fprintf (stderr, "Foveon interpolation...\n");
02631 
02632   foveon_fixed (dscr, 4, "DarkShieldColRange");
02633   foveon_fixed (ppm[0][0], 27, "PostPolyMatrix");
02634   foveon_fixed (satlev, 3, "SaturationLevel");
02635   foveon_fixed (keep, 4, "KeepImageArea");
02636   foveon_fixed (active, 4, "ActiveImageArea");
02637   foveon_fixed (chroma_dq, 3, "ChromaDQ");
02638   foveon_fixed (color_dq, 3,
02639     foveon_camf_param ("IncludeBlocks", "ColorDQ") ?
02640         "ColorDQ" : "ColorDQCamRGB");
02641   if (foveon_camf_param ("IncludeBlocks", "ColumnFilter"))
02642          foveon_fixed (&cfilt, 1, "ColumnFilter");
02643 
02644   memset (ddft, 0, sizeof ddft);
02645   if (!foveon_camf_param ("IncludeBlocks", "DarkDrift")
02646      || !foveon_fixed (ddft[1][0], 12, "DarkDrift"))
02647     for (i=0; i < 2; i++) {
02648       foveon_fixed (dstb, 4, i ? "DarkShieldBottom":"DarkShieldTop");
02649       for (row = dstb[1]; row <= dstb[3]; row++)
02650     for (col = dstb[0]; col <= dstb[2]; col++)
02651       FORC3 ddft[i+1][c][1] += (short) image[row*width+col][c];
02652       FORC3 ddft[i+1][c][1] /= (dstb[3]-dstb[1]+1) * (dstb[2]-dstb[0]+1);
02653     }
02654 
02655   if (!(cp = foveon_camf_param ("WhiteBalanceIlluminants", model2)))
02656   { fprintf (stderr, "%s: Invalid white balance \"%s\"\n", ifname, model2);
02657     return; }
02658   foveon_fixed (cam_xyz, 9, cp);
02659   foveon_fixed (correct, 9,
02660     foveon_camf_param ("WhiteBalanceCorrections", model2));
02661   memset (last, 0, sizeof last);
02662   for (i=0; i < 3; i++)
02663     for (j=0; j < 3; j++)
02664       FORC3 last[i][j] += correct[i][c] * cam_xyz[c][j];
02665 
02666   sprintf (str, "%sRGBNeutral", model2);
02667   if (foveon_camf_param ("IncludeBlocks", str))
02668     foveon_fixed (div, 3, str);
02669   else {
02670     #define LAST(x,y) last[(i+x)%3][(c+y)%3]
02671     for (i=0; i < 3; i++)
02672       FORC3 diag[c][i] = LAST(1,1)*LAST(2,2) - LAST(1,2)*LAST(2,1);
02673     #undef LAST
02674     FORC3 div[c] = diag[c][0]*0.3127 + diag[c][1]*0.329 + diag[c][2]*0.3583;
02675   }
02676   num = 0;
02677   FORC3 if (num < div[c]) num = div[c];
02678   FORC3 div[c] /= num;
02679 
02680   memset (trans, 0, sizeof trans);
02681   for (i=0; i < 3; i++)
02682     for (j=0; j < 3; j++)
02683       FORC3 trans[i][j] += rgb_cam[i][c] * last[c][j] * div[j];
02684   FORC3 trsum[c] = trans[c][0] + trans[c][1] + trans[c][2];
02685   dsum = (6*trsum[0] + 11*trsum[1] + 3*trsum[2]) / 20;
02686   for (i=0; i < 3; i++)
02687     FORC3 last[i][c] = trans[i][c] * dsum / trsum[i];
02688   memset (trans, 0, sizeof trans);
02689   for (i=0; i < 3; i++)
02690     for (j=0; j < 3; j++)
02691       FORC3 trans[i][j] += (i==c ? 32 : -1) * last[c][j] / 30;
02692 
02693   foveon_make_curves (curve, color_dq, div, cfilt);
02694   FORC3 chroma_dq[c] /= 3;
02695   foveon_make_curves (curve+3, chroma_dq, div, cfilt);
02696   FORC3 dsum += chroma_dq[c] / div[c];
02697   curve[6] = foveon_make_curve (dsum, dsum, cfilt);
02698   curve[7] = foveon_make_curve (dsum*2, dsum*2, cfilt);
02699 
02700   sgain = (float (*)[3]) foveon_camf_matrix (dim, "SpatialGain");
02701   if (!sgain) return;
02702   sgrow = (float (*)[3]) calloc (dim[1], sizeof *sgrow);
02703   sgx = (width + dim[1]-2) / (dim[1]-1);
02704 
02705   black = (float (*)[3]) calloc (height, sizeof *black);
02706   for (row=0; row < height; row++) {
02707     for (i=0; i < 6; i++)
02708       ddft[0][0][i] = ddft[1][0][i] +
02709     row / (height-1.0) * (ddft[2][0][i] - ddft[1][0][i]);
02710     FORC3 black[row][c] =
02711     ( foveon_avg (image[row*width]+c, dscr[0], cfilt) +
02712       foveon_avg (image[row*width]+c, dscr[1], cfilt) * 3
02713       - ddft[0][c][0] ) / 4 - ddft[0][c][1];
02714   }
02715   memcpy (black, black+8, sizeof *black*8);
02716   memcpy (black+height-11, black+height-22, 11*sizeof *black);
02717   memcpy (last, black, sizeof last);
02718 
02719   for (row=1; row < height-1; row++) {
02720     FORC3 if (last[1][c] > last[0][c]) {
02721     if (last[1][c] > last[2][c])
02722       black[row][c] = (last[0][c] > last[2][c]) ? last[0][c]:last[2][c];
02723       } else
02724     if (last[1][c] < last[2][c])
02725       black[row][c] = (last[0][c] < last[2][c]) ? last[0][c]:last[2][c];
02726     memmove (last, last+1, 2*sizeof last[0]);
02727     memcpy (last[2], black[row+1], sizeof last[2]);
02728   }
02729   FORC3 black[row][c] = (last[0][c] + last[1][c])/2;
02730   FORC3 black[0][c] = (black[1][c] + black[3][c])/2;
02731 
02732   val = 1 - exp(-1/24.0);
02733   memcpy (fsum, black, sizeof fsum);
02734   for (row=1; row < height; row++)
02735     FORC3 fsum[c] += black[row][c] =
02736     (black[row][c] - black[row-1][c])*val + black[row-1][c];
02737   memcpy (last[0], black[height-1], sizeof last[0]);
02738   FORC3 fsum[c] /= height;
02739   for (row = height; row--; )
02740     FORC3 last[0][c] = black[row][c] =
02741     (black[row][c] - fsum[c] - last[0][c])*val + last[0][c];
02742 
02743   memset (total, 0, sizeof total);
02744   for (row=2; row < height; row+=4)
02745     for (col=2; col < width; col+=4) {
02746       FORC3 total[c] += (short) image[row*width+col][c];
02747       total[3]++;
02748     }
02749   for (row=0; row < height; row++)
02750     FORC3 black[row][c] += fsum[c]/2 + total[c]/(total[3]*100.0);
02751 
02752   for (row=0; row < height; row++) {
02753     for (i=0; i < 6; i++)
02754       ddft[0][0][i] = ddft[1][0][i] +
02755     row / (height-1.0) * (ddft[2][0][i] - ddft[1][0][i]);
02756     pix = image[row*width];
02757     memcpy (prev, pix, sizeof prev);
02758     frow = row / (height-1.0) * (dim[2]-1);
02759     if ((irow = frow) == dim[2]-1) irow--;
02760     frow -= irow;
02761     for (i=0; i < dim[1]; i++)
02762       FORC3 sgrow[i][c] = sgain[ irow   *dim[1]+i][c] * (1-frow) +
02763               sgain[(irow+1)*dim[1]+i][c] *    frow;
02764     for (col=0; col < width; col++) {
02765       FORC3 {
02766     diff = pix[c] - prev[c];
02767     prev[c] = pix[c];
02768     ipix[c] = pix[c] + floor ((diff + (diff*diff >> 14)) * cfilt
02769         - ddft[0][c][1] - ddft[0][c][0] * ((float) col/width - 0.5)
02770         - black[row][c] );
02771       }
02772       FORC3 {
02773     work[0][c] = ipix[c] * ipix[c] >> 14;
02774     work[2][c] = ipix[c] * work[0][c] >> 14;
02775     work[1][2-c] = ipix[(c+1) % 3] * ipix[(c+2) % 3] >> 14;
02776       }
02777       FORC3 {
02778     for (val=i=0; i < 3; i++)
02779       for (  j=0; j < 3; j++)
02780         val += ppm[c][i][j] * work[i][j];
02781     ipix[c] = floor ((ipix[c] + floor(val)) *
02782         ( sgrow[col/sgx  ][c] * (sgx - col%sgx) +
02783           sgrow[col/sgx+1][c] * (col%sgx) ) / sgx / div[c]);
02784     if (ipix[c] > 32000) ipix[c] = 32000;
02785     pix[c] = ipix[c];
02786       }
02787       pix += 4;
02788     }
02789   }
02790   free (black);
02791   free (sgrow);
02792   free (sgain);
02793 
02794   if ((badpix = (unsigned int *) foveon_camf_matrix (dim, "BadPixels"))) {
02795     for (i=0; i < dim[0]; i++) {
02796       col = (badpix[i] >> 8 & 0xfff) - keep[0];
02797       row = (badpix[i] >> 20       ) - keep[1];
02798       if ((unsigned)(row-1) > height-3 || (unsigned)(col-1) > width-3)
02799     continue;
02800       memset (fsum, 0, sizeof fsum);
02801       for (sum=j=0; j < 8; j++)
02802     if (badpix[i] & (1 << j)) {
02803       FORC3 fsum[c] += (short)
02804         image[(row+hood[j*2])*width+col+hood[j*2+1]][c];
02805       sum++;
02806     }
02807       if (sum) FORC3 image[row*width+col][c] = fsum[c]/sum;
02808     }
02809     free (badpix);
02810   }
02811 
02812   /* Array for 5x5 Gaussian averaging of red values */
02813   smrow[6] = (int (*)[3]) calloc (width*5, sizeof **smrow);
02814   merror (smrow[6], "foveon_interpolate()");
02815   for (i=0; i < 5; i++)
02816     smrow[i] = smrow[6] + i*width;
02817 
02818   /* Sharpen the reds against these Gaussian averages */
02819   for (smlast=-1, row=2; row < height-2; row++) {
02820     while (smlast < row+2) {
02821       for (i=0; i < 6; i++)
02822     smrow[(i+5) % 6] = smrow[i];
02823       pix = image[++smlast*width+2];
02824       for (col=2; col < width-2; col++) {
02825     smrow[4][col][0] =
02826       (pix[0]*6 + (pix[-4]+pix[4])*4 + pix[-8]+pix[8] + 8) >> 4;
02827     pix += 4;
02828       }
02829     }
02830     pix = image[row*width+2];
02831     for (col=2; col < width-2; col++) {
02832       smred = ( 6 *  smrow[2][col][0]
02833           + 4 * (smrow[1][col][0] + smrow[3][col][0])
02834           +      smrow[0][col][0] + smrow[4][col][0] + 8 ) >> 4;
02835       if (col == 2)
02836     smred_p = smred;
02837       i = pix[0] + ((pix[0] - ((smred*7 + smred_p) >> 3)) >> 3);
02838       if (i > 32000) i = 32000;
02839       pix[0] = i;
02840       smred_p = smred;
02841       pix += 4;
02842     }
02843   }
02844 
02845   /* Adjust the brighter pixels for better linearity */
02846   min = 0xffff;
02847   FORC3 {
02848     i = satlev[c] / div[c];
02849     if (min > i) min = i;
02850   }
02851   limit = min * 9 >> 4;
02852   for (pix=image[0]; pix < image[height*width]; pix+=4) {
02853     if (pix[0] <= limit || pix[1] <= limit || pix[2] <= limit)
02854       continue;
02855     min = max = pix[0];
02856     for (c=1; c < 3; c++) {
02857       if (min > pix[c]) min = pix[c];
02858       if (max < pix[c]) max = pix[c];
02859     }
02860     if (min >= limit*2) {
02861       pix[0] = pix[1] = pix[2] = max;
02862     } else {
02863       i = 0x4000 - ((min - limit) << 14) / limit;
02864       i = 0x4000 - (i*i >> 14);
02865       i = i*i >> 14;
02866       FORC3 pix[c] += (max - pix[c]) * i >> 14;
02867     }
02868   }
02869 /*
02870    Because photons that miss one detector often hit another,
02871    the sum R+G+B is much less noisy than the individual colors.
02872    So smooth the hues without smoothing the total.
02873  */
02874   for (smlast=-1, row=2; row < height-2; row++) {
02875     while (smlast < row+2) {
02876       for (i=0; i < 6; i++)
02877     smrow[(i+5) % 6] = smrow[i];
02878       pix = image[++smlast*width+2];
02879       for (col=2; col < width-2; col++) {
02880     FORC3 smrow[4][col][c] = (pix[c-4]+2*pix[c]+pix[c+4]+2) >> 2;
02881     pix += 4;
02882       }
02883     }
02884     pix = image[row*width+2];
02885     for (col=2; col < width-2; col++) {
02886       FORC3 dev[c] = -foveon_apply_curve (curve[7], pix[c] -
02887     ((smrow[1][col][c] + 2*smrow[2][col][c] + smrow[3][col][c]) >> 2));
02888       sum = (dev[0] + dev[1] + dev[2]) >> 3;
02889       FORC3 pix[c] += dev[c] - sum;
02890       pix += 4;
02891     }
02892   }
02893   for (smlast=-1, row=2; row < height-2; row++) {
02894     while (smlast < row+2) {
02895       for (i=0; i < 6; i++)
02896     smrow[(i+5) % 6] = smrow[i];
02897       pix = image[++smlast*width+2];
02898       for (col=2; col < width-2; col++) {
02899     FORC3 smrow[4][col][c] =
02900         (pix[c-8]+pix[c-4]+pix[c]+pix[c+4]+pix[c+8]+2) >> 2;
02901     pix += 4;
02902       }
02903     }
02904     pix = image[row*width+2];
02905     for (col=2; col < width-2; col++) {
02906       for (total[3]=375, sum=60, c=0; c < 3; c++) {
02907     for (total[c]=i=0; i < 5; i++)
02908       total[c] += smrow[i][col][c];
02909     total[3] += total[c];
02910     sum += pix[c];
02911       }
02912       if (sum < 0) sum = 0;
02913       j = total[3] > 375 ? (sum << 16) / total[3] : sum * 174;
02914       FORC3 pix[c] += foveon_apply_curve (curve[6],
02915         ((j*total[c] + 0x8000) >> 16) - pix[c]);
02916       pix += 4;
02917     }
02918   }
02919 
02920   /* Transform the image to a different colorspace */
02921   for (pix=image[0]; pix < image[height*width]; pix+=4) {
02922     FORC3 pix[c] -= foveon_apply_curve (curve[c], pix[c]);
02923     sum = (pix[0]+pix[1]+pix[1]+pix[2]) >> 2;
02924     FORC3 pix[c] -= foveon_apply_curve (curve[c], pix[c]-sum);
02925     FORC3 {
02926       for (dsum=i=0; i < 3; i++)
02927     dsum += trans[c][i] * pix[i];
02928       if (dsum < 0)  dsum = 0;
02929       if (dsum > 24000) dsum = 24000;
02930       ipix[c] = dsum + 0.5;
02931     }
02932     FORC3 pix[c] = ipix[c];
02933   }
02934 
02935   /* Smooth the image bottom-to-top and save at 1/4 scale */
02936   shrink = (short (*)[3]) calloc ((width/4) * (height/4), sizeof *shrink);
02937   merror (shrink, "foveon_interpolate()");
02938   for (row = height/4; row--; )
02939     for (col=0; col < width/4; col++) {
02940       ipix[0] = ipix[1] = ipix[2] = 0;
02941       for (i=0; i < 4; i++)
02942     for (j=0; j < 4; j++)
02943       FORC3 ipix[c] += image[(row*4+i)*width+col*4+j][c];
02944       FORC3
02945     if (row+2 > height/4)
02946       shrink[row*(width/4)+col][c] = ipix[c] >> 4;
02947     else
02948       shrink[row*(width/4)+col][c] =
02949         (shrink[(row+1)*(width/4)+col][c]*1840 + ipix[c]*141 + 2048) >> 12;
02950     }
02951   /* From the 1/4-scale image, smooth right-to-left */
02952   for (row=0; row < (height & ~3); row++) {
02953     ipix[0] = ipix[1] = ipix[2] = 0;
02954     if ((row & 3) == 0)
02955       for (col = width & ~3 ; col--; )
02956     FORC3 smrow[0][col][c] = ipix[c] =
02957       (shrink[(row/4)*(width/4)+col/4][c]*1485 + ipix[c]*6707 + 4096) >> 13;
02958 
02959   /* Then smooth left-to-right */
02960     ipix[0] = ipix[1] = ipix[2] = 0;
02961     for (col=0; col < (width & ~3); col++)
02962       FORC3 smrow[1][col][c] = ipix[c] =
02963     (smrow[0][col][c]*1485 + ipix[c]*6707 + 4096) >> 13;
02964 
02965   /* Smooth top-to-bottom */
02966     if (row == 0)
02967       memcpy (smrow[2], smrow[1], sizeof **smrow * width);
02968     else
02969       for (col=0; col < (width & ~3); col++)
02970     FORC3 smrow[2][col][c] =
02971       (smrow[2][col][c]*6707 + smrow[1][col][c]*1485 + 4096) >> 13;
02972 
02973   /* Adjust the chroma toward the smooth values */
02974     for (col=0; col < (width & ~3); col++) {
02975       for (i=j=30, c=0; c < 3; c++) {
02976     i += smrow[2][col][c];
02977     j += image[row*width+col][c];
02978       }
02979       j = (j << 16) / i;
02980       for (sum=c=0; c < 3; c++) {
02981     ipix[c] = foveon_apply_curve (curve[c+3],
02982       ((smrow[2][col][c] * j + 0x8000) >> 16) - image[row*width+col][c]);
02983     sum += ipix[c];
02984       }
02985       sum >>= 3;
02986       FORC3 {
02987     i = image[row*width+col][c] + ipix[c] - sum;
02988     if (i < 0) i = 0;
02989     image[row*width+col][c] = i;
02990       }
02991     }
02992   }
02993   free (shrink);
02994   free (smrow[6]);
02995   for (i=0; i < 8; i++)
02996     free (curve[i]);
02997 
02998   /* Trim off the black border */
02999   active[1] -= keep[1];
03000   active[3] -= 2;
03001   i = active[2] - active[0];
03002   for (row=0; row < active[3]-active[1]; row++)
03003     memcpy (image[row*i], image[(row+active[1])*width+active[0]],
03004      i * sizeof *image);
03005   width = i;
03006   height = row;
03007 }
03008 #undef image
03009 
03010 /* END GPL BLOCK */
03011 
03012 /*
03013    Seach from the current directory up to the root looking for
03014    a ".badpixels" file, and fix those pixels now.
03015  */
03016 void CLASS bad_pixels()
03017 {
03018   FILE *fp=NULL;
03019   char *fname, *cp, line[128];
03020   int len, time, row, col, r, c, rad, tot, n, fixed=0;
03021 
03022   if (!filters) return;
03023   for (len=32 ; ; len *= 2) {
03024     fname = (char *) malloc (len);
03025     if (!fname) return;
03026     if (getcwd (fname, len-16)) break;
03027     free (fname);
03028     if (errno != ERANGE) return;
03029   }
03030 #if defined(WIN32) || defined(DJGPP)
03031   if (fname[1] == ':')
03032     memmove (fname, fname+2, len-2);
03033   for (cp=fname; *cp; cp++)
03034     if (*cp == '\\') *cp = '/';
03035 #endif
03036   cp = fname + strlen(fname);
03037   if (cp[-1] == '/') cp--;
03038   while (*fname == '/') {
03039     strcpy (cp, "/.badpixels");
03040     if ((fp = fopen (fname, "r"))) break;
03041     if (cp == fname) break;
03042     while (*--cp != '/');
03043   }
03044   free (fname);
03045   if (!fp) return;
03046   while (fgets (line, 128, fp)) {
03047     cp = strchr (line, '#');
03048     if (cp) *cp = 0;
03049     if (sscanf (line, "%d %d %d", &col, &row, &time) != 3) continue;
03050     if ((unsigned) col >= width || (unsigned) row >= height) continue;
03051     if (time > timestamp) continue;
03052     for (tot=n=0, rad=1; rad < 3 && n==0; rad++)
03053       for (r = row-rad; r <= row+rad; r++)
03054     for (c = col-rad; c <= col+rad; c++)
03055       if ((unsigned) r < height && (unsigned) c < width &&
03056         (r != row || c != col) && fc(r,c) == fc(row,col)) {
03057         tot += BAYER2(r,c);
03058         n++;
03059       }
03060     BAYER2(row,col) = tot/n;
03061     if (verbose) {
03062       if (!fixed++)
03063     fprintf (stderr, "Fixed bad pixels at:");
03064       fprintf (stderr, " %d,%d", col, row);
03065     }
03066   }
03067   if (fixed) fputc ('\n', stderr);
03068   fclose (fp);
03069 }
03070 
03071 void CLASS subtract (char *fname)
03072 {
03073   FILE *fp;
03074   int dim[3]={0,0,0}, comment=0, number=0, error=0, nd=0, c, row, col;
03075   ushort *pixel;
03076 
03077   if (!(fp = fopen (fname, "rb"))) {
03078     perror (fname);  return;
03079   }
03080   if (fgetc(fp) != 'P' || fgetc(fp) != '5') error = 1;
03081   while (!error && nd < 3 && (c = fgetc(fp)) != EOF) {
03082     if (c == '#')  comment = 1;
03083     if (c == '\n') comment = 0;
03084     if (comment) continue;
03085     if (isdigit(c)) number = 1;
03086     if (number) {
03087       if (isdigit(c)) dim[nd] = dim[nd]*10 + c -'0';
03088       else if (isspace(c)) {
03089     number = 0;  nd++;
03090       } else error = 1;
03091     }
03092   }
03093   if (error || nd < 3) {
03094     fprintf (stderr, "%s is not a valid PGM file!\n", fname);
03095     fclose (fp);  return;
03096   } else if (dim[0] != width || dim[1] != height || dim[2] != 65535) {
03097     fprintf (stderr, "%s has the wrong dimensions!\n", fname);
03098     fclose (fp);  return;
03099   }
03100   pixel = (ushort *) calloc (width, sizeof *pixel);
03101   merror (pixel, "subtract()");
03102   for (row=0; row < height; row++) {
03103     fread (pixel, 2, width, fp);
03104     for (col=0; col < width; col++)
03105       BAYER(row,col) = MAX (BAYER(row,col) - ntohs(pixel[col]), 0);
03106   }
03107   free (pixel);
03108   black = 0;
03109 }
03110 
03111 void CLASS pseudoinverse (double (*in)[3], double (*out)[3], int size)
03112 {
03113   double work[3][6], num;
03114   int i, j, k;
03115 
03116   for (i=0; i < 3; i++) {
03117     for (j=0; j < 6; j++)
03118       work[i][j] = j == i+3;
03119     for (j=0; j < 3; j++)
03120       for (k=0; k < size; k++)
03121     work[i][j] += in[k][i] * in[k][j];
03122   }
03123   for (i=0; i < 3; i++) {
03124     num = work[i][i];
03125     for (j=0; j < 6; j++)
03126       work[i][j] /= num;
03127     for (k=0; k < 3; k++) {
03128       if (k==i) continue;
03129       num = work[k][i];
03130       for (j=0; j < 6; j++)
03131     work[k][j] -= work[i][j] * num;
03132     }
03133   }
03134   for (i=0; i < size; i++)
03135     for (j=0; j < 3; j++)
03136       for (out[i][j]=k=0; k < 3; k++)
03137     out[i][j] += work[j][k+3] * in[i][k];
03138 }
03139 
03140 void CLASS cam_xyz_coeff (double cam_xyz[4][3])
03141 {
03142   double cam_rgb[4][3], inverse[4][3], num;
03143   int i, j, k;
03144 
03145   for (i=0; i < colors; i++)        /* Multiply out XYZ colorspace */
03146     for (j=0; j < 3; j++)
03147       for (cam_rgb[i][j] = k=0; k < 3; k++)
03148     cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j];
03149 
03150   for (i=0; i < colors; i++) {      /* Normalize cam_rgb so that */
03151     for (num=j=0; j < 3; j++)       /* cam_rgb * (1,1,1) is (1,1,1,1) */
03152       num += cam_rgb[i][j];
03153     for (j=0; j < 3; j++)
03154       cam_rgb[i][j] /= num;
03155     pre_mul[i] = 1 / num;
03156   }
03157   pseudoinverse (cam_rgb, inverse, colors);
03158   for (raw_color = i=0; i < 3; i++)
03159     for (j=0; j < colors; j++)
03160       rgb_cam[i][j] = inverse[j][i];
03161 }
03162 
03163 #ifdef COLORCHECK
03164 void CLASS colorcheck()
03165 {
03166 #define NSQ 24
03167 // Coordinates of the GretagMacbeth ColorChecker squares
03168 // width, height, 1st_column, 1st_row
03169   static const int cut[NSQ][4] = {
03170     { 241, 231, 234, 274 },
03171     { 251, 235, 534, 274 },
03172     { 255, 239, 838, 272 },
03173     { 255, 240, 1146, 274 },
03174     { 251, 237, 1452, 278 },
03175     { 243, 238, 1758, 288 },
03176     { 253, 253, 218, 558 },
03177     { 255, 249, 524, 562 },
03178     { 261, 253, 830, 562 },
03179     { 260, 255, 1144, 564 },
03180     { 261, 255, 1450, 566 },
03181     { 247, 247, 1764, 576 },
03182     { 255, 251, 212, 862 },
03183     { 259, 259, 518, 862 },
03184     { 263, 261, 826, 864 },
03185     { 265, 263, 1138, 866 },
03186     { 265, 257, 1450, 872 },
03187     { 257, 255, 1762, 874 },
03188     { 257, 253, 212, 1164 },
03189     { 262, 251, 516, 1172 },
03190     { 263, 257, 826, 1172 },
03191     { 263, 255, 1136, 1176 },
03192     { 255, 252, 1452, 1182 },
03193     { 257, 253, 1760, 1180 } };
03194 // ColorChecker Chart under 6500-kelvin illumination
03195   static const double gmb_xyY[NSQ][3] = {
03196     { 0.400, 0.350, 10.1 },     // Dark Skin
03197     { 0.377, 0.345, 35.8 },     // Light Skin
03198     { 0.247, 0.251, 19.3 },     // Blue Sky
03199     { 0.337, 0.422, 13.3 },     // Foliage
03200     { 0.265, 0.240, 24.3 },     // Blue Flower
03201     { 0.261, 0.343, 43.1 },     // Bluish Green
03202     { 0.506, 0.407, 30.1 },     // Orange
03203     { 0.211, 0.175, 12.0 },     // Purplish Blue
03204     { 0.453, 0.306, 19.8 },     // Moderate Red
03205     { 0.285, 0.202, 6.6 },      // Purple
03206     { 0.380, 0.489, 44.3 },     // Yellow Green
03207     { 0.473, 0.438, 43.1 },     // Orange Yellow
03208     { 0.187, 0.129, 6.1 },      // Blue
03209     { 0.305, 0.478, 23.4 },     // Green
03210     { 0.539, 0.313, 12.0 },     // Red
03211     { 0.448, 0.470, 59.1 },     // Yellow
03212     { 0.364, 0.233, 19.8 },     // Magenta
03213     { 0.196, 0.252, 19.8 },     // Cyan
03214     { 0.310, 0.316, 90.0 },     // White
03215     { 0.310, 0.316, 59.1 },     // Neutral 8
03216     { 0.310, 0.316, 36.2 },     // Neutral 6.5
03217     { 0.310, 0.316, 19.8 },     // Neutral 5
03218     { 0.310, 0.316, 9.0 },      // Neutral 3.5
03219     { 0.310, 0.316, 3.1 } };        // Black
03220   double gmb_cam[NSQ][4], gmb_xyz[NSQ][3];
03221   double inverse[NSQ][3], cam_xyz[4][3], num;
03222   int c, i, j, k, sq, row, col, count[4];
03223 
03224   memset (gmb_cam, 0, sizeof gmb_cam);
03225   for (sq=0; sq < NSQ; sq++) {
03226     FORCC count[c] = 0;
03227     for   (row=cut[sq][3]; row < cut[sq][3]+cut[sq][1]; row++)
03228       for (col=cut[sq][2]; col < cut[sq][2]+cut[sq][0]; col++) {
03229     c = FC(row,col);
03230     if (c >= colors) c -= 2;
03231     gmb_cam[sq][c] += BAYER(row,col);
03232     count[c]++;
03233       }
03234     FORCC gmb_cam[sq][c] = gmb_cam[sq][c]/count[c] - black;
03235     gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1];
03236     gmb_xyz[sq][1] = gmb_xyY[sq][2];
03237     gmb_xyz[sq][2] = gmb_xyY[sq][2] *
03238         (1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1];
03239   }
03240   pseudoinverse (gmb_xyz, inverse, NSQ);
03241   for (i=0; i < colors; i++)
03242     for (j=0; j < 3; j++)
03243       for (cam_xyz[i][j] = k=0; k < NSQ; k++)
03244     cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j];
03245   cam_xyz_coeff (cam_xyz);
03246   if (verbose) {
03247     printf ("    { \"%s %s\", %d,\n\t{", make, model, black);
03248     num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]);
03249     FORCC for (j=0; j < 3; j++)
03250       printf ("%c%d", (c | j) ? ',':' ', (int) (cam_xyz[c][j] * num + 0.5));
03251     puts (" } },");
03252   }
03253 #undef NSQ
03254 }
03255 #endif
03256 
03257 void CLASS scale_colors()
03258 {
03259   int row, col, x, y, c, val, sum[8];
03260   double dsum[8], dmin, dmax;
03261   float scale_mul[4];
03262 
03263   maximum -= black;
03264   if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1)) {
03265     memset (dsum, 0, sizeof dsum);
03266     for (row=0; row < height-7; row += 8)
03267       for (col=0; col < width-7; col += 8) {
03268     memset (sum, 0, sizeof sum);
03269     for (y=row; y < row+8; y++)
03270       for (x=col; x < col+8; x++)
03271         FORC4 {
03272           val = image[y*width+x][c];
03273           if (!val) continue;
03274           val -= black;
03275           if (val > maximum-25) goto skip_block;
03276           if (val < 0) val = 0;
03277           sum[c] += val;
03278           sum[c+4]++;
03279         }
03280     for (c=0; c < 8; c++) dsum[c] += sum[c];
03281 skip_block:
03282     continue;
03283       }
03284     FORC4 if (dsum[c]) pre_mul[c] = dsum[c+4] / dsum[c];
03285   }
03286   if (use_camera_wb && cam_mul[0] != -1) {
03287     memset (sum, 0, sizeof sum);
03288     for (row=0; row < 8; row++)
03289       for (col=0; col < 8; col++) {
03290     c = FC(row,col);
03291     if ((val = white[row][col] - black) > 0)
03292       sum[c] += val;
03293     sum[c+4]++;
03294       }
03295     if (sum[0] && sum[1] && sum[2] && sum[3])
03296       FORC4 pre_mul[c] = (float) sum[c+4] / sum[c];
03297     else if (cam_mul[0] && cam_mul[2])
03298       memcpy (pre_mul, cam_mul, sizeof pre_mul);
03299     else
03300       fprintf (stderr, "%s: Cannot use camera white balance.\n", ifname);
03301   }
03302   if (user_mul[0])
03303     memcpy (pre_mul, user_mul, sizeof pre_mul);
03304   if (pre_mul[3] == 0) pre_mul[3] = colors < 4 ? pre_mul[1] : 1;
03305   for (dmin=DBL_MAX, dmax=c=0; c < 4; c++) {
03306     if (dmin > pre_mul[c])
03307     dmin = pre_mul[c];
03308     if (dmax < pre_mul[c])
03309     dmax = pre_mul[c];
03310   }
03311   if (!highlight) dmax = dmin;
03312   FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum;
03313   if (verbose) {
03314     fprintf (stderr, "Scaling with black=%d, pre_mul[] =", black);
03315     FORC4 fprintf (stderr, " %f", pre_mul[c]);
03316     fputc ('\n', stderr);
03317   }
03318   for (row=0; row < height; row++)
03319     for (col=0; col < width; col++)
03320       FORC4 {
03321     val = image[row*width+col][c];
03322     if (!val) continue;
03323     val -= black;
03324     val *= scale_mul[c];
03325     image[row*width+col][c] = CLIP(val);
03326       }
03327   if (filters && colors == 3) {
03328     if (four_color_rgb) {
03329       colors++;
03330       FORC3 rgb_cam[c][3] = rgb_cam[c][1] /= 2;
03331     } else {
03332       for (row = FC(1,0) >> 1; row < height; row+=2)
03333     for (col = FC(row,1) & 1; col < width; col+=2)
03334       image[row*width+col][1] = image[row*width+col][3];
03335       filters &= ~((filters & 0x55555555) << 1);
03336     }
03337   }
03338 }
03339 
03340 void CLASS border_interpolate (int border)
03341 {
03342   unsigned row, col, y, x, f, c, sum[8];
03343 
03344   for (row=0; row < height; row++)
03345     for (col=0; col < width; col++) {
03346       if (col==border && row >= border && row < height-border)
03347     col = width-border;
03348       memset (sum, 0, sizeof sum);
03349       for (y=row-1; y != row+2; y++)
03350     for (x=col-1; x != col+2; x++)
03351       if (y < height && x < width) {
03352         f = fc(y,x);
03353         sum[f] += image[y*width+x][f];
03354         sum[f+4]++;
03355       }
03356       f = fc(row,col);
03357       FORCC if (c != f && sum[c+4])
03358     image[row*width+col][c] = sum[c] / sum[c+4];
03359     }
03360 }
03361 
03362 void CLASS lin_interpolate()
03363 {
03364   int code[16][16][32], *ip, sum[4];
03365   int c, i, x, y, row, col, shift, color;
03366   ushort *pix;
03367 
03368   if (verbose) fprintf (stderr, "Bilinear interpolation...\n");
03369 
03370   border_interpolate(1);
03371   for (row=0; row < 16; row++)
03372     for (col=0; col < 16; col++) {
03373       ip = code[row][col];
03374       memset (sum, 0, sizeof sum);
03375       for (y=-1; y <= 1; y++)
03376     for (x=-1; x <= 1; x++) {
03377       shift = (y==0) + (x==0);
03378       if (shift == 2) continue;
03379       color = fc(row+y,col+x);
03380       *ip++ = (width*y + x)*4 + color;
03381       *ip++ = shift;
03382       *ip++ = color;
03383       sum[color] += 1 << shift;
03384     }
03385       FORCC
03386     if (c != fc(row,col)) {
03387       *ip++ = c;
03388       *ip++ = sum[c];
03389     }
03390     }
03391   for (row=1; row < height-1; row++)
03392     for (col=1; col < width-1; col++) {
03393       pix = image[row*width+col];
03394       ip = code[row & 15][col & 15];
03395       memset (sum, 0, sizeof sum);
03396       for (i=8; i--; ip+=3)
03397     sum[ip[2]] += pix[ip[0]] << ip[1];
03398       for (i=colors; --i; ip+=2)
03399     pix[ip[0]] = sum[ip[0]] / ip[1];
03400     }
03401 }
03402 
03403 /*
03404    This algorithm is officially called:
03405 
03406    "Interpolation using a Threshold-based variable number of gradients"
03407 
03408    described in http://scien.stanford.edu/class/psych221/projects/99/tingchen/algodep/vargra.html
03409 
03410    I've extended the basic idea to work with non-Bayer filter arrays.
03411    Gradients are numbered clockwise from NW=0 to W=7.
03412  */
03413 void CLASS vng_interpolate()
03414 {
03415   static const signed char *cp, terms[] = {
03416     -2,-2,+0,-1,0,0x01, -2,-2,+0,+0,1,0x01, -2,-1,-1,+0,0,0x01,
03417     -2,-1,+0,-1,0,0x02, -2,-1,+0,+0,0,0x03, -2,-1,+0,+1,1,0x01,
03418     -2,+0,+0,-1,0,0x06, -2,+0,+0,+0,1,0x02, -2,+0,+0,+1,0,0x03,
03419     -2,+1,-1,+0,0,0x04, -2,+1,+0,-1,1,0x04, -2,+1,+0,+0,0,0x06,
03420     -2,+1,+0,+1,0,0x02, -2,+2,+0,+0,1,0x04, -2,+2,+0,+1,0,0x04,
03421     -1,-2,-1,+0,0,0x80, -1,-2,+0,-1,0,0x01, -1,-2,+1,-1,0,0x01,
03422     -1,-2,+1,+0,1,0x01, -1,-1,-1,+1,0,0x88, -1,-1,+1,-2,0,0x40,
03423     -1,-1,+1,-1,0,0x22, -1,-1,+1,+0,0,0x33, -1,-1,+1,+1,1,0x11,
03424     -1,+0,-1,+2,0,0x08, -1,+0,+0,-1,0,0x44, -1,+0,+0,+1,0,0x11,
03425     -1,+0,+1,-2,1,0x40, -1,+0,+1,-1,0,0x66, -1,+0,+1,+0,1,0x22,
03426     -1,+0,+1,+1,0,0x33, -1,+0,+1,+2,1,0x10, -1,+1,+1,-1,1,0x44,
03427     -1,+1,+1,+0,0,0x66, -1,+1,+1,+1,0,0x22, -1,+1,+1,+2,0,0x10,
03428     -1,+2,+0,+1,0,0x04, -1,+2,+1,+0,1,0x04, -1,+2,+1,+1,0,0x04,
03429     +0,-2,+0,+0,1,0x80, +0,-1,+0,+1,1,0x88, +0,-1,+1,-2,0,0x40,
03430     +0,-1,+1,+0,0,0x11, +0,-1,+2,-2,0,0x40, +0,-1,+2,-1,0,0x20,
03431     +0,-1,+2,+0,0,0x30, +0,-1,+2,+1,1,0x10, +0,+0,+0,+2,1,0x08,
03432     +0,+0,+2,-2,1,0x40, +0,+0,+2,-1,0,0x60, +0,+0,+2,+0,1,0x20,
03433     +0,+0,+2,+1,0,0x30, +0,+0,+2,+2,1,0x10, +0,+1,+1,+0,0,0x44,
03434     +0,+1,+1,+2,0,0x10, +0,+1,+2,-1,1,0x40, +0,+1,+2,+0,0,0x60,
03435     +0,+1,+2,+1,0,0x20, +0,+1,+2,+2,0,0x10, +1,-2,+1,+0,0,0x80,
03436     +1,-1,+1,+1,0,0x88, +1,+0,+1,+2,0,0x08, +1,+0,+2,-1,0,0x40,
03437     +1,+0,+2,+1,0,0x10
03438   }, chood[] = { -1,-1, -1,0, -1,+1, 0,+1, +1,+1, +1,0, +1,-1, 0,-1 };
03439   ushort (*brow[5])[4], *pix;
03440   int prow=7, pcol=1, *ip, *code[16][16], gval[8], gmin, gmax, sum[4];
03441   int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag;
03442   int g, diff, thold, num, c;
03443 
03444   lin_interpolate();
03445   if (verbose) fprintf (stderr, "VNG interpolation...\n");
03446 
03447   if (filters == 1) prow = pcol = 15;
03448   ip = (int *) calloc ((prow+1)*(pcol+1), 1280);
03449   merror (ip, "vng_interpolate()");
03450   for (row=0; row <= prow; row++)       /* Precalculate for VNG */
03451     for (col=0; col <= pcol; col++) {
03452       code[row][col] = ip;
03453       for (cp=terms, t=0; t < 64; t++) {
03454     y1 = *cp++;  x1 = *cp++;
03455     y2 = *cp++;  x2 = *cp++;
03456     weight = *cp++;
03457     grads = *cp++;
03458     color = fc(row+y1,col+x1);
03459     if (fc(row+y2,col+x2) != color) continue;
03460     diag = (fc(row,col+1) == color && fc(row+1,col) == color) ? 2:1;
03461     if (abs(y1-y2) == diag && abs(x1-x2) == diag) continue;
03462     *ip++ = (y1*width + x1)*4 + color;
03463     *ip++ = (y2*width + x2)*4 + color;
03464     *ip++ = weight;
03465     for (g=0; g < 8; g++)
03466       if (grads & 1<<g) *ip++ = g;
03467     *ip++ = -1;
03468       }
03469       *ip++ = INT_MAX;
03470       for (cp=chood, g=0; g < 8; g++) {
03471     y = *cp++;  x = *cp++;
03472     *ip++ = (y*width + x) * 4;
03473     color = fc(row,col);
03474     if (fc(row+y,col+x) != color && fc(row+y*2,col+x*2) == color)
03475       *ip++ = (y*width + x) * 8 + color;
03476     else
03477       *ip++ = 0;
03478       }
03479     }
03480   brow[4] = (ushort (*)[4]) calloc (width*3, sizeof **brow);
03481   merror (brow[4], "vng_interpolate()");
03482   for (row=0; row < 3; row++)
03483     brow[row] = brow[4] + row*width;
03484   for (row=2; row < height-2; row++) {      /* Do VNG interpolation */
03485     for (col=2; col < width-2; col++) {
03486       pix = image[row*width+col];
03487       ip = code[row & prow][col & pcol];
03488       memset (gval, 0, sizeof gval);
03489       while ((g = ip[0]) != INT_MAX) {      /* Calculate gradients */
03490     diff = ABS(pix[g] - pix[ip[1]]) << ip[2];
03491     gval[ip[3]] += diff;
03492     ip += 5;
03493     if ((g = ip[-1]) == -1) continue;
03494     gval[g] += diff;
03495     while ((g = *ip++) != -1)
03496       gval[g] += diff;
03497       }
03498       ip++;
03499       gmin = gmax = gval[0];            /* Choose a threshold */
03500       for (g=1; g < 8; g++) {
03501     if (gmin > gval[g]) gmin = gval[g];
03502     if (gmax < gval[g]) gmax = gval[g];
03503       }
03504       if (gmax == 0) {
03505     memcpy (brow[2][col], pix, sizeof *image);
03506     continue;
03507       }
03508       thold = gmin + (gmax >> 1);
03509       memset (sum, 0, sizeof sum);
03510       color = fc(row,col);
03511       for (num=g=0; g < 8; g++,ip+=2) {     /* Average the neighbors */
03512     if (gval[g] <= thold) {
03513       FORCC
03514         if (c == color && ip[1])
03515           sum[c] += (pix[c] + pix[ip[1]]) >> 1;
03516         else
03517           sum[c] += pix[ip[0] + c];
03518       num++;
03519     }
03520       }
03521       FORCC {                   /* Save to buffer */
03522     t = pix[color];
03523     if (c != color)
03524       t += (sum[c] - sum[color]) / num;
03525     brow[2][col][c] = CLIP(t);
03526       }
03527     }
03528     if (row > 3)                /* Write buffer to image */
03529       memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image);
03530     for (g=0; g < 4; g++)
03531       brow[(g-1) & 3] = brow[g];
03532   }
03533   memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image);
03534   memcpy (image[(row-1)*width+2], brow[1]+2, (width-4)*sizeof *image);
03535   free (brow[4]);
03536   free (code[0][0]);
03537 }
03538 
03539 void CLASS cam_to_cielab (ushort cam[4], float lab[3])
03540 {
03541   int c, i, j, k;
03542   float r, xyz[3];
03543   static float cbrt[0x10000], xyz_cam[3][4];
03544 
03545   if (cam == NULL) {
03546     for (i=0; i < 0x10000; i++) {
03547       r = i / 65535.0;
03548       cbrt[i] = r > 0.008856 ? pow(r,1/3.0) : 7.787*r + 16/116.0;
03549     }
03550     for (i=0; i < 3; i++)
03551       for (j=0; j < colors; j++)
03552         for (xyz_cam[i][j] = k=0; k < 3; k++)
03553       xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i];
03554   } else {
03555     xyz[0] = xyz[1] = xyz[2] = 0.5;
03556     FORCC {
03557       xyz[0] += xyz_cam[0][c] * cam[c];
03558       xyz[1] += xyz_cam[1][c] * cam[c];
03559       xyz[2] += xyz_cam[2][c] * cam[c];
03560     }
03561     xyz[0] = cbrt[CLIP((int) xyz[0])];
03562     xyz[1] = cbrt[CLIP((int) xyz[1])];
03563     xyz[2] = cbrt[CLIP((int) xyz[2])];
03564     lab[0] = 116 * xyz[1] - 16;
03565     lab[1] = 500 * (xyz[0] - xyz[1]);
03566     lab[2] = 200 * (xyz[1] - xyz[2]);
03567   }
03568 }
03569 
03570 /*
03571    Adaptive Homogeneity-Directed interpolation is based on
03572    the work of Keigo Hirakawa, Thomas Parks, and Paul Lee.
03573  */
03574 #define TS 256      /* Tile Size */
03575 
03576 void CLASS ahd_interpolate()
03577 {
03578   int i, j, top, left, row, col, tr, tc, fc, c, d, val, hm[2];
03579   ushort (*pix)[4], (*rix)[3];
03580   static const int dir[4] = { -1, 1, -TS, TS };
03581   unsigned ldiff[2][4], abdiff[2][4], leps, abeps;
03582   float flab[3];
03583   ushort (*rgb)[TS][TS][3];
03584    short (*lab)[TS][TS][3];
03585    char (*homo)[TS][TS], *buffer;
03586 
03587   if (verbose) fprintf (stderr, "AHD interpolation...\n");
03588 
03589   border_interpolate(3);
03590   buffer = (char *) malloc (26*TS*TS);      /* 1664 kB */
03591   merror (buffer, "ahd_interpolate()");
03592   rgb  = (ushort(*)[TS][TS][3]) buffer;
03593   lab  = (short (*)[TS][TS][3])(buffer + 12*TS*TS);
03594   homo = (char  (*)[TS][TS])   (buffer + 24*TS*TS);
03595 
03596   for (top=0; top < height; top += TS-6)
03597     for (left=0; left < width; left += TS-6) {
03598       memset (rgb, 0, 12*TS*TS);
03599 
03600 /*  Interpolate green horizontally and vertically:      */
03601       for (row = top < 2 ? 2:top; row < top+TS && row < height-2; row++) {
03602     col = left + (FC(row,left) == 1);
03603     if (col < 2) col += 2;
03604     for (fc = FC(row,col); col < left+TS && col < width-2; col+=2) {
03605       pix = image + row*width+col;
03606       val = ((pix[-1][1] + pix[0][fc] + pix[1][1]) * 2
03607         - pix[-2][fc] - pix[2][fc]) >> 2;
03608       rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]);
03609       val = ((pix[-width][1] + pix[0][fc] + pix[width][1]) * 2
03610         - pix[-2*width][fc] - pix[2*width][fc]) >> 2;
03611       rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]);
03612     }
03613       }
03614 /*  Interpolate red and blue, and convert to CIELab:        */
03615       for (d=0; d < 2; d++)
03616     for (row=top+1; row < top+TS-1 && row < height-1; row++)
03617       for (col=left+1; col < left+TS-1 && col < width-1; col++) {
03618         pix = image + row*width+col;
03619         rix = &rgb[d][row-top][col-left];
03620         if ((c = 2 - FC(row,col)) == 1) {
03621           c = FC(row+1,col);
03622           val = pix[0][1] + (( pix[-1][2-c] + pix[1][2-c]
03623                  - rix[-1][1] - rix[1][1] ) >> 1);
03624           rix[0][2-c] = CLIP(val);
03625           val = pix[0][1] + (( pix[-width][c] + pix[width][c]
03626                  - rix[-TS][1] - rix[TS][1] ) >> 1);
03627         } else
03628           val = rix[0][1] + (( pix[-width-1][c] + pix[-width+1][c]
03629                  + pix[+width-1][c] + pix[+width+1][c]
03630                  - rix[-TS-1][1] - rix[-TS+1][1]
03631                  - rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2);
03632         rix[0][c] = CLIP(val);
03633         c = FC(row,col);
03634         rix[0][c] = pix[0][c];
03635         cam_to_cielab (rix[0], flab);
03636         FORC3 lab[d][row-top][col-left][c] = 64*flab[c];
03637       }
03638 /*  Build homogeneity maps from the CIELab images:      */
03639       memset (homo, 0, 2*TS*TS);
03640       for (row=top+2; row < top+TS-2 && row < height; row++) {
03641     tr = row-top;
03642     for (col=left+2; col < left+TS-2 && col < width; col++) {
03643       tc = col-left;
03644       for (d=0; d < 2; d++)
03645         for (i=0; i < 4; i++)
03646           ldiff[d][i] = ABS(lab[d][tr][tc][0]-lab[d][tr][tc+dir[i]][0]);
03647       leps = MIN(MAX(ldiff[0][0],ldiff[0][1]),
03648              MAX(ldiff[1][2],ldiff[1][3]));
03649       for (d=0; d < 2; d++)
03650         for (i=0; i < 4; i++)
03651           if (i >> 1 == d || ldiff[d][i] <= leps)
03652         abdiff[d][i] = SQR(lab[d][tr][tc][1]-lab[d][tr][tc+dir[i]][1])
03653                  + SQR(lab[d][tr][tc][2]-lab[d][tr][tc+dir[i]][2]);
03654       abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]),
03655               MAX(abdiff[1][2],abdiff[1][3]));
03656       for (d=0; d < 2; d++)
03657         for (i=0; i < 4; i++)
03658           if (ldiff[d][i] <= leps && abdiff[d][i] <= abeps)
03659         homo[d][tr][tc]++;
03660     }
03661       }
03662 /*  Combine the most homogenous pixels for the final result:    */
03663       for (row=top+3; row < top+TS-3 && row < height-3; row++) {
03664     tr = row-top;
03665     for (col=left+3; col < left+TS-3 && col < width-3; col++) {
03666       tc = col-left;
03667       for (d=0; d < 2; d++)
03668         for (hm[d]=0, i=tr-1; i <= tr+1; i++)
03669           for (j=tc-1; j <= tc+1; j++)
03670         hm[d] += homo[d][i][j];
03671       if (hm[0] != hm[1])
03672         FORC3 image[row*width+col][c] = rgb[hm[1] > hm[0]][tr][tc][c];
03673       else
03674         FORC3 image[row*width+col][c] =
03675         (rgb[0][tr][tc][c] + rgb[1][tr][tc][c]) >> 1;
03676     }
03677       }
03678     }
03679   free (buffer);
03680 }
03681 #undef TS
03682 
03683 /*
03684    Bilateral Filtering was developed by C. Tomasi and R. Manduchi.
03685  */
03686 void CLASS bilateral_filter()
03687 {
03688   float (**window)[7], *kernel, scale_r, elut[1024], sum[5];
03689   int c, i, wr, ws, wlast, row, col, y, x;
03690   unsigned sep;
03691 
03692   if (verbose) fprintf (stderr, "Bilateral filtering...\n");
03693 
03694   wr = ceil(sigma_d*2);     /* window radius */
03695   ws = 2*wr + 1;        /* window size */
03696   window = (float (**)[7]) calloc ((ws+1)*sizeof *window +
03697         ws*width*sizeof **window + ws*sizeof *kernel, 1);
03698   merror (window, "bilateral_filter()");
03699   for (i=0; i <= ws; i++)
03700     window[i] = (float (*)[7]) (window+ws+1) + i*width;
03701   kernel = (float *) window[ws] + wr;
03702   for (i=-wr; i <= wr; i++)
03703     kernel[i] = 256 / (2*SQR(sigma_d)) * i*i + 0.25;
03704   scale_r     = 256 / (2*SQR(sigma_r));
03705   for (i=0; i < 1024; i++)
03706     elut[i] = exp (-i/256.0);
03707 
03708   for (wlast=-1, row=0; row < height; row++) {
03709     while (wlast < row+wr) {
03710       wlast++;
03711       for (i=0; i <= ws; i++)   /* rotate window rows */
03712     window[(ws+i) % (ws+1)] = window[i];
03713       if (wlast < height)
03714     for (col=0; col < width; col++) {
03715       FORCC window[ws-1][col][c] = image[wlast*width+col][c];
03716       cam_to_cielab (image[wlast*width+col], window[ws-1][col]+4);
03717     }
03718     }
03719     for (col=0; col < width; col++) {
03720       memset (sum, 0, sizeof sum);
03721       for (y=-wr; y <= wr; y++)
03722     if ((unsigned)(row+y) < height)
03723       for (x=-wr; x <= wr; x++)
03724         if ((unsigned)(col+x) < width) {
03725           sep = ( SQR(window[wr+y][col+x][4] - window[wr][col][4])
03726             + SQR(window[wr+y][col+x][5] - window[wr][col][5])
03727             + SQR(window[wr+y][col+x][6] - window[wr][col][6]) )
03728             * scale_r + kernel[y] + kernel[x];
03729           if (sep < 1024) {
03730         FORCC sum[c] += elut[sep] * window[wr+y][col+x][c];
03731         sum[4] += elut[sep];
03732           }
03733         }
03734       FORCC image[row*width+col][c] = sum[c]/sum[4];
03735     }
03736   }
03737   free (window);
03738 }
03739 
03740 #define SCALE (4 >> shrink)
03741 void CLASS recover_highlights()
03742 {
03743   float *map, sum, wgt, grow;
03744   int hsat[4], count, spread, change, val, i;
03745   unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x;
03746   ushort *pixel;
03747   static const signed char dir[8][2] =
03748     { {-1,-1}, {-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1} };
03749 
03750   if (verbose) fprintf (stderr, "Highlight recovery...\n");
03751 
03752   grow = pow (2, 4-highlight);
03753   FORCC hsat[c] = 32000 * pre_mul[c];
03754   for (kc=0, c=1; c < colors; c++)
03755     if (pre_mul[kc] < pre_mul[c]) kc = c;
03756   high = height / SCALE;
03757   wide =  width / SCALE;
03758   map = (float *) calloc (high*wide, sizeof *map);
03759   merror (map, "recover_highlights()");
03760   FORCC if (c != kc) {
03761     memset (map, 0, high*wide*sizeof *map);
03762     for (mrow=0; mrow < high; mrow++)
03763       for (mcol=0; mcol < wide; mcol++) {
03764     sum = wgt = count = 0;
03765     for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++)
03766       for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) {
03767         pixel = image[row*width+col];
03768         if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000) {
03769           sum += pixel[c];
03770           wgt += pixel[kc];
03771           count++;
03772         }
03773       }
03774     if (count == SCALE*SCALE)
03775       map[mrow*wide+mcol] = sum / wgt;
03776       }
03777     for (spread = 32/grow; spread--; ) {
03778       for (mrow=0; mrow < high; mrow++)
03779     for (mcol=0; mcol < wide; mcol++) {
03780       if (map[mrow*wide+mcol]) continue;
03781       sum = count = 0;
03782       for (d=0; d < 8; d++) {
03783         y = mrow + dir[d][0];
03784         x = mcol + dir[d][1];
03785         if (y < high && x < wide && map[y*wide+x] > 0) {
03786           sum  += (1 + (d & 1)) * map[y*wide+x];
03787           count += 1 + (d & 1);
03788         }
03789       }
03790       if (count > 3)
03791         map[mrow*wide+mcol] = - (sum+grow) / (count+grow);
03792     }
03793       for (change=i=0; i < high*wide; i++)
03794     if (map[i] < 0) {
03795       map[i] = -map[i];
03796       change = 1;
03797     }
03798       if (!change) break;
03799     }
03800     for (i=0; i < high*wide; i++)
03801       if (map[i] == 0) map[i] = 1;
03802     for (mrow=0; mrow < high; mrow++)
03803       for (mcol=0; mcol < wide; mcol++) {
03804     for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++)
03805       for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) {
03806         pixel = image[row*width+col];
03807         if (pixel[c] / hsat[c] > 1) {
03808           val = pixel[kc] * map[mrow*wide+mcol];
03809           if (pixel[c] < val) pixel[c] = CLIP(val);
03810         }
03811       }
03812       }
03813   }
03814   free (map);
03815 }
03816 #undef SCALE
03817 
03818 void CLASS tiff_get (unsigned base,
03819     unsigned *tag, unsigned *type, unsigned *len, unsigned *save)
03820 {
03821   *tag  = get2();
03822   *type = get2();
03823   *len  = get4();
03824   *save = ftell(ifp) + 4;
03825   if (*len * ("1112481124848"[*type < 13 ? *type:0]-'0') > 4)
03826     fseek (ifp, get4()+base, SEEK_SET);
03827 }
03828 
03829 void CLASS parse_thumb_note (int base, unsigned toff, unsigned tlen)
03830 {
03831   unsigned entries, tag, type, len, save;
03832 
03833   entries = get2();
03834   while (entries--) {
03835     tiff_get (base, &tag, &type, &len, &save);
03836     if (tag == toff) thumb_offset = get4();
03837     if (tag == tlen) thumb_length = get4();
03838     fseek (ifp, save, SEEK_SET);
03839   }
03840 }
03841 
03842 void CLASS parse_makernote (int base)
03843 {
03844   static const uchar xlat[2][256] = {
03845   { 0xc1,0xbf,0x6d,0x0d,0x59,0xc5,0x13,0x9d,0x83,0x61,0x6b,0x4f,0xc7,0x7f,0x3d,0x3d,
03846     0x53,0x59,0xe3,0xc7,0xe9,0x2f,0x95,0xa7,0x95,0x1f,0xdf,0x7f,0x2b,0x29,0xc7,0x0d,
03847     0xdf,0x07,0xef,0x71,0x89,0x3d,0x13,0x3d,0x3b,0x13,0xfb,0x0d,0x89,0xc1,0x65,0x1f,
03848     0xb3,0x0d,0x6b,0x29,0xe3,0xfb,0xef,0xa3,0x6b,0x47,0x7f,0x95,0x35,0xa7,0x47,0x4f,
03849     0xc7,0xf1,0x59,0x95,0x35,0x11,0x29,0x61,0xf1,0x3d,0xb3,0x2b,0x0d,0x43,0x89,0xc1,
03850     0x9d,0x9d,0x89,0x65,0xf1,0xe9,0xdf,0xbf,0x3d,0x7f,0x53,0x97,0xe5,0xe9,0x95,0x17,
03851     0x1d,0x3d,0x8b,0xfb,0xc7,0xe3,0x67,0xa7,0x07,0xf1,0x71,0xa7,0x53,0xb5,0x29,0x89,
03852     0xe5,0x2b,0xa7,0x17,0x29,0xe9,0x4f,0xc5,0x65,0x6d,0x6b,0xef,0x0d,0x89,0x49,0x2f,
03853     0xb3,0x43,0x53,0x65,0x1d,0x49,0xa3,0x13,0x89,0x59,0xef,0x6b,0xef,0x65,0x1d,0x0b,
03854     0x59,0x13,0xe3,0x4f,0x9d,0xb3,0x29,0x43,0x2b,0x07,0x1d,0x95,0x59,0x59,0x47,0xfb,
03855     0xe5,0xe9,0x61,0x47,0x2f,0x35,0x7f,0x17,0x7f,0xef,0x7f,0x95,0x95,0x71,0xd3,0xa3,
03856     0x0b,0x71,0xa3,0xad,0x0b,0x3b,0xb5,0xfb,0xa3,0xbf,0x4f,0x83,0x1d,0xad,0xe9,0x2f,
03857     0x71,0x65,0xa3,0xe5,0x07,0x35,0x3d,0x0d,0xb5,0xe9,0xe5,0x47,0x3b,0x9d,0xef,0x35,
03858     0xa3,0xbf,0xb3,0xdf,0x53,0xd3,0x97,0x53,0x49,0x71,0x07,0x35,0x61,0x71,0x2f,0x43,
03859     0x2f,0x11,0xdf,0x17,0x97,0xfb,0x95,0x3b,0x7f,0x6b,0xd3,0x25,0xbf,0xad,0xc7,0xc5,
03860     0xc5,0xb5,0x8b,0xef,0x2f,0xd3,0x07,0x6b,0x25,0x49,0x95,0x25,0x49,0x6d,0x71,0xc7 },
03861   { 0xa7,0xbc,0xc9,0xad,0x91,0xdf,0x85,0xe5,0xd4,0x78,0xd5,0x17,0x46,0x7c,0x29,0x4c,
03862     0x4d,0x03,0xe9,0x25,0x68,0x11,0x86,0xb3,0xbd,0xf7,0x6f,0x61,0x22,0xa2,0x26,0x34,
03863     0x2a,0xbe,0x1e,0x46,0x14,0x68,0x9d,0x44,0x18,0xc2,0x40,0xf4,0x7e,0x5f,0x1b,0xad,
03864     0x0b,0x94,0xb6,0x67,0xb4,0x0b,0xe1,0xea,0x95,0x9c,0x66,0xdc,0xe7,0x5d,0x6c,0x05,
03865     0xda,0xd5,0xdf,0x7a,0xef,0xf6,0xdb,0x1f,0x82,0x4c,0xc0,0x68,0x47,0xa1,0xbd,0xee,
03866     0x39,0x50,0x56,0x4a,0xdd,0xdf,0xa5,0xf8,0xc6,0xda,0xca,0x90,0xca,0x01,0x42,0x9d,
03867     0x8b,0x0c,0x73,0x43,0x75,0x05,0x94,0xde,0x24,0xb3,0x80,0x34,0xe5,0x2c,0xdc,0x9b,
03868     0x3f,0xca,0x33,0x45,0xd0,0xdb,0x5f,0xf5,0x52,0xc3,0x21,0xda,0xe2,0x22,0x72,0x6b,
03869     0x3e,0xd0,0x5b,0xa8,0x87,0x8c,0x06,0x5d,0x0f,0xdd,0x09,0x19,0x93,0xd0,0xb9,0xfc,
03870     0x8b,0x0f,0x84,0x60,0x33,0x1c,0x9b,0x45,0xf1,0xf0,0xa3,0x94,0x3a,0x12,0x77,0x33,
03871     0x4d,0x44,0x78,0x28,0x3c,0x9e,0xfd,0x65,0x57,0x16,0x94,0x6b,0xfb,0x59,0xd0,0xc8,
03872     0x22,0x36,0xdb,0xd2,0x63,0x98,0x43,0xa1,0x04,0x87,0x86,0xf7,0xa6,0x26,0xbb,0xd6,
03873     0x59,0x4d,0xbf,0x6a,0x2e,0xaa,0x2b,0xef,0xe6,0x78,0xb6,0x4e,0xe0,0x2f,0xdc,0x7c,
03874     0xbe,0x57,0x19,0x32,0x7e,0x2a,0xd0,0xb8,0xba,0x29,0x00,0x3c,0x52,0x7d,0xa8,0x49,
03875     0x3b,0x2d,0xeb,0x25,0x49,0xfa,0xa3,0xaa,0x39,0xa7,0xc5,0xa7,0x50,0x11,0x36,0xfb,
03876     0xc6,0x67,0x4a,0xf5,0xa5,0x12,0x65,0x7e,0xb0,0xdf,0xaf,0x4e,0xb3,0x61,0x7f,0x2f } };
03877   unsigned offset=0, entries, tag, type, len, save, c;
03878   unsigned ver97=0, serial=0, i, wb[4]={0,0,0,0};
03879   uchar buf97[324], ci, cj, ck;
03880   short sorder;
03881   char buf[10];
03882 /*
03883    The MakerNote might have its own TIFF header (possibly with
03884    its own byte-order!), or it might just be a table.
03885  */
03886   sorder = order;
03887   fread (buf, 1, 10, ifp);
03888   if (!strncmp (buf,"KDK" ,3) ||    /* these aren't TIFF tables */
03889       !strncmp (buf,"VER" ,3) ||
03890       !strncmp (buf,"IIII",4) ||
03891       !strncmp (buf,"MMMM",4)) return;
03892   if (!strncmp (buf,"KC"  ,2) ||    /* Konica KD-400Z, KD-510Z */
03893       !strncmp (buf,"MLY" ,3)) {    /* Minolta DiMAGE G series */
03894     order = 0x4d4d;
03895     while ((i=ftell(ifp)) < data_offset && i < 16384) {
03896       wb[0] = wb[2];  wb[2] = wb[1];  wb[1] = wb[3];
03897       wb[3] = get2();
03898       if (wb[1] == 256 && wb[3] == 256 &&
03899       wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640)
03900     FORC4 cam_mul[c] = wb[c];
03901     }
03902     goto quit;
03903   }
03904   if (!strcmp (buf,"Nikon")) {
03905     base = ftell(ifp);
03906     order = get2();
03907     if (get2() != 42) goto quit;
03908     offset = get4();
03909     fseek (ifp, offset-8, SEEK_CUR);
03910   } else if (!strncmp (buf,"FUJIFILM",8) ||
03911          !strncmp (buf,"SONY",4) ||
03912          !strcmp  (buf,"Panasonic")) {
03913     order = 0x4949;
03914     fseek (ifp,  2, SEEK_CUR);
03915   } else if (!strcmp (buf,"OLYMP") ||
03916          !strcmp (buf,"LEICA") ||
03917          !strcmp (buf,"Ricoh") ||
03918          !strcmp (buf,"EPSON"))
03919     fseek (ifp, -2, SEEK_CUR);
03920   else if (!strcmp (buf,"AOC") ||
03921        !strcmp (buf,"QVC"))
03922     fseek (ifp, -4, SEEK_CUR);
03923   else fseek (ifp, -10, SEEK_CUR);
03924 
03925   entries = get2();
03926   if (entries > 1000) return;
03927   while (entries--) {
03928     tiff_get (base, &tag, &type, &len, &save);
03929     if (tag == 2 && strstr(make,"NIKON"))
03930       iso_speed = (get2(),get2());
03931     if (tag == 4 && len == 27) {
03932       iso_speed = 50 * pow (2, (get4(),get2())/32.0 - 4);
03933       aperture = (get2(), pow (2, get2()/64.0));
03934       shutter = pow (2, ((short) get2())/-32.0);
03935     }
03936     if (tag == 8 && type == 4)
03937       shot_order = get4();
03938     if (tag == 0xc && len == 4) {
03939       cam_mul[0] = getrat();
03940       cam_mul[2] = getrat();
03941     }
03942     if (tag == 0x10 && type == 4)
03943       unique_id = get4();
03944     if (tag == 0x14 && len == 2560 && type == 7) {
03945       fseek (ifp, 1248, SEEK_CUR);
03946       goto get2_256;
03947     }
03948     if (strstr(make,"PENTAX")) {
03949       if (tag == 0x1b) tag = 0x1018;
03950       if (tag == 0x1c) tag = 0x1017;
03951     }
03952     if (tag == 0x1d)
03953       while ((c = fgetc(ifp)))
03954     serial = serial*10 + (isdigit(c) ? c - '0' : c % 10);
03955     if (tag == 0x81 && type == 4) {
03956       data_offset = get4();
03957       fseek (ifp, data_offset + 41, SEEK_SET);
03958       raw_height = get2() * 2;
03959       raw_width  = get2();
03960       filters = 0x61616161;
03961     }
03962     if ((tag == 0x81  && type == 7) ||
03963     (tag == 0x100 && type == 7) ||
03964     (tag == 0x280 && type == 1)) {
03965       thumb_offset = ftell(ifp);
03966       thumb_length = len;
03967     }
03968     if (tag == 0x88 && type == 4 && (thumb_offset = get4()))
03969       thumb_offset += base;
03970     if (tag == 0x89 && type == 4)
03971       thumb_length = get4();
03972     if (tag == 0x8c)
03973       curve_offset = ftell(ifp) + 2112;
03974     if (tag == 0x96)
03975       curve_offset = ftell(ifp) + 2;
03976     if (tag == 0x97) {
03977       for (i=0; i < 4; i++)
03978     ver97 = (ver97 << 4) + fgetc(ifp)-'0';
03979       switch (ver97) {
03980     case 0x100:
03981       fseek (ifp, 68, SEEK_CUR);
03982       FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2();
03983       break;
03984     case 0x102:
03985       fseek (ifp, 6, SEEK_CUR);
03986       goto get2_rggb;
03987     case 0x103:
03988       fseek (ifp, 16, SEEK_CUR);
03989       FORC4 cam_mul[c] = get2();
03990       }
03991       if (ver97 >> 8 == 2) {
03992     if (ver97 != 0x205) fseek (ifp, 280, SEEK_CUR);
03993     fread (buf97, 324, 1, ifp);
03994       }
03995     }
03996     if (tag == 0xa7 && ver97 >> 8 == 2) {
03997       ci = xlat[0][serial & 0xff];
03998       cj = xlat[1][fgetc(ifp)^fgetc(ifp)^fgetc(ifp)^fgetc(ifp)];
03999       ck = 0x60;
04000       for (i=0; i < 324; i++)
04001     buf97[i] ^= (cj += ci * ck++);
04002       FORC4 cam_mul[c ^ (c >> 1)] =
04003     sget2 (buf97 + (ver97 == 0x205 ? 14:6) + c*2);
04004     }
04005     if (tag == 0x200 && len == 4)
04006       black = (get2()+get2()+get2()+get2())/4;
04007     if (tag == 0x201 && len == 4)
04008       goto get2_rggb;
04009     if (tag == 0x401 && len == 4) {
04010       black = (get4()+get4()+get4()+get4())/4;
04011     }
04012     if (tag == 0xe01) {     /* Nikon Capture Note */
04013       type = order;
04014       order = 0x4949;
04015       fseek (ifp, 22, SEEK_CUR);
04016       for (offset=22; offset+22 < len; offset += 22+i) {
04017     tag = get4();
04018     fseek (ifp, 14, SEEK_CUR);
04019     i = get4()-4;
04020     if (tag == 0x76a43207) flip = get2();
04021     else fseek (ifp, i, SEEK_CUR);
04022       }
04023       order = type;
04024     }
04025     if (tag == 0xe80 && len == 256 && type == 7) {
04026       fseek (ifp, 48, SEEK_CUR);
04027       cam_mul[0] = get2() * 508 * 1.078 / 0x10000;
04028       cam_mul[2] = get2() * 382 * 1.173 / 0x10000;
04029     }
04030     if (tag == 0xf00 && type == 7) {
04031       if (len == 614)
04032     fseek (ifp, 176, SEEK_CUR);
04033       else if (len == 734 || len == 1502)
04034     fseek (ifp, 148, SEEK_CUR);
04035       else goto next;
04036       goto get2_256;
04037     }
04038     if (tag == 0x1011 && len == 9 && use_camera_wb) {
04039       for (i=0; i < 3; i++)
04040     FORC3 rgb_cam[i][c] = ((short) get2()) / 256.0;
04041       raw_color = rgb_cam[0][0] < 1;
04042     }
04043     if (tag == 0x1012 && len == 4)
04044       for (black = i=0; i < 4; i++)
04045     black += get2() << 2;
04046     if (tag == 0x1017)
04047       cam_mul[0] = get2() / 256.0;
04048     if (tag == 0x1018)
04049       cam_mul[2] = get2() / 256.0;
04050     if (tag == 0x2011 && len == 2) {
04051 get2_256:
04052       order = 0x4d4d;
04053       cam_mul[0] = get2() / 256.0;
04054       cam_mul[2] = get2() / 256.0;
04055     }
04056     if (tag == 0x2020)
04057       parse_thumb_note (base, 257, 258);
04058     if (tag == 0xb028) {
04059       fseek (ifp, get4(), SEEK_SET);
04060       parse_thumb_note (base, 136, 137);
04061     }
04062     if (tag == 0x4001) {
04063       i = len == 582 ? 50 : len == 653 ? 68 : len == 796 ? 126 : 0;
04064       fseek (ifp, i, SEEK_CUR);
04065 get2_rggb:
04066       FORC4 cam_mul[c ^ (c >> 1)] = get2();
04067     }
04068 next:
04069     fseek (ifp, save, SEEK_SET);
04070   }
04071 quit:
04072   order = sorder;
04073 }
04074 
04075 /*
04076    Since the TIFF DateTime string has no timezone information,
04077    assume that the camera's clock was set to Universal Time.
04078  */
04079 void CLASS get_timestamp (int reversed)
04080 {
04081   struct tm t;
04082   char str[20];
04083   int i;
04084 
04085   if (timestamp) return;
04086   str[19] = 0;
04087   if (reversed)
04088     for (i=19; i--; ) str[i] = fgetc(ifp);
04089   else
04090     fread (str, 19, 1, ifp);
04091   memset (&t, 0, sizeof t);
04092   if (sscanf (str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon,
04093     &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6)
04094     return;
04095   t.tm_year -= 1900;
04096   t.tm_mon -= 1;
04097   if (mktime(&t) > 0)
04098     timestamp = mktime(&t);
04099 }
04100 
04101 void CLASS parse_exif (int base)
04102 {
04103   unsigned kodak, entries, tag, type, len, save;
04104   double expo;
04105 
04106   kodak = !strncmp(make,"EASTMAN",7);
04107   entries = get2();
04108   while (entries--) {
04109     tiff_get (base, &tag, &type, &len, &save);
04110     switch (tag) {
04111       case 33434:  shutter = getrat();          break;
04112       case 33437:  aperture = getrat();         break;
04113       case 34855:  iso_speed = get2();          break;
04114       case 36867:
04115       case 36868:  get_timestamp(0);            break;
04116       case 37377:  if ((expo = -getrat()) < 128)
04117              shutter = pow (2, expo);       break;
04118       case 37378:  aperture = pow (2, getrat()/2);  break;
04119       case 37386:  focal_len = getrat();        break;
04120       case 37500:  parse_makernote (base);      break;
04121       case 40962:  if (kodak) raw_width  = get4();  break;
04122       case 40963:  if (kodak) raw_height = get4();  break;
04123     }
04124     fseek (ifp, save, SEEK_SET);
04125   }
04126 }
04127 
04128 void CLASS romm_coeff (float romm_cam[3][3])
04129 {
04130   static const float rgb_romm[3][3] =   /* ROMM == Kodak ProPhoto */
04131   { {  2.034193, -0.727420, -0.306766 },
04132     { -0.228811,  1.231729, -0.002922 },
04133     { -0.008565, -0.153273,  1.161839 } };
04134   int i, j, k;
04135 
04136   for (raw_color = i=0; i < 3; i++)
04137     for (j=0; j < 3; j++)
04138       for (rgb_cam[i][j] = k=0; k < 3; k++)
04139     rgb_cam[i][j] += rgb_romm[i][k] * romm_cam[k][j];
04140 }
04141 
04142 void CLASS parse_mos (int offset)
04143 {
04144   char data[40];
04145   int skip, from, i, c, neut[4], planes=0, frot=0;
04146   static const char *mod[] =
04147   { "","DCB2","Volare","Cantare","CMost","Valeo 6","Valeo 11","Valeo 22",
04148     "","Valeo 17","","Aptus 17","Aptus 22","Aptus 75","Aptus 65" };
04149   float romm_cam[3][3];
04150 
04151   fseek (ifp, offset, SEEK_SET);
04152   while (1) {
04153     if (get4() != 0x504b5453) break;
04154     get4();
04155     fread (data, 1, 40, ifp);
04156     skip = get4();
04157     from = ftell(ifp);
04158     if (!strcmp(data,"JPEG_preview_data")) {
04159       thumb_offset = from;
04160       thumb_length = skip;
04161     }
04162     if (!strcmp(data,"icc_camera_profile")) {
04163       profile_offset = from;
04164       profile_length = skip;
04165     }
04166     if (!strcmp(data,"ShootObj_back_type")) {
04167       fscanf (ifp, "%d", &i);
04168       if ((unsigned) i < sizeof mod / sizeof (*mod))
04169     strcpy (model, mod[i]);
04170     }
04171     if (!strcmp(data,"CaptProf_color_matrix") && use_camera_wb) {
04172       for (i=0; i < 9; i++)
04173     fscanf (ifp, "%f", &romm_cam[0][i]);
04174       romm_coeff (romm_cam);
04175     }
04176     if (!strcmp(data,"CaptProf_number_of_planes"))
04177       fscanf (ifp, "%d", &planes);
04178     if (!strcmp(data,"CaptProf_raw_data_rotation"))
04179       fscanf (ifp, "%d", &flip);
04180     if (!strcmp(data,"CaptProf_mosaic_pattern"))
04181       FORC4 {
04182     fscanf (ifp, "%d", &i);
04183     if (i == 1) frot = c ^ (c >> 1);
04184       }
04185     if (!strcmp(data,"ImgProf_rotation_angle")) {
04186       fscanf (ifp, "%d", &i);
04187       flip = i - flip;
04188     }
04189     if (!strcmp(data,"NeutObj_neutrals") && !cam_mul[0]) {
04190       FORC4 fscanf (ifp, "%d", neut+c);
04191       FORC3 cam_mul[c] = (float) neut[0] / neut[c+1];
04192     }
04193     parse_mos (from);
04194     fseek (ifp, skip+from, SEEK_SET);
04195   }
04196   if (planes)
04197     filters = (planes == 1) * 0x01010101 *
04198     (uchar) "\x94\x61\x16\x49"[(flip/90 + frot) & 3];
04199 }
04200 
04201 void CLASS linear_table (unsigned len)
04202 {
04203   int i;
04204   if (len > 0x1000) len = 0x1000;
04205   read_shorts (curve, len);
04206   for (i=len; i < 0x1000; i++)
04207     curve[i] = curve[i-1];
04208   maximum = curve[0xfff];
04209 }
04210 
04211 void CLASS parse_kodak_ifd (int base)
04212 {
04213   unsigned entries, tag, type, len, save;
04214   int i, c, wbi=-2, wbtemp=6500;
04215   float mul[3], num;
04216 
04217   entries = get2();
04218   if (entries > 1024) return;
04219   while (entries--) {
04220     tiff_get (base, &tag, &type, &len, &save);
04221     if (tag == 1020) wbi = getint(type);
04222     if (tag == 1021 && len == 72) {     /* WB set in software */
04223       fseek (ifp, 40, SEEK_CUR);
04224       FORC3 cam_mul[c] = 2048.0 / get2();
04225       wbi = -2;
04226     }
04227     if (tag == 2118) wbtemp = getint(type);
04228     if (tag == 2130 + wbi)
04229       FORC3 mul[c] = getreal(type);
04230     if (tag == 2140 + wbi && wbi >= 0)
04231       FORC3 {
04232     for (num=i=0; i < 4; i++)
04233       num += getreal(type) * pow (wbtemp/100.0, i);
04234     cam_mul[c] = 2048 / (num * mul[c]);
04235       }
04236     if (tag == 2317) linear_table (len);
04237     if (tag == 6020) iso_speed = getint(type);
04238     fseek (ifp, save, SEEK_SET);
04239   }
04240 }
04241 
04242 void CLASS parse_minolta (int base);
04243 
04244 int CLASS parse_tiff_ifd (int base, int level)
04245 {
04246   unsigned entries, tag, type, len, plen=16, save;
04247   int ifd, use_cm=0, cfa, i, j, c, ima_len=0;
04248   char software[64], *cbuf, *cp;
04249   uchar cfa_pat[16], cfa_pc[] = { 0,1,2,3 }, tab[256];
04250   double dblack, cc[4][4], cm[4][3], cam_xyz[4][3], num, sx, sy;
04251   double ab[]={ 1,1,1,1 }, asn[] = { 0,0,0,0 }, xyz[] = { 1,1,1 };
04252   unsigned *buf, sony_offset=0, sony_length=0, sony_key=0;
04253   struct jhead jh;
04254   FILE *sfp;
04255 
04256   if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0])
04257     return 1;
04258   ifd = tiff_nifds++;
04259   for (j=0; j < 4; j++)
04260     for (i=0; i < 4; i++)
04261       cc[j][i] = i == j;
04262   entries = get2();
04263   if (entries > 512) return 1;
04264   while (entries--) {
04265     tiff_get (base, &tag, &type, &len, &save);
04266     switch (tag) {
04267       case 17: case 18:
04268     if (type == 3 && len == 1)
04269       cam_mul[(tag-17)*2] = get2() / 256.0;
04270     break;
04271       case 23:
04272     if (type == 3) iso_speed = get2();
04273     break;
04274       case 36: case 37: case 38:
04275     cam_mul[tag-0x24] = get2();
04276     break;
04277       case 39:
04278     if (len < 50 || cam_mul[0]) break;
04279     fseek (ifp, 12, SEEK_CUR);
04280     FORC3 cam_mul[c] = get2();
04281     break;
04282       case 2: case 256:         /* ImageWidth */
04283     tiff_ifd[ifd].width = getint(type);
04284     break;
04285       case 3: case 257:         /* ImageHeight */
04286     tiff_ifd[ifd].height = getint(type);
04287     break;
04288       case 258:             /* BitsPerSample */
04289     tiff_ifd[ifd].samples = len;
04290     tiff_ifd[ifd].bps = get2();
04291     break;
04292       case 259:             /* Compression */
04293     tiff_ifd[ifd].comp = get2();
04294     break;
04295       case 262:             /* PhotometricInterpretation */
04296     tiff_ifd[ifd].phint = get2();
04297     break;
04298       case 271:             /* Make */
04299     fgets (make, 64, ifp);
04300     break;
04301       case 272:             /* Model */
04302     fgets (model, 64, ifp);
04303     break;
04304       case 273:             /* StripOffset */
04305       case 513:
04306     tiff_ifd[ifd].offset = get4()+base;
04307     if (!tiff_ifd[ifd].bps) {
04308       fseek (ifp, tiff_ifd[ifd].offset, SEEK_SET);
04309       if (ljpeg_start (&jh, 1)) {
04310         tiff_ifd[ifd].comp    = 6;
04311         tiff_ifd[ifd].width   = jh.wide << (jh.clrs == 2);
04312         tiff_ifd[ifd].height  = jh.high;
04313         tiff_ifd[ifd].bps     = jh.bits;
04314         tiff_ifd[ifd].samples = jh.clrs;
04315       }
04316     }
04317     break;
04318       case 274:             /* Orientation */
04319     tiff_ifd[ifd].flip = "50132467"[get2() & 7]-'0';
04320     break;
04321       case 277:             /* SamplesPerPixel */
04322     tiff_ifd[ifd].samples = getint(type);
04323     break;
04324       case 279:             /* StripByteCounts */
04325       case 514:
04326     tiff_ifd[ifd].bytes = get4();
04327     break;
04328       case 305:             /* Software */
04329     fgets (software, 64, ifp);
04330     if (!strncmp(software,"Adobe",5) ||
04331         !strncmp(software,"dcraw",5) ||
04332         !strncmp(software,"Bibble",6) ||
04333         !strncmp(software,"Nikon Scan",10) ||
04334         !strcmp (software,"Digital Photo Professional"))
04335       is_raw = 0;
04336     break;
04337       case 306:             /* DateTime */
04338     get_timestamp(0);
04339     break;
04340       case 323:             /* TileLength */
04341     tile_length = getint(type);
04342     break;
04343       case 324:             /* TileOffsets */
04344     tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4();
04345     if (len == 4) load_raw = &CLASS sinar_4shot_load_raw;
04346     break;
04347       case 330:             /* SubIFDs */
04348     if (!strcmp(model,"DSLR-A100") && tiff_ifd[ifd].width == 3872) {
04349       data_offset = get4()+base;
04350       ifd++;  break;
04351     }
04352     while (len--) {
04353       i = ftell(ifp);
04354       fseek (ifp, get4()+base, SEEK_SET);
04355       if (parse_tiff_ifd (base, level+1)) break;
04356       fseek (ifp, i+4, SEEK_SET);
04357     }
04358     break;
04359       case 400:
04360     strcpy (make, "Sarnoff");
04361     maximum = 0xfff;
04362     break;
04363       case 29184: sony_offset = get4();  break;
04364       case 29185: sony_length = get4();  break;
04365       case 29217: sony_key    = get4();  break;
04366       case 29443:
04367     FORC4 cam_mul[c ^ (c < 2)] = get2();
04368     break;
04369       case 33405:           /* Model2 */
04370     fgets (model2, 64, ifp);
04371     break;
04372       case 33422:           /* CFAPattern */
04373       case 64777:           /* Kodak P-series */
04374     if ((plen=len) > 16) plen = 16;
04375     fread (cfa_pat, 1, plen, ifp);
04376     for (colors=cfa=i=0; i < plen; i++) {
04377       colors += !(cfa & (1 << cfa_pat[i]));
04378       cfa |= 1 << cfa_pat[i];
04379     }
04380     if (cfa == 070) memcpy (cfa_pc,"\003\004\005",3);   /* CMY */
04381     if (cfa == 072) memcpy (cfa_pc,"\005\003\004\001",4);   /* GMCY */
04382     goto guess_cfa_pc;
04383       case 33424:
04384     fseek (ifp, get4()+base, SEEK_SET);
04385     parse_kodak_ifd (base);
04386     break;
04387       case 33434:           /* ExposureTime */
04388     shutter = getrat();
04389     break;
04390       case 33437:           /* FNumber */
04391     aperture = getrat();
04392     break;
04393       case 34306:           /* Leaf white balance */
04394     FORC4 cam_mul[c ^ 1] = 4096.0 / get2();
04395     break;
04396       case 34307:           /* Leaf CatchLight color matrix */
04397     fread (software, 1, 7, ifp);
04398     if (strncmp(software,"MATRIX",6)) break;
04399     colors = 4;
04400     for (raw_color = i=0; i < 3; i++) {
04401       FORC4 fscanf (ifp, "%f", &rgb_cam[i][c^1]);
04402       if (!use_camera_wb) continue;
04403       num = 0;
04404       FORC4 num += rgb_cam[i][c];
04405       FORC4 rgb_cam[i][c] /= num;
04406     }
04407     break;
04408       case 34310:           /* Leaf metadata */
04409     parse_mos (ftell(ifp));
04410       case 34303:
04411     strcpy (make, "Leaf");
04412     break;
04413       case 34665:           /* EXIF tag */
04414     fseek (ifp, get4()+base, SEEK_SET);
04415     parse_exif (base);
04416     break;
04417       case 34675:           /* InterColorProfile */
04418       case 50831:           /* AsShotICCProfile */
04419     profile_offset = ftell(ifp);
04420     profile_length = len;
04421     break;
04422       case 37122:           /* CompressedBitsPerPixel */
04423     kodak_cbpp = get4();
04424     break;
04425       case 37386:           /* FocalLength */
04426     focal_len = getrat();
04427     break;
04428       case 37393:           /* ImageNumber */
04429     shot_order = getint(type);
04430     break;
04431       case 37400:           /* old Kodak KDC tag */
04432     for (raw_color = i=0; i < 3; i++) {
04433       getrat();
04434       FORC3 rgb_cam[i][c] = getrat();
04435     }
04436     break;
04437       case 46275:           /* Imacon tags */
04438     strcpy (make, "Imacon");
04439     data_offset = ftell(ifp);
04440     ima_len = len;
04441     break;
04442       case 46279:
04443     fseek (ifp, 78, SEEK_CUR);
04444     raw_width  = get4();
04445     raw_height = get4();
04446     left_margin = get4() & 7;
04447     width = raw_width - left_margin - (get4() & 7);
04448     top_margin = get4() & 7;
04449     height = raw_height - top_margin - (get4() & 7);
04450     fseek (ifp, 52, SEEK_CUR);
04451     FORC3 cam_mul[c] = getreal(11);
04452     fseek (ifp, 114, SEEK_CUR);
04453     flip = (get2() >> 7) * 90;
04454     if (width * height * 6 == ima_len) {
04455       if (flip % 180 == 90) SWAP(width,height);
04456       filters = flip = 0;
04457     }
04458     break;
04459       case 50454:           /* Sinar tag */
04460       case 50455:
04461     if (!(cbuf = (char *) malloc(len))) break;
04462     fread (cbuf, 1, len, ifp);
04463     for (cp = cbuf-1; cp && cp < cbuf+len; cp = strchr(cp,'\n'))
04464       if (!strncmp (++cp,"Neutral ",8))
04465         sscanf (cp+8, "%f %f %f", cam_mul, cam_mul+1, cam_mul+2);
04466     free (cbuf);
04467     break;
04468       case 50706:           /* DNGVersion */
04469     FORC4 dng_version = (dng_version << 8) + fgetc(ifp);
04470     break;
04471       case 50710:           /* CFAPlaneColor */
04472     if (len > 4) len = 4;
04473     colors = len;
04474     fread (cfa_pc, 1, colors, ifp);
04475 guess_cfa_pc:
04476     FORCC tab[cfa_pc[c]] = c;
04477     cdesc[c] = 0;
04478     for (i=16; i--; )
04479       filters = filters << 2 | tab[cfa_pat[i % plen]];
04480     break;
04481       case 50711:           /* CFALayout */
04482     if (get2() == 2) {
04483       fuji_width = 1;
04484       filters = 0x49494949;
04485     }
04486     break;
04487       case 291:
04488       case 50712:           /* LinearizationTable */
04489     linear_table (len);
04490     break;
04491       case 50714:           /* BlackLevel */
04492       case 50715:           /* BlackLevelDeltaH */
04493       case 50716:           /* BlackLevelDeltaV */
04494     for (dblack=i=0; i < len; i++)
04495       dblack += getreal(type);
04496     black += dblack/len + 0.5;
04497     break;
04498       case 50717:           /* WhiteLevel */
04499     maximum = getint(type);
04500     break;
04501       case 50718:           /* DefaultScale */
04502     sx = getrat();
04503     sy = getrat();
04504     if (sx > sy) xmag = sx / sy;
04505     else         ymag = sy / sx;
04506     break;
04507       case 50721:           /* ColorMatrix1 */
04508       case 50722:           /* ColorMatrix2 */
04509     FORCC for (j=0; j < 3; j++)
04510       cm[c][j] = getrat();
04511     use_cm = 1;
04512     break;
04513       case 50723:           /* CameraCalibration1 */
04514       case 50724:           /* CameraCalibration2 */
04515     for (i=0; i < colors; i++)
04516       FORCC cc[i][c] = getrat();
04517       case 50727:           /* AnalogBalance */
04518     FORCC ab[c] = getrat();
04519     break;
04520       case 50728:           /* AsShotNeutral */
04521     FORCC asn[c] = getreal(type);
04522     break;
04523       case 50729:           /* AsShotWhiteXY */
04524     xyz[0] = getrat();
04525     xyz[1] = getrat();
04526     xyz[2] = 1 - xyz[0] - xyz[1];
04527     FORC3 xyz[c] /= d65_white[c];
04528     break;
04529       case 50740:           /* DNGPrivateData */
04530     if (dng_version) break;
04531     i = order;
04532     parse_minolta (j = get4()+base);
04533     order = i;
04534     fseek (ifp, j, SEEK_SET);
04535     parse_tiff_ifd (base, level+1);
04536     break;
04537       case 50752:
04538     read_shorts (cr2_slice, 3);
04539     break;
04540       case 50829:           /* ActiveArea */
04541     top_margin = getint(type);
04542     left_margin = getint(type);
04543     height = getint(type) - top_margin;
04544     width = getint(type) - left_margin;
04545     break;
04546       case 64772:           /* Kodak P-series */
04547     fseek (ifp, 16, SEEK_CUR);
04548     data_offset = get4();
04549     fseek (ifp, 28, SEEK_CUR);
04550     data_offset += get4();
04551     load_raw = &CLASS packed_12_load_raw;
04552     }
04553     fseek (ifp, save, SEEK_SET);
04554   }
04555   if (sony_length && (buf = (unsigned *) malloc(sony_length))) {
04556     fseek (ifp, sony_offset, SEEK_SET);
04557     fread (buf, sony_length, 1, ifp);
04558     sony_decrypt (buf, sony_length/4, 1, sony_key);
04559     sfp = ifp;
04560     if ((ifp = tmpfile())) {
04561       fwrite (buf, sony_length, 1, ifp);
04562       fseek (ifp, 0, SEEK_SET);
04563       parse_tiff_ifd (-sony_offset, level);
04564       fclose (ifp);
04565     }
04566     ifp = sfp;
04567     free (buf);
04568   }
04569   for (i=0; i < colors; i++)
04570     FORCC cc[i][c] *= ab[i];
04571   if (use_cm) {
04572     FORCC for (i=0; i < 3; i++)
04573       for (cam_xyz[c][i]=j=0; j < colors; j++)
04574     cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i];
04575     cam_xyz_coeff (cam_xyz);
04576   }
04577   if (asn[0])
04578     FORCC pre_mul[c] = 1 / asn[c];
04579   if (!use_cm)
04580     FORCC pre_mul[c] /= cc[c][c];
04581   return 0;
04582 }
04583 
04584 void CLASS parse_tiff (int base)
04585 {
04586   int doff, max_samp=0, raw=-1, thm=-1, i;
04587   struct jhead jh;
04588 
04589   fseek (ifp, base, SEEK_SET);
04590   order = get2();
04591   if (order != 0x4949 && order != 0x4d4d) return;
04592   get2();
04593   memset (tiff_ifd, 0, sizeof tiff_ifd);
04594   tiff_nifds = 0;
04595   while ((doff = get4())) {
04596     fseek (ifp, doff+base, SEEK_SET);
04597     if (parse_tiff_ifd (base, 0)) break;
04598   }
04599   thumb_misc = 16;
04600   if (thumb_offset) {
04601     fseek (ifp, thumb_offset, SEEK_SET);
04602     if (ljpeg_start (&jh, 1)) {
04603       thumb_misc   = jh.bits;
04604       thumb_width  = jh.wide;
04605       thumb_height = jh.high;
04606     }
04607   }
04608   for (i=0; i < tiff_nifds; i++) {
04609     if (max_samp < tiff_ifd[i].samples)
04610     max_samp = tiff_ifd[i].samples;
04611     if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) &&
04612     tiff_ifd[i].width*tiff_ifd[i].height > raw_width*raw_height) {
04613       raw_width     = tiff_ifd[i].width;
04614       raw_height    = tiff_ifd[i].height;
04615       tiff_bps      = tiff_ifd[i].bps;
04616       tiff_compress = tiff_ifd[i].comp;
04617       data_offset   = tiff_ifd[i].offset;
04618       tiff_flip     = tiff_ifd[i].flip;
04619       tiff_samples  = tiff_ifd[i].samples;
04620       fuji_secondary = tiff_samples == 2;
04621       raw = i;
04622     }
04623   }
04624   fuji_width *= (raw_width+1)/2;
04625   if (tiff_ifd[0].flip) tiff_flip = tiff_ifd[0].flip;
04626   if (raw >= 0 && !load_raw)
04627     switch (tiff_compress) {
04628       case 0:  case 1:
04629     load_raw = tiff_bps > 8 ?
04630       &CLASS unpacked_load_raw : &CLASS eight_bit_load_raw;
04631     if (tiff_ifd[raw].bytes * 5 == raw_width * raw_height * 8)
04632       load_raw = &CLASS olympus_e300_load_raw;
04633     break;
04634       case 6:  case 7:  case 99:
04635     load_raw = &CLASS lossless_jpeg_load_raw;       break;
04636       case 262:
04637     load_raw = &CLASS kodak_262_load_raw;           break;
04638       case 32773:
04639     load_raw = &CLASS packed_12_load_raw;           break;
04640       case 65535:
04641     load_raw = &CLASS pentax_k10_load_raw;          break;
04642       case 65000:
04643     switch (tiff_ifd[raw].phint) {
04644       case 2: load_raw = &CLASS kodak_rgb_load_raw;   filters = 0;  break;
04645       case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0;  break;
04646       case 32803: load_raw = &CLASS kodak_65000_load_raw;
04647     }
04648     }
04649   if (tiff_samples == 3 && tiff_bps == 8)
04650     if (!dng_version) is_raw = 0;
04651   for (i=0; i < tiff_nifds; i++)
04652     if (i != raw && tiff_ifd[i].samples == max_samp &&
04653     tiff_ifd[i].width * tiff_ifd[i].height / SQR(tiff_ifd[i].bps+1) >
04654           thumb_width *       thumb_height / SQR(thumb_misc+1)) {
04655       thumb_width  = tiff_ifd[i].width;
04656       thumb_height = tiff_ifd[i].height;
04657       thumb_offset = tiff_ifd[i].offset;
04658       thumb_length = tiff_ifd[i].bytes;
04659       thumb_misc   = tiff_ifd[i].bps;
04660       thm = i;
04661     }
04662   if (thm >= 0) {
04663     thumb_misc |= tiff_ifd[thm].samples << 5;
04664     switch (tiff_ifd[thm].comp) {
04665       case 0:
04666     write_thumb = &CLASS layer_thumb;
04667     break;
04668       case 1:
04669     if (tiff_ifd[thm].bps > 8)
04670       thumb_load_raw = &CLASS kodak_thumb_load_raw;
04671     else
04672       write_thumb = &CLASS ppm_thumb;
04673     break;
04674       case 65000:
04675     thumb_load_raw = tiff_ifd[thm].phint == 6 ?
04676         &CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw;
04677     }
04678   }
04679 }
04680 
04681 void CLASS parse_minolta (int base)
04682 {
04683   int save, tag, len, offset, high=0, wide=0, i, c;
04684 
04685   fseek (ifp, base, SEEK_SET);
04686   if (fgetc(ifp) || fgetc(ifp)-'M' || fgetc(ifp)-'R') return;
04687   order = fgetc(ifp) * 0x101;
04688   offset = base + get4() + 8;
04689   while ((save=ftell(ifp)) < offset) {
04690     for (tag=i=0; i < 4; i++)
04691       tag = tag << 8 | fgetc(ifp);
04692     len = get4();
04693     switch (tag) {
04694       case 0x505244:                /* PRD */
04695     fseek (ifp, 8, SEEK_CUR);
04696     high = get2();
04697     wide = get2();
04698     break;
04699       case 0x574247:                /* WBG */
04700     get4();
04701     i = strstr(model,"A200") ? 3:0;
04702     FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2();
04703     break;
04704       case 0x545457:                /* TTW */
04705     parse_tiff (ftell(ifp));
04706     data_offset = offset;
04707     }
04708     fseek (ifp, save+len+8, SEEK_SET);
04709   }
04710   raw_height = high;
04711   raw_width  = wide;
04712 }
04713 
04714 /*
04715    Many cameras have a "debug mode" that writes JPEG and raw
04716    at the same time.  The raw file has no header, so try to
04717    to open the matching JPEG file and read its metadata.
04718  */
04719 void CLASS parse_external_jpeg()
04720 {
04721   char *file, *ext, *jname, *jfile, *jext;
04722   FILE *save=ifp;
04723 
04724   ext  = strrchr (ifname, '.');
04725   file = strrchr (ifname, '/');
04726   if (!file) file = strrchr (ifname, '\\');
04727   if (!file) file = ifname-1;
04728   file++;
04729   if (!ext || strlen(ext) != 4 || ext-file != 8) return;
04730   jname = (char *) malloc (strlen(ifname) + 1);
04731   merror (jname, "parse_external()");
04732   strcpy (jname, ifname);
04733   jfile = file - ifname + jname;
04734   jext  = ext  - ifname + jname;
04735   if (strcasecmp (ext, ".jpg")) {
04736     strcpy (jext, isupper(ext[1]) ? ".JPG":".jpg");
04737     memcpy (jfile, file+4, 4);
04738     memcpy (jfile+4, file, 4);
04739   } else
04740     while (isdigit(*--jext)) {
04741       if (*jext != '9') {
04742         (*jext)++;
04743     break;
04744       }
04745       *jext = '0';
04746     }
04747   if (strcmp (jname, ifname)) {
04748     if ((ifp = fopen (jname, "rb"))) {
04749       if (verbose)
04750     fprintf (stderr, "Reading metadata from %s...\n", jname);
04751       parse_tiff (12);
04752       thumb_offset = 0;
04753       is_raw = 1;
04754       fclose (ifp);
04755     }
04756   }
04757   if (!timestamp)
04758     fprintf (stderr, "Failed to read metadata from %s\n", jname);
04759   free (jname);
04760   ifp = save;
04761 }
04762 
04763 /*
04764    CIFF block 0x1030 contains an 8x8 white sample.
04765    Load this into white[][] for use in scale_colors().
04766  */
04767 void CLASS ciff_block_1030()
04768 {
04769   static const ushort key[] = { 0x410, 0x45f3 };
04770   int i, bpp, row, col, vbits=0;
04771   unsigned long bitbuf=0;
04772 
04773   if ((get2(),get4()) != 0x80008 || !get4()) return;
04774   bpp = get2();
04775   if (bpp != 10 && bpp != 12) return;
04776   for (i=row=0; row < 8; row++)
04777     for (col=0; col < 8; col++) {
04778       if (vbits < bpp) {
04779     bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]);
04780     vbits += 16;
04781       }
04782       white[row][col] =
04783     bitbuf << (LONG_BIT - vbits) >> (LONG_BIT - bpp);
04784       vbits -= bpp;
04785     }
04786 }
04787 
04788 /*
04789    Parse a CIFF file, better known as Canon CRW format.
04790  */
04791 void CLASS parse_ciff (int offset, int length)
04792 {
04793   int tboff, nrecs, c, type, len, save, wbi=-1;
04794   ushort key[] = { 0x410, 0x45f3 };
04795 
04796   fseek (ifp, offset+length-4, SEEK_SET);
04797   tboff = get4() + offset;
04798   fseek (ifp, tboff, SEEK_SET);
04799   nrecs = get2();
04800   if (nrecs > 100) return;
04801   while (nrecs--) {
04802     type = get2();
04803     len  = get4();
04804     save = ftell(ifp) + 4;
04805     fseek (ifp, offset+get4(), SEEK_SET);
04806     if ((((type >> 8) + 8) | 8) == 0x38)
04807       parse_ciff (ftell(ifp), len); /* Parse a sub-table */
04808 
04809     if (type == 0x080a) {
04810       fread (make, 64, 1, ifp);
04811       fseek (ifp, strlen(make) - 63, SEEK_CUR);
04812       fread (model, 64, 1, ifp);
04813     }
04814     if (type == 0x1810) {
04815       fseek (ifp, 12, SEEK_CUR);
04816       flip = get4();
04817     }
04818     if (type == 0x1835)         /* Get the decoder table */
04819       tiff_compress = get4();
04820     if (type == 0x2007) {
04821       thumb_offset = ftell(ifp);
04822       thumb_length = len;
04823     }
04824     if (type == 0x1818) {
04825       shutter = pow (2, -int_to_float((get4(),get4())));
04826       aperture = pow (2, int_to_float(get4())/2);
04827     }
04828     if (type == 0x102a) {
04829       iso_speed = pow (2, (get4(),get2())/32.0 - 4) * 50;
04830       aperture  = pow (2, (get2(),(short)get2())/64.0);
04831       shutter   = pow (2,-((short)get2())/32.0);
04832       wbi = (get2(),get2());
04833       if (wbi > 17) wbi = 0;
04834       fseek (ifp, 32, SEEK_CUR);
04835       if (shutter > 1e6) shutter = get2()/10.0;
04836     }
04837     if (type == 0x102c) {
04838       if (get2() > 512) {       /* Pro90, G1 */
04839     fseek (ifp, 118, SEEK_CUR);
04840     FORC4 cam_mul[c ^ 2] = get2();
04841       } else {              /* G2, S30, S40 */
04842     fseek (ifp, 98, SEEK_CUR);
04843     FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2();
04844       }
04845     }
04846     if (type == 0x0032) {
04847       if (len == 768) {         /* EOS D30 */
04848     fseek (ifp, 72, SEEK_CUR);
04849     FORC4 cam_mul[c ^ (c >> 1)] = 1024.0 / get2();
04850     if (!wbi) cam_mul[0] = -1;  /* use my auto white balance */
04851       } else if (!cam_mul[0]) {
04852     if (get2() == key[0])       /* Pro1, G6, S60, S70 */
04853       c = (strstr(model,"Pro1") ?
04854           "012346000000000000":"01345:000000006008")[wbi]-'0'+ 2;
04855     else {              /* G3, G5, S45, S50 */
04856       c = "023457000000006000"[wbi]-'0';
04857       key[0] = key[1] = 0;
04858     }
04859     fseek (ifp, 78 + c*8, SEEK_CUR);
04860     FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1];
04861     if (!wbi) cam_mul[0] = -1;
04862       }
04863     }
04864     if (type == 0x10a9) {       /* D60, 10D, 300D, and clones */
04865       if (len > 66) wbi = "0134567028"[wbi]-'0';
04866       fseek (ifp, 2 + wbi*8, SEEK_CUR);
04867       FORC4 cam_mul[c ^ (c >> 1)] = get2();
04868     }
04869     if (type == 0x1030 && (0x18040 >> wbi & 1))
04870       ciff_block_1030();        /* all that don't have 0x10a9 */
04871     if (type == 0x1031) {
04872       raw_width = (get2(),get2());
04873       raw_height = get2();
04874     }
04875     if (type == 0x5029) {
04876       focal_len = len >> 16;
04877       if ((len & 0xffff) == 2) focal_len /= 32;
04878     }
04879     if (type == 0x5813) flash_used = int_to_float(len);
04880     if (type == 0x5814) canon_ev   = int_to_float(len);
04881     if (type == 0x5817) shot_order = len;
04882     if (type == 0x5834) unique_id  = len;
04883     if (type == 0x580e) timestamp  = len;
04884     if (type == 0x180e) timestamp  = get4();
04885 #ifdef LOCALTIME
04886     if ((type | 0x4000) == 0x580e)
04887       timestamp = mktime (gmtime (&timestamp));
04888 #endif
04889     fseek (ifp, save, SEEK_SET);
04890   }
04891 }
04892 
04893 void CLASS parse_rollei()
04894 {
04895   char line[128], *val;
04896   struct tm t;
04897 
04898   fseek (ifp, 0, SEEK_SET);
04899   memset (&t, 0, sizeof t);
04900   do {
04901     fgets (line, 128, ifp);
04902     if ((val = strchr(line,'=')))
04903       *val++ = 0;
04904     else
04905       val = line + strlen(line);
04906     if (!strcmp(line,"DAT"))
04907       sscanf (val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year);
04908     if (!strcmp(line,"TIM"))
04909       sscanf (val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec);
04910     if (!strcmp(line,"HDR"))
04911       thumb_offset = atoi(val);
04912     if (!strcmp(line,"X  "))
04913       raw_width = atoi(val);
04914     if (!strcmp(line,"Y  "))
04915       raw_height = atoi(val);
04916     if (!strcmp(line,"TX "))
04917       thumb_width = atoi(val);
04918     if (!strcmp(line,"TY "))
04919       thumb_height = atoi(val);
04920   } while (strncmp(line,"EOHD",4));
04921   data_offset = thumb_offset + thumb_width * thumb_height * 2;
04922   t.tm_year -= 1900;
04923   t.tm_mon -= 1;
04924   if (mktime(&t) > 0)
04925     timestamp = mktime(&t);
04926   strcpy (make, "Rollei");
04927   strcpy (model,"d530flex");
04928   write_thumb = &CLASS rollei_thumb;
04929 }
04930 
04931 void CLASS parse_phase_one (int base)
04932 {
04933   unsigned entries, tag, type, len, data, save, i, c;
04934   float romm_cam[3][3];
04935   char *cp;
04936 
04937   memset (&ph1, 0, sizeof ph1);
04938   fseek (ifp, base, SEEK_SET);
04939   order = get4() & 0xffff;
04940   if (get4() >> 8 != 0x526177) return;      /* "Raw" */
04941   fseek (ifp, base+get4(), SEEK_SET);
04942   entries = get4();
04943   get4();
04944   while (entries--) {
04945     tag  = get4();
04946     type = get4();
04947     len  = get4();
04948     data = get4();
04949     save = ftell(ifp);
04950     fseek (ifp, base+data, SEEK_SET);
04951     switch (tag) {
04952       case 0x100:  flip = "0653"[data & 3]-'0';  break;
04953       case 0x106:
04954     for (i=0; i < 9; i++)
04955       romm_cam[0][i] = getreal(11);
04956     romm_coeff (romm_cam);
04957     break;
04958       case 0x107:
04959     FORC3 cam_mul[c] = pre_mul[c] = getreal(11);
04960     break;
04961       case 0x108:  raw_width     = data;    break;
04962       case 0x109:  raw_height    = data;    break;
04963       case 0x10a:  left_margin   = data;    break;
04964       case 0x10b:  top_margin    = data;    break;
04965       case 0x10c:  width         = data;    break;
04966       case 0x10d:  height        = data;    break;
04967       case 0x10e:  ph1.format    = data;    break;
04968       case 0x10f:  data_offset   = data+base;   break;
04969       case 0x110:  meta_offset   = data+base;
04970            meta_length   = len;         break;
04971       case 0x112:  ph1.key_off   = save - 4;        break;
04972       case 0x210:  ph1.tag_210   = int_to_float(data);  break;
04973       case 0x21a:  ph1.tag_21a   = data;        break;
04974       case 0x21c:  strip_offset  = data+base;       break;
04975       case 0x21d:  ph1.black     = data;        break;
04976       case 0x222:  ph1.split_col = data - left_margin;  break;
04977       case 0x223:  ph1.black_off = data+base;       break;
04978       case 0x301:
04979     model[63] = 0;
04980     fread (model, 1, 63, ifp);
04981     if ((cp = strstr(model," camera"))) *cp = 0;
04982     }
04983     fseek (ifp, save, SEEK_SET);
04984   }
04985   load_raw = ph1.format < 3 ?
04986     &CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c;
04987   maximum = 0xffff;
04988   strcpy (make, "Phase One");
04989   if (model[0]) return;
04990   switch (raw_height) {
04991     case 2060: strcpy (model,"LightPhase"); break;
04992     case 2682: strcpy (model,"H 10");       break;
04993     case 4128: strcpy (model,"H 20");       break;
04994     case 5488: strcpy (model,"H 25");       break;
04995   }
04996 }
04997 
04998 void CLASS parse_fuji (int offset)
04999 {
05000   unsigned entries, tag, len, save, c;
05001 
05002   fseek (ifp, offset, SEEK_SET);
05003   entries = get4();
05004   if (entries > 255) return;
05005   while (entries--) {
05006     tag = get2();
05007     len = get2();
05008     save = ftell(ifp);
05009     if (tag == 0x100) {
05010       raw_height = get2();
05011       raw_width  = get2();
05012     } else if (tag == 0x121) {
05013       height = get2();
05014       if ((width = get2()) == 4284) width += 3;
05015     } else if (tag == 0x130)
05016       fuji_layout = fgetc(ifp) >> 7;
05017     if (tag == 0x2ff0)
05018       FORC4 cam_mul[c ^ 1] = get2();
05019     fseek (ifp, save+len, SEEK_SET);
05020   }
05021   if (fuji_layout) {
05022     height *= 2;
05023     width  /= 2;
05024   }
05025 }
05026 
05027 int CLASS parse_jpeg (int offset)
05028 {
05029   int len, save, hlen, mark;
05030 
05031   fseek (ifp, offset, SEEK_SET);
05032   if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0;
05033 
05034   while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) {
05035     order = 0x4d4d;
05036     len   = get2() - 2;
05037     save  = ftell(ifp);
05038     if (mark == 0xc0 || mark == 0xc3) {
05039       fgetc(ifp);
05040       raw_height = get2();
05041       raw_width  = get2();
05042     }
05043     order = get2();
05044     hlen  = get4();
05045     if (get4() == 0x48454150)       /* "HEAP" */
05046       parse_ciff (save+hlen, len-hlen);
05047     parse_tiff (save+6);
05048     fseek (ifp, save+len, SEEK_SET);
05049   }
05050   return 1;
05051 }
05052 
05053 void CLASS parse_riff()
05054 {
05055   unsigned i, size, end;
05056   char tag[4], date[64], month[64];
05057   static const char mon[12][4] =
05058   { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" };
05059   struct tm t;
05060 
05061   order = 0x4949;
05062   fread (tag, 4, 1, ifp);
05063   size = get4();
05064   if (!memcmp(tag,"RIFF",4) || !memcmp(tag,"LIST",4)) {
05065     end = ftell(ifp) + size;
05066     get4();
05067     while (ftell(ifp) < end)
05068       parse_riff();
05069   } else if (!memcmp(tag,"IDIT",4) && size < 64) {
05070     fread (date, 64, 1, ifp);
05071     date[size] = 0;
05072     memset (&t, 0, sizeof t);
05073     if (sscanf (date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday,
05074     &t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) {
05075       for (i=0; i < 12 && strcmp(mon[i],month); i++);
05076       t.tm_mon = i;
05077       t.tm_year -= 1900;
05078       if (mktime(&t) > 0)
05079     timestamp = mktime(&t);
05080     }
05081   } else
05082     fseek (ifp, size, SEEK_CUR);
05083 }
05084 
05085 void CLASS parse_smal (int offset, int fsize)
05086 {
05087   int ver;
05088 
05089   fseek (ifp, offset+2, SEEK_SET);
05090   order = 0x4949;
05091   ver = fgetc(ifp);
05092   if (ver == 6)
05093     fseek (ifp, 5, SEEK_CUR);
05094   if (get4() != fsize) return;
05095   if (ver > 6) data_offset = get4();
05096   raw_height = height = get2();
05097   raw_width  = width  = get2();
05098   strcpy (make, "SMaL");
05099   sprintf (model, "v%d %dx%d", ver, width, height);
05100   if (ver == 6) load_raw = &CLASS smal_v6_load_raw;
05101   if (ver == 9) load_raw = &CLASS smal_v9_load_raw;
05102 }
05103 
05104 char * CLASS foveon_gets (int offset, char *str, int len)
05105 {
05106   int i;
05107   fseek (ifp, offset, SEEK_SET);
05108   for (i=0; i < len-1; i++)
05109     if ((str[i] = get2()) == 0) break;
05110   str[i] = 0;
05111   return str;
05112 }
05113 
05114 void CLASS parse_foveon()
05115 {
05116   int entries, img=0, off, len, tag, save, i, wide, high, pent, poff[256][2];
05117   char name[64], value[64];
05118 
05119   order = 0x4949;           /* Little-endian */
05120   fseek (ifp, 36, SEEK_SET);
05121   flip = get4();
05122   fseek (ifp, -4, SEEK_END);
05123   fseek (ifp, get4(), SEEK_SET);
05124   if (get4() != 0x64434553) return; /* SECd */
05125   entries = (get4(),get4());
05126   while (entries--) {
05127     off = get4();
05128     len = get4();
05129     tag = get4();
05130     save = ftell(ifp);
05131     fseek (ifp, off, SEEK_SET);
05132     if (get4() != (0x20434553 | (tag << 24))) return;
05133     switch (tag) {
05134       case 0x47414d49:          /* IMAG */
05135       case 0x32414d49:          /* IMA2 */
05136     fseek (ifp, 12, SEEK_CUR);
05137     wide = get4();
05138     high = get4();
05139     if (wide > raw_width && high > raw_height) {
05140       raw_width  = wide;
05141       raw_height = high;
05142       data_offset = off+24;
05143     }
05144     fseek (ifp, off+28, SEEK_SET);
05145     if (fgetc(ifp) == 0xff && fgetc(ifp) == 0xd8) {
05146       thumb_offset = off+28;
05147       thumb_length = len-28;
05148     }
05149     if (++img == 2 && !thumb_length) {
05150       thumb_offset = off+24;
05151       thumb_width = wide;
05152       thumb_height = high;
05153       write_thumb = &CLASS foveon_thumb;
05154     }
05155     break;
05156       case 0x464d4143:          /* CAMF */
05157     meta_offset = off+24;
05158     meta_length = len-28;
05159     if (meta_length > 0x20000)
05160         meta_length = 0x20000;
05161     break;
05162       case 0x504f5250:          /* PROP */
05163     pent = (get4(),get4());
05164     fseek (ifp, 12, SEEK_CUR);
05165     off += pent*8 + 24;
05166     if (pent > 256) pent=256;
05167     for (i=0; i < pent*2; i++)
05168       poff[0][i] = off + get4()*2;
05169     for (i=0; i < pent; i++) {
05170       foveon_gets (poff[i][0], name, 64);
05171       foveon_gets (poff[i][1], value, 64);
05172       if (!strcmp (name, "ISO"))
05173         iso_speed = atoi(value);
05174       if (!strcmp (name, "CAMMANUF"))
05175         strcpy (make, value);
05176       if (!strcmp (name, "CAMMODEL"))
05177         strcpy (model, value);
05178       if (!strcmp (name, "WB_DESC"))
05179         strcpy (model2, value);
05180       if (!strcmp (name, "TIME"))
05181         timestamp = atoi(value);
05182       if (!strcmp (name, "EXPTIME"))
05183         shutter = atoi(value) / 1000000.0;
05184       if (!strcmp (name, "APERTURE"))
05185         aperture = atof(value);
05186       if (!strcmp (name, "FLENGTH"))
05187         focal_len = atof(value);
05188     }
05189 #ifdef LOCALTIME
05190     timestamp = mktime (gmtime (&timestamp));
05191 #endif
05192     }
05193     fseek (ifp, save, SEEK_SET);
05194   }
05195   is_foveon = 1;
05196 }
05197 
05198 /*
05199    Thanks to Adobe for providing these excellent CAM -> XYZ matrices!
05200  */
05201 void CLASS adobe_coeff (char *make, char *model)
05202 {
05203   static const struct {
05204     const char *prefix;
05205     short black, trans[12];
05206   } table[] = {
05207     { "Canon EOS D2000", 0,
05208     { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } },
05209     { "Canon EOS D6000", 0,
05210     { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } },
05211     { "Canon EOS D30", 0,
05212     { 9805,-2689,-1312,-5803,13064,3068,-2438,3075,8775 } },
05213     { "Canon EOS D60", 0,
05214     { 6188,-1341,-890,-7168,14489,2937,-2640,3228,8483 } },
05215     { "Canon EOS 5D", 0,
05216     { 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } },
05217     { "Canon EOS 20Da", 0,
05218     { 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } },
05219     { "Canon EOS 20D", 0,
05220     { 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } },
05221     { "Canon EOS 30D", 0,
05222     { 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } },
05223     { "Canon EOS 350D", 0,
05224     { 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } },
05225     { "Canon EOS 400D", 0,
05226     { 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } },
05227     { "Canon EOS-1Ds Mark II", 0,
05228     { 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } },
05229     { "Canon EOS-1D Mark II N", 0,
05230     { 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } },
05231     { "Canon EOS-1D Mark II", 0,
05232     { 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } },
05233     { "Canon EOS-1DS", 0,
05234     { 4374,3631,-1743,-7520,15212,2472,-2892,3632,8161 } },
05235     { "Canon EOS-1D", 0,
05236     { 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } },
05237     { "Canon EOS", 0,
05238     { 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } },
05239     { "Canon PowerShot A50", 0,
05240     { -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } },
05241     { "Canon PowerShot A5", 0,
05242     { -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } },
05243     { "Canon PowerShot G1", 0,
05244     { -4778,9467,2172,4743,-1141,4344,-5146,9908,6077,-1566,11051,557 } },
05245     { "Canon PowerShot G2", 0,
05246     { 9087,-2693,-1049,-6715,14382,2537,-2291,2819,7790 } },
05247     { "Canon PowerShot G3", 0,
05248     { 9212,-2781,-1073,-6573,14189,2605,-2300,2844,7664 } },
05249     { "Canon PowerShot G5", 0,
05250     { 9757,-2872,-933,-5972,13861,2301,-1622,2328,7212 } },
05251     { "Canon PowerShot G6", 0,
05252     { 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } },
05253     { "Canon PowerShot Pro1", 0,
05254     { 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } },
05255     { "Canon PowerShot Pro70", 34,
05256     { -4155,9818,1529,3939,-25,4522,-5521,9870,6610,-2238,10873,1342 } },
05257     { "Canon PowerShot Pro90", 0,
05258     { -4963,9896,2235,4642,-987,4294,-5162,10011,5859,-1770,11230,577 } },
05259     { "Canon PowerShot S30", 0,
05260     { 10566,-3652,-1129,-6552,14662,2006,-2197,2581,7670 } },
05261     { "Canon PowerShot S40", 0,
05262     { 8510,-2487,-940,-6869,14231,2900,-2318,2829,9013 } },
05263     { "Canon PowerShot S45", 0,
05264     { 8163,-2333,-955,-6682,14174,2751,-2077,2597,8041 } },
05265     { "Canon PowerShot S50", 0,
05266     { 8882,-2571,-863,-6348,14234,2288,-1516,2172,6569 } },
05267     { "Canon PowerShot S60", 0,
05268     { 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } },
05269     { "Canon PowerShot S70", 0,
05270     { 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } },
05271     { "Canon PowerShot A610", 0, /* copied from the S60 */
05272     { 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } },
05273     { "Canon PowerShot A620", 0, /* DJC */
05274     { 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } },
05275     { "Contax N Digital", 0,
05276     { 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } },
05277     { "EPSON R-D1", 0,
05278     { 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } },
05279     { "FUJIFILM FinePix E550", 0,
05280     { 11044,-3888,-1120,-7248,15168,2208,-1531,2277,8069 } },
05281     { "FUJIFILM FinePix E900", 0,
05282     { 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } },
05283     { "FUJIFILM FinePix F8", 0,
05284     { 11044,-3888,-1120,-7248,15168,2208,-1531,2277,8069 } },
05285     { "FUJIFILM FinePix F7", 0,
05286     { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
05287     { "FUJIFILM FinePix S20Pro", 0,
05288     { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
05289     { "FUJIFILM FinePix S2Pro", 128,
05290     { 12492,-4690,-1402,-7033,15423,1647,-1507,2111,7697 } },
05291     { "FUJIFILM FinePix S3Pro", 0,
05292     { 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } },
05293     { "FUJIFILM FinePix S5000", 0,
05294     { 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } },
05295     { "FUJIFILM FinePix S5100", 0,
05296     { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
05297     { "FUJIFILM FinePix S5500", 0,
05298     { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
05299     { "FUJIFILM FinePix S5200", 0,
05300     { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
05301     { "FUJIFILM FinePix S5600", 0,
05302     { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
05303     { "FUJIFILM FinePix S7000", 0,
05304     { 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } },
05305     { "FUJIFILM FinePix S9000", 0,
05306     { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
05307     { "FUJIFILM FinePix S9500", 0,
05308     { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
05309     { "FUJIFILM FinePix S9100", 0,
05310     { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
05311     { "FUJIFILM FinePix S9600", 0,
05312     { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
05313     { "Imacon Ixpress", 0,  /* DJC */
05314     { 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } },
05315     { "KODAK NC2000", 0,    /* DJC */
05316     { 16475,-6903,-1218,-851,10375,477,2505,-7,1020 } },
05317     { "Kodak DCS315C", 8,
05318     { 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } },
05319     { "Kodak DCS330C", 8,
05320     { 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } },
05321     { "KODAK DCS420", 0,
05322     { 10868,-1852,-644,-1537,11083,484,2343,628,2216 } },
05323     { "KODAK DCS460", 0,
05324     { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
05325     { "KODAK EOSDCS1", 0,
05326     { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
05327     { "KODAK EOSDCS3B", 0,
05328     { 9898,-2700,-940,-2478,12219,206,1985,634,1031 } },
05329     { "Kodak DCS520C", 180,
05330     { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } },
05331     { "Kodak DCS560C", 188,
05332     { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } },
05333     { "Kodak DCS620C", 180,
05334     { 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } },
05335     { "Kodak DCS620X", 185,
05336     { 13095,-6231,154,12221,-21,-2137,895,4602,2258 } },
05337     { "Kodak DCS660C", 214,
05338     { 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } },
05339     { "Kodak DCS720X", 0,
05340     { 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } },
05341     { "Kodak DCS760C", 0,
05342     { 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } },
05343     { "Kodak DCS Pro SLR", 0,
05344     { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
05345     { "Kodak DCS Pro 14nx", 0,
05346     { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
05347     { "Kodak DCS Pro 14", 0,
05348     { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } },
05349     { "Kodak ProBack645", 0,
05350     { 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } },
05351     { "Kodak ProBack", 0,
05352     { 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } },
05353     { "KODAK P712", 0,
05354     { 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } },
05355     { "KODAK P850", 0,
05356     { 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } },
05357     { "KODAK P880", 0,
05358     { 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } },
05359     { "Leaf CMost", 0,
05360     { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
05361     { "Leaf Valeo 6", 0,
05362     { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
05363     { "Leaf Aptus 65", 0,
05364     { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
05365     { "Leaf Aptus 75", 0,
05366     { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
05367     { "Leaf", 0,
05368     { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
05369     { "Micron 2010", 110,   /* DJC */
05370     { 16695,-3761,-2151,155,9682,163,3433,951,4904 } },
05371     { "Minolta DiMAGE 5", 0,
05372     { 8983,-2942,-963,-6556,14476,2237,-2426,2887,8014 } },
05373     { "Minolta DiMAGE 7Hi", 0,
05374     { 11368,-3894,-1242,-6521,14358,2339,-2475,3056,7285 } },
05375     { "Minolta DiMAGE 7", 0,
05376     { 9144,-2777,-998,-6676,14556,2281,-2470,3019,7744 } },
05377     { "Minolta DiMAGE A1", 0,
05378     { 9274,-2547,-1167,-8220,16323,1943,-2273,2720,8340 } },
05379     { "MINOLTA DiMAGE A200", 0,
05380     { 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } },
05381     { "Minolta DiMAGE A2", 0,
05382     { 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } },
05383     { "Minolta DiMAGE Z2", 0,   /* DJC */
05384     { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
05385     { "MINOLTA DYNAX 5", 0,
05386     { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
05387     { "MINOLTA DYNAX 7", 0,
05388     { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
05389     { "NIKON D100", 0,
05390     { 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } },
05391     { "NIKON D1H", 0,
05392     { 7577,-2166,-926,-7454,15592,1934,-2377,2808,8606 } },
05393     { "NIKON D1X", 0,
05394     { 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } },
05395     { "NIKON D1", 0,    /* multiplied by 2.218750, 1.0, 1.148438 */
05396     { 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } },
05397     { "NIKON D2H", 0,
05398     { 5710,-901,-615,-8594,16617,2024,-2975,4120,6830 } },
05399     { "NIKON D2X", 0,
05400     { 10231,-2769,-1255,-8301,15900,2552,-797,680,7148 } },
05401     { "NIKON D50", 0,
05402     { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
05403     { "NIKON D70", 0,
05404     { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
05405     { "NIKON D80", 0,
05406     { 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } },
05407     { "NIKON D200", 0,
05408     { 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } },
05409     { "NIKON E950", 0,      /* DJC */
05410     { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
05411     { "NIKON E995", 0,  /* copied from E5000 */
05412     { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
05413     { "NIKON E2500", 0,
05414     { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
05415     { "NIKON E4300", 0, /* copied from Minolta DiMAGE Z2 */
05416     { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
05417     { "NIKON E4500", 0,
05418     { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
05419     { "NIKON E5000", 0,
05420     { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
05421     { "NIKON E5400", 0,
05422     { 9349,-2987,-1001,-7919,15766,2266,-2098,2680,6839 } },
05423     { "NIKON E5700", 0,
05424     { -5368,11478,2368,5537,-113,3148,-4969,10021,5782,778,9028,211 } },
05425     { "NIKON E8400", 0,
05426     { 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } },
05427     { "NIKON E8700", 0,
05428     { 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
05429     { "NIKON E8800", 0,
05430     { 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } },
05431     { "OLYMPUS C5050", 0,
05432     { 10508,-3124,-1273,-6079,14294,1901,-1653,2306,6237 } },
05433     { "OLYMPUS C5060", 0,
05434     { 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } },
05435     { "OLYMPUS C7070", 0,
05436     { 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } },
05437     { "OLYMPUS C70", 0,
05438     { 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } },
05439     { "OLYMPUS C80", 0,
05440     { 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } },
05441     { "OLYMPUS E-10", 0,
05442     { 12745,-4500,-1416,-6062,14542,1580,-1934,2256,6603 } },
05443     { "OLYMPUS E-1", 0,
05444     { 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } },
05445     { "OLYMPUS E-20", 0,
05446     { 13173,-4732,-1499,-5807,14036,1895,-2045,2452,7142 } },
05447     { "OLYMPUS E-300", 0,
05448     { 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } },
05449     { "OLYMPUS E-330", 0,
05450     { 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } },
05451     { "OLYMPUS E-400", 0,
05452     { 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } },
05453     { "OLYMPUS E-500", 0,
05454     { 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } },
05455     { "OLYMPUS SP350", 0,
05456     { 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } },
05457     { "OLYMPUS SP3", 0,
05458     { 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } },
05459     { "OLYMPUS SP500UZ", 0,
05460     { 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } },
05461     { "PENTAX *ist DL2", 0,
05462     { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
05463     { "PENTAX *ist DL", 0,
05464     { 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } },
05465     { "PENTAX *ist DS2", 0,
05466     { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
05467     { "PENTAX *ist DS", 0,
05468     { 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } },
05469     { "PENTAX *ist D", 0,
05470     { 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } },
05471     { "PENTAX K10D", 0,
05472     { 28402,-6651,-983,-14699,32553,6467,-1746,1571,25283 } },
05473     { "PENTAX K1", 0,
05474     { 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } },
05475     { "Panasonic DMC-FZ30", 0,
05476     { 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } },
05477     { "Panasonic DMC-FZ50", 0,
05478     { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
05479     { "Panasonic DMC-LC1", 0,
05480     { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
05481     { "Panasonic DMC-LX1", 0,
05482     { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
05483     { "Panasonic DMC-LX2", 0,
05484     { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
05485     { "SAMSUNG GX-1", 0,
05486     { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
05487     { "Sinar", 0,       /* DJC */
05488     { 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } },
05489     { "SONY DSC-F828", 491,
05490     { 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } },
05491     { "SONY DSC-R1", 512,
05492     { 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } },
05493     { "SONY DSC-V3", 0,
05494     { 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } },
05495     { "SONY DSLR-A100", 0,
05496     { 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } }
05497   };
05498   double cam_xyz[4][3];
05499   char name[130];
05500   int i, j;
05501 
05502   sprintf (name, "%s %s", make, model);
05503   for (i=0; i < sizeof table / sizeof *table; i++)
05504     if (!strncmp (name, table[i].prefix, strlen(table[i].prefix))) {
05505       if (table[i].black)
05506     black = table[i].black;
05507       for (j=0; j < 12; j++)
05508     cam_xyz[0][j] = table[i].trans[j] / 10000.0;
05509       cam_xyz_coeff (cam_xyz);
05510       break;
05511     }
05512 }
05513 
05514 void CLASS simple_coeff (int index)
05515 {
05516   static const float table[][12] = {
05517   /* index 0 -- all Foveon cameras */
05518   { 1.4032,-0.2231,-0.1016,-0.5263,1.4816,0.017,-0.0112,0.0183,0.9113 },
05519   /* index 1 -- Kodak DC20 and DC25 */
05520   { 2.25,0.75,-1.75,-0.25,-0.25,0.75,0.75,-0.25,-0.25,-1.75,0.75,2.25 },
05521   /* index 2 -- Logitech Fotoman Pixtura */
05522   { 1.893,-0.418,-0.476,-0.495,1.773,-0.278,-1.017,-0.655,2.672 },
05523   /* index 3 -- Nikon E880, E900, and E990 */
05524   { -1.936280,  1.800443, -1.448486,  2.584324,
05525      1.405365, -0.524955, -0.289090,  0.408680,
05526     -1.204965,  1.082304,  2.941367, -1.818705 }
05527   };
05528   int i, c;
05529 
05530   for (raw_color = i=0; i < 3; i++)
05531     FORCC rgb_cam[i][c] = table[index][i*colors+c];
05532 }
05533 
05534 short CLASS guess_byte_order (int words)
05535 {
05536   uchar test[4][2];
05537   int t=2, msb;
05538   double diff, sum[2] = {0,0};
05539 
05540   fread (test[0], 2, 2, ifp);
05541   for (words-=2; words--; ) {
05542     fread (test[t], 2, 1, ifp);
05543     for (msb=0; msb < 2; msb++) {
05544       diff = (test[t^2][msb] << 8 | test[t^2][!msb])
05545        - (test[t  ][msb] << 8 | test[t  ][!msb]);
05546       sum[msb] += diff*diff;
05547     }
05548     t = (t+1) & 3;
05549   }
05550   return sum[0] < sum[1] ? 0x4d4d : 0x4949;
05551 }
05552 
05553 /*
05554    Identify which camera created this file, and set global variables
05555    accordingly.
05556  */
05557 void CLASS identify()
05558 {
05559   char head[32], *cp;
05560   unsigned hlen, fsize, i, c, is_canon;
05561   struct jhead jh;
05562   static const struct {
05563     int fsize;
05564     char make[12], model[19], withjpeg;
05565   } table[] = {
05566     {    62464, "Kodak",    "DC20"       ,0 },
05567     {   124928, "Kodak",    "DC20"       ,0 },
05568     {  1652736, "Kodak",    "DCS200"     ,0 },
05569     {   311696, "ST Micro", "STV680 VGA" ,0 },  /* SPYz */
05570     {   614400, "Kodak",    "KAI-0340"   ,0 },
05571     {   787456, "Creative", "PC-CAM 600" ,0 },
05572     {  1138688, "Minolta",  "RD175"      ,0 },
05573     {  3840000, "Foculus",  "531C"       ,0 },
05574     {  1447680, "AVT",      "F-145C"     ,0 },
05575     {  1920000, "AVT",      "F-201C"     ,0 },
05576     {  5067304, "AVT",      "F-510C"     ,0 },
05577     { 10134608, "AVT",      "F-510C"     ,0 },
05578     { 16157136, "AVT",      "F-810C"     ,0 },
05579     {  1409024, "Sony",     "XCD-SX910CR",0 },
05580     {  2818048, "Sony",     "XCD-SX910CR",0 },
05581     {  3884928, "Micron",   "2010"       ,0 },
05582     {  6624000, "Pixelink", "A782"       ,0 },
05583     { 13248000, "Pixelink", "A782"       ,0 },
05584     {  6291456, "RoverShot","3320AF"     ,0 },
05585     {  6573120, "Canon",    "PowerShot A610",0 },
05586     {  9219600, "Canon",    "PowerShot A620",0 },
05587     {  7710960, "Canon",    "PowerShot S3 IS",0 },
05588     {  5939200, "OLYMPUS",  "C770UZ"     ,0 },
05589     {  1581060, "NIKON",    "E900"       ,1 },  /* or E900s,E910 */
05590     {  2465792, "NIKON",    "E950"       ,1 },  /* or E800,E700 */
05591     {  2940928, "NIKON",    "E2100"      ,1 },  /* or E2500 */
05592     {  4771840, "NIKON",    "E990"       ,1 },  /* or E995, Oly C3030Z */
05593     {  4775936, "NIKON",    "E3700"      ,1 },  /* or Optio 33WR */
05594     {  5869568, "NIKON",    "E4300"      ,1 },  /* or DiMAGE Z2 */
05595     {  5865472, "NIKON",    "E4500"      ,1 },
05596     {  7438336, "NIKON",    "E5000"      ,1 },  /* or E5700 */
05597     {  1976352, "CASIO",    "QV-2000UX"  ,1 },
05598     {  3217760, "CASIO",    "QV-3*00EX"  ,1 },
05599     {  6218368, "CASIO",    "QV-5700"    ,1 },
05600     {  7530816, "CASIO",    "QV-R51"     ,1 },
05601     {  7684000, "CASIO",    "QV-4000"    ,1 },
05602     {  4948608, "CASIO",    "EX-S100"    ,1 },
05603     {  7542528, "CASIO",    "EX-Z50"     ,1 },
05604     {  7753344, "CASIO",    "EX-Z55"     ,1 },
05605     {  7426656, "CASIO",    "EX-P505"    ,1 },
05606     {  9313536, "CASIO",    "EX-P600"    ,1 },
05607     { 10979200, "CASIO",    "EX-P700"    ,1 },
05608     {  3178560, "PENTAX",   "Optio S"    ,1 },
05609     {  4841984, "PENTAX",   "Optio S"    ,1 },
05610     {  6114240, "PENTAX",   "Optio S4"   ,1 },  /* or S4i */
05611     { 12582980, "Sinar",    ""           ,0 },
05612     { 33292868, "Sinar",    ""           ,0 },
05613     { 44390468, "Sinar",    ""           ,0 } };
05614   static const char *corp[] =
05615     { "Canon", "NIKON", "EPSON", "KODAK", "Kodak", "OLYMPUS", "PENTAX",
05616       "MINOLTA", "Minolta", "Konica", "CASIO", "Sinar", "Phase One",
05617       "SAMSUNG" };
05618 
05619   tiff_flip = flip = filters = -1;  /* 0 is valid, so -1 is unknown */
05620   raw_height = raw_width = fuji_width = cr2_slice[0] = 0;
05621   maximum = height = width = top_margin = left_margin = 0;
05622   make[0] = model[0] = model2[0] = cdesc[0] = 0;
05623   iso_speed = shutter = aperture = focal_len = unique_id = 0;
05624   memset (white, 0, sizeof white);
05625   thumb_offset = thumb_length = thumb_width = thumb_height = 0;
05626   load_raw = thumb_load_raw = NULL;
05627   write_thumb = &CLASS jpeg_thumb;
05628   data_offset = meta_length = tiff_bps = tiff_compress = 0;
05629   kodak_cbpp = zero_after_ff = dng_version = fuji_secondary = 0;
05630   timestamp = shot_order = tiff_samples = black = is_foveon = 0;
05631   is_raw = raw_color = use_gamma = xmag = ymag = 1;
05632   tile_length = INT_MAX;
05633   for (i=0; i < 4; i++) {
05634     cam_mul[i] = i == 1;
05635     pre_mul[i] = i < 3;
05636     FORC3 rgb_cam[c][i] = c == i;
05637   }
05638   colors = 3;
05639   tiff_bps = 12;
05640   for (i=0; i < 0x1000; i++) curve[i] = i;
05641   profile_length = 0;
05642 
05643   order = get2();
05644   hlen = get4();
05645   fseek (ifp, 0, SEEK_SET);
05646   fread (head, 1, 32, ifp);
05647   fseek (ifp, 0, SEEK_END);
05648   fsize = ftell(ifp);
05649   if ((cp = (char *) memmem (head, 32, "MMMM", 4)) ||
05650       (cp = (char *) memmem (head, 32, "IIII", 4))) {
05651     parse_phase_one (cp-head);
05652     if (cp-head) parse_tiff(0);
05653   } else if (order == 0x4949 || order == 0x4d4d) {
05654     if (!memcmp (head+6,"HEAPCCDR",8)) {
05655       data_offset = hlen;
05656       parse_ciff (hlen, fsize - hlen);
05657     } else {
05658       parse_tiff(0);
05659     }
05660   } else if (!memcmp (head,"\xff\xd8\xff\xe1",4) &&
05661          !memcmp (head+6,"Exif",4)) {
05662     fseek (ifp, 4, SEEK_SET);
05663     data_offset = 4 + get2();
05664     fseek (ifp, data_offset, SEEK_SET);
05665     if (fgetc(ifp) != 0xff)
05666       parse_tiff(12);
05667     thumb_offset = 0;
05668   } else if (!memcmp (head,"BM",2) &&
05669     head[26] == 1 && head[28] == 16 && head[30] == 0) {
05670     data_offset = 0x1000;
05671     order = 0x4949;
05672     fseek (ifp, 38, SEEK_SET);
05673     if (get4() == 2834 && get4() == 2834 && get4() == 0 && get4() == 4096) {
05674       strcpy (model, "BMQ");
05675       flip = 3;
05676       goto nucore;
05677     }
05678   } else if (!memcmp (head,"BR",2)) {
05679     strcpy (model, "RAW");
05680 nucore:
05681     strcpy (make, "Nucore");
05682     order = 0x4949;
05683     fseek (ifp, 10, SEEK_SET);
05684     data_offset += get4();
05685     raw_width = (get4(),get4());
05686     raw_height = get4();
05687     if (model[0] == 'B' && raw_width == 2597) {
05688       raw_width++;
05689       data_offset -= 0x1000;
05690     }
05691   } else if (!memcmp (head+25,"ARECOYK",7)) {
05692     strcpy (make, "Contax");
05693     strcpy (model,"N Digital");
05694     fseek (ifp, 33, SEEK_SET);
05695     get_timestamp(1);
05696     fseek (ifp, 60, SEEK_SET);
05697     FORC4 cam_mul[c ^ (c >> 1)] = get4();
05698   } else if (!strcmp (head, "PXN")) {
05699     strcpy (make, "Logitech");
05700     strcpy (model,"Fotoman Pixtura");
05701   } else if (!memcmp (head,"FUJIFILM",8)) {
05702     fseek (ifp, 84, SEEK_SET);
05703     thumb_offset = get4();
05704     thumb_length = get4();
05705     fseek (ifp, 92, SEEK_SET);
05706     parse_fuji (get4());
05707     if (thumb_offset > 120) {
05708       fseek (ifp, 120, SEEK_SET);
05709       fuji_secondary = (i = get4()) && 1;
05710       if (fuji_secondary && shot_select)
05711     parse_fuji (i);
05712     }
05713     fseek (ifp, 100, SEEK_SET);
05714     data_offset = get4();
05715     parse_tiff (thumb_offset+12);
05716   } else if (!memcmp (head,"RIFF",4)) {
05717     fseek (ifp, 0, SEEK_SET);
05718     parse_riff();
05719   } else if (!memcmp (head,"DSC-Image",9))
05720     parse_rollei();
05721   else if (!memcmp (head,"\0MRM",4))
05722     parse_minolta(0);
05723   else if (!memcmp (head,"FOVb",4))
05724     parse_foveon();
05725   else
05726     for (i=0; i < sizeof table / sizeof *table; i++)
05727       if (fsize == table[i].fsize) {
05728     strcpy (make,  table[i].make );
05729     strcpy (model, table[i].model);
05730     if (table[i].withjpeg)
05731       parse_external_jpeg();
05732       }
05733   if (make[0] == 0) parse_smal (0, fsize);
05734   if (make[0] == 0) parse_jpeg (is_raw = 0);
05735 
05736   for (i=0; i < sizeof corp / sizeof *corp; i++)
05737     if (strstr (make, corp[i]))     /* Simplify company names */
05738     strcpy (make, corp[i]);
05739   if (!strncmp (make,"KODAK",5))
05740     make[16] = model[16] = 0;
05741   cp = make + strlen(make);     /* Remove trailing spaces */
05742   while (*--cp == ' ') *cp = 0;
05743   cp = model + strlen(model);
05744   while (*--cp == ' ') *cp = 0;
05745   i = strlen(make);         /* Remove make from model */
05746   if (!strncmp (model, make, i) && model[i++] == ' ')
05747     memmove (model, model+i, 64-i);
05748   if (!strncmp (model,"Digital Camera ",15))
05749     strcpy (model, model+15);
05750   make[63] = model[63] = model2[63] = 0;
05751   if (!is_raw) return;
05752 
05753   if ((raw_height | raw_width) < 0)
05754        raw_height = raw_width  = 0;
05755   if (!maximum) maximum = (1 << tiff_bps) - 1;
05756   if (!height) height = raw_height;
05757   if (!width)  width  = raw_width;
05758   if (fuji_width) {
05759     width = height + fuji_width;
05760     height = width - 1;
05761     xmag = ymag = 1;
05762   }
05763   if (!strcmp(model,"K10D")) {      /* Camera DNGs are not cropped! */
05764     height = 2616;
05765     width  = 3896;
05766   }
05767   if (dng_version) {
05768     strcat (model," DNG");
05769     if (filters == UINT_MAX) filters = 0;
05770     if (!filters)
05771       colors = tiff_samples;
05772     if (tiff_compress == 1)
05773       load_raw = &CLASS adobe_dng_load_raw_nc;
05774     if (tiff_compress == 7)
05775       load_raw = &CLASS adobe_dng_load_raw_lj;
05776     FORC4 cam_mul[c] = pre_mul[c];
05777     goto dng_skip;
05778   }
05779 
05780 /*  We'll try to decode anything from Canon or Nikon. */
05781 
05782   if ((is_canon = !strcmp(make,"Canon"))) {
05783     load_raw = memcmp (head+6,"HEAPCCDR",8) ?
05784     &CLASS lossless_jpeg_load_raw : &CLASS canon_compressed_load_raw;
05785     maximum = 0xfff;
05786   }
05787   if (!strcmp(make,"NIKON"))
05788     load_raw = nikon_is_compressed() ?
05789     &CLASS nikon_compressed_load_raw : &CLASS nikon_load_raw;
05790   if (!strncmp (make,"OLYMPUS",7))
05791     height += height & 1;
05792 
05793 /* Set parameters based on camera name (for non-DNG files). */
05794 
05795   if (is_foveon) {
05796     if (height*2 < width) ymag = 2;
05797     if (height   > width) xmag = 2;
05798     filters = 0;
05799     load_raw = &CLASS foveon_load_raw;
05800     simple_coeff(0);
05801   } else if (!strcmp(model,"PowerShot 600")) {
05802     height = 613;
05803     width  = 854;
05804     raw_width = 896;
05805     colors = 4;
05806     filters = 0xe1e4e1e4;
05807     load_raw = &CLASS canon_600_load_raw;
05808   } else if (!strcmp(model,"PowerShot A5") ||
05809          !strcmp(model,"PowerShot A5 Zoom")) {
05810     height = 773;
05811     width  = 960;
05812     raw_width = 992;
05813     colors = 4;
05814     filters = 0x1e4e1e4e;
05815     load_raw = &CLASS canon_a5_load_raw;
05816   } else if (!strcmp(model,"PowerShot A50")) {
05817     height =  968;
05818     width  = 1290;
05819     raw_width = 1320;
05820     colors = 4;
05821     filters = 0x1b4e4b1e;
05822     load_raw = &CLASS canon_a5_load_raw;
05823   } else if (!strcmp(model,"PowerShot Pro70")) {
05824     height = 1024;
05825     width  = 1552;
05826     colors = 4;
05827     filters = 0x1e4b4e1b;
05828     load_raw = &CLASS canon_a5_load_raw;
05829   } else if (!strcmp(model,"PowerShot A610")) {
05830     height = 1960;
05831     width  = 2616;
05832     raw_height = 1968;
05833     raw_width  = 2672;
05834     top_margin  = 8;
05835     left_margin = 12;
05836     load_raw = &CLASS canon_a5_load_raw;
05837   } else if (!strcmp(model,"PowerShot A620")) {
05838     height = 2328;
05839     width  = 3112;
05840     raw_height = 2340;
05841     raw_width  = 3152;
05842     top_margin  = 12;
05843     left_margin = 36;
05844     load_raw = &CLASS canon_a5_load_raw;
05845   } else if (!strcmp(model,"PowerShot S3 IS")) {
05846     height = 2128;
05847     width  = 2840;
05848     raw_height = 2136;
05849     raw_width  = 2888;
05850     top_margin  = 8;
05851     left_margin = 44;
05852     load_raw = &CLASS canon_a5_load_raw;
05853   } else if (!strcmp(model,"PowerShot Pro90 IS")) {
05854     width  = 1896;
05855     colors = 4;
05856     filters = 0xb4b4b4b4;
05857   } else if (is_canon && raw_width == 2144) {
05858     height = 1550;
05859     width  = 2088;
05860     top_margin  = 8;
05861     left_margin = 4;
05862     if (!strcmp(model,"PowerShot G1")) {
05863       colors = 4;
05864       filters = 0xb4b4b4b4;
05865     }
05866   } else if (is_canon && raw_width == 2224) {
05867     height = 1448;
05868     width  = 2176;
05869     top_margin  = 6;
05870     left_margin = 48;
05871   } else if (is_canon && raw_width == 2376) {
05872     height = 1720;
05873     width  = 2312;
05874     top_margin  = 6;
05875     left_margin = 12;
05876   } else if (is_canon && raw_width == 2672) {
05877     height = 1960;
05878     width  = 2616;
05879     top_margin  = 6;
05880     left_margin = 12;
05881   } else if (is_canon && raw_width == 3152) {
05882     height = 2056;
05883     width  = 3088;
05884     top_margin  = 12;
05885     left_margin = 64;
05886     if (unique_id == 0x80000170)
05887       adobe_coeff ("Canon","EOS 300D");
05888     maximum = 0xfa0;
05889   } else if (is_canon && raw_width == 3160) {
05890     height = 2328;
05891     width  = 3112;
05892     top_margin  = 12;
05893     left_margin = 44;
05894   } else if (is_canon && raw_width == 3344) {
05895     height = 2472;
05896     width  = 3288;
05897     top_margin  = 6;
05898     left_margin = 4;
05899   } else if (!strcmp(model,"EOS D2000C")) {
05900     filters = 0x61616161;
05901     black = curve[200];
05902   } else if (is_canon && raw_width == 3516) {
05903     top_margin  = 14;
05904     left_margin = 42;
05905     if (unique_id == 0x80000189)
05906       adobe_coeff ("Canon","EOS 350D");
05907     goto canon_cr2;
05908   } else if (is_canon && raw_width == 3596) {
05909     top_margin  = 12;
05910     left_margin = 74;
05911     goto canon_cr2;
05912   } else if (is_canon && raw_width == 3948) {
05913     top_margin  = 18;
05914     left_margin = 42;
05915     height -= 2;
05916     if (unique_id == 0x80000236)
05917       adobe_coeff ("Canon","EOS 400D");
05918     goto canon_cr2;
05919   } else if (is_canon && raw_width == 4476) {
05920     top_margin  = 34;
05921     left_margin = 90;
05922     maximum = 0xe6c;
05923     goto canon_cr2;
05924   } else if (is_canon && raw_width == 5108) {
05925     top_margin  = 13;
05926     left_margin = 98;
05927     maximum = 0xe80;
05928 canon_cr2:
05929     height -= top_margin;
05930     width  -= left_margin;
05931   } else if (!strcmp(model,"D1")) {
05932     cam_mul[0] *= 256/527.0;
05933     cam_mul[2] *= 256/317.0;
05934   } else if (!strcmp(model,"D1X")) {
05935     width -= 4;
05936     ymag = 2;
05937   } else if (!strncmp(model,"D50",3) || !strncmp(model,"D70",3)) {
05938     width--;
05939     maximum = 0xf53;
05940   } else if (!strcmp(model,"D80")) {
05941     height -= 3;
05942     width  -= 4;
05943   } else if (!strcmp(model,"D100")) {
05944     if (tiff_compress == 34713 && load_raw == &CLASS nikon_load_raw)
05945       raw_width = (width += 3) + 3;
05946     maximum = 0xf44;
05947   } else if (!strcmp(model,"D200")) {
05948     left_margin = 1;
05949     width -= 4;
05950     maximum = 0xfbc;
05951     filters = 0x94949494;
05952   } else if (!strncmp(model,"D2H",3)) {
05953     left_margin = 6;
05954     width -= 14;
05955   } else if (!strcmp(model,"D2X")) {
05956     width -= 8;
05957     maximum = 0xf35;
05958   } else if (fsize == 1581060) {
05959     height = 963;
05960     width = 1287;
05961     raw_width = 1632;
05962     load_raw = &CLASS nikon_e900_load_raw;
05963     maximum = 0x3f4;
05964     colors = 4;
05965     filters = 0x1e1e1e1e;
05966     simple_coeff(3);
05967     pre_mul[0] = 1.2085;
05968     pre_mul[1] = 1.0943;
05969     pre_mul[3] = 1.1103;
05970   } else if (fsize == 2465792) {
05971     height = 1203;
05972     width  = 1616;
05973     raw_width = 2048;
05974     load_raw = &CLASS nikon_e900_load_raw;
05975     maximum = 0x3dd;
05976     colors = 4;
05977     filters = 0x4b4b4b4b;
05978     adobe_coeff ("NIKON","E950");
05979   } else if (fsize == 4771840) {
05980     height = 1540;
05981     width  = 2064;
05982     colors = 4;
05983     filters = 0xe1e1e1e1;
05984     load_raw = &CLASS nikon_load_raw;
05985     if (!timestamp && nikon_e995())
05986       strcpy (model, "E995");
05987     if (strcmp(model,"E995")) {
05988       filters = 0xb4b4b4b4;
05989       simple_coeff(3);
05990       pre_mul[0] = 1.196;
05991       pre_mul[1] = 1.246;
05992       pre_mul[2] = 1.018;
05993     }
05994   } else if (!strcmp(model,"E2100")) {
05995     if (!timestamp && !nikon_e2100()) goto cp_e2500;
05996     height = 1206;
05997     width  = 1616;
05998     load_raw = &CLASS nikon_e2100_load_raw;
05999     pre_mul[0] = 1.945;
06000     pre_mul[2] = 1.040;
06001   } else if (!strcmp(model,"E2500")) {
06002 cp_e2500:
06003     strcpy (model, "E2500");
06004     height = 1204;
06005     width  = 1616;
06006     colors = 4;
06007     filters = 0x4b4b4b4b;
06008   } else if (fsize == 4775936) {
06009     height = 1542;
06010     width  = 2064;
06011     load_raw = &CLASS nikon_e2100_load_raw;
06012     pre_mul[0] = 1.818;
06013     pre_mul[2] = 1.618;
06014     if (!timestamp) nikon_3700();
06015     if (model[0] == 'E' && atoi(model+1) < 3700)
06016       filters = 0x49494949;
06017     if (!strcmp(model,"Optio 33WR")) {
06018       flip = 1;
06019       filters = 0x16161616;
06020       pre_mul[0] = 1.331;
06021       pre_mul[2] = 1.820;
06022     }
06023   } else if (fsize == 5869568) {
06024     height = 1710;
06025     width  = 2288;
06026     filters = 0x16161616;
06027     if (!timestamp && minolta_z2()) {
06028       strcpy (make, "Minolta");
06029       strcpy (model,"DiMAGE Z2");
06030     }
06031     if (make[0] == 'M')
06032       load_raw = &CLASS nikon_e2100_load_raw;
06033   } else if (!strcmp(model,"E4500")) {
06034     height = 1708;
06035     width  = 2288;
06036     colors = 4;
06037     filters = 0xb4b4b4b4;
06038   } else if (fsize == 7438336) {
06039     height = 1924;
06040     width  = 2576;
06041     colors = 4;
06042     filters = 0xb4b4b4b4;
06043   } else if (!strncmp(model,"R-D1",4)) {
06044     tiff_compress = 34713;
06045     load_raw = &CLASS nikon_load_raw;
06046   } else if (!strcmp(model,"FinePix S5100") ||
06047          !strcmp(model,"FinePix S5500")) {
06048     load_raw = &CLASS unpacked_load_raw;
06049     maximum = 0x3e00;
06050   } else if (!strncmp(model,"FinePix",7)) {
06051     if (!strcmp(model+7,"S2Pro")) {
06052       strcpy (model+7," S2Pro");
06053       height = 2144;
06054       width  = 2880;
06055       flip = 6;
06056     } else
06057       maximum = 0x3e00;
06058     if (fuji_secondary && shot_select)
06059       maximum = 0x2f00;
06060     top_margin = (raw_height - height)/2;
06061     left_margin = (raw_width - width )/2;
06062     if (fuji_secondary)
06063       data_offset += (shot_select > 0) * ( strcmp(model+7," S3Pro")
06064         ? (raw_width *= 2) : raw_height*raw_width*2 );
06065     fuji_width = width >> !fuji_layout;
06066     width = (height >> fuji_layout) + fuji_width;
06067     raw_height = height;
06068     height = width - 1;
06069     load_raw = &CLASS fuji_load_raw;
06070     if (!(fuji_width & 1)) filters = 0x49494949;
06071   } else if (!strcmp(model,"RD175")) {
06072     height = 986;
06073     width = 1534;
06074     data_offset = 513;
06075     filters = 0x61616161;
06076     load_raw = &CLASS minolta_rd175_load_raw;
06077   } else if (!strcmp(model,"KD-400Z")) {
06078     height = 1712;
06079     width  = 2312;
06080     raw_width = 2336;
06081     goto konica_400z;
06082   } else if (!strcmp(model,"KD-510Z")) {
06083     goto konica_510z;
06084   } else if (!strcasecmp(make,"MINOLTA")) {
06085     load_raw = &CLASS unpacked_load_raw;
06086     maximum = 0xf7d;
06087     if (!strncmp(model,"DiMAGE A",8)) {
06088       if (!strcmp(model,"DiMAGE A200"))
06089     filters = 0x49494949;
06090       load_raw = &CLASS packed_12_load_raw;
06091       maximum = model[8] == '1' ? 0xf8b : 0xfff;
06092     } else if (!strncmp(model,"ALPHA",5) ||
06093            !strncmp(model,"DYNAX",5) ||
06094            !strncmp(model,"MAXXUM",6)) {
06095       sprintf (model+20, "DYNAX %-10s", model+6+(model[0]=='M'));
06096       adobe_coeff (make, model+20);
06097       load_raw = &CLASS packed_12_load_raw;
06098       maximum = 0xffb;
06099     } else if (!strncmp(model,"DiMAGE G",8)) {
06100       if (model[8] == '4') {
06101     height = 1716;
06102     width  = 2304;
06103       } else if (model[8] == '5') {
06104 konica_510z:
06105     height = 1956;
06106     width  = 2607;
06107     raw_width = 2624;
06108       } else if (model[8] == '6') {
06109     height = 2136;
06110     width  = 2848;
06111       }
06112       data_offset += 14;
06113       filters = 0x61616161;
06114 konica_400z:
06115       load_raw = &CLASS unpacked_load_raw;
06116       maximum = 0x3df;
06117       order = 0x4d4d;
06118     }
06119   } else if (!strcmp(model,"*ist DS")) {
06120     height -= 2;
06121   } else if (!strcmp(model,"Optio S")) {
06122     if (fsize == 3178560) {
06123       height = 1540;
06124       width  = 2064;
06125       load_raw = &CLASS eight_bit_load_raw;
06126       cam_mul[0] *= 4;
06127       cam_mul[2] *= 4;
06128       pre_mul[0] = 1.391;
06129       pre_mul[2] = 1.188;
06130     } else {
06131       height = 1544;
06132       width  = 2068;
06133       raw_width = 3136;
06134       load_raw = &CLASS packed_12_load_raw;
06135       maximum = 0xf7c;
06136       pre_mul[0] = 1.137;
06137       pre_mul[2] = 1.453;
06138     }
06139   } else if (!strncmp(model,"Optio S4",8)) {
06140     height = 1737;
06141     width  = 2324;
06142     raw_width = 3520;
06143     load_raw = &CLASS packed_12_load_raw;
06144     maximum = 0xf7a;
06145     pre_mul[0] = 1.980;
06146     pre_mul[2] = 1.570;
06147   } else if (!strcmp(model,"STV680 VGA")) {
06148     height = 484;
06149     width  = 644;
06150     load_raw = &CLASS eight_bit_load_raw;
06151     flip = 2;
06152     filters = 0x16161616;
06153     black = 16;
06154     pre_mul[0] = 1.097;
06155     pre_mul[2] = 1.128;
06156   } else if (!strcmp(model,"KAI-0340")) {
06157     height = 477;
06158     width  = 640;
06159     order = 0x4949;
06160     data_offset = 3840;
06161     load_raw = &CLASS unpacked_load_raw;
06162     pre_mul[0] = 1.561;
06163     pre_mul[2] = 2.454;
06164   } else if (!strcmp(model,"531C")) {
06165     height = 1200;
06166     width  = 1600;
06167     load_raw = &CLASS unpacked_load_raw;
06168     filters = 0x49494949;
06169     pre_mul[1] = 1.218;
06170   } else if (!strcmp(model,"F-145C")) {
06171     height = 1040;
06172     width  = 1392;
06173     load_raw = &CLASS eight_bit_load_raw;
06174   } else if (!strcmp(model,"F-201C")) {
06175     height = 1200;
06176     width  = 1600;
06177     load_raw = &CLASS eight_bit_load_raw;
06178   } else if (!strcmp(model,"F-510C")) {
06179     height = 1958;
06180     width  = 2588;
06181     load_raw = fsize < 7500000 ?
06182     &CLASS eight_bit_load_raw : &CLASS unpacked_load_raw;
06183     maximum = 0xfff0;
06184   } else if (!strcmp(model,"F-810C")) {
06185     height = 2469;
06186     width  = 3272;
06187     load_raw = &CLASS unpacked_load_raw;
06188     maximum = 0xfff0;
06189   } else if (!strcmp(model,"XCD-SX910CR")) {
06190     height = 1024;
06191     width  = 1375;
06192     raw_width = 1376;
06193     filters = 0x49494949;
06194     maximum = 0x3ff;
06195     load_raw = fsize < 2000000 ?
06196     &CLASS eight_bit_load_raw : &CLASS unpacked_load_raw;
06197   } else if (!strcmp(model,"2010")) {
06198     height = 1207;
06199     width  = 1608;
06200     order = 0x4949;
06201     filters = 0x16161616;
06202     data_offset = 3212;
06203     maximum = 0x3ff;
06204     load_raw = &CLASS unpacked_load_raw;
06205   } else if (!strcmp(model,"A782")) {
06206     height = 3000;
06207     width  = 2208;
06208     filters = 0x61616161;
06209     load_raw = fsize < 10000000 ?
06210     &CLASS eight_bit_load_raw : &CLASS unpacked_load_raw;
06211     maximum = 0xffc0;
06212   } else if (!strcmp(model,"3320AF")) {
06213     height = 1536;
06214     raw_width = width = 2048;
06215     filters = 0x61616161;
06216     load_raw = &CLASS unpacked_load_raw;
06217     maximum = 0x3ff;
06218     pre_mul[0] = 1.717;
06219     pre_mul[2] = 1.138;
06220     fseek (ifp, 0x300000, SEEK_SET);
06221     if ((order = guess_byte_order(0x10000)) == 0x4d4d) {
06222       height -= (top_margin = 16);
06223       width -= (left_margin = 28);
06224       maximum = 0xf5c0;
06225       strcpy (make, "ISG");
06226       model[0] = 0;
06227     }
06228   } else if (!strcmp(make,"Imacon")) {
06229     sprintf (model, "Ixpress %d-Mp", height*width/1000000);
06230     load_raw = &CLASS imacon_full_load_raw;
06231     if (filters) {
06232       if (left_margin & 1) filters = 0x61616161;
06233       load_raw = &CLASS unpacked_load_raw;
06234     }
06235     maximum = 0xffff;
06236   } else if (!strcmp(make,"Sinar")) {
06237     if (!memcmp(head,"8BPS",4)) {
06238       fseek (ifp, 14, SEEK_SET);
06239       height = get4();
06240       width  = get4();
06241       filters = 0x61616161;
06242       data_offset = 68;
06243     }
06244     if (!load_raw) load_raw = &CLASS unpacked_load_raw;
06245     maximum = 0x3fff;
06246   } else if (!strcmp(make,"Leaf")) {
06247     maximum = 0x3fff;
06248     if (tiff_samples > 1) filters = 0;
06249     if (tiff_samples > 1 || tile_length < raw_height)
06250       load_raw = &CLASS leaf_hdr_load_raw;
06251     if ((width | height) == 2048) {
06252       if (tiff_samples == 1) {
06253     filters = 1;
06254     strcpy (cdesc, "RBTG");
06255     strcpy (model, "CatchLight");
06256     top_margin =  8; left_margin = 18; height = 2032; width = 2016;
06257       } else {
06258     strcpy (model, "DCB2");
06259     top_margin = 10; left_margin = 16; height = 2028; width = 2022;
06260       }
06261     } else if (width+height == 3144+2060) {
06262       if (!model[0]) strcpy (model, "Cantare");
06263       if (width > height) {
06264      top_margin = 6; left_margin = 32; height = 2048;  width = 3072;
06265     filters = 0x61616161;
06266       } else {
06267     left_margin = 6;  top_margin = 32;  width = 2048; height = 3072;
06268     filters = 0x16161616;
06269       }
06270       if (!cam_mul[0] || model[0] == 'V') filters = 0;
06271     } else if (width == 2116) {
06272       strcpy (model, "Valeo 6");
06273       height -= 2 * (top_margin = 30);
06274       width -= 2 * (left_margin = 55);
06275       filters = 0x49494949;
06276     } else if (width == 3171) {
06277       strcpy (model, "Valeo 6");
06278       height -= 2 * (top_margin = 24);
06279       width -= 2 * (left_margin = 24);
06280       filters = 0x16161616;
06281     }
06282   } else if (!strcmp(make,"LEICA") || !strcmp(make,"Panasonic")) {
06283     maximum = 0xfff0;
06284     if (width == 2568)
06285       adobe_coeff ("Panasonic","DMC-LC1");
06286     else if (width == 3304) {
06287       maximum = 0xf94c;
06288       width -= 16;
06289       adobe_coeff ("Panasonic","DMC-FZ30");
06290     } else if (width == 3690) {
06291       maximum = 0xf7f0;
06292       height -= 3;
06293       width = 3672;
06294       left_margin = 3;
06295       filters = 0x49494949;
06296       adobe_coeff ("Panasonic","DMC-FZ50");
06297     } else if (width == 3770) {
06298       height = 2760;
06299       width  = 3672;
06300       top_margin  = 15;
06301       left_margin = 17;
06302       adobe_coeff ("Panasonic","DMC-FZ50");
06303     } else if (width == 3880) {
06304       maximum = 0xf7f0;
06305       width -= 22;
06306       left_margin = 6;
06307       adobe_coeff ("Panasonic","DMC-LX1");
06308     } else if (width == 4290) {
06309       height--;
06310       width = 4248;
06311       left_margin = 3;
06312       filters = 0x49494949;
06313       adobe_coeff ("Panasonic","DMC-LX2");
06314     } else if (width == 4330) {
06315       height = 2400;
06316       width  = 4248;
06317       top_margin  = 15;
06318       left_margin = 17;
06319       adobe_coeff ("Panasonic","DMC-LX2");
06320     }
06321     load_raw = &CLASS unpacked_load_raw;
06322   } else if (!strcmp(model,"E-1") ||
06323          !strcmp(model,"E-400")) {
06324     filters = 0x61616161;
06325     maximum = 0xfff0;
06326   } else if (!strcmp(model,"E-10") ||
06327         !strncmp(model,"E-20",4)) {
06328     maximum = 0xffc0;
06329     black <<= 2;
06330   } else if (!strcmp(model,"E-300") ||
06331          !strcmp(model,"E-500")) {
06332     width -= 20;
06333     maximum = 0xfc30;
06334     if (load_raw == &CLASS unpacked_load_raw) black = 0;
06335   } else if (!strcmp(model,"E-330")) {
06336     width -= 30;
06337   } else if (!strcmp(model,"C770UZ")) {
06338     height = 1718;
06339     width  = 2304;
06340     filters = 0x16161616;
06341     load_raw = &CLASS nikon_e2100_load_raw;
06342   } else if (!strcmp(make,"OLYMPUS")) {
06343     load_raw = &CLASS olympus_cseries_load_raw;
06344     if (!strcmp(model,"C5050Z") ||
06345     !strcmp(model,"C8080WZ"))
06346       filters = 0x16161616;
06347     if (!strcmp(model,"SP500UZ"))
06348       filters = 0x49494949;
06349   } else if (!strcmp(model,"N Digital")) {
06350     height = 2047;
06351     width  = 3072;
06352     filters = 0x61616161;
06353     data_offset = 0x1a00;
06354     load_raw = &CLASS packed_12_load_raw;
06355     maximum = 0xf1e;
06356   } else if (!strcmp(model,"DSC-F828")) {
06357     width = 3288;
06358     left_margin = 5;
06359     data_offset = 862144;
06360     load_raw = &CLASS sony_load_raw;
06361     filters = 0x9c9c9c9c;
06362     colors = 4;
06363     strcpy (cdesc, "RGBE");
06364   } else if (!strcmp(model,"DSC-V3")) {
06365     width = 3109;
06366     left_margin = 59;
06367     data_offset = 787392;
06368     load_raw = &CLASS sony_load_raw;
06369   } else if (!strcmp(make,"SONY") && raw_width == 3984) {
06370     adobe_coeff ("SONY","DSC-R1");
06371     width = 3925;
06372     order = 0x4d4d;
06373   } else if (!strcmp(model,"DSLR-A100")) {
06374     height--;
06375     load_raw = &CLASS sony_arw_load_raw;
06376     maximum = 0xfeb;
06377   } else if (!strncmp(model,"P850",4)) {
06378     maximum = 0xf7c;
06379   } else if (!strcasecmp(make,"KODAK")) {
06380     if (filters == UINT_MAX) filters = 0x61616161;
06381     if (!strncmp(model,"NC2000",6)) {
06382       width -= 4;
06383       left_margin = 2;
06384     } else if (!strcmp(model,"EOSDCS3B")) {
06385       width -= 4;
06386       left_margin = 2;
06387     } else if (!strcmp(model,"EOSDCS1")) {
06388       width -= 4;
06389       left_margin = 2;
06390     } else if (!strcmp(model,"DCS420")) {
06391       width -= 4;
06392       left_margin = 2;
06393     } else if (!strcmp(model,"DCS460")) {
06394       width -= 4;
06395       left_margin = 2;
06396     } else if (!strcmp(model,"DCS460A")) {
06397       width -= 4;
06398       left_margin = 2;
06399       colors = 1;
06400       filters = 0;
06401     } else if (!strcmp(model,"DCS660M")) {
06402       black = 214;
06403       colors = 1;
06404       filters = 0;
06405     } else if (!strcmp(model,"DCS760M")) {
06406       colors = 1;
06407       filters = 0;
06408     }
06409     if (load_raw == &CLASS eight_bit_load_raw)
06410     load_raw = &CLASS kodak_easy_load_raw;
06411     if (strstr(model,"DC25")) {
06412       strcpy (model, "DC25");
06413       data_offset = 15424;
06414     }
06415     if (!strncmp(model,"DC2",3)) {
06416       height = 242;
06417       if (fsize < 100000) {
06418     raw_width = 256; width = 249;
06419       } else {
06420     raw_width = 512; width = 501;
06421       }
06422       data_offset += raw_width + 1;
06423       colors = 4;
06424       filters = 0x8d8d8d8d;
06425       simple_coeff(1);
06426       pre_mul[1] = 1.179;
06427       pre_mul[2] = 1.209;
06428       pre_mul[3] = 1.036;
06429       load_raw = &CLASS kodak_easy_load_raw;
06430     } else if (!strcmp(model,"40")) {
06431       strcpy (model, "DC40");
06432       height = 512;
06433       width  = 768;
06434       data_offset = 1152;
06435       load_raw = &CLASS kodak_radc_load_raw;
06436     } else if (strstr(model,"DC50")) {
06437       strcpy (model, "DC50");
06438       height = 512;
06439       width  = 768;
06440       data_offset = 19712;
06441       load_raw = &CLASS kodak_radc_load_raw;
06442     } else if (strstr(model,"DC120")) {
06443       strcpy (model, "DC120");
06444       height = 976;
06445       width  = 848;
06446       load_raw = tiff_compress == 7 ?
06447     &CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw;
06448     } else if (!strcmp(model,"DCS200")) {
06449       thumb_height = 128;
06450       thumb_width  = 192;
06451       thumb_offset = 6144;
06452       thumb_misc   = 360;
06453       write_thumb = &CLASS layer_thumb;
06454       height = 1024;
06455       width  = 1536;
06456       data_offset = 79872;
06457       load_raw = &CLASS eight_bit_load_raw;
06458       black = 17;
06459     }
06460   } else if (!strcmp(model,"Fotoman Pixtura")) {
06461     height = 512;
06462     width  = 768;
06463     data_offset = 3632;
06464     load_raw = &CLASS kodak_radc_load_raw;
06465     filters = 0x61616161;
06466     simple_coeff(2);
06467   } else if (!strcmp(make,"Rollei")) {
06468     switch (raw_width) {
06469       case 1316:
06470     height = 1030;
06471     width  = 1300;
06472     top_margin  = 1;
06473     left_margin = 6;
06474     break;
06475       case 2568:
06476     height = 1960;
06477     width  = 2560;
06478     top_margin  = 2;
06479     left_margin = 8;
06480     }
06481     filters = 0x16161616;
06482     load_raw = &CLASS rollei_load_raw;
06483     pre_mul[0] = 1.8;
06484     pre_mul[2] = 1.3;
06485   } else if (!strcmp(model,"PC-CAM 600")) {
06486     height = 768;
06487     data_offset = width = 1024;
06488     filters = 0x49494949;
06489     load_raw = &CLASS eight_bit_load_raw;
06490     pre_mul[0] = 1.14;
06491     pre_mul[2] = 2.73;
06492   } else if (!strcmp(model,"QV-2000UX")) {
06493     height = 1208;
06494     width  = 1632;
06495     data_offset = width * 2;
06496     load_raw = &CLASS eight_bit_load_raw;
06497   } else if (fsize == 3217760) {
06498     height = 1546;
06499     width  = 2070;
06500     raw_width = 2080;
06501     load_raw = &CLASS eight_bit_load_raw;
06502   } else if (!strcmp(model,"QV-4000")) {
06503     height = 1700;
06504     width  = 2260;
06505     load_raw = &CLASS unpacked_load_raw;
06506     maximum = 0xffff;
06507   } else if (!strcmp(model,"QV-5700")) {
06508     height = 1924;
06509     width  = 2576;
06510     load_raw = &CLASS casio_qv5700_load_raw;
06511   } else if (!strcmp(model,"QV-R51")) {
06512     height = 1926;
06513     width  = 2576;
06514     raw_width = 3904;
06515     load_raw = &CLASS packed_12_load_raw;
06516     pre_mul[0] = 1.340;
06517     pre_mul[2] = 1.672;
06518   } else if (!strcmp(model,"EX-S100")) {
06519     height = 1544;
06520     width  = 2058;
06521     raw_width = 3136;
06522     load_raw = &CLASS packed_12_load_raw;
06523     pre_mul[0] = 1.631;
06524     pre_mul[2] = 1.106;
06525   } else if (!strcmp(model,"EX-Z50")) {
06526     height = 1931;
06527     width  = 2570;
06528     raw_width = 3904;
06529     load_raw = &CLASS packed_12_load_raw;
06530     pre_mul[0] = 2.529;
06531     pre_mul[2] = 1.185;
06532   } else if (!strcmp(model,"EX-Z55")) {
06533     height = 1960;
06534     width  = 2570;
06535     raw_width = 3904;
06536     load_raw = &CLASS packed_12_load_raw;
06537     pre_mul[0] = 1.520;
06538     pre_mul[2] = 1.316;
06539   } else if (!strcmp(model,"EX-P505")) {
06540     height = 1928;
06541     width  = 2568;
06542     raw_width = 3852;
06543     load_raw = &CLASS packed_12_load_raw;
06544     pre_mul[0] = 2.07;
06545     pre_mul[2] = 1.88;
06546   } else if (fsize == 9313536) {    /* EX-P600 or QV-R61 */
06547     height = 2142;
06548     width  = 2844;
06549     raw_width = 4288;
06550     load_raw = &CLASS packed_12_load_raw;
06551     pre_mul[0] = 1.797;
06552     pre_mul[2] = 1.219;
06553   } else if (!strcmp(model,"EX-P700")) {
06554     height = 2318;
06555     width  = 3082;
06556     raw_width = 4672;
06557     load_raw = &CLASS packed_12_load_raw;
06558     pre_mul[0] = 1.758;
06559     pre_mul[2] = 1.504;
06560   } else if (!strcmp(make,"Nucore")) {
06561     filters = 0x61616161;
06562     load_raw = &CLASS unpacked_load_raw;
06563     if (width == 2598) {
06564       filters = 0x16161616;
06565       load_raw = &CLASS nucore_load_raw;
06566       flip = 2;
06567     }
06568   }
06569   if (!model[0])
06570     sprintf (model, "%dx%d", width, height);
06571   if (filters == UINT_MAX) filters = 0x94949494;
06572   if (raw_color) adobe_coeff (make, model);
06573   if (thumb_offset && !thumb_height) {
06574     fseek (ifp, thumb_offset, SEEK_SET);
06575     if (ljpeg_start (&jh, 1)) {
06576       thumb_width  = jh.wide;
06577       thumb_height = jh.high;
06578     }
06579   }
06580 dng_skip:
06581   if (!load_raw || !height) is_raw = 0;
06582 #ifdef NO_JPEG
06583   if (load_raw == kodak_jpeg_load_raw) {
06584     fprintf (stderr, "%s: You must link dcraw.c with libjpeg!!\n", ifname);
06585     is_raw = 0;
06586   }
06587 #endif
06588   if (flip == -1) flip = tiff_flip;
06589   if (flip == -1) flip = 0;
06590   if (!cdesc[0])
06591     strcpy (cdesc, colors == 3 ? "RGB":"GMCY");
06592   if (!raw_height) raw_height = height;
06593   if (!raw_width ) raw_width  = width;
06594   if (filters && colors == 3)
06595     for (i=0; i < 32; i+=4) {
06596       if ((filters >> i & 15) == 9)
06597     filters |= 2 << i;
06598       if ((filters >> i & 15) == 6)
06599     filters |= 8 << i;
06600     }
06601 }
06602 
06603 #ifndef NO_LCMS
06604 void CLASS apply_profile (char *input, char *output)
06605 {
06606   char *prof;
06607   cmsHPROFILE hInProfile=NULL, hOutProfile=NULL;
06608   cmsHTRANSFORM hTransform;
06609   FILE *fp;
06610   unsigned size;
06611 
06612   cmsErrorAction (LCMS_ERROR_SHOW);
06613   if (strcmp (input, "embed"))
06614     hInProfile = cmsOpenProfileFromFile (input, "r");
06615   else if (profile_length) {
06616     prof = (char *) malloc (profile_length);
06617     merror (prof, "apply_profile()");
06618     fseek (ifp, profile_offset, SEEK_SET);
06619     fread (prof, 1, profile_length, ifp);
06620     hInProfile = cmsOpenProfileFromMem (prof, profile_length);
06621     free (prof);
06622   } else
06623     fprintf (stderr, "%s has no embedded profile.\n", ifname);
06624   if (!hInProfile) return;
06625   if (!output)
06626     hOutProfile = cmsCreate_sRGBProfile();
06627   else if ((fp = fopen (output, "rb"))) {
06628     fread (&size, 4, 1, fp);
06629     fseek (fp, 0, SEEK_SET);
06630     oprof = (unsigned *) malloc (size = ntohl(size));
06631     merror (oprof, "apply_profile()");
06632     fread (oprof, 1, size, fp);
06633     fclose (fp);
06634     if (!(hOutProfile = cmsOpenProfileFromMem (oprof, size))) {
06635       free (oprof);
06636       oprof = NULL;
06637     }
06638   } else
06639     fprintf (stderr, "Cannot open %s!\n", output);
06640   if (!hOutProfile) goto quit;
06641   if (verbose)
06642     fprintf (stderr, "Applying color profile...\n");
06643   hTransform = cmsCreateTransform (hInProfile, TYPE_RGBA_16,
06644     hOutProfile, TYPE_RGBA_16, INTENT_PERCEPTUAL, 0);
06645   cmsDoTransform (hTransform, image, image, width*height);
06646   raw_color = 1;        /* Don't use rgb_cam with a profile */
06647   cmsDeleteTransform (hTransform);
06648   cmsCloseProfile (hOutProfile);
06649 quit:
06650   cmsCloseProfile (hInProfile);
06651 }
06652 #endif
06653 
06654 void CLASS convert_to_rgb()
06655 {
06656   int mix_green, row, col, c, i, j, k;
06657   ushort *img;
06658   float out[3], out_cam[3][4];
06659   double num, inverse[3][3];
06660   static const double xyzd50_srgb[3][3] =
06661   { { 0.436083, 0.385083, 0.143055 },
06662     { 0.222507, 0.716888, 0.060608 },
06663     { 0.013930, 0.097097, 0.714022 } };
06664   static const double rgb_rgb[3][3] =
06665   { { 1,0,0 }, { 0,1,0 }, { 0,0,1 } };
06666   static const double adobe_rgb[3][3] =
06667   { { 0.715146, 0.284856, 0.000000 },
06668     { 0.000000, 1.000000, 0.000000 },
06669     { 0.000000, 0.041166, 0.958839 } };
06670   static const double wide_rgb[3][3] =
06671   { { 0.593087, 0.404710, 0.002206 },
06672     { 0.095413, 0.843149, 0.061439 },
06673     { 0.011621, 0.069091, 0.919288 } };
06674   static const double prophoto_rgb[3][3] =
06675   { { 0.529317, 0.330092, 0.140588 },
06676     { 0.098368, 0.873465, 0.028169 },
06677     { 0.016879, 0.117663, 0.865457 } };
06678   static const double (*out_rgb[])[3] =
06679   { rgb_rgb, adobe_rgb, wide_rgb, prophoto_rgb, xyz_rgb };
06680   static const char *name[] =
06681   { "sRGB", "Adobe RGB (1998)", "WideGamut D65", "ProPhoto D65", "XYZ" };
06682   static const unsigned phead[] =
06683   { 1024, 0, 0x2100000, 0x6d6e7472, 0x52474220, 0x58595a20, 0, 0, 0,
06684     0x61637370, 0, 0, 0x6e6f6e65, 0, 0, 0, 0, 0xf6d6, 0x10000, 0xd32d };
06685   unsigned pbody[] =
06686   { 10, 0x63707274, 0, 36,  /* cprt */
06687     0x64657363, 0, 40,  /* desc */
06688     0x77747074, 0, 20,  /* wtpt */
06689     0x626b7074, 0, 20,  /* bkpt */
06690     0x72545243, 0, 14,  /* rTRC */
06691     0x67545243, 0, 14,  /* gTRC */
06692     0x62545243, 0, 14,  /* bTRC */
06693     0x7258595a, 0, 20,  /* rXYZ */
06694     0x6758595a, 0, 20,  /* gXYZ */
06695     0x6258595a, 0, 20 };    /* bXYZ */
06696   static const unsigned pwhite[] = { 0xf351, 0x10000, 0x116cc };
06697   unsigned pcurve[] = { 0x63757276, 0, 1, 0x1000000 };
06698 
06699   memcpy (out_cam, rgb_cam, sizeof out_cam);
06700   raw_color |= colors == 1 || document_mode ||
06701         output_color < 1 || output_color > 5;
06702   if (!raw_color) {
06703     oprof = (unsigned *) calloc (phead[0], 1);
06704     merror (oprof, "convert_to_rgb()");
06705     memcpy (oprof, phead, sizeof phead);
06706     if (output_color == 5) oprof[4] = oprof[5];
06707     oprof[0] = 132 + 12*pbody[0];
06708     for (i=0; i < pbody[0]; i++) {
06709       oprof[oprof[0]/4] = i ? (i > 1 ? 0x58595a20 : 0x64657363) : 0x74657874;
06710       pbody[i*3+2] = oprof[0];
06711       oprof[0] += (pbody[i*3+3] + 3) & -4;
06712     }
06713     memcpy (oprof+32, pbody, sizeof pbody);
06714     oprof[pbody[5]/4+2] = strlen(name[output_color-1]) + 1;
06715     memcpy ((char *)oprof+pbody[8]+8, pwhite, sizeof pwhite);
06716     if (output_bps == 8)
06717 #ifdef SRGB_GAMMA
06718       pcurve[3] = 0x2330000;
06719 #else
06720       pcurve[3] = 0x1f00000;
06721 #endif
06722     for (i=4; i < 7; i++)
06723       memcpy ((char *)oprof+pbody[i*3+2], pcurve, sizeof pcurve);
06724     pseudoinverse ((double (*)[3]) out_rgb[output_color-1], inverse, 3);
06725     for (i=0; i < 3; i++)
06726       for (j=0; j < 3; j++) {
06727     for (num = k=0; k < 3; k++)
06728       num += xyzd50_srgb[i][k] * inverse[j][k];
06729         oprof[pbody[j*3+23]/4+i+2] = num * 0x10000 + 0.5;
06730       }
06731     for (i=0; i < phead[0]/4; i++)
06732       oprof[i] = htonl(oprof[i]);
06733     strcpy ((char *)oprof+pbody[2]+8, "auto-generated by dcraw");
06734     strcpy ((char *)oprof+pbody[5]+12, name[output_color-1]);
06735     for (i=0; i < 3; i++)
06736       for (j=0; j < colors; j++)
06737     for (out_cam[i][j] = k=0; k < 3; k++)
06738       out_cam[i][j] += out_rgb[output_color-1][i][k] * rgb_cam[k][j];
06739   }
06740   if (verbose)
06741     fprintf (stderr, raw_color ? "Building histograms...\n" :
06742     "Converting to %s colorspace...\n", name[output_color-1]);
06743 
06744   mix_green = rgb_cam[1][1] == rgb_cam[1][3];
06745   memset (histogram, 0, sizeof histogram);
06746   for (img=image[0], row=0; row < height; row++)
06747     for (col=0; col < width; col++, img+=4) {
06748       if (!raw_color) {
06749     out[0] = out[1] = out[2] = 0;
06750     FORCC {
06751       out[0] += out_cam[0][c] * img[c];
06752       out[1] += out_cam[1][c] * img[c];
06753       out[2] += out_cam[2][c] * img[c];
06754     }
06755     FORC3 img[c] = CLIP((int) out[c]);
06756       }
06757       else if (document_mode)
06758     img[0] = img[FC(row,col)];
06759       else if (mix_green)
06760     img[1] = (img[1] + img[3]) >> 1;
06761       FORCC histogram[c][img[c] >> 3]++;
06762     }
06763   if (colors == 4 && (output_color || mix_green)) colors = 3;
06764   if (document_mode && filters) colors = 1;
06765 }
06766 
06767 void CLASS fuji_rotate()
06768 {
06769   int i, wide, high, row, col;
06770   double step;
06771   float r, c, fr, fc;
06772   unsigned ur, uc;
06773   ushort (*img)[4], (*pix)[4];
06774 
06775   if (!fuji_width) return;
06776   if (verbose)
06777     fprintf (stderr, "Rotating image 45 degrees...\n");
06778   fuji_width = (fuji_width - 1 + shrink) >> shrink;
06779   step = sqrt(0.5);
06780   wide = fuji_width / step;
06781   high = (height - fuji_width) / step;
06782   img = (ushort (*)[4]) calloc (wide*high, sizeof *img);
06783   merror (img, "fuji_rotate()");
06784 
06785   for (row=0; row < high; row++)
06786     for (col=0; col < wide; col++) {
06787       ur = r = fuji_width + (row-col)*step;
06788       uc = c = (row+col)*step;
06789       if (ur > height-2 || uc > width-2) continue;
06790       fr = r - ur;
06791       fc = c - uc;
06792       pix = image + ur*width + uc;
06793       for (i=0; i < colors; i++)
06794     img[row*wide+col][i] =
06795       (pix[    0][i]*(1-fc) + pix[      1][i]*fc) * (1-fr) +
06796       (pix[width][i]*(1-fc) + pix[width+1][i]*fc) * fr;
06797     }
06798   free (image);
06799   width  = wide;
06800   height = high;
06801   image  = img;
06802   fuji_width = 0;
06803 }
06804 
06805 int CLASS flip_index (int row, int col)
06806 {
06807   if (flip & 4) SWAP(row,col);
06808   if (flip & 2) row = iheight - 1 - row;
06809   if (flip & 1) col = iwidth  - 1 - col;
06810   return row * iwidth + col;
06811 }
06812 
06813 void CLASS gamma_lut (uchar lut[0x10000])
06814 {
06815   int perc, c, val, total, i;
06816   float white=0, r;
06817 
06818   perc = width * height * 0.01;     /* 99th percentile white point */
06819   if (fuji_width) perc /= 2;
06820   if (highlight) perc = 0;
06821   FORCC {
06822     for (val=0x2000, total=0; --val > 32; )
06823       if ((total += histogram[c][val]) > perc) break;
06824     if (white < val) white = val;
06825   }
06826   white *= 8 / bright;
06827   for (i=0; i < 0x10000; i++) {
06828     r = i / white;
06829     val = 256 * ( !use_gamma ? r :
06830 #ifdef SRGB_GAMMA
06831     r <= 0.00304 ? r*12.92 : pow(r,2.5/6)*1.055-0.055 );
06832 #else
06833     r <= 0.018 ? r*4.5 : pow(r,0.45)*1.099-0.099 );
06834 #endif
06835     if (val > 255) val = 255;
06836     lut[i] = val;
06837   }
06838 }
06839 
06840 struct tiff_tag {
06841   ushort tag, type;
06842   int count;
06843   union { short s0, s1; int i0; } val;
06844 };
06845 
06846 struct tiff_hdr {
06847   ushort order, magic;
06848   int ifd;
06849   ushort pad, ntag;
06850   struct tiff_tag tag[15];
06851   int nextifd;
06852   ushort pad2, nexif;
06853   struct tiff_tag exif[4];
06854   short bps[4];
06855   int rat[6];
06856   char make[64], model[72], soft[32], date[20];
06857 };
06858 
06859 void CLASS tiff_set (ushort *ntag,
06860     ushort tag, ushort type, int count, int val)
06861 {
06862   struct tiff_tag *tt;
06863 
06864   tt = (struct tiff_tag *)(ntag+1) + (*ntag)++;
06865   tt->tag = tag;
06866   tt->type = type;
06867   tt->count = count;
06868   if (type == 3 && count == 1)
06869     tt->val.s0 = val;
06870   else tt->val.i0 = val;
06871 }
06872 
06873 #define TOFF(ptr) ((char *)(&(ptr)) - (char *)(&th))
06874 
06875 void CLASS write_ppm_tiff (FILE *ofp)
06876 {
06877   struct tiff_hdr th;
06878   struct tm *t;
06879   uchar *ppm, lut[0x10000];
06880   ushort *ppm2;
06881   int i, c, row, col, psize=0, soff, rstep, cstep;
06882 
06883   iheight = height;
06884   iwidth  = width;
06885   if (flip & 4) {
06886     SWAP(height,width);
06887     SWAP(ymag,xmag);
06888   }
06889   ppm = (uchar *) calloc (width, colors*xmag*output_bps/8);
06890   ppm2 = (ushort *) ppm;
06891   merror (ppm, "write_ppm_tiff()");
06892 
06893   memset (&th, 0, sizeof th);
06894   th.order = htonl(0x4d4d4949) >> 16;
06895   th.magic = 42;
06896   th.ifd = 10;
06897   tiff_set (&th.ntag, 256, 4, 1, xmag*width);
06898   tiff_set (&th.ntag, 257, 4, 1, ymag*height);
06899   tiff_set (&th.ntag, 258, 3, colors, output_bps);
06900   if (colors > 2)
06901     th.tag[th.ntag-1].val.i0 = TOFF(th.bps);
06902   FORC4 th.bps[c] = output_bps;
06903   tiff_set (&th.ntag, 259, 3, 1, 1);
06904   tiff_set (&th.ntag, 262, 3, 1, 1 + (colors > 1));
06905   tiff_set (&th.ntag, 271, 2, 64, TOFF(th.make));
06906   tiff_set (&th.ntag, 272, 2, 72, TOFF(th.model));
06907   if (oprof) psize = ntohl(oprof[0]);
06908   tiff_set (&th.ntag, 273, 4, 1, sizeof th + psize);
06909   tiff_set (&th.ntag, 277, 3, 1, colors);
06910   tiff_set (&th.ntag, 278, 4, 1, ymag*height);
06911   tiff_set (&th.ntag, 279, 4, 1, ymag*height*xmag*width*colors*output_bps/8);
06912   tiff_set (&th.ntag, 305, 2, 32, TOFF(th.soft));
06913   tiff_set (&th.ntag, 306, 2, 20, TOFF(th.date));
06914   tiff_set (&th.ntag, 34665, 4, 1, TOFF(th.nexif));
06915   if (psize) tiff_set (&th.ntag, 34675, 7, psize, sizeof th);
06916   tiff_set (&th.nexif, 33434, 5, 1, TOFF(th.rat[0]));
06917   tiff_set (&th.nexif, 33437, 5, 1, TOFF(th.rat[2]));
06918   tiff_set (&th.nexif, 34855, 3, 1, iso_speed);
06919   tiff_set (&th.nexif, 37386, 5, 1, TOFF(th.rat[4]));
06920   for (i=0; i < 6; i++) th.rat[i] = 1000000;
06921   th.rat[0] *= shutter;
06922   th.rat[2] *= aperture;
06923   th.rat[4] *= focal_len;
06924   strncpy (th.make, make, 64);
06925   strncpy (th.model, model, 72);
06926   strcpy (th.soft, "dcraw v"VERSION);
06927   t = gmtime (&timestamp);
06928   sprintf (th.date, "%04d:%02d:%02d %02d:%02d:%02d",
06929       t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);
06930 
06931   if (output_tiff) {
06932     fwrite (&th, sizeof th, 1, ofp);
06933     if (psize)
06934       fwrite (oprof, psize, 1, ofp);
06935   } else if (colors > 3)
06936     fprintf (ofp,
06937       "P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n",
06938     xmag*width, ymag*height, colors, (1 << output_bps)-1, cdesc);
06939   else
06940     fprintf (ofp, "P%d\n%d %d\n%d\n",
06941     colors/2+5, xmag*width, ymag*height, (1 << output_bps)-1);
06942 
06943   if (output_bps == 8)
06944     gamma_lut (lut);
06945   soff  = flip_index (0, 0);
06946   cstep = flip_index (0, 1) - soff;
06947   rstep = flip_index (1, 0) - flip_index (0, width);
06948   for (row=0; row < height; row++, soff += rstep) {
06949     for (col=0; col < width; col++, soff += cstep)
06950       FORCC for (i=0; i < xmag; i++)
06951     if (output_bps == 8)
06952          ppm [(col*xmag+i)*colors+c] = lut[image[soff][c]];
06953     else ppm2[(col*xmag+i)*colors+c] =     image[soff][c];
06954     if (output_bps == 16 && !output_tiff && th.order == 0x4949)
06955       swab (ppm2, ppm2, xmag*width*colors*2);
06956     for (i=0; i < ymag; i++)
06957       fwrite (ppm, colors*output_bps/8, xmag*width, ofp);
06958   }
06959   free (ppm);
06960 }
06961 
06962 int CLASS main (int argc, char **argv)
06963 {
06964   int arg, status=0, user_flip=-1, user_black=-1, user_qual=-1;
06965   int timestamp_only=0, thumbnail_only=0, identify_only=0, write_to_stdout=0;
06966   int half_size=0, use_fuji_rotate=1, quality, i, c;
06967   char opt, *ofname, *sp, *cp, *dark_frame = NULL;
06968   const char *write_ext;
06969   struct utimbuf ut;
06970   FILE *ofp = stdout;
06971 #ifndef NO_LCMS
06972   char *cam_profile = NULL, *out_profile = NULL;
06973 #endif
06974 
06975 #ifndef LOCALTIME
06976   putenv ("TZ=UTC");
06977 #endif
06978   if (argc == 1) {
06979     fprintf (stderr,
06980     "\nRaw Photo Decoder \"dcraw\" v"VERSION
06981     "\nby Dave Coffin, dcoffin a cybercom o net"
06982     "\n\nUsage:  %s [options] file1 file2 ...\n"
06983     "\nValid options:"
06984     "\n-v        Print verbose messages"
06985     "\n-c        Write image data to standard output"
06986     "\n-e        Extract embedded thumbnail image"
06987     "\n-i        Identify files without decoding them"
06988     "\n-z        Change file dates to camera timestamp"
06989     "\n-a        Use automatic white balance"
06990     "\n-w        Use camera white balance, if possible"
06991     "\n-r <nums> Set raw white balance (four values required)"
06992     "\n-b <num>  Adjust brightness (default = 1.0)"
06993     "\n-k <num>  Set black point"
06994     "\n-K <file> Subtract dark frame (16-bit raw PGM)"
06995     "\n-H [0-9]  Highlight mode (0=clip, 1=no clip, 2+=recover)"
06996     "\n-t [0-7]  Flip image (0=none, 3=180, 5=90CCW, 6=90CW)"
06997     "\n-o [0-5]  Output colorspace (raw,sRGB,Adobe,Wide,ProPhoto,XYZ)"
06998 #ifndef NO_LCMS
06999     "\n-o <file> Apply output ICC profile from file"
07000     "\n-p <file> Apply camera ICC profile from file or \"embed\""
07001 #endif
07002     "\n-d        Document Mode (no color, no interpolation)"
07003     "\n-D        Document Mode without scaling (totally raw)"
07004     "\n-q [0-3]  Set the interpolation quality"
07005     "\n-h        Half-size color image (twice as fast as \"-q 0\")"
07006     "\n-f        Interpolate RGGB as four colors"
07007     "\n-B <domain> <range>  Apply bilateral filter to reduce noise"
07008     "\n-j        Show Fuji Super CCD images tilted 45 degrees"
07009     "\n-s [0-99] Select a different raw image from the same file"
07010     "\n-4        Write 16-bit linear instead of 8-bit with gamma"
07011     "\n-T        Write TIFF instead of PPM"
07012     "\n\n", argv[0]);
07013     return 1;
07014   }
07015 
07016   argv[argc] = "";
07017   for (arg=1; argv[arg][0] == '-'; ) {
07018     opt = argv[arg++][1];
07019     if ((cp = strchr (sp="BbrktqsH", opt)))
07020       for (i=0; i < "21411111"[cp-sp]-'0'; i++)
07021     if (!isdigit(argv[arg+i][0])) {
07022       fprintf (stderr, "Non-numeric argument to \"-%c\"\n", opt);
07023       return 1;
07024     }
07025     switch (opt) {
07026       case 'B':  sigma_d     = atof(argv[arg++]);
07027          sigma_r     = atof(argv[arg++]);  break;
07028       case 'b':  bright      = atof(argv[arg++]);  break;
07029       case 'r':
07030        FORC4 user_mul[c] = atof(argv[arg++]);  break;
07031       case 'k':  user_black  = atoi(argv[arg++]);  break;
07032       case 't':  user_flip   = atoi(argv[arg++]);  break;
07033       case 'q':  user_qual   = atoi(argv[arg++]);  break;
07034       case 's':  shot_select = atoi(argv[arg++]);  break;
07035       case 'H':  highlight   = atoi(argv[arg++]);  break;
07036       case 'o':
07037     if (isdigit(argv[arg][0]) && !argv[arg][1])
07038       output_color = atoi(argv[arg++]);
07039 #ifndef NO_LCMS
07040     else     out_profile = argv[arg++];
07041     break;
07042       case 'p':  cam_profile = argv[arg++];
07043 #endif
07044     break;
07045       case 'K':  dark_frame  = argv[arg++];
07046     break;
07047       case 'z':  timestamp_only    = 1;  break;
07048       case 'e':  thumbnail_only    = 1;  break;
07049       case 'i':  identify_only     = 1;  break;
07050       case 'c':  write_to_stdout   = 1;  break;
07051       case 'v':  verbose           = 1;  break;
07052       case 'h':  half_size         = 1;     /* "-h" implies "-f" */
07053       case 'f':  four_color_rgb    = 1;  break;
07054       case 'd':  document_mode     = 1;  break;
07055       case 'D':  document_mode     = 2;  break;
07056       case 'a':  use_auto_wb       = 1;  break;
07057       case 'w':  use_camera_wb     = 1;  break;
07058       case 'j':  use_fuji_rotate   = 0;  break;
07059       case 'm':  output_color      = 0;  break;
07060       case 'T':  output_tiff       = 1;  break;
07061       case '4':  output_bps       = 16;  break;
07062       default:
07063     fprintf (stderr, "Unknown option \"-%c\".\n", opt);
07064     return 1;
07065     }
07066   }
07067   if (arg == argc) {
07068     fprintf (stderr, "No files to process.\n");
07069     return 1;
07070   }
07071   if (write_to_stdout) {
07072     if (isatty(1)) {
07073       fprintf (stderr, "Will not write an image to the terminal!\n");
07074       return 1;
07075     }
07076 #if defined(WIN32) || defined(DJGPP) || defined(__CYGWIN__)
07077     if (setmode(1,O_BINARY) < 0) {
07078       perror("setmode()");
07079       return 1;
07080     }
07081 #endif
07082   }
07083   for ( ; arg < argc; arg++) {
07084     status = 1;
07085     image = NULL;
07086     oprof = NULL;
07087     if (setjmp (failure)) {
07088       if (fileno(ifp) > 2) fclose(ifp);
07089       if (fileno(ofp) > 2) fclose(ofp);
07090       if (image) free (image);
07091       status = 1;
07092       continue;
07093     }
07094     ifname = argv[arg];
07095     if (!(ifp = fopen (ifname, "rb"))) {
07096       perror (ifname);
07097       continue;
07098     }
07099     status = (identify(),!is_raw);
07100     if (timestamp_only) {
07101       if ((status = !timestamp))
07102     fprintf (stderr, "%s has no timestamp.\n", ifname);
07103       else if (identify_only)
07104     printf ("%10ld%10d %s\n", (long) timestamp, shot_order, ifname);
07105       else {
07106     if (verbose)
07107       fprintf (stderr, "%s time set to %d.\n", ifname, (int) timestamp);
07108     ut.actime = ut.modtime = timestamp;
07109     utime (ifname, &ut);
07110       }
07111       goto next;
07112     }
07113     write_fun = &CLASS write_ppm_tiff;
07114     if (thumbnail_only) {
07115       if ((status = !thumb_offset)) {
07116     fprintf (stderr, "%s has no thumbnail.\n", ifname);
07117     goto next;
07118       } else if (thumb_load_raw) {
07119     load_raw = thumb_load_raw;
07120     data_offset = thumb_offset;
07121     height = thumb_height;
07122     width  = thumb_width;
07123     filters = 0;
07124       } else {
07125     fseek (ifp, thumb_offset, SEEK_SET);
07126     write_fun = write_thumb;
07127     goto thumbnail;
07128       }
07129     }
07130     if (load_raw == &CLASS kodak_ycbcr_load_raw) {
07131       height += height & 1;
07132       width  += width  & 1;
07133     }
07134     if (identify_only && verbose && make[0]) {
07135       printf ("\nFilename: %s\n", ifname);
07136       printf ("Timestamp: %s", ctime(&timestamp));
07137       printf ("Camera: %s %s\n", make, model);
07138       printf ("ISO speed: %d\n", (int) iso_speed);
07139       printf ("Shutter: ");
07140       if (shutter > 0 && shutter < 1)
07141     shutter = (printf ("1/"), 1 / shutter);
07142       printf ("%0.1f sec\n", shutter);
07143       printf ("Aperture: f/%0.1f\n", aperture);
07144       printf ("Focal Length: %0.1f mm\n", focal_len);
07145       printf ("Secondary pixels: %s\n", fuji_secondary ? "yes":"no");
07146       printf ("Embedded ICC profile: %s\n", profile_length ? "yes":"no");
07147       printf ("Decodable with dcraw: %s\n", is_raw ? "yes":"no");
07148       if (thumb_offset)
07149     printf ("Thumb size:  %4d x %d\n", thumb_width, thumb_height);
07150       printf ("Full size:   %4d x %d\n", raw_width, raw_height);
07151     } else if (!is_raw)
07152       fprintf (stderr, "Cannot decode %s\n", ifname);
07153     if (!is_raw) goto next;
07154     if (user_flip >= 0)
07155       flip = user_flip;
07156     switch ((flip+3600) % 360) {
07157       case 270:  flip = 5;  break;
07158       case 180:  flip = 3;  break;
07159       case  90:  flip = 6;
07160     }
07161     shrink = half_size && filters;
07162     iheight = (height + shrink) >> shrink;
07163     iwidth  = (width  + shrink) >> shrink;
07164     if (identify_only) {
07165       if (verbose) {
07166     if (fuji_width && use_fuji_rotate) {
07167       fuji_width = (fuji_width - 1 + shrink) >> shrink;
07168       iwidth = fuji_width / sqrt(0.5);
07169       iheight = (iheight - fuji_width) / sqrt(0.5);
07170     }
07171     iheight *= ymag;
07172     iwidth  *= xmag;
07173     if (flip & 4)
07174       SWAP(iheight,iwidth);
07175     printf ("Image size:  %4d x %d\n", width, height);
07176     printf ("Output size: %4d x %d\n", iwidth, iheight);
07177     printf ("Raw colors: %d", colors);
07178     if (filters) {
07179       printf ("\nFilter pattern: ");
07180       if (!cdesc[3]) cdesc[3] = 'G';
07181       for (i=0; i < 16; i++)
07182         putchar (cdesc[fc(i >> 1,i & 1)]);
07183     }
07184     printf ("\nDaylight multipliers:");
07185     FORCC printf (" %f", pre_mul[c]);
07186     if (cam_mul[0] > 0) {
07187       printf ("\nCamera multipliers:");
07188       FORC4 printf (" %f", cam_mul[c]);
07189     }
07190     putchar ('\n');
07191       } else
07192     printf ("%s is a %s %s image.\n", ifname, make, model);
07193 next:
07194       fclose(ifp);
07195       continue;
07196     }
07197     image = (ushort (*)[4])
07198     calloc (iheight*iwidth*sizeof *image + meta_length, 1);
07199     merror (image, "main()");
07200     meta_data = (char *) (image + iheight*iwidth);
07201     if (verbose)
07202       fprintf (stderr,
07203     "Loading %s %s image from %s...\n", make, model, ifname);
07204     fseek (ifp, data_offset, SEEK_SET);
07205     (*load_raw)();
07206     bad_pixels();
07207     if (dark_frame) subtract (dark_frame);
07208     height = iheight;
07209     width  = iwidth;
07210     quality = 2 + !fuji_width;
07211     if (user_qual >= 0) quality = user_qual;
07212     if (user_black >= 0) black = user_black;
07213 #ifdef COLORCHECK
07214     colorcheck();
07215 #endif
07216     if (is_foveon && !document_mode) foveon_interpolate();
07217     if (!is_foveon && document_mode < 2) scale_colors();
07218     if (shrink) filters = 0;
07219     cam_to_cielab (NULL,NULL);
07220     if (filters && !document_mode) {
07221       if (quality == 0)
07222     lin_interpolate();
07223       else if (quality < 3 || colors > 3)
07224        vng_interpolate();
07225       else ahd_interpolate();
07226     }
07227     if (sigma_d > 0 && sigma_r > 0) bilateral_filter();
07228     if (!is_foveon && highlight > 1) recover_highlights();
07229     if (use_fuji_rotate) fuji_rotate();
07230 #ifndef NO_LCMS
07231     if (cam_profile) apply_profile (cam_profile, out_profile);
07232 #endif
07233     convert_to_rgb();
07234 thumbnail:
07235     if (write_fun == &CLASS jpeg_thumb)
07236       write_ext = ".jpg";
07237     else if (output_tiff && write_fun == &CLASS write_ppm_tiff)
07238       write_ext = ".tiff";
07239     else
07240       write_ext = ".pgm\0.ppm\0.ppm\0.pam" + colors*5-5;
07241     ofname = (char *) malloc (strlen(ifname) + 16);
07242     merror (ofname, "main()");
07243     if (write_to_stdout)
07244       strcpy (ofname, "standard output");
07245     else {
07246       strcpy (ofname, ifname);
07247       if ((cp = strrchr (ofname, '.'))) *cp = 0;
07248       if (thumbnail_only)
07249     strcat (ofname, ".thumb");
07250       strcat (ofname, write_ext);
07251       ofp = fopen (ofname, "wb");
07252       if (!ofp) {
07253     status = 1;
07254     perror(ofname);
07255     goto cleanup;
07256       }
07257     }
07258     if (verbose)
07259       fprintf (stderr, "Writing data to %s ...\n", ofname);
07260     (*write_fun)(ofp);
07261     fclose(ifp);
07262     if (ofp != stdout) fclose(ofp);
07263 cleanup:
07264     if (oprof) free(oprof);
07265     free (ofname);
07266     free (image);
07267   }
07268   return status;
07269 }

Generated on Sat Jan 27 11:36:12 2007 for libopenraw by  doxygen 1.4.7