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