source: trunk/src/3rdparty/libjpeg/jquant2.c@ 561

Last change on this file since 561 was 2, checked in by Dmitry A. Kuminov, 17 years ago

Initially imported qt-all-opensource-src-4.5.1 from Trolltech.

File size: 47.3 KB
Line 
1/*
2 * jquant2.c
3 *
4 * Copyright (C) 1991-1996, Thomas G. Lane.
5 * This file is part of the Independent JPEG Group's software.
6 * For conditions of distribution and use, see the accompanying README file.
7 *
8 * This file contains 2-pass color quantization (color mapping) routines.
9 * These routines provide selection of a custom color map for an image,
10 * followed by mapping of the image to that color map, with optional
11 * Floyd-Steinberg dithering.
12 * It is also possible to use just the second pass to map to an arbitrary
13 * externally-given color map.
14 *
15 * Note: ordered dithering is not supported, since there isn't any fast
16 * way to compute intercolor distances; it's unclear that ordered dither's
17 * fundamental assumptions even hold with an irregularly spaced color map.
18 */
19
20#define JPEG_INTERNALS
21#include "jinclude.h"
22#include "jpeglib.h"
23
24#ifdef QUANT_2PASS_SUPPORTED
25
26
27/*
28 * This module implements the well-known Heckbert paradigm for color
29 * quantization. Most of the ideas used here can be traced back to
30 * Heckbert's seminal paper
31 * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
32 * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
33 *
34 * In the first pass over the image, we accumulate a histogram showing the
35 * usage count of each possible color. To keep the histogram to a reasonable
36 * size, we reduce the precision of the input; typical practice is to retain
37 * 5 or 6 bits per color, so that 8 or 4 different input values are counted
38 * in the same histogram cell.
39 *
40 * Next, the color-selection step begins with a box representing the whole
41 * color space, and repeatedly splits the "largest" remaining box until we
42 * have as many boxes as desired colors. Then the mean color in each
43 * remaining box becomes one of the possible output colors.
44 *
45 * The second pass over the image maps each input pixel to the closest output
46 * color (optionally after applying a Floyd-Steinberg dithering correction).
47 * This mapping is logically trivial, but making it go fast enough requires
48 * considerable care.
49 *
50 * Heckbert-style quantizers vary a good deal in their policies for choosing
51 * the "largest" box and deciding where to cut it. The particular policies
52 * used here have proved out well in experimental comparisons, but better ones
53 * may yet be found.
54 *
55 * In earlier versions of the IJG code, this module quantized in YCbCr color
56 * space, processing the raw upsampled data without a color conversion step.
57 * This allowed the color conversion math to be done only once per colormap
58 * entry, not once per pixel. However, that optimization precluded other
59 * useful optimizations (such as merging color conversion with upsampling)
60 * and it also interfered with desired capabilities such as quantizing to an
61 * externally-supplied colormap. We have therefore abandoned that approach.
62 * The present code works in the post-conversion color space, typically RGB.
63 *
64 * To improve the visual quality of the results, we actually work in scaled
65 * RGB space, giving G distances more weight than R, and R in turn more than
66 * B. To do everything in integer math, we must use integer scale factors.
67 * The 2/3/1 scale factors used here correspond loosely to the relative
68 * weights of the colors in the NTSC grayscale equation.
69 * If you want to use this code to quantize a non-RGB color space, you'll
70 * probably need to change these scale factors.
71 */
72
73#define R_SCALE 2 /* scale R distances by this much */
74#define G_SCALE 3 /* scale G distances by this much */
75#define B_SCALE 1 /* and B by this much */
76
77/* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
78 * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
79 * and B,G,R orders. If you define some other weird order in jmorecfg.h,
80 * you'll get compile errors until you extend this logic. In that case
81 * you'll probably want to tweak the histogram sizes too.
82 */
83
84#if RGB_RED == 0
85#define C0_SCALE R_SCALE
86#endif
87#if RGB_BLUE == 0
88#define C0_SCALE B_SCALE
89#endif
90#if RGB_GREEN == 1
91#define C1_SCALE G_SCALE
92#endif
93#if RGB_RED == 2
94#define C2_SCALE R_SCALE
95#endif
96#if RGB_BLUE == 2
97#define C2_SCALE B_SCALE
98#endif
99
100
101/*
102 * First we have the histogram data structure and routines for creating it.
103 *
104 * The number of bits of precision can be adjusted by changing these symbols.
105 * We recommend keeping 6 bits for G and 5 each for R and B.
106 * If you have plenty of memory and cycles, 6 bits all around gives marginally
107 * better results; if you are short of memory, 5 bits all around will save
108 * some space but degrade the results.
109 * To maintain a fully accurate histogram, we'd need to allocate a "long"
110 * (preferably unsigned long) for each cell. In practice this is overkill;
111 * we can get by with 16 bits per cell. Few of the cell counts will overflow,
112 * and clamping those that do overflow to the maximum value will give close-
113 * enough results. This reduces the recommended histogram size from 256Kb
114 * to 128Kb, which is a useful savings on PC-class machines.
115 * (In the second pass the histogram space is re-used for pixel mapping data;
116 * in that capacity, each cell must be able to store zero to the number of
117 * desired colors. 16 bits/cell is plenty for that too.)
118 * Since the JPEG code is intended to run in small memory model on 80x86
119 * machines, we can't just allocate the histogram in one chunk. Instead
120 * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
121 * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
122 * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
123 * on 80x86 machines, the pointer row is in near memory but the actual
124 * arrays are in far memory (same arrangement as we use for image arrays).
125 */
126
127#define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
128
129/* These will do the right thing for either R,G,B or B,G,R color order,
130 * but you may not like the results for other color orders.
131 */
132#define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
133#define HIST_C1_BITS 6 /* bits of precision in G histogram */
134#define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
135
136/* Number of elements along histogram axes. */
137#define HIST_C0_ELEMS (1<<HIST_C0_BITS)
138#define HIST_C1_ELEMS (1<<HIST_C1_BITS)
139#define HIST_C2_ELEMS (1<<HIST_C2_BITS)
140
141/* These are the amounts to shift an input value to get a histogram index. */
142#define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
143#define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
144#define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
145
146
147typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
148
149typedef histcell FAR * histptr; /* for pointers to histogram cells */
150
151typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
152typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
153typedef hist2d * hist3d; /* type for top-level pointer */
154
155
156/* Declarations for Floyd-Steinberg dithering.
157 *
158 * Errors are accumulated into the array fserrors[], at a resolution of
159 * 1/16th of a pixel count. The error at a given pixel is propagated
160 * to its not-yet-processed neighbors using the standard F-S fractions,
161 * ... (here) 7/16
162 * 3/16 5/16 1/16
163 * We work left-to-right on even rows, right-to-left on odd rows.
164 *
165 * We can get away with a single array (holding one row's worth of errors)
166 * by using it to store the current row's errors at pixel columns not yet
167 * processed, but the next row's errors at columns already processed. We
168 * need only a few extra variables to hold the errors immediately around the
169 * current column. (If we are lucky, those variables are in registers, but
170 * even if not, they're probably cheaper to access than array elements are.)
171 *
172 * The fserrors[] array has (#columns + 2) entries; the extra entry at
173 * each end saves us from special-casing the first and last pixels.
174 * Each entry is three values long, one value for each color component.
175 *
176 * Note: on a wide image, we might not have enough room in a PC's near data
177 * segment to hold the error array; so it is allocated with alloc_large.
178 */
179
180#if BITS_IN_JSAMPLE == 8
181typedef INT16 FSERROR; /* 16 bits should be enough */
182typedef int LOCFSERROR; /* use 'int' for calculation temps */
183#else
184typedef INT32 FSERROR; /* may need more than 16 bits */
185typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
186#endif
187
188typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
189
190
191/* Private subobject */
192
193typedef struct {
194 struct jpeg_color_quantizer pub; /* public fields */
195
196 /* Space for the eventually created colormap is stashed here */
197 JSAMPARRAY sv_colormap; /* colormap allocated at init time */
198 int desired; /* desired # of colors = size of colormap */
199
200 /* Variables for accumulating image statistics */
201 hist3d histogram; /* pointer to the histogram */
202
203 boolean needs_zeroed; /* TRUE if next pass must zero histogram */
204
205 /* Variables for Floyd-Steinberg dithering */
206 FSERRPTR fserrors; /* accumulated errors */
207 boolean on_odd_row; /* flag to remember which row we are on */
208 int * error_limiter; /* table for clamping the applied error */
209} my_cquantizer;
210
211typedef my_cquantizer * my_cquantize_ptr;
212
213
214/*
215 * Prescan some rows of pixels.
216 * In this module the prescan simply updates the histogram, which has been
217 * initialized to zeroes by start_pass.
218 * An output_buf parameter is required by the method signature, but no data
219 * is actually output (in fact the buffer controller is probably passing a
220 * NULL pointer).
221 */
222
223METHODDEF(void)
224prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
225 JSAMPARRAY output_buf, int num_rows)
226{
227 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
228 register JSAMPROW ptr;
229 register histptr histp;
230 register hist3d histogram = cquantize->histogram;
231 int row;
232 JDIMENSION col;
233 JDIMENSION width = cinfo->output_width;
234
235 for (row = 0; row < num_rows; row++) {
236 ptr = input_buf[row];
237 for (col = width; col > 0; col--) {
238 /* get pixel value and index into the histogram */
239 histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
240 [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
241 [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
242 /* increment, check for overflow and undo increment if so. */
243 if (++(*histp) <= 0)
244 (*histp)--;
245 ptr += 3;
246 }
247 }
248}
249
250
251/*
252 * Next we have the really interesting routines: selection of a colormap
253 * given the completed histogram.
254 * These routines work with a list of "boxes", each representing a rectangular
255 * subset of the input color space (to histogram precision).
256 */
257
258typedef struct {
259 /* The bounds of the box (inclusive); expressed as histogram indexes */
260 int c0min, c0max;
261 int c1min, c1max;
262 int c2min, c2max;
263 /* The volume (actually 2-norm) of the box */
264 INT32 volume;
265 /* The number of nonzero histogram cells within this box */
266 long colorcount;
267} box;
268
269typedef box * boxptr;
270
271
272LOCAL(boxptr)
273find_biggest_color_pop (boxptr boxlist, int numboxes)
274/* Find the splittable box with the largest color population */
275/* Returns NULL if no splittable boxes remain */
276{
277 register boxptr boxp;
278 register int i;
279 register long maxc = 0;
280 boxptr which = NULL;
281
282 for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
283 if (boxp->colorcount > maxc && boxp->volume > 0) {
284 which = boxp;
285 maxc = boxp->colorcount;
286 }
287 }
288 return which;
289}
290
291
292LOCAL(boxptr)
293find_biggest_volume (boxptr boxlist, int numboxes)
294/* Find the splittable box with the largest (scaled) volume */
295/* Returns NULL if no splittable boxes remain */
296{
297 register boxptr boxp;
298 register int i;
299 register INT32 maxv = 0;
300 boxptr which = NULL;
301
302 for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
303 if (boxp->volume > maxv) {
304 which = boxp;
305 maxv = boxp->volume;
306 }
307 }
308 return which;
309}
310
311
312LOCAL(void)
313update_box (j_decompress_ptr cinfo, boxptr boxp)
314/* Shrink the min/max bounds of a box to enclose only nonzero elements, */
315/* and recompute its volume and population */
316{
317 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
318 hist3d histogram = cquantize->histogram;
319 histptr histp;
320 int c0,c1,c2;
321 int c0min,c0max,c1min,c1max,c2min,c2max;
322 INT32 dist0,dist1,dist2;
323 long ccount;
324
325 c0min = boxp->c0min; c0max = boxp->c0max;
326 c1min = boxp->c1min; c1max = boxp->c1max;
327 c2min = boxp->c2min; c2max = boxp->c2max;
328
329 if (c0max > c0min)
330 for (c0 = c0min; c0 <= c0max; c0++)
331 for (c1 = c1min; c1 <= c1max; c1++) {
332 histp = & histogram[c0][c1][c2min];
333 for (c2 = c2min; c2 <= c2max; c2++)
334 if (*histp++ != 0) {
335 boxp->c0min = c0min = c0;
336 goto have_c0min;
337 }
338 }
339 have_c0min:
340 if (c0max > c0min)
341 for (c0 = c0max; c0 >= c0min; c0--)
342 for (c1 = c1min; c1 <= c1max; c1++) {
343 histp = & histogram[c0][c1][c2min];
344 for (c2 = c2min; c2 <= c2max; c2++)
345 if (*histp++ != 0) {
346 boxp->c0max = c0max = c0;
347 goto have_c0max;
348 }
349 }
350 have_c0max:
351 if (c1max > c1min)
352 for (c1 = c1min; c1 <= c1max; c1++)
353 for (c0 = c0min; c0 <= c0max; c0++) {
354 histp = & histogram[c0][c1][c2min];
355 for (c2 = c2min; c2 <= c2max; c2++)
356 if (*histp++ != 0) {
357 boxp->c1min = c1min = c1;
358 goto have_c1min;
359 }
360 }
361 have_c1min:
362 if (c1max > c1min)
363 for (c1 = c1max; c1 >= c1min; c1--)
364 for (c0 = c0min; c0 <= c0max; c0++) {
365 histp = & histogram[c0][c1][c2min];
366 for (c2 = c2min; c2 <= c2max; c2++)
367 if (*histp++ != 0) {
368 boxp->c1max = c1max = c1;
369 goto have_c1max;
370 }
371 }
372 have_c1max:
373 if (c2max > c2min)
374 for (c2 = c2min; c2 <= c2max; c2++)
375 for (c0 = c0min; c0 <= c0max; c0++) {
376 histp = & histogram[c0][c1min][c2];
377 for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
378 if (*histp != 0) {
379 boxp->c2min = c2min = c2;
380 goto have_c2min;
381 }
382 }
383 have_c2min:
384 if (c2max > c2min)
385 for (c2 = c2max; c2 >= c2min; c2--)
386 for (c0 = c0min; c0 <= c0max; c0++) {
387 histp = & histogram[c0][c1min][c2];
388 for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
389 if (*histp != 0) {
390 boxp->c2max = c2max = c2;
391 goto have_c2max;
392 }
393 }
394 have_c2max:
395
396 /* Update box volume.
397 * We use 2-norm rather than real volume here; this biases the method
398 * against making long narrow boxes, and it has the side benefit that
399 * a box is splittable iff norm > 0.
400 * Since the differences are expressed in histogram-cell units,
401 * we have to shift back to JSAMPLE units to get consistent distances;
402 * after which, we scale according to the selected distance scale factors.
403 */
404 dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
405 dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
406 dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
407 boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
408
409 /* Now scan remaining volume of box and compute population */
410 ccount = 0;
411 for (c0 = c0min; c0 <= c0max; c0++)
412 for (c1 = c1min; c1 <= c1max; c1++) {
413 histp = & histogram[c0][c1][c2min];
414 for (c2 = c2min; c2 <= c2max; c2++, histp++)
415 if (*histp != 0) {
416 ccount++;
417 }
418 }
419 boxp->colorcount = ccount;
420}
421
422
423LOCAL(int)
424median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
425 int desired_colors)
426/* Repeatedly select and split the largest box until we have enough boxes */
427{
428 int n,lb;
429 int c0,c1,c2,cmax;
430 register boxptr b1,b2;
431
432 while (numboxes < desired_colors) {
433 /* Select box to split.
434 * Current algorithm: by population for first half, then by volume.
435 */
436 if (numboxes*2 <= desired_colors) {
437 b1 = find_biggest_color_pop(boxlist, numboxes);
438 } else {
439 b1 = find_biggest_volume(boxlist, numboxes);
440 }
441 if (b1 == NULL) /* no splittable boxes left! */
442 break;
443 b2 = &boxlist[numboxes]; /* where new box will go */
444 /* Copy the color bounds to the new box. */
445 b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
446 b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
447 /* Choose which axis to split the box on.
448 * Current algorithm: longest scaled axis.
449 * See notes in update_box about scaling distances.
450 */
451 c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
452 c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
453 c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
454 /* We want to break any ties in favor of green, then red, blue last.
455 * This code does the right thing for R,G,B or B,G,R color orders only.
456 */
457#if RGB_RED == 0
458 cmax = c1; n = 1;
459 if (c0 > cmax) { cmax = c0; n = 0; }
460 if (c2 > cmax) { n = 2; }
461#else
462 cmax = c1; n = 1;
463 if (c2 > cmax) { cmax = c2; n = 2; }
464 if (c0 > cmax) { n = 0; }
465#endif
466 /* Choose split point along selected axis, and update box bounds.
467 * Current algorithm: split at halfway point.
468 * (Since the box has been shrunk to minimum volume,
469 * any split will produce two nonempty subboxes.)
470 * Note that lb value is max for lower box, so must be < old max.
471 */
472 switch (n) {
473 case 0:
474 lb = (b1->c0max + b1->c0min) / 2;
475 b1->c0max = lb;
476 b2->c0min = lb+1;
477 break;
478 case 1:
479 lb = (b1->c1max + b1->c1min) / 2;
480 b1->c1max = lb;
481 b2->c1min = lb+1;
482 break;
483 case 2:
484 lb = (b1->c2max + b1->c2min) / 2;
485 b1->c2max = lb;
486 b2->c2min = lb+1;
487 break;
488 }
489 /* Update stats for boxes */
490 update_box(cinfo, b1);