blob: 9ce3ff36337f3271f9a64000eacaa9ffec14d85f [file] [log] [blame]
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001/*
2 * jquant2.c
3 *
Thomas G. Lane489583f1996-02-07 00:00:00 +00004 * Copyright (C) 1991-1996, Thomas G. Lane.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00005 * This file is part of the Independent JPEG Group's software.
6 * For conditions of distribution and use, see the accompanying README file.
7 *
8 * This file contains 2-pass color quantization (color mapping) routines.
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00009 * These routines provide selection of a custom color map for an image,
10 * followed by mapping of the image to that color map, with optional
11 * Floyd-Steinberg dithering.
12 * It is also possible to use just the second pass to map to an arbitrary
13 * externally-given color map.
14 *
15 * Note: ordered dithering is not supported, since there isn't any fast
16 * way to compute intercolor distances; it's unclear that ordered dither's
17 * fundamental assumptions even hold with an irregularly spaced color map.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000018 */
19
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000020#define JPEG_INTERNALS
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000021#include "jinclude.h"
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000022#include "jpeglib.h"
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000023
24#ifdef QUANT_2PASS_SUPPORTED
25
26
27/*
Thomas G. Lane4a6b7301992-03-17 00:00:00 +000028 * This module implements the well-known Heckbert paradigm for color
29 * quantization. Most of the ideas used here can be traced back to
30 * Heckbert's seminal paper
31 * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
32 * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
33 *
34 * In the first pass over the image, we accumulate a histogram showing the
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000035 * usage count of each possible color. To keep the histogram to a reasonable
Thomas G. Lane4a6b7301992-03-17 00:00:00 +000036 * size, we reduce the precision of the input; typical practice is to retain
37 * 5 or 6 bits per color, so that 8 or 4 different input values are counted
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000038 * in the same histogram cell.
39 *
40 * Next, the color-selection step begins with a box representing the whole
41 * color space, and repeatedly splits the "largest" remaining box until we
42 * have as many boxes as desired colors. Then the mean color in each
43 * remaining box becomes one of the possible output colors.
44 *
Thomas G. Lane4a6b7301992-03-17 00:00:00 +000045 * The second pass over the image maps each input pixel to the closest output
46 * color (optionally after applying a Floyd-Steinberg dithering correction).
47 * This mapping is logically trivial, but making it go fast enough requires
48 * considerable care.
49 *
50 * Heckbert-style quantizers vary a good deal in their policies for choosing
51 * the "largest" box and deciding where to cut it. The particular policies
52 * used here have proved out well in experimental comparisons, but better ones
53 * may yet be found.
54 *
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000055 * In earlier versions of the IJG code, this module quantized in YCbCr color
56 * space, processing the raw upsampled data without a color conversion step.
57 * This allowed the color conversion math to be done only once per colormap
58 * entry, not once per pixel. However, that optimization precluded other
59 * useful optimizations (such as merging color conversion with upsampling)
60 * and it also interfered with desired capabilities such as quantizing to an
61 * externally-supplied colormap. We have therefore abandoned that approach.
62 * The present code works in the post-conversion color space, typically RGB.
63 *
64 * To improve the visual quality of the results, we actually work in scaled
65 * RGB space, giving G distances more weight than R, and R in turn more than
66 * B. To do everything in integer math, we must use integer scale factors.
67 * The 2/3/1 scale factors used here correspond loosely to the relative
68 * weights of the colors in the NTSC grayscale equation.
69 * If you want to use this code to quantize a non-RGB color space, you'll
70 * probably need to change these scale factors.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000071 */
72
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000073#define R_SCALE 2 /* scale R distances by this much */
74#define G_SCALE 3 /* scale G distances by this much */
75#define B_SCALE 1 /* and B by this much */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +000076
DRCf25c0712009-04-03 12:00:51 +000077static const int c_scales[3]={R_SCALE, G_SCALE, B_SCALE};
78#define C0_SCALE c_scales[rgb_red[cinfo->out_color_space]]
79#define C1_SCALE c_scales[rgb_green[cinfo->out_color_space]]
80#define C2_SCALE c_scales[rgb_blue[cinfo->out_color_space]]
Thomas G. Lane4a6b7301992-03-17 00:00:00 +000081
82/*
83 * First we have the histogram data structure and routines for creating it.
84 *
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000085 * The number of bits of precision can be adjusted by changing these symbols.
86 * We recommend keeping 6 bits for G and 5 each for R and B.
Thomas G. Lane4a6b7301992-03-17 00:00:00 +000087 * If you have plenty of memory and cycles, 6 bits all around gives marginally
88 * better results; if you are short of memory, 5 bits all around will save
89 * some space but degrade the results.
90 * To maintain a fully accurate histogram, we'd need to allocate a "long"
91 * (preferably unsigned long) for each cell. In practice this is overkill;
92 * we can get by with 16 bits per cell. Few of the cell counts will overflow,
93 * and clamping those that do overflow to the maximum value will give close-
94 * enough results. This reduces the recommended histogram size from 256Kb
95 * to 128Kb, which is a useful savings on PC-class machines.
96 * (In the second pass the histogram space is re-used for pixel mapping data;
97 * in that capacity, each cell must be able to store zero to the number of
98 * desired colors. 16 bits/cell is plenty for that too.)
99 * Since the JPEG code is intended to run in small memory model on 80x86
100 * machines, we can't just allocate the histogram in one chunk. Instead
101 * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000102 * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
103 * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000104 * on 80x86 machines, the pointer row is in near memory but the actual
105 * arrays are in far memory (same arrangement as we use for image arrays).
106 */
107
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000108#define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000109
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000110/* These will do the right thing for either R,G,B or B,G,R color order,
111 * but you may not like the results for other color orders.
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000112 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000113#define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
114#define HIST_C1_BITS 6 /* bits of precision in G histogram */
115#define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000116
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000117/* Number of elements along histogram axes. */
118#define HIST_C0_ELEMS (1<<HIST_C0_BITS)
119#define HIST_C1_ELEMS (1<<HIST_C1_BITS)
120#define HIST_C2_ELEMS (1<<HIST_C2_BITS)
121
122/* These are the amounts to shift an input value to get a histogram index. */
123#define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
124#define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
125#define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000126
127
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000128typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000129
130typedef histcell FAR * histptr; /* for pointers to histogram cells */
131
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000132typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
133typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000134typedef hist2d * hist3d; /* type for top-level pointer */
135
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000136
137/* Declarations for Floyd-Steinberg dithering.
138 *
139 * Errors are accumulated into the array fserrors[], at a resolution of
140 * 1/16th of a pixel count. The error at a given pixel is propagated
141 * to its not-yet-processed neighbors using the standard F-S fractions,
142 * ... (here) 7/16
143 * 3/16 5/16 1/16
144 * We work left-to-right on even rows, right-to-left on odd rows.
145 *
146 * We can get away with a single array (holding one row's worth of errors)
147 * by using it to store the current row's errors at pixel columns not yet
148 * processed, but the next row's errors at columns already processed. We
149 * need only a few extra variables to hold the errors immediately around the
150 * current column. (If we are lucky, those variables are in registers, but
151 * even if not, they're probably cheaper to access than array elements are.)
152 *
153 * The fserrors[] array has (#columns + 2) entries; the extra entry at
154 * each end saves us from special-casing the first and last pixels.
155 * Each entry is three values long, one value for each color component.
156 *
157 * Note: on a wide image, we might not have enough room in a PC's near data
158 * segment to hold the error array; so it is allocated with alloc_large.
159 */
160
161#if BITS_IN_JSAMPLE == 8
162typedef INT16 FSERROR; /* 16 bits should be enough */
163typedef int LOCFSERROR; /* use 'int' for calculation temps */
164#else
165typedef INT32 FSERROR; /* may need more than 16 bits */
166typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
167#endif
168
169typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
170
171
172/* Private subobject */
173
174typedef struct {
175 struct jpeg_color_quantizer pub; /* public fields */
176
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000177 /* Space for the eventually created colormap is stashed here */
178 JSAMPARRAY sv_colormap; /* colormap allocated at init time */
179 int desired; /* desired # of colors = size of colormap */
180
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000181 /* Variables for accumulating image statistics */
182 hist3d histogram; /* pointer to the histogram */
183
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000184 boolean needs_zeroed; /* TRUE if next pass must zero histogram */
185
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000186 /* Variables for Floyd-Steinberg dithering */
187 FSERRPTR fserrors; /* accumulated errors */
188 boolean on_odd_row; /* flag to remember which row we are on */
189 int * error_limiter; /* table for clamping the applied error */
190} my_cquantizer;
191
192typedef my_cquantizer * my_cquantize_ptr;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000193
194
195/*
196 * Prescan some rows of pixels.
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000197 * In this module the prescan simply updates the histogram, which has been
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000198 * initialized to zeroes by start_pass.
199 * An output_buf parameter is required by the method signature, but no data
200 * is actually output (in fact the buffer controller is probably passing a
201 * NULL pointer).
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000202 */
203
Thomas G. Lane489583f1996-02-07 00:00:00 +0000204METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000205prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
206 JSAMPARRAY output_buf, int num_rows)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000207{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000208 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
209 register JSAMPROW ptr;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000210 register histptr histp;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000211 register hist3d histogram = cquantize->histogram;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000212 int row;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000213 JDIMENSION col;
214 JDIMENSION width = cinfo->output_width;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000215
216 for (row = 0; row < num_rows; row++) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000217 ptr = input_buf[row];
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000218 for (col = width; col > 0; col--) {
219 /* get pixel value and index into the histogram */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000220 histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
221 [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
222 [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000223 /* increment, check for overflow and undo increment if so. */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000224 if (++(*histp) <= 0)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000225 (*histp)--;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000226 ptr += 3;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000227 }
228 }
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000229}
230
231
232/*
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000233 * Next we have the really interesting routines: selection of a colormap
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000234 * given the completed histogram.
235 * These routines work with a list of "boxes", each representing a rectangular
236 * subset of the input color space (to histogram precision).
237 */
238
239typedef struct {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000240 /* The bounds of the box (inclusive); expressed as histogram indexes */
241 int c0min, c0max;
242 int c1min, c1max;
243 int c2min, c2max;
244 /* The volume (actually 2-norm) of the box */
245 INT32 volume;
246 /* The number of nonzero histogram cells within this box */
247 long colorcount;
248} box;
249
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000250typedef box * boxptr;
251
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000252
Thomas G. Lane489583f1996-02-07 00:00:00 +0000253LOCAL(boxptr)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000254find_biggest_color_pop (boxptr boxlist, int numboxes)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000255/* Find the splittable box with the largest color population */
256/* Returns NULL if no splittable boxes remain */
257{
258 register boxptr boxp;
259 register int i;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000260 register long maxc = 0;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000261 boxptr which = NULL;
262
263 for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000264 if (boxp->colorcount > maxc && boxp->volume > 0) {
265 which = boxp;
266 maxc = boxp->colorcount;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000267 }
268 }
269 return which;
270}
271
272
Thomas G. Lane489583f1996-02-07 00:00:00 +0000273LOCAL(boxptr)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000274find_biggest_volume (boxptr boxlist, int numboxes)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000275/* Find the splittable box with the largest (scaled) volume */
276/* Returns NULL if no splittable boxes remain */
277{
278 register boxptr boxp;
279 register int i;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000280 register INT32 maxv = 0;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000281 boxptr which = NULL;
282
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000283 for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000284 if (boxp->volume > maxv) {
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000285 which = boxp;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000286 maxv = boxp->volume;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000287 }
288 }
289 return which;
290}
291
292
Thomas G. Lane489583f1996-02-07 00:00:00 +0000293LOCAL(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000294update_box (j_decompress_ptr cinfo, boxptr boxp)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000295/* Shrink the min/max bounds of a box to enclose only nonzero elements, */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000296/* and recompute its volume and population */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000297{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000298 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
299 hist3d histogram = cquantize->histogram;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000300 histptr histp;
301 int c0,c1,c2;
302 int c0min,c0max,c1min,c1max,c2min,c2max;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000303 INT32 dist0,dist1,dist2;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000304 long ccount;
305
306 c0min = boxp->c0min; c0max = boxp->c0max;
307 c1min = boxp->c1min; c1max = boxp->c1max;
308 c2min = boxp->c2min; c2max = boxp->c2max;
309
310 if (c0max > c0min)
311 for (c0 = c0min; c0 <= c0max; c0++)
312 for (c1 = c1min; c1 <= c1max; c1++) {
313 histp = & histogram[c0][c1][c2min];
314 for (c2 = c2min; c2 <= c2max; c2++)
315 if (*histp++ != 0) {
316 boxp->c0min = c0min = c0;
317 goto have_c0min;
318 }
319 }
320 have_c0min:
321 if (c0max > c0min)
322 for (c0 = c0max; c0 >= c0min; c0--)
323 for (c1 = c1min; c1 <= c1max; c1++) {
324 histp = & histogram[c0][c1][c2min];
325 for (c2 = c2min; c2 <= c2max; c2++)
326 if (*histp++ != 0) {
327 boxp->c0max = c0max = c0;
328 goto have_c0max;
329 }
330 }
331 have_c0max:
332 if (c1max > c1min)
333 for (c1 = c1min; c1 <= c1max; c1++)
334 for (c0 = c0min; c0 <= c0max; c0++) {
335 histp = & histogram[c0][c1][c2min];
336 for (c2 = c2min; c2 <= c2max; c2++)
337 if (*histp++ != 0) {
338 boxp->c1min = c1min = c1;
339 goto have_c1min;
340 }
341 }
342 have_c1min:
343 if (c1max > c1min)
344 for (c1 = c1max; c1 >= c1min; c1--)
345 for (c0 = c0min; c0 <= c0max; c0++) {
346 histp = & histogram[c0][c1][c2min];
347 for (c2 = c2min; c2 <= c2max; c2++)
348 if (*histp++ != 0) {
349 boxp->c1max = c1max = c1;
350 goto have_c1max;
351 }
352 }
353 have_c1max:
354 if (c2max > c2min)
355 for (c2 = c2min; c2 <= c2max; c2++)
356 for (c0 = c0min; c0 <= c0max; c0++) {
357 histp = & histogram[c0][c1min][c2];
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000358 for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000359 if (*histp != 0) {
360 boxp->c2min = c2min = c2;
361 goto have_c2min;
362 }
363 }
364 have_c2min:
365 if (c2max > c2min)
366 for (c2 = c2max; c2 >= c2min; c2--)
367 for (c0 = c0min; c0 <= c0max; c0++) {
368 histp = & histogram[c0][c1min][c2];
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000369 for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000370 if (*histp != 0) {
371 boxp->c2max = c2max = c2;
372 goto have_c2max;
373 }
374 }
375 have_c2max:
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000376
377 /* Update box volume.
378 * We use 2-norm rather than real volume here; this biases the method
379 * against making long narrow boxes, and it has the side benefit that
380 * a box is splittable iff norm > 0.
381 * Since the differences are expressed in histogram-cell units,
382 * we have to shift back to JSAMPLE units to get consistent distances;
383 * after which, we scale according to the selected distance scale factors.
384 */
385 dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
386 dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
387 dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
388 boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000389
390 /* Now scan remaining volume of box and compute population */
391 ccount = 0;
392 for (c0 = c0min; c0 <= c0max; c0++)
393 for (c1 = c1min; c1 <= c1max; c1++) {
394 histp = & histogram[c0][c1][c2min];
395 for (c2 = c2min; c2 <= c2max; c2++, histp++)
396 if (*histp != 0) {
397 ccount++;
398 }
399 }
400 boxp->colorcount = ccount;
401}
402
403
Thomas G. Lane489583f1996-02-07 00:00:00 +0000404LOCAL(int)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000405median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
406 int desired_colors)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000407/* Repeatedly select and split the largest box until we have enough boxes */
408{
409 int n,lb;
410 int c0,c1,c2,cmax;
411 register boxptr b1,b2;
412
413 while (numboxes < desired_colors) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000414 /* Select box to split.
415 * Current algorithm: by population for first half, then by volume.
416 */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000417 if (numboxes*2 <= desired_colors) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000418 b1 = find_biggest_color_pop(boxlist, numboxes);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000419 } else {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000420 b1 = find_biggest_volume(boxlist, numboxes);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000421 }
422 if (b1 == NULL) /* no splittable boxes left! */
423 break;
424 b2 = &boxlist[numboxes]; /* where new box will go */
425 /* Copy the color bounds to the new box. */
426 b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
427 b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
428 /* Choose which axis to split the box on.
429 * Current algorithm: longest scaled axis.
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000430 * See notes in update_box about scaling distances.
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000431 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000432 c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
433 c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
434 c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
435 /* We want to break any ties in favor of green, then red, blue last.
436 * This code does the right thing for R,G,B or B,G,R color orders only.
437 */
DRCf25c0712009-04-03 12:00:51 +0000438 if (rgb_red[cinfo->out_color_space] == 0) {
439 cmax = c1; n = 1;
440 if (c0 > cmax) { cmax = c0; n = 0; }
441 if (c2 > cmax) { n = 2; }
442 }
443 else {
444 cmax = c1; n = 1;
445 if (c2 > cmax) { cmax = c2; n = 2; }
446 if (c0 > cmax) { n = 0; }
447 }
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000448 /* Choose split point along selected axis, and update box bounds.
449 * Current algorithm: split at halfway point.
450 * (Since the box has been shrunk to minimum volume,
451 * any split will produce two nonempty subboxes.)
452 * Note that lb value is max for lower box, so must be < old max.
453 */
454 switch (n) {
455 case 0:
456 lb = (b1->c0max + b1->c0min) / 2;
457 b1->c0max = lb;
458 b2->c0min = lb+1;
459 break;
460 case 1:
461 lb = (b1->c1max + b1->c1min) / 2;
462 b1->c1max = lb;
463 b2->c1min = lb+1;
464 break;
465 case 2:
466 lb = (b1->c2max + b1->c2min) / 2;
467 b1->c2max = lb;
468 b2->c2min = lb+1;
469 break;
470 }
471 /* Update stats for boxes */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000472 update_box(cinfo, b1);
473 update_box(cinfo, b2);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000474 numboxes++;
475 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000476 return numboxes;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000477}
478
479
Thomas G. Lane489583f1996-02-07 00:00:00 +0000480LOCAL(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000481compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
482/* Compute representative color for a box, put it in colormap[icolor] */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000483{
484 /* Current algorithm: mean weighted by pixels (not colors) */
485 /* Note it is important to get the rounding correct! */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000486 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
487 hist3d histogram = cquantize->histogram;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000488 histptr histp;
489 int c0,c1,c2;
490 int c0min,c0max,c1min,c1max,c2min,c2max;
491 long count;
492 long total = 0;
493 long c0total = 0;
494 long c1total = 0;
495 long c2total = 0;
496
497 c0min = boxp->c0min; c0max = boxp->c0max;
498 c1min = boxp->c1min; c1max = boxp->c1max;
499 c2min = boxp->c2min; c2max = boxp->c2max;
500
501 for (c0 = c0min; c0 <= c0max; c0++)
502 for (c1 = c1min; c1 <= c1max; c1++) {
503 histp = & histogram[c0][c1][c2min];
504 for (c2 = c2min; c2 <= c2max; c2++) {
505 if ((count = *histp++) != 0) {
506 total += count;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000507 c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
508 c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
509 c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000510 }
511 }
512 }
513
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000514 cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
515 cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
516 cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000517}
518
519
Thomas G. Lane489583f1996-02-07 00:00:00 +0000520LOCAL(void)
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000521select_colors (j_decompress_ptr cinfo, int desired_colors)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000522/* Master routine for color selection */
523{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000524 boxptr boxlist;
525 int numboxes;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000526 int i;
527
528 /* Allocate workspace for box list */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000529 boxlist = (boxptr) (*cinfo->mem->alloc_small)
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000530 ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000531 /* Initialize one box containing whole space */
532 numboxes = 1;
533 boxlist[0].c0min = 0;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000534 boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000535 boxlist[0].c1min = 0;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000536 boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000537 boxlist[0].c2min = 0;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000538 boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000539 /* Shrink it to actually-used volume and set its statistics */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000540 update_box(cinfo, & boxlist[0]);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000541 /* Perform median-cut to produce final box list */
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000542 numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000543 /* Compute the representative color for each box, fill colormap */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000544 for (i = 0; i < numboxes; i++)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000545 compute_color(cinfo, & boxlist[i], i);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000546 cinfo->actual_number_of_colors = numboxes;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000547 TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000548}
549
550
551/*
552 * These routines are concerned with the time-critical task of mapping input
553 * colors to the nearest color in the selected colormap.
554 *
555 * We re-use the histogram space as an "inverse color map", essentially a
556 * cache for the results of nearest-color searches. All colors within a
557 * histogram cell will be mapped to the same colormap entry, namely the one
558 * closest to the cell's center. This may not be quite the closest entry to
559 * the actual input color, but it's almost as good. A zero in the cache
560 * indicates we haven't found the nearest color for that cell yet; the array
561 * is cleared to zeroes before starting the mapping pass. When we find the
562 * nearest color for a cell, its colormap index plus one is recorded in the
563 * cache for future use. The pass2 scanning routines call fill_inverse_cmap
564 * when they need to use an unfilled entry in the cache.
565 *
566 * Our method of efficiently finding nearest colors is based on the "locally
567 * sorted search" idea described by Heckbert and on the incremental distance
568 * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
569 * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
570 * the distances from a given colormap entry to each cell of the histogram can
571 * be computed quickly using an incremental method: the differences between
572 * distances to adjacent cells themselves differ by a constant. This allows a
573 * fairly fast implementation of the "brute force" approach of computing the
574 * distance from every colormap entry to every histogram cell. Unfortunately,
575 * it needs a work array to hold the best-distance-so-far for each histogram
576 * cell (because the inner loop has to be over cells, not colormap entries).
577 * The work array elements have to be INT32s, so the work array would need
578 * 256Kb at our recommended precision. This is not feasible in DOS machines.
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000579 *
580 * To get around these problems, we apply Thomas' method to compute the
581 * nearest colors for only the cells within a small subbox of the histogram.
582 * The work array need be only as big as the subbox, so the memory usage
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000583 * problem is solved. Furthermore, we need not fill subboxes that are never
584 * referenced in pass2; many images use only part of the color gamut, so a
585 * fair amount of work is saved. An additional advantage of this
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000586 * approach is that we can apply Heckbert's locality criterion to quickly
587 * eliminate colormap entries that are far away from the subbox; typically
588 * three-fourths of the colormap entries are rejected by Heckbert's criterion,
589 * and we need not compute their distances to individual cells in the subbox.
590 * The speed of this approach is heavily influenced by the subbox size: too
591 * small means too much overhead, too big loses because Heckbert's criterion
592 * can't eliminate as many colormap entries. Empirically the best subbox
593 * size seems to be about 1/512th of the histogram (1/8th in each direction).
594 *
595 * Thomas' article also describes a refined method which is asymptotically
596 * faster than the brute-force method, but it is also far more complex and
597 * cannot efficiently be applied to small subboxes. It is therefore not
598 * useful for programs intended to be portable to DOS machines. On machines
599 * with plenty of memory, filling the whole histogram in one shot with Thomas'
600 * refined method might be faster than the present code --- but then again,
601 * it might not be any faster, and it's certainly more complicated.
602 */
603
604
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000605/* log2(histogram cells in update box) for each axis; this can be adjusted */
606#define BOX_C0_LOG (HIST_C0_BITS-3)
607#define BOX_C1_LOG (HIST_C1_BITS-3)
608#define BOX_C2_LOG (HIST_C2_BITS-3)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000609
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000610#define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
611#define BOX_C1_ELEMS (1<<BOX_C1_LOG)
612#define BOX_C2_ELEMS (1<<BOX_C2_LOG)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000613
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000614#define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
615#define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
616#define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000617
618
619/*
620 * The next three routines implement inverse colormap filling. They could
621 * all be folded into one big routine, but splitting them up this way saves
622 * some stack space (the mindist[] and bestdist[] arrays need not coexist)
623 * and may allow some compilers to produce better code by registerizing more
624 * inner-loop variables.
625 */
626
Thomas G. Lane489583f1996-02-07 00:00:00 +0000627LOCAL(int)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000628find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000629 JSAMPLE colorlist[])
630/* Locate the colormap entries close enough to an update box to be candidates
631 * for the nearest entry to some cell(s) in the update box. The update box
632 * is specified by the center coordinates of its first cell. The number of
633 * candidate colormap entries is returned, and their colormap indexes are
634 * placed in colorlist[].
635 * This routine uses Heckbert's "locally sorted search" criterion to select
636 * the colors that need further consideration.
637 */
638{
639 int numcolors = cinfo->actual_number_of_colors;
640 int maxc0, maxc1, maxc2;
641 int centerc0, centerc1, centerc2;
642 int i, x, ncolors;
643 INT32 minmaxdist, min_dist, max_dist, tdist;
644 INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
645
646 /* Compute true coordinates of update box's upper corner and center.
647 * Actually we compute the coordinates of the center of the upper-corner
648 * histogram cell, which are the upper bounds of the volume we care about.
649 * Note that since ">>" rounds down, the "center" values may be closer to
650 * min than to max; hence comparisons to them must be "<=", not "<".
651 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000652 maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000653 centerc0 = (minc0 + maxc0) >> 1;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000654 maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000655 centerc1 = (minc1 + maxc1) >> 1;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000656 maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000657 centerc2 = (minc2 + maxc2) >> 1;
658
659 /* For each color in colormap, find:
660 * 1. its minimum squared-distance to any point in the update box
661 * (zero if color is within update box);
662 * 2. its maximum squared-distance to any point in the update box.
663 * Both of these can be found by considering only the corners of the box.
664 * We save the minimum distance for each color in mindist[];
665 * only the smallest maximum distance is of interest.
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000666 */
667 minmaxdist = 0x7FFFFFFFL;
668
669 for (i = 0; i < numcolors; i++) {
670 /* We compute the squared-c0-distance term, then add in the other two. */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000671 x = GETJSAMPLE(cinfo->colormap[0][i]);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000672 if (x < minc0) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000673 tdist = (x - minc0) * C0_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000674 min_dist = tdist*tdist;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000675 tdist = (x - maxc0) * C0_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000676 max_dist = tdist*tdist;
677 } else if (x > maxc0) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000678 tdist = (x - maxc0) * C0_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000679 min_dist = tdist*tdist;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000680 tdist = (x - minc0) * C0_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000681 max_dist = tdist*tdist;
682 } else {
683 /* within cell range so no contribution to min_dist */
684 min_dist = 0;
685 if (x <= centerc0) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000686 tdist = (x - maxc0) * C0_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000687 max_dist = tdist*tdist;
688 } else {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000689 tdist = (x - minc0) * C0_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000690 max_dist = tdist*tdist;
691 }
692 }
693
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000694 x = GETJSAMPLE(cinfo->colormap[1][i]);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000695 if (x < minc1) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000696 tdist = (x - minc1) * C1_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000697 min_dist += tdist*tdist;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000698 tdist = (x - maxc1) * C1_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000699 max_dist += tdist*tdist;
700 } else if (x > maxc1) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000701 tdist = (x - maxc1) * C1_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000702 min_dist += tdist*tdist;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000703 tdist = (x - minc1) * C1_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000704 max_dist += tdist*tdist;
705 } else {
706 /* within cell range so no contribution to min_dist */
707 if (x <= centerc1) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000708 tdist = (x - maxc1) * C1_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000709 max_dist += tdist*tdist;
710 } else {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000711 tdist = (x - minc1) * C1_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000712 max_dist += tdist*tdist;
713 }
714 }
715
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000716 x = GETJSAMPLE(cinfo->colormap[2][i]);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000717 if (x < minc2) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000718 tdist = (x - minc2) * C2_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000719 min_dist += tdist*tdist;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000720 tdist = (x - maxc2) * C2_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000721 max_dist += tdist*tdist;
722 } else if (x > maxc2) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000723 tdist = (x - maxc2) * C2_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000724 min_dist += tdist*tdist;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000725 tdist = (x - minc2) * C2_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000726 max_dist += tdist*tdist;
727 } else {
728 /* within cell range so no contribution to min_dist */
729 if (x <= centerc2) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000730 tdist = (x - maxc2) * C2_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000731 max_dist += tdist*tdist;
732 } else {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000733 tdist = (x - minc2) * C2_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000734 max_dist += tdist*tdist;
735 }
736 }
737
738 mindist[i] = min_dist; /* save away the results */
739 if (max_dist < minmaxdist)
740 minmaxdist = max_dist;
741 }
742
743 /* Now we know that no cell in the update box is more than minmaxdist
744 * away from some colormap entry. Therefore, only colors that are
745 * within minmaxdist of some part of the box need be considered.
746 */
747 ncolors = 0;
748 for (i = 0; i < numcolors; i++) {
749 if (mindist[i] <= minmaxdist)
750 colorlist[ncolors++] = (JSAMPLE) i;
751 }
752 return ncolors;
753}
754
755
Thomas G. Lane489583f1996-02-07 00:00:00 +0000756LOCAL(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000757find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000758 int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
759/* Find the closest colormap entry for each cell in the update box,
760 * given the list of candidate colors prepared by find_nearby_colors.
761 * Return the indexes of the closest entries in the bestcolor[] array.
762 * This routine uses Thomas' incremental distance calculation method to
763 * find the distance from a colormap entry to successive cells in the box.
764 */
765{
766 int ic0, ic1, ic2;
767 int i, icolor;
768 register INT32 * bptr; /* pointer into bestdist[] array */
769 JSAMPLE * cptr; /* pointer into bestcolor[] array */
770 INT32 dist0, dist1; /* initial distance values */
771 register INT32 dist2; /* current distance in inner loop */
772 INT32 xx0, xx1; /* distance increments */
773 register INT32 xx2;
774 INT32 inc0, inc1, inc2; /* initial values for increments */
775 /* This array holds the distance to the nearest-so-far color for each cell */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000776 INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000777
778 /* Initialize best-distance for each cell of the update box */
779 bptr = bestdist;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000780 for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000781 *bptr++ = 0x7FFFFFFFL;
782
783 /* For each color selected by find_nearby_colors,
784 * compute its distance to the center of each cell in the box.
785 * If that's less than best-so-far, update best distance and color number.
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000786 */
787
788 /* Nominal steps between cell centers ("x" in Thomas article) */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000789#define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
790#define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
791#define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000792
793 for (i = 0; i < numcolors; i++) {
794 icolor = GETJSAMPLE(colorlist[i]);
795 /* Compute (square of) distance from minc0/c1/c2 to this color */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000796 inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000797 dist0 = inc0*inc0;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000798 inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000799 dist0 += inc1*inc1;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000800 inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000801 dist0 += inc2*inc2;
802 /* Form the initial difference increments */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000803 inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
804 inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
805 inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000806 /* Now loop over all cells in box, updating distance per Thomas method */
807 bptr = bestdist;
808 cptr = bestcolor;
809 xx0 = inc0;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000810 for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000811 dist1 = dist0;
812 xx1 = inc1;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000813 for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000814 dist2 = dist1;
815 xx2 = inc2;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000816 for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000817 if (dist2 < *bptr) {
818 *bptr = dist2;
819 *cptr = (JSAMPLE) icolor;
820 }
821 dist2 += xx2;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000822 xx2 += 2 * STEP_C2 * STEP_C2;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000823 bptr++;
824 cptr++;
825 }
826 dist1 += xx1;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000827 xx1 += 2 * STEP_C1 * STEP_C1;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000828 }
829 dist0 += xx0;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000830 xx0 += 2 * STEP_C0 * STEP_C0;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000831 }
832 }
833}
834
835
Thomas G. Lane489583f1996-02-07 00:00:00 +0000836LOCAL(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000837fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000838/* Fill the inverse-colormap entries in the update box that contains */
839/* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
840/* we can fill as many others as we wish.) */
841{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000842 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
843 hist3d histogram = cquantize->histogram;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000844 int minc0, minc1, minc2; /* lower left corner of update box */
845 int ic0, ic1, ic2;
846 register JSAMPLE * cptr; /* pointer into bestcolor[] array */
847 register histptr cachep; /* pointer into main cache array */
848 /* This array lists the candidate colormap indexes. */
849 JSAMPLE colorlist[MAXNUMCOLORS];
850 int numcolors; /* number of candidate colors */
851 /* This array holds the actually closest colormap index for each cell. */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000852 JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000853
854 /* Convert cell coordinates to update box ID */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000855 c0 >>= BOX_C0_LOG;
856 c1 >>= BOX_C1_LOG;
857 c2 >>= BOX_C2_LOG;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000858
859 /* Compute true coordinates of update box's origin corner.
860 * Actually we compute the coordinates of the center of the corner
861 * histogram cell, which are the lower bounds of the volume we care about.
862 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000863 minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
864 minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
865 minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000866
867 /* Determine which colormap entries are close enough to be candidates
868 * for the nearest entry to some cell in the update box.
869 */
870 numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
871
872 /* Determine the actually nearest colors. */
873 find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
874 bestcolor);
875
876 /* Save the best color numbers (plus 1) in the main cache array */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000877 c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
878 c1 <<= BOX_C1_LOG;
879 c2 <<= BOX_C2_LOG;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000880 cptr = bestcolor;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000881 for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
882 for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000883 cachep = & histogram[c0+ic0][c1+ic1][c2];
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000884 for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000885 *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
886 }
887 }
888 }
889}
890
891
892/*
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000893 * Map some rows of pixels to the output colormapped representation.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000894 */
895
Thomas G. Lane489583f1996-02-07 00:00:00 +0000896METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000897pass2_no_dither (j_decompress_ptr cinfo,
898 JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000899/* This version performs no dithering */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000900{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000901 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
902 hist3d histogram = cquantize->histogram;
903 register JSAMPROW inptr, outptr;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000904 register histptr cachep;
905 register int c0, c1, c2;
906 int row;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000907 JDIMENSION col;
908 JDIMENSION width = cinfo->output_width;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000909
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000910 for (row = 0; row < num_rows; row++) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000911 inptr = input_buf[row];
912 outptr = output_buf[row];
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000913 for (col = width; col > 0; col--) {
914 /* get pixel value and index into the cache */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000915 c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
916 c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
917 c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000918 cachep = & histogram[c0][c1][c2];
919 /* If we have not seen this color before, find nearest colormap entry */
920 /* and update the cache */
921 if (*cachep == 0)
922 fill_inverse_cmap(cinfo, c0,c1,c2);
923 /* Now emit the colormap index for this cell */
924 *outptr++ = (JSAMPLE) (*cachep - 1);
925 }
926 }
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000927}
928
929
Thomas G. Lane489583f1996-02-07 00:00:00 +0000930METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000931pass2_fs_dither (j_decompress_ptr cinfo,
932 JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000933/* This version performs Floyd-Steinberg dithering */
934{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000935 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
936 hist3d histogram = cquantize->histogram;
Thomas G. Lanecc7150e1993-02-18 00:00:00 +0000937 register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
938 LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
939 LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
940 register FSERRPTR errorptr; /* => fserrors[] at column before current */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000941 JSAMPROW inptr; /* => current input pixel */
Thomas G. Lanecc7150e1993-02-18 00:00:00 +0000942 JSAMPROW outptr; /* => current output pixel */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000943 histptr cachep;
Thomas G. Lanecc7150e1993-02-18 00:00:00 +0000944 int dir; /* +1 or -1 depending on direction */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000945 int dir3; /* 3*dir, for advancing inptr & errorptr */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000946 int row;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000947 JDIMENSION col;
948 JDIMENSION width = cinfo->output_width;
Thomas G. Lane88aeed41992-12-10 00:00:00 +0000949 JSAMPLE *range_limit = cinfo->sample_range_limit;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000950 int *error_limit = cquantize->error_limiter;
951 JSAMPROW colormap0 = cinfo->colormap[0];
952 JSAMPROW colormap1 = cinfo->colormap[1];
953 JSAMPROW colormap2 = cinfo->colormap[2];
Thomas G. Lane88aeed41992-12-10 00:00:00 +0000954 SHIFT_TEMPS
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000955
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000956 for (row = 0; row < num_rows; row++) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000957 inptr = input_buf[row];
958 outptr = output_buf[row];
959 if (cquantize->on_odd_row) {
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000960 /* work right to left in this row */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000961 inptr += (width-1) * 3; /* so point to rightmost pixel */
962 outptr += width-1;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000963 dir = -1;
Thomas G. Lanecc7150e1993-02-18 00:00:00 +0000964 dir3 = -3;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000965 errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
966 cquantize->on_odd_row = FALSE; /* flip for next time */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000967 } else {
968 /* work left to right in this row */
969 dir = 1;
Thomas G. Lanecc7150e1993-02-18 00:00:00 +0000970 dir3 = 3;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000971 errorptr = cquantize->fserrors; /* => entry before first real column */
972 cquantize->on_odd_row = TRUE; /* flip for next time */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000973 }
Thomas G. Lanecc7150e1993-02-18 00:00:00 +0000974 /* Preset error values: no error propagated to first pixel from left */
975 cur0 = cur1 = cur2 = 0;
976 /* and no error propagated to row below yet */
977 belowerr0 = belowerr1 = belowerr2 = 0;
978 bpreverr0 = bpreverr1 = bpreverr2 = 0;
979
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000980 for (col = width; col > 0; col--) {
Thomas G. Lanecc7150e1993-02-18 00:00:00 +0000981 /* curN holds the error propagated from the previous pixel on the
982 * current line. Add the error propagated from the previous line
983 * to form the complete error correction term for this pixel, and
984 * round the error term (which is expressed * 16) to an integer.
Thomas G. Lane88aeed41992-12-10 00:00:00 +0000985 * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
Thomas G. Lanecc7150e1993-02-18 00:00:00 +0000986 * for either sign of the error value.
987 * Note: errorptr points to *previous* column's array entry.
Thomas G. Lane88aeed41992-12-10 00:00:00 +0000988 */
Thomas G. Lanecc7150e1993-02-18 00:00:00 +0000989 cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
990 cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
991 cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000992 /* Limit the error using transfer function set by init_error_limit.
993 * See comments with init_error_limit for rationale.
Thomas G. Lanecc7150e1993-02-18 00:00:00 +0000994 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000995 cur0 = error_limit[cur0];
996 cur1 = error_limit[cur1];
997 cur2 = error_limit[cur2];
998 /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
999 * The maximum error is +- MAXJSAMPLE (or less with error limiting);
1000 * this sets the required size of the range_limit array.
1001 */
1002 cur0 += GETJSAMPLE(inptr[0]);
1003 cur1 += GETJSAMPLE(inptr[1]);
1004 cur2 += GETJSAMPLE(inptr[2]);
Thomas G. Lanecc7150e1993-02-18 00:00:00 +00001005 cur0 = GETJSAMPLE(range_limit[cur0]);
1006 cur1 = GETJSAMPLE(range_limit[cur1]);
1007 cur2 = GETJSAMPLE(range_limit[cur2]);
Thomas G. Lane88aeed41992-12-10 00:00:00 +00001008 /* Index into the cache with adjusted pixel value */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001009 cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001010 /* If we have not seen this color before, find nearest colormap */
1011 /* entry and update the cache */
1012 if (*cachep == 0)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001013 fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001014 /* Now emit the colormap index for this cell */
Thomas G. Lanecc7150e1993-02-18 00:00:00 +00001015 { register int pixcode = *cachep - 1;
1016 *outptr = (JSAMPLE) pixcode;
1017 /* Compute representation error for this pixel */
1018 cur0 -= GETJSAMPLE(colormap0[pixcode]);
1019 cur1 -= GETJSAMPLE(colormap1[pixcode]);
1020 cur2 -= GETJSAMPLE(colormap2[pixcode]);
1021 }
1022 /* Compute error fractions to be propagated to adjacent pixels.
1023 * Add these into the running sums, and simultaneously shift the
1024 * next-line error sums left by 1 column.
1025 */
1026 { register LOCFSERROR bnexterr, delta;
1027
1028 bnexterr = cur0; /* Process component 0 */
1029 delta = cur0 * 2;
1030 cur0 += delta; /* form error * 3 */
1031 errorptr[0] = (FSERROR) (bpreverr0 + cur0);
1032 cur0 += delta; /* form error * 5 */
1033 bpreverr0 = belowerr0 + cur0;
1034 belowerr0 = bnexterr;
1035 cur0 += delta; /* form error * 7 */
1036 bnexterr = cur1; /* Process component 1 */
1037 delta = cur1 * 2;
1038 cur1 += delta; /* form error * 3 */
1039 errorptr[1] = (FSERROR) (bpreverr1 + cur1);
1040 cur1 += delta; /* form error * 5 */
1041 bpreverr1 = belowerr1 + cur1;
1042 belowerr1 = bnexterr;
1043 cur1 += delta; /* form error * 7 */
1044 bnexterr = cur2; /* Process component 2 */
1045 delta = cur2 * 2;
1046 cur2 += delta; /* form error * 3 */
1047 errorptr[2] = (FSERROR) (bpreverr2 + cur2);
1048 cur2 += delta; /* form error * 5 */
1049 bpreverr2 = belowerr2 + cur2;
1050 belowerr2 = bnexterr;
1051 cur2 += delta; /* form error * 7 */
1052 }
1053 /* At this point curN contains the 7/16 error value to be propagated
1054 * to the next pixel on the current line, and all the errors for the
1055 * next line have been shifted over. We are therefore ready to move on.
1056 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001057 inptr += dir3; /* Advance pixel pointers to next column */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001058 outptr += dir;
Thomas G. Lanecc7150e1993-02-18 00:00:00 +00001059 errorptr += dir3; /* advance errorptr to current column */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001060 }
Thomas G. Lanecc7150e1993-02-18 00:00:00 +00001061 /* Post-loop cleanup: we must unload the final error values into the
1062 * final fserrors[] entry. Note we need not unload belowerrN because
1063 * it is for the dummy column before or after the actual array.
1064 */
1065 errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
1066 errorptr[1] = (FSERROR) bpreverr1;
1067 errorptr[2] = (FSERROR) bpreverr2;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001068 }
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001069}
1070
1071
1072/*
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001073 * Initialize the error-limiting transfer function (lookup table).
1074 * The raw F-S error computation can potentially compute error values of up to
1075 * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
1076 * much less, otherwise obviously wrong pixels will be created. (Typical
1077 * effects include weird fringes at color-area boundaries, isolated bright
1078 * pixels in a dark area, etc.) The standard advice for avoiding this problem
1079 * is to ensure that the "corners" of the color cube are allocated as output
1080 * colors; then repeated errors in the same direction cannot cause cascading
1081 * error buildup. However, that only prevents the error from getting
1082 * completely out of hand; Aaron Giles reports that error limiting improves
1083 * the results even with corner colors allocated.
1084 * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
1085 * well, but the smoother transfer function used below is even better. Thanks
1086 * to Aaron Giles for this idea.
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001087 */
1088
Thomas G. Lane489583f1996-02-07 00:00:00 +00001089LOCAL(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001090init_error_limit (j_decompress_ptr cinfo)
1091/* Allocate and fill in the error_limiter table */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001092{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001093 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1094 int * table;
1095 int in, out;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001096
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001097 table = (int *) (*cinfo->mem->alloc_small)
1098 ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
1099 table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
1100 cquantize->error_limiter = table;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001101
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001102#define STEPSIZE ((MAXJSAMPLE+1)/16)
1103 /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
1104 out = 0;
1105 for (in = 0; in < STEPSIZE; in++, out++) {
1106 table[in] = out; table[-in] = -out;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001107 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001108 /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
1109 for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
1110 table[in] = out; table[-in] = -out;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001111 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001112 /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
1113 for (; in <= MAXJSAMPLE; in++) {
1114 table[in] = out; table[-in] = -out;
1115 }
1116#undef STEPSIZE
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001117}
1118
1119
1120/*
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001121 * Finish up at the end of each pass.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001122 */
1123
Thomas G. Lane489583f1996-02-07 00:00:00 +00001124METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001125finish_pass1 (j_decompress_ptr cinfo)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001126{
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001127 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1128
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001129 /* Select the representative colors and fill in cinfo->colormap */
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001130 cinfo->colormap = cquantize->sv_colormap;
1131 select_colors(cinfo, cquantize->desired);
1132 /* Force next pass to zero the color index table */
1133 cquantize->needs_zeroed = TRUE;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001134}
1135
1136
Thomas G. Lane489583f1996-02-07 00:00:00 +00001137METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001138finish_pass2 (j_decompress_ptr cinfo)
1139{
1140 /* no work */
1141}
1142
1143
1144/*
1145 * Initialize for each processing pass.
1146 */
1147
Thomas G. Lane489583f1996-02-07 00:00:00 +00001148METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001149start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
1150{
1151 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1152 hist3d histogram = cquantize->histogram;
1153 int i;
1154
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001155 /* Only F-S dithering or no dithering is supported. */
1156 /* If user asks for ordered dither, give him F-S. */
1157 if (cinfo->dither_mode != JDITHER_NONE)
1158 cinfo->dither_mode = JDITHER_FS;
1159
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001160 if (is_pre_scan) {
1161 /* Set up method pointers */
1162 cquantize->pub.color_quantize = prescan_quantize;
1163 cquantize->pub.finish_pass = finish_pass1;
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001164 cquantize->needs_zeroed = TRUE; /* Always zero histogram */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001165 } else {
1166 /* Set up method pointers */
1167 if (cinfo->dither_mode == JDITHER_FS)
1168 cquantize->pub.color_quantize = pass2_fs_dither;
1169 else
1170 cquantize->pub.color_quantize = pass2_no_dither;
1171 cquantize->pub.finish_pass = finish_pass2;
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001172
1173 /* Make sure color count is acceptable */
1174 i = cinfo->actual_number_of_colors;
1175 if (i < 1)
1176 ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
1177 if (i > MAXNUMCOLORS)
1178 ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
1179
1180 if (cinfo->dither_mode == JDITHER_FS) {
1181 size_t arraysize = (size_t) ((cinfo->output_width + 2) *
1182 (3 * SIZEOF(FSERROR)));
1183 /* Allocate Floyd-Steinberg workspace if we didn't already. */
1184 if (cquantize->fserrors == NULL)
1185 cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
1186 ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
1187 /* Initialize the propagated errors to zero. */
1188 jzero_far((void FAR *) cquantize->fserrors, arraysize);
1189 /* Make the error-limit table if we didn't already. */
1190 if (cquantize->error_limiter == NULL)
1191 init_error_limit(cinfo);
1192 cquantize->on_odd_row = FALSE;
1193 }
1194
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001195 }
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001196 /* Zero the histogram or inverse color map, if necessary */
1197 if (cquantize->needs_zeroed) {
1198 for (i = 0; i < HIST_C0_ELEMS; i++) {
1199 jzero_far((void FAR *) histogram[i],
1200 HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
1201 }
1202 cquantize->needs_zeroed = FALSE;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001203 }
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001204}
1205
1206
1207/*
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001208 * Switch to a new external colormap between output passes.
1209 */
1210
Thomas G. Lane489583f1996-02-07 00:00:00 +00001211METHODDEF(void)
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001212new_color_map_2_quant (j_decompress_ptr cinfo)
1213{
1214 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1215
1216 /* Reset the inverse color map */
1217 cquantize->needs_zeroed = TRUE;
1218}
1219
1220
1221/*
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001222 * Module initialization routine for 2-pass color quantization.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001223 */
1224
Thomas G. Lane489583f1996-02-07 00:00:00 +00001225GLOBAL(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001226jinit_2pass_quantizer (j_decompress_ptr cinfo)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001227{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001228 my_cquantize_ptr cquantize;
1229 int i;
1230
1231 cquantize = (my_cquantize_ptr)
1232 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
1233 SIZEOF(my_cquantizer));
1234 cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
1235 cquantize->pub.start_pass = start_pass_2_quant;
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001236 cquantize->pub.new_color_map = new_color_map_2_quant;
1237 cquantize->fserrors = NULL; /* flag optional arrays not allocated */
1238 cquantize->error_limiter = NULL;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001239
1240 /* Make sure jdmaster didn't give me a case I can't handle */
1241 if (cinfo->out_color_components != 3)
1242 ERREXIT(cinfo, JERR_NOTIMPL);
1243
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001244 /* Allocate the histogram/inverse colormap storage */
1245 cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
1246 ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
1247 for (i = 0; i < HIST_C0_ELEMS; i++) {
1248 cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
1249 ((j_common_ptr) cinfo, JPOOL_IMAGE,
1250 HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
1251 }
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001252 cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001253
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001254 /* Allocate storage for the completed colormap, if required.
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001255 * We do this now since it is FAR storage and may affect
1256 * the memory manager's space calculations.
1257 */
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001258 if (cinfo->enable_2pass_quant) {
1259 /* Make sure color count is acceptable */
1260 int desired = cinfo->desired_number_of_colors;
1261 /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
1262 if (desired < 8)
1263 ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
1264 /* Make sure colormap indexes can be represented by JSAMPLEs */
1265 if (desired > MAXNUMCOLORS)
1266 ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
1267 cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
1268 ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
1269 cquantize->desired = desired;
1270 } else
1271 cquantize->sv_colormap = NULL;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001272
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001273 /* Only F-S dithering or no dithering is supported. */
1274 /* If user asks for ordered dither, give him F-S. */
1275 if (cinfo->dither_mode != JDITHER_NONE)
1276 cinfo->dither_mode = JDITHER_FS;
1277
1278 /* Allocate Floyd-Steinberg workspace if necessary.
1279 * This isn't really needed until pass 2, but again it is FAR storage.
1280 * Although we will cope with a later change in dither_mode,
1281 * we do not promise to honor max_memory_to_use if dither_mode changes.
1282 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001283 if (cinfo->dither_mode == JDITHER_FS) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001284 cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001285 ((j_common_ptr) cinfo, JPOOL_IMAGE,
1286 (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
1287 /* Might as well create the error-limiting table too. */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001288 init_error_limit(cinfo);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001289 }
1290}
1291
1292#endif /* QUANT_2PASS_SUPPORTED */