• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files

hvirtual/cinelerra/dcraw.c

Go to the documentation of this file.
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.321 $
00023    $Date: 2006/03/31 21:54:29 $
00024  */
00025 
00026 #define _GNU_SOURCE
00027 #define _USE_MATH_DEFINES
00028 #include <ctype.h>
00029 #include <errno.h>
00030 #include <fcntl.h>
00031 #include <float.h>
00032 #include <limits.h>
00033 #include <math.h>
00034 #include <setjmp.h>
00035 #include <stdio.h>
00036 #include <stdlib.h>
00037 #include <string.h>
00038 #include <time.h>
00039 /*
00040    NO_JPEG disables decoding of compressed Kodak DC120 files.
00041    NO_LCMS disables the "-p" option.
00042  */
00043 
00044 // CINELERRA
00045 #define NO_LCMS
00046 
00047 #ifndef NO_JPEG
00048 #include <jpeglib.h>
00049 #endif
00050 #ifndef NO_LCMS
00051 #include <lcms.h>
00052 #endif
00053 
00054 #ifdef __CYGWIN__
00055 #include <io.h>
00056 #endif
00057 #ifdef WIN32
00058 #include <sys/utime.h>
00059 #include <winsock2.h>
00060 #pragma comment(lib, "ws2_32.lib")
00061 #define strcasecmp stricmp
00062 typedef __int64 INT64;
00063 typedef unsigned __int64 UINT64;
00064 #else
00065 #include <unistd.h>
00066 #include <utime.h>
00067 #include <netinet/in.h>
00068 typedef long long INT64;
00069 typedef unsigned long long UINT64;
00070 #endif
00071 
00072 #ifdef LJPEG_DECODE
00073 #error Please compile dcraw.c by itself.
00074 #error Do not link it with ljpeg_decode.
00075 #endif
00076 
00077 #ifndef LONG_BIT
00078 #define LONG_BIT (8 * sizeof (long))
00079 #endif
00080 
00081 #define ushort UshORt
00082 typedef unsigned char uchar;
00083 typedef unsigned short ushort;
00084 
00085 /*
00086    All global variables are defined here, and all functions that
00087    access them are prefixed with "CLASS".  Note that a thread-safe
00088    C++ class cannot have non-const static local variables.
00089  */
00090 
00091 
00092 
00093 // CINELERRA
00094 char dcraw_info[1024];
00095 float **dcraw_data;
00096 int dcraw_alpha;
00097 float dcraw_matrix[9];
00098 
00099 
00100 FILE *ifp;
00101 short order;
00102 char *ifname, make[64], model[72], model2[64], *meta_data, cdesc[5];
00103 float flash_used, canon_ev, iso_speed, shutter, aperture, focal_len;
00104 time_t timestamp;
00105 unsigned shot_order, kodak_cbpp, filters;
00106 int profile_offset, profile_length;
00107 int thumb_offset, thumb_length, thumb_width, thumb_height, thumb_misc;
00108 int data_offset, strip_offset, curve_offset, meta_offset, meta_length;
00109 int tiff_nifds, tiff_flip, tiff_bps, tiff_compress;
00110 int raw_height, raw_width, top_margin, left_margin;
00111 int height, width, fuji_width, colors, tiff_samples;
00112 int black, maximum, clip_max, raw_color, use_gamma;
00113 int iheight, iwidth, shrink, flip, xmag, ymag;
00114 int zero_after_ff, is_raw, dng_version, is_foveon;
00115 ushort (*image)[4], white[8][8], curve[0x1000], cr2_slice[3];
00116 float bright=1, red_scale=1, blue_scale=1, sigma_d=0, sigma_r=0;
00117 int four_color_rgb=0, document_mode=0, clip_color=1;
00118 int verbose=0, use_auto_wb=0, use_camera_wb=0, output_color=1;
00119 int fuji_layout, fuji_secondary, use_secondary=0;
00120 float cam_mul[4], pre_mul[4], rgb_cam[3][4];    /* RGB from camera color */
00121 const double xyz_rgb[3][3] = {                  /* XYZ from RGB */
00122   { 0.412453, 0.357580, 0.180423 },
00123   { 0.212671, 0.715160, 0.072169 },
00124   { 0.019334, 0.119193, 0.950227 } };
00125 const float d65_white[3] = { 0.950456, 1, 1.088754 };
00126 #define camera_red  cam_mul[0]
00127 #define camera_blue cam_mul[2]
00128 int histogram[4][0x2000];
00129 void write_ppm(FILE *);
00130 void (*write_thumb)(FILE *), (*write_fun)(FILE *);
00131 void (*load_raw)(), (*thumb_load_raw)();
00132 jmp_buf failure;
00133 
00134 struct decode {
00135   struct decode *branch[2];
00136   int leaf;
00137 } first_decode[2048], *second_decode, *free_decode;
00138 
00139 struct {
00140   int width, height, bps, comp, phint, offset, flip, samples, bytes;
00141 } tiff_ifd[10];
00142 
00143 #define CLASS
00144 
00145 #define FORC3 for (c=0; c < 3; c++)
00146 #define FORC4 for (c=0; c < 4; c++)
00147 #define FORCC for (c=0; c < colors; c++)
00148 
00149 #define SQR(x) ((x)*(x))
00150 #define ABS(x) (((int)(x) ^ ((int)(x) >> 31)) - ((int)(x) >> 31))
00151 #define MIN(a,b) ((a) < (b) ? (a) : (b))
00152 #define MAX(a,b) ((a) > (b) ? (a) : (b))
00153 #define LIM(x,min,max) MAX(min,MIN(x,max))
00154 #define ULIM(x,y,z) ((y) < (z) ? LIM(x,y,z) : LIM(x,z,y))
00155 #define CLIP(x) LIM(x,0,clip_max)
00156 #define SWAP(a,b) { a ^= b; a ^= (b ^= a); }
00157 
00158 /*
00159    In order to inline this calculation, I make the risky
00160    assumption that all filter patterns can be described
00161    by a repeating pattern of eight rows and two columns
00162 
00163    Return values are either 0/1/2/3 = G/M/C/Y or 0/1/2/3 = R/G1/B/G2
00164  */
00165 #define FC(row,col) \
00166         (filters >> ((((row) << 1 & 14) + ((col) & 1)) << 1) & 3)
00167 
00168 #define BAYER(row,col) \
00169         image[((row) >> shrink)*iwidth + ((col) >> shrink)][FC(row,col)]
00170 
00171 /*
00172         PowerShot 600   PowerShot A50   PowerShot Pro70 Pro90 & G1
00173         0xe1e4e1e4:     0x1b4e4b1e:     0x1e4b4e1b:     0xb4b4b4b4:
00174 
00175           0 1 2 3 4 5     0 1 2 3 4 5     0 1 2 3 4 5     0 1 2 3 4 5
00176         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
00177         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
00178         2 M G M G M G   2 Y C Y C Y C   2 C Y C Y C Y
00179         3 C Y C Y C Y   3 G M G M G M   3 G M G M G M
00180                         4 C Y C Y C Y   4 Y C Y C Y C
00181         PowerShot A5    5 G M G M G M   5 G M G M G M
00182         0x1e4e1e4e:     6 Y C Y C Y C   6 C Y C Y C Y
00183                         7 M G M G M G   7 M G M G M G
00184           0 1 2 3 4 5
00185         0 C Y C Y C Y
00186         1 G M G M G M
00187         2 C Y C Y C Y
00188         3 M G M G M G
00189 
00190    All RGB cameras use one of these Bayer grids:
00191 
00192         0x16161616:     0x61616161:     0x49494949:     0x94949494:
00193 
00194           0 1 2 3 4 5     0 1 2 3 4 5     0 1 2 3 4 5     0 1 2 3 4 5
00195         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
00196         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
00197         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
00198         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
00199  */
00200 
00201 #ifndef __GLIBC__
00202 char *my_memmem (char *haystack, size_t haystacklen,
00203               char *needle, size_t needlelen)
00204 {
00205   char *c;
00206   for (c = haystack; c <= haystack + haystacklen - needlelen; c++)
00207     if (!memcmp (c, needle, needlelen))
00208       return c;
00209   return NULL;
00210 }
00211 #define memmem my_memmem
00212 #endif
00213 
00214 void CLASS merror (void *ptr, char *where)
00215 {
00216   if (ptr) return;
00217   fprintf (stderr, "%s: Out of memory in %s\n", ifname, where);
00218   longjmp (failure, 1);
00219 }
00220 
00221 ushort CLASS sget2 (uchar *s)
00222 {
00223   if (order == 0x4949)          /* "II" means little-endian */
00224     return s[0] | s[1] << 8;
00225   else                          /* "MM" means big-endian */
00226     return s[0] << 8 | s[1];
00227 }
00228 
00229 ushort CLASS get2()
00230 {
00231   uchar str[2] = { 0xff,0xff };
00232   fread (str, 1, 2, ifp);
00233   return sget2(str);
00234 }
00235 
00236 int CLASS sget4 (uchar *s)
00237 {
00238   if (order == 0x4949)
00239     return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24;
00240   else
00241     return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3];
00242 }
00243 #define sget4(s) sget4((uchar *)s)
00244 
00245 int CLASS get4()
00246 {
00247   uchar str[4] = { 0xff,0xff,0xff,0xff };
00248   fread (str, 1, 4, ifp);
00249   return sget4(str);
00250 }
00251 
00252 int CLASS getint (int type)
00253 {
00254   return type == 3 ? get2() : get4();
00255 }
00256 
00257 float CLASS int_to_float (int i)
00258 {
00259   union { int i; float f; } u;
00260   u.i = i;
00261   return u.f;
00262 }
00263 
00264 double CLASS getreal (int type)
00265 {
00266   double num;
00267   switch (type) {
00268     case 3: return (unsigned short) get2();
00269     case 4: return (unsigned int) get4();
00270     case 5:  num = (unsigned int) get4();
00271       return num / (unsigned int) get4();
00272     case 8: return (signed short) get2();
00273     case 9: return (signed int) get4();
00274     case 10: num = (signed int) get4();
00275       return num / (signed int) get4();
00276     case 11: return int_to_float (get4());
00277     case 12:
00278       fprintf (stderr, "%s: TIFF doubles not supported!\n", ifname);
00279       longjmp (failure, 4);
00280     default: return fgetc(ifp);
00281   }
00282 }
00283 #define getrat() getreal(10)
00284 
00285 void CLASS read_shorts (ushort *pixel, int count)
00286 {
00287   fread (pixel, 2, count, ifp);
00288   if ((order == 0x4949) == (ntohs(0x1234) == 0x1234))
00289     swab (pixel, pixel, count*2);
00290 }
00291 
00292 void CLASS canon_600_fixed_wb (int temp)
00293 {
00294   static const short mul[4][5] = {
00295     {  667, 358,397,565,452 },
00296     {  731, 390,367,499,517 },
00297     { 1119, 396,348,448,537 },
00298     { 1399, 485,431,508,688 } };
00299   int lo, hi, i;
00300   float frac=0;
00301 
00302   for (lo=4; --lo; )
00303     if (*mul[lo] <= temp) break;
00304   for (hi=0; hi < 3; hi++)
00305     if (*mul[hi] >= temp) break;
00306   if (lo != hi)
00307     frac = (float) (temp - *mul[lo]) / (*mul[hi] - *mul[lo]);
00308   for (i=1; i < 5; i++)
00309     pre_mul[i-1] = 1 / (frac * mul[hi][i] + (1-frac) * mul[lo][i]);
00310 }
00311 
00312 /* Return values:  0 = white  1 = near white  2 = not white */
00313 int CLASS canon_600_color (int ratio[2], int mar)
00314 {
00315   int clipped=0, target, miss;
00316 
00317   if (flash_used) {
00318     if (ratio[1] < -104)
00319       { ratio[1] = -104; clipped = 1; }
00320     if (ratio[1] >   12)
00321       { ratio[1] =   12; clipped = 1; }
00322   } else {
00323     if (ratio[1] < -264 || ratio[1] > 461) return 2;
00324     if (ratio[1] < -50)
00325       { ratio[1] = -50; clipped = 1; }
00326     if (ratio[1] > 307)
00327       { ratio[1] = 307; clipped = 1; }
00328   }
00329   target = flash_used || ratio[1] < 197
00330         ? -38 - (398 * ratio[1] >> 10)
00331         : -123 + (48 * ratio[1] >> 10);
00332   if (target - mar <= ratio[0] &&
00333       target + 20  >= ratio[0] && !clipped) return 0;
00334   miss = target - ratio[0];
00335   if (abs(miss) >= mar*4) return 2;
00336   if (miss < -20) miss = -20;
00337   if (miss > mar) miss = mar;
00338   ratio[0] = target - miss;
00339   return 1;
00340 }
00341 
00342 void CLASS canon_600_auto_wb()
00343 {
00344   int mar, row, col, i, j, st, count[] = { 0,0 };
00345   int test[8], total[2][8], ratio[2][2], stat[2];
00346 
00347   memset (&total, 0, sizeof total);
00348   i = canon_ev + 0.5;
00349   if      (i < 10) mar = 150;
00350   else if (i > 12) mar = 20;
00351   else mar = 280 - 20 * i;
00352   if (flash_used) mar = 80;
00353   for (row=14; row < height-14; row+=4)
00354     for (col=10; col < width; col+=2) {
00355       for (i=0; i < 8; i++)
00356         test[(i & 4) + FC(row+(i >> 1),col+(i & 1))] =
00357                     BAYER(row+(i >> 1),col+(i & 1));
00358       for (i=0; i < 8; i++)
00359         if (test[i] < 150 || test[i] > 1500) goto next;
00360       for (i=0; i < 4; i++)
00361         if (abs(test[i] - test[i+4]) > 50) goto next;
00362       for (i=0; i < 2; i++) {
00363         for (j=0; j < 4; j+=2)
00364           ratio[i][j >> 1] = ((test[i*4+j+1]-test[i*4+j]) << 10) / test[i*4+j];
00365         stat[i] = canon_600_color (ratio[i], mar);
00366       }
00367       if ((st = stat[0] | stat[1]) > 1) goto next;
00368       for (i=0; i < 2; i++)
00369         if (stat[i])
00370           for (j=0; j < 2; j++)
00371             test[i*4+j*2+1] = test[i*4+j*2] * (0x400 + ratio[i][j]) >> 10;
00372       for (i=0; i < 8; i++)
00373         total[st][i] += test[i];
00374       count[st]++;
00375 next: continue;
00376     }
00377   if (count[0] | count[1]) {
00378     st = count[0]*200 < count[1];
00379     for (i=0; i < 4; i++)
00380       pre_mul[i] = 1.0 / (total[st][i] + total[st][i+4]);
00381   }
00382 }
00383 
00384 void CLASS canon_600_coeff()
00385 {
00386   static const short table[6][12] = {
00387     { -190,702,-1878,2390,   1861,-1349,905,-393, -432,944,2617,-2105  },
00388     { -1203,1715,-1136,1648, 1388,-876,267,245,  -1641,2153,3921,-3409 },
00389     { -615,1127,-1563,2075,  1437,-925,509,3,     -756,1268,2519,-2007 },
00390     { -190,702,-1886,2398,   2153,-1641,763,-251, -452,964,3040,-2528  },
00391     { -190,702,-1878,2390,   1861,-1349,905,-393, -432,944,2617,-2105  },
00392     { -807,1319,-1785,2297,  1388,-876,769,-257,  -230,742,2067,-1555  } };
00393   int t=0, i, c;
00394   float mc, yc;
00395 
00396   mc = pre_mul[1] / pre_mul[2];
00397   yc = pre_mul[3] / pre_mul[2];
00398   if (mc > 1 && mc <= 1.28 && yc < 0.8789) t=1;
00399   if (mc > 1.28 && mc <= 2) {
00400     if  (yc < 0.8789) t=3;
00401     else if (yc <= 2) t=4;
00402   }
00403   if (flash_used) t=5;
00404   for (raw_color = i=0; i < 3; i++)
00405     FORCC rgb_cam[i][c] = table[t][i*4 + c] / 1024.0;
00406 }
00407 
00408 void CLASS canon_600_load_raw()
00409 {
00410   uchar  data[1120], *dp;
00411   ushort pixel[896], *pix;
00412   int irow, row, col, val;
00413   static const short mul[4][2] =
00414   { { 1141,1145 }, { 1128,1109 }, { 1178,1149 }, { 1128,1109 } };
00415 
00416   for (irow=row=0; irow < height; irow++)
00417   {
00418     fread (data, 1120, 1, ifp);
00419     for (dp=data, pix=pixel; dp < data+1120; dp+=10, pix+=8)
00420     {
00421       pix[0] = (dp[0] << 2) + (dp[1] >> 6    );
00422       pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3);
00423       pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3);
00424       pix[3] = (dp[4] << 2) + (dp[1]      & 3);
00425       pix[4] = (dp[5] << 2) + (dp[9]      & 3);
00426       pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3);
00427       pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3);
00428       pix[7] = (dp[8] << 2) + (dp[9] >> 6    );
00429     }
00430     for (col=0; col < width; col++)
00431       BAYER(row,col) = pixel[col];
00432     for (col=width; col < 896; col++)
00433       black += pixel[col];
00434     if ((row+=2) > height) row = 1;
00435   }
00436   black = black / ((896 - width) * height) - 4;
00437   for (row=0; row < height; row++)
00438     for (col=0; col < width; col++) {
00439       val = (BAYER(row,col) - black) * mul[row & 3][col & 1] >> 9;
00440       if (val < 0) val = 0;
00441       BAYER(row,col) = val;
00442     }
00443   canon_600_fixed_wb(1311);
00444   canon_600_auto_wb();
00445   canon_600_coeff();
00446   maximum = (0x3ff - black) * 1109 >> 9;
00447   black = 0;
00448 }
00449 
00450 void CLASS canon_a5_load_raw()
00451 {
00452   uchar  data[1940], *dp;
00453   ushort pixel[1552], *pix;
00454   int row, col;
00455 
00456   for (row=0; row < height; row++) {
00457     fread (data, raw_width * 10 / 8, 1, ifp);
00458     for (dp=data, pix=pixel; pix < pixel+raw_width; dp+=10, pix+=8)
00459     {
00460       pix[0] = (dp[1] << 2) + (dp[0] >> 6);
00461       pix[1] = (dp[0] << 4) + (dp[3] >> 4);
00462       pix[2] = (dp[3] << 6) + (dp[2] >> 2);
00463       pix[3] = (dp[2] << 8) + (dp[5]     );
00464       pix[4] = (dp[4] << 2) + (dp[7] >> 6);
00465       pix[5] = (dp[7] << 4) + (dp[6] >> 4);
00466       pix[6] = (dp[6] << 6) + (dp[9] >> 2);
00467       pix[7] = (dp[9] << 8) + (dp[8]     );
00468     }
00469     for (col=0; col < width; col++)
00470       BAYER(row,col) = (pixel[col] & 0x3ff);
00471     for (col=width; col < raw_width; col++)
00472       black += pixel[col] & 0x3ff;
00473   }
00474   if (raw_width > width)
00475     black /= (raw_width - width) * height;
00476   maximum = 0x3ff;
00477 }
00478 
00479 /*
00480    getbits(-1) initializes the buffer
00481    getbits(n) where 0 <= n <= 25 returns an n-bit integer
00482  */
00483 unsigned CLASS getbits (int nbits)
00484 {
00485   static unsigned bitbuf=0;
00486   static int vbits=0, reset=0;
00487   unsigned c;
00488 
00489   if (nbits == -1)
00490     return bitbuf = vbits = reset = 0;
00491   if (nbits == 0 || reset) return 0;
00492   while (vbits < nbits) {
00493     c = fgetc(ifp);
00494     if ((reset = zero_after_ff && c == 0xff && fgetc(ifp))) return 0;
00495     bitbuf = (bitbuf << 8) + c;
00496     vbits += 8;
00497   }
00498   vbits -= nbits;
00499   return bitbuf << (32-nbits-vbits) >> (32-nbits);
00500 }
00501 
00502 void CLASS init_decoder()
00503 {
00504   memset (first_decode, 0, sizeof first_decode);
00505   free_decode = first_decode;
00506 }
00507 
00508 /*
00509    Construct a decode tree according the specification in *source.
00510    The first 16 bytes specify how many codes should be 1-bit, 2-bit
00511    3-bit, etc.  Bytes after that are the leaf values.
00512 
00513    For example, if the source is
00514 
00515     { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
00516       0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff  },
00517 
00518    then the code is
00519 
00520         00              0x04
00521         010             0x03
00522         011             0x05
00523         100             0x06
00524         101             0x02
00525         1100            0x07
00526         1101            0x01
00527         11100           0x08
00528         11101           0x09
00529         11110           0x00
00530         111110          0x0a
00531         1111110         0x0b
00532         1111111         0xff
00533  */
00534 uchar * CLASS make_decoder (const uchar *source, int level)
00535 {
00536   struct decode *cur;
00537   static int leaf;
00538   int i, next;
00539 
00540   if (level==0) leaf=0;
00541   cur = free_decode++;
00542   if (free_decode > first_decode+2048) {
00543     fprintf (stderr, "%s: decoder table overflow\n", ifname);
00544     longjmp (failure, 2);
00545   }
00546   for (i=next=0; i <= leaf && next < 16; )
00547     i += source[next++];
00548   if (i > leaf) {
00549     if (level < next) {
00550       cur->branch[0] = free_decode;
00551       make_decoder (source, level+1);
00552       cur->branch[1] = free_decode;
00553       make_decoder (source, level+1);
00554     } else
00555       cur->leaf = source[16 + leaf++];
00556   }
00557   return (uchar *) source + 16 + leaf;
00558 }
00559 
00560 void CLASS crw_init_tables (unsigned table)
00561 {
00562   static const uchar first_tree[3][29] = {
00563     { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
00564       0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff  },
00565     { 0,2,2,3,1,1,1,1,2,0,0,0,0,0,0,0,
00566       0x03,0x02,0x04,0x01,0x05,0x00,0x06,0x07,0x09,0x08,0x0a,0x0b,0xff  },
00567     { 0,0,6,3,1,1,2,0,0,0,0,0,0,0,0,0,
00568       0x06,0x05,0x07,0x04,0x08,0x03,0x09,0x02,0x00,0x0a,0x01,0x0b,0xff  },
00569   };
00570   static const uchar second_tree[3][180] = {
00571     { 0,2,2,2,1,4,2,1,2,5,1,1,0,0,0,139,
00572       0x03,0x04,0x02,0x05,0x01,0x06,0x07,0x08,
00573       0x12,0x13,0x11,0x14,0x09,0x15,0x22,0x00,0x21,0x16,0x0a,0xf0,
00574       0x23,0x17,0x24,0x31,0x32,0x18,0x19,0x33,0x25,0x41,0x34,0x42,
00575       0x35,0x51,0x36,0x37,0x38,0x29,0x79,0x26,0x1a,0x39,0x56,0x57,
00576       0x28,0x27,0x52,0x55,0x58,0x43,0x76,0x59,0x77,0x54,0x61,0xf9,
00577       0x71,0x78,0x75,0x96,0x97,0x49,0xb7,0x53,0xd7,0x74,0xb6,0x98,
00578       0x47,0x48,0x95,0x69,0x99,0x91,0xfa,0xb8,0x68,0xb5,0xb9,0xd6,
00579       0xf7,0xd8,0x67,0x46,0x45,0x94,0x89,0xf8,0x81,0xd5,0xf6,0xb4,
00580       0x88,0xb1,0x2a,0x44,0x72,0xd9,0x87,0x66,0xd4,0xf5,0x3a,0xa7,
00581       0x73,0xa9,0xa8,0x86,0x62,0xc7,0x65,0xc8,0xc9,0xa1,0xf4,0xd1,
00582       0xe9,0x5a,0x92,0x85,0xa6,0xe7,0x93,0xe8,0xc1,0xc6,0x7a,0x64,
00583       0xe1,0x4a,0x6a,0xe6,0xb3,0xf1,0xd3,0xa5,0x8a,0xb2,0x9a,0xba,
00584       0x84,0xa4,0x63,0xe5,0xc5,0xf3,0xd2,0xc4,0x82,0xaa,0xda,0xe4,
00585       0xf2,0xca,0x83,0xa3,0xa2,0xc3,0xea,0xc2,0xe2,0xe3,0xff,0xff  },
00586     { 0,2,2,1,4,1,4,1,3,3,1,0,0,0,0,140,
00587       0x02,0x03,0x01,0x04,0x05,0x12,0x11,0x06,
00588       0x13,0x07,0x08,0x14,0x22,0x09,0x21,0x00,0x23,0x15,0x31,0x32,
00589       0x0a,0x16,0xf0,0x24,0x33,0x41,0x42,0x19,0x17,0x25,0x18,0x51,
00590       0x34,0x43,0x52,0x29,0x35,0x61,0x39,0x71,0x62,0x36,0x53,0x26,
00591       0x38,0x1a,0x37,0x81,0x27,0x91,0x79,0x55,0x45,0x28,0x72,0x59,
00592       0xa1,0xb1,0x44,0x69,0x54,0x58,0xd1,0xfa,0x57,0xe1,0xf1,0xb9,
00593       0x49,0x47,0x63,0x6a,0xf9,0x56,0x46,0xa8,0x2a,0x4a,0x78,0x99,
00594       0x3a,0x75,0x74,0x86,0x65,0xc1,0x76,0xb6,0x96,0xd6,0x89,0x85,
00595       0xc9,0xf5,0x95,0xb4,0xc7,0xf7,0x8a,0x97,0xb8,0x73,0xb7,0xd8,
00596       0xd9,0x87,0xa7,0x7a,0x48,0x82,0x84,0xea,0xf4,0xa6,0xc5,0x5a,
00597       0x94,0xa4,0xc6,0x92,0xc3,0x68,0xb5,0xc8,0xe4,0xe5,0xe6,0xe9,
00598       0xa2,0xa3,0xe3,0xc2,0x66,0x67,0x93,0xaa,0xd4,0xd5,0xe7,0xf8,
00599       0x88,0x9a,0xd7,0x77,0xc4,0x64,0xe2,0x98,0xa5,0xca,0xda,0xe8,
00600       0xf3,0xf6,0xa9,0xb2,0xb3,0xf2,0xd2,0x83,0xba,0xd3,0xff,0xff  },
00601     { 0,0,6,2,1,3,3,2,5,1,2,2,8,10,0,117,
00602       0x04,0x05,0x03,0x06,0x02,0x07,0x01,0x08,
00603       0x09,0x12,0x13,0x14,0x11,0x15,0x0a,0x16,0x17,0xf0,0x00,0x22,
00604       0x21,0x18,0x23,0x19,0x24,0x32,0x31,0x25,0x33,0x38,0x37,0x34,
00605       0x35,0x36,0x39,0x79,0x57,0x58,0x59,0x28,0x56,0x78,0x27,0x41,
00606       0x29,0x77,0x26,0x42,0x76,0x99,0x1a,0x55,0x98,0x97,0xf9,0x48,
00607       0x54,0x96,0x89,0x47,0xb7,0x49,0xfa,0x75,0x68,0xb6,0x67,0x69,
00608       0xb9,0xb8,0xd8,0x52,0xd7,0x88,0xb5,0x74,0x51,0x46,0xd9,0xf8,
00609       0x3a,0xd6,0x87,0x45,0x7a,0x95,0xd5,0xf6,0x86,0xb4,0xa9,0x94,
00610       0x53,0x2a,0xa8,0x43,0xf5,0xf7,0xd4,0x66,0xa7,0x5a,0x44,0x8a,
00611       0xc9,0xe8,0xc8,0xe7,0x9a,0x6a,0x73,0x4a,0x61,0xc7,0xf4,0xc6,
00612       0x65,0xe9,0x72,0xe6,0x71,0x91,0x93,0xa6,0xda,0x92,0x85,0x62,
00613       0xf3,0xc5,0xb2,0xa4,0x84,0xba,0x64,0xa5,0xb3,0xd2,0x81,0xe5,
00614       0xd3,0xaa,0xc4,0xca,0xf2,0xb1,0xe4,0xd1,0x83,0x63,0xea,0xc3,
00615       0xe2,0x82,0xf1,0xa3,0xc2,0xa1,0xc1,0xe3,0xa2,0xe1,0xff,0xff  }
00616   };
00617   if (table > 2) table = 2;
00618   init_decoder();
00619   make_decoder ( first_tree[table], 0);
00620   second_decode = free_decode;
00621   make_decoder (second_tree[table], 0);
00622 }
00623 
00624 /*
00625    Return 0 if the image starts with compressed data,
00626    1 if it starts with uncompressed low-order bits.
00627 
00628    In Canon compressed data, 0xff is always followed by 0x00.
00629  */
00630 int CLASS canon_has_lowbits()
00631 {
00632   uchar test[0x4000];
00633   int ret=1, i;
00634 
00635   fseek (ifp, 0, SEEK_SET);
00636   fread (test, 1, sizeof test, ifp);
00637   for (i=540; i < sizeof test - 1; i++)
00638     if (test[i] == 0xff) {
00639       if (test[i+1]) return 1;
00640       ret=0;
00641     }
00642   return ret;
00643 }
00644 
00645 void CLASS canon_compressed_load_raw()
00646 {
00647   ushort *pixel, *prow;
00648   int lowbits, i, row, r, col, save, val;
00649   unsigned irow, icol;
00650   struct decode *decode, *dindex;
00651   int block, diffbuf[64], leaf, len, diff, carry=0, pnum=0, base[2];
00652   uchar c;
00653 
00654   crw_init_tables (tiff_compress);
00655   pixel = calloc (raw_width*8, sizeof *pixel);
00656   merror (pixel, "canon_compressed_load_raw()");
00657   lowbits = canon_has_lowbits();
00658   if (!lowbits) maximum = 0x3ff;
00659   fseek (ifp, 540 + lowbits*raw_height*raw_width/4, SEEK_SET);
00660   zero_after_ff = 1;
00661   getbits(-1);
00662   for (row = 0; row < raw_height; row += 8) {
00663     for (block=0; block < raw_width >> 3; block++) {
00664       memset (diffbuf, 0, sizeof diffbuf);
00665       decode = first_decode;
00666       for (i=0; i < 64; i++ ) {
00667         for (dindex=decode; dindex->branch[0]; )
00668           dindex = dindex->branch[getbits(1)];
00669         leaf = dindex->leaf;
00670         decode = second_decode;
00671         if (leaf == 0 && i) break;
00672         if (leaf == 0xff) continue;
00673         i  += leaf >> 4;
00674         len = leaf & 15;
00675         if (len == 0) continue;
00676         diff = getbits(len);
00677         if ((diff & (1 << (len-1))) == 0)
00678           diff -= (1 << len) - 1;
00679         if (i < 64) diffbuf[i] = diff;
00680       }
00681       diffbuf[0] += carry;
00682       carry = diffbuf[0];
00683       for (i=0; i < 64; i++ ) {
00684         if (pnum++ % raw_width == 0)
00685           base[0] = base[1] = 512;
00686         pixel[(block << 6) + i] = ( base[i & 1] += diffbuf[i] );
00687       }
00688     }
00689     if (lowbits) {
00690       save = ftell(ifp);
00691       fseek (ifp, 26 + row*raw_width/4, SEEK_SET);
00692       for (prow=pixel, i=0; i < raw_width*2; i++) {
00693         c = fgetc(ifp);
00694         for (r=0; r < 8; r+=2, prow++) {
00695           val = (*prow << 2) + ((c >> r) & 3);
00696           if (raw_width == 2672 && val < 512) val += 2;
00697           *prow = val;
00698         }
00699       }
00700       fseek (ifp, save, SEEK_SET);
00701     }
00702     for (r=0; r < 8; r++) {
00703       irow = row - top_margin + r;
00704       if (irow >= height) continue;
00705       for (col = 0; col < raw_width; col++) {
00706         icol = col - left_margin;
00707         if (icol < width)
00708           BAYER(irow,icol) = pixel[r*raw_width+col];
00709         else
00710           black += pixel[r*raw_width+col];
00711       }
00712     }
00713   }
00714   free (pixel);
00715   if (raw_width > width)
00716     black /= (raw_width - width) * height;
00717 }
00718 
00719 /*
00720    Not a full implementation of Lossless JPEG, just
00721    enough to decode Canon, Kodak and Adobe DNG images.
00722  */
00723 struct jhead {
00724   int bits, high, wide, clrs, restart, vpred[4];
00725   struct decode *huff[4];
00726   ushort *row;
00727 };
00728 
00729 int CLASS ljpeg_start (struct jhead *jh, int info_only)
00730 {
00731   int i, tag, len;
00732   uchar data[0x10000], *dp;
00733 
00734   init_decoder();
00735   for (i=0; i < 4; i++)
00736     jh->huff[i] = free_decode;
00737   jh->restart = INT_MAX;
00738   fread (data, 2, 1, ifp);
00739   if (data[1] != 0xd8) return 0;
00740   do {
00741     fread (data, 2, 2, ifp);
00742     tag =  data[0] << 8 | data[1];
00743     len = (data[2] << 8 | data[3]) - 2;
00744     if (tag <= 0xff00) return 0;
00745     fread (data, 1, len, ifp);
00746     switch (tag) {
00747       case 0xffc0:
00748       case 0xffc3:
00749         jh->bits = data[0];
00750         jh->high = data[1] << 8 | data[2];
00751         jh->wide = data[3] << 8 | data[4];
00752         jh->clrs = data[5];
00753         break;
00754       case 0xffc4:
00755         if (info_only) break;
00756         for (dp = data; dp < data+len && *dp < 4; ) {
00757           jh->huff[*dp] = free_decode;
00758           dp = make_decoder (++dp, 0);
00759         }
00760         break;
00761       case 0xffdd:
00762         jh->restart = data[0] << 8 | data[1];
00763     }
00764   } while (tag != 0xffda);
00765   if (info_only) return 1;
00766   jh->row = calloc (jh->wide*jh->clrs, 2);
00767   merror (jh->row, " jpeg_start()");
00768   return zero_after_ff = 1;
00769 }
00770 
00771 int CLASS ljpeg_diff (struct decode *dindex)
00772 {
00773   int len, diff;
00774 
00775   while (dindex->branch[0])
00776     dindex = dindex->branch[getbits(1)];
00777   len = dindex->leaf;
00778   if (len == 16 && (!dng_version || dng_version >= 0x1010000))
00779     return -32768;
00780   diff = getbits(len);
00781   if ((diff & (1 << (len-1))) == 0)
00782     diff -= (1 << len) - 1;
00783   return diff;
00784 }
00785 
00786 void CLASS ljpeg_row (int jrow, struct jhead *jh)
00787 {
00788   int col, c, diff;
00789   ushort *outp=jh->row;
00790 
00791   if (jrow * jh->wide % jh->restart == 0) {
00792     FORC4 jh->vpred[c] = 1 << (jh->bits-1);
00793     if (jrow) get2();                   /* Eat the FF Dx marker */
00794     getbits(-1);
00795   }
00796   for (col=0; col < jh->wide; col++)
00797     for (c=0; c < jh->clrs; c++) {
00798       diff = ljpeg_diff (jh->huff[c]);
00799       *outp = col ? outp[-jh->clrs]+diff : (jh->vpred[c] += diff);
00800       outp++;
00801     }
00802 }
00803 
00804 void CLASS lossless_jpeg_load_raw()
00805 {
00806   int jwide, jrow, jcol, val, jidx, i, j, row=0, col=0;
00807   struct jhead jh;
00808   int min=INT_MAX;
00809 
00810   if (!ljpeg_start (&jh, 0)) return;
00811   jwide = jh.wide * jh.clrs;
00812 
00813   for (jrow=0; jrow < jh.high; jrow++) {
00814     ljpeg_row (jrow, &jh);
00815     for (jcol=0; jcol < jwide; jcol++) {
00816       val = jh.row[jcol];
00817       if (jh.bits <= 12)
00818         val = curve[val];
00819       if (cr2_slice[0]) {
00820         jidx = jrow*jwide + jcol;
00821         i = jidx / (cr2_slice[1]*jh.high);
00822         if ((j = i >= cr2_slice[0]))
00823                  i  = cr2_slice[0];
00824         jidx -= i * (cr2_slice[1]*jh.high);
00825         row = jidx / cr2_slice[1+j];
00826         col = jidx % cr2_slice[1+j] + i*cr2_slice[1];
00827       }
00828       if ((unsigned) (row-top_margin) < height) {
00829         if ((unsigned) (col-left_margin) < width) {
00830           BAYER(row-top_margin,col-left_margin) = val;
00831           if (min > val) min = val;
00832         } else black += val;
00833       }
00834       if (++col >= raw_width)
00835         col = (row++,0);
00836     }
00837   }
00838   free (jh.row);
00839   if (raw_width > width)
00840     black /= (raw_width - width) * height;
00841   if (!strcasecmp(make,"KODAK"))
00842     black = min;
00843 }
00844 
00845 void CLASS adobe_copy_pixel (int row, int col, ushort **rp)
00846 {
00847   unsigned r, c;
00848 
00849   r = row -= top_margin;
00850   c = col -= left_margin;
00851   if (fuji_secondary && use_secondary) (*rp)++;
00852   if (filters) {
00853     if (fuji_width) {
00854       r = row + fuji_width - 1 - (col >> 1);
00855       c = row + ((col+1) >> 1);
00856     }
00857     if (r < height && c < width)
00858       BAYER(r,c) = **rp < 0x1000 ? curve[**rp] : **rp;
00859     *rp += 1 + fuji_secondary;
00860   } else {
00861     if (r < height && c < width)
00862       for (c=0; c < tiff_samples; c++)
00863         image[row*width+col][c] = (*rp)[c] < 0x1000 ? curve[(*rp)[c]]:(*rp)[c];
00864     *rp += tiff_samples;
00865   }
00866   if (fuji_secondary && use_secondary) (*rp)--;
00867 }
00868 
00869 void CLASS adobe_dng_load_raw_lj()
00870 {
00871   int save, twide, trow=0, tcol=0, jrow, jcol;
00872   struct jhead jh;
00873   ushort *rp;
00874 
00875   while (1) {
00876     save = ftell(ifp);
00877     fseek (ifp, get4(), SEEK_SET);
00878     if (!ljpeg_start (&jh, 0)) break;
00879     if (trow >= raw_height) break;
00880     if (jh.high > raw_height-trow)
00881         jh.high = raw_height-trow;
00882     twide = jh.wide;
00883     if (filters) twide *= jh.clrs;
00884     else         colors = jh.clrs;
00885     if (fuji_secondary) twide /= 2;
00886     if (twide > raw_width-tcol)
00887         twide = raw_width-tcol;
00888 
00889     for (jrow=0; jrow < jh.high; jrow++) {
00890       ljpeg_row (jrow, &jh);
00891       for (rp=jh.row, jcol=0; jcol < twide; jcol++)
00892         adobe_copy_pixel (trow+jrow, tcol+jcol, &rp);
00893     }
00894     fseek (ifp, save+4, SEEK_SET);
00895     if ((tcol += twide) >= raw_width) {
00896       tcol = 0;
00897       trow += jh.high;
00898     }
00899     free (jh.row);
00900   }
00901 }
00902 
00903 void CLASS adobe_dng_load_raw_nc()
00904 {
00905   ushort *pixel, *rp;
00906   int row, col;
00907 
00908   pixel = calloc (raw_width * tiff_samples, sizeof *pixel);
00909   merror (pixel, "adobe_dng_load_raw_nc()");
00910   for (row=0; row < raw_height; row++) {
00911     if (tiff_bps == 16)
00912       read_shorts (pixel, raw_width * tiff_samples);
00913     else {
00914       getbits(-1);
00915       for (col=0; col < raw_width * tiff_samples; col++)
00916         pixel[col] = getbits(tiff_bps);
00917     }
00918     for (rp=pixel, col=0; col < raw_width; col++)
00919       adobe_copy_pixel (row, col, &rp);
00920   }
00921   free (pixel);
00922 }
00923 
00924 void CLASS nikon_compressed_load_raw()
00925 {
00926   static const uchar nikon_tree[] = {
00927     0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0,
00928     5,4,3,6,2,7,1,0,8,9,11,10,12
00929   };
00930   int csize, row, col, i, diff;
00931   ushort vpred[4], hpred[2], *curve;
00932 
00933   init_decoder();
00934   make_decoder (nikon_tree, 0);
00935 
00936   fseek (ifp, curve_offset, SEEK_SET);
00937   read_shorts (vpred, 4);
00938   csize = get2();
00939   curve = calloc (csize, sizeof *curve);
00940   merror (curve, "nikon_compressed_load_raw()");
00941   read_shorts (curve, csize);
00942 
00943   fseek (ifp, data_offset, SEEK_SET);
00944   getbits(-1);
00945 
00946   for (row=0; row < height; row++)
00947     for (col=0; col < raw_width; col++)
00948     {
00949       diff = ljpeg_diff (first_decode);
00950       if (col < 2) {
00951         i = 2*(row & 1) + (col & 1);
00952         vpred[i] += diff;
00953         hpred[col] = vpred[i];
00954       } else
00955         hpred[col & 1] += diff;
00956       if ((unsigned) (col-left_margin) >= width) continue;
00957       diff = hpred[col & 1];
00958       if (diff >= csize) diff = csize-1;
00959       BAYER(row,col-left_margin) = curve[diff];
00960     }
00961   free (curve);
00962 }
00963 
00964 void CLASS nikon_load_raw()
00965 {
00966   int irow, row, col, i;
00967 
00968   getbits(-1);
00969   for (irow=0; irow < height; irow++) {
00970     row = irow;
00971     if (make[0] == 'O' || model[0] == 'E') {
00972       row = irow * 2 % height + irow / (height/2);
00973       if (row == 1 && data_offset == 0) {
00974         fseek (ifp, 0, SEEK_END);
00975         fseek (ifp, ftell(ifp)/2, SEEK_SET);
00976         getbits(-1);
00977       }
00978     }
00979     for (col=0; col < raw_width; col++) {
00980       i = getbits(12);
00981       if ((unsigned) (col-left_margin) < width)
00982         BAYER(row,col-left_margin) = i;
00983       if (tiff_compress == 34713 && (col % 10) == 9)
00984         getbits(8);
00985     }
00986   }
00987 }
00988 
00989 /*
00990    Figure out if a NEF file is compressed.  These fancy heuristics
00991    are only needed for the D100, thanks to a bug in some cameras
00992    that tags all images as "compressed".
00993  */
00994 int CLASS nikon_is_compressed()
00995 {
00996   uchar test[256];
00997   int i;
00998 
00999   if (tiff_compress != 34713)
01000     return 0;
01001   if (strcmp(model,"D100")