JQUANT2.C
上传用户:wep9318
上传日期:2007-01-07
资源大小:893k
文件大小:46k
源码类别:

图片显示

开发平台:

Visual C++

  1. /*
  2.  * jquant2.c
  3.  *
  4.  * Copyright (C) 1991-1994, Thomas G. Lane.
  5.  * This file is part of the Independent JPEG Group's software.
  6.  * For conditions of distribution and use, see the accompanying README file.
  7.  *
  8.  * This file contains 2-pass color quantization (color mapping) routines.
  9.  * These routines provide selection of a custom color map for an image,
  10.  * followed by mapping of the image to that color map, with optional
  11.  * Floyd-Steinberg dithering.
  12.  * It is also possible to use just the second pass to map to an arbitrary
  13.  * externally-given color map.
  14.  *
  15.  * Note: ordered dithering is not supported, since there isn't any fast
  16.  * way to compute intercolor distances; it's unclear that ordered dither's
  17.  * fundamental assumptions even hold with an irregularly spaced color map.
  18.  */
  19. #define JPEG_INTERNALS
  20. #include "jinclude.h"
  21. #include "jpeglib.h"
  22. #ifdef QUANT_2PASS_SUPPORTED
  23. /*
  24.  * This module implements the well-known Heckbert paradigm for color
  25.  * quantization.  Most of the ideas used here can be traced back to
  26.  * Heckbert's seminal paper
  27.  *   Heckbert, Paul.  "Color Image Quantization for Frame Buffer Display",
  28.  *   Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  29.  *
  30.  * In the first pass over the image, we accumulate a histogram showing the
  31.  * usage count of each possible color.  To keep the histogram to a reasonable
  32.  * size, we reduce the precision of the input; typical practice is to retain
  33.  * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  34.  * in the same histogram cell.
  35.  *
  36.  * Next, the color-selection step begins with a box representing the whole
  37.  * color space, and repeatedly splits the "largest" remaining box until we
  38.  * have as many boxes as desired colors.  Then the mean color in each
  39.  * remaining box becomes one of the possible output colors.
  40.  * 
  41.  * The second pass over the image maps each input pixel to the closest output
  42.  * color (optionally after applying a Floyd-Steinberg dithering correction).
  43.  * This mapping is logically trivial, but making it go fast enough requires
  44.  * considerable care.
  45.  *
  46.  * Heckbert-style quantizers vary a good deal in their policies for choosing
  47.  * the "largest" box and deciding where to cut it.  The particular policies
  48.  * used here have proved out well in experimental comparisons, but better ones
  49.  * may yet be found.
  50.  *
  51.  * In earlier versions of the IJG code, this module quantized in YCbCr color
  52.  * space, processing the raw upsampled data without a color conversion step.
  53.  * This allowed the color conversion math to be done only once per colormap
  54.  * entry, not once per pixel.  However, that optimization precluded other
  55.  * useful optimizations (such as merging color conversion with upsampling)
  56.  * and it also interfered with desired capabilities such as quantizing to an
  57.  * externally-supplied colormap.  We have therefore abandoned that approach.
  58.  * The present code works in the post-conversion color space, typically RGB.
  59.  *
  60.  * To improve the visual quality of the results, we actually work in scaled
  61.  * RGB space, giving G distances more weight than R, and R in turn more than
  62.  * B.  To do everything in integer math, we must use integer scale factors.
  63.  * The 2/3/1 scale factors used here correspond loosely to the relative
  64.  * weights of the colors in the NTSC grayscale equation.
  65.  * If you want to use this code to quantize a non-RGB color space, you'll
  66.  * probably need to change these scale factors.
  67.  */
  68. #define R_SCALE 2 /* scale R distances by this much */
  69. #define G_SCALE 3 /* scale G distances by this much */
  70. #define B_SCALE 1 /* and B by this much */
  71. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  72.  * in jmorecfg.h.  As the code stands, it will do the right thing for R,G,B
  73.  * and B,G,R orders.  If you define some other weird order in jmorecfg.h,
  74.  * you'll get compile errors until you extend this logic.  In that case
  75.  * you'll probably want to tweak the histogram sizes too.
  76.  */
  77. #if RGB_RED == 0
  78. #define C0_SCALE R_SCALE
  79. #endif
  80. #if RGB_BLUE == 0
  81. #define C0_SCALE B_SCALE
  82. #endif
  83. #if RGB_GREEN == 1
  84. #define C1_SCALE G_SCALE
  85. #endif
  86. #if RGB_RED == 2
  87. #define C2_SCALE R_SCALE
  88. #endif
  89. #if RGB_BLUE == 2
  90. #define C2_SCALE B_SCALE
  91. #endif
  92. /*
  93.  * First we have the histogram data structure and routines for creating it.
  94.  *
  95.  * The number of bits of precision can be adjusted by changing these symbols.
  96.  * We recommend keeping 6 bits for G and 5 each for R and B.
  97.  * If you have plenty of memory and cycles, 6 bits all around gives marginally
  98.  * better results; if you are short of memory, 5 bits all around will save
  99.  * some space but degrade the results.
  100.  * To maintain a fully accurate histogram, we'd need to allocate a "long"
  101.  * (preferably unsigned long) for each cell.  In practice this is overkill;
  102.  * we can get by with 16 bits per cell.  Few of the cell counts will overflow,
  103.  * and clamping those that do overflow to the maximum value will give close-
  104.  * enough results.  This reduces the recommended histogram size from 256Kb
  105.  * to 128Kb, which is a useful savings on PC-class machines.
  106.  * (In the second pass the histogram space is re-used for pixel mapping data;
  107.  * in that capacity, each cell must be able to store zero to the number of
  108.  * desired colors.  16 bits/cell is plenty for that too.)
  109.  * Since the JPEG code is intended to run in small memory model on 80x86
  110.  * machines, we can't just allocate the histogram in one chunk.  Instead
  111.  * of a true 3-D array, we use a row of pointers to 2-D arrays.  Each
  112.  * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  113.  * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries.  Note that
  114.  * on 80x86 machines, the pointer row is in near memory but the actual
  115.  * arrays are in far memory (same arrangement as we use for image arrays).
  116.  */
  117. #define MAXNUMCOLORS  (MAXJSAMPLE+1) /* maximum size of colormap */
  118. /* These will do the right thing for either R,G,B or B,G,R color order,
  119.  * but you may not like the results for other color orders.
  120.  */
  121. #define HIST_C0_BITS  5 /* bits of precision in R/B histogram */
  122. #define HIST_C1_BITS  6 /* bits of precision in G histogram */
  123. #define HIST_C2_BITS  5 /* bits of precision in B/R histogram */
  124. /* Number of elements along histogram axes. */
  125. #define HIST_C0_ELEMS  (1<<HIST_C0_BITS)
  126. #define HIST_C1_ELEMS  (1<<HIST_C1_BITS)
  127. #define HIST_C2_ELEMS  (1<<HIST_C2_BITS)
  128. /* These are the amounts to shift an input value to get a histogram index. */
  129. #define C0_SHIFT  (BITS_IN_JSAMPLE-HIST_C0_BITS)
  130. #define C1_SHIFT  (BITS_IN_JSAMPLE-HIST_C1_BITS)
  131. #define C2_SHIFT  (BITS_IN_JSAMPLE-HIST_C2_BITS)
  132. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  133. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  134. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  135. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  136. typedef hist2d * hist3d; /* type for top-level pointer */
  137. /* Declarations for Floyd-Steinberg dithering.
  138.  *
  139.  * Errors are accumulated into the array fserrors[], at a resolution of
  140.  * 1/16th of a pixel count.  The error at a given pixel is propagated
  141.  * to its not-yet-processed neighbors using the standard F-S fractions,
  142.  * ... (here) 7/16
  143.  * 3/16 5/16 1/16
  144.  * We work left-to-right on even rows, right-to-left on odd rows.
  145.  *
  146.  * We can get away with a single array (holding one row's worth of errors)
  147.  * by using it to store the current row's errors at pixel columns not yet
  148.  * processed, but the next row's errors at columns already processed.  We
  149.  * need only a few extra variables to hold the errors immediately around the
  150.  * current column.  (If we are lucky, those variables are in registers, but
  151.  * even if not, they're probably cheaper to access than array elements are.)
  152.  *
  153.  * The fserrors[] array has (#columns + 2) entries; the extra entry at
  154.  * each end saves us from special-casing the first and last pixels.
  155.  * Each entry is three values long, one value for each color component.
  156.  *
  157.  * Note: on a wide image, we might not have enough room in a PC's near data
  158.  * segment to hold the error array; so it is allocated with alloc_large.
  159.  */
  160. #if BITS_IN_JSAMPLE == 8
  161. typedef INT16 FSERROR; /* 16 bits should be enough */
  162. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  163. #else
  164. typedef INT32 FSERROR; /* may need more than 16 bits */
  165. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  166. #endif
  167. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  168. /* Private subobject */
  169. typedef struct {
  170.   struct jpeg_color_quantizer pub; /* public fields */
  171.   /* Variables for accumulating image statistics */
  172.   hist3d histogram; /* pointer to the histogram */
  173.   /* Variables for Floyd-Steinberg dithering */
  174.   FSERRPTR fserrors; /* accumulated errors */
  175.   boolean on_odd_row; /* flag to remember which row we are on */
  176.   int * error_limiter; /* table for clamping the applied error */
  177. } my_cquantizer;
  178. typedef my_cquantizer * my_cquantize_ptr;
  179. /*
  180.  * Prescan some rows of pixels.
  181.  * In this module the prescan simply updates the histogram, which has been
  182.  * initialized to zeroes by start_pass.
  183.  * An output_buf parameter is required by the method signature, but no data
  184.  * is actually output (in fact the buffer controller is probably passing a
  185.  * NULL pointer).
  186.  */
  187. METHODDEF void
  188. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  189.   JSAMPARRAY output_buf, int num_rows)
  190. {
  191.   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  192.   register JSAMPROW ptr;
  193.   register histptr histp;
  194.   register hist3d histogram = cquantize->histogram;
  195.   int row;
  196.   JDIMENSION col;
  197.   JDIMENSION width = cinfo->output_width;
  198.   for (row = 0; row < num_rows; row++) {
  199.     ptr = input_buf[row];
  200.     for (col = width; col > 0; col--) {
  201.       /* get pixel value and index into the histogram */
  202.       histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  203.  [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  204.  [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  205.       /* increment, check for overflow and undo increment if so. */
  206.       if (++(*histp) <= 0)
  207. (*histp)--;
  208.       ptr += 3;
  209.     }
  210.   }
  211. }
  212. /*
  213.  * Next we have the really interesting routines: selection of a colormap
  214.  * given the completed histogram.
  215.  * These routines work with a list of "boxes", each representing a rectangular
  216.  * subset of the input color space (to histogram precision).
  217.  */
  218. typedef struct {
  219.   /* The bounds of the box (inclusive); expressed as histogram indexes */
  220.   int c0min, c0max;
  221.   int c1min, c1max;
  222.   int c2min, c2max;
  223.   /* The volume (actually 2-norm) of the box */
  224.   INT32 volume;
  225.   /* The number of nonzero histogram cells within this box */
  226.   long colorcount;
  227. } box;
  228. typedef box * boxptr;
  229. LOCAL boxptr
  230. find_biggest_color_pop (boxptr boxlist, int numboxes)
  231. /* Find the splittable box with the largest color population */
  232. /* Returns NULL if no splittable boxes remain */
  233. {
  234.   register boxptr boxp;
  235.   register int i;
  236.   register long maxc = 0;
  237.   boxptr which = NULL;
  238.   
  239.   for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  240.     if (boxp->colorcount > maxc && boxp->volume > 0) {
  241.       which = boxp;
  242.       maxc = boxp->colorcount;
  243.     }
  244.   }
  245.   return which;
  246. }
  247. LOCAL boxptr
  248. find_biggest_volume (boxptr boxlist, int numboxes)
  249. /* Find the splittable box with the largest (scaled) volume */
  250. /* Returns NULL if no splittable boxes remain */
  251. {
  252.   register boxptr boxp;
  253.   register int i;
  254.   register INT32 maxv = 0;
  255.   boxptr which = NULL;
  256.   
  257.   for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  258.     if (boxp->volume > maxv) {
  259.       which = boxp;
  260.       maxv = boxp->volume;
  261.     }
  262.   }
  263.   return which;
  264. }
  265. LOCAL void
  266. update_box (j_decompress_ptr cinfo, boxptr boxp)
  267. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  268. /* and recompute its volume and population */
  269. {
  270.   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  271.   hist3d histogram = cquantize->histogram;
  272.   histptr histp;
  273.   int c0,c1,c2;
  274.   int c0min,c0max,c1min,c1max,c2min,c2max;
  275.   INT32 dist0,dist1,dist2;
  276.   long ccount;
  277.   
  278.   c0min = boxp->c0min;  c0max = boxp->c0max;
  279.   c1min = boxp->c1min;  c1max = boxp->c1max;
  280.   c2min = boxp->c2min;  c2max = boxp->c2max;
  281.   
  282.   if (c0max > c0min)
  283.     for (c0 = c0min; c0 <= c0max; c0++)
  284.       for (c1 = c1min; c1 <= c1max; c1++) {
  285. histp = & histogram[c0][c1][c2min];
  286. for (c2 = c2min; c2 <= c2max; c2++)
  287.   if (*histp++ != 0) {
  288.     boxp->c0min = c0min = c0;
  289.     goto have_c0min;
  290.   }
  291.       }
  292.  have_c0min:
  293.   if (c0max > c0min)
  294.     for (c0 = c0max; c0 >= c0min; c0--)
  295.       for (c1 = c1min; c1 <= c1max; c1++) {
  296. histp = & histogram[c0][c1][c2min];
  297. for (c2 = c2min; c2 <= c2max; c2++)
  298.   if (*histp++ != 0) {
  299.     boxp->c0max = c0max = c0;
  300.     goto have_c0max;
  301.   }
  302.       }
  303.  have_c0max:
  304.   if (c1max > c1min)
  305.     for (c1 = c1min; c1 <= c1max; c1++)
  306.       for (c0 = c0min; c0 <= c0max; c0++) {
  307. histp = & histogram[c0][c1][c2min];
  308. for (c2 = c2min; c2 <= c2max; c2++)
  309.   if (*histp++ != 0) {
  310.     boxp->c1min = c1min = c1;
  311.     goto have_c1min;
  312.   }
  313.       }
  314.  have_c1min:
  315.   if (c1max > c1min)
  316.     for (c1 = c1max; c1 >= c1min; c1--)
  317.       for (c0 = c0min; c0 <= c0max; c0++) {
  318. histp = & histogram[c0][c1][c2min];
  319. for (c2 = c2min; c2 <= c2max; c2++)
  320.   if (*histp++ != 0) {
  321.     boxp->c1max = c1max = c1;
  322.     goto have_c1max;
  323.   }
  324.       }
  325.  have_c1max:
  326.   if (c2max > c2min)
  327.     for (c2 = c2min; c2 <= c2max; c2++)
  328.       for (c0 = c0min; c0 <= c0max; c0++) {
  329. histp = & histogram[c0][c1min][c2];
  330. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  331.   if (*histp != 0) {
  332.     boxp->c2min = c2min = c2;
  333.     goto have_c2min;
  334.   }
  335.       }
  336.  have_c2min:
  337.   if (c2max > c2min)
  338.     for (c2 = c2max; c2 >= c2min; c2--)
  339.       for (c0 = c0min; c0 <= c0max; c0++) {
  340. histp = & histogram[c0][c1min][c2];
  341. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  342.   if (*histp != 0) {
  343.     boxp->c2max = c2max = c2;
  344.     goto have_c2max;
  345.   }
  346.       }
  347.  have_c2max:
  348.   /* Update box volume.
  349.    * We use 2-norm rather than real volume here; this biases the method
  350.    * against making long narrow boxes, and it has the side benefit that
  351.    * a box is splittable iff norm > 0.
  352.    * Since the differences are expressed in histogram-cell units,
  353.    * we have to shift back to JSAMPLE units to get consistent distances;
  354.    * after which, we scale according to the selected distance scale factors.
  355.    */
  356.   dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  357.   dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  358.   dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  359.   boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  360.   
  361.   /* Now scan remaining volume of box and compute population */
  362.   ccount = 0;
  363.   for (c0 = c0min; c0 <= c0max; c0++)
  364.     for (c1 = c1min; c1 <= c1max; c1++) {
  365.       histp = & histogram[c0][c1][c2min];
  366.       for (c2 = c2min; c2 <= c2max; c2++, histp++)
  367. if (*histp != 0) {
  368.   ccount++;
  369. }
  370.     }
  371.   boxp->colorcount = ccount;
  372. }
  373. LOCAL int
  374. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  375.     int desired_colors)
  376. /* Repeatedly select and split the largest box until we have enough boxes */
  377. {
  378.   int n,lb;
  379.   int c0,c1,c2,cmax;
  380.   register boxptr b1,b2;
  381.   while (numboxes < desired_colors) {
  382.     /* Select box to split.
  383.      * Current algorithm: by population for first half, then by volume.
  384.      */
  385.     if (numboxes*2 <= desired_colors) {
  386.       b1 = find_biggest_color_pop(boxlist, numboxes);
  387.     } else {
  388.       b1 = find_biggest_volume(boxlist, numboxes);
  389.     }
  390.     if (b1 == NULL) /* no splittable boxes left! */
  391.       break;
  392.     b2 = &boxlist[numboxes]; /* where new box will go */
  393.     /* Copy the color bounds to the new box. */
  394.     b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  395.     b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  396.     /* Choose which axis to split the box on.
  397.      * Current algorithm: longest scaled axis.
  398.      * See notes in update_box about scaling distances.
  399.      */
  400.     c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  401.     c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  402.     c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  403.     /* We want to break any ties in favor of green, then red, blue last.
  404.      * This code does the right thing for R,G,B or B,G,R color orders only.
  405.      */
  406. #if RGB_RED == 0
  407.     cmax = c1; n = 1;
  408.     if (c0 > cmax) { cmax = c0; n = 0; }
  409.     if (c2 > cmax) { n = 2; }
  410. #else
  411.     cmax = c1; n = 1;
  412.     if (c2 > cmax) { cmax = c2; n = 2; }
  413.     if (c0 > cmax) { n = 0; }
  414. #endif
  415.     /* Choose split point along selected axis, and update box bounds.
  416.      * Current algorithm: split at halfway point.
  417.      * (Since the box has been shrunk to minimum volume,
  418.      * any split will produce two nonempty subboxes.)
  419.      * Note that lb value is max for lower box, so must be < old max.
  420.      */
  421.     switch (n) {
  422.     case 0:
  423.       lb = (b1->c0max + b1->c0min) / 2;
  424.       b1->c0max = lb;
  425.       b2->c0min = lb+1;
  426.       break;
  427.     case 1:
  428.       lb = (b1->c1max + b1->c1min) / 2;
  429.       b1->c1max = lb;
  430.       b2->c1min = lb+1;
  431.       break;
  432.     case 2:
  433.       lb = (b1->c2max + b1->c2min) / 2;
  434.       b1->c2max = lb;
  435.       b2->c2min = lb+1;
  436.       break;
  437.     }
  438.     /* Update stats for boxes */
  439.     update_box(cinfo, b1);
  440.     update_box(cinfo, b2);
  441.     numboxes++;
  442.   }
  443.   return numboxes;
  444. }
  445. LOCAL void
  446. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  447. /* Compute representative color for a box, put it in colormap[icolor] */
  448. {
  449.   /* Current algorithm: mean weighted by pixels (not colors) */
  450.   /* Note it is important to get the rounding correct! */
  451.   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  452.   hist3d histogram = cquantize->histogram;
  453.   histptr histp;
  454.   int c0,c1,c2;
  455.   int c0min,c0max,c1min,c1max,c2min,c2max;
  456.   long count;
  457.   long total = 0;
  458.   long c0total = 0;
  459.   long c1total = 0;
  460.   long c2total = 0;
  461.   
  462.   c0min = boxp->c0min;  c0max = boxp->c0max;
  463.   c1min = boxp->c1min;  c1max = boxp->c1max;
  464.   c2min = boxp->c2min;  c2max = boxp->c2max;
  465.   
  466.   for (c0 = c0min; c0 <= c0max; c0++)
  467.     for (c1 = c1min; c1 <= c1max; c1++) {
  468.       histp = & histogram[c0][c1][c2min];
  469.       for (c2 = c2min; c2 <= c2max; c2++) {
  470. if ((count = *histp++) != 0) {
  471.   total += count;
  472.   c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  473.   c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  474.   c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  475. }
  476.       }
  477.     }
  478.   
  479.   cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  480.   cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  481.   cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  482. }
  483. LOCAL void
  484. select_colors (j_decompress_ptr cinfo)
  485. /* Master routine for color selection */
  486. {
  487.   boxptr boxlist;
  488.   int numboxes;
  489.   int desired = cinfo->desired_number_of_colors;
  490.   int i;
  491.   /* Allocate workspace for box list */
  492.   boxlist = (boxptr) (*cinfo->mem->alloc_small)
  493.     ((j_common_ptr) cinfo, JPOOL_IMAGE, desired * SIZEOF(box));
  494.   /* Initialize one box containing whole space */
  495.   numboxes = 1;
  496.   boxlist[0].c0min = 0;
  497.   boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  498.   boxlist[0].c1min = 0;
  499.   boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  500.   boxlist[0].c2min = 0;
  501.   boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  502.   /* Shrink it to actually-used volume and set its statistics */
  503.   update_box(cinfo, & boxlist[0]);
  504.   /* Perform median-cut to produce final box list */
  505.   numboxes = median_cut(cinfo, boxlist, numboxes, desired);
  506.   /* Compute the representative color for each box, fill colormap */
  507.   for (i = 0; i < numboxes; i++)
  508.     compute_color(cinfo, & boxlist[i], i);
  509.   cinfo->actual_number_of_colors = numboxes;
  510.   TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  511. }
  512. /*
  513.  * These routines are concerned with the time-critical task of mapping input
  514.  * colors to the nearest color in the selected colormap.
  515.  *
  516.  * We re-use the histogram space as an "inverse color map", essentially a
  517.  * cache for the results of nearest-color searches.  All colors within a
  518.  * histogram cell will be mapped to the same colormap entry, namely the one
  519.  * closest to the cell's center.  This may not be quite the closest entry to
  520.  * the actual input color, but it's almost as good.  A zero in the cache
  521.  * indicates we haven't found the nearest color for that cell yet; the array
  522.  * is cleared to zeroes before starting the mapping pass.  When we find the
  523.  * nearest color for a cell, its colormap index plus one is recorded in the
  524.  * cache for future use.  The pass2 scanning routines call fill_inverse_cmap
  525.  * when they need to use an unfilled entry in the cache.
  526.  *
  527.  * Our method of efficiently finding nearest colors is based on the "locally
  528.  * sorted search" idea described by Heckbert and on the incremental distance
  529.  * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  530.  * Gems II (James Arvo, ed.  Academic Press, 1991).  Thomas points out that
  531.  * the distances from a given colormap entry to each cell of the histogram can
  532.  * be computed quickly using an incremental method: the differences between
  533.  * distances to adjacent cells themselves differ by a constant.  This allows a
  534.  * fairly fast implementation of the "brute force" approach of computing the
  535.  * distance from every colormap entry to every histogram cell.  Unfortunately,
  536.  * it needs a work array to hold the best-distance-so-far for each histogram
  537.  * cell (because the inner loop has to be over cells, not colormap entries).
  538.  * The work array elements have to be INT32s, so the work array would need
  539.  * 256Kb at our recommended precision.  This is not feasible in DOS machines.
  540.  *
  541.  * To get around these problems, we apply Thomas' method to compute the
  542.  * nearest colors for only the cells within a small subbox of the histogram.
  543.  * The work array need be only as big as the subbox, so the memory usage
  544.  * problem is solved.  Furthermore, we need not fill subboxes that are never
  545.  * referenced in pass2; many images use only part of the color gamut, so a
  546.  * fair amount of work is saved.  An additional advantage of this
  547.  * approach is that we can apply Heckbert's locality criterion to quickly
  548.  * eliminate colormap entries that are far away from the subbox; typically
  549.  * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  550.  * and we need not compute their distances to individual cells in the subbox.
  551.  * The speed of this approach is heavily influenced by the subbox size: too
  552.  * small means too much overhead, too big loses because Heckbert's criterion
  553.  * can't eliminate as many colormap entries.  Empirically the best subbox
  554.  * size seems to be about 1/512th of the histogram (1/8th in each direction).
  555.  *
  556.  * Thomas' article also describes a refined method which is asymptotically
  557.  * faster than the brute-force method, but it is also far more complex and
  558.  * cannot efficiently be applied to small subboxes.  It is therefore not
  559.  * useful for programs intended to be portable to DOS machines.  On machines
  560.  * with plenty of memory, filling the whole histogram in one shot with Thomas'
  561.  * refined method might be faster than the present code --- but then again,
  562.  * it might not be any faster, and it's certainly more complicated.
  563.  */
  564. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  565. #define BOX_C0_LOG  (HIST_C0_BITS-3)
  566. #define BOX_C1_LOG  (HIST_C1_BITS-3)
  567. #define BOX_C2_LOG  (HIST_C2_BITS-3)
  568. #define BOX_C0_ELEMS  (1<<BOX_C0_LOG) /* # of hist cells in update box */
  569. #define BOX_C1_ELEMS  (1<<BOX_C1_LOG)
  570. #define BOX_C2_ELEMS  (1<<BOX_C2_LOG)
  571. #define BOX_C0_SHIFT  (C0_SHIFT + BOX_C0_LOG)
  572. #define BOX_C1_SHIFT  (C1_SHIFT + BOX_C1_LOG)
  573. #define BOX_C2_SHIFT  (C2_SHIFT + BOX_C2_LOG)
  574. /*
  575.  * The next three routines implement inverse colormap filling.  They could
  576.  * all be folded into one big routine, but splitting them up this way saves
  577.  * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  578.  * and may allow some compilers to produce better code by registerizing more
  579.  * inner-loop variables.
  580.  */
  581. LOCAL int
  582. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  583.     JSAMPLE colorlist[])
  584. /* Locate the colormap entries close enough to an update box to be candidates
  585.  * for the nearest entry to some cell(s) in the update box.  The update box
  586.  * is specified by the center coordinates of its first cell.  The number of
  587.  * candidate colormap entries is returned, and their colormap indexes are
  588.  * placed in colorlist[].
  589.  * This routine uses Heckbert's "locally sorted search" criterion to select
  590.  * the colors that need further consideration.
  591.  */
  592. {
  593.   int numcolors = cinfo->actual_number_of_colors;
  594.   int maxc0, maxc1, maxc2;
  595.   int centerc0, centerc1, centerc2;
  596.   int i, x, ncolors;
  597.   INT32 minmaxdist, min_dist, max_dist, tdist;
  598.   INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  599.   /* Compute true coordinates of update box's upper corner and center.
  600.    * Actually we compute the coordinates of the center of the upper-corner
  601.    * histogram cell, which are the upper bounds of the volume we care about.
  602.    * Note that since ">>" rounds down, the "center" values may be closer to
  603.    * min than to max; hence comparisons to them must be "<=", not "<".
  604.    */
  605.   maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  606.   centerc0 = (minc0 + maxc0) >> 1;
  607.   maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  608.   centerc1 = (minc1 + maxc1) >> 1;
  609.   maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  610.   centerc2 = (minc2 + maxc2) >> 1;
  611.   /* For each color in colormap, find:
  612.    *  1. its minimum squared-distance to any point in the update box
  613.    *     (zero if color is within update box);
  614.    *  2. its maximum squared-distance to any point in the update box.
  615.    * Both of these can be found by considering only the corners of the box.
  616.    * We save the minimum distance for each color in mindist[];
  617.    * only the smallest maximum distance is of interest.
  618.    */
  619.   minmaxdist = 0x7FFFFFFFL;
  620.   for (i = 0; i < numcolors; i++) {
  621.     /* We compute the squared-c0-distance term, then add in the other two. */
  622.     x = GETJSAMPLE(cinfo->colormap[0][i]);
  623.     if (x < minc0) {
  624.       tdist = (x - minc0) * C0_SCALE;
  625.       min_dist = tdist*tdist;
  626.       tdist = (x - maxc0) * C0_SCALE;
  627.       max_dist = tdist*tdist;
  628.     } else if (x > maxc0) {
  629.       tdist = (x - maxc0) * C0_SCALE;
  630.       min_dist = tdist*tdist;
  631.       tdist = (x - minc0) * C0_SCALE;
  632.       max_dist = tdist*tdist;
  633.     } else {
  634.       /* within cell range so no contribution to min_dist */
  635.       min_dist = 0;
  636.       if (x <= centerc0) {
  637. tdist = (x - maxc0) * C0_SCALE;
  638. max_dist = tdist*tdist;
  639.       } else {
  640. tdist = (x - minc0) * C0_SCALE;
  641. max_dist = tdist*tdist;
  642.       }
  643.     }
  644.     x = GETJSAMPLE(cinfo->colormap[1][i]);
  645.     if (x < minc1) {
  646.       tdist = (x - minc1) * C1_SCALE;
  647.       min_dist += tdist*tdist;
  648.       tdist = (x - maxc1) * C1_SCALE;
  649.       max_dist += tdist*tdist;
  650.     } else if (x > maxc1) {
  651.       tdist = (x - maxc1) * C1_SCALE;
  652.       min_dist += tdist*tdist;
  653.       tdist = (x - minc1) * C1_SCALE;
  654.       max_dist += tdist*tdist;
  655.     } else {
  656.       /* within cell range so no contribution to min_dist */
  657.       if (x <= centerc1) {
  658. tdist = (x - maxc1) * C1_SCALE;
  659. max_dist += tdist*tdist;
  660.       } else {
  661. tdist = (x - minc1) * C1_SCALE;
  662. max_dist += tdist*tdist;
  663.       }
  664.     }
  665.     x = GETJSAMPLE(cinfo->colormap[2][i]);
  666.     if (x < minc2) {
  667.       tdist = (x - minc2) * C2_SCALE;
  668.       min_dist += tdist*tdist;
  669.       tdist = (x - maxc2) * C2_SCALE;
  670.       max_dist += tdist*tdist;
  671.     } else if (x > maxc2) {
  672.       tdist = (x - maxc2) * C2_SCALE;
  673.       min_dist += tdist*tdist;
  674.       tdist = (x - minc2) * C2_SCALE;
  675.       max_dist += tdist*tdist;
  676.     } else {
  677.       /* within cell range so no contribution to min_dist */
  678.       if (x <= centerc2) {
  679. tdist = (x - maxc2) * C2_SCALE;
  680. max_dist += tdist*tdist;
  681.       } else {
  682. tdist = (x - minc2) * C2_SCALE;
  683. max_dist += tdist*tdist;
  684.       }
  685.     }
  686.     mindist[i] = min_dist; /* save away the results */
  687.     if (max_dist < minmaxdist)
  688.       minmaxdist = max_dist;
  689.   }
  690.   /* Now we know that no cell in the update box is more than minmaxdist
  691.    * away from some colormap entry.  Therefore, only colors that are
  692.    * within minmaxdist of some part of the box need be considered.
  693.    */
  694.   ncolors = 0;
  695.   for (i = 0; i < numcolors; i++) {
  696.     if (mindist[i] <= minmaxdist)
  697.       colorlist[ncolors++] = (JSAMPLE) i;
  698.   }
  699.   return ncolors;
  700. }
  701. LOCAL void
  702. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  703.   int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  704. /* Find the closest colormap entry for each cell in the update box,
  705.  * given the list of candidate colors prepared by find_nearby_colors.
  706.  * Return the indexes of the closest entries in the bestcolor[] array.
  707.  * This routine uses Thomas' incremental distance calculation method to
  708.  * find the distance from a colormap entry to successive cells in the box.
  709.  */
  710. {
  711.   int ic0, ic1, ic2;
  712.   int i, icolor;
  713.   register INT32 * bptr; /* pointer into bestdist[] array */
  714.   JSAMPLE * cptr; /* pointer into bestcolor[] array */
  715.   INT32 dist0, dist1; /* initial distance values */
  716.   register INT32 dist2; /* current distance in inner loop */
  717.   INT32 xx0, xx1; /* distance increments */
  718.   register INT32 xx2;
  719.   INT32 inc0, inc1, inc2; /* initial values for increments */
  720.   /* This array holds the distance to the nearest-so-far color for each cell */
  721.   INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  722.   /* Initialize best-distance for each cell of the update box */
  723.   bptr = bestdist;
  724.   for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  725.     *bptr++ = 0x7FFFFFFFL;
  726.   
  727.   /* For each color selected by find_nearby_colors,
  728.    * compute its distance to the center of each cell in the box.
  729.    * If that's less than best-so-far, update best distance and color number.
  730.    */
  731.   
  732.   /* Nominal steps between cell centers ("x" in Thomas article) */
  733. #define STEP_C0  ((1 << C0_SHIFT) * C0_SCALE)
  734. #define STEP_C1  ((1 << C1_SHIFT) * C1_SCALE)
  735. #define STEP_C2  ((1 << C2_SHIFT) * C2_SCALE)
  736.   
  737.   for (i = 0; i < numcolors; i++) {
  738.     icolor = GETJSAMPLE(colorlist[i]);
  739.     /* Compute (square of) distance from minc0/c1/c2 to this color */
  740.     inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  741.     dist0 = inc0*inc0;
  742.     inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  743.     dist0 += inc1*inc1;
  744.     inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  745.     dist0 += inc2*inc2;
  746.     /* Form the initial difference increments */
  747.     inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  748.     inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  749.     inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  750.     /* Now loop over all cells in box, updating distance per Thomas method */
  751.     bptr = bestdist;
  752.     cptr = bestcolor;
  753.     xx0 = inc0;
  754.     for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  755.       dist1 = dist0;
  756.       xx1 = inc1;
  757.       for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  758. dist2 = dist1;
  759. xx2 = inc2;
  760. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  761.   if (dist2 < *bptr) {
  762.     *bptr = dist2;
  763.     *cptr = (JSAMPLE) icolor;
  764.   }
  765.   dist2 += xx2;
  766.   xx2 += 2 * STEP_C2 * STEP_C2;
  767.   bptr++;
  768.   cptr++;
  769. }
  770. dist1 += xx1;
  771. xx1 += 2 * STEP_C1 * STEP_C1;
  772.       }
  773.       dist0 += xx0;
  774.       xx0 += 2 * STEP_C0 * STEP_C0;
  775.     }
  776.   }
  777. }
  778. LOCAL void
  779. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  780. /* Fill the inverse-colormap entries in the update box that contains */
  781. /* histogram cell c0/c1/c2.  (Only that one cell MUST be filled, but */
  782. /* we can fill as many others as we wish.) */
  783. {
  784.   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  785.   hist3d histogram = cquantize->histogram;
  786.   int minc0, minc1, minc2; /* lower left corner of update box */
  787.   int ic0, ic1, ic2;
  788.   register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  789.   register histptr cachep; /* pointer into main cache array */
  790.   /* This array lists the candidate colormap indexes. */
  791.   JSAMPLE colorlist[MAXNUMCOLORS];
  792.   int numcolors; /* number of candidate colors */
  793.   /* This array holds the actually closest colormap index for each cell. */
  794.   JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  795.   /* Convert cell coordinates to update box ID */
  796.   c0 >>= BOX_C0_LOG;
  797.   c1 >>= BOX_C1_LOG;
  798.   c2 >>= BOX_C2_LOG;
  799.   /* Compute true coordinates of update box's origin corner.
  800.    * Actually we compute the coordinates of the center of the corner
  801.    * histogram cell, which are the lower bounds of the volume we care about.
  802.    */
  803.   minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  804.   minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  805.   minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  806.   
  807.   /* Determine which colormap entries are close enough to be candidates
  808.    * for the nearest entry to some cell in the update box.
  809.    */
  810.   numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  811.   /* Determine the actually nearest colors. */
  812.   find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  813.    bestcolor);
  814.   /* Save the best color numbers (plus 1) in the main cache array */
  815.   c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  816.   c1 <<= BOX_C1_LOG;
  817.   c2 <<= BOX_C2_LOG;
  818.   cptr = bestcolor;
  819.   for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  820.     for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  821.       cachep = & histogram[c0+ic0][c1+ic1][c2];
  822.       for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  823. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  824.       }
  825.     }
  826.   }
  827. }
  828. /*
  829.  * Map some rows of pixels to the output colormapped representation.
  830.  */
  831. METHODDEF void
  832. pass2_no_dither (j_decompress_ptr cinfo,
  833.  JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  834. /* This version performs no dithering */
  835. {
  836.   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  837.   hist3d histogram = cquantize->histogram;
  838.   register JSAMPROW inptr, outptr;
  839.   register histptr cachep;
  840.   register int c0, c1, c2;
  841.   int row;
  842.   JDIMENSION col;
  843.   JDIMENSION width = cinfo->output_width;
  844.   for (row = 0; row < num_rows; row++) {
  845.     inptr = input_buf[row];
  846.     outptr = output_buf[row];
  847.     for (col = width; col > 0; col--) {
  848.       /* get pixel value and index into the cache */
  849.       c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  850.       c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  851.       c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  852.       cachep = & histogram[c0][c1][c2];
  853.       /* If we have not seen this color before, find nearest colormap entry */
  854.       /* and update the cache */
  855.       if (*cachep == 0)
  856. fill_inverse_cmap(cinfo, c0,c1,c2);
  857.       /* Now emit the colormap index for this cell */
  858.       *outptr++ = (JSAMPLE) (*cachep - 1);
  859.     }
  860.   }
  861. }
  862. METHODDEF void
  863. pass2_fs_dither (j_decompress_ptr cinfo,
  864.  JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  865. /* This version performs Floyd-Steinberg dithering */
  866. {
  867.   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  868.   hist3d histogram = cquantize->histogram;
  869.   register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  870.   LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  871.   LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  872.   register FSERRPTR errorptr; /* => fserrors[] at column before current */
  873.   JSAMPROW inptr; /* => current input pixel */
  874.   JSAMPROW outptr; /* => current output pixel */
  875.   histptr cachep;
  876.   int dir; /* +1 or -1 depending on direction */
  877.   int dir3; /* 3*dir, for advancing inptr & errorptr */
  878.   int row;
  879.   JDIMENSION col;
  880.   JDIMENSION width = cinfo->output_width;
  881.   JSAMPLE *range_limit = cinfo->sample_range_limit;
  882.   int *error_limit = cquantize->error_limiter;
  883.   JSAMPROW colormap0 = cinfo->colormap[0];
  884.   JSAMPROW colormap1 = cinfo->colormap[1];
  885.   JSAMPROW colormap2 = cinfo->colormap[2];
  886.   SHIFT_TEMPS
  887.   for (row = 0; row < num_rows; row++) {
  888.     inptr = input_buf[row];
  889.     outptr = output_buf[row];
  890.     if (cquantize->on_odd_row) {
  891.       /* work right to left in this row */
  892.       inptr += (width-1) * 3; /* so point to rightmost pixel */
  893.       outptr += width-1;
  894.       dir = -1;
  895.       dir3 = -3;
  896.       errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  897.       cquantize->on_odd_row = FALSE; /* flip for next time */
  898.     } else {
  899.       /* work left to right in this row */
  900.       dir = 1;
  901.       dir3 = 3;
  902.       errorptr = cquantize->fserrors; /* => entry before first real column */
  903.       cquantize->on_odd_row = TRUE; /* flip for next time */
  904.     }
  905.     /* Preset error values: no error propagated to first pixel from left */
  906.     cur0 = cur1 = cur2 = 0;
  907.     /* and no error propagated to row below yet */
  908.     belowerr0 = belowerr1 = belowerr2 = 0;
  909.     bpreverr0 = bpreverr1 = bpreverr2 = 0;
  910.     for (col = width; col > 0; col--) {
  911.       /* curN holds the error propagated from the previous pixel on the
  912.        * current line.  Add the error propagated from the previous line
  913.        * to form the complete error correction term for this pixel, and
  914.        * round the error term (which is expressed * 16) to an integer.
  915.        * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  916.        * for either sign of the error value.
  917.        * Note: errorptr points to *previous* column's array entry.
  918.        */
  919.       cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  920.       cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  921.       cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  922.       /* Limit the error using transfer function set by init_error_limit.
  923.        * See comments with init_error_limit for rationale.
  924.        */
  925.       cur0 = error_limit[cur0];
  926.       cur1 = error_limit[cur1];
  927.       cur2 = error_limit[cur2];
  928.       /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  929.        * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  930.        * this sets the required size of the range_limit array.
  931.        */
  932.       cur0 += GETJSAMPLE(inptr[0]);
  933.       cur1 += GETJSAMPLE(inptr[1]);
  934.       cur2 += GETJSAMPLE(inptr[2]);
  935.       cur0 = GETJSAMPLE(range_limit[cur0]);
  936.       cur1 = GETJSAMPLE(range_limit[cur1]);
  937.       cur2 = GETJSAMPLE(range_limit[cur2]);
  938.       /* Index into the cache with adjusted pixel value */
  939.       cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  940.       /* If we have not seen this color before, find nearest colormap */
  941.       /* entry and update the cache */
  942.       if (*cachep == 0)
  943. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  944.       /* Now emit the colormap index for this cell */
  945.       { register int pixcode = *cachep - 1;
  946. *outptr = (JSAMPLE) pixcode;
  947. /* Compute representation error for this pixel */
  948. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  949. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  950. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  951.       }
  952.       /* Compute error fractions to be propagated to adjacent pixels.
  953.        * Add these into the running sums, and simultaneously shift the
  954.        * next-line error sums left by 1 column.
  955.        */
  956.       { register LOCFSERROR bnexterr, delta;
  957. bnexterr = cur0; /* Process component 0 */
  958. delta = cur0 * 2;
  959. cur0 += delta; /* form error * 3 */
  960. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  961. cur0 += delta; /* form error * 5 */
  962. bpreverr0 = belowerr0 + cur0;
  963. belowerr0 = bnexterr;
  964. cur0 += delta; /* form error * 7 */
  965. bnexterr = cur1; /* Process component 1 */
  966. delta = cur1 * 2;
  967. cur1 += delta; /* form error * 3 */
  968. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  969. cur1 += delta; /* form error * 5 */
  970. bpreverr1 = belowerr1 + cur1;
  971. belowerr1 = bnexterr;
  972. cur1 += delta; /* form error * 7 */
  973. bnexterr = cur2; /* Process component 2 */
  974. delta = cur2 * 2;
  975. cur2 += delta; /* form error * 3 */
  976. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  977. cur2 += delta; /* form error * 5 */
  978. bpreverr2 = belowerr2 + cur2;
  979. belowerr2 = bnexterr;
  980. cur2 += delta; /* form error * 7 */
  981.       }
  982.       /* At this point curN contains the 7/16 error value to be propagated
  983.        * to the next pixel on the current line, and all the errors for the
  984.        * next line have been shifted over.  We are therefore ready to move on.
  985.        */
  986.       inptr += dir3; /* Advance pixel pointers to next column */
  987.       outptr += dir;
  988.       errorptr += dir3; /* advance errorptr to current column */
  989.     }
  990.     /* Post-loop cleanup: we must unload the final error values into the
  991.      * final fserrors[] entry.  Note we need not unload belowerrN because
  992.      * it is for the dummy column before or after the actual array.
  993.      */
  994.     errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  995.     errorptr[1] = (FSERROR) bpreverr1;
  996.     errorptr[2] = (FSERROR) bpreverr2;
  997.   }
  998. }
  999. /*
  1000.  * Initialize the error-limiting transfer function (lookup table).
  1001.  * The raw F-S error computation can potentially compute error values of up to
  1002.  * +- MAXJSAMPLE.  But we want the maximum correction applied to a pixel to be
  1003.  * much less, otherwise obviously wrong pixels will be created.  (Typical
  1004.  * effects include weird fringes at color-area boundaries, isolated bright
  1005.  * pixels in a dark area, etc.)  The standard advice for avoiding this problem
  1006.  * is to ensure that the "corners" of the color cube are allocated as output
  1007.  * colors; then repeated errors in the same direction cannot cause cascading
  1008.  * error buildup.  However, that only prevents the error from getting
  1009.  * completely out of hand; Aaron Giles reports that error limiting improves
  1010.  * the results even with corner colors allocated.
  1011.  * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  1012.  * well, but the smoother transfer function used below is even better.  Thanks
  1013.  * to Aaron Giles for this idea.
  1014.  */
  1015. LOCAL void
  1016. init_error_limit (j_decompress_ptr cinfo)
  1017. /* Allocate and fill in the error_limiter table */
  1018. {
  1019.   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  1020.   int * table;
  1021.   int in, out;
  1022.   table = (int *) (*cinfo->mem->alloc_small)
  1023.     ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  1024.   table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  1025.   cquantize->error_limiter = table;
  1026. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  1027.   /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  1028.   out = 0;
  1029.   for (in = 0; in < STEPSIZE; in++, out++) {
  1030.     table[in] = out; table[-in] = -out;
  1031.   }
  1032.   /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  1033.   for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  1034.     table[in] = out; table[-in] = -out;
  1035.   }
  1036.   /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  1037.   for (; in <= MAXJSAMPLE; in++) {
  1038.     table[in] = out; table[-in] = -out;
  1039.   }
  1040. #undef STEPSIZE
  1041. }
  1042. /*
  1043.  * Finish up at the end of each pass.
  1044.  */
  1045. METHODDEF void
  1046. finish_pass1 (j_decompress_ptr cinfo)
  1047. {
  1048.   /* Select the representative colors and fill in cinfo->colormap */
  1049.   select_colors(cinfo);
  1050. }
  1051. METHODDEF void
  1052. finish_pass2 (j_decompress_ptr cinfo)
  1053. {
  1054.   /* no work */
  1055. }
  1056. /*
  1057.  * Initialize for each processing pass.
  1058.  */
  1059. METHODDEF void
  1060. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  1061. {
  1062.   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  1063.   hist3d histogram = cquantize->histogram;
  1064.   int i;
  1065.   if (is_pre_scan) {
  1066.     /* Set up method pointers */
  1067.     cquantize->pub.color_quantize = prescan_quantize;
  1068.     cquantize->pub.finish_pass = finish_pass1;
  1069.   } else {
  1070.     /* Set up method pointers */
  1071.     if (cinfo->dither_mode == JDITHER_FS)
  1072.       cquantize->pub.color_quantize = pass2_fs_dither;
  1073.     else
  1074.       cquantize->pub.color_quantize = pass2_no_dither;
  1075.     cquantize->pub.finish_pass = finish_pass2;
  1076.   }
  1077.   /* Zero the histogram or inverse color map */
  1078.   for (i = 0; i < HIST_C0_ELEMS; i++) {
  1079.     jzero_far((void FAR *) histogram[i],
  1080.       HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  1081.   }
  1082. }
  1083. /*
  1084.  * Module initialization routine for 2-pass color quantization.
  1085.  */
  1086. GLOBAL void
  1087. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  1088. {
  1089.   my_cquantize_ptr cquantize;
  1090.   int i;
  1091.   cquantize = (my_cquantize_ptr)
  1092.     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  1093. SIZEOF(my_cquantizer));
  1094.   cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  1095.   cquantize->pub.start_pass = start_pass_2_quant;
  1096.   /* Make sure jdmaster didn't give me a case I can't handle */
  1097.   if (cinfo->out_color_components != 3)
  1098.     ERREXIT(cinfo, JERR_NOTIMPL);
  1099.   /* Only F-S dithering or no dithering is supported. */
  1100.   /* If user asks for ordered dither, give him F-S. */
  1101.   if (cinfo->dither_mode != JDITHER_NONE)
  1102.     cinfo->dither_mode = JDITHER_FS;
  1103.   /* Make sure color count is acceptable */
  1104.   i = (cinfo->colormap != NULL) ? cinfo->actual_number_of_colors
  1105. : cinfo->desired_number_of_colors;
  1106.   /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  1107.   if (i < 8)
  1108.     ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  1109.   /* Make sure colormap indexes can be represented by JSAMPLEs */
  1110.   if (i > MAXNUMCOLORS)
  1111.     ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  1112.   /* Allocate the histogram/inverse colormap storage */
  1113.   cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  1114.     ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  1115.   for (i = 0; i < HIST_C0_ELEMS; i++) {
  1116.     cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  1117.       ((j_common_ptr) cinfo, JPOOL_IMAGE,
  1118.        HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  1119.   }
  1120.   /* Allocate storage for the completed colormap,
  1121.    * unless it has been supplied by the application.
  1122.    * We do this now since it is FAR storage and may affect
  1123.    * the memory manager's space calculations.
  1124.    */
  1125.   if (cinfo->colormap == NULL) {
  1126.     cinfo->colormap = (*cinfo->mem->alloc_sarray)
  1127.       ((j_common_ptr) cinfo, JPOOL_IMAGE,
  1128.        (JDIMENSION) cinfo->desired_number_of_colors, (JDIMENSION) 3);
  1129.   }
  1130.   /* Allocate Floyd-Steinberg workspace if necessary. */
  1131.   /* This isn't needed until pass 2, but again it is FAR storage. */
  1132.   if (cinfo->dither_mode == JDITHER_FS) {
  1133.     size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  1134.  (3 * SIZEOF(FSERROR)));
  1135.     cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  1136.       ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  1137.     /* Initialize the propagated errors to zero. */
  1138.     jzero_far((void FAR *) cquantize->fserrors, arraysize);
  1139.     cquantize->on_odd_row = FALSE;
  1140.     init_error_limit(cinfo);
  1141.   }
  1142. }
  1143. #endif /* QUANT_2PASS_SUPPORTED */