jquant2.c
Go to the documentation of this file.
00001 /*
00002  * jquant2.c
00003  *
00004  * Copyright (C) 1991-1996, Thomas G. Lane.
00005  * This file is part of the Independent JPEG Group's software.
00006  * For conditions of distribution and use, see the accompanying README file.
00007  *
00008  * This file contains 2-pass color quantization (color mapping) routines.
00009  * These routines provide selection of a custom color map for an image,
00010  * followed by mapping of the image to that color map, with optional
00011  * Floyd-Steinberg dithering.
00012  * It is also possible to use just the second pass to map to an arbitrary
00013  * externally-given color map.
00014  *
00015  * Note: ordered dithering is not supported, since there isn't any fast
00016  * way to compute intercolor distances; it's unclear that ordered dither's
00017  * fundamental assumptions even hold with an irregularly spaced color map.
00018  */
00019 
00020 #define JPEG_INTERNALS
00021 #include "jinclude.h"
00022 #include "jpeglib.h"
00023 
00024 #ifdef QUANT_2PASS_SUPPORTED
00025 
00026 
00027 /*
00028  * This module implements the well-known Heckbert paradigm for color
00029  * quantization.  Most of the ideas used here can be traced back to
00030  * Heckbert's seminal paper
00031  *   Heckbert, Paul.  "Color Image Quantization for Frame Buffer Display",
00032  *   Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
00033  *
00034  * In the first pass over the image, we accumulate a histogram showing the
00035  * usage count of each possible color.  To keep the histogram to a reasonable
00036  * size, we reduce the precision of the input; typical practice is to retain
00037  * 5 or 6 bits per color, so that 8 or 4 different input values are counted
00038  * in the same histogram cell.
00039  *
00040  * Next, the color-selection step begins with a box representing the whole
00041  * color space, and repeatedly splits the "largest" remaining box until we
00042  * have as many boxes as desired colors.  Then the mean color in each
00043  * remaining box becomes one of the possible output colors.
00044  * 
00045  * The second pass over the image maps each input pixel to the closest output
00046  * color (optionally after applying a Floyd-Steinberg dithering correction).
00047  * This mapping is logically trivial, but making it go fast enough requires
00048  * considerable care.
00049  *
00050  * Heckbert-style quantizers vary a good deal in their policies for choosing
00051  * the "largest" box and deciding where to cut it.  The particular policies
00052  * used here have proved out well in experimental comparisons, but better ones
00053  * may yet be found.
00054  *
00055  * In earlier versions of the IJG code, this module quantized in YCbCr color
00056  * space, processing the raw upsampled data without a color conversion step.
00057  * This allowed the color conversion math to be done only once per colormap
00058  * entry, not once per pixel.  However, that optimization precluded other
00059  * useful optimizations (such as merging color conversion with upsampling)
00060  * and it also interfered with desired capabilities such as quantizing to an
00061  * externally-supplied colormap.  We have therefore abandoned that approach.
00062  * The present code works in the post-conversion color space, typically RGB.
00063  *
00064  * To improve the visual quality of the results, we actually work in scaled
00065  * RGB space, giving G distances more weight than R, and R in turn more than
00066  * B.  To do everything in integer math, we must use integer scale factors.
00067  * The 2/3/1 scale factors used here correspond loosely to the relative
00068  * weights of the colors in the NTSC grayscale equation.
00069  * If you want to use this code to quantize a non-RGB color space, you'll
00070  * probably need to change these scale factors.
00071  */
00072 
00073 #define R_SCALE 2               /* scale R distances by this much */
00074 #define G_SCALE 3               /* scale G distances by this much */
00075 #define B_SCALE 1               /* and B by this much */
00076 
00077 /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
00078  * in jmorecfg.h.  As the code stands, it will do the right thing for R,G,B
00079  * and B,G,R orders.  If you define some other weird order in jmorecfg.h,
00080  * you'll get compile errors until you extend this logic.  In that case
00081  * you'll probably want to tweak the histogram sizes too.
00082  */
00083 
00084 #if RGB_RED == 0
00085 #define C0_SCALE R_SCALE
00086 #endif
00087 #if RGB_BLUE == 0
00088 #define C0_SCALE B_SCALE
00089 #endif
00090 #if RGB_GREEN == 1
00091 #define C1_SCALE G_SCALE
00092 #endif
00093 #if RGB_RED == 2
00094 #define C2_SCALE R_SCALE
00095 #endif
00096 #if RGB_BLUE == 2
00097 #define C2_SCALE B_SCALE
00098 #endif
00099 
00100 
00101 /*
00102  * First we have the histogram data structure and routines for creating it.
00103  *
00104  * The number of bits of precision can be adjusted by changing these symbols.
00105  * We recommend keeping 6 bits for G and 5 each for R and B.
00106  * If you have plenty of memory and cycles, 6 bits all around gives marginally
00107  * better results; if you are short of memory, 5 bits all around will save
00108  * some space but degrade the results.
00109  * To maintain a fully accurate histogram, we'd need to allocate a "long"
00110  * (preferably unsigned long) for each cell.  In practice this is overkill;
00111  * we can get by with 16 bits per cell.  Few of the cell counts will overflow,
00112  * and clamping those that do overflow to the maximum value will give close-
00113  * enough results.  This reduces the recommended histogram size from 256Kb
00114  * to 128Kb, which is a useful savings on PC-class machines.
00115  * (In the second pass the histogram space is re-used for pixel mapping data;
00116  * in that capacity, each cell must be able to store zero to the number of
00117  * desired colors.  16 bits/cell is plenty for that too.)
00118  * Since the JPEG code is intended to run in small memory model on 80x86
00119  * machines, we can't just allocate the histogram in one chunk.  Instead
00120  * of a true 3-D array, we use a row of pointers to 2-D arrays.  Each
00121  * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
00122  * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries.  Note that
00123  * on 80x86 machines, the pointer row is in near memory but the actual
00124  * arrays are in far memory (same arrangement as we use for image arrays).
00125  */
00126 
00127 #define MAXNUMCOLORS  (MAXJSAMPLE+1) /* maximum size of colormap */
00128 
00129 /* These will do the right thing for either R,G,B or B,G,R color order,
00130  * but you may not like the results for other color orders.
00131  */
00132 #define HIST_C0_BITS  5         /* bits of precision in R/B histogram */
00133 #define HIST_C1_BITS  6         /* bits of precision in G histogram */
00134 #define HIST_C2_BITS  5         /* bits of precision in B/R histogram */
00135 
00136 /* Number of elements along histogram axes. */
00137 #define HIST_C0_ELEMS  (1<<HIST_C0_BITS)
00138 #define HIST_C1_ELEMS  (1<<HIST_C1_BITS)
00139 #define HIST_C2_ELEMS  (1<<HIST_C2_BITS)
00140 
00141 /* These are the amounts to shift an input value to get a histogram index. */
00142 #define C0_SHIFT  (BITS_IN_JSAMPLE-HIST_C0_BITS)
00143 #define C1_SHIFT  (BITS_IN_JSAMPLE-HIST_C1_BITS)
00144 #define C2_SHIFT  (BITS_IN_JSAMPLE-HIST_C2_BITS)
00145 
00146 
00147 typedef UINT16 histcell;        /* histogram cell; prefer an unsigned type */
00148 
00149 typedef histcell FAR * histptr; /* for pointers to histogram cells */
00150 
00151 typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
00152 typedef hist1d FAR * hist2d;    /* type for the 2nd-level pointers */
00153 typedef hist2d * hist3d;        /* type for top-level pointer */
00154 
00155 
00156 /* Declarations for Floyd-Steinberg dithering.
00157  *
00158  * Errors are accumulated into the array fserrors[], at a resolution of
00159  * 1/16th of a pixel count.  The error at a given pixel is propagated
00160  * to its not-yet-processed neighbors using the standard F-S fractions,
00161  *              ...     (here)  7/16
00162  *              3/16    5/16    1/16
00163  * We work left-to-right on even rows, right-to-left on odd rows.
00164  *
00165  * We can get away with a single array (holding one row's worth of errors)
00166  * by using it to store the current row's errors at pixel columns not yet
00167  * processed, but the next row's errors at columns already processed.  We
00168  * need only a few extra variables to hold the errors immediately around the
00169  * current column.  (If we are lucky, those variables are in registers, but
00170  * even if not, they're probably cheaper to access than array elements are.)
00171  *
00172  * The fserrors[] array has (#columns + 2) entries; the extra entry at
00173  * each end saves us from special-casing the first and last pixels.
00174  * Each entry is three values long, one value for each color component.
00175  *
00176  * Note: on a wide image, we might not have enough room in a PC's near data
00177  * segment to hold the error array; so it is allocated with alloc_large.
00178  */
00179 
00180 #if BITS_IN_JSAMPLE == 8
00181 typedef INT16 FSERROR;          /* 16 bits should be enough */
00182 typedef int LOCFSERROR;         /* use 'int' for calculation temps */
00183 #else
00184 typedef INT32 FSERROR;          /* may need more than 16 bits */
00185 typedef INT32 LOCFSERROR;       /* be sure calculation temps are big enough */
00186 #endif
00187 
00188 typedef FSERROR FAR *FSERRPTR;  /* pointer to error array (in FAR storage!) */
00189 
00190 
00191 /* Private subobject */
00192 
00193 typedef struct {
00194   struct jpeg_color_quantizer pub; /* public fields */
00195 
00196   /* Space for the eventually created colormap is stashed here */
00197   JSAMPARRAY sv_colormap;       /* colormap allocated at init time */
00198   int desired;                  /* desired # of colors = size of colormap */
00199 
00200   /* Variables for accumulating image statistics */
00201   hist3d histogram;             /* pointer to the histogram */
00202 
00203   boolean needs_zeroed;         /* TRUE if next pass must zero histogram */
00204 
00205   /* Variables for Floyd-Steinberg dithering */
00206   FSERRPTR fserrors;            /* accumulated errors */
00207   boolean on_odd_row;           /* flag to remember which row we are on */
00208   int * error_limiter;          /* table for clamping the applied error */
00209 } my_cquantizer;
00210 
00211 typedef my_cquantizer * my_cquantize_ptr;
00212 
00213 
00214 /*
00215  * Prescan some rows of pixels.
00216  * In this module the prescan simply updates the histogram, which has been
00217  * initialized to zeroes by start_pass.
00218  * An output_buf parameter is required by the method signature, but no data
00219  * is actually output (in fact the buffer controller is probably passing a
00220  * NULL pointer).
00221  */
00222 
00223 METHODDEF(void)
00224 prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
00225                   JSAMPARRAY output_buf, int num_rows)
00226 {
00227   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
00228   register JSAMPROW ptr;
00229   register histptr histp;
00230   register hist3d histogram = cquantize->histogram;
00231   int row;
00232   JDIMENSION col;
00233   JDIMENSION width = cinfo->output_width;
00234 
00235   for (row = 0; row < num_rows; row++) {
00236     ptr = input_buf[row];
00237     for (col = width; col > 0; col--) {
00238       /* get pixel value and index into the histogram */
00239       histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
00240                          [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
00241                          [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
00242       /* increment, check for overflow and undo increment if so. */
00243       if (++(*histp) <= 0)
00244         (*histp)--;
00245       ptr += 3;
00246     }
00247   }
00248 }
00249 
00250 
00251 /*
00252  * Next we have the really interesting routines: selection of a colormap
00253  * given the completed histogram.
00254  * These routines work with a list of "boxes", each representing a rectangular
00255  * subset of the input color space (to histogram precision).
00256  */
00257 
00258 typedef struct {
00259   /* The bounds of the box (inclusive); expressed as histogram indexes */
00260   int c0min, c0max;
00261   int c1min, c1max;
00262   int c2min, c2max;
00263   /* The volume (actually 2-norm) of the box */
00264   INT32 volume;
00265   /* The number of nonzero histogram cells within this box */
00266   long colorcount;
00267 } box;
00268 
00269 typedef box * boxptr;
00270 
00271 
00272 LOCAL(boxptr)
00273 find_biggest_color_pop (boxptr boxlist, int numboxes)
00274 /* Find the splittable box with the largest color population */
00275 /* Returns NULL if no splittable boxes remain */
00276 {
00277   register boxptr boxp;
00278   register int i;
00279   register long maxc = 0;
00280   boxptr which = NULL;
00281   
00282   for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
00283     if (boxp->colorcount > maxc && boxp->volume > 0) {
00284       which = boxp;
00285       maxc = boxp->colorcount;
00286     }
00287   }
00288   return which;
00289 }
00290 
00291 
00292 LOCAL(boxptr)
00293 find_biggest_volume (boxptr boxlist, int numboxes)
00294 /* Find the splittable box with the largest (scaled) volume */
00295 /* Returns NULL if no splittable boxes remain */
00296 {
00297   register boxptr boxp;
00298   register int i;
00299   register INT32 maxv = 0;
00300   boxptr which = NULL;
00301   
00302   for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
00303     if (boxp->volume > maxv) {
00304       which = boxp;
00305       maxv = boxp->volume;
00306     }
00307   }
00308   return which;
00309 }
00310 
00311 
00312 LOCAL(void)
00313 update_box (j_decompress_ptr cinfo, boxptr boxp)
00314 /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
00315 /* and recompute its volume and population */
00316 {
00317   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
00318   hist3d histogram = cquantize->histogram;
00319   histptr histp;
00320   int c0,c1,c2;
00321   int c0min,c0max,c1min,c1max,c2min,c2max;
00322   INT32 dist0,dist1,dist2;
00323   long ccount;
00324   
00325   c0min = boxp->c0min;  c0max = boxp->c0max;
00326   c1min = boxp->c1min;  c1max = boxp->c1max;
00327   c2min = boxp->c2min;  c2max = boxp->c2max;
00328   
00329   if (c0max > c0min)
00330     for (c0 = c0min; c0 <= c0max; c0++)
00331       for (c1 = c1min; c1 <= c1max; c1++) {
00332         histp = & histogram[c0][c1][c2min];
00333         for (c2 = c2min; c2 <= c2max; c2++)
00334           if (*histp++ != 0) {
00335             boxp->c0min = c0min = c0;
00336             goto have_c0min;
00337           }
00338       }
00339  have_c0min:
00340   if (c0max > c0min)
00341     for (c0 = c0max; c0 >= c0min; c0--)
00342       for (c1 = c1min; c1 <= c1max; c1++) {
00343         histp = & histogram[c0][c1][c2min];
00344         for (c2 = c2min; c2 <= c2max; c2++)
00345           if (*histp++ != 0) {
00346             boxp->c0max = c0max = c0;
00347             goto have_c0max;
00348           }
00349       }
00350  have_c0max:
00351   if (c1max > c1min)
00352     for (c1 = c1min; c1 <= c1max; c1++)
00353       for (c0 = c0min; c0 <= c0max; c0++) {
00354         histp = & histogram[c0][c1][c2min];
00355         for (c2 = c2min; c2 <= c2max; c2++)
00356           if (*histp++ != 0) {
00357             boxp->c1min = c1min = c1;
00358             goto have_c1min;
00359           }
00360       }
00361  have_c1min:
00362   if (c1max > c1min)
00363     for (c1 = c1max; c1 >= c1min; c1--)
00364       for (c0 = c0min; c0 <= c0max; c0++) {
00365         histp = & histogram[c0][c1][c2min];
00366         for (c2 = c2min; c2 <= c2max; c2++)
00367           if (*histp++ != 0) {
00368             boxp->c1max = c1max = c1;
00369             goto have_c1max;
00370           }
00371       }
00372  have_c1max:
00373   if (c2max > c2min)
00374     for (c2 = c2min; c2 <= c2max; c2++)
00375       for (c0 = c0min; c0 <= c0max; c0++) {
00376         histp = & histogram[c0][c1min][c2];
00377         for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
00378           if (*histp != 0) {
00379             boxp->c2min = c2min = c2;
00380             goto have_c2min;
00381           }
00382       }
00383  have_c2min:
00384   if (c2max > c2min)
00385     for (c2 = c2max; c2 >= c2min; c2--)
00386       for (c0 = c0min; c0 <= c0max; c0++) {
00387         histp = & histogram[c0][c1min][c2];
00388         for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
00389           if (*histp != 0) {
00390             boxp->c2max = c2max = c2;
00391             goto have_c2max;
00392           }
00393       }
00394  have_c2max:
00395 
00396   /* Update box volume.
00397    * We use 2-norm rather than real volume here; this biases the method
00398    * against making long narrow boxes, and it has the side benefit that
00399    * a box is splittable iff norm > 0.
00400    * Since the differences are expressed in histogram-cell units,
00401    * we have to shift back to JSAMPLE units to get consistent distances;
00402    * after which, we scale according to the selected distance scale factors.
00403    */
00404   dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
00405   dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
00406   dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
00407   boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
00408   
00409   /* Now scan remaining volume of box and compute population */
00410   ccount = 0;
00411   for (c0 = c0min; c0 <= c0max; c0++)
00412     for (c1 = c1min; c1 <= c1max; c1++) {
00413       histp = & histogram[c0][c1][c2min];
00414       for (c2 = c2min; c2 <= c2max; c2++, histp++)
00415         if (*histp != 0) {
00416           ccount++;
00417         }
00418     }
00419   boxp->colorcount = ccount;
00420 }
00421 
00422 
00423 LOCAL(int)
00424 median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
00425             int desired_colors)
00426 /* Repeatedly select and split the largest box until we have enough boxes */
00427 {
00428   int n,lb;
00429   int c0,c1,c2,cmax;
00430   register boxptr b1,b2;
00431 
00432   while (numboxes < desired_colors) {
00433     /* Select box to split.
00434      * Current algorithm: by population for first half, then by volume.
00435      */
00436     if (numboxes*2 <= desired_colors) {
00437       b1 = find_biggest_color_pop(boxlist, numboxes);
00438     } else {
00439       b1 = find_biggest_volume(boxlist, numboxes);
00440     }
00441     if (b1 == NULL)             /* no splittable boxes left! */
00442       break;
00443     b2 = &boxlist[numboxes];    /* where new box will go */
00444     /* Copy the color bounds to the new box. */
00445     b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
00446     b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
00447     /* Choose which axis to split the box on.
00448      * Current algorithm: longest scaled axis.
00449      * See notes in update_box about scaling distances.
00450      */
00451     c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
00452     c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
00453     c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
00454     /* We want to break any ties in favor of green, then red, blue last.
00455      * This code does the right thing for R,G,B or B,G,R color orders only.
00456      */
00457 #if RGB_RED == 0
00458     cmax = c1; n = 1;
00459     if (c0 > cmax) { cmax = c0; n = 0; }
00460     if (c2 > cmax) { n = 2; }
00461 #else
00462     cmax = c1; n = 1;
00463     if (c2 > cmax) { cmax = c2; n = 2; }
00464     if (c0 > cmax) { n = 0; }
00465 #endif
00466     /* Choose split point along selected axis, and update box bounds.
00467      * Current algorithm: split at halfway point.
00468      * (Since the box has been shrunk to minimum volume,
00469      * any split will produce two nonempty subboxes.)
00470      * Note that lb value is max for lower box, so must be < old max.
00471      */
00472     switch (n) {
00473     case 0:
00474       lb = (b1->c0max + b1->c0min) / 2;
00475       b1->c0max = lb;
00476       b2->c0min = lb+1;
00477       break;
00478     case 1:
00479       lb = (b1->c1max + b1->c1min) / 2;
00480       b1->c1max = lb;
00481       b2->c1min = lb+1;
00482       break;
00483     case 2:
00484       lb = (b1->c2max + b1->c2min) / 2;
00485       b1->c2max = lb;
00486       b2->c2min = lb+1;
00487       break;
00488     }
00489     /* Update stats for boxes */
00490     update_box(cinfo, b1);
00491     update_box(cinfo, b2);
00492     numboxes++;
00493   }
00494   return numboxes;
00495 }
00496 
00497 
00498 LOCAL(void)
00499 compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
00500 /* Compute representative color for a box, put it in colormap[icolor] */
00501 {
00502   /* Current algorithm: mean weighted by pixels (not colors) */
00503   /* Note it is important to get the rounding correct! */
00504   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
00505   hist3d histogram = cquantize->histogram;
00506   histptr histp;
00507   int c0,c1,c2;
00508   int c0min,c0max,c1min,c1max,c2min,c2max;
00509   long count;
00510   long total = 0;
00511   long c0total = 0;
00512   long c1total = 0;
00513   long c2total = 0;
00514   
00515   c0min = boxp->c0min;  c0max = boxp->c0max;
00516   c1min = boxp->c1min;  c1max = boxp->c1max;
00517   c2min = boxp->c2min;  c2max = boxp->c2max;
00518   
00519   for (c0 = c0min; c0 <= c0max; c0++)
00520     for (c1 = c1min; c1 <= c1max; c1++) {
00521       histp = & histogram[c0][c1][c2min];
00522       for (c2 = c2min; c2 <= c2max; c2++) {
00523         if ((count = *histp++) != 0) {
00524           total += count;
00525           c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
00526           c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
00527           c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
00528         }
00529       }
00530     }
00531   
00532   cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
00533   cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
00534   cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
00535 }
00536 
00537 
00538 LOCAL(void)
00539 select_colors (j_decompress_ptr cinfo, int desired_colors)
00540 /* Master routine for color selection */
00541 {
00542   boxptr boxlist;
00543   int numboxes;
00544   int i;
00545 
00546   /* Allocate workspace for box list */
00547   boxlist = (boxptr) (*cinfo->mem->alloc_small)
00548     ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
00549   /* Initialize one box containing whole space */
00550   numboxes = 1;
00551   boxlist[0].c0min = 0;
00552   boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
00553   boxlist[0].c1min = 0;
00554   boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
00555   boxlist[0].c2min = 0;
00556   boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
00557   /* Shrink it to actually-used volume and set its statistics */
00558   update_box(cinfo, & boxlist[0]);
00559   /* Perform median-cut to produce final box list */
00560   numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
00561   /* Compute the representative color for each box, fill colormap */
00562   for (i = 0; i < numboxes; i++)
00563     compute_color(cinfo, & boxlist[i], i);
00564   cinfo->actual_number_of_colors = numboxes;
00565   TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
00566 }
00567 
00568 
00569 /*
00570  * These routines are concerned with the time-critical task of mapping input
00571  * colors to the nearest color in the selected colormap.
00572  *
00573  * We re-use the histogram space as an "inverse color map", essentially a
00574  * cache for the results of nearest-color searches.  All colors within a
00575  * histogram cell will be mapped to the same colormap entry, namely the one
00576  * closest to the cell's center.  This may not be quite the closest entry to
00577  * the actual input color, but it's almost as good.  A zero in the cache
00578  * indicates we haven't found the nearest color for that cell yet; the array
00579  * is cleared to zeroes before starting the mapping pass.  When we find the
00580  * nearest color for a cell, its colormap index plus one is recorded in the
00581  * cache for future use.  The pass2 scanning routines call fill_inverse_cmap
00582  * when they need to use an unfilled entry in the cache.
00583  *
00584  * Our method of efficiently finding nearest colors is based on the "locally
00585  * sorted search" idea described by Heckbert and on the incremental distance
00586  * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
00587  * Gems II (James Arvo, ed.  Academic Press, 1991).  Thomas points out that
00588  * the distances from a given colormap entry to each cell of the histogram can
00589  * be computed quickly using an incremental method: the differences between
00590  * distances to adjacent cells themselves differ by a constant.  This allows a
00591  * fairly fast implementation of the "brute force" approach of computing the
00592  * distance from every colormap entry to every histogram cell.  Unfortunately,
00593  * it needs a work array to hold the best-distance-so-far for each histogram
00594  * cell (because the inner loop has to be over cells, not colormap entries).
00595  * The work array elements have to be INT32s, so the work array would need
00596  * 256Kb at our recommended precision.  This is not feasible in DOS machines.
00597  *
00598  * To get around these problems, we apply Thomas' method to compute the
00599  * nearest colors for only the cells within a small subbox of the histogram.
00600  * The work array need be only as big as the subbox, so the memory usage
00601  * problem is solved.  Furthermore, we need not fill subboxes that are never
00602  * referenced in pass2; many images use only part of the color gamut, so a
00603  * fair amount of work is saved.  An additional advantage of this
00604  * approach is that we can apply Heckbert's locality criterion to quickly
00605  * eliminate colormap entries that are far away from the subbox; typically
00606  * three-fourths of the colormap entries are rejected by Heckbert's criterion,
00607  * and we need not compute their distances to individual cells in the subbox.
00608  * The speed of this approach is heavily influenced by the subbox size: too
00609  * small means too much overhead, too big loses because Heckbert's criterion
00610  * can't eliminate as many colormap entries.  Empirically the best subbox
00611  * size seems to be about 1/512th of the histogram (1/8th in each direction).
00612  *
00613  * Thomas' article also describes a refined method which is asymptotically
00614  * faster than the brute-force method, but it is also far more complex and
00615  * cannot efficiently be applied to small subboxes.  It is therefore not
00616  * useful for programs intended to be portable to DOS machines.  On machines
00617  * with plenty of memory, filling the whole histogram in one shot with Thomas'
00618  * refined method might be faster than the present code --- but then again,
00619  * it might not be any faster, and it's certainly more complicated.
00620  */
00621 
00622 
00623 /* log2(histogram cells in update box) for each axis; this can be adjusted */
00624 #define BOX_C0_LOG  (HIST_C0_BITS-3)
00625 #define BOX_C1_LOG  (HIST_C1_BITS-3)
00626 #define BOX_C2_LOG  (HIST_C2_BITS-3)
00627 
00628 #define BOX_C0_ELEMS  (1<<BOX_C0_LOG) /* # of hist cells in update box */
00629 #define BOX_C1_ELEMS  (1<<BOX_C1_LOG)
00630 #define BOX_C2_ELEMS  (1<<BOX_C2_LOG)
00631 
00632 #define BOX_C0_SHIFT  (C0_SHIFT + BOX_C0_LOG)
00633 #define BOX_C1_SHIFT  (C1_SHIFT + BOX_C1_LOG)
00634 #define BOX_C2_SHIFT  (C2_SHIFT + BOX_C2_LOG)
00635 
00636 
00637 /*
00638  * The next three routines implement inverse colormap filling.  They could
00639  * all be folded into one big routine, but splitting them up this way saves
00640  * some stack space (the mindist[] and bestdist[] arrays need not coexist)
00641  * and may allow some compilers to produce better code by registerizing more
00642  * inner-loop variables.
00643  */
00644 
00645 LOCAL(int)
00646 find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
00647                     JSAMPLE colorlist[])
00648 /* Locate the colormap entries close enough to an update box to be candidates
00649  * for the nearest entry to some cell(s) in the update box.  The update box
00650  * is specified by the center coordinates of its first cell.  The number of
00651  * candidate colormap entries is returned, and their colormap indexes are
00652  * placed in colorlist[].
00653  * This routine uses Heckbert's "locally sorted search" criterion to select
00654  * the colors that need further consideration.
00655  */
00656 {
00657   int numcolors = cinfo->actual_number_of_colors;
00658   int maxc0, maxc1, maxc2;
00659   int centerc0, centerc1, centerc2;
00660   int i, x, ncolors;
00661   INT32 minmaxdist, min_dist, max_dist, tdist;
00662   INT32 mindist[MAXNUMCOLORS];  /* min distance to colormap entry i */
00663 
00664   /* Compute true coordinates of update box's upper corner and center.
00665    * Actually we compute the coordinates of the center of the upper-corner
00666    * histogram cell, which are the upper bounds of the volume we care about.
00667    * Note that since ">>" rounds down, the "center" values may be closer to
00668    * min than to max; hence comparisons to them must be "<=", not "<".
00669    */
00670   maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
00671   centerc0 = (minc0 + maxc0) >> 1;
00672   maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
00673   centerc1 = (minc1 + maxc1) >> 1;
00674   maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
00675   centerc2 = (minc2 + maxc2) >> 1;
00676 
00677   /* For each color in colormap, find:
00678    *  1. its minimum squared-distance to any point in the update box
00679    *     (zero if color is within update box);
00680    *  2. its maximum squared-distance to any point in the update box.
00681    * Both of these can be found by considering only the corners of the box.
00682    * We save the minimum distance for each color in mindist[];
00683    * only the smallest maximum distance is of interest.
00684    */
00685   minmaxdist = 0x7FFFFFFFL;
00686 
00687   for (i = 0; i < numcolors; i++) {
00688     /* We compute the squared-c0-distance term, then add in the other two. */
00689     x = GETJSAMPLE(cinfo->colormap[0][i]);
00690     if (x < minc0) {
00691       tdist = (x - minc0) * C0_SCALE;
00692       min_dist = tdist*tdist;
00693       tdist = (x - maxc0) * C0_SCALE;
00694       max_dist = tdist*tdist;
00695     } else if (x > maxc0) {
00696       tdist = (x - maxc0) * C0_SCALE;
00697       min_dist = tdist*tdist;
00698       tdist = (x - minc0) * C0_SCALE;
00699       max_dist = tdist*tdist;
00700     } else {
00701       /* within cell range so no contribution to min_dist */
00702       min_dist = 0;
00703       if (x <= centerc0) {
00704         tdist = (x - maxc0) * C0_SCALE;
00705         max_dist = tdist*tdist;
00706       } else {
00707         tdist = (x - minc0) * C0_SCALE;
00708         max_dist = tdist*tdist;
00709       }
00710     }
00711 
00712     x = GETJSAMPLE(cinfo->colormap[1][i]);
00713     if (x < minc1) {
00714       tdist = (x - minc1) * C1_SCALE;
00715       min_dist += tdist*tdist;
00716       tdist = (x - maxc1) * C1_SCALE;
00717       max_dist += tdist*tdist;
00718     } else if (x > maxc1) {
00719       tdist = (x - maxc1) * C1_SCALE;
00720       min_dist += tdist*tdist;
00721       tdist = (x - minc1) * C1_SCALE;
00722       max_dist += tdist*tdist;
00723     } else {
00724       /* within cell range so no contribution to min_dist */
00725       if (x <= centerc1) {
00726         tdist = (x - maxc1) * C1_SCALE;
00727         max_dist += tdist*tdist;
00728       } else {
00729         tdist = (x - minc1) * C1_SCALE;
00730         max_dist += tdist*tdist;
00731       }
00732     }
00733 
00734     x = GETJSAMPLE(cinfo->colormap[2][i]);
00735     if (x < minc2) {
00736       tdist = (x - minc2) * C2_SCALE;
00737       min_dist += tdist*tdist;
00738       tdist = (x - maxc2) * C2_SCALE;
00739       max_dist += tdist*tdist;
00740     } else if (x > maxc2) {
00741       tdist = (x - maxc2) * C2_SCALE;
00742       min_dist += tdist*tdist;
00743       tdist = (x - minc2) * C2_SCALE;
00744       max_dist += tdist*tdist;
00745     } else {
00746       /* within cell range so no contribution to min_dist */
00747       if (x <= centerc2) {
00748         tdist = (x - maxc2) * C2_SCALE;
00749         max_dist += tdist*tdist;
00750       } else {
00751         tdist = (x - minc2) * C2_SCALE;
00752         max_dist += tdist*tdist;
00753       }
00754     }
00755 
00756     mindist[i] = min_dist;      /* save away the results */
00757     if (max_dist < minmaxdist)
00758       minmaxdist = max_dist;
00759   }
00760 
00761   /* Now we know that no cell in the update box is more than minmaxdist
00762    * away from some colormap entry.  Therefore, only colors that are
00763    * within minmaxdist of some part of the box need be considered.
00764    */
00765   ncolors = 0;
00766   for (i = 0; i < numcolors; i++) {
00767     if (mindist[i] <= minmaxdist)
00768       colorlist[ncolors++] = (JSAMPLE) i;
00769   }
00770   return ncolors;
00771 }
00772 
00773 
00774 LOCAL(void)
00775 find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
00776                   int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
00777 /* Find the closest colormap entry for each cell in the update box,
00778  * given the list of candidate colors prepared by find_nearby_colors.
00779  * Return the indexes of the closest entries in the bestcolor[] array.
00780  * This routine uses Thomas' incremental distance calculation method to
00781  * find the distance from a colormap entry to successive cells in the box.
00782  */
00783 {
00784   int ic0, ic1, ic2;
00785   int i, icolor;
00786   register INT32 * bptr;        /* pointer into bestdist[] array */
00787   JSAMPLE * cptr;               /* pointer into bestcolor[] array */
00788   INT32 dist0, dist1;           /* initial distance values */
00789   register INT32 dist2;         /* current distance in inner loop */
00790   INT32 xx0, xx1;               /* distance increments */
00791   register INT32 xx2;
00792   INT32 inc0, inc1, inc2;       /* initial values for increments */
00793   /* This array holds the distance to the nearest-so-far color for each cell */
00794   INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
00795 
00796   /* Initialize best-distance for each cell of the update box */
00797   bptr = bestdist;
00798   for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
00799     *bptr++ = 0x7FFFFFFFL;
00800   
00801   /* For each color selected by find_nearby_colors,
00802    * compute its distance to the center of each cell in the box.
00803    * If that's less than best-so-far, update best distance and color number.
00804    */
00805   
00806   /* Nominal steps between cell centers ("x" in Thomas article) */
00807 #define STEP_C0  ((1 << C0_SHIFT) * C0_SCALE)
00808 #define STEP_C1  ((1 << C1_SHIFT) * C1_SCALE)
00809 #define STEP_C2  ((1 << C2_SHIFT) * C2_SCALE)
00810   
00811   for (i = 0; i < numcolors; i++) {
00812     icolor = GETJSAMPLE(colorlist[i]);
00813     /* Compute (square of) distance from minc0/c1/c2 to this color */
00814     inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
00815     dist0 = inc0*inc0;
00816     inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
00817     dist0 += inc1*inc1;
00818     inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
00819     dist0 += inc2*inc2;
00820     /* Form the initial difference increments */
00821     inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
00822     inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
00823     inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
00824     /* Now loop over all cells in box, updating distance per Thomas method */
00825     bptr = bestdist;
00826     cptr = bestcolor;
00827     xx0 = inc0;
00828     for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
00829       dist1 = dist0;
00830       xx1 = inc1;
00831       for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
00832         dist2 = dist1;
00833         xx2 = inc2;
00834         for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
00835           if (dist2 < *bptr) {
00836             *bptr = dist2;
00837             *cptr = (JSAMPLE) icolor;
00838           }
00839           dist2 += xx2;
00840           xx2 += 2 * STEP_C2 * STEP_C2;
00841           bptr++;
00842           cptr++;
00843         }
00844         dist1 += xx1;
00845         xx1 += 2 * STEP_C1 * STEP_C1;
00846       }
00847       dist0 += xx0;
00848       xx0 += 2 * STEP_C0 * STEP_C0;
00849     }
00850   }
00851 }
00852 
00853 
00854 LOCAL(void)
00855 fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
00856 /* Fill the inverse-colormap entries in the update box that contains */
00857 /* histogram cell c0/c1/c2.  (Only that one cell MUST be filled, but */
00858 /* we can fill as many others as we wish.) */
00859 {
00860   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
00861   hist3d histogram = cquantize->histogram;
00862   int minc0, minc1, minc2;      /* lower left corner of update box */
00863   int ic0, ic1, ic2;
00864   register JSAMPLE * cptr;      /* pointer into bestcolor[] array */
00865   register histptr cachep;      /* pointer into main cache array */
00866   /* This array lists the candidate colormap indexes. */
00867   JSAMPLE colorlist[MAXNUMCOLORS];
00868   int numcolors;                /* number of candidate colors */
00869   /* This array holds the actually closest colormap index for each cell. */
00870   JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
00871 
00872   /* Convert cell coordinates to update box ID */
00873   c0 >>= BOX_C0_LOG;
00874   c1 >>= BOX_C1_LOG;
00875   c2 >>= BOX_C2_LOG;
00876 
00877   /* Compute true coordinates of update box's origin corner.
00878    * Actually we compute the coordinates of the center of the corner
00879    * histogram cell, which are the lower bounds of the volume we care about.
00880    */
00881   minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
00882   minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
00883   minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
00884   
00885   /* Determine which colormap entries are close enough to be candidates
00886    * for the nearest entry to some cell in the update box.
00887    */
00888   numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
00889 
00890   /* Determine the actually nearest colors. */
00891   find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
00892                    bestcolor);
00893 
00894   /* Save the best color numbers (plus 1) in the main cache array */
00895   c0 <<= BOX_C0_LOG;            /* convert ID back to base cell indexes */
00896   c1 <<= BOX_C1_LOG;
00897   c2 <<= BOX_C2_LOG;
00898   cptr = bestcolor;
00899   for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
00900     for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
00901       cachep = & histogram[c0+ic0][c1+ic1][c2];
00902       for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
00903         *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
00904       }
00905     }
00906   }
00907 }
00908 
00909 
00910 /*
00911  * Map some rows of pixels to the output colormapped representation.
00912  */
00913 
00914 METHODDEF(void)
00915 pass2_no_dither (j_decompress_ptr cinfo,
00916                  JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
00917 /* This version performs no dithering */
00918 {
00919   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
00920   hist3d histogram = cquantize->histogram;
00921   register JSAMPROW inptr, outptr;
00922   register histptr cachep;
00923   register int c0, c1, c2;
00924   int row;
00925   JDIMENSION col;
00926   JDIMENSION width = cinfo->output_width;
00927 
00928   for (row = 0; row < num_rows; row++) {
00929     inptr = input_buf[row];
00930     outptr = output_buf[row];
00931     for (col = width; col > 0; col--) {
00932       /* get pixel value and index into the cache */
00933       c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
00934       c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
00935       c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
00936       cachep = & histogram[c0][c1][c2];
00937       /* If we have not seen this color before, find nearest colormap entry */
00938       /* and update the cache */
00939       if (*cachep == 0)
00940         fill_inverse_cmap(cinfo, c0,c1,c2);
00941       /* Now emit the colormap index for this cell */
00942       *outptr++ = (JSAMPLE) (*cachep - 1);
00943     }
00944   }
00945 }
00946 
00947 
00948 METHODDEF(void)
00949 pass2_fs_dither (j_decompress_ptr cinfo,
00950                  JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
00951 /* This version performs Floyd-Steinberg dithering */
00952 {
00953   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
00954   hist3d histogram = cquantize->histogram;
00955   register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
00956   LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
00957   LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
00958   register FSERRPTR errorptr;   /* => fserrors[] at column before current */
00959   JSAMPROW inptr;               /* => current input pixel */
00960   JSAMPROW outptr;              /* => current output pixel */
00961   histptr cachep;
00962   int dir;                      /* +1 or -1 depending on direction */
00963   int dir3;                     /* 3*dir, for advancing inptr & errorptr */
00964   int row;
00965   JDIMENSION col;
00966   JDIMENSION width = cinfo->output_width;
00967   JSAMPLE *range_limit = cinfo->sample_range_limit;
00968   int *error_limit = cquantize->error_limiter;
00969   JSAMPROW colormap0 = cinfo->colormap[0];
00970   JSAMPROW colormap1 = cinfo->colormap[1];
00971   JSAMPROW colormap2 = cinfo->colormap[2];
00972   SHIFT_TEMPS
00973 
00974   for (row = 0; row < num_rows; row++) {
00975     inptr = input_buf[row];
00976     outptr = output_buf[row];
00977     if (cquantize->on_odd_row) {
00978       /* work right to left in this row */
00979       inptr += (width-1) * 3;   /* so point to rightmost pixel */
00980       outptr += width-1;
00981       dir = -1;
00982       dir3 = -3;
00983       errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
00984       cquantize->on_odd_row = FALSE; /* flip for next time */
00985     } else {
00986       /* work left to right in this row */
00987       dir = 1;
00988       dir3 = 3;
00989       errorptr = cquantize->fserrors; /* => entry before first real column */
00990       cquantize->on_odd_row = TRUE; /* flip for next time */
00991     }
00992     /* Preset error values: no error propagated to first pixel from left */
00993     cur0 = cur1 = cur2 = 0;
00994     /* and no error propagated to row below yet */
00995     belowerr0 = belowerr1 = belowerr2 = 0;
00996     bpreverr0 = bpreverr1 = bpreverr2 = 0;
00997 
00998     for (col = width; col > 0; col--) {
00999       /* curN holds the error propagated from the previous pixel on the
01000        * current line.  Add the error propagated from the previous line
01001        * to form the complete error correction term for this pixel, and
01002        * round the error term (which is expressed * 16) to an integer.
01003        * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
01004        * for either sign of the error value.
01005        * Note: errorptr points to *previous* column's array entry.
01006        */
01007       cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
01008       cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
01009       cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
01010       /* Limit the error using transfer function set by init_error_limit.
01011        * See comments with init_error_limit for rationale.
01012        */
01013       cur0 = error_limit[cur0];
01014       cur1 = error_limit[cur1];
01015       cur2 = error_limit[cur2];
01016       /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
01017        * The maximum error is +- MAXJSAMPLE (or less with error limiting);
01018        * this sets the required size of the range_limit array.
01019        */
01020       cur0 += GETJSAMPLE(inptr[0]);
01021       cur1 += GETJSAMPLE(inptr[1]);
01022       cur2 += GETJSAMPLE(inptr[2]);
01023       cur0 = GETJSAMPLE(range_limit[cur0]);
01024       cur1 = GETJSAMPLE(range_limit[cur1]);
01025       cur2 = GETJSAMPLE(range_limit[cur2]);
01026       /* Index into the cache with adjusted pixel value */
01027       cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
01028       /* If we have not seen this color before, find nearest colormap */
01029       /* entry and update the cache */
01030       if (*cachep == 0)
01031         fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
01032       /* Now emit the colormap index for this cell */
01033       { register int pixcode = *cachep - 1;
01034         *outptr = (JSAMPLE) pixcode;
01035         /* Compute representation error for this pixel */
01036         cur0 -= GETJSAMPLE(colormap0[pixcode]);
01037         cur1 -= GETJSAMPLE(colormap1[pixcode]);
01038         cur2 -= GETJSAMPLE(colormap2[pixcode]);
01039       }
01040       /* Compute error fractions to be propagated to adjacent pixels.
01041        * Add these into the running sums, and simultaneously shift the
01042        * next-line error sums left by 1 column.
01043        */
01044       { register LOCFSERROR bnexterr, delta;
01045 
01046         bnexterr = cur0;        /* Process component 0 */
01047         delta = cur0 * 2;
01048         cur0 += delta;          /* form error * 3 */
01049         errorptr[0] = (FSERROR) (bpreverr0 + cur0);
01050         cur0 += delta;          /* form error * 5 */
01051         bpreverr0 = belowerr0 + cur0;
01052         belowerr0 = bnexterr;
01053         cur0 += delta;          /* form error * 7 */
01054         bnexterr = cur1;        /* Process component 1 */
01055         delta = cur1 * 2;
01056         cur1 += delta;          /* form error * 3 */
01057         errorptr[1] = (FSERROR) (bpreverr1 + cur1);
01058         cur1 += delta;          /* form error * 5 */
01059         bpreverr1 = belowerr1 + cur1;
01060         belowerr1 = bnexterr;
01061         cur1 += delta;          /* form error * 7 */
01062         bnexterr = cur2;        /* Process component 2 */
01063         delta = cur2 * 2;
01064         cur2 += delta;          /* form error * 3 */
01065         errorptr[2] = (FSERROR) (bpreverr2 + cur2);
01066         cur2 += delta;          /* form error * 5 */
01067         bpreverr2 = belowerr2 + cur2;
01068         belowerr2 = bnexterr;
01069         cur2 += delta;          /* form error * 7 */
01070       }
01071       /* At this point curN contains the 7/16 error value to be propagated
01072        * to the next pixel on the current line, and all the errors for the
01073        * next line have been shifted over.  We are therefore ready to move on.
01074        */
01075       inptr += dir3;            /* Advance pixel pointers to next column */
01076       outptr += dir;
01077       errorptr += dir3;         /* advance errorptr to current column */
01078     }
01079     /* Post-loop cleanup: we must unload the final error values into the
01080      * final fserrors[] entry.  Note we need not unload belowerrN because
01081      * it is for the dummy column before or after the actual array.
01082      */
01083     errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
01084     errorptr[1] = (FSERROR) bpreverr1;
01085     errorptr[2] = (FSERROR) bpreverr2;
01086   }
01087 }
01088 
01089 
01090 /*
01091  * Initialize the error-limiting transfer function (lookup table).
01092  * The raw F-S error computation can potentially compute error values of up to
01093  * +- MAXJSAMPLE.  But we want the maximum correction applied to a pixel to be
01094  * much less, otherwise obviously wrong pixels will be created.  (Typical
01095  * effects include weird fringes at color-area boundaries, isolated bright
01096  * pixels in a dark area, etc.)  The standard advice for avoiding this problem
01097  * is to ensure that the "corners" of the color cube are allocated as output
01098  * colors; then repeated errors in the same direction cannot cause cascading
01099  * error buildup.  However, that only prevents the error from getting
01100  * completely out of hand; Aaron Giles reports that error limiting improves
01101  * the results even with corner colors allocated.
01102  * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
01103  * well, but the smoother transfer function used below is even better.  Thanks
01104  * to Aaron Giles for this idea.
01105  */
01106 
01107 LOCAL(void)
01108 init_error_limit (j_decompress_ptr cinfo)
01109 /* Allocate and fill in the error_limiter table */
01110 {
01111   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
01112   int * table;
01113   int in, out;
01114 
01115   table = (int *) (*cinfo->mem->alloc_small)
01116     ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
01117   table += MAXJSAMPLE;          /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
01118   cquantize->error_limiter = table;
01119 
01120 #define STEPSIZE ((MAXJSAMPLE+1)/16)
01121   /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
01122   out = 0;
01123   for (in = 0; in < STEPSIZE; in++, out++) {
01124     table[in] = out; table[-in] = -out;
01125   }
01126   /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
01127   for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
01128     table[in] = out; table[-in] = -out;
01129   }
01130   /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
01131   for (; in <= MAXJSAMPLE; in++) {
01132     table[in] = out; table[-in] = -out;
01133   }
01134 #undef STEPSIZE
01135 }
01136 
01137 
01138 /*
01139  * Finish up at the end of each pass.
01140  */
01141 
01142 METHODDEF(void)
01143 finish_pass1 (j_decompress_ptr cinfo)
01144 {
01145   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
01146 
01147   /* Select the representative colors and fill in cinfo->colormap */
01148   cinfo->colormap = cquantize->sv_colormap;
01149   select_colors(cinfo, cquantize->desired);
01150   /* Force next pass to zero the color index table */
01151   cquantize->needs_zeroed = TRUE;
01152 }
01153 
01154 
01155 METHODDEF(void)
01156 finish_pass2 (j_decompress_ptr cinfo)
01157 {
01158   /* no work */
01159 }
01160 
01161 
01162 /*
01163  * Initialize for each processing pass.
01164  */
01165 
01166 METHODDEF(void)
01167 start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
01168 {
01169   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
01170   hist3d histogram = cquantize->histogram;
01171   int i;
01172 
01173   /* Only F-S dithering or no dithering is supported. */
01174   /* If user asks for ordered dither, give him F-S. */
01175   if (cinfo->dither_mode != JDITHER_NONE)
01176     cinfo->dither_mode = JDITHER_FS;
01177 
01178   if (is_pre_scan) {
01179     /* Set up method pointers */
01180     cquantize->pub.color_quantize = prescan_quantize;
01181     cquantize->pub.finish_pass = finish_pass1;
01182     cquantize->needs_zeroed = TRUE; /* Always zero histogram */
01183   } else {
01184     /* Set up method pointers */
01185     if (cinfo->dither_mode == JDITHER_FS)
01186       cquantize->pub.color_quantize = pass2_fs_dither;
01187     else
01188       cquantize->pub.color_quantize = pass2_no_dither;
01189     cquantize->pub.finish_pass = finish_pass2;
01190 
01191     /* Make sure color count is acceptable */
01192     i = cinfo->actual_number_of_colors;
01193     if (i < 1)
01194       ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
01195     if (i > MAXNUMCOLORS)
01196       ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
01197 
01198     if (cinfo->dither_mode == JDITHER_FS) {
01199       size_t arraysize = (size_t) ((cinfo->output_width + 2) *
01200                                    (3 * SIZEOF(FSERROR)));
01201       /* Allocate Floyd-Steinberg workspace if we didn't already. */
01202       if (cquantize->fserrors == NULL)
01203         cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
01204           ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
01205       /* Initialize the propagated errors to zero. */
01206       jzero_far((void FAR *) cquantize->fserrors, arraysize);
01207       /* Make the error-limit table if we didn't already. */
01208       if (cquantize->error_limiter == NULL)
01209         init_error_limit(cinfo);
01210       cquantize->on_odd_row = FALSE;
01211     }
01212 
01213   }
01214   /* Zero the histogram or inverse color map, if necessary */
01215   if (cquantize->needs_zeroed) {
01216     for (i = 0; i < HIST_C0_ELEMS; i++) {
01217       jzero_far((void FAR *) histogram[i],
01218                 HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
01219     }
01220     cquantize->needs_zeroed = FALSE;
01221   }
01222 }
01223 
01224 
01225 /*
01226  * Switch to a new external colormap between output passes.
01227  */
01228 
01229 METHODDEF(void)
01230 new_color_map_2_quant (j_decompress_ptr cinfo)
01231 {
01232   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
01233 
01234   /* Reset the inverse color map */
01235   cquantize->needs_zeroed = TRUE;
01236 }
01237 
01238 
01239 /*
01240  * Module initialization routine for 2-pass color quantization.
01241  */
01242 
01243 GLOBAL(void)
01244 jinit_2pass_quantizer (j_decompress_ptr cinfo)
01245 {
01246   my_cquantize_ptr cquantize;
01247   int i;
01248 
01249   cquantize = (my_cquantize_ptr)
01250     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
01251                                 SIZEOF(my_cquantizer));
01252   cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
01253   cquantize->pub.start_pass = start_pass_2_quant;
01254   cquantize->pub.new_color_map = new_color_map_2_quant;
01255   cquantize->fserrors = NULL;   /* flag optional arrays not allocated */
01256   cquantize->error_limiter = NULL;
01257 
01258   /* Make sure jdmaster didn't give me a case I can't handle */
01259   if (cinfo->out_color_components != 3)
01260     ERREXIT(cinfo, JERR_NOTIMPL);
01261 
01262   /* Allocate the histogram/inverse colormap storage */
01263   cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
01264     ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
01265   for (i = 0; i < HIST_C0_ELEMS; i++) {
01266     cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
01267       ((j_common_ptr) cinfo, JPOOL_IMAGE,
01268        HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
01269   }
01270   cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
01271 
01272   /* Allocate storage for the completed colormap, if required.
01273    * We do this now since it is FAR storage and may affect
01274    * the memory manager's space calculations.
01275    */
01276   if (cinfo->enable_2pass_quant) {
01277     /* Make sure color count is acceptable */
01278     int desired = cinfo->desired_number_of_colors;
01279     /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
01280     if (desired < 8)
01281       ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
01282     /* Make sure colormap indexes can be represented by JSAMPLEs */
01283     if (desired > MAXNUMCOLORS)
01284       ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
01285     cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
01286       ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
01287     cquantize->desired = desired;
01288   } else
01289     cquantize->sv_colormap = NULL;
01290 
01291   /* Only F-S dithering or no dithering is supported. */
01292   /* If user asks for ordered dither, give him F-S. */
01293   if (cinfo->dither_mode != JDITHER_NONE)
01294     cinfo->dither_mode = JDITHER_FS;
01295 
01296   /* Allocate Floyd-Steinberg workspace if necessary.
01297    * This isn't really needed until pass 2, but again it is FAR storage.
01298    * Although we will cope with a later change in dither_mode,
01299    * we do not promise to honor max_memory_to_use if dither_mode changes.
01300    */
01301   if (cinfo->dither_mode == JDITHER_FS) {
01302     cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
01303       ((j_common_ptr) cinfo, JPOOL_IMAGE,
01304        (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
01305     /* Might as well create the error-limiting table too. */
01306     init_error_limit(cinfo);
01307   }
01308 }
01309 
01310 #endif /* QUANT_2PASS_SUPPORTED */


openhrp3
Author(s): AIST, General Robotix Inc., Nakamura Lab of Dept. of Mechano Informatics at University of Tokyo
autogenerated on Thu Apr 11 2019 03:30:17