]> git.saurik.com Git - wxWidgets.git/blob - src/common/quantize.cpp
Don't call a function that might do drawing when setting a null image list
[wxWidgets.git] / src / common / quantize.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: quantize.cpp
3 // Purpose: wxQuantize implementation
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 22/6/2000
7 // RCS-ID: $Id$
8 // Copyright: (c) Thomas G. Lane, Vaclav Slavik, Julian Smart
9 // Licence: wxWindows licence + JPEG library licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 /*
13 * jquant2.c
14 *
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.
18 *
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.
25 *
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.
29 */
30
31 /* modified by Vaclav Slavik for use as jpeglib-independent module */
32
33 #ifdef __GNUG__
34 #pragma implementation "quantize.h"
35 #endif
36
37 // For compilers that support precompilation, includes "wx/wx.h".
38 #include "wx/wxprec.h"
39
40 #ifdef __BORLANDC__
41 #pragma hdrstop
42 #endif
43
44 #ifndef WX_PRECOMP
45 #endif
46
47 #include "wx/image.h"
48 #include "wx/quantize.h"
49
50 #ifdef __WXMSW__
51 #include <windows.h>
52 #endif
53
54 #include <stdlib.h>
55 #include <string.h>
56
57 #if defined(__OS2__)
58 #define RGB_RED_OS2 0
59 #define RGB_GREEN_OS2 1
60 #define RGB_BLUE_OS2 2
61 #else
62 #define RGB_RED 0
63 #define RGB_GREEN 1
64 #define RGB_BLUE 2
65 #endif
66 #define RGB_PIXELSIZE 3
67
68 #define MAXJSAMPLE 255
69 #define CENTERJSAMPLE 128
70 #define BITS_IN_JSAMPLE 8
71 #define GETJSAMPLE(value) ((int) (value))
72
73 #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
74
75 typedef unsigned short UINT16;
76 typedef signed short INT16;
77 typedef signed int INT32;
78
79 typedef unsigned char JSAMPLE;
80 typedef JSAMPLE *JSAMPROW;
81 typedef JSAMPROW *JSAMPARRAY;
82 typedef unsigned int JDIMENSION;
83
84 typedef struct {
85 void *cquantize;
86 JDIMENSION output_width;
87 JSAMPARRAY colormap;
88 int actual_number_of_colors;
89 int desired_number_of_colors;
90 JSAMPLE *sample_range_limit, *srl_orig;
91 } j_decompress;
92
93 #if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
94 #define JMETHOD(type,methodname,arglist) type (__cdecl methodname) arglist
95 #else
96 #define JMETHOD(type,methodname,arglist) type (methodname) arglist
97 #endif
98
99 typedef j_decompress *j_decompress_ptr;
100 struct jpeg_color_quantizer {
101 JMETHOD(void, start_pass, (j_decompress_ptr cinfo, bool is_pre_scan));
102 JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
103 JSAMPARRAY input_buf, JSAMPARRAY output_buf,
104 int num_rows));
105 JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
106 JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
107 };
108
109
110
111
112 /*
113 * This module implements the well-known Heckbert paradigm for color
114 * quantization. Most of the ideas used here can be traced back to
115 * Heckbert's seminal paper
116 * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
117 * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
118 *
119 * In the first pass over the image, we accumulate a histogram showing the
120 * usage count of each possible color. To keep the histogram to a reasonable
121 * size, we reduce the precision of the input; typical practice is to retain
122 * 5 or 6 bits per color, so that 8 or 4 different input values are counted
123 * in the same histogram cell.
124 *
125 * Next, the color-selection step begins with a box representing the whole
126 * color space, and repeatedly splits the "largest" remaining box until we
127 * have as many boxes as desired colors. Then the mean color in each
128 * remaining box becomes one of the possible output colors.
129 *
130 * The second pass over the image maps each input pixel to the closest output
131 * color (optionally after applying a Floyd-Steinberg dithering correction).
132 * This mapping is logically trivial, but making it go fast enough requires
133 * considerable care.
134 *
135 * Heckbert-style quantizers vary a good deal in their policies for choosing
136 * the "largest" box and deciding where to cut it. The particular policies
137 * used here have proved out well in experimental comparisons, but better ones
138 * may yet be found.
139 *
140 * In earlier versions of the IJG code, this module quantized in YCbCr color
141 * space, processing the raw upsampled data without a color conversion step.
142 * This allowed the color conversion math to be done only once per colormap
143 * entry, not once per pixel. However, that optimization precluded other
144 * useful optimizations (such as merging color conversion with upsampling)
145 * and it also interfered with desired capabilities such as quantizing to an
146 * externally-supplied colormap. We have therefore abandoned that approach.
147 * The present code works in the post-conversion color space, typically RGB.
148 *
149 * To improve the visual quality of the results, we actually work in scaled
150 * RGB space, giving G distances more weight than R, and R in turn more than
151 * B. To do everything in integer math, we must use integer scale factors.
152 * The 2/3/1 scale factors used here correspond loosely to the relative
153 * weights of the colors in the NTSC grayscale equation.
154 * If you want to use this code to quantize a non-RGB color space, you'll
155 * probably need to change these scale factors.
156 */
157
158 #define R_SCALE 2 /* scale R distances by this much */
159 #define G_SCALE 3 /* scale G distances by this much */
160 #define B_SCALE 1 /* and B by this much */
161
162 /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
163 * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
164 * and B,G,R orders. If you define some other weird order in jmorecfg.h,
165 * you'll get compile errors until you extend this logic. In that case
166 * you'll probably want to tweak the histogram sizes too.
167 */
168
169 #if defined(__OS2__)
170
171 #if RGB_RED_OS2 == 0
172 #define C0_SCALE R_SCALE
173 #endif
174 #if RGB_BLUE_OS2 == 0
175 #define C0_SCALE B_SCALE
176 #endif
177 #if RGB_GREEN_OS2 == 1
178 #define C1_SCALE G_SCALE
179 #endif
180 #if RGB_RED_OS2 == 2
181 #define C2_SCALE R_SCALE
182 #endif
183 #if RGB_BLUE_OS2 == 2
184 #define C2_SCALE B_SCALE
185 #endif
186
187 #else
188
189 #if RGB_RED == 0
190 #define C0_SCALE R_SCALE
191 #endif
192 #if RGB_BLUE == 0
193 #define C0_SCALE B_SCALE
194 #endif
195 #if RGB_GREEN == 1
196 #define C1_SCALE G_SCALE
197 #endif
198 #if RGB_RED == 2
199 #define C2_SCALE R_SCALE
200 #endif
201 #if RGB_BLUE == 2
202 #define C2_SCALE B_SCALE
203 #endif
204
205 #endif
206
207 /*
208 * First we have the histogram data structure and routines for creating it.
209 *
210 * The number of bits of precision can be adjusted by changing these symbols.
211 * We recommend keeping 6 bits for G and 5 each for R and B.
212 * If you have plenty of memory and cycles, 6 bits all around gives marginally
213 * better results; if you are short of memory, 5 bits all around will save
214 * some space but degrade the results.
215 * To maintain a fully accurate histogram, we'd need to allocate a "long"
216 * (preferably unsigned long) for each cell. In practice this is overkill;
217 * we can get by with 16 bits per cell. Few of the cell counts will overflow,
218 * and clamping those that do overflow to the maximum value will give close-
219 * enough results. This reduces the recommended histogram size from 256Kb
220 * to 128Kb, which is a useful savings on PC-class machines.
221 * (In the second pass the histogram space is re-used for pixel mapping data;
222 * in that capacity, each cell must be able to store zero to the number of
223 * desired colors. 16 bits/cell is plenty for that too.)
224 * Since the JPEG code is intended to run in small memory model on 80x86
225 * machines, we can't just allocate the histogram in one chunk. Instead
226 * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
227 * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
228 * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
229 * on 80x86 machines, the pointer row is in near memory but the actual
230 * arrays are in far memory (same arrangement as we use for image arrays).
231 */
232
233 #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
234
235 /* These will do the right thing for either R,G,B or B,G,R color order,
236 * but you may not like the results for other color orders.
237 */
238 #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
239 #define HIST_C1_BITS 6 /* bits of precision in G histogram */
240 #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
241
242 /* Number of elements along histogram axes. */
243 #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
244 #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
245 #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
246
247 /* These are the amounts to shift an input value to get a histogram index. */
248 #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
249 #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
250 #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
251
252
253 typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
254
255 typedef histcell * histptr; /* for pointers to histogram cells */
256
257 typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
258 typedef hist1d * hist2d; /* type for the 2nd-level pointers */
259 typedef hist2d * hist3d; /* type for top-level pointer */
260
261
262 /* Declarations for Floyd-Steinberg dithering.
263 *
264 * Errors are accumulated into the array fserrors[], at a resolution of
265 * 1/16th of a pixel count. The error at a given pixel is propagated
266 * to its not-yet-processed neighbors using the standard F-S fractions,
267 * ... (here) 7/16
268 * 3/16 5/16 1/16
269 * We work left-to-right on even rows, right-to-left on odd rows.
270 *
271 * We can get away with a single array (holding one row's worth of errors)
272 * by using it to store the current row's errors at pixel columns not yet
273 * processed, but the next row's errors at columns already processed. We
274 * need only a few extra variables to hold the errors immediately around the
275 * current column. (If we are lucky, those variables are in registers, but
276 * even if not, they're probably cheaper to access than array elements are.)
277 *
278 * The fserrors[] array has (#columns + 2) entries; the extra entry at
279 * each end saves us from special-casing the first and last pixels.
280 * Each entry is three values long, one value for each color component.
281 *
282 * Note: on a wide image, we might not have enough room in a PC's near data
283 * segment to hold the error array; so it is allocated with alloc_large.
284 */
285
286 #if BITS_IN_JSAMPLE == 8
287 typedef INT16 FSERROR; /* 16 bits should be enough */
288 typedef int LOCFSERROR; /* use 'int' for calculation temps */
289 #else
290 typedef INT32 FSERROR; /* may need more than 16 bits */
291 typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
292 #endif
293
294 typedef FSERROR *FSERRPTR; /* pointer to error array (in storage!) */
295
296
297 /* Private subobject */
298
299 typedef struct {
300
301 struct {
302 void (*finish_pass)(j_decompress_ptr);
303 void (*color_quantize)(j_decompress_ptr, JSAMPARRAY, JSAMPARRAY, int);
304 void (*start_pass)(j_decompress_ptr, bool);
305 void (*new_color_map)(j_decompress_ptr);
306 } pub;
307
308 /* Space for the eventually created colormap is stashed here */
309 JSAMPARRAY sv_colormap; /* colormap allocated at init time */
310 int desired; /* desired # of colors = size of colormap */
311
312 /* Variables for accumulating image statistics */
313 hist3d histogram; /* pointer to the histogram */
314
315 bool needs_zeroed; /* true if next pass must zero histogram */
316
317 /* Variables for Floyd-Steinberg dithering */
318 FSERRPTR fserrors; /* accumulated errors */
319 bool on_odd_row; /* flag to remember which row we are on */
320 int * error_limiter; /* table for clamping the applied error */
321 } my_cquantizer;
322
323 typedef my_cquantizer * my_cquantize_ptr;
324
325
326 /*
327 * Prescan some rows of pixels.
328 * In this module the prescan simply updates the histogram, which has been
329 * initialized to zeroes by start_pass.
330 * An output_buf parameter is required by the method signature, but no data
331 * is actually output (in fact the buffer controller is probably passing a
332 * NULL pointer).
333 */
334
335 void
336 prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
337 JSAMPARRAY WXUNUSED(output_buf), int num_rows)
338 {
339 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
340 register JSAMPROW ptr;
341 register histptr histp;
342 register hist3d histogram = cquantize->histogram;
343 int row;
344 JDIMENSION col;
345 JDIMENSION width = cinfo->output_width;
346
347 for (row = 0; row < num_rows; row++) {
348 ptr = input_buf[row];
349 for (col = width; col > 0; col--) {
350
351 {
352
353 /* get pixel value and index into the histogram */
354 histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
355 [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
356 [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
357 /* increment, check for overflow and undo increment if so. */
358 if (++(*histp) <= 0)
359 (*histp)--;
360 }
361 ptr += 3;
362 }
363 }
364 }
365
366
367 /*
368 * Next we have the really interesting routines: selection of a colormap
369 * given the completed histogram.
370 * These routines work with a list of "boxes", each representing a rectangular
371 * subset of the input color space (to histogram precision).
372 */
373
374 typedef struct {
375 /* The bounds of the box (inclusive); expressed as histogram indexes */
376 int c0min, c0max;
377 int c1min, c1max;
378 int c2min, c2max;
379 /* The volume (actually 2-norm) of the box */
380 INT32 volume;
381 /* The number of nonzero histogram cells within this box */
382 long colorcount;
383 } box;
384
385 typedef box * boxptr;
386
387
388 boxptr
389 find_biggest_color_pop (boxptr boxlist, int numboxes)
390 /* Find the splittable box with the largest color population */
391 /* Returns NULL if no splittable boxes remain */
392 {
393 register boxptr boxp;
394 register int i;
395 register long maxc = 0;
396 boxptr which = NULL;
397
398 for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
399 if (boxp->colorcount > maxc && boxp->volume > 0) {
400 which = boxp;
401 maxc = boxp->colorcount;
402 }
403 }
404 return which;
405 }
406
407
408 boxptr
409 find_biggest_volume (boxptr boxlist, int numboxes)
410 /* Find the splittable box with the largest (scaled) volume */
411 /* Returns NULL if no splittable boxes remain */
412 {
413 register boxptr boxp;
414 register int i;
415 register INT32 maxv = 0;
416 boxptr which = NULL;
417
418 for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
419 if (boxp->volume > maxv) {
420 which = boxp;
421 maxv = boxp->volume;
422 }
423 }
424 return which;
425 }
426
427
428 void
429 update_box (j_decompress_ptr cinfo, boxptr boxp)
430 /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
431 /* and recompute its volume and population */
432 {
433 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
434 hist3d histogram = cquantize->histogram;
435 histptr histp;
436 int c0,c1,c2;
437 int c0min,c0max,c1min,c1max,c2min,c2max;
438 INT32 dist0,dist1,dist2;
439 long ccount;
440
441 c0min = boxp->c0min; c0max = boxp->c0max;
442 c1min = boxp->c1min; c1max = boxp->c1max;
443 c2min = boxp->c2min; c2max = boxp->c2max;
444
445 if (c0max > c0min)
446 for (c0 = c0min; c0 <= c0max; c0++)
447 for (c1 = c1min; c1 <= c1max; c1++) {
448 histp = & histogram[c0][c1][c2min];
449 for (c2 = c2min; c2 <= c2max; c2++)
450 if (*histp++ != 0) {
451 boxp->c0min = c0min = c0;
452 goto have_c0min;
453 }
454 }
455 have_c0min:
456 if (c0max > c0min)
457 for (c0 = c0max; c0 >= c0min; c0--)
458 for (c1 = c1min; c1 <= c1max; c1++) {
459 histp = & histogram[c0][c1][c2min];
460 for (c2 = c2min; c2 <= c2max; c2++)
461 if (*histp++ != 0) {
462 boxp->c0max = c0max = c0;
463 goto have_c0max;
464 }
465 }
466 have_c0max:
467 if (c1max > c1min)
468 for (c1 = c1min; c1 <= c1max; c1++)
469 for (c0 = c0min; c0 <= c0max; c0++) {
470 histp = & histogram[c0][c1][c2min];
471 for (c2 = c2min; c2 <= c2max; c2++)
472 if (*histp++ != 0) {
473 boxp->c1min = c1min = c1;
474 goto have_c1min;
475 }
476 }
477 have_c1min:
478 if (c1max > c1min)
479 for (c1 = c1max; c1 >= c1min; c1--)
480 for (c0 = c0min; c0 <= c0max; c0++) {
481 histp = & histogram[c0][c1][c2min];
482 for (c2 = c2min; c2 <= c2max; c2++)
483 if (*histp++ != 0) {
484 boxp->c1max = c1max = c1;
485 goto have_c1max;
486 }
487 }
488 have_c1max:
489 if (c2max > c2min)
490 for (c2 = c2min; c2 <= c2max; c2++)
491 for (c0 = c0min; c0 <= c0max; c0++) {
492 histp = & histogram[c0][c1min][c2];
493 for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
494 if (*histp != 0) {
495 boxp->c2min = c2min = c2;
496 goto have_c2min;
497 }
498 }
499 have_c2min:
500 if (c2max > c2min)
501 for (c2 = c2max; c2 >= c2min; c2--)
502 for (c0 = c0min; c0 <= c0max; c0++) {
503 histp = & histogram[c0][c1min][c2];
504 for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
505 if (*histp != 0) {
506 boxp->c2max = c2max = c2;
507 goto have_c2max;
508 }
509 }
510 have_c2max:
511
512 /* Update box volume.
513 * We use 2-norm rather than real volume here; this biases the method
514 * against making long narrow boxes, and it has the side benefit that
515 * a box is splittable iff norm > 0.
516 * Since the differences are expressed in histogram-cell units,
517 * we have to shift back to JSAMPLE units to get consistent distances;
518 * after which, we scale according to the selected distance scale factors.
519 */
520 dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
521 dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
522 dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
523 boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
524
525 /* Now scan remaining volume of box and compute population */
526 ccount = 0;
527 for (c0 = c0min; c0 <= c0max; c0++)
528 for (c1 = c1min; c1 <= c1max; c1++) {
529 histp = & histogram[c0][c1][c2min];
530 for (c2 = c2min; c2 <= c2max; c2++, histp++)
531 if (*histp != 0) {
532 ccount++;
533 }
534 }
535 boxp->colorcount = ccount;
536 }
537
538
539 int
540 median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
541 int desired_colors)
542 /* Repeatedly select and split the largest box until we have enough boxes */
543 {
544 int n,lb;
545 int c0,c1,c2,cmax;
546 register boxptr b1,b2;
547
548 while (numboxes < desired_colors) {
549 /* Select box to split.
550 * Current algorithm: by population for first half, then by volume.
551 */
552 if ((numboxes*2) <= desired_colors) {
553 b1 = find_biggest_color_pop(boxlist, numboxes);
554 } else {
555 b1 = find_biggest_volume(boxlist, numboxes);
556 }
557 if (b1 == NULL) /* no splittable boxes left! */
558 break;
559 b2 = &boxlist[numboxes]; /* where new box will go */
560 /* Copy the color bounds to the new box. */
561 b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
562 b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
563 /* Choose which axis to split the box on.
564 * Current algorithm: longest scaled axis.
565 * See notes in update_box about scaling distances.
566 */
567 c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
568 c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
569 c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
570 /* We want to break any ties in favor of green, then red, blue last.
571 * This code does the right thing for R,G,B or B,G,R color orders only.
572 */
573 #if defined(__VISAGECPP__)
574
575 #if RGB_RED_OS2 == 0
576 cmax = c1; n = 1;
577 if (c0 > cmax) { cmax = c0; n = 0; }
578 if (c2 > cmax) { n = 2; }
579 #else
580 cmax = c1; n = 1;
581 if (c2 > cmax) { cmax = c2; n = 2; }
582 if (c0 > cmax) { n = 0; }
583 #endif
584
585 #else
586
587 #if RGB_RED == 0
588 cmax = c1; n = 1;
589 if (c0 > cmax) { cmax = c0; n = 0; }
590 if (c2 > cmax) { n = 2; }
591 #else
592 cmax = c1; n = 1;
593 if (c2 > cmax) { cmax = c2; n = 2; }
594 if (c0 > cmax) { n = 0; }
595 #endif
596
597 #endif
598 /* Choose split point along selected axis, and update box bounds.
599 * Current algorithm: split at halfway point.
600 * (Since the box has been shrunk to minimum volume,
601 * any split will produce two nonempty subboxes.)
602 * Note that lb value is max for lower box, so must be < old max.
603 */
604 switch (n) {
605 case 0:
606 lb = (b1->c0max + b1->c0min) / 2;
607 b1->c0max = lb;
608 b2->c0min = lb+1;
609 break;
610 case 1:
611 lb = (b1->c1max + b1->c1min) / 2;
612 b1->c1max = lb;
613 b2->c1min = lb+1;
614 break;
615 case 2:
616 lb = (b1->c2max + b1->c2min) / 2;
617 b1->c2max = lb;
618 b2->c2min = lb+1;
619 break;
620 }
621 /* Update stats for boxes */
622 update_box(cinfo, b1);
623 update_box(cinfo, b2);
624 numboxes++;
625 }
626 return numboxes;
627 }
628
629
630 void
631 compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
632 /* Compute representative color for a box, put it in colormap[icolor] */
633 {
634 /* Current algorithm: mean weighted by pixels (not colors) */
635 /* Note it is important to get the rounding correct! */
636 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
637 hist3d histogram = cquantize->histogram;
638 histptr histp;
639 int c0,c1,c2;
640 int c0min,c0max,c1min,c1max,c2min,c2max;
641 long count;
642 long total = 0;
643 long c0total = 0;
644 long c1total = 0;
645 long c2total = 0;
646
647 c0min = boxp->c0min; c0max = boxp->c0max;
648 c1min = boxp->c1min; c1max = boxp->c1max;
649 c2min = boxp->c2min; c2max = boxp->c2max;
650
651 for (c0 = c0min; c0 <= c0max; c0++)
652 for (c1 = c1min; c1 <= c1max; c1++) {
653 histp = & histogram[c0][c1][c2min];
654 for (c2 = c2min; c2 <= c2max; c2++) {
655 if ((count = *histp++) != 0) {
656 total += count;
657 c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
658 c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
659 c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
660 }
661 }
662 }
663
664 cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
665 cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
666 cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
667 }
668
669
670 static void
671 select_colors (j_decompress_ptr cinfo, int desired_colors)
672 /* Master routine for color selection */
673 {
674 boxptr boxlist;
675 int numboxes;
676 int i;
677
678 /* Allocate workspace for box list */
679 boxlist = (boxptr) malloc(desired_colors * sizeof(box));
680 /* Initialize one box containing whole space */
681 numboxes = 1;
682 boxlist[0].c0min = 0;
683 boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
684 boxlist[0].c1min = 0;
685 boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
686 boxlist[0].c2min = 0;
687 boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
688 /* Shrink it to actually-used volume and set its statistics */
689 update_box(cinfo, & boxlist[0]);
690 /* Perform median-cut to produce final box list */
691 numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
692 /* Compute the representative color for each box, fill colormap */
693 for (i = 0; i < numboxes; i++)
694 compute_color(cinfo, & boxlist[i], i);
695 cinfo->actual_number_of_colors = numboxes;
696
697 free(boxlist); //FIXME?? I don't know if this is correct - VS
698 }
699
700
701 /*
702 * These routines are concerned with the time-critical task of mapping input
703 * colors to the nearest color in the selected colormap.
704 *
705 * We re-use the histogram space as an "inverse color map", essentially a
706 * cache for the results of nearest-color searches. All colors within a
707 * histogram cell will be mapped to the same colormap entry, namely the one
708 * closest to the cell's center. This may not be quite the closest entry to
709 * the actual input color, but it's almost as good. A zero in the cache
710 * indicates we haven't found the nearest color for that cell yet; the array
711 * is cleared to zeroes before starting the mapping pass. When we find the
712 * nearest color for a cell, its colormap index plus one is recorded in the
713 * cache for future use. The pass2 scanning routines call fill_inverse_cmap
714 * when they need to use an unfilled entry in the cache.
715 *
716 * Our method of efficiently finding nearest colors is based on the "locally
717 * sorted search" idea described by Heckbert and on the incremental distance
718 * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
719 * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
720 * the distances from a given colormap entry to each cell of the histogram can
721 * be computed quickly using an incremental method: the differences between
722 * distances to adjacent cells themselves differ by a constant. This allows a
723 * fairly fast implementation of the "brute force" approach of computing the
724 * distance from every colormap entry to every histogram cell. Unfortunately,
725 * it needs a work array to hold the best-distance-so-far for each histogram
726 * cell (because the inner loop has to be over cells, not colormap entries).
727 * The work array elements have to be INT32s, so the work array would need
728 * 256Kb at our recommended precision. This is not feasible in DOS machines.
729 *
730 * To get around these problems, we apply Thomas' method to compute the
731 * nearest colors for only the cells within a small subbox of the histogram.
732 * The work array need be only as big as the subbox, so the memory usage
733 * problem is solved. Furthermore, we need not fill subboxes that are never
734 * referenced in pass2; many images use only part of the color gamut, so a
735 * fair amount of work is saved. An additional advantage of this
736 * approach is that we can apply Heckbert's locality criterion to quickly
737 * eliminate colormap entries that are far away from the subbox; typically
738 * three-fourths of the colormap entries are rejected by Heckbert's criterion,
739 * and we need not compute their distances to individual cells in the subbox.
740 * The speed of this approach is heavily influenced by the subbox size: too
741 * small means too much overhead, too big loses because Heckbert's criterion
742 * can't eliminate as many colormap entries. Empirically the best subbox
743 * size seems to be about 1/512th of the histogram (1/8th in each direction).
744 *
745 * Thomas' article also describes a refined method which is asymptotically
746 * faster than the brute-force method, but it is also far more complex and
747 * cannot efficiently be applied to small subboxes. It is therefore not
748 * useful for programs intended to be portable to DOS machines. On machines
749 * with plenty of memory, filling the whole histogram in one shot with Thomas'
750 * refined method might be faster than the present code --- but then again,
751 * it might not be any faster, and it's certainly more complicated.
752 */
753
754
755 /* log2(histogram cells in update box) for each axis; this can be adjusted */
756 #define BOX_C0_LOG (HIST_C0_BITS-3)
757 #define BOX_C1_LOG (HIST_C1_BITS-3)
758 #define BOX_C2_LOG (HIST_C2_BITS-3)
759
760 #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
761 #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
762 #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
763
764 #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
765 #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
766 #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
767
768
769 /*
770 * The next three routines implement inverse colormap filling. They could
771 * all be folded into one big routine, but splitting them up this way saves
772 * some stack space (the mindist[] and bestdist[] arrays need not coexist)
773 * and may allow some compilers to produce better code by registerizing more
774 * inner-loop variables.
775 */
776
777 static int
778 find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
779 JSAMPLE colorlist[])
780 /* Locate the colormap entries close enough to an update box to be candidates
781 * for the nearest entry to some cell(s) in the update box. The update box
782 * is specified by the center coordinates of its first cell. The number of
783 * candidate colormap entries is returned, and their colormap indexes are
784 * placed in colorlist[].
785 * This routine uses Heckbert's "locally sorted search" criterion to select
786 * the colors that need further consideration.
787 */
788 {
789 int numcolors = cinfo->actual_number_of_colors;
790 int maxc0, maxc1, maxc2;
791 int centerc0, centerc1, centerc2;
792 int i, x, ncolors;
793 INT32 minmaxdist, min_dist, max_dist, tdist;
794 INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
795
796 /* Compute true coordinates of update box's upper corner and center.
797 * Actually we compute the coordinates of the center of the upper-corner
798 * histogram cell, which are the upper bounds of the volume we care about.
799 * Note that since ">>" rounds down, the "center" values may be closer to
800 * min than to max; hence comparisons to them must be "<=", not "<".
801 */
802 maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
803 centerc0 = (minc0 + maxc0) >> 1;
804 maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
805 centerc1 = (minc1 + maxc1) >> 1;
806 maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
807 centerc2 = (minc2 + maxc2) >> 1;
808
809 /* For each color in colormap, find:
810 * 1. its minimum squared-distance to any point in the update box
811 * (zero if color is within update box);
812 * 2. its maximum squared-distance to any point in the update box.
813 * Both of these can be found by considering only the corners of the box.
814 * We save the minimum distance for each color in mindist[];
815 * only the smallest maximum distance is of interest.
816 */
817 minmaxdist = 0x7FFFFFFFL;
818
819 for (i = 0; i < numcolors; i++) {
820 /* We compute the squared-c0-distance term, then add in the other two. */
821 x = GETJSAMPLE(cinfo->colormap[0][i]);
822 if (x < minc0) {
823 tdist = (x - minc0) * C0_SCALE;
824 min_dist = tdist*tdist;
825 tdist = (x - maxc0) * C0_SCALE;
826 max_dist = tdist*tdist;
827 } else if (x > maxc0) {
828 tdist = (x - maxc0) * C0_SCALE;
829 min_dist = tdist*tdist;
830 tdist = (x - minc0) * C0_SCALE;
831 max_dist = tdist*tdist;
832 } else {
833 /* within cell range so no contribution to min_dist */
834 min_dist = 0;
835 if (x <= centerc0) {
836 tdist = (x - maxc0) * C0_SCALE;
837 max_dist = tdist*tdist;
838 } else {
839 tdist = (x - minc0) * C0_SCALE;
840 max_dist = tdist*tdist;
841 }
842 }
843
844 x = GETJSAMPLE(cinfo->colormap[1][i]);
845 if (x < minc1) {
846 tdist = (x - minc1) * C1_SCALE;
847 min_dist += tdist*tdist;
848 tdist = (x - maxc1) * C1_SCALE;
849 max_dist += tdist*tdist;
850 } else if (x > maxc1) {
851 tdist = (x - maxc1) * C1_SCALE;
852 min_dist += tdist*tdist;
853 tdist = (x - minc1) * C1_SCALE;
854 max_dist += tdist*tdist;
855 } else {
856 /* within cell range so no contribution to min_dist */
857 if (x <= centerc1) {
858 tdist = (x - maxc1) * C1_SCALE;
859 max_dist += tdist*tdist;
860 } else {
861 tdist = (x - minc1) * C1_SCALE;
862 max_dist += tdist*tdist;
863 }
864 }
865
866 x = GETJSAMPLE(cinfo->colormap[2][i]);
867 if (x < minc2) {
868 tdist = (x - minc2) * C2_SCALE;
869 min_dist += tdist*tdist;
870 tdist = (x - maxc2) * C2_SCALE;
871 max_dist += tdist*tdist;
872 } else if (x > maxc2) {
873 tdist = (x - maxc2) * C2_SCALE;
874 min_dist += tdist*tdist;
875 tdist = (x - minc2) * C2_SCALE;
876 max_dist += tdist*tdist;
877 } else {
878 /* within cell range so no contribution to min_dist */
879 if (x <= centerc2) {
880 tdist = (x - maxc2) * C2_SCALE;
881 max_dist += tdist*tdist;
882 } else {
883 tdist = (x - minc2) * C2_SCALE;
884 max_dist += tdist*tdist;
885 }
886 }
887
888 mindist[i] = min_dist; /* save away the results */
889 if (max_dist < minmaxdist)
890 minmaxdist = max_dist;
891 }
892
893 /* Now we know that no cell in the update box is more than minmaxdist
894 * away from some colormap entry. Therefore, only colors that are
895 * within minmaxdist of some part of the box need be considered.
896 */
897 ncolors = 0;
898 for (i = 0; i < numcolors; i++) {
899 if (mindist[i] <= minmaxdist)
900 colorlist[ncolors++] = (JSAMPLE) i;
901 }
902 return ncolors;
903 }
904
905
906 static void
907 find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
908 int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
909 /* Find the closest colormap entry for each cell in the update box,
910 * given the list of candidate colors prepared by find_nearby_colors.
911 * Return the indexes of the closest entries in the bestcolor[] array.
912 * This routine uses Thomas' incremental distance calculation method to
913 * find the distance from a colormap entry to successive cells in the box.
914 */
915 {
916 int ic0, ic1, ic2;
917 int i, icolor;
918 register INT32 * bptr; /* pointer into bestdist[] array */
919 JSAMPLE * cptr; /* pointer into bestcolor[] array */
920 INT32 dist0, dist1; /* initial distance values */
921 register INT32 dist2; /* current distance in inner loop */
922 INT32 xx0, xx1; /* distance increments */
923 register INT32 xx2;
924 INT32 inc0, inc1, inc2; /* initial values for increments */
925 /* This array holds the distance to the nearest-so-far color for each cell */
926 INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
927
928 /* Initialize best-distance for each cell of the update box */
929 bptr = bestdist;
930 for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
931 *bptr++ = 0x7FFFFFFFL;
932
933 /* For each color selected by find_nearby_colors,
934 * compute its distance to the center of each cell in the box.
935 * If that's less than best-so-far, update best distance and color number.
936 */
937
938 /* Nominal steps between cell centers ("x" in Thomas article) */
939 #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
940 #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
941 #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
942
943 for (i = 0; i < numcolors; i++) {
944 icolor = GETJSAMPLE(colorlist[i]);
945 /* Compute (square of) distance from minc0/c1/c2 to this color */
946 inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
947 dist0 = inc0*inc0;
948 inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
949 dist0 += inc1*inc1;
950 inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
951 dist0 += inc2*inc2;
952 /* Form the initial difference increments */
953 inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
954 inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
955 inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
956 /* Now loop over all cells in box, updating distance per Thomas method */
957 bptr = bestdist;
958 cptr = bestcolor;
959 xx0 = inc0;
960 for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
961 dist1 = dist0;
962 xx1 = inc1;
963 for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
964 dist2 = dist1;
965 xx2 = inc2;
966 for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
967 if (dist2 < *bptr) {
968 *bptr = dist2;
969 *cptr = (JSAMPLE) icolor;
970 }
971 dist2 += xx2;
972 xx2 += 2 * STEP_C2 * STEP_C2;
973 bptr++;
974 cptr++;
975 }
976 dist1 += xx1;
977 xx1 += 2 * STEP_C1 * STEP_C1;
978 }
979 dist0 += xx0;
980 xx0 += 2 * STEP_C0 * STEP_C0;
981 }
982 }
983 }
984
985
986 static void
987 fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
988 /* Fill the inverse-colormap entries in the update box that contains */
989 /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
990 /* we can fill as many others as we wish.) */
991 {
992 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
993 hist3d histogram = cquantize->histogram;
994 int minc0, minc1, minc2; /* lower left corner of update box */
995 int ic0, ic1, ic2;
996 register JSAMPLE * cptr; /* pointer into bestcolor[] array */
997 register histptr cachep; /* pointer into main cache array */
998 /* This array lists the candidate colormap indexes. */
999 JSAMPLE colorlist[MAXNUMCOLORS];
1000 int numcolors; /* number of candidate colors */
1001 /* This array holds the actually closest colormap index for each cell. */
1002 JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
1003
1004 /* Convert cell coordinates to update box ID */
1005 c0 >>= BOX_C0_LOG;
1006 c1 >>= BOX_C1_LOG;
1007 c2 >>= BOX_C2_LOG;
1008
1009 /* Compute true coordinates of update box's origin corner.
1010 * Actually we compute the coordinates of the center of the corner
1011 * histogram cell, which are the lower bounds of the volume we care about.
1012 */
1013 minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
1014 minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
1015 minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
1016
1017 /* Determine which colormap entries are close enough to be candidates
1018 * for the nearest entry to some cell in the update box.
1019 */
1020 numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
1021
1022 /* Determine the actually nearest colors. */
1023 find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
1024 bestcolor);
1025
1026 /* Save the best color numbers (plus 1) in the main cache array */
1027 c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
1028 c1 <<= BOX_C1_LOG;
1029 c2 <<= BOX_C2_LOG;
1030 cptr = bestcolor;
1031 for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
1032 for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
1033 cachep = & histogram[c0+ic0][c1+ic1][c2];
1034 for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
1035 *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
1036 }
1037 }
1038 }
1039 }
1040
1041
1042 /*
1043 * Map some rows of pixels to the output colormapped representation.
1044 */
1045
1046 void
1047 pass2_no_dither (j_decompress_ptr cinfo,
1048 JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
1049 /* This version performs no dithering */
1050 {
1051 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1052 hist3d histogram = cquantize->histogram;
1053 register JSAMPROW inptr, outptr;
1054 register histptr cachep;
1055 register int c0, c1, c2;
1056 int row;
1057 JDIMENSION col;
1058 JDIMENSION width = cinfo->output_width;
1059
1060 for (row = 0; row < num_rows; row++) {
1061 inptr = input_buf[row];
1062 outptr = output_buf[row];
1063 for (col = width; col > 0; col--) {
1064 /* get pixel value and index into the cache */
1065 c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
1066 c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
1067 c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
1068 cachep = & histogram[c0][c1][c2];
1069 /* If we have not seen this color before, find nearest colormap entry */
1070 /* and update the cache */
1071 if (*cachep == 0)
1072 fill_inverse_cmap(cinfo, c0,c1,c2);
1073 /* Now emit the colormap index for this cell */
1074 *outptr++ = (JSAMPLE) (*cachep - 1);
1075 }
1076 }
1077 }
1078
1079
1080 void
1081 pass2_fs_dither (j_decompress_ptr cinfo,
1082 JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
1083 /* This version performs Floyd-Steinberg dithering */
1084 {
1085 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1086 hist3d histogram = cquantize->histogram;
1087 register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
1088 LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
1089 LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
1090 register FSERRPTR errorptr; /* => fserrors[] at column before current */
1091 JSAMPROW inptr; /* => current input pixel */
1092 JSAMPROW outptr; /* => current output pixel */
1093 histptr cachep;
1094 int dir; /* +1 or -1 depending on direction */
1095 int dir3; /* 3*dir, for advancing inptr & errorptr */
1096 int row;
1097 JDIMENSION col;
1098 JDIMENSION width = cinfo->output_width;
1099 JSAMPLE *range_limit = cinfo->sample_range_limit;
1100 int *error_limit = cquantize->error_limiter;
1101 JSAMPROW colormap0 = cinfo->colormap[0];
1102 JSAMPROW colormap1 = cinfo->colormap[1];
1103 JSAMPROW colormap2 = cinfo->colormap[2];
1104
1105
1106 for (row = 0; row < num_rows; row++) {
1107 inptr = input_buf[row];
1108 outptr = output_buf[row];
1109 if (cquantize->on_odd_row) {
1110 /* work right to left in this row */
1111 inptr += (width-1) * 3; /* so point to rightmost pixel */
1112 outptr += width-1;
1113 dir = -1;
1114 dir3 = -3;
1115 errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
1116 cquantize->on_odd_row = FALSE; /* flip for next time */
1117 } else {
1118 /* work left to right in this row */
1119 dir = 1;
1120 dir3 = 3;
1121 errorptr = cquantize->fserrors; /* => entry before first real column */
1122 cquantize->on_odd_row = TRUE; /* flip for next time */
1123 }
1124 /* Preset error values: no error propagated to first pixel from left */
1125 cur0 = cur1 = cur2 = 0;
1126 /* and no error propagated to row below yet */
1127 belowerr0 = belowerr1 = belowerr2 = 0;
1128 bpreverr0 = bpreverr1 = bpreverr2 = 0;
1129
1130 for (col = width; col > 0; col--) {
1131 /* curN holds the error propagated from the previous pixel on the
1132 * current line. Add the error propagated from the previous line
1133 * to form the complete error correction term for this pixel, and
1134 * round the error term (which is expressed * 16) to an integer.
1135 * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
1136 * for either sign of the error value.
1137 * Note: errorptr points to *previous* column's array entry.
1138 */
1139 cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
1140 cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
1141 cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
1142 /* Limit the error using transfer function set by init_error_limit.
1143 * See comments with init_error_limit for rationale.
1144 */
1145 cur0 = error_limit[cur0];
1146 cur1 = error_limit[cur1];
1147 cur2 = error_limit[cur2];
1148 /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
1149 * The maximum error is +- MAXJSAMPLE (or less with error limiting);
1150 * this sets the required size of the range_limit array.
1151 */
1152 cur0 += GETJSAMPLE(inptr[0]);
1153 cur1 += GETJSAMPLE(inptr[1]);
1154 cur2 += GETJSAMPLE(inptr[2]);
1155 cur0 = GETJSAMPLE(range_limit[cur0]);
1156 cur1 = GETJSAMPLE(range_limit[cur1]);
1157 cur2 = GETJSAMPLE(range_limit[cur2]);
1158 /* Index into the cache with adjusted pixel value */
1159 cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
1160 /* If we have not seen this color before, find nearest colormap */
1161 /* entry and update the cache */
1162 if (*cachep == 0)
1163 fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
1164 /* Now emit the colormap index for this cell */
1165 { register int pixcode = *cachep - 1;
1166 *outptr = (JSAMPLE) pixcode;
1167 /* Compute representation error for this pixel */
1168 cur0 -= GETJSAMPLE(colormap0[pixcode]);
1169 cur1 -= GETJSAMPLE(colormap1[pixcode]);
1170 cur2 -= GETJSAMPLE(colormap2[pixcode]);
1171 }
1172 /* Compute error fractions to be propagated to adjacent pixels.
1173 * Add these into the running sums, and simultaneously shift the
1174 * next-line error sums left by 1 column.
1175 */
1176 { register LOCFSERROR bnexterr, delta;
1177
1178 bnexterr = cur0; /* Process component 0 */
1179 delta = cur0 * 2;
1180 cur0 += delta; /* form error * 3 */
1181 errorptr[0] = (FSERROR) (bpreverr0 + cur0);
1182 cur0 += delta; /* form error * 5 */
1183 bpreverr0 = belowerr0 + cur0;
1184 belowerr0 = bnexterr;
1185 cur0 += delta; /* form error * 7 */
1186 bnexterr = cur1; /* Process component 1 */
1187 delta = cur1 * 2;
1188 cur1 += delta; /* form error * 3 */
1189 errorptr[1] = (FSERROR) (bpreverr1 + cur1);
1190 cur1 += delta; /* form error * 5 */
1191 bpreverr1 = belowerr1 + cur1;
1192 belowerr1 = bnexterr;
1193 cur1 += delta; /* form error * 7 */
1194 bnexterr = cur2; /* Process component 2 */
1195 delta = cur2 * 2;
1196 cur2 += delta; /* form error * 3 */
1197 errorptr[2] = (FSERROR) (bpreverr2 + cur2);
1198 cur2 += delta; /* form error * 5 */
1199 bpreverr2 = belowerr2 + cur2;
1200 belowerr2 = bnexterr;
1201 cur2 += delta; /* form error * 7 */
1202 }
1203 /* At this point curN contains the 7/16 error value to be propagated
1204 * to the next pixel on the current line, and all the errors for the
1205 * next line have been shifted over. We are therefore ready to move on.
1206 */
1207 inptr += dir3; /* Advance pixel pointers to next column */
1208 outptr += dir;
1209 errorptr += dir3; /* advance errorptr to current column */
1210 }
1211 /* Post-loop cleanup: we must unload the final error values into the
1212 * final fserrors[] entry. Note we need not unload belowerrN because
1213 * it is for the dummy column before or after the actual array.
1214 */
1215 errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
1216 errorptr[1] = (FSERROR) bpreverr1;
1217 errorptr[2] = (FSERROR) bpreverr2;
1218 }
1219 }
1220
1221
1222 /*
1223 * Initialize the error-limiting transfer function (lookup table).
1224 * The raw F-S error computation can potentially compute error values of up to
1225 * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
1226 * much less, otherwise obviously wrong pixels will be created. (Typical
1227 * effects include weird fringes at color-area boundaries, isolated bright
1228 * pixels in a dark area, etc.) The standard advice for avoiding this problem
1229 * is to ensure that the "corners" of the color cube are allocated as output
1230 * colors; then repeated errors in the same direction cannot cause cascading
1231 * error buildup. However, that only prevents the error from getting
1232 * completely out of hand; Aaron Giles reports that error limiting improves
1233 * the results even with corner colors allocated.
1234 * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
1235 * well, but the smoother transfer function used below is even better. Thanks
1236 * to Aaron Giles for this idea.
1237 */
1238
1239 static void
1240 init_error_limit (j_decompress_ptr cinfo)
1241 /* Allocate and fill in the error_limiter table */
1242 {
1243 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1244 int * table;
1245 int in, out;
1246
1247 table = (int *) malloc((MAXJSAMPLE*2+1) * sizeof(int));
1248 table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
1249 cquantize->error_limiter = table;
1250
1251 #define STEPSIZE ((MAXJSAMPLE+1)/16)
1252 /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
1253 out = 0;
1254 for (in = 0; in < STEPSIZE; in++, out++) {
1255 table[in] = out; table[-in] = -out;
1256 }
1257 /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
1258 for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
1259 table[in] = out; table[-in] = -out;
1260 }
1261 /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
1262 for (; in <= MAXJSAMPLE; in++) {
1263 table[in] = out; table[-in] = -out;
1264 }
1265 #undef STEPSIZE
1266 }
1267
1268
1269 /*
1270 * Finish up at the end of each pass.
1271 */
1272
1273 void
1274 finish_pass1 (j_decompress_ptr cinfo)
1275 {
1276 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1277
1278 /* Select the representative colors and fill in cinfo->colormap */
1279 cinfo->colormap = cquantize->sv_colormap;
1280 select_colors(cinfo, cquantize->desired);
1281 /* Force next pass to zero the color index table */
1282 cquantize->needs_zeroed = TRUE;
1283 }
1284
1285
1286 void
1287 finish_pass2 (j_decompress_ptr WXUNUSED(cinfo))
1288 {
1289 /* no work */
1290 }
1291
1292
1293 /*
1294 * Initialize for each processing pass.
1295 */
1296
1297 void
1298 start_pass_2_quant (j_decompress_ptr cinfo, bool is_pre_scan)
1299 {
1300 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1301 hist3d histogram = cquantize->histogram;
1302 int i;
1303
1304 if (is_pre_scan) {
1305 /* Set up method pointers */
1306 cquantize->pub.color_quantize = prescan_quantize;
1307 cquantize->pub.finish_pass = finish_pass1;
1308 cquantize->needs_zeroed = TRUE; /* Always zero histogram */
1309 } else {
1310 /* Set up method pointers */
1311 cquantize->pub.color_quantize = pass2_fs_dither;
1312 cquantize->pub.finish_pass = finish_pass2;
1313
1314 /* Make sure color count is acceptable */
1315 i = cinfo->actual_number_of_colors;
1316
1317 {
1318 size_t arraysize = (size_t) ((cinfo->output_width + 2) *
1319 (3 * sizeof(FSERROR)));
1320 /* Allocate Floyd-Steinberg workspace if we didn't already. */
1321 if (cquantize->fserrors == NULL)
1322 cquantize->fserrors = (INT16*) malloc(arraysize);
1323 /* Initialize the propagated errors to zero. */
1324 memset((void *) cquantize->fserrors, 0, arraysize);
1325 /* Make the error-limit table if we didn't already. */
1326 if (cquantize->error_limiter == NULL)
1327 init_error_limit(cinfo);
1328 cquantize->on_odd_row = FALSE;
1329 }
1330
1331 }
1332 /* Zero the histogram or inverse color map, if necessary */
1333 if (cquantize->needs_zeroed) {
1334 for (i = 0; i < HIST_C0_ELEMS; i++) {
1335 memset((void *) histogram[i], 0,
1336 HIST_C1_ELEMS*HIST_C2_ELEMS * sizeof(histcell));
1337 }
1338 cquantize->needs_zeroed = FALSE;
1339 }
1340 }
1341
1342
1343 /*
1344 * Switch to a new external colormap between output passes.
1345 */
1346
1347 void
1348 new_color_map_2_quant (j_decompress_ptr cinfo)
1349 {
1350 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
1351
1352 /* Reset the inverse color map */
1353 cquantize->needs_zeroed = TRUE;
1354 }
1355
1356
1357 /*
1358 * Module initialization routine for 2-pass color quantization.
1359 */
1360
1361 void
1362 jinit_2pass_quantizer (j_decompress_ptr cinfo)
1363 {
1364 my_cquantize_ptr cquantize;
1365 int i;
1366
1367 cquantize = (my_cquantize_ptr) malloc(sizeof(my_cquantizer));
1368 cinfo->cquantize = (jpeg_color_quantizer *) cquantize;
1369 cquantize->pub.start_pass = start_pass_2_quant;
1370 cquantize->pub.new_color_map = new_color_map_2_quant;
1371 cquantize->fserrors = NULL; /* flag optional arrays not allocated */
1372 cquantize->error_limiter = NULL;
1373
1374
1375 /* Allocate the histogram/inverse colormap storage */
1376 cquantize->histogram = (hist3d) malloc(HIST_C0_ELEMS * sizeof(hist2d));
1377 for (i = 0; i < HIST_C0_ELEMS; i++) {
1378 cquantize->histogram[i] = (hist2d) malloc(HIST_C1_ELEMS*HIST_C2_ELEMS * sizeof(histcell));
1379 }
1380 cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
1381
1382 /* Allocate storage for the completed colormap, if required.
1383 * We do this now since it is storage and may affect
1384 * the memory manager's space calculations.
1385 */
1386 {
1387 /* Make sure color count is acceptable */
1388 int desired = cinfo->desired_number_of_colors;
1389
1390 cquantize->sv_colormap = (JSAMPARRAY) malloc(sizeof(JSAMPROW) * 3);
1391 cquantize->sv_colormap[0] = (JSAMPROW) malloc(sizeof(JSAMPLE) * desired);
1392 cquantize->sv_colormap[1] = (JSAMPROW) malloc(sizeof(JSAMPLE) * desired);
1393 cquantize->sv_colormap[2] = (JSAMPROW) malloc(sizeof(JSAMPLE) * desired);
1394
1395 cquantize->desired = desired;
1396 }
1397
1398 /* Allocate Floyd-Steinberg workspace if necessary.
1399 * This isn't really needed until pass 2, but again it is storage.
1400 * Although we will cope with a later change in dither_mode,
1401 * we do not promise to honor max_memory_to_use if dither_mode changes.
1402 */
1403 {
1404 cquantize->fserrors = (FSERRPTR) malloc(
1405 (size_t) ((cinfo->output_width + 2) * (3 * sizeof(FSERROR))));
1406 /* Might as well create the error-limiting table too. */
1407 init_error_limit(cinfo);
1408 }
1409 }
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420 void
1421 prepare_range_limit_table (j_decompress_ptr cinfo)
1422 /* Allocate and fill in the sample_range_limit table */
1423 {
1424 JSAMPLE * table;
1425 int i;
1426
1427 table = (JSAMPLE *) malloc((5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * sizeof(JSAMPLE));
1428 cinfo->srl_orig = table;
1429 table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
1430 cinfo->sample_range_limit = table;
1431 /* First segment of "simple" table: limit[x] = 0 for x < 0 */
1432 memset(table - (MAXJSAMPLE+1), 0, (MAXJSAMPLE+1) * sizeof(JSAMPLE));
1433 /* Main part of "simple" table: limit[x] = x */
1434 for (i = 0; i <= MAXJSAMPLE; i++)
1435 table[i] = (JSAMPLE) i;
1436 table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
1437 /* End of simple table, rest of first half of post-IDCT table */
1438 for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
1439 table[i] = MAXJSAMPLE;
1440 /* Second half of post-IDCT table */
1441 memset(table + (2 * (MAXJSAMPLE+1)), 0,
1442 (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * sizeof(JSAMPLE));
1443 memcpy(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
1444 cinfo->sample_range_limit, CENTERJSAMPLE * sizeof(JSAMPLE));
1445 }
1446
1447
1448
1449
1450 /*
1451 * wxQuantize
1452 */
1453
1454 IMPLEMENT_DYNAMIC_CLASS(wxQuantize, wxObject)
1455
1456 void wxQuantize::DoQuantize(unsigned w, unsigned h, unsigned char **in_rows, unsigned char **out_rows,
1457 unsigned char *palette, int desiredNoColours)
1458 {
1459 j_decompress dec;
1460 my_cquantize_ptr cquantize;
1461
1462 dec.output_width = w;
1463 dec.desired_number_of_colors = desiredNoColours;
1464 prepare_range_limit_table(&dec);
1465 jinit_2pass_quantizer(&dec);
1466 cquantize = (my_cquantize_ptr) dec.cquantize;
1467
1468
1469 cquantize->pub.start_pass(&dec, TRUE);
1470 cquantize->pub.color_quantize(&dec, in_rows, out_rows, h);
1471 cquantize->pub.finish_pass(&dec);
1472
1473 cquantize->pub.start_pass(&dec, FALSE);
1474 cquantize->pub.color_quantize(&dec, in_rows, out_rows, h);
1475 cquantize->pub.finish_pass(&dec);
1476
1477
1478 for (int i = 0; i < dec.desired_number_of_colors; i++) {
1479 palette[3 * i + 0] = dec.colormap[0][i];
1480 palette[3 * i + 1] = dec.colormap[1][i];
1481 palette[3 * i + 2] = dec.colormap[2][i];
1482 }
1483
1484 for (int ii = 0; ii < HIST_C0_ELEMS; ii++) free(cquantize->histogram[ii]);
1485 free(cquantize->histogram);
1486 free(dec.colormap[0]);
1487 free(dec.colormap[1]);
1488 free(dec.colormap[2]);
1489 free(dec.colormap);
1490 free(dec.srl_orig);
1491
1492 //free(cquantize->error_limiter);
1493 free((void*)(cquantize->error_limiter - MAXJSAMPLE)); // To reverse what was done to it
1494
1495 free(cquantize->fserrors);
1496 free(cquantize);
1497 }
1498
1499 // TODO: somehow make use of the Windows system colours, rather than ignoring them for the
1500 // purposes of quantization.
1501
1502 bool wxQuantize::Quantize(const wxImage& src, wxImage& dest,
1503 wxPalette** pPalette,
1504 int desiredNoColours,
1505 unsigned char** eightBitData,
1506 int flags)
1507
1508 {
1509 int i;
1510 int w = src.GetWidth();
1511 int h = src.GetHeight();
1512
1513 int windowsSystemColourCount = 20;
1514
1515 int paletteShift = 0;
1516
1517 // Shift the palette up by the number of Windows system colours,
1518 // if necessary
1519 if (flags & wxQUANTIZE_INCLUDE_WINDOWS_COLOURS)
1520 paletteShift = windowsSystemColourCount;
1521
1522 // Make room for the Windows system colours
1523 #ifdef __WXMSW__
1524 if ((flags & wxQUANTIZE_INCLUDE_WINDOWS_COLOURS) && (desiredNoColours > (256 - windowsSystemColourCount)))
1525 desiredNoColours = 256 - windowsSystemColourCount;
1526 #endif
1527
1528 // create rows info:
1529 unsigned char **rows = new unsigned char *[h];
1530 h = src.GetHeight(), w = src.GetWidth();
1531 unsigned char *imgdt = src.GetData();
1532 for (i = 0; i < h; i++)
1533 rows[i] = imgdt + 3/*RGB*/ * w * i;
1534
1535 unsigned char palette[3*256];
1536
1537 // This is the image as represented by palette indexes.
1538 unsigned char *data8bit = new unsigned char[w * h];
1539 unsigned char **outrows = new unsigned char *[h];
1540 for (i = 0; i < h; i++)
1541 outrows[i] = data8bit + w * i;
1542
1543 //RGB->palette
1544 DoQuantize(w, h, rows, outrows, palette, desiredNoColours);
1545
1546 delete[] rows;
1547 delete[] outrows;
1548
1549 // palette->RGB(max.256)
1550
1551 if (flags & wxQUANTIZE_FILL_DESTINATION_IMAGE)
1552 {
1553 if (!dest.Ok())
1554 dest.Create(w, h);
1555
1556 imgdt = dest.GetData();
1557 for (i = 0; i < w * h; i++)
1558 {
1559 unsigned char c = data8bit[i];
1560 imgdt[3 * i + 0/*R*/] = palette[3 * c + 0];
1561 imgdt[3 * i + 1/*G*/] = palette[3 * c + 1];
1562 imgdt[3 * i + 2/*B*/] = palette[3 * c + 2];
1563 }
1564 }
1565
1566 if (eightBitData && (flags & wxQUANTIZE_RETURN_8BIT_DATA))
1567 {
1568 #ifdef __WXMSW__
1569 if (flags & wxQUANTIZE_INCLUDE_WINDOWS_COLOURS)
1570 {
1571 // We need to shift the palette entries up
1572 // to make room for the Windows system colours.
1573 for (i = 0; i < w * h; i++)
1574 data8bit[i] = data8bit[i] + paletteShift;
1575 }
1576 #endif
1577 *eightBitData = data8bit;
1578 }
1579 else
1580 delete[] data8bit;
1581
1582 #if wxUSE_PALETTE
1583 // Make a wxWindows palette
1584 if (pPalette)
1585 {
1586 unsigned char* r = new unsigned char[256];
1587 unsigned char* g = new unsigned char[256];
1588 unsigned char* b = new unsigned char[256];
1589
1590 #ifdef __WXMSW__
1591 // Fill the first 20 entries with Windows system colours
1592 if (flags & wxQUANTIZE_INCLUDE_WINDOWS_COLOURS)
1593 {
1594 HDC hDC = ::GetDC(NULL);
1595 PALETTEENTRY* entries = new PALETTEENTRY[windowsSystemColourCount];
1596 ::GetSystemPaletteEntries(hDC, 0, windowsSystemColourCount, entries);
1597 ::ReleaseDC(NULL, hDC);
1598
1599 for (i = 0; i < windowsSystemColourCount; i++)
1600 {
1601 r[i] = entries[i].peRed;
1602 g[i] = entries[i].peGreen;
1603 b[i] = entries[i].peBlue;
1604 }
1605 delete[] entries;
1606 }
1607 #endif
1608
1609 for (i = 0; i < desiredNoColours; i++)
1610 {
1611 r[i+paletteShift] = palette[i*3 + 0];
1612 g[i+paletteShift] = palette[i*3 + 1];
1613 b[i+paletteShift] = palette[i*3 + 2];
1614 }
1615
1616 // Blank out any remaining palette entries
1617 for (i = desiredNoColours+paletteShift; i < 256; i++)
1618 {
1619 r[i] = 0;
1620 g[i] = 0;
1621 b[i] = 0;
1622 }
1623 *pPalette = new wxPalette(256, r, g, b);
1624 delete[] r;
1625 delete[] g;
1626 delete[] b;
1627 }
1628 #endif // wxUSE_PALETTE
1629
1630 return TRUE;
1631 }
1632
1633 // This version sets a palette in the destination image so you don't
1634 // have to manage it yourself.
1635
1636 bool wxQuantize::Quantize(const wxImage& src,
1637 wxImage& dest,
1638 int desiredNoColours,
1639 unsigned char** eightBitData,
1640 int flags)
1641 {
1642 wxPalette* palette = NULL;
1643 if ( !Quantize(src, dest, & palette, desiredNoColours, eightBitData, flags) )
1644 return FALSE;
1645
1646 #if wxUSE_PALETTE
1647 if (palette)
1648 {
1649 dest.SetPalette(* palette);
1650 delete palette;
1651 }
1652 #endif // wxUSE_PALETTE
1653
1654 return TRUE;
1655 }
1656