PageRenderTime 261ms CodeModel.GetById 28ms app.highlight 202ms RepoModel.GetById 1ms app.codeStats 2ms

/src/FreeImage/Source/LibRawLite/internal/dcraw_common.cpp

https://bitbucket.org/cabalistic/ogredeps/
C++ | 9257 lines | 8724 code | 384 blank | 149 comment | 2770 complexity | 72935f0889776ffd03608fe38e768ba2 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1/* 
   2  Copyright 2008-2010 LibRaw LLC (info@libraw.org)
   3
   4LibRaw is free software; you can redistribute it and/or modify
   5it under the terms of the one of three licenses as you choose:
   6
   71. GNU LESSER GENERAL PUBLIC LICENSE version 2.1
   8   (See file LICENSE.LGPL provided in LibRaw distribution archive for details).
   9
  102. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
  11   (See file LICENSE.CDDL provided in LibRaw distribution archive for details).
  12
  133. LibRaw Software License 27032010
  14   (See file LICENSE.LibRaw.pdf provided in LibRaw distribution archive for details).
  15
  16   This file is generated from Dave Coffin's dcraw.c
  17   dcraw.c -- Dave Coffin's raw photo decoder
  18   Copyright 1997-2010 by Dave Coffin, dcoffin a cybercom o net
  19
  20   Look into dcraw homepage (probably http://cybercom.net/~dcoffin/dcraw/)
  21   for more information
  22*/
  23
  24#include <math.h>
  25#define CLASS LibRaw::
  26#include "libraw/libraw_types.h"
  27#define LIBRAW_LIBRARY_BUILD
  28#define LIBRAW_IO_REDEFINED
  29#include "libraw/libraw.h"
  30#include "internal/defines.h"
  31#include "internal/var_defines.h"
  32#include "internal/libraw_bytebuffer.h"
  33
  34#ifdef ANDROID
  35#include <asm/byteorder.h> 
  36void swab(const void *from, void*to, ssize_t n) 
  37{ 
  38	if (n < 0) 
  39		return; 
  40 		 
  41	for (ssize_t i = 0; i < (n/2)*2; i += 2) 
  42	{
  43		*((uint16_t*)to+i) = __arch__swab16(*((uint16_t*)from+i)); 
  44	}
  45} 
  46#endif
  47
  48#ifndef __GLIBC__
  49char *my_memmem (char *haystack, size_t haystacklen,
  50	      char *needle, size_t needlelen)
  51{
  52  char *c;
  53  for (c = haystack; c <= haystack + haystacklen - needlelen; c++)
  54    if (!memcmp (c, needle, needlelen))
  55      return c;
  56  return 0;
  57}
  58#define memmem my_memmem
  59#endif
  60
  61
  62ushort CLASS sget2 (uchar *s)
  63{
  64  if (order == 0x4949)		/* "II" means little-endian */
  65    return s[0] | s[1] << 8;
  66  else				/* "MM" means big-endian */
  67    return s[0] << 8 | s[1];
  68}
  69
  70ushort CLASS get2()
  71{
  72  uchar str[2] = { 0xff,0xff };
  73  fread (str, 1, 2, ifp);
  74  return sget2(str);
  75}
  76
  77unsigned CLASS sget4 (uchar *s)
  78{
  79  if (order == 0x4949)
  80    return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24;
  81  else
  82    return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3];
  83}
  84#define sget4(s) sget4((uchar *)s)
  85
  86unsigned CLASS get4()
  87{
  88  uchar str[4] = { 0xff,0xff,0xff,0xff };
  89  fread (str, 1, 4, ifp);
  90  return sget4(str);
  91}
  92
  93unsigned CLASS getint (int type)
  94{
  95  return type == 3 ? get2() : get4();
  96}
  97
  98float CLASS int_to_float (int i)
  99{
 100  union { int i; float f; } u;
 101  u.i = i;
 102  return u.f;
 103}
 104
 105double CLASS getreal (int type)
 106{
 107  union { char c[8]; double d; } u;
 108  int i, rev;
 109
 110  switch (type) {
 111    case 3: return (unsigned short) get2();
 112    case 4: return (unsigned int) get4();
 113    case 5:  u.d = (unsigned int) get4();
 114      return u.d / (unsigned int) get4();
 115    case 8: return (signed short) get2();
 116    case 9: return (signed int) get4();
 117    case 10: u.d = (signed int) get4();
 118      return u.d / (signed int) get4();
 119    case 11: return int_to_float (get4());
 120    case 12:
 121      rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234));
 122      for (i=0; i < 8; i++)
 123	u.c[i ^ rev] = fgetc(ifp);
 124      return u.d;
 125    default: return fgetc(ifp);
 126  }
 127}
 128
 129void CLASS read_shorts (ushort *pixel, int count)
 130{
 131  if (fread (pixel, 2, count, ifp) < count) derror();
 132  if ((order == 0x4949) == (ntohs(0x1234) == 0x1234))
 133      swab ((char*)pixel, (char*)pixel, count*2);
 134}
 135
 136#ifdef LIBRAW_LIBRARY_BUILD
 137#define RBAYER(x,y) raw_image[(x)*raw_width+(y)]
 138#define RRBAYER(x,y) raw_image[((x)+top_margin)*raw_width+(y)+left_margin]
 139#define CBAYER(x,y) color_image[((x)+top_margin)*raw_width+(y)+left_margin][FC((x),(y))]
 140#else
 141#define CBAYER(x,y) BAYER((x),(y))
 142#define RBAYER(x,y) BAYER((x),(y))
 143#define RRBAYER(x,y) BAYER((x),(y))
 144#endif
 145
 146void CLASS canon_600_fixed_wb (int temp)
 147{
 148  static const short mul[4][5] = {
 149    {  667, 358,397,565,452 },
 150    {  731, 390,367,499,517 },
 151    { 1119, 396,348,448,537 },
 152    { 1399, 485,431,508,688 } };
 153  int lo, hi, i;
 154  float frac=0;
 155
 156  for (lo=4; --lo; )
 157    if (*mul[lo] <= temp) break;
 158  for (hi=0; hi < 3; hi++)
 159    if (*mul[hi] >= temp) break;
 160  if (lo != hi)
 161    frac = (float) (temp - *mul[lo]) / (*mul[hi] - *mul[lo]);
 162  for (i=1; i < 5; i++)
 163    pre_mul[i-1] = 1 / (frac * mul[hi][i] + (1-frac) * mul[lo][i]);
 164#ifdef LIBRAW_LIBRARY_BUILD
 165  color_flags.pre_mul_state = LIBRAW_COLORSTATE_CONST;
 166#endif
 167}
 168
 169/* Return values:  0 = white  1 = near white  2 = not white */
 170int CLASS canon_600_color (int ratio[2], int mar)
 171{
 172  int clipped=0, target, miss;
 173
 174  if (flash_used) {
 175    if (ratio[1] < -104)
 176      { ratio[1] = -104; clipped = 1; }
 177    if (ratio[1] >   12)
 178      { ratio[1] =   12; clipped = 1; }
 179  } else {
 180    if (ratio[1] < -264 || ratio[1] > 461) return 2;
 181    if (ratio[1] < -50)
 182      { ratio[1] = -50; clipped = 1; }
 183    if (ratio[1] > 307)
 184      { ratio[1] = 307; clipped = 1; }
 185  }
 186  target = flash_used || ratio[1] < 197
 187	? -38 - (398 * ratio[1] >> 10)
 188	: -123 + (48 * ratio[1] >> 10);
 189  if (target - mar <= ratio[0] &&
 190      target + 20  >= ratio[0] && !clipped) return 0;
 191  miss = target - ratio[0];
 192  if (abs(miss) >= mar*4) return 2;
 193  if (miss < -20) miss = -20;
 194  if (miss > mar) miss = mar;
 195  ratio[0] = target - miss;
 196  return 1;
 197}
 198
 199void CLASS canon_600_auto_wb()
 200{
 201  int mar, row, col, i, j, st, count[] = { 0,0 };
 202  int test[8], total[2][8], ratio[2][2], stat[2];
 203
 204  memset (&total, 0, sizeof total);
 205  i = canon_ev + 0.5;
 206  if      (i < 10) mar = 150;
 207  else if (i > 12) mar = 20;
 208  else mar = 280 - 20 * i;
 209  if (flash_used) mar = 80;
 210  for (row=14; row < height-14; row+=4)
 211    for (col=10; col < width; col+=2) {
 212      for (i=0; i < 8; i++)
 213	test[(i & 4) + FC(row+(i >> 1),col+(i & 1))] =
 214		    BAYER(row+(i >> 1),col+(i & 1));
 215      for (i=0; i < 8; i++)
 216	if (test[i] < 150 || test[i] > 1500) goto next;
 217      for (i=0; i < 4; i++)
 218	if (abs(test[i] - test[i+4]) > 50) goto next;
 219      for (i=0; i < 2; i++) {
 220	for (j=0; j < 4; j+=2)
 221	  ratio[i][j >> 1] = ((test[i*4+j+1]-test[i*4+j]) << 10) / test[i*4+j];
 222	stat[i] = canon_600_color (ratio[i], mar);
 223      }
 224      if ((st = stat[0] | stat[1]) > 1) goto next;
 225      for (i=0; i < 2; i++)
 226	if (stat[i])
 227	  for (j=0; j < 2; j++)
 228	    test[i*4+j*2+1] = test[i*4+j*2] * (0x400 + ratio[i][j]) >> 10;
 229      for (i=0; i < 8; i++)
 230	total[st][i] += test[i];
 231      count[st]++;
 232next: ;
 233    }
 234  if (count[0] | count[1]) {
 235    st = count[0]*200 < count[1];
 236    for (i=0; i < 4; i++)
 237      pre_mul[i] = 1.0 / (total[st][i] + total[st][i+4]);
 238#ifdef LIBRAW_LIBRARY_BUILD
 239    color_flags.pre_mul_state = LIBRAW_COLORSTATE_CALCULATED;
 240#endif
 241  }
 242}
 243
 244void CLASS canon_600_coeff()
 245{
 246  static const short table[6][12] = {
 247    { -190,702,-1878,2390,   1861,-1349,905,-393, -432,944,2617,-2105  },
 248    { -1203,1715,-1136,1648, 1388,-876,267,245,  -1641,2153,3921,-3409 },
 249    { -615,1127,-1563,2075,  1437,-925,509,3,     -756,1268,2519,-2007 },
 250    { -190,702,-1886,2398,   2153,-1641,763,-251, -452,964,3040,-2528  },
 251    { -190,702,-1878,2390,   1861,-1349,905,-393, -432,944,2617,-2105  },
 252    { -807,1319,-1785,2297,  1388,-876,769,-257,  -230,742,2067,-1555  } };
 253  int t=0, i, c;
 254  float mc, yc;
 255
 256  mc = pre_mul[1] / pre_mul[2];
 257  yc = pre_mul[3] / pre_mul[2];
 258  if (mc > 1 && mc <= 1.28 && yc < 0.8789) t=1;
 259  if (mc > 1.28 && mc <= 2) {
 260    if  (yc < 0.8789) t=3;
 261    else if (yc <= 2) t=4;
 262  }
 263  if (flash_used) t=5;
 264  for (raw_color = i=0; i < 3; i++)
 265    FORCC rgb_cam[i][c] = table[t][i*4 + c] / 1024.0;
 266#ifdef LIBRAW_LIBRARY_BUILD
 267  color_flags.rgb_cam_state = LIBRAW_COLORSTATE_CALCULATED;
 268#endif
 269}
 270
 271void CLASS canon_600_load_raw()
 272{
 273  uchar  data[1120], *dp;
 274  ushort pixel[896], *pix;
 275  int irow, row, col, val;
 276  static const short mul[4][2] =
 277  { { 1141,1145 }, { 1128,1109 }, { 1178,1149 }, { 1128,1109 } };
 278
 279  for (irow=row=0; irow < height; irow++) {
 280    if (fread (data, 1, raw_width*5/4, ifp) < raw_width*5/4) derror();
 281    for (dp=data, pix=pixel; dp < data+1120; dp+=10, pix+=8) {
 282      pix[0] = (dp[0] << 2) + (dp[1] >> 6    );
 283      pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3);
 284      pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3);
 285      pix[3] = (dp[4] << 2) + (dp[1]      & 3);
 286      pix[4] = (dp[5] << 2) + (dp[9]      & 3);
 287      pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3);
 288      pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3);
 289      pix[7] = (dp[8] << 2) + (dp[9] >> 6    );
 290    }
 291#ifndef LIBRAW_LIBRARY_BUILD
 292    for (col=0; col < width; col++)
 293        {
 294            BAYER(row,col) = pixel[col];
 295        }
 296#else
 297    for (col=0; col < raw_width; col++)
 298            RBAYER(row,col) = pixel[col];
 299#endif
 300
 301    for (col=width; col < raw_width; col++)
 302        {
 303            black += pixel[col];
 304        }
 305    if ((row+=2) > height) row = 1;
 306  }
 307  if (raw_width > width)
 308    black = black / ((raw_width - width) * height) - 4;
 309#ifndef LIBRAW_LIBRARY_BUILD
 310  for (row=0; row < height; row++)
 311    for (col=0; col < width; col++) {
 312      if ((val = BAYER(row,col) - black) < 0) val = 0;
 313      val = val * mul[row & 3][col & 1] >> 9;
 314      BAYER(row,col) = val;
 315    }
 316#else
 317  for (row=0; row < height; row++)
 318    for (col=0; col < raw_width; col++) {
 319      if ((val = RBAYER(row,col) - black) < 0) val = 0;
 320      val = val * mul[row & 3][col & 1] >> 9;
 321      RBAYER(row,col) = val;
 322    }
 323
 324#endif
 325  canon_600_fixed_wb(1311);
 326  canon_600_auto_wb();
 327  canon_600_coeff();
 328  maximum = (0x3ff - black) * 1109 >> 9;
 329  black = 0;
 330}
 331
 332void CLASS remove_zeroes()
 333{
 334  unsigned row, col, tot, n, r, c;
 335
 336#ifdef LIBRAW_LIBRARY_BUILD
 337  RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES,0,2);
 338#endif
 339  for (row=0; row < height; row++)
 340    for (col=0; col < width; col++)
 341      if (BAYER(row,col) == 0) {
 342	tot = n = 0;
 343	for (r = row-2; r <= row+2; r++)
 344	  for (c = col-2; c <= col+2; c++)
 345	    if (r < height && c < width &&
 346		FC(r,c) == FC(row,col) && BAYER(r,c))
 347	      tot += (n++,BAYER(r,c));
 348	if (n) BAYER(row,col) = tot/n;
 349      }
 350#ifdef LIBRAW_LIBRARY_BUILD
 351  RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES,1,2);
 352#endif
 353}
 354
 355int CLASS canon_s2is()
 356{
 357  unsigned row;
 358
 359  for (row=0; row < 100; row++) {
 360    fseek (ifp, row*3340 + 3284, SEEK_SET);
 361    if (getc(ifp) > 15) return 1;
 362  }
 363  return 0;
 364}
 365
 366/*
 367   getbits(-1) initializes the buffer
 368   getbits(n) where 0 <= n <= 25 returns an n-bit integer
 369 */
 370
 371unsigned CLASS getbithuff (int nbits, ushort *huff)
 372{
 373#ifdef LIBRAW_NOTHREADS
 374  static unsigned bitbuf=0;
 375  static int vbits=0, reset=0;
 376#else
 377#define bitbuf tls->getbits.bitbuf
 378#define vbits  tls->getbits.vbits
 379#define reset  tls->getbits.reset
 380#endif
 381  unsigned c;
 382
 383  if (nbits == -1)
 384    return bitbuf = vbits = reset = 0;
 385  if (nbits == 0 || vbits < 0) return 0;
 386  while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF &&
 387    !(reset = zero_after_ff && c == 0xff && fgetc(ifp))) {
 388    bitbuf = (bitbuf << 8) + (uchar) c;
 389    vbits += 8;
 390  }
 391  c = bitbuf << (32-vbits) >> (32-nbits);
 392  if (huff) {
 393    vbits -= huff[c] >> 8;
 394    c = (uchar) huff[c];
 395  } else
 396    vbits -= nbits;
 397  if (vbits < 0) derror();
 398  return c;
 399#ifndef LIBRAW_NOTHREADS
 400#undef bitbuf
 401#undef vbits
 402#undef reset
 403#endif
 404}
 405
 406#define getbits(n) getbithuff(n,0)
 407#define gethuff(h) getbithuff(*h,h+1)
 408
 409/*
 410   Construct a decode tree according to the specification in *source.
 411   The first 16 bytes specify how many codes should be 1-bit, 2-bit
 412   3-bit, etc.  Bytes after that are the leaf values.
 413
 414   For example, if the source is
 415
 416    { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
 417      0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff  },
 418
 419   then the code is
 420
 421	00		0x04
 422	010		0x03
 423	011		0x05
 424	100		0x06
 425	101		0x02
 426	1100		0x07
 427	1101		0x01
 428	11100		0x08
 429	11101		0x09
 430	11110		0x00
 431	111110		0x0a
 432	1111110		0x0b
 433	1111111		0xff
 434 */
 435ushort * CLASS make_decoder_ref (const uchar **source)
 436{
 437  int max, len, h, i, j;
 438  const uchar *count;
 439  ushort *huff;
 440
 441  count = (*source += 16) - 17;
 442  for (max=16; max && !count[max]; max--);
 443  huff = (ushort *) calloc (1 + (1 << max), sizeof *huff);
 444  merror (huff, "make_decoder()");
 445  huff[0] = max;
 446  for (h=len=1; len <= max; len++)
 447    for (i=0; i < count[len]; i++, ++*source)
 448      for (j=0; j < 1 << (max-len); j++)
 449	if (h <= 1 << max)
 450	  huff[h++] = len << 8 | **source;
 451  return huff;
 452}
 453
 454ushort * CLASS make_decoder (const uchar *source)
 455{
 456  return make_decoder_ref (&source);
 457}
 458
 459void CLASS crw_init_tables (unsigned table, ushort *huff[2])
 460{
 461  static const uchar first_tree[3][29] = {
 462    { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
 463      0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff  },
 464    { 0,2,2,3,1,1,1,1,2,0,0,0,0,0,0,0,
 465      0x03,0x02,0x04,0x01,0x05,0x00,0x06,0x07,0x09,0x08,0x0a,0x0b,0xff  },
 466    { 0,0,6,3,1,1,2,0,0,0,0,0,0,0,0,0,
 467
 468      0x06,0x05,0x07,0x04,0x08,0x03,0x09,0x02,0x00,0x0a,0x01,0x0b,0xff  },
 469  };
 470  static const uchar second_tree[3][180] = {
 471    { 0,2,2,2,1,4,2,1,2,5,1,1,0,0,0,139,
 472      0x03,0x04,0x02,0x05,0x01,0x06,0x07,0x08,
 473      0x12,0x13,0x11,0x14,0x09,0x15,0x22,0x00,0x21,0x16,0x0a,0xf0,
 474      0x23,0x17,0x24,0x31,0x32,0x18,0x19,0x33,0x25,0x41,0x34,0x42,
 475      0x35,0x51,0x36,0x37,0x38,0x29,0x79,0x26,0x1a,0x39,0x56,0x57,
 476      0x28,0x27,0x52,0x55,0x58,0x43,0x76,0x59,0x77,0x54,0x61,0xf9,
 477      0x71,0x78,0x75,0x96,0x97,0x49,0xb7,0x53,0xd7,0x74,0xb6,0x98,
 478      0x47,0x48,0x95,0x69,0x99,0x91,0xfa,0xb8,0x68,0xb5,0xb9,0xd6,
 479      0xf7,0xd8,0x67,0x46,0x45,0x94,0x89,0xf8,0x81,0xd5,0xf6,0xb4,
 480      0x88,0xb1,0x2a,0x44,0x72,0xd9,0x87,0x66,0xd4,0xf5,0x3a,0xa7,
 481      0x73,0xa9,0xa8,0x86,0x62,0xc7,0x65,0xc8,0xc9,0xa1,0xf4,0xd1,
 482      0xe9,0x5a,0x92,0x85,0xa6,0xe7,0x93,0xe8,0xc1,0xc6,0x7a,0x64,
 483      0xe1,0x4a,0x6a,0xe6,0xb3,0xf1,0xd3,0xa5,0x8a,0xb2,0x9a,0xba,
 484      0x84,0xa4,0x63,0xe5,0xc5,0xf3,0xd2,0xc4,0x82,0xaa,0xda,0xe4,
 485      0xf2,0xca,0x83,0xa3,0xa2,0xc3,0xea,0xc2,0xe2,0xe3,0xff,0xff  },
 486    { 0,2,2,1,4,1,4,1,3,3,1,0,0,0,0,140,
 487      0x02,0x03,0x01,0x04,0x05,0x12,0x11,0x06,
 488      0x13,0x07,0x08,0x14,0x22,0x09,0x21,0x00,0x23,0x15,0x31,0x32,
 489      0x0a,0x16,0xf0,0x24,0x33,0x41,0x42,0x19,0x17,0x25,0x18,0x51,
 490      0x34,0x43,0x52,0x29,0x35,0x61,0x39,0x71,0x62,0x36,0x53,0x26,
 491      0x38,0x1a,0x37,0x81,0x27,0x91,0x79,0x55,0x45,0x28,0x72,0x59,
 492      0xa1,0xb1,0x44,0x69,0x54,0x58,0xd1,0xfa,0x57,0xe1,0xf1,0xb9,
 493      0x49,0x47,0x63,0x6a,0xf9,0x56,0x46,0xa8,0x2a,0x4a,0x78,0x99,
 494      0x3a,0x75,0x74,0x86,0x65,0xc1,0x76,0xb6,0x96,0xd6,0x89,0x85,
 495      0xc9,0xf5,0x95,0xb4,0xc7,0xf7,0x8a,0x97,0xb8,0x73,0xb7,0xd8,
 496      0xd9,0x87,0xa7,0x7a,0x48,0x82,0x84,0xea,0xf4,0xa6,0xc5,0x5a,
 497      0x94,0xa4,0xc6,0x92,0xc3,0x68,0xb5,0xc8,0xe4,0xe5,0xe6,0xe9,
 498      0xa2,0xa3,0xe3,0xc2,0x66,0x67,0x93,0xaa,0xd4,0xd5,0xe7,0xf8,
 499      0x88,0x9a,0xd7,0x77,0xc4,0x64,0xe2,0x98,0xa5,0xca,0xda,0xe8,
 500      0xf3,0xf6,0xa9,0xb2,0xb3,0xf2,0xd2,0x83,0xba,0xd3,0xff,0xff  },
 501    { 0,0,6,2,1,3,3,2,5,1,2,2,8,10,0,117,
 502      0x04,0x05,0x03,0x06,0x02,0x07,0x01,0x08,
 503      0x09,0x12,0x13,0x14,0x11,0x15,0x0a,0x16,0x17,0xf0,0x00,0x22,
 504      0x21,0x18,0x23,0x19,0x24,0x32,0x31,0x25,0x33,0x38,0x37,0x34,
 505      0x35,0x36,0x39,0x79,0x57,0x58,0x59,0x28,0x56,0x78,0x27,0x41,
 506      0x29,0x77,0x26,0x42,0x76,0x99,0x1a,0x55,0x98,0x97,0xf9,0x48,
 507      0x54,0x96,0x89,0x47,0xb7,0x49,0xfa,0x75,0x68,0xb6,0x67,0x69,
 508      0xb9,0xb8,0xd8,0x52,0xd7,0x88,0xb5,0x74,0x51,0x46,0xd9,0xf8,
 509      0x3a,0xd6,0x87,0x45,0x7a,0x95,0xd5,0xf6,0x86,0xb4,0xa9,0x94,
 510      0x53,0x2a,0xa8,0x43,0xf5,0xf7,0xd4,0x66,0xa7,0x5a,0x44,0x8a,
 511      0xc9,0xe8,0xc8,0xe7,0x9a,0x6a,0x73,0x4a,0x61,0xc7,0xf4,0xc6,
 512      0x65,0xe9,0x72,0xe6,0x71,0x91,0x93,0xa6,0xda,0x92,0x85,0x62,
 513      0xf3,0xc5,0xb2,0xa4,0x84,0xba,0x64,0xa5,0xb3,0xd2,0x81,0xe5,
 514      0xd3,0xaa,0xc4,0xca,0xf2,0xb1,0xe4,0xd1,0x83,0x63,0xea,0xc3,
 515      0xe2,0x82,0xf1,0xa3,0xc2,0xa1,0xc1,0xe3,0xa2,0xe1,0xff,0xff  }
 516  };
 517  if (table > 2) table = 2;
 518  huff[0] = make_decoder ( first_tree[table]);
 519  huff[1] = make_decoder (second_tree[table]);
 520}
 521
 522/*
 523   Return 0 if the image starts with compressed data,
 524   1 if it starts with uncompressed low-order bits.
 525
 526   In Canon compressed data, 0xff is always followed by 0x00.
 527 */
 528int CLASS canon_has_lowbits()
 529{
 530  uchar test[0x4000];
 531  int ret=1;
 532  unsigned i;
 533
 534  fseek (ifp, 0, SEEK_SET);
 535  fread (test, 1, sizeof test, ifp);
 536  for (i=540; i < sizeof test - 1; i++)
 537    if (test[i] == 0xff) {
 538      if (test[i+1]) return 1;
 539      ret=0;
 540    }
 541  return ret;
 542}
 543
 544void CLASS canon_compressed_load_raw()
 545{
 546  ushort *pixel, *prow, *huff[2];
 547  int nblocks, lowbits, i, c, row, r, col, save, val;
 548  unsigned irow, icol;
 549  int block, diffbuf[64], leaf, len, diff, carry=0, pnum=0, base[2];
 550
 551  crw_init_tables (tiff_compress, huff);
 552  pixel = (ushort *) calloc (raw_width*8, sizeof *pixel);
 553  merror (pixel, "canon_compressed_load_raw()");
 554  lowbits = canon_has_lowbits();
 555  if (!lowbits) maximum = 0x3ff;
 556  fseek (ifp, 540 + lowbits*raw_height*raw_width/4, SEEK_SET);
 557  zero_after_ff = 1;
 558  getbits(-1);
 559  for (row=0; row < raw_height; row+=8) {
 560    nblocks = MIN (8, raw_height-row) * raw_width >> 6;
 561    for (block=0; block < nblocks; block++) {
 562      memset (diffbuf, 0, sizeof diffbuf);
 563      for (i=0; i < 64; i++ ) {
 564	leaf = gethuff(huff[i > 0]);
 565	if (leaf == 0 && i) break;
 566	if (leaf == 0xff) continue;
 567	i  += leaf >> 4;
 568	len = leaf & 15;
 569	if (len == 0) continue;
 570	diff = getbits(len);
 571	if ((diff & (1 << (len-1))) == 0)
 572	  diff -= (1 << len) - 1;
 573	if (i < 64) diffbuf[i] = diff;
 574      }
 575      diffbuf[0] += carry;
 576      carry = diffbuf[0];
 577      for (i=0; i < 64; i++ ) {
 578	if (pnum++ % raw_width == 0)
 579	  base[0] = base[1] = 512;
 580	if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10)
 581	  derror();
 582      }
 583    }
 584    if (lowbits) {
 585      save = ftell(ifp);
 586      fseek (ifp, 26 + row*raw_width/4, SEEK_SET);
 587      for (prow=pixel, i=0; i < raw_width*2; i++) {
 588	c = fgetc(ifp);
 589	for (r=0; r < 8; r+=2, prow++) {
 590	  val = (*prow << 2) + ((c >> r) & 3);
 591	  if (raw_width == 2672 && val < 512) val += 2;
 592	  *prow = val;
 593	}
 594      }
 595      fseek (ifp, save, SEEK_SET);
 596    }
 597
 598#ifdef LIBRAW_LIBRARY_BUILD
 599    for (r=0; r < 8; r++) {
 600        if(row+r>=raw_height) break; // Not sure that raw_height is always N*8
 601        // MOVE entire row into place
 602        memmove(&raw_image[(row+r)*raw_width],&pixel[r*raw_width],raw_width*sizeof(pixel[0]));
 603
 604        irow = row - top_margin + r;
 605        if (irow >= height) continue; // if row above image area than irow is VERY positive :)
 606
 607        // only margins!
 608        for (col=0; col < left_margin; col++) 
 609            {
 610                icol = col - left_margin;
 611                c = FC(irow,icol);
 612                if (icol >= width && col > 1 && (unsigned) (col-left_margin+2) > width+3)
 613                    cblack[c] += (cblack[4+c]++,pixel[r*raw_width+col]);
 614            }
 615        for (col=width+left_margin; col < raw_width; col++) 
 616            {
 617                icol = col - left_margin;
 618                c = FC(irow,icol);
 619                if (icol >= width && col > 1 && (unsigned) (col-left_margin+2) > width+3)
 620                    cblack[c] += (cblack[4+c]++,pixel[r*raw_width+col]);
 621            }
 622
 623    }
 624#else
 625    // dcraw original code
 626    for (r=0; r < 8; r++) {
 627      irow = row - top_margin + r;
 628      if (irow >= height) continue;
 629      for (col=0; col < raw_width; col++) {
 630	icol = col - left_margin;
 631	c = FC(irow,icol);
 632	if (icol < width)
 633	  BAYER(irow,icol) = pixel[r*raw_width+col];
 634	else if (col > 1 && (unsigned) (col-left_margin+2) > width+3)
 635	  cblack[c] += (cblack[4+c]++,pixel[r*raw_width+col]);
 636      }
 637    }
 638#endif
 639  }
 640  free (pixel);
 641  FORC(2) free (huff[c]);
 642  FORC4 if (cblack[4+c]) cblack[c] /= cblack[4+c];
 643}
 644
 645int CLASS ljpeg_start (struct jhead *jh, int info_only)
 646{
 647  int c, tag, len;
 648  uchar data[0x10000];
 649  const uchar *dp;
 650
 651  memset (jh, 0, sizeof *jh);
 652  jh->restart = INT_MAX;
 653  fread (data, 2, 1, ifp);
 654  if (data[1] != 0xd8) return 0;
 655  do {
 656    fread (data, 2, 2, ifp);
 657    tag =  data[0] << 8 | data[1];
 658    len = (data[2] << 8 | data[3]) - 2;
 659    if (tag <= 0xff00) return 0;
 660    fread (data, 1, len, ifp);
 661    switch (tag) {
 662      case 0xffc3:
 663	jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3;
 664      case 0xffc0:
 665	jh->bits = data[0];
 666	jh->high = data[1] << 8 | data[2];
 667	jh->wide = data[3] << 8 | data[4];
 668	jh->clrs = data[5] + jh->sraw;
 669	if (len == 9 && !dng_version) getc(ifp);
 670	break;
 671      case 0xffc4:
 672	if (info_only) break;
 673	for (dp = data; dp < data+len && (c = *dp++) < 4; )
 674	  jh->free[c] = jh->huff[c] = make_decoder_ref (&dp);
 675	break;
 676      case 0xffda:
 677	jh->psv = data[1+data[0]*2];
 678	jh->bits -= data[3+data[0]*2] & 15;
 679	break;
 680      case 0xffdd:
 681	jh->restart = data[0] << 8 | data[1];
 682    }
 683  } while (tag != 0xffda);
 684  if (info_only) return 1;
 685  FORC(5) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c];
 686  if (jh->sraw) {
 687    FORC(4)        jh->huff[2+c] = jh->huff[1];
 688    FORC(jh->sraw) jh->huff[1+c] = jh->huff[0];
 689  }
 690  jh->row = (ushort *) calloc (jh->wide*jh->clrs, 4);
 691  merror (jh->row, "ljpeg_start()");
 692  return zero_after_ff = 1;
 693}
 694
 695void CLASS ljpeg_end (struct jhead *jh)
 696{
 697  int c;
 698  FORC4 if (jh->free[c]) free (jh->free[c]);
 699  free (jh->row);
 700}
 701
 702// used for kodak-262 decoder
 703int CLASS ljpeg_diff (ushort *huff)
 704{
 705  int len, diff;
 706
 707  len = gethuff(huff);
 708  if (len == 16 && (!dng_version || dng_version >= 0x1010000))
 709    return -32768;
 710  diff = getbits(len);
 711  if ((diff & (1 << (len-1))) == 0)
 712    diff -= (1 << len) - 1;
 713  return diff;
 714}
 715
 716#ifdef LIBRAW_LIBRARY_BUILD
 717int CLASS ljpeg_diff_new (LibRaw_bit_buffer& bits, LibRaw_byte_buffer* buf,ushort *huff)
 718{
 719  int len, diff;
 720
 721  len = bits._gethuff_lj(buf,*huff,huff+1);
 722  if (len == 16 && (!dng_version || dng_version >= 0x1010000))
 723    return -32768;
 724  diff = bits._getbits_lj(buf,len);
 725  if ((diff & (1 << (len-1))) == 0)
 726    diff -= (1 << len) - 1;
 727  return diff;
 728}
 729
 730int CLASS ljpeg_diff_pef (LibRaw_bit_buffer& bits, LibRaw_byte_buffer* buf,ushort *huff)
 731{
 732  int len, diff;
 733
 734  len = bits._gethuff(buf,*huff,huff+1,zero_after_ff);
 735  if (len == 16 && (!dng_version || dng_version >= 0x1010000))
 736    return -32768;
 737  diff = bits._getbits(buf,len,zero_after_ff);
 738  if ((diff & (1 << (len-1))) == 0)
 739    diff -= (1 << len) - 1;
 740  return diff;
 741}
 742
 743
 744#endif
 745
 746
 747ushort * CLASS ljpeg_row (int jrow, struct jhead *jh)
 748{
 749  int col, c, diff, pred, spred=0;
 750  ushort mark=0, *row[3];
 751
 752  if (jrow * jh->wide % jh->restart == 0) {
 753    FORC(6) jh->vpred[c] = 1 << (jh->bits-1);
 754    if (jrow) {
 755      fseek (ifp, -2, SEEK_CUR);
 756      do mark = (mark << 8) + (c = fgetc(ifp));
 757      while (c != EOF && mark >> 4 != 0xffd);
 758    }
 759    getbits(-1);
 760  }
 761  FORC3 row[c] = jh->row + jh->wide*jh->clrs*((jrow+c) & 1);
 762  for (col=0; col < jh->wide; col++)
 763    FORC(jh->clrs) {
 764      diff = ljpeg_diff (jh->huff[c]);
 765      if (jh->sraw && c <= jh->sraw && (col | c))
 766		    pred = spred;
 767      else if (col) pred = row[0][-jh->clrs];
 768      else	    pred = (jh->vpred[c] += diff) - diff;
 769      if (jrow && col) switch (jh->psv) {
 770	case 1:	break;
 771	case 2: pred = row[1][0];					break;
 772	case 3: pred = row[1][-jh->clrs];				break;
 773	case 4: pred = pred +   row[1][0] - row[1][-jh->clrs];		break;
 774	case 5: pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1);	break;
 775	case 6: pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1);	break;
 776	case 7: pred = (pred + row[1][0]) >> 1;				break;
 777	default: pred = 0;
 778      }
 779      if ((**row = pred + diff) >> jh->bits) derror();
 780      if (c <= jh->sraw) spred = **row;
 781      row[0]++; row[1]++;
 782    }
 783  return row[2];
 784}
 785
 786#ifdef LIBRAW_LIBRARY_BUILD
 787ushort * CLASS ljpeg_row_new (int jrow, struct jhead *jh, LibRaw_bit_buffer& bits,LibRaw_byte_buffer* bytes)
 788{
 789  int col, c, diff, pred, spred=0;
 790  ushort mark=0, *row[3];
 791
 792  if (jrow * jh->wide % jh->restart == 0) {
 793    FORC(6) jh->vpred[c] = 1 << (jh->bits-1);
 794    if (jrow) {
 795        bytes->unseek2();
 796        do mark = (mark << 8) + (c = bytes->get_byte());
 797        while (c != EOF && mark >> 4 != 0xffd);
 798    }
 799    bits.reset();
 800  }
 801  FORC3 row[c] = jh->row + jh->wide*jh->clrs*((jrow+c) & 1);
 802  for (col=0; col < jh->wide; col++)
 803    FORC(jh->clrs) {
 804        diff = ljpeg_diff_new (bits,bytes,jh->huff[c]);
 805      if (jh->sraw && c <= jh->sraw && (col | c))
 806		    pred = spred;
 807      else if (col) pred = row[0][-jh->clrs];
 808      else	    pred = (jh->vpred[c] += diff) - diff;
 809      if (jrow && col) switch (jh->psv) {
 810	case 1:	break;
 811	case 2: pred = row[1][0];					break;
 812	case 3: pred = row[1][-jh->clrs];				break;
 813	case 4: pred = pred +   row[1][0] - row[1][-jh->clrs];		break;
 814	case 5: pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1);	break;
 815	case 6: pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1);	break;
 816	case 7: pred = (pred + row[1][0]) >> 1;				break;
 817	default: pred = 0;
 818      }
 819      if ((**row = pred + diff) >> jh->bits) derror();
 820      if (c <= jh->sraw) spred = **row;
 821      row[0]++; row[1]++;
 822    }
 823  return row[2];
 824}
 825
 826#endif
 827
 828void CLASS lossless_jpeg_load_raw()
 829{
 830  int jwide, jrow, jcol, val, c, i, row=0, col=0;
 831#ifndef LIBRAW_LIBRARY_BUILD
 832  int jidx,j;
 833#endif
 834  struct jhead jh;
 835  int min=INT_MAX;
 836  ushort *rp;
 837#ifdef LIBRAW_LIBRARY_BUILD
 838  int save_min = 0;
 839  unsigned slicesW[16],slicesWcnt=0,slices;
 840  unsigned *offset;
 841  unsigned t_y=0,t_x=0,t_s=0,slice=0,pixelsInSlice,pixno;
 842  if (!strcasecmp(make,"KODAK"))
 843      save_min = 1;
 844#endif
 845
 846#ifdef LIBRAW_LIBRARY_BUILD
 847  if (cr2_slice[0]>15)
 848      throw LIBRAW_EXCEPTION_IO_EOF; // change many slices
 849#else
 850  fprintf(stderr,"Too many CR2 slices: %d\n",cr2_slice[0]+1);
 851  return;
 852#endif
 853
 854
 855  if (!ljpeg_start (&jh, 0)) return;
 856  jwide = jh.wide * jh.clrs;
 857
 858#ifdef LIBRAW_LIBRARY_BUILD
 859  if(cr2_slice[0])
 860      {
 861          for(i=0;i<cr2_slice[0];i++)
 862              slicesW[slicesWcnt++] = cr2_slice[1];
 863          slicesW[slicesWcnt++] = cr2_slice[2];
 864      }
 865  else
 866      {
 867          // not sliced
 868          slicesW[slicesWcnt++] = raw_width; // safe fallback
 869      }
 870       
 871  slices = slicesWcnt * jh.high;
 872  offset = (unsigned*)calloc(slices+1,sizeof(offset[0]));
 873  
 874  for(slice=0;slice<slices;slice++)
 875      {
 876          offset[slice] = (t_x + t_y * raw_width)| (t_s<<28);
 877          if(offset[slice] & 0x0fffffff >= raw_width * raw_height)
 878              throw LIBRAW_EXCEPTION_IO_BADFILE; 
 879          t_y++;
 880          if(t_y == jh.high)
 881              {
 882                  t_y = 0;
 883                  t_x += slicesW[t_s++];
 884              }
 885      }
 886  offset[slices] = offset[slices-1];
 887  slice = 1; // next slice
 888  pixno = offset[0];
 889  pixelsInSlice = slicesW[0];
 890#endif
 891
 892#ifdef LIBRAW_LIBRARY_BUILD
 893  LibRaw_byte_buffer *buf=NULL;
 894  if(data_size)
 895      buf = ifp->make_byte_buffer(data_size);
 896  LibRaw_bit_buffer bits;
 897#endif
 898  for (jrow=0; jrow < jh.high; jrow++) {
 899#ifdef LIBRAW_LIBRARY_BUILD
 900      if (data_size)
 901          rp = ljpeg_row_new (jrow, &jh,bits,buf);
 902      else
 903#endif
 904    rp = ljpeg_row (jrow, &jh);
 905
 906    if (load_flags & 1)
 907      row = jrow & 1 ? height-1-jrow/2 : jrow/2;
 908    for (jcol=0; jcol < jwide; jcol++) {
 909      val = *rp++;
 910      if (jh.bits <= 12)
 911	val = curve[val & 0xfff];
 912#ifndef LIBRAW_LIBRARY_BUILD
 913      // slow dcraw way to calculate row/col
 914      if (cr2_slice[0]) {
 915	jidx = jrow*jwide + jcol;
 916	i = jidx / (cr2_slice[1]*jh.high);
 917	if ((j = i >= cr2_slice[0]))
 918		 i  = cr2_slice[0];
 919	jidx -= i * (cr2_slice[1]*jh.high);
 920	row = jidx / cr2_slice[1+j];
 921	col = jidx % cr2_slice[1+j] + i*cr2_slice[1];
 922      }
 923#else
 924      // new fast one, but for data_size defined only (i.e. new CR2 format, not 1D/1Ds)
 925      if(data_size) 
 926          {
 927              row = pixno/raw_width;
 928              col = pixno % raw_width;
 929              pixno++;
 930              if (0 == --pixelsInSlice)
 931                  {
 932                      unsigned o = offset[slice++];
 933                      pixno = o & 0x0fffffff;
 934                      pixelsInSlice = slicesW[o>>28];
 935                  }
 936          }
 937#endif
 938#ifndef LIBRAW_LIBRARY_BUILD
 939
 940      if (raw_width == 3984 && (col -= 2) < 0)
 941              col += (row--,raw_width);
 942
 943      if ((unsigned) (row-top_margin) < height) {
 944	c = FC(row-top_margin,col-left_margin);
 945	if ((unsigned) (col-left_margin) < width) {
 946	  BAYER(row-top_margin,col-left_margin) = val;
 947	  if (min > val) min = val;
 948	} else if (col > 1 && (unsigned) (col-left_margin+2) > width+3)
 949	  cblack[c] += (cblack[4+c]++,val);
 950      }
 951#else
 952      if (raw_width == 3984)
 953          {
 954              if ( (col -= 2) < 0)
 955                  col += (row--,raw_width);
 956              if(row >= 0 && row < raw_height && col >= 0 && col < raw_width)
 957                  RBAYER(row,col) = val;
 958          }
 959      else 
 960          RBAYER(row,col) = val;
 961
 962      if ((unsigned) (row-top_margin) < height) 
 963          {
 964              // within image height
 965              if ((unsigned) (col-left_margin) < width) 
 966                  {
 967                      // within image area, save min
 968                      if(save_min)
 969                          if (min > val) min = val;
 970                  } 
 971              else if (col > 1 && (unsigned) (col-left_margin+2) > width+3) 
 972                  {
 973                      c = FC(row-top_margin,col-left_margin);
 974                      cblack[c] += (cblack[4+c]++,val);
 975                  }
 976          }
 977#endif
 978
 979#ifndef LIBRAW_LIBRARY_BUILD
 980      if (++col >= raw_width)
 981	col = (row++,0);
 982#else
 983      if(!data_size) // 1D or 1Ds case
 984          if (++col >= raw_width)
 985              col = (row++,0);
 986#endif
 987    }
 988  }
 989  ljpeg_end (&jh);
 990  FORC4 if (cblack[4+c]) cblack[c] /= cblack[4+c];
 991  if (!strcasecmp(make,"KODAK"))
 992    black = min;
 993#ifdef LIBRAW_LIBRARY_BUILD
 994  if(buf)
 995      delete buf;
 996  free(offset);
 997#endif
 998}
 999
1000void CLASS canon_sraw_load_raw()
1001{
1002  struct jhead jh;
1003  short *rp=0, (*ip)[4];
1004  int jwide, slice, scol, ecol, row, col, jrow=0, jcol=0, pix[3], c;
1005  int v[3]={0,0,0}, ver, hue;
1006  char *cp;
1007
1008  if (!ljpeg_start (&jh, 0)) return;
1009  jwide = (jh.wide >>= 1) * jh.clrs;
1010
1011#ifdef LIBRAW_LIBRARY_BUILD
1012  if(!data_size)
1013      throw LIBRAW_EXCEPTION_IO_BADFILE;
1014  LibRaw_byte_buffer *buf = ifp->make_byte_buffer(data_size);
1015  LibRaw_bit_buffer bits;
1016#endif
1017
1018
1019  for (ecol=slice=0; slice <= cr2_slice[0]; slice++) {
1020    scol = ecol;
1021    ecol += cr2_slice[1] * 2 / jh.clrs;
1022    if (!cr2_slice[0] || ecol > raw_width-1) ecol = raw_width & -2;
1023    for (row=0; row < height; row += (jh.clrs >> 1) - 1) {
1024      ip = (short (*)[4]) image + row*width;
1025      for (col=scol; col < ecol; col+=2, jcol+=jh.clrs) {
1026	if ((jcol %= jwide) == 0)
1027#ifdef LIBRAW_LIBRARY_BUILD
1028            rp = (short*) ljpeg_row_new (jrow++, &jh,bits,buf);
1029#else
1030            rp = (short *) ljpeg_row (jrow++, &jh);
1031#endif
1032	if (col >= width) continue;
1033	FORC (jh.clrs-2)
1034	  ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c];
1035	ip[col][1] = rp[jcol+jh.clrs-2] - 16384;
1036	ip[col][2] = rp[jcol+jh.clrs-1] - 16384;
1037      }
1038    }
1039  }
1040  for (cp=model2; *cp && !isdigit(*cp); cp++);
1041  sscanf (cp, "%d.%d.%d", v, v+1, v+2);
1042  ver = (v[0]*1000 + v[1])*1000 + v[2];
1043  hue = (jh.sraw+1) << 2;
1044  if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006))
1045    hue = jh.sraw << 1;
1046  ip = (short (*)[4]) image;
1047  rp = ip[0];
1048  for (row=0; row < height; row++, ip+=width) {
1049    if (row & (jh.sraw >> 1))
1050      for (col=0; col < width; col+=2)
1051	for (c=1; c < 3; c++)
1052	  if (row == height-1)
1053	       ip[col][c] =  ip[col-width][c];
1054	  else ip[col][c] = (ip[col-width][c] + ip[col+width][c] + 1) >> 1;
1055    for (col=1; col < width; col+=2)
1056      for (c=1; c < 3; c++)
1057	if (col == width-1)
1058	     ip[col][c] =  ip[col-1][c];
1059	else ip[col][c] = (ip[col-1][c] + ip[col+1][c] + 1) >> 1;
1060  }
1061  for ( ; rp < ip[0]; rp+=4) {
1062    if (unique_id < 0x80000218) {
1063      pix[0] = rp[0] + rp[2] - 512;
1064      pix[2] = rp[0] + rp[1] - 512;
1065      pix[1] = rp[0] + ((-778*rp[1] - (rp[2] << 11)) >> 12) - 512;
1066    } else {
1067      rp[1] = (rp[1] << 2) + hue;
1068      rp[2] = (rp[2] << 2) + hue;
1069      pix[0] = rp[0] + ((   50*rp[1] + 22929*rp[2]) >> 14);
1070      pix[1] = rp[0] + ((-5640*rp[1] - 11751*rp[2]) >> 14);
1071      pix[2] = rp[0] + ((29040*rp[1] -   101*rp[2]) >> 14);
1072    }
1073    FORC3 
1074        rp[c] = CLIP(pix[c] * sraw_mul[c] >> 10);
1075  }
1076#ifdef LIBRAW_LIBRARY_BUILD
1077  delete buf;
1078#endif
1079  ljpeg_end (&jh);
1080  maximum = 0x3fff;
1081}
1082
1083void CLASS adobe_copy_pixel (int row, int col, ushort **rp)
1084{
1085  unsigned r, c;
1086
1087#ifndef LIBRAW_LIBRARY_BUILD
1088  r = row -= top_margin;
1089  c = col -= left_margin;
1090  if (is_raw == 2 && shot_select) (*rp)++;
1091  if (filters) {
1092    if (fuji_width) {
1093      r = row + fuji_width - 1 - (col >> 1);
1094      c = row + ((col+1) >> 1);
1095    }
1096    if (r < height && c < width)
1097      BAYER(r,c) = **rp < 0x1000 ? curve[**rp] : **rp;
1098    *rp += is_raw;
1099  } else {
1100    if (r < height && c < width)
1101      FORC(tiff_samples)
1102	image[row*width+col][c] = (*rp)[c] < 0x1000 ? curve[(*rp)[c]]:(*rp)[c];
1103    *rp += tiff_samples;
1104  }
1105#else
1106  if (is_raw == 2 && shot_select) (*rp)++;
1107  if (filters) {
1108      if(row < raw_height && col < raw_width)
1109          RBAYER(row,col) = **rp < 0x1000 ? curve[**rp] : **rp;
1110    *rp += is_raw;
1111  } else {
1112      if (row < raw_height && col < raw_width)
1113          FORC(tiff_samples)
1114              color_image[row*raw_width+col][c] = (*rp)[c]<0x1000 ? curve[(*rp)[c]]:(*rp)[c];
1115      *rp += tiff_samples;
1116  }
1117
1118#endif
1119  if (is_raw == 2 && shot_select) (*rp)--;
1120
1121}
1122
1123void CLASS adobe_dng_load_raw_lj()
1124{
1125  unsigned save, trow=0, tcol=0, jwide, jrow, jcol, row, col;
1126  struct jhead jh;
1127  ushort *rp;
1128  while (trow < raw_height) {
1129    save = ftell(ifp);
1130    if (tile_length < INT_MAX)
1131      fseek (ifp, get4(), SEEK_SET);
1132    if (!ljpeg_start (&jh, 0)) break;
1133    jwide = jh.wide;
1134    if (filters) jwide *= jh.clrs;
1135    jwide /= is_raw;
1136#ifdef LIBRAW_LIBRARY_BUILD
1137    if(!data_size)
1138        throw LIBRAW_EXCEPTION_IO_BADFILE;
1139    LibRaw_byte_buffer *buf = ifp->make_byte_buffer(data_size);
1140    LibRaw_bit_buffer bits;
1141#endif
1142    for (row=col=jrow=0; jrow < jh.high; jrow++) {
1143#ifdef LIBRAW_LIBRARY_BUILD
1144        rp = ljpeg_row_new (jrow, &jh,bits,buf);
1145#else
1146        rp = ljpeg_row (jrow, &jh);
1147#endif
1148      for (jcol=0; jcol < jwide; jcol++) {
1149	adobe_copy_pixel (trow+row, tcol+col, &rp);
1150	if (++col >= tile_width || col >= raw_width)
1151	  row += 1 + (col = 0);
1152      }
1153    }
1154    fseek (ifp, save+4, SEEK_SET);
1155    if ((tcol += tile_width) >= raw_width)
1156      trow += tile_length + (tcol = 0);
1157    ljpeg_end (&jh);
1158#ifdef LIBRAW_LIBRARY_BUILD
1159    delete buf;
1160#endif
1161  }
1162}
1163
1164void CLASS adobe_dng_load_raw_nc()
1165{
1166  ushort *pixel, *rp;
1167  int row, col;
1168
1169  pixel = (ushort *) calloc (raw_width * tiff_samples, sizeof *pixel);
1170  merror (pixel, "adobe_dng_load_raw_nc()");
1171
1172
1173#ifdef LIBRAW_LIBRARY_BUILD
1174  int dsz= raw_height*raw_width * tiff_samples * tiff_bps/8;
1175  LibRaw_byte_buffer *buf = NULL;
1176  if (tiff_bps != 16)
1177      {
1178          buf = ifp->make_byte_buffer(dsz);
1179      }
1180  LibRaw_bit_buffer bits;
1181#endif
1182
1183  for (row=0; row < raw_height; row++) {
1184    if (tiff_bps == 16)
1185      read_shorts (pixel, raw_width * tiff_samples);
1186    else {
1187#ifdef LIBRAW_LIBRARY_BUILD
1188        bits.reset();
1189        for (col=0; col < raw_width * tiff_samples; col++)
1190            pixel[col] = bits._getbits(buf,tiff_bps,zero_after_ff);
1191
1192#else
1193      getbits(-1);
1194      for (col=0; col < raw_width * tiff_samples; col++)
1195	pixel[col] = getbits(tiff_bps);
1196#endif
1197    }
1198    for (rp=pixel, col=0; col < raw_width; col++)
1199      adobe_copy_pixel (row, col, &rp);
1200  }
1201  free (pixel);
1202#ifdef LIBRAW_LIBRARY_BUILD
1203    if(buf)
1204        delete buf;
1205#endif
1206}
1207
1208void CLASS pentax_load_raw()
1209{
1210  ushort bit[2][15], huff[4097];
1211  int dep, row, col, diff, c, i;
1212  ushort vpred[2][2] = {{0,0},{0,0}}, hpred[2];
1213
1214  fseek (ifp, meta_offset, SEEK_SET);
1215  dep = (get2() + 12) & 15;
1216  fseek (ifp, 12, SEEK_CUR);
1217  FORC(dep) bit[0][c] = get2();
1218  FORC(dep) bit[1][c] = fgetc(ifp);
1219  FORC(dep)
1220    for (i=bit[0][c]; i <= ((bit[0][c]+(4096 >> bit[1][c])-1) & 4095); )
1221      huff[++i] = bit[1][c] << 8 | c;
1222  huff[0] = 12;
1223  fseek (ifp, data_offset, SEEK_SET);
1224#ifdef LIBRAW_LIBRARY_BUILD
1225  if(!data_size)
1226      throw LIBRAW_EXCEPTION_IO_BADFILE;
1227  LibRaw_byte_buffer *buf = ifp->make_byte_buffer(data_size);
1228  LibRaw_bit_buffer bits;
1229  bits.reset();
1230#else
1231  getbits(-1);
1232#endif
1233  for (row=0; row < raw_height; row++)
1234      {
1235          for (col=0; col < raw_width; col++) {
1236#ifdef LIBRAW_LIBRARY_BUILD
1237              diff = ljpeg_diff_pef(bits,buf,huff);
1238#else
1239              diff = ljpeg_diff (huff);
1240#endif
1241              if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
1242              else	   hpred[col & 1] += diff;
1243
1244              unsigned val = hpred[col & 1];
1245
1246#ifndef LIBRAW_LIBRARY_BUILD
1247              if ((unsigned) (row-top_margin) < height && 
1248                  (unsigned)(col-left_margin) < width)
1249                  BAYER(row-top_margin,col-left_margin) = val;
1250#else
1251              RBAYER(row,col) = val;
1252#endif
1253              if (val >> tiff_bps) derror();
1254          }
1255      }
1256#ifdef LIBRAW_LIBRARY_BUILD
1257  delete buf;
1258#endif
1259}
1260
1261void CLASS nikon_compressed_load_raw()
1262{
1263  static const uchar nikon_tree[][32] = {
1264    { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0,	/* 12-bit lossy */
1265      5,4,3,6,2,7,1,0,8,9,11,10,12 },
1266    { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0,	/* 12-bit lossy after split */
1267      0x39,0x5a,0x38,0x27,0x16,5,4,3,2,1,0,11,12,12 },
1268    { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,  /* 12-bit lossless */
1269      5,4,6,3,7,2,8,1,9,0,10,11,12 },
1270    { 0,1,4,3,1,1,1,1,1,2,0,0,0,0,0,0,	/* 14-bit lossy */
1271      5,6,4,7,8,3,9,2,1,0,10,11,12,13,14 },
1272    { 0,1,5,1,1,1,1,1,1,1,2,0,0,0,0,0,	/* 14-bit lossy after split */
1273      8,0x5c,0x4b,0x3a,0x29,7,6,5,4,3,2,1,0,13,14 },
1274    { 0,1,4,2,2,3,1,2,0,0,0,0,0,0,0,0,	/* 14-bit lossless */
1275      7,6,8,5,9,4,10,3,11,12,2,0,1,13,14 } };
1276  ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize;
1277  int i, min, max, step=0, tree=0, split=0, row, col, len, shl, diff;
1278
1279  fseek (ifp, meta_offset, SEEK_SET);
1280  ver0 = fgetc(ifp);
1281  ver1 = fgetc(ifp);
1282  if (ver0 == 0x49 || ver1 == 0x58)
1283    fseek (ifp, 2110, SEEK_CUR);
1284  if (ver0 == 0x46) tree = 2;
1285  if (tiff_bps == 14) tree += 3;
1286  read_shorts (vpred[0], 4);
1287  max = 1 << tiff_bps & 0x7fff;
1288  if ((csize = get2()) > 1)
1289    step = max / (csize-1);
1290  if (ver0 == 0x44 && ver1 == 0x20 && step > 0) {
1291    for (i=0; i < csize; i++)
1292      curve[i*step] = get2();
1293    for (i=0; i < max; i++)
1294      curve[i] = ( curve[i-i%step]*(step-i%step) +
1295		   curve[i-i%step+step]*(i%step) ) / step;
1296#ifdef LIBRAW_LIBRARY_BUILD
1297    color_flags.curve_state = LIBRAW_COLORSTATE_LOADED;
1298#endif
1299    fseek (ifp, meta_offset+562, SEEK_SET);
1300    split = get2();
1301  } else if (ver0 != 0x46 && csize <= 0x4001)
1302      {
1303    read_shorts (curve, max=csize);
1304#ifdef LIBRAW_LIBRARY_BUILD
1305    color_flags.curve_state = LIBRAW_COLORSTATE_LOADED;
1306#endif
1307      }
1308  while (curve[max-2] == curve[max-1]) max--;
1309  huff = make_decoder (nikon_tree[tree]);
1310  fseek (ifp, data_offset, SEEK_SET);
1311#ifdef LIBRAW_LIBRARY_BUILD
1312  if(!data_size)
1313      throw LIBRAW_EXCEPTION_IO_BADFILE;
1314  LibRaw_byte_buffer *buf = ifp->make_byte_buffer(data_size);
1315  LibRaw_bit_buffer bits;
1316  bits.reset();
1317#else
1318  getbits(-1);
1319#endif
1320  for (min=row=0; row < height; row++) {
1321    if (split && row == split) {
1322      free (huff);
1323      huff = make_decoder (nikon_tree[tree+1]);
1324      max += (min = 16) << 1;
1325    }
1326    for (col=0; col < raw_width; col++) {
1327#ifdef LIBRAW_LIBRARY_BUILD
1328        i = bits._gethuff(buf,*huff,huff+1,zero_after_ff);
1329#else
1330      i = gethuff(huff);
1331#endif
1332      len = i & 15;
1333      shl = i >> 4;
1334#ifdef LIBRAW_LIBRARY_BUILD
1335      diff = ((bits._getbits(buf,len-shl,zero_after_ff) << 1) + 1) << shl >> 1;
1336#else
1337      diff = ((getbits(len-shl) << 1) + 1) << shl >> 1;
1338#endif
1339      if ((diff & (1 << (len-1))) == 0)
1340	diff -= (1 << len) - !shl;
1341      if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
1342      else	   hpred[col & 1] += diff;
1343      if ((ushort)(hpred[col & 1] + min) >= max) derror();
1344#ifndef LIBRAW_LIBRARY_BUILD
1345      if ((unsigned) (col-left_margin) < width)
1346	BAYER(row,col-left_margin) =  curve[LIM((short)hpred[col & 1],0,0x3fff)];
1347#else
1348      ushort xval = hpred[col & 1];
1349      xval = curve[LIM((short)xval,0,0x3fff)];
1350      RBAYER(row,col) = xval;
1351#endif
1352
1353    }
1354  }
1355#ifdef LIBRAW_LIBRARY_BUILD
1356  delete buf;
1357#endif
1358  free (huff);
1359}
1360
1361/*
1362   Figure out if a NEF file is compressed.  These fancy heuristics
1363   are only needed for the D100, thanks to a bug in some cameras
1364   that tags all images as "compressed".
1365 */
1366int CLASS nikon_is_compressed()
1367{
1368  uchar test[256];
1369  int i;
1370
1371  fseek (ifp, data_offset, SEEK_SET);
1372  fread (test, 1, 256, ifp);
1373  for (i=15; i < 256; i+=16)
1374    if (test[i]) return 1;
1375  return 0;
1376}
1377
1378/*
1379   Returns 1 for a Coolpix 995, 0 for anything else.
1380 */
1381int CLASS nikon_e995()
1382{
1383  int i, histo[256];
1384  const uchar often[] = { 0x00, 0x55, 0xaa, 0xff };
1385
1386  memset (histo, 0, sizeof histo);
1387  fseek (ifp, -2000, SEEK_END);
1388  for (i=0; i < 2000; i++)
1389    histo[fgetc(ifp)]++;
1390  for (i=0; i < 4; i++)
1391    if (histo[often[i]] < 200)
1392      return 0;
1393  return 1;
1394}
1395
1396/*
1397   Returns 1 for a Coolpix 2100, 0 for anything else.
1398 */
1399int CLASS nikon_e2100()
1400{
1401  uchar t[12];
1402  int i;
1403
1404  fseek (ifp, 0, SEEK_SET);
1405  for (i=0; i < 1024; i++) {
1406    fread (t, 1, 12, ifp);
1407    if (((t[2] & t[4] & t[7] & t[9]) >> 4
1408	& t[1] & t[6] & t[8] & t[11] & 3) != 3)
1409      return 0;
1410  }
1411  return 1;
1412}
1413
1414void CLASS nikon_3700()
1415{
1416  int bits, i;
1417  uchar dp[24];
1418  static const struct {
1419    int bits;
1420    char t_make[12], t_model[15];
1421  } table[] = {
1422    { 0x00, "PENTAX",  "Optio 33WR" },
1423    { 0x03, "NIKON",   "E3200" },
1424    { 0x32, "NIKON",   "E3700" },
1425    { 0x33, "OLYMPUS", "C740UZ" } };
1426
1427  fseek (ifp, 3072, SEEK_SET);
1428  fread (dp, 1, 24, ifp);
1429  bits = (dp[8] & 3) << 4 | (dp[20] & 3);
1430  for (i=0; i < sizeof table / sizeof *table; i++)
1431    if (bits == table[i].bits) {
1432      strcpy (make,  table[i].t_make );
1433      strcpy (model, table[i].t_model);
1434    }
1435}
1436
1437/*
1438   Separates a Minolta DiMAGE Z2 from a Nikon E4300.
1439 */
1440int CLASS minolta_z2()
1441{
1442  int i, nz;
1443  char tail[424];
1444
1445  fseek (ifp, -sizeof tail, SEEK_END);
1446  fread (tail, 1, sizeof tail, ifp);
1447  for (nz=i=0; i < sizeof tail; i++)
1448    if (tail[i]) nz++;
1449  return nz > 20;
1450}
1451
1452/*
1453   The Fuji Super CCD is just a Bayer grid rotated 45 degrees.
1454 */
1455void CLASS fuji_load_raw()
1456{
1457#ifndef LIBRAW_LIBRARY_BUILD
1458  ushort *pixel;
1459  int wide, row, col, r, c;
1460
1461  fseek (ifp, (top_margin*raw_width + left_margin) * 2, SEEK_CUR);
1462  wide = fuji_width << !fuji_layout;
1463  pixel = (ushort *) calloc (wide, sizeof *pixel);
1464  merror (pixel, "fuji_load_raw()");
1465  for (row=0; row < raw_height; row++) {
1466    read_shorts (pixel, wide);
1467    fseek (ifp, 2*(raw_width - wide), SEEK_CUR);
1468    for (col=0; col < wide; col++) {
1469      if (fuji_layout) {
1470	r = fuji_width - 1 - col + (row >> 1);
1471	c = col + ((row+1) >> 1);
1472      } else {
1473	r = fuji_width - 1 + row - (col >> 1);
1474	c = row + ((col+1) >> 1);
1475      }
1476      BAYER(r,c) = pixel[col];
1477    }
1478  }
1479  free (pixel);
1480#else
1481  read_shorts(raw_image,raw_width*raw_height);
1482#endif
1483}
1484void CLASS ppm_thumb()
1485{
1486  char *thumb;
1487  thumb_length = thumb_width*thumb_height*3;
1488  thumb = (char *) malloc (thumb_length);
1489  merror (thumb, "ppm_thumb()");
1490  fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
1491  fread  (thumb, 1, thumb_length, ifp);
1492  fwrite (thumb, 1, thumb_length, ofp);
1493  free (thumb);
1494}
1495
1496void CLASS layer_thumb()
1497{
1498  int i, c;
1499  char *thumb, map[][4] = { "012","102" };
1500
1501  colors = thumb_misc >> 5 & 7;
1502  thumb_length = thumb_width*thumb_height;
1503  thumb = (char *) calloc (colors, thumb_length);
1504  merror (thumb, "layer_thumb()");
1505  fprintf (ofp, "P%d\n%d %d\n255\n",
1506	5 + (colors >> 1), thumb_width, thumb_height);
1507  fread (thumb, thumb_length, colors, ifp);
1508  for (i=0; i < thumb_length; i++)
1509    FORCC putc (thumb[i+thumb_length*(map[thumb_misc >> 8][c]-'0')], ofp);
1510  free (thumb);
1511}
1512
1513void CLASS rollei_thumb()
1514{
1515  unsigned i;
1516  ushort *thumb;
1517
1518  thumb_length = thumb_width * thumb_height;
1519  thumb = (ushort *) calloc (thumb_length, 2);
1520  merror (thumb, "rollei_thumb()");
1521  fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
1522  read_shorts (thumb, thumb_length);
1523  for (i=0; i < thumb_length; i++) {
1524    putc (thumb[i] << 3, ofp);
1525    putc (thumb[i] >> 5  << 2, ofp);
1526    putc (thumb[i] >> 11 << 3, ofp);
1527  }
1528  free (thumb);
1529}
1530
1531void CLASS rollei_load_raw()
1532{
1533  uchar pixel[10];
1534  unsigned iten=0, isix, i, buffer=0, row, col, todo[16];
1535
1536  isix = raw_width * raw_height * 5 / 8;
1537  while (fread (pixel, 1, 10, ifp) == 10) {
1538    for (i=0; i < 10; i+=2) {
1539      todo[i]   = iten++;
1540      todo[i+1] = pixel[i] << 8 | pixel[i+1];
1541      buffer    = pixel[i] >> 2 | buffer << 6;
1542    }
1543    for (   ; i < 16; i+=2) {
1544      todo[i]   = isix++;
1545      todo[i+1] = buffer >> (14-i)*5;
1546    }
1547    for (i=0; i < 16; i+=2) {
1548#ifndef LIBRAW_LIBRARY_BUILD
1549      row = todo[i] / raw_width - top_margin;
1550      col = todo[i] % raw_width - left_margin;
1551      if (row < height && col < width)
1552              BAYER(row,col) = (todo[i+1] & 0x3ff);
1553#else
1554      RBAYER(todo[i] / raw_width,todo[i] % raw_width) = (todo[i+1] & 0x3ff);
1555#endif
1556    }
1557  }
1558  maximum = 0x3ff;
1559}
1560
1561int CLASS bayer (unsigned row, unsigned col)
1562{
1563  return (row < height && col < width) ? BAYER(row,col) : 0;
1564}
1565
1566void CLASS phase_one_flat_field (int is_float, int nc)
1567{
1568  ushort head[8];
1569  unsigned wide, y, x, c, rend, cend, row, col;
1570  float *mrow, num, mult[4];
1571
1572  read_shorts (head, 8);
1573  wide = head[2] / head[4];
1574  mrow = (float *) calloc (nc*wide, sizeof *mrow);
1575  merror (mrow, "phase_one_flat_field()");
1576  for (y=0; y < head[3] / head[5]; y++) {
1577    for (x=0; x < wide; x++)
1578      for (c=0; c < nc; c+=2) {
1579	num = is_float ? getreal(11) : get2()/32768.0;
1580	if (y==0) mrow[c*wide+x] = num;
1581	else mrow[(c+1)*wide+x] = (num - mrow[c*wide+x]) / head[5];
1582      }
1583    if (y==0) continue;
1584    rend = head[1]-top_margin + y*head[5];
1585    for (row = rend-head[5]; row < height && row < rend; row++) {
1586      for (x=1; x < wide; x++) {
1587	for (c=0; c < nc; c+=2) {
1588	  mult[c] = mrow[c*wide+x-1];
1589	  mult[c+1] = (mrow[c*wide+x] - mult[c]) / head[4];
1590	}
1591	cend = head[0]-left_margin + x*head[4];
1592	for (col = cend-head[4]; col < width && col < cend; col++) {
1593	  c = nc > 2 ? FC(row,col) : 0;
1594	  if (!(c & 1)) {
1595	    c = BAYER(row,col) * mult[c];
1596	    BAYER(row,col) = LIM(c,0,65535);
1597	  }
1598	  for (c=0; c < nc; c+=2)
1599	    mult[c] += mult[c+1];
1600	}
1601      }
1602      for (x=0; x < wide; x++)
1603	for (c=0; c < nc; c+=2)
1604	  mrow[c*wide+x] += mrow[(c+1)*wide+x];
1605    }
1606  }
1607  free (mrow);
1608}
1609
1610void CLASS phase_one_correct()
1611{
1612  unsigned entries, tag, data, save, col, row, type;
1613  int len, i, j, k, cip, val[4], dev[4], sum, max;
1614  int head[9], diff, mindiff=INT_MAX, off_412=0;
1615  static const signed char dir[12][2] =
1616    { {-1,-1}, {-1,1}, {1,-1}, {1,1}, {-2,0}, {0,-2}, {0,2}, {2,0},
1617      {-2,-2}, {-2,2}, {2,-2}, {2,2} };
1618  float poly[8], num, cfrac, frac, mult[2], *yval[2];
1619  ushort *xval[2];
1620
1621  if (half_size || !meta_length) return;
1622#ifdef DCRAW_VERBOSE
1623  if (verbose) fprintf (stderr,_("Phase One correction...\n"));
1624#endif
1625  fseek (ifp, meta_offset, SEEK_SET);
1626  order = get2();
1627  fseek (ifp, 6, SEEK_CUR);
1628  fseek (ifp, meta_offset+get4(), SEEK_SET);
1629  entries = get4();  get4();
1630  while (entries--) {
1631    tag  = get4();
1632    len  = get4();
1633    data = get4();
1634    save = ftell(ifp);
1635    fseek (ifp, meta_offset+data, SEEK_SET);
1636    if (tag == 0x419) {				/* Polynomial curve */
1637      for (get4(), i=0; i < 8; i++)
1638	poly[i] = getreal(11);
1639      poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1;
1640      for (i=0; i < 0x10000; i++) {
1641	num = (poly[5]*i + poly[3])*i + poly[1];
1642	curve[i] = LIM(num,0,65535);
1643      } goto apply;				/* apply to right half */
1644    } else if (tag == 0x41a) {			/* Polynomial curve */
1645      for (i=0; i < 4; i++)
1646	poly[i] = getreal(11);
1647      for (i=0; i < 0x10000; i++) {
1648	for (num=0, j=4; j--; )
1649	  num = num * i + poly[j];
1650	curve[i] = LIM(num+i,0,65535);
1651      } apply:					/* apply to whole image */
1652      for (row=0; row < height; row++)
1653	for (col = (tag & 1)*ph1.split_col; col < width; col++)
1654	  BAYER(row,col) = curve[BAYER(row,col)];
1655    } else if (tag == 0x400) {			/* Sensor defects */
1656      while ((len -= 8) >= 0) {
1657	col  = get2() - left_margin;
1658	row  = get2() - top_margin;
1659	type = get2(); get2();
1660	if (col >= width) continue;
1661	if (type == 131)			/* Bad column */
1662	  for (row=0; row < height; row++)
1663	    if (FC(row,col) == 1) {
1664	      for (sum=i=0; i < 4; i++)
1665		sum += val[i] = bayer (row+dir[i][0], col+dir[i][1]);
1666	      for (max=i=0; i < 4; i++) {
1667		dev[i] = abs((val[i] << 2) - sum);
1668		if (dev[max] < dev[i]) max = i;
1669	      }
1670	      BAYER(row,col) = (sum - val[max])/3.0 + 0.5;
1671	    } else {
1672	      for (sum=0, i=8; i < 12; i++)
1673		sum += bayer (row+dir[i][0], col+dir[i][1]);
1674	      BAYER(row,col) = 0.5 + sum * 0.0732233 +
1675		(bayer(row,col-2) + bayer(row,col+2)) * 0.3535534;
1676	    }
1677	else if (type == 129) {			/* Bad pixel */
1678	  if (row >= height) continue;
1679	  j = (FC(row,col) != 1) * 4;
1680	  for (sum=0, i=j; i < j+8; i++)
1681	    sum += bayer (row+dir[i][0], col+dir[i][1]);
1682	  BAYER(row,col) = (sum + 4) >> 3;
1683	}
1684      }
1685    } else if (tag == 0x401) {			/* All-color flat fields */
1686      phase_one_flat_field (1, 2);
1687    } else if (tag == 0x416 || tag == 0x410) {
1688      phase_one_flat_field (0, 2);
1689    } else if (tag == 0x40b) {			/* Red+blue flat field */
1690      phase_one_flat_field (0, 4);
1691    } else if (tag == 0x412) {
1692      fseek (ifp, 36, SEEK_CUR);
1693      diff = abs (get2() - ph1.tag_21a);
1694      if (mindiff > diff) {
1695	mindiff = diff;
1696	off_412 = ftell(ifp) - 38;
1697      }
1698    }
1699    fseek (ifp, save, SEEK_SET);
1700  }
1701  if (off_412) {
1702    fseek (ifp, off_412, SEEK_SET);
1703    for (i=0; i < 9; i++) head[i] = get4() & 0x7fff;
1704    yval[0] = (float *) calloc (head[1]*head[3] + head[2]*head[4], 6);
1705    merror (yval[0], "phase_one_correct()");
1706    yval[1] = (float  *) (yval[0] + head[1]*head[3]);
1707    xval[0] = (ushort *) (yval[1] + head[2]*head[4]);
1708    xval[1] = (ushort *) (xval[0] + head[1]*head[3]);
1709    get2();
1710    for (i=0; i < 2; i++)
1711      for (j=0; j < head[i+1]*head[i+3]; j++)
1712	yval[i][j] = getreal(11);
1713    for (i=0; i < 2; i++)
1714      for (j=0; j < head[i+1]*head[i+3]; j++)
1715	xval[i][j] = get2();
1716    for (row=0; row < height; row++)
1717      for (col=0; col < width; col++) {
1718	cfrac = (float) col * head[3] / raw_width;
1719	cfrac -= cip = cfrac;
1720	num = BAYER(row,col) * 0.5;
1721	for (i=cip; i < cip+2; i++) {
1722	  for (k=j=0; j < head[1]; j++)
1723	    if (num < xval[0][k = head[1]*i+j]) break;
1724	  frac = (j == 0 || j == head[1]) ? 0 :
1725		(xval[0][k] - num) / (xval[0][k] - xval[0][k-1]);
1726	  mult[i-cip] = yval[0][k-1] * frac + yval

Large files files are truncated, but you can click here to view the full file