Blame gtkmm-osx/jpeg-6b/jquant2.c

darco 56a656
/*
darco 56a656
 * jquant2.c
darco 56a656
 *
darco 56a656
 * Copyright (C) 1991-1996, Thomas G. Lane.
darco 56a656
 * This file is part of the Independent JPEG Group's software.
darco 56a656
 * For conditions of distribution and use, see the accompanying README file.
darco 56a656
 *
darco 56a656
 * This file contains 2-pass color quantization (color mapping) routines.
darco 56a656
 * These routines provide selection of a custom color map for an image,
darco 56a656
 * followed by mapping of the image to that color map, with optional
darco 56a656
 * Floyd-Steinberg dithering.
darco 56a656
 * It is also possible to use just the second pass to map to an arbitrary
darco 56a656
 * externally-given color map.
darco 56a656
 *
darco 56a656
 * Note: ordered dithering is not supported, since there isn't any fast
darco 56a656
 * way to compute intercolor distances; it's unclear that ordered dither's
darco 56a656
 * fundamental assumptions even hold with an irregularly spaced color map.
darco 56a656
 */
darco 56a656
darco 56a656
#define JPEG_INTERNALS
darco 56a656
#include "jinclude.h"
darco 56a656
#include "jpeglib.h"
darco 56a656
darco 56a656
#ifdef QUANT_2PASS_SUPPORTED
darco 56a656
darco 56a656
darco 56a656
/*
darco 56a656
 * This module implements the well-known Heckbert paradigm for color
darco 56a656
 * quantization.  Most of the ideas used here can be traced back to
darco 56a656
 * Heckbert's seminal paper
darco 56a656
 *   Heckbert, Paul.  "Color Image Quantization for Frame Buffer Display",
darco 56a656
 *   Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
darco 56a656
 *
darco 56a656
 * In the first pass over the image, we accumulate a histogram showing the
darco 56a656
 * usage count of each possible color.  To keep the histogram to a reasonable
darco 56a656
 * size, we reduce the precision of the input; typical practice is to retain
darco 56a656
 * 5 or 6 bits per color, so that 8 or 4 different input values are counted
darco 56a656
 * in the same histogram cell.
darco 56a656
 *
darco 56a656
 * Next, the color-selection step begins with a box representing the whole
darco 56a656
 * color space, and repeatedly splits the "largest" remaining box until we
darco 56a656
 * have as many boxes as desired colors.  Then the mean color in each
darco 56a656
 * remaining box becomes one of the possible output colors.
darco 56a656
 * 
darco 56a656
 * The second pass over the image maps each input pixel to the closest output
darco 56a656
 * color (optionally after applying a Floyd-Steinberg dithering correction).
darco 56a656
 * This mapping is logically trivial, but making it go fast enough requires
darco 56a656
 * considerable care.
darco 56a656
 *
darco 56a656
 * Heckbert-style quantizers vary a good deal in their policies for choosing
darco 56a656
 * the "largest" box and deciding where to cut it.  The particular policies
darco 56a656
 * used here have proved out well in experimental comparisons, but better ones
darco 56a656
 * may yet be found.
darco 56a656
 *
darco 56a656
 * In earlier versions of the IJG code, this module quantized in YCbCr color
darco 56a656
 * space, processing the raw upsampled data without a color conversion step.
darco 56a656
 * This allowed the color conversion math to be done only once per colormap
darco 56a656
 * entry, not once per pixel.  However, that optimization precluded other
darco 56a656
 * useful optimizations (such as merging color conversion with upsampling)
darco 56a656
 * and it also interfered with desired capabilities such as quantizing to an
darco 56a656
 * externally-supplied colormap.  We have therefore abandoned that approach.
darco 56a656
 * The present code works in the post-conversion color space, typically RGB.
darco 56a656
 *
darco 56a656
 * To improve the visual quality of the results, we actually work in scaled
darco 56a656
 * RGB space, giving G distances more weight than R, and R in turn more than
darco 56a656
 * B.  To do everything in integer math, we must use integer scale factors.
darco 56a656
 * The 2/3/1 scale factors used here correspond loosely to the relative
darco 56a656
 * weights of the colors in the NTSC grayscale equation.
darco 56a656
 * If you want to use this code to quantize a non-RGB color space, you'll
darco 56a656
 * probably need to change these scale factors.
darco 56a656
 */
darco 56a656
darco 56a656
#define R_SCALE 2		/* scale R distances by this much */
darco 56a656
#define G_SCALE 3		/* scale G distances by this much */
darco 56a656
#define B_SCALE 1		/* and B by this much */
darco 56a656
darco 56a656
/* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
darco 56a656
 * in jmorecfg.h.  As the code stands, it will do the right thing for R,G,B
darco 56a656
 * and B,G,R orders.  If you define some other weird order in jmorecfg.h,
darco 56a656
 * you'll get compile errors until you extend this logic.  In that case
darco 56a656
 * you'll probably want to tweak the histogram sizes too.
darco 56a656
 */
darco 56a656
darco 56a656
#if RGB_RED == 0
darco 56a656
#define C0_SCALE R_SCALE
darco 56a656
#endif
darco 56a656
#if RGB_BLUE == 0
darco 56a656
#define C0_SCALE B_SCALE
darco 56a656
#endif
darco 56a656
#if RGB_GREEN == 1
darco 56a656
#define C1_SCALE G_SCALE
darco 56a656
#endif
darco 56a656
#if RGB_RED == 2
darco 56a656
#define C2_SCALE R_SCALE
darco 56a656
#endif
darco 56a656
#if RGB_BLUE == 2
darco 56a656
#define C2_SCALE B_SCALE
darco 56a656
#endif
darco 56a656
darco 56a656
darco 56a656
/*
darco 56a656
 * First we have the histogram data structure and routines for creating it.
darco 56a656
 *
darco 56a656
 * The number of bits of precision can be adjusted by changing these symbols.
darco 56a656
 * We recommend keeping 6 bits for G and 5 each for R and B.
darco 56a656
 * If you have plenty of memory and cycles, 6 bits all around gives marginally
darco 56a656
 * better results; if you are short of memory, 5 bits all around will save
darco 56a656
 * some space but degrade the results.
darco 56a656
 * To maintain a fully accurate histogram, we'd need to allocate a "long"
darco 56a656
 * (preferably unsigned long) for each cell.  In practice this is overkill;
darco 56a656
 * we can get by with 16 bits per cell.  Few of the cell counts will overflow,
darco 56a656
 * and clamping those that do overflow to the maximum value will give close-
darco 56a656
 * enough results.  This reduces the recommended histogram size from 256Kb
darco 56a656
 * to 128Kb, which is a useful savings on PC-class machines.
darco 56a656
 * (In the second pass the histogram space is re-used for pixel mapping data;
darco 56a656
 * in that capacity, each cell must be able to store zero to the number of
darco 56a656
 * desired colors.  16 bits/cell is plenty for that too.)
darco 56a656
 * Since the JPEG code is intended to run in small memory model on 80x86
darco 56a656
 * machines, we can't just allocate the histogram in one chunk.  Instead
darco 56a656
 * of a true 3-D array, we use a row of pointers to 2-D arrays.  Each
darco 56a656
 * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
darco 56a656
 * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries.  Note that
darco 56a656
 * on 80x86 machines, the pointer row is in near memory but the actual
darco 56a656
 * arrays are in far memory (same arrangement as we use for image arrays).
darco 56a656
 */
darco 56a656
darco 56a656
#define MAXNUMCOLORS  (MAXJSAMPLE+1) /* maximum size of colormap */
darco 56a656
darco 56a656
/* These will do the right thing for either R,G,B or B,G,R color order,
darco 56a656
 * but you may not like the results for other color orders.
darco 56a656
 */
darco 56a656
#define HIST_C0_BITS  5		/* bits of precision in R/B histogram */
darco 56a656
#define HIST_C1_BITS  6		/* bits of precision in G histogram */
darco 56a656
#define HIST_C2_BITS  5		/* bits of precision in B/R histogram */
darco 56a656
darco 56a656
/* Number of elements along histogram axes. */
darco 56a656
#define HIST_C0_ELEMS  (1<
darco 56a656
#define HIST_C1_ELEMS  (1<
darco 56a656
#define HIST_C2_ELEMS  (1<
darco 56a656
darco 56a656
/* These are the amounts to shift an input value to get a histogram index. */
darco 56a656
#define C0_SHIFT  (BITS_IN_JSAMPLE-HIST_C0_BITS)
darco 56a656
#define C1_SHIFT  (BITS_IN_JSAMPLE-HIST_C1_BITS)
darco 56a656
#define C2_SHIFT  (BITS_IN_JSAMPLE-HIST_C2_BITS)
darco 56a656
darco 56a656
darco 56a656
typedef UINT16 histcell;	/* histogram cell; prefer an unsigned type */
darco 56a656
darco 56a656
typedef histcell FAR * histptr;	/* for pointers to histogram cells */
darco 56a656
darco 56a656
typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
darco 56a656
typedef hist1d FAR * hist2d;	/* type for the 2nd-level pointers */
darco 56a656
typedef hist2d * hist3d;	/* type for top-level pointer */
darco 56a656
darco 56a656
darco 56a656
/* Declarations for Floyd-Steinberg dithering.
darco 56a656
 *
darco 56a656
 * Errors are accumulated into the array fserrors[], at a resolution of
darco 56a656
 * 1/16th of a pixel count.  The error at a given pixel is propagated
darco 56a656
 * to its not-yet-processed neighbors using the standard F-S fractions,
darco 56a656
 *		...	(here)	7/16
darco 56a656
 *		3/16	5/16	1/16
darco 56a656
 * We work left-to-right on even rows, right-to-left on odd rows.
darco 56a656
 *
darco 56a656
 * We can get away with a single array (holding one row's worth of errors)
darco 56a656
 * by using it to store the current row's errors at pixel columns not yet
darco 56a656
 * processed, but the next row's errors at columns already processed.  We
darco 56a656
 * need only a few extra variables to hold the errors immediately around the
darco 56a656
 * current column.  (If we are lucky, those variables are in registers, but
darco 56a656
 * even if not, they're probably cheaper to access than array elements are.)
darco 56a656
 *
darco 56a656
 * The fserrors[] array has (#columns + 2) entries; the extra entry at
darco 56a656
 * each end saves us from special-casing the first and last pixels.
darco 56a656
 * Each entry is three values long, one value for each color component.
darco 56a656
 *
darco 56a656
 * Note: on a wide image, we might not have enough room in a PC's near data
darco 56a656
 * segment to hold the error array; so it is allocated with alloc_large.
darco 56a656
 */
darco 56a656
darco 56a656
#if BITS_IN_JSAMPLE == 8
darco 56a656
typedef INT16 FSERROR;		/* 16 bits should be enough */
darco 56a656
typedef int LOCFSERROR;		/* use 'int' for calculation temps */
darco 56a656
#else
darco 56a656
typedef INT32 FSERROR;		/* may need more than 16 bits */
darco 56a656
typedef INT32 LOCFSERROR;	/* be sure calculation temps are big enough */
darco 56a656
#endif
darco 56a656
darco 56a656
typedef FSERROR FAR *FSERRPTR;	/* pointer to error array (in FAR storage!) */
darco 56a656
darco 56a656
darco 56a656
/* Private subobject */
darco 56a656
darco 56a656
typedef struct {
darco 56a656
  struct jpeg_color_quantizer pub; /* public fields */
darco 56a656
darco 56a656
  /* Space for the eventually created colormap is stashed here */
darco 56a656
  JSAMPARRAY sv_colormap;	/* colormap allocated at init time */
darco 56a656
  int desired;			/* desired # of colors = size of colormap */
darco 56a656
darco 56a656
  /* Variables for accumulating image statistics */
darco 56a656
  hist3d histogram;		/* pointer to the histogram */
darco 56a656
darco 56a656
  boolean needs_zeroed;		/* TRUE if next pass must zero histogram */
darco 56a656
darco 56a656
  /* Variables for Floyd-Steinberg dithering */
darco 56a656
  FSERRPTR fserrors;		/* accumulated errors */
darco 56a656
  boolean on_odd_row;		/* flag to remember which row we are on */
darco 56a656
  int * error_limiter;		/* table for clamping the applied error */
darco 56a656
} my_cquantizer;
darco 56a656
darco 56a656
typedef my_cquantizer * my_cquantize_ptr;
darco 56a656
darco 56a656
darco 56a656
/*
darco 56a656
 * Prescan some rows of pixels.
darco 56a656
 * In this module the prescan simply updates the histogram, which has been
darco 56a656
 * initialized to zeroes by start_pass.
darco 56a656
 * An output_buf parameter is required by the method signature, but no data
darco 56a656
 * is actually output (in fact the buffer controller is probably passing a
darco 56a656
 * NULL pointer).
darco 56a656
 */
darco 56a656
darco 56a656
METHODDEF(void)
darco 56a656
prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
darco 56a656
		  JSAMPARRAY output_buf, int num_rows)
darco 56a656
{
darco 56a656
  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
darco 56a656
  register JSAMPROW ptr;
darco 56a656
  register histptr histp;
darco 56a656
  register hist3d histogram = cquantize->histogram;
darco 56a656
  int row;
darco 56a656
  JDIMENSION col;
darco 56a656
  JDIMENSION width = cinfo->output_width;
darco 56a656
darco 56a656
  for (row = 0; row < num_rows; row++) {
darco 56a656
    ptr = input_buf[row];
darco 56a656
    for (col = width; col > 0; col--) {
darco 56a656
      /* get pixel value and index into the histogram */
darco 56a656
      histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
darco 56a656
			 [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
darco 56a656
			 [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
darco 56a656
      /* increment, check for overflow and undo increment if so. */
darco 56a656
      if (++(*histp) <= 0)
darco 56a656
	(*histp)--;
darco 56a656
      ptr += 3;
darco 56a656
    }
darco 56a656
  }
darco 56a656
}
darco 56a656
darco 56a656
darco 56a656
/*
darco 56a656
 * Next we have the really interesting routines: selection of a colormap
darco 56a656
 * given the completed histogram.
darco 56a656
 * These routines work with a list of "boxes", each representing a rectangular
darco 56a656
 * subset of the input color space (to histogram precision).
darco 56a656
 */
darco 56a656
darco 56a656
typedef struct {
darco 56a656
  /* The bounds of the box (inclusive); expressed as histogram indexes */
darco 56a656
  int c0min, c0max;
darco 56a656
  int c1min, c1max;
darco 56a656
  int c2min, c2max;
darco 56a656
  /* The volume (actually 2-norm) of the box */
darco 56a656
  INT32 volume;
darco 56a656
  /* The number of nonzero histogram cells within this box */
darco 56a656
  long colorcount;
darco 56a656
} box;
darco 56a656
darco 56a656
typedef box * boxptr;
darco 56a656
darco 56a656
darco 56a656
LOCAL(boxptr)
darco 56a656
find_biggest_color_pop (boxptr boxlist, int numboxes)
darco 56a656
/* Find the splittable box with the largest color population */
darco 56a656
/* Returns NULL if no splittable boxes remain */
darco 56a656
{
darco 56a656
  register boxptr boxp;
darco 56a656
  register int i;
darco 56a656
  register long maxc = 0;
darco 56a656
  boxptr which = NULL;
darco 56a656
  
darco 56a656
  for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
darco 56a656
    if (boxp->colorcount > maxc && boxp->volume > 0) {
darco 56a656
      which = boxp;
darco 56a656
      maxc = boxp->colorcount;
darco 56a656
    }
darco 56a656
  }
darco 56a656
  return which;
darco 56a656
}
darco 56a656
darco 56a656
darco 56a656
LOCAL(boxptr)
darco 56a656
find_biggest_volume (boxptr boxlist, int numboxes)
darco 56a656
/* Find the splittable box with the largest (scaled) volume */
darco 56a656
/* Returns NULL if no splittable boxes remain */
darco 56a656
{
darco 56a656
  register boxptr boxp;
darco 56a656
  register int i;
darco 56a656
  register INT32 maxv = 0;
darco 56a656
  boxptr which = NULL;
darco 56a656
  
darco 56a656
  for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
darco 56a656
    if (boxp->volume > maxv) {
darco 56a656
      which = boxp;
darco 56a656
      maxv = boxp->volume;
darco 56a656
    }
darco 56a656
  }
darco 56a656
  return which;
darco 56a656
}
darco 56a656
darco 56a656
darco 56a656
LOCAL(void)
darco 56a656
update_box (j_decompress_ptr cinfo, boxptr boxp)
darco 56a656
/* Shrink the min/max bounds of a box to enclose only nonzero elements, */
darco 56a656
/* and recompute its volume and population */
darco 56a656
{
darco 56a656
  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
darco 56a656
  hist3d histogram = cquantize->histogram;
darco 56a656
  histptr histp;
darco 56a656
  int c0,c1,c2;
darco 56a656
  int c0min,c0max,c1min,c1max,c2min,c2max;
darco 56a656
  INT32 dist0,dist1,dist2;
darco 56a656
  long ccount;
darco 56a656
  
darco 56a656
  c0min = boxp->c0min;  c0max = boxp->c0max;
darco 56a656
  c1min = boxp->c1min;  c1max = boxp->c1max;
darco 56a656
  c2min = boxp->c2min;  c2max = boxp->c2max;
darco 56a656
  
darco 56a656
  if (c0max > c0min)
darco 56a656
    for (c0 = c0min; c0 <= c0max; c0++)
darco 56a656
      for (c1 = c1min; c1 <= c1max; c1++) {
darco 56a656
	histp = & histogram[c0][c1][c2min];
darco 56a656
	for (c2 = c2min; c2 <= c2max; c2++)
darco 56a656
	  if (*histp++ != 0) {
darco 56a656
	    boxp->c0min = c0min = c0;
darco 56a656
	    goto have_c0min;
darco 56a656
	  }
darco 56a656
      }
darco 56a656
 have_c0min:
darco 56a656
  if (c0max > c0min)
darco 56a656
    for (c0 = c0max; c0 >= c0min; c0--)
darco 56a656
      for (c1 = c1min; c1 <= c1max; c1++) {
darco 56a656
	histp = & histogram[c0][c1][c2min];
darco 56a656
	for (c2 = c2min; c2 <= c2max; c2++)
darco 56a656
	  if (*histp++ != 0) {
darco 56a656
	    boxp->c0max = c0max = c0;
darco 56a656
	    goto have_c0max;
darco 56a656
	  }
darco 56a656
      }
darco 56a656
 have_c0max:
darco 56a656
  if (c1max > c1min)
darco 56a656
    for (c1 = c1min; c1 <= c1max; c1++)
darco 56a656
      for (c0 = c0min; c0 <= c0max; c0++) {
darco 56a656
	histp = & histogram[c0][c1][c2min];
darco 56a656
	for (c2 = c2min; c2 <= c2max; c2++)
darco 56a656
	  if (*histp++ != 0) {
darco 56a656
	    boxp->c1min = c1min = c1;
darco 56a656
	    goto have_c1min;
darco 56a656
	  }
darco 56a656
      }
darco 56a656
 have_c1min:
darco 56a656
  if (c1max > c1min)
darco 56a656
    for (c1 = c1max; c1 >= c1min; c1--)
darco 56a656
      for (c0 = c0min; c0 <= c0max; c0++) {
darco 56a656
	histp = & histogram[c0][c1][c2min];
darco 56a656
	for (c2 = c2min; c2 <= c2max; c2++)
darco 56a656
	  if (*histp++ != 0) {
darco 56a656
	    boxp->c1max = c1max = c1;
darco 56a656
	    goto have_c1max;
darco 56a656
	  }
darco 56a656
      }
darco 56a656
 have_c1max:
darco 56a656
  if (c2max > c2min)
darco 56a656
    for (c2 = c2min; c2 <= c2max; c2++)
darco 56a656
      for (c0 = c0min; c0 <= c0max; c0++) {
darco 56a656
	histp = & histogram[c0][c1min][c2];
darco 56a656
	for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
darco 56a656
	  if (*histp != 0) {
darco 56a656
	    boxp->c2min = c2min = c2;
darco 56a656
	    goto have_c2min;
darco 56a656
	  }
darco 56a656
      }
darco 56a656
 have_c2min:
darco 56a656
  if (c2max > c2min)
darco 56a656
    for (c2 = c2max; c2 >= c2min; c2--)
darco 56a656
      for (c0 = c0min; c0 <= c0max; c0++) {
darco 56a656
	histp = & histogram[c0][c1min][c2];
darco 56a656
	for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
darco 56a656
	  if (*histp != 0) {
darco 56a656
	    boxp->c2max = c2max = c2;
darco 56a656
	    goto have_c2max;
darco 56a656
	  }
darco 56a656
      }
darco 56a656
 have_c2max:
darco 56a656
darco 56a656
  /* Update box volume.
darco 56a656
   * We use 2-norm rather than real volume here; this biases the method
darco 56a656
   * against making long narrow boxes, and it has the side benefit that
darco 56a656
   * a box is splittable iff norm > 0.
darco 56a656
   * Since the differences are expressed in histogram-cell units,
darco 56a656
   * we have to shift back to JSAMPLE units to get consistent distances;
darco 56a656
   * after which, we scale according to the selected distance scale factors.
darco 56a656
   */
darco 56a656
  dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
darco 56a656
  dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
darco 56a656
  dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
darco 56a656
  boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
darco 56a656
  
darco 56a656
  /* Now scan remaining volume of box and compute population */
darco 56a656
  ccount = 0;
darco 56a656
  for (c0 = c0min; c0 <= c0max; c0++)
darco 56a656
    for (c1 = c1min; c1 <= c1max; c1++) {
darco 56a656
      histp = & histogram[c0][c1][c2min];
darco 56a656
      for (c2 = c2min; c2 <= c2max; c2++, histp++)
darco 56a656
	if (*histp != 0) {
darco 56a656
	  ccount++;
darco 56a656
	}
darco 56a656
    }
darco 56a656
  boxp->colorcount = ccount;
darco 56a656
}
darco 56a656
darco 56a656
darco 56a656
LOCAL(int)
darco 56a656
median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
darco 56a656
	    int desired_colors)
darco 56a656
/* Repeatedly select and split the largest box until we have enough boxes */
darco 56a656
{
darco 56a656
  int n,lb;
darco 56a656
  int c0,c1,c2,cmax;
darco 56a656
  register boxptr b1,b2;
darco 56a656
darco 56a656
  while (numboxes < desired_colors) {
darco 56a656
    /* Select box to split.
darco 56a656
     * Current algorithm: by population for first half, then by volume.
darco 56a656
     */
darco 56a656
    if (numboxes*2 <= desired_colors) {
darco 56a656
      b1 = find_biggest_color_pop(boxlist, numboxes);
darco 56a656
    } else {
darco 56a656
      b1 = find_biggest_volume(boxlist, numboxes);
darco 56a656
    }
darco 56a656
    if (b1 == NULL)		/* no splittable boxes left! */
darco 56a656
      break;
darco 56a656
    b2 = &boxlist[numboxes];	/* where new box will go */
darco 56a656
    /* Copy the color bounds to the new box. */
darco 56a656
    b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
darco 56a656
    b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
darco 56a656
    /* Choose which axis to split the box on.
darco 56a656
     * Current algorithm: longest scaled axis.
darco 56a656
     * See notes in update_box about scaling distances.
darco 56a656
     */
darco 56a656
    c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
darco 56a656
    c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
darco 56a656
    c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
darco 56a656
    /* We want to break any ties in favor of green, then red, blue last.
darco 56a656
     * This code does the right thing for R,G,B or B,G,R color orders only.
darco 56a656
     */
darco 56a656
#if RGB_RED == 0
darco 56a656
    cmax = c1; n = 1;
darco 56a656
    if (c0 > cmax) { cmax = c0; n = 0; }
darco 56a656
    if (c2 > cmax) { n = 2; }
darco 56a656
#else
darco 56a656
    cmax = c1; n = 1;
darco 56a656
    if (c2 > cmax) { cmax = c2; n = 2; }
darco 56a656
    if (c0 > cmax) { n = 0; }
darco 56a656
#endif
darco 56a656
    /* Choose split point along selected axis, and update box bounds.
darco 56a656
     * Current algorithm: split at halfway point.
darco 56a656
     * (Since the box has been shrunk to minimum volume,
darco 56a656
     * any split will produce two nonempty subboxes.)
darco 56a656
     * Note that lb value is max for lower box, so must be < old max.
darco 56a656
     */
darco 56a656
    switch (n) {
darco 56a656
    case 0:
darco 56a656
      lb = (b1->c0max + b1->c0min) / 2;
darco 56a656
      b1->c0max = lb;
darco 56a656
      b2->c0min = lb+1;
darco 56a656
      break;
darco 56a656
    case 1:
darco 56a656
      lb = (b1->c1max + b1->c1min) / 2;
darco 56a656
      b1->c1max = lb;
darco 56a656
      b2->c1min = lb+1;
darco 56a656
      break;
darco 56a656
    case 2:
darco 56a656
      lb = (b1->c2max + b1->c2min) / 2;
darco 56a656
      b1->c2max = lb;
darco 56a656
      b2->c2min = lb+1;
darco 56a656
      break;
darco 56a656
    }
darco 56a656
    /* Update stats for boxes */
darco 56a656
    update_box(cinfo, b1);
darco 56a656
    update_box(cinfo, b2);
darco 56a656
    numboxes++;
darco 56a656
  }
darco 56a656
  return numboxes;
darco 56a656
}
darco 56a656
darco 56a656
darco 56a656
LOCAL(void)
darco 56a656
compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
darco 56a656
/* Compute representative color for a box, put it in colormap[icolor] */
darco 56a656
{
darco 56a656
  /* Current algorithm: mean weighted by pixels (not colors) */
darco 56a656
  /* Note it is important to get the rounding correct! */
darco 56a656
  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
darco 56a656
  hist3d histogram = cquantize->histogram;
darco 56a656
  histptr histp;
darco 56a656
  int c0,c1,c2;
darco 56a656
  int c0min,c0max,c1min,c1max,c2min,c2max;
darco 56a656
  long count;
darco 56a656
  long total = 0;
darco 56a656
  long c0total = 0;
darco 56a656
  long c1total = 0;
darco 56a656
  long c2total = 0;
darco 56a656
  
darco 56a656
  c0min = boxp->c0min;  c0max = boxp->c0max;
darco 56a656
  c1min = boxp->c1min;  c1max = boxp->c1max;
darco 56a656
  c2min = boxp->c2min;  c2max = boxp->c2max;
darco 56a656
  
darco 56a656
  for (c0 = c0min; c0 <= c0max; c0++)
darco 56a656
    for (c1 = c1min; c1 <= c1max; c1++) {
darco 56a656
      histp = & histogram[c0][c1][c2min];
darco 56a656
      for (c2 = c2min; c2 <= c2max; c2++) {
darco 56a656
	if ((count = *histp++) != 0) {
darco 56a656
	  total += count;
darco 56a656
	  c0total += ((c0 << C0_SHIFT) + ((1<<c0_shift)>>1)) * count;</c0_shift)>
darco 56a656
	  c1total += ((c1 << C1_SHIFT) + ((1<<c1_shift)>>1)) * count;</c1_shift)>
darco 56a656
	  c2total += ((c2 << C2_SHIFT) + ((1<<c2_shift)>>1)) * count;</c2_shift)>
darco 56a656
	}
darco 56a656
      }
darco 56a656
    }
darco 56a656
  
darco 56a656
  cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
darco 56a656
  cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
darco 56a656
  cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
darco 56a656
}
darco 56a656
darco 56a656
darco 56a656
LOCAL(void)
darco 56a656
select_colors (j_decompress_ptr cinfo, int desired_colors)
darco 56a656
/* Master routine for color selection */
darco 56a656
{
darco 56a656
  boxptr boxlist;
darco 56a656
  int numboxes;
darco 56a656
  int i;
darco 56a656
darco 56a656
  /* Allocate workspace for box list */
darco 56a656
  boxlist = (boxptr) (*cinfo->mem->alloc_small)
darco 56a656
    ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
darco 56a656
  /* Initialize one box containing whole space */
darco 56a656
  numboxes = 1;
darco 56a656
  boxlist[0].c0min = 0;
darco 56a656
  boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
darco 56a656
  boxlist[0].c1min = 0;
darco 56a656
  boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
darco 56a656
  boxlist[0].c2min = 0;
darco 56a656
  boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
darco 56a656
  /* Shrink it to actually-used volume and set its statistics */
darco 56a656
  update_box(cinfo, & boxlist[0]);
darco 56a656
  /* Perform median-cut to produce final box list */
darco 56a656
  numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
darco 56a656
  /* Compute the representative color for each box, fill colormap */
darco 56a656
  for (i = 0; i < numboxes; i++)
darco 56a656
    compute_color(cinfo, & boxlist[i], i);
darco 56a656
  cinfo->actual_number_of_colors = numboxes;
darco 56a656
  TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
darco 56a656
}
darco 56a656
darco 56a656
darco 56a656
/*
darco 56a656
 * These routines are concerned with the time-critical task of mapping input
darco 56a656
 * colors to the nearest color in the selected colormap.
darco 56a656
 *
darco 56a656
 * We re-use the histogram space as an "inverse color map", essentially a
darco 56a656
 * cache for the results of nearest-color searches.  All colors within a
darco 56a656
 * histogram cell will be mapped to the same colormap entry, namely the one
darco 56a656
 * closest to the cell's center.  This may not be quite the closest entry to
darco 56a656
 * the actual input color, but it's almost as good.  A zero in the cache
darco 56a656
 * indicates we haven't found the nearest color for that cell yet; the array
darco 56a656
 * is cleared to zeroes before starting the mapping pass.  When we find the
darco 56a656
 * nearest color for a cell, its colormap index plus one is recorded in the
darco 56a656
 * cache for future use.  The pass2 scanning routines call fill_inverse_cmap
darco 56a656
 * when they need to use an unfilled entry in the cache.
darco 56a656
 *
darco 56a656
 * Our method of efficiently finding nearest colors is based on the "locally
darco 56a656
 * sorted search" idea described by Heckbert and on the incremental distance
darco 56a656
 * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
darco 56a656
 * Gems II (James Arvo, ed.  Academic Press, 1991).  Thomas points out that
darco 56a656
 * the distances from a given colormap entry to each cell of the histogram can
darco 56a656
 * be computed quickly using an incremental method: the differences between
darco 56a656
 * distances to adjacent cells themselves differ by a constant.  This allows a
darco 56a656
 * fairly fast implementation of the "brute force" approach of computing the
darco 56a656
 * distance from every colormap entry to every histogram cell.  Unfortunately,
darco 56a656
 * it needs a work array to hold the best-distance-so-far for each histogram
darco 56a656
 * cell (because the inner loop has to be over cells, not colormap entries).
darco 56a656
 * The work array elements have to be INT32s, so the work array would need
darco 56a656
 * 256Kb at our recommended precision.  This is not feasible in DOS machines.
darco 56a656
 *
darco 56a656
 * To get around these problems, we apply Thomas' method to compute the
darco 56a656
 * nearest colors for only the cells within a small subbox of the histogram.
darco 56a656
 * The work array need be only as big as the subbox, so the memory usage
darco 56a656
 * problem is solved.  Furthermore, we need not fill subboxes that are never
darco 56a656
 * referenced in pass2; many images use only part of the color gamut, so a
darco 56a656
 * fair amount of work is saved.  An additional advantage of this
darco 56a656
 * approach is that we can apply Heckbert's locality criterion to quickly
darco 56a656
 * eliminate colormap entries that are far away from the subbox; typically
darco 56a656
 * three-fourths of the colormap entries are rejected by Heckbert's criterion,
darco 56a656
 * and we need not compute their distances to individual cells in the subbox.
darco 56a656
 * The speed of this approach is heavily influenced by the subbox size: too
darco 56a656
 * small means too much overhead, too big loses because Heckbert's criterion
darco 56a656
 * can't eliminate as many colormap entries.  Empirically the best subbox
darco 56a656
 * size seems to be about 1/512th of the histogram (1/8th in each direction).
darco 56a656
 *
darco 56a656
 * Thomas' article also describes a refined method which is asymptotically
darco 56a656
 * faster than the brute-force method, but it is also far more complex and
darco 56a656
 * cannot efficiently be applied to small subboxes.  It is therefore not
darco 56a656
 * useful for programs intended to be portable to DOS machines.  On machines
darco 56a656
 * with plenty of memory, filling the whole histogram in one shot with Thomas'
darco 56a656
 * refined method might be faster than the present code --- but then again,
darco 56a656
 * it might not be any faster, and it's certainly more complicated.
darco 56a656
 */
darco 56a656
darco 56a656
darco 56a656
/* log2(histogram cells in update box) for each axis; this can be adjusted */
darco 56a656
#define BOX_C0_LOG  (HIST_C0_BITS-3)
darco 56a656
#define BOX_C1_LOG  (HIST_C1_BITS-3)
darco 56a656
#define BOX_C2_LOG  (HIST_C2_BITS-3)
darco 56a656
darco 56a656
#define BOX_C0_ELEMS  (1<
darco 56a656
#define BOX_C1_ELEMS  (1<
darco 56a656
#define BOX_C2_ELEMS  (1<
darco 56a656
darco 56a656
#define BOX_C0_SHIFT  (C0_SHIFT + BOX_C0_LOG)
darco 56a656
#define BOX_C1_SHIFT  (C1_SHIFT + BOX_C1_LOG)
darco 56a656
#define BOX_C2_SHIFT  (C2_SHIFT + BOX_C2_LOG)
darco 56a656
darco 56a656
darco 56a656
/*
darco 56a656
 * The next three routines implement inverse colormap filling.  They could
darco 56a656
 * all be folded into one big routine, but splitting them up this way saves
darco 56a656
 * some stack space (the mindist[] and bestdist[] arrays need not coexist)
darco 56a656
 * and may allow some compilers to produce better code by registerizing more
darco 56a656
 * inner-loop variables.
darco 56a656
 */
darco 56a656
darco 56a656
LOCAL(int)
darco 56a656
find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
darco 56a656
		    JSAMPLE colorlist[])
darco 56a656
/* Locate the colormap entries close enough to an update box to be candidates
darco 56a656
 * for the nearest entry to some cell(s) in the update box.  The update box
darco 56a656
 * is specified by the center coordinates of its first cell.  The number of
darco 56a656
 * candidate colormap entries is returned, and their colormap indexes are
darco 56a656
 * placed in colorlist[].
darco 56a656
 * This routine uses Heckbert's "locally sorted search" criterion to select
darco 56a656
 * the colors that need further consideration.
darco 56a656
 */
darco 56a656
{
darco 56a656
  int numcolors = cinfo->actual_number_of_colors;
darco 56a656
  int maxc0, maxc1, maxc2;
darco 56a656
  int centerc0, centerc1, centerc2;
darco 56a656
  int i, x, ncolors;
darco 56a656
  INT32 minmaxdist, min_dist, max_dist, tdist;
darco 56a656
  INT32 mindist[MAXNUMCOLORS];	/* min distance to colormap entry i */
darco 56a656
darco 56a656
  /* Compute true coordinates of update box's upper corner and center.
darco 56a656
   * Actually we compute the coordinates of the center of the upper-corner
darco 56a656
   * histogram cell, which are the upper bounds of the volume we care about.
darco 56a656
   * Note that since ">>" rounds down, the "center" values may be closer to
darco 56a656
   * min than to max; hence comparisons to them must be "<=", not "<".
darco 56a656
   */
darco 56a656
  maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
darco 56a656
  centerc0 = (minc0 + maxc0) >> 1;
darco 56a656
  maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
darco 56a656
  centerc1 = (minc1 + maxc1) >> 1;
darco 56a656
  maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
darco 56a656
  centerc2 = (minc2 + maxc2) >> 1;
darco 56a656
darco 56a656
  /* For each color in colormap, find:
darco 56a656
   *  1. its minimum squared-distance to any point in the update box
darco 56a656
   *     (zero if color is within update box);
darco 56a656
   *  2. its maximum squared-distance to any point in the update box.
darco 56a656
   * Both of these can be found by considering only the corners of the box.
darco 56a656
   * We save the minimum distance for each color in mindist[];
darco 56a656
   * only the smallest maximum distance is of interest.
darco 56a656
   */
darco 56a656
  minmaxdist = 0x7FFFFFFFL;
darco 56a656
darco 56a656
  for (i = 0; i < numcolors; i++) {
darco 56a656
    /* We compute the squared-c0-distance term, then add in the other two. */
darco 56a656
    x = GETJSAMPLE(cinfo->colormap[0][i]);
darco 56a656
    if (x < minc0) {
darco 56a656
      tdist = (x - minc0) * C0_SCALE;
darco 56a656
      min_dist = tdist*tdist;
darco 56a656
      tdist = (x - maxc0) * C0_SCALE;
darco 56a656
      max_dist = tdist*tdist;
darco 56a656
    } else if (x > maxc0) {
darco 56a656
      tdist = (x - maxc0) * C0_SCALE;
darco 56a656
      min_dist = tdist*tdist;
darco 56a656
      tdist = (x - minc0) * C0_SCALE;
darco 56a656
      max_dist = tdist*tdist;
darco 56a656
    } else {
darco 56a656
      /* within cell range so no contribution to min_dist */
darco 56a656
      min_dist = 0;
darco 56a656
      if (x <= centerc0) {
darco 56a656
	tdist = (x - maxc0) * C0_SCALE;
darco 56a656
	max_dist = tdist*tdist;
darco 56a656
      } else {
darco 56a656
	tdist = (x - minc0) * C0_SCALE;
darco 56a656
	max_dist = tdist*tdist;
darco 56a656
      }
darco 56a656
    }
darco 56a656
darco 56a656
    x = GETJSAMPLE(cinfo->colormap[1][i]);
darco 56a656
    if (x < minc1) {
darco 56a656
      tdist = (x - minc1) * C1_SCALE;
darco 56a656
      min_dist += tdist*tdist;
darco 56a656
      tdist = (x - maxc1) * C1_SCALE;
darco 56a656
      max_dist += tdist*tdist;
darco 56a656
    } else if (x > maxc1) {
darco 56a656
      tdist = (x - maxc1) * C1_SCALE;
darco 56a656
      min_dist += tdist*tdist;
darco 56a656
      tdist = (x - minc1) * C1_SCALE;
darco 56a656
      max_dist += tdist*tdist;
darco 56a656
    } else {
darco 56a656
      /* within cell range so no contribution to min_dist */
darco 56a656
      if (x <= centerc1) {
darco 56a656
	tdist = (x - maxc1) * C1_SCALE;
darco 56a656
	max_dist += tdist*tdist;
darco 56a656
      } else {
darco 56a656
	tdist = (x - minc1) * C1_SCALE;
darco 56a656
	max_dist += tdist*tdist;
darco 56a656
      }
darco 56a656
    }
darco 56a656
darco 56a656
    x = GETJSAMPLE(cinfo->colormap[2][i]);
darco 56a656
    if (x < minc2) {
darco 56a656
      tdist = (x - minc2) * C2_SCALE;
darco 56a656
      min_dist += tdist*tdist;
darco 56a656
      tdist = (x - maxc2) * C2_SCALE;
darco 56a656
      max_dist += tdist*tdist;
darco 56a656
    } else if (x > maxc2) {
darco 56a656
      tdist = (x - maxc2) * C2_SCALE;
darco 56a656
      min_dist += tdist*tdist;
darco 56a656
      tdist = (x - minc2) * C2_SCALE;
darco 56a656
      max_dist += tdist*tdist;
darco 56a656
    } else {
darco 56a656
      /* within cell range so no contribution to min_dist */
darco 56a656
      if (x <= centerc2) {
darco 56a656
	tdist = (x - maxc2) * C2_SCALE;
darco 56a656
	max_dist += tdist*tdist;
darco 56a656
      } else {
darco 56a656
	tdist = (x - minc2) * C2_SCALE;
darco 56a656
	max_dist += tdist*tdist;
darco 56a656
      }
darco 56a656
    }
darco 56a656
darco 56a656
    mindist[i] = min_dist;	/* save away the results */
darco 56a656
    if (max_dist < minmaxdist)
darco 56a656
      minmaxdist = max_dist;
darco 56a656
  }
darco 56a656
darco 56a656
  /* Now we know that no cell in the update box is more than minmaxdist
darco 56a656
   * away from some colormap entry.  Therefore, only colors that are
darco 56a656
   * within minmaxdist of some part of the box need be considered.
darco 56a656
   */
darco 56a656
  ncolors = 0;
darco 56a656
  for (i = 0; i < numcolors; i++) {
darco 56a656
    if (mindist[i] <= minmaxdist)
darco 56a656
      colorlist[ncolors++] = (JSAMPLE) i;
darco 56a656
  }
darco 56a656
  return ncolors;
darco 56a656
}
darco 56a656
darco 56a656
darco 56a656
LOCAL(void)
darco 56a656
find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
darco 56a656
		  int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
darco 56a656
/* Find the closest colormap entry for each cell in the update box,
darco 56a656
 * given the list of candidate colors prepared by find_nearby_colors.
darco 56a656
 * Return the indexes of the closest entries in the bestcolor[] array.
darco 56a656
 * This routine uses Thomas' incremental distance calculation method to
darco 56a656
 * find the distance from a colormap entry to successive cells in the box.
darco 56a656
 */
darco 56a656
{
darco 56a656
  int ic0, ic1, ic2;
darco 56a656
  int i, icolor;
darco 56a656
  register INT32 * bptr;	/* pointer into bestdist[] array */
darco 56a656
  JSAMPLE * cptr;		/* pointer into bestcolor[] array */
darco 56a656
  INT32 dist0, dist1;		/* initial distance values */
darco 56a656
  register INT32 dist2;		/* current distance in inner loop */
darco 56a656
  INT32 xx0, xx1;		/* distance increments */
darco 56a656
  register INT32 xx2;
darco 56a656
  INT32 inc0, inc1, inc2;	/* initial values for increments */
darco 56a656
  /* This array holds the distance to the nearest-so-far color for each cell */
darco 56a656
  INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
darco 56a656
darco 56a656
  /* Initialize best-distance for each cell of the update box */
darco 56a656
  bptr = bestdist;
darco 56a656
  for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
darco 56a656
    *bptr++ = 0x7FFFFFFFL;
darco 56a656
  
darco 56a656
  /* For each color selected by find_nearby_colors,
darco 56a656
   * compute its distance to the center of each cell in the box.
darco 56a656
   * If that's less than best-so-far, update best distance and color number.
darco 56a656
   */
darco 56a656
  
darco 56a656
  /* Nominal steps between cell centers ("x" in Thomas article) */
darco 56a656
#define STEP_C0  ((1 << C0_SHIFT) * C0_SCALE)
darco 56a656
#define STEP_C1  ((1 << C1_SHIFT) * C1_SCALE)
darco 56a656
#define STEP_C2  ((1 << C2_SHIFT) * C2_SCALE)
darco 56a656
  
darco 56a656
  for (i = 0; i < numcolors; i++) {
darco 56a656
    icolor = GETJSAMPLE(colorlist[i]);
darco 56a656
    /* Compute (square of) distance from minc0/c1/c2 to this color */
darco 56a656
    inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
darco 56a656
    dist0 = inc0*inc0;
darco 56a656
    inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
darco 56a656
    dist0 += inc1*inc1;
darco 56a656
    inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
darco 56a656
    dist0 += inc2*inc2;
darco 56a656
    /* Form the initial difference increments */
darco 56a656
    inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
darco 56a656
    inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
darco 56a656
    inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
darco 56a656
    /* Now loop over all cells in box, updating distance per Thomas method */
darco 56a656
    bptr = bestdist;
darco 56a656
    cptr = bestcolor;
darco 56a656
    xx0 = inc0;
darco 56a656
    for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
darco 56a656
      dist1 = dist0;
darco 56a656
      xx1 = inc1;
darco 56a656
      for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
darco 56a656
	dist2 = dist1;
darco 56a656
	xx2 = inc2;
darco 56a656
	for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
darco 56a656
	  if (dist2 < *bptr) {
darco 56a656
	    *bptr = dist2;
darco 56a656
	    *cptr = (JSAMPLE) icolor;
darco 56a656
	  }
darco 56a656
	  dist2 += xx2;
darco 56a656
	  xx2 += 2 * STEP_C2 * STEP_C2;
darco 56a656
	  bptr++;
darco 56a656
	  cptr++;
darco 56a656
	}
darco 56a656
	dist1 += xx1;
darco 56a656
	xx1 += 2 * STEP_C1 * STEP_C1;
darco 56a656
      }
darco 56a656
      dist0 += xx0;
darco 56a656
      xx0 += 2 * STEP_C0 * STEP_C0;
darco 56a656
    }
darco 56a656
  }
darco 56a656
}
darco 56a656
darco 56a656
darco 56a656
LOCAL(void)
darco 56a656
fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
darco 56a656
/* Fill the inverse-colormap entries in the update box that contains */
darco 56a656
/* histogram cell c0/c1/c2.  (Only that one cell MUST be filled, but */
darco 56a656
/* we can fill as many others as we wish.) */
darco 56a656
{
darco 56a656
  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
darco 56a656
  hist3d histogram = cquantize->histogram;
darco 56a656
  int minc0, minc1, minc2;	/* lower left corner of update box */
darco 56a656
  int ic0, ic1, ic2;
darco 56a656
  register JSAMPLE * cptr;	/* pointer into bestcolor[] array */
darco 56a656
  register histptr cachep;	/* pointer into main cache array */
darco 56a656
  /* This array lists the candidate colormap indexes. */
darco 56a656
  JSAMPLE colorlist[MAXNUMCOLORS];
darco 56a656
  int numcolors;		/* number of candidate colors */
darco 56a656
  /* This array holds the actually closest colormap index for each cell. */
darco 56a656
  JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
darco 56a656
darco 56a656
  /* Convert cell coordinates to update box ID */
darco 56a656
  c0 >>= BOX_C0_LOG;
darco 56a656
  c1 >>= BOX_C1_LOG;
darco 56a656
  c2 >>= BOX_C2_LOG;
darco 56a656
darco 56a656
  /* Compute true coordinates of update box's origin corner.
darco 56a656
   * Actually we compute the coordinates of the center of the corner
darco 56a656
   * histogram cell, which are the lower bounds of the volume we care about.
darco 56a656
   */
darco 56a656
  minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
darco 56a656
  minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
darco 56a656
  minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
darco 56a656
  
darco 56a656
  /* Determine which colormap entries are close enough to be candidates
darco 56a656
   * for the nearest entry to some cell in the update box.
darco 56a656
   */
darco 56a656
  numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
darco 56a656
darco 56a656
  /* Determine the actually nearest colors. */
darco 56a656
  find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
darco 56a656
		   bestcolor);
darco 56a656
darco 56a656
  /* Save the best color numbers (plus 1) in the main cache array */
darco 56a656
  c0 <<= BOX_C0_LOG;		/* convert ID back to base cell indexes */
darco 56a656
  c1 <<= BOX_C1_LOG;
darco 56a656
  c2 <<= BOX_C2_LOG;
darco 56a656
  cptr = bestcolor;
darco 56a656
  for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
darco 56a656
    for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
darco 56a656
      cachep = & histogram[c0+ic0][c1+ic1][c2];
darco 56a656
      for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
darco 56a656
	*cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
darco 56a656
      }
darco 56a656
    }
darco 56a656
  }
darco 56a656
}
darco 56a656
darco 56a656
darco 56a656
/*
darco 56a656
 * Map some rows of pixels to the output colormapped representation.
darco 56a656
 */
darco 56a656
darco 56a656
METHODDEF(void)
darco 56a656
pass2_no_dither (j_decompress_ptr cinfo,
darco 56a656
		 JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
darco 56a656
/* This version performs no dithering */
darco 56a656
{
darco 56a656
  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
darco 56a656
  hist3d histogram = cquantize->histogram;
darco 56a656
  register JSAMPROW inptr, outptr;
darco 56a656
  register histptr cachep;
darco 56a656
  register int c0, c1, c2;
darco 56a656
  int row;
darco 56a656
  JDIMENSION col;
darco 56a656
  JDIMENSION width = cinfo->output_width;
darco 56a656
darco 56a656
  for (row = 0; row < num_rows; row++) {
darco 56a656
    inptr = input_buf[row];
darco 56a656
    outptr = output_buf[row];
darco 56a656
    for (col = width; col > 0; col--) {
darco 56a656
      /* get pixel value and index into the cache */
darco 56a656
      c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
darco 56a656
      c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
darco 56a656
      c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
darco 56a656
      cachep = & histogram[c0][c1][c2];
darco 56a656
      /* If we have not seen this color before, find nearest colormap entry */
darco 56a656
      /* and update the cache */
darco 56a656
      if (*cachep == 0)
darco 56a656
	fill_inverse_cmap(cinfo, c0,c1,c2);
darco 56a656
      /* Now emit the colormap index for this cell */
darco 56a656
      *outptr++ = (JSAMPLE) (*cachep - 1);
darco 56a656
    }
darco 56a656
  }
darco 56a656
}
darco 56a656
darco 56a656
darco 56a656
METHODDEF(void)
darco 56a656
pass2_fs_dither (j_decompress_ptr cinfo,
darco 56a656
		 JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
darco 56a656
/* This version performs Floyd-Steinberg dithering */
darco 56a656
{
darco 56a656
  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
darco 56a656
  hist3d histogram = cquantize->histogram;
darco 56a656
  register LOCFSERROR cur0, cur1, cur2;	/* current error or pixel value */
darco 56a656
  LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
darco 56a656
  LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
darco 56a656
  register FSERRPTR errorptr;	/* => fserrors[] at column before current */
darco 56a656
  JSAMPROW inptr;		/* => current input pixel */
darco 56a656
  JSAMPROW outptr;		/* => current output pixel */
darco 56a656
  histptr cachep;
darco 56a656
  int dir;			/* +1 or -1 depending on direction */
darco 56a656
  int dir3;			/* 3*dir, for advancing inptr & errorptr */
darco 56a656
  int row;
darco 56a656
  JDIMENSION col;
darco 56a656
  JDIMENSION width = cinfo->output_width;
darco 56a656
  JSAMPLE *range_limit = cinfo->sample_range_limit;
darco 56a656
  int *error_limit = cquantize->error_limiter;
darco 56a656
  JSAMPROW colormap0 = cinfo->colormap[0];
darco 56a656
  JSAMPROW colormap1 = cinfo->colormap[1];
darco 56a656
  JSAMPROW colormap2 = cinfo->colormap[2];
darco 56a656
  SHIFT_TEMPS
darco 56a656
darco 56a656
  for (row = 0; row < num_rows; row++) {
darco 56a656
    inptr = input_buf[row];
darco 56a656
    outptr = output_buf[row];
darco 56a656
    if (cquantize->on_odd_row) {
darco 56a656
      /* work right to left in this row */
darco 56a656
      inptr += (width-1) * 3;	/* so point to rightmost pixel */
darco 56a656
      outptr += width-1;
darco 56a656
      dir = -1;
darco 56a656
      dir3 = -3;
darco 56a656
      errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
darco 56a656
      cquantize->on_odd_row = FALSE; /* flip for next time */
darco 56a656
    } else {
darco 56a656
      /* work left to right in this row */
darco 56a656
      dir = 1;
darco 56a656
      dir3 = 3;
darco 56a656
      errorptr = cquantize->fserrors; /* => entry before first real column */
darco 56a656
      cquantize->on_odd_row = TRUE; /* flip for next time */
darco 56a656
    }
darco 56a656
    /* Preset error values: no error propagated to first pixel from left */
darco 56a656
    cur0 = cur1 = cur2 = 0;
darco 56a656
    /* and no error propagated to row below yet */
darco 56a656
    belowerr0 = belowerr1 = belowerr2 = 0;
darco 56a656
    bpreverr0 = bpreverr1 = bpreverr2 = 0;
darco 56a656
darco 56a656
    for (col = width; col > 0; col--) {
darco 56a656
      /* curN holds the error propagated from the previous pixel on the
darco 56a656
       * current line.  Add the error propagated from the previous line
darco 56a656
       * to form the complete error correction term for this pixel, and
darco 56a656
       * round the error term (which is expressed * 16) to an integer.
darco 56a656
       * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
darco 56a656
       * for either sign of the error value.
darco 56a656
       * Note: errorptr points to *previous* column's array entry.
darco 56a656
       */
darco 56a656
      cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
darco 56a656
      cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
darco 56a656
      cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
darco 56a656
      /* Limit the error using transfer function set by init_error_limit.
darco 56a656
       * See comments with init_error_limit for rationale.
darco 56a656
       */
darco 56a656
      cur0 = error_limit[cur0];
darco 56a656
      cur1 = error_limit[cur1];
darco 56a656
      cur2 = error_limit[cur2];
darco 56a656
      /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
darco 56a656
       * The maximum error is +- MAXJSAMPLE (or less with error limiting);
darco 56a656
       * this sets the required size of the range_limit array.
darco 56a656
       */
darco 56a656
      cur0 += GETJSAMPLE(inptr[0]);
darco 56a656
      cur1 += GETJSAMPLE(inptr[1]);
darco 56a656
      cur2 += GETJSAMPLE(inptr[2]);
darco 56a656
      cur0 = GETJSAMPLE(range_limit[cur0]);
darco 56a656
      cur1 = GETJSAMPLE(range_limit[cur1]);
darco 56a656
      cur2 = GETJSAMPLE(range_limit[cur2]);
darco 56a656
      /* Index into the cache with adjusted pixel value */
darco 56a656
      cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
darco 56a656
      /* If we have not seen this color before, find nearest colormap */
darco 56a656
      /* entry and update the cache */
darco 56a656
      if (*cachep == 0)
darco 56a656
	fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
darco 56a656
      /* Now emit the colormap index for this cell */
darco 56a656
      { register int pixcode = *cachep - 1;
darco 56a656
	*outptr = (JSAMPLE) pixcode;
darco 56a656
	/* Compute representation error for this pixel */
darco 56a656
	cur0 -= GETJSAMPLE(colormap0[pixcode]);
darco 56a656
	cur1 -= GETJSAMPLE(colormap1[pixcode]);
darco 56a656
	cur2 -= GETJSAMPLE(colormap2[pixcode]);
darco 56a656
      }
darco 56a656
      /* Compute error fractions to be propagated to adjacent pixels.
darco 56a656
       * Add these into the running sums, and simultaneously shift the
darco 56a656
       * next-line error sums left by 1 column.
darco 56a656
       */
darco 56a656
      { register LOCFSERROR bnexterr, delta;
darco 56a656
darco 56a656
	bnexterr = cur0;	/* Process component 0 */
darco 56a656
	delta = cur0 * 2;
darco 56a656
	cur0 += delta;		/* form error * 3 */
darco 56a656
	errorptr[0] = (FSERROR) (bpreverr0 + cur0);
darco 56a656
	cur0 += delta;		/* form error * 5 */
darco 56a656
	bpreverr0 = belowerr0 + cur0;
darco 56a656
	belowerr0 = bnexterr;
darco 56a656
	cur0 += delta;		/* form error * 7 */
darco 56a656
	bnexterr = cur1;	/* Process component 1 */
darco 56a656
	delta = cur1 * 2;
darco 56a656
	cur1 += delta;		/* form error * 3 */
darco 56a656
	errorptr[1] = (FSERROR) (bpreverr1 + cur1);
darco 56a656
	cur1 += delta;		/* form error * 5 */
darco 56a656
	bpreverr1 = belowerr1 + cur1;
darco 56a656
	belowerr1 = bnexterr;
darco 56a656
	cur1 += delta;		/* form error * 7 */
darco 56a656
	bnexterr = cur2;	/* Process component 2 */
darco 56a656
	delta = cur2 * 2;
darco 56a656
	cur2 += delta;		/* form error * 3 */
darco 56a656
	errorptr[2] = (FSERROR) (bpreverr2 + cur2);
darco 56a656
	cur2 += delta;		/* form error * 5 */
darco 56a656
	bpreverr2 = belowerr2 + cur2;
darco 56a656
	belowerr2 = bnexterr;
darco 56a656
	cur2 += delta;		/* form error * 7 */
darco 56a656
      }
darco 56a656
      /* At this point curN contains the 7/16 error value to be propagated
darco 56a656
       * to the next pixel on the current line, and all the errors for the
darco 56a656
       * next line have been shifted over.  We are therefore ready to move on.
darco 56a656
       */
darco 56a656
      inptr += dir3;		/* Advance pixel pointers to next column */
darco 56a656
      outptr += dir;
darco 56a656
      errorptr += dir3;		/* advance errorptr to current column */
darco 56a656
    }
darco 56a656
    /* Post-loop cleanup: we must unload the final error values into the
darco 56a656
     * final fserrors[] entry.  Note we need not unload belowerrN because
darco 56a656
     * it is for the dummy column before or after the actual array.
darco 56a656
     */
darco 56a656
    errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
darco 56a656
    errorptr[1] = (FSERROR) bpreverr1;
darco 56a656
    errorptr[2] = (FSERROR) bpreverr2;
darco 56a656
  }
darco 56a656
}
darco 56a656
darco 56a656
darco 56a656
/*
darco 56a656
 * Initialize the error-limiting transfer function (lookup table).
darco 56a656
 * The raw F-S error computation can potentially compute error values of up to
darco 56a656
 * +- MAXJSAMPLE.  But we want the maximum correction applied to a pixel to be
darco 56a656
 * much less, otherwise obviously wrong pixels will be created.  (Typical
darco 56a656
 * effects include weird fringes at color-area boundaries, isolated bright
darco 56a656
 * pixels in a dark area, etc.)  The standard advice for avoiding this problem
darco 56a656
 * is to ensure that the "corners" of the color cube are allocated as output
darco 56a656
 * colors; then repeated errors in the same direction cannot cause cascading
darco 56a656
 * error buildup.  However, that only prevents the error from getting
darco 56a656
 * completely out of hand; Aaron Giles reports that error limiting improves
darco 56a656
 * the results even with corner colors allocated.
darco 56a656
 * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
darco 56a656
 * well, but the smoother transfer function used below is even better.  Thanks
darco 56a656
 * to Aaron Giles for this idea.
darco 56a656
 */
darco 56a656
darco 56a656
LOCAL(void)
darco 56a656
init_error_limit (j_decompress_ptr cinfo)
darco 56a656
/* Allocate and fill in the error_limiter table */
darco 56a656
{
darco 56a656
  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
darco 56a656
  int * table;
darco 56a656
  int in, out;
darco 56a656
darco 56a656
  table = (int *) (*cinfo->mem->alloc_small)
darco 56a656
    ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
darco 56a656
  table += MAXJSAMPLE;		/* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
darco 56a656
  cquantize->error_limiter = table;
darco 56a656
darco 56a656
#define STEPSIZE ((MAXJSAMPLE+1)/16)
darco 56a656
  /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
darco 56a656
  out = 0;
darco 56a656
  for (in = 0; in < STEPSIZE; in++, out++) {
darco 56a656
    table[in] = out; table[-in] = -out;
darco 56a656
  }
darco 56a656
  /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
darco 56a656
  for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
darco 56a656
    table[in] = out; table[-in] = -out;
darco 56a656
  }
darco 56a656
  /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
darco 56a656
  for (; in <= MAXJSAMPLE; in++) {
darco 56a656
    table[in] = out; table[-in] = -out;
darco 56a656
  }
darco 56a656
#undef STEPSIZE
darco 56a656
}
darco 56a656
darco 56a656
darco 56a656
/*
darco 56a656
 * Finish up at the end of each pass.
darco 56a656
 */
darco 56a656
darco 56a656
METHODDEF(void)
darco 56a656
finish_pass1 (j_decompress_ptr cinfo)
darco 56a656
{
darco 56a656
  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
darco 56a656
darco 56a656
  /* Select the representative colors and fill in cinfo->colormap */
darco 56a656
  cinfo->colormap = cquantize->sv_colormap;
darco 56a656
  select_colors(cinfo, cquantize->desired);
darco 56a656
  /* Force next pass to zero the color index table */
darco 56a656
  cquantize->needs_zeroed = TRUE;
darco 56a656
}
darco 56a656
darco 56a656
darco 56a656
METHODDEF(void)
darco 56a656
finish_pass2 (j_decompress_ptr cinfo)
darco 56a656
{
darco 56a656
  /* no work */
darco 56a656
}
darco 56a656
darco 56a656
darco 56a656
/*
darco 56a656
 * Initialize for each processing pass.
darco 56a656
 */
darco 56a656
darco 56a656
METHODDEF(void)
darco 56a656
start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
darco 56a656
{
darco 56a656
  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
darco 56a656
  hist3d histogram = cquantize->histogram;
darco 56a656
  int i;
darco 56a656
darco 56a656
  /* Only F-S dithering or no dithering is supported. */
darco 56a656
  /* If user asks for ordered dither, give him F-S. */
darco 56a656
  if (cinfo->dither_mode != JDITHER_NONE)
darco 56a656
    cinfo->dither_mode = JDITHER_FS;
darco 56a656
darco 56a656
  if (is_pre_scan) {
darco 56a656
    /* Set up method pointers */
darco 56a656
    cquantize->pub.color_quantize = prescan_quantize;
darco 56a656
    cquantize->pub.finish_pass = finish_pass1;
darco 56a656
    cquantize->needs_zeroed = TRUE; /* Always zero histogram */
darco 56a656
  } else {
darco 56a656
    /* Set up method pointers */
darco 56a656
    if (cinfo->dither_mode == JDITHER_FS)
darco 56a656
      cquantize->pub.color_quantize = pass2_fs_dither;
darco 56a656
    else
darco 56a656
      cquantize->pub.color_quantize = pass2_no_dither;
darco 56a656
    cquantize->pub.finish_pass = finish_pass2;
darco 56a656
darco 56a656
    /* Make sure color count is acceptable */
darco 56a656
    i = cinfo->actual_number_of_colors;
darco 56a656
    if (i < 1)
darco 56a656
      ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
darco 56a656
    if (i > MAXNUMCOLORS)
darco 56a656
      ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
darco 56a656
darco 56a656
    if (cinfo->dither_mode == JDITHER_FS) {
darco 56a656
      size_t arraysize = (size_t) ((cinfo->output_width + 2) *
darco 56a656
				   (3 * SIZEOF(FSERROR)));
darco 56a656
      /* Allocate Floyd-Steinberg workspace if we didn't already. */
darco 56a656
      if (cquantize->fserrors == NULL)
darco 56a656
	cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
darco 56a656
	  ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
darco 56a656
      /* Initialize the propagated errors to zero. */
darco 56a656
      jzero_far((void FAR *) cquantize->fserrors, arraysize);
darco 56a656
      /* Make the error-limit table if we didn't already. */
darco 56a656
      if (cquantize->error_limiter == NULL)
darco 56a656
	init_error_limit(cinfo);
darco 56a656
      cquantize->on_odd_row = FALSE;
darco 56a656
    }
darco 56a656
darco 56a656
  }
darco 56a656
  /* Zero the histogram or inverse color map, if necessary */
darco 56a656
  if (cquantize->needs_zeroed) {
darco 56a656
    for (i = 0; i < HIST_C0_ELEMS; i++) {
darco 56a656
      jzero_far((void FAR *) histogram[i],
darco 56a656
		HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
darco 56a656
    }
darco 56a656
    cquantize->needs_zeroed = FALSE;
darco 56a656
  }
darco 56a656
}
darco 56a656
darco 56a656
darco 56a656
/*
darco 56a656
 * Switch to a new external colormap between output passes.
darco 56a656
 */
darco 56a656
darco 56a656
METHODDEF(void)
darco 56a656
new_color_map_2_quant (j_decompress_ptr cinfo)
darco 56a656
{
darco 56a656
  my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
darco 56a656
darco 56a656
  /* Reset the inverse color map */
darco 56a656
  cquantize->needs_zeroed = TRUE;
darco 56a656
}
darco 56a656
darco 56a656
darco 56a656
/*
darco 56a656
 * Module initialization routine for 2-pass color quantization.
darco 56a656
 */
darco 56a656
darco 56a656
GLOBAL(void)
darco 56a656
jinit_2pass_quantizer (j_decompress_ptr cinfo)
darco 56a656
{
darco 56a656
  my_cquantize_ptr cquantize;
darco 56a656
  int i;
darco 56a656
darco 56a656
  cquantize = (my_cquantize_ptr)
darco 56a656
    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
darco 56a656
				SIZEOF(my_cquantizer));
darco 56a656
  cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
darco 56a656
  cquantize->pub.start_pass = start_pass_2_quant;
darco 56a656
  cquantize->pub.new_color_map = new_color_map_2_quant;
darco 56a656
  cquantize->fserrors = NULL;	/* flag optional arrays not allocated */
darco 56a656
  cquantize->error_limiter = NULL;
darco 56a656
darco 56a656
  /* Make sure jdmaster didn't give me a case I can't handle */
darco 56a656
  if (cinfo->out_color_components != 3)
darco 56a656
    ERREXIT(cinfo, JERR_NOTIMPL);
darco 56a656
darco 56a656
  /* Allocate the histogram/inverse colormap storage */
darco 56a656
  cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
darco 56a656
    ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
darco 56a656
  for (i = 0; i < HIST_C0_ELEMS; i++) {
darco 56a656
    cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
darco 56a656
      ((j_common_ptr) cinfo, JPOOL_IMAGE,
darco 56a656
       HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
darco 56a656
  }
darco 56a656
  cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
darco 56a656
darco 56a656
  /* Allocate storage for the completed colormap, if required.
darco 56a656
   * We do this now since it is FAR storage and may affect
darco 56a656
   * the memory manager's space calculations.
darco 56a656
   */
darco 56a656
  if (cinfo->enable_2pass_quant) {
darco 56a656
    /* Make sure color count is acceptable */
darco 56a656
    int desired = cinfo->desired_number_of_colors;
darco 56a656
    /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
darco 56a656
    if (desired < 8)
darco 56a656
      ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
darco 56a656
    /* Make sure colormap indexes can be represented by JSAMPLEs */
darco 56a656
    if (desired > MAXNUMCOLORS)
darco 56a656
      ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
darco 56a656
    cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
darco 56a656
      ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
darco 56a656
    cquantize->desired = desired;
darco 56a656
  } else
darco 56a656
    cquantize->sv_colormap = NULL;
darco 56a656
darco 56a656
  /* Only F-S dithering or no dithering is supported. */
darco 56a656
  /* If user asks for ordered dither, give him F-S. */
darco 56a656
  if (cinfo->dither_mode != JDITHER_NONE)
darco 56a656
    cinfo->dither_mode = JDITHER_FS;
darco 56a656
darco 56a656
  /* Allocate Floyd-Steinberg workspace if necessary.
darco 56a656
   * This isn't really needed until pass 2, but again it is FAR storage.
darco 56a656
   * Although we will cope with a later change in dither_mode,
darco 56a656
   * we do not promise to honor max_memory_to_use if dither_mode changes.
darco 56a656
   */
darco 56a656
  if (cinfo->dither_mode == JDITHER_FS) {
darco 56a656
    cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
darco 56a656
      ((j_common_ptr) cinfo, JPOOL_IMAGE,
darco 56a656
       (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
darco 56a656
    /* Might as well create the error-limiting table too. */
darco 56a656
    init_error_limit(cinfo);
darco 56a656
  }
darco 56a656
}
darco 56a656
darco 56a656
#endif /* QUANT_2PASS_SUPPORTED */