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