2 * Copyright 2005 Ben Hutchings.
4 * This is derived from jquant2.c and parts of jdmaster.c, jmorecfg.h,
5 * jpegint.h and jpeglib.h, from the Independent JPEG Group's software.
6 * Copyright (C) 1991-1998, Thomas G. Lane.
8 * This file contains 2-pass color quantization (color mapping) routines.
9 * These routines provide selection of a custom color map for an image,
10 * followed by mapping of the image to that color map, with optional
11 * Floyd-Steinberg dithering.
12 * It is also possible to use just the second pass to map to an arbitrary
13 * externally-given color map.
15 * Note: ordered dithering is not supported, since there isn't any fast
16 * way to compute intercolor distances; it's unclear that ordered dither's
17 * fundamental assumptions even hold with an irregularly spaced color map.
21 * These definitions cover what would normally be defind in jconfig.h,
22 * jmorecfg.h, jpegint.h and jpeglib.h.
32 * This controls whether an additional alpha channel is expected in the
33 * input buffer. If so, output color 0 is reserved for fully transparent
34 * pixels and the alpha channel is otherwise ignored. That is, only
35 * binary transparency is really supported.
39 typedef uint16_t UINT16;
40 typedef int16_t INT16;
41 typedef int32_t INT32;
44 #define BITS_IN_JSAMPLE 8
45 #define MAXJSAMPLE 255
46 #define CENTERJSAMPLE 128
47 #define GETJSAMPLE(value) ((int) (value))
49 typedef int JDIMENSION;
65 #define JMETHOD(return_type, name, param_list) return_type (* name) param_list
66 #define METHODDEF(return_type) static return_type
67 #define LOCAL(return_type) static return_type
68 #define GLOBAL(return_type) return_type
70 #define TRACEMS1(cinfo, b, message_num, param_1)
72 #define ERREXIT(cinfo, message_num) abort()
73 #define ERREXIT1(cinfo, message_num, param_1) abort()
76 #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
78 #define jzero_far(base, length) memset(base, 0, length)
79 #define MEMZERO(base, length) memset(base, 0, length)
80 #define MEMCOPY(dest, source, length) memcpy(dest, source, length)
82 struct jpeg_decompress_struct {
84 J_DITHER_MODE dither_mode; /* type of color dithering to use */
86 /* Description of actual output image that will be returned to application.
87 * These fields are computed by jpeg_start_decompress().
88 * You can also use jpeg_calc_output_dimensions() to determine these values
89 * in advance of calling jpeg_start_decompress().
91 JDIMENSION output_width; /* scaled image width */
92 JDIMENSION output_height; /* scaled image height */
94 /* When quantizing colors, the output colormap is described by these fields.
95 * The application can supply a colormap by setting colormap non-NULL before
96 * calling jpeg_start_decompress; otherwise a colormap is created during
97 * jpeg_start_decompress or jpeg_start_output.
98 * The map has 3 rows and actual_number_of_colors columns.
100 int actual_number_of_colors; /* number of entries in use */
101 JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
102 JSAMPLE * sample_range_limit; /* table for fast range-limiting */
104 struct jpeg_color_quantizer * cquantize;
107 typedef struct jpeg_decompress_struct * j_decompress_ptr;
108 typedef j_decompress_ptr j_common_ptr;
110 struct jpeg_color_quantizer {
111 JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
112 JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
113 JSAMPARRAY input_buf, JSAMPARRAY output_buf,
115 JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
119 * This module implements the well-known Heckbert paradigm for color
120 * quantization. Most of the ideas used here can be traced back to
121 * Heckbert's seminal paper
122 * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
123 * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
125 * In the first pass over the image, we accumulate a histogram showing the
126 * usage count of each possible color. To keep the histogram to a reasonable
127 * size, we reduce the precision of the input; typical practice is to retain
128 * 5 or 6 bits per color, so that 8 or 4 different input values are counted
129 * in the same histogram cell.
131 * Next, the color-selection step begins with a box representing the whole
132 * color space, and repeatedly splits the "largest" remaining box until we
133 * have as many boxes as desired colors. Then the mean color in each
134 * remaining box becomes one of the possible output colors.
136 * The second pass over the image maps each input pixel to the closest output
137 * color (optionally after applying a Floyd-Steinberg dithering correction).
138 * This mapping is logically trivial, but making it go fast enough requires
141 * Heckbert-style quantizers vary a good deal in their policies for choosing
142 * the "largest" box and deciding where to cut it. The particular policies
143 * used here have proved out well in experimental comparisons, but better ones
146 * In earlier versions of the IJG code, this module quantized in YCbCr color
147 * space, processing the raw upsampled data without a color conversion step.
148 * This allowed the color conversion math to be done only once per colormap
149 * entry, not once per pixel. However, that optimization precluded other
150 * useful optimizations (such as merging color conversion with upsampling)
151 * and it also interfered with desired capabilities such as quantizing to an
152 * externally-supplied colormap. We have therefore abandoned that approach.
153 * The present code works in the post-conversion color space, typically RGB.
155 * To improve the visual quality of the results, we actually work in scaled
156 * RGB space, giving G distances more weight than R, and R in turn more than
157 * B. To do everything in integer math, we must use integer scale factors.
158 * The 2/3/1 scale factors used here correspond loosely to the relative
159 * weights of the colors in the NTSC grayscale equation.
160 * If you want to use this code to quantize a non-RGB color space, you'll
161 * probably need to change these scale factors.
164 #define R_SCALE 2 /* scale R distances by this much */
165 #define G_SCALE 3 /* scale G distances by this much */
166 #define B_SCALE 1 /* and B by this much */
168 /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
169 * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
170 * and B,G,R orders. If you define some other weird order in jmorecfg.h,
171 * you'll get compile errors until you extend this logic. In that case
172 * you'll probably want to tweak the histogram sizes too.
176 #define C0_SCALE R_SCALE
179 #define C0_SCALE B_SCALE
182 #define C1_SCALE G_SCALE
185 #define C2_SCALE R_SCALE
188 #define C2_SCALE B_SCALE
193 * First we have the histogram data structure and routines for creating it.
195 * The number of bits of precision can be adjusted by changing these symbols.
196 * We recommend keeping 6 bits for G and 5 each for R and B.
197 * If you have plenty of memory and cycles, 6 bits all around gives marginally
198 * better results; if you are short of memory, 5 bits all around will save
199 * some space but degrade the results.
200 * To maintain a fully accurate histogram, we'd need to allocate a "long"
201 * (preferably unsigned long) for each cell. In practice this is overkill;
202 * we can get by with 16 bits per cell. Few of the cell counts will overflow,
203 * and clamping those that do overflow to the maximum value will give close-
204 * enough results. This reduces the recommended histogram size from 256Kb
205 * to 128Kb, which is a useful savings on PC-class machines.
206 * (In the second pass the histogram space is re-used for pixel mapping data;
207 * in that capacity, each cell must be able to store zero to the number of
208 * desired colors. 16 bits/cell is plenty for that too.)
209 * Since the JPEG code is intended to run in small memory model on 80x86
210 * machines, we can't just allocate the histogram in one chunk. Instead
211 * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
212 * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
213 * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
214 * on 80x86 machines, the pointer row is in near memory but the actual
215 * arrays are in far memory (same arrangement as we use for image arrays).
218 #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
220 /* These will do the right thing for either R,G,B or B,G,R color order,
221 * but you may not like the results for other color orders.
223 #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
224 #define HIST_C1_BITS 6 /* bits of precision in G histogram */
225 #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
227 /* Number of elements along histogram axes. */
228 #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
229 #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
230 #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
232 /* These are the amounts to shift an input value to get a histogram index. */
233 #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
234 #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
235 #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
238 typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
240 typedef histcell FAR * histptr; /* for pointers to histogram cells */
242 typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
243 typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
244 typedef hist2d * hist3d; /* type for top-level pointer */
247 /* Declarations for Floyd-Steinberg dithering.
249 * Errors are accumulated into the array fserrors[], at a resolution of
250 * 1/16th of a pixel count. The error at a given pixel is propagated
251 * to its not-yet-processed neighbors using the standard F-S fractions,
254 * We work left-to-right on even rows, right-to-left on odd rows.
256 * We can get away with a single array (holding one row's worth of errors)
257 * by using it to store the current row's errors at pixel columns not yet
258 * processed, but the next row's errors at columns already processed. We
259 * need only a few extra variables to hold the errors immediately around the
260 * current column. (If we are lucky, those variables are in registers, but
261 * even if not, they're probably cheaper to access than array elements are.)
263 * The fserrors[] array has (#columns + 2) entries; the extra entry at
264 * each end saves us from special-casing the first and last pixels.
265 * Each entry is three values long, one value for each color component.
267 * Note: on a wide image, we might not have enough room in a PC's near data
268 * segment to hold the error array; so it is allocated with alloc_large.
271 #if BITS_IN_JSAMPLE == 8
272 typedef INT16 FSERROR; /* 16 bits should be enough */
273 typedef int LOCFSERROR; /* use 'int' for calculation temps */
275 typedef INT32 FSERROR; /* may need more than 16 bits */
276 typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
279 typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
282 /* Private subobject */
285 struct jpeg_color_quantizer pub; /* public fields */
287 /* Space for the eventually created colormap is stashed here */
288 JSAMPROW sv_colormap[3]; /* colormap allocated at init time */
289 int desired; /* desired # of colors = size of colormap */
291 /* Variables for accumulating image statistics */
292 hist3d histogram; /* pointer to the histogram */
294 boolean needs_zeroed; /* TRUE if next pass must zero histogram */
296 /* Variables for Floyd-Steinberg dithering */
297 FSERRPTR fserrors; /* accumulated errors */
298 boolean on_odd_row; /* flag to remember which row we are on */
299 int * error_limiter; /* table for clamping the applied error */
302 typedef my_cquantizer * my_cquantize_ptr;
306 * Prescan some rows of pixels.
307 * In this module the prescan simply updates the histogram, which has been
308 * initialized to zeroes by start_pass.
309 * An output_buf parameter is required by the method signature, but no data
310 * is actually output (in fact the buffer controller is probably passing a
315 prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
316 JSAMPARRAY output_buf, int num_rows)
318 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
319 register JSAMPROW ptr;
320 register histptr histp;
321 register hist3d histogram = cquantize->histogram;
324 JDIMENSION width = cinfo->output_width;
326 for (row = 0; row < num_rows; row++) {
327 ptr = input_buf[row];
328 for (col = width; col > 0; col--) {
329 /* ignore transparent pixels */
330 if (!HAS_ALPHA || GETJSAMPLE(ptr[3]) != 0) {
331 /* get pixel value and index into the histogram */
332 histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
333 [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
334 [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
335 /* increment, check for overflow and undo increment if so. */
346 * Next we have the really interesting routines: selection of a colormap
347 * given the completed histogram.
348 * These routines work with a list of "boxes", each representing a rectangular
349 * subset of the input color space (to histogram precision).
353 /* The bounds of the box (inclusive); expressed as histogram indexes */
357 /* The volume (actually 2-norm) of the box */
359 /* The number of nonzero histogram cells within this box */
363 typedef box * boxptr;
367 find_biggest_color_pop (boxptr boxlist, int numboxes)
368 /* Find the splittable box with the largest color population */
369 /* Returns NULL if no splittable boxes remain */
371 register boxptr boxp;
373 register long maxc = 0;
376 for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
377 if (boxp->colorcount > maxc && boxp->volume > 0) {
379 maxc = boxp->colorcount;
387 find_biggest_volume (boxptr boxlist, int numboxes)
388 /* Find the splittable box with the largest (scaled) volume */
389 /* Returns NULL if no splittable boxes remain */
391 register boxptr boxp;
393 register INT32 maxv = 0;
396 for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
397 if (boxp->volume > maxv) {
407 update_box (j_decompress_ptr cinfo, boxptr boxp)
408 /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
409 /* and recompute its volume and population */
411 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
412 hist3d histogram = cquantize->histogram;
415 int c0min,c0max,c1min,c1max,c2min,c2max;
416 INT32 dist0,dist1,dist2;
419 c0min = boxp->c0min; c0max = boxp->c0max;
420 c1min = boxp->c1min; c1max = boxp->c1max;
421 c2min = boxp->c2min; c2max = boxp->c2max;
424 for (c0 = c0min; c0 <= c0max; c0++)
425 for (c1 = c1min; c1 <= c1max; c1++) {
426 histp = & histogram[c0][c1][c2min];
427 for (c2 = c2min; c2 <= c2max; c2++)
429 boxp->c0min = c0min = c0;
435 for (c0 = c0max; c0 >= c0min; c0--)
436 for (c1 = c1min; c1 <= c1max; c1++) {
437 histp = & histogram[c0][c1][c2min];
438 for (c2 = c2min; c2 <= c2max; c2++)
440 boxp->c0max = c0max = c0;
446 for (c1 = c1min; c1 <= c1max; c1++)
447 for (c0 = c0min; c0 <= c0max; c0++) {
448 histp = & histogram[c0][c1][c2min];
449 for (c2 = c2min; c2 <= c2max; c2++)
451 boxp->c1min = c1min = c1;
457 for (c1 = c1max; c1 >= c1min; c1--)
458 for (c0 = c0min; c0 <= c0max; c0++) {
459 histp = & histogram[c0][c1][c2min];
460 for (c2 = c2min; c2 <= c2max; c2++)
462 boxp->c1max = c1max = c1;
468 for (c2 = c2min; c2 <= c2max; c2++)
469 for (c0 = c0min; c0 <= c0max; c0++) {
470 histp = & histogram[c0][c1min][c2];
471 for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
473 boxp->c2min = c2min = c2;
479 for (c2 = c2max; c2 >= c2min; c2--)
480 for (c0 = c0min; c0 <= c0max; c0++) {
481 histp = & histogram[c0][c1min][c2];
482 for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
484 boxp->c2max = c2max = c2;
490 /* Update box volume.
491 * We use 2-norm rather than real volume here; this biases the method
492 * against making long narrow boxes, and it has the side benefit that
493 * a box is splittable iff norm > 0.
494 * Since the differences are expressed in histogram-cell units,
495 * we have to shift back to JSAMPLE units to get consistent distances;
496 * after which, we scale according to the selected distance scale factors.
498 dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
499 dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
500 dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
501 boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
503 /* Now scan remaining volume of box and compute population */
505 for (c0 = c0min; c0 <= c0max; c0++)
506 for (c1 = c1min; c1 <= c1max; c1++) {
507 histp = & histogram[c0][c1][c2min];
508 for (c2 = c2min; c2 <= c2max; c2++, histp++)
513 boxp->colorcount = ccount;
518 median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
520 /* Repeatedly select and split the largest box until we have enough boxes */
524 register boxptr b1,b2;
526 while (numboxes < desired_colors) {
527 /* Select box to split.
528 * Current algorithm: by population for first half, then by volume.
530 if (numboxes*2 <= desired_colors) {
531 b1 = find_biggest_color_pop(boxlist, numboxes);
533 b1 = find_biggest_volume(boxlist, numboxes);
535 if (b1 == NULL) /* no splittable boxes left! */
537 b2 = &boxlist[numboxes]; /* where new box will go */
538 /* Copy the color bounds to the new box. */
539 b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
540 b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
541 /* Choose which axis to split the box on.
542 * Current algorithm: longest scaled axis.
543 * See notes in update_box about scaling distances.
545 c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
546 c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
547 c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
548 /* We want to break any ties in favor of green, then red, blue last.
549 * This code does the right thing for R,G,B or B,G,R color orders only.
553 if (c0 > cmax) { cmax = c0; n = 0; }
554 if (c2 > cmax) { n = 2; }
557 if (c2 > cmax) { cmax = c2; n = 2; }
558 if (c0 > cmax) { n = 0; }
560 /* Choose split point along selected axis, and update box bounds.
561 * Current algorithm: split at halfway point.
562 * (Since the box has been shrunk to minimum volume,
563 * any split will produce two nonempty subboxes.)
564 * Note that lb value is max for lower box, so must be < old max.
568 lb = (b1->c0max + b1->c0min) / 2;
573 lb = (b1->c1max + b1->c1min) / 2;
578 lb = (b1->c2max + b1->c2min) / 2;
583 /* Update stats for boxes */
584 update_box(cinfo, b1);
585 update_box(cinfo, b2);
593 compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
594 /* Compute representative color for a box, put it in colormap[icolor] */
596 /* Current algorithm: mean weighted by pixels (not colors) */
597 /* Note it is important to get the rounding correct! */
598 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
599 hist3d histogram = cquantize->histogram;
602 int c0min,c0max,c1min,c1max,c2min,c2max;
609 c0min = boxp->c0min; c0max = boxp->c0max;
610 c1min = boxp->c1min; c1max = boxp->c1max;
611 c2min = boxp->c2min; c2max = boxp->c2max;
613 for (c0 = c0min; c0 <= c0max; c0++)
614 for (c1 = c1min; c1 <= c1max; c1++) {
615 histp = & histogram[c0][c1][c2min];
616 for (c2 = c2min; c2 <= c2max; c2++) {
617 if ((count = *histp++) != 0) {
619 c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
620 c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
621 c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
627 cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
628 cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
629 cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
631 cinfo->colormap[0][icolor] = 0;
632 cinfo->colormap[1][icolor] = 0;
633 cinfo->colormap[2][icolor] = 0;
639 select_colors (j_decompress_ptr cinfo, int desired_colors)
640 /* Master routine for color selection */
646 /* Allocate workspace for box list */
647 boxlist = (boxptr) malloc(desired_colors * SIZEOF(box));
648 /* Initialize one box containing whole space */
650 boxlist[0].c0min = 0;
651 boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
652 boxlist[0].c1min = 0;
653 boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
654 boxlist[0].c2min = 0;
655 boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
656 /* Shrink it to actually-used volume and set its statistics */
657 update_box(cinfo, & boxlist[0]);
658 /* Perform median-cut to produce final box list */
659 numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
660 /* Compute the representative color for each box, fill colormap */
661 for (i = 0; i < numboxes; i++)
662 compute_color(cinfo, & boxlist[i], i);
663 cinfo->actual_number_of_colors = numboxes;
664 TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
669 * These routines are concerned with the time-critical task of mapping input
670 * colors to the nearest color in the selected colormap.
672 * We re-use the histogram space as an "inverse color map", essentially a
673 * cache for the results of nearest-color searches. All colors within a
674 * histogram cell will be mapped to the same colormap entry, namely the one
675 * closest to the cell's center. This may not be quite the closest entry to
676 * the actual input color, but it's almost as good. A zero in the cache
677 * indicates we haven't found the nearest color for that cell yet; the array
678 * is cleared to zeroes before starting the mapping pass. When we find the
679 * nearest color for a cell, its colormap index plus one is recorded in the
680 * cache for future use. The pass2 scanning routines call fill_inverse_cmap
681 * when they need to use an unfilled entry in the cache.
683 * Our method of efficiently finding nearest colors is based on the "locally
684 * sorted search" idea described by Heckbert and on the incremental distance
685 * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
686 * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
687 * the distances from a given colormap entry to each cell of the histogram can
688 * be computed quickly using an incremental method: the differences between
689 * distances to adjacent cells themselves differ by a constant. This allows a
690 * fairly fast implementation of the "brute force" approach of computing the
691 * distance from every colormap entry to every histogram cell. Unfortunately,
692 * it needs a work array to hold the best-distance-so-far for each histogram
693 * cell (because the inner loop has to be over cells, not colormap entries).
694 * The work array elements have to be INT32s, so the work array would need
695 * 256Kb at our recommended precision. This is not feasible in DOS machines.
697 * To get around these problems, we apply Thomas' method to compute the
698 * nearest colors for only the cells within a small subbox of the histogram.
699 * The work array need be only as big as the subbox, so the memory usage
700 * problem is solved. Furthermore, we need not fill subboxes that are never
701 * referenced in pass2; many images use only part of the color gamut, so a
702 * fair amount of work is saved. An additional advantage of this
703 * approach is that we can apply Heckbert's locality criterion to quickly
704 * eliminate colormap entries that are far away from the subbox; typically
705 * three-fourths of the colormap entries are rejected by Heckbert's criterion,
706 * and we need not compute their distances to individual cells in the subbox.
707 * The speed of this approach is heavily influenced by the subbox size: too
708 * small means too much overhead, too big loses because Heckbert's criterion
709 * can't eliminate as many colormap entries. Empirically the best subbox
710 * size seems to be about 1/512th of the histogram (1/8th in each direction).
712 * Thomas' article also describes a refined method which is asymptotically
713 * faster than the brute-force method, but it is also far more complex and
714 * cannot efficiently be applied to small subboxes. It is therefore not
715 * useful for programs intended to be portable to DOS machines. On machines
716 * with plenty of memory, filling the whole histogram in one shot with Thomas'
717 * refined method might be faster than the present code --- but then again,
718 * it might not be any faster, and it's certainly more complicated.
722 /* log2(histogram cells in update box) for each axis; this can be adjusted */
723 #define BOX_C0_LOG (HIST_C0_BITS-3)
724 #define BOX_C1_LOG (HIST_C1_BITS-3)
725 #define BOX_C2_LOG (HIST_C2_BITS-3)
727 #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
728 #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
729 #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
731 #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
732 #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
733 #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
737 * The next three routines implement inverse colormap filling. They could
738 * all be folded into one big routine, but splitting them up this way saves
739 * some stack space (the mindist[] and bestdist[] arrays need not coexist)
740 * and may allow some compilers to produce better code by registerizing more
741 * inner-loop variables.
745 find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
747 /* Locate the colormap entries close enough to an update box to be candidates
748 * for the nearest entry to some cell(s) in the update box. The update box
749 * is specified by the center coordinates of its first cell. The number of
750 * candidate colormap entries is returned, and their colormap indexes are
751 * placed in colorlist[].
752 * This routine uses Heckbert's "locally sorted search" criterion to select
753 * the colors that need further consideration.
756 int numcolors = cinfo->actual_number_of_colors;
757 int maxc0, maxc1, maxc2;
758 int centerc0, centerc1, centerc2;
760 INT32 minmaxdist, min_dist, max_dist, tdist;
761 INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
763 /* Compute true coordinates of update box's upper corner and center.
764 * Actually we compute the coordinates of the center of the upper-corner
765 * histogram cell, which are the upper bounds of the volume we care about.
766 * Note that since ">>" rounds down, the "center" values may be closer to
767 * min than to max; hence comparisons to them must be "<=", not "<".
769 maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
770 centerc0 = (minc0 + maxc0) >> 1;
771 maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
772 centerc1 = (minc1 + maxc1) >> 1;
773 maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
774 centerc2 = (minc2 + maxc2) >> 1;
776 /* For each color in colormap, find:
777 * 1. its minimum squared-distance to any point in the update box
778 * (zero if color is within update box);
779 * 2. its maximum squared-distance to any point in the update box.
780 * Both of these can be found by considering only the corners of the box.
781 * We save the minimum distance for each color in mindist[];
782 * only the smallest maximum distance is of interest.
784 minmaxdist = 0x7FFFFFFFL;
786 for (i = 0; i < numcolors; i++) {
787 /* We compute the squared-c0-distance term, then add in the other two. */
788 x = GETJSAMPLE(cinfo->colormap[0][i]);
790 tdist = (x - minc0) * C0_SCALE;
791 min_dist = tdist*tdist;
792 tdist = (x - maxc0) * C0_SCALE;
793 max_dist = tdist*tdist;
794 } else if (x > maxc0) {
795 tdist = (x - maxc0) * C0_SCALE;
796 min_dist = tdist*tdist;
797 tdist = (x - minc0) * C0_SCALE;
798 max_dist = tdist*tdist;
800 /* within cell range so no contribution to min_dist */
803 tdist = (x - maxc0) * C0_SCALE;
804 max_dist = tdist*tdist;
806 tdist = (x - minc0) * C0_SCALE;
807 max_dist = tdist*tdist;
811 x = GETJSAMPLE(cinfo->colormap[1][i]);
813 tdist = (x - minc1) * C1_SCALE;
814 min_dist += tdist*tdist;
815 tdist = (x - maxc1) * C1_SCALE;
816 max_dist += tdist*tdist;
817 } else if (x > maxc1) {
818 tdist = (x - maxc1) * C1_SCALE;
819 min_dist += tdist*tdist;
820 tdist = (x - minc1) * C1_SCALE;
821 max_dist += tdist*tdist;
823 /* within cell range so no contribution to min_dist */
825 tdist = (x - maxc1) * C1_SCALE;
826 max_dist += tdist*tdist;
828 tdist = (x - minc1) * C1_SCALE;
829 max_dist += tdist*tdist;
833 x = GETJSAMPLE(cinfo->colormap[2][i]);
835 tdist = (x - minc2) * C2_SCALE;
836 min_dist += tdist*tdist;
837 tdist = (x - maxc2) * C2_SCALE;
838 max_dist += tdist*tdist;
839 } else if (x > maxc2) {
840 tdist = (x - maxc2) * C2_SCALE;
841 min_dist += tdist*tdist;
842 tdist = (x - minc2) * C2_SCALE;
843 max_dist += tdist*tdist;
845 /* within cell range so no contribution to min_dist */
847 tdist = (x - maxc2) * C2_SCALE;
848 max_dist += tdist*tdist;
850 tdist = (x - minc2) * C2_SCALE;
851 max_dist += tdist*tdist;
855 mindist[i] = min_dist; /* save away the results */
856 if (max_dist < minmaxdist)
857 minmaxdist = max_dist;
860 /* Now we know that no cell in the update box is more than minmaxdist
861 * away from some colormap entry. Therefore, only colors that are
862 * within minmaxdist of some part of the box need be considered.
865 for (i = 0; i < numcolors; i++) {
866 if (mindist[i] <= minmaxdist)
867 colorlist[ncolors++] = (JSAMPLE) i;
874 find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
875 int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
876 /* Find the closest colormap entry for each cell in the update box,
877 * given the list of candidate colors prepared by find_nearby_colors.
878 * Return the indexes of the closest entries in the bestcolor[] array.
879 * This routine uses Thomas' incremental distance calculation method to
880 * find the distance from a colormap entry to successive cells in the box.
885 register INT32 * bptr; /* pointer into bestdist[] array */
886 JSAMPLE * cptr; /* pointer into bestcolor[] array */
887 INT32 dist0, dist1; /* initial distance values */
888 register INT32 dist2; /* current distance in inner loop */
889 INT32 xx0, xx1; /* distance increments */
891 INT32 inc0, inc1, inc2; /* initial values for increments */
892 /* This array holds the distance to the nearest-so-far color for each cell */
893 INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
895 /* Initialize best-distance for each cell of the update box */
897 for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
898 *bptr++ = 0x7FFFFFFFL;
900 /* For each color selected by find_nearby_colors,
901 * compute its distance to the center of each cell in the box.
902 * If that's less than best-so-far, update best distance and color number.
905 /* Nominal steps between cell centers ("x" in Thomas article) */
906 #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
907 #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
908 #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
910 for (i = 0; i < numcolors; i++) {
911 icolor = GETJSAMPLE(colorlist[i]);
912 /* Compute (square of) distance from minc0/c1/c2 to this color */
913 inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
915 inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
917 inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
919 /* Form the initial difference increments */
920 inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
921 inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
922 inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
923 /* Now loop over all cells in box, updating distance per Thomas method */
927 for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
930 for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
933 for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
936 *cptr = (JSAMPLE) icolor;
939 xx2 += 2 * STEP_C2 * STEP_C2;
944 xx1 += 2 * STEP_C1 * STEP_C1;
947 xx0 += 2 * STEP_C0 * STEP_C0;
954 fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
955 /* Fill the inverse-colormap entries in the update box that contains */
956 /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
957 /* we can fill as many others as we wish.) */
959 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
960 hist3d histogram = cquantize->histogram;
961 int minc0, minc1, minc2; /* lower left corner of update box */
963 register JSAMPLE * cptr; /* pointer into bestcolor[] array */
964 register histptr cachep; /* pointer into main cache array */
965 /* This array lists the candidate colormap indexes. */
966 JSAMPLE colorlist[MAXNUMCOLORS];
967 int numcolors; /* number of candidate colors */
968 /* This array holds the actually closest colormap index for each cell. */
969 JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
971 /* Convert cell coordinates to update box ID */
976 /* Compute true coordinates of update box's origin corner.
977 * Actually we compute the coordinates of the center of the corner
978 * histogram cell, which are the lower bounds of the volume we care about.
980 minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
981 minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
982 minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
984 /* Determine which colormap entries are close enough to be candidates
985 * for the nearest entry to some cell in the update box.
987 numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
989 /* Determine the actually nearest colors. */
990 find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
993 /* Save the best color numbers (plus 1) in the main cache array */
994 c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
998 for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
999 for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
1000 cachep = & histogram[c0+ic0][c1+ic1][c2];
1001 for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
1002 *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
1010 * Map some rows of pixels to the output colormapped representation.
1014 pass2_no_dither (j_decompress_ptr cinfo,
1015 JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
1016 /* This version performs no dithering */
1018 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1019 hist3d histogram = cquantize->histogram;
1020 register JSAMPROW inptr, outptr;
1021 register histptr cachep;
1022 register int c0, c1, c2;
1025 JDIMENSION width = cinfo->output_width;
1027 for (row = 0; row < num_rows; row++) {
1028 inptr = input_buf[row];
1029 outptr = output_buf[row];
1030 for (col = width; col > 0; col--) {
1031 /* get pixel value and index into the cache */
1032 c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
1033 c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
1034 c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
1035 if (HAS_ALPHA && *inptr++ == 0) {
1038 cachep = & histogram[c0][c1][c2];
1039 /* If we have not seen this color before, find nearest colormap entry */
1040 /* and update the cache */
1042 fill_inverse_cmap(cinfo, c0,c1,c2);
1043 /* Now emit the colormap index for this cell */
1044 *outptr++ = (JSAMPLE) (*cachep - 1 + HAS_ALPHA);
1052 pass2_fs_dither (j_decompress_ptr cinfo,
1053 JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
1054 /* This version performs Floyd-Steinberg dithering */
1056 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1057 hist3d histogram = cquantize->histogram;
1058 register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
1059 LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
1060 LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
1061 register FSERRPTR errorptr; /* => fserrors[] at column before current */
1062 JSAMPROW inptr; /* => current input pixel */
1063 JSAMPROW outptr; /* => current output pixel */
1065 int dir; /* +1 or -1 depending on direction */
1066 int dir_comp; /* 3*dir or 4*dir, for advancing inptr */
1067 int dir3; /* 3*dir, for advancing errorptr */
1070 JDIMENSION width = cinfo->output_width;
1071 JSAMPLE *range_limit = cinfo->sample_range_limit;
1072 int *error_limit = cquantize->error_limiter;
1073 JSAMPROW colormap0 = cinfo->colormap[0];
1074 JSAMPROW colormap1 = cinfo->colormap[1];
1075 JSAMPROW colormap2 = cinfo->colormap[2];
1078 for (row = 0; row < num_rows; row++) {
1079 inptr = input_buf[row];
1080 outptr = output_buf[row];
1081 if (cquantize->on_odd_row) {
1082 /* work right to left in this row */
1083 inptr += (width-1) * (3+HAS_ALPHA); /* so point to rightmost pixel */
1087 dir_comp = -3-HAS_ALPHA;
1088 errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
1089 cquantize->on_odd_row = FALSE; /* flip for next time */
1091 /* work left to right in this row */
1094 dir_comp = 3+HAS_ALPHA;
1095 errorptr = cquantize->fserrors; /* => entry before first real column */
1096 cquantize->on_odd_row = TRUE; /* flip for next time */
1098 /* Preset error values: no error propagated to first pixel from left */
1099 cur0 = cur1 = cur2 = 0;
1100 /* and no error propagated to row below yet */
1101 belowerr0 = belowerr1 = belowerr2 = 0;
1102 bpreverr0 = bpreverr1 = bpreverr2 = 0;
1104 for (col = width; col > 0; col--) {
1105 if (HAS_ALPHA && inptr[3] == 0) {
1106 /* Output transparent pixel and reset error values. */
1108 cur0 = cur1 = cur2 = 0;
1110 /* curN holds the error propagated from the previous pixel on the
1111 * current line. Add the error propagated from the previous line
1112 * to form the complete error correction term for this pixel, and
1113 * round the error term (which is expressed * 16) to an integer.
1114 * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
1115 * for either sign of the error value.
1116 * Note: errorptr points to *previous* column's array entry.
1118 cur0 = RIGHT_SHIFT(cur0 + errorptr[dir_comp+0] + 8, 4);
1119 cur1 = RIGHT_SHIFT(cur1 + errorptr[dir_comp+1] + 8, 4);
1120 cur2 = RIGHT_SHIFT(cur2 + errorptr[dir_comp+2] + 8, 4);
1121 /* Limit the error using transfer function set by init_error_limit.
1122 * See comments with init_error_limit for rationale.
1124 cur0 = error_limit[cur0];
1125 cur1 = error_limit[cur1];
1126 cur2 = error_limit[cur2];
1127 /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
1128 * The maximum error is +- MAXJSAMPLE (or less with error limiting);
1129 * this sets the required size of the range_limit array.
1131 cur0 += GETJSAMPLE(inptr[0]);
1132 cur1 += GETJSAMPLE(inptr[1]);
1133 cur2 += GETJSAMPLE(inptr[2]);
1134 cur0 = GETJSAMPLE(range_limit[cur0]);
1135 cur1 = GETJSAMPLE(range_limit[cur1]);
1136 cur2 = GETJSAMPLE(range_limit[cur2]);
1137 /* Index into the cache with adjusted pixel value */
1138 cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
1139 /* If we have not seen this color before, find nearest colormap */
1140 /* entry and update the cache */
1142 fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
1143 /* Now emit the colormap index for this cell */
1144 { register int pixcode = *cachep - 1;
1145 *outptr = (JSAMPLE) pixcode + HAS_ALPHA;
1146 /* Compute representation error for this pixel */
1147 cur0 -= GETJSAMPLE(colormap0[pixcode]);
1148 cur1 -= GETJSAMPLE(colormap1[pixcode]);
1149 cur2 -= GETJSAMPLE(colormap2[pixcode]);
1151 /* Compute error fractions to be propagated to adjacent pixels.
1152 * Add these into the running sums, and simultaneously shift the
1153 * next-line error sums left by 1 column.
1155 { register LOCFSERROR bnexterr, delta;
1157 bnexterr = cur0; /* Process component 0 */
1159 cur0 += delta; /* form error * 3 */
1160 errorptr[0] = (FSERROR) (bpreverr0 + cur0);
1161 cur0 += delta; /* form error * 5 */
1162 bpreverr0 = belowerr0 + cur0;
1163 belowerr0 = bnexterr;
1164 cur0 += delta; /* form error * 7 */
1165 bnexterr = cur1; /* Process component 1 */
1167 cur1 += delta; /* form error * 3 */
1168 errorptr[1] = (FSERROR) (bpreverr1 + cur1);
1169 cur1 += delta; /* form error * 5 */
1170 bpreverr1 = belowerr1 + cur1;
1171 belowerr1 = bnexterr;
1172 cur1 += delta; /* form error * 7 */
1173 bnexterr = cur2; /* Process component 2 */
1175 cur2 += delta; /* form error * 3 */
1176 errorptr[2] = (FSERROR) (bpreverr2 + cur2);
1177 cur2 += delta; /* form error * 5 */
1178 bpreverr2 = belowerr2 + cur2;
1179 belowerr2 = bnexterr;
1180 cur2 += delta; /* form error * 7 */
1182 /* At this point curN contains the 7/16 error value to be propagated
1183 * to the next pixel on the current line, and all the errors for the
1184 * next line have been shifted over. We are therefore ready to move on.
1187 inptr += dir_comp; /* Advance pixel pointers to next column */
1189 errorptr += dir3; /* advance errorptr to current column */
1191 /* Post-loop cleanup: we must unload the final error values into the
1192 * final fserrors[] entry. Note we need not unload belowerrN because
1193 * it is for the dummy column before or after the actual array.
1195 errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
1196 errorptr[1] = (FSERROR) bpreverr1;
1197 errorptr[2] = (FSERROR) bpreverr2;
1203 * Initialize the error-limiting transfer function (lookup table).
1204 * The raw F-S error computation can potentially compute error values of up to
1205 * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
1206 * much less, otherwise obviously wrong pixels will be created. (Typical
1207 * effects include weird fringes at color-area boundaries, isolated bright
1208 * pixels in a dark area, etc.) The standard advice for avoiding this problem
1209 * is to ensure that the "corners" of the color cube are allocated as output
1210 * colors; then repeated errors in the same direction cannot cause cascading
1211 * error buildup. However, that only prevents the error from getting
1212 * completely out of hand; Aaron Giles reports that error limiting improves
1213 * the results even with corner colors allocated.
1214 * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
1215 * well, but the smoother transfer function used below is even better. Thanks
1216 * to Aaron Giles for this idea.
1220 init_error_limit (j_decompress_ptr cinfo)
1221 /* Allocate and fill in the error_limiter table */
1223 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1227 table = (int *) malloc((MAXJSAMPLE*2+1) * SIZEOF(int));
1228 table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
1229 cquantize->error_limiter = table;
1231 #define STEPSIZE ((MAXJSAMPLE+1)/16)
1232 /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
1234 for (in = 0; in < STEPSIZE; in++, out++) {
1235 table[in] = out; table[-in] = -out;
1237 /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
1238 for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
1239 table[in] = out; table[-in] = -out;
1241 /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
1242 for (; in <= MAXJSAMPLE; in++) {
1243 table[in] = out; table[-in] = -out;
1250 * Finish up at the end of each pass.
1254 finish_pass1 (j_decompress_ptr cinfo)
1256 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1258 /* Select the representative colors and fill in cinfo->colormap */
1259 cinfo->colormap = cquantize->sv_colormap;
1260 select_colors(cinfo, cquantize->desired);
1261 /* Force next pass to zero the color index table */
1262 cquantize->needs_zeroed = TRUE;
1267 finish_pass2 (j_decompress_ptr cinfo)
1274 * Initialize for each processing pass.
1278 start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
1280 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1281 hist3d histogram = cquantize->histogram;
1285 /* Set up method pointers */
1286 cquantize->pub.color_quantize = prescan_quantize;
1287 cquantize->pub.finish_pass = finish_pass1;
1288 cquantize->needs_zeroed = TRUE; /* Always zero histogram */
1290 /* Set up method pointers */
1291 if (cinfo->dither_mode == JDITHER_FS)
1292 cquantize->pub.color_quantize = pass2_fs_dither;
1294 cquantize->pub.color_quantize = pass2_no_dither;
1295 cquantize->pub.finish_pass = finish_pass2;
1297 /* Make sure color count is acceptable */
1298 i = cinfo->actual_number_of_colors;
1300 ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
1301 if (i > MAXNUMCOLORS)
1302 ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
1304 if (cinfo->dither_mode == JDITHER_FS) {
1305 size_t arraysize = (size_t) ((cinfo->output_width + 2) *
1306 (3 * SIZEOF(FSERROR)));
1307 /* Allocate Floyd-Steinberg workspace if we didn't already. */
1308 if (cquantize->fserrors == NULL)
1309 cquantize->fserrors = (FSERRPTR) malloc(arraysize);
1310 /* Initialize the propagated errors to zero. */
1311 jzero_far((void FAR *) cquantize->fserrors, arraysize);
1312 /* Make the error-limit table if we didn't already. */
1313 if (cquantize->error_limiter == NULL)
1314 init_error_limit(cinfo);
1315 cquantize->on_odd_row = FALSE;
1319 /* Zero the histogram or inverse color map, if necessary */
1320 if (cquantize->needs_zeroed) {
1321 for (i = 0; i < HIST_C0_ELEMS; i++) {
1322 jzero_far((void FAR *) histogram[i],
1323 HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
1325 cquantize->needs_zeroed = FALSE;
1331 * Several decompression processes need to range-limit values to the range
1332 * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
1333 * due to noise introduced by quantization, roundoff error, etc. These
1334 * processes are inner loops and need to be as fast as possible. On most
1335 * machines, particularly CPUs with pipelines or instruction prefetch,
1336 * a (subscript-check-less) C table lookup
1337 * x = sample_range_limit[x];
1338 * is faster than explicit tests
1340 * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
1341 * These processes all use a common table prepared by the routine below.
1343 * For most steps we can mathematically guarantee that the initial value
1344 * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
1345 * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
1346 * limiting step (just after the IDCT), a wildly out-of-range value is
1347 * possible if the input data is corrupt. To avoid any chance of indexing
1348 * off the end of memory and getting a bad-pointer trap, we perform the
1349 * post-IDCT limiting thus:
1350 * x = range_limit[x & MASK];
1351 * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
1352 * samples. Under normal circumstances this is more than enough range and
1353 * a correct output will be generated; with bogus input data the mask will
1354 * cause wraparound, and we will safely generate a bogus-but-in-range output.
1355 * For the post-IDCT step, we want to convert the data from signed to unsigned
1356 * representation by adding CENTERJSAMPLE at the same time that we limit it.
1357 * So the post-IDCT limiting table ends up looking like this:
1358 * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
1359 * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
1360 * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
1361 * 0,1,...,CENTERJSAMPLE-1
1362 * Negative inputs select values from the upper half of the table after
1365 * We can save some space by overlapping the start of the post-IDCT table
1366 * with the simpler range limiting table. The post-IDCT table begins at
1367 * sample_range_limit + CENTERJSAMPLE.
1369 * Note that the table is allocated in near data space on PCs; it's small
1370 * enough and used often enough to justify this.
1374 prepare_range_limit_table (j_decompress_ptr cinfo)
1375 /* Allocate and fill in the sample_range_limit table */
1380 table = (JSAMPLE *) malloc(
1381 (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
1382 table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
1383 cinfo->sample_range_limit = table;
1384 /* First segment of "simple" table: limit[x] = 0 for x < 0 */
1385 MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
1386 /* Main part of "simple" table: limit[x] = x */
1387 for (i = 0; i <= MAXJSAMPLE; i++)
1388 table[i] = (JSAMPLE) i;
1389 table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
1390 /* End of simple table, rest of first half of post-IDCT table */
1391 for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
1392 table[i] = MAXJSAMPLE;
1393 /* Second half of post-IDCT table */
1394 MEMZERO(table + (2 * (MAXJSAMPLE+1)),
1395 (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
1396 MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
1397 cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
1401 void quantize (JSAMPARRAY input_buf,
1402 JSAMPARRAY output_buf,
1403 int width, int height,
1404 J_DITHER_MODE dither_mode,
1405 int desired /*number_of_colors*/,
1406 unsigned int * output_colors)
1408 struct jpeg_decompress_struct cinfo_buf = {}, * cinfo;
1409 my_cquantizer cquantize_buf = {}, * cquantize;
1414 cinfo->dither_mode = dither_mode;
1415 cinfo->output_width = width;
1416 cinfo->output_height = height;
1417 prepare_range_limit_table(cinfo);
1419 cquantize = &cquantize_buf;
1420 cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
1421 cquantize->pub.start_pass = start_pass_2_quant;
1422 cquantize->fserrors = NULL; /* flag optional arrays not allocated */
1423 cquantize->error_limiter = NULL;
1425 /* Allocate the histogram/inverse colormap storage */
1426 cquantize->histogram = (hist3d) malloc(HIST_C0_ELEMS * SIZEOF(hist2d));
1427 for (i = 0; i < HIST_C0_ELEMS; i++) {
1428 cquantize->histogram[i] = (hist2d) malloc(
1429 HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
1432 /* Allocate storage for the completed colormap, if required.
1434 if (desired < 1+HAS_ALPHA)
1435 ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1+HAS_ALPHA);
1436 /* Make sure colormap indexes can be represented by JSAMPLEs */
1437 if (desired > MAXNUMCOLORS)
1438 ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
1439 desired -= HAS_ALPHA;
1440 cquantize->sv_colormap[0] = malloc((JDIMENSION) desired * (JDIMENSION) 3);
1441 cquantize->sv_colormap[1] = cquantize->sv_colormap[0] + (JDIMENSION) desired;
1442 cquantize->sv_colormap[2] = cquantize->sv_colormap[1] + (JDIMENSION) desired;
1443 cquantize->desired = desired;
1445 for (pass_flag = 1; pass_flag >= 0; --pass_flag) {
1446 start_pass_2_quant(cinfo, pass_flag);
1447 cquantize->pub.color_quantize(cinfo, input_buf, output_buf, height);
1448 cquantize->pub.finish_pass(cinfo);
1452 output_colors[0] = 0;
1453 for (i = 0; i != desired; ++i) {
1454 output_colors[HAS_ALPHA+i] = (0xFF000000
1455 + (cquantize->sv_colormap[2][i] << 16)
1456 + (cquantize->sv_colormap[1][i] << 8)
1457 + cquantize->sv_colormap[0][i]);
1460 if (cinfo->sample_range_limit)
1461 free(cinfo->sample_range_limit - (MAXJSAMPLE+1));
1462 free(cquantize->sv_colormap[0]);
1463 if (cquantize->histogram) {
1464 for (i = 0; i < HIST_C0_ELEMS; i++)
1465 free(cquantize->histogram[i]);
1466 free(cquantize->histogram);
1468 free(cquantize->fserrors);
1469 if (cquantize->error_limiter)
1470 free(cquantize->error_limiter - MAXJSAMPLE);