Commit message: Development branch merged to master
CVE: CVE-2020-24889
Vulnerability description: A buffer overflow vulnerability in LibRaw version < 20.0 LibRaw::GetNormalizedModel in src/metadata/normalize_model.cpp may lead to context-dependent arbitrary code execution.

Project: LibRaw

double timer_elapsed(const starttime_t& start)
{
#ifdef LIBRAW_WIN32_CALLS
	LARGE_INTEGER ended, freq;
	QueryPerformanceCounter(&ended);
	QueryPerformanceFrequency(&freq);
	return double(ended.QuadPart - start.started.QuadPart) / double(freq.QuadPart);
#else
	struct timeval ended;
	gettimeofday(&ended, NULL);
	return double(ended.tv_sec - start.started.tv_sec) + double(ended.tv_usec - start.started.tv_usec) / 1000000.0;
#endif
}

Project: LibRaw

int LibRaw::subtract_black_internal()
{
  CHECK_ORDER_LOW(LIBRAW_PROGRESS_RAW2_IMAGE);

  try
  {
    if (!is_phaseone_compressed() &&
        (C.cblack[0] || C.cblack[1] || C.cblack[2] || C.cblack[3] ||
         (C.cblack[4] && C.cblack[5])))
    {
      int cblk[4], i;
      for (i = 0; i < 4; i++)
        cblk[i] = C.cblack[i];

      int size = S.iheight * S.iwidth;
      int dmax = 0;
      if (C.cblack[4] && C.cblack[5])
      {
        for (i = 0; i < size * 4; i++)
        {
          int val = imgdata.image[0][i];
          val -= C.cblack[6 + i / 4 / S.iwidth % C.cblack[4] * C.cblack[5] +
                          i / 4 % S.iwidth % C.cblack[5]];
          val -= cblk[i & 3];
          imgdata.image[0][i] = CLIP(val);
          if (dmax < val)
            dmax = val;
        }
      }
      else
      {
        for (i = 0; i < size * 4; i++)
        {
          int val = imgdata.image[0][i];
          val -= cblk[i & 3];
          imgdata.image[0][i] = CLIP(val);
          if (dmax < val)
            dmax = val;
        }
      }
      C.data_maximum = dmax & 0xffff;
      C.maximum -= C.black;
      ZERO(C.cblack); // Yeah, we used cblack[6+] values too!
      C.black = 0;
    }
    else
    {
      // Nothing to Do, maximum is already calculated, black level is 0, so no
      // change only calculate channel maximum;
      int idx;
      ushort *p = (ushort *)imgdata.image;
      int dmax = 0;
      for (idx = 0; idx < S.iheight * S.iwidth * 4; idx++)
        if (dmax < p[idx])
          dmax = p[idx];
      C.data_maximum = dmax;
    }
    return 0;
  }
  catch (LibRaw_exceptions err)
  {
    EXCEPTION_HANDLER(err);
  }
}

Project: LibRaw

static inline void fuji_zerobits(struct fuji_compressed_block *info, int *count)
{
  uchar zero = 0;
  *count = 0;
  while (zero == 0)
  {
    zero = (info->cur_buf[info->cur_pos] >> (7 - info->cur_bit)) & 1;
    info->cur_bit++;
    info->cur_bit &= 7;
    if (!info->cur_bit)
    {
      ++info->cur_pos;
      fuji_fill_buffer(info);
    }
    if (zero)
      break;
    ++*count;
  }
}

Project: LibRaw

void LibRaw::hat_transform(float *temp, float *base, int st, int size, int sc)
{
  int i;
  for (i = 0; i < sc; i++)
    temp[i] = 2 * base[st * i] + base[st * (sc - i)] + base[st * (i + sc)];
  for (; i + sc < size; i++)
    temp[i] = 2 * base[st * i] + base[st * (i - sc)] + base[st * (i + sc)];
  for (; i < size; i++)
    temp[i] = 2 * base[st * i] + base[st * (i - sc)] +
              base[st * (2 * size - 2 - (i + sc))];
}

Project: LibRaw

  virtual INT64 size() { return cbView_; }

Project: LibRaw

void LibRaw::copy_line_to_bayer(struct fuji_compressed_block *info,
                                int cur_line, int cur_block,
                                int cur_block_width)
{
  ushort *lineBufB[3];
  ushort *lineBufG[6];
  ushort *lineBufR[3];
  unsigned pixel_count;
  ushort *line_buf;

  int fuji_bayer[2][2];
  for (int r = 0; r < 2; r++)
    for (int c = 0; c < 2; c++)
      fuji_bayer[r][c] = FC(r, c); // We'll downgrade G2 to G below

  int offset = libraw_internal_data.unpacker_data.fuji_block_width * cur_block +
               6 * imgdata.sizes.raw_width * cur_line;
  ushort *raw_block_data = imgdata.rawdata.raw_image + offset;
  int row_count = 0;

  for (int i = 0; i < 3; i++)
  {
    lineBufR[i] = info->linebuf[_R2 + i] + 1;
    lineBufB[i] = info->linebuf[_B2 + i] + 1;
  }
  for (int i = 0; i < 6; i++)
    lineBufG[i] = info->linebuf[_G2 + i] + 1;

  while (row_count < 6)
  {
    pixel_count = 0;
    while (pixel_count < cur_block_width)
    {
      switch (fuji_bayer[row_count & 1][pixel_count & 1])
      {
      case 0: // red
        line_buf = lineBufR[row_count >> 1];
        break;
      case 1:  // green
      case 3:  // second green
      default: // to make static analyzer happy
        line_buf = lineBufG[row_count];
        break;
      case 2: // blue
        line_buf = lineBufB[row_count >> 1];
        break;
      }

      raw_block_data[pixel_count] = line_buf[pixel_count >> 1];
      ++pixel_count;
    }
    ++row_count;
    raw_block_data += imgdata.sizes.raw_width;
  }
}

Project: LibRaw

int LibRaw_buffer_datastream::jpeg_src(void *jpegdata)
{
#if defined(NO_JPEG) || !defined(USE_JPEG)
  return -1;
#else
  j_decompress_ptr cinfo = (j_decompress_ptr)jpegdata;
  jpeg_mem_src(cinfo, (unsigned char *)buf + streampos, streamsize - streampos);
  return 0;
#endif
}

Project: LibRaw

void AAHD::make_ahd_gline(int i)
{
  int iwidth = libraw.imgdata.sizes.iwidth;
  int js = libraw.COLOR(i, 0) & 1;
  int kc = libraw.COLOR(i, js);
  /*
   * js -- начальная х-координата, которая попадает мимо известного зелёного
   * kc -- известный цвет в точке интерполирования
   */
  int hvdir[2] = {Pe, Ps};
  for (int d = 0; d < 2; ++d)
  {
    int moff = nr_offset(i + nr_margin, nr_margin + js);
    for (int j = js; j < iwidth; j += 2, moff += 2)
    {
      ushort3 *cnr;
      cnr = &rgb_ahd[d][moff];
      int h1 = 2 * cnr[-hvdir[d]][1] - int(cnr[-2 * hvdir[d]][kc] + cnr[0][kc]);
      int h2 = 2 * cnr[+hvdir[d]][1] - int(cnr[+2 * hvdir[d]][kc] + cnr[0][kc]);
      int h0 = (h1 + h2) / 4;
      int eg = cnr[0][kc] + h0;
      int min = MIN(cnr[-hvdir[d]][1], cnr[+hvdir[d]][1]);
      int max = MAX(cnr[-hvdir[d]][1], cnr[+hvdir[d]][1]);
      min -= min / OverFraction;
      max += max / OverFraction;
      if (eg < min)
        eg = min - sqrt(float(min - eg));
      else if (eg > max)
        eg = max + sqrt(float(eg - max));
      if (eg > channel_maximum[1])
        eg = channel_maximum[1];
      else if (eg < channel_minimum[1])
        eg = channel_minimum[1];
      cnr[0][1] = eg;
    }
  }
}

Project: LibRaw

static inline void fuji_read_code(struct fuji_compressed_block *info, int *data,
                                  int bits_to_read)
{
  uchar bits_left = bits_to_read;
  uchar bits_left_in_byte = 8 - (info->cur_bit & 7);
  *data = 0;
  if (!bits_to_read)
    return;
  if (bits_to_read >= bits_left_in_byte)
  {
    do
    {
      *data <<= bits_left_in_byte;
      bits_left -= bits_left_in_byte;
      *data |= info->cur_buf[info->cur_pos] & ((1 << bits_left_in_byte) - 1);
      ++info->cur_pos;
      fuji_fill_buffer(info);
      bits_left_in_byte = 8;
    } while (bits_left >= 8);
  }
  if (!bits_left)
  {
    info->cur_bit = (8 - (bits_left_in_byte & 7)) & 7;
    return;
  }
  *data <<= bits_left;
  bits_left_in_byte -= bits_left;
  *data |= ((1 << bits_left) - 1) &
           ((unsigned)info->cur_buf[info->cur_pos] >> bits_left_in_byte);
  info->cur_bit = (8 - (bits_left_in_byte & 7)) & 7;
}

Project: LibRaw

void LibRaw::ahd_interpolate_r_and_b_and_convert_to_cielab(
    int top, int left, ushort (*inout_rgb)[LIBRAW_AHD_TILE][LIBRAW_AHD_TILE][3],
    short (*out_lab)[LIBRAW_AHD_TILE][LIBRAW_AHD_TILE][3])
{
  int direction;
  for (direction = 0; direction < 2; direction++)
  {
    ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(
        top, left, inout_rgb[direction], out_lab[direction]);
  }
}

Project: LibRaw

  inline void reconstruct_base()
  {
    /* this subterfuge is to overcome the private-ness of
     * LibRaw_buffer_datastream */
    (LibRaw_buffer_datastream &)*this =
        LibRaw_buffer_datastream(pView_, (size_t)cbView_);
  }

Project: LibRaw

void LibRaw::lch_to_rgb(double (*image2)[3])
{
  int indx;
  for (indx = 0; indx < height * width; indx++)
  {

    image[indx][0] = CLIP(image2[indx][0] / 3.0 - image2[indx][2] / 6.0 +
                          image2[indx][1] / 3.464101615);
    image[indx][1] = CLIP(image2[indx][0] / 3.0 - image2[indx][2] / 6.0 -
                          image2[indx][1] / 3.464101615);
    image[indx][2] = CLIP(image2[indx][0] / 3.0 + image2[indx][2] / 3.0);
  }
}

Project: LibRaw

void LibRaw::setPentaxBodyFeatures(unsigned long long id)
{

  ilm.CamID = id;

  switch (id)
  {
  case 0x12994:
  case 0x12aa2:
  case 0x12b1a:
  case 0x12b60:
  case 0x12b62:
  case 0x12b7e:
  case 0x12b80:
  case 0x12b9c:
  case 0x12b9d:
  case 0x12ba2:
  case 0x12c1e:
  case 0x12c20:
  case 0x12cd2:
  case 0x12cd4:
  case 0x12cfa:
  case 0x12d72:
  case 0x12d73:
  case 0x12db8:
  case 0x12dfe:
  case 0x12e6c:
  case 0x12e76:
  case 0x12ef8:
  case 0x12f52:
  case 0x12f70:
  case 0x12f71:
  case 0x12fb6:
  case 0x12fc0:
  case 0x12fca:
  case 0x1301a:
  case 0x13024:
  case 0x1309c:
  case 0x13222:
  case 0x1322c:
    ilm.CameraMount = LIBRAW_MOUNT_Pentax_K;
    ilm.CameraFormat = LIBRAW_FORMAT_APSC;
    break;
  case 0x13092: // K-1
  case 0x13240: // K-1 Mark II
    ilm.CameraMount = LIBRAW_MOUNT_Pentax_K;
    ilm.CameraFormat = LIBRAW_FORMAT_FF;
    break;
  case 0x12e08: // 645D
  case 0x13010: // 645Z
    ilm.CameraMount = LIBRAW_MOUNT_Pentax_645;
    ilm.CameraFormat = LIBRAW_FORMAT_CROP645;
    break;
  case 0x12ee4: // Q
  case 0x12f66: // Q10
    ilm.CameraMount = LIBRAW_MOUNT_Pentax_Q;
    ilm.CameraFormat = LIBRAW_FORMAT_1div2p3INCH;
    break;
  case 0x12f7a: // Q7
  case 0x1302e: // Q-S1
    ilm.CameraMount = LIBRAW_MOUNT_Pentax_Q;
    ilm.CameraFormat = LIBRAW_FORMAT_1div1p7INCH;
    break;
  case 0x12f84: // MX-1
    ilm.LensMount = LIBRAW_MOUNT_FixedLens;
    ilm.CameraMount = LIBRAW_MOUNT_FixedLens;
    ilm.CameraFormat = LIBRAW_FORMAT_1div1p7INCH;
    ilm.FocalType = LIBRAW_FT_ZOOM_LENS;
    break;
  case 0x1320e: // GR III
    ilm.CameraMount = LIBRAW_MOUNT_FixedLens;
    ilm.LensMount = LIBRAW_MOUNT_FixedLens;
    ilm.CameraFormat = LIBRAW_FORMAT_APSC;
    ilm.LensFormat = LIBRAW_FORMAT_APSC;
    ilm.FocalType = LIBRAW_FT_PRIME_LENS;
    break;
  default:
    ilm.LensMount = LIBRAW_MOUNT_FixedLens;
    ilm.CameraMount = LIBRAW_MOUNT_FixedLens;
  }
  return;
}

Project: LibRaw

	file_mapping() : map(0), fsize(0), fd(-1){}

Project: LibRaw

void LibRaw::dcb_correction2()
{
  int current, row, col, c, u = width, v = 2 * u, indx;
  ushort(*pix)[4];

  for (row = 4; row < height - 4; row++)
    for (col = 4 + (FC(row, 2) & 1), indx = row * width + col, c = FC(row, col);
         col < u - 4; col += 2, indx += 2)
    {

      current = 4 * image[indx][3] +
                2 * (image[indx + u][3] + image[indx - u][3] +
                     image[indx + 1][3] + image[indx - 1][3]) +
                image[indx + v][3] + image[indx - v][3] + image[indx + 2][3] +
                image[indx - 2][3];

      image[indx][1] = CLIP(
          ((16 - current) * ((image[indx - 1][1] + image[indx + 1][1]) / 2.0 +
                             image[indx][c] -
                             (image[indx + 2][c] + image[indx - 2][c]) / 2.0) +
           current * ((image[indx - u][1] + image[indx + u][1]) / 2.0 +
                      image[indx][c] -
                      (image[indx + v][c] + image[indx - v][c]) / 2.0)) /
          16.0);
    }
}

Project: LibRaw

  void libraw_close(libraw_data_t *lr)
  {
    if (!lr)
      return;
    LibRaw *ip = (LibRaw *)lr->parent_class;
    delete ip;
  }

Project: LibRaw

void LibRaw::hasselblad_load_raw()
{
  struct jhead jh;
  int shot, row, col, *back[5], len[2], diff[12], pred, sh, f, s, c;
  unsigned upix, urow, ucol;
  ushort *ip;

  if (!ljpeg_start(&jh, 0))
    return;
  order = 0x4949;
  ph1_bits(-1);
  try
  {
    back[4] = (int *)calloc(raw_width, 3 * sizeof **back);
    merror(back[4], "hasselblad_load_raw()");
    FORC3 back[c] = back[4] + c * raw_width;
    cblack[6] >>= sh = tiff_samples > 1;
    shot = LIM(shot_select, 1, tiff_samples) - 1;
    for (row = 0; row < raw_height; row++)
    {
      checkCancel();
      FORC4 back[(c + 3) & 3] = back[c];
      for (col = 0; col < raw_width; col += 2)
      {
        for (s = 0; s < tiff_samples * 2; s += 2)
        {
          FORC(2) len[c] = ph1_huff(jh.huff[0]);
          FORC(2)
          {
            diff[s + c] = ph1_bits(len[c]);
            if ((diff[s + c] & (1 << (len[c] - 1))) == 0)
              diff[s + c] -= (1 << len[c]) - 1;
            if (diff[s + c] == 65535)
              diff[s + c] = -32768;
          }
        }
        for (s = col; s < col + 2; s++)
        {
          pred = 0x8000 + load_flags;
          if (col)
            pred = back[2][s - 2];
          if (col && row > 1)
            switch (jh.psv)
            {
            case 11:
              pred += back[0][s] / 2 - back[0][s - 2] / 2;
              break;
            }
          f = (row & 1) * 3 ^ ((col + s) & 1);
          FORC(tiff_samples)
          {
            pred += diff[(s & 1) * tiff_samples + c];
            upix = pred >> sh & 0xffff;
            if (raw_image && c == shot)
              RAW(row, s) = upix;
            if (image)
            {
              urow = row - top_margin + (c & 1);
              ucol = col - left_margin - ((c >> 1) & 1);
              ip = &image[urow * width + ucol][f];
              if (urow < height && ucol < width)
                *ip = c < 4 ? upix : (*ip + upix) >> 1;
            }
          }
          back[2][s] = pred;
        }
      }
    }
  }
  catch (...)
  {
    free(back[4]);
    ljpeg_end(&jh);
    throw;
  }
  free(back[4]);
  ljpeg_end(&jh);
  if (image)
    mix_green = 1;
}

Project: LibRaw

void DHT::illustrate_dirs()
{
#if defined(LIBRAW_USE_OPENMP)
#pragma omp parallel for schedule(guided)
#endif
  for (int i = 0; i < libraw.imgdata.sizes.iheight; ++i)
  {
    illustrate_dline(i);
  }
}

Project: LibRaw

int LibRaw::canon_600_color(int ratio[2], int mar)
{
  int clipped = 0, target, miss;

  if (flash_used)
  {
    if (ratio[1] < -104)
    {
      ratio[1] = -104;
      clipped = 1;
    }
    if (ratio[1] > 12)
    {
      ratio[1] = 12;
      clipped = 1;
    }
  }
  else
  {
    if (ratio[1] < -264 || ratio[1] > 461)
      return 2;
    if (ratio[1] < -50)
    {
      ratio[1] = -50;
      clipped = 1;
    }
    if (ratio[1] > 307)
    {
      ratio[1] = 307;
      clipped = 1;
    }
  }
  target = flash_used || ratio[1] < 197 ? -38 - (398 * ratio[1] >> 10)
                                        : -123 + (48 * ratio[1] >> 10);
  if (target - mar <= ratio[0] && target + 20 >= ratio[0] && !clipped)
    return 0;
  miss = target - ratio[0];
  if (abs(miss) >= mar * 4)
    return 2;
  if (miss < -20)
    miss = -20;
  if (miss > mar)
    miss = mar;
  ratio[0] = target - miss;
  return 1;
}

Project: LibRaw

void LibRaw::dcb_color2(float (*image2)[3])
{
  int row, col, c, d, u = width, indx;

  for (row = 1; row < height - 1; row++)
    for (col = 1 + (FC(row, 1) & 1), indx = row * width + col,
        c = 2 - FC(row, col);
         col < u - 1; col += 2, indx += 2)
    {

      image2[indx][c] =
          CLIP((4 * image2[indx][1] - image2[indx + u + 1][1] -
                image2[indx + u - 1][1] - image2[indx - u + 1][1] -
                image2[indx - u - 1][1] + image[indx + u + 1][c] +
                image[indx + u - 1][c] + image[indx - u + 1][c] +
                image[indx - u - 1][c]) /
               4.0);
    }

  for (row = 1; row < height - 1; row++)
    for (col = 1 + (FC(row, 2) & 1), indx = row * width + col,
        c = FC(row, col + 1), d = 2 - c;
         col < width - 1; col += 2, indx += 2)
    {

      image2[indx][c] = CLIP((image[indx + 1][c] + image[indx - 1][c]) / 2.0);
      image2[indx][d] =
          CLIP((2 * image2[indx][1] - image2[indx + u][1] -
                image2[indx - u][1] + image[indx + u][d] + image[indx - u][d]) /
               2.0);
    }
}

Project: LibRaw

  virtual int get_char() {return f->sbumpc();}

Project: LibRaw

void LibRaw::getOlympus_CameraType2()
{

  if (OlyID != 0x0ULL)
    return;

  int i = 0;

  fread(imOly.CameraType2, 6, 1, ifp);
  imOly.CameraType2[5] = 0;
  while ((i < 6) && imOly.CameraType2[i])
  {
    OlyID = OlyID << 8 | imOly.CameraType2[i];
    if (i < 5 && isspace(imOly.CameraType2[i + 1]))
      imOly.CameraType2[i + 1] = '\0';
    i++;
  }
  unique_id = OlyID;
  setOlympusBodyFeatures(OlyID);
  return;
}

Project: LibRaw

  int get_diag_rbg(int x, int y, int hc)
  {
    float dlurd = calc_dist(
        nraw[nr_offset(y - 1, x - 1)][1] * nraw[nr_offset(y + 1, x + 1)][1],
        nraw[nr_offset(y, x)][1] * nraw[nr_offset(y, x)][1]);
    float druld = calc_dist(
        nraw[nr_offset(y - 1, x + 1)][1] * nraw[nr_offset(y + 1, x - 1)][1],
        nraw[nr_offset(y, x)][1] * nraw[nr_offset(y, x)][1]);
    float e = calc_dist(dlurd, druld);
    char d =
        druld < dlurd ? (e > T() ? RULDSH : RULD) : (e > T() ? LURDSH : LURD);
    return d;
  }

Project: LibRaw

  virtual void DoRead(void *data, uint32 count, uint64 offset)
  {
    if (parent_stream)
    {
      parent_stream->seek(offset, SEEK_SET);
      parent_stream->read(data, 1, count);
    }
  }

Project: LibRaw

void LibRaw::stretch()
{
  ushort newdim, (*img)[4], *pix0, *pix1;
  int row, col, c;
  double rc, frac;

  if (pixel_aspect == 1)
    return;
  RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH, 0, 2);
  if (pixel_aspect < 1)
  {
    newdim = height / pixel_aspect + 0.5;
    img = (ushort(*)[4])calloc(width, newdim * sizeof *img);
    merror(img, "stretch()");
    for (rc = row = 0; row < newdim; row++, rc += pixel_aspect)
    {
      frac = rc - (c = rc);
      pix0 = pix1 = image[c * width];
      if (c + 1 < height)
        pix1 += width * 4;
      for (col = 0; col < width; col++, pix0 += 4, pix1 += 4)
        FORCC img[row * width + col][c] =
            pix0[c] * (1 - frac) + pix1[c] * frac + 0.5;
    }
    height = newdim;
  }
  else
  {
    newdim = width * pixel_aspect + 0.5;
    img = (ushort(*)[4])calloc(height, newdim * sizeof *img);
    merror(img, "stretch()");
    for (rc = col = 0; col < newdim; col++, rc += 1 / pixel_aspect)
    {
      frac = rc - (c = rc);
      pix0 = pix1 = image[c];
      if (c + 1 < width)
        pix1 += 4;
      for (row = 0; row < height; row++, pix0 += width * 4, pix1 += width * 4)
        FORCC img[row * newdim + col][c] =
            pix0[c] * (1 - frac) + pix1[c] * frac + 0.5;
    }
    width = newdim;
  }
  free(image);
  image = img;
  RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH, 1, 2);
}

Project: LibRaw

int LibRaw::fcol(int row, int col)
{
  static const char filter[16][16] = {
      {2, 1, 1, 3, 2, 3, 2, 0, 3, 2, 3, 0, 1, 2, 1, 0},
      {0, 3, 0, 2, 0, 1, 3, 1, 0, 1, 1, 2, 0, 3, 3, 2},
      {2, 3, 3, 2, 3, 1, 1, 3, 3, 1, 2, 1, 2, 0, 0, 3},
      {0, 1, 0, 1, 0, 2, 0, 2, 2, 0, 3, 0, 1, 3, 2, 1},
      {3, 1, 1, 2, 0, 1, 0, 2, 1, 3, 1, 3, 0, 1, 3, 0},
      {2, 0, 0, 3, 3, 2, 3, 1, 2, 0, 2, 0, 3, 2, 2, 1},
      {2, 3, 3, 1, 2, 1, 2, 1, 2, 1, 1, 2, 3, 0, 0, 1},
      {1, 0, 0, 2, 3, 0, 0, 3, 0, 3, 0, 3, 2, 1, 2, 3},
      {2, 3, 3, 1, 1, 2, 1, 0, 3, 2, 3, 0, 2, 3, 1, 3},
      {1, 0, 2, 0, 3, 0, 3, 2, 0, 1, 1, 2, 0, 1, 0, 2},
      {0, 1, 1, 3, 3, 2, 2, 1, 1, 3, 3, 0, 2, 1, 3, 2},
      {2, 3, 2, 0, 0, 1, 3, 0, 2, 0, 1, 2, 3, 0, 1, 0},
      {1, 3, 1, 2, 3, 2, 3, 2, 0, 2, 0, 1, 1, 0, 3, 0},
      {0, 2, 0, 3, 1, 0, 0, 1, 1, 3, 3, 2, 3, 2, 2, 1},
      {2, 1, 3, 2, 3, 1, 2, 1, 0, 3, 0, 2, 0, 2, 0, 2},
      {0, 3, 1, 0, 0, 2, 0, 3, 2, 1, 3, 1, 1, 3, 1, 3}};

  if (filters == 1)
    return filter[(row + top_margin) & 15][(col + left_margin) & 15];
  if (filters == 9)
    return xtrans[(row + 6) % 6][(col + 6) % 6];
  return FC(row, col);
}

Project: LibRaw

int show_files(void *q)
{
  char *p;
  int cnt = 0;
  while (p = get_next_file())
  {
    printf("%s\n", p);
    cnt++;
  }
  return cnt;
}

Project: LibRaw

  int libraw_open_wfile(libraw_data_t *lr, const wchar_t *file)
  {
    if (!lr)
      return EINVAL;
    LibRaw *ip = (LibRaw *)lr->parent_class;
    return ip->open_file(file);
  }

Project: LibRaw

void LibRaw::kodak_rgb_load_raw()
{
  if (!image)
    throw LIBRAW_EXCEPTION_IO_CORRUPT;
  short buf[768], *bp;
  int row, col, len, c, i, rgb[3], ret;
  ushort *ip = image[0];

  for (row = 0; row < height; row++)
  {
    checkCancel();
    for (col = 0; col < width; col += 256)
    {
      len = MIN(256, width - col);
      ret = kodak_65000_decode(buf, len * 3);
      memset(rgb, 0, sizeof rgb);
      for (bp = buf, i = 0; i < len; i++, ip += 4)
        if (load_flags == 12)
          FORC3 ip[c] = ret ? (*bp++) : (rgb[c] += *bp++);
        else
          FORC3 if ((ip[c] = ret ? (*bp++) : (rgb[c] += *bp++)) >> 12) derror();
    }
  }
}

Project: LibRaw

void LibRaw::dcb_color3(float (*image3)[3])
{
  int row, col, c, d, u = width, indx;

  for (row = 1; row < height - 1; row++)
    for (col = 1 + (FC(row, 1) & 1), indx = row * width + col,
        c = 2 - FC(row, col);
         col < u - 1; col += 2, indx += 2)
    {

      image3[indx][c] =
          CLIP((4 * image3[indx][1] - image3[indx + u + 1][1] -
                image3[indx + u - 1][1] - image3[indx - u + 1][1] -
                image3[indx - u - 1][1] + image[indx + u + 1][c] +
                image[indx + u - 1][c] + image[indx - u + 1][c] +
                image[indx - u - 1][c]) /
               4.0);
    }

  for (row = 1; row < height - 1; row++)
    for (col = 1 + (FC(row, 2) & 1), indx = row * width + col,
        c = FC(row, col + 1), d = 2 - c;
         col < width - 1; col += 2, indx += 2)
    {

      image3[indx][c] =
          CLIP((2 * image3[indx][1] - image3[indx + 1][1] -
                image3[indx - 1][1] + image[indx + 1][c] + image[indx - 1][c]) /
               2.0);
      image3[indx][d] = CLIP((image[indx + u][d] + image[indx - u][d]) / 2.0);
    }
}

Project: LibRaw

int LibRaw_buffer_datastream::scanf_one(const char *fmt, void *val)
{
  int scanf_res;
  if (streampos > streamsize)
    return 0;
#ifndef WIN32SECURECALLS
  scanf_res = sscanf((char *)(buf + streampos), fmt, val);
#else
  scanf_res = sscanf_s((char *)(buf + streampos), fmt, val);
#endif
  if (scanf_res > 0)
  {
    int xcnt = 0;
    while (streampos < streamsize)
    {
      streampos++;
      xcnt++;
      if (buf[streampos] == 0 || buf[streampos] == ' ' ||
          buf[streampos] == '\t' || buf[streampos] == '\n' || xcnt > 24)
        break;
    }
  }
  return scanf_res;
}

Project: LibRaw

int LibRaw_file_datastream::read(void *ptr, size_t size, size_t nmemb)
{
/* Visual Studio 2008 marks sgetn as insecure, but VS2010 does not. */
#if defined(WIN32SECURECALLS) && (_MSC_VER < 1600)
  LR_STREAM_CHK();
  return int(f->_Sgetn_s(static_cast<char *>(ptr), nmemb * size, nmemb * size) /
             (size > 0 ? size : 1));
#else
  LR_STREAM_CHK();
  return int(f->sgetn(static_cast<char *>(ptr), std::streamsize(nmemb * size)) /
             (size > 0 ? size : 1));
#endif
}

Project: LibRaw

void LibRaw::dcb_restore_from_buffer(float (*image2)[3])
{
  int indx;

  for (indx = 0; indx < height * width; indx++)
  {
    image[indx][0] = image2[indx][0]; // R
    image[indx][2] = image2[indx][2]; // B
  }
}

Project: LibRaw

void close_mapping(struct file_mapping& data)
{
#ifdef LIBRAW_WIN32_CALLS
	if (data.map) UnmapViewOfFile(data.map);
	if (data.fd_map != INVALID_HANDLE_VALUE) CloseHandle(data.fd_map);
	if (data.fd != INVALID_HANDLE_VALUE) CloseHandle(data.fd);
	data.map = 0;
	data.fsize = 0;
	data.fd = data.fd_map = INVALID_HANDLE_VALUE;
#else
	if (data.map)
		munmap(data.map, data.fsize);
	if (data.fd >= 0)
		close(data.fd);
	data.map = 0;
	data.fsize = 0;
	data.fd = -1;
#endif
}

Project: LibRaw

inline unsigned int __DNG_HalfToFloat(ushort halfValue)
{
  int sign = (halfValue >> 15) & 0x00000001;
  int exponent = (halfValue >> 10) & 0x0000001f;
  int mantissa = halfValue & 0x000003ff;
  if (exponent == 0)
  {
    if (mantissa == 0)
    {
      return (unsigned int)(sign << 31);
    }
    else
    {
      while (!(mantissa & 0x00000400))
      {
        mantissa <<= 1;
        exponent -= 1;
      }
      exponent += 1;
      mantissa &= ~0x00000400;
    }
  }
  else if (exponent == 31)
  {
    if (mantissa == 0)
    {
      return (unsigned int)((sign << 31) | ((0x1eL + 127 - 15) << 23) |
                            (0x3ffL << 13));
    }
    else
    {
      return 0;
    }
  }
  exponent += (127 - 15);
  mantissa <<= 13;
  return (unsigned int)((sign << 31) | (exponent << 23) | mantissa);
}

Project: LibRaw

void LibRaw::ciff_block_1030()
{
  static const ushort key[] = {0x410, 0x45f3};
  int i, bpp, row, col, vbits = 0;
  unsigned long bitbuf = 0;

  if ((get2(), get4()) != 0x80008 || !get4())
    return;
  bpp = get2();
  if (bpp != 10 && bpp != 12)
    return;
  for (i = row = 0; row < 8; row++)
    for (col = 0; col < 8; col++)
    {
      if (vbits < bpp)
      {
        bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]);
        vbits += 16;
      }
      white[row][col] = bitbuf >> (vbits -= bpp) & ~(-1 << bpp);
    }
}

Project: LibRaw

  libraw_internal_data_t *get_internal_data_pointer()
  {
    return &libraw_internal_data;
  }

Project: LibRaw

void LibRaw::vng_interpolate()
{
  static const signed char *cp,
      terms[] =
          {-2, -2, +0,   -1, 0,  0x01, -2, -2, +0,   +0, 1,  0x01, -2, -1, -1,
           +0, 0,  0x01, -2, -1, +0,   -1, 0,  0x02, -2, -1, +0,   +0, 0,  0x03,
           -2, -1, +0,   +1, 1,  0x01, -2, +0, +0,   -1, 0,  0x06, -2, +0, +0,
           +0, 1,  0x02, -2, +0, +0,   +1, 0,  0x03, -2, +1, -1,   +0, 0,  0x04,
           -2, +1, +0,   -1, 1,  0x04, -2, +1, +0,   +0, 0,  0x06, -2, +1, +0,
           +1, 0,  0x02, -2, +2, +0,   +0, 1,  0x04, -2, +2, +0,   +1, 0,  0x04,
           -1, -2, -1,   +0, 0,  -128, -1, -2, +0,   -1, 0,  0x01, -1, -2, +1,
           -1, 0,  0x01, -1, -2, +1,   +0, 1,  0x01, -1, -1, -1,   +1, 0,  -120,
           -1, -1, +1,   -2, 0,  0x40, -1, -1, +1,   -1, 0,  0x22, -1, -1, +1,
           +0, 0,  0x33, -1, -1, +1,   +1, 1,  0x11, -1, +0, -1,   +2, 0,  0x08,
           -1, +0, +0,   -1, 0,  0x44, -1, +0, +0,   +1, 0,  0x11, -1, +0, +1,
           -2, 1,  0x40, -1, +0, +1,   -1, 0,  0x66, -1, +0, +1,   +0, 1,  0x22,
           -1, +0, +1,   +1, 0,  0x33, -1, +0, +1,   +2, 1,  0x10, -1, +1, +1,
           -1, 1,  0x44, -1, +1, +1,   +0, 0,  0x66, -1, +1, +1,   +1, 0,  0x22,
           -1, +1, +1,   +2, 0,  0x10, -1, +2, +0,   +1, 0,  0x04, -1, +2, +1,
           +0, 1,  0x04, -1, +2, +1,   +1, 0,  0x04, +0, -2, +0,   +0, 1,  -128,
           +0, -1, +0,   +1, 1,  -120, +0, -1, +1,   -2, 0,  0x40, +0, -1, +1,
           +0, 0,  0x11, +0, -1, +2,   -2, 0,  0x40, +0, -1, +2,   -1, 0,  0x20,
           +0, -1, +2,   +0, 0,  0x30, +0, -1, +2,   +1, 1,  0x10, +0, +0, +0,
           +2, 1,  0x08, +0, +0, +2,   -2, 1,  0x40, +0, +0, +2,   -1, 0,  0x60,
           +0, +0, +2,   +0, 1,  0x20, +0, +0, +2,   +1, 0,  0x30, +0, +0, +2,
           +2, 1,  0x10, +0, +1, +1,   +0, 0,  0x44, +0, +1, +1,   +2, 0,  0x10,
           +0, +1, +2,   -1, 1,  0x40, +0, +1, +2,   +0, 0,  0x60, +0, +1, +2,
           +1, 0,  0x20, +0, +1, +2,   +2, 0,  0x10, +1, -2, +1,   +0, 0,  -128,
           +1, -1, +1,   +1, 0,  -120, +1, +0, +1,   +2, 0,  0x08, +1, +0, +2,
           -1, 0,  0x40, +1, +0, +2,   +1, 0,  0x10},
      chood[] = {-1, -1, -1, 0, -1, +1, 0, +1, +1, +1, +1, 0, +1, -1, 0, -1};
  ushort(*brow[5])[4], *pix;
  int prow = 8, pcol = 2, *ip, *code[16][16], gval[8], gmin, gmax, sum[4];
  int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag;
  int g, diff, thold, num, c;

  lin_interpolate();

  if (filters == 1)
    prow = pcol = 16;
  if (filters == 9)
    prow = pcol = 6;
  ip = (int *)calloc(prow * pcol, 1280);
  merror(ip, "vng_interpolate()");
  for (row = 0; row < prow; row++) /* Precalculate for VNG */
    for (col = 0; col < pcol; col++)
    {
      code[row][col] = ip;
      for (cp = terms, t = 0; t < 64; t++)
      {
        y1 = *cp++;
        x1 = *cp++;
        y2 = *cp++;
        x2 = *cp++;
        weight = *cp++;
        grads = *cp++;
        color = fcol(row + y1, col + x1);
        if (fcol(row + y2, col + x2) != color)
          continue;
        diag = (fcol(row, col + 1) == color && fcol(row + 1, col) == color) ? 2
                                                                            : 1;
        if (abs(y1 - y2) == diag && abs(x1 - x2) == diag)
          continue;
        *ip++ = (y1 * width + x1) * 4 + color;
        *ip++ = (y2 * width + x2) * 4 + color;
        *ip++ = weight;
        for (g = 0; g < 8; g++)
          if (grads & 1 << g)
            *ip++ = g;
        *ip++ = -1;
      }
      *ip++ = INT_MAX;
      for (cp = chood, g = 0; g < 8; g++)
      {
        y = *cp++;
        x = *cp++;
        *ip++ = (y * width + x) * 4;
        color = fcol(row, col);
        if (fcol(row + y, col + x) != color &&
            fcol(row + y * 2, col + x * 2) == color)
          *ip++ = (y * width + x) * 8 + color;
        else
          *ip++ = 0;
      }
    }
  brow[4] = (ushort(*)[4])calloc(width * 3, sizeof **brow);
  merror(brow[4], "vng_interpolate()");
  for (row = 0; row < 3; row++)
    brow[row] = brow[4] + row * width;
  for (row = 2; row < height - 2; row++)
  { /* Do VNG interpolation */
    if (!((row - 2) % 256))
      RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, (row - 2) / 256 + 1,
                   ((height - 3) / 256) + 1);
    for (col = 2; col < width - 2; col++)
    {
      pix = image[row * width + col];
      ip = code[row % prow][col % pcol];
      memset(gval, 0, sizeof gval);
      while ((g = ip[0]) != INT_MAX)
      { /* Calculate gradients */
        diff = ABS(pix[g] - pix[ip[1]]) << ip[2];
        gval[ip[3]] += diff;
        ip += 5;
        if ((g = ip[-1]) == -1)
          continue;
        gval[g] += diff;
        while ((g = *ip++) != -1)
          gval[g] += diff;
      }
      ip++;
      gmin = gmax = gval[0]; /* Choose a threshold */
      for (g = 1; g < 8; g++)
      {
        if (gmin > gval[g])
          gmin = gval[g];
        if (gmax < gval[g])
          gmax = gval[g];
      }
      if (gmax == 0)
      {
        memcpy(brow[2][col], pix, sizeof *image);
        continue;
      }
      thold = gmin + (gmax >> 1);
      memset(sum, 0, sizeof sum);
      color = fcol(row, col);
      for (num = g = 0; g < 8; g++, ip += 2)
      { /* Average the neighbors */
        if (gval[g] <= thold)
        {
          FORCC
          if (c == color && ip[1])
            sum[c] += (pix[c] + pix[ip[1]]) >> 1;
          else
            sum[c] += pix[ip[0] + c];
          num++;
        }
      }
      FORCC
      { /* Save to buffer */
        t = pix[color];
        if (c != color)
          t += (sum[c] - sum[color]) / num;
        brow[2][col][c] = CLIP(t);
      }
    }
    if (row > 3) /* Write buffer to image */
      memcpy(image[(row - 2) * width + 2], brow[0] + 2,
             (width - 4) * sizeof *image);
    for (g = 0; g < 4; g++)
      brow[(g - 1) & 3] = brow[g];
  }
  memcpy(image[(row - 2) * width + 2], brow[0] + 2,
         (width - 4) * sizeof *image);
  memcpy(image[(row - 1) * width + 2], brow[1] + 2,
         (width - 4) * sizeof *image);
  free(brow[4]);
  free(code[0][0]);
}

Project: LibRaw

  static unsigned sgetn(int n, uchar *s)
  {
    unsigned result = 0;
    while (n-- > 0)
      result = (result << 8) | (*s++);
    return result;
  }

Project: LibRaw

void LibRaw::remove_zeroes()
{
  unsigned row, col, tot, n;
  int r, c;

  RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES, 0, 2);

  for (row = 0; row < height; row++)
    for (col = 0; col < width; col++)
      if (BAYER(row, col) == 0)
      {
        tot = n = 0;
        for (r = (int)row - 2; r <= (int)row + 2; r++)
          for (c = (int)col - 2; c <= (int)col + 2; c++)
            if (r >= 0 && r < height && c >= 0 && c < width &&
                FC(r, c) == FC(row, col) && BAYER(r, c))
              tot += (n++, BAYER(r, c));
        if (n)
          BAYER(row, col) = tot / n;
      }
  RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES, 1, 2);
}

Project: LibRaw

void LibRaw::init_fuji_block(struct fuji_compressed_block *info,
                             const struct fuji_compressed_params *params,
                             INT64 raw_offset, unsigned dsize)
{
  info->linealloc =
      (ushort *)calloc(sizeof(ushort), _ltotal * (params->line_width + 2));
  merror(info->linealloc, "init_fuji_block()");

  INT64 fsize = libraw_internal_data.internal_data.input->size();
  info->max_read_size =
      _min(unsigned(fsize - raw_offset), dsize); // Data size may be incorrect?
  info->fillbytes = 1;

  info->input = libraw_internal_data.internal_data.input;
  info->linebuf[_R0] = info->linealloc;
  for (int i = _R1; i <= _B4; i++)
    info->linebuf[i] = info->linebuf[i - 1] + params->line_width + 2;

  // init buffer
  info->cur_buf = (uchar *)malloc(XTRANS_BUF_SIZE);
  merror(info->cur_buf, "init_fuji_block()");
  info->cur_bit = 0;
  info->cur_pos = 0;
  info->cur_buf_offset = raw_offset;
  for (int j = 0; j < 3; j++)
    for (int i = 0; i < 41; i++)
    {
      info->grad_even[j][i].value1 = params->maxDiff;
      info->grad_even[j][i].value2 = 1;
      info->grad_odd[j][i].value1 = params->maxDiff;
      info->grad_odd[j][i].value2 = 1;
    }

  info->cur_buf_size = 0;
  fuji_fill_buffer(info);
}

Project: LibRaw

void LibRaw::parse_riff()
{
  unsigned i, size, end;
  char tag[4], date[64], month[64];
  static const char mon[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
                                  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  struct tm t;

  order = 0x4949;
  fread(tag, 4, 1, ifp);
  size = get4();
  end = ftell(ifp) + size;
  if (!memcmp(tag, "RIFF", 4) || !memcmp(tag, "LIST", 4))
  {
    int maxloop = 1000;
    get4();
    while (ftell(ifp) + 7 < end && !feof(ifp) && maxloop--)
      parse_riff();
  }
  else if (!memcmp(tag, "nctg", 4))
  {
    while (ftell(ifp) + 7 < end)
    {
      i = get2();
      size = get2();
      if ((i + 1) >> 1 == 10 && size == 20)
        get_timestamp(0);
      else
        fseek(ifp, size, SEEK_CUR);
    }
  }
  else if (!memcmp(tag, "IDIT", 4) && size < 64)
  {
    fread(date, 64, 1, ifp);
    date[size] = 0;
    memset(&t, 0, sizeof t);
    if (sscanf(date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday, &t.tm_hour,
               &t.tm_min, &t.tm_sec, &t.tm_year) == 6)
    {
      for (i = 0; i < 12 && strcasecmp(mon[i], month); i++)
        ;
      t.tm_mon = i;
      t.tm_year -= 1900;
      if (mktime(&t) > 0)
        timestamp = mktime(&t);
    }
  }
  else
    fseek(ifp, size, SEEK_CUR);
}

Project: LibRaw

void LibRaw::parse_rollei()
{
  char line[128], *val;
  struct tm t;

  fseek(ifp, 0, SEEK_SET);
  memset(&t, 0, sizeof t);
  do
  {
    line[0] = 0;
    if (!fgets(line, 128, ifp))
      break;
    if(!line[0]) break; // zero-length
    if ((val = strchr(line, '=')))
      *val++ = 0;
    else
      val = line + strbuflen(line);
    if (!strcmp(line, "DAT"))
      sscanf(val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year);
    if (!strcmp(line, "TIM"))
      sscanf(val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec);
    if (!strcmp(line, "HDR"))
      thumb_offset = atoi(val);
    if (!strcmp(line, "X  "))
      raw_width = atoi(val);
    if (!strcmp(line, "Y  "))
      raw_height = atoi(val);
    if (!strcmp(line, "TX "))
      thumb_width = atoi(val);
    if (!strcmp(line, "TY "))
      thumb_height = atoi(val);
    if (!strcmp(line, "APT"))
      aperture = atof(val);
    if (!strcmp(line, "SPE"))
      shutter = atof(val);
    if (!strcmp(line, "FOCLEN"))
      focal_len = atof(val);
    if (!strcmp(line, "BLKOFS"))
      black = atoi(val) +1;
    if (!strcmp(line, "ORI"))
      switch (atoi(val)) {
      case 1:
        flip = 6;
        break;
      case 2:
        flip = 3;
        break;
      case 3:
        flip = 5;
        break;
      }
    if (!strcmp(line, "CUTRECT")) {
      sscanf(val, "%hu %hu %hu %hu",
             &imgdata.sizes.raw_inset_crop.cleft,
             &imgdata.sizes.raw_inset_crop.ctop,
             &imgdata.sizes.raw_inset_crop.cwidth,
             &imgdata.sizes.raw_inset_crop.cheight);
    }
  } while (strncmp(line, "EOHD", 4));
  data_offset = thumb_offset + thumb_width * thumb_height * 2;
  t.tm_year -= 1900;
  t.tm_mon -= 1;
  if (mktime(&t) > 0)
    timestamp = mktime(&t);
  strcpy(make, "Rollei");
  strcpy(model, "d530flex");
  write_thumb = &LibRaw::rollei_thumb;
}

Project: LibRaw

  const char *libraw_version() { return LibRaw::version(); }

Project: LibRaw

void LibRaw::setCanonBodyFeatures(unsigned long long id)
{

  ilm.CamID = id;
  if ((id == 0x80000001ULL) || // 1D
      (id == 0x80000174ULL) || // 1D2
      (id == 0x80000232ULL) || // 1D2N
      (id == 0x80000169ULL) || // 1D3
      (id == 0x80000281ULL)    // 1D4
  )
  {
    ilm.CameraFormat = LIBRAW_FORMAT_APSH;
    ilm.CameraMount = LIBRAW_MOUNT_Canon_EF;
  }
  else if ((id == 0x80000167ULL) || // 1Ds
           (id == 0x80000188ULL) || // 1Ds2
           (id == 0x80000215ULL) || // 1Ds3
           (id == 0x80000269ULL) || // 1DX
           (id == 0x80000328ULL) || // 1DX2
           (id == 0x80000324ULL) || // 1DC
           (id == 0x80000213ULL) || // 5D
           (id == 0x80000218ULL) || // 5D2
           (id == 0x80000285ULL) || // 5D3
           (id == 0x80000349ULL) || // 5D4
           (id == 0x80000382ULL) || // 5DS
           (id == 0x80000401ULL) || // 5DS R
           (id == 0x80000302ULL) || // 6D
           (id == 0x80000406ULL)    // 6D Mark II

  )
  {
    ilm.CameraFormat = LIBRAW_FORMAT_FF;
    ilm.CameraMount = LIBRAW_MOUNT_Canon_EF;
  }
  else if ((id == 0x80000331ULL) || // M
           (id == 0x80000355ULL) || // M2
           (id == 0x03740000ULL) || // M3
           (id == 0x03840000ULL) || // M10
           (id == 0x03940000ULL) || // M5
           (id == 0x00000412ULL) || // M50
           (id == 0x04070000ULL) || // M6
           (id == 0x03980000ULL) || // M100
           (id == CanonID_EOS_M6_Mark_II)
  )
  {
    ilm.CameraFormat = LIBRAW_FORMAT_APSC;
    ilm.CameraMount = LIBRAW_MOUNT_Canon_EF_M;
  }
  else if ((id == 0x80000424ULL) || // EOS R
           (id == 0x80000433ULL)    // EOS RP
  )
  {
    ilm.CameraFormat = LIBRAW_FORMAT_FF;
    ilm.CameraMount = LIBRAW_MOUNT_Canon_RF;
  }
  else if ((id == 0x01140000ULL) || // D30
           (id == 0x01668000ULL) || // D60
           (id > 0x80000000ULL))
  {
    ilm.CameraFormat = LIBRAW_FORMAT_APSC;
    ilm.CameraMount = LIBRAW_MOUNT_Canon_EF;
  }
}

Project: LibRaw

	file_mapping() : map(0), fsize(0), fd(INVALID_HANDLE_VALUE), fd_map(INVALID_HANDLE_VALUE){}

Project: LibRaw

void LibRaw::blend_highlights()
{
  int clip = INT_MAX, row, col, c, i, j;
  static const float trans[2][4][4] = {
      {{1, 1, 1}, {1.7320508, -1.7320508, 0}, {-1, -1, 2}},
      {{1, 1, 1, 1}, {1, -1, 1, -1}, {1, 1, -1, -1}, {1, -1, -1, 1}}};
  static const float itrans[2][4][4] = {
      {{1, 0.8660254, -0.5}, {1, -0.8660254, -0.5}, {1, 0, 1}},
      {{1, 1, 1, 1}, {1, -1, 1, -1}, {1, 1, -1, -1}, {1, -1, -1, 1}}};
  float cam[2][4], lab[2][4], sum[2], chratio;

  if ((unsigned)(colors - 3) > 1)
    return;
  RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, 0, 2);
  FORCC if (clip > (i = 65535 * pre_mul[c])) clip = i;
  for (row = 0; row < height; row++)
    for (col = 0; col < width; col++)
    {
      FORCC if (image[row * width + col][c] > clip) break;
      if (c == colors)
        continue;
      FORCC
      {
        cam[0][c] = image[row * width + col][c];
        cam[1][c] = MIN(cam[0][c], clip);
      }
      for (i = 0; i < 2; i++)
      {
        FORCC for (lab[i][c] = j = 0; j < colors; j++) lab[i][c] +=
            trans[colors - 3][c][j] * cam[i][j];
        for (sum[i] = 0, c = 1; c < colors; c++)
          sum[i] += SQR(lab[i][c]);
      }
      chratio = sqrt(sum[1] / sum[0]);
      for (c = 1; c < colors; c++)
        lab[0][c] *= chratio;
      FORCC for (cam[0][c] = j = 0; j < colors; j++) cam[0][c] +=
          itrans[colors - 3][c][j] * lab[0][j];
      FORCC image[row * width + col][c] = cam[0][c] / colors;
    }
  RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, 1, 2);
}

Project: LibRaw

void write_ppm(unsigned width, unsigned height, unsigned short *bitmap,
               const char *fname)
{
  if (!bitmap)
    return;

  FILE *f = fopen(fname, "wb");
  if (!f)
    return;
  int bits = 16;
  fprintf(f, "P5\n%d %d\n%d\n", width, height, (1 << bits) - 1);
  unsigned char *data = (unsigned char *)bitmap;
  unsigned data_size = width * height * 2;
#define SWAP(a, b)                                                             \
  {                                                                            \
    a ^= b;                                                                    \
    a ^= (b ^= a);                                                             \
  }
  for (unsigned i = 0; i < data_size; i += 2)
    SWAP(data[i], data[i + 1]);
#undef SWAP
  fwrite(data, data_size, 1, f);
  fclose(f);
}

Project: LibRaw

static void DecodeFPDelta(unsigned char *input, unsigned char *output, int cols,
                          int channels, int bytesPerSample)
{
  DecodeDeltaBytes(input, cols * bytesPerSample, channels);
  int32_t rowIncrement = cols * channels;

  if (bytesPerSample == 2)
  {

#if LibRawBigEndian
    const unsigned char *input0 = input;
    const unsigned char *input1 = input + rowIncrement;
#else
    const unsigned char *input1 = input;
    const unsigned char *input0 = input + rowIncrement;
#endif
    for (int col = 0; col < rowIncrement; ++col)
    {
      output[0] = input0[col];
      output[1] = input1[col];
      output += 2;
    }
  }
  else if (bytesPerSample == 3)
  {
    const unsigned char *input0 = input;
    const unsigned char *input1 = input + rowIncrement;
    const unsigned char *input2 = input + rowIncrement * 2;
    for (int col = 0; col < rowIncrement; ++col)
    {
      output[0] = input0[col];
      output[1] = input1[col];
      output[2] = input2[col];
      output += 3;
    }
  }
  else
  {
#if LibRawBigEndian
    const unsigned char *input0 = input;
    const unsigned char *input1 = input + rowIncrement;
    const unsigned char *input2 = input + rowIncrement * 2;
    const unsigned char *input3 = input + rowIncrement * 3;
#else
    const unsigned char *input3 = input;
    const unsigned char *input2 = input + rowIncrement;
    const unsigned char *input1 = input + rowIncrement * 2;
    const unsigned char *input0 = input + rowIncrement * 3;
#endif
    for (int col = 0; col < rowIncrement; ++col)
    {
      output[0] = input0[col];
      output[1] = input1[col];
      output[2] = input2[col];
      output[3] = input3[col];
      output += 4;
    }
  }
}

Project: LibRaw

  int own_filtering_supported() { return 0; }

Project: LibRaw

  DllDef int libraw_get_raw_height(libraw_data_t *lr)
  {
    if (!lr)
      return EINVAL;
    return lr->sizes.raw_height;
  }

Project: LibRaw

int LibRaw::minolta_z2()
{
  int i, nz;
  char tail[424];

  fseek(ifp, -sizeof tail, SEEK_END);
  fread(tail, 1, sizeof tail, ifp);
  for (nz = i = 0; i < sizeof tail; i++)
    if (tail[i])
      nz++;
  return nz > 20;
}

Project: LibRaw

void LibRaw::x3f_dpq_interpolate_af_sd(int xstart, int ystart, int xend,
                                       int yend, int xstep, int ystep,
                                       int scale)
{
  unsigned short *image = (ushort *)imgdata.rawdata.color3_image;
  unsigned int rowpitch =
      imgdata.rawdata.sizes.raw_pitch / 2; // in 16-bit words
  // Interpolate single pixel
  for (int y = ystart; y < yend && y < imgdata.rawdata.sizes.height +
                                           imgdata.rawdata.sizes.top_margin;
       y += ystep)
  {
    uint16_t *row0 = &image[imgdata.sizes.raw_width * 3 * y]; // Наша строка
    uint16_t *row1 =
        &image[imgdata.sizes.raw_width * 3 * (y + 1)]; // Следующая строка
    uint16_t *row_minus =
        &image[imgdata.sizes.raw_width * 3 * (y - scale)]; // Строка выше
    uint16_t *row_plus =
        &image[imgdata.sizes.raw_width * 3 *
               (y + scale)]; // Строка ниже AF-point (scale=2 -> ниже row1
    uint16_t *row_minus1 = &image[imgdata.sizes.raw_width * 3 * (y - 1)];
    for (int x = xstart; x < xend && x < imgdata.rawdata.sizes.width +
                                             imgdata.rawdata.sizes.left_margin;
         x += xstep)
    {
      uint16_t *pixel00 = &row0[x * 3]; // Current pixel
      float sumR = 0.f, sumG = 0.f;
      float cnt = 0.f;
      for (int xx = -scale; xx <= scale; xx += scale)
      {
        sumR += row_minus[(x + xx) * 3];
        sumR += row_plus[(x + xx) * 3];
        sumG += row_minus[(x + xx) * 3 + 1];
        sumG += row_plus[(x + xx) * 3 + 1];
        cnt += 1.f;
        if (xx)
        {
          cnt += 1.f;
          sumR += row0[(x + xx) * 3];
          sumG += row0[(x + xx) * 3 + 1];
        }
      }
      pixel00[0] = sumR / 8.f;
      pixel00[1] = sumG / 8.f;

      if (scale == 2)
      {
        uint16_t *pixel0B = &row0[x * 3 + 3]; // right pixel
        uint16_t *pixel1B = &row1[x * 3 + 3]; // right pixel
        float sumG0 = 0, sumG1 = 0.f;
        float cnt = 0.f;
        for (int xx = -scale; xx <= scale; xx += scale)
        {
          sumG0 += row_minus1[(x + xx) * 3 + 2];
          sumG1 += row_plus[(x + xx) * 3 + 2];
          cnt += 1.f;
          if (xx)
          {
            sumG0 += row0[(x + xx) * 3 + 2];
            sumG1 += row1[(x + xx) * 3 + 2];
            cnt += 1.f;
          }
        }
        pixel0B[2] = sumG0 / cnt;
        pixel1B[2] = sumG1 / cnt;
      }

      //			uint16_t* pixel10 = &row1[x*3]; // Pixel below current
      //			uint16_t* pixel_bottom = &row_plus[x*3];
    }
  }
}

Project: LibRaw

int LibRaw_file_datastream::valid() { return f.get() ? 1 : 0; }

Project: LibRaw

void LibRaw::layer_thumb()
{
  int i, c;
  char *thumb, map[][4] = {"012", "102"};

  colors = thumb_misc >> 5 & 7;
  thumb_length = thumb_width * thumb_height;
  thumb = (char *)calloc(colors, thumb_length);
  merror(thumb, "layer_thumb()");
  fprintf(ofp, "P%d\n%d %d\n255\n", 5 + (colors >> 1), thumb_width,
          thumb_height);
  fread(thumb, thumb_length, colors, ifp);
  for (i = 0; i < thumb_length; i++)
    FORCC putc(thumb[i + thumb_length * (map[thumb_misc >> 8][c] - '0')], ofp);
  free(thumb);
}

Project: LibRaw

void DHT::make_greens()
{
#if defined(LIBRAW_USE_OPENMP)
#pragma omp parallel for schedule(guided)
#endif
  for (int i = 0; i < libraw.imgdata.sizes.iheight; ++i)
  {
    make_gline(i);
  }
}

Project: LibRaw

char *LibRaw_file_datastream::gets(char *str, int sz)
{
  LR_STREAM_CHK();
  std::istream is(f.get());
  is.getline(str, sz);
  if (is.fail())
    return 0;
  return str;
}

Project: LibRaw

void LibRaw::parse_cine()
{
  unsigned off_head, off_setup, off_image, i;

  order = 0x4949;
  fseek(ifp, 4, SEEK_SET);
  is_raw = get2() == 2;
  fseek(ifp, 14, SEEK_CUR);
  is_raw *= get4();
  off_head = get4();
  off_setup = get4();
  off_image = get4();
  timestamp = get4();
  if ((i = get4()))
    timestamp = i;
  fseek(ifp, off_head + 4, SEEK_SET);
  raw_width = get4();
  raw_height = get4();
  switch (get2(), get2())
  {
  case 8:
    load_raw = &LibRaw::eight_bit_load_raw;
    break;
  case 16:
    load_raw = &LibRaw::unpacked_load_raw;
  }
  fseek(ifp, off_setup + 792, SEEK_SET);
  strcpy(make, "CINE");
  sprintf(model, "%d", get4());
  fseek(ifp, 12, SEEK_CUR);
  switch ((i = get4()) & 0xffffff)
  {
  case 3:
    filters = 0x94949494;
    break;
  case 4:
    filters = 0x49494949;
    break;
  default:
    is_raw = 0;
  }
  fseek(ifp, 72, SEEK_CUR);
  switch ((get4() + 3600) % 360)
  {
  case 270:
    flip = 4;
    break;
  case 180:
    flip = 1;
    break;
  case 90:
    flip = 7;
    break;
  case 0:
    flip = 2;
  }
  cam_mul[0] = getreal(11);
  cam_mul[2] = getreal(11);
  maximum = ~((~0u) << get4());
  fseek(ifp, 668, SEEK_CUR);
  shutter = get4() / 1000000000.0;
  fseek(ifp, off_image, SEEK_SET);
  if (shot_select < is_raw)
    fseek(ifp, shot_select * 8, SEEK_CUR);
  data_offset = (INT64)get4() + 8;
  data_offset += (INT64)get4() << 32;
}

Project: LibRaw

void AAHD::combine_image()
{
  for (int i = 0, i_out = 0; i < libraw.imgdata.sizes.iheight; ++i)
  {
    int moff = nr_offset(i + nr_margin, nr_margin);
    for (int j = 0; j < libraw.imgdata.sizes.iwidth; j++, ++moff, ++i_out)
    {
      if (ndir[moff] & HOT)
      {
        int c = libraw.COLOR(i, j);
        rgb_ahd[1][moff][c] = rgb_ahd[0][moff][c] =
            libraw.imgdata.image[i_out][c];
      }
      if (ndir[moff] & VER)
      {
        libraw.imgdata.image[i_out][0] = rgb_ahd[1][moff][0];
        libraw.imgdata.image[i_out][3] = libraw.imgdata.image[i_out][1] =
            rgb_ahd[1][moff][1];
        libraw.imgdata.image[i_out][2] = rgb_ahd[1][moff][2];
      }
      else
      {
        libraw.imgdata.image[i_out][0] = rgb_ahd[0][moff][0];
        libraw.imgdata.image[i_out][3] = libraw.imgdata.image[i_out][1] =
            rgb_ahd[0][moff][1];
        libraw.imgdata.image[i_out][2] = rgb_ahd[0][moff][2];
      }
    }
  }
}

Project: LibRaw

void LibRaw::kodak_jpeg_load_raw()
{
  if (data_size < 1)
    throw LIBRAW_EXCEPTION_DECODE_JPEG;

  int row, col;
  struct jpeg_decompress_struct cinfo;
  struct jpeg_error_mgr pub;
  cinfo.err = jpeg_std_error(&pub);
  pub.error_exit = jpegErrorExit_k;

  unsigned char *jpg_buf = (unsigned char *)malloc(data_size);
  merror(jpg_buf, "kodak_jpeg_load_raw");
  unsigned char *pixel_buf = (unsigned char *)malloc(width * 3);
  jpeg_create_decompress(&cinfo);
  merror(pixel_buf, "kodak_jpeg_load_raw");

  fread(jpg_buf, data_size, 1, ifp);
  swab((char *)jpg_buf, (char *)jpg_buf, data_size);
  try
  {
    jpeg_mem_src(&cinfo, jpg_buf, data_size);
    int rc = jpeg_read_header(&cinfo, TRUE);
    if (rc != 1)
      throw LIBRAW_EXCEPTION_DECODE_JPEG;

    jpeg_start_decompress(&cinfo);
    if ((cinfo.output_width != width) || (cinfo.output_height * 2 != height) ||
        (cinfo.output_components != 3))
    {
      throw LIBRAW_EXCEPTION_DECODE_JPEG;
    }

    unsigned char *buf[1];
    buf[0] = pixel_buf;

    while (cinfo.output_scanline < cinfo.output_height)
    {
      checkCancel();
      row = cinfo.output_scanline * 2;
      jpeg_read_scanlines(&cinfo, buf, 1);
      unsigned char(*pixel)[3] = (unsigned char(*)[3])buf[0];
      for (col = 0; col < width; col += 2)
      {
        RAW(row + 0, col + 0) = pixel[col + 0][1] << 1;
        RAW(row + 1, col + 1) = pixel[col + 1][1] << 1;
        RAW(row + 0, col + 1) = pixel[col][0] + pixel[col + 1][0];
        RAW(row + 1, col + 0) = pixel[col][2] + pixel[col + 1][2];
      }
    }
  }
  catch (...)
  {
    jpeg_finish_decompress(&cinfo);
    jpeg_destroy_decompress(&cinfo);
    free(jpg_buf);
    free(pixel_buf);
    throw;
  }
  jpeg_finish_decompress(&cinfo);
  jpeg_destroy_decompress(&cinfo);
  free(jpg_buf);
  free(pixel_buf);
  maximum = 0xff << 1;
}

Project: LibRaw

int LibRaw::parse_jpeg(int offset)
{
  int len, save, hlen, mark;
  fseek(ifp, offset, SEEK_SET);
  if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8)
    return 0;

  while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda)
  {
    order = 0x4d4d;
    len = get2() - 2;
    save = ftell(ifp);
    if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9)
    {
      fgetc(ifp);
      raw_height = get2();
      raw_width = get2();
    }
    order = get2();
    hlen = get4();
    if (get4() == 0x48454150 && (save + hlen) >= 0 &&
        (save + hlen) <= ifp->size()) /* "HEAP" */
    {
      parse_ciff(save + hlen, len - hlen, 0);
    }
    if (parse_tiff(save + 6))
      apply_tiff();
    fseek(ifp, save + len, SEEK_SET);
  }
  return 1;
}

Project: LibRaw

void LibRaw::fuji_rotate() {}

Project: LibRaw

void LibRaw::ahd_interpolate_green_h_and_v(
    int top, int left, ushort (*out_rgb)[LIBRAW_AHD_TILE][LIBRAW_AHD_TILE][3])
{
  int row, col;
  int c, val;
  ushort(*pix)[4];
  const int rowlimit = MIN(top + LIBRAW_AHD_TILE, height - 2);
  const int collimit = MIN(left + LIBRAW_AHD_TILE, width - 2);

  for (row = top; row < rowlimit; row++)
  {
    col = left + (FC(row, left) & 1);
    for (c = FC(row, col); col < collimit; col += 2)
    {
      pix = image + row * width + col;
      val =
          ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >>
          2;
      out_rgb[0][row - top][col - left][1] = ULIM(val, pix[-1][1], pix[1][1]);
      val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 -
             pix[-2 * width][c] - pix[2 * width][c]) >>
            2;
      out_rgb[1][row - top][col - left][1] =
          ULIM(val, pix[-width][1], pix[width][1]);
    }
  }
}

Project: LibRaw
File: libraw_cxx.cpp

int LibRaw::is_coolscan_nef()
{
  return load_raw == &LibRaw::nikon_coolscan_load_raw;
}

Project: LibRaw

  DllDef float libraw_get_cam_mul(libraw_data_t *lr, int index)
  {
    if (!lr)
      return EINVAL;
    return lr->color.cam_mul[LIM(index, 0, 3)];
  }

Project: LibRaw

unsigned LibRaw::get4()
{
  uchar str[4] = {0xff, 0xff, 0xff, 0xff};
  fread(str, 1, 4, ifp);
  return sget4(str);
}

Project: LibRaw

void LibRaw::parseNikonMakernote(int base, int uptag, unsigned dng_writer)
{
#define icWB imgdata.color.WB_Coeffs

  unsigned offset = 0, entries, tag, type, len, save;

  unsigned c, i;
  uchar *LensData_buf;
  uchar ColorBalanceData_buf[324];
  int ColorBalanceData_ready = 0;
  uchar ci, cj, ck;
  unsigned serial = 0;
  unsigned custom_serial = 0;
  unsigned LensData_len = 0;

  short morder, sorder = order;
  char buf[10];
  INT64 fsize = ifp->size();

  fread(buf, 1, 10, ifp);

  if (!strcmp(buf, "Nikon"))
  {
    if (buf[6] != '\2')
      return;
    base = ftell(ifp);
    order = get2();
    if (get2() != 42)
      goto quit;
    offset = get4();
    fseek(ifp, offset - 8, SEEK_CUR);
  }
  else
  {
    fseek(ifp, -10, SEEK_CUR);
  }

  entries = get2();
  if (entries > 1000)
    return;
  morder = order;

  while (entries--)
  {
    order = morder;
    tiff_get(base, &tag, &type, &len, &save);

    INT64 pos = ifp->tell();
    if (len > 8 && pos + len > 2 * fsize)
    {
      fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
      continue;
    }
    tag |= uptag << 16;
    if (len > 100 * 1024 * 1024)
      goto next; // 100Mb tag? No!

    if (tag == 0x0002)
    {
      if (!iso_speed)
        iso_speed = (get2(), get2());
    }
    else if (tag == 0x000a)
    {
      ilm.LensMount = ilm.CameraMount = LIBRAW_MOUNT_FixedLens;
      ilm.FocalType = LIBRAW_FT_ZOOM_LENS;
    }
    else if ((tag == 0x000c) && (len == 4) && (type == 5))
    {
      cam_mul[0] = getreal(type);
      cam_mul[2] = getreal(type);
      cam_mul[1] = getreal(type);
      cam_mul[3] = getreal(type);
    }
    else if (tag == 0x0011)
    {
      if (is_raw)
      {
        fseek(ifp, get4() + base, SEEK_SET);
        parse_tiff_ifd(base);
      }
    }
    else if (tag == 0x0012)
    {
      ci = fgetc(ifp);
      cj = fgetc(ifp);
      ck = fgetc(ifp);
      if (ck)
        imgdata.makernotes.common.FlashEC = (float)(ci * cj) / (float)ck;
    }
    else if (tag == 0x0014)
    {
      if (type == 7)
      {
        if (len == 2560)
        { // E5400, E8400, E8700, E8800
          fseek(ifp, 0x4e0L, SEEK_CUR);
          order = 0x4d4d;
          cam_mul[0] = get2() / 256.0;
          cam_mul[2] = get2() / 256.0;
          cam_mul[1] = cam_mul[3] = 1.0;
          icWB[LIBRAW_WBI_Auto][0] = get2();
          icWB[LIBRAW_WBI_Auto][2] = get2();
          icWB[LIBRAW_WBI_Daylight][0] = get2();
          icWB[LIBRAW_WBI_Daylight][2] = get2();
          fseek(ifp, 0x18L, SEEK_CUR);
          icWB[LIBRAW_WBI_Tungsten][0] = get2();
          icWB[LIBRAW_WBI_Tungsten][2] = get2();
          fseek(ifp, 0x18L, SEEK_CUR);
          icWB[LIBRAW_WBI_FL_W][0] = get2();
          icWB[LIBRAW_WBI_FL_W][2] = get2();
          icWB[LIBRAW_WBI_FL_N][0] = get2();
          icWB[LIBRAW_WBI_FL_N][2] = get2();
          icWB[LIBRAW_WBI_FL_D][0] = get2();
          icWB[LIBRAW_WBI_FL_D][2] = get2();
          icWB[LIBRAW_WBI_Cloudy][0] = get2();
          icWB[LIBRAW_WBI_Cloudy][2] = get2();
          fseek(ifp, 0x18L, SEEK_CUR);
          icWB[LIBRAW_WBI_Flash][0] = get2();
          icWB[LIBRAW_WBI_Flash][2] = get2();

          icWB[LIBRAW_WBI_Auto][1] = icWB[LIBRAW_WBI_Auto][3] =
              icWB[LIBRAW_WBI_Daylight][1] = icWB[LIBRAW_WBI_Daylight][3] =
                  icWB[LIBRAW_WBI_Tungsten][1] = icWB[LIBRAW_WBI_Tungsten][3] =
                      icWB[LIBRAW_WBI_FL_W][1] = icWB[LIBRAW_WBI_FL_W][3] =
                          icWB[LIBRAW_WBI_FL_N][1] = icWB[LIBRAW_WBI_FL_N][3] =
                              icWB[LIBRAW_WBI_FL_D][1] =
                                  icWB[LIBRAW_WBI_FL_D][3] =
                                      icWB[LIBRAW_WBI_Cloudy][1] =
                                          icWB[LIBRAW_WBI_Cloudy][3] =
                                              icWB[LIBRAW_WBI_Flash][1] =
                                                  icWB[LIBRAW_WBI_Flash][3] =
                                                      256;

          if (strncmp(model, "E8700", 5))
          {
            fseek(ifp, 0x18L, SEEK_CUR);
            icWB[LIBRAW_WBI_Shade][0] = get2();
            icWB[LIBRAW_WBI_Shade][2] = get2();
            icWB[LIBRAW_WBI_Shade][1] = icWB[LIBRAW_WBI_Shade][3] = 256;
          }
        }
        else if (len == 1280)
        { // E5000, E5700
          cam_mul[0] = cam_mul[1] = cam_mul[2] = cam_mul[3] = 1.0;
        }
        else
        {
          fread(buf, 1, 10, ifp);
          if (!strncmp(buf, "NRW ", 4))
          { // P6000, P7000, P7100, B700, P1000
            if (!strcmp(buf + 4, "0100"))
            { // P6000
              fseek(ifp, 0x13deL, SEEK_CUR);
              cam_mul[0] = get4() << 1;
              cam_mul[1] = get4();
              cam_mul[3] = get4();
              cam_mul[2] = get4() << 1;
              Nikon_NRW_WBtag(LIBRAW_WBI_Daylight, 0);
              Nikon_NRW_WBtag(LIBRAW_WBI_Cloudy, 0);
              fseek(ifp, 0x10L, SEEK_CUR);
              Nikon_NRW_WBtag(LIBRAW_WBI_Tungsten, 0);
              Nikon_NRW_WBtag(LIBRAW_WBI_FL_W, 0);
              Nikon_NRW_WBtag(LIBRAW_WBI_Flash, 0);
              fseek(ifp, 0x10L, SEEK_CUR);
              Nikon_NRW_WBtag(LIBRAW_WBI_Custom, 0);
              Nikon_NRW_WBtag(LIBRAW_WBI_Auto, 0);
            }
            else
            { // P7000, P7100, B700, P1000
              fseek(ifp, 0x16L, SEEK_CUR);
              black = get2();
              if (cam_mul[0] < 0.1f)
              {
                fseek(ifp, 0x16L, SEEK_CUR);
                cam_mul[0] = get4() << 1;
                cam_mul[1] = get4();
                cam_mul[3] = get4();
                cam_mul[2] = get4() << 1;
              }
              else
              {
                fseek(ifp, 0x26L, SEEK_CUR);
              }
              if (len != 332)
              { // not A1000
                Nikon_NRW_WBtag(LIBRAW_WBI_Daylight, 1);
                Nikon_NRW_WBtag(LIBRAW_WBI_Cloudy, 1);
                Nikon_NRW_WBtag(LIBRAW_WBI_Shade, 1);
                Nikon_NRW_WBtag(LIBRAW_WBI_Tungsten, 1);
                Nikon_NRW_WBtag(LIBRAW_WBI_FL_W, 1);
                Nikon_NRW_WBtag(LIBRAW_WBI_FL_N, 1);
                Nikon_NRW_WBtag(LIBRAW_WBI_FL_D, 1);
                Nikon_NRW_WBtag(LIBRAW_WBI_HT_Mercury, 1);
                fseek(ifp, 0x14L, SEEK_CUR);
                Nikon_NRW_WBtag(LIBRAW_WBI_Custom, 1);
                Nikon_NRW_WBtag(LIBRAW_WBI_Auto, 1);
              }
              else
              {
                fseek(ifp, 0xc8L, SEEK_CUR);
                Nikon_NRW_WBtag(LIBRAW_WBI_Auto, 1);
              }
            }
          }
        }
      }
    }
    else if (tag == 0x001b)
    {
      imNikon.HighSpeedCropFormat = get2();
      imNikon.SensorHighSpeedCrop.cwidth = get2();
      imNikon.SensorHighSpeedCrop.cheight = get2();
      imNikon.SensorWidth = get2();
      imNikon.SensorHeight = get2();
      imNikon.SensorHighSpeedCrop.cleft = get2();
      imNikon.SensorHighSpeedCrop.ctop = get2();
      switch (imNikon.HighSpeedCropFormat)
      {
      case 0:
      case 1:
      case 2:
      case 4:
        imgdata.sizes.raw_inset_crop.aspect = LIBRAW_IMAGE_ASPECT_3to2;
        break;
      case 11:
        ilm.CameraFormat = LIBRAW_FORMAT_FF;
        imgdata.sizes.raw_inset_crop.aspect = LIBRAW_IMAGE_ASPECT_3to2;
        break;
      case 12:
        ilm.CameraFormat = LIBRAW_FORMAT_APSC;
        imgdata.sizes.raw_inset_crop.aspect = LIBRAW_IMAGE_ASPECT_3to2;
        break;
      case 3:
        imgdata.sizes.raw_inset_crop.aspect = LIBRAW_IMAGE_ASPECT_5to4;
        break;
      case 6:
        imgdata.sizes.raw_inset_crop.aspect = LIBRAW_IMAGE_ASPECT_16to9;
        break;
      case 17:
        imgdata.sizes.raw_inset_crop.aspect = LIBRAW_IMAGE_ASPECT_1to1;
        break;
      default:
        imgdata.sizes.raw_inset_crop.aspect = LIBRAW_IMAGE_ASPECT_OTHER;
        break;
      }
    }
    else if (tag == 0x001d)
    { // serial number
      if (len > 0)
      {
        int model_len = (int)strbuflen(model);
        while ((c = fgetc(ifp)) && (len-- > 0) && (c != EOF))
        {
          if ((!custom_serial) && (!isdigit(c)))
          {
            if (((model_len == 3) && !strcmp(model, "D50")) ||
                ((model_len >= 4) && !isalnum(model[model_len - 4]) &&
                 !strncmp(&model[model_len - 3], "D50", 3)))
            {
              custom_serial = 34;
            }
            else
            {
              custom_serial = 96;
            }
            break;
          }
          serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10);
        }
        if (!imgdata.shootinginfo.BodySerial[0])
          sprintf(imgdata.shootinginfo.BodySerial, "%d", serial);
      }
    }
    else if (tag == 0x0025)
    {
      if (!iso_speed || (iso_speed == 65535))
      {
        iso_speed =
            int(100.0 *
                libraw_powf64l(2.0f, double((uchar)fgetc(ifp)) / 12.0 - 5.0));
      }
    }
    else if (tag == 0x003b)
    { // WB for multi-exposure (ME); all 1s for regular exposures
      imNikon.ME_WB[0] = getreal(type);
      imNikon.ME_WB[2] = getreal(type);
      imNikon.ME_WB[1] = getreal(type);
      imNikon.ME_WB[3] = getreal(type);
    }
    else if (tag == 0x003d)
    { // not corrected for file bitcount, to be patched in open_datastream
      FORC4 cblack[c ^ c >> 1] = get2();
      i = cblack[3];
      FORC3 if (i > cblack[c]) i = cblack[c];
      FORC4 cblack[c] -= i;
      black += i;
    }
    else if (tag == 0x0045)
    { /* upper left pixel (x,y), size (width,height) */
      imgdata.sizes.raw_inset_crop.cleft = get2();
      imgdata.sizes.raw_inset_crop.ctop = get2();
      imgdata.sizes.raw_inset_crop.cwidth = get2();
      imgdata.sizes.raw_inset_crop.cheight = get2();
    }
    else if (tag == 0x0082)
    { // lens attachment
      stmread(ilm.Attachment, len, ifp);
    }
    else if (tag == 0x0083)
    { // lens type
      imgdata.lens.nikon.LensType = fgetc(ifp);
    }
    else if (tag == 0x0084)
    { // lens
      ilm.MinFocal = getreal(type);
      ilm.MaxFocal = getreal(type);
      ilm.MaxAp4MinFocal = getreal(type);
      ilm.MaxAp4MaxFocal = getreal(type);
    }
    else if (tag == 0x008b)
    { // lens f-stops
      ci = fgetc(ifp);
      cj = fgetc(ifp);
      ck = fgetc(ifp);
      if (ck)
      {
        imgdata.lens.nikon.LensFStops = ci * cj * (12 / ck);
        ilm.LensFStops = (float)imgdata.lens.nikon.LensFStops / 12.0f;
      }
    }
    else if ((tag == 0x008c) || (tag == 0x0096))
    {
      meta_offset = ftell(ifp);
    }
    else if (tag == 0x0093)
    {
      imNikon.NEFCompression = i = get2();
      if ((i == 7) || (i == 9))
      {
        ilm.LensMount = LIBRAW_MOUNT_FixedLens;
        ilm.CameraMount = LIBRAW_MOUNT_FixedLens;
      }
    }
    else if (tag == 0x0097)
    { // ver97
      FORC4 imNikon.ColorBalanceVersion =
          imNikon.ColorBalanceVersion * 10 + fgetc(ifp) - '0';
      switch (imNikon.ColorBalanceVersion)
      {
      case 100: // NIKON D100
        fseek(ifp, 0x44L, SEEK_CUR);
        FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2();
        break;
      case 102: // NIKON D2H
        fseek(ifp, 0x6L, SEEK_CUR);
        FORC4 cam_mul[c ^ (c >> 1)] = get2();
        break;
      case 103: // NIKON D70, D70s
        fseek(ifp, 0x10L, SEEK_CUR);
        FORC4 cam_mul[c] = get2();
      }
      if (imNikon.ColorBalanceVersion >= 200)
      {
        /*
        204: NIKON D2X, D2Xs
        205: NIKON D50
        206: NIKON D2Hs
        207: NIKON D200
        208: NIKON D40, D40X, D80
        209: NIKON D3, D3X, D300, D700
        210: NIKON D60
        211: NIKON D90, D5000
        212: NIKON D300S
        213: NIKON D3000
        214: NIKON D3S
        215: NIKON D3100
        216: NIKON D5100, D7000
        217: NIKON D4, D600, D800, D800E, D3200
        -= unknown =-
        218: NIKON D5200, D7100
        219: NIKON D5300
        220: NIKON D610, Df
        221: NIKON D3300
        222: NIKON D4S
        223: NIKON D750, D810
        224: NIKON D3400, D3500, D5500, D5600, D7200
        225: NIKON D5, D500
        226: NIKON D7500
        227: NIKON D850
         */
        if (imNikon.ColorBalanceVersion != 205)
        {
          fseek(ifp, 0x118L, SEEK_CUR);
        }
        ColorBalanceData_ready =
            (fread(ColorBalanceData_buf, 324, 1, ifp) == 1);
      }
      if ((imNikon.ColorBalanceVersion >= 400) &&
          (imNikon.ColorBalanceVersion <= 405))
      { // 1 J1, 1 V1, 1 J2, 1 V2, 1 J3, 1 S1, 1 AW1, 1 S2, 1 J4, 1 V3, 1 J5
        ilm.CameraFormat = LIBRAW_FORMAT_1INCH;
        ilm.CameraMount = LIBRAW_MOUNT_Nikon_CX;
      }
      else if ((imNikon.ColorBalanceVersion >= 500) &&
               (imNikon.ColorBalanceVersion <= 502))
      { // P7700, P7800, P330, P340
        ilm.CameraMount = ilm.LensMount = LIBRAW_MOUNT_FixedLens;
        ilm.FocalType = LIBRAW_FT_ZOOM_LENS;
      }
      else if (imNikon.ColorBalanceVersion == 601)
      { // Coolpix A
        ilm.CameraFormat = ilm.LensFormat = LIBRAW_FORMAT_APSC;
        ilm.CameraMount = ilm.LensMount = LIBRAW_MOUNT_FixedLens;
        ilm.FocalType = LIBRAW_FT_PRIME_LENS;
      }
    }
    else if (tag == 0x0098)
    { // contains lens data
      FORC4 imNikon.LensDataVersion =
          imNikon.LensDataVersion * 10 + fgetc(ifp) - '0';
      switch (imNikon.LensDataVersion)
      {
      case 100:
        LensData_len = 9;
        break;
      case 101:
      case 201: // encrypted, starting from v.201
      case 202:
      case 203:
        LensData_len = 15;
        break;
      case 204:
        LensData_len = 16;
        break;
      case 400:
        LensData_len = 459;
        break;
      case 401:
        LensData_len = 590;
        break;
      case 402:
        LensData_len = 509;
        break;
      case 403:
        LensData_len = 879;
        break;
      case 800:
        LensData_len = 58;
        break;
      }
      if (LensData_len)
      {
        LensData_buf = (uchar *)malloc(LensData_len);
        fread(LensData_buf, LensData_len, 1, ifp);
      }
    }
    else if (tag == 0x00a0)
    {
      stmread(imgdata.shootinginfo.BodySerial, len, ifp);
    }
    else if (tag == 0x00a7)
    { // shutter count
      imNikon.key = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp);
      if (custom_serial)
      {
        ci = xlat[0][custom_serial];
      }
      else
      {
        ci = xlat[0][serial & 0xff];
      }
      cj = xlat[1][imNikon.key];
      ck = 0x60;
      if (((unsigned)(imNikon.ColorBalanceVersion - 200) < 18) &&
          ColorBalanceData_ready)
      {
        for (i = 0; i < 324; i++)
          ColorBalanceData_buf[i] ^= (cj += ci * ck++);
        i = "66666>666;6A;:;555"[imNikon.ColorBalanceVersion - 200] - '0';
        FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] =
            sget2(ColorBalanceData_buf + (i & -2) + c * 2);
      }

      if (LensData_len)
      {
        if (imNikon.LensDataVersion > 200)
        {
          for (i = 0; i < LensData_len; i++)
          {
            LensData_buf[i] ^= (cj += ci * ck++);
          }
        }
        processNikonLensData(LensData_buf, LensData_len);
        LensData_len = 0;
        free(LensData_buf);
      }
    }
    else if (tag == 0x00a8)
    { // contains flash data
      FORC4 imNikon.FlashInfoVersion =
          imNikon.FlashInfoVersion * 10 + fgetc(ifp) - '0';
    }
    else if (tag == 0x00b0)
    {
      get4(); // ME (multi-exposure) tag version, 4 symbols
      imNikon.ExposureMode = get4();
      imNikon.nMEshots = get4();
      imNikon.MEgainOn = get4();
    }
    else if (tag == 0x00b9)
    {
      imNikon.AFFineTune = fgetc(ifp);
      imNikon.AFFineTuneIndex = fgetc(ifp);
      imNikon.AFFineTuneAdj = (int8_t)fgetc(ifp);
    }
    else if ((tag == 0x0100) && (type == 7))
    {
      thumb_offset = ftell(ifp);
      thumb_length = len;
    }
    else if (tag == 0x0e01)
    { /* Nikon Software / in-camera edit Note */
      int loopc = 0;
      int WhiteBalanceAdj_active = 0;
      order = 0x4949;
      fseek(ifp, 22, SEEK_CUR);
      for (offset = 22; offset + 22 < len; offset += 22 + i)
      {
        if (loopc++ > 1024)
          throw LIBRAW_EXCEPTION_IO_CORRUPT;
        tag = get4();
        fseek(ifp, 14, SEEK_CUR);
        i = get4() - 4;

        if (tag == 0x76a43204)
        {
          WhiteBalanceAdj_active = fgetc(ifp);
        }
        else if (tag == 0xbf3c6c20)
        {
          if (WhiteBalanceAdj_active)
          {
            union {
              double dbl;
              unsigned long long lng;
            } un;
            un.dbl = getreal(12);
            if ((un.lng != 0x3FF0000000000000ULL) &&
                (un.lng != 0x000000000000F03FULL))
            {
              cam_mul[0] = un.dbl;
              cam_mul[2] = getreal(12);
              cam_mul[1] = cam_mul[3] = 1.0;
              i -= 16;
            }
            else
              i -= 8;
          }
          fseek(ifp, i, SEEK_CUR);
        }
        else if (tag == 0x76a43207)
        {
          flip = get2();
        }
        else
        {
          fseek(ifp, i, SEEK_CUR);
        }
      }
    }
    else if (tag == 0x0e22)
    {
      FORC4 imNikon.NEFBitDepth[c] = get2();
    }
  next:
    fseek(ifp, save, SEEK_SET);
  }
quit:
  order = sorder;
#undef icWB
}

Project: LibRaw
File: libraw_cxx.cpp

  void default_memory_callback(void *, const char *file, const char *where)
  {
    fprintf(stderr, "%s: Out of memory in %s\n", file ? file : "unknown file",
            where);
  }

Project: LibRaw

void LibRaw::copy_fuji_uncropped(unsigned short cblack[4],
				 unsigned short *dmaxp) {}

Project: LibRaw

void LibRaw::Nikon_NRW_WBtag(int wb, int skip)
{

#define icWB imgdata.color.WB_Coeffs
  int r, g0, g1, b;
  if (skip)
    get4(); // skip wb "CCT", it is not unique
  r = get4();
  g0 = get4();
  g1 = get4();
  b = get4();
  if (r && g0 && g1 && b)
  {
    icWB[wb][0] = r << 1;
    icWB[wb][1] = g0;
    icWB[wb][2] = b << 1;
    icWB[wb][3] = g1;
  }
  return;
#undef icWB
}

Project: LibRaw

void LibRaw::tiff_set(struct tiff_hdr *th, ushort *ntag, ushort tag,
                      ushort type, int count, int val)
{
  struct libraw_tiff_tag *tt;
  int c;

  tt = (struct libraw_tiff_tag *)(ntag + 1) + (*ntag)++;
  tt->val.i = val;
  if (type == 1 && count <= 4)
    FORC(4) tt->val.c[c] = val >> (c << 3);
  else if (type == 2)
  {
    count = strnlen((char *)th + val, count - 1) + 1;
    if (count <= 4)
      FORC(4) tt->val.c[c] = ((char *)th)[val + c];
  }
  else if (type == 3 && count <= 2)
    FORC(2) tt->val.s[c] = val >> (c << 4);
  tt->count = count;
  tt->type = type;
  tt->tag = tag;
}

Project: LibRaw

void create_mapping(struct file_mapping& data, const std::string& fn)
{
#ifdef LIBRAW_WIN32_CALLS
	std::wstring fpath(fn.begin(), fn.end());
	if ((data.fd = CreateFileW(fpath.c_str(), GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0)) == INVALID_HANDLE_VALUE) return;
	LARGE_INTEGER fs;
	if (!GetFileSizeEx(data.fd, &fs)) return;
	data.fsize = fs.QuadPart;
	if ((data.fd_map = ::CreateFileMapping(data.fd, 0, PAGE_READONLY, fs.HighPart, fs.LowPart, 0)) == INVALID_HANDLE_VALUE) return;
	data.map = MapViewOfFile(data.fd_map, FILE_MAP_READ, 0, 0, data.fsize);
#else
	struct stat stt;
	if ((data.fd = open(fn.c_str(), O_RDONLY)) < 0) return;
	if (fstat(data.fd, &stt) != 0) return;
	data.fsize = stt.st_size;
	data.map = mmap(0, data.fsize, PROT_READ | PROT_WRITE, MAP_PRIVATE, data.fd, 0);
	return;
#endif
}

Project: LibRaw

void print_verbose(FILE* outfile, LibRaw& MyCoolRawProcessor, std::string& fn)
{
	id2hr_t *MountName, *FormatName, *Aspect, *Crop, *DriveMode;
	int ret;

	if ((ret = MyCoolRawProcessor.adjust_sizes_info_only()))
	{
		fprintf(outfile, "Cannot decode %s: %s\n", fn.c_str(), libraw_strerror(ret));
		return; // no recycle, open_file will recycle
	}

	fprintf(outfile, "\nFilename: %s\n", fn.c_str());
	if (C.OriginalRawFileName[0])
		fprintf(outfile, "OriginalRawFileName: =%s=\n", C.OriginalRawFileName);
	fprintf(outfile, "Timestamp: %s", ctime(&(P2.timestamp)));
	fprintf(outfile, "Camera: %s %s ID: 0x%llx\n", P1.make, P1.model, mnLens.CamID);
	fprintf(outfile, "Normalized Make/Model: =%s/%s= ", P1.normalized_make,
		P1.normalized_model);
	fprintf(outfile, "CamMaker ID: %d, ", P1.maker_index);
	const char *CamMakerName = LibRaw::cameramakeridx2maker(P1.maker_index);
	if (CamMakerName)
		fprintf(outfile, "%s\n", CamMakerName);
	else
		fprintf(outfile, "Undefined\n");
	{
		int i = 0;
		char sep[] = ", ";
		if (C.UniqueCameraModel[0]) {
			i++;
			fprintf(outfile, "UniqueCameraModel: =%s=", C.UniqueCameraModel);
		}
		if (C.LocalizedCameraModel[0]) {
			if (i) {
				fprintf(outfile, "%s", sep);
				i++;
			}
			fprintf(outfile, "LocalizedCameraModel: =%s=", C.LocalizedCameraModel);
		}
		if (i) {
			fprintf(outfile, "\n");
			i = 0;
		}
		if (C.ImageUniqueID[0]) {
			if (i) fprintf(outfile, "%s", sep);
			i++;
			fprintf(outfile, "ImageUniqueID: =%s=", C.ImageUniqueID);
		}
		if (C.RawDataUniqueID[0]) {
			if (i) fprintf(outfile, "%s", sep);
			i++;
			fprintf(outfile, "RawDataUniqueID: =%s=", C.RawDataUniqueID);
		}
		if (i) fprintf(outfile, "\n");
	}

	if (ShootingInfo.BodySerial[0] && strcmp(ShootingInfo.BodySerial, "0"))
	{
		trimSpaces(ShootingInfo.BodySerial);
		fprintf(outfile, "Body#: %s", ShootingInfo.BodySerial);
	}
	else if (C.model2[0] && (!strncasecmp(P1.normalized_make, "Kodak", 5)))
	{
		trimSpaces(C.model2);
		fprintf(outfile, "Body#: %s", C.model2);
	}
	if (ShootingInfo.InternalBodySerial[0])
	{
		trimSpaces(ShootingInfo.InternalBodySerial);
		fprintf(outfile, " BodyAssy#: %s", ShootingInfo.InternalBodySerial);
	}
	if (exifLens.LensSerial[0])
	{
		trimSpaces(exifLens.LensSerial);
		fprintf(outfile, " Lens#: %s", exifLens.LensSerial);
	}
	if (exifLens.InternalLensSerial[0])
	{
		trimSpaces(exifLens.InternalLensSerial);
		fprintf(outfile, " LensAssy#: %s", exifLens.InternalLensSerial);
	}
	if (P2.artist[0])
		fprintf(outfile, " Owner: %s\n", P2.artist);
	if (P1.dng_version)
	{
		fprintf(outfile, " DNG Version: ");
		for (int i = 24; i >= 0; i -= 8)
			fprintf(outfile, "%d%c", P1.dng_version >> i & 255, i ? '.' : '\n');
	}
	fprintf(outfile, "\nEXIF:\n");
	fprintf(outfile, "\tMinFocal: %0.1f mm\n", exifLens.MinFocal);
	fprintf(outfile, "\tMaxFocal: %0.1f mm\n", exifLens.MaxFocal);
	fprintf(outfile, "\tMaxAp @MinFocal: f/%0.1f\n", exifLens.MaxAp4MinFocal);
	fprintf(outfile, "\tMaxAp @MaxFocal: f/%0.1f\n", exifLens.MaxAp4MaxFocal);
	fprintf(outfile, "\tMaxAperture @CurFocal: f/%0.1f\n", exifLens.EXIF_MaxAp);
	fprintf(outfile, "\tFocalLengthIn35mmFormat: %d mm\n",
		exifLens.FocalLengthIn35mmFormat);
	fprintf(outfile, "\tLensMake: %s\n", exifLens.LensMake);
	fprintf(outfile, "\tLens: %s\n", exifLens.Lens);
	fprintf(outfile, "\n");

	fprintf(outfile, "\nMakernotes:\n");
	fprintf(outfile, "\tDriveMode: %d\n", ShootingInfo.DriveMode);
	fprintf(outfile, "\tFocusMode: %d\n", ShootingInfo.FocusMode);
	fprintf(outfile, "\tMeteringMode: %d\n", ShootingInfo.MeteringMode);
	fprintf(outfile, "\tAFPoint: %d\n", ShootingInfo.AFPoint);
	fprintf(outfile, "\tExposureMode: %d\n", ShootingInfo.ExposureMode);
	fprintf(outfile, "\tExposureProgram: %d\n", ShootingInfo.ExposureProgram);
	fprintf(outfile, "\tImageStabilization: %d\n", ShootingInfo.ImageStabilization);
	if (mnLens.body[0])
	{
		fprintf(outfile, "\tHost Body: %s\n", mnLens.body);
	}
	if (Hasselblad.CaptureSequenceInitiator[0])
	{
		fprintf(outfile, "\tInitiator: %s\n", Hasselblad.CaptureSequenceInitiator);
	}
	if (Hasselblad.SensorUnitConnector[0])
	{
		fprintf(outfile, "\tSU Connector: %s\n", Hasselblad.SensorUnitConnector);
	}
	fprintf(outfile, "\tCameraFormat: %d, ", mnLens.CameraFormat);
	FormatName = lookup_id2hr(mnLens.CameraFormat, FormatNames, nFormats);
	if (FormatName)
		fprintf(outfile, "%s\n", FormatName->name);
	else
		fprintf(outfile, "Unknown\n");

	if (!strncasecmp(P1.make, "Nikon", 5) && Nikon.SensorHighSpeedCrop.cwidth)
	{
		fprintf(outfile, "\tNikon crop: %d, ", Nikon.HighSpeedCropFormat);
		Crop = lookup_id2hr(Nikon.HighSpeedCropFormat, NikonCrops, nNikonCrops);
		if (Crop)
			fprintf(outfile, "%s\n", Crop->name);
		else
			fprintf(outfile, "Unknown\n");
		fprintf(outfile, "\tSensor used area %d x %d; crop from: %d x %d at top left "
			"pixel: (%d, %d)\n",
			Nikon.SensorWidth, Nikon.SensorHeight,
			Nikon.SensorHighSpeedCrop.cwidth,
			Nikon.SensorHighSpeedCrop.cheight,
			Nikon.SensorHighSpeedCrop.cleft, Nikon.SensorHighSpeedCrop.ctop);
	}

	fprintf(outfile, "\tCameraMount: %d, ", mnLens.CameraMount);
	MountName = lookup_id2hr(mnLens.CameraMount, MountNames, nMounts);
	if (MountName)
		fprintf(outfile, "%s\n", MountName->name);
	else
		fprintf(outfile, "Unknown\n");

	if (mnLens.LensID == -1)
		fprintf(outfile, "\tLensID: n/a\n");
	else
		fprintf(outfile, "\tLensID: %llu 0x%0llx\n", mnLens.LensID, mnLens.LensID);

	fprintf(outfile, "\tLens: %s\n", mnLens.Lens);
	fprintf(outfile, "\tLensFormat: %d, ", mnLens.LensFormat);
	FormatName = lookup_id2hr(mnLens.LensFormat, FormatNames, nFormats);
	if (FormatName)
		fprintf(outfile, "%s\n", FormatName->name);
	else
		fprintf(outfile, "Unknown\n");

	fprintf(outfile, "\tLensMount: %d, ", mnLens.LensMount);
	MountName = lookup_id2hr(mnLens.LensMount, MountNames, nMounts);
	if (MountName)
		fprintf(outfile, "%s\n", MountName->name);
	else
		fprintf(outfile, "Unknown\n");

	fprintf(outfile, "\tFocalType: %d, ", mnLens.FocalType);
	switch (mnLens.FocalType)
	{
	case LIBRAW_FT_UNDEFINED:
		fprintf(outfile, "Undefined\n");
		break;
	case LIBRAW_FT_PRIME_LENS:
		fprintf(outfile, "Prime lens\n");
		break;
	case LIBRAW_FT_ZOOM_LENS:
		fprintf(outfile, "Zoom lens\n");
		break;
	default:
		fprintf(outfile, "Unknown\n");
		break;
	}
	fprintf(outfile, "\tLensFeatures_pre: %s\n", mnLens.LensFeatures_pre);
	fprintf(outfile, "\tLensFeatures_suf: %s\n", mnLens.LensFeatures_suf);
	fprintf(outfile, "\tMinFocal: %0.1f mm\n", mnLens.MinFocal);
	fprintf(outfile, "\tMaxFocal: %0.1f mm\n", mnLens.MaxFocal);
	fprintf(outfile, "\tMaxAp @MinFocal: f/%0.1f\n", mnLens.MaxAp4MinFocal);
	fprintf(outfile, "\tMaxAp @MaxFocal: f/%0.1f\n", mnLens.MaxAp4MaxFocal);
	fprintf(outfile, "\tMinAp @MinFocal: f/%0.1f\n", mnLens.MinAp4MinFocal);
	fprintf(outfile, "\tMinAp @MaxFocal: f/%0.1f\n", mnLens.MinAp4MaxFocal);
	fprintf(outfile, "\tMaxAp: f/%0.1f\n", mnLens.MaxAp);
	fprintf(outfile, "\tMinAp: f/%0.1f\n", mnLens.MinAp);
	fprintf(outfile, "\tCurFocal: %0.1f mm\n", mnLens.CurFocal);
	fprintf(outfile, "\tCurAp: f/%0.1f\n", mnLens.CurAp);
	fprintf(outfile, "\tMaxAp @CurFocal: f/%0.1f\n", mnLens.MaxAp4CurFocal);
	fprintf(outfile, "\tMinAp @CurFocal: f/%0.1f\n", mnLens.MinAp4CurFocal);

	if (exifLens.makernotes.FocalLengthIn35mmFormat > 1.0f)
		fprintf(outfile, "\tFocalLengthIn35mmFormat: %0.1f mm\n",
		exifLens.makernotes.FocalLengthIn35mmFormat);

	if (exifLens.nikon.EffectiveMaxAp > 0.1f)
		fprintf(outfile, "\tEffectiveMaxAp: f/%0.1f\n",
		exifLens.nikon.EffectiveMaxAp);

	if (exifLens.makernotes.LensFStops > 0.1f)
		fprintf(outfile, "\tLensFStops @CurFocal: %0.2f\n",
		exifLens.makernotes.LensFStops);

	fprintf(outfile, "\tTeleconverterID: %lld\n", mnLens.TeleconverterID);
	fprintf(outfile, "\tTeleconverter: %s\n", mnLens.Teleconverter);
	fprintf(outfile, "\tAdapterID: %lld\n", mnLens.AdapterID);
	fprintf(outfile, "\tAdapter: %s\n", mnLens.Adapter);
	fprintf(outfile, "\tAttachmentID: %lld\n", mnLens.AttachmentID);
	fprintf(outfile, "\tAttachment: %s\n", mnLens.Attachment);
	fprintf(outfile, "\n");

	fprintf(outfile, "ISO speed: %d\n", (int)P2.iso_speed);
	if (P3.real_ISO > 0.1f)
		fprintf(outfile, "real ISO speed: %d\n", (int)P3.real_ISO);
	fprintf(outfile, "Shutter: ");
	if (P2.shutter > 0 && P2.shutter < 1)
		P2.shutter = fprintf(outfile, "1/%0.1f\n", 1.0f / P2.shutter);
	else if (P2.shutter >= 1)
		fprintf(outfile, "%0.1f sec\n", P2.shutter);
	else /* negative*/
		fprintf(outfile, " negative value\n");
	fprintf(outfile, "Aperture: f/%0.1f\n", P2.aperture);
	fprintf(outfile, "Focal length: %0.1f mm\n", P2.focal_len);
	if (P3.exifAmbientTemperature > -273.15f)
		fprintf(outfile, "Ambient temperature (exif data): %6.2f° C\n",
		P3.exifAmbientTemperature);
	if (P3.CameraTemperature > -273.15f)
		fprintf(outfile, "Camera temperature: %6.2f° C\n", P3.CameraTemperature);
	if (P3.SensorTemperature > -273.15f)
		fprintf(outfile, "Sensor temperature: %6.2f° C\n", P3.SensorTemperature);
	if (P3.SensorTemperature2 > -273.15f)
		fprintf(outfile, "Sensor temperature2: %6.2f° C\n", P3.SensorTemperature2);
	if (P3.LensTemperature > -273.15f)
		fprintf(outfile, "Lens temperature: %6.2f° C\n", P3.LensTemperature);
	if (P3.AmbientTemperature > -273.15f)
		fprintf(outfile, "Ambient temperature: %6.2f° C\n", P3.AmbientTemperature);
	if (P3.BatteryTemperature > -273.15f)
		fprintf(outfile, "Battery temperature: %6.2f° C\n", P3.BatteryTemperature);
	if (P3.FlashGN > 1.0f)
		fprintf(outfile, "Flash Guide Number: %6.2f\n", P3.FlashGN);
	fprintf(outfile, "Flash exposure compensation: %0.2f EV\n", P3.FlashEC);
	if (C.profile)
		fprintf(outfile, "Embedded ICC profile: yes, %d bytes\n", C.profile_length);
	else
		fprintf(outfile, "Embedded ICC profile: no\n");

	if (C.dng_levels.baseline_exposure > -999.f)
		fprintf(outfile, "Baseline exposure: %04.3f\n", C.dng_levels.baseline_exposure);

	fprintf(outfile, "Number of raw images: %d\n", P1.raw_count);

	if (Fuji.DriveMode != -1)
	{
		fprintf(outfile, "Fuji Drive Mode: %d, ", Fuji.DriveMode);
		DriveMode =
			lookup_id2hr(Fuji.DriveMode, FujiDriveModes, nFujiDriveModes);
		if (DriveMode)
			fprintf(outfile, "%s\n", DriveMode->name);
		else
			fprintf(outfile, "Unknown\n");
	}

	if (Fuji.CropMode)
	{
		fprintf(outfile, "Fuji Crop Mode: %d, ", Fuji.CropMode);
		Crop = lookup_id2hr(Fuji.CropMode, FujiCrops, nFujiCrops);
		if (Crop)
			fprintf(outfile, "%s\n", Crop->name);
		else
			fprintf(outfile, "Unknown\n");
	}

	if (Fuji.ExpoMidPointShift > -999.f)
		fprintf(outfile, "Fuji Exposure shift: %04.3f\n", Fuji.ExpoMidPointShift);

	if (Fuji.DynamicRange != 0xffff)
		fprintf(outfile, "Fuji Dynamic Range: %d\n", Fuji.DynamicRange);
	if (Fuji.FilmMode != 0xffff)
		fprintf(outfile, "Fuji Film Mode: %d\n", Fuji.FilmMode);
	if (Fuji.DynamicRangeSetting != 0xffff)
		fprintf(outfile, "Fuji Dynamic Range Setting: %d\n",
		Fuji.DynamicRangeSetting);
	if (Fuji.DevelopmentDynamicRange != 0xffff)
		fprintf(outfile, "Fuji Development Dynamic Range: %d\n",
		Fuji.DevelopmentDynamicRange);
	if (Fuji.AutoDynamicRange != 0xffff)
		fprintf(outfile, "Fuji Auto Dynamic Range: %d\n", Fuji.AutoDynamicRange);

	if (S.pixel_aspect != 1)
		fprintf(outfile, "Pixel Aspect Ratio: %0.6f\n", S.pixel_aspect);
	if (T.tlength)
		fprintf(outfile, "Thumb size:  %4d x %d\n", T.twidth, T.theight);
	fprintf(outfile, "Full size:   %4d x %d\n", S.raw_width, S.raw_height);

	if (S.raw_inset_crop.cwidth)
	{
		fprintf(outfile, "Raw inset, width x height: %4d x %d ", S.raw_inset_crop.cwidth,
			S.raw_inset_crop.cheight);
		if (S.raw_inset_crop.cleft != 0xffff)
			fprintf(outfile, "left: %d ", S.raw_inset_crop.cleft);
		if (S.raw_inset_crop.ctop != 0xffff)
			fprintf(outfile, "top: %d", S.raw_inset_crop.ctop);
		fprintf(outfile, "\n");
	}

	fprintf(outfile, "Aspect: ");
	Aspect =
		lookup_id2hr(S.raw_inset_crop.aspect, AspectRatios, nAspectRatios);
	if (Aspect)
		fprintf(outfile, "%s\n", Aspect->name);
	else
		fprintf(outfile, "Other %d\n", S.raw_inset_crop.aspect);

	fprintf(outfile, "Image size:  %4d x %d\n", S.width, S.height);
	fprintf(outfile, "Output size: %4d x %d\n", S.iwidth, S.iheight);
	fprintf(outfile, "Image flip: %d\n", S.flip);

	if (Canon.SensorWidth)
		fprintf(outfile, "SensorWidth          = %d\n", Canon.SensorWidth);
	if (Canon.SensorHeight)
		fprintf(outfile, "SensorHeight         = %d\n", Canon.SensorHeight);
	if (Canon.SensorLeftBorder != -1)
		fprintf(outfile, "SensorLeftBorder     = %d\n", Canon.SensorLeftBorder);
	if (Canon.SensorTopBorder != -1)
		fprintf(outfile, "SensorTopBorder      = %d\n", Canon.SensorTopBorder);
	if (Canon.SensorRightBorder)
		fprintf(outfile, "SensorRightBorder    = %d\n", Canon.SensorRightBorder);
	if (Canon.SensorBottomBorder)
		fprintf(outfile, "SensorBottomBorder   = %d\n", Canon.SensorBottomBorder);
	if (Canon.BlackMaskLeftBorder)
		fprintf(outfile, "BlackMaskLeftBorder  = %d\n", Canon.BlackMaskLeftBorder);
	if (Canon.BlackMaskTopBorder)
		fprintf(outfile, "BlackMaskTopBorder   = %d\n", Canon.BlackMaskTopBorder);
	if (Canon.BlackMaskRightBorder)
		fprintf(outfile, "BlackMaskRightBorder = %d\n", Canon.BlackMaskRightBorder);
	if (Canon.BlackMaskBottomBorder)
		fprintf(outfile, "BlackMaskBottomBorder= %d\n", Canon.BlackMaskBottomBorder);

	if (Hasselblad.BaseISO)
		fprintf(outfile, "Hasselblad base ISO: %d\n", Hasselblad.BaseISO);
	if (Hasselblad.Gain)
		fprintf(outfile, "Hasselblad gain: %g\n", Hasselblad.Gain);

	fprintf(outfile, "Raw colors: %d", P1.colors);
	if (P1.filters)
	{
		fprintf(outfile, "\nFilter pattern: ");
		if (!P1.cdesc[3])
			P1.cdesc[3] = 'G';
		for (int i = 0; i < 16; i++)
			putchar(P1.cdesc[MyCoolRawProcessor.fcol(i >> 1, i & 1)]);
	}

	if (Canon.ChannelBlackLevel[0])
		fprintf(outfile, "\nCanon makernotes, ChannelBlackLevel: %d %d %d %d\n",
		Canon.ChannelBlackLevel[0], Canon.ChannelBlackLevel[1],
		Canon.ChannelBlackLevel[2], Canon.ChannelBlackLevel[3]);

	if (C.black)
	{
		fprintf(outfile, "\nblack: %d", C.black);
	}
	if (C.cblack[0] != 0)
	{
		fprintf(outfile, "\ncblack[0 .. 3]:");
		for (int c = 0; c < 4; c++)
			fprintf(outfile, " %d", C.cblack[c]);
	}
	if ((C.cblack[4] * C.cblack[5]) > 0)
	{
		fprintf(outfile, "\nBlackLevelRepeatDim: %d x %d\n", C.cblack[4], C.cblack[4]);
		int n = C.cblack[4] * C.cblack[5];
		fprintf(outfile, "cblack[6 .. %d]:", 6 + n - 1);
		for (int c = 6; c < 6 + n; c++)
			fprintf(outfile, " %d", C.cblack[c]);
	}

	if (C.linear_max[0] != 0)
	{
		fprintf(outfile, "\nHighlight linearity limits:");
		for (int c = 0; c < 4; c++)
			fprintf(outfile, " %ld", C.linear_max[c]);
	}

	if (P1.colors > 1)
	{
		if (C.cam_mul[0] > 0)
		{
			fprintf(outfile, "\nMakernotes 'As shot' WB multipliers:");
			for (int c = 0; c < 4; c++)
				fprintf(outfile, " %f", C.cam_mul[c]);
		}

		for (int cnt = 0; cnt < nEXIF_LightSources; cnt++)
		{
			if (C.WB_Coeffs[cnt][0] > 0)
			{
				fprintf(outfile, "\nMakernotes '%s' WB multipliers:", EXIF_LightSources[cnt]);
				for (int c = 0; c < 4; c++)
					fprintf(outfile, " %d", C.WB_Coeffs[cnt][c]);
			}
		}
		if (C.WB_Coeffs[LIBRAW_WBI_Sunset][0] > 0)
		{
			fprintf(outfile, "\nMakernotes 'Sunset' multipliers:");
			for (int c = 0; c < 4; c++)
				fprintf(outfile, " %d", C.WB_Coeffs[LIBRAW_WBI_Sunset][c]);
		}

		if (C.WB_Coeffs[LIBRAW_WBI_Other][0] > 0)
		{
			fprintf(outfile, "\nMakernotes 'Other' multipliers:");
			for (int c = 0; c < 4; c++)
				fprintf(outfile, " %d", C.WB_Coeffs[LIBRAW_WBI_Other][c]);
		}

		if (C.WB_Coeffs[LIBRAW_WBI_Auto][0] > 0)
		{
			fprintf(outfile, "\nMakernotes 'Camera Auto' WB multipliers:");
			for (int c = 0; c < 4; c++)
				fprintf(outfile, " %d", C.WB_Coeffs[LIBRAW_WBI_Auto][c]);
		}
		if (C.WB_Coeffs[LIBRAW_WBI_Measured][0] > 0)
		{
			fprintf(outfile, "\nMakernotes 'Camera Measured' WB multipliers:");
			for (int c = 0; c < 4; c++)
				fprintf(outfile, " %d", C.WB_Coeffs[LIBRAW_WBI_Measured][c]);
		}

		if (C.WB_Coeffs[LIBRAW_WBI_Custom][0] > 0)
		{
			fprintf(outfile, "\nMakernotes 'Custom' WB multipliers:");
			for (int c = 0; c < 4; c++)
				fprintf(outfile, " %d", C.WB_Coeffs[LIBRAW_WBI_Custom][c]);
		}
		if (C.WB_Coeffs[LIBRAW_WBI_Custom1][0] > 0)
		{
			fprintf(outfile, "\nMakernotes 'Custom1' WB multipliers:");
			for (int c = 0; c < 4; c++)
				fprintf(outfile, " %d", C.WB_Coeffs[LIBRAW_WBI_Custom1][c]);
		}
		if (C.WB_Coeffs[LIBRAW_WBI_Custom2][0] > 0)
		{
			fprintf(outfile, "\nMakernotes 'Custom2' WB multipliers:");
			for (int c = 0; c < 4; c++)
				fprintf(outfile, " %d", C.WB_Coeffs[LIBRAW_WBI_Custom2][c]);
		}
		if (C.WB_Coeffs[LIBRAW_WBI_Custom3][0] > 0)
		{
			fprintf(outfile, "\nMakernotes 'Custom3' WB multipliers:");
			for (int c = 0; c < 4; c++)
				fprintf(outfile, " %d", C.WB_Coeffs[LIBRAW_WBI_Custom3][c]);
		}
		if (C.WB_Coeffs[LIBRAW_WBI_Custom4][0] > 0)
		{
			fprintf(outfile, "\nMakernotes 'Custom4' WB multipliers:");
			for (int c = 0; c < 4; c++)
				fprintf(outfile, " %d", C.WB_Coeffs[LIBRAW_WBI_Custom4][c]);
		}
		if (C.WB_Coeffs[LIBRAW_WBI_Custom5][0] > 0)
		{
			fprintf(outfile, "\nMakernotes 'Custom5' WB multipliers:");
			for (int c = 0; c < 4; c++)
				fprintf(outfile, " %d", C.WB_Coeffs[LIBRAW_WBI_Custom5][c]);
		}
		if (C.WB_Coeffs[LIBRAW_WBI_Custom6][0] > 0)
		{
			fprintf(outfile, "\nMakernotes 'Custom6' WB multipliers:");
			for (int c = 0; c < 4; c++)
				fprintf(outfile, " %d", C.WB_Coeffs[LIBRAW_WBI_Custom6][c]);
		}

		if ((Nikon.ME_WB[0] != 0.0f) && (Nikon.ME_WB[0] != 1.0f))
		{
			fprintf(outfile, "\nNikon multi-exposure WB multipliers:");
			for (int c = 0; c < 4; c++)
				fprintf(outfile, " %f", Nikon.ME_WB[c]);
		}

		if (C.rgb_cam[0][0] > 0.0001)
		{
			fprintf(outfile, "\n\nCamera2RGB matrix (mode: %d):\n", MyCoolRawProcessor.imgdata.params.use_camera_matrix);
			for (int i = 0; i < P1.colors; i++)
				fprintf(outfile, "%6.4f\t%6.4f\t%6.4f\n", C.rgb_cam[i][0], C.rgb_cam[i][1],
				C.rgb_cam[i][2]);
		}

		fprintf(outfile, "\nXYZ->CamRGB matrix:\n");
		for (int i = 0; i < P1.colors; i++)
			fprintf(outfile, "%6.4f\t%6.4f\t%6.4f\n", C.cam_xyz[i][0], C.cam_xyz[i][1],
			C.cam_xyz[i][2]);

    for (int cnt = 0; cnt < 2; cnt++) {
      if (fabsf(C.P1_color[cnt].romm_cam[0]) > 0)
      {
        fprintf(outfile, "\nPhaseOne Matrix %d:\n", cnt+1);
        for (int i = 0; i < 3; i++)
          fprintf(outfile, "%6.4f\t%6.4f\t%6.4f\n", C.P1_color[cnt].romm_cam[i * 3],
          C.P1_color[cnt].romm_cam[i * 3 + 1],
          C.P1_color[cnt].romm_cam[i * 3 + 2]);
      }
    }

		if (fabsf(C.cmatrix[0][0]) > 0)
		{
			fprintf(outfile, "\ncamRGB -> sRGB Matrix:\n");
			for (int i = 0; i < P1.colors; i++)
			{
				for (int j = 0; j < P1.colors; j++)
					fprintf(outfile, "%6.4f\t", C.cmatrix[i][j]);
				fprintf(outfile, "\n");
			}
		}

		if (fabsf(C.ccm[0][0]) > 0)
		{
			fprintf(outfile, "\nColor Correction Matrix:\n");
			for (int i = 0; i < P1.colors; i++)
			{
				for (int j = 0; j < P1.colors; j++)
					fprintf(outfile, "%6.4f\t", C.ccm[i][j]);
				fprintf(outfile, "\n");
			}
		}

    for (int cnt = 0; cnt < 2; cnt++) {
      if (C.dng_color[cnt].illuminant != LIBRAW_WBI_None) {
        if (C.dng_color[cnt].illuminant < nEXIF_LightSources) {
          fprintf(outfile, "\nDNG Illuminant %d: %s",
            cnt + 1, EXIF_LightSources[C.dng_color[cnt].illuminant]);
        }
        else if (C.dng_color[cnt].illuminant == LIBRAW_WBI_Other) {
          fprintf(outfile, "\nDNG Illuminant %d: Other", cnt + 1);
        }
        else {
          fprintf(outfile, "\nDNG Illuminant %d is out of EXIF LightSources range [0:24, 255]: %d",
            cnt + 1, C.dng_color[cnt].illuminant);
        }
      }
    }

    for (int n=0; n<2; n++) {
      if (fabsf(C.dng_color[n].colormatrix[0][0]) > 0)
      {
        fprintf(outfile, "\nDNG color matrix %d:\n", n+1);
        for (int i = 0; i < P1.colors; i++)
          fprintf(outfile, "%6.4f\t%6.4f\t%6.4f\n", C.dng_color[n].colormatrix[i][0],
          C.dng_color[n].colormatrix[i][1],
          C.dng_color[n].colormatrix[i][2]);
      }
    }

    for (int n=0; n<2; n++) {
      if (fabsf(C.dng_color[n].calibration[0][0]) > 0)
      {
        fprintf(outfile, "\nDNG calibration matrix %d:\n", n+1);
        for (int i = 0; i < P1.colors; i++)
        {
          for (int j = 0; j < P1.colors; j++)
            fprintf(outfile, "%6.4f\t", C.dng_color[n].calibration[j][i]);
          fprintf(outfile, "\n");
        }
      }
    }

    for (int n=0; n<2; n++) {
      if (fabsf(C.dng_color[n].forwardmatrix[0][0]) > 0)
      {
        fprintf(outfile, "\nDNG forward matrix %d:\n", n+1);
        for (int i = 0; i < P1.colors; i++)
          fprintf(outfile, "%6.4f\t%6.4f\t%6.4f\n", C.dng_color[n].forwardmatrix[0][i],
          C.dng_color[n].forwardmatrix[1][i],
          C.dng_color[n].forwardmatrix[2][i]);
      }
    }

		fprintf(outfile, "\nDerived D65 multipliers:");
		for (int c = 0; c < P1.colors; c++)
			fprintf(outfile, " %f", C.pre_mul[c]);
	}
	fprintf(outfile, "\n");

	if (Sony.PixelShiftGroupID)
	{
		fprintf(outfile, "\nSony PixelShiftGroupPrefix 0x%x PixelShiftGroupID %d, ",
			Sony.PixelShiftGroupPrefix, Sony.PixelShiftGroupID);
		if (Sony.numInPixelShiftGroup)
		{
			fprintf(outfile, "shot# %d (starts at 1) of total %d\n",
				Sony.numInPixelShiftGroup, Sony.nShotsInPixelShiftGroup);
		}
		else
		{
			fprintf(outfile, "shots in PixelShiftGroup %d, already ARQ\n",
				Sony.nShotsInPixelShiftGroup);
		}
	}

	if (Sony.Sony0x9400_version)
		fprintf(outfile, "\nSONY Sequence data, tag 0x9400 version '%x'\n"
		"\tReleaseMode2: %d\n"
		"\tSequenceImageNumber: %d (starts at zero)\n"
		"\tSequenceLength1: %d shot(s)\n"
		"\tSequenceFileNumber: %d (starts at zero, exiftool starts at 1)\n"
		"\tSequenceLength2: %d file(s)\n",
		Sony.Sony0x9400_version, Sony.Sony0x9400_ReleaseMode2,
		Sony.Sony0x9400_SequenceImageNumber,
		Sony.Sony0x9400_SequenceLength1,
		Sony.Sony0x9400_SequenceFileNumber,
		Sony.Sony0x9400_SequenceLength2);
}

Project: LibRaw

int main(int ac, char *av[])
{
  int i, ret, verbose = 0, output_thumbs = 0;

  // don't use fixed size buffers in real apps!
  char outfn[1024], thumbfn[1024];

  LibRaw RawProcessor;
  RawProcessor.imgdata.params.custom_camera_strings = customCameras;
  if (ac < 2)
  {
    printf("simple_dcraw - LibRaw %s sample. Emulates dcraw [-D] [-T] [-v] "
           "[-e] [-E]\n"
           " %d cameras supported\n"
           "Usage: %s [-D] [-T] [-v] [-e] raw-files....\n"
           "\t-4 - 16-bit mode\n"
           "\t-L - list supported cameras and exit\n"
           "\t-v - verbose output\n"
           "\t-T - output TIFF files instead of .pgm/ppm\n"
           "\t-e - extract thumbnails (same as dcraw -e in separate run)\n",
           LibRaw::version(), LibRaw::cameraCount(), av[0]);
    return 0;
  }

  putenv((char *)"TZ=UTC"); // dcraw compatibility, affects TIFF datestamp field

#define P1 RawProcessor.imgdata.idata
#define S RawProcessor.imgdata.sizes
#define C RawProcessor.imgdata.color
#define T RawProcessor.imgdata.thumbnail
#define P2 RawProcessor.imgdata.other
#define OUT RawProcessor.imgdata.params

  for (i = 1; i < ac; i++)
  {
    if (av[i][0] == '-')
    {
      if (av[i][1] == 'T' && av[i][2] == 0)
        OUT.output_tiff = 1;
      if (av[i][1] == 'v' && av[i][2] == 0)
        verbose++;
      if (av[i][1] == 'e' && av[i][2] == 0)
        output_thumbs++;
      if (av[i][1] == '4' && av[i][2] == 0)
        OUT.output_bps = 16;
      if (av[i][1] == 'C' && av[i][2] == 0)
        RawProcessor.set_progress_handler(my_progress_callback, NULL);
      if (av[i][1] == 'L' && av[i][2] == 0)
      {
        const char **clist = LibRaw::cameraList();
        const char **cc = clist;
        while (*cc)
        {
          printf("%s\n", *cc);
          cc++;
        }

        exit(0);
      }
      continue;
    }

    if (verbose)
      printf("Processing file %s\n", av[i]);

    if ((ret = RawProcessor.open_file(av[i])) != LIBRAW_SUCCESS)
    {
      fprintf(stderr, "Cannot open_file %s: %s\n", av[i], libraw_strerror(ret));
      continue; // no recycle b/c open file will recycle itself
    }

    if (!output_thumbs) // No unpack for thumb extraction
      if ((ret = RawProcessor.unpack()) != LIBRAW_SUCCESS)
      {
        fprintf(stderr, "Cannot unpack %s: %s\n", av[i], libraw_strerror(ret));
        continue;
      }

    // thumbnail unpacking and output in the middle of main
    // image processing - for test purposes!
    if (output_thumbs)
    {
      if ((ret = RawProcessor.unpack_thumb()) != LIBRAW_SUCCESS)
      {
        fprintf(stderr, "Cannot unpack_thumb %s: %s\n", av[i],
                libraw_strerror(ret));
        if (LIBRAW_FATAL_ERROR(ret))
          continue; // skip to next file
      }
      else
      {
        snprintf(thumbfn, sizeof(thumbfn), "%s.%s", av[i],
                 T.tformat == LIBRAW_THUMBNAIL_JPEG ? "thumb.jpg"
                                                    : "thumb.ppm");

        if (verbose)
          printf("Writing thumbnail file %s\n", thumbfn);
        if (LIBRAW_SUCCESS != (ret = RawProcessor.dcraw_thumb_writer(thumbfn)))
        {
          fprintf(stderr, "Cannot write %s: %s\n", thumbfn,
                  libraw_strerror(ret));
          if (LIBRAW_FATAL_ERROR(ret))
            continue;
        }
      }
      continue;
    }

    ret = RawProcessor.dcraw_process();

    if (LIBRAW_SUCCESS != ret)
    {
      fprintf(stderr, "Cannot do postpocessing on %s: %s\n", av[i],
              libraw_strerror(ret));
      if (LIBRAW_FATAL_ERROR(ret))
        continue;
    }
    snprintf(outfn, sizeof(outfn), "%s.%s", av[i],
             OUT.output_tiff ? "tiff" : (P1.colors > 1 ? "ppm" : "pgm"));

    if (verbose)
      printf("Writing file %s\n", outfn);

    if (LIBRAW_SUCCESS != (ret = RawProcessor.dcraw_ppm_tiff_writer(outfn)))
      fprintf(stderr, "Cannot write %s: %s\n", outfn, libraw_strerror(ret));

    RawProcessor.recycle(); // just for show this call
  }
  return 0;
}

Project: LibRaw

void LibRaw::tiff_head(struct tiff_hdr *th, int full)
{
  int c, psize = 0;
  struct tm *t;

  memset(th, 0, sizeof *th);
  th->t_order = htonl(0x4d4d4949) >> 16;
  th->magic = 42;
  th->ifd = 10;
  th->rat[0] = th->rat[2] = 300;
  th->rat[1] = th->rat[3] = 1;
  FORC(6) th->rat[4 + c] = 1000000;
  th->rat[4] *= shutter;
  th->rat[6] *= aperture;
  th->rat[8] *= focal_len;
  strncpy(th->t_desc, desc, 512);
  strncpy(th->t_make, make, 64);
  strncpy(th->t_model, model, 64);
  strcpy(th->soft, "dcraw v" DCRAW_VERSION);
  t = localtime(&timestamp);
  sprintf(th->date, "%04d:%02d:%02d %02d:%02d:%02d", t->tm_year + 1900,
          t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);
  strncpy(th->t_artist, artist, 64);
  if (full)
  {
    tiff_set(th, &th->ntag, 254, 4, 1, 0);
    tiff_set(th, &th->ntag, 256, 4, 1, width);
    tiff_set(th, &th->ntag, 257, 4, 1, height);
    tiff_set(th, &th->ntag, 258, 3, colors, output_bps);
    if (colors > 2)
      th->tag[th->ntag - 1].val.i = TOFF(th->bps);
    FORC4 th->bps[c] = output_bps;
    tiff_set(th, &th->ntag, 259, 3, 1, 1);
    tiff_set(th, &th->ntag, 262, 3, 1, 1 + (colors > 1));
  }
  tiff_set(th, &th->ntag, 270, 2, 512, TOFF(th->t_desc));
  tiff_set(th, &th->ntag, 271, 2, 64, TOFF(th->t_make));
  tiff_set(th, &th->ntag, 272, 2, 64, TOFF(th->t_model));
  if (full)
  {
    if (oprof)
      psize = ntohl(oprof[0]);
    tiff_set(th, &th->ntag, 273, 4, 1, sizeof *th + psize);
    tiff_set(th, &th->ntag, 277, 3, 1, colors);
    tiff_set(th, &th->ntag, 278, 4, 1, height);
    tiff_set(th, &th->ntag, 279, 4, 1,
             height * width * colors * output_bps / 8);
  }
  else
    tiff_set(th, &th->ntag, 274, 3, 1, "12435867"[flip] - '0');
  tiff_set(th, &th->ntag, 282, 5, 1, TOFF(th->rat[0]));
  tiff_set(th, &th->ntag, 283, 5, 1, TOFF(th->rat[2]));
  tiff_set(th, &th->ntag, 284, 3, 1, 1);
  tiff_set(th, &th->ntag, 296, 3, 1, 2);
  tiff_set(th, &th->ntag, 305, 2, 32, TOFF(th->soft));
  tiff_set(th, &th->ntag, 306, 2, 20, TOFF(th->date));
  tiff_set(th, &th->ntag, 315, 2, 64, TOFF(th->t_artist));
  tiff_set(th, &th->ntag, 34665, 4, 1, TOFF(th->nexif));
  if (psize)
    tiff_set(th, &th->ntag, 34675, 7, psize, sizeof *th);
  tiff_set(th, &th->nexif, 33434, 5, 1, TOFF(th->rat[4]));
  tiff_set(th, &th->nexif, 33437, 5, 1, TOFF(th->rat[6]));
  tiff_set(th, &th->nexif, 34855, 3, 1, iso_speed);
  tiff_set(th, &th->nexif, 37386, 5, 1, TOFF(th->rat[8]));
  if (gpsdata[1])
  {
    tiff_set(th, &th->ntag, 34853, 4, 1, TOFF(th->ngps));
    tiff_set(th, &th->ngps, 0, 1, 4, 0x202);
    tiff_set(th, &th->ngps, 1, 2, 2, gpsdata[29]);
    tiff_set(th, &th->ngps, 2, 5, 3, TOFF(th->gps[0]));
    tiff_set(th, &th->ngps, 3, 2, 2, gpsdata[30]);
    tiff_set(th, &th->ngps, 4, 5, 3, TOFF(th->gps[6]));
    tiff_set(th, &th->ngps, 5, 1, 1, gpsdata[31]);
    tiff_set(th, &th->ngps, 6, 5, 1, TOFF(th->gps[18]));
    tiff_set(th, &th->ngps, 7, 5, 3, TOFF(th->gps[12]));
    tiff_set(th, &th->ngps, 18, 2, 12, TOFF(th->gps[20]));
    tiff_set(th, &th->ngps, 29, 2, 12, TOFF(th->gps[23]));
    memcpy(th->gps, gpsdata, sizeof th->gps);
  }
}

Project: LibRaw

void LibRaw::read_shorts(ushort *pixel, unsigned count)
{
  if (fread(pixel, 2, count, ifp) < count)
    derror();
  if ((order == 0x4949) == (ntohs(0x1234) == 0x1234))
    swab((char *)pixel, (char *)pixel, count * 2);
}

Project: LibRaw

void LibRaw::dcb_ver(float (*image3)[3])
{
  int row, col, u = width, v = 2 * u, indx;

  for (row = 2; row < height - 2; row++)
    for (col = 2 + (FC(row, 2) & 1), indx = row * width + col; col < u - 2;
         col += 2, indx += 2)
    {

      image3[indx][1] = CLIP((image[indx + u][1] + image[indx - u][1]) / 2.0);
    }
}

Project: LibRaw

void usage(const char *p)
{
  printf("%s: Multi-threaded LibRaw sample app. Emulates dcraw -h [-w] [-a]\n",
         p);
  printf("Options:\n"
         "-J n  - set parallel job count (default 2)\n"
         "-v    - verbose\n"
         "-w    - use camera white balance\n"
         "-a    - average image for white balance\n");
  exit(1);
}

Project: LibRaw

void LibRaw::identify()
{
  static const short pana[][6] = {
      // raw_width, raw_height, left_margin, top_margin, width_increment,
      // height_increment
      {3130, 1743, 4, 0, -6, 0},      /* 00 */
      {3130, 2055, 4, 0, -6, 0},      /* 01 */
      {3130, 2319, 4, 0, -6, 0},      /* 02 DMC-FZ8 */
      {3170, 2103, 18, 0, -42, 20},   /* 03 */
      {3170, 2367, 18, 13, -42, -21}, /* 04 */
      {3177, 2367, 0, 0, -1, 0},      /* 05 DMC-L1 */
      {3304, 2458, 0, 0, -1, 0},      /* 06 DMC-FZ30 */
      {3330, 2463, 9, 0, -5, 0},      /* 07 DMC-FZ18 */
      {3330, 2479, 9, 0, -17, 4},     /* 08 */
      {3370, 1899, 15, 0, -44, 20},   /* 09 */
      {3370, 2235, 15, 0, -44, 20},   /* 10 */
      {3370, 2511, 15, 10, -44, -21}, /* 11 */
      {3690, 2751, 3, 0, -8, -3},     /* 12 DMC-FZ50 */
      {3710, 2751, 0, 0, -3, 0},      /* 13 DMC-L10 */
      {3724, 2450, 0, 0, 0, -2},      /* 14 */
      {3770, 2487, 17, 0, -44, 19},   /* 15 */
      {3770, 2799, 17, 15, -44, -19}, /* 16 */
      {3880, 2170, 6, 0, -6, 0},      /* 17 DMC-LX1 */
      {4060, 3018, 0, 0, 0, -2},      /* 18 DMC-FZ35, DMC-FZ38 */
      {4290, 2391, 3, 0, -8, -1},     /* 19 DMC-LX2 */
      {4330, 2439, 17, 15, -44, -19}, /* 20 "D-LUX 3" */
      {4508, 2962, 0, 0, -3, -4},     /* 21 */
      {4508, 3330, 0, 0, -3, -6},     /* 22 */
      {10480, 7794, 0, 0, -2, 0},     /* 23: G9 in high-res */
  };
  // clang-format off

  static const ushort canon[][11] = {
      // raw_width, raw_height, left_margin, top_margin, width_decrement,
      // height_decrement, mask01, mask03, mask11,
	  // mask13, CFA_filters.
	  { 1944, 1416, 0, 0, 48, 0 }, /* 00 0x3010000; "PowerShot Pro90 IS" */
	  { 2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25 }, /* 01 0x1120000 0x4040000; "PowerShot S30", "PowerShot G1" */
	  { 2224, 1456, 48, 6, 0, 2 }, /* 02 0x1140000; "EOS D30" */
	  { 2376, 1728, 12, 6, 52, 2 }, /* 03 0x1100000 0x1110000 0x1190000 0x1210000; "PowerShot G2",
			  "PowerShot S40", "PowerShot G3", "PowerShot S45" */
	  { 2672, 1968, 12, 6, 44, 2 }, /* 04 0x1290000 0x1310000 0x1390000; "PowerShot G5", "PowerShot S50", "PowerShot S60" */
	  { 3152, 2068, 64, 12, 0, 0, 16 }, /* 05 0x1668000 0x80000168 0x80000170;
										 "EOS D60", "EOS 10D", "EOS 300D" */
	  { 3160, 2344, 44, 12, 4, 4 }, /* 06 0x1400000 0x1380000; "PowerShot G6", "PowerShot S70" */
	  { 3344, 2484, 4, 6, 52, 6 },  /* 07 0x1370000; "PowerShot Pro1" */
	  { 3516, 2328, 42, 14, 0, 0 }, /* 08 0x80000189; "EOS 350D" */
	  { 3596, 2360, 74, 12, 0, 0 }, /* 09 0x80000174 0x80000175 0x80000232 0x80000234; "EOS-1D Mark II",
			  "EOS 20D", "EOS-1D Mark II N", "EOS 30D" */
	  { 3744, 2784, 52, 12, 8, 12 }, /* 10 0x2700000 0x2720000 0x2920000 0x2950000; "PowerShot G11",
			   "PowerShot S90", "PowerShot G12", "PowerShot S95" */
	  { 3944, 2622, 30, 18, 6, 2 }, /* 11 0x80000190; "EOS 40D" */
	  { 3948, 2622, 42, 18, 0, 2 }, /* 12 0x80000236 0x80000254; "EOS 400D", "EOS 1000D" */
	  { 3984, 2622, 76, 20, 0, 2, 14 }, /* 13 0x80000169; "EOS-1D Mark III" */
	  { 4032, 2656, 112, 44, 10, 0 }, /* 14 APS-C crop mode: 0x80000406?? 0x80000433; "EOS 6D Mark II"??,
			  "EOS RP" */
	  { 4104, 3048, 48, 12, 24, 12 }, /* 15 0x2230000; "PowerShot G9" */
	  { 4116, 2178, 4, 2, 0, 0 },     /* 16 ?? */
	  { 4152, 2772, 192, 12, 0, 0 },  /* 17 0x2460000; "PowerShot SX1 IS" */
	  { 4160, 3124, 104, 11, 8, 65 }, /* 18 0x3110000 0x3320000 0x3330000 0x3360000; "PowerShot S100
			   (new)", "PowerShot S100V", "PowerShot G15", "PowerShot S110
			   (new)" */
	  { 4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49 }, /* 19 0x3340000; "PowerShot SX50 HS" */
	  { 4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49 }, /* 20 0x3540000 0x3550000; "PowerShot G16", "PowerShot S120" */
	  { 4312, 2876, 22, 18, 0, 2 },  /* 21 0x80000176; "EOS 450D" */
	  { 4352, 2850, 144, 46, 0, 0 }, /* 22 APS-C crop mode: 0x80000424; "EOS R" */
	  { 4352, 2874, 62, 18, 0, 0 },  /* 23 0x80000288; "EOS 1100D" */
	  { 4476, 2954, 90, 34, 0, 0 },  /* 24 0x80000213; "EOS 5D" */
	  { 4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49 },                      /* 25 0x2490000; "PowerShot G10" */
	  { 4480, 3366, 80, 50, 0, 0 },  /* 26 0x3640000; "PowerShot G1 X Mark II" */
	  { 4496, 3366, 80, 50, 12, 0 }, /* 27 0x3080000; "PowerShot G1 X" */
	  { 4768, 3516, 96, 16, 0, 0, 0, 16 }, /* 28 0x3750000; "PowerShot SX60 HS" */
	  { 4832, 3204, 62, 26, 0, 0 },        /* 29 0x80000252; "EOS 500D" */
	  { 4832, 3228, 62, 51, 0, 0 },        /* 30 0x80000261; "EOS 50D" */
	  { 5108, 3349, 98, 13, 0, 0 },        /* 31 0x80000188; "EOS-1Ds Mark II" */
	  { 5120, 3318, 142, 45, 62, 0 },      /* 32 0x80000281;  "EOS-1D Mark IV" */
	  { 5280, 3528, 72, 52, 0, 0 }, /* 33 0x3840000 0x80000301 0x80000326 0x80000331 0x80000346
			  0x80000355; "EOS M10", "EOS 650D", "EOS 700D", "EOS M", "EOS
			  100D", "EOS M2" */
	  { 5344, 3516, 142, 51, 0, 0 }, /* 34 0x80000270 0x80000286 0x80000287 0x80000327 0x80000404
			  0x80000422; "EOS 550D", "EOS 600D", "EOS 60D", "EOS 1200D", "EOS
			  1300D", "EOS 3000D" */
	  { 5344, 3584, 126, 100, 0, 2 }, /* 35 0x80000269 0x80000324; "EOS-1D X", "EOS-1D C" */
	  { 5344, 3950, 98, 18, 0, 0, 0, 24, 0, 0 }, /* 36 0x805; "SX70 HS" */
	  { 5360, 3516, 158, 51, 0, 0 },             /* 37 0x80000250; "EOS 7D" */
	  { 5568, 3708, 72, 38, 0, 0 }, /* 38 0x80000289 0x80000302 0x80000325 0x80000328; "EOS 7D Mark II",
			  "EOS 6D", "EOS 70D", "EOS-1D X MARK II" */
	  { 5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49 }, /* 39 0x3780000 0x3850000 0x3930000 0x3950000 0x3970000 0x4100000;
				 "PowerShot G7 X", "PowerShot G3 X", "PowerShot G9 X",
				 "PowerShot G5 X", "PowerShot G7 X Mark II", "PowerShot G9 X
				 Mark II" */
	  { 5712, 3774, 62, 20, 10, 2 }, /* 40 0x80000215; "EOS-1Ds Mark III" */
	  { 5792, 3804, 158, 51, 0, 0 }, /* 41 0x80000218; "EOS 5D Mark II" */
	  { 5920, 3950, 122, 80, 2, 0 }, /* 42 0x80000285; "EOS 5D Mark III" */
	  { 6096, 4051, 76, 35, 0, 0 },  /* 43 0x80000432; "EOS 1500D" */
	  { 6096, 4056, 72, 34, 0, 0 },  /* 44 0x3740000 0x80000347 0x80000393; "EOS
									  M3", "EOS 760D", "EOS 750D" */
	  { 6288, 4056, 264, 36, 0, 0 }, /* 45 0x3940000 0x3980000 0x4070000 0x4180000 0x80000350
				 0x80000405 0x80000408 0x80000417 0x80000436 0x412; "EOS M5",
				 "EOS M100", "EOS M6", "PowerShot G1 X Mark III", "EOS 80D",
				 "EOS 800D", "EOS 77D", "EOS 200D", "EOS 250D", "EOS M50" */
	  { 6384, 4224, 120, 44, 0, 0 }, /* 46 0x80000406 0x80000433; "EOS 6D Mark II", "EOS RP" */
	  { 6880, 4544, 136, 42, 0, 0 }, /* 47 0x80000349; "EOS 5D Mark IV" */
	  { 6888, 4546, 146, 48, 0, 0 }, /* 48 0x80000424; "EOS R" */
	  { 7128, 4732, 144, 72, 0, 0 }, /* M6 II, 90D */
	  { 8896, 5920, 160, 64, 0, 0 }, /* 49 0x80000382 0x80000401; "EOS 5DS", "EOS 5DS R" */
  };

  static const libraw_custom_camera_t const_table[] = {
	  { 786432, 1024, 768, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-080C" },
	  { 1447680, 1392, 1040, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-145C" },
	  { 1920000, 1600, 1200, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-201C" },
	  { 5067304, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C" },
	  { 5067316, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C", 12 },
	  { 10134608, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C" },
	  { 10134620, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C", 12 },
	  { 16157136, 3272, 2469, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-810C" },
	  { 15980544, 3264, 2448, 0, 0, 0, 0, 8, 0x61, 0, 1, "AgfaPhoto", "DC-833m" },
	  { 9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Alcatel", "5035D" },
	  { 31850496, 4608, 3456, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 4:3" },
	  { 23887872, 4608, 2592, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 16:9" },
	  { 32257024, 4624, 3488, 8, 2, 16, 2, 0, 0x94, 0, 0, "GITUP", "GIT2P 4:3" },
	  { 24192768, 4624, 2616, 8, 2, 16, 2, 0, 0x94, 0, 0, "GITUP", "GIT2P 16:9" },
	  { 18016000, 4000, 2252, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "G3DUO 16:9" },
	  //          {24000000, 4000, 3000, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP",
      //          "G3DUO 4:3"}, // Conflict w/ Samsung WB550

      //   Android Raw dumps id start
      //   File Size in bytes Horizontal Res Vertical Flag then bayer order eg
      //   0x16 bbgr 0x94 rggb
	  { 1540857, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "Samsung", "S3" },
	  { 2658304, 1212, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontMipi" },
	  { 2842624, 1296, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontQCOM" },
	  { 2969600, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wMipi" },
	  { 3170304, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wQCOM" },
	  { 3763584, 1584, 1184, 0, 0, 0, 0, 96, 0x61, 0, 0, "I_Mobile", "I_StyleQ6" },
	  { 5107712, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel1" },
	  { 5382640, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel2" },
	  { 5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688" },
	  { 5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688" },
	  { 5364240, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688" },
	  { 6299648, 2592, 1944, 0, 0, 0, 0, 1, 0x16, 0, 0, "OmniVisi", "OV5648" },
	  { 6721536, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "OmniVisi", "OV56482" },
	  { 6746112, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "OneSV" },
	  { 9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "5mp" },
	  { 9830400, 2560, 1920, 0, 0, 0, 0, 96, 0x61, 0, 0, "NGM", "ForwardArt" },
	  { 10186752, 3264, 2448, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX219-mipi 8mp" },
	  { 10223360, 2608, 1944, 0, 0, 0, 0, 96, 0x16, 0, 0, "Sony", "IMX" },
	  { 10782464, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "MyTouch4GSlide" },
	  { 10788864, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "Xperia", "L" },
	  { 15967488, 3264, 2446, 0, 0, 0, 0, 96, 0x16, 0, 0, "OmniVison", "OV8850" },
	  { 16224256, 4208, 3082, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3MipiL" },
	  { 16424960, 4208, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "IMX135", "MipiL" },
	  { 17326080, 4164, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3LQCom" },
	  { 17522688, 4212, 3120, 0, 0, 0, 0, 0, 0x16, 0, 0, "Sony", "IMX135-QCOM" },
	  { 19906560, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7mipi" },
	  { 19976192, 5312, 2988, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G4" },
	  { 20389888, 4632, 3480, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "RedmiNote3Pro" },
	  { 20500480, 4656, 3496, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX298-mipi 16mp" },
	  { 21233664, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7qcom" },
	  { 26023936, 4192, 3104, 0, 0, 0, 0, 96, 0x94, 0, 0, "THL", "5000" },
	  { 26257920, 4208, 3120, 0, 0, 0, 0, 96, 0x94, 0, 0, "Sony", "IMX214" },
	  { 26357760, 4224, 3120, 0, 0, 0, 0, 96, 0x61, 0, 0, "OV", "13860" },
	  { 41312256, 5248, 3936, 0, 0, 0, 0, 96, 0x61, 0, 0, "Meizu", "MX4" },
	  { 42923008, 5344, 4016, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "IMX230" },
      //   Android Raw dumps id end
	  { 20137344, 3664, 2748, 0, 0, 0, 0, 0x40, 0x49, 0, 0, "Aptina", "MT9J003", 0xffff },
	  { 2868726, 1384, 1036, 0, 0, 0, 0, 64, 0x49, 0, 8, "Baumer", "TXG14", 1078 },
	  { 5298000, 2400, 1766, 12, 12, 44, 2, 40, 0x94, 0, 2, "Canon", "PowerShot SD300" }, // chdk hack
	  { 6553440, 2664, 1968, 4, 4, 44, 4, 40, 0x94, 0, 2, "Canon", "PowerShot A460" }, // chdk hack
	  { 6573120, 2672, 1968, 12, 8, 44, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A610" }, // chdk hack
	  { 6653280, 2672, 1992, 10, 6, 42, 2, 40, 0x94, 0, 2, "Canon", "PowerShot A530" }, // chdk hack
	  { 7710960, 2888, 2136, 44, 8, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot S3 IS" }, // chdk hack
	  { 9219600, 3152, 2340, 36, 12, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A620" }, // chdk hack
	  { 9243240, 3152, 2346, 12, 7, 44, 13, 40, 0x49, 0, 2, "Canon", "PowerShot A470" }, // chdk hack
	  { 10341600, 3336, 2480, 6, 5, 32, 3, 40, 0x94, 0, 2, "Canon", "PowerShot A720 IS" }, // chdk hack
	  { 10383120, 3344, 2484, 12, 6, 44, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A630" }, // chdk hack
	  { 12945240, 3736, 2772, 12, 6, 52, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A640" }, // chdk hack
	  { 15636240, 4104, 3048, 48, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot A650" }, // chdk hack
	  { 15467760, 3720, 2772, 6, 12, 30, 0, 40, 0x94, 0, 2, "Canon", "PowerShot SX110 IS" }, // chdk hack
	  { 15534576, 3728, 2778, 12, 9, 44, 9, 40, 0x94, 0, 2, "Canon", "PowerShot SX120 IS" }, // chdk hack
	  { 18653760, 4080, 3048, 24, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot SX20 IS" }, // chdk hack
	  { 18763488, 4104, 3048, 10, 22, 82, 22, 8, 0x49, 0, 0, "Canon", "PowerShot D10" }, // ? chdk hack ?
	  { 19131120, 4168, 3060, 92, 16, 4, 1, 40, 0x94, 0, 2, "Canon", "PowerShot SX220 HS" }, // chdk hack
	  { 21936096, 4464, 3276, 25, 10, 73, 12, 40, 0x16, 0, 2, "Canon", "PowerShot SX30 IS" }, // chdk hack
	  { 24724224, 4704, 3504, 8, 16, 56, 8, 40, 0x49, 0, 2, "Canon", "PowerShot A3300 IS" }, // chdk hack
	  { 30858240, 5248, 3920, 8, 16, 56, 16, 40, 0x94, 0, 2, "Canon", "IXUS 160" }, // chdk hack
	  { 1976352, 1632, 1211, 0, 2, 0, 1, 0, 0x94, 0, 1, "Casio", "QV-2000UX" },
	  { 3217760, 2080, 1547, 0, 0, 10, 1, 0, 0x94, 0, 1, "Casio", "QV-3*00EX" },
	  { 6218368, 2585, 1924, 0, 0, 9, 0, 0, 0x94, 0, 1, "Casio", "QV-5700" },
	  { 7816704, 2867, 2181, 0, 0, 34, 36, 0, 0x16, 0, 1, "Casio", "EX-Z60" },
	  { 2937856, 1621, 1208, 0, 0, 1, 0, 0, 0x94, 7, 13, "Casio", "EX-S20" },
	  { 4948608, 2090, 1578, 0, 0, 32, 34, 0, 0x94, 7, 1, "Casio", "EX-S100" },
	  { 6054400, 2346, 1720, 2, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "QV-R41" },
	  { 7426656, 2568, 1928, 0, 0, 0, 0, 0, 0x94, 0, 1, "Casio", "EX-P505" },
	  { 7530816, 2602, 1929, 0, 0, 22, 0, 0, 0x94, 7, 1, "Casio", "QV-R51" },
	  { 7542528, 2602, 1932, 0, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "EX-Z50" },
	  { 7562048, 2602, 1937, 0, 0, 25, 0, 0, 0x16, 7, 1, "Casio", "EX-Z500" },
	  { 7753344, 2602, 1986, 0, 0, 32, 26, 0, 0x94, 7, 1, "Casio", "EX-Z55" },
	  { 9313536, 2858, 2172, 0, 0, 14, 30, 0, 0x94, 7, 1, "Casio", "EX-P600" },
	  { 10834368, 3114, 2319, 0, 0, 27, 0, 0, 0x94, 0, 1, "Casio", "EX-Z750" },
	  { 10843712, 3114, 2321, 0, 0, 25, 0, 0, 0x94, 0, 1, "Casio", "EX-Z75" },
	  { 10979200, 3114, 2350, 0, 0, 32, 32, 0, 0x94, 7, 1, "Casio", "EX-P700" },
	  { 12310144, 3285, 2498, 0, 0, 6, 30, 0, 0x94, 0, 1, "Casio", "EX-Z850" },
	  { 12489984, 3328, 2502, 0, 0, 47, 35, 0, 0x94, 0, 1, "Casio", "EX-Z8" },
	  { 15499264, 3754, 2752, 0, 0, 82, 0, 0, 0x94, 0, 1, "Casio", "EX-Z1050" },
	  { 18702336, 4096, 3044, 0, 0, 24, 0, 80, 0x94, 7, 1, "Casio", "EX-ZR100" },
	  { 7684000, 2260, 1700, 0, 0, 0, 0, 13, 0x94, 0, 1, "Casio", "QV-4000" },
	  { 787456, 1024, 769, 0, 1, 0, 0, 0, 0x49, 0, 0, "Creative", "PC-CAM 600" },
	  { 28829184, 4384, 3288, 0, 0, 0, 0, 36, 0x61, 0, 0, "DJI" },
	  { 15151104, 4608, 3288, 0, 0, 0, 0, 0, 0x94, 0, 0, "Matrix" },
	  { 3840000, 1600, 1200, 0, 0, 0, 0, 65, 0x49, 0, 0, "Foculus", "531C" },
	  { 307200, 640, 480, 0, 0, 0, 0, 0, 0x94, 0, 0, "Generic" },
	  { 62464, 256, 244, 1, 1, 6, 1, 0, 0x8d, 0, 0, "Kodak", "DC20" },
	  { 124928, 512, 244, 1, 1, 10, 1, 0, 0x8d, 0, 0, "Kodak", "DC20" },
	  { 1652736, 1536, 1076, 0, 52, 0, 0, 0, 0x61, 0, 0, "Kodak", "DCS200" },
	  { 4159302, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330" },
	  { 4162462, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330", 3160 },
	  { 2247168, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330" },
	  { 3370752, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330" },
	  { 6163328, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603" },
	  { 6166488, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603", 3160 },
	  { 460800, 640, 480, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603" },
	  { 9116448, 2848, 2134, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603" },
	  { 12241200, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP" },
	  { 12272756, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP", 31556 },
	  { 18000000, 4000, 3000, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "12MP" },
	  { 614400, 640, 480, 0, 3, 0, 0, 64, 0x94, 0, 0, "Kodak", "KAI-0340" },
	  { 15360000, 3200, 2400, 0, 0, 0, 0, 96, 0x16, 0, 0, "Lenovo", "A820" },
	  { 3884928, 1608, 1207, 0, 0, 0, 0, 96, 0x16, 0, 0, "Micron", "2010", 3212 },
	  { 1138688, 1534, 986, 0, 0, 0, 0, 0, 0x61, 0, 0, "Minolta", "RD175", 513 },
	  { 1581060, 1305, 969, 0, 0, 18, 6, 6, 0x1e, 4, 1, "Nikon", "E900" }, // "diag raw" hack
	  { 2465792, 1638, 1204, 0, 0, 22, 1, 6, 0x4b, 5, 1, "Nikon", "E950" }, // "diag raw" hack; possibly also Nikon E700, E800, E775;
	  // Olympus C2020Z
	  { 2940928, 1616, 1213, 0, 0, 0, 7, 30, 0x94, 0, 1, "Nikon", "E2100" }, // "diag raw" hack; also Nikon E2500
	  { 4771840, 2064, 1541, 0, 0, 0, 1, 6, 0xe1, 0, 1, "Nikon", "E990" }, // "diag raw" hack; possibly also Nikon E880, E885, E995;
	  // Olympus C3030Z
	  { 4775936, 2064, 1542, 0, 0, 0, 0, 30, 0x94, 0, 1, "Nikon", "E3700" }, // "diag raw" hack; Nikon E3100, E3200, E3500; Pentax "Optio
	  // 33WR"; possibly also Olympus C740UZ
	  { 5865472, 2288, 1709, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E4500" }, // "diag raw" hack; possibly also Olympus C4040Z
	  { 5869568, 2288, 1710, 0, 0, 0, 0, 6, 0x16, 0, 1, "Nikon", "E4300" }, // "diag raw" hack; also Minolta "DiMAGE Z2"
	  { 7438336, 2576, 1925, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E5000" }, // also Nikon E5700
	  { 8998912, 2832, 2118, 0, 0, 0, 0, 30, 0x94, 7, 1, "Nikon", "COOLPIX S6" }, // "diag raw" hack
	  { 5939200, 2304, 1718, 0, 0, 0, 0, 30, 0x16, 0, 0, "Olympus", "C770UZ" }, // possibly also Olympus C4100Z, C765UZ
	  { 3178560, 2064, 1540, 0, 0, 0, 0, 0, 0x94, 0, 1, "Pentax", "Optio S" },
	  { 4841984, 2090, 1544, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S" },
	  { 6114240, 2346, 1737, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S4" },
	  { 10702848, 3072, 2322, 0, 0, 0, 21, 30, 0x94, 0, 1, "Pentax", "Optio 750Z" },
	  { 4147200, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD" },
	  { 4151666, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD", 8 },
	  { 13248000, 2208, 3000, 0, 0, 0, 0, 13, 0x61, 0, 0, "Pixelink", "A782" },
	  { 6291456, 2048, 1536, 0, 0, 0, 0, 96, 0x61, 0, 0, "RoverShot", "3320AF" },
	  { 311696, 644, 484, 0, 0, 0, 0, 0, 0x16, 0, 8, "ST Micro", "STV680 VGA" },
	  { 16098048, 3288, 2448, 0, 0, 24, 0, 9, 0x94, 0, 1, "Samsung", "S85" }, // hack
	  { 16215552, 3312, 2448, 0, 0, 48, 0, 9, 0x94, 0, 1, "Samsung", "S85" }, // hack
	  { 20487168, 3648, 2808, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550" },
	  { 24000000, 4000, 3000, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550" },
	  { 12582980, 3072, 2048, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68 }, // Sinarback 23; same res. as Leaf Volare & Cantare
	  { 33292868, 4080, 4080, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68 }, // Sinarback 44
	  { 44390468, 4080, 5440, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68 }, // Sinarback 54
	  { 1409024, 1376, 1024, 0, 0, 1, 0, 0, 0x49, 0, 0, "Sony", "XCD-SX910CR" },
	  { 2818048, 1376, 1024, 0, 0, 1, 0, 97, 0x49, 0, 0, "Sony", "XCD-SX910CR" },
  };

  libraw_custom_camera_t
      table[64 + sizeof(const_table) / sizeof(const_table[0])];


  // clang-format on

  char head[64], *cp;
  int hlen, flen, fsize, zero_fsize = 1, i, c;
  struct jhead jh;

  unsigned camera_count =
      parse_custom_cameras(64, table, imgdata.params.custom_camera_strings);
  for (int q = 0; q < sizeof(const_table) / sizeof(const_table[0]); q++)
    memmove(&table[q + camera_count], &const_table[q], sizeof(const_table[0]));
  camera_count += sizeof(const_table) / sizeof(const_table[0]);

  tiff_flip = flip = filters = UINT_MAX; /* unknown */
  raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0;
  maximum = height = width = top_margin = left_margin = 0;
  cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0;
  iso_speed = shutter = aperture = focal_len = 0;
  unique_id = 0ULL;
  tiff_nifds = 0;
  is_NikonTransfer = 0;
  is_Sony = 0;
  is_pana_raw = 0;
  maker_index = LIBRAW_CAMERAMAKER_Unknown;
  is_4K_RAFdata = 0;
  FujiCropMode = 0;
  is_PentaxRicohMakernotes = 0;
  normalized_model[0] = 0;
  normalized_make[0] = 0;
  CM_found = 0;
  memset(tiff_ifd, 0, sizeof tiff_ifd);
  libraw_internal_data.unpacker_data.crx_track_selected = -1;
  libraw_internal_data.unpacker_data.CR3_CTMDtag = 0;
  imgdata.makernotes.hasselblad.nIFD_CM[0] =
    imgdata.makernotes.hasselblad.nIFD_CM[1] = -1;
  imgdata.makernotes.kodak.ISOCalibrationGain = 1.0f;
  imgdata.makernotes.common.CameraTemperature = imgdata.makernotes.common.SensorTemperature =
      imgdata.makernotes.common.SensorTemperature2 = imgdata.makernotes.common.LensTemperature =
          imgdata.makernotes.common.AmbientTemperature = imgdata.makernotes.common.BatteryTemperature =
              imgdata.makernotes.common.exifAmbientTemperature = -1000.0f;

  for (i = 0; i < LIBRAW_IFD_MAXCOUNT; i++)
  {
    tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant =
        0xffff;
    for (int c = 0; c < 4; c++)
      tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f;
  }

  memset(gpsdata, 0, sizeof gpsdata);
  memset(cblack, 0, sizeof cblack);
  memset(white, 0, sizeof white);
  memset(mask, 0, sizeof mask);
  thumb_offset = thumb_length = thumb_width = thumb_height = 0;
  load_raw = thumb_load_raw = 0;
  write_thumb = &LibRaw::jpeg_thumb;
  data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0;
  kodak_cbpp = zero_after_ff = dng_version = load_flags = 0;
  timestamp = shot_order = tiff_samples = black = is_foveon = 0;
  mix_green = profile_length = data_error = zero_is_bad = 0;
  pixel_aspect = is_raw = raw_color = 1;
  tile_width = tile_length = 0;
  metadata_blocks = 0;

  for (i = 0; i < 4; i++)
  {
    cam_mul[i] = i == 1;
    pre_mul[i] = i < 3;
    FORC3 cmatrix[c][i] = 0;
    FORC3 rgb_cam[c][i] = c == i;
  }
  colors = 3;
  for (i = 0; i < 0x10000; i++)
    curve[i] = i;

  order = get2();
  hlen = get4();
  fseek(ifp, 0, SEEK_SET);

  if (fread(head, 1, 64, ifp) < 64)
    throw LIBRAW_EXCEPTION_IO_CORRUPT;
  libraw_internal_data.unpacker_data.lenRAFData =
      libraw_internal_data.unpacker_data.posRAFData = 0;

  fseek(ifp, 0, SEEK_END);
  flen = fsize = ftell(ifp);
  if ((cp = (char *)memmem(head, 32, (char *)"MMMM", 4)) ||
      (cp = (char *)memmem(head, 32, (char *)"IIII", 4)))
  {
    parse_phase_one(cp - head);
    if (cp - head && parse_tiff(0))
      apply_tiff();
  }
  else if (order == 0x4949 || order == 0x4d4d)
  {
    if (!memcmp(head + 6, "HEAPCCDR", 8))
    {
      data_offset = hlen;
      parse_ciff(hlen, flen - hlen, 0);
      load_raw = &LibRaw::canon_load_raw;
    }
    else if (parse_tiff(0))
      apply_tiff();
  }
  else if (!memcmp(head, "\xff\xd8\xff\xe1", 4) && !memcmp(head + 6, "Exif", 4))
  {
    fseek(ifp, 4, SEEK_SET);
    data_offset = 4 + get2();
    fseek(ifp, data_offset, SEEK_SET);
    if (fgetc(ifp) != 0xff)
      parse_tiff(12);
    thumb_offset = 0;
  }
  else if (!memcmp(head + 25, "ARECOYK", 7))
  {
    strcpy(make, "Contax");
    strcpy(model, "N Digital");
    parse_kyocera();
  }
  else if (!strcmp(head, "PXN"))
  {
    strcpy(make, "Logitech");
    strcpy(model, "Fotoman Pixtura");
  }
  else if (!strcmp(head, "qktk"))
  {
    strcpy(make, "Apple");
    strcpy(model, "QuickTake 100");
    load_raw = &LibRaw::quicktake_100_load_raw;
  }
  else if (!strcmp(head, "qktn"))
  {
    strcpy(make, "Apple");
    strcpy(model, "QuickTake 150");
    load_raw = &LibRaw::kodak_radc_load_raw;
  }
  else if (!memcmp(head, "FUJIFILM", 8))
  {
    memcpy(imFuji.SerialSignature, head + 0x10, 0x0c);
    imFuji.SerialSignature[0x0c] = 0;
    strncpy(model, head + 0x1c, 0x20);
    model[0x20] = 0;
    memcpy(model2, head + 0x3c, 4);
    model2[4] = 0;
    strcpy(imFuji.RAFVersion, model2);
    fseek(ifp, 84, SEEK_SET);
    thumb_offset = get4();
    thumb_length = get4();
    fseek(ifp, 92, SEEK_SET);
    parse_fuji(get4());
    if (thumb_offset > 120)
    {
      fseek(ifp, 120, SEEK_SET);
      is_raw += (i = get4()) ? 1 : 0;
      if (is_raw == 2 && shot_select)
        parse_fuji(i);
    }
    load_raw = &LibRaw::unpacked_load_raw;
    fseek(ifp, 100 + 28 * (shot_select > 0), SEEK_SET);
    parse_tiff(data_offset = get4());
    parse_tiff(thumb_offset + 12);
    apply_tiff();
  }
  else if (!memcmp(head, "RIFF", 4))
  {
    fseek(ifp, 0, SEEK_SET);
    parse_riff();
  }
  else if (!memcmp(head + 4, "ftypqt   ", 9))
  {
    fseek(ifp, 0, SEEK_SET);
    parse_qt(fsize);
    is_raw = 0;
  }
  else if (!memcmp(head, "\0\001\0\001\0@", 6))
  {
    fseek(ifp, 6, SEEK_SET);
    fread(make, 1, 8, ifp);
    fread(model, 1, 8, ifp);
    fread(model2, 1, 16, ifp);
    data_offset = get2();
    get2();
    raw_width = get2();
    raw_height = get2();
    load_raw = &LibRaw::nokia_load_raw;
    filters = 0x61616161;
  }
  else if (!memcmp(head, "NOKIARAW", 8))
  {
    strcpy(make, "NOKIA");
    order = 0x4949;
    fseek(ifp, 300, SEEK_SET);
    data_offset = get4();
    i = get4(); // bytes count
    width = get2();
    height = get2();

    // Data integrity check
    if (width < 1 || width > 16000 || height < 1 || height > 16000 ||
        i < (width * height) || i > (2 * width * height))
      throw LIBRAW_EXCEPTION_IO_CORRUPT;

    switch (tiff_bps = i * 8 / (width * height))
    {
    case 8:
      load_raw = &LibRaw::eight_bit_load_raw;
      break;
    case 10:
      load_raw = &LibRaw::nokia_load_raw;
      break;
    case 0:
      throw LIBRAW_EXCEPTION_IO_CORRUPT;
      break;
    }
    raw_height = height + (top_margin = i / (width * tiff_bps / 8) - height);
    mask[0][3] = 1;
    filters = 0x61616161;
  }
  else if (!memcmp(head, "ARRI", 4))
  {
    order = 0x4949;
    fseek(ifp, 20, SEEK_SET);
    width = get4();
    height = get4();
    strcpy(make, "ARRI");
    fseek(ifp, 668, SEEK_SET);
    fread(model, 1, 64, ifp);
    model[63] = 0;
    fseek(ifp, 760, SEEK_SET);
    fread(software, 1, 64, ifp);
    if((unsigned char)software[0] == 0xff) software[0] = 0;
    software[63] = 0;
    data_offset = 4096;
    load_raw = &LibRaw::packed_load_raw;
    load_flags = 88;
    filters = 0x61616161;
    fixupArri();
  }
  else if (!memcmp(head, "XPDS", 4))
  {
    order = 0x4949;
    fseek(ifp, 0x800, SEEK_SET);
    fread(make, 1, 41, ifp);
    raw_height = get2();
    raw_width = get2();
    fseek(ifp, 56, SEEK_CUR);
    fread(model, 1, 30, ifp);
    data_offset = 0x10000;
    load_raw = &LibRaw::canon_rmf_load_raw;
    gamma_curve(0, 12.25, 1, 1023);
  }
  else if (!memcmp(head + 4, "RED1", 4))
  {
    strcpy(make, "Red");
    strcpy(model, "One");
    parse_redcine();
    load_raw = &LibRaw::redcine_load_raw;
    gamma_curve(1 / 2.4, 12.92, 1, 4095);
    filters = 0x49494949;
  }
  else if (!memcmp(head, "DSC-Image", 9))
    parse_rollei();
  else if (!memcmp(head, "PWAD", 4))
    parse_sinar_ia();
  else if (!memcmp(head, "\0MRM", 4))
    parse_minolta(0);
  else if (!memcmp(head, "FOVb", 4))
  {
    parse_x3f();
  }
  else if (!memcmp(head, "CI", 2))
    parse_cine();
  else if (!memcmp(head + 4, "ftypcrx ", 8))
  {
    int err;
    unsigned long long szAtomList;
    short nesting = -1;
    short nTrack = -1;
    short TrackType;
    char AtomNameStack[128];
    strcpy(make, "Canon");

    szAtomList = ifp->size();
    err = parseCR3(0ULL, szAtomList, nesting, AtomNameStack, nTrack, TrackType);
    if ((err == 0 || err == -14) &&
        nTrack >= 0) // no error, or too deep nesting
      selectCRXTrack(nTrack);
  }

  if (make[0] == 0)
    for (zero_fsize = i = 0; i < camera_count; i++)
      if (fsize == table[i].fsize)
      {
        strcpy(make, table[i].t_make);
        strcpy(model, table[i].t_model);
        flip = table[i].flags >> 2;
        zero_is_bad = table[i].flags & 2;
#if 0
        // External jpeg support removed from libraw
        if (table[i].flags & 1) parse_external_jpeg();
#endif
        data_offset = table[i].offset == 0xffff ? 0 : table[i].offset;
        raw_width = table[i].rw;
        raw_height = table[i].rh;
        left_margin = table[i].lm;
        top_margin = table[i].tm;
        width = raw_width - left_margin - table[i].rm;
        height = raw_height - top_margin - table[i].bm;
        filters = 0x1010101U * table[i].cf;
        colors = 4 - !((filters & filters >> 1) & 0x5555);
        load_flags = table[i].lf & 0xff;
        if (table[i].lf & 0x100) /* Monochrome sensor dump */
        {
          colors = 1;
          filters = 0;
        }
        switch (tiff_bps = (fsize - data_offset) * 8 / (raw_width * raw_height))
        {
        case 6:
          load_raw = &LibRaw::minolta_rd175_load_raw;
          ilm.CameraMount = LIBRAW_MOUNT_Minolta_A;
          break;
        case 8:
          load_raw = &LibRaw::eight_bit_load_raw;
          break;
        case 10:
          if ((fsize - data_offset) / raw_height * 3 >= raw_width * 4)
          {
            load_raw = &LibRaw::android_loose_load_raw;
            break;
          }
          else if (load_flags & 1)
          {
            load_raw = &LibRaw::android_tight_load_raw;
            break;
          }
        case 12:
          load_flags |= 128;
          load_raw = &LibRaw::packed_load_raw;
          break;
        case 16:
          order = 0x4949 | 0x404 * (load_flags & 1);
          tiff_bps -= load_flags >> 4;
          tiff_bps -= load_flags = load_flags >> 1 & 7;
          load_raw = table[i].offset == 0xffff
                         ? &LibRaw::unpacked_load_raw_reversed
                         : &LibRaw::unpacked_load_raw;
        }
        maximum = (1 << tiff_bps) - (1 << table[i].max);
        break;
      }
  if (zero_fsize)
    fsize = 0;
  if (make[0] == 0)
    parse_smal(0, flen);
  if (make[0] == 0)
  {
    parse_jpeg(0);
    fseek(ifp, 0, SEEK_END);
    int sz = ftell(ifp);
    if (!strncmp(model, "RP_imx219", 9) && sz >= 0x9cb600 &&
        !fseek(ifp, -0x9cb600, SEEK_END) && fread(head, 1, 0x20, ifp) &&
        !strncmp(head, "BRCM", 4))
    {
      strcpy(make, "Broadcom");
      strcpy(model, "RPi IMX219");
      if (raw_height > raw_width)
        flip = 5;
      data_offset = ftell(ifp) + 0x8000 - 0x20;
      parse_broadcom();
      black = 66;
      maximum = 0x3ff;
      load_raw = &LibRaw::broadcom_load_raw;
      thumb_offset = 0;
      thumb_length = sz - 0x9cb600 - 1;
    }
    else if (!(strncmp(model, "ov5647", 6) && strncmp(model, "RP_OV5647", 9)) &&
             sz >= 0x61b800 && !fseek(ifp, -0x61b800, SEEK_END) &&
             fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4))
    {
      strcpy(make, "Broadcom");
      if (!strncmp(model, "ov5647", 6))
        strcpy(model, "RPi OV5647 v.1");
      else
        strcpy(model, "RPi OV5647 v.2");
      if (raw_height > raw_width)
        flip = 5;
      data_offset = ftell(ifp) + 0x8000 - 0x20;
      parse_broadcom();
      black = 16;
      maximum = 0x3ff;
      load_raw = &LibRaw::broadcom_load_raw;
      thumb_offset = 0;
      thumb_length = sz - 0x61b800 - 1;
    }
    else
      is_raw = 0;
  }

  // make sure strings are terminated
  desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0;

  for (i = 0; i < sizeof CorpTable / sizeof *CorpTable; i++)
  {
    if (strcasestr(make, CorpTable[i].CorpName))
    { /* Simplify company names */
      maker_index = CorpTable[i].CorpId;
      strcpy(make, CorpTable[i].CorpName);
    }
  }
  if ((!strncmp(make, "Kodak", 5) || !strncmp(make, "Leica", 5)) &&
      ((cp = strcasestr(model, " DIGITAL CAMERA")) ||
       (cp = strstr(model, "FILE VERSION"))))
    *cp = 0;
  if (!strncasecmp(model, "PENTAX", 6))
  {
    maker_index = LIBRAW_CAMERAMAKER_Pentax;
    strcpy(make, "Pentax");
  }

  remove_trailing_spaces(make, sizeof(make));
  remove_trailing_spaces(model, sizeof(model));

  i = strbuflen(make); /* Remove make from model */
  if (!strncasecmp(model, make, i) && model[i++] == ' ')
    memmove(model, model + i, 64 - i);
  if (!strncmp(model, "FinePix ", 8))
    memmove(model, model + 8, strlen(model) - 7);
  if (!strncmp(model, "Digital Camera ", 15))
    memmove(model, model + 15, strlen(model) - 14);
  desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0;
  if (!is_raw)
    goto notraw;

  if (!height)
    height = raw_height;
  if (!width)
    width = raw_width;

  if ((maker_index == LIBRAW_CAMERAMAKER_Pentax) ||
      (maker_index == LIBRAW_CAMERAMAKER_Samsung)) {
    if (height == 2624 &&
        width == 3936) // Pentax K10D, Samsung GX10; 0x12c1e, 0x12c20
    {
      height = 2616;
      width = 3896;
    }
    if (height == 3136 &&
        width == 4864) // Pentax K20D, Samsung GX20; 0x12cd2, 0x12cd4
    {
      height = 3124;
      width = 4688;
      filters = 0x16161616;
    }
  }

  if (maker_index == LIBRAW_CAMERAMAKER_Pentax) {
    if (width == 4352 &&
        (!strcmp(model, "K-r") ||
         !strcmp(model, "K-x"))) /* Pentax K-r, K-x; 0x12e6c, 0x12dfe */
    {
      width = 4309;
      filters = 0x16161616;
    }
    if (width >= 4960 &&
        !strncmp(
            model, "K-5",
            3)) /* Pentax K-5, "K-5 II", "K-5 II s"; 0x12e76, 0x12f70, 0x12f71 */
    {
      left_margin = 10;
      width = 4950;
      filters = 0x16161616;
    }
    if (width == 6080 && !strcmp(model, "K-70")) /* Pentax K-70; 0x13222 */
    {
      height = 4016;
      top_margin = 32;
      width = 6020;
      left_margin = 60;
    }
    if (width == 4736 && !strcmp(model, "K-7")) /* Pentax K-7; 0x12db8 */
    {
      height = 3122;
      width = 4684;
      filters = 0x16161616;
      top_margin = 2;
    }
    if (width == 6080 &&
        !strcmp(model, "K-3 II")) /* moved back; Pentax "K-3 II"; 0x1309c */
    {
      left_margin = 4;
      width = 6040;
    }
    if (width == 6112 && !strcmp(model, "KP")) /* Pentax KP; 0x1322c */
    {
      /* From DNG, maybe too strict */
      left_margin = 54;
      top_margin = 28;
      width = 6028;
      height = raw_height - top_margin;
    }
    if (width == 6080 && !strcmp(model, "K-3")) /* Pentax K-3; 0x12fc0 */
    {
      left_margin = 4;
      width = 6040;
    }
    if (width == 7424 && !strcmp(model, "645D")) /* Pentax 645D; 0x12e08 */
    {
      height = 5502;
      width = 7328;
      filters = 0x61616161;
      top_margin = 29;
      left_margin = 48;
    }
  }
  if ((maker_index == LIBRAW_CAMERAMAKER_Ricoh) &&
      height == 3014 && width == 4096)  /* Ricoh GX200 */
    width = 4014;

  if (dng_version)
  {
    if (filters == UINT_MAX)
      filters = 0;
    if (!filters)
      colors = tiff_samples;
    switch (tiff_compress)
    {
    case 0: /* Compression not set, assuming uncompressed */
    case 1:
#ifdef USE_DNGSDK
      // Uncompressed float
      if (load_raw != &LibRaw::float_dng_load_raw_placeholder)
#endif
        load_raw = &LibRaw::packed_dng_load_raw;
      break;
    case 7:
      load_raw = &LibRaw::lossless_dng_load_raw;
      break;
    case 8:
      load_raw = &LibRaw::deflate_dng_load_raw;
      break;
#ifdef USE_GPRSDK
    case 9:
        load_raw = &LibRaw::vc5_dng_load_raw_placeholder;
        break;
#endif
    case 34892:
      load_raw = &LibRaw::lossy_dng_load_raw;
      break;
    default:
      load_raw = 0;
    }
    GetNormalizedModel();
    goto dng_skip;
  }

  if (!strncmp(make, "Canon", 5) && !fsize && tiff_bps != 15)
  {
      bool fromtable = false;
    if (!load_raw)
      load_raw = &LibRaw::lossless_jpeg_load_raw;
    for (i = 0; i < sizeof canon / sizeof *canon; i++)
      if (raw_width == canon[i][0] && raw_height == canon[i][1])
      {
        width = raw_width - (left_margin = canon[i][2]);
        height = raw_height - (top_margin = canon[i][3]);
        width -= canon[i][4];
        height -= canon[i][5];
        mask[0][1] = canon[i][6];
        mask[0][3] = -canon[i][7];
        mask[1][1] = canon[i][8];
        mask[1][3] = -canon[i][9];
        if (canon[i][10])
          filters = canon[i][10] * 0x01010101U;
        fromtable = true;
      }
    if ((unique_id | 0x20000ULL) ==
        0x2720000ULL) /* "PowerShot G11", "PowerShot SX120 IS", "PowerShot S90";
                         0x2700000, 0x2710000, 0x2720000 */
    {
      left_margin = 8;
      top_margin = 16;
    }
    if(!fromtable && imgdata.makernotes.canon.AverageBlackLevel) // not known, but metadata known
    {
        FORC4 cblack[c] = imgdata.makernotes.canon.ChannelBlackLevel[c];
        black = cblack[4] = cblack[5] = 0;
        // Prevent automatic BL calculation
        mask[0][3] = 1;
        mask[0][1] = 2;

        if(imgdata.makernotes.canon.SensorWidth == raw_width
            && imgdata.makernotes.canon.SensorHeight == raw_height)
        {
            left_margin = (imgdata.makernotes.canon.SensorLeftBorder+1) & 0xfffe; // round to 2
            width = imgdata.makernotes.canon.SensorRightBorder - left_margin;
            top_margin = (imgdata.makernotes.canon.SensorTopBorder +1)  & 0xfffe;
            height = imgdata.makernotes.canon.SensorBottomBorder - top_margin;
        }
    }
  }

  if (fsize == 4771840)
  { // hack Nikon 3mpix: E880, E885, E990, E995; Olympus C3030Z
    if (!timestamp && nikon_e995())
      strcpy(model, "E995");
  }
  else if (fsize == 2940928)
  { // hack Nikon 2mpix: E2100, E2500
    if (!timestamp && !nikon_e2100())
      strcpy(model, "E2500");
  }
  else if (fsize == 4775936)
  { // hack Nikon 3mpix: E3100, E3200, E3500, E3700; Pentax "Optio 33WR";
    // Olympus C740UZ
    if (!timestamp)
      nikon_3700();
  }
  else if (fsize == 5869568)
  { // hack Nikon 4mpix: E4300; hack Minolta "DiMAGE Z2"
    if (!timestamp && minolta_z2())
    {
      maker_index = LIBRAW_CAMERAMAKER_Minolta;
      strcpy(make, "Minolta");
      strcpy(model, "DiMAGE Z2");
    }
  }

  if (!strcmp(model, "KAI-0340") && find_green(16, 16, 3840, 5120) < 25)
  {
    height = 480;
    top_margin = filters = 0;
    strcpy(model, "C603");
  }

  GetNormalizedModel();

  if (!strncmp(make, "Canon", 5) && !tiff_flip && imCanon.MakernotesFlip)
  {
    tiff_flip = imCanon.MakernotesFlip;
  }

  if (!strncmp(make, "Nikon", 5))
  {
    if (!load_raw)
      load_raw = &LibRaw::packed_load_raw;
    if (model[0] == 'E') // Nikon E8800, E8700, E8400, E5700, E5400, E5000,
                         // others are diag hacks?
      load_flags |= !data_offset << 2 | 2;
  }
  /* Set parameters based on camera name (for non-DNG files). */

  /* Always 512 for arw2_load_raw */
  if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0])
  {
    black = (load_raw == &LibRaw::sony_arw2_load_raw)
                ? 512
                : (128 << (tiff_bps - 12));
  }

  if (is_foveon)
  {
    if (height * 2 < width)
      pixel_aspect = 0.5;
    if (height > width)
      pixel_aspect = 2;
    filters = 0;
  }
  else if (!strncmp(make, "Pentax", 6) &&
           !strncmp(model, "K-1",
                    3)) /* Pentax K-1, Pentax "K-1 Mark II"; 0x13092, 0x13240 */
  {
    top_margin = 18;
    height = raw_height - top_margin;
    if (raw_width ==
        7392) /* Pentax K-1, Pentax "K-1 Mark II"; 0x13092, 0x13240 */
    {
      left_margin = 6;
      width = 7376;
    }
  }
  else if (!strncmp(make, "Canon", 5) && tiff_bps == 15) // Canon sRAW
  {
    if (width == 3344)
      width = 3272;
    else if (width == 3872)
      width = 3866;

    if (height > width)
    {
      SWAP(height, width);
      SWAP(raw_height, raw_width);
    }
    if (width == 7200 &&
        height == 3888) // Canon EOS 5DS (R); 0x80000382, 0x80000401
    {
      raw_width = width = 6480;
      raw_height = height = 4320;
    }
    filters = 0;
    tiff_samples = colors = 3;
    load_raw = &LibRaw::canon_sraw_load_raw;
  }
  else if (!strcmp(normalized_model, "PowerShot 600"))
  {
    height = 613;
    width = 854;
    raw_width = 896;
    colors = 4;
    filters = 0xe1e4e1e4;
    load_raw = &LibRaw::canon_600_load_raw;
  }
  else if (!strcmp(normalized_model, "PowerShot A5") ||
           !strcmp(normalized_model, "PowerShot A5 Zoom"))
  {
    height = 773;
    width = 960;
    raw_width = 992;
    pixel_aspect = 256 / 235.0;
    filters = 0x1e4e1e4e;
    goto canon_a5;
  }
  else if (!strcmp(normalized_model, "PowerShot A50"))
  {
    height = 968;
    width = 1290;
    raw_width = 1320;
    filters = 0x1b4e4b1e;
    goto canon_a5;
  }
  else if (!strcmp(normalized_model, "PowerShot Pro70"))
  {
    height = 1024;
    width = 1552;
    filters = 0x1e4b4e1b;
  canon_a5:
    colors = 4;
    tiff_bps = 10;
    load_raw = &LibRaw::packed_load_raw;
    load_flags = 40;
  }
  else if (!strcmp(normalized_model, "PowerShot Pro90 IS") ||
           !strcmp(normalized_model, "PowerShot G1"))
  {
    colors = 4;
    filters = 0xb4b4b4b4;
  }
  else if (!strcmp(normalized_model, "PowerShot A610")) // chdk hack
  {
    if (canon_s2is())
      strcpy(model + 10, "S2 IS"); // chdk hack
  }
  else if (!strcmp(normalized_model, "PowerShot SX220 HS")) // chdk hack
  {
    mask[1][3] = -4;
    top_margin = 16;
    left_margin = 92;
  }
  else if (!strcmp(normalized_model, "PowerShot S120")) // chdk hack
  {
    raw_width = 4192;
    raw_height = 3062;
    width = 4022;
    height = 3016;
    mask[0][0] = top_margin = 31;
    mask[0][2] = top_margin + height;
    left_margin = 120;
    mask[0][1] = 23;
    mask[0][3] = 72;
  }
  else if (!strcmp(normalized_model, "PowerShot G16"))
  {
    mask[0][0] = 0;
    mask[0][2] = 80;
    mask[0][1] = 0;
    mask[0][3] = 16;
    top_margin = 29;
    left_margin = 120;
    width = raw_width - left_margin - 48;
    height = raw_height - top_margin - 14;
  }
  else if (!strcmp(normalized_model, "PowerShot SX50 HS"))
  {
    top_margin = 17;
  }
  else if (!strcmp(model, "EOS D2000C"))
  {
    filters = 0x61616161;
    if (!black)
      black = curve[200];
  }

  else if (makeIs(LIBRAW_CAMERAMAKER_Nikon))
  {
    if (!strcmp(model, "D1"))
    { // Nikon D1
      imgdata.other.analogbalance[0] = cam_mul[0];
      imgdata.other.analogbalance[2] = cam_mul[2];
      imgdata.other.analogbalance[1] = imgdata.other.analogbalance[3] =
          cam_mul[1];
      cam_mul[0] = cam_mul[1] = cam_mul[2] = 1.0f;
    }

    else if (!strcmp(model, "D1X")) // Nikon D1X
    {
      width -= 4;
      pixel_aspect = 0.5;
    }
    else if (!strcmp(model, "D40X") || // Nikon D40X
             !strcmp(model, "D60") ||  // Nikon D60
             !strcmp(model, "D80") ||  // Nikon D80
             !strcmp(model, "D3000"))  // Nikon D3000
    {
      height -= 3;
      width -= 4;
    }
    else if (!strcmp(model, "D3") ||  // Nikon D3
             !strcmp(model, "D3S") || // Nikon D3S
             !strcmp(model, "D700"))  // Nikon D700
    {
      width -= 4;
      left_margin = 2;
    }
    else if (!strcmp(model, "D3100")) // Nikon D3100
    {
      width -= 28;
      left_margin = 6;
    }
    else if (!strcmp(model, "D5000") || // Nikon D5000
             !strcmp(model, "D90"))     // Nikon D90
    {
      width -= 42;
    }
    else if (!strcmp(model, "D5100") ||   // Nikon D5100
             !strcmp(model, "D7000") ||   // Nikon D7000
             !strcmp(model, "COOLPIX A")) // Nikon "COOLPIX A"
    {
      width -= 44;
    }
    else if (!strcmp(model, "D3200") ||  // Nikon D3200
             !strcmp(model, "D600") ||   // Nikon D600
             !strcmp(model, "D610") ||   // Nikon D610
             !strncmp(model, "D800", 4)) // Nikons: D800, D800E
    {
      width -= 46;
    }
    else if (!strcmp(model, "D4") || // Nikon D4
             !strcmp(model, "Df"))   // Nikon Df
    {
      width -= 52;
      left_margin = 2;
    }
    else if (!strcmp(model, "D500")) // Nikon D500
    {
      // Empty - to avoid width-1 below
    }
    else if (!strncmp(model, "D40", 3) || // Nikon D40
             !strncmp(model, "D50", 3) || // Nikon D50
             !strncmp(model, "D70", 3))   // Nikon D70
    {
      width--;
    }
    else if (!strcmp(model, "D100")) // Nikon D100
    {
      if (load_flags) // compressed NEF
        raw_width = (width += 3) + 3;
    }
    else if (!strcmp(model, "D200")) // Nikon D200
    {
      left_margin = 1;
      width -= 4;
      filters = 0x94949494;
    }
    else if (!strncmp(model, "D2H", 3)) // Nikons: D2H, D2Hs
    {
      left_margin = 6;
      width -= 14;
    }
    else if (!strncmp(model, "D2X", 3)) // Nikons: D2X, D2Xs
    {
      if (width == 3264) // in-camera Hi-speed crop: On
        width -= 32;
      else
        width -= 8;
    }
    else if (!strncmp(model, "D300", 4)) // Nikon D300, Nikon D300s
    {
      width -= 32;
    }
    else if (raw_width == 4032) // Nikon "COOLPIX P7700", "COOLPIX P7800",
                                // "COOLPIX P330", "COOLPIX P340"
    {
      if (!strcmp(normalized_model, "COOLPIX P7700")) // Nikon "COOLPIX P7700"
      {
        maximum = 65504;
        load_flags = 0;
      }
      else if (!strcmp(normalized_model,
                       "COOLPIX P7800")) // Nikon "COOLPIX P7800"
      {
        maximum = 65504;
        load_flags = 0;
      }
      else if (!strcmp(model, "COOLPIX P340")) // Nikon "COOLPIX P340"
      {
        load_flags = 0;
      }
    }
    else if (!strncmp(model, "COOLPIX P", 9) &&
             raw_width != 4032) // Nikon "COOLPIX P1000", "COOLPIX P6000",
                                // "COOLPIX P7000", "COOLPIX P7100"
    {
      load_flags = 24;
      filters = 0x94949494;
      /* the following 'if' is most probably obsolete, because we now read black
       * level from metadata */
      if ((model[9] == '7') && /* P7000, P7100 */
          ((iso_speed >= 400) || (iso_speed == 0)) &&
          !strstr(software, "V1.2")) /* v. 1.2 seen for P7000 only */
        black = 255;
    }
    else if (!strncmp(model, "COOLPIX B700", 12)) // Nikon "COOLPIX B700"
    {
      load_flags = 24;
    }
    else if (!strncmp(model, "1 ",
                      2)) // Nikons: "1 AW1", "1 J1", "1 J2", "1 J3", "1 J4", "1
                          // J5", "1 S1", "1 S2", "1 V1", "1 V2", "1 V3"
    {
      height -= 2;
    }

    else if ((fsize == 4771840) &&
             strcmp(model, "E995")) // other than Nikon E995
    {
      filters = 0xb4b4b4b4;
      simple_coeff(3);
      pre_mul[0] = 1.196;
      pre_mul[1] = 1.246;
      pre_mul[2] = 1.018;
    }
    else if (!strcmp(model, "E2500"))
    {
      height -= 2;
      load_flags = 6;
      colors = 4;
      filters = 0x4b4b4b4b;
    }
  }

  else if (fsize == 1581060) // hack Nikon 1mpix: E900
  {
    simple_coeff(3);
    pre_mul[0] = 1.2085;
    pre_mul[1] = 1.0943;
    pre_mul[3] = 1.1103;
  }
  else if (fsize == 3178560) // Pentax "Optio S"
  {
    cam_mul[0] *= 4;
    cam_mul[2] *= 4;
  }
  else if (fsize == 4775936) // hack Nikon 3mpix: E3100, E3200, E3500, E3700;
                             // Pentax "Optio 33WR"; Olympus C740UZ
  {
    if (model[0] == 'E' && atoi(model + 1) < 3700)
      filters = 0x49494949;
    if (!strcmp(model, "Optio 33WR")) /* Pentax "Optio 33WR"; 0x129c6 */
    {
      flip = 1;
      filters = 0x16161616;
    }
    if (make[0] == 'O') // Olympus C740UZ ?
    {
      i = find_green(12, 32, 1188864, 3576832);
      c = find_green(12, 32, 2383920, 2387016);
      if (abs(i) < abs(c))
      {
        SWAP(i, c);
        load_flags = 24;
      }
      if (i < 0)
        filters = 0x61616161;
    }
  }
  else if (fsize ==
           5869568) // hack Nikon 4mpix: E4300; hack Minolta "DiMAGE Z2"
  {
    load_flags = 6 + 24 * (make[0] == 'M');
  }
  else if (fsize == 6291456) // RoverShot 3320AF
  {
    fseek(ifp, 0x300000, SEEK_SET);
    if ((order = guess_byte_order(0x10000)) == 0x4d4d)
    {
      height -= (top_margin = 16);
      width -= (left_margin = 28);
      maximum = 0xf5c0;
      strcpy(make, "ISG");
      model[0] = 0;
    }
  }
  else if (!strncmp(make, "Fujifilm", 8))
  {

    if (!strcmp(model, "S2Pro"))
    {
      height = 2144;
      width = 2880;
      flip = 6;
    }
    else if (load_raw != &LibRaw::packed_load_raw && strncmp(model, "X-", 2) &&
             filters >= 1000) // Bayer and not an X-model
      maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00;

    if (FujiCropMode == 1)
    { // FF crop on GFX
      width = raw_width;
      height = raw_height;
    }
    else if (FujiCropMode == 4)
    { /* electronic shutter, high speed mode (1.25x crop) */
      height = raw_height;
    }

    top_margin = (raw_height - height) >> 2 << 1;
    left_margin = (raw_width - width) >> 2 << 1;

    if (!strcmp(model, "X-T3") || !strcmp(model, "X-T30"))
    {
      top_margin = 0;
      if (FujiCropMode == 0)
      {
        top_margin = 6;
        height = 4174;
        left_margin = 0;
        width = 6251;
      }
      else if (FujiCropMode == 4)
      { /* electronic shutter, high speed mode (1.25x crop) */
        left_margin = 624;
        width = 5004;
      }
    }

    if (width == 2848 || // Fujifilm X-S1, X10, XF1
        width == 3664)   // Fujifilm "HS10 HS11"
      filters = 0x16161616;

    if (width == 4032 || // Fujifilm X20, X30, XQ1, XQ2
        width == 4952)   // Fujifilm X-A1, X-A2, X-E1, X-M1, X-Pro1
      left_margin = 0;

    if (width == 3328 &&
        (width -= 66)) // Fujifilm F550EXR, F600EXR, F770EXR, F800EXR, F900EXR,
                       // HS20EXR, HS30EXR, HS33EXR, HS50EXR
      left_margin = 34;

    if (width == 4936) // Fujifilm X-E2S, X-E2, X-T10, X-T1, X100S, X100T, X70
      left_margin = 4;

    if (width == 6032) // Fujifilm X100F, X-T2, X-T20, X-Pro2, X-H1, X-E3,
      left_margin = 0;

    if (!strcmp(normalized_model, "DBP for GX680"))
    {
      /*
      7712 2752 -> 5504 3856
      */

      /*
      width = 688;
      height = 30848;
      raw_width = 688;
      raw_height = 30848;
      */

      raw_width = 5504;
      raw_height = 3856;
      left_margin = 32;
      top_margin = 8;
      width = raw_width - left_margin - 32;
      height = raw_height - top_margin - 8;

      load_raw = &LibRaw::unpacked_load_raw_FujiDBP;
      //  maximum = 0x0fff;
      filters = 0x16161616;
      load_flags = 0;
      flip = 6;
    }

    if (!strcmp(model, "HS50EXR") || !strcmp(model, "F900EXR"))
    {
      width += 2;
      left_margin = 0;
      filters = 0x16161616;
    }
    if (!strncmp(model, "GFX 50", 6))
    {
      left_margin = 0;
      top_margin = 0;
    }
    if (!strncmp(model, "GFX 100", 7))
    {
      left_margin = 0;
      width = raw_width - 146;
      height = raw_height - (top_margin = 2);
      if (tiff_bps == 16)
        maximum = 0xffff;
    }
    if (!strcmp(normalized_model, "S5100"))
    {
      height -= (top_margin = 6);
    }
    if (fuji_layout)
      raw_width *= is_raw;
    if (filters == 9)
      FORC(36)
      ((char *)xtrans)[c] =
          xtrans_abs[(c / 6 + top_margin) % 6][(c + left_margin) % 6];
  }
  else if (!strcmp(model, "KD-400Z")) // Konica KD-400Z
  {
    height = 1712;
    width = 2312;
    raw_width = 2336;
    goto konica_400z;
  }
  else if (!strcmp(model, "KD-510Z")) // Konica KD-510Z
  {
    goto konica_510z;
  }
  else if (makeIs(LIBRAW_CAMERAMAKER_Minolta))
  {
    if (!load_raw && (maximum = 0xfff))
    {
      load_raw = &LibRaw::unpacked_load_raw;
    }
    if (!strncmp(model, "DiMAGE A",
                 8)) // Minolta "DiMAGE A1", "DiMAGE A2", "DiMAGE A200"
    {
      if (!strcmp(model, "DiMAGE A200"))
        filters = 0x49494949;
      tiff_bps = 12;
      load_raw = &LibRaw::packed_load_raw;
    }
    else if (!strncmp(normalized_model, "Dynax", 5))
    {
      /*
      'make' can be 'Konica', 'Minolta', or 'Konica Minolta';
      'normalized_make' is 'Minolta', where it started;
      aliases (MAXXUM in USA, DYNAX in Europe, Alpha in Japan - also gave
      A-mount and Sony Alpha line their names): "Dynax 5D", "Maxxum 5D", "Alpha
      5D", "Alpha Sweet Digital", "Dynax 7D", "Maxxum 7D", "Alpha 7D"
       */
      load_raw = &LibRaw::packed_load_raw;
    }
    else if (!strncmp(model, "DiMAGE G",
                      8)) // hack Minolta "DiMAGE G400", "DiMAGE G500", "DiMAGE
                          // G530", "DiMAGE G600"
    {
      if (model[8] == '4') // DiMAGE G400
      {
        height = 1716;
        width = 2304;
      }
      else if (model[8] == '5') // DiMAGE G500 / G530
      {
      konica_510z:
        height = 1956;
        width = 2607;
        raw_width = 2624;
      }
      else if (model[8] == '6') // DiMAGE G600
      {
        height = 2136;
        width = 2848;
      }
      data_offset += 14;
      filters = 0x61616161;
    konica_400z:
      load_raw = &LibRaw::unpacked_load_raw;
      maximum = 0x3df;
      order = 0x4d4d;
    }
  }
  else if (!strcmp(model, "*ist D")) /* Pentax "*ist D"; 0x12994 */
  {
    load_raw = &LibRaw::unpacked_load_raw;
    data_error = -1;
  }
  else if (!strcmp(model, "*ist DS")) /* Pentax "*ist DS"; 0x12aa2 */
  {
    height -= 2;
  }

  else if (makeIs(LIBRAW_CAMERAMAKER_Samsung))
  {
    if (raw_width == 4704) // Samsung NX100, NX10, NX11,
    {
      height -= top_margin = 8;
      width -= 2 * (left_margin = 8);
      load_flags = 32;
    }
    else if (!strcmp(model, "NX3000")) // Samsung NX3000; raw_width: 5600
    {
      top_margin = 38;
      left_margin = 92;
      width = 5456;
      height = 3634;
      filters = 0x61616161;
      colors = 3;
    }
    else if (raw_height == 3714) // Samsung NX2000, NX300M, NX300, NX30, EK-GN120
    {
      height -= top_margin = 18;
      left_margin = raw_width - (width = 5536);
      if (raw_width != 5600)
        left_margin = top_margin = 0;
      filters = 0x61616161;
      colors = 3;
    }
    else if (raw_width == 5632) // Samsung NX1000, NX200, NX20, NX210
    {
      order = 0x4949;
      height = 3694;
      top_margin = 2;
      width = 5574 - (left_margin = 32 + tiff_bps);
      if (tiff_bps == 12)
        load_flags = 80;
    }
    else if (raw_width == 5664) // Samsung "NX mini"
    {
      height -= top_margin = 17;
      left_margin = 96;
      width = 5544;
      filters = 0x49494949;
    }
    else if (raw_width == 6496) // Samsung NX1, NX500
    {
      filters = 0x61616161;
      if (!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3])
        black = 1 << (tiff_bps - 7);
    }
    else if (!strcmp(model, "EX1")) // Samsung EX1; raw_width: 3688
    {
      order = 0x4949;
      height -= 20;
      top_margin = 2;
      if ((width -= 6) > 3682)
      {
        height -= 10;
        width -= 46;
        top_margin = 8;
      }
    }
    else if (!strcmp(model, "WB2000")) // Samsung WB2000; raw_width: 3728
    {
      order = 0x4949;
      height -= 3;
      top_margin = 2;
      if ((width -= 10) > 3718)
      {
        height -= 28;
        width -= 56;
        top_margin = 8;
      }
    }
    else if (!strcmp(model, "WB550")) // Samsung WB550; raw_width: 4000
    {
      order = 0x4949;
    }
    else if (!strcmp(model, "EX2F")) // Samsung EX2F; raw_width: 4176
    {
      height = 3030;
      width = 4040;
      top_margin = 15;
      left_margin = 24;
      order = 0x4949;
      filters = 0x49494949;
      load_raw = &LibRaw::unpacked_load_raw;
    }
  }

  else if (!strcmp(model, "STV680 VGA"))
  {
    black = 16;
  }
  else if (!strcmp(model, "N95"))
  {
    height = raw_height - (top_margin = 2);
  }
  else if (!strcmp(model, "640x480"))
  {
    gamma_curve(0.45, 4.5, 1, 255);
  }
  else if (makeIs(LIBRAW_CAMERAMAKER_Hasselblad))
  {
    if (load_raw == &LibRaw::lossless_jpeg_load_raw)
      load_raw = &LibRaw::hasselblad_load_raw;

    if ((imHassy.SensorCode == 4) && !strncmp(model, "V96C", 4)) { // Hasselblad V96C
      strcpy(model, "V96C");
      strcpy(normalized_model, model);
      height -= (top_margin = 6);
      width -= (left_margin = 3) + 7;
      filters = 0x61616161;

    } else if ((imHassy.SensorCode == 9) && imHassy.uncropped) { // various Hasselblad '-39'
      height = 5444;
      width = 7248;
      top_margin = 4;
      left_margin = 7;
      filters = 0x61616161;

    } else if ((imHassy.SensorCode == 13) && imHassy.uncropped) { // Hasselblad H4D-40, H5D-40
      height -= 84;
      width -= 82;
      top_margin = 4;
      left_margin = 41;
      filters = 0x61616161;

    } else if ((imHassy.SensorCode == 11) && imHassy.uncropped) { // Hasselblad H5D-50
      height -= 84;
      width -= 82;
      top_margin = 4;
      left_margin = 41;
      filters = 0x61616161;

    } else if ((imHassy.SensorCode == 15) &&
               !imHassy.SensorSubCode && // Hasselblad H5D-50c
               imHassy.uncropped) {
      left_margin = 52;
      top_margin = 100;
      width = 8272;
      height = 6200;
      black = 256;

    } else if ((imHassy.SensorCode == 15) &&
               (imHassy.SensorSubCode == 2) && // various Hasselblad X1D cameras
               imHassy.uncropped) {
      top_margin = 96;
      height -= 96;
      left_margin = 48;
      width -= 106;
      maximum = 0xffff;
      tiff_bps = 16;

    } else if ((imHassy.SensorCode == 12) && imHassy.uncropped) { // Hasselblad H4D-60
      if (black > 500) { // (imHassy.format == LIBRAW_HF_FFF)
        top_margin = 12;
        left_margin = 44;
        width = 8956;
        height = 6708;
        memset(cblack, 0, sizeof(cblack));
        black = 512;
      } else { // (imHassy.format == LIBRAW_HF_3FR)
        top_margin = 8;
        left_margin = 40;
        width = 8964;
        height = 6716;
        black += load_flags = 256;
        maximum = 0x8101;
      }

    } else if ((imHassy.SensorCode == 17) && imHassy.uncropped) { // Hasselblad H6D-100c, A6D-100c
      left_margin = 64;
      width = 11608;
      top_margin = 108;
      height = raw_height - top_margin;
    }

    if (tiff_samples > 1)
    {
      is_raw = tiff_samples + 1;
      if (!shot_select && !half_size)
        filters = 0;
    }
  }
  else if (makeIs(LIBRAW_CAMERAMAKER_Sinar))
  {
    if (!load_raw)
      load_raw = &LibRaw::unpacked_load_raw;
    if (is_raw > 1 && !shot_select)
      filters = 0;
    maximum = 0x3fff;
  }
  else if (load_raw == &LibRaw::sinar_4shot_load_raw)
  {
    if (is_raw > 1 && !shot_select)
      filters = 0;
  }
  else if (makeIs(LIBRAW_CAMERAMAKER_Leaf))
  {
    maximum = 0x3fff;
    fseek(ifp, data_offset, SEEK_SET);
    if (ljpeg_start(&jh, 1) && jh.bits == 15)
      maximum = 0x1fff;
    if (tiff_samples > 1)
      filters = 0;
    if (tiff_samples > 1 || tile_length < raw_height)
    {
      load_raw = &LibRaw::leaf_hdr_load_raw;
      raw_width = tile_width;
    }
    if ((width | height) == 2048)
    {
      if (tiff_samples == 1)
      {
        filters = 1;
        strcpy(cdesc, "RBTG");
        strcpy(model, "CatchLight");
        strcpy(normalized_model, model);
        top_margin = 8;
        left_margin = 18;
        height = 2032;
        width = 2016;
      }
      else
      {
        strcpy(model, "DCB2");
        strcpy(normalized_model, model);
        top_margin = 10;
        left_margin = 16;
        height = 2028;
        width = 2022;
      }
    }
    else if (width + height == 3144 + 2060)
    {
      if (!model[0])
      {
        strcpy(model, "Cantare");
        strcpy(normalized_model, model);
      }
      if (width > height)
      {
        top_margin = 6;
        left_margin = 32;
        height = 2048;
        width = 3072;
        filters = 0x61616161;
      }
      else
      {
        left_margin = 6;
        top_margin = 32;
        width = 2048;
        height = 3072;
        filters = 0x16161616;
      }
      if (!cam_mul[0] || model[0] == 'V')
        filters = 0;
      else
        is_raw = tiff_samples;
    }
    else if (width == 2116) // Leaf "Valeo 6"
    {
      strcpy(model, "Valeo 6");
      strcpy(normalized_model, model);
      height -= 2 * (top_margin = 30);
      width -= 2 * (left_margin = 55);
      filters = 0x49494949;
    }
    else if (width == 3171) // Leaf "Valeo 6"
    {
      strcpy(model, "Valeo 6");
      strcpy(normalized_model, model);
      height -= 2 * (top_margin = 24);
      width -= 2 * (left_margin = 24);
      filters = 0x16161616;
    }
  }
  else if (makeIs(LIBRAW_CAMERAMAKER_Panasonic))
  {
    if (raw_width > 0 &&
        ((flen - data_offset) / (raw_width * 8 / 7) == raw_height))
      load_raw = &LibRaw::panasonic_load_raw;
    if (!load_raw)
    {
      load_raw = &LibRaw::unpacked_load_raw;
      load_flags = 4;
    }
    zero_is_bad = 1;
    if ((height += 12) > raw_height)
      height = raw_height;
    for (i = 0; i < sizeof pana / sizeof *pana; i++)
      if (raw_width == pana[i][0] && raw_height == pana[i][1])
      {
        left_margin = pana[i][2];
        top_margin = pana[i][3];
        width += pana[i][4];
        height += pana[i][5];
      }
    filters = 0x01010101U *
              (uchar) "\x94\x61\x49\x16"[((filters - 1) ^ (left_margin & 1) ^
                                          (top_margin << 1)) &
                                         3];
  }
  else if (!strcmp(model, "C770UZ")) // Olympus C770UZ; 0x5358373732; Why it is above of make check??
  {
    height = 1718;
    width = 2304;
    filters = 0x16161616;
    load_raw = &LibRaw::packed_load_raw;
    load_flags = 30;
  }
  else if (makeIs(LIBRAW_CAMERAMAKER_Olympus))
  {
    height += height & 1;
    if (exif_cfa)
      filters = exif_cfa;

    if (width ==
        4100) // Olympus E-PL2, E-PL1, E-P2, E-P1, E-620, E-600, E-5, E-30;
              // 0x5330303334, 0x5330303237, 0x5330303236, 0x5330303139,
              // 0x5330303233, 0x5330303330, 0x5330303333, 0x5330303137
      width -= 4;

    if (width == 4080) // Olympus E-PM1, E-PL3, E-P3; 0x5330303339,
                       // 0x5330303338, 0x5330303332
      width -= 24;

    if (width == 10400) // Olympus PEN-F; 0x5330303631
      width -= 12;

    if (width == 9280) // Olympus E-M5 Mark II; 0x5330303532
    {
      width -= 6;
      height -= 6;
    }

    if (load_raw == &LibRaw::unpacked_load_raw)
      load_flags = 4;
    tiff_bps = 12;
    if (!strcmp(model, "E-300") ||
        !strcmp(model,
                "E-500")) // Olympus E-300, E-500; 0x4434303431, 0x5330303034
    {
      width -= 20;
      if (load_raw == &LibRaw::unpacked_load_raw)
      {
        maximum = 0xfc3;
        memset(cblack, 0, sizeof cblack);
      }
    }
    else if (!strcmp(
                 model,
                 "STYLUS1")) // Olympus STYLUS1 but not STYLUS1,1s; 0x4434353732
    {
      width -= 14;
      maximum = 0xfff;
    }
    else if (!strcmp(model, "E-330")) // Olympus E-330; 0x5330303033
    {
      width -= 30;
      if (load_raw == &LibRaw::unpacked_load_raw)
        maximum = 0xf79;
    }
    else if (!strcmp(model, "SP550UZ")) // Olympus SP550UZ; 0x4434333231
    {
      thumb_length = flen - (thumb_offset = 0xa39800);
      thumb_height = 480;
      thumb_width = 640;
    }
    else if (!strcmp(model, "TG-4")) // Olympus TG-4; 0x4434353836
    {
      width -= 16;
    }
    else if (!strcmp(model, "TG-5") || // Olympus TG-5; 0x4434353933
             !strcmp(model, "TG-6"))   // Olympus TG-6; 0x4434363033
    {
      width -= 26;
    }
  }
  else if (!strcmp(model, "N Digital")) // Contax N Digital
  {
    height = 2047;
    width = 3072;
    filters = 0x61616161;
    data_offset = 0x1a00;
    load_raw = &LibRaw::packed_load_raw;
  }
  else if (makeIs(LIBRAW_CAMERAMAKER_Sony))
  {
    if (!strcmp(model, "DSC-F828")) // Sony DSC-F828
    {
      width = 3288;
      left_margin = 5;
      mask[1][3] = -17;
      data_offset = 862144;
      load_raw = &LibRaw::sony_load_raw;
      filters = 0x9c9c9c9c;
      colors = 4;
      strcpy(cdesc, "RGBE");
    }
    else if (!strcmp(model, "DSC-V3")) // Sony DSC-V3
    {
      width = 3109;
      left_margin = 59;
      mask[0][1] = 9;
      data_offset = 787392;
      load_raw = &LibRaw::sony_load_raw;
    }
    else if (raw_width == 3984) /* Sony DSC-R1; 0x002 */
    {
      width = 3925;
      order = 0x4d4d;
    }
    else if (raw_width == 4288) /* Sony ILCE-7S, ILCE-7SM2, DSLR-A700,
                                   DSLR-A500; 0x13e, 0x15e, 0x102, 0x112 */
    {
      width -= 32;
    }
    else if (raw_width == 4600) /* Sony DSLR-A290, DSLR-A350, DSLR-A380; 0x10a,
                                   0x104, 0x107 */
    {
      if (!strcmp(model, "DSLR-A350")) /* Sony DSLR-A350; 0x104 */
        height -= 4;
      black = 0;
    }
    else if (raw_width ==
             4928) /* Sony DSLR-A580, NEX-C3, SLT-A35, DSC-HX99, SLT-A55V,
                      NEX-5N, SLT-A37, SLT-A57, NEX-F3, NEX-6, NEX-5R, NEX-3N,
                      NEX-5T; 0x11b, 0x11c, 0x11d, 0x16f, 0x119, 0x120, 0x123,
                      0x124, 0x125, 0x127, 0x128, 0x131, 0x133 */
    {
      if (height < 3280)
        width -= 8;
    }
    else if (raw_width ==
             5504) /* Sony ILCE-3000, SLT-A58, DSC-RX100M3, ILCE-QX1,
                      DSC-RX10M4, DSC-RX100M6, DSC-RX100, DSC-RX100M2, DSC-RX10,
                      ILCE-5000, DSC-RX100M4, DSC-RX10M2, DSC-RX10M3,
                      DSC-RX100M5, DSC-RX100M5A; 0x12e, 0x12f, 0x13d, 0x15a,
                      0x16d, 0x16e, 0x129, 0x134, 0x135, 0x139, 0x155, 0x156,
                      0x163, 0x164, 0x171 */
    {
      width -= height > 3664 ? 8 : 32;
    }
    else if (raw_width ==
             6048) /* Sony SLT-A65, DSC-RX1, SLT-A77, DSC-RX1, ILCA-77M2,
                      ILCE-7M3, NEX-7, SLT-A99V, ILCE-7, DSC-RX1R, ILCE-6000,
                      ILCE-5100, ILCE-7M2, ILCA-68, ILCE-6300, ILCE-9,
                      ILCE-6500, ILCE-6400; 0x11e, 0x11f, 0x12a, 0x13f, 0x16b,
                      0x121, 0x126, 0x132, 0x136, 0x138, 0x153, 0x154, 0x161,
                      0x165, 0x166, 0x168, 0x173 */
    {
      width -= 24;
      if (strstr(normalized_model, "RX1") ||
          strstr(normalized_model,
                 "A99")) /* Sony DSC-RX1, SLT-A99V; 0x12a, 0x126 */
        width -= 6;
    }
    else if (raw_width == 7392) /* Sony ILCE-7R; 0x137 */
    {
      width -= 30;
    }
    else if (raw_width ==
             8000) /* Sony ILCE-7RM2, ILCE-7RM2, ILCE-7RM3, DSC-RX1RM2,
                      ILCA-99M2; 0x15b, 0x16a, 0x158, 0x162 */
    {
      width -= 32;
    }
    else if (raw_width == 9600) /* Sony ILCE-7RM4*/
    {
      width -= 32;
    }
    else if (!strcmp(model, "DSLR-A100")) /* Sony DSLR-A100; 0x100 */
    {
      if (width == 3880)
      {
        height--;
        width = ++raw_width;
      }
      else
      {
        height -= 4;
        width -= 4;
        order = 0x4d4d;
        load_flags = 2;
      }
      filters = 0x61616161;
    }
  }

  else if (!strcmp(model, "PIXL"))
  {
    height -= top_margin = 4;
    width -= left_margin = 32;
    gamma_curve(0, 7, 1, 255);
  }
  else if (!strcmp(model, "C603") || // Kodak C603
           !strcmp(model, "C330") || // Kodak C303
           !strcmp(model, "12MP"))
  {
    order = 0x4949;
    if (filters && data_offset)
    {
      fseek(ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET);
      read_shorts(curve, 256);
    }
    else
      gamma_curve(0, 3.875, 1, 255);
    load_raw = filters ? &LibRaw::eight_bit_load_raw
                       : strcmp(model, "C330") ? &LibRaw::kodak_c603_load_raw
                                               : &LibRaw::kodak_c330_load_raw;
    load_flags = tiff_bps > 16;
    tiff_bps = 8;
  }
  else if (!strncasecmp(model, "EasyShare", 9))
  {
    data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000;
    load_raw = &LibRaw::packed_load_raw;
  }
  else if (makeIs(LIBRAW_CAMERAMAKER_Kodak))
  {
    if (filters == UINT_MAX)
      filters = 0x61616161;
    if (!strncmp(model, "NC2000", 6) || !strncmp(model, "EOSDCS", 6) ||
        !strncmp(model, "DCS4", 4))
    {
      width -= 4;
      left_margin = 2;
    }
    else if (!strcmp(model, "DCS660M"))
    {
      black = 214;
    }
    if (!strcmp(model + 4, "20X"))
      strcpy(cdesc, "MYCY");
    if (!strcmp(model, "DC25"))
    {
      data_offset = 15424;
    }
    if (!strncmp(model, "DC2", 3))
    {
      raw_height = 2 + (height = 242);
      if (!strncmp(model, "DC290", 5))
        iso_speed = 100;
      if (!strncmp(model, "DC280", 5))
        iso_speed = 70;
      if (flen < 100000)
      {
        raw_width = 256;
        width = 249;
        pixel_aspect = (4.0 * height) / (3.0 * width);
      }
      else
      {
        raw_width = 512;
        width = 501;
        pixel_aspect = (493.0 * height) / (373.0 * width);
      }
      top_margin = left_margin = 1;
      colors = 4;
      filters = 0x8d8d8d8d;
      simple_coeff(1);
      pre_mul[1] = 1.179;
      pre_mul[2] = 1.209;
      pre_mul[3] = 1.036;
      load_raw = &LibRaw::eight_bit_load_raw;
    }
    else if (!strcmp(model, "DC40"))
    {
      height = 512;
      width = 768;
      data_offset = 1152;
      load_raw = &LibRaw::kodak_radc_load_raw;
      tiff_bps = 12;
      FORC4 cam_mul[c] = 1.0f;
    }
    else if (!strcmp(model, "DC50"))
    {
      height = 512;
      width = 768;
      iso_speed = 84;
      data_offset = 19712;
      load_raw = &LibRaw::kodak_radc_load_raw;
      FORC4 cam_mul[c] = 1.0f;
    }
    else if (!strcmp(model, "DC120"))
    {
      raw_height = height = 976;
      raw_width = width = 848;
      iso_speed = 160;
      pixel_aspect = height / 0.75 / width;
      load_raw = tiff_compress == 7 ? &LibRaw::kodak_jpeg_load_raw
                                    : &LibRaw::kodak_dc120_load_raw;
    }
    else if (!strcmp(model, "DCS200"))
    {
      thumb_height = 128;
      thumb_width = 192;
      thumb_offset = 6144;
      thumb_misc = 360;
      iso_speed = 140;
      write_thumb = &LibRaw::layer_thumb;
      black = 17;
    }
  }
  else if (!strcmp(model, "Fotoman Pixtura"))
  {
    height = 512;
    width = 768;
    data_offset = 3632;
    load_raw = &LibRaw::kodak_radc_load_raw;
    filters = 0x61616161;
    simple_coeff(2);
  }
  else if (!strncmp(model, "QuickTake", 9))
  {
    if (head[5])
      strcpy(model + 10, "200");
    fseek(ifp, 544, SEEK_SET);
    height = get2();
    width = get2();
    data_offset = (get4(), get2()) == 30 ? 738 : 736;
    if (height > width)
    {
      SWAP(height, width);
      fseek(ifp, data_offset - 6, SEEK_SET);
      flip = ~get2() & 3 ? 5 : 6;
    }
    filters = 0x61616161;
  }
  else if (makeIs(LIBRAW_CAMERAMAKER_Rollei) && !load_raw)
  {
    switch (raw_width)
    {
    case 1316: // Rollei d530flex
      height = 1030;
      width = 1300;
      top_margin = 1;
      left_margin = 6;
      break;
    case 2568:
      height = 1960;
      width = 2560;
      top_margin = 2;
      left_margin = 8;
    }
    filters = 0x16161616;
    load_raw = &LibRaw::rollei_load_raw;
  }
  else if (!strcmp(model, "GRAS-50S5C"))
  {
    height = 2048;
    width = 2440;
    load_raw = &LibRaw::unpacked_load_raw;
    data_offset = 0;
    filters = 0x49494949;
    order = 0x4949;
    maximum = 0xfffC;
  }
  else if (!strcmp(model, "BB-500CL"))
  {
    height = 2058;
    width = 2448;
    load_raw = &LibRaw::unpacked_load_raw;
    data_offset = 0;
    filters = 0x94949494;
    order = 0x4949;
    maximum = 0x3fff;
  }
  else if (!strcmp(model, "BB-500GE"))
  {
    height = 2058;
    width = 2456;
    load_raw = &LibRaw::unpacked_load_raw;
    data_offset = 0;
    filters = 0x94949494;
    order = 0x4949;
    maximum = 0x3fff;
  }
  else if (!strcmp(model, "SVS625CL"))
  {
    height = 2050;
    width = 2448;
    load_raw = &LibRaw::unpacked_load_raw;
    data_offset = 0;
    filters = 0x94949494;
    order = 0x4949;
    maximum = 0x0fff;
  }
  /* Early reject for damaged images */
  if (!load_raw || height < 22 || width < 22 ||
      (tiff_bps > 16 &&
       (load_raw != &LibRaw::deflate_dng_load_raw &&
        load_raw != &LibRaw::float_dng_load_raw_placeholder)) ||
      tiff_samples > 4 || colors > 4 ||
      colors < 1
      /* alloc in unpack() may be fooled by size adjust */
      || ((int)width + (int)left_margin > 65535) ||
      ((int)height + (int)top_margin > 65535))
  {
    is_raw = 0;
    RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2);
    return;
  }
  if (!model[0])
  {
    sprintf(model, "%dx%d", width, height);
    strcpy(normalized_model, model);
  }

  if (!(imgdata.params.raw_processing_options &
        LIBRAW_PROCESSING_ZEROFILTERS_FOR_MONOCHROMETIFFS) &&
      (filters == UINT_MAX)) // Default dcraw behaviour
    filters = 0x94949494;
  else if (filters == UINT_MAX)
  {
    if (tiff_nifds > 0 && tiff_samples == 1)
    {
      colors = 1;
      filters = 0;
    }
    else
      filters = 0x94949494;
  }

  if (thumb_offset && !thumb_height)
  {
    fseek(ifp, thumb_offset, SEEK_SET);
    if (ljpeg_start(&jh, 1))
    {
      thumb_width = jh.wide;
      thumb_height = jh.high;
    }
  }

dng_skip:
  if (dng_version) /* Override black level by DNG tags */
  {
    /* copy DNG data from per-IFD field to color.dng */
    int iifd = find_ifd_by_offset(data_offset);
    int pifd = find_ifd_by_offset(thumb_offset);

#define CFAROUND(value, filters)                                               \
  filters ? (filters >= 1000 ? ((value + 1) / 2) * 2 : ((value + 5) / 6) * 6)  \
          : value

#define IFDCOLORINDEX(ifd, subset, bit)                                        \
  (tiff_ifd[ifd].dng_color[subset].parsedfields & bit)                         \
      ? ifd                                                                    \
      : ((tiff_ifd[0].dng_color[subset].parsedfields & bit) ? 0 : -1)

#define IFDLEVELINDEX(ifd, bit)                                                \
  (tiff_ifd[ifd].dng_levels.parsedfields & bit)                                \
      ? ifd                                                                    \
      : ((tiff_ifd[0].dng_levels.parsedfields & bit) ? 0 : -1)

#define COPYARR(to, from) memmove(&to, &from, sizeof(from))

    if (iifd < tiff_nifds && iifd >=0)
    {
      int sidx;
      // Per field, not per structure
      if (!(imgdata.params.raw_processing_options &
          LIBRAW_PROCESSING_DONT_CHECK_DNG_ILLUMINANT))
      {
        int illidx[2], cmidx[2], calidx[2], abidx;
        for (int i = 0; i < 2; i++)
        {
          illidx[i] = IFDCOLORINDEX(iifd, i, LIBRAW_DNGFM_ILLUMINANT);
          cmidx[i] = IFDCOLORINDEX(iifd, i, LIBRAW_DNGFM_COLORMATRIX);
          calidx[i] = IFDCOLORINDEX(iifd, i, LIBRAW_DNGFM_CALIBRATION);
        }
        abidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_ANALOGBALANCE);
        // Data found, all in same ifd, illuminants are inited
        if (illidx[0] >= 0 && illidx[0] < tiff_nifds &&
            illidx[0] == illidx[1] && illidx[0] == cmidx[0] &&
            illidx[0] == cmidx[1] &&
            tiff_ifd[illidx[0]].dng_color[0].illuminant > 0 &&
            tiff_ifd[illidx[0]].dng_color[1].illuminant > 0)
        {
          sidx = illidx[0]; // => selected IFD
          double cc[4][4], cm[4][3], cam_xyz[4][3];
          // CM -> Color Matrix
          // CC -> Camera calibration
          for (int j = 0; j < 4; j++)
            for (int i = 0; i < 4; i++)
              cc[j][i] = i == j;
          int colidx = -1;

          // IS D65 here?
          for (int i = 0; i < 2; i++)
          {
            int ill = tiff_ifd[sidx].dng_color[i].illuminant;
            if (tiff_ifd[sidx].dng_color[i].illuminant == LIBRAW_WBI_D65)
            {
              colidx = i;
              break;
            }
          }

          // Other daylight-type ill
          if (colidx < 0)
            for (int i = 0; i < 2; i++)
            {
              int ill = tiff_ifd[sidx].dng_color[i].illuminant;
              if (ill == LIBRAW_WBI_Daylight || ill == LIBRAW_WBI_D55 ||
                  ill == LIBRAW_WBI_D75 || ill == LIBRAW_WBI_D50 ||
                  ill == LIBRAW_WBI_Flash)
              {
                colidx = i;
                break;
              }
            }
          if (colidx >= 0) // Selected
          {
            // Init camera matrix from DNG
            FORCC for (int j = 0; j < 3; j++) cm[c][j] =
                tiff_ifd[sidx].dng_color[colidx].colormatrix[c][j];

            if (calidx[colidx] == sidx)
            {
              for (int i = 0; i < colors; i++)
                FORCC
              cc[i][c] = tiff_ifd[sidx].dng_color[colidx].calibration[i][c];
            }

            if (abidx == sidx)
              for (int i = 0; i < colors; i++)
                FORCC cc[i][c] *= tiff_ifd[sidx].dng_levels.analogbalance[i];
            int j;
            FORCC for (int i = 0; i < 3; i++) for (cam_xyz[c][i] = j = 0;
                                                   j < colors; j++)
                cam_xyz[c][i] +=
                cc[c][j] * cm[j][i]; // add AsShotXY later * xyz[i];
            cam_xyz_coeff(cmatrix, cam_xyz);
          }
        }
      }

      if (imgdata.params.raw_processing_options &
          LIBRAW_PROCESSING_USE_DNG_DEFAULT_CROP)
      {
        sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPORIGIN);
        int sidx2 = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPSIZE);
        if (sidx >= 0 && sidx == sidx2 &&
            tiff_ifd[sidx].dng_levels.default_crop[2] > 0 &&
            tiff_ifd[sidx].dng_levels.default_crop[3] > 0)
        {
          int lm = tiff_ifd[sidx].dng_levels.default_crop[0];
          int lmm = CFAROUND(lm, filters);
          int tm = tiff_ifd[sidx].dng_levels.default_crop[1];
          int tmm = CFAROUND(tm, filters);
          int ww = tiff_ifd[sidx].dng_levels.default_crop[2];
          int hh = tiff_ifd[sidx].dng_levels.default_crop[3];
          if (lmm > lm)
            ww -= (lmm - lm);
          if (tmm > tm)
            hh -= (tmm - tm);
          if (left_margin + lm + ww <= raw_width &&
              top_margin + tm + hh <= raw_height)
          {
            left_margin += lmm;
            top_margin += tmm;
            width = ww;
            height = hh;
          }
        }
      }
      if (!(imgdata.color.dng_color[0].parsedfields &
            LIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes)
      {
        sidx = IFDCOLORINDEX(iifd, 0, LIBRAW_DNGFM_FORWARDMATRIX);
        if (sidx >= 0)
          COPYARR(imgdata.color.dng_color[0].forwardmatrix,
                  tiff_ifd[sidx].dng_color[0].forwardmatrix);
      }
      if (!(imgdata.color.dng_color[1].parsedfields &
            LIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes)
      {
        sidx = IFDCOLORINDEX(iifd, 1, LIBRAW_DNGFM_FORWARDMATRIX);
        if (sidx >= 0)
          COPYARR(imgdata.color.dng_color[1].forwardmatrix,
                  tiff_ifd[sidx].dng_color[1].forwardmatrix);
      }
      for (int ss = 0; ss < 2; ss++)
      {
        sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_COLORMATRIX);
        if (sidx >= 0)
          COPYARR(imgdata.color.dng_color[ss].colormatrix,
                  tiff_ifd[sidx].dng_color[ss].colormatrix);

        sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_CALIBRATION);
        if (sidx >= 0)
          COPYARR(imgdata.color.dng_color[ss].calibration,
                  tiff_ifd[sidx].dng_color[ss].calibration);

        sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_ILLUMINANT);
        if (sidx >= 0)
          imgdata.color.dng_color[ss].illuminant =
              tiff_ifd[sidx].dng_color[ss].illuminant;
      }
      // Levels
      sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_ANALOGBALANCE);
      if (sidx >= 0)
        COPYARR(imgdata.color.dng_levels.analogbalance,
                tiff_ifd[sidx].dng_levels.analogbalance);

      sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_BASELINEEXPOSURE);
      if (sidx >= 0)
        imgdata.color.dng_levels.baseline_exposure =
            tiff_ifd[sidx].dng_levels.baseline_exposure;

      sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_WHITE);
      if(sidx >= 0 && tiff_ifd[sidx].dng_levels.dng_whitelevel[0])
          COPYARR(imgdata.color.dng_levels.dng_whitelevel,
            tiff_ifd[sidx].dng_levels.dng_whitelevel);
      else if(tiff_ifd[iifd].sample_format <= 2  && tiff_ifd[iifd].bps > 0 && tiff_ifd[iifd].bps < 32)
          FORC4
            imgdata.color.dng_levels.dng_whitelevel[c] = (1<<tiff_ifd[iifd].bps)-1;



      sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_ASSHOTNEUTRAL);
      if (sidx >= 0)
      {
        COPYARR(imgdata.color.dng_levels.asshotneutral,
                tiff_ifd[sidx].dng_levels.asshotneutral);
        if (imgdata.color.dng_levels.asshotneutral[0])
        {
          cam_mul[3] = 0;
          FORCC
          if (fabs(imgdata.color.dng_levels.asshotneutral[c]) > 0.0001)
            cam_mul[c] = 1 / imgdata.color.dng_levels.asshotneutral[c];
        }
      }
      sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_BLACK);
      if (sidx >= 0)
      {
        imgdata.color.dng_levels.dng_fblack =
            tiff_ifd[sidx].dng_levels.dng_fblack;
        imgdata.color.dng_levels.dng_black =
            tiff_ifd[sidx].dng_levels.dng_black;
        COPYARR(imgdata.color.dng_levels.dng_cblack,
                tiff_ifd[sidx].dng_levels.dng_cblack);
        COPYARR(imgdata.color.dng_levels.dng_fcblack,
                tiff_ifd[sidx].dng_levels.dng_fcblack);
      }


      if (pifd >= 0)
      {
        sidx = IFDLEVELINDEX(pifd, LIBRAW_DNGFM_PREVIEWCS);
        if (sidx >= 0)
          imgdata.color.dng_levels.preview_colorspace =
              tiff_ifd[sidx].dng_levels.preview_colorspace;
      }
      sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_OPCODE2);
      if (sidx >= 0)
        meta_offset = tiff_ifd[sidx].opcode2_offset;

      sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_LINTABLE);
      INT64 linoff = -1;
      int linlen = 0;
      if (sidx >= 0)
      {
        linoff = tiff_ifd[sidx].lineartable_offset;
        linlen = tiff_ifd[sidx].lineartable_len;
      }

      if (linoff >= 0 && linlen > 0)
      {
        INT64 pos = ftell(ifp);
        fseek(ifp, linoff, SEEK_SET);
        linear_table(linlen);
        fseek(ifp, pos, SEEK_SET);
      }
      // Need to add curve too
    }
    /* Copy DNG black level to LibRaw's */
    if(load_raw == &LibRaw::lossy_dng_load_raw)
    {
        maximum = 0xffff;
        FORC4 imgdata.color.linear_max[c]=imgdata.color.dng_levels.dng_whitelevel[c] = 0xffff;
    }
    else
    {
        maximum = imgdata.color.dng_levels.dng_whitelevel[0];
    }
    black = imgdata.color.dng_levels.dng_black;

    if(tiff_samples > 1 && tiff_samples <= 4 && imgdata.color.dng_levels.dng_cblack[4] * imgdata.color.dng_levels.dng_cblack[5] * tiff_samples
         == imgdata.color.dng_levels.dng_cblack[LIBRAW_CBLACK_SIZE-1])
    {
        /* Special case, per_channel blacks in RepeatDim, average for per-channel */
        int csum[4]={0,0,0,0}, ccount[4] = {0,0,0,0};
        int i = 6;
        for(int row = 0; row < imgdata.color.dng_levels.dng_cblack[4]; row++)
            for(int col = 0; col < imgdata.color.dng_levels.dng_cblack[5]; col++)
                for(int c = 0; c < tiff_samples; c++)
                {
                    csum[c] += imgdata.color.dng_levels.dng_cblack[i];
                    ccount[c]++;
                    i++;
                }
        for(int c = 0; c < 4; c++)
            if(ccount[c])
                imgdata.color.dng_levels.dng_cblack[c] += csum[c]/ccount[c];
        imgdata.color.dng_levels.dng_cblack[4] = imgdata.color.dng_levels.dng_cblack[5] = 0;
    }

    memmove(cblack,imgdata.color.dng_levels.dng_cblack,sizeof(cblack));

    if (iifd < tiff_nifds && iifd >=0)
    {
        int sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_LINEARRESPONSELIMIT);
        if (sidx >= 0)
        {
            imgdata.color.dng_levels.LinearResponseLimit =
                tiff_ifd[sidx].dng_levels.LinearResponseLimit;
            if (imgdata.color.dng_levels.LinearResponseLimit > 0.1 &&
                imgdata.color.dng_levels.LinearResponseLimit <= 1.0)
            {
                // And approx promote it to linear_max:
                int bl4 = 0, bl64 = 0;
                for (int chan = 0; chan < colors && chan < 4; chan++)
                    bl4 += cblack[chan];
                bl4 /= LIM(colors, 1, 4);

                if (cblack[4] * cblack[5] > 0)
                {
                    unsigned cnt = 0;
                    for (unsigned c = 0; c < 4096 && c < cblack[4] * cblack[5]; c++)
                    {
                        bl64 += cblack[c + 6];
                        cnt++;
                    }
                    bl64 /= LIM(cnt, 1, 4096);
                }
                int rblack = black + bl4 + bl64;
                for (int chan = 0; chan < colors && chan < 4; chan++)
                    imgdata.color.linear_max[chan] =
                    (maximum - rblack) *
                    imgdata.color.dng_levels.LinearResponseLimit +
                    rblack;
            }
        }
    }
  }

  /* Early reject for damaged images */
  if (!load_raw || height < 22 || width < 22 ||
      (tiff_bps > 16 &&
       (load_raw != &LibRaw::deflate_dng_load_raw &&
        load_raw != &LibRaw::float_dng_load_raw_placeholder)) ||
      tiff_samples > 4 || colors > 4 || colors < 1)
  {
    is_raw = 0;
    RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2);
    return;
  }
  {
    // Check cam_mul range
    int cmul_ok = 1;
    FORCC if (cam_mul[c] <= 0.001f) cmul_ok = 0;
    ;

    if (cmul_ok)
    {
      double cmin = cam_mul[0], cmax;
      double cnorm[4];
      FORCC cmin = MIN(cmin, cam_mul[c]);
      FORCC cnorm[c] = cam_mul[c] / cmin;
      cmax = cmin = cnorm[0];
      FORCC
      {
        cmin = MIN(cmin, cnorm[c]);
        cmax = MIN(cmax, cnorm[c]);
      }
      if (cmin <= 0.01f || cmax > 100.f)
        cmul_ok = false;
    }
    if (!cmul_ok)
    {
      if (cam_mul[0] > 0)
        cam_mul[0] = 0;
      cam_mul[3] = 0;
    }
  }
  if ((use_camera_matrix & ((use_camera_wb || dng_version) | 0x2)) &&
      cmatrix[0][0] > 0.125)
  {
    memcpy(rgb_cam, cmatrix, sizeof cmatrix);
    raw_color = 0;
  }
  if (raw_color && !CM_found)
    CM_found = adobe_coeff(maker_index, normalized_model);
  else if ((imgdata.color.cam_xyz[0][0] < 0.01) && !CM_found)
    CM_found = adobe_coeff(maker_index, normalized_model, 1);

  if (load_raw == &LibRaw::kodak_radc_load_raw)
    if ((raw_color) && !CM_found)
		CM_found = adobe_coeff(LIBRAW_CAMERAMAKER_Apple, "Quicktake");

  if ((maker_index != LIBRAW_CAMERAMAKER_Unknown) && normalized_model[0])
    SetStandardIlluminants (maker_index, normalized_model);

  // Clear erorneus fuji_width if not set through parse_fuji or for DNG
  if (fuji_width && !dng_version &&
      !(imgdata.process_warnings & LIBRAW_WARN_PARSEFUJI_PROCESSED))
    fuji_width = 0;

  if (fuji_width)
  {
    fuji_width = width >> !fuji_layout;
    filters = fuji_width & 1 ? 0x94949494 : 0x49494949;
    width = (height >> fuji_layout) + fuji_width;
    height = width - 1;
    pixel_aspect = 1;
  }
  else
  {
    if (raw_height < height)
      raw_height = height;
    if (raw_width < width)
      raw_width = width;
  }
  if (!tiff_bps)
    tiff_bps = 12;
  if (!maximum)
  {
    maximum = (1 << tiff_bps) - 1;
    if (maximum < 0x10000 && curve[maximum] > 0 &&
        load_raw == &LibRaw::sony_arw2_load_raw)
      maximum = curve[maximum];
  }
  if (maximum > 0xffff)
    maximum = 0xffff;
  if (!load_raw || height < 22 || width < 22 ||
      (tiff_bps > 16 &&
       (load_raw != &LibRaw::deflate_dng_load_raw &&
        load_raw != &LibRaw::float_dng_load_raw_placeholder)) ||
      tiff_samples > 6 || colors > 4)
    is_raw = 0;

  if (raw_width < 22 || raw_width > 64000 || raw_height < 22 ||
      raw_height > 64000)
    is_raw = 0;

#ifdef NO_JASPER
  if (load_raw == &LibRaw::redcine_load_raw)
  {
    is_raw = 0;
    imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER;
  }
#endif
#ifdef NO_JPEG
  if (load_raw == &LibRaw::kodak_jpeg_load_raw ||
      load_raw == &LibRaw::lossy_dng_load_raw)
  {
    is_raw = 0;
    imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB;
  }
#endif
  if (!cdesc[0])
    strcpy(cdesc, colors == 3 ? "RGBG" : "GMCY");
  if (!raw_height)
    raw_height = height;
  if (!raw_width)
    raw_width = width;
  if (filters > 999 && colors == 3)
    filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) &
               filters << 1;
notraw:
  if (flip == UINT_MAX)
    flip = tiff_flip;
  if (flip == UINT_MAX)
    flip = 0;

  // Convert from degrees to bit-field if needed
  if (flip > 89 || flip < -89)
  {
    switch ((flip + 3600) % 360)
    {
    case 270:
      flip = 5;
      break;
    case 180:
      flip = 3;
      break;
    case 90:
      flip = 6;
      break;
    }
  }

  if (pana_bpp)
    imgdata.color.raw_bps = pana_bpp;
  else if ((load_raw == &LibRaw::phase_one_load_raw) ||
           (load_raw == &LibRaw::phase_one_load_raw_c))
    imgdata.color.raw_bps = ph1.format;
  else
    imgdata.color.raw_bps = tiff_bps;

  RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2);
}

Project: LibRaw

void LibRaw::dcb_decide(float (*image2)[3], float (*image3)[3])
{
  int row, col, c, d, u = width, v = 2 * u, indx;
  float current, current2, current3;

  for (row = 2; row < height - 2; row++)
    for (col = 2 + (FC(row, 2) & 1), indx = row * width + col, c = FC(row, col);
         col < u - 2; col += 2, indx += 2)
    {

      d = ABS(c - 2);

      current = MAX(image[indx + v][c],
                    MAX(image[indx - v][c],
                        MAX(image[indx - 2][c], image[indx + 2][c]))) -
                MIN(image[indx + v][c],
                    MIN(image[indx - v][c],
                        MIN(image[indx - 2][c], image[indx + 2][c]))) +
                MAX(image[indx + 1 + u][d],
                    MAX(image[indx + 1 - u][d],
                        MAX(image[indx - 1 + u][d], image[indx - 1 - u][d]))) -
                MIN(image[indx + 1 + u][d],
                    MIN(image[indx + 1 - u][d],
                        MIN(image[indx - 1 + u][d], image[indx - 1 - u][d])));

      current2 =
          MAX(image2[indx + v][d],
              MAX(image2[indx - v][d],
                  MAX(image2[indx - 2][d], image2[indx + 2][d]))) -
          MIN(image2[indx + v][d],
              MIN(image2[indx - v][d],
                  MIN(image2[indx - 2][d], image2[indx + 2][d]))) +
          MAX(image2[indx + 1 + u][c],
              MAX(image2[indx + 1 - u][c],
                  MAX(image2[indx - 1 + u][c], image2[indx - 1 - u][c]))) -
          MIN(image2[indx + 1 + u][c],
              MIN(image2[indx + 1 - u][c],
                  MIN(image2[indx - 1 + u][c], image2[indx - 1 - u][c])));

      current3 =
          MAX(image3[indx + v][d],
              MAX(image3[indx - v][d],
                  MAX(image3[indx - 2][d], image3[indx + 2][d]))) -
          MIN(image3[indx + v][d],
              MIN(image3[indx - v][d],
                  MIN(image3[indx - 2][d], image3[indx + 2][d]))) +
          MAX(image3[indx + 1 + u][c],
              MAX(image3[indx + 1 - u][c],
                  MAX(image3[indx - 1 + u][c], image3[indx - 1 - u][c]))) -
          MIN(image3[indx + 1 + u][c],
              MIN(image3[indx + 1 - u][c],
                  MIN(image3[indx - 1 + u][c], image3[indx - 1 - u][c])));

      if (ABS(current - current2) < ABS(current - current3))
        image[indx][1] = image2[indx][1];
      else
        image[indx][1] = image3[indx][1];
    }
}