6
* This code is adapted pretty much entirely from jquant2.c,
7
* Copyright (C) 1991-1996, Thomas G. Lane. That file is
8
* part of the Independent JPEG Group's software. Conditions of
9
* use are compatible with the gd license. See the gd license
10
* statement and README-JPEG.TXT for additional information.
12
* This file contains 2-pass color quantization (color mapping) routines.
13
* These routines provide selection of a custom color map for an image,
14
* followed by mapping of the image to that color map, with optional
15
* Floyd-Steinberg dithering.
17
* It is also possible to use just the second pass to map to an arbitrary
18
* externally-given color map.
20
* Note: ordered dithering is not supported, since there isn't any fast
21
* way to compute intercolor distances; it's unclear that ordered dither's
22
* fundamental assumptions even hold with an irregularly spaced color map.
24
* SUPPORT FOR ALPHA CHANNELS WAS HACKED IN BY THOMAS BOUTELL, who also
25
* adapted the code to work within gd rather than within libjpeg, and
26
* may not have done a great job of either. It's not Thomas G. Lane's fault.
30
#include "gdhelpers.h"
33
* This module implements the well-known Heckbert paradigm for color
34
* quantization. Most of the ideas used here can be traced back to
35
* Heckbert's seminal paper
36
* Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
37
* Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
39
* In the first pass over the image, we accumulate a histogram showing the
40
* usage count of each possible color. To keep the histogram to a reasonable
41
* size, we reduce the precision of the input; typical practice is to retain
42
* 5 or 6 bits per color, so that 8 or 4 different input values are counted
43
* in the same histogram cell.
45
* Next, the color-selection step begins with a box representing the whole
46
* color space, and repeatedly splits the "largest" remaining box until we
47
* have as many boxes as desired colors. Then the mean color in each
48
* remaining box becomes one of the possible output colors.
50
* The second pass over the image maps each input pixel to the closest output
51
* color (optionally after applying a Floyd-Steinberg dithering correction).
52
* This mapping is logically trivial, but making it go fast enough requires
55
* Heckbert-style quantizers vary a good deal in their policies for choosing
56
* the "largest" box and deciding where to cut it. The particular policies
57
* used here have proved out well in experimental comparisons, but better ones
60
* In earlier versions of the IJG code, this module quantized in YCbCr color
61
* space, processing the raw upsampled data without a color conversion step.
62
* This allowed the color conversion math to be done only once per colormap
63
* entry, not once per pixel. However, that optimization precluded other
64
* useful optimizations (such as merging color conversion with upsampling)
65
* and it also interfered with desired capabilities such as quantizing to an
66
* externally-supplied colormap. We have therefore abandoned that approach.
67
* The present code works in the post-conversion color space, typically RGB.
69
* To improve the visual quality of the results, we actually work in scaled
70
* RGBA space, giving G distances more weight than R, and R in turn more than
71
* B. Alpha is weighted least. To do everything in integer math, we must
72
* use integer scale factors. The 2/3/1 scale factors used here correspond
73
* loosely to the relative weights of the colors in the NTSC grayscale
85
#define R_SCALE 2 /* scale R distances by this much */
86
#define G_SCALE 3 /* scale G distances by this much */
87
#define B_SCALE 1 /* and B by this much */
88
#define A_SCALE 4 /* and alpha by this much. This really
89
only scales by 1 because alpha
90
values are 7-bit to begin with. */
92
/* Channel ordering (fixed in gd) */
93
#define C0_SCALE R_SCALE
94
#define C1_SCALE G_SCALE
95
#define C2_SCALE B_SCALE
96
#define C3_SCALE A_SCALE
99
* First we have the histogram data structure and routines for creating it.
101
* The number of bits of precision can be adjusted by changing these symbols.
102
* We recommend keeping 6 bits for G and 5 each for R and B.
103
* If you have plenty of memory and cycles, 6 bits all around gives marginally
104
* better results; if you are short of memory, 5 bits all around will save
105
* some space but degrade the results.
106
* To maintain a fully accurate histogram, we'd need to allocate a "long"
107
* (preferably unsigned long) for each cell. In practice this is overkill;
108
* we can get by with 16 bits per cell. Few of the cell counts will overflow,
109
* and clamping those that do overflow to the maximum value will give close-
110
* enough results. This reduces the recommended histogram size from 256Kb
111
* to 128Kb, which is a useful savings on PC-class machines.
112
* (In the second pass the histogram space is re-used for pixel mapping data;
113
* in that capacity, each cell must be able to store zero to the number of
114
* desired colors. 16 bits/cell is plenty for that too.)
115
* Since the JPEG code is intended to run in small memory model on 80x86
116
* machines, we can't just allocate the histogram in one chunk. Instead
117
* of a true 3-D array, we use a row of pointers to 2-D arrays. Each
118
* pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
119
* each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
120
* on 80x86 machines, the pointer row is in near memory but the actual
121
* arrays are in far memory (same arrangement as we use for image arrays).
124
#define MAXNUMCOLORS (gdMaxColors) /* maximum size of colormap */
126
#define HIST_C0_BITS 5 /* bits of precision in R histogram */
127
#define HIST_C1_BITS 6 /* bits of precision in G histogram */
128
#define HIST_C2_BITS 5 /* bits of precision in B histogram */
129
#define HIST_C3_BITS 3 /* bits of precision in A histogram */
131
/* Number of elements along histogram axes. */
132
#define HIST_C0_ELEMS (1<<HIST_C0_BITS)
133
#define HIST_C1_ELEMS (1<<HIST_C1_BITS)
134
#define HIST_C2_ELEMS (1<<HIST_C2_BITS)
135
#define HIST_C3_ELEMS (1<<HIST_C3_BITS)
137
/* These are the amounts to shift an input value to get a histogram index. */
138
#define C0_SHIFT (8-HIST_C0_BITS)
139
#define C1_SHIFT (8-HIST_C1_BITS)
140
#define C2_SHIFT (8-HIST_C2_BITS)
141
/* Beware! Alpha is 7 bit to begin with */
142
#define C3_SHIFT (7-HIST_C3_BITS)
145
typedef unsigned short histcell; /* histogram cell; prefer an unsigned type */
147
typedef histcell *histptr; /* for pointers to histogram cells */
149
typedef histcell hist1d[HIST_C3_ELEMS]; /* typedefs for the array */
150
typedef hist1d *hist2d; /* type for the 2nd-level pointers */
151
typedef hist2d *hist3d; /* type for third-level pointer */
152
typedef hist3d *hist4d; /* type for top-level pointer */
155
/* Declarations for Floyd-Steinberg dithering.
157
* Errors are accumulated into the array fserrors[], at a resolution of
158
* 1/16th of a pixel count. The error at a given pixel is propagated
159
* to its not-yet-processed neighbors using the standard F-S fractions,
162
* We work left-to-right on even rows, right-to-left on odd rows.
164
* We can get away with a single array (holding one row's worth of errors)
165
* by using it to store the current row's errors at pixel columns not yet
166
* processed, but the next row's errors at columns already processed. We
167
* need only a few extra variables to hold the errors immediately around the
168
* current column. (If we are lucky, those variables are in registers, but
169
* even if not, they're probably cheaper to access than array elements are.)
171
* The fserrors[] array has (#columns + 2) entries; the extra entry at
172
* each end saves us from special-casing the first and last pixels.
173
* Each entry is three values long, one value for each color component.
177
typedef signed short FSERROR; /* 16 bits should be enough */
178
typedef int LOCFSERROR; /* use 'int' for calculation temps */
180
typedef FSERROR *FSERRPTR; /* pointer to error array */
186
hist4d histogram; /* pointer to the histogram */
187
int needs_zeroed; /* TRUE if next pass must zero histogram */
189
/* Variables for Floyd-Steinberg dithering */
190
FSERRPTR fserrors; /* accumulated errors */
191
int on_odd_row; /* flag to remember which row we are on */
192
int *error_limiter; /* table for clamping the applied error */
193
int *error_limiter_storage; /* gdMalloc'd storage for the above */
194
int transparentIsPresent; /* TBB: for rescaling to ensure that */
195
int opaqueIsPresent; /* 100% opacity & transparency are preserved */
199
typedef my_cquantizer *my_cquantize_ptr;
202
* Prescan the pixel array.
204
* The prescan simply updates the histogram, which has been
205
* initialized to zeroes by start_pass.
210
prescan_quantize (gdImagePtr im, my_cquantize_ptr cquantize)
212
register histptr histp;
213
register hist4d histogram = cquantize->histogram;
219
for (row = 0; row < im->sy; row++)
221
ptr = im->tpixels[row];
222
for (col = width; col > 0; col--)
224
/* get pixel value and index into the histogram */
226
r = gdTrueColorGetRed (*ptr) >> C0_SHIFT;
227
g = gdTrueColorGetGreen (*ptr) >> C1_SHIFT;
228
b = gdTrueColorGetBlue (*ptr) >> C2_SHIFT;
229
a = gdTrueColorGetAlpha (*ptr);
230
/* We must have 100% opacity and transparency available
231
in the color map to do an acceptable job with alpha
232
channel, if opacity and transparency are present in the
233
original, because of the visual properties of large
234
flat-color border areas (requiring 100% transparency)
235
and the behavior of poorly implemented browsers
236
(requiring 100% opacity). Test for the presence of
237
these here, and rescale the most opaque and transparent
238
palette entries at the end if so. This avoids the need
239
to develop a fuller understanding I have not been able
240
to reach so far in my study of this subject. TBB */
241
if (a == gdAlphaTransparent)
243
cquantize->transparentIsPresent = 1;
245
if (a == gdAlphaOpaque)
247
cquantize->opaqueIsPresent = 1;
250
histp = &histogram[r][g][b][a];
251
/* increment, check for overflow and undo increment if so. */
261
* Next we have the really interesting routines: selection of a colormap
262
* given the completed histogram.
263
* These routines work with a list of "boxes", each representing a rectangular
264
* subset of the input color space (to histogram precision).
269
/* The bounds of the box (inclusive); expressed as histogram indexes */
274
/* The volume (actually 2-norm) of the box */
276
/* The number of nonzero histogram cells within this box */
284
find_biggest_color_pop (boxptr boxlist, int numboxes)
285
/* Find the splittable box with the largest color population */
286
/* Returns NULL if no splittable boxes remain */
288
register boxptr boxp;
290
register long maxc = 0;
293
for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++)
295
if (boxp->colorcount > maxc && boxp->volume > 0)
298
maxc = boxp->colorcount;
306
find_biggest_volume (boxptr boxlist, int numboxes)
307
/* Find the splittable box with the largest (scaled) volume */
308
/* Returns NULL if no splittable boxes remain */
310
register boxptr boxp;
312
register int maxv = 0;
315
for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++)
317
if (boxp->volume > maxv)
328
update_box (gdImagePtr im, my_cquantize_ptr cquantize, boxptr boxp)
329
/* Shrink the min/max bounds of a box to enclose only nonzero elements, */
330
/* and recompute its volume and population */
332
hist4d histogram = cquantize->histogram;
335
int c0min, c0max, c1min, c1max, c2min, c2max, c3min, c3max;
336
int dist0, dist1, dist2, dist3;
350
for (c0 = c0min; c0 <= c0max; c0++)
352
for (c1 = c1min; c1 <= c1max; c1++)
354
for (c2 = c2min; c2 <= c2max; c2++)
356
histp = &histogram[c0][c1][c2][c3min];
357
for (c3 = c3min; c3 <= c3max; c3++)
361
boxp->c0min = c0min = c0;
372
for (c0 = c0max; c0 >= c0min; c0--)
374
for (c1 = c1min; c1 <= c1max; c1++)
376
for (c2 = c2min; c2 <= c2max; c2++)
378
histp = &histogram[c0][c1][c2][c3min];
379
for (c3 = c3min; c3 <= c3max; c3++)
383
boxp->c0max = c0max = c0;
393
for (c1 = c1min; c1 <= c1max; c1++)
394
for (c0 = c0min; c0 <= c0max; c0++)
396
for (c2 = c2min; c2 <= c2max; c2++)
398
histp = &histogram[c0][c1][c2][c3min];
399
for (c3 = c3min; c3 <= c3max; c3++)
402
boxp->c1min = c1min = c1;
409
for (c1 = c1max; c1 >= c1min; c1--)
410
for (c0 = c0min; c0 <= c0max; c0++)
412
for (c2 = c2min; c2 <= c2max; c2++)
414
histp = &histogram[c0][c1][c2][c3min];
415
for (c3 = c3min; c3 <= c3max; c3++)
418
boxp->c1max = c1max = c1;
424
/* The original version hand-rolled the array lookup a little, but
425
with four dimensions, I don't even want to think about it. TBB */
427
for (c2 = c2min; c2 <= c2max; c2++)
428
for (c0 = c0min; c0 <= c0max; c0++)
429
for (c1 = c1min; c1 <= c1max; c1++)
430
for (c3 = c3min; c3 <= c3max; c3++)
431
if (histogram[c0][c1][c2][c3] != 0)
433
boxp->c2min = c2min = c2;
438
for (c2 = c2max; c2 >= c2min; c2--)
439
for (c0 = c0min; c0 <= c0max; c0++)
440
for (c1 = c1min; c1 <= c1max; c1++)
441
for (c3 = c3min; c3 <= c3max; c3++)
442
if (histogram[c0][c1][c2][c3] != 0)
444
boxp->c2max = c2max = c2;
449
for (c3 = c3min; c3 <= c3max; c3++)
450
for (c0 = c0min; c0 <= c0max; c0++)
451
for (c1 = c1min; c1 <= c1max; c1++)
452
for (c2 = c2min; c2 <= c2max; c2++)
453
if (histogram[c0][c1][c2][c3] != 0)
455
boxp->c3min = c3min = c3;
460
for (c3 = c3max; c3 >= c3min; c3--)
461
for (c0 = c0min; c0 <= c0max; c0++)
462
for (c1 = c1min; c1 <= c1max; c1++)
463
for (c2 = c2min; c2 <= c2max; c2++)
464
if (histogram[c0][c1][c2][c3] != 0)
466
boxp->c3max = c3max = c3;
470
/* Update box volume.
471
* We use 2-norm rather than real volume here; this biases the method
472
* against making long narrow boxes, and it has the side benefit that
473
* a box is splittable iff norm > 0.
474
* Since the differences are expressed in histogram-cell units,
475
* we have to shift back to 8-bit units to get consistent distances;
476
* after which, we scale according to the selected distance scale factors.
477
* TBB: alpha shifts back to 7 bit units. That was accounted for in the
478
* alpha scale factor.
480
dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
481
dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
482
dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
483
dist3 = ((c3max - c3min) << C3_SHIFT) * C3_SCALE;
484
boxp->volume = dist0 * dist0 + dist1 * dist1 + dist2 * dist2 + dist3 * dist3;
486
/* Now scan remaining volume of box and compute population */
488
for (c0 = c0min; c0 <= c0max; c0++)
489
for (c1 = c1min; c1 <= c1max; c1++)
490
for (c2 = c2min; c2 <= c2max; c2++)
492
histp = &histogram[c0][c1][c2][c3min];
493
for (c3 = c3min; c3 <= c3max; c3++, histp++)
499
boxp->colorcount = ccount;
504
median_cut (gdImagePtr im, my_cquantize_ptr cquantize,
505
boxptr boxlist, int numboxes,
507
/* Repeatedly select and split the largest box until we have enough boxes */
510
int c0, c1, c2, c3, cmax;
511
register boxptr b1, b2;
513
while (numboxes < desired_colors)
515
/* Select box to split.
516
* Current algorithm: by population for first half, then by volume.
518
if (numboxes * 2 <= desired_colors)
520
b1 = find_biggest_color_pop (boxlist, numboxes);
524
b1 = find_biggest_volume (boxlist, numboxes);
526
if (b1 == NULL) /* no splittable boxes left! */
528
b2 = &boxlist[numboxes]; /* where new box will go */
529
/* Copy the color bounds to the new box. */
530
b2->c0max = b1->c0max;
531
b2->c1max = b1->c1max;
532
b2->c2max = b1->c2max;
533
b2->c3max = b1->c3max;
534
b2->c0min = b1->c0min;
535
b2->c1min = b1->c1min;
536
b2->c2min = b1->c2min;
537
b2->c3min = b1->c3min;
538
/* Choose which axis to split the box on.
539
* Current algorithm: longest scaled axis.
540
* See notes in update_box about scaling distances.
542
c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
543
c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
544
c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
545
c3 = ((b1->c3max - b1->c3min) << C3_SHIFT) * C3_SCALE;
546
/* We want to break any ties in favor of green, then red, then blue,
564
/* Choose split point along selected axis, and update box bounds.
565
* Current algorithm: split at halfway point.
566
* (Since the box has been shrunk to minimum volume,
567
* any split will produce two nonempty subboxes.)
568
* Note that lb value is max for lower box, so must be < old max.
573
lb = (b1->c0max + b1->c0min) / 2;
578
lb = (b1->c1max + b1->c1min) / 2;
583
lb = (b1->c2max + b1->c2min) / 2;
588
lb = (b1->c3max + b1->c3min) / 2;
593
/* Update stats for boxes */
594
update_box (im, cquantize, b1);
595
update_box (im, cquantize, b2);
603
compute_color (gdImagePtr im, my_cquantize_ptr cquantize,
604
boxptr boxp, int icolor)
606
Compute representative color for a box, put it in
607
palette index icolor */
609
/* Current algorithm: mean weighted by pixels (not colors) */
610
/* Note it is important to get the rounding correct! */
611
hist4d histogram = cquantize->histogram;
614
int c0min, c0max, c1min, c1max, c2min, c2max, c3min, c3max;
631
for (c0 = c0min; c0 <= c0max; c0++)
633
for (c1 = c1min; c1 <= c1max; c1++)
635
for (c2 = c2min; c2 <= c2max; c2++)
637
histp = &histogram[c0][c1][c2][c3min];
638
for (c3 = c3min; c3 <= c3max; c3++)
640
if ((count = *histp++) != 0)
643
c0total += ((c0 << C0_SHIFT) + ((1 << C0_SHIFT) >> 1)) * count;
644
c1total += ((c1 << C1_SHIFT) + ((1 << C1_SHIFT) >> 1)) * count;
645
c2total += ((c2 << C2_SHIFT) + ((1 << C2_SHIFT) >> 1)) * count;
646
c3total += ((c3 << C3_SHIFT) + ((1 << C3_SHIFT) >> 1)) * count;
652
im->red[icolor] = (int) ((c0total + (total >> 1)) / total);
653
im->green[icolor] = (int) ((c1total + (total >> 1)) / total);
654
im->blue[icolor] = (int) ((c2total + (total >> 1)) / total);
655
im->alpha[icolor] = (int) ((c3total + (total >> 1)) / total);
656
im->open[icolor] = 0;
657
if (im->colorsTotal <= icolor)
659
im->colorsTotal = icolor + 1;
664
select_colors (gdImagePtr im, my_cquantize_ptr cquantize, int desired_colors)
665
/* Master routine for color selection */
671
/* Allocate workspace for box list */
672
boxlist = (boxptr) gdMalloc (desired_colors * sizeof (box));
673
/* Initialize one box containing whole space */
675
/* Note maxval for alpha is different */
676
boxlist[0].c0min = 0;
677
boxlist[0].c0max = 255 >> C0_SHIFT;
678
boxlist[0].c1min = 0;
679
boxlist[0].c1max = 255 >> C1_SHIFT;
680
boxlist[0].c2min = 0;
681
boxlist[0].c2max = 255 >> C2_SHIFT;
682
boxlist[0].c3min = 0;
683
boxlist[0].c3max = gdAlphaMax >> C3_SHIFT;
684
/* Shrink it to actually-used volume and set its statistics */
685
update_box (im, cquantize, &boxlist[0]);
686
/* Perform median-cut to produce final box list */
687
numboxes = median_cut (im, cquantize, boxlist, numboxes, desired_colors);
688
/* Compute the representative color for each box, fill colormap */
689
for (i = 0; i < numboxes; i++)
690
compute_color (im, cquantize, &boxlist[i], i);
691
/* TBB: if the image contains colors at both scaled ends
692
of the alpha range, rescale slightly to make sure alpha
693
covers the full spectrum from 100% transparent to 100%
694
opaque. Even a faint distinct background color is
695
generally considered failure with regard to alpha. */
697
im->colorsTotal = numboxes;
703
* These routines are concerned with the time-critical task of mapping input
704
* colors to the nearest color in the selected colormap.
706
* We re-use the histogram space as an "inverse color map", essentially a
707
* cache for the results of nearest-color searches. All colors within a
708
* histogram cell will be mapped to the same colormap entry, namely the one
709
* closest to the cell's center. This may not be quite the closest entry to
710
* the actual input color, but it's almost as good. A zero in the cache
711
* indicates we haven't found the nearest color for that cell yet; the array
712
* is cleared to zeroes before starting the mapping pass. When we find the
713
* nearest color for a cell, its colormap index plus one is recorded in the
714
* cache for future use. The pass2 scanning routines call fill_inverse_cmap
715
* when they need to use an unfilled entry in the cache.
717
* Our method of efficiently finding nearest colors is based on the "locally
718
* sorted search" idea described by Heckbert and on the incremental distance
719
* calculation described by Spencer W. Thomas in chapter III.1 of Graphics
720
* Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
721
* the distances from a given colormap entry to each cell of the histogram can
722
* be computed quickly using an incremental method: the differences between
723
* distances to adjacent cells themselves differ by a constant. This allows a
724
* fairly fast implementation of the "brute force" approach of computing the
725
* distance from every colormap entry to every histogram cell. Unfortunately,
726
* it needs a work array to hold the best-distance-so-far for each histogram
727
* cell (because the inner loop has to be over cells, not colormap entries).
728
* The work array elements have to be INT32s, so the work array would need
729
* 256Kb at our recommended precision. This is not feasible in DOS machines.
731
* To get around these problems, we apply Thomas' method to compute the
732
* nearest colors for only the cells within a small subbox of the histogram.
733
* The work array need be only as big as the subbox, so the memory usage
734
* problem is solved. Furthermore, we need not fill subboxes that are never
735
* referenced in pass2; many images use only part of the color gamut, so a
736
* fair amount of work is saved. An additional advantage of this
737
* approach is that we can apply Heckbert's locality criterion to quickly
738
* eliminate colormap entries that are far away from the subbox; typically
739
* three-fourths of the colormap entries are rejected by Heckbert's criterion,
740
* and we need not compute their distances to individual cells in the subbox.
741
* The speed of this approach is heavily influenced by the subbox size: too
742
* small means too much overhead, too big loses because Heckbert's criterion
743
* can't eliminate as many colormap entries. Empirically the best subbox
744
* size seems to be about 1/512th of the histogram (1/8th in each direction).
746
* Thomas' article also describes a refined method which is asymptotically
747
* faster than the brute-force method, but it is also far more complex and
748
* cannot efficiently be applied to small subboxes. It is therefore not
749
* useful for programs intended to be portable to DOS machines. On machines
750
* with plenty of memory, filling the whole histogram in one shot with Thomas'
751
* refined method might be faster than the present code --- but then again,
752
* it might not be any faster, and it's certainly more complicated.
756
/* log2(histogram cells in update box) for each axis; this can be adjusted */
757
#define BOX_C0_LOG (HIST_C0_BITS-3)
758
#define BOX_C1_LOG (HIST_C1_BITS-3)
759
#define BOX_C2_LOG (HIST_C2_BITS-3)
760
#define BOX_C3_LOG (HIST_C3_BITS-3)
762
#define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
763
#define BOX_C1_ELEMS (1<<BOX_C1_LOG)
764
#define BOX_C2_ELEMS (1<<BOX_C2_LOG)
765
#define BOX_C3_ELEMS (1<<BOX_C3_LOG)
767
#define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
768
#define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
769
#define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
770
#define BOX_C3_SHIFT (C3_SHIFT + BOX_C3_LOG)
774
* The next three routines implement inverse colormap filling. They could
775
* all be folded into one big routine, but splitting them up this way saves
776
* some stack space (the mindist[] and bestdist[] arrays need not coexist)
777
* and may allow some compilers to produce better code by registerizing more
778
* inner-loop variables.
782
find_nearby_colors (gdImagePtr im, my_cquantize_ptr cquantize,
783
int minc0, int minc1, int minc2, int minc3, int colorlist[])
784
/* Locate the colormap entries close enough to an update box to be candidates
785
* for the nearest entry to some cell(s) in the update box. The update box
786
* is specified by the center coordinates of its first cell. The number of
787
* candidate colormap entries is returned, and their colormap indexes are
788
* placed in colorlist[].
789
* This routine uses Heckbert's "locally sorted search" criterion to select
790
* the colors that need further consideration.
793
int numcolors = im->colorsTotal;
794
int maxc0, maxc1, maxc2, maxc3;
795
int centerc0, centerc1, centerc2, centerc3;
797
int minmaxdist, min_dist, max_dist, tdist;
798
int mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
800
/* Compute true coordinates of update box's upper corner and center.
801
* Actually we compute the coordinates of the center of the upper-corner
802
* histogram cell, which are the upper bounds of the volume we care about.
803
* Note that since ">>" rounds down, the "center" values may be closer to
804
* min than to max; hence comparisons to them must be "<=", not "<".
806
maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
807
centerc0 = (minc0 + maxc0) >> 1;
808
maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
809
centerc1 = (minc1 + maxc1) >> 1;
810
maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
811
centerc2 = (minc2 + maxc2) >> 1;
812
maxc3 = minc3 + ((1 << BOX_C3_SHIFT) - (1 << C3_SHIFT));
813
centerc3 = (minc3 + maxc3) >> 1;
815
/* For each color in colormap, find:
816
* 1. its minimum squared-distance to any point in the update box
817
* (zero if color is within update box);
818
* 2. its maximum squared-distance to any point in the update box.
819
* Both of these can be found by considering only the corners of the box.
820
* We save the minimum distance for each color in mindist[];
821
* only the smallest maximum distance is of interest.
823
minmaxdist = 0x7FFFFFFFL;
825
for (i = 0; i < numcolors; i++)
827
/* We compute the squared-c0-distance term, then add in the other three. */
831
tdist = (x - minc0) * C0_SCALE;
832
min_dist = tdist * tdist;
833
tdist = (x - maxc0) * C0_SCALE;
834
max_dist = tdist * tdist;
838
tdist = (x - maxc0) * C0_SCALE;
839
min_dist = tdist * tdist;
840
tdist = (x - minc0) * C0_SCALE;
841
max_dist = tdist * tdist;
845
/* within cell range so no contribution to min_dist */
849
tdist = (x - maxc0) * C0_SCALE;
850
max_dist = tdist * tdist;
854
tdist = (x - minc0) * C0_SCALE;
855
max_dist = tdist * tdist;
862
tdist = (x - minc1) * C1_SCALE;
863
min_dist += tdist * tdist;
864
tdist = (x - maxc1) * C1_SCALE;
865
max_dist += tdist * tdist;
869
tdist = (x - maxc1) * C1_SCALE;
870
min_dist += tdist * tdist;
871
tdist = (x - minc1) * C1_SCALE;
872
max_dist += tdist * tdist;
876
/* within cell range so no contribution to min_dist */
879
tdist = (x - maxc1) * C1_SCALE;
880
max_dist += tdist * tdist;
884
tdist = (x - minc1) * C1_SCALE;
885
max_dist += tdist * tdist;
892
tdist = (x - minc2) * C2_SCALE;
893
min_dist += tdist * tdist;
894
tdist = (x - maxc2) * C2_SCALE;
895
max_dist += tdist * tdist;
899
tdist = (x - maxc2) * C2_SCALE;
900
min_dist += tdist * tdist;
901
tdist = (x - minc2) * C2_SCALE;
902
max_dist += tdist * tdist;
906
/* within cell range so no contribution to min_dist */
909
tdist = (x - maxc2) * C2_SCALE;
910
max_dist += tdist * tdist;
914
tdist = (x - minc2) * C2_SCALE;
915
max_dist += tdist * tdist;
922
tdist = (x - minc3) * C3_SCALE;
923
min_dist += tdist * tdist;
924
tdist = (x - maxc3) * C3_SCALE;
925
max_dist += tdist * tdist;
929
tdist = (x - maxc3) * C3_SCALE;
930
min_dist += tdist * tdist;
931
tdist = (x - minc3) * C3_SCALE;
932
max_dist += tdist * tdist;
936
/* within cell range so no contribution to min_dist */
939
tdist = (x - maxc3) * C3_SCALE;
940
max_dist += tdist * tdist;
944
tdist = (x - minc3) * C3_SCALE;
945
max_dist += tdist * tdist;
949
mindist[i] = min_dist; /* save away the results */
950
if (max_dist < minmaxdist)
951
minmaxdist = max_dist;
954
/* Now we know that no cell in the update box is more than minmaxdist
955
* away from some colormap entry. Therefore, only colors that are
956
* within minmaxdist of some part of the box need be considered.
959
for (i = 0; i < numcolors; i++)
961
if (mindist[i] <= minmaxdist)
962
colorlist[ncolors++] = i;
969
find_best_colors (gdImagePtr im, my_cquantize_ptr cquantize,
970
int minc0, int minc1, int minc2, int minc3,
971
int numcolors, int colorlist[], int bestcolor[])
972
/* Find the closest colormap entry for each cell in the update box,
973
* given the list of candidate colors prepared by find_nearby_colors.
974
* Return the indexes of the closest entries in the bestcolor[] array.
975
* This routine uses Thomas' incremental distance calculation method to
976
* find the distance from a colormap entry to successive cells in the box.
979
int ic0, ic1, ic2, ic3;
981
register int *bptr; /* pointer into bestdist[] array */
982
int *cptr; /* pointer into bestcolor[] array */
983
int dist0, dist1, dist2; /* initial distance values */
984
register int dist3; /* current distance in inner loop */
985
int xx0, xx1, xx2; /* distance increments */
987
int inc0, inc1, inc2, inc3; /* initial values for increments */
988
/* This array holds the distance to the nearest-so-far color for each cell */
989
int bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS * BOX_C3_ELEMS];
991
/* Initialize best-distance for each cell of the update box */
993
for (i = BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS * BOX_C3_ELEMS - 1; i >= 0; i--)
994
*bptr++ = 0x7FFFFFFFL;
996
/* For each color selected by find_nearby_colors,
997
* compute its distance to the center of each cell in the box.
998
* If that's less than best-so-far, update best distance and color number.
1001
/* Nominal steps between cell centers ("x" in Thomas article) */
1002
#define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
1003
#define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
1004
#define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
1005
#define STEP_C3 ((1 << C3_SHIFT) * C3_SCALE)
1007
for (i = 0; i < numcolors; i++)
1009
icolor = colorlist[i];
1010
/* Compute (square of) distance from minc0/c1/c2 to this color */
1011
inc0 = (minc0 - (im->red[icolor])) * C0_SCALE;
1012
dist0 = inc0 * inc0;
1013
inc1 = (minc1 - (im->green[icolor])) * C1_SCALE;
1014
dist0 += inc1 * inc1;
1015
inc2 = (minc2 - (im->blue[icolor])) * C2_SCALE;
1016
dist0 += inc2 * inc2;
1017
inc3 = (minc3 - (im->alpha[icolor])) * C3_SCALE;
1018
dist0 += inc3 * inc3;
1019
/* Form the initial difference increments */
1020
inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
1021
inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
1022
inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
1023
inc3 = inc3 * (2 * STEP_C3) + STEP_C3 * STEP_C3;
1024
/* Now loop over all cells in box, updating distance per Thomas method */
1028
for (ic0 = BOX_C0_ELEMS - 1; ic0 >= 0; ic0--)
1032
for (ic1 = BOX_C1_ELEMS - 1; ic1 >= 0; ic1--)
1036
for (ic2 = BOX_C2_ELEMS - 1; ic2 >= 0; ic2--)
1038
for (ic3 = BOX_C3_ELEMS - 1; ic3 >= 0; ic3--)
1046
xx3 += 2 * STEP_C3 * STEP_C3;
1051
xx2 += 2 * STEP_C2 * STEP_C2;
1054
xx1 += 2 * STEP_C1 * STEP_C1;
1057
xx0 += 2 * STEP_C0 * STEP_C0;
1064
fill_inverse_cmap (gdImagePtr im, my_cquantize_ptr cquantize,
1065
int c0, int c1, int c2, int c3)
1066
/* Fill the inverse-colormap entries in the update box that contains */
1067
/* histogram cell c0/c1/c2/c3. (Only that one cell MUST be filled, but */
1068
/* we can fill as many others as we wish.) */
1070
hist4d histogram = cquantize->histogram;
1071
int minc0, minc1, minc2, minc3; /* lower left corner of update box */
1072
int ic0, ic1, ic2, ic3;
1073
register int *cptr; /* pointer into bestcolor[] array */
1074
register histptr cachep; /* pointer into main cache array */
1075
/* This array lists the candidate colormap indexes. */
1076
int colorlist[MAXNUMCOLORS];
1077
int numcolors; /* number of candidate colors */
1078
/* This array holds the actually closest colormap index for each cell. */
1079
int bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS * BOX_C3_ELEMS];
1081
/* Convert cell coordinates to update box ID */
1087
/* Compute true coordinates of update box's origin corner.
1088
* Actually we compute the coordinates of the center of the corner
1089
* histogram cell, which are the lower bounds of the volume we care about.
1091
minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
1092
minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
1093
minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
1094
minc3 = (c3 << BOX_C3_SHIFT) + ((1 << C3_SHIFT) >> 1);
1095
/* Determine which colormap entries are close enough to be candidates
1096
* for the nearest entry to some cell in the update box.
1098
numcolors = find_nearby_colors (im, cquantize, minc0, minc1, minc2, minc3, colorlist);
1100
/* Determine the actually nearest colors. */
1101
find_best_colors (im, cquantize, minc0, minc1, minc2, minc3, numcolors, colorlist,
1104
/* Save the best color numbers (plus 1) in the main cache array */
1105
c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
1110
for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++)
1112
for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++)
1114
for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++)
1116
cachep = &histogram[c0 + ic0][c1 + ic1][c2 + ic2][c3];
1117
for (ic3 = 0; ic3 < BOX_C3_ELEMS; ic3++)
1119
*cachep++ = (histcell) ((*cptr++) + 1);
1128
* Map some rows of pixels to the output colormapped representation.
1132
pass2_no_dither (gdImagePtr im, my_cquantize_ptr cquantize)
1133
/* This version performs no dithering */
1135
hist4d histogram = cquantize->histogram;
1136
register int *inptr;
1137
register unsigned char *outptr;
1138
register histptr cachep;
1139
register int c0, c1, c2, c3;
1143
int num_rows = im->sy;
1144
for (row = 0; row < num_rows; row++)
1146
inptr = im->tpixels[row];
1147
outptr = im->pixels[row];
1148
for (col = 0; col < width; col++)
1151
/* get pixel value and index into the cache */
1152
r = gdTrueColorGetRed (*inptr);
1153
g = gdTrueColorGetGreen (*inptr);
1154
b = gdTrueColorGetBlue (*inptr);
1155
a = gdTrueColorGetAlpha (*inptr++);
1160
cachep = &histogram[c0][c1][c2][c3];
1161
/* If we have not seen this color before, find nearest colormap entry */
1162
/* and update the cache */
1166
/* TBB: quick and dirty approach for use when testing
1167
fill_inverse_cmap for errors */
1170
int mindist = 0x7FFFFFFF;
1171
for (i = 0; (i < im->colorsTotal); i++)
1173
int rdist = (im->red[i] >> C0_SHIFT) - c0;
1174
int gdist = (im->green[i] >> C1_SHIFT) - c1;
1175
int bdist = (im->blue[i] >> C2_SHIFT) - c2;
1176
int adist = (im->alpha[i] >> C3_SHIFT) - c3;
1177
int dist = (rdist * rdist) * R_SCALE +
1178
(gdist * gdist) * G_SCALE +
1179
(bdist * bdist) * B_SCALE +
1180
(adist * adist) * A_SCALE;
1189
fill_inverse_cmap (im, cquantize, c0, c1, c2, c3);
1191
/* Now emit the colormap index for this cell */
1192
*outptr++ = (*cachep - 1);
1197
/* We assume that right shift corresponds to signed division by 2 with
1198
* rounding towards minus infinity. This is correct for typical "arithmetic
1199
* shift" instructions that shift in copies of the sign bit. But some
1200
* C compilers implement >> with an unsigned shift. For these machines you
1201
* must define RIGHT_SHIFT_IS_UNSIGNED.
1202
* RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
1203
* It is only applied with constant shift counts. SHIFT_TEMPS must be
1204
* included in the variables of any routine using RIGHT_SHIFT.
1207
#ifdef RIGHT_SHIFT_IS_UNSIGNED
1208
#define SHIFT_TEMPS INT32 shift_temp;
1209
#define RIGHT_SHIFT(x,shft) \
1210
((shift_temp = (x)) < 0 ? \
1211
(shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
1212
(shift_temp >> (shft)))
1215
#define RIGHT_SHIFT(x,shft) ((x) >> (shft))
1220
pass2_fs_dither (gdImagePtr im, my_cquantize_ptr cquantize)
1222
/* This version performs Floyd-Steinberg dithering */
1224
hist4d histogram = cquantize->histogram;
1225
register LOCFSERROR cur0, cur1, cur2, cur3; /* current error or pixel value */
1226
LOCFSERROR belowerr0, belowerr1, belowerr2, belowerr3; /* error for pixel below cur */
1227
LOCFSERROR bpreverr0, bpreverr1, bpreverr2, bpreverr3; /* error for below/prev col */
1228
register FSERRPTR errorptr; /* => fserrors[] at column before current */
1229
int *inptr; /* => current input pixel */
1230
unsigned char *outptr; /* => current output pixel */
1232
int dir; /* +1 or -1 depending on direction */
1233
int dir4; /* 4*dir, for advancing errorptr */
1237
int num_rows = im->sy;
1238
int *error_limit = cquantize->error_limiter;
1239
int *colormap0 = im->red;
1240
int *colormap1 = im->green;
1241
int *colormap2 = im->blue;
1242
int *colormap3 = im->alpha;
1245
for (row = 0; row < num_rows; row++)
1247
inptr = im->tpixels[row];
1248
outptr = im->pixels[row];
1249
if (cquantize->on_odd_row)
1251
/* work right to left in this row */
1252
inptr += (width - 1); /* so point to rightmost pixel */
1253
outptr += width - 1;
1256
errorptr = cquantize->fserrors + (width + 1) * 4; /* => entry after last column */
1257
cquantize->on_odd_row = FALSE; /* flip for next time */
1261
/* work left to right in this row */
1264
errorptr = cquantize->fserrors; /* => entry before first real column */
1265
cquantize->on_odd_row = TRUE; /* flip for next time */
1267
/* Preset error values: no error propagated to first pixel from left */
1268
cur0 = cur1 = cur2 = cur3 = 0;
1269
/* and no error propagated to row below yet */
1270
belowerr0 = belowerr1 = belowerr2 = belowerr3 = 0;
1271
bpreverr0 = bpreverr1 = bpreverr2 = bpreverr3 = 0;
1273
for (col = width; col > 0; col--)
1276
/* curN holds the error propagated from the previous pixel on the
1277
* current line. Add the error propagated from the previous line
1278
* to form the complete error correction term for this pixel, and
1279
* round the error term (which is expressed * 16) to an integer.
1280
* RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
1281
* for either sign of the error value.
1282
* Note: errorptr points to *previous* column's array entry.
1284
cur0 = RIGHT_SHIFT (cur0 + errorptr[dir4 + 0] + 8, 4);
1285
cur1 = RIGHT_SHIFT (cur1 + errorptr[dir4 + 1] + 8, 4);
1286
cur2 = RIGHT_SHIFT (cur2 + errorptr[dir4 + 2] + 8, 4);
1287
cur3 = RIGHT_SHIFT (cur3 + errorptr[dir4 + 3] + 8, 4);
1288
/* Limit the error using transfer function set by init_error_limit.
1289
* See comments with init_error_limit for rationale.
1291
cur0 = error_limit[cur0];
1292
cur1 = error_limit[cur1];
1293
cur2 = error_limit[cur2];
1294
cur3 = error_limit[cur3];
1295
/* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
1296
* The maximum error is +- MAXJSAMPLE (or less with error limiting);
1297
* but we'll be lazy and just clamp this with an if test (TBB).
1299
cur0 += gdTrueColorGetRed (*inptr);
1300
cur1 += gdTrueColorGetGreen (*inptr);
1301
cur2 += gdTrueColorGetBlue (*inptr);
1302
/* Expand to 8 bits for consistency with dithering algorithm -- TBB */
1303
a = gdTrueColorGetAlpha (*inptr);
1304
cur3 += (a << 1) + (a >> 6);
1337
/* Index into the cache with adjusted pixel value */
1342
[cur3 >> (C3_SHIFT + 1)];
1343
/* If we have not seen this color before, find nearest colormap */
1344
/* entry and update the cache */
1346
fill_inverse_cmap (im, cquantize,
1347
cur0 >> C0_SHIFT, cur1 >> C1_SHIFT, cur2 >> C2_SHIFT,
1348
cur3 >> (C3_SHIFT + 1));
1349
/* Now emit the colormap index for this cell */
1351
register int pixcode = *cachep - 1;
1353
/* Compute representation error for this pixel */
1354
cur0 -= colormap0[pixcode];
1355
cur1 -= colormap1[pixcode];
1356
cur2 -= colormap2[pixcode];
1357
cur3 -= ((colormap3[pixcode] << 1) + (colormap3[pixcode] >> 6));
1359
/* Compute error fractions to be propagated to adjacent pixels.
1360
* Add these into the running sums, and simultaneously shift the
1361
* next-line error sums left by 1 column.
1364
register LOCFSERROR bnexterr, delta;
1366
bnexterr = cur0; /* Process component 0 */
1368
cur0 += delta; /* form error * 3 */
1369
errorptr[0] = (FSERROR) (bpreverr0 + cur0);
1370
cur0 += delta; /* form error * 5 */
1371
bpreverr0 = belowerr0 + cur0;
1372
belowerr0 = bnexterr;
1373
cur0 += delta; /* form error * 7 */
1374
bnexterr = cur1; /* Process component 1 */
1376
cur1 += delta; /* form error * 3 */
1377
errorptr[1] = (FSERROR) (bpreverr1 + cur1);
1378
cur1 += delta; /* form error * 5 */
1379
bpreverr1 = belowerr1 + cur1;
1380
belowerr1 = bnexterr;
1381
cur1 += delta; /* form error * 7 */
1382
bnexterr = cur2; /* Process component 2 */
1384
cur2 += delta; /* form error * 3 */
1385
errorptr[2] = (FSERROR) (bpreverr2 + cur2);
1386
cur2 += delta; /* form error * 5 */
1387
bpreverr2 = belowerr2 + cur2;
1388
belowerr2 = bnexterr;
1389
cur2 += delta; /* form error * 7 */
1390
bnexterr = cur3; /* Process component 3 */
1392
cur3 += delta; /* form error * 3 */
1393
errorptr[3] = (FSERROR) (bpreverr3 + cur3);
1394
cur3 += delta; /* form error * 5 */
1395
bpreverr3 = belowerr3 + cur3;
1396
belowerr3 = bnexterr;
1397
cur3 += delta; /* form error * 7 */
1399
/* At this point curN contains the 7/16 error value to be propagated
1400
* to the next pixel on the current line, and all the errors for the
1401
* next line have been shifted over. We are therefore ready to move on.
1403
inptr += dir; /* Advance pixel pointers to next column */
1405
errorptr += dir4; /* advance errorptr to current column */
1407
/* Post-loop cleanup: we must unload the final error values into the
1408
* final fserrors[] entry. Note we need not unload belowerrN because
1409
* it is for the dummy column before or after the actual array.
1411
errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
1412
errorptr[1] = (FSERROR) bpreverr1;
1413
errorptr[2] = (FSERROR) bpreverr2;
1414
errorptr[3] = (FSERROR) bpreverr3;
1420
* Initialize the error-limiting transfer function (lookup table).
1421
* The raw F-S error computation can potentially compute error values of up to
1422
* +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
1423
* much less, otherwise obviously wrong pixels will be created. (Typical
1424
* effects include weird fringes at color-area boundaries, isolated bright
1425
* pixels in a dark area, etc.) The standard advice for avoiding this problem
1426
* is to ensure that the "corners" of the color cube are allocated as output
1427
* colors; then repeated errors in the same direction cannot cause cascading
1428
* error buildup. However, that only prevents the error from getting
1429
* completely out of hand; Aaron Giles reports that error limiting improves
1430
* the results even with corner colors allocated.
1431
* A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
1432
* well, but the smoother transfer function used below is even better. Thanks
1433
* to Aaron Giles for this idea.
1437
init_error_limit (gdImagePtr im, my_cquantize_ptr cquantize)
1438
/* Allocate and fill in the error_limiter table */
1443
cquantize->error_limiter_storage = (int *) gdMalloc ((255 * 2 + 1) * sizeof (int));
1444
if (!cquantize->error_limiter_storage)
1448
/* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
1449
cquantize->error_limiter = cquantize->error_limiter_storage + 255;
1450
table = cquantize->error_limiter;
1451
#define STEPSIZE ((255+1)/16)
1452
/* Map errors 1:1 up to +- MAXJSAMPLE/16 */
1454
for (in = 0; in < STEPSIZE; in++, out++)
1459
/* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
1460
for (; in < STEPSIZE * 3; in++, out += (in & 1) ? 0 : 1)
1465
/* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
1466
for (; in <= 255; in++)
1476
zeroHistogram (hist4d histogram)
1480
/* Zero the histogram or inverse color map */
1481
for (i = 0; i < HIST_C0_ELEMS; i++)
1483
for (j = 0; j < HIST_C1_ELEMS; j++)
1485
memset (histogram[i][j],
1487
HIST_C2_ELEMS * HIST_C3_ELEMS * sizeof (histcell));
1492
/* Here we go at last. */
1494
gdImageTrueColorToPalette (gdImagePtr im, int dither, int colorsWanted)
1496
my_cquantize_ptr cquantize = 0;
1501
/* Nothing to do! */
1504
if (colorsWanted > gdMaxColors)
1506
colorsWanted = gdMaxColors;
1508
im->pixels = gdCalloc (sizeof (unsigned char *), im->sy);
1514
for (i = 0; (i < im->sy); i++)
1516
im->pixels[i] = gdCalloc (sizeof (unsigned char *), im->sx);
1522
cquantize = (my_cquantize_ptr) gdCalloc (sizeof (my_cquantizer), 1);
1528
/* Allocate the histogram/inverse colormap storage */
1529
cquantize->histogram = (hist4d) gdMalloc (HIST_C0_ELEMS * sizeof (hist3d));
1530
for (i = 0; i < HIST_C0_ELEMS; i++)
1533
cquantize->histogram[i] = (hist3d) gdCalloc (HIST_C1_ELEMS,
1535
if (!cquantize->histogram[i])
1539
for (j = 0; (j < HIST_C1_ELEMS); j++)
1541
cquantize->histogram[i][j] = (hist2d) gdCalloc (HIST_C2_ELEMS * HIST_C3_ELEMS,
1543
if (!cquantize->histogram[i][j])
1549
cquantize->fserrors = (FSERRPTR) gdMalloc (4 * sizeof (FSERROR));
1550
init_error_limit (im, cquantize);
1551
arraysize = (size_t) ((im->sx + 2) *
1552
(4 * sizeof (FSERROR)));
1553
/* Allocate Floyd-Steinberg workspace. */
1554
cquantize->fserrors = gdCalloc (arraysize, 1);
1555
if (!cquantize->fserrors)
1559
cquantize->on_odd_row = FALSE;
1562
zeroHistogram (cquantize->histogram);
1563
prescan_quantize (im, cquantize);
1564
select_colors (im, cquantize, 256);
1565
/* TBB HACK REMOVE */
1567
FILE *out = fopen ("palettemap.png", "wb");
1569
gdImagePtr im2 = gdImageCreateTrueColor (256, 256);
1570
for (i = 0; (i < 256); i++)
1572
gdImageFilledRectangle (im2, (i % 16) * 16, (i / 16) * 16,
1573
(i % 16) * 16 + 15, (i / 16) * 16 + 15,
1574
gdTrueColorAlpha (im->red[i], im->green[i],
1575
im->blue[i], im->alpha[i]));
1577
gdImagePng (im2, out);
1579
gdImageDestroy (im2);
1581
zeroHistogram (cquantize->histogram);
1584
pass2_fs_dither (im, cquantize);
1588
pass2_no_dither (im, cquantize);
1590
if (cquantize->transparentIsPresent)
1594
for (i = 0; (i < im->colorsTotal); i++)
1596
if (im->alpha[i] > mt)
1602
for (i = 0; (i < im->colorsTotal); i++)
1604
if (im->alpha[i] == mt)
1606
im->alpha[i] = gdAlphaTransparent;
1610
if (cquantize->opaqueIsPresent)
1614
for (i = 0; (i < im->colorsTotal); i++)
1616
if (im->alpha[i] < mo)
1622
for (i = 0; (i < im->colorsTotal); i++)
1624
if (im->alpha[i] == mo)
1626
im->alpha[i] = gdAlphaOpaque;
1630
/* Success! Get rid of the truecolor image data. */
1632
/* Junk the truecolor pixels */
1633
for (i = 0; i < im->sy; i++)
1635
gdFree (im->tpixels[i]);
1637
gdFree (im->tpixels);
1639
/* Tediously free stuff. */
1643
/* On failure only */
1644
for (i = 0; i < im->sy; i++)
1648
gdFree (im->pixels[i]);
1653
gdFree (im->pixels);
1657
for (i = 0; i < HIST_C0_ELEMS; i++)
1659
if (cquantize->histogram[i])
1662
for (j = 0; j < HIST_C1_ELEMS; j++)
1664
if (cquantize->histogram[i][j])
1666
gdFree (cquantize->histogram[i][j]);
1669
gdFree (cquantize->histogram[i]);
1672
if (cquantize->histogram)
1674
gdFree (cquantize->histogram);
1676
if (cquantize->fserrors)
1678
gdFree (cquantize->fserrors);
1680
if (cquantize->error_limiter_storage)
1682
gdFree (cquantize->error_limiter_storage);