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