1 : /*
2 : * jquant2.c
3 : *
4 : * Copyright (C) 1991-1996, Thomas G. Lane.
5 : * Copyright (C) 2009, D. R. Commander.
6 : * 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.
10 : * 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.
19 : */
20 :
21 : #define JPEG_INTERNALS
22 : #include "jinclude.h"
23 : #include "jpeglib.h"
24 :
25 : #ifdef QUANT_2PASS_SUPPORTED
26 :
27 :
28 : /*
29 : * 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
36 : * usage count of each possible color. To keep the histogram to a reasonable
37 : * 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
39 : * 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 : *
46 : * 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 : *
56 : * 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.
72 : */
73 :
74 : #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 */
77 :
78 : static 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]]
82 :
83 : /*
84 : * First we have the histogram data structure and routines for creating it.
85 : *
86 : * 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.
88 : * 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
103 : * 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
105 : * 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 :
109 : #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
110 :
111 : /* 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.
113 : */
114 : #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 */
117 :
118 : /* 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)
127 :
128 :
129 : typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
130 :
131 : typedef histcell FAR * histptr; /* for pointers to histogram cells */
132 :
133 : typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
134 : typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
135 : typedef hist2d * hist3d; /* type for top-level pointer */
136 :
137 :
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
163 : typedef INT16 FSERROR; /* 16 bits should be enough */
164 : typedef int LOCFSERROR; /* use 'int' for calculation temps */
165 : #else
166 : typedef INT32 FSERROR; /* may need more than 16 bits */
167 : typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
168 : #endif
169 :
170 : typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
171 :
172 :
173 : /* Private subobject */
174 :
175 : typedef struct {
176 : struct jpeg_color_quantizer pub; /* public fields */
177 :
178 : /* 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 :
182 : /* Variables for accumulating image statistics */
183 : hist3d histogram; /* pointer to the histogram */
184 :
185 : boolean needs_zeroed; /* TRUE if next pass must zero histogram */
186 :
187 : /* 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 :
193 : typedef my_cquantizer * my_cquantize_ptr;
194 :
195 :
196 : /*
197 : * Prescan some rows of pixels.
198 : * In this module the prescan simply updates the histogram, which has been
199 : * 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).
203 : */
204 :
205 : METHODDEF(void)
206 0 : prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
207 : JSAMPARRAY output_buf, int num_rows)
208 : {
209 0 : my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
210 : register JSAMPROW ptr;
211 : register histptr histp;
212 0 : register hist3d histogram = cquantize->histogram;
213 : int row;
214 : JDIMENSION col;
215 0 : JDIMENSION width = cinfo->output_width;
216 :
217 0 : for (row = 0; row < num_rows; row++) {
218 0 : ptr = input_buf[row];
219 0 : for (col = width; col > 0; col--) {
220 : /* get pixel value and index into the histogram */
221 0 : histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
222 0 : [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
223 0 : [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
224 : /* increment, check for overflow and undo increment if so. */
225 0 : if (++(*histp) <= 0)
226 0 : (*histp)--;
227 0 : ptr += 3;
228 : }
229 : }
230 0 : }
231 :
232 :
233 : /*
234 : * Next we have the really interesting routines: selection of a colormap
235 : * 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 :
240 : typedef struct {
241 : /* 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 :
251 : typedef box * boxptr;
252 :
253 :
254 : LOCAL(boxptr)
255 0 : find_biggest_color_pop (boxptr boxlist, int numboxes)
256 : /* 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;
261 0 : register long maxc = 0;
262 0 : boxptr which = NULL;
263 :
264 0 : for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
265 0 : if (boxp->colorcount > maxc && boxp->volume > 0) {
266 0 : which = boxp;
267 0 : maxc = boxp->colorcount;
268 : }
269 : }
270 0 : return which;
271 : }
272 :
273 :
274 : LOCAL(boxptr)
275 0 : find_biggest_volume (boxptr boxlist, int numboxes)
276 : /* 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;
281 0 : register INT32 maxv = 0;
282 0 : boxptr which = NULL;
283 :
284 0 : for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
285 0 : if (boxp->volume > maxv) {
286 0 : which = boxp;
287 0 : maxv = boxp->volume;
288 : }
289 : }
290 0 : return which;
291 : }
292 :
293 :
294 : LOCAL(void)
295 0 : update_box (j_decompress_ptr cinfo, boxptr boxp)
296 : /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
297 : /* and recompute its volume and population */
298 : {
299 0 : my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
300 0 : hist3d histogram = cquantize->histogram;
301 : histptr histp;
302 : int c0,c1,c2;
303 : int c0min,c0max,c1min,c1max,c2min,c2max;
304 : INT32 dist0,dist1,dist2;
305 : long ccount;
306 :
307 0 : c0min = boxp->c0min; c0max = boxp->c0max;
308 0 : c1min = boxp->c1min; c1max = boxp->c1max;
309 0 : c2min = boxp->c2min; c2max = boxp->c2max;
310 :
311 0 : if (c0max > c0min)
312 0 : for (c0 = c0min; c0 <= c0max; c0++)
313 0 : for (c1 = c1min; c1 <= c1max; c1++) {
314 0 : histp = & histogram[c0][c1][c2min];
315 0 : for (c2 = c2min; c2 <= c2max; c2++)
316 0 : if (*histp++ != 0) {
317 0 : boxp->c0min = c0min = c0;
318 0 : goto have_c0min;
319 : }
320 : }
321 : have_c0min:
322 0 : if (c0max > c0min)
323 0 : for (c0 = c0max; c0 >= c0min; c0--)
324 0 : for (c1 = c1min; c1 <= c1max; c1++) {
325 0 : histp = & histogram[c0][c1][c2min];
326 0 : for (c2 = c2min; c2 <= c2max; c2++)
327 0 : if (*histp++ != 0) {
328 0 : boxp->c0max = c0max = c0;
329 0 : goto have_c0max;
330 : }
331 : }
332 : have_c0max:
333 0 : if (c1max > c1min)
334 0 : for (c1 = c1min; c1 <= c1max; c1++)
335 0 : for (c0 = c0min; c0 <= c0max; c0++) {
336 0 : histp = & histogram[c0][c1][c2min];
337 0 : for (c2 = c2min; c2 <= c2max; c2++)
338 0 : if (*histp++ != 0) {
339 0 : boxp->c1min = c1min = c1;
340 0 : goto have_c1min;
341 : }
342 : }
343 : have_c1min:
344 0 : if (c1max > c1min)
345 0 : for (c1 = c1max; c1 >= c1min; c1--)
346 0 : for (c0 = c0min; c0 <= c0max; c0++) {
347 0 : histp = & histogram[c0][c1][c2min];
348 0 : for (c2 = c2min; c2 <= c2max; c2++)
349 0 : if (*histp++ != 0) {
350 0 : boxp->c1max = c1max = c1;
351 0 : goto have_c1max;
352 : }
353 : }
354 : have_c1max:
355 0 : if (c2max > c2min)
356 0 : for (c2 = c2min; c2 <= c2max; c2++)
357 0 : for (c0 = c0min; c0 <= c0max; c0++) {
358 0 : histp = & histogram[c0][c1min][c2];
359 0 : for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
360 0 : if (*histp != 0) {
361 0 : boxp->c2min = c2min = c2;
362 0 : goto have_c2min;
363 : }
364 : }
365 : have_c2min:
366 0 : if (c2max > c2min)
367 0 : for (c2 = c2max; c2 >= c2min; c2--)
368 0 : for (c0 = c0min; c0 <= c0max; c0++) {
369 0 : histp = & histogram[c0][c1min][c2];
370 0 : for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
371 0 : if (*histp != 0) {
372 0 : boxp->c2max = c2max = c2;
373 0 : goto have_c2max;
374 : }
375 : }
376 : have_c2max:
377 :
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 0 : dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
387 0 : dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
388 0 : dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
389 0 : boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
390 :
391 : /* Now scan remaining volume of box and compute population */
392 0 : ccount = 0;
393 0 : for (c0 = c0min; c0 <= c0max; c0++)
394 0 : for (c1 = c1min; c1 <= c1max; c1++) {
395 0 : histp = & histogram[c0][c1][c2min];
396 0 : for (c2 = c2min; c2 <= c2max; c2++, histp++)
397 0 : if (*histp != 0) {
398 0 : ccount++;
399 : }
400 : }
401 0 : boxp->colorcount = ccount;
402 0 : }
403 :
404 :
405 : LOCAL(int)
406 0 : median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
407 : int desired_colors)
408 : /* 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 0 : while (numboxes < desired_colors) {
415 : /* Select box to split.
416 : * Current algorithm: by population for first half, then by volume.
417 : */
418 0 : if (numboxes*2 <= desired_colors) {
419 0 : b1 = find_biggest_color_pop(boxlist, numboxes);
420 : } else {
421 0 : b1 = find_biggest_volume(boxlist, numboxes);
422 : }
423 0 : if (b1 == NULL) /* no splittable boxes left! */
424 0 : break;
425 0 : b2 = &boxlist[numboxes]; /* where new box will go */
426 : /* Copy the color bounds to the new box. */
427 0 : b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
428 0 : 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.
431 : * See notes in update_box about scaling distances.
432 : */
433 0 : c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
434 0 : c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
435 0 : 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 : */
439 0 : if (rgb_red[cinfo->out_color_space] == 0) {
440 0 : cmax = c1; n = 1;
441 0 : if (c0 > cmax) { cmax = c0; n = 0; }
442 0 : if (c2 > cmax) { n = 2; }
443 : }
444 : else {
445 0 : cmax = c1; n = 1;
446 0 : if (c2 > cmax) { cmax = c2; n = 2; }
447 0 : if (c0 > cmax) { n = 0; }
448 : }
449 : /* 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 0 : switch (n) {
456 : case 0:
457 0 : lb = (b1->c0max + b1->c0min) / 2;
458 0 : b1->c0max = lb;
459 0 : b2->c0min = lb+1;
460 0 : break;
461 : case 1:
462 0 : lb = (b1->c1max + b1->c1min) / 2;
463 0 : b1->c1max = lb;
464 0 : b2->c1min = lb+1;
465 0 : break;
466 : case 2:
467 0 : lb = (b1->c2max + b1->c2min) / 2;
468 0 : b1->c2max = lb;
469 0 : b2->c2min = lb+1;
470 0 : break;
471 : }
472 : /* Update stats for boxes */
473 0 : update_box(cinfo, b1);
474 0 : update_box(cinfo, b2);
475 0 : numboxes++;
476 : }
477 0 : return numboxes;
478 : }
479 :
480 :
481 : LOCAL(void)
482 0 : compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
483 : /* Compute representative color for a box, put it in colormap[icolor] */
484 : {
485 : /* Current algorithm: mean weighted by pixels (not colors) */
486 : /* Note it is important to get the rounding correct! */
487 0 : my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
488 0 : hist3d histogram = cquantize->histogram;
489 : histptr histp;
490 : int c0,c1,c2;
491 : int c0min,c0max,c1min,c1max,c2min,c2max;
492 : long count;
493 0 : long total = 0;
494 0 : long c0total = 0;
495 0 : long c1total = 0;
496 0 : long c2total = 0;
497 :
498 0 : c0min = boxp->c0min; c0max = boxp->c0max;
499 0 : c1min = boxp->c1min; c1max = boxp->c1max;
500 0 : c2min = boxp->c2min; c2max = boxp->c2max;
501 :
502 0 : for (c0 = c0min; c0 <= c0max; c0++)
503 0 : for (c1 = c1min; c1 <= c1max; c1++) {
504 0 : histp = & histogram[c0][c1][c2min];
505 0 : for (c2 = c2min; c2 <= c2max; c2++) {
506 0 : if ((count = *histp++) != 0) {
507 0 : total += count;
508 0 : c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
509 0 : c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
510 0 : c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
511 : }
512 : }
513 : }
514 :
515 0 : cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
516 0 : cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
517 0 : cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
518 0 : }
519 :
520 :
521 : LOCAL(void)
522 0 : select_colors (j_decompress_ptr cinfo, int desired_colors)
523 : /* Master routine for color selection */
524 : {
525 : boxptr boxlist;
526 : int numboxes;
527 : int i;
528 :
529 : /* Allocate workspace for box list */
530 0 : boxlist = (boxptr) (*cinfo->mem->alloc_small)
531 0 : ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
532 : /* Initialize one box containing whole space */
533 0 : numboxes = 1;
534 0 : boxlist[0].c0min = 0;
535 0 : boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
536 0 : boxlist[0].c1min = 0;
537 0 : boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
538 0 : boxlist[0].c2min = 0;
539 0 : boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
540 : /* Shrink it to actually-used volume and set its statistics */
541 0 : update_box(cinfo, & boxlist[0]);
542 : /* Perform median-cut to produce final box list */
543 0 : numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
544 : /* Compute the representative color for each box, fill colormap */
545 0 : for (i = 0; i < numboxes; i++)
546 0 : compute_color(cinfo, & boxlist[i], i);
547 0 : cinfo->actual_number_of_colors = numboxes;
548 0 : TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
549 0 : }
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.
580 : *
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
584 : * 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
587 : * 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 :
606 : /* 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)
610 :
611 : #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)
614 :
615 : #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)
618 :
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 :
628 : LOCAL(int)
629 0 : find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
630 : 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 0 : 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 : */
653 0 : maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
654 0 : centerc0 = (minc0 + maxc0) >> 1;
655 0 : maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
656 0 : centerc1 = (minc1 + maxc1) >> 1;
657 0 : maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
658 0 : 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.
667 : */
668 0 : minmaxdist = 0x7FFFFFFFL;
669 :
670 0 : for (i = 0; i < numcolors; i++) {
671 : /* We compute the squared-c0-distance term, then add in the other two. */
672 0 : x = GETJSAMPLE(cinfo->colormap[0][i]);
673 0 : if (x < minc0) {
674 0 : tdist = (x - minc0) * C0_SCALE;
675 0 : min_dist = tdist*tdist;
676 0 : tdist = (x - maxc0) * C0_SCALE;
677 0 : max_dist = tdist*tdist;
678 0 : } else if (x > maxc0) {
679 0 : tdist = (x - maxc0) * C0_SCALE;
680 0 : min_dist = tdist*tdist;
681 0 : tdist = (x - minc0) * C0_SCALE;
682 0 : max_dist = tdist*tdist;
683 : } else {
684 : /* within cell range so no contribution to min_dist */
685 0 : min_dist = 0;
686 0 : if (x <= centerc0) {
687 0 : tdist = (x - maxc0) * C0_SCALE;
688 0 : max_dist = tdist*tdist;
689 : } else {
690 0 : tdist = (x - minc0) * C0_SCALE;
691 0 : max_dist = tdist*tdist;
692 : }
693 : }
694 :
695 0 : x = GETJSAMPLE(cinfo->colormap[1][i]);
696 0 : if (x < minc1) {
697 0 : tdist = (x - minc1) * C1_SCALE;
698 0 : min_dist += tdist*tdist;
699 0 : tdist = (x - maxc1) * C1_SCALE;
700 0 : max_dist += tdist*tdist;
701 0 : } else if (x > maxc1) {
702 0 : tdist = (x - maxc1) * C1_SCALE;
703 0 : min_dist += tdist*tdist;
704 0 : tdist = (x - minc1) * C1_SCALE;
705 0 : max_dist += tdist*tdist;
706 : } else {
707 : /* within cell range so no contribution to min_dist */
708 0 : if (x <= centerc1) {
709 0 : tdist = (x - maxc1) * C1_SCALE;
710 0 : max_dist += tdist*tdist;
711 : } else {
712 0 : tdist = (x - minc1) * C1_SCALE;
713 0 : max_dist += tdist*tdist;
714 : }
715 : }
716 :
717 0 : x = GETJSAMPLE(cinfo->colormap[2][i]);
718 0 : if (x < minc2) {
719 0 : tdist = (x - minc2) * C2_SCALE;
720 0 : min_dist += tdist*tdist;
721 0 : tdist = (x - maxc2) * C2_SCALE;
722 0 : max_dist += tdist*tdist;
723 0 : } else if (x > maxc2) {
724 0 : tdist = (x - maxc2) * C2_SCALE;
725 0 : min_dist += tdist*tdist;
726 0 : tdist = (x - minc2) * C2_SCALE;
727 0 : max_dist += tdist*tdist;
728 : } else {
729 : /* within cell range so no contribution to min_dist */
730 0 : if (x <= centerc2) {
731 0 : tdist = (x - maxc2) * C2_SCALE;
732 0 : max_dist += tdist*tdist;
733 : } else {
734 0 : tdist = (x - minc2) * C2_SCALE;
735 0 : max_dist += tdist*tdist;
736 : }
737 : }
738 :
739 0 : mindist[i] = min_dist; /* save away the results */
740 0 : if (max_dist < minmaxdist)
741 0 : 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 0 : ncolors = 0;
749 0 : for (i = 0; i < numcolors; i++) {
750 0 : if (mindist[i] <= minmaxdist)
751 0 : colorlist[ncolors++] = (JSAMPLE) i;
752 : }
753 0 : return ncolors;
754 : }
755 :
756 :
757 : LOCAL(void)
758 0 : find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
759 : 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 */
777 : INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
778 :
779 : /* Initialize best-distance for each cell of the update box */
780 0 : bptr = bestdist;
781 0 : for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
782 0 : *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.
787 : */
788 :
789 : /* Nominal steps between cell centers ("x" in Thomas article) */
790 : #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)
793 :
794 0 : for (i = 0; i < numcolors; i++) {
795 0 : icolor = GETJSAMPLE(colorlist[i]);
796 : /* Compute (square of) distance from minc0/c1/c2 to this color */
797 0 : inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
798 0 : dist0 = inc0*inc0;
799 0 : inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
800 0 : dist0 += inc1*inc1;
801 0 : inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
802 0 : dist0 += inc2*inc2;
803 : /* Form the initial difference increments */
804 0 : inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
805 0 : inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
806 0 : inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
807 : /* Now loop over all cells in box, updating distance per Thomas method */
808 0 : bptr = bestdist;
809 0 : cptr = bestcolor;
810 0 : xx0 = inc0;
811 0 : for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
812 0 : dist1 = dist0;
813 0 : xx1 = inc1;
814 0 : for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
815 0 : dist2 = dist1;
816 0 : xx2 = inc2;
817 0 : for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
818 0 : if (dist2 < *bptr) {
819 0 : *bptr = dist2;
820 0 : *cptr = (JSAMPLE) icolor;
821 : }
822 0 : dist2 += xx2;
823 0 : xx2 += 2 * STEP_C2 * STEP_C2;
824 0 : bptr++;
825 0 : cptr++;
826 : }
827 0 : dist1 += xx1;
828 0 : xx1 += 2 * STEP_C1 * STEP_C1;
829 : }
830 0 : dist0 += xx0;
831 0 : xx0 += 2 * STEP_C0 * STEP_C0;
832 : }
833 : }
834 0 : }
835 :
836 :
837 : LOCAL(void)
838 0 : fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
839 : /* 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 : {
843 0 : my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
844 0 : hist3d histogram = cquantize->histogram;
845 : 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. */
853 : JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
854 :
855 : /* Convert cell coordinates to update box ID */
856 0 : c0 >>= BOX_C0_LOG;
857 0 : c1 >>= BOX_C1_LOG;
858 0 : c2 >>= BOX_C2_LOG;
859 :
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 : */
864 0 : minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
865 0 : minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
866 0 : minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
867 :
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 0 : numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
872 :
873 : /* Determine the actually nearest colors. */
874 0 : 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 */
878 0 : c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
879 0 : c1 <<= BOX_C1_LOG;
880 0 : c2 <<= BOX_C2_LOG;
881 0 : cptr = bestcolor;
882 0 : for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
883 0 : for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
884 0 : cachep = & histogram[c0+ic0][c1+ic1][c2];
885 0 : for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
886 0 : *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
887 : }
888 : }
889 : }
890 0 : }
891 :
892 :
893 : /*
894 : * Map some rows of pixels to the output colormapped representation.
895 : */
896 :
897 : METHODDEF(void)
898 0 : pass2_no_dither (j_decompress_ptr cinfo,
899 : JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
900 : /* This version performs no dithering */
901 : {
902 0 : my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
903 0 : hist3d histogram = cquantize->histogram;
904 : register JSAMPROW inptr, outptr;
905 : register histptr cachep;
906 : register int c0, c1, c2;
907 : int row;
908 : JDIMENSION col;
909 0 : JDIMENSION width = cinfo->output_width;
910 :
911 0 : for (row = 0; row < num_rows; row++) {
912 0 : inptr = input_buf[row];
913 0 : outptr = output_buf[row];
914 0 : for (col = width; col > 0; col--) {
915 : /* get pixel value and index into the cache */
916 0 : c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
917 0 : c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
918 0 : c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
919 0 : cachep = & histogram[c0][c1][c2];
920 : /* If we have not seen this color before, find nearest colormap entry */
921 : /* and update the cache */
922 0 : if (*cachep == 0)
923 0 : fill_inverse_cmap(cinfo, c0,c1,c2);
924 : /* Now emit the colormap index for this cell */
925 0 : *outptr++ = (JSAMPLE) (*cachep - 1);
926 : }
927 : }
928 0 : }
929 :
930 :
931 : METHODDEF(void)
932 0 : pass2_fs_dither (j_decompress_ptr cinfo,
933 : JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
934 : /* This version performs Floyd-Steinberg dithering */
935 : {
936 0 : my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
937 0 : hist3d histogram = cquantize->histogram;
938 : 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 */
942 : JSAMPROW inptr; /* => current input pixel */
943 : JSAMPROW outptr; /* => current output pixel */
944 : histptr cachep;
945 : int dir; /* +1 or -1 depending on direction */
946 : int dir3; /* 3*dir, for advancing inptr & errorptr */
947 : int row;
948 : JDIMENSION col;
949 0 : JDIMENSION width = cinfo->output_width;
950 0 : JSAMPLE *range_limit = cinfo->sample_range_limit;
951 0 : int *error_limit = cquantize->error_limiter;
952 0 : JSAMPROW colormap0 = cinfo->colormap[0];
953 0 : JSAMPROW colormap1 = cinfo->colormap[1];
954 0 : JSAMPROW colormap2 = cinfo->colormap[2];
955 : SHIFT_TEMPS
956 :
957 0 : for (row = 0; row < num_rows; row++) {
958 0 : inptr = input_buf[row];
959 0 : outptr = output_buf[row];
960 0 : if (cquantize->on_odd_row) {
961 : /* work right to left in this row */
962 0 : inptr += (width-1) * 3; /* so point to rightmost pixel */
963 0 : outptr += width-1;
964 0 : dir = -1;
965 0 : dir3 = -3;
966 0 : errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
967 0 : cquantize->on_odd_row = FALSE; /* flip for next time */
968 : } else {
969 : /* work left to right in this row */
970 0 : dir = 1;
971 0 : dir3 = 3;
972 0 : errorptr = cquantize->fserrors; /* => entry before first real column */
973 0 : cquantize->on_odd_row = TRUE; /* flip for next time */
974 : }
975 : /* Preset error values: no error propagated to first pixel from left */
976 0 : cur0 = cur1 = cur2 = 0;
977 : /* and no error propagated to row below yet */
978 0 : belowerr0 = belowerr1 = belowerr2 = 0;
979 0 : bpreverr0 = bpreverr1 = bpreverr2 = 0;
980 :
981 0 : for (col = width; col > 0; col--) {
982 : /* 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.
986 : * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
987 : * for either sign of the error value.
988 : * Note: errorptr points to *previous* column's array entry.
989 : */
990 0 : cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
991 0 : cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
992 0 : cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
993 : /* Limit the error using transfer function set by init_error_limit.
994 : * See comments with init_error_limit for rationale.
995 : */
996 0 : cur0 = error_limit[cur0];
997 0 : cur1 = error_limit[cur1];
998 0 : 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 0 : cur0 += GETJSAMPLE(inptr[0]);
1004 0 : cur1 += GETJSAMPLE(inptr[1]);
1005 0 : cur2 += GETJSAMPLE(inptr[2]);
1006 0 : cur0 = GETJSAMPLE(range_limit[cur0]);
1007 0 : cur1 = GETJSAMPLE(range_limit[cur1]);
1008 0 : cur2 = GETJSAMPLE(range_limit[cur2]);
1009 : /* Index into the cache with adjusted pixel value */
1010 0 : cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
1011 : /* If we have not seen this color before, find nearest colormap */
1012 : /* entry and update the cache */
1013 0 : if (*cachep == 0)
1014 0 : fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
1015 : /* Now emit the colormap index for this cell */
1016 0 : { register int pixcode = *cachep - 1;
1017 0 : *outptr = (JSAMPLE) pixcode;
1018 : /* Compute representation error for this pixel */
1019 0 : cur0 -= GETJSAMPLE(colormap0[pixcode]);
1020 0 : cur1 -= GETJSAMPLE(colormap1[pixcode]);
1021 0 : 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 0 : bnexterr = cur0; /* Process component 0 */
1030 0 : delta = cur0 * 2;
1031 0 : cur0 += delta; /* form error * 3 */
1032 0 : errorptr[0] = (FSERROR) (bpreverr0 + cur0);
1033 0 : cur0 += delta; /* form error * 5 */
1034 0 : bpreverr0 = belowerr0 + cur0;
1035 0 : belowerr0 = bnexterr;
1036 0 : cur0 += delta; /* form error * 7 */
1037 0 : bnexterr = cur1; /* Process component 1 */
1038 0 : delta = cur1 * 2;
1039 0 : cur1 += delta; /* form error * 3 */
1040 0 : errorptr[1] = (FSERROR) (bpreverr1 + cur1);
1041 0 : cur1 += delta; /* form error * 5 */
1042 0 : bpreverr1 = belowerr1 + cur1;
1043 0 : belowerr1 = bnexterr;
1044 0 : cur1 += delta; /* form error * 7 */
1045 0 : bnexterr = cur2; /* Process component 2 */
1046 0 : delta = cur2 * 2;
1047 0 : cur2 += delta; /* form error * 3 */
1048 0 : errorptr[2] = (FSERROR) (bpreverr2 + cur2);
1049 0 : cur2 += delta; /* form error * 5 */
1050 0 : bpreverr2 = belowerr2 + cur2;
1051 0 : belowerr2 = bnexterr;
1052 0 : 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 : */
1058 0 : inptr += dir3; /* Advance pixel pointers to next column */
1059 0 : outptr += dir;
1060 0 : errorptr += dir3; /* advance errorptr to current column */
1061 : }
1062 : /* 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 0 : errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
1067 0 : errorptr[1] = (FSERROR) bpreverr1;
1068 0 : errorptr[2] = (FSERROR) bpreverr2;
1069 : }
1070 0 : }
1071 :
1072 :
1073 : /*
1074 : * 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.
1088 : */
1089 :
1090 : LOCAL(void)
1091 0 : init_error_limit (j_decompress_ptr cinfo)
1092 : /* Allocate and fill in the error_limiter table */
1093 : {
1094 0 : my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1095 : int * table;
1096 : int in, out;
1097 :
1098 0 : table = (int *) (*cinfo->mem->alloc_small)
1099 0 : ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
1100 0 : table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
1101 0 : cquantize->error_limiter = table;
1102 :
1103 : #define STEPSIZE ((MAXJSAMPLE+1)/16)
1104 : /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
1105 0 : out = 0;
1106 0 : for (in = 0; in < STEPSIZE; in++, out++) {
1107 0 : table[in] = out; table[-in] = -out;
1108 : }
1109 : /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
1110 0 : for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
1111 0 : table[in] = out; table[-in] = -out;
1112 : }
1113 : /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
1114 0 : for (; in <= MAXJSAMPLE; in++) {
1115 0 : table[in] = out; table[-in] = -out;
1116 : }
1117 : #undef STEPSIZE
1118 0 : }
1119 :
1120 :
1121 : /*
1122 : * Finish up at the end of each pass.
1123 : */
1124 :
1125 : METHODDEF(void)
1126 0 : finish_pass1 (j_decompress_ptr cinfo)
1127 : {
1128 0 : my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1129 :
1130 : /* Select the representative colors and fill in cinfo->colormap */
1131 0 : cinfo->colormap = cquantize->sv_colormap;
1132 0 : select_colors(cinfo, cquantize->desired);
1133 : /* Force next pass to zero the color index table */
1134 0 : cquantize->needs_zeroed = TRUE;
1135 0 : }
1136 :
1137 :
1138 : METHODDEF(void)
1139 0 : finish_pass2 (j_decompress_ptr cinfo)
1140 : {
1141 : /* no work */
1142 0 : }
1143 :
1144 :
1145 : /*
1146 : * Initialize for each processing pass.
1147 : */
1148 :
1149 : METHODDEF(void)
1150 0 : start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
1151 : {
1152 0 : my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1153 0 : hist3d histogram = cquantize->histogram;
1154 : int i;
1155 :
1156 : /* Only F-S dithering or no dithering is supported. */
1157 : /* If user asks for ordered dither, give him F-S. */
1158 0 : if (cinfo->dither_mode != JDITHER_NONE)
1159 0 : cinfo->dither_mode = JDITHER_FS;
1160 :
1161 0 : if (is_pre_scan) {
1162 : /* Set up method pointers */
1163 0 : cquantize->pub.color_quantize = prescan_quantize;
1164 0 : cquantize->pub.finish_pass = finish_pass1;
1165 0 : cquantize->needs_zeroed = TRUE; /* Always zero histogram */
1166 : } else {
1167 : /* Set up method pointers */
1168 0 : if (cinfo->dither_mode == JDITHER_FS)
1169 0 : cquantize->pub.color_quantize = pass2_fs_dither;
1170 : else
1171 0 : cquantize->pub.color_quantize = pass2_no_dither;
1172 0 : cquantize->pub.finish_pass = finish_pass2;
1173 :
1174 : /* Make sure color count is acceptable */
1175 0 : i = cinfo->actual_number_of_colors;
1176 0 : if (i < 1)
1177 0 : ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
1178 0 : if (i > MAXNUMCOLORS)
1179 0 : ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
1180 :
1181 0 : if (cinfo->dither_mode == JDITHER_FS) {
1182 0 : size_t arraysize = (size_t) ((cinfo->output_width + 2) *
1183 : (3 * SIZEOF(FSERROR)));
1184 : /* Allocate Floyd-Steinberg workspace if we didn't already. */
1185 0 : if (cquantize->fserrors == NULL)
1186 0 : cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
1187 0 : ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
1188 : /* Initialize the propagated errors to zero. */
1189 0 : jzero_far((void FAR *) cquantize->fserrors, arraysize);
1190 : /* Make the error-limit table if we didn't already. */
1191 0 : if (cquantize->error_limiter == NULL)
1192 0 : init_error_limit(cinfo);
1193 0 : cquantize->on_odd_row = FALSE;
1194 : }
1195 :
1196 : }
1197 : /* Zero the histogram or inverse color map, if necessary */
1198 0 : if (cquantize->needs_zeroed) {
1199 0 : for (i = 0; i < HIST_C0_ELEMS; i++) {
1200 0 : jzero_far((void FAR *) histogram[i],
1201 : HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
1202 : }
1203 0 : cquantize->needs_zeroed = FALSE;
1204 : }
1205 0 : }
1206 :
1207 :
1208 : /*
1209 : * Switch to a new external colormap between output passes.
1210 : */
1211 :
1212 : METHODDEF(void)
1213 0 : new_color_map_2_quant (j_decompress_ptr cinfo)
1214 : {
1215 0 : my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1216 :
1217 : /* Reset the inverse color map */
1218 0 : cquantize->needs_zeroed = TRUE;
1219 0 : }
1220 :
1221 :
1222 : /*
1223 : * Module initialization routine for 2-pass color quantization.
1224 : */
1225 :
1226 : GLOBAL(void)
1227 0 : jinit_2pass_quantizer (j_decompress_ptr cinfo)
1228 : {
1229 : my_cquantize_ptr cquantize;
1230 : int i;
1231 :
1232 0 : cquantize = (my_cquantize_ptr)
1233 0 : (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
1234 : SIZEOF(my_cquantizer));
1235 0 : cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
1236 0 : cquantize->pub.start_pass = start_pass_2_quant;
1237 0 : cquantize->pub.new_color_map = new_color_map_2_quant;
1238 0 : cquantize->fserrors = NULL; /* flag optional arrays not allocated */
1239 0 : cquantize->error_limiter = NULL;
1240 :
1241 : /* Make sure jdmaster didn't give me a case I can't handle */
1242 0 : if (cinfo->out_color_components != 3)
1243 0 : ERREXIT(cinfo, JERR_NOTIMPL);
1244 :
1245 : /* Allocate the histogram/inverse colormap storage */
1246 0 : cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
1247 0 : ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
1248 0 : for (i = 0; i < HIST_C0_ELEMS; i++) {
1249 0 : cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
1250 0 : ((j_common_ptr) cinfo, JPOOL_IMAGE,
1251 : HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
1252 : }
1253 0 : cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
1254 :
1255 : /* Allocate storage for the completed colormap, if required.
1256 : * We do this now since it is FAR storage and may affect
1257 : * the memory manager's space calculations.
1258 : */
1259 0 : if (cinfo->enable_2pass_quant) {
1260 : /* Make sure color count is acceptable */
1261 0 : int desired = cinfo->desired_number_of_colors;
1262 : /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
1263 0 : if (desired < 8)
1264 0 : ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
1265 : /* Make sure colormap indexes can be represented by JSAMPLEs */
1266 0 : if (desired > MAXNUMCOLORS)
1267 0 : ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
1268 0 : cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
1269 0 : ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
1270 0 : cquantize->desired = desired;
1271 : } else
1272 0 : cquantize->sv_colormap = NULL;
1273 :
1274 : /* Only F-S dithering or no dithering is supported. */
1275 : /* If user asks for ordered dither, give him F-S. */
1276 0 : if (cinfo->dither_mode != JDITHER_NONE)
1277 0 : 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 : */
1284 0 : if (cinfo->dither_mode == JDITHER_FS) {
1285 0 : cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
1286 0 : ((j_common_ptr) cinfo, JPOOL_IMAGE,
1287 0 : (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
1288 : /* Might as well create the error-limiting table too. */
1289 0 : init_error_limit(cinfo);
1290 : }
1291 0 : }
1292 :
1293 : #endif /* QUANT_2PASS_SUPPORTED */
|