1 ///////////////////////////////////////////////////////////////////////////// 
   3 // Purpose:     wxQuantize implementation 
   4 // Author:      Julian Smart 
   8 // Copyright:   (c) Thomas G. Lane, Vaclav Slavik, Julian Smart 
   9 // Licence:     wxWindows licence + JPEG library licence 
  10 ///////////////////////////////////////////////////////////////////////////// 
  15  * Copyright (C) 1991-1996, Thomas G. Lane. 
  16  * This file is part of the Independent JPEG Group's software. 
  17  * For conditions of distribution and use, see the accompanying README file. 
  19  * This file contains 2-pass color quantization (color mapping) routines. 
  20  * These routines provide selection of a custom color map for an image, 
  21  * followed by mapping of the image to that color map, with optional 
  22  * Floyd-Steinberg dithering. 
  23  * It is also possible to use just the second pass to map to an arbitrary 
  24  * externally-given color map. 
  26  * Note: ordered dithering is not supported, since there isn't any fast 
  27  * way to compute intercolor distances; it's unclear that ordered dither's 
  28  * fundamental assumptions even hold with an irregularly spaced color map. 
  31 /* modified by Vaclav Slavik for use as jpeglib-independent module */ 
  34 #pragma implementation "quantize.h" 
  37 // For compilers that support precompilation, includes "wx/wx.h". 
  38 #include "wx/wxprec.h" 
  49 #include "wx/quantize.h" 
  57 #define RGB_PIXELSIZE 3 
  59 #define MAXJSAMPLE        255 
  60 #define CENTERJSAMPLE     128 
  61 #define BITS_IN_JSAMPLE   8 
  62 #define GETJSAMPLE(value) ((int) (value)) 
  64 #define RIGHT_SHIFT(x,shft) ((x) >> (shft)) 
  66 typedef unsigned short UINT16
; 
  67 typedef signed short INT16
; 
  68 typedef signed int INT32
; 
  70 typedef unsigned char JSAMPLE
; 
  71 typedef JSAMPLE 
*JSAMPROW
; 
  72 typedef JSAMPROW 
*JSAMPARRAY
; 
  73 typedef unsigned int JDIMENSION
; 
  77         JDIMENSION output_width
; 
  79         int actual_number_of_colors
; 
  80         int desired_number_of_colors
; 
  81         JSAMPLE 
*sample_range_limit
, *srl_orig
; 
  84 typedef j_decompress 
*j_decompress_ptr
; 
  88  * This module implements the well-known Heckbert paradigm for color 
  89  * quantization.  Most of the ideas used here can be traced back to 
  90  * Heckbert's seminal paper 
  91  *   Heckbert, Paul.  "Color Image Quantization for Frame Buffer Display", 
  92  *   Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304. 
  94  * In the first pass over the image, we accumulate a histogram showing the 
  95  * usage count of each possible color.  To keep the histogram to a reasonable 
  96  * size, we reduce the precision of the input; typical practice is to retain 
  97  * 5 or 6 bits per color, so that 8 or 4 different input values are counted 
  98  * in the same histogram cell. 
 100  * Next, the color-selection step begins with a box representing the whole 
 101  * color space, and repeatedly splits the "largest" remaining box until we 
 102  * have as many boxes as desired colors.  Then the mean color in each 
 103  * remaining box becomes one of the possible output colors. 
 105  * The second pass over the image maps each input pixel to the closest output 
 106  * color (optionally after applying a Floyd-Steinberg dithering correction). 
 107  * This mapping is logically trivial, but making it go fast enough requires 
 110  * Heckbert-style quantizers vary a good deal in their policies for choosing 
 111  * the "largest" box and deciding where to cut it.  The particular policies 
 112  * used here have proved out well in experimental comparisons, but better ones 
 115  * In earlier versions of the IJG code, this module quantized in YCbCr color 
 116  * space, processing the raw upsampled data without a color conversion step. 
 117  * This allowed the color conversion math to be done only once per colormap 
 118  * entry, not once per pixel.  However, that optimization precluded other 
 119  * useful optimizations (such as merging color conversion with upsampling) 
 120  * and it also interfered with desired capabilities such as quantizing to an 
 121  * externally-supplied colormap.  We have therefore abandoned that approach. 
 122  * The present code works in the post-conversion color space, typically RGB. 
 124  * To improve the visual quality of the results, we actually work in scaled 
 125  * RGB space, giving G distances more weight than R, and R in turn more than 
 126  * B.  To do everything in integer math, we must use integer scale factors. 
 127  * The 2/3/1 scale factors used here correspond loosely to the relative 
 128  * weights of the colors in the NTSC grayscale equation. 
 129  * If you want to use this code to quantize a non-RGB color space, you'll 
 130  * probably need to change these scale factors. 
 133 #define R_SCALE 2               /* scale R distances by this much */ 
 134 #define G_SCALE 3               /* scale G distances by this much */ 
 135 #define B_SCALE 1               /* and B by this much */ 
 137 /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined 
 138  * in jmorecfg.h.  As the code stands, it will do the right thing for R,G,B 
 139  * and B,G,R orders.  If you define some other weird order in jmorecfg.h, 
 140  * you'll get compile errors until you extend this logic.  In that case 
 141  * you'll probably want to tweak the histogram sizes too. 
 145 #define C0_SCALE R_SCALE 
 148 #define C0_SCALE B_SCALE 
 151 #define C1_SCALE G_SCALE 
 154 #define C2_SCALE R_SCALE 
 157 #define C2_SCALE B_SCALE 
 162  * First we have the histogram data structure and routines for creating it. 
 164  * The number of bits of precision can be adjusted by changing these symbols. 
 165  * We recommend keeping 6 bits for G and 5 each for R and B. 
 166  * If you have plenty of memory and cycles, 6 bits all around gives marginally 
 167  * better results; if you are short of memory, 5 bits all around will save 
 168  * some space but degrade the results. 
 169  * To maintain a fully accurate histogram, we'd need to allocate a "long" 
 170  * (preferably unsigned long) for each cell.  In practice this is overkill; 
 171  * we can get by with 16 bits per cell.  Few of the cell counts will overflow, 
 172  * and clamping those that do overflow to the maximum value will give close- 
 173  * enough results.  This reduces the recommended histogram size from 256Kb 
 174  * to 128Kb, which is a useful savings on PC-class machines. 
 175  * (In the second pass the histogram space is re-used for pixel mapping data; 
 176  * in that capacity, each cell must be able to store zero to the number of 
 177  * desired colors.  16 bits/cell is plenty for that too.) 
 178  * Since the JPEG code is intended to run in small memory model on 80x86 
 179  * machines, we can't just allocate the histogram in one chunk.  Instead 
 180  * of a true 3-D array, we use a row of pointers to 2-D arrays.  Each 
 181  * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and 
 182  * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries.  Note that 
 183  * on 80x86 machines, the pointer row is in near memory but the actual 
 184  * arrays are in far memory (same arrangement as we use for image arrays). 
 187 #define MAXNUMCOLORS  (MAXJSAMPLE+1) /* maximum size of colormap */ 
 189 /* These will do the right thing for either R,G,B or B,G,R color order, 
 190  * but you may not like the results for other color orders. 
 192 #define HIST_C0_BITS  5         /* bits of precision in R/B histogram */ 
 193 #define HIST_C1_BITS  6         /* bits of precision in G histogram */ 
 194 #define HIST_C2_BITS  5         /* bits of precision in B/R histogram */ 
 196 /* Number of elements along histogram axes. */ 
 197 #define HIST_C0_ELEMS  (1<<HIST_C0_BITS) 
 198 #define HIST_C1_ELEMS  (1<<HIST_C1_BITS) 
 199 #define HIST_C2_ELEMS  (1<<HIST_C2_BITS) 
 201 /* These are the amounts to shift an input value to get a histogram index. */ 
 202 #define C0_SHIFT  (BITS_IN_JSAMPLE-HIST_C0_BITS) 
 203 #define C1_SHIFT  (BITS_IN_JSAMPLE-HIST_C1_BITS) 
 204 #define C2_SHIFT  (BITS_IN_JSAMPLE-HIST_C2_BITS) 
 207 typedef UINT16 histcell
;        /* histogram cell; prefer an unsigned type */ 
 209 typedef histcell  
* histptr
;    /* for pointers to histogram cells */ 
 211 typedef histcell hist1d
[HIST_C2_ELEMS
]; /* typedefs for the array */ 
 212 typedef hist1d  
* hist2d
;       /* type for the 2nd-level pointers */ 
 213 typedef hist2d 
* hist3d
;        /* type for top-level pointer */ 
 216 /* Declarations for Floyd-Steinberg dithering. 
 218  * Errors are accumulated into the array fserrors[], at a resolution of 
 219  * 1/16th of a pixel count.  The error at a given pixel is propagated 
 220  * to its not-yet-processed neighbors using the standard F-S fractions, 
 223  * We work left-to-right on even rows, right-to-left on odd rows. 
 225  * We can get away with a single array (holding one row's worth of errors) 
 226  * by using it to store the current row's errors at pixel columns not yet 
 227  * processed, but the next row's errors at columns already processed.  We 
 228  * need only a few extra variables to hold the errors immediately around the 
 229  * current column.  (If we are lucky, those variables are in registers, but 
 230  * even if not, they're probably cheaper to access than array elements are.) 
 232  * The fserrors[] array has (#columns + 2) entries; the extra entry at 
 233  * each end saves us from special-casing the first and last pixels. 
 234  * Each entry is three values long, one value for each color component. 
 236  * Note: on a wide image, we might not have enough room in a PC's near data 
 237  * segment to hold the error array; so it is allocated with alloc_large. 
 240 #if BITS_IN_JSAMPLE == 8 
 241 typedef INT16 FSERROR
;          /* 16 bits should be enough */ 
 242 typedef int LOCFSERROR
;         /* use 'int' for calculation temps */ 
 244 typedef INT32 FSERROR
;          /* may need more than 16 bits */ 
 245 typedef INT32 LOCFSERROR
;       /* be sure calculation temps are big enough */ 
 248 typedef FSERROR  
*FSERRPTR
;     /* pointer to error array (in  storage!) */ 
 251 /* Private subobject */ 
 256        void (*finish_pass
)(j_decompress_ptr
); 
 257        void (*color_quantize
)(j_decompress_ptr
, JSAMPARRAY
, JSAMPARRAY
, int); 
 258        void (*start_pass
)(j_decompress_ptr
, bool); 
 259        void (*new_color_map
)(j_decompress_ptr
); 
 262   /* Space for the eventually created colormap is stashed here */ 
 263   JSAMPARRAY sv_colormap
;       /* colormap allocated at init time */ 
 264   int desired
;                  /* desired # of colors = size of colormap */ 
 266   /* Variables for accumulating image statistics */ 
 267   hist3d histogram
;             /* pointer to the histogram */ 
 269   bool needs_zeroed
;            /* true if next pass must zero histogram */ 
 271   /* Variables for Floyd-Steinberg dithering */ 
 272   FSERRPTR fserrors
;            /* accumulated errors */ 
 273   bool on_odd_row
;              /* flag to remember which row we are on */ 
 274   int * error_limiter
;          /* table for clamping the applied error */ 
 277 typedef my_cquantizer 
* my_cquantize_ptr
; 
 281  * Prescan some rows of pixels. 
 282  * In this module the prescan simply updates the histogram, which has been 
 283  * initialized to zeroes by start_pass. 
 284  * An output_buf parameter is required by the method signature, but no data 
 285  * is actually output (in fact the buffer controller is probably passing a 
 290 prescan_quantize (j_decompress_ptr cinfo
, JSAMPARRAY input_buf
, 
 291                   JSAMPARRAY output_buf
, int num_rows
) 
 293   my_cquantize_ptr cquantize 
= (my_cquantize_ptr
) cinfo
->cquantize
; 
 294   register JSAMPROW ptr
; 
 295   register histptr histp
; 
 296   register hist3d histogram 
= cquantize
->histogram
; 
 299   JDIMENSION width 
= cinfo
->output_width
; 
 301   for (row 
= 0; row 
< num_rows
; row
++) { 
 302     ptr 
= input_buf
[row
]; 
 303     for (col 
= width
; col 
> 0; col
--) { 
 307           /* get pixel value and index into the histogram */ 
 308           histp 
= & histogram
[GETJSAMPLE(ptr
[0]) >> C0_SHIFT
] 
 309                              [GETJSAMPLE(ptr
[1]) >> C1_SHIFT
] 
 310                              [GETJSAMPLE(ptr
[2]) >> C2_SHIFT
]; 
 311           /* increment, check for overflow and undo increment if so. */ 
 322  * Next we have the really interesting routines: selection of a colormap 
 323  * given the completed histogram. 
 324  * These routines work with a list of "boxes", each representing a rectangular 
 325  * subset of the input color space (to histogram precision). 
 329   /* The bounds of the box (inclusive); expressed as histogram indexes */ 
 333   /* The volume (actually 2-norm) of the box */ 
 335   /* The number of nonzero histogram cells within this box */ 
 339 typedef box 
* boxptr
; 
 343 find_biggest_color_pop (boxptr boxlist
, int numboxes
) 
 344 /* Find the splittable box with the largest color population */ 
 345 /* Returns NULL if no splittable boxes remain */ 
 347   register boxptr boxp
; 
 349   register long maxc 
= 0; 
 352   for (i 
= 0, boxp 
= boxlist
; i 
< numboxes
; i
++, boxp
++) { 
 353     if (boxp
->colorcount 
> maxc 
&& boxp
->volume 
> 0) { 
 355       maxc 
= boxp
->colorcount
; 
 363 find_biggest_volume (boxptr boxlist
, int numboxes
) 
 364 /* Find the splittable box with the largest (scaled) volume */ 
 365 /* Returns NULL if no splittable boxes remain */ 
 367   register boxptr boxp
; 
 369   register INT32 maxv 
= 0; 
 372   for (i 
= 0, boxp 
= boxlist
; i 
< numboxes
; i
++, boxp
++) { 
 373     if (boxp
->volume 
> maxv
) { 
 383 update_box (j_decompress_ptr cinfo
, boxptr boxp
) 
 384 /* Shrink the min/max bounds of a box to enclose only nonzero elements, */ 
 385 /* and recompute its volume and population */ 
 387   my_cquantize_ptr cquantize 
= (my_cquantize_ptr
) cinfo
->cquantize
; 
 388   hist3d histogram 
= cquantize
->histogram
; 
 391   int c0min
,c0max
,c1min
,c1max
,c2min
,c2max
; 
 392   INT32 dist0
,dist1
,dist2
; 
 395   c0min 
= boxp
->c0min
;  c0max 
= boxp
->c0max
; 
 396   c1min 
= boxp
->c1min
;  c1max 
= boxp
->c1max
; 
 397   c2min 
= boxp
->c2min
;  c2max 
= boxp
->c2max
; 
 400     for (c0 
= c0min
; c0 
<= c0max
; c0
++) 
 401       for (c1 
= c1min
; c1 
<= c1max
; c1
++) { 
 402         histp 
= & histogram
[c0
][c1
][c2min
]; 
 403         for (c2 
= c2min
; c2 
<= c2max
; c2
++) 
 405             boxp
->c0min 
= c0min 
= c0
; 
 411     for (c0 
= c0max
; c0 
>= c0min
; c0
--) 
 412       for (c1 
= c1min
; c1 
<= c1max
; c1
++) { 
 413         histp 
= & histogram
[c0
][c1
][c2min
]; 
 414         for (c2 
= c2min
; c2 
<= c2max
; c2
++) 
 416             boxp
->c0max 
= c0max 
= c0
; 
 422     for (c1 
= c1min
; c1 
<= c1max
; c1
++) 
 423       for (c0 
= c0min
; c0 
<= c0max
; c0
++) { 
 424         histp 
= & histogram
[c0
][c1
][c2min
]; 
 425         for (c2 
= c2min
; c2 
<= c2max
; c2
++) 
 427             boxp
->c1min 
= c1min 
= c1
; 
 433     for (c1 
= c1max
; c1 
>= c1min
; c1
--) 
 434       for (c0 
= c0min
; c0 
<= c0max
; c0
++) { 
 435         histp 
= & histogram
[c0
][c1
][c2min
]; 
 436         for (c2 
= c2min
; c2 
<= c2max
; c2
++) 
 438             boxp
->c1max 
= c1max 
= c1
; 
 444     for (c2 
= c2min
; c2 
<= c2max
; c2
++) 
 445       for (c0 
= c0min
; c0 
<= c0max
; c0
++) { 
 446         histp 
= & histogram
[c0
][c1min
][c2
]; 
 447         for (c1 
= c1min
; c1 
<= c1max
; c1
++, histp 
+= HIST_C2_ELEMS
) 
 449             boxp
->c2min 
= c2min 
= c2
; 
 455     for (c2 
= c2max
; c2 
>= c2min
; c2
--) 
 456       for (c0 
= c0min
; c0 
<= c0max
; c0
++) { 
 457         histp 
= & histogram
[c0
][c1min
][c2
]; 
 458         for (c1 
= c1min
; c1 
<= c1max
; c1
++, histp 
+= HIST_C2_ELEMS
) 
 460             boxp
->c2max 
= c2max 
= c2
; 
 466   /* Update box volume. 
 467    * We use 2-norm rather than real volume here; this biases the method 
 468    * against making long narrow boxes, and it has the side benefit that 
 469    * a box is splittable iff norm > 0. 
 470    * Since the differences are expressed in histogram-cell units, 
 471    * we have to shift back to JSAMPLE units to get consistent distances; 
 472    * after which, we scale according to the selected distance scale factors. 
 474   dist0 
= ((c0max 
- c0min
) << C0_SHIFT
) * C0_SCALE
; 
 475   dist1 
= ((c1max 
- c1min
) << C1_SHIFT
) * C1_SCALE
; 
 476   dist2 
= ((c2max 
- c2min
) << C2_SHIFT
) * C2_SCALE
; 
 477   boxp
->volume 
= dist0
*dist0 
+ dist1
*dist1 
+ dist2
*dist2
; 
 479   /* Now scan remaining volume of box and compute population */ 
 481   for (c0 
= c0min
; c0 
<= c0max
; c0
++) 
 482     for (c1 
= c1min
; c1 
<= c1max
; c1
++) { 
 483       histp 
= & histogram
[c0
][c1
][c2min
]; 
 484       for (c2 
= c2min
; c2 
<= c2max
; c2
++, histp
++) 
 489   boxp
->colorcount 
= ccount
; 
 494 median_cut (j_decompress_ptr cinfo
, boxptr boxlist
, int numboxes
, 
 496 /* Repeatedly select and split the largest box until we have enough boxes */ 
 500   register boxptr b1
,b2
; 
 502   while (numboxes 
< desired_colors
) { 
 503     /* Select box to split. 
 504      * Current algorithm: by population for first half, then by volume. 
 506     if (numboxes
*2 <= desired_colors
) { 
 507       b1 
= find_biggest_color_pop(boxlist
, numboxes
); 
 509       b1 
= find_biggest_volume(boxlist
, numboxes
); 
 511     if (b1 
== NULL
)             /* no splittable boxes left! */ 
 513     b2 
= &boxlist
[numboxes
];    /* where new box will go */ 
 514     /* Copy the color bounds to the new box. */ 
 515     b2
->c0max 
= b1
->c0max
; b2
->c1max 
= b1
->c1max
; b2
->c2max 
= b1
->c2max
; 
 516     b2
->c0min 
= b1
->c0min
; b2
->c1min 
= b1
->c1min
; b2
->c2min 
= b1
->c2min
; 
 517     /* Choose which axis to split the box on. 
 518      * Current algorithm: longest scaled axis. 
 519      * See notes in update_box about scaling distances. 
 521     c0 
= ((b1
->c0max 
- b1
->c0min
) << C0_SHIFT
) * C0_SCALE
; 
 522     c1 
= ((b1
->c1max 
- b1
->c1min
) << C1_SHIFT
) * C1_SCALE
; 
 523     c2 
= ((b1
->c2max 
- b1
->c2min
) << C2_SHIFT
) * C2_SCALE
; 
 524     /* We want to break any ties in favor of green, then red, blue last. 
 525      * This code does the right thing for R,G,B or B,G,R color orders only. 
 529     if (c0 
> cmax
) { cmax 
= c0
; n 
= 0; } 
 530     if (c2 
> cmax
) { n 
= 2; } 
 533     if (c2 
> cmax
) { cmax 
= c2
; n 
= 2; } 
 534     if (c0 
> cmax
) { n 
= 0; } 
 536     /* Choose split point along selected axis, and update box bounds. 
 537      * Current algorithm: split at halfway point. 
 538      * (Since the box has been shrunk to minimum volume, 
 539      * any split will produce two nonempty subboxes.) 
 540      * Note that lb value is max for lower box, so must be < old max. 
 544       lb 
= (b1
->c0max 
+ b1
->c0min
) / 2; 
 549       lb 
= (b1
->c1max 
+ b1
->c1min
) / 2; 
 554       lb 
= (b1
->c2max 
+ b1
->c2min
) / 2; 
 559     /* Update stats for boxes */ 
 560     update_box(cinfo
, b1
); 
 561     update_box(cinfo
, b2
); 
 569 compute_color (j_decompress_ptr cinfo
, boxptr boxp
, int icolor
) 
 570 /* Compute representative color for a box, put it in colormap[icolor] */ 
 572   /* Current algorithm: mean weighted by pixels (not colors) */ 
 573   /* Note it is important to get the rounding correct! */ 
 574   my_cquantize_ptr cquantize 
= (my_cquantize_ptr
) cinfo
->cquantize
; 
 575   hist3d histogram 
= cquantize
->histogram
; 
 578   int c0min
,c0max
,c1min
,c1max
,c2min
,c2max
; 
 585   c0min 
= boxp
->c0min
;  c0max 
= boxp
->c0max
; 
 586   c1min 
= boxp
->c1min
;  c1max 
= boxp
->c1max
; 
 587   c2min 
= boxp
->c2min
;  c2max 
= boxp
->c2max
; 
 589   for (c0 
= c0min
; c0 
<= c0max
; c0
++) 
 590     for (c1 
= c1min
; c1 
<= c1max
; c1
++) { 
 591       histp 
= & histogram
[c0
][c1
][c2min
]; 
 592       for (c2 
= c2min
; c2 
<= c2max
; c2
++) { 
 593         if ((count 
= *histp
++) != 0) { 
 595           c0total 
+= ((c0 
<< C0_SHIFT
) + ((1<<C0_SHIFT
)>>1)) * count
; 
 596           c1total 
+= ((c1 
<< C1_SHIFT
) + ((1<<C1_SHIFT
)>>1)) * count
; 
 597           c2total 
+= ((c2 
<< C2_SHIFT
) + ((1<<C2_SHIFT
)>>1)) * count
; 
 602   cinfo
->colormap
[0][icolor
] = (JSAMPLE
) ((c0total 
+ (total
>>1)) / total
); 
 603   cinfo
->colormap
[1][icolor
] = (JSAMPLE
) ((c1total 
+ (total
>>1)) / total
); 
 604   cinfo
->colormap
[2][icolor
] = (JSAMPLE
) ((c2total 
+ (total
>>1)) / total
); 
 609 select_colors (j_decompress_ptr cinfo
, int desired_colors
) 
 610 /* Master routine for color selection */ 
 616   /* Allocate workspace for box list */ 
 617   boxlist 
= (boxptr
) malloc(desired_colors 
* sizeof(box
)); 
 618   /* Initialize one box containing whole space */ 
 620   boxlist
[0].c0min 
= 0; 
 621   boxlist
[0].c0max 
= MAXJSAMPLE 
>> C0_SHIFT
; 
 622   boxlist
[0].c1min 
= 0; 
 623   boxlist
[0].c1max 
= MAXJSAMPLE 
>> C1_SHIFT
; 
 624   boxlist
[0].c2min 
= 0; 
 625   boxlist
[0].c2max 
= MAXJSAMPLE 
>> C2_SHIFT
; 
 626   /* Shrink it to actually-used volume and set its statistics */ 
 627   update_box(cinfo
, & boxlist
[0]); 
 628   /* Perform median-cut to produce final box list */ 
 629   numboxes 
= median_cut(cinfo
, boxlist
, numboxes
, desired_colors
); 
 630   /* Compute the representative color for each box, fill colormap */ 
 631   for (i 
= 0; i 
< numboxes
; i
++) 
 632     compute_color(cinfo
, & boxlist
[i
], i
); 
 633   cinfo
->actual_number_of_colors 
= numboxes
; 
 635   free(boxlist
); //FIXME?? I don't know if this is correct - VS 
 640  * These routines are concerned with the time-critical task of mapping input 
 641  * colors to the nearest color in the selected colormap. 
 643  * We re-use the histogram space as an "inverse color map", essentially a 
 644  * cache for the results of nearest-color searches.  All colors within a 
 645  * histogram cell will be mapped to the same colormap entry, namely the one 
 646  * closest to the cell's center.  This may not be quite the closest entry to 
 647  * the actual input color, but it's almost as good.  A zero in the cache 
 648  * indicates we haven't found the nearest color for that cell yet; the array 
 649  * is cleared to zeroes before starting the mapping pass.  When we find the 
 650  * nearest color for a cell, its colormap index plus one is recorded in the 
 651  * cache for future use.  The pass2 scanning routines call fill_inverse_cmap 
 652  * when they need to use an unfilled entry in the cache. 
 654  * Our method of efficiently finding nearest colors is based on the "locally 
 655  * sorted search" idea described by Heckbert and on the incremental distance 
 656  * calculation described by Spencer W. Thomas in chapter III.1 of Graphics 
 657  * Gems II (James Arvo, ed.  Academic Press, 1991).  Thomas points out that 
 658  * the distances from a given colormap entry to each cell of the histogram can 
 659  * be computed quickly using an incremental method: the differences between 
 660  * distances to adjacent cells themselves differ by a constant.  This allows a 
 661  * fairly fast implementation of the "brute force" approach of computing the 
 662  * distance from every colormap entry to every histogram cell.  Unfortunately, 
 663  * it needs a work array to hold the best-distance-so-far for each histogram 
 664  * cell (because the inner loop has to be over cells, not colormap entries). 
 665  * The work array elements have to be INT32s, so the work array would need 
 666  * 256Kb at our recommended precision.  This is not feasible in DOS machines. 
 668  * To get around these problems, we apply Thomas' method to compute the 
 669  * nearest colors for only the cells within a small subbox of the histogram. 
 670  * The work array need be only as big as the subbox, so the memory usage 
 671  * problem is solved.  Furthermore, we need not fill subboxes that are never 
 672  * referenced in pass2; many images use only part of the color gamut, so a 
 673  * fair amount of work is saved.  An additional advantage of this 
 674  * approach is that we can apply Heckbert's locality criterion to quickly 
 675  * eliminate colormap entries that are far away from the subbox; typically 
 676  * three-fourths of the colormap entries are rejected by Heckbert's criterion, 
 677  * and we need not compute their distances to individual cells in the subbox. 
 678  * The speed of this approach is heavily influenced by the subbox size: too 
 679  * small means too much overhead, too big loses because Heckbert's criterion 
 680  * can't eliminate as many colormap entries.  Empirically the best subbox 
 681  * size seems to be about 1/512th of the histogram (1/8th in each direction). 
 683  * Thomas' article also describes a refined method which is asymptotically 
 684  * faster than the brute-force method, but it is also far more complex and 
 685  * cannot efficiently be applied to small subboxes.  It is therefore not 
 686  * useful for programs intended to be portable to DOS machines.  On machines 
 687  * with plenty of memory, filling the whole histogram in one shot with Thomas' 
 688  * refined method might be faster than the present code --- but then again, 
 689  * it might not be any faster, and it's certainly more complicated. 
 693 /* log2(histogram cells in update box) for each axis; this can be adjusted */ 
 694 #define BOX_C0_LOG  (HIST_C0_BITS-3) 
 695 #define BOX_C1_LOG  (HIST_C1_BITS-3) 
 696 #define BOX_C2_LOG  (HIST_C2_BITS-3) 
 698 #define BOX_C0_ELEMS  (1<<BOX_C0_LOG) /* # of hist cells in update box */ 
 699 #define BOX_C1_ELEMS  (1<<BOX_C1_LOG) 
 700 #define BOX_C2_ELEMS  (1<<BOX_C2_LOG) 
 702 #define BOX_C0_SHIFT  (C0_SHIFT + BOX_C0_LOG) 
 703 #define BOX_C1_SHIFT  (C1_SHIFT + BOX_C1_LOG) 
 704 #define BOX_C2_SHIFT  (C2_SHIFT + BOX_C2_LOG) 
 708  * The next three routines implement inverse colormap filling.  They could 
 709  * all be folded into one big routine, but splitting them up this way saves 
 710  * some stack space (the mindist[] and bestdist[] arrays need not coexist) 
 711  * and may allow some compilers to produce better code by registerizing more 
 712  * inner-loop variables. 
 716 find_nearby_colors (j_decompress_ptr cinfo
, int minc0
, int minc1
, int minc2
, 
 718 /* Locate the colormap entries close enough to an update box to be candidates 
 719  * for the nearest entry to some cell(s) in the update box.  The update box 
 720  * is specified by the center coordinates of its first cell.  The number of 
 721  * candidate colormap entries is returned, and their colormap indexes are 
 722  * placed in colorlist[]. 
 723  * This routine uses Heckbert's "locally sorted search" criterion to select 
 724  * the colors that need further consideration. 
 727   int numcolors 
= cinfo
->actual_number_of_colors
; 
 728   int maxc0
, maxc1
, maxc2
; 
 729   int centerc0
, centerc1
, centerc2
; 
 731   INT32 minmaxdist
, min_dist
, max_dist
, tdist
; 
 732   INT32 mindist
[MAXNUMCOLORS
];  /* min distance to colormap entry i */ 
 734   /* Compute true coordinates of update box's upper corner and center. 
 735    * Actually we compute the coordinates of the center of the upper-corner 
 736    * histogram cell, which are the upper bounds of the volume we care about. 
 737    * Note that since ">>" rounds down, the "center" values may be closer to 
 738    * min than to max; hence comparisons to them must be "<=", not "<". 
 740   maxc0 
= minc0 
+ ((1 << BOX_C0_SHIFT
) - (1 << C0_SHIFT
)); 
 741   centerc0 
= (minc0 
+ maxc0
) >> 1; 
 742   maxc1 
= minc1 
+ ((1 << BOX_C1_SHIFT
) - (1 << C1_SHIFT
)); 
 743   centerc1 
= (minc1 
+ maxc1
) >> 1; 
 744   maxc2 
= minc2 
+ ((1 << BOX_C2_SHIFT
) - (1 << C2_SHIFT
)); 
 745   centerc2 
= (minc2 
+ maxc2
) >> 1; 
 747   /* For each color in colormap, find: 
 748    *  1. its minimum squared-distance to any point in the update box 
 749    *     (zero if color is within update box); 
 750    *  2. its maximum squared-distance to any point in the update box. 
 751    * Both of these can be found by considering only the corners of the box. 
 752    * We save the minimum distance for each color in mindist[]; 
 753    * only the smallest maximum distance is of interest. 
 755   minmaxdist 
= 0x7FFFFFFFL
; 
 757   for (i 
= 0; i 
< numcolors
; i
++) { 
 758     /* We compute the squared-c0-distance term, then add in the other two. */ 
 759     x 
= GETJSAMPLE(cinfo
->colormap
[0][i
]); 
 761       tdist 
= (x 
- minc0
) * C0_SCALE
; 
 762       min_dist 
= tdist
*tdist
; 
 763       tdist 
= (x 
- maxc0
) * C0_SCALE
; 
 764       max_dist 
= tdist
*tdist
; 
 765     } else if (x 
> maxc0
) { 
 766       tdist 
= (x 
- maxc0
) * C0_SCALE
; 
 767       min_dist 
= tdist
*tdist
; 
 768       tdist 
= (x 
- minc0
) * C0_SCALE
; 
 769       max_dist 
= tdist
*tdist
; 
 771       /* within cell range so no contribution to min_dist */ 
 774         tdist 
= (x 
- maxc0
) * C0_SCALE
; 
 775         max_dist 
= tdist
*tdist
; 
 777         tdist 
= (x 
- minc0
) * C0_SCALE
; 
 778         max_dist 
= tdist
*tdist
; 
 782     x 
= GETJSAMPLE(cinfo
->colormap
[1][i
]); 
 784       tdist 
= (x 
- minc1
) * C1_SCALE
; 
 785       min_dist 
+= tdist
*tdist
; 
 786       tdist 
= (x 
- maxc1
) * C1_SCALE
; 
 787       max_dist 
+= tdist
*tdist
; 
 788     } else if (x 
> maxc1
) { 
 789       tdist 
= (x 
- maxc1
) * C1_SCALE
; 
 790       min_dist 
+= tdist
*tdist
; 
 791       tdist 
= (x 
- minc1
) * C1_SCALE
; 
 792       max_dist 
+= tdist
*tdist
; 
 794       /* within cell range so no contribution to min_dist */ 
 796         tdist 
= (x 
- maxc1
) * C1_SCALE
; 
 797         max_dist 
+= tdist
*tdist
; 
 799         tdist 
= (x 
- minc1
) * C1_SCALE
; 
 800         max_dist 
+= tdist
*tdist
; 
 804     x 
= GETJSAMPLE(cinfo
->colormap
[2][i
]); 
 806       tdist 
= (x 
- minc2
) * C2_SCALE
; 
 807       min_dist 
+= tdist
*tdist
; 
 808       tdist 
= (x 
- maxc2
) * C2_SCALE
; 
 809       max_dist 
+= tdist
*tdist
; 
 810     } else if (x 
> maxc2
) { 
 811       tdist 
= (x 
- maxc2
) * C2_SCALE
; 
 812       min_dist 
+= tdist
*tdist
; 
 813       tdist 
= (x 
- minc2
) * C2_SCALE
; 
 814       max_dist 
+= tdist
*tdist
; 
 816       /* within cell range so no contribution to min_dist */ 
 818         tdist 
= (x 
- maxc2
) * C2_SCALE
; 
 819         max_dist 
+= tdist
*tdist
; 
 821         tdist 
= (x 
- minc2
) * C2_SCALE
; 
 822         max_dist 
+= tdist
*tdist
; 
 826     mindist
[i
] = min_dist
;      /* save away the results */ 
 827     if (max_dist 
< minmaxdist
) 
 828       minmaxdist 
= max_dist
; 
 831   /* Now we know that no cell in the update box is more than minmaxdist 
 832    * away from some colormap entry.  Therefore, only colors that are 
 833    * within minmaxdist of some part of the box need be considered. 
 836   for (i 
= 0; i 
< numcolors
; i
++) { 
 837     if (mindist
[i
] <= minmaxdist
) 
 838       colorlist
[ncolors
++] = (JSAMPLE
) i
; 
 845 find_best_colors (j_decompress_ptr cinfo
, int minc0
, int minc1
, int minc2
, 
 846                   int numcolors
, JSAMPLE colorlist
[], JSAMPLE bestcolor
[]) 
 847 /* Find the closest colormap entry for each cell in the update box, 
 848  * given the list of candidate colors prepared by find_nearby_colors. 
 849  * Return the indexes of the closest entries in the bestcolor[] array. 
 850  * This routine uses Thomas' incremental distance calculation method to 
 851  * find the distance from a colormap entry to successive cells in the box. 
 856   register INT32 
* bptr
;        /* pointer into bestdist[] array */ 
 857   JSAMPLE 
* cptr
;               /* pointer into bestcolor[] array */ 
 858   INT32 dist0
, dist1
;           /* initial distance values */ 
 859   register INT32 dist2
;         /* current distance in inner loop */ 
 860   INT32 xx0
, xx1
;               /* distance increments */ 
 862   INT32 inc0
, inc1
, inc2
;       /* initial values for increments */ 
 863   /* This array holds the distance to the nearest-so-far color for each cell */ 
 864   INT32 bestdist
[BOX_C0_ELEMS 
* BOX_C1_ELEMS 
* BOX_C2_ELEMS
]; 
 866   /* Initialize best-distance for each cell of the update box */ 
 868   for (i 
= BOX_C0_ELEMS
*BOX_C1_ELEMS
*BOX_C2_ELEMS
-1; i 
>= 0; i
--) 
 869     *bptr
++ = 0x7FFFFFFFL
; 
 871   /* For each color selected by find_nearby_colors, 
 872    * compute its distance to the center of each cell in the box. 
 873    * If that's less than best-so-far, update best distance and color number. 
 876   /* Nominal steps between cell centers ("x" in Thomas article) */ 
 877 #define STEP_C0  ((1 << C0_SHIFT) * C0_SCALE) 
 878 #define STEP_C1  ((1 << C1_SHIFT) * C1_SCALE) 
 879 #define STEP_C2  ((1 << C2_SHIFT) * C2_SCALE) 
 881   for (i 
= 0; i 
< numcolors
; i
++) { 
 882     icolor 
= GETJSAMPLE(colorlist
[i
]); 
 883     /* Compute (square of) distance from minc0/c1/c2 to this color */ 
 884     inc0 
= (minc0 
- GETJSAMPLE(cinfo
->colormap
[0][icolor
])) * C0_SCALE
; 
 886     inc1 
= (minc1 
- GETJSAMPLE(cinfo
->colormap
[1][icolor
])) * C1_SCALE
; 
 888     inc2 
= (minc2 
- GETJSAMPLE(cinfo
->colormap
[2][icolor
])) * C2_SCALE
; 
 890     /* Form the initial difference increments */ 
 891     inc0 
= inc0 
* (2 * STEP_C0
) + STEP_C0 
* STEP_C0
; 
 892     inc1 
= inc1 
* (2 * STEP_C1
) + STEP_C1 
* STEP_C1
; 
 893     inc2 
= inc2 
* (2 * STEP_C2
) + STEP_C2 
* STEP_C2
; 
 894     /* Now loop over all cells in box, updating distance per Thomas method */ 
 898     for (ic0 
= BOX_C0_ELEMS
-1; ic0 
>= 0; ic0
--) { 
 901       for (ic1 
= BOX_C1_ELEMS
-1; ic1 
>= 0; ic1
--) { 
 904         for (ic2 
= BOX_C2_ELEMS
-1; ic2 
>= 0; ic2
--) { 
 907             *cptr 
= (JSAMPLE
) icolor
; 
 910           xx2 
+= 2 * STEP_C2 
* STEP_C2
; 
 915         xx1 
+= 2 * STEP_C1 
* STEP_C1
; 
 918       xx0 
+= 2 * STEP_C0 
* STEP_C0
; 
 925 fill_inverse_cmap (j_decompress_ptr cinfo
, int c0
, int c1
, int c2
) 
 926 /* Fill the inverse-colormap entries in the update box that contains */ 
 927 /* histogram cell c0/c1/c2.  (Only that one cell MUST be filled, but */ 
 928 /* we can fill as many others as we wish.) */ 
 930   my_cquantize_ptr cquantize 
= (my_cquantize_ptr
) cinfo
->cquantize
; 
 931   hist3d histogram 
= cquantize
->histogram
; 
 932   int minc0
, minc1
, minc2
;      /* lower left corner of update box */ 
 934   register JSAMPLE 
* cptr
;      /* pointer into bestcolor[] array */ 
 935   register histptr cachep
;      /* pointer into main cache array */ 
 936   /* This array lists the candidate colormap indexes. */ 
 937   JSAMPLE colorlist
[MAXNUMCOLORS
]; 
 938   int numcolors
;                /* number of candidate colors */ 
 939   /* This array holds the actually closest colormap index for each cell. */ 
 940   JSAMPLE bestcolor
[BOX_C0_ELEMS 
* BOX_C1_ELEMS 
* BOX_C2_ELEMS
]; 
 942   /* Convert cell coordinates to update box ID */ 
 947   /* Compute true coordinates of update box's origin corner. 
 948    * Actually we compute the coordinates of the center of the corner 
 949    * histogram cell, which are the lower bounds of the volume we care about. 
 951   minc0 
= (c0 
<< BOX_C0_SHIFT
) + ((1 << C0_SHIFT
) >> 1); 
 952   minc1 
= (c1 
<< BOX_C1_SHIFT
) + ((1 << C1_SHIFT
) >> 1); 
 953   minc2 
= (c2 
<< BOX_C2_SHIFT
) + ((1 << C2_SHIFT
) >> 1); 
 955   /* Determine which colormap entries are close enough to be candidates 
 956    * for the nearest entry to some cell in the update box. 
 958   numcolors 
= find_nearby_colors(cinfo
, minc0
, minc1
, minc2
, colorlist
); 
 960   /* Determine the actually nearest colors. */ 
 961   find_best_colors(cinfo
, minc0
, minc1
, minc2
, numcolors
, colorlist
, 
 964   /* Save the best color numbers (plus 1) in the main cache array */ 
 965   c0 
<<= BOX_C0_LOG
;            /* convert ID back to base cell indexes */ 
 969   for (ic0 
= 0; ic0 
< BOX_C0_ELEMS
; ic0
++) { 
 970     for (ic1 
= 0; ic1 
< BOX_C1_ELEMS
; ic1
++) { 
 971       cachep 
= & histogram
[c0
+ic0
][c1
+ic1
][c2
]; 
 972       for (ic2 
= 0; ic2 
< BOX_C2_ELEMS
; ic2
++) { 
 973         *cachep
++ = (histcell
) (GETJSAMPLE(*cptr
++) + 1); 
 981  * Map some rows of pixels to the output colormapped representation. 
 985 pass2_no_dither (j_decompress_ptr cinfo
, 
 986                  JSAMPARRAY input_buf
, JSAMPARRAY output_buf
, int num_rows
) 
 987 /* This version performs no dithering */ 
 989   my_cquantize_ptr cquantize 
= (my_cquantize_ptr
) cinfo
->cquantize
; 
 990   hist3d histogram 
= cquantize
->histogram
; 
 991   register JSAMPROW inptr
, outptr
; 
 992   register histptr cachep
; 
 993   register int c0
, c1
, c2
; 
 996   JDIMENSION width 
= cinfo
->output_width
; 
 998   for (row 
= 0; row 
< num_rows
; row
++) { 
 999     inptr 
= input_buf
[row
]; 
1000     outptr 
= output_buf
[row
]; 
1001     for (col 
= width
; col 
> 0; col
--) { 
1002       /* get pixel value and index into the cache */ 
1003       c0 
= GETJSAMPLE(*inptr
++) >> C0_SHIFT
; 
1004       c1 
= GETJSAMPLE(*inptr
++) >> C1_SHIFT
; 
1005       c2 
= GETJSAMPLE(*inptr
++) >> C2_SHIFT
; 
1006       cachep 
= & histogram
[c0
][c1
][c2
]; 
1007       /* If we have not seen this color before, find nearest colormap entry */ 
1008       /* and update the cache */ 
1010         fill_inverse_cmap(cinfo
, c0
,c1
,c2
); 
1011       /* Now emit the colormap index for this cell */ 
1012       *outptr
++ = (JSAMPLE
) (*cachep 
- 1); 
1019 pass2_fs_dither (j_decompress_ptr cinfo
, 
1020                  JSAMPARRAY input_buf
, JSAMPARRAY output_buf
, int num_rows
) 
1021 /* This version performs Floyd-Steinberg dithering */ 
1023   my_cquantize_ptr cquantize 
= (my_cquantize_ptr
) cinfo
->cquantize
; 
1024   hist3d histogram 
= cquantize
->histogram
; 
1025   register LOCFSERROR cur0
, cur1
, cur2
; /* current error or pixel value */ 
1026   LOCFSERROR belowerr0
, belowerr1
, belowerr2
; /* error for pixel below cur */ 
1027   LOCFSERROR bpreverr0
, bpreverr1
, bpreverr2
; /* error for below/prev col */ 
1028   register FSERRPTR errorptr
;   /* => fserrors[] at column before current */ 
1029   JSAMPROW inptr
;               /* => current input pixel */ 
1030   JSAMPROW outptr
;              /* => current output pixel */ 
1032   int dir
;                      /* +1 or -1 depending on direction */ 
1033   int dir3
;                     /* 3*dir, for advancing inptr & errorptr */ 
1036   JDIMENSION width 
= cinfo
->output_width
; 
1037   JSAMPLE 
*range_limit 
= cinfo
->sample_range_limit
; 
1038   int *error_limit 
= cquantize
->error_limiter
; 
1039   JSAMPROW colormap0 
= cinfo
->colormap
[0]; 
1040   JSAMPROW colormap1 
= cinfo
->colormap
[1]; 
1041   JSAMPROW colormap2 
= cinfo
->colormap
[2]; 
1044   for (row 
= 0; row 
< num_rows
; row
++) { 
1045     inptr 
= input_buf
[row
]; 
1046     outptr 
= output_buf
[row
]; 
1047     if (cquantize
->on_odd_row
) { 
1048       /* work right to left in this row */ 
1049       inptr 
+= (width
-1) * 3;   /* so point to rightmost pixel */ 
1053       errorptr 
= cquantize
->fserrors 
+ (width
+1)*3; /* => entry after last column */ 
1054       cquantize
->on_odd_row 
= false; /* flip for next time */ 
1056       /* work left to right in this row */ 
1059       errorptr 
= cquantize
->fserrors
; /* => entry before first real column */ 
1060       cquantize
->on_odd_row 
= true; /* flip for next time */ 
1062     /* Preset error values: no error propagated to first pixel from left */ 
1063     cur0 
= cur1 
= cur2 
= 0; 
1064     /* and no error propagated to row below yet */ 
1065     belowerr0 
= belowerr1 
= belowerr2 
= 0; 
1066     bpreverr0 
= bpreverr1 
= bpreverr2 
= 0; 
1068     for (col 
= width
; col 
> 0; col
--) { 
1069       /* curN holds the error propagated from the previous pixel on the 
1070        * current line.  Add the error propagated from the previous line 
1071        * to form the complete error correction term for this pixel, and 
1072        * round the error term (which is expressed * 16) to an integer. 
1073        * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct 
1074        * for either sign of the error value. 
1075        * Note: errorptr points to *previous* column's array entry. 
1077       cur0 
= RIGHT_SHIFT(cur0 
+ errorptr
[dir3
+0] + 8, 4); 
1078       cur1 
= RIGHT_SHIFT(cur1 
+ errorptr
[dir3
+1] + 8, 4); 
1079       cur2 
= RIGHT_SHIFT(cur2 
+ errorptr
[dir3
+2] + 8, 4); 
1080       /* Limit the error using transfer function set by init_error_limit. 
1081        * See comments with init_error_limit for rationale. 
1083       cur0 
= error_limit
[cur0
]; 
1084       cur1 
= error_limit
[cur1
]; 
1085       cur2 
= error_limit
[cur2
]; 
1086       /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE. 
1087        * The maximum error is +- MAXJSAMPLE (or less with error limiting); 
1088        * this sets the required size of the range_limit array. 
1090       cur0 
+= GETJSAMPLE(inptr
[0]); 
1091       cur1 
+= GETJSAMPLE(inptr
[1]); 
1092       cur2 
+= GETJSAMPLE(inptr
[2]); 
1093       cur0 
= GETJSAMPLE(range_limit
[cur0
]); 
1094       cur1 
= GETJSAMPLE(range_limit
[cur1
]); 
1095       cur2 
= GETJSAMPLE(range_limit
[cur2
]); 
1096       /* Index into the cache with adjusted pixel value */ 
1097       cachep 
= & histogram
[cur0
>>C0_SHIFT
][cur1
>>C1_SHIFT
][cur2
>>C2_SHIFT
]; 
1098       /* If we have not seen this color before, find nearest colormap */ 
1099       /* entry and update the cache */ 
1101         fill_inverse_cmap(cinfo
, cur0
>>C0_SHIFT
,cur1
>>C1_SHIFT
,cur2
>>C2_SHIFT
); 
1102       /* Now emit the colormap index for this cell */ 
1103       { register int pixcode 
= *cachep 
- 1; 
1104         *outptr 
= (JSAMPLE
) pixcode
; 
1105         /* Compute representation error for this pixel */ 
1106         cur0 
-= GETJSAMPLE(colormap0
[pixcode
]); 
1107         cur1 
-= GETJSAMPLE(colormap1
[pixcode
]); 
1108         cur2 
-= GETJSAMPLE(colormap2
[pixcode
]); 
1110       /* Compute error fractions to be propagated to adjacent pixels. 
1111        * Add these into the running sums, and simultaneously shift the 
1112        * next-line error sums left by 1 column. 
1114       { register LOCFSERROR bnexterr
, delta
; 
1116         bnexterr 
= cur0
;        /* Process component 0 */ 
1118         cur0 
+= delta
;          /* form error * 3 */ 
1119         errorptr
[0] = (FSERROR
) (bpreverr0 
+ cur0
); 
1120         cur0 
+= delta
;          /* form error * 5 */ 
1121         bpreverr0 
= belowerr0 
+ cur0
; 
1122         belowerr0 
= bnexterr
; 
1123         cur0 
+= delta
;          /* form error * 7 */ 
1124         bnexterr 
= cur1
;        /* Process component 1 */ 
1126         cur1 
+= delta
;          /* form error * 3 */ 
1127         errorptr
[1] = (FSERROR
) (bpreverr1 
+ cur1
); 
1128         cur1 
+= delta
;          /* form error * 5 */ 
1129         bpreverr1 
= belowerr1 
+ cur1
; 
1130         belowerr1 
= bnexterr
; 
1131         cur1 
+= delta
;          /* form error * 7 */ 
1132         bnexterr 
= cur2
;        /* Process component 2 */ 
1134         cur2 
+= delta
;          /* form error * 3 */ 
1135         errorptr
[2] = (FSERROR
) (bpreverr2 
+ cur2
); 
1136         cur2 
+= delta
;          /* form error * 5 */ 
1137         bpreverr2 
= belowerr2 
+ cur2
; 
1138         belowerr2 
= bnexterr
; 
1139         cur2 
+= delta
;          /* form error * 7 */ 
1141       /* At this point curN contains the 7/16 error value to be propagated 
1142        * to the next pixel on the current line, and all the errors for the 
1143        * next line have been shifted over.  We are therefore ready to move on. 
1145       inptr 
+= dir3
;            /* Advance pixel pointers to next column */ 
1147       errorptr 
+= dir3
;         /* advance errorptr to current column */ 
1149     /* Post-loop cleanup: we must unload the final error values into the 
1150      * final fserrors[] entry.  Note we need not unload belowerrN because 
1151      * it is for the dummy column before or after the actual array. 
1153     errorptr
[0] = (FSERROR
) bpreverr0
; /* unload prev errs into array */ 
1154     errorptr
[1] = (FSERROR
) bpreverr1
; 
1155     errorptr
[2] = (FSERROR
) bpreverr2
; 
1161  * Initialize the error-limiting transfer function (lookup table). 
1162  * The raw F-S error computation can potentially compute error values of up to 
1163  * +- MAXJSAMPLE.  But we want the maximum correction applied to a pixel to be 
1164  * much less, otherwise obviously wrong pixels will be created.  (Typical 
1165  * effects include weird fringes at color-area boundaries, isolated bright 
1166  * pixels in a dark area, etc.)  The standard advice for avoiding this problem 
1167  * is to ensure that the "corners" of the color cube are allocated as output 
1168  * colors; then repeated errors in the same direction cannot cause cascading 
1169  * error buildup.  However, that only prevents the error from getting 
1170  * completely out of hand; Aaron Giles reports that error limiting improves 
1171  * the results even with corner colors allocated. 
1172  * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty 
1173  * well, but the smoother transfer function used below is even better.  Thanks 
1174  * to Aaron Giles for this idea. 
1178 init_error_limit (j_decompress_ptr cinfo
) 
1179 /* Allocate and fill in the error_limiter table */ 
1181   my_cquantize_ptr cquantize 
= (my_cquantize_ptr
) cinfo
->cquantize
; 
1185   table 
= (int *) malloc((MAXJSAMPLE
*2+1) * sizeof(int)); 
1186   table 
+= MAXJSAMPLE
;          /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */ 
1187   cquantize
->error_limiter 
= table
; 
1189 #define STEPSIZE ((MAXJSAMPLE+1)/16) 
1190   /* Map errors 1:1 up to +- MAXJSAMPLE/16 */ 
1192   for (in 
= 0; in 
< STEPSIZE
; in
++, out
++) { 
1193     table
[in
] = out
; table
[-in
] = -out
; 
1195   /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */ 
1196   for (; in 
< STEPSIZE
*3; in
++, out 
+= (in
&1) ? 0 : 1) { 
1197     table
[in
] = out
; table
[-in
] = -out
; 
1199   /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */ 
1200   for (; in 
<= MAXJSAMPLE
; in
++) { 
1201     table
[in
] = out
; table
[-in
] = -out
; 
1208  * Finish up at the end of each pass. 
1212 finish_pass1 (j_decompress_ptr cinfo
) 
1214   my_cquantize_ptr cquantize 
= (my_cquantize_ptr
) cinfo
->cquantize
; 
1216   /* Select the representative colors and fill in cinfo->colormap */ 
1217   cinfo
->colormap 
= cquantize
->sv_colormap
; 
1218   select_colors(cinfo
, cquantize
->desired
); 
1219   /* Force next pass to zero the color index table */ 
1220   cquantize
->needs_zeroed 
= true; 
1225 finish_pass2 (j_decompress_ptr cinfo
) 
1232  * Initialize for each processing pass. 
1236 start_pass_2_quant (j_decompress_ptr cinfo
, bool is_pre_scan
) 
1238   my_cquantize_ptr cquantize 
= (my_cquantize_ptr
) cinfo
->cquantize
; 
1239   hist3d histogram 
= cquantize
->histogram
; 
1243     /* Set up method pointers */ 
1244     cquantize
->pub
.color_quantize 
= prescan_quantize
; 
1245     cquantize
->pub
.finish_pass 
= finish_pass1
; 
1246     cquantize
->needs_zeroed 
= true; /* Always zero histogram */ 
1248     /* Set up method pointers */ 
1249     cquantize
->pub
.color_quantize 
= pass2_fs_dither
; 
1250     cquantize
->pub
.finish_pass 
= finish_pass2
; 
1252     /* Make sure color count is acceptable */ 
1253     i 
= cinfo
->actual_number_of_colors
; 
1256       size_t arraysize 
= (size_t) ((cinfo
->output_width 
+ 2) * 
1257                                    (3 * sizeof(FSERROR
))); 
1258       /* Allocate Floyd-Steinberg workspace if we didn't already. */ 
1259       if (cquantize
->fserrors 
== NULL
) 
1260         cquantize
->fserrors 
= (INT16
*) malloc(arraysize
); 
1261       /* Initialize the propagated errors to zero. */ 
1262       memset((void  *) cquantize
->fserrors
, 0, arraysize
); 
1263       /* Make the error-limit table if we didn't already. */ 
1264       if (cquantize
->error_limiter 
== NULL
) 
1265         init_error_limit(cinfo
); 
1266       cquantize
->on_odd_row 
= false; 
1270   /* Zero the histogram or inverse color map, if necessary */ 
1271   if (cquantize
->needs_zeroed
) { 
1272     for (i 
= 0; i 
< HIST_C0_ELEMS
; i
++) { 
1273       memset((void  *) histogram
[i
], 0, 
1274                 HIST_C1_ELEMS
*HIST_C2_ELEMS 
* sizeof(histcell
)); 
1276     cquantize
->needs_zeroed 
= false; 
1282  * Switch to a new external colormap between output passes. 
1286 new_color_map_2_quant (j_decompress_ptr cinfo
) 
1288   my_cquantize_ptr cquantize 
= (my_cquantize_ptr
) cinfo
->cquantize
; 
1290   /* Reset the inverse color map */ 
1291   cquantize
->needs_zeroed 
= true; 
1296  * Module initialization routine for 2-pass color quantization. 
1300 jinit_2pass_quantizer (j_decompress_ptr cinfo
) 
1302   my_cquantize_ptr cquantize
; 
1305   cquantize 
= (my_cquantize_ptr
) malloc(sizeof(my_cquantizer
)); 
1306   cinfo
->cquantize 
= (struct jpeg_color_quantizer 
*) cquantize
; 
1307   cquantize
->pub
.start_pass 
= start_pass_2_quant
; 
1308   cquantize
->pub
.new_color_map 
= new_color_map_2_quant
; 
1309   cquantize
->fserrors 
= NULL
;   /* flag optional arrays not allocated */ 
1310   cquantize
->error_limiter 
= NULL
; 
1313   /* Allocate the histogram/inverse colormap storage */ 
1314   cquantize
->histogram 
= (hist3d
) malloc(HIST_C0_ELEMS 
* sizeof(hist2d
)); 
1315   for (i 
= 0; i 
< HIST_C0_ELEMS
; i
++) { 
1316     cquantize
->histogram
[i
] = (hist2d
) malloc(HIST_C1_ELEMS
*HIST_C2_ELEMS 
* sizeof(histcell
)); 
1318   cquantize
->needs_zeroed 
= true; /* histogram is garbage now */ 
1320   /* Allocate storage for the completed colormap, if required. 
1321    * We do this now since it is  storage and may affect 
1322    * the memory manager's space calculations. 
1325     /* Make sure color count is acceptable */ 
1326     int desired 
= cinfo
->desired_number_of_colors
; 
1328     cquantize
->sv_colormap 
= (JSAMPARRAY
) malloc(sizeof(JSAMPROW
) * 3); 
1329     cquantize
->sv_colormap
[0] = (JSAMPROW
) malloc(sizeof(JSAMPLE
) * desired
); 
1330     cquantize
->sv_colormap
[1] = (JSAMPROW
) malloc(sizeof(JSAMPLE
) * desired
); 
1331     cquantize
->sv_colormap
[2] = (JSAMPROW
) malloc(sizeof(JSAMPLE
) * desired
); 
1333     cquantize
->desired 
= desired
; 
1336   /* Allocate Floyd-Steinberg workspace if necessary. 
1337    * This isn't really needed until pass 2, but again it is  storage. 
1338    * Although we will cope with a later change in dither_mode, 
1339    * we do not promise to honor max_memory_to_use if dither_mode changes. 
1342     cquantize
->fserrors 
= (FSERRPTR
) malloc( 
1343        (size_t) ((cinfo
->output_width 
+ 2) * (3 * sizeof(FSERROR
)))); 
1344     /* Might as well create the error-limiting table too. */ 
1345     init_error_limit(cinfo
); 
1359 prepare_range_limit_table (j_decompress_ptr cinfo
) 
1360 /* Allocate and fill in the sample_range_limit table */ 
1365   table 
= (JSAMPLE 
*) malloc((5 * (MAXJSAMPLE
+1) + CENTERJSAMPLE
) * sizeof(JSAMPLE
)); 
1366   cinfo
->srl_orig 
= table
; 
1367   table 
+= (MAXJSAMPLE
+1);      /* allow negative subscripts of simple table */ 
1368   cinfo
->sample_range_limit 
= table
; 
1369   /* First segment of "simple" table: limit[x] = 0 for x < 0 */ 
1370   memset(table 
- (MAXJSAMPLE
+1), 0, (MAXJSAMPLE
+1) * sizeof(JSAMPLE
)); 
1371   /* Main part of "simple" table: limit[x] = x */ 
1372   for (i 
= 0; i 
<= MAXJSAMPLE
; i
++) 
1373     table
[i
] = (JSAMPLE
) i
; 
1374   table 
+= CENTERJSAMPLE
;       /* Point to where post-IDCT table starts */ 
1375   /* End of simple table, rest of first half of post-IDCT table */ 
1376   for (i 
= CENTERJSAMPLE
; i 
< 2*(MAXJSAMPLE
+1); i
++) 
1377     table
[i
] = MAXJSAMPLE
; 
1378   /* Second half of post-IDCT table */ 
1379   memset(table 
+ (2 * (MAXJSAMPLE
+1)), 0, 
1380           (2 * (MAXJSAMPLE
+1) - CENTERJSAMPLE
) * sizeof(JSAMPLE
)); 
1381   memcpy(table 
+ (4 * (MAXJSAMPLE
+1) - CENTERJSAMPLE
), 
1382           cinfo
->sample_range_limit
, CENTERJSAMPLE 
* sizeof(JSAMPLE
)); 
1392 IMPLEMENT_DYNAMIC_CLASS(wxQuantize
, wxObject
) 
1394 void wxQuantize::DoQuantize(unsigned w
, unsigned h
, unsigned char **in_rows
, unsigned char **out_rows
, 
1395     unsigned char *palette
, int desiredNoColours
) 
1398     my_cquantize_ptr cquantize
; 
1400     dec
.output_width 
= w
; 
1401     dec
.desired_number_of_colors 
= desiredNoColours
; 
1402     prepare_range_limit_table(&dec
); 
1403     jinit_2pass_quantizer(&dec
); 
1404     cquantize 
= (my_cquantize_ptr
) dec
.cquantize
; 
1407     cquantize
->pub
.start_pass(&dec
, true); 
1408     cquantize
->pub
.color_quantize(&dec
, in_rows
, out_rows
, h
); 
1409     cquantize
->pub
.finish_pass(&dec
); 
1411     cquantize
->pub
.start_pass(&dec
, false); 
1412     cquantize
->pub
.color_quantize(&dec
, in_rows
, out_rows
, h
); 
1413     cquantize
->pub
.finish_pass(&dec
); 
1416     for (int i 
= 0; i 
< dec
.desired_number_of_colors
; i
++) { 
1417         palette
[3 * i 
+ 0] = dec
.colormap
[0][i
]; 
1418         palette
[3 * i 
+ 1] = dec
.colormap
[1][i
]; 
1419         palette
[3 * i 
+ 2] = dec
.colormap
[2][i
]; 
1422     for (int ii 
= 0; ii 
< HIST_C0_ELEMS
; ii
++) free(cquantize
->histogram
[ii
]); 
1423     free(cquantize
->histogram
); 
1424     free(dec
.colormap
[0]); 
1425     free(dec
.colormap
[1]); 
1426     free(dec
.colormap
[2]); 
1430     //free(cquantize->error_limiter); 
1431     free((void*)(cquantize
->error_limiter 
- MAXJSAMPLE
)); // To reverse what was done to it 
1433     free(cquantize
->fserrors
); 
1437 // TODO: somehow make use of the Windows system colours, rather than ignoring them for the 
1438 // purposes of quantization. 
1440 bool wxQuantize::Quantize(const wxImage
& src
, wxImage
& dest
, wxPalette
** pPalette
, int desiredNoColours
, 
1441         unsigned char** eightBitData
, int flags
) 
1445     int w 
= src
.GetWidth(); 
1446     int h 
= src
.GetHeight(); 
1448     int windowsSystemColourCount 
= 20; 
1449     int paletteShift 
= 0; 
1451     // Shift the palette up by the number of Windows system colours, 
1453     if (flags 
& wxQUANTIZE_INCLUDE_WINDOWS_COLOURS
) 
1454         paletteShift 
= windowsSystemColourCount
; 
1456     // Make room for the Windows system colours 
1458     if ((flags 
& wxQUANTIZE_INCLUDE_WINDOWS_COLOURS
) && (desiredNoColours 
> (256 - windowsSystemColourCount
))) 
1459         desiredNoColours 
= 256 - windowsSystemColourCount
; 
1462     // create rows info: 
1463     unsigned char **rows 
= new unsigned char *[h
]; 
1464     h 
= src
.GetHeight(), w 
= src
.GetWidth(); 
1465     unsigned char *imgdt 
= src
.GetData(); 
1466     for (i 
= 0; i 
< h
; i
++) 
1467         rows
[i
] = imgdt 
+ 3/*RGB*/ * w 
* i
; 
1469     unsigned char palette
[3*256]; 
1471     // This is the image as represented by palette indexes. 
1472     unsigned char *data8bit 
= new unsigned char[w 
* h
]; 
1473     unsigned char **outrows 
= new unsigned char *[h
]; 
1474     for (i 
= 0; i 
< h
; i
++) 
1475         outrows
[i
] = data8bit 
+ w 
* i
; 
1478     DoQuantize(w
, h
, rows
, outrows
, palette
, desiredNoColours
); 
1483     // palette->RGB(max.256) 
1485     if (flags 
& wxQUANTIZE_FILL_DESTINATION_IMAGE
) 
1490         imgdt 
= dest
.GetData(); 
1491         for (i 
= 0; i 
< w 
* h
; i
++) 
1493             unsigned char c 
= data8bit
[i
]; 
1494             imgdt
[3 * i 
+ 0/*R*/] = palette
[3 * c 
+ 0]; 
1495             imgdt
[3 * i 
+ 1/*G*/] = palette
[3 * c 
+ 1]; 
1496             imgdt
[3 * i 
+ 2/*B*/] = palette
[3 * c 
+ 2]; 
1500     if (eightBitData 
&& (flags 
& wxQUANTIZE_RETURN_8BIT_DATA
)) 
1503         if (flags 
& wxQUANTIZE_INCLUDE_WINDOWS_COLOURS
) 
1505             // We need to shift the palette entries up 
1506             // to make room for the Windows system colours. 
1507             for (i 
= 0; i 
< w 
* h
; i
++) 
1508                 data8bit
[i
] = data8bit
[i
] + paletteShift
; 
1511         *eightBitData 
= data8bit
; 
1516     // Make a wxWindows palette 
1519         unsigned char* r 
= new unsigned char[256]; 
1520         unsigned char* g 
= new unsigned char[256]; 
1521         unsigned char* b 
= new unsigned char[256]; 
1524         // Fill the first 20 entries with Windows system colours 
1525         if (flags 
& wxQUANTIZE_INCLUDE_WINDOWS_COLOURS
) 
1527             HDC hDC 
= ::GetDC(NULL
); 
1528             PALETTEENTRY
* entries 
= new PALETTEENTRY
[windowsSystemColourCount
]; 
1529             ::GetSystemPaletteEntries(hDC
, 0, windowsSystemColourCount
, entries
); 
1530             ::ReleaseDC(NULL
, hDC
); 
1532             for (i 
= 0; i 
< windowsSystemColourCount
; i
++) 
1534                 r
[i
] = entries
[i
].peRed
; 
1535                 g
[i
] = entries
[i
].peGreen
; 
1536                 b
[i
] = entries
[i
].peBlue
; 
1542         for (i 
= 0; i 
< desiredNoColours
; i
++) 
1544             r
[i
+paletteShift
] = palette
[i
*3 + 0]; 
1545             g
[i
+paletteShift
] = palette
[i
*3 + 1]; 
1546             b
[i
+paletteShift
] = palette
[i
*3 + 2]; 
1549         // Blank out any remaining palette entries 
1550         for (i 
= desiredNoColours
+paletteShift
; i 
< 256; i
++) 
1556         *pPalette 
= new wxPalette(256, r
, g
, b
);