1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxQuantize implementation
4 // Author: Julian Smart
8 // Copyright: (c) Thomas G. Lane, Vaclav Slavik, Julian Smart
9 // Licence: wxWindows licence + JPEG library licence
10 /////////////////////////////////////////////////////////////////////////////
15 * Copyright (C) 1991-1996, Thomas G. Lane.
16 * This file is part of the Independent JPEG Group's software.
17 * For conditions of distribution and use, see the accompanying README file.
19 * This file contains 2-pass color quantization (color mapping) routines.
20 * These routines provide selection of a custom color map for an image,
21 * followed by mapping of the image to that color map, with optional
22 * Floyd-Steinberg dithering.
23 * It is also possible to use just the second pass to map to an arbitrary
24 * externally-given color map.
26 * Note: ordered dithering is not supported, since there isn't any fast
27 * way to compute intercolor distances; it's unclear that ordered dither's
28 * fundamental assumptions even hold with an irregularly spaced color map.
31 /* modified by Vaclav Slavik for use as jpeglib-independent module */
33 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
34 #pragma implementation "quantize.h"
37 // For compilers that support precompilation, includes "wx/wx.h".
38 #include "wx/wxprec.h"
45 #include "wx/palette.h"
51 #include "wx/quantize.h"
54 #include "wx/msw/private.h"
62 #define RGB_GREEN_OS2 1
63 #define RGB_BLUE_OS2 2
69 #define RGB_PIXELSIZE 3
71 #define MAXJSAMPLE 255
72 #define CENTERJSAMPLE 128
73 #define BITS_IN_JSAMPLE 8
74 #define GETJSAMPLE(value) ((int) (value))
76 #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
78 typedef unsigned short UINT16
;
79 typedef signed short INT16
;
80 typedef signed int INT32
;
82 typedef unsigned char JSAMPLE
;
83 typedef JSAMPLE
*JSAMPROW
;
84 typedef JSAMPROW
*JSAMPARRAY
;
85 typedef unsigned int JDIMENSION
;
89 JDIMENSION output_width
;
91 int actual_number_of_colors
;
92 int desired_number_of_colors
;
93 JSAMPLE
*sample_range_limit
, *srl_orig
;
96 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
97 #define JMETHOD(type,methodname,arglist) type (__cdecl methodname) arglist
99 #define JMETHOD(type,methodname,arglist) type (methodname) arglist
102 typedef j_decompress
*j_decompress_ptr
;
103 struct jpeg_color_quantizer
{
104 JMETHOD(void, start_pass
, (j_decompress_ptr cinfo
, bool is_pre_scan
));
105 JMETHOD(void, color_quantize
, (j_decompress_ptr cinfo
,
106 JSAMPARRAY input_buf
, JSAMPARRAY output_buf
,
108 JMETHOD(void, finish_pass
, (j_decompress_ptr cinfo
));
109 JMETHOD(void, new_color_map
, (j_decompress_ptr cinfo
));
116 * This module implements the well-known Heckbert paradigm for color
117 * quantization. Most of the ideas used here can be traced back to
118 * Heckbert's seminal paper
119 * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
120 * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
122 * In the first pass over the image, we accumulate a histogram showing the
123 * usage count of each possible color. To keep the histogram to a reasonable
124 * size, we reduce the precision of the input; typical practice is to retain
125 * 5 or 6 bits per color, so that 8 or 4 different input values are counted
126 * in the same histogram cell.
128 * Next, the color-selection step begins with a box representing the whole
129 * color space, and repeatedly splits the "largest" remaining box until we
130 * have as many boxes as desired colors. Then the mean color in each
131 * remaining box becomes one of the possible output colors.
133 * The second pass over the image maps each input pixel to the closest output
134 * color (optionally after applying a Floyd-Steinberg dithering correction).
135 * This mapping is logically trivial, but making it go fast enough requires
138 * Heckbert-style quantizers vary a good deal in their policies for choosing
139 * the "largest" box and deciding where to cut it. The particular policies
140 * used here have proved out well in experimental comparisons, but better ones
143 * In earlier versions of the IJG code, this module quantized in YCbCr color
144 * space, processing the raw upsampled data without a color conversion step.
145 * This allowed the color conversion math to be done only once per colormap
146 * entry, not once per pixel. However, that optimization precluded other
147 * useful optimizations (such as merging color conversion with upsampling)
148 * and it also interfered with desired capabilities such as quantizing to an
149 * externally-supplied colormap. We have therefore abandoned that approach.
150 * The present code works in the post-conversion color space, typically RGB.
152 * To improve the visual quality of the results, we actually work in scaled
153 * RGB space, giving G distances more weight than R, and R in turn more than
154 * B. To do everything in integer math, we must use integer scale factors.
155 * The 2/3/1 scale factors used here correspond loosely to the relative
156 * weights of the colors in the NTSC grayscale equation.
157 * If you want to use this code to quantize a non-RGB color space, you'll
158 * probably need to change these scale factors.
161 #define R_SCALE 2 /* scale R distances by this much */
162 #define G_SCALE 3 /* scale G distances by this much */
163 #define B_SCALE 1 /* and B by this much */
165 /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
166 * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
167 * and B,G,R orders. If you define some other weird order in jmorecfg.h,
168 * you'll get compile errors until you extend this logic. In that case
169 * you'll probably want to tweak the histogram sizes too.
175 #define C0_SCALE R_SCALE
177 #if RGB_BLUE_OS2 == 0
178 #define C0_SCALE B_SCALE
180 #if RGB_GREEN_OS2 == 1
181 #define C1_SCALE G_SCALE
184 #define C2_SCALE R_SCALE
186 #if RGB_BLUE_OS2 == 2
187 #define C2_SCALE B_SCALE
193 #define C0_SCALE R_SCALE
196 #define C0_SCALE B_SCALE
199 #define C1_SCALE G_SCALE
202 #define C2_SCALE R_SCALE
205 #define C2_SCALE B_SCALE
211 * First we have the histogram data structure and routines for creating it.
213 * The number of bits of precision can be adjusted by changing these symbols.
214 * We recommend keeping 6 bits for G and 5 each for R and B.
215 * If you have plenty of memory and cycles, 6 bits all around gives marginally
216 * better results; if you are short of memory, 5 bits all around will save
217 * some space but degrade the results.
218 * To maintain a fully accurate histogram, we'd need to allocate a "long"
219 * (preferably unsigned long) for each cell. In practice this is overkill;
220 * we can get by with 16 bits per cell. Few of the cell counts will overflow,
221 * and clamping those that do overflow to the maximum value will give close-
222 * enough results. This reduces the recommended histogram size from 256Kb
223 * to 128Kb, which is a useful savings on PC-class machines.
224 * (In the second pass the histogram space is re-used for pixel mapping data;
225 * in that capacity, each cell must be able to store zero to the number of
226 * desired colors. 16 bits/cell is plenty for that too.)
227 * Since the JPEG code is intended to run in small memory model on 80x86
228 * machines, we can't just allocate the histogram in one chunk. Instead
229 * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
230 * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
231 * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
232 * on 80x86 machines, the pointer row is in near memory but the actual
233 * arrays are in far memory (same arrangement as we use for image arrays).
236 #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
238 /* These will do the right thing for either R,G,B or B,G,R color order,
239 * but you may not like the results for other color orders.
241 #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
242 #define HIST_C1_BITS 6 /* bits of precision in G histogram */
243 #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
245 /* Number of elements along histogram axes. */
246 #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
247 #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
248 #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
250 /* These are the amounts to shift an input value to get a histogram index. */
251 #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
252 #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
253 #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
256 typedef UINT16 histcell
; /* histogram cell; prefer an unsigned type */
258 typedef histcell
* histptr
; /* for pointers to histogram cells */
260 typedef histcell hist1d
[HIST_C2_ELEMS
]; /* typedefs for the array */
261 typedef hist1d
* hist2d
; /* type for the 2nd-level pointers */
262 typedef hist2d
* hist3d
; /* type for top-level pointer */
265 /* Declarations for Floyd-Steinberg dithering.
267 * Errors are accumulated into the array fserrors[], at a resolution of
268 * 1/16th of a pixel count. The error at a given pixel is propagated
269 * to its not-yet-processed neighbors using the standard F-S fractions,
272 * We work left-to-right on even rows, right-to-left on odd rows.
274 * We can get away with a single array (holding one row's worth of errors)
275 * by using it to store the current row's errors at pixel columns not yet
276 * processed, but the next row's errors at columns already processed. We
277 * need only a few extra variables to hold the errors immediately around the
278 * current column. (If we are lucky, those variables are in registers, but
279 * even if not, they're probably cheaper to access than array elements are.)
281 * The fserrors[] array has (#columns + 2) entries; the extra entry at
282 * each end saves us from special-casing the first and last pixels.
283 * Each entry is three values long, one value for each color component.
285 * Note: on a wide image, we might not have enough room in a PC's near data
286 * segment to hold the error array; so it is allocated with alloc_large.
289 #if BITS_IN_JSAMPLE == 8
290 typedef INT16 FSERROR
; /* 16 bits should be enough */
291 typedef int LOCFSERROR
; /* use 'int' for calculation temps */
293 typedef INT32 FSERROR
; /* may need more than 16 bits */
294 typedef INT32 LOCFSERROR
; /* be sure calculation temps are big enough */
297 typedef FSERROR
*FSERRPTR
; /* pointer to error array (in storage!) */
300 /* Private subobject */
305 void (*finish_pass
)(j_decompress_ptr
);
306 void (*color_quantize
)(j_decompress_ptr
, JSAMPARRAY
, JSAMPARRAY
, int);
307 void (*start_pass
)(j_decompress_ptr
, bool);
308 void (*new_color_map
)(j_decompress_ptr
);
311 /* Space for the eventually created colormap is stashed here */
312 JSAMPARRAY sv_colormap
; /* colormap allocated at init time */
313 int desired
; /* desired # of colors = size of colormap */
315 /* Variables for accumulating image statistics */
316 hist3d histogram
; /* pointer to the histogram */
318 bool needs_zeroed
; /* true if next pass must zero histogram */
320 /* Variables for Floyd-Steinberg dithering */
321 FSERRPTR fserrors
; /* accumulated errors */
322 bool on_odd_row
; /* flag to remember which row we are on */
323 int * error_limiter
; /* table for clamping the applied error */
326 typedef my_cquantizer
* my_cquantize_ptr
;
330 * Prescan some rows of pixels.
331 * In this module the prescan simply updates the histogram, which has been
332 * initialized to zeroes by start_pass.
333 * An output_buf parameter is required by the method signature, but no data
334 * is actually output (in fact the buffer controller is probably passing a
339 prescan_quantize (j_decompress_ptr cinfo
, JSAMPARRAY input_buf
,
340 JSAMPARRAY
WXUNUSED(output_buf
), int num_rows
)
342 my_cquantize_ptr cquantize
= (my_cquantize_ptr
) cinfo
->cquantize
;
343 register JSAMPROW ptr
;
344 register histptr histp
;
345 register hist3d histogram
= cquantize
->histogram
;
348 JDIMENSION width
= cinfo
->output_width
;
350 for (row
= 0; row
< num_rows
; row
++) {
351 ptr
= input_buf
[row
];
352 for (col
= width
; col
> 0; col
--) {
356 /* get pixel value and index into the histogram */
357 histp
= & histogram
[GETJSAMPLE(ptr
[0]) >> C0_SHIFT
]
358 [GETJSAMPLE(ptr
[1]) >> C1_SHIFT
]
359 [GETJSAMPLE(ptr
[2]) >> C2_SHIFT
];
360 /* increment, check for overflow and undo increment if so. */
371 * Next we have the really interesting routines: selection of a colormap
372 * given the completed histogram.
373 * These routines work with a list of "boxes", each representing a rectangular
374 * subset of the input color space (to histogram precision).
378 /* The bounds of the box (inclusive); expressed as histogram indexes */
382 /* The volume (actually 2-norm) of the box */
384 /* The number of nonzero histogram cells within this box */
388 typedef box
* boxptr
;
392 find_biggest_color_pop (boxptr boxlist
, int numboxes
)
393 /* Find the splittable box with the largest color population */
394 /* Returns NULL if no splittable boxes remain */
396 register boxptr boxp
;
398 register long maxc
= 0;
401 for (i
= 0, boxp
= boxlist
; i
< numboxes
; i
++, boxp
++) {
402 if (boxp
->colorcount
> maxc
&& boxp
->volume
> 0) {
404 maxc
= boxp
->colorcount
;
412 find_biggest_volume (boxptr boxlist
, int numboxes
)
413 /* Find the splittable box with the largest (scaled) volume */
414 /* Returns NULL if no splittable boxes remain */
416 register boxptr boxp
;
418 register INT32 maxv
= 0;
421 for (i
= 0, boxp
= boxlist
; i
< numboxes
; i
++, boxp
++) {
422 if (boxp
->volume
> maxv
) {
432 update_box (j_decompress_ptr cinfo
, boxptr boxp
)
433 /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
434 /* and recompute its volume and population */
436 my_cquantize_ptr cquantize
= (my_cquantize_ptr
) cinfo
->cquantize
;
437 hist3d histogram
= cquantize
->histogram
;
440 int c0min
,c0max
,c1min
,c1max
,c2min
,c2max
;
441 INT32 dist0
,dist1
,dist2
;
444 c0min
= boxp
->c0min
; c0max
= boxp
->c0max
;
445 c1min
= boxp
->c1min
; c1max
= boxp
->c1max
;
446 c2min
= boxp
->c2min
; c2max
= boxp
->c2max
;
449 for (c0
= c0min
; c0
<= c0max
; c0
++)
450 for (c1
= c1min
; c1
<= c1max
; c1
++) {
451 histp
= & histogram
[c0
][c1
][c2min
];
452 for (c2
= c2min
; c2
<= c2max
; c2
++)
454 boxp
->c0min
= c0min
= c0
;
460 for (c0
= c0max
; c0
>= c0min
; c0
--)
461 for (c1
= c1min
; c1
<= c1max
; c1
++) {
462 histp
= & histogram
[c0
][c1
][c2min
];
463 for (c2
= c2min
; c2
<= c2max
; c2
++)
465 boxp
->c0max
= c0max
= c0
;
471 for (c1
= c1min
; c1
<= c1max
; c1
++)
472 for (c0
= c0min
; c0
<= c0max
; c0
++) {
473 histp
= & histogram
[c0
][c1
][c2min
];
474 for (c2
= c2min
; c2
<= c2max
; c2
++)
476 boxp
->c1min
= c1min
= c1
;
482 for (c1
= c1max
; c1
>= c1min
; c1
--)
483 for (c0
= c0min
; c0
<= c0max
; c0
++) {
484 histp
= & histogram
[c0
][c1
][c2min
];
485 for (c2
= c2min
; c2
<= c2max
; c2
++)
487 boxp
->c1max
= c1max
= c1
;
493 for (c2
= c2min
; c2
<= c2max
; c2
++)
494 for (c0
= c0min
; c0
<= c0max
; c0
++) {
495 histp
= & histogram
[c0
][c1min
][c2
];
496 for (c1
= c1min
; c1
<= c1max
; c1
++, histp
+= HIST_C2_ELEMS
)
498 boxp
->c2min
= c2min
= c2
;
504 for (c2
= c2max
; c2
>= c2min
; c2
--)
505 for (c0
= c0min
; c0
<= c0max
; c0
++) {
506 histp
= & histogram
[c0
][c1min
][c2
];
507 for (c1
= c1min
; c1
<= c1max
; c1
++, histp
+= HIST_C2_ELEMS
)
509 boxp
->c2max
= c2max
= c2
;
515 /* Update box volume.
516 * We use 2-norm rather than real volume here; this biases the method
517 * against making long narrow boxes, and it has the side benefit that
518 * a box is splittable iff norm > 0.
519 * Since the differences are expressed in histogram-cell units,
520 * we have to shift back to JSAMPLE units to get consistent distances;
521 * after which, we scale according to the selected distance scale factors.
523 dist0
= ((c0max
- c0min
) << C0_SHIFT
) * C0_SCALE
;
524 dist1
= ((c1max
- c1min
) << C1_SHIFT
) * C1_SCALE
;
525 dist2
= ((c2max
- c2min
) << C2_SHIFT
) * C2_SCALE
;
526 boxp
->volume
= dist0
*dist0
+ dist1
*dist1
+ dist2
*dist2
;
528 /* Now scan remaining volume of box and compute population */
530 for (c0
= c0min
; c0
<= c0max
; c0
++)
531 for (c1
= c1min
; c1
<= c1max
; c1
++) {
532 histp
= & histogram
[c0
][c1
][c2min
];
533 for (c2
= c2min
; c2
<= c2max
; c2
++, histp
++)
538 boxp
->colorcount
= ccount
;
543 median_cut (j_decompress_ptr cinfo
, boxptr boxlist
, int numboxes
,
545 /* Repeatedly select and split the largest box until we have enough boxes */
549 register boxptr b1
,b2
;
551 while (numboxes
< desired_colors
) {
552 /* Select box to split.
553 * Current algorithm: by population for first half, then by volume.
555 if ((numboxes
*2) <= desired_colors
) {
556 b1
= find_biggest_color_pop(boxlist
, numboxes
);
558 b1
= find_biggest_volume(boxlist
, numboxes
);
560 if (b1
== NULL
) /* no splittable boxes left! */
562 b2
= &boxlist
[numboxes
]; /* where new box will go */
563 /* Copy the color bounds to the new box. */
564 b2
->c0max
= b1
->c0max
; b2
->c1max
= b1
->c1max
; b2
->c2max
= b1
->c2max
;
565 b2
->c0min
= b1
->c0min
; b2
->c1min
= b1
->c1min
; b2
->c2min
= b1
->c2min
;
566 /* Choose which axis to split the box on.
567 * Current algorithm: longest scaled axis.
568 * See notes in update_box about scaling distances.
570 c0
= ((b1
->c0max
- b1
->c0min
) << C0_SHIFT
) * C0_SCALE
;
571 c1
= ((b1
->c1max
- b1
->c1min
) << C1_SHIFT
) * C1_SCALE
;
572 c2
= ((b1
->c2max
- b1
->c2min
) << C2_SHIFT
) * C2_SCALE
;
573 /* We want to break any ties in favor of green, then red, blue last.
574 * This code does the right thing for R,G,B or B,G,R color orders only.
576 #if defined(__VISAGECPP__)
580 if (c0
> cmax
) { cmax
= c0
; n
= 0; }
581 if (c2
> cmax
) { n
= 2; }
584 if (c2
> cmax
) { cmax
= c2
; n
= 2; }
585 if (c0
> cmax
) { n
= 0; }
592 if (c0
> cmax
) { cmax
= c0
; n
= 0; }
593 if (c2
> cmax
) { n
= 2; }
596 if (c2
> cmax
) { cmax
= c2
; n
= 2; }
597 if (c0
> cmax
) { n
= 0; }
601 /* Choose split point along selected axis, and update box bounds.
602 * Current algorithm: split at halfway point.
603 * (Since the box has been shrunk to minimum volume,
604 * any split will produce two nonempty subboxes.)
605 * Note that lb value is max for lower box, so must be < old max.
609 lb
= (b1
->c0max
+ b1
->c0min
) / 2;
614 lb
= (b1
->c1max
+ b1
->c1min
) / 2;
619 lb
= (b1
->c2max
+ b1
->c2min
) / 2;
624 /* Update stats for boxes */
625 update_box(cinfo
, b1
);
626 update_box(cinfo
, b2
);
634 compute_color (j_decompress_ptr cinfo
, boxptr boxp
, int icolor
)
635 /* Compute representative color for a box, put it in colormap[icolor] */
637 /* Current algorithm: mean weighted by pixels (not colors) */
638 /* Note it is important to get the rounding correct! */
639 my_cquantize_ptr cquantize
= (my_cquantize_ptr
) cinfo
->cquantize
;
640 hist3d histogram
= cquantize
->histogram
;
643 int c0min
,c0max
,c1min
,c1max
,c2min
,c2max
;
650 c0min
= boxp
->c0min
; c0max
= boxp
->c0max
;
651 c1min
= boxp
->c1min
; c1max
= boxp
->c1max
;
652 c2min
= boxp
->c2min
; c2max
= boxp
->c2max
;
654 for (c0
= c0min
; c0
<= c0max
; c0
++)
655 for (c1
= c1min
; c1
<= c1max
; c1
++) {
656 histp
= & histogram
[c0
][c1
][c2min
];
657 for (c2
= c2min
; c2
<= c2max
; c2
++) {
658 if ((count
= *histp
++) != 0) {
660 c0total
+= ((c0
<< C0_SHIFT
) + ((1<<C0_SHIFT
)>>1)) * count
;
661 c1total
+= ((c1
<< C1_SHIFT
) + ((1<<C1_SHIFT
)>>1)) * count
;
662 c2total
+= ((c2
<< C2_SHIFT
) + ((1<<C2_SHIFT
)>>1)) * count
;
667 cinfo
->colormap
[0][icolor
] = (JSAMPLE
) ((c0total
+ (total
>>1)) / total
);
668 cinfo
->colormap
[1][icolor
] = (JSAMPLE
) ((c1total
+ (total
>>1)) / total
);
669 cinfo
->colormap
[2][icolor
] = (JSAMPLE
) ((c2total
+ (total
>>1)) / total
);
674 select_colors (j_decompress_ptr cinfo
, int desired_colors
)
675 /* Master routine for color selection */
681 /* Allocate workspace for box list */
682 boxlist
= (boxptr
) malloc(desired_colors
* sizeof(box
));
683 /* Initialize one box containing whole space */
685 boxlist
[0].c0min
= 0;
686 boxlist
[0].c0max
= MAXJSAMPLE
>> C0_SHIFT
;
687 boxlist
[0].c1min
= 0;
688 boxlist
[0].c1max
= MAXJSAMPLE
>> C1_SHIFT
;
689 boxlist
[0].c2min
= 0;
690 boxlist
[0].c2max
= MAXJSAMPLE
>> C2_SHIFT
;
691 /* Shrink it to actually-used volume and set its statistics */
692 update_box(cinfo
, & boxlist
[0]);
693 /* Perform median-cut to produce final box list */
694 numboxes
= median_cut(cinfo
, boxlist
, numboxes
, desired_colors
);
695 /* Compute the representative color for each box, fill colormap */
696 for (i
= 0; i
< numboxes
; i
++)
697 compute_color(cinfo
, & boxlist
[i
], i
);
698 cinfo
->actual_number_of_colors
= numboxes
;
700 free(boxlist
); //FIXME?? I don't know if this is correct - VS
705 * These routines are concerned with the time-critical task of mapping input
706 * colors to the nearest color in the selected colormap.
708 * We re-use the histogram space as an "inverse color map", essentially a
709 * cache for the results of nearest-color searches. All colors within a
710 * histogram cell will be mapped to the same colormap entry, namely the one
711 * closest to the cell's center. This may not be quite the closest entry to
712 * the actual input color, but it's almost as good. A zero in the cache
713 * indicates we haven't found the nearest color for that cell yet; the array
714 * is cleared to zeroes before starting the mapping pass. When we find the
715 * nearest color for a cell, its colormap index plus one is recorded in the
716 * cache for future use. The pass2 scanning routines call fill_inverse_cmap
717 * when they need to use an unfilled entry in the cache.
719 * Our method of efficiently finding nearest colors is based on the "locally
720 * sorted search" idea described by Heckbert and on the incremental distance
721 * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
722 * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
723 * the distances from a given colormap entry to each cell of the histogram can
724 * be computed quickly using an incremental method: the differences between
725 * distances to adjacent cells themselves differ by a constant. This allows a
726 * fairly fast implementation of the "brute force" approach of computing the
727 * distance from every colormap entry to every histogram cell. Unfortunately,
728 * it needs a work array to hold the best-distance-so-far for each histogram
729 * cell (because the inner loop has to be over cells, not colormap entries).
730 * The work array elements have to be INT32s, so the work array would need
731 * 256Kb at our recommended precision. This is not feasible in DOS machines.
733 * To get around these problems, we apply Thomas' method to compute the
734 * nearest colors for only the cells within a small subbox of the histogram.
735 * The work array need be only as big as the subbox, so the memory usage
736 * problem is solved. Furthermore, we need not fill subboxes that are never
737 * referenced in pass2; many images use only part of the color gamut, so a
738 * fair amount of work is saved. An additional advantage of this
739 * approach is that we can apply Heckbert's locality criterion to quickly
740 * eliminate colormap entries that are far away from the subbox; typically
741 * three-fourths of the colormap entries are rejected by Heckbert's criterion,
742 * and we need not compute their distances to individual cells in the subbox.
743 * The speed of this approach is heavily influenced by the subbox size: too
744 * small means too much overhead, too big loses because Heckbert's criterion
745 * can't eliminate as many colormap entries. Empirically the best subbox
746 * size seems to be about 1/512th of the histogram (1/8th in each direction).
748 * Thomas' article also describes a refined method which is asymptotically
749 * faster than the brute-force method, but it is also far more complex and
750 * cannot efficiently be applied to small subboxes. It is therefore not
751 * useful for programs intended to be portable to DOS machines. On machines
752 * with plenty of memory, filling the whole histogram in one shot with Thomas'
753 * refined method might be faster than the present code --- but then again,
754 * it might not be any faster, and it's certainly more complicated.
758 /* log2(histogram cells in update box) for each axis; this can be adjusted */
759 #define BOX_C0_LOG (HIST_C0_BITS-3)
760 #define BOX_C1_LOG (HIST_C1_BITS-3)
761 #define BOX_C2_LOG (HIST_C2_BITS-3)
763 #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
764 #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
765 #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
767 #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
768 #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
769 #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
773 * The next three routines implement inverse colormap filling. They could
774 * all be folded into one big routine, but splitting them up this way saves
775 * some stack space (the mindist[] and bestdist[] arrays need not coexist)
776 * and may allow some compilers to produce better code by registerizing more
777 * inner-loop variables.
781 find_nearby_colors (j_decompress_ptr cinfo
, int minc0
, int minc1
, int minc2
,
783 /* Locate the colormap entries close enough to an update box to be candidates
784 * for the nearest entry to some cell(s) in the update box. The update box
785 * is specified by the center coordinates of its first cell. The number of
786 * candidate colormap entries is returned, and their colormap indexes are
787 * placed in colorlist[].
788 * This routine uses Heckbert's "locally sorted search" criterion to select
789 * the colors that need further consideration.
792 int numcolors
= cinfo
->actual_number_of_colors
;
793 int maxc0
, maxc1
, maxc2
;
794 int centerc0
, centerc1
, centerc2
;
796 INT32 minmaxdist
, min_dist
, max_dist
, tdist
;
797 INT32 mindist
[MAXNUMCOLORS
]; /* min distance to colormap entry i */
799 /* Compute true coordinates of update box's upper corner and center.
800 * Actually we compute the coordinates of the center of the upper-corner
801 * histogram cell, which are the upper bounds of the volume we care about.
802 * Note that since ">>" rounds down, the "center" values may be closer to
803 * min than to max; hence comparisons to them must be "<=", not "<".
805 maxc0
= minc0
+ ((1 << BOX_C0_SHIFT
) - (1 << C0_SHIFT
));
806 centerc0
= (minc0
+ maxc0
) >> 1;
807 maxc1
= minc1
+ ((1 << BOX_C1_SHIFT
) - (1 << C1_SHIFT
));
808 centerc1
= (minc1
+ maxc1
) >> 1;
809 maxc2
= minc2
+ ((1 << BOX_C2_SHIFT
) - (1 << C2_SHIFT
));
810 centerc2
= (minc2
+ maxc2
) >> 1;
812 /* For each color in colormap, find:
813 * 1. its minimum squared-distance to any point in the update box
814 * (zero if color is within update box);
815 * 2. its maximum squared-distance to any point in the update box.
816 * Both of these can be found by considering only the corners of the box.
817 * We save the minimum distance for each color in mindist[];
818 * only the smallest maximum distance is of interest.
820 minmaxdist
= 0x7FFFFFFFL
;
822 for (i
= 0; i
< numcolors
; i
++) {
823 /* We compute the squared-c0-distance term, then add in the other two. */
824 x
= GETJSAMPLE(cinfo
->colormap
[0][i
]);
826 tdist
= (x
- minc0
) * C0_SCALE
;
827 min_dist
= tdist
*tdist
;
828 tdist
= (x
- maxc0
) * C0_SCALE
;
829 max_dist
= tdist
*tdist
;
830 } else if (x
> maxc0
) {
831 tdist
= (x
- maxc0
) * C0_SCALE
;
832 min_dist
= tdist
*tdist
;
833 tdist
= (x
- minc0
) * C0_SCALE
;
834 max_dist
= tdist
*tdist
;
836 /* within cell range so no contribution to min_dist */
839 tdist
= (x
- maxc0
) * C0_SCALE
;
840 max_dist
= tdist
*tdist
;
842 tdist
= (x
- minc0
) * C0_SCALE
;
843 max_dist
= tdist
*tdist
;
847 x
= GETJSAMPLE(cinfo
->colormap
[1][i
]);
849 tdist
= (x
- minc1
) * C1_SCALE
;
850 min_dist
+= tdist
*tdist
;
851 tdist
= (x
- maxc1
) * C1_SCALE
;
852 max_dist
+= tdist
*tdist
;
853 } else if (x
> maxc1
) {
854 tdist
= (x
- maxc1
) * C1_SCALE
;
855 min_dist
+= tdist
*tdist
;
856 tdist
= (x
- minc1
) * C1_SCALE
;
857 max_dist
+= tdist
*tdist
;
859 /* within cell range so no contribution to min_dist */
861 tdist
= (x
- maxc1
) * C1_SCALE
;
862 max_dist
+= tdist
*tdist
;
864 tdist
= (x
- minc1
) * C1_SCALE
;
865 max_dist
+= tdist
*tdist
;
869 x
= GETJSAMPLE(cinfo
->colormap
[2][i
]);
871 tdist
= (x
- minc2
) * C2_SCALE
;
872 min_dist
+= tdist
*tdist
;
873 tdist
= (x
- maxc2
) * C2_SCALE
;
874 max_dist
+= tdist
*tdist
;
875 } else if (x
> maxc2
) {
876 tdist
= (x
- maxc2
) * C2_SCALE
;
877 min_dist
+= tdist
*tdist
;
878 tdist
= (x
- minc2
) * C2_SCALE
;
879 max_dist
+= tdist
*tdist
;
881 /* within cell range so no contribution to min_dist */
883 tdist
= (x
- maxc2
) * C2_SCALE
;
884 max_dist
+= tdist
*tdist
;
886 tdist
= (x
- minc2
) * C2_SCALE
;
887 max_dist
+= tdist
*tdist
;
891 mindist
[i
] = min_dist
; /* save away the results */
892 if (max_dist
< minmaxdist
)
893 minmaxdist
= max_dist
;
896 /* Now we know that no cell in the update box is more than minmaxdist
897 * away from some colormap entry. Therefore, only colors that are
898 * within minmaxdist of some part of the box need be considered.
901 for (i
= 0; i
< numcolors
; i
++) {
902 if (mindist
[i
] <= minmaxdist
)
903 colorlist
[ncolors
++] = (JSAMPLE
) i
;
910 find_best_colors (j_decompress_ptr cinfo
, int minc0
, int minc1
, int minc2
,
911 int numcolors
, JSAMPLE colorlist
[], JSAMPLE bestcolor
[])
912 /* Find the closest colormap entry for each cell in the update box,
913 * given the list of candidate colors prepared by find_nearby_colors.
914 * Return the indexes of the closest entries in the bestcolor[] array.
915 * This routine uses Thomas' incremental distance calculation method to
916 * find the distance from a colormap entry to successive cells in the box.
921 register INT32
* bptr
; /* pointer into bestdist[] array */
922 JSAMPLE
* cptr
; /* pointer into bestcolor[] array */
923 INT32 dist0
, dist1
; /* initial distance values */
924 register INT32 dist2
; /* current distance in inner loop */
925 INT32 xx0
, xx1
; /* distance increments */
927 INT32 inc0
, inc1
, inc2
; /* initial values for increments */
928 /* This array holds the distance to the nearest-so-far color for each cell */
929 INT32 bestdist
[BOX_C0_ELEMS
* BOX_C1_ELEMS
* BOX_C2_ELEMS
];
931 /* Initialize best-distance for each cell of the update box */
933 for (i
= BOX_C0_ELEMS
*BOX_C1_ELEMS
*BOX_C2_ELEMS
-1; i
>= 0; i
--)
934 *bptr
++ = 0x7FFFFFFFL
;
936 /* For each color selected by find_nearby_colors,
937 * compute its distance to the center of each cell in the box.
938 * If that's less than best-so-far, update best distance and color number.
941 /* Nominal steps between cell centers ("x" in Thomas article) */
942 #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
943 #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
944 #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
946 for (i
= 0; i
< numcolors
; i
++) {
947 icolor
= GETJSAMPLE(colorlist
[i
]);
948 /* Compute (square of) distance from minc0/c1/c2 to this color */
949 inc0
= (minc0
- GETJSAMPLE(cinfo
->colormap
[0][icolor
])) * C0_SCALE
;
951 inc1
= (minc1
- GETJSAMPLE(cinfo
->colormap
[1][icolor
])) * C1_SCALE
;
953 inc2
= (minc2
- GETJSAMPLE(cinfo
->colormap
[2][icolor
])) * C2_SCALE
;
955 /* Form the initial difference increments */
956 inc0
= inc0
* (2 * STEP_C0
) + STEP_C0
* STEP_C0
;
957 inc1
= inc1
* (2 * STEP_C1
) + STEP_C1
* STEP_C1
;
958 inc2
= inc2
* (2 * STEP_C2
) + STEP_C2
* STEP_C2
;
959 /* Now loop over all cells in box, updating distance per Thomas method */
963 for (ic0
= BOX_C0_ELEMS
-1; ic0
>= 0; ic0
--) {
966 for (ic1
= BOX_C1_ELEMS
-1; ic1
>= 0; ic1
--) {
969 for (ic2
= BOX_C2_ELEMS
-1; ic2
>= 0; ic2
--) {
972 *cptr
= (JSAMPLE
) icolor
;
975 xx2
+= 2 * STEP_C2
* STEP_C2
;
980 xx1
+= 2 * STEP_C1
* STEP_C1
;
983 xx0
+= 2 * STEP_C0
* STEP_C0
;
990 fill_inverse_cmap (j_decompress_ptr cinfo
, int c0
, int c1
, int c2
)
991 /* Fill the inverse-colormap entries in the update box that contains */
992 /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
993 /* we can fill as many others as we wish.) */
995 my_cquantize_ptr cquantize
= (my_cquantize_ptr
) cinfo
->cquantize
;
996 hist3d histogram
= cquantize
->histogram
;
997 int minc0
, minc1
, minc2
; /* lower left corner of update box */
999 register JSAMPLE
* cptr
; /* pointer into bestcolor[] array */
1000 register histptr cachep
; /* pointer into main cache array */
1001 /* This array lists the candidate colormap indexes. */
1002 JSAMPLE colorlist
[MAXNUMCOLORS
];
1003 int numcolors
; /* number of candidate colors */
1004 /* This array holds the actually closest colormap index for each cell. */
1005 JSAMPLE bestcolor
[BOX_C0_ELEMS
* BOX_C1_ELEMS
* BOX_C2_ELEMS
];
1007 /* Convert cell coordinates to update box ID */
1012 /* Compute true coordinates of update box's origin corner.
1013 * Actually we compute the coordinates of the center of the corner
1014 * histogram cell, which are the lower bounds of the volume we care about.
1016 minc0
= (c0
<< BOX_C0_SHIFT
) + ((1 << C0_SHIFT
) >> 1);
1017 minc1
= (c1
<< BOX_C1_SHIFT
) + ((1 << C1_SHIFT
) >> 1);
1018 minc2
= (c2
<< BOX_C2_SHIFT
) + ((1 << C2_SHIFT
) >> 1);
1020 /* Determine which colormap entries are close enough to be candidates
1021 * for the nearest entry to some cell in the update box.
1023 numcolors
= find_nearby_colors(cinfo
, minc0
, minc1
, minc2
, colorlist
);
1025 /* Determine the actually nearest colors. */
1026 find_best_colors(cinfo
, minc0
, minc1
, minc2
, numcolors
, colorlist
,
1029 /* Save the best color numbers (plus 1) in the main cache array */
1030 c0
<<= BOX_C0_LOG
; /* convert ID back to base cell indexes */
1034 for (ic0
= 0; ic0
< BOX_C0_ELEMS
; ic0
++) {
1035 for (ic1
= 0; ic1
< BOX_C1_ELEMS
; ic1
++) {
1036 cachep
= & histogram
[c0
+ic0
][c1
+ic1
][c2
];
1037 for (ic2
= 0; ic2
< BOX_C2_ELEMS
; ic2
++) {
1038 *cachep
++ = (histcell
) (GETJSAMPLE(*cptr
++) + 1);
1046 * Map some rows of pixels to the output colormapped representation.
1050 pass2_no_dither (j_decompress_ptr cinfo
,
1051 JSAMPARRAY input_buf
, JSAMPARRAY output_buf
, int num_rows
)
1052 /* This version performs no dithering */
1054 my_cquantize_ptr cquantize
= (my_cquantize_ptr
) cinfo
->cquantize
;
1055 hist3d histogram
= cquantize
->histogram
;
1056 register JSAMPROW inptr
, outptr
;
1057 register histptr cachep
;
1058 register int c0
, c1
, c2
;
1061 JDIMENSION width
= cinfo
->output_width
;
1063 for (row
= 0; row
< num_rows
; row
++) {
1064 inptr
= input_buf
[row
];
1065 outptr
= output_buf
[row
];
1066 for (col
= width
; col
> 0; col
--) {
1067 /* get pixel value and index into the cache */
1068 c0
= GETJSAMPLE(*inptr
++) >> C0_SHIFT
;
1069 c1
= GETJSAMPLE(*inptr
++) >> C1_SHIFT
;
1070 c2
= GETJSAMPLE(*inptr
++) >> C2_SHIFT
;
1071 cachep
= & histogram
[c0
][c1
][c2
];
1072 /* If we have not seen this color before, find nearest colormap entry */
1073 /* and update the cache */
1075 fill_inverse_cmap(cinfo
, c0
,c1
,c2
);
1076 /* Now emit the colormap index for this cell */
1077 *outptr
++ = (JSAMPLE
) (*cachep
- 1);
1084 pass2_fs_dither (j_decompress_ptr cinfo
,
1085 JSAMPARRAY input_buf
, JSAMPARRAY output_buf
, int num_rows
)
1086 /* This version performs Floyd-Steinberg dithering */
1088 my_cquantize_ptr cquantize
= (my_cquantize_ptr
) cinfo
->cquantize
;
1089 hist3d histogram
= cquantize
->histogram
;
1090 register LOCFSERROR cur0
, cur1
, cur2
; /* current error or pixel value */
1091 LOCFSERROR belowerr0
, belowerr1
, belowerr2
; /* error for pixel below cur */
1092 LOCFSERROR bpreverr0
, bpreverr1
, bpreverr2
; /* error for below/prev col */
1093 register FSERRPTR errorptr
; /* => fserrors[] at column before current */
1094 JSAMPROW inptr
; /* => current input pixel */
1095 JSAMPROW outptr
; /* => current output pixel */
1097 int dir
; /* +1 or -1 depending on direction */
1098 int dir3
; /* 3*dir, for advancing inptr & errorptr */
1101 JDIMENSION width
= cinfo
->output_width
;
1102 JSAMPLE
*range_limit
= cinfo
->sample_range_limit
;
1103 int *error_limit
= cquantize
->error_limiter
;
1104 JSAMPROW colormap0
= cinfo
->colormap
[0];
1105 JSAMPROW colormap1
= cinfo
->colormap
[1];
1106 JSAMPROW colormap2
= cinfo
->colormap
[2];
1109 for (row
= 0; row
< num_rows
; row
++) {
1110 inptr
= input_buf
[row
];
1111 outptr
= output_buf
[row
];
1112 if (cquantize
->on_odd_row
) {
1113 /* work right to left in this row */
1114 inptr
+= (width
-1) * 3; /* so point to rightmost pixel */
1118 errorptr
= cquantize
->fserrors
+ (width
+1)*3; /* => entry after last column */
1119 cquantize
->on_odd_row
= FALSE
; /* flip for next time */
1121 /* work left to right in this row */
1124 errorptr
= cquantize
->fserrors
; /* => entry before first real column */
1125 cquantize
->on_odd_row
= TRUE
; /* flip for next time */
1127 /* Preset error values: no error propagated to first pixel from left */
1128 cur0
= cur1
= cur2
= 0;
1129 /* and no error propagated to row below yet */
1130 belowerr0
= belowerr1
= belowerr2
= 0;
1131 bpreverr0
= bpreverr1
= bpreverr2
= 0;
1133 for (col
= width
; col
> 0; col
--) {
1134 /* curN holds the error propagated from the previous pixel on the
1135 * current line. Add the error propagated from the previous line
1136 * to form the complete error correction term for this pixel, and
1137 * round the error term (which is expressed * 16) to an integer.
1138 * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
1139 * for either sign of the error value.
1140 * Note: errorptr points to *previous* column's array entry.
1142 cur0
= RIGHT_SHIFT(cur0
+ errorptr
[dir3
+0] + 8, 4);
1143 cur1
= RIGHT_SHIFT(cur1
+ errorptr
[dir3
+1] + 8, 4);
1144 cur2
= RIGHT_SHIFT(cur2
+ errorptr
[dir3
+2] + 8, 4);
1145 /* Limit the error using transfer function set by init_error_limit.
1146 * See comments with init_error_limit for rationale.
1148 cur0
= error_limit
[cur0
];
1149 cur1
= error_limit
[cur1
];
1150 cur2
= error_limit
[cur2
];
1151 /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
1152 * The maximum error is +- MAXJSAMPLE (or less with error limiting);
1153 * this sets the required size of the range_limit array.
1155 cur0
+= GETJSAMPLE(inptr
[0]);
1156 cur1
+= GETJSAMPLE(inptr
[1]);
1157 cur2
+= GETJSAMPLE(inptr
[2]);
1158 cur0
= GETJSAMPLE(range_limit
[cur0
]);
1159 cur1
= GETJSAMPLE(range_limit
[cur1
]);
1160 cur2
= GETJSAMPLE(range_limit
[cur2
]);
1161 /* Index into the cache with adjusted pixel value */
1162 cachep
= & histogram
[cur0
>>C0_SHIFT
][cur1
>>C1_SHIFT
][cur2
>>C2_SHIFT
];
1163 /* If we have not seen this color before, find nearest colormap */
1164 /* entry and update the cache */
1166 fill_inverse_cmap(cinfo
, cur0
>>C0_SHIFT
,cur1
>>C1_SHIFT
,cur2
>>C2_SHIFT
);
1167 /* Now emit the colormap index for this cell */
1168 { register int pixcode
= *cachep
- 1;
1169 *outptr
= (JSAMPLE
) pixcode
;
1170 /* Compute representation error for this pixel */
1171 cur0
-= GETJSAMPLE(colormap0
[pixcode
]);
1172 cur1
-= GETJSAMPLE(colormap1
[pixcode
]);
1173 cur2
-= GETJSAMPLE(colormap2
[pixcode
]);
1175 /* Compute error fractions to be propagated to adjacent pixels.
1176 * Add these into the running sums, and simultaneously shift the
1177 * next-line error sums left by 1 column.
1179 { register LOCFSERROR bnexterr
, delta
;
1181 bnexterr
= cur0
; /* Process component 0 */
1183 cur0
+= delta
; /* form error * 3 */
1184 errorptr
[0] = (FSERROR
) (bpreverr0
+ cur0
);
1185 cur0
+= delta
; /* form error * 5 */
1186 bpreverr0
= belowerr0
+ cur0
;
1187 belowerr0
= bnexterr
;
1188 cur0
+= delta
; /* form error * 7 */
1189 bnexterr
= cur1
; /* Process component 1 */
1191 cur1
+= delta
; /* form error * 3 */
1192 errorptr
[1] = (FSERROR
) (bpreverr1
+ cur1
);
1193 cur1
+= delta
; /* form error * 5 */
1194 bpreverr1
= belowerr1
+ cur1
;
1195 belowerr1
= bnexterr
;
1196 cur1
+= delta
; /* form error * 7 */
1197 bnexterr
= cur2
; /* Process component 2 */
1199 cur2
+= delta
; /* form error * 3 */
1200 errorptr
[2] = (FSERROR
) (bpreverr2
+ cur2
);
1201 cur2
+= delta
; /* form error * 5 */
1202 bpreverr2
= belowerr2
+ cur2
;
1203 belowerr2
= bnexterr
;
1204 cur2
+= delta
; /* form error * 7 */
1206 /* At this point curN contains the 7/16 error value to be propagated
1207 * to the next pixel on the current line, and all the errors for the
1208 * next line have been shifted over. We are therefore ready to move on.
1210 inptr
+= dir3
; /* Advance pixel pointers to next column */
1212 errorptr
+= dir3
; /* advance errorptr to current column */
1214 /* Post-loop cleanup: we must unload the final error values into the
1215 * final fserrors[] entry. Note we need not unload belowerrN because
1216 * it is for the dummy column before or after the actual array.
1218 errorptr
[0] = (FSERROR
) bpreverr0
; /* unload prev errs into array */
1219 errorptr
[1] = (FSERROR
) bpreverr1
;
1220 errorptr
[2] = (FSERROR
) bpreverr2
;
1226 * Initialize the error-limiting transfer function (lookup table).
1227 * The raw F-S error computation can potentially compute error values of up to
1228 * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
1229 * much less, otherwise obviously wrong pixels will be created. (Typical
1230 * effects include weird fringes at color-area boundaries, isolated bright
1231 * pixels in a dark area, etc.) The standard advice for avoiding this problem
1232 * is to ensure that the "corners" of the color cube are allocated as output
1233 * colors; then repeated errors in the same direction cannot cause cascading
1234 * error buildup. However, that only prevents the error from getting
1235 * completely out of hand; Aaron Giles reports that error limiting improves
1236 * the results even with corner colors allocated.
1237 * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
1238 * well, but the smoother transfer function used below is even better. Thanks
1239 * to Aaron Giles for this idea.
1243 init_error_limit (j_decompress_ptr cinfo
)
1244 /* Allocate and fill in the error_limiter table */
1246 my_cquantize_ptr cquantize
= (my_cquantize_ptr
) cinfo
->cquantize
;
1250 table
= (int *) malloc((MAXJSAMPLE
*2+1) * sizeof(int));
1251 table
+= MAXJSAMPLE
; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
1252 cquantize
->error_limiter
= table
;
1254 #define STEPSIZE ((MAXJSAMPLE+1)/16)
1255 /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
1257 for (in
= 0; in
< STEPSIZE
; in
++, out
++) {
1258 table
[in
] = out
; table
[-in
] = -out
;
1260 /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
1261 for (; in
< STEPSIZE
*3; in
++, out
+= (in
&1) ? 0 : 1) {
1262 table
[in
] = out
; table
[-in
] = -out
;
1264 /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
1265 for (; in
<= MAXJSAMPLE
; in
++) {
1266 table
[in
] = out
; table
[-in
] = -out
;
1273 * Finish up at the end of each pass.
1277 finish_pass1 (j_decompress_ptr cinfo
)
1279 my_cquantize_ptr cquantize
= (my_cquantize_ptr
) cinfo
->cquantize
;
1281 /* Select the representative colors and fill in cinfo->colormap */
1282 cinfo
->colormap
= cquantize
->sv_colormap
;
1283 select_colors(cinfo
, cquantize
->desired
);
1284 /* Force next pass to zero the color index table */
1285 cquantize
->needs_zeroed
= TRUE
;
1290 finish_pass2 (j_decompress_ptr
WXUNUSED(cinfo
))
1297 * Initialize for each processing pass.
1301 start_pass_2_quant (j_decompress_ptr cinfo
, bool is_pre_scan
)
1303 my_cquantize_ptr cquantize
= (my_cquantize_ptr
) cinfo
->cquantize
;
1304 hist3d histogram
= cquantize
->histogram
;
1307 /* Set up method pointers */
1308 cquantize
->pub
.color_quantize
= prescan_quantize
;
1309 cquantize
->pub
.finish_pass
= finish_pass1
;
1310 cquantize
->needs_zeroed
= TRUE
; /* Always zero histogram */
1312 /* Set up method pointers */
1313 cquantize
->pub
.color_quantize
= pass2_fs_dither
;
1314 cquantize
->pub
.finish_pass
= finish_pass2
;
1317 size_t arraysize
= (size_t) ((cinfo
->output_width
+ 2) *
1318 (3 * sizeof(FSERROR
)));
1319 /* Allocate Floyd-Steinberg workspace if we didn't already. */
1320 if (cquantize
->fserrors
== NULL
)
1321 cquantize
->fserrors
= (INT16
*) malloc(arraysize
);
1322 /* Initialize the propagated errors to zero. */
1323 memset((void *) cquantize
->fserrors
, 0, arraysize
);
1324 /* Make the error-limit table if we didn't already. */
1325 if (cquantize
->error_limiter
== NULL
)
1326 init_error_limit(cinfo
);
1327 cquantize
->on_odd_row
= FALSE
;
1331 /* Zero the histogram or inverse color map, if necessary */
1332 if (cquantize
->needs_zeroed
) {
1333 for (int i
= 0; i
< HIST_C0_ELEMS
; i
++) {
1334 memset((void *) histogram
[i
], 0,
1335 HIST_C1_ELEMS
*HIST_C2_ELEMS
* sizeof(histcell
));
1337 cquantize
->needs_zeroed
= FALSE
;
1343 * Switch to a new external colormap between output passes.
1347 new_color_map_2_quant (j_decompress_ptr cinfo
)
1349 my_cquantize_ptr cquantize
= (my_cquantize_ptr
) cinfo
->cquantize
;
1351 /* Reset the inverse color map */
1352 cquantize
->needs_zeroed
= TRUE
;
1357 * Module initialization routine for 2-pass color quantization.
1361 jinit_2pass_quantizer (j_decompress_ptr cinfo
)
1363 my_cquantize_ptr cquantize
;
1366 cquantize
= (my_cquantize_ptr
) malloc(sizeof(my_cquantizer
));
1367 cinfo
->cquantize
= (jpeg_color_quantizer
*) cquantize
;
1368 cquantize
->pub
.start_pass
= start_pass_2_quant
;
1369 cquantize
->pub
.new_color_map
= new_color_map_2_quant
;
1370 cquantize
->fserrors
= NULL
; /* flag optional arrays not allocated */
1371 cquantize
->error_limiter
= NULL
;
1374 /* Allocate the histogram/inverse colormap storage */
1375 cquantize
->histogram
= (hist3d
) malloc(HIST_C0_ELEMS
* sizeof(hist2d
));
1376 for (i
= 0; i
< HIST_C0_ELEMS
; i
++) {
1377 cquantize
->histogram
[i
] = (hist2d
) malloc(HIST_C1_ELEMS
*HIST_C2_ELEMS
* sizeof(histcell
));
1379 cquantize
->needs_zeroed
= TRUE
; /* histogram is garbage now */
1381 /* Allocate storage for the completed colormap, if required.
1382 * We do this now since it is storage and may affect
1383 * the memory manager's space calculations.
1386 /* Make sure color count is acceptable */
1387 int desired
= cinfo
->desired_number_of_colors
;
1389 cquantize
->sv_colormap
= (JSAMPARRAY
) malloc(sizeof(JSAMPROW
) * 3);
1390 cquantize
->sv_colormap
[0] = (JSAMPROW
) malloc(sizeof(JSAMPLE
) * desired
);
1391 cquantize
->sv_colormap
[1] = (JSAMPROW
) malloc(sizeof(JSAMPLE
) * desired
);
1392 cquantize
->sv_colormap
[2] = (JSAMPROW
) malloc(sizeof(JSAMPLE
) * desired
);
1394 cquantize
->desired
= desired
;
1397 /* Allocate Floyd-Steinberg workspace if necessary.
1398 * This isn't really needed until pass 2, but again it is storage.
1399 * Although we will cope with a later change in dither_mode,
1400 * we do not promise to honor max_memory_to_use if dither_mode changes.
1403 cquantize
->fserrors
= (FSERRPTR
) malloc(
1404 (size_t) ((cinfo
->output_width
+ 2) * (3 * sizeof(FSERROR
))));
1405 /* Might as well create the error-limiting table too. */
1406 init_error_limit(cinfo
);
1420 prepare_range_limit_table (j_decompress_ptr cinfo
)
1421 /* Allocate and fill in the sample_range_limit table */
1426 table
= (JSAMPLE
*) malloc((5 * (MAXJSAMPLE
+1) + CENTERJSAMPLE
) * sizeof(JSAMPLE
));
1427 cinfo
->srl_orig
= table
;
1428 table
+= (MAXJSAMPLE
+1); /* allow negative subscripts of simple table */
1429 cinfo
->sample_range_limit
= table
;
1430 /* First segment of "simple" table: limit[x] = 0 for x < 0 */
1431 memset(table
- (MAXJSAMPLE
+1), 0, (MAXJSAMPLE
+1) * sizeof(JSAMPLE
));
1432 /* Main part of "simple" table: limit[x] = x */
1433 for (i
= 0; i
<= MAXJSAMPLE
; i
++)
1434 table
[i
] = (JSAMPLE
) i
;
1435 table
+= CENTERJSAMPLE
; /* Point to where post-IDCT table starts */
1436 /* End of simple table, rest of first half of post-IDCT table */
1437 for (i
= CENTERJSAMPLE
; i
< 2*(MAXJSAMPLE
+1); i
++)
1438 table
[i
] = MAXJSAMPLE
;
1439 /* Second half of post-IDCT table */
1440 memset(table
+ (2 * (MAXJSAMPLE
+1)), 0,
1441 (2 * (MAXJSAMPLE
+1) - CENTERJSAMPLE
) * sizeof(JSAMPLE
));
1442 memcpy(table
+ (4 * (MAXJSAMPLE
+1) - CENTERJSAMPLE
),
1443 cinfo
->sample_range_limit
, CENTERJSAMPLE
* sizeof(JSAMPLE
));
1453 IMPLEMENT_DYNAMIC_CLASS(wxQuantize
, wxObject
)
1455 void wxQuantize::DoQuantize(unsigned w
, unsigned h
, unsigned char **in_rows
, unsigned char **out_rows
,
1456 unsigned char *palette
, int desiredNoColours
)
1459 my_cquantize_ptr cquantize
;
1461 dec
.output_width
= w
;
1462 dec
.desired_number_of_colors
= desiredNoColours
;
1463 prepare_range_limit_table(&dec
);
1464 jinit_2pass_quantizer(&dec
);
1465 cquantize
= (my_cquantize_ptr
) dec
.cquantize
;
1468 cquantize
->pub
.start_pass(&dec
, TRUE
);
1469 cquantize
->pub
.color_quantize(&dec
, in_rows
, out_rows
, h
);
1470 cquantize
->pub
.finish_pass(&dec
);
1472 cquantize
->pub
.start_pass(&dec
, FALSE
);
1473 cquantize
->pub
.color_quantize(&dec
, in_rows
, out_rows
, h
);
1474 cquantize
->pub
.finish_pass(&dec
);
1477 for (int i
= 0; i
< dec
.desired_number_of_colors
; i
++) {
1478 palette
[3 * i
+ 0] = dec
.colormap
[0][i
];
1479 palette
[3 * i
+ 1] = dec
.colormap
[1][i
];
1480 palette
[3 * i
+ 2] = dec
.colormap
[2][i
];
1483 for (int ii
= 0; ii
< HIST_C0_ELEMS
; ii
++) free(cquantize
->histogram
[ii
]);
1484 free(cquantize
->histogram
);
1485 free(dec
.colormap
[0]);
1486 free(dec
.colormap
[1]);
1487 free(dec
.colormap
[2]);
1491 //free(cquantize->error_limiter);
1492 free((void*)(cquantize
->error_limiter
- MAXJSAMPLE
)); // To reverse what was done to it
1494 free(cquantize
->fserrors
);
1498 // TODO: somehow make use of the Windows system colours, rather than ignoring them for the
1499 // purposes of quantization.
1501 bool wxQuantize::Quantize(const wxImage
& src
, wxImage
& dest
,
1502 wxPalette
** pPalette
,
1503 int desiredNoColours
,
1504 unsigned char** eightBitData
,
1510 int windowsSystemColourCount
= 20;
1512 int paletteShift
= 0;
1514 // Shift the palette up by the number of Windows system colours,
1516 if (flags
& wxQUANTIZE_INCLUDE_WINDOWS_COLOURS
)
1517 paletteShift
= windowsSystemColourCount
;
1519 // Make room for the Windows system colours
1521 if ((flags
& wxQUANTIZE_INCLUDE_WINDOWS_COLOURS
) && (desiredNoColours
> (256 - windowsSystemColourCount
)))
1522 desiredNoColours
= 256 - windowsSystemColourCount
;
1525 // create rows info:
1526 int h
= src
.GetHeight();
1527 int w
= src
.GetWidth();
1528 unsigned char **rows
= new unsigned char *[h
];
1529 unsigned char *imgdt
= src
.GetData();
1530 for (i
= 0; i
< h
; i
++)
1531 rows
[i
] = imgdt
+ 3/*RGB*/ * w
* i
;
1533 unsigned char palette
[3*256];
1535 // This is the image as represented by palette indexes.
1536 unsigned char *data8bit
= new unsigned char[w
* h
];
1537 unsigned char **outrows
= new unsigned char *[h
];
1538 for (i
= 0; i
< h
; i
++)
1539 outrows
[i
] = data8bit
+ w
* i
;
1542 DoQuantize(w
, h
, rows
, outrows
, palette
, desiredNoColours
);
1547 // palette->RGB(max.256)
1549 if (flags
& wxQUANTIZE_FILL_DESTINATION_IMAGE
)
1554 imgdt
= dest
.GetData();
1555 for (i
= 0; i
< w
* h
; i
++)
1557 unsigned char c
= data8bit
[i
];
1558 imgdt
[3 * i
+ 0/*R*/] = palette
[3 * c
+ 0];
1559 imgdt
[3 * i
+ 1/*G*/] = palette
[3 * c
+ 1];
1560 imgdt
[3 * i
+ 2/*B*/] = palette
[3 * c
+ 2];
1564 if (eightBitData
&& (flags
& wxQUANTIZE_RETURN_8BIT_DATA
))
1567 if (flags
& wxQUANTIZE_INCLUDE_WINDOWS_COLOURS
)
1569 // We need to shift the palette entries up
1570 // to make room for the Windows system colours.
1571 for (i
= 0; i
< w
* h
; i
++)
1572 data8bit
[i
] = data8bit
[i
] + paletteShift
;
1575 *eightBitData
= data8bit
;
1581 // Make a wxWindows palette
1584 unsigned char* r
= new unsigned char[256];
1585 unsigned char* g
= new unsigned char[256];
1586 unsigned char* b
= new unsigned char[256];
1589 // Fill the first 20 entries with Windows system colours
1590 if (flags
& wxQUANTIZE_INCLUDE_WINDOWS_COLOURS
)
1592 HDC hDC
= ::GetDC(NULL
);
1593 PALETTEENTRY
* entries
= new PALETTEENTRY
[windowsSystemColourCount
];
1594 ::GetSystemPaletteEntries(hDC
, 0, windowsSystemColourCount
, entries
);
1595 ::ReleaseDC(NULL
, hDC
);
1597 for (i
= 0; i
< windowsSystemColourCount
; i
++)
1599 r
[i
] = entries
[i
].peRed
;
1600 g
[i
] = entries
[i
].peGreen
;
1601 b
[i
] = entries
[i
].peBlue
;
1607 for (i
= 0; i
< desiredNoColours
; i
++)
1609 r
[i
+paletteShift
] = palette
[i
*3 + 0];
1610 g
[i
+paletteShift
] = palette
[i
*3 + 1];
1611 b
[i
+paletteShift
] = palette
[i
*3 + 2];
1614 // Blank out any remaining palette entries
1615 for (i
= desiredNoColours
+paletteShift
; i
< 256; i
++)
1621 *pPalette
= new wxPalette(256, r
, g
, b
);
1626 #endif // wxUSE_PALETTE
1631 // This version sets a palette in the destination image so you don't
1632 // have to manage it yourself.
1634 bool wxQuantize::Quantize(const wxImage
& src
,
1636 int desiredNoColours
,
1637 unsigned char** eightBitData
,
1640 wxPalette
* palette
= NULL
;
1641 if ( !Quantize(src
, dest
, & palette
, desiredNoColours
, eightBitData
, flags
) )
1647 dest
.SetPalette(* palette
);
1650 #endif // wxUSE_PALETTE