PageRenderTime 1093ms CodeModel.GetById 99ms app.highlight 915ms RepoModel.GetById 1ms app.codeStats 3ms

/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
   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[0][k] * (1-frac);
1727	}
1728	i = ((mult[0] * (1-cfrac) + mult[1] * cfrac)
1729		* (row + top_margin) + num) * 2;
1730	BAYER(row,col) = LIM(i,0,65535);
1731      }
1732    free (yval[0]);
1733  }
1734}
1735
1736void CLASS phase_one_load_raw()
1737{
1738  int row, col, a, b;
1739  ushort *pixel, akey, bkey, mask;
1740
1741  fseek (ifp, ph1.key_off, SEEK_SET);
1742  akey = get2();
1743  bkey = get2();
1744  mask = ph1.format == 1 ? 0x5555:0x1354;
1745#ifndef LIBRAW_LIBRARY_BUILD
1746  fseek (ifp, data_offset + top_margin*raw_width*2, SEEK_SET);
1747  pixel = (ushort *) calloc (raw_width, sizeof *pixel);
1748  merror (pixel, "phase_one_load_raw()");
1749  for (row=0; row < height; row++) {
1750    read_shorts (pixel, raw_width);
1751    if (ph1.format)
1752      for (col=0; col < raw_width; col+=2) {
1753	a = pixel[col+0] ^ akey;
1754	b = pixel[col+1] ^ bkey;
1755	pixel[col+0] = (a & mask) | (b & ~mask);
1756	pixel[col+1] = (b & mask) | (a & ~mask);
1757      }
1758    for (col=0; col < width; col++)
1759      BAYER(row,col) = pixel[col+left_margin];
1760  }
1761  free (pixel);
1762  phase_one_correct();
1763#else
1764  fseek (ifp, data_offset, SEEK_SET);
1765  pixel = (ushort *) calloc (raw_width, sizeof *pixel);
1766  merror (pixel, "phase_one_load_raw()");
1767  for (row=0; row < raw_height; row++) {
1768    read_shorts (pixel, raw_width);
1769    if (ph1.format)
1770        for (col=0; col < raw_width; col+=2) {
1771            a = pixel[col+0] ^ akey;
1772            b = pixel[col+1] ^ bkey;
1773            pixel[col+0] = (a & mask) | (b & ~mask);
1774            pixel[col+1] = (b & mask) | (a & ~mask);
1775        }
1776    memmove(&raw_image[row*raw_width],pixel,raw_width*sizeof(pixel[0]));
1777  }
1778  free (pixel);
1779  // use correct on postprocessing!
1780  imgdata.rawdata.use_ph1_correct=1;
1781#endif
1782}
1783
1784unsigned CLASS ph1_bithuff (int nbits, ushort *huff)
1785{
1786#ifndef LIBRAW_NOTHREADS
1787#define bitbuf tls->ph1_bits.bitbuf
1788#define vbits  tls->ph1_bits.vbits    
1789#else
1790  static UINT64 bitbuf=0;
1791  static int vbits=0;
1792#endif
1793  unsigned c;
1794
1795  if (nbits == -1)
1796    return bitbuf = vbits = 0;
1797  if (nbits == 0) return 0;
1798  if (vbits < nbits) {
1799    bitbuf = bitbuf << 32 | get4();
1800    vbits += 32;
1801  }
1802  c = bitbuf << (64-vbits) >> (64-nbits);
1803  if (huff) {
1804    vbits -= huff[c] >> 8;
1805    return (uchar) huff[c];
1806  }
1807  vbits -= nbits;
1808  return c;
1809#ifndef LIBRAW_NOTHREADS
1810#undef bitbuf
1811#undef vbits
1812#endif
1813}
1814#define ph1_bits(n) ph1_bithuff(n,0)
1815#define ph1_huff(h) ph1_bithuff(*h,h+1)
1816
1817void CLASS phase_one_load_raw_c()
1818{
1819  static const int length[] = { 8,7,6,9,11,10,5,12,14,13 };
1820  int *offset, len[2], pred[2], row, col, i, j;
1821  ushort *pixel;
1822  short (*t_black)[2];
1823
1824  pixel = (ushort *) calloc (raw_width + raw_height*4, 2);
1825  merror (pixel, "phase_one_load_raw_c()");
1826  offset = (int *) (pixel + raw_width);
1827  fseek (ifp, strip_offset, SEEK_SET);
1828  for (row=0; row < raw_height; row++)
1829    offset[row] = get4();
1830  t_black = (short (*)[2]) offset + raw_height;
1831  fseek (ifp, ph1.black_off, SEEK_SET);
1832  if (ph1.black_off)
1833      {
1834          read_shorts ((ushort *) t_black[0], raw_height*2);
1835#ifdef LIBRAW_LIBRARY_BUILD
1836          imgdata.rawdata.ph1_black = (short (*)[2])calloc(raw_height*2,sizeof(short));
1837          merror (imgdata.rawdata.ph1_black, "phase_one_load_raw_c()");
1838          memmove(imgdata.rawdata.ph1_black,(short *) t_black[0],raw_height*2*sizeof(short));
1839#endif
1840      }
1841  for (i=0; i < 256; i++)
1842    curve[i] = i*i / 3.969 + 0.5;
1843#ifdef LIBRAW_LIBRARY_BUILD
1844  color_flags.curve_state = LIBRAW_COLORSTATE_CALCULATED;
1845#endif
1846  for (row=0; row < raw_height; row++) {
1847    fseek (ifp, data_offset + offset[row], SEEK_SET);
1848    ph1_bits(-1);
1849    pred[0] = pred[1] = 0;
1850    for (col=0; col < raw_width; col++) {
1851      if (col >= (raw_width & -8))
1852	len[0] = len[1] = 14;
1853      else if ((col & 7) == 0)
1854	for (i=0; i < 2; i++) {
1855	  for (j=0; j < 5 && !ph1_bits(1); j++);
1856	  if (j--) len[i] = length[j*2 + ph1_bits(1)];
1857	}
1858      if ((i = len[col & 1]) == 14)
1859	pixel[col] = pred[col & 1] = ph1_bits(16);
1860      else
1861	pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1));
1862      if (pred[col & 1] >> 16) derror();
1863      if (ph1.format == 5 && pixel[col] < 256)
1864	pixel[col] = curve[pixel[col]];
1865    }
1866#ifndef LIBRAW_LIBRARY_BUILD
1867    if ((unsigned) (row-top_margin) < height)
1868      for (col=0; col < width; col++) {
1869	i = (pixel[col+left_margin] << 2)
1870		- ph1.t_black + t_black[row][col >= ph1.split_col];
1871	if (i > 0) BAYER(row-top_margin,col) = i;
1872      }
1873#else
1874    for (col=0; col < raw_width; col++) 
1875        {
1876            i = (pixel[col] << 2);
1877            RBAYER(row,col) = i;
1878        }
1879#endif
1880  }
1881  free (pixel);
1882#ifndef LIBRAW_LIBRARY_BUILD
1883  phase_one_correct();
1884  maximum = 0xfffc - ph1.t_black;
1885#else
1886  maximum = 0xfffc;
1887  black = ph1.t_black;
1888#endif
1889}
1890
1891void CLASS hasselblad_load_raw()
1892{
1893  struct jhead jh;
1894  int row, col, pred[2], len[2], diff, c;
1895
1896  if (!ljpeg_start (&jh, 0)) return;
1897  order = 0x4949;
1898  ph1_bits(-1);
1899#ifndef LIBRAW_LIBRARY_BUILD
1900  for (row=-top_margin; row < height; row++) {
1901    pred[0] = pred[1] = 0x8000 + load_flags;
1902    for (col=-left_margin; col < raw_width-left_margin; col+=2) {
1903      FORC(2) len[c] = ph1_huff(jh.huff[0]);
1904      FORC(2) {
1905	diff = ph1_bits(len[c]);
1906	if ((diff & (1 << (len[c]-1))) == 0)
1907	  diff -= (1 << len[c]) - 1;
1908	if (diff == 65535) diff = -32768;
1909	pred[c] += diff;
1910	if (row >= 0 && (unsigned)(col+c) < width)
1911	  BAYER(row,col+c) = pred[c];
1912      }
1913    }
1914  }
1915#else
1916  for (row=0; row < raw_height; row++) {
1917    pred[0] = pred[1] = 0x8000 + load_flags;
1918    for (col=0; col < raw_width; col+=2) {
1919      FORC(2) len[c] = ph1_huff(jh.huff[0]);
1920      FORC(2) {
1921	diff = ph1_bits(len[c]);
1922	if ((diff & (1 << (len[c]-1))) == 0)
1923	  diff -= (1 << len[c]) - 1;
1924	if (diff == 65535) diff = -32768;
1925	pred[c] += diff;
1926        RBAYER(row,col+c) = pred[c];
1927      }
1928    }
1929  }
1930
1931#endif
1932  ljpeg_end (&jh);
1933  maximum = 0xffff;
1934}
1935
1936void CLASS leaf_hdr_load_raw()
1937{
1938  ushort *pixel;
1939  unsigned tile=0, r, c, row, col;
1940
1941  pixel = (ushort *) calloc (raw_width, sizeof *pixel);
1942  merror (pixel, "leaf_hdr_load_raw()");
1943  FORC(tiff_samples)
1944    for (r=0; r < raw_height; r++) {
1945      if (r % tile_length == 0) {
1946	fseek (ifp, data_offset + 4*tile++, SEEK_SET);
1947	fseek (ifp, get4() + 2*left_margin, SEEK_SET);
1948      }
1949      if (filters && c != shot_select) continue;
1950      read_shorts (pixel, raw_width);
1951#ifndef LIBRAW_LIBRARY_BUILD
1952      if ((row = r - top_margin) >= height) continue;
1953      for (col=0; col < width; col++)
1954	if (filters)  BAYER(row,col) = pixel[col];
1955	else image[row*width+col][c] = pixel[col];
1956#else
1957      if(filters)
1958          memmove(&raw_image[r*raw_width],pixel,raw_width*sizeof(pixel[0]));
1959      else
1960          for (col=0; col < raw_width; col++)
1961              color_image[r*raw_width+col][c] = pixel[col];
1962#endif
1963    }
1964  free (pixel);
1965  if (!filters) {
1966    maximum = 0xffff;
1967    raw_color = 1;
1968  }
1969}
1970
1971void CLASS sinar_4shot_load_raw()
1972{
1973  ushort *pixel;
1974  unsigned shot, row, col, r, c;
1975
1976  if ((shot = shot_select) || half_size) {
1977    if (shot) shot--;
1978    if (shot > 3) shot = 3;
1979    fseek (ifp, data_offset + shot*4, SEEK_SET);
1980    fseek (ifp, get4(), SEEK_SET);
1981    unpacked_load_raw();
1982    return;
1983  }
1984  free (image);
1985  image = (ushort (*)[4])
1986	calloc ((iheight=height)*(iwidth=width), sizeof *image);
1987  merror (image, "sinar_4shot_load_raw()");
1988  pixel = (ushort *) calloc (raw_width, sizeof *pixel);
1989  merror (pixel, "sinar_4shot_load_raw()");
1990  for (shot=0; shot < 4; shot++) {
1991    fseek (ifp, data_offset + shot*4, SEEK_SET);
1992    fseek (ifp, get4(), SEEK_SET);
1993#ifndef LIBRAW_LIBRARY_BUILD
1994    for (row=0; row < raw_height; row++) {
1995      read_shorts (pixel, raw_width);
1996      if ((r = row-top_margin - (shot >> 1 & 1)) >= height) continue;
1997      for (col=0; col < raw_width; col++) {
1998	if ((c = col-left_margin - (shot & 1)) >= width) continue;
1999	 image[r*width+c][FC(row,col)] = pixel[col];
2000      }
2001    }
2002#else
2003    for (row=0; row < raw_height; row++) {
2004      read_shorts (pixel, raw_width);
2005      if ((r = row - (shot >> 1 & 1)) >= raw_height) continue;
2006      for (col=0; col < raw_width; col++) {
2007	if ((c = col- (shot & 1)) >= raw_width) continue;
2008         color_image[r*width+c][FC(row,col)] = pixel[col];
2009      }
2010    }
2011#endif
2012  }
2013  free (pixel);
2014  shrink = filters = 0;
2015}
2016
2017void CLASS imacon_full_load_raw()
2018{
2019  int row, col;
2020
2021#ifndef LIBRAW_LIBRARY_BUILD
2022  for (row=0; row < height; row++)
2023    for (col=0; col < width; col++)
2024        {
2025            read_shorts (image[row*width+col], 3);
2026        }
2027#else
2028  for (row=0; row < height; row++)
2029    for (col=0; col < width; col++)
2030        {
2031            read_shorts (color_image[(row+top_margin)*raw_width+col+left_margin], 3);
2032        }
2033#endif
2034}
2035
2036void CLASS packed_load_raw()
2037{
2038  int vbits=0, bwide, pwide, rbits, bite, half, irow, row, col, val, i;
2039  int zero=0;
2040  UINT64 bitbuf=0;
2041
2042  if (raw_width * 8 >= width * tiff_bps)	/* Is raw_width in bytes? */
2043       pwide = (bwide = raw_width) * 8 / tiff_bps;
2044  else bwide = (pwide = raw_width) * tiff_bps / 8;
2045  rbits = bwide * 8 - pwide * tiff_bps;
2046  if (load_flags & 1) bwide = bwide * 16 / 15;
2047  fseek (ifp, top_margin*bwide, SEEK_CUR);
2048  bite = 8 + (load_flags & 24);
2049  half = (height+1) >> 1;
2050  for (irow=0; irow < height; irow++) 
2051  {
2052    row = irow;
2053    if (load_flags & 2 &&
2054	(row = irow % half * 2 + irow / half) == 1 &&
2055	load_flags & 4) {
2056      if (vbits=0, tiff_compress)
2057	fseek (ifp, data_offset - (-half*bwide & -2048), SEEK_SET);
2058      else {
2059	fseek (ifp, 0, SEEK_END);
2060	fseek (ifp, ftell(ifp) >> 3 << 2, SEEK_SET);
2061      }
2062    }
2063    for (col=0; col < pwide; col++) {
2064      for (vbits -= tiff_bps; vbits < 0; vbits += bite) {
2065	bitbuf <<= bite;
2066	for (i=0; i < bite; i+=8)
2067	  bitbuf |= (unsigned) (fgetc(ifp) << i);
2068      }
2069      val = bitbuf << (64-tiff_bps-vbits) >> (64-tiff_bps);
2070      i = (col ^ (load_flags >> 6)) - left_margin;
2071#ifdef LIBRAW_LIBRARY_BUILD
2072      RBAYER(row+top_margin,i+left_margin) = val;
2073      if (((unsigned)i>=width) && (load_flags & 32) ) {
2074	black += val;
2075	zero += !val;
2076      }
2077#else
2078      if ((unsigned) i < width)
2079	BAYER(row,i+left_margin) = val;
2080      else if (load_flags & 32) {
2081	black += val;
2082	zero += !val;
2083      }
2084#endif
2085      if (load_flags & 1 && (col % 10) == 9 &&
2086	fgetc(ifp) && col < width+left_margin) derror();
2087    }
2088    vbits -= rbits;
2089  }
2090  if (load_flags & 32 && pwide > width)
2091    black /= (pwide - width) * height;
2092  if (zero*4 > (pwide - width) * height)
2093    black = 0;
2094}
2095
2096void CLASS unpacked_load_raw()
2097{
2098  ushort *pixel;
2099  int row, col, bits=0;
2100
2101  while (1 << ++bits < maximum);
2102#ifndef LIBRAW_LIBRARY_BUILD
2103  fseek (ifp, (top_margin*raw_width + left_margin) * 2, SEEK_CUR);
2104  pixel = (ushort *) calloc (width, sizeof *pixel);
2105  merror (pixel, "unpacked_load_raw()");
2106  for (row=0; row < height; row++) {
2107    read_shorts (pixel, width);
2108    fseek (ifp, 2*(raw_width - width), SEEK_CUR);
2109    for (col=0; col < width; col++)
2110      if ((BAYER2(row,col) = pixel[col] >> load_flags) >> bits) derror();
2111  }
2112  free (pixel);
2113#else
2114  // fseek (ifp, (top_margin*raw_width + left_margin) * 2, SEEK_CUR);
2115  pixel = (ushort *) calloc (raw_width, sizeof *pixel);
2116  merror (pixel, "unpacked_load_raw()");
2117  for (row=0; row < raw_height; row++) {
2118    read_shorts (pixel, raw_width);
2119    for (col=0; col < raw_width; col++)
2120        {
2121            RBAYER(row,col) = pixel[col]>>load_flags;
2122            if( ((unsigned)(row-top_margin) < height)
2123                && ((unsigned)(col-left_margin)<width ))
2124                if(RBAYER(row,col)>>bits)
2125                    derror();
2126        }
2127  }
2128  free (pixel);
2129#endif
2130}
2131
2132void CLASS nokia_load_raw()
2133{
2134  uchar  *data,  *dp;
2135  ushort *pixel, *pix;
2136  int rev, dwide, row, c;
2137
2138  rev = 3 * (order == 0x4949);
2139  dwide = raw_width * 5 / 4;
2140  data = (uchar *) malloc (dwide + raw_width*2);
2141  merror (data, "nokia_load_raw()");
2142  pixel = (ushort *) (data + dwide);
2143  for (row=0; row < raw_height; row++) {
2144    if (fread (data+dwide, 1, dwide, ifp) < dwide) derror();
2145    FORC(dwide) data[c] = data[dwide+(c ^ rev)];
2146    for (dp=data, pix=pixel; pix < pixel+raw_width; dp+=5, pix+=4)
2147      FORC4 pix[c] = (dp[c] << 2) | (dp[4] >> (c << 1) & 3);
2148    if (row < top_margin)
2149      FORC(width) black += pixel[c];
2150#ifndef LIBRAW_LIBRARY_BUILD
2151    else
2152      FORC(width) BAYER(row-top_margin,c) = pixel[c];
2153#else
2154    memmove(&raw_image[row*raw_width],pixel,width*sizeof(pixel[0]));
2155#endif
2156  }
2157  free (data);
2158  if (top_margin) black /= top_margin * width;
2159  maximum = 0x3ff;
2160}
2161
2162unsigned CLASS pana_bits (int nbits)
2163{
2164#ifndef LIBRAW_NOTHREADS
2165#define buf tls->pana_bits.buf
2166#define vbits tls->pana_bits.vbits   
2167#else
2168  static uchar buf[0x4000];
2169  static int vbits;
2170#endif
2171  int byte;
2172
2173  if (!nbits) return vbits=0;
2174  if (!vbits) {
2175    fread (buf+load_flags, 1, 0x4000-load_flags, ifp);
2176    fread (buf, 1, load_flags, ifp);
2177  }
2178  vbits = (vbits - nbits) & 0x1ffff;
2179  byte = vbits >> 3 ^ 0x3ff0;
2180  return (buf[byte] | buf[byte+1] << 8) >> (vbits & 7) & ~(-1 << nbits);
2181#ifndef LIBRAW_NOTHREADS
2182#undef buf
2183#undef vbits
2184#endif
2185}
2186
2187void CLASS panasonic_load_raw()
2188{
2189  int row, col, i, j, sh=0, pred[2], nonz[2];
2190
2191  pana_bits(0);
2192  for (row=0; row < height; row++)
2193    for (col=0; col < raw_width; col++) {
2194      if ((i = col % 14) == 0)
2195	pred[0] = pred[1] = nonz[0] = nonz[1] = 0;
2196      if (i % 3 == 2) sh = 4 >> (3 - pana_bits(2));
2197      if (nonz[i & 1]) {
2198	if ((j = pana_bits(8))) {
2199	  if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4)
2200	       pred[i & 1] &= ~(-1 << sh);
2201	  pred[i & 1] += j << sh;
2202	}
2203      } else if ((nonz[i & 1] = pana_bits(8)) || i > 11)
2204	pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4);
2205#ifndef LIBRAW_LIBRARY_BUILD
2206      if (col < width)
2207              if ((BAYER(row,col) = pred[col & 1]) > 4098) derror();
2208#else
2209      RBAYER(row,col) = pred[col & 1];
2210      if (col < width)
2211          if (RBAYER(row,col) > 4098) derror();
2212#endif
2213    }
2214}
2215
2216
2217void CLASS olympus_load_raw()
2218{
2219  ushort huff[4096];
2220  int row, col, nbits, sign, low, high, i, c, w, n, nw;
2221  int acarry[2][3], *carry, pred, diff;
2222
2223  huff[n=0] = 0xc0c;
2224  for (i=12; i--; )
2225    FORC(2048 >> i) huff[++n] = (i+1) << 8 | i;
2226  fseek (ifp, 7, SEEK_CUR);
2227#ifdef LIBRAW_LIBRARY_BUILD
2228  if(!data_size)
2229      throw LIBRAW_EXCEPTION_IO_BADFILE;
2230  LibRaw_byte_buffer *buf = ifp->make_byte_buffer(data_size);
2231  LibRaw_bit_buffer bits;
2232  bits.reset();
2233#else
2234  getbits(-1);
2235#endif
2236  for (row=0; row < height; row++) {
2237    memset (acarry, 0, sizeof acarry);
2238    for (col=0; col < raw_width; col++) {
2239      carry = acarry[col & 1];
2240      i = 2 * (carry[2] < 3);
2241      for (nbits=2+i; (ushort) carry[0] >> (nbits+i); nbits++);
2242#ifdef LIBRAW_LIBRARY_BUILD
2243      low = (sign = bits._getbits(buf,3,zero_after_ff)) & 3;
2244      sign = sign << 29 >> 31;
2245      if ((high = bits._gethuff(buf,12,huff,zero_after_ff)) == 12)
2246          high = bits._getbits(buf,16-nbits,zero_after_ff) >> 1;
2247      carry[0] = (high << nbits) | bits._getbits(buf,nbits,zero_after_ff);
2248#else
2249      low = (sign = getbits(3)) & 3;
2250      sign = sign << 29 >> 31;
2251      if ((high = getbithuff(12,huff)) == 12)
2252	high = getbits(16-nbits) >> 1;
2253      carry[0] = (high << nbits) | getbits(nbits);
2254#endif
2255      diff = (carry[0] ^ sign) + carry[1];
2256      carry[1] = (diff*3 + carry[1]) >> 5;
2257      carry[2] = carry[0] > 16 ? 0 : carry[2]+1;
2258      if (col >= width) continue;
2259      if (row < 2 && col < 2) pred = 0;
2260      else if (row < 2) pred = RBAYER(row,col-2);
2261      else if (col < 2) pred = RBAYER(row-2,col);
2262      else {
2263	w  = RBAYER(row,col-2);
2264	n  = RBAYER(row-2,col);
2265	nw = RBAYER(row-2,col-2);
2266	if ((w < nw && nw < n) || (n < nw && nw < w)) {
2267	  if (ABS(w-nw) > 32 || ABS(n-nw) > 32)
2268	    pred = w + n - nw;
2269	  else pred = (w + n) >> 1;
2270	} else pred = ABS(w-nw) > ABS(n-nw) ? w : n;
2271      }
2272      if ((RBAYER(row,col) = pred + ((diff << 2) | low)) >> 12) derror();
2273    }
2274  }
2275#ifdef LIBRAW_LIBRARY_BUILD
2276  delete buf;
2277#endif
2278}
2279
2280
2281void CLASS minolta_rd175_load_raw()
2282{
2283  uchar pixel[768];
2284  unsigned irow, box, row, col;
2285
2286  for (irow=0; irow < 1481; irow++) {
2287    if (fread (pixel, 1, 768, ifp) < 768) derror();
2288    box = irow / 82;
2289    row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box-12)*2);
2290    switch (irow) {
2291      case 1477: case 1479: continue;
2292      case 1476: row = 984; break;
2293      case 1480: row = 985; break;
2294      case 1478: row = 985; box = 1;
2295    }
2296    if ((box < 12) && (box & 1)) {
2297      for (col=0; col < 1533; col++, row ^= 1)
2298	if (col != 1) RRBAYER(row,col) = (col+1) & 2 ?
2299		   pixel[col/2-1] + pixel[col/2+1] : pixel[col/2] << 1;
2300      RRBAYER(row,1)    = pixel[1]   << 1;
2301      RRBAYER(row,1533) = pixel[765] << 1;
2302    } else
2303      for (col=row & 1; col < 1534; col+=2)
2304          RRBAYER(row,col) = pixel[col/2] << 1;
2305  }
2306  maximum = 0xff << 1;
2307}
2308
2309void CLASS quicktake_100_load_raw()
2310{
2311  uchar pixel[484][644];
2312  static const short gstep[16] =
2313  { -89,-60,-44,-32,-22,-15,-8,-2,2,8,15,22,32,44,60,89 };
2314  static const short rstep[6][4] =
2315  { {  -3,-1,1,3  }, {  -5,-1,1,5  }, {  -8,-2,2,8  },
2316    { -13,-3,3,13 }, { -19,-4,4,19 }, { -28,-6,6,28 } };
2317  static const short t_curve[256] =
2318  { 0,1,2,3,4,5,6,7,8,9,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,
2319    28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,53,
2320    54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78,
2321    79,80,81,82,83,84,86,88,90,92,94,97,99,101,103,105,107,110,112,114,116,
2322    118,120,123,125,127,129,131,134,136,138,140,142,144,147,149,151,153,155,
2323    158,160,162,164,166,168,171,173,175,177,179,181,184,186,188,190,192,195,
2324    197,199,201,203,205,208,210,212,214,216,218,221,223,226,230,235,239,244,
2325    248,252,257,261,265,270,274,278,283,287,291,296,300,305,309,313,318,322,
2326    326,331,335,339,344,348,352,357,361,365,370,374,379,383,387,392,396,400,
2327    405,409,413,418,422,426,431,435,440,444,448,453,457,461,466,470,474,479,
2328    483,487,492,496,500,508,519,531,542,553,564,575,587,598,609,620,631,643,
2329    654,665,676,687,698,710,721,732,743,754,766,777,788,799,810,822,833,844,
2330    855,866,878,889,900,911,922,933,945,956,967,978,989,1001,1012,1023 };
2331  int rb, row, col, sharp, val=0;
2332
2333  getbits(-1);
2334  memset (pixel, 0x80, sizeof pixel);
2335  for (row=2; row < height+2; row++) {
2336    for (col=2+(row & 1); col < width+2; col+=2) {
2337      val = ((pixel[row-1][col-1] + 2*pixel[row-1][col+1] +
2338		pixel[row][col-2]) >> 2) + gstep[getbits(4)];
2339      pixel[row][col] = val = LIM(val,0,255);
2340      if (col < 4)
2341	pixel[row][col-2] = pixel[row+1][~row & 1] = val;
2342      if (row == 2)
2343	pixel[row-1][col+1] = pixel[row-1][col+3] = val;
2344    }
2345    pixel[row][col] = val;
2346  }
2347  for (rb=0; rb < 2; rb++)
2348    for (row=2+rb; row < height+2; row+=2)
2349      for (col=3-(row & 1); col < width+2; col+=2) {
2350	if (row < 4 || col < 4) sharp = 2;
2351	else {
2352	  val = ABS(pixel[row-2][col] - pixel[row][col-2])
2353	      + ABS(pixel[row-2][col] - pixel[row-2][col-2])
2354	      + ABS(pixel[row][col-2] - pixel[row-2][col-2]);
2355	  sharp = val <  4 ? 0 : val <  8 ? 1 : val < 16 ? 2 :
2356		  val < 32 ? 3 : val < 48 ? 4 : 5;
2357	}
2358	val = ((pixel[row-2][col] + pixel[row][col-2]) >> 1)
2359	      + rstep[sharp][getbits(2)];
2360	pixel[row][col] = val = LIM(val,0,255);
2361	if (row < 4) pixel[row-2][col+2] = val;
2362	if (col < 4) pixel[row+2][col-2] = val;
2363      }
2364  for (row=2; row < height+2; row++)
2365    for (col=3-(row & 1); col < width+2; col+=2) {
2366      val = ((pixel[row][col-1] + (pixel[row][col] << 2) +
2367	      pixel[row][col+1]) >> 1) - 0x100;
2368      pixel[row][col] = LIM(val,0,255);
2369    }
2370  for (row=0; row < height; row++)
2371    for (col=0; col < width; col++)
2372            RBAYER(row,col) = t_curve[pixel[row+2][col+2]];
2373  maximum = 0x3ff;
2374}
2375
2376#define radc_token(tree) ((signed char) getbithuff(8,huff[tree]))
2377
2378#define FORYX for (y=1; y < 3; y++) for (x=col+1; x >= col; x--)
2379
2380#define PREDICTOR (c ? (buf[c][y-1][x] + buf[c][y][x+1]) / 2 \
2381: (buf[c][y-1][x+1] + 2*buf[c][y-1][x] + buf[c][y][x+1]) / 4)
2382
2383void CLASS kodak_radc_load_raw()
2384{
2385  static const char src[] = {
2386    1,1, 2,3, 3,4, 4,2, 5,7, 6,5, 7,6, 7,8,
2387    1,0, 2,1, 3,3, 4,4, 5,2, 6,7, 7,6, 8,5, 8,8,
2388    2,1, 2,3, 3,0, 3,2, 3,4, 4,6, 5,5, 6,7, 6,8,
2389    2,0, 2,1, 2,3, 3,2, 4,4, 5,6, 6,7, 7,5, 7,8,
2390    2,1, 2,4, 3,0, 3,2, 3,3, 4,7, 5,5, 6,6, 6,8,
2391    2,3, 3,1, 3,2, 3,4, 3,5, 3,6, 4,7, 5,0, 5,8,
2392    2,3, 2,6, 3,0, 3,1, 4,4, 4,5, 4,7, 5,2, 5,8,
2393    2,4, 2,7, 3,3, 3,6, 4,1, 4,2, 4,5, 5,0, 5,8,
2394    2,6, 3,1, 3,3, 3,5, 3,7, 3,8, 4,0, 5,2, 5,4,
2395    2,0, 2,1, 3,2, 3,3, 4,4, 4,5, 5,6, 5,7, 4,8,
2396    1,0, 2,2, 2,-2,
2397    1,-3, 1,3,
2398    2,-17, 2,-5, 2,5, 2,17,
2399    2,-7, 2,2, 2,9, 2,18,
2400    2,-18, 2,-9, 2,-2, 2,7,
2401    2,-28, 2,28, 3,-49, 3,-9, 3,9, 4,49, 5,-79, 5,79,
2402    2,-1, 2,13, 2,26, 3,39, 4,-16, 5,55, 6,-37, 6,76,
2403    2,-26, 2,-13, 2,1, 3,-39, 4,16, 5,-55, 6,-76, 6,37
2404  };
2405  ushort huff[19][256];
2406  int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val;
2407  short last[3] = { 16,16,16 }, mul[3], buf[3][3][386];
2408  static const ushort pt[] =
2409    { 0,0, 1280,1344, 2320,3616, 3328,8000, 4095,16383, 65535,16383 };
2410
2411  for (i=2; i < 12; i+=2)
2412    for (c=pt[i-2]; c <= pt[i]; c++)
2413      curve[c] = (float)
2414	(c-pt[i-2]) / (pt[i]-pt[i-2]) * (pt[i+1]-pt[i-1]) + pt[i-1] + 0.5;
2415  for (s=i=0; i < sizeof src; i+=2)
2416    FORC(256 >> src[i])
2417      huff[0][s++] = src[i] << 8 | (uchar) src[i+1];
2418  s = kodak_cbpp == 243 ? 2 : 3;
2419  FORC(256) huff[18][c] = (8-s) << 8 | c >> s << s | 1 << (s-1);
2420  getbits(-1);
2421  for (i=0; i < sizeof(buf)/sizeof(short); i++)
2422    buf[0][0][i] = 2048;
2423  for (row=0; row < height; row+=4) {
2424    FORC3 mul[c] = getbits(6);
2425    FORC3 {
2426      val = ((0x1000000/last[c] + 0x7ff) >> 12) * mul[c];
2427      s = val > 65564 ? 10:12;
2428      x = ~(-1 << (s-1));
2429      val <<= 12-s;
2430      for (i=0; i < sizeof(buf[0])/sizeof(short); i++)
2431	buf[c][0][i] = (buf[c][0][i] * val + x) >> s;
2432      last[c] = mul[c];
2433      for (r=0; r <= !c; r++) {
2434	buf[c][1][width/2] = buf[c][2][width/2] = mul[c] << 7;
2435	for (tree=1, col=width/2; col > 0; ) {
2436	  if ((tree = radc_token(tree))) {
2437	    col -= 2;
2438	    if (tree == 8)
2439	      FORYX buf[c][y][x] = (uchar) radc_token(18) * mul[c];
2440	    else
2441	      FORYX buf[c][y][x] = radc_token(tree+10) * 16 + PREDICTOR;
2442	  } else
2443	    do {
2444	      nreps = (col > 2) ? radc_token(9) + 1 : 1;
2445	      for (rep=0; rep < 8 && rep < nreps && col > 0; rep++) {
2446		col -= 2;
2447		FORYX buf[c][y][x] = PREDICTOR;
2448		if (rep & 1) {
2449		  step = radc_token(10) << 4;
2450		  FORYX buf[c][y][x] += step;
2451		}
2452	      }
2453	    } while (nreps == 9);
2454	}
2455	for (y=0; y < 2; y++)
2456	  for (x=0; x < width/2; x++) {
2457	    val = (buf[c][y+1][x] << 4) / mul[c];
2458	    if (val < 0) val = 0;
2459	    if (c) CBAYER(row+y*2+c-1,x*2+2-c) = val;
2460	    else   CBAYER(row+r*2+y,x*2+y) = val;
2461	  }
2462	memcpy (buf[c][0]+!c, buf[c][2], sizeof buf[c][0]-2*!c);
2463      }
2464    }
2465    for (y=row; y < row+4; y++)
2466      for (x=0; x < width; x++)
2467	if ((x+y) & 1) {
2468	  r = x ? x-1 : x+1;
2469	  s = x+1 < width ? x+1 : x-1;
2470	  val = (CBAYER(y,x)-2048)*2 + (CBAYER(y,r)+CBAYER(y,s))/2;
2471	  if (val < 0) val = 0;
2472	  CBAYER(y,x) = val;
2473	}
2474  }
2475#ifndef LIBRAW_LIBRARY_BUILD
2476  for (i=0; i < iheight*iwidth*4; i++)
2477    image[0][i] = curve[image[0][i]];
2478#else
2479  for (i=0; i < height*width*4; i++)
2480    color_image[0][i] = curve[color_image[0][i]];
2481#endif
2482  maximum = 0x3fff;
2483}
2484
2485#undef FORYX
2486#undef PREDICTOR
2487
2488#ifdef NO_JPEG
2489void CLASS kodak_jpeg_load_raw() {}
2490#else
2491
2492METHODDEF(boolean)
2493fill_input_buffer (j_decompress_ptr cinfo)
2494{
2495#ifndef LIBRAW_NOTHREADS
2496#define jpeg_buffer tls->jpeg_buffer
2497#else
2498  static uchar jpeg_buffer[4096];
2499#endif
2500  size_t nbytes;
2501
2502  nbytes = fread (jpeg_buffer, 1, 4096, ifp);
2503  swab (jpeg_buffer, jpeg_buffer, nbytes);
2504  cinfo->src->next_input_byte = jpeg_buffer;
2505  cinfo->src->bytes_in_buffer = nbytes;
2506  return TRUE;
2507#ifndef LIBRAW_NOTHREADS
2508#undef jpeg_buffer
2509#endif
2510}
2511
2512void CLASS kodak_jpeg_load_raw()
2513{
2514  struct jpeg_decompress_struct cinfo;
2515  struct jpeg_error_mgr jerr;
2516  JSAMPARRAY buf;
2517  JSAMPLE (*pixel)[3];
2518  int row, col;
2519
2520  cinfo.err = jpeg_std_error (&jerr);
2521  jpeg_create_decompress (&cinfo);
2522  jpeg_stdio_src (&cinfo, ifp);
2523  cinfo.src->fill_input_buffer = fill_input_buffer;
2524  jpeg_read_header (&cinfo, TRUE);
2525  jpeg_start_decompress (&cinfo);
2526  if ((cinfo.output_width      != width  ) ||
2527      (cinfo.output_height*2   != height ) ||
2528      (cinfo.output_components != 3      )) {
2529#ifdef DCRAW_VERBOSE
2530    fprintf (stderr,_("%s: incorrect JPEG dimensions\n"), ifname);
2531#endif
2532    jpeg_destroy_decompress (&cinfo);
2533#ifdef LIBRAW_LIBRARY_BUILD
2534    throw LIBRAW_EXCEPTION_DECODE_JPEG;
2535#else
2536    longjmp (failure, 3);
2537#endif
2538  }
2539  buf = (*cinfo.mem->alloc_sarray)
2540		((j_common_ptr) &cinfo, JPOOL_IMAGE, width*3, 1);
2541
2542  while (cinfo.output_scanline < cinfo.output_height) {
2543    row = cinfo.output_scanline * 2;
2544    jpeg_read_scanlines (&cinfo, buf, 1);
2545    pixel = (JSAMPLE (*)[3]) buf[0];
2546    for (col=0; col < width; col+=2) {
2547      RBAYER(row+0,col+0) = pixel[col+0][1] << 1;
2548      RBAYER(row+1,col+1) = pixel[col+1][1] << 1;
2549      RBAYER(row+0,col+1) = pixel[col][0] + pixel[col+1][0];
2550      RBAYER(row+1,col+0) = pixel[col][2] + pixel[col+1][2];
2551    }
2552  }
2553  jpeg_finish_decompress (&cinfo);
2554  jpeg_destroy_decompress (&cinfo);
2555  maximum = 0xff << 1;
2556}
2557#endif
2558
2559void CLASS kodak_dc120_load_raw()
2560{
2561  static const int mul[4] = { 162, 192, 187,  92 };
2562  static const int add[4] = {   0, 636, 424, 212 };
2563  uchar pixel[848];
2564  int row, shift, col;
2565
2566  for (row=0; row < height; row++) {
2567    if (fread (pixel, 1, 848, ifp) < 848) derror();
2568    shift = row * mul[row & 3] + add[row & 3];
2569    for (col=0; col < width; col++)
2570      RBAYER(row,col) = (ushort) pixel[(col + shift) % 848];
2571  }
2572  maximum = 0xff;
2573}
2574
2575void CLASS eight_bit_load_raw()
2576{
2577  uchar *pixel;
2578  unsigned row, col, val, lblack=0;
2579
2580  pixel = (uchar *) calloc (raw_width, sizeof *pixel);
2581  merror (pixel, "eight_bit_load_raw()");
2582#ifndef LIBRAW_LIBRARY_BUILD
2583  fseek (ifp, top_margin*raw_width, SEEK_CUR);
2584  for (row=0; row < height; row++) {
2585    if (fread (pixel, 1, raw_width, ifp) < raw_width) derror();
2586    for (col=0; col < raw_width; col++) {
2587      val = curve[pixel[col]];
2588      if ((unsigned) (col-left_margin) < width)
2589	BAYER(row,col-left_margin) = val;
2590      else lblack += val;
2591    }
2592  }
2593#else
2594  for (row=0; row < raw_height; row++) {
2595    if (fread (pixel, 1, raw_width, ifp) < raw_width) derror();
2596    for (col=0; col < raw_width; col++) {
2597            val = curve[pixel[col]];
2598        RBAYER(row,col) = val;
2599        if((unsigned) (row-top_margin)< height)
2600            if ((unsigned) (col-left_margin) >= width)
2601                lblack+=val;
2602    }
2603  }
2604#endif
2605
2606  free (pixel);
2607  if (raw_width > width+1)
2608    black = lblack / ((raw_width - width) * height);
2609  if (!strncmp(model,"DC2",3))
2610    black = 0;
2611  maximum = curve[0xff];
2612}
2613
2614void CLASS kodak_yrgb_load_raw()
2615{
2616  uchar *pixel;
2617  int row, col, y, cb, cr, rgb[3], c;
2618
2619  pixel = (uchar *) calloc (raw_width, 3*sizeof *pixel);
2620  merror (pixel, "kodak_yrgb_load_raw()");
2621  for (row=0; row < height; row++) {
2622    if (~row & 1)
2623      if (fread (pixel, raw_width, 3, ifp) < 3) derror();
2624    for (col=0; col < raw_width; col++) {
2625      y  = pixel[width*2*(row & 1) + col];
2626      cb = pixel[width + (col & -2)]   - 128;
2627      cr = pixel[width + (col & -2)+1] - 128;
2628      rgb[1] = y-((cb + cr + 2) >> 2);
2629      rgb[2] = rgb[1] + cb;
2630      rgb[0] = rgb[1] + cr;
2631      FORC3{
2632#ifndef LIBRAW_LIBRARY_BUILD
2633          image[row*width+col][c] = curve[LIM(rgb[c],0,255)];
2634#else
2635          color_image[(row+top_margin)*raw_width+col+left_margin][c] = curve[LIM(rgb[c],0,255)];
2636#endif
2637      }
2638    }
2639  }
2640  free (pixel);
2641  maximum = curve[0xff];
2642}
2643
2644void CLASS kodak_262_load_raw()
2645{
2646  static const uchar kodak_tree[2][26] =
2647  { { 0,1,5,1,1,2,0,0,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 },
2648    { 0,3,1,1,1,1,1,2,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 } };
2649  ushort *huff[2];
2650  uchar *pixel;
2651  int *strip, ns, c, row, col, chess, pi=0, pi1, pi2, pred, val;
2652
2653  FORC(2) huff[c] = make_decoder (kodak_tree[c]);
2654  ns = (raw_height+63) >> 5;
2655  pixel = (uchar *) malloc (raw_width*32 + ns*4);
2656  merror (pixel, "kodak_262_load_raw()");
2657  strip = (int *) (pixel + raw_width*32);
2658  order = 0x4d4d;
2659  FORC(ns) strip[c] = get4();
2660  for (row=0; row < raw_height; row++) {
2661    if ((row & 31) == 0) {
2662      fseek (ifp, strip[row >> 5], SEEK_SET);
2663      getbits(-1);
2664      pi = 0;
2665    }
2666    for (col=0; col < raw_width; col++) {
2667      chess = (row + col) & 1;
2668      pi1 = chess ? pi-2           : pi-raw_width-1;
2669      pi2 = chess ? pi-2*raw_width : pi-raw_width+1;
2670      if (col <= chess) pi1 = -1;
2671      if (pi1 < 0) pi1 = pi2;
2672      if (pi2 < 0) pi2 = pi1;
2673      if (pi1 < 0 && col > 1) pi1 = pi2 = pi-2;
2674      pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1;
2675      pixel[pi] = val = pred + ljpeg_diff (huff[chess]);
2676      if (val >> 8) derror();
2677
2678      val = curve[pixel[pi++]];
2679
2680#ifdef LIBRAW_LIBRARY_BUILD
2681      RBAYER(row,col) = val;
2682      if ((unsigned) (col-left_margin) >= width)
2683          black+=val;
2684#else
2685      if ((unsigned) (col-left_margin) < width)
2686	BAYER(row,col-left_margin) = val;
2687      else black += val;
2688#endif
2689    }
2690  }
2691  free (pixel);
2692  FORC(2) free (huff[c]);
2693  if (raw_width > width)
2694    black /= (raw_width - width) * height;
2695}
2696
2697int CLASS kodak_65000_decode (short *out, int bsize)
2698{
2699  uchar c, blen[768];
2700  ushort raw[6];
2701  INT64 bitbuf=0;
2702  int save, bits=0, i, j, len, diff;
2703
2704  save = ftell(ifp);
2705  bsize = (bsize + 3) & -4;
2706  for (i=0; i < bsize; i+=2) {
2707    c = fgetc(ifp);
2708    if ((blen[i  ] = c & 15) > 12 ||
2709	(blen[i+1] = c >> 4) > 12 ) {
2710      fseek (ifp, save, SEEK_SET);
2711      for (i=0; i < bsize; i+=8) {
2712	read_shorts (raw, 6);
2713	out[i  ] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12;
2714	out[i+1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12;
2715	for (j=0; j < 6; j++)
2716	  out[i+2+j] = raw[j] & 0xfff;
2717      }
2718      return 1;
2719    }
2720  }
2721  if ((bsize & 7) == 4) {
2722    bitbuf  = fgetc(ifp) << 8;
2723    bitbuf += fgetc(ifp);
2724    bits = 16;
2725  }
2726  for (i=0; i < bsize; i++) {
2727    len = blen[i];
2728    if (bits < len) {
2729      for (j=0; j < 32; j+=8)
2730	bitbuf += (INT64) fgetc(ifp) << (bits+(j^8));
2731      bits += 32;
2732    }
2733    diff = bitbuf & (0xffff >> (16-len));
2734    bitbuf >>= len;
2735    bits -= len;
2736    if ((diff & (1 << (len-1))) == 0)
2737      diff -= (1 << len) - 1;
2738    out[i] = diff;
2739  }
2740  return 0;
2741}
2742
2743void CLASS kodak_65000_load_raw()
2744{
2745  short buf[256];
2746  int row, col, len, pred[2], ret, i;
2747
2748  for (row=0; row < height; row++)
2749    for (col=0; col < width; col+=256) {
2750      pred[0] = pred[1] = 0;
2751      len = MIN (256, width-col);
2752      ret = kodak_65000_decode (buf, len);
2753      for (i=0; i < len; i++)
2754#ifndef LIBRAW_LIBRARY_BUILD
2755	if ((BAYER(row,col+i) =	curve[ret ? buf[i] :
2756		(pred[i & 1] += buf[i])]) >> 12) derror();
2757#else
2758      {
2759          ushort val = ret ? buf[i] : (pred[i & 1] += buf[i]);
2760          val = curve[val];
2761          RBAYER(row,col+i) = val;
2762          if(curve[val]>>12) derror();
2763      }
2764#endif
2765    }
2766}
2767
2768void CLASS kodak_ycbcr_load_raw()
2769{
2770  short buf[384], *bp;
2771  int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3];
2772  ushort *ip;
2773
2774  for (row=0; row < height; row+=2)
2775    for (col=0; col < width; col+=128) {
2776      len = MIN (128, width-col);
2777      kodak_65000_decode (buf, len*3);
2778      y[0][1] = y[1][1] = cb = cr = 0;
2779      for (bp=buf, i=0; i < len; i+=2, bp+=2) {
2780	cb += bp[4];
2781	cr += bp[5];
2782	rgb[1] = -((cb + cr + 2) >> 2);
2783	rgb[2] = rgb[1] + cb;
2784	rgb[0] = rgb[1] + cr;
2785	for (j=0; j < 2; j++)
2786	  for (k=0; k < 2; k++) {
2787	    if ((y[j][k] = y[j][k^1] + *bp++) >> 10) derror();
2788#ifndef LIBRAW_LIBRARY_BUILD
2789	    ip = image[(row+j)*width + col+i+k];
2790	    FORC3 ip[c] = curve[LIM(y[j][k]+rgb[c], 0, 0xfff)];
2791#else
2792	    ip = color_image[(row+top_margin+j)*raw_width + col+i+k+left_margin];
2793            FORC3 ip[c] = curve[LIM(y[j][k]+rgb[c], 0, 0xfff)];
2794#endif
2795	  }
2796      }
2797    }
2798}
2799
2800void CLASS kodak_rgb_load_raw()
2801{
2802  short buf[768], *bp;
2803  int row, col, len, c, i, rgb[3];
2804#ifndef LIBRAW_LIBRARY_BUILD
2805  ushort *ip=image[0];
2806#else
2807  ushort *ip;
2808#endif
2809
2810  for (row=0; row < height; row++)
2811    for (col=0; col < width; col+=256) {
2812      len = MIN (256, width-col);
2813      kodak_65000_decode (buf, len*3);
2814      memset (rgb, 0, sizeof rgb);
2815#ifdef LIBRAW_LIBRARY_BUILD
2816      ip = &color_image[(row+top_margin)*raw_width+left_margin][0];
2817#endif
2818      for (bp=buf, i=0; i < len; i++, ip+=4)
2819          FORC3{
2820              if ((ip[c] = rgb[c] += *bp++) >> 12) derror();
2821          }
2822    }
2823}
2824
2825void CLASS kodak_ycbcr_load_thumb()
2826{
2827  short buf[384], *bp;
2828  int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3];
2829  ushort *ip;
2830
2831  for (row=0; row < height; row+=2)
2832    for (col=0; col < width; col+=128) {
2833      len = MIN (128, width-col);
2834      kodak_65000_decode (buf, len*3);
2835      y[0][1] = y[1][1] = cb = cr = 0;
2836      for (bp=buf, i=0; i < len; i+=2, bp+=2) {
2837	cb += bp[4];
2838	cr += bp[5];
2839	rgb[1] = -((cb + cr + 2) >> 2);
2840	rgb[2] = rgb[1] + cb;
2841	rgb[0] = rgb[1] + cr;
2842	for (j=0; j < 2; j++)
2843	  for (k=0; k < 2; k++) {
2844	    if ((y[j][k] = y[j][k^1] + *bp++) >> 10) derror();
2845	    ip = image[(row+j)*width + col+i+k];
2846	    FORC3 ip[c] = curve[LIM(y[j][k]+rgb[c], 0, 0xfff)];
2847	  }
2848      }
2849    }
2850}
2851
2852void CLASS kodak_rgb_load_thumb()
2853{
2854  short buf[768], *bp;
2855  int row, col, len, c, i, rgb[3];
2856  ushort *ip=image[0];
2857
2858  for (row=0; row < height; row++)
2859    for (col=0; col < width; col+=256) {
2860      len = MIN (256, width-col);
2861      kodak_65000_decode (buf, len*3);
2862      memset (rgb, 0, sizeof rgb);
2863      for (bp=buf, i=0; i < len; i++, ip+=4)
2864	FORC3 if ((ip[c] = rgb[c] += *bp++) >> 12) derror();
2865    }
2866}
2867
2868void CLASS kodak_thumb_load_raw()
2869{
2870  int row, col;
2871  colors = thumb_misc >> 5;
2872  for (row=0; row < height; row++)
2873    for (col=0; col < width; col++)
2874      read_shorts (image[row*width+col], colors);
2875  maximum = (1 << (thumb_misc & 31)) - 1;
2876}
2877
2878void CLASS sony_decrypt (unsigned *data, int len, int start, int key)
2879{
2880#ifndef LIBRAW_NOTHREADS
2881#define pad tls->sony_decrypt.pad
2882#define p   tls->sony_decrypt.p
2883#else
2884  static unsigned pad[128], p;
2885#endif
2886
2887  if (start) {
2888    for (p=0; p < 4; p++)
2889      pad[p] = key = key * 48828125 + 1;
2890    pad[3] = pad[3] << 1 | (pad[0]^pad[2]) >> 31;
2891    for (p=4; p < 127; p++)
2892      pad[p] = (pad[p-4]^pad[p-2]) << 1 | (pad[p-3]^pad[p-1]) >> 31;
2893    for (p=0; p < 127; p++)
2894      pad[p] = htonl(pad[p]);
2895  }
2896  while (len--)
2897    *data++ ^= pad[p++ & 127] = pad[(p+1) & 127] ^ pad[(p+65) & 127];
2898#ifndef LIBRAW_NOTHREADS
2899#undef pad
2900#undef p
2901#endif
2902}
2903
2904void CLASS sony_load_raw()
2905{
2906  uchar head[40];
2907  ushort *pixel;
2908  unsigned i, key, row, col;
2909
2910  fseek (ifp, 200896, SEEK_SET);
2911  fseek (ifp, (unsigned) fgetc(ifp)*4 - 1, SEEK_CUR);
2912  order = 0x4d4d;
2913  key = get4();
2914  fseek (ifp, 164600, SEEK_SET);
2915  fread (head, 1, 40, ifp);
2916  sony_decrypt ((unsigned int *) head, 10, 1, key);
2917  for (i=26; i-- > 22; )
2918    key = key << 8 | head[i];
2919  fseek (ifp, data_offset, SEEK_SET);
2920  pixel = (ushort *) calloc (raw_width, sizeof *pixel);
2921  merror (pixel, "sony_load_raw()");
2922  for (row=0; row < height; row++) {
2923    if (fread (pixel, 2, raw_width, ifp) < raw_width) derror();
2924    sony_decrypt ((unsigned int *) pixel, raw_width/2, !row, key);
2925    for (col=9; col < left_margin; col++)
2926      black += ntohs(pixel[col]);
2927#ifndef LIBRAW_LIBRARY_BUILD
2928    for (col=0; col < width; col++)
2929      if ((BAYER(row,col) = ntohs(pixel[col+left_margin])) >> 14)
2930	derror();
2931#else
2932    for (col=0; col < raw_width; col++)
2933        {
2934            RBAYER(row,col) = ntohs(pixel[col]);
2935            if(col >= left_margin && col < width+left_margin
2936               && (RBAYER(row,col)>>14))
2937                derror();
2938        }
2939#endif
2940   }
2941  free (pixel);
2942  if (left_margin > 9)
2943    black /= (left_margin-9) * height;
2944  maximum = 0x3ff0;
2945}
2946
2947void CLASS sony_arw_load_raw()
2948{
2949  ushort huff[32768];
2950  static const ushort tab[18] =
2951  { 0xf11,0xf10,0xe0f,0xd0e,0xc0d,0xb0c,0xa0b,0x90a,0x809,
2952    0x708,0x607,0x506,0x405,0x304,0x303,0x300,0x202,0x201 };
2953  int i, c, n, col, row, len, diff, sum=0;
2954
2955  for (n=i=0; i < 18; i++)
2956    FORC(32768 >> (tab[i] >> 8)) huff[n++] = tab[i];
2957#ifdef LIBRAW_LIBRARY_BUILD
2958  LibRaw_byte_buffer *buf=NULL;
2959  if(data_size)
2960      buf = ifp->make_byte_buffer(data_size);
2961  else
2962      getbits(-1);
2963      
2964  LibRaw_bit_buffer bits;
2965  bits.reset();
2966#else
2967  getbits(-1);
2968#endif
2969  for (col = raw_width; col--; )
2970    for (row=0; row < raw_height+1; row+=2) {
2971      if (row == raw_height) row = 1;
2972#ifdef LIBRAW_LIBRARY_BUILD
2973      if(data_size)
2974          {
2975              len = bits._gethuff(buf,15,huff,zero_after_ff);
2976              diff = bits._getbits(buf,len,zero_after_ff);
2977          }
2978      else
2979          {
2980              len = getbithuff(15,huff);
2981              diff = getbits(len);
2982          }
2983#else
2984      len = getbithuff(15,huff);
2985      diff = getbits(len);
2986#endif
2987      if ((diff & (1 << (len-1))) == 0)
2988	diff -= (1 << len) - 1;
2989      if ((sum += diff) >> 12) derror();
2990#ifndef LIBRAW_LIBRARY_BUILD
2991      if (row < height)
2992          {
2993              BAYER(row,col) = sum;
2994          }
2995#else
2996      RBAYER(row,col) = sum;
2997#endif
2998    }
2999#ifdef LIBRAW_LIBRARY_BUILD
3000  if(buf) delete buf;
3001#endif
3002}
3003
3004void CLASS sony_arw2_load_raw()
3005{
3006  uchar *data, *dp;
3007  ushort pix[16];
3008  int row, col, val, max, min, imax, imin, sh, bit, i;
3009
3010  data = (uchar *) malloc (raw_width);
3011  merror (data, "sony_arw2_load_raw()");
3012  for (row=0; row < height; row++) {
3013    fread (data, 1, raw_width, ifp);
3014    for (dp=data, col=0; col < raw_width-30; dp+=16) {
3015      max = 0x7ff & (val = sget4(dp));
3016      min = 0x7ff & val >> 11;
3017      imax = 0x0f & val >> 22;
3018      imin = 0x0f & val >> 26;
3019      for (sh=0; sh < 4 && 0x80 << sh <= max-min; sh++);
3020      for (bit=30, i=0; i < 16; i++)
3021	if      (i == imax) pix[i] = max;
3022	else if (i == imin) pix[i] = min;
3023	else {
3024	  pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min;
3025	  if (pix[i] > 0x7ff) pix[i] = 0x7ff;
3026	  bit += 7;
3027	}
3028      for (i=0; i < 16; i++, col+=2)
3029#ifdef LIBRAW_LIBRARY_BUILD
3030	RBAYER(row,col) = curve[pix[i] << 1] >> 2;
3031#else
3032	if (col < width) BAYER(row,col) = curve[pix[i] << 1] >> 2;
3033#endif
3034      col -= col & 1 ? 1:31;
3035    }
3036  }
3037  free (data);
3038}
3039 
3040#define HOLE(row) ((holes >> (((row) - raw_height) & 7)) & 1)
3041
3042/* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */
3043void CLASS smal_decode_segment (unsigned seg[2][2], int holes)
3044{
3045  uchar hist[3][13] = {
3046    { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 },
3047    { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 },
3048    { 3, 3, 0, 0, 63,     47,     31,     15,    0 } };
3049  int low, high=0xff, carry=0, nbits=8;
3050  int s, count, bin, next, i, sym[3];
3051  uchar diff, pred[]={0,0};
3052  ushort data=0, range=0;
3053  unsigned pix, row, col;
3054
3055  fseek (ifp, seg[0][1]+1, SEEK_SET);
3056  getbits(-1);
3057  for (pix=seg[0][0]; pix < seg[1][0]; pix++) {
3058    for (s=0; s < 3; s++) {
3059      data = data << nbits | getbits(nbits);
3060      if (carry < 0)
3061	carry = (nbits += carry+1) < 1 ? nbits-1 : 0;
3062      while (--nbits >= 0)
3063	if ((data >> nbits & 0xff) == 0xff) break;
3064      if (nbits > 0)
3065	  data = ((data & ((1 << (nbits-1)) - 1)) << 1) |
3066	((data + (((data & (1 << (nbits-1)))) << 1)) & (-1 << nbits));
3067      if (nbits >= 0) {
3068	data += getbits(1);
3069	carry = nbits - 8;
3070      }
3071      count = ((((data-range+1) & 0xffff) << 2) - 1) / (high >> 4);
3072      for (bin=0; hist[s][bin+5] > count; bin++);
3073		low = hist[s][bin+5] * (high >> 4) >> 2;
3074      if (bin) high = hist[s][bin+4] * (high >> 4) >> 2;
3075      high -= low;
3076      for (nbits=0; high << nbits < 128; nbits++);
3077      range = (range+low) << nbits;
3078      high <<= nbits;
3079      next = hist[s][1];
3080      if (++hist[s][2] > hist[s][3]) {
3081	next = (next+1) & hist[s][0];
3082	hist[s][3] = (hist[s][next+4] - hist[s][next+5]) >> 2;
3083	hist[s][2] = 1;
3084      }
3085      if (hist[s][hist[s][1]+4] - hist[s][hist[s][1]+5] > 1) {
3086	if (bin < hist[s][1])
3087	  for (i=bin; i < hist[s][1]; i++) hist[s][i+5]--;
3088	else if (next <= bin)
3089	  for (i=hist[s][1]; i < bin; i++) hist[s][i+5]++;
3090      }
3091      hist[s][1] = next;
3092      sym[s] = bin;
3093    }
3094    diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3);
3095    if (sym[0] & 4)
3096      diff = diff ? -diff : 0x80;
3097    if (ftell(ifp) + 12 >= seg[1][1])
3098      diff = 0;
3099    pred[pix & 1] += diff;
3100#ifndef LIBRAW_LIBRARY_BUILD
3101    row = pix / raw_width - top_margin;
3102    col = pix % raw_width - left_margin;
3103    if (row < height && col < width)
3104            BAYER(row,col) = pred[pix & 1];
3105#else
3106    row = pix / raw_width - top_margin;
3107    RBAYER(pix / raw_width, pix % raw_width) = pred[pix & 1];
3108#endif
3109    if (!(pix & 1) && HOLE(row)) pix += 2;
3110  }
3111  maximum = 0xff;
3112}
3113
3114void CLASS smal_v6_load_raw()
3115{
3116  unsigned seg[2][2];
3117
3118  fseek (ifp, 16, SEEK_SET);
3119  seg[0][0] = 0;
3120  seg[0][1] = get2();
3121  seg[1][0] = raw_width * raw_height;
3122  seg[1][1] = INT_MAX;
3123  smal_decode_segment (seg, 0);
3124}
3125
3126int CLASS median4 (int *p)
3127{
3128  int min, max, sum, i;
3129
3130  min = max = sum = p[0];
3131  for (i=1; i < 4; i++) {
3132    sum += p[i];
3133    if (min > p[i]) min = p[i];
3134    if (max < p[i]) max = p[i];
3135  }
3136  return (sum - min - max) >> 1;
3137}
3138
3139void CLASS fill_holes (int holes)
3140{
3141  int row, col, val[4];
3142
3143  for (row=2; row < height-2; row++) {
3144    if (!HOLE(row)) continue;
3145    for (col=1; col < width-1; col+=4) {
3146      val[0] = BAYER(row-1,col-1);
3147      val[1] = BAYER(row-1,col+1);
3148      val[2] = BAYER(row+1,col-1);
3149      val[3] = BAYER(row+1,col+1);
3150      BAYER(row,col) = median4(val);
3151    }
3152    for (col=2; col < width-2; col+=4)
3153      if (HOLE(row-2) || HOLE(row+2))
3154	BAYER(row,col) = (BAYER(row,col-2) + BAYER(row,col+2)) >> 1;
3155      else {
3156	val[0] = BAYER(row,col-2);
3157	val[1] = BAYER(row,col+2);
3158	val[2] = BAYER(row-2,col);
3159	val[3] = BAYER(row+2,col);
3160	BAYER(row,col) = median4(val);
3161      }
3162  }
3163}
3164
3165void CLASS smal_v9_load_raw()
3166{
3167  unsigned seg[256][2], offset, nseg, holes, i;
3168
3169  fseek (ifp, 67, SEEK_SET);
3170  offset = get4();
3171  nseg = fgetc(ifp);
3172  fseek (ifp, offset, SEEK_SET);
3173  for (i=0; i < nseg*2; i++)
3174    seg[0][i] = get4() + data_offset*(i & 1);
3175  fseek (ifp, 78, SEEK_SET);
3176  holes = fgetc(ifp);
3177  fseek (ifp, 88, SEEK_SET);
3178  seg[nseg][0] = raw_height * raw_width;
3179  seg[nseg][1] = get4() + data_offset;
3180  for (i=0; i < nseg; i++)
3181    smal_decode_segment (seg+i, holes);
3182  if (holes) fill_holes (holes);
3183}
3184
3185void CLASS redcine_load_raw()
3186{
3187#ifndef NO_JASPER
3188  int c, row, col;
3189  jas_stream_t *in;
3190  jas_image_t *jimg;
3191  jas_matrix_t *jmat;
3192  jas_seqent_t *data;
3193  ushort *img, *pix;
3194
3195  jas_init();
3196#ifndef LIBRAW_LIBRARY_BUILD
3197  in = jas_stream_fopen (ifname, "rb");
3198#else
3199  in = (jas_stream_t*)ifp->make_jas_stream();
3200  if(!in)
3201          throw LIBRAW_EXCEPTION_DECODE_JPEG2000;
3202#endif
3203  jas_stream_seek (in, data_offset+20, SEEK_SET);
3204  jimg = jas_image_decode (in, -1, 0);
3205#ifndef LIBRAW_LIBRARY_BUILD
3206  if (!jimg) longjmp (failure, 3);
3207#else
3208  if(!jimg)
3209      {
3210          jas_stream_close (in);
3211          throw LIBRAW_EXCEPTION_DECODE_JPEG2000;
3212      }
3213#endif
3214  jmat = jas_matrix_create (height/2, width/2);
3215  merror (jmat, "redcine_load_raw()");
3216  img = (ushort *) calloc ((height+2)*(width+2), 2);
3217  merror (img, "redcine_load_raw()");
3218  FORC4 {
3219    jas_image_readcmpt (jimg, c, 0, 0, width/2, height/2, jmat);
3220    data = jas_matrix_getref (jmat, 0, 0);
3221    for (row = c >> 1; row < height; row+=2)
3222      for (col = c & 1; col < width; col+=2)
3223	img[(row+1)*(width+2)+col+1] = data[(row/2)*(width/2)+col/2];
3224  }
3225  for (col=1; col <= width; col++) {
3226    img[col] = img[2*(width+2)+col];
3227    img[(height+1)*(width+2)+col] = img[(height-1)*(width+2)+col];
3228  }
3229  for (row=0; row < height+2; row++) {
3230    img[row*(width+2)] = img[row*(width+2)+2];
3231    img[(row+1)*(width+2)-1] = img[(row+1)*(width+2)-3];
3232  }
3233  for (row=1; row <= height; row++) {
3234    pix = img + row*(width+2) + (col = 1 + (FC(row,1) & 1));
3235    for (   ; col <= width; col+=2, pix+=2) {
3236      c = (((pix[0] - 0x800) << 3) +
3237	pix[-(width+2)] + pix[width+2] + pix[-1] + pix[1]) >> 2;
3238      pix[0] = LIM(c,0,4095);
3239    }
3240  }
3241  for (row=0; row < height; row++)
3242    for (col=0; col < width; col++)
3243      RBAYER(row,col) = curve[img[(row+1)*(width+2)+col+1]];
3244  free (img);
3245  jas_matrix_destroy (jmat);
3246  jas_image_destroy (jimg);
3247  jas_stream_close (in);
3248#endif
3249}
3250
3251
3252void CLASS gamma_curve (double pwr, double ts, int mode, int imax)
3253{
3254  int i;
3255  double g[6], bnd[2]={0,0}, r;
3256
3257  g[0] = pwr;
3258  g[1] = ts;
3259  g[2] = g[3] = g[4] = 0;
3260  bnd[g[1] >= 1] = 1;
3261  if (g[1] && (g[1]-1)*(g[0]-1) <= 0) {
3262    for (i=0; i < 48; i++) {
3263      g[2] = (bnd[0] + bnd[1])/2;
3264      if (g[0]) bnd[(pow(g[2]/g[1],-g[0]) - 1)/g[0] - 1/g[2] > -1] = g[2];
3265      else	bnd[g[2]/exp(1-1/g[2]) < g[1]] = g[2];
3266    }
3267    g[3] = g[2] / g[1];
3268    if (g[0]) g[4] = g[2] * (1/g[0] - 1);
3269  }
3270  if (g[0]) g[5] = 1 / (g[1]*SQR(g[3])/2 - g[4]*(1 - g[3]) +
3271		(1 - pow(g[3],1+g[0]))*(1 + g[4])/(1 + g[0])) - 1;
3272  else      g[5] = 1 / (g[1]*SQR(g[3])/2 + 1
3273		- g[2] - g[3] -	g[2]*g[3]*(log(g[3]) - 1)) - 1;
3274  if (!mode--) {
3275    memcpy (gamm, g, sizeof gamm);
3276    return;
3277  }
3278  for (i=0; i < 0x10000; i++) {
3279    curve[i] = 0xffff;
3280    if ((r = (double) i / imax) < 1)
3281      curve[i] = 0x10000 * ( mode
3282	? (r < g[3] ? r*g[1] : (g[0] ? pow( r,g[0])*(1+g[4])-g[4]    : log(r)*g[2]+1))
3283	: (r < g[2] ? r/g[1] : (g[0] ? pow((r+g[4])/(1+g[4]),1/g[0]) : exp((r-1)/g[2]))));
3284  }
3285}
3286
3287void CLASS pseudoinverse (double (*in)[3], double (*out)[3], int size)
3288{
3289  double work[3][6], num;
3290  int i, j, k;
3291
3292  for (i=0; i < 3; i++) {
3293    for (j=0; j < 6; j++)
3294      work[i][j] = j == i+3;
3295    for (j=0; j < 3; j++)
3296      for (k=0; k < size; k++)
3297	work[i][j] += in[k][i] * in[k][j];
3298  }
3299  for (i=0; i < 3; i++) {
3300    num = work[i][i];
3301    for (j=0; j < 6; j++)
3302      work[i][j] /= num;
3303    for (k=0; k < 3; k++) {
3304      if (k==i) continue;
3305      num = work[k][i];
3306      for (j=0; j < 6; j++)
3307	work[k][j] -= work[i][j] * num;
3308    }
3309  }
3310  for (i=0; i < size; i++)
3311    for (j=0; j < 3; j++)
3312      for (out[i][j]=k=0; k < 3; k++)
3313	out[i][j] += work[j][k+3] * in[i][k];
3314}
3315
3316void CLASS cam_xyz_coeff (double cam_xyz[4][3])
3317{
3318  double cam_rgb[4][3], inverse[4][3], num;
3319  int i, j, k;
3320
3321  for (i=0; i < colors; i++)		/* Multiply out XYZ colorspace */
3322    for (j=0; j < 3; j++)
3323      for (cam_rgb[i][j] = k=0; k < 3; k++)
3324	cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j];
3325
3326  for (i=0; i < colors; i++) {		/* Normalize cam_rgb so that */
3327    for (num=j=0; j < 3; j++)		/* cam_rgb * (1,1,1) is (1,1,1,1) */
3328      num += cam_rgb[i][j];
3329    for (j=0; j < 3; j++)
3330      cam_rgb[i][j] /= num;
3331    pre_mul[i] = 1 / num;
3332  }
3333  pseudoinverse (cam_rgb, inverse, colors);
3334  for (raw_color = i=0; i < 3; i++)
3335    for (j=0; j < colors; j++)
3336      rgb_cam[i][j] = inverse[j][i];
3337#ifdef LIBRAW_LIBRARY_BUILD
3338  color_flags.pre_mul_state = LIBRAW_COLORSTATE_CONST;
3339  color_flags.rgb_cam_state = LIBRAW_COLORSTATE_CONST;
3340#endif
3341}
3342
3343#ifdef COLORCHECK
3344void CLASS colorcheck()
3345{
3346#define NSQ 24
3347// Coordinates of the GretagMacbeth ColorChecker squares
3348// width, height, 1st_column, 1st_row
3349  int cut[NSQ][4];			// you must set these
3350// ColorChecker Chart under 6500-kelvin illumination
3351  static const double gmb_xyY[NSQ][3] = {
3352    { 0.400, 0.350, 10.1 },		// Dark Skin
3353    { 0.377, 0.345, 35.8 },		// Light Skin
3354    { 0.247, 0.251, 19.3 },		// Blue Sky
3355    { 0.337, 0.422, 13.3 },		// Foliage
3356    { 0.265, 0.240, 24.3 },		// Blue Flower
3357    { 0.261, 0.343, 43.1 },		// Bluish Green
3358    { 0.506, 0.407, 30.1 },		// Orange
3359    { 0.211, 0.175, 12.0 },		// Purplish Blue
3360    { 0.453, 0.306, 19.8 },		// Moderate Red
3361    { 0.285, 0.202, 6.6 },		// Purple
3362    { 0.380, 0.489, 44.3 },		// Yellow Green
3363    { 0.473, 0.438, 43.1 },		// Orange Yellow
3364    { 0.187, 0.129, 6.1 },		// Blue
3365    { 0.305, 0.478, 23.4 },		// Green
3366    { 0.539, 0.313, 12.0 },		// Red
3367    { 0.448, 0.470, 59.1 },		// Yellow
3368    { 0.364, 0.233, 19.8 },		// Magenta
3369    { 0.196, 0.252, 19.8 },		// Cyan
3370    { 0.310, 0.316, 90.0 },		// White
3371    { 0.310, 0.316, 59.1 },		// Neutral 8
3372    { 0.310, 0.316, 36.2 },		// Neutral 6.5
3373    { 0.310, 0.316, 19.8 },		// Neutral 5
3374    { 0.310, 0.316, 9.0 },		// Neutral 3.5
3375    { 0.310, 0.316, 3.1 } };		// Black
3376  double gmb_cam[NSQ][4], gmb_xyz[NSQ][3];
3377  double inverse[NSQ][3], cam_xyz[4][3], num;
3378  int c, i, j, k, sq, row, col, count[4];
3379
3380  memset (gmb_cam, 0, sizeof gmb_cam);
3381  for (sq=0; sq < NSQ; sq++) {
3382    FORCC count[c] = 0;
3383    for   (row=cut[sq][3]; row < cut[sq][3]+cut[sq][1]; row++)
3384      for (col=cut[sq][2]; col < cut[sq][2]+cut[sq][0]; col++) {
3385	c = FC(row,col);
3386	if (c >= colors) c -= 2;
3387	gmb_cam[sq][c] += BAYER(row,col);
3388	count[c]++;
3389      }
3390    FORCC gmb_cam[sq][c] = gmb_cam[sq][c]/count[c] - black;
3391    gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1];
3392    gmb_xyz[sq][1] = gmb_xyY[sq][2];
3393    gmb_xyz[sq][2] = gmb_xyY[sq][2] *
3394		(1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1];
3395  }
3396  pseudoinverse (gmb_xyz, inverse, NSQ);
3397  for (i=0; i < colors; i++)
3398    for (j=0; j < 3; j++)
3399      for (cam_xyz[i][j] = k=0; k < NSQ; k++)
3400	cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j];
3401  cam_xyz_coeff (cam_xyz);
3402#ifdef DCRAW_VERBOSE
3403  if (verbose) {
3404    printf ("    { \"%s %s\", %d,\n\t{", make, model, black);
3405    num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]);
3406    FORCC for (j=0; j < 3; j++)
3407      printf ("%c%d", (c | j) ? ',':' ', (int) (cam_xyz[c][j] * num + 0.5));
3408    puts (" } },");
3409  }
3410#endif
3411#undef NSQ
3412}
3413#endif
3414
3415void CLASS hat_transform (float *temp, float *base, int st, int size, int sc)
3416{
3417  int i;
3418  for (i=0; i < sc; i++)
3419    temp[i] = 2*base[st*i] + base[st*(sc-i)] + base[st*(i+sc)];
3420  for (; i+sc < size; i++)
3421    temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(i+sc)];
3422  for (; i < size; i++)
3423    temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(2*size-2-(i+sc))];
3424}
3425
3426#if !defined(LIBRAW_USE_OPENMP)
3427void CLASS wavelet_denoise()
3428{
3429  float *fimg=0, *temp, thold, mul[2], avg, diff;
3430  int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2];
3431  ushort *window[4];
3432  static const float noise[] =
3433  { 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 };
3434
3435#ifdef DCRAW_VERBOSE
3436  if (verbose) fprintf (stderr,_("Wavelet denoising...\n"));
3437#endif
3438
3439  while (maximum << scale < 0x10000) scale++;
3440  maximum <<= --scale;
3441  black <<= scale;
3442  FORC4 cblack[c] <<= scale;
3443  if ((size = iheight*iwidth) < 0x15550000)
3444    fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg);
3445  merror (fimg, "wavelet_denoise()");
3446  temp = fimg + size*3;
3447  if ((nc = colors) == 3 && filters) nc++;
3448  FORC(nc) {			/* denoise R,G1,B,G3 individually */
3449    for (i=0; i < size; i++)
3450        fimg[i] = 256 * sqrt((double)(image[i][c] << scale));
3451    for (hpass=lev=0; lev < 5; lev++) {
3452      lpass = size*((lev & 1)+1);
3453      for (row=0; row < iheight; row++) {
3454	hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev);
3455	for (col=0; col < iwidth; col++)
3456	  fimg[lpass + row*iwidth + col] = temp[col] * 0.25;
3457      }
3458      for (col=0; col < iwidth; col++) {
3459	hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev);
3460	for (row=0; row < iheight; row++)
3461	  fimg[lpass + row*iwidth + col] = temp[row] * 0.25;
3462      }
3463      thold = threshold * noise[lev];
3464      for (i=0; i < size; i++) {
3465	fimg[hpass+i] -= fimg[lpass+i];
3466	if	(fimg[hpass+i] < -thold) fimg[hpass+i] += thold;
3467	else if (fimg[hpass+i] >  thold) fimg[hpass+i] -= thold;
3468	else	 fimg[hpass+i] = 0;
3469	if (hpass) fimg[i] += fimg[hpass+i];
3470      }
3471      hpass = lpass;
3472    }
3473    for (i=0; i < size; i++)
3474      image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000);
3475  }
3476  if (filters && colors == 3) {  /* pull G1 and G3 closer together */
3477    for (row=0; row < 2; row++) {
3478      mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1];
3479      blk[row] = cblack[FC(row,0) | 1];
3480    }
3481    for (i=0; i < 4; i++)
3482      window[i] = (ushort *) fimg + width*i;
3483    for (wlast=-1, row=1; row < height-1; row++) {
3484      while (wlast < row+1) {
3485	for (wlast++, i=0; i < 4; i++)
3486	  window[(i+3) & 3] = window[i];
3487	for (col = FC(wlast,1) & 1; col < width; col+=2)
3488	  window[2][col] = BAYER(wlast,col);
3489      }
3490      thold = threshold/512;
3491      for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) {
3492	avg = ( window[0][col-1] + window[0][col+1] +
3493		window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 )
3494	      * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5;
3495	avg = avg < 0 ? 0 : sqrt(avg);
3496	diff = sqrt((double)(BAYER(row,col))) - avg;
3497	if      (diff < -thold) diff += thold;
3498	else if (diff >  thold) diff -= thold;
3499	else diff = 0;
3500	BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5);
3501      }
3502    }
3503  }
3504  free (fimg);
3505}
3506#else /* LIBRAW_USE_OPENMP */
3507void CLASS wavelet_denoise()
3508{
3509  float *fimg=0, *temp, thold, mul[2], avg, diff;
3510   int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2];
3511  ushort *window[4];
3512  static const float noise[] =
3513  { 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 };
3514
3515#ifdef DCRAW_VERBOSE
3516  if (verbose) fprintf (stderr,_("Wavelet denoising...\n"));
3517#endif
3518
3519  while (maximum << scale < 0x10000) scale++;
3520  maximum <<= --scale;
3521  black <<= scale;
3522  FORC4 cblack[c] <<= scale;
3523  if ((size = iheight*iwidth) < 0x15550000)
3524    fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg);
3525  merror (fimg, "wavelet_denoise()");
3526  temp = fimg + size*3;
3527  if ((nc = colors) == 3 && filters) nc++;
3528#ifdef LIBRAW_LIBRARY_BUILD
3529#pragma omp parallel default(shared) private(i,col,row,thold,lev,lpass,hpass,temp,c) firstprivate(scale,size) 
3530#endif
3531  {
3532      temp = (float*)malloc( (iheight + iwidth) * sizeof *fimg);
3533    FORC(nc) {			/* denoise R,G1,B,G3 individually */
3534#ifdef LIBRAW_LIBRARY_BUILD
3535#pragma omp for
3536#endif
3537      for (i=0; i < size; i++)
3538        fimg[i] = 256 * sqrt((double)(image[i][c] << scale));
3539      for (hpass=lev=0; lev < 5; lev++) {
3540	lpass = size*((lev & 1)+1);
3541#ifdef LIBRAW_LIBRARY_BUILD
3542#pragma omp for
3543#endif
3544	for (row=0; row < iheight; row++) {
3545	  hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev);
3546	  for (col=0; col < iwidth; col++)
3547	    fimg[lpass + row*iwidth + col] = temp[col] * 0.25;
3548	}
3549#ifdef LIBRAW_LIBRARY_BUILD
3550#pragma omp for
3551#endif
3552	for (col=0; col < iwidth; col++) {
3553	  hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev);
3554	  for (row=0; row < iheight; row++)
3555	    fimg[lpass + row*iwidth + col] = temp[row] * 0.25;
3556	}
3557	thold = threshold * noise[lev];
3558#ifdef LIBRAW_LIBRARY_BUILD
3559#pragma omp for
3560#endif
3561	for (i=0; i < size; i++) {
3562	  fimg[hpass+i] -= fimg[lpass+i];
3563	  if	(fimg[hpass+i] < -thold) fimg[hpass+i] += thold;
3564	  else if (fimg[hpass+i] >  thold) fimg[hpass+i] -= thold;
3565	  else	 fimg[hpass+i] = 0;
3566	  if (hpass) fimg[i] += fimg[hpass+i];
3567	}
3568	hpass = lpass;
3569      }
3570#ifdef LIBRAW_LIBRARY_BUILD
3571#pragma omp for
3572#endif
3573      for (i=0; i < size; i++)
3574	image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000);
3575    }
3576    free(temp);
3577  } /* end omp parallel */
3578/* the following loops are hard to parallize, no idea yes,
3579 * problem is wlast which is carrying dependency
3580 * second part should be easyer, but did not yet get it right.
3581 */
3582  if (filters && colors == 3) {  /* pull G1 and G3 closer together */
3583   for (row=0; row < 2; row++){
3584      mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1];
3585      blk[row] = cblack[FC(