blob: da964f7d5bc2f648d38a7cad3be4547e03d95019 [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.
DRC8ece7fe2009-08-06 08:32:00 +00005 * Copyright (C) 2009, D. R. Commander.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00006 * This file is part of the Independent JPEG Group's software.
7 * For conditions of distribution and use, see the accompanying README file.
8 *
9 * This file contains 2-pass color quantization (color mapping) routines.
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000010 * These routines provide selection of a custom color map for an image,
11 * followed by mapping of the image to that color map, with optional
12 * Floyd-Steinberg dithering.
13 * It is also possible to use just the second pass to map to an arbitrary
14 * externally-given color map.
15 *
16 * Note: ordered dithering is not supported, since there isn't any fast
17 * way to compute intercolor distances; it's unclear that ordered dither's
18 * fundamental assumptions even hold with an irregularly spaced color map.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000019 */
20
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000021#define JPEG_INTERNALS
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000022#include "jinclude.h"
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000023#include "jpeglib.h"
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000024
25#ifdef QUANT_2PASS_SUPPORTED
26
27
28/*
Thomas G. Lane4a6b7301992-03-17 00:00:00 +000029 * This module implements the well-known Heckbert paradigm for color
30 * quantization. Most of the ideas used here can be traced back to
31 * Heckbert's seminal paper
32 * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
33 * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
34 *
35 * In the first pass over the image, we accumulate a histogram showing the
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000036 * usage count of each possible color. To keep the histogram to a reasonable
Thomas G. Lane4a6b7301992-03-17 00:00:00 +000037 * size, we reduce the precision of the input; typical practice is to retain
38 * 5 or 6 bits per color, so that 8 or 4 different input values are counted
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000039 * in the same histogram cell.
40 *
41 * Next, the color-selection step begins with a box representing the whole
42 * color space, and repeatedly splits the "largest" remaining box until we
43 * have as many boxes as desired colors. Then the mean color in each
44 * remaining box becomes one of the possible output colors.
45 *
Thomas G. Lane4a6b7301992-03-17 00:00:00 +000046 * The second pass over the image maps each input pixel to the closest output
47 * color (optionally after applying a Floyd-Steinberg dithering correction).
48 * This mapping is logically trivial, but making it go fast enough requires
49 * considerable care.
50 *
51 * Heckbert-style quantizers vary a good deal in their policies for choosing
52 * the "largest" box and deciding where to cut it. The particular policies
53 * used here have proved out well in experimental comparisons, but better ones
54 * may yet be found.
55 *
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000056 * In earlier versions of the IJG code, this module quantized in YCbCr color
57 * space, processing the raw upsampled data without a color conversion step.
58 * This allowed the color conversion math to be done only once per colormap
59 * entry, not once per pixel. However, that optimization precluded other
60 * useful optimizations (such as merging color conversion with upsampling)
61 * and it also interfered with desired capabilities such as quantizing to an
62 * externally-supplied colormap. We have therefore abandoned that approach.
63 * The present code works in the post-conversion color space, typically RGB.
64 *
65 * To improve the visual quality of the results, we actually work in scaled
66 * RGB space, giving G distances more weight than R, and R in turn more than
67 * B. To do everything in integer math, we must use integer scale factors.
68 * The 2/3/1 scale factors used here correspond loosely to the relative
69 * weights of the colors in the NTSC grayscale equation.
70 * If you want to use this code to quantize a non-RGB color space, you'll
71 * probably need to change these scale factors.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000072 */
73
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000074#define R_SCALE 2 /* scale R distances by this much */
75#define G_SCALE 3 /* scale G distances by this much */
76#define B_SCALE 1 /* and B by this much */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +000077
DRCf25c0712009-04-03 12:00:51 +000078static const int c_scales[3]={R_SCALE, G_SCALE, B_SCALE};
79#define C0_SCALE c_scales[rgb_red[cinfo->out_color_space]]
80#define C1_SCALE c_scales[rgb_green[cinfo->out_color_space]]
81#define C2_SCALE c_scales[rgb_blue[cinfo->out_color_space]]
Thomas G. Lane4a6b7301992-03-17 00:00:00 +000082
83/*
84 * First we have the histogram data structure and routines for creating it.
85 *
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000086 * The number of bits of precision can be adjusted by changing these symbols.
87 * We recommend keeping 6 bits for G and 5 each for R and B.
Thomas G. Lane4a6b7301992-03-17 00:00:00 +000088 * If you have plenty of memory and cycles, 6 bits all around gives marginally
89 * better results; if you are short of memory, 5 bits all around will save
90 * some space but degrade the results.
91 * To maintain a fully accurate histogram, we'd need to allocate a "long"
92 * (preferably unsigned long) for each cell. In practice this is overkill;
93 * we can get by with 16 bits per cell. Few of the cell counts will overflow,
94 * and clamping those that do overflow to the maximum value will give close-
95 * enough results. This reduces the recommended histogram size from 256Kb
96 * to 128Kb, which is a useful savings on PC-class machines.
97 * (In the second pass the histogram space is re-used for pixel mapping data;
98 * in that capacity, each cell must be able to store zero to the number of
99 * desired colors. 16 bits/cell is plenty for that too.)
100 * Since the JPEG code is intended to run in small memory model on 80x86
101 * machines, we can't just allocate the histogram in one chunk. Instead
102 * 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 +0000103 * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
104 * 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 +0000105 * on 80x86 machines, the pointer row is in near memory but the actual
106 * arrays are in far memory (same arrangement as we use for image arrays).
107 */
108
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000109#define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000110
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000111/* These will do the right thing for either R,G,B or B,G,R color order,
112 * but you may not like the results for other color orders.
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000113 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000114#define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
115#define HIST_C1_BITS 6 /* bits of precision in G histogram */
116#define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000117
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000118/* Number of elements along histogram axes. */
119#define HIST_C0_ELEMS (1<<HIST_C0_BITS)
120#define HIST_C1_ELEMS (1<<HIST_C1_BITS)
121#define HIST_C2_ELEMS (1<<HIST_C2_BITS)
122
123/* These are the amounts to shift an input value to get a histogram index. */
124#define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
125#define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
126#define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000127
128
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000129typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000130
131typedef histcell FAR * histptr; /* for pointers to histogram cells */
132
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000133typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
134typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000135typedef hist2d * hist3d; /* type for top-level pointer */
136
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000137
138/* Declarations for Floyd-Steinberg dithering.
139 *
140 * Errors are accumulated into the array fserrors[], at a resolution of
141 * 1/16th of a pixel count. The error at a given pixel is propagated
142 * to its not-yet-processed neighbors using the standard F-S fractions,
143 * ... (here) 7/16
144 * 3/16 5/16 1/16
145 * We work left-to-right on even rows, right-to-left on odd rows.
146 *
147 * We can get away with a single array (holding one row's worth of errors)
148 * by using it to store the current row's errors at pixel columns not yet
149 * processed, but the next row's errors at columns already processed. We
150 * need only a few extra variables to hold the errors immediately around the
151 * current column. (If we are lucky, those variables are in registers, but
152 * even if not, they're probably cheaper to access than array elements are.)
153 *
154 * The fserrors[] array has (#columns + 2) entries; the extra entry at
155 * each end saves us from special-casing the first and last pixels.
156 * Each entry is three values long, one value for each color component.
157 *
158 * Note: on a wide image, we might not have enough room in a PC's near data
159 * segment to hold the error array; so it is allocated with alloc_large.
160 */
161
162#if BITS_IN_JSAMPLE == 8
163typedef INT16 FSERROR; /* 16 bits should be enough */
164typedef int LOCFSERROR; /* use 'int' for calculation temps */
165#else
166typedef INT32 FSERROR; /* may need more than 16 bits */
167typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
168#endif
169
170typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
171
172
173/* Private subobject */
174
175typedef struct {
176 struct jpeg_color_quantizer pub; /* public fields */
177
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000178 /* Space for the eventually created colormap is stashed here */
179 JSAMPARRAY sv_colormap; /* colormap allocated at init time */
180 int desired; /* desired # of colors = size of colormap */
181
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000182 /* Variables for accumulating image statistics */
183 hist3d histogram; /* pointer to the histogram */
184
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000185 boolean needs_zeroed; /* TRUE if next pass must zero histogram */
186
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000187 /* Variables for Floyd-Steinberg dithering */
188 FSERRPTR fserrors; /* accumulated errors */
189 boolean on_odd_row; /* flag to remember which row we are on */
190 int * error_limiter; /* table for clamping the applied error */
191} my_cquantizer;
192
193typedef my_cquantizer * my_cquantize_ptr;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000194
195
196/*
197 * Prescan some rows of pixels.
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000198 * In this module the prescan simply updates the histogram, which has been
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000199 * initialized to zeroes by start_pass.
200 * An output_buf parameter is required by the method signature, but no data
201 * is actually output (in fact the buffer controller is probably passing a
202 * NULL pointer).
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000203 */
204
Thomas G. Lane489583f1996-02-07 00:00:00 +0000205METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000206prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
207 JSAMPARRAY output_buf, int num_rows)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000208{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000209 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
210 register JSAMPROW ptr;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000211 register histptr histp;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000212 register hist3d histogram = cquantize->histogram;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000213 int row;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000214 JDIMENSION col;
215 JDIMENSION width = cinfo->output_width;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000216
217 for (row = 0; row < num_rows; row++) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000218 ptr = input_buf[row];
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000219 for (col = width; col > 0; col--) {
220 /* get pixel value and index into the histogram */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000221 histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
222 [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
223 [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000224 /* increment, check for overflow and undo increment if so. */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000225 if (++(*histp) <= 0)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000226 (*histp)--;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000227 ptr += 3;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000228 }
229 }
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000230}
231
232
233/*
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000234 * Next we have the really interesting routines: selection of a colormap
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000235 * given the completed histogram.
236 * These routines work with a list of "boxes", each representing a rectangular
237 * subset of the input color space (to histogram precision).
238 */
239
240typedef struct {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000241 /* The bounds of the box (inclusive); expressed as histogram indexes */
242 int c0min, c0max;
243 int c1min, c1max;
244 int c2min, c2max;
245 /* The volume (actually 2-norm) of the box */
246 INT32 volume;
247 /* The number of nonzero histogram cells within this box */
248 long colorcount;
249} box;
250
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000251typedef box * boxptr;
252
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000253
Thomas G. Lane489583f1996-02-07 00:00:00 +0000254LOCAL(boxptr)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000255find_biggest_color_pop (boxptr boxlist, int numboxes)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000256/* Find the splittable box with the largest color population */
257/* Returns NULL if no splittable boxes remain */
258{
259 register boxptr boxp;
260 register int i;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000261 register long maxc = 0;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000262 boxptr which = NULL;
263
264 for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000265 if (boxp->colorcount > maxc && boxp->volume > 0) {
266 which = boxp;
267 maxc = boxp->colorcount;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000268 }
269 }
270 return which;
271}
272
273
Thomas G. Lane489583f1996-02-07 00:00:00 +0000274LOCAL(boxptr)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000275find_biggest_volume (boxptr boxlist, int numboxes)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000276/* Find the splittable box with the largest (scaled) volume */
277/* Returns NULL if no splittable boxes remain */
278{
279 register boxptr boxp;
280 register int i;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000281 register INT32 maxv = 0;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000282 boxptr which = NULL;
283
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000284 for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000285 if (boxp->volume > maxv) {
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000286 which = boxp;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000287 maxv = boxp->volume;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000288 }
289 }
290 return which;
291}
292
293
Thomas G. Lane489583f1996-02-07 00:00:00 +0000294LOCAL(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000295update_box (j_decompress_ptr cinfo, boxptr boxp)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000296/* Shrink the min/max bounds of a box to enclose only nonzero elements, */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000297/* and recompute its volume and population */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000298{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000299 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
300 hist3d histogram = cquantize->histogram;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000301 histptr histp;
302 int c0,c1,c2;
303 int c0min,c0max,c1min,c1max,c2min,c2max;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000304 INT32 dist0,dist1,dist2;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000305 long ccount;
306
307 c0min = boxp->c0min; c0max = boxp->c0max;
308 c1min = boxp->c1min; c1max = boxp->c1max;
309 c2min = boxp->c2min; c2max = boxp->c2max;
310
311 if (c0max > c0min)
312 for (c0 = c0min; c0 <= c0max; c0++)
313 for (c1 = c1min; c1 <= c1max; c1++) {
314 histp = & histogram[c0][c1][c2min];
315 for (c2 = c2min; c2 <= c2max; c2++)
316 if (*histp++ != 0) {
317 boxp->c0min = c0min = c0;
318 goto have_c0min;
319 }
320 }
321 have_c0min:
322 if (c0max > c0min)
323 for (c0 = c0max; c0 >= c0min; c0--)
324 for (c1 = c1min; c1 <= c1max; c1++) {
325 histp = & histogram[c0][c1][c2min];
326 for (c2 = c2min; c2 <= c2max; c2++)
327 if (*histp++ != 0) {
328 boxp->c0max = c0max = c0;
329 goto have_c0max;
330 }
331 }
332 have_c0max:
333 if (c1max > c1min)
334 for (c1 = c1min; c1 <= c1max; c1++)
335 for (c0 = c0min; c0 <= c0max; c0++) {
336 histp = & histogram[c0][c1][c2min];
337 for (c2 = c2min; c2 <= c2max; c2++)
338 if (*histp++ != 0) {
339 boxp->c1min = c1min = c1;
340 goto have_c1min;
341 }
342 }
343 have_c1min:
344 if (c1max > c1min)
345 for (c1 = c1max; c1 >= c1min; c1--)
346 for (c0 = c0min; c0 <= c0max; c0++) {
347 histp = & histogram[c0][c1][c2min];
348 for (c2 = c2min; c2 <= c2max; c2++)
349 if (*histp++ != 0) {
350 boxp->c1max = c1max = c1;
351 goto have_c1max;
352 }
353 }
354 have_c1max:
355 if (c2max > c2min)
356 for (c2 = c2min; c2 <= c2max; c2++)
357 for (c0 = c0min; c0 <= c0max; c0++) {
358 histp = & histogram[c0][c1min][c2];
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000359 for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000360 if (*histp != 0) {
361 boxp->c2min = c2min = c2;
362 goto have_c2min;
363 }
364 }
365 have_c2min:
366 if (c2max > c2min)
367 for (c2 = c2max; c2 >= c2min; c2--)
368 for (c0 = c0min; c0 <= c0max; c0++) {
369 histp = & histogram[c0][c1min][c2];
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000370 for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000371 if (*histp != 0) {
372 boxp->c2max = c2max = c2;
373 goto have_c2max;
374 }
375 }
376 have_c2max:
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000377
378 /* Update box volume.
379 * We use 2-norm rather than real volume here; this biases the method
380 * against making long narrow boxes, and it has the side benefit that
381 * a box is splittable iff norm > 0.
382 * Since the differences are expressed in histogram-cell units,
383 * we have to shift back to JSAMPLE units to get consistent distances;
384 * after which, we scale according to the selected distance scale factors.
385 */
386 dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
387 dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
388 dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
389 boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000390
391 /* Now scan remaining volume of box and compute population */
392 ccount = 0;
393 for (c0 = c0min; c0 <= c0max; c0++)
394 for (c1 = c1min; c1 <= c1max; c1++) {
395 histp = & histogram[c0][c1][c2min];
396 for (c2 = c2min; c2 <= c2max; c2++, histp++)
397 if (*histp != 0) {
398 ccount++;
399 }
400 }
401 boxp->colorcount = ccount;
402}
403
404
Thomas G. Lane489583f1996-02-07 00:00:00 +0000405LOCAL(int)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000406median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
407 int desired_colors)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000408/* Repeatedly select and split the largest box until we have enough boxes */
409{
410 int n,lb;
411 int c0,c1,c2,cmax;
412 register boxptr b1,b2;
413
414 while (numboxes < desired_colors) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000415 /* Select box to split.
416 * Current algorithm: by population for first half, then by volume.
417 */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000418 if (numboxes*2 <= desired_colors) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000419 b1 = find_biggest_color_pop(boxlist, numboxes);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000420 } else {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000421 b1 = find_biggest_volume(boxlist, numboxes);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000422 }
423 if (b1 == NULL) /* no splittable boxes left! */
424 break;
425 b2 = &boxlist[numboxes]; /* where new box will go */
426 /* Copy the color bounds to the new box. */
427 b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
428 b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
429 /* Choose which axis to split the box on.
430 * Current algorithm: longest scaled axis.
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000431 * See notes in update_box about scaling distances.
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000432 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000433 c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
434 c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
435 c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
436 /* We want to break any ties in favor of green, then red, blue last.
437 * This code does the right thing for R,G,B or B,G,R color orders only.
438 */
DRCf25c0712009-04-03 12:00:51 +0000439 if (rgb_red[cinfo->out_color_space] == 0) {
440 cmax = c1; n = 1;
441 if (c0 > cmax) { cmax = c0; n = 0; }
442 if (c2 > cmax) { n = 2; }
443 }
444 else {
445 cmax = c1; n = 1;
446 if (c2 > cmax) { cmax = c2; n = 2; }
447 if (c0 > cmax) { n = 0; }
448 }
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000449 /* Choose split point along selected axis, and update box bounds.
450 * Current algorithm: split at halfway point.
451 * (Since the box has been shrunk to minimum volume,
452 * any split will produce two nonempty subboxes.)
453 * Note that lb value is max for lower box, so must be < old max.
454 */
455 switch (n) {
456 case 0:
457 lb = (b1->c0max + b1->c0min) / 2;
458 b1->c0max = lb;
459 b2->c0min = lb+1;
460 break;
461 case 1:
462 lb = (b1->c1max + b1->c1min) / 2;
463 b1->c1max = lb;
464 b2->c1min = lb+1;
465 break;
466 case 2:
467 lb = (b1->c2max + b1->c2min) / 2;
468 b1->c2max = lb;
469 b2->c2min = lb+1;
470 break;
471 }
472 /* Update stats for boxes */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000473 update_box(cinfo, b1);
474 update_box(cinfo, b2);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000475 numboxes++;
476 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000477 return numboxes;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000478}
479
480
Thomas G. Lane489583f1996-02-07 00:00:00 +0000481LOCAL(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000482compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
483/* Compute representative color for a box, put it in colormap[icolor] */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000484{
485 /* Current algorithm: mean weighted by pixels (not colors) */
486 /* Note it is important to get the rounding correct! */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000487 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
488 hist3d histogram = cquantize->histogram;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000489 histptr histp;
490 int c0,c1,c2;
491 int c0min,c0max,c1min,c1max,c2min,c2max;
492 long count;
493 long total = 0;
494 long c0total = 0;
495 long c1total = 0;
496 long c2total = 0;
497
498 c0min = boxp->c0min; c0max = boxp->c0max;
499 c1min = boxp->c1min; c1max = boxp->c1max;
500 c2min = boxp->c2min; c2max = boxp->c2max;
501
502 for (c0 = c0min; c0 <= c0max; c0++)
503 for (c1 = c1min; c1 <= c1max; c1++) {
504 histp = & histogram[c0][c1][c2min];
505 for (c2 = c2min; c2 <= c2max; c2++) {
506 if ((count = *histp++) != 0) {
507 total += count;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000508 c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
509 c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
510 c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000511 }
512 }
513 }
514
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000515 cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
516 cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
517 cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000518}
519
520
Thomas G. Lane489583f1996-02-07 00:00:00 +0000521LOCAL(void)
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000522select_colors (j_decompress_ptr cinfo, int desired_colors)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000523/* Master routine for color selection */
524{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000525 boxptr boxlist;
526 int numboxes;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000527 int i;
528
529 /* Allocate workspace for box list */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000530 boxlist = (boxptr) (*cinfo->mem->alloc_small)
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000531 ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000532 /* Initialize one box containing whole space */
533 numboxes = 1;
534 boxlist[0].c0min = 0;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000535 boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000536 boxlist[0].c1min = 0;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000537 boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000538 boxlist[0].c2min = 0;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000539 boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000540 /* Shrink it to actually-used volume and set its statistics */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000541 update_box(cinfo, & boxlist[0]);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000542 /* Perform median-cut to produce final box list */
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000543 numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000544 /* Compute the representative color for each box, fill colormap */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000545 for (i = 0; i < numboxes; i++)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000546 compute_color(cinfo, & boxlist[i], i);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000547 cinfo->actual_number_of_colors = numboxes;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000548 TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000549}
550
551
552/*
553 * These routines are concerned with the time-critical task of mapping input
554 * colors to the nearest color in the selected colormap.
555 *
556 * We re-use the histogram space as an "inverse color map", essentially a
557 * cache for the results of nearest-color searches. All colors within a
558 * histogram cell will be mapped to the same colormap entry, namely the one
559 * closest to the cell's center. This may not be quite the closest entry to
560 * the actual input color, but it's almost as good. A zero in the cache
561 * indicates we haven't found the nearest color for that cell yet; the array
562 * is cleared to zeroes before starting the mapping pass. When we find the
563 * nearest color for a cell, its colormap index plus one is recorded in the
564 * cache for future use. The pass2 scanning routines call fill_inverse_cmap
565 * when they need to use an unfilled entry in the cache.
566 *
567 * Our method of efficiently finding nearest colors is based on the "locally
568 * sorted search" idea described by Heckbert and on the incremental distance
569 * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
570 * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
571 * the distances from a given colormap entry to each cell of the histogram can
572 * be computed quickly using an incremental method: the differences between
573 * distances to adjacent cells themselves differ by a constant. This allows a
574 * fairly fast implementation of the "brute force" approach of computing the
575 * distance from every colormap entry to every histogram cell. Unfortunately,
576 * it needs a work array to hold the best-distance-so-far for each histogram
577 * cell (because the inner loop has to be over cells, not colormap entries).
578 * The work array elements have to be INT32s, so the work array would need
579 * 256Kb at our recommended precision. This is not feasible in DOS machines.
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000580 *
581 * To get around these problems, we apply Thomas' method to compute the
582 * nearest colors for only the cells within a small subbox of the histogram.
583 * The work array need be only as big as the subbox, so the memory usage
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000584 * problem is solved. Furthermore, we need not fill subboxes that are never
585 * referenced in pass2; many images use only part of the color gamut, so a
586 * fair amount of work is saved. An additional advantage of this
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000587 * approach is that we can apply Heckbert's locality criterion to quickly
588 * eliminate colormap entries that are far away from the subbox; typically
589 * three-fourths of the colormap entries are rejected by Heckbert's criterion,
590 * and we need not compute their distances to individual cells in the subbox.
591 * The speed of this approach is heavily influenced by the subbox size: too
592 * small means too much overhead, too big loses because Heckbert's criterion
593 * can't eliminate as many colormap entries. Empirically the best subbox
594 * size seems to be about 1/512th of the histogram (1/8th in each direction).
595 *
596 * Thomas' article also describes a refined method which is asymptotically
597 * faster than the brute-force method, but it is also far more complex and
598 * cannot efficiently be applied to small subboxes. It is therefore not
599 * useful for programs intended to be portable to DOS machines. On machines
600 * with plenty of memory, filling the whole histogram in one shot with Thomas'
601 * refined method might be faster than the present code --- but then again,
602 * it might not be any faster, and it's certainly more complicated.
603 */
604
605
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000606/* log2(histogram cells in update box) for each axis; this can be adjusted */
607#define BOX_C0_LOG (HIST_C0_BITS-3)
608#define BOX_C1_LOG (HIST_C1_BITS-3)
609#define BOX_C2_LOG (HIST_C2_BITS-3)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000610
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000611#define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
612#define BOX_C1_ELEMS (1<<BOX_C1_LOG)
613#define BOX_C2_ELEMS (1<<BOX_C2_LOG)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000614
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000615#define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
616#define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
617#define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000618
619
620/*
621 * The next three routines implement inverse colormap filling. They could
622 * all be folded into one big routine, but splitting them up this way saves
623 * some stack space (the mindist[] and bestdist[] arrays need not coexist)
624 * and may allow some compilers to produce better code by registerizing more
625 * inner-loop variables.
626 */
627
Thomas G. Lane489583f1996-02-07 00:00:00 +0000628LOCAL(int)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000629find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000630 JSAMPLE colorlist[])
631/* Locate the colormap entries close enough to an update box to be candidates
632 * for the nearest entry to some cell(s) in the update box. The update box
633 * is specified by the center coordinates of its first cell. The number of
634 * candidate colormap entries is returned, and their colormap indexes are
635 * placed in colorlist[].
636 * This routine uses Heckbert's "locally sorted search" criterion to select
637 * the colors that need further consideration.
638 */
639{
640 int numcolors = cinfo->actual_number_of_colors;
641 int maxc0, maxc1, maxc2;
642 int centerc0, centerc1, centerc2;
643 int i, x, ncolors;
644 INT32 minmaxdist, min_dist, max_dist, tdist;
645 INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
646
647 /* Compute true coordinates of update box's upper corner and center.
648 * Actually we compute the coordinates of the center of the upper-corner
649 * histogram cell, which are the upper bounds of the volume we care about.
650 * Note that since ">>" rounds down, the "center" values may be closer to
651 * min than to max; hence comparisons to them must be "<=", not "<".
652 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000653 maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000654 centerc0 = (minc0 + maxc0) >> 1;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000655 maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000656 centerc1 = (minc1 + maxc1) >> 1;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000657 maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000658 centerc2 = (minc2 + maxc2) >> 1;
659
660 /* For each color in colormap, find:
661 * 1. its minimum squared-distance to any point in the update box
662 * (zero if color is within update box);
663 * 2. its maximum squared-distance to any point in the update box.
664 * Both of these can be found by considering only the corners of the box.
665 * We save the minimum distance for each color in mindist[];
666 * only the smallest maximum distance is of interest.
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000667 */
668 minmaxdist = 0x7FFFFFFFL;
669
670 for (i = 0; i < numcolors; i++) {
671 /* We compute the squared-c0-distance term, then add in the other two. */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000672 x = GETJSAMPLE(cinfo->colormap[0][i]);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000673 if (x < minc0) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000674 tdist = (x - minc0) * C0_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000675 min_dist = tdist*tdist;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000676 tdist = (x - maxc0) * C0_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000677 max_dist = tdist*tdist;
678 } else if (x > maxc0) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000679 tdist = (x - maxc0) * C0_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000680 min_dist = tdist*tdist;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000681 tdist = (x - minc0) * C0_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000682 max_dist = tdist*tdist;
683 } else {
684 /* within cell range so no contribution to min_dist */
685 min_dist = 0;
686 if (x <= centerc0) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000687 tdist = (x - maxc0) * C0_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000688 max_dist = tdist*tdist;
689 } else {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000690 tdist = (x - minc0) * C0_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000691 max_dist = tdist*tdist;
692 }
693 }
694
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000695 x = GETJSAMPLE(cinfo->colormap[1][i]);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000696 if (x < minc1) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000697 tdist = (x - minc1) * C1_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000698 min_dist += tdist*tdist;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000699 tdist = (x - maxc1) * C1_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000700 max_dist += tdist*tdist;
701 } else if (x > maxc1) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000702 tdist = (x - maxc1) * C1_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000703 min_dist += tdist*tdist;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000704 tdist = (x - minc1) * C1_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000705 max_dist += tdist*tdist;
706 } else {
707 /* within cell range so no contribution to min_dist */
708 if (x <= centerc1) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000709 tdist = (x - maxc1) * C1_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000710 max_dist += tdist*tdist;
711 } else {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000712 tdist = (x - minc1) * C1_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000713 max_dist += tdist*tdist;
714 }
715 }
716
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000717 x = GETJSAMPLE(cinfo->colormap[2][i]);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000718 if (x < minc2) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000719 tdist = (x - minc2) * C2_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000720 min_dist += tdist*tdist;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000721 tdist = (x - maxc2) * C2_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000722 max_dist += tdist*tdist;
723 } else if (x > maxc2) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000724 tdist = (x - maxc2) * C2_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000725 min_dist += tdist*tdist;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000726 tdist = (x - minc2) * C2_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000727 max_dist += tdist*tdist;
728 } else {
729 /* within cell range so no contribution to min_dist */
730 if (x <= centerc2) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000731 tdist = (x - maxc2) * C2_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000732 max_dist += tdist*tdist;
733 } else {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000734 tdist = (x - minc2) * C2_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000735 max_dist += tdist*tdist;
736 }
737 }
738
739 mindist[i] = min_dist; /* save away the results */
740 if (max_dist < minmaxdist)
741 minmaxdist = max_dist;
742 }
743
744 /* Now we know that no cell in the update box is more than minmaxdist
745 * away from some colormap entry. Therefore, only colors that are
746 * within minmaxdist of some part of the box need be considered.
747 */
748 ncolors = 0;
749 for (i = 0; i < numcolors; i++) {
750 if (mindist[i] <= minmaxdist)
751 colorlist[ncolors++] = (JSAMPLE) i;
752 }
753 return ncolors;
754}
755
756
Thomas G. Lane489583f1996-02-07 00:00:00 +0000757LOCAL(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000758find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000759 int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
760/* Find the closest colormap entry for each cell in the update box,
761 * given the list of candidate colors prepared by find_nearby_colors.
762 * Return the indexes of the closest entries in the bestcolor[] array.
763 * This routine uses Thomas' incremental distance calculation method to
764 * find the distance from a colormap entry to successive cells in the box.
765 */
766{
767 int ic0, ic1, ic2;
768 int i, icolor;
769 register INT32 * bptr; /* pointer into bestdist[] array */
770 JSAMPLE * cptr; /* pointer into bestcolor[] array */
771 INT32 dist0, dist1; /* initial distance values */
772 register INT32 dist2; /* current distance in inner loop */
773 INT32 xx0, xx1; /* distance increments */
774 register INT32 xx2;
775 INT32 inc0, inc1, inc2; /* initial values for increments */
776 /* This array holds the distance to the nearest-so-far color for each cell */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000777 INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000778
779 /* Initialize best-distance for each cell of the update box */
780 bptr = bestdist;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000781 for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000782 *bptr++ = 0x7FFFFFFFL;
783
784 /* For each color selected by find_nearby_colors,
785 * compute its distance to the center of each cell in the box.
786 * If that's less than best-so-far, update best distance and color number.
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000787 */
788
789 /* Nominal steps between cell centers ("x" in Thomas article) */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000790#define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
791#define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
792#define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000793
794 for (i = 0; i < numcolors; i++) {
795 icolor = GETJSAMPLE(colorlist[i]);
796 /* Compute (square of) distance from minc0/c1/c2 to this color */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000797 inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000798 dist0 = inc0*inc0;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000799 inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000800 dist0 += inc1*inc1;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000801 inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000802 dist0 += inc2*inc2;
803 /* Form the initial difference increments */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000804 inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
805 inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
806 inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000807 /* Now loop over all cells in box, updating distance per Thomas method */
808 bptr = bestdist;
809 cptr = bestcolor;
810 xx0 = inc0;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000811 for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000812 dist1 = dist0;
813 xx1 = inc1;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000814 for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000815 dist2 = dist1;
816 xx2 = inc2;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000817 for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000818 if (dist2 < *bptr) {
819 *bptr = dist2;
820 *cptr = (JSAMPLE) icolor;
821 }
822 dist2 += xx2;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000823 xx2 += 2 * STEP_C2 * STEP_C2;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000824 bptr++;
825 cptr++;
826 }
827 dist1 += xx1;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000828 xx1 += 2 * STEP_C1 * STEP_C1;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000829 }
830 dist0 += xx0;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000831 xx0 += 2 * STEP_C0 * STEP_C0;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000832 }
833 }
834}
835
836
Thomas G. Lane489583f1996-02-07 00:00:00 +0000837LOCAL(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000838fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000839/* Fill the inverse-colormap entries in the update box that contains */
840/* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
841/* we can fill as many others as we wish.) */
842{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000843 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
844 hist3d histogram = cquantize->histogram;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000845 int minc0, minc1, minc2; /* lower left corner of update box */
846 int ic0, ic1, ic2;
847 register JSAMPLE * cptr; /* pointer into bestcolor[] array */
848 register histptr cachep; /* pointer into main cache array */
849 /* This array lists the candidate colormap indexes. */
850 JSAMPLE colorlist[MAXNUMCOLORS];
851 int numcolors; /* number of candidate colors */
852 /* This array holds the actually closest colormap index for each cell. */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000853 JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000854
855 /* Convert cell coordinates to update box ID */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000856 c0 >>= BOX_C0_LOG;
857 c1 >>= BOX_C1_LOG;
858 c2 >>= BOX_C2_LOG;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000859
860 /* Compute true coordinates of update box's origin corner.
861 * Actually we compute the coordinates of the center of the corner
862 * histogram cell, which are the lower bounds of the volume we care about.
863 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000864 minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
865 minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
866 minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000867
868 /* Determine which colormap entries are close enough to be candidates
869 * for the nearest entry to some cell in the update box.
870 */
871 numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
872
873 /* Determine the actually nearest colors. */
874 find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
875 bestcolor);
876
877 /* Save the best color numbers (plus 1) in the main cache array */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000878 c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
879 c1 <<= BOX_C1_LOG;
880 c2 <<= BOX_C2_LOG;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000881 cptr = bestcolor;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000882 for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
883 for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000884 cachep = & histogram[c0+ic0][c1+ic1][c2];
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000885 for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000886 *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
887 }
888 }
889 }
890}
891
892
893/*
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000894 * Map some rows of pixels to the output colormapped representation.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000895 */
896
Thomas G. Lane489583f1996-02-07 00:00:00 +0000897METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000898pass2_no_dither (j_decompress_ptr cinfo,
899 JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000900/* This version performs no dithering */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000901{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000902 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
903 hist3d histogram = cquantize->histogram;
904 register JSAMPROW inptr, outptr;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000905 register histptr cachep;
906 register int c0, c1, c2;
907 int row;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000908 JDIMENSION col;
909 JDIMENSION width = cinfo->output_width;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000910
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000911 for (row = 0; row < num_rows; row++) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000912 inptr = input_buf[row];
913 outptr = output_buf[row];
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000914 for (col = width; col > 0; col--) {
915 /* get pixel value and index into the cache */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000916 c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
917 c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
918 c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000919 cachep = & histogram[c0][c1][c2];
920 /* If we have not seen this color before, find nearest colormap entry */
921 /* and update the cache */
922 if (*cachep == 0)
923 fill_inverse_cmap(cinfo, c0,c1,c2);
924 /* Now emit the colormap index for this cell */
925 *outptr++ = (JSAMPLE) (*cachep - 1);
926 }
927 }
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000928}
929
930
Thomas G. Lane489583f1996-02-07 00:00:00 +0000931METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000932pass2_fs_dither (j_decompress_ptr cinfo,
933 JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000934/* This version performs Floyd-Steinberg dithering */
935{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000936 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
937 hist3d histogram = cquantize->histogram;
Thomas G. Lanecc7150e1993-02-18 00:00:00 +0000938 register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
939 LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
940 LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
941 register FSERRPTR errorptr; /* => fserrors[] at column before current */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000942 JSAMPROW inptr; /* => current input pixel */
Thomas G. Lanecc7150e1993-02-18 00:00:00 +0000943 JSAMPROW outptr; /* => current output pixel */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000944 histptr cachep;
Thomas G. Lanecc7150e1993-02-18 00:00:00 +0000945 int dir; /* +1 or -1 depending on direction */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000946 int dir3; /* 3*dir, for advancing inptr & errorptr */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000947 int row;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000948 JDIMENSION col;
949 JDIMENSION width = cinfo->output_width;
Thomas G. Lane88aeed41992-12-10 00:00:00 +0000950 JSAMPLE *range_limit = cinfo->sample_range_limit;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000951 int *error_limit = cquantize->error_limiter;
952 JSAMPROW colormap0 = cinfo->colormap[0];
953 JSAMPROW colormap1 = cinfo->colormap[1];
954 JSAMPROW colormap2 = cinfo->colormap[2];
Thomas G. Lane88aeed41992-12-10 00:00:00 +0000955 SHIFT_TEMPS
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000956
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000957 for (row = 0; row < num_rows; row++) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000958 inptr = input_buf[row];
959 outptr = output_buf[row];
960 if (cquantize->on_odd_row) {
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000961 /* work right to left in this row */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000962 inptr += (width-1) * 3; /* so point to rightmost pixel */
963 outptr += width-1;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000964 dir = -1;
Thomas G. Lanecc7150e1993-02-18 00:00:00 +0000965 dir3 = -3;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000966 errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
967 cquantize->on_odd_row = FALSE; /* flip for next time */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000968 } else {
969 /* work left to right in this row */
970 dir = 1;
Thomas G. Lanecc7150e1993-02-18 00:00:00 +0000971 dir3 = 3;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000972 errorptr = cquantize->fserrors; /* => entry before first real column */
973 cquantize->on_odd_row = TRUE; /* flip for next time */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000974 }
Thomas G. Lanecc7150e1993-02-18 00:00:00 +0000975 /* Preset error values: no error propagated to first pixel from left */
976 cur0 = cur1 = cur2 = 0;
977 /* and no error propagated to row below yet */
978 belowerr0 = belowerr1 = belowerr2 = 0;
979 bpreverr0 = bpreverr1 = bpreverr2 = 0;
980
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000981 for (col = width; col > 0; col--) {
Thomas G. Lanecc7150e1993-02-18 00:00:00 +0000982 /* curN holds the error propagated from the previous pixel on the
983 * current line. Add the error propagated from the previous line
984 * to form the complete error correction term for this pixel, and
985 * round the error term (which is expressed * 16) to an integer.
Thomas G. Lane88aeed41992-12-10 00:00:00 +0000986 * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
Thomas G. Lanecc7150e1993-02-18 00:00:00 +0000987 * for either sign of the error value.
988 * Note: errorptr points to *previous* column's array entry.
Thomas G. Lane88aeed41992-12-10 00:00:00 +0000989 */
Thomas G. Lanecc7150e1993-02-18 00:00:00 +0000990 cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
991 cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
992 cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000993 /* Limit the error using transfer function set by init_error_limit.
994 * See comments with init_error_limit for rationale.
Thomas G. Lanecc7150e1993-02-18 00:00:00 +0000995 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000996 cur0 = error_limit[cur0];
997 cur1 = error_limit[cur1];
998 cur2 = error_limit[cur2];
999 /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
1000 * The maximum error is +- MAXJSAMPLE (or less with error limiting);
1001 * this sets the required size of the range_limit array.
1002 */
1003 cur0 += GETJSAMPLE(inptr[0]);
1004 cur1 += GETJSAMPLE(inptr[1]);
1005 cur2 += GETJSAMPLE(inptr[2]);
Thomas G. Lanecc7150e1993-02-18 00:00:00 +00001006 cur0 = GETJSAMPLE(range_limit[cur0]);
1007 cur1 = GETJSAMPLE(range_limit[cur1]);
1008 cur2 = GETJSAMPLE(range_limit[cur2]);
Thomas G. Lane88aeed41992-12-10 00:00:00 +00001009 /* Index into the cache with adjusted pixel value */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001010 cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001011 /* If we have not seen this color before, find nearest colormap */
1012 /* entry and update the cache */
1013 if (*cachep == 0)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001014 fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001015 /* Now emit the colormap index for this cell */
Thomas G. Lanecc7150e1993-02-18 00:00:00 +00001016 { register int pixcode = *cachep - 1;
1017 *outptr = (JSAMPLE) pixcode;
1018 /* Compute representation error for this pixel */
1019 cur0 -= GETJSAMPLE(colormap0[pixcode]);
1020 cur1 -= GETJSAMPLE(colormap1[pixcode]);
1021 cur2 -= GETJSAMPLE(colormap2[pixcode]);
1022 }
1023 /* Compute error fractions to be propagated to adjacent pixels.
1024 * Add these into the running sums, and simultaneously shift the
1025 * next-line error sums left by 1 column.
1026 */
1027 { register LOCFSERROR bnexterr, delta;
1028
1029 bnexterr = cur0; /* Process component 0 */
1030 delta = cur0 * 2;
1031 cur0 += delta; /* form error * 3 */
1032 errorptr[0] = (FSERROR) (bpreverr0 + cur0);
1033 cur0 += delta; /* form error * 5 */
1034 bpreverr0 = belowerr0 + cur0;
1035 belowerr0 = bnexterr;
1036 cur0 += delta; /* form error * 7 */
1037 bnexterr = cur1; /* Process component 1 */
1038 delta = cur1 * 2;
1039 cur1 += delta; /* form error * 3 */
1040 errorptr[1] = (FSERROR) (bpreverr1 + cur1);
1041 cur1 += delta; /* form error * 5 */
1042 bpreverr1 = belowerr1 + cur1;
1043 belowerr1 = bnexterr;
1044 cur1 += delta; /* form error * 7 */
1045 bnexterr = cur2; /* Process component 2 */
1046 delta = cur2 * 2;
1047 cur2 += delta; /* form error * 3 */
1048 errorptr[2] = (FSERROR) (bpreverr2 + cur2);
1049 cur2 += delta; /* form error * 5 */
1050 bpreverr2 = belowerr2 + cur2;
1051 belowerr2 = bnexterr;
1052 cur2 += delta; /* form error * 7 */
1053 }
1054 /* At this point curN contains the 7/16 error value to be propagated
1055 * to the next pixel on the current line, and all the errors for the
1056 * next line have been shifted over. We are therefore ready to move on.
1057 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001058 inptr += dir3; /* Advance pixel pointers to next column */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001059 outptr += dir;
Thomas G. Lanecc7150e1993-02-18 00:00:00 +00001060 errorptr += dir3; /* advance errorptr to current column */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001061 }
Thomas G. Lanecc7150e1993-02-18 00:00:00 +00001062 /* Post-loop cleanup: we must unload the final error values into the
1063 * final fserrors[] entry. Note we need not unload belowerrN because
1064 * it is for the dummy column before or after the actual array.
1065 */
1066 errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
1067 errorptr[1] = (FSERROR) bpreverr1;
1068 errorptr[2] = (FSERROR) bpreverr2;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001069 }
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001070}
1071
1072
1073/*
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001074 * Initialize the error-limiting transfer function (lookup table).
1075 * The raw F-S error computation can potentially compute error values of up to
1076 * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
1077 * much less, otherwise obviously wrong pixels will be created. (Typical
1078 * effects include weird fringes at color-area boundaries, isolated bright
1079 * pixels in a dark area, etc.) The standard advice for avoiding this problem
1080 * is to ensure that the "corners" of the color cube are allocated as output
1081 * colors; then repeated errors in the same direction cannot cause cascading
1082 * error buildup. However, that only prevents the error from getting
1083 * completely out of hand; Aaron Giles reports that error limiting improves
1084 * the results even with corner colors allocated.
1085 * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
1086 * well, but the smoother transfer function used below is even better. Thanks
1087 * to Aaron Giles for this idea.
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001088 */
1089
Thomas G. Lane489583f1996-02-07 00:00:00 +00001090LOCAL(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001091init_error_limit (j_decompress_ptr cinfo)
1092/* Allocate and fill in the error_limiter table */
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001093{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001094 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1095 int * table;
1096 int in, out;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001097
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001098 table = (int *) (*cinfo->mem->alloc_small)
1099 ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
1100 table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
1101 cquantize->error_limiter = table;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001102
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001103#define STEPSIZE ((MAXJSAMPLE+1)/16)
1104 /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
1105 out = 0;
1106 for (in = 0; in < STEPSIZE; in++, out++) {
1107 table[in] = out; table[-in] = -out;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001108 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001109 /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
1110 for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
1111 table[in] = out; table[-in] = -out;
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001112 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001113 /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
1114 for (; in <= MAXJSAMPLE; in++) {
1115 table[in] = out; table[-in] = -out;
1116 }
1117#undef STEPSIZE
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001118}
1119
1120
1121/*
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001122 * Finish up at the end of each pass.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001123 */
1124
Thomas G. Lane489583f1996-02-07 00:00:00 +00001125METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001126finish_pass1 (j_decompress_ptr cinfo)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001127{
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001128 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1129
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001130 /* Select the representative colors and fill in cinfo->colormap */
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001131 cinfo->colormap = cquantize->sv_colormap;
1132 select_colors(cinfo, cquantize->desired);
1133 /* Force next pass to zero the color index table */
1134 cquantize->needs_zeroed = TRUE;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001135}
1136
1137
Thomas G. Lane489583f1996-02-07 00:00:00 +00001138METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001139finish_pass2 (j_decompress_ptr cinfo)
1140{
1141 /* no work */
1142}
1143
1144
1145/*
1146 * Initialize for each processing pass.
1147 */
1148
Thomas G. Lane489583f1996-02-07 00:00:00 +00001149METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001150start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
1151{
1152 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1153 hist3d histogram = cquantize->histogram;
1154 int i;
1155
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001156 /* Only F-S dithering or no dithering is supported. */
1157 /* If user asks for ordered dither, give him F-S. */
1158 if (cinfo->dither_mode != JDITHER_NONE)
1159 cinfo->dither_mode = JDITHER_FS;
1160
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001161 if (is_pre_scan) {
1162 /* Set up method pointers */
1163 cquantize->pub.color_quantize = prescan_quantize;
1164 cquantize->pub.finish_pass = finish_pass1;
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001165 cquantize->needs_zeroed = TRUE; /* Always zero histogram */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001166 } else {
1167 /* Set up method pointers */
1168 if (cinfo->dither_mode == JDITHER_FS)
1169 cquantize->pub.color_quantize = pass2_fs_dither;
1170 else
1171 cquantize->pub.color_quantize = pass2_no_dither;
1172 cquantize->pub.finish_pass = finish_pass2;
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001173
1174 /* Make sure color count is acceptable */
1175 i = cinfo->actual_number_of_colors;
1176 if (i < 1)
1177 ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
1178 if (i > MAXNUMCOLORS)
1179 ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
1180
1181 if (cinfo->dither_mode == JDITHER_FS) {
1182 size_t arraysize = (size_t) ((cinfo->output_width + 2) *
1183 (3 * SIZEOF(FSERROR)));
1184 /* Allocate Floyd-Steinberg workspace if we didn't already. */
1185 if (cquantize->fserrors == NULL)
1186 cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
1187 ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
1188 /* Initialize the propagated errors to zero. */
1189 jzero_far((void FAR *) cquantize->fserrors, arraysize);
1190 /* Make the error-limit table if we didn't already. */
1191 if (cquantize->error_limiter == NULL)
1192 init_error_limit(cinfo);
1193 cquantize->on_odd_row = FALSE;
1194 }
1195
Thomas G. Lane4a6b7301992-03-17 00:00:00 +00001196 }
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001197 /* Zero the histogram or inverse color map, if necessary */
1198 if (cquantize->needs_zeroed) {
1199 for (i = 0; i < HIST_C0_ELEMS; i++) {
1200 jzero_far((void FAR *) histogram[i],
1201 HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
1202 }
1203 cquantize->needs_zeroed = FALSE;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001204 }
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001205}
1206
1207
1208/*
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001209 * Switch to a new external colormap between output passes.
1210 */
1211
Thomas G. Lane489583f1996-02-07 00:00:00 +00001212METHODDEF(void)
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001213new_color_map_2_quant (j_decompress_ptr cinfo)
1214{
1215 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1216
1217 /* Reset the inverse color map */
1218 cquantize->needs_zeroed = TRUE;
1219}
1220
1221
1222/*
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001223 * Module initialization routine for 2-pass color quantization.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001224 */
1225
Thomas G. Lane489583f1996-02-07 00:00:00 +00001226GLOBAL(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001227jinit_2pass_quantizer (j_decompress_ptr cinfo)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001228{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001229 my_cquantize_ptr cquantize;
1230 int i;
1231
1232 cquantize = (my_cquantize_ptr)
1233 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
1234 SIZEOF(my_cquantizer));
1235 cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
1236 cquantize->pub.start_pass = start_pass_2_quant;
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001237 cquantize->pub.new_color_map = new_color_map_2_quant;
1238 cquantize->fserrors = NULL; /* flag optional arrays not allocated */
1239 cquantize->error_limiter = NULL;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001240
1241 /* Make sure jdmaster didn't give me a case I can't handle */
1242 if (cinfo->out_color_components != 3)
1243 ERREXIT(cinfo, JERR_NOTIMPL);
1244
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001245 /* Allocate the histogram/inverse colormap storage */
1246 cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
1247 ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
1248 for (i = 0; i < HIST_C0_ELEMS; i++) {
1249 cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
1250 ((j_common_ptr) cinfo, JPOOL_IMAGE,
1251 HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
1252 }
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001253 cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001254
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001255 /* Allocate storage for the completed colormap, if required.
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001256 * We do this now since it is FAR storage and may affect
1257 * the memory manager's space calculations.
1258 */
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001259 if (cinfo->enable_2pass_quant) {
1260 /* Make sure color count is acceptable */
1261 int desired = cinfo->desired_number_of_colors;
1262 /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
1263 if (desired < 8)
1264 ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
1265 /* Make sure colormap indexes can be represented by JSAMPLEs */
1266 if (desired > MAXNUMCOLORS)
1267 ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
1268 cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
1269 ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
1270 cquantize->desired = desired;
1271 } else
1272 cquantize->sv_colormap = NULL;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001273
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001274 /* Only F-S dithering or no dithering is supported. */
1275 /* If user asks for ordered dither, give him F-S. */
1276 if (cinfo->dither_mode != JDITHER_NONE)
1277 cinfo->dither_mode = JDITHER_FS;
1278
1279 /* Allocate Floyd-Steinberg workspace if necessary.
1280 * This isn't really needed until pass 2, but again it is FAR storage.
1281 * Although we will cope with a later change in dither_mode,
1282 * we do not promise to honor max_memory_to_use if dither_mode changes.
1283 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001284 if (cinfo->dither_mode == JDITHER_FS) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001285 cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001286 ((j_common_ptr) cinfo, JPOOL_IMAGE,
1287 (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
1288 /* Might as well create the error-limiting table too. */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001289 init_error_limit(cinfo);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001290 }
1291}
1292
1293#endif /* QUANT_2PASS_SUPPORTED */