~ubuntu-branches/ubuntu/lucid/graphviz/lucid-security

« back to all changes in this revision

Viewing changes to gd/gd_topal.c

  • Committer: Bazaar Package Importer
  • Author(s): Stephen M Moraco
  • Date: 2002-02-05 18:52:12 UTC
  • Revision ID: james.westby@ubuntu.com-20020205185212-8i04c70te00rc40y
Tags: upstream-1.7.16
ImportĀ upstreamĀ versionĀ 1.7.16

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
 
 
2
 
 
3
/*
 
4
 * gd_topal.c 
 
5
 * 
 
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.
 
11
 *
 
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.
 
16
 *
 
17
 * It is also possible to use just the second pass to map to an arbitrary
 
18
 * externally-given color map.
 
19
 *
 
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.
 
23
 *
 
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.
 
27
 */
 
28
 
 
29
#include "gd.h"
 
30
#include "gdhelpers.h"
 
31
 
 
32
/*
 
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.
 
38
 *
 
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.
 
44
 *
 
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.
 
49
 * 
 
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
 
53
 * considerable care.
 
54
 *
 
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
 
58
 * may yet be found.
 
59
 *
 
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.
 
68
 *
 
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 
 
74
 * equation. 
 
75
 */
 
76
 
 
77
#ifndef TRUE
 
78
#define TRUE 1
 
79
#endif /* TRUE */
 
80
 
 
81
#ifndef FALSE
 
82
#define FALSE 0
 
83
#endif /* FALSE */
 
84
 
 
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. */
 
91
 
 
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
 
97
 
 
98
/*
 
99
 * First we have the histogram data structure and routines for creating it.
 
100
 *
 
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).
 
122
 */
 
123
 
 
124
#define MAXNUMCOLORS  (gdMaxColors)     /* maximum size of colormap */
 
125
 
 
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 */
 
130
 
 
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)
 
136
 
 
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)
 
143
 
 
144
 
 
145
typedef unsigned short histcell;        /* histogram cell; prefer an unsigned type */
 
146
 
 
147
typedef histcell *histptr;      /* for pointers to histogram cells */
 
148
 
 
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 */
 
153
 
 
154
 
 
155
/* Declarations for Floyd-Steinberg dithering.
 
156
 
 
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,
 
160
 *              ...     (here)  7/16
 
161
 *              3/16    5/16    1/16
 
162
 * We work left-to-right on even rows, right-to-left on odd rows.
 
163
 *
 
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.)
 
170
 *
 
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.
 
174
 *
 
175
 */
 
176
 
 
177
typedef signed short FSERROR;   /* 16 bits should be enough */
 
178
typedef int LOCFSERROR;         /* use 'int' for calculation temps */
 
179
 
 
180
typedef FSERROR *FSERRPTR;      /* pointer to error array */
 
181
 
 
182
/* Private object */
 
183
 
 
184
typedef struct
 
185
  {
 
186
    hist4d histogram;           /* pointer to the histogram */
 
187
    int needs_zeroed;           /* TRUE if next pass must zero histogram */
 
188
 
 
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 */
 
196
  }
 
197
my_cquantizer;
 
198
 
 
199
typedef my_cquantizer *my_cquantize_ptr;
 
200
 
 
201
/*
 
202
 * Prescan the pixel array. 
 
203
 * 
 
204
 * The prescan simply updates the histogram, which has been
 
205
 * initialized to zeroes by start_pass.
 
206
 *
 
207
 */
 
208
 
 
209
static void
 
210
prescan_quantize (gdImagePtr im, my_cquantize_ptr cquantize)
 
211
{
 
212
  register histptr histp;
 
213
  register hist4d histogram = cquantize->histogram;
 
214
  int row;
 
215
  int col;
 
216
  int *ptr;
 
217
  int width = im->sx;
 
218
 
 
219
  for (row = 0; row < im->sy; row++)
 
220
    {
 
221
      ptr = im->tpixels[row];
 
222
      for (col = width; col > 0; col--)
 
223
        {
 
224
          /* get pixel value and index into the histogram */
 
225
          int r, g, b, a;
 
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)
 
242
            {
 
243
              cquantize->transparentIsPresent = 1;
 
244
            }
 
245
          if (a == gdAlphaOpaque)
 
246
            {
 
247
              cquantize->opaqueIsPresent = 1;
 
248
            }
 
249
          a >>= C3_SHIFT;
 
250
          histp = &histogram[r][g][b][a];
 
251
          /* increment, check for overflow and undo increment if so. */
 
252
          if (++(*histp) <= 0)
 
253
            (*histp)--;
 
254
          ptr++;
 
255
        }
 
256
    }
 
257
}
 
258
 
 
259
 
 
260
/*
 
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).
 
265
 */
 
266
 
 
267
typedef struct
 
268
{
 
269
  /* The bounds of the box (inclusive); expressed as histogram indexes */
 
270
  int c0min, c0max;
 
271
  int c1min, c1max;
 
272
  int c2min, c2max;
 
273
  int c3min, c3max;
 
274
  /* The volume (actually 2-norm) of the box */
 
275
  int volume;
 
276
  /* The number of nonzero histogram cells within this box */
 
277
  long colorcount;
 
278
}
 
279
box;
 
280
 
 
281
typedef box *boxptr;
 
282
 
 
283
static boxptr
 
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 */
 
287
{
 
288
  register boxptr boxp;
 
289
  register int i;
 
290
  register long maxc = 0;
 
291
  boxptr which = NULL;
 
292
 
 
293
  for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++)
 
294
    {
 
295
      if (boxp->colorcount > maxc && boxp->volume > 0)
 
296
        {
 
297
          which = boxp;
 
298
          maxc = boxp->colorcount;
 
299
        }
 
300
    }
 
301
  return which;
 
302
}
 
303
 
 
304
 
 
305
static boxptr
 
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 */
 
309
{
 
310
  register boxptr boxp;
 
311
  register int i;
 
312
  register int maxv = 0;
 
313
  boxptr which = NULL;
 
314
 
 
315
  for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++)
 
316
    {
 
317
      if (boxp->volume > maxv)
 
318
        {
 
319
          which = boxp;
 
320
          maxv = boxp->volume;
 
321
        }
 
322
    }
 
323
  return which;
 
324
}
 
325
 
 
326
 
 
327
static void
 
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 */
 
331
{
 
332
  hist4d histogram = cquantize->histogram;
 
333
  histptr histp;
 
334
  int c0, c1, c2, c3;
 
335
  int c0min, c0max, c1min, c1max, c2min, c2max, c3min, c3max;
 
336
  int dist0, dist1, dist2, dist3;
 
337
  long ccount;
 
338
 
 
339
  c0min = boxp->c0min;
 
340
  c0max = boxp->c0max;
 
341
  c1min = boxp->c1min;
 
342
  c1max = boxp->c1max;
 
343
  c2min = boxp->c2min;
 
344
  c2max = boxp->c2max;
 
345
  c3min = boxp->c3min;
 
346
  c3max = boxp->c3max;
 
347
 
 
348
  if (c0max > c0min)
 
349
    {
 
350
      for (c0 = c0min; c0 <= c0max; c0++)
 
351
        {
 
352
          for (c1 = c1min; c1 <= c1max; c1++)
 
353
            {
 
354
              for (c2 = c2min; c2 <= c2max; c2++)
 
355
                {
 
356
                  histp = &histogram[c0][c1][c2][c3min];
 
357
                  for (c3 = c3min; c3 <= c3max; c3++)
 
358
                    {
 
359
                      if (*histp++ != 0)
 
360
                        {
 
361
                          boxp->c0min = c0min = c0;
 
362
                          goto have_c0min;
 
363
                        }
 
364
                    }
 
365
                }
 
366
            }
 
367
        }
 
368
    }
 
369
have_c0min:
 
370
  if (c0max > c0min)
 
371
    {
 
372
      for (c0 = c0max; c0 >= c0min; c0--)
 
373
        {
 
374
          for (c1 = c1min; c1 <= c1max; c1++)
 
375
            {
 
376
              for (c2 = c2min; c2 <= c2max; c2++)
 
377
                {
 
378
                  histp = &histogram[c0][c1][c2][c3min];
 
379
                  for (c3 = c3min; c3 <= c3max; c3++)
 
380
                    {
 
381
                      if (*histp++ != 0)
 
382
                        {
 
383
                          boxp->c0max = c0max = c0;
 
384
                          goto have_c0max;
 
385
                        }
 
386
                    }
 
387
                }
 
388
            }
 
389
        }
 
390
    }
 
391
have_c0max:
 
392
  if (c1max > c1min)
 
393
    for (c1 = c1min; c1 <= c1max; c1++)
 
394
      for (c0 = c0min; c0 <= c0max; c0++)
 
395
        {
 
396
          for (c2 = c2min; c2 <= c2max; c2++)
 
397
            {
 
398
              histp = &histogram[c0][c1][c2][c3min];
 
399
              for (c3 = c3min; c3 <= c3max; c3++)
 
400
                if (*histp++ != 0)
 
401
                  {
 
402
                    boxp->c1min = c1min = c1;
 
403
                    goto have_c1min;
 
404
                  }
 
405
            }
 
406
        }
 
407
have_c1min:
 
408
  if (c1max > c1min)
 
409
    for (c1 = c1max; c1 >= c1min; c1--)
 
410
      for (c0 = c0min; c0 <= c0max; c0++)
 
411
        {
 
412
          for (c2 = c2min; c2 <= c2max; c2++)
 
413
            {
 
414
              histp = &histogram[c0][c1][c2][c3min];
 
415
              for (c3 = c3min; c3 <= c3max; c3++)
 
416
                if (*histp++ != 0)
 
417
                  {
 
418
                    boxp->c1max = c1max = c1;
 
419
                    goto have_c1max;
 
420
                  }
 
421
            }
 
422
        }
 
423
have_c1max:
 
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 */
 
426
  if (c2max > c2min)
 
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)
 
432
              {
 
433
                boxp->c2min = c2min = c2;
 
434
                goto have_c2min;
 
435
              }
 
436
have_c2min:
 
437
  if (c2max > c2min)
 
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)
 
443
              {
 
444
                boxp->c2max = c2max = c2;
 
445
                goto have_c2max;
 
446
              }
 
447
have_c2max:
 
448
  if (c3max > c3min)
 
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)
 
454
              {
 
455
                boxp->c3min = c3min = c3;
 
456
                goto have_c3min;
 
457
              }
 
458
have_c3min:
 
459
  if (c3max > c3min)
 
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)
 
465
              {
 
466
                boxp->c3max = c3max = c3;
 
467
                goto have_c3max;
 
468
              }
 
469
have_c3max:
 
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. 
 
479
   */
 
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;
 
485
 
 
486
  /* Now scan remaining volume of box and compute population */
 
487
  ccount = 0;
 
488
  for (c0 = c0min; c0 <= c0max; c0++)
 
489
    for (c1 = c1min; c1 <= c1max; c1++)
 
490
      for (c2 = c2min; c2 <= c2max; c2++)
 
491
        {
 
492
          histp = &histogram[c0][c1][c2][c3min];
 
493
          for (c3 = c3min; c3 <= c3max; c3++, histp++)
 
494
            if (*histp != 0)
 
495
              {
 
496
                ccount++;
 
497
              }
 
498
        }
 
499
  boxp->colorcount = ccount;
 
500
}
 
501
 
 
502
 
 
503
static int
 
504
median_cut (gdImagePtr im, my_cquantize_ptr cquantize,
 
505
            boxptr boxlist, int numboxes,
 
506
            int desired_colors)
 
507
/* Repeatedly select and split the largest box until we have enough boxes */
 
508
{
 
509
  int n, lb;
 
510
  int c0, c1, c2, c3, cmax;
 
511
  register boxptr b1, b2;
 
512
 
 
513
  while (numboxes < desired_colors)
 
514
    {
 
515
      /* Select box to split.
 
516
       * Current algorithm: by population for first half, then by volume.
 
517
       */
 
518
      if (numboxes * 2 <= desired_colors)
 
519
        {
 
520
          b1 = find_biggest_color_pop (boxlist, numboxes);
 
521
        }
 
522
      else
 
523
        {
 
524
          b1 = find_biggest_volume (boxlist, numboxes);
 
525
        }
 
526
      if (b1 == NULL)           /* no splittable boxes left! */
 
527
        break;
 
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.
 
541
       */
 
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, 
 
547
         with alpha last. */
 
548
      cmax = c1;
 
549
      n = 1;
 
550
      if (c0 > cmax)
 
551
        {
 
552
          cmax = c0;
 
553
          n = 0;
 
554
        }
 
555
      if (c2 > cmax)
 
556
        {
 
557
          cmax = c2;
 
558
          n = 2;
 
559
        }
 
560
      if (c3 > cmax)
 
561
        {
 
562
          n = 3;
 
563
        }
 
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.
 
569
       */
 
570
      switch (n)
 
571
        {
 
572
        case 0:
 
573
          lb = (b1->c0max + b1->c0min) / 2;
 
574
          b1->c0max = lb;
 
575
          b2->c0min = lb + 1;
 
576
          break;
 
577
        case 1:
 
578
          lb = (b1->c1max + b1->c1min) / 2;
 
579
          b1->c1max = lb;
 
580
          b2->c1min = lb + 1;
 
581
          break;
 
582
        case 2:
 
583
          lb = (b1->c2max + b1->c2min) / 2;
 
584
          b1->c2max = lb;
 
585
          b2->c2min = lb + 1;
 
586
          break;
 
587
        case 3:
 
588
          lb = (b1->c3max + b1->c3min) / 2;
 
589
          b1->c3max = lb;
 
590
          b2->c3min = lb + 1;
 
591
          break;
 
592
        }
 
593
      /* Update stats for boxes */
 
594
      update_box (im, cquantize, b1);
 
595
      update_box (im, cquantize, b2);
 
596
      numboxes++;
 
597
    }
 
598
  return numboxes;
 
599
}
 
600
 
 
601
 
 
602
static void
 
603
compute_color (gdImagePtr im, my_cquantize_ptr cquantize,
 
604
               boxptr boxp, int icolor)
 
605
/* 
 
606
   Compute representative color for a box, put it in 
 
607
   palette index icolor */
 
608
{
 
609
  /* Current algorithm: mean weighted by pixels (not colors) */
 
610
  /* Note it is important to get the rounding correct! */
 
611
  hist4d histogram = cquantize->histogram;
 
612
  histptr histp;
 
613
  int c0, c1, c2, c3;
 
614
  int c0min, c0max, c1min, c1max, c2min, c2max, c3min, c3max;
 
615
  long count;
 
616
  long total = 0;
 
617
  long c0total = 0;
 
618
  long c1total = 0;
 
619
  long c2total = 0;
 
620
  long c3total = 0;
 
621
 
 
622
  c0min = boxp->c0min;
 
623
  c0max = boxp->c0max;
 
624
  c1min = boxp->c1min;
 
625
  c1max = boxp->c1max;
 
626
  c2min = boxp->c2min;
 
627
  c2max = boxp->c2max;
 
628
  c3min = boxp->c3min;
 
629
  c3max = boxp->c3max;
 
630
 
 
631
  for (c0 = c0min; c0 <= c0max; c0++)
 
632
    {
 
633
      for (c1 = c1min; c1 <= c1max; c1++)
 
634
        {
 
635
          for (c2 = c2min; c2 <= c2max; c2++)
 
636
            {
 
637
              histp = &histogram[c0][c1][c2][c3min];
 
638
              for (c3 = c3min; c3 <= c3max; c3++)
 
639
                {
 
640
                  if ((count = *histp++) != 0)
 
641
                    {
 
642
                      total += count;
 
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;
 
647
                    }
 
648
                }
 
649
            }
 
650
        }
 
651
    }
 
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)
 
658
    {
 
659
      im->colorsTotal = icolor + 1;
 
660
    }
 
661
}
 
662
 
 
663
static void
 
664
select_colors (gdImagePtr im, my_cquantize_ptr cquantize, int desired_colors)
 
665
/* Master routine for color selection */
 
666
{
 
667
  boxptr boxlist;
 
668
  int numboxes;
 
669
  int i;
 
670
 
 
671
  /* Allocate workspace for box list */
 
672
  boxlist = (boxptr) gdMalloc (desired_colors * sizeof (box));
 
673
  /* Initialize one box containing whole space */
 
674
  numboxes = 1;
 
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. */
 
696
 
 
697
  im->colorsTotal = numboxes;
 
698
  gdFree (boxlist);
 
699
}
 
700
 
 
701
 
 
702
/*
 
703
 * These routines are concerned with the time-critical task of mapping input
 
704
 * colors to the nearest color in the selected colormap.
 
705
 *
 
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.
 
716
 *
 
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.
 
730
 *
 
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).
 
745
 *
 
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.
 
753
 */
 
754
 
 
755
 
 
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)
 
761
 
 
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)
 
766
 
 
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)
 
771
 
 
772
 
 
773
/*
 
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.
 
779
 */
 
780
 
 
781
static int
 
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.
 
791
 */
 
792
{
 
793
  int numcolors = im->colorsTotal;
 
794
  int maxc0, maxc1, maxc2, maxc3;
 
795
  int centerc0, centerc1, centerc2, centerc3;
 
796
  int i, x, ncolors;
 
797
  int minmaxdist, min_dist, max_dist, tdist;
 
798
  int mindist[MAXNUMCOLORS];    /* min distance to colormap entry i */
 
799
 
 
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 "<".
 
805
   */
 
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;
 
814
 
 
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.
 
822
   */
 
823
  minmaxdist = 0x7FFFFFFFL;
 
824
 
 
825
  for (i = 0; i < numcolors; i++)
 
826
    {
 
827
      /* We compute the squared-c0-distance term, then add in the other three. */
 
828
      x = im->red[i];
 
829
      if (x < minc0)
 
830
        {
 
831
          tdist = (x - minc0) * C0_SCALE;
 
832
          min_dist = tdist * tdist;
 
833
          tdist = (x - maxc0) * C0_SCALE;
 
834
          max_dist = tdist * tdist;
 
835
        }
 
836
      else if (x > maxc0)
 
837
        {
 
838
          tdist = (x - maxc0) * C0_SCALE;
 
839
          min_dist = tdist * tdist;
 
840
          tdist = (x - minc0) * C0_SCALE;
 
841
          max_dist = tdist * tdist;
 
842
        }
 
843
      else
 
844
        {
 
845
          /* within cell range so no contribution to min_dist */
 
846
          min_dist = 0;
 
847
          if (x <= centerc0)
 
848
            {
 
849
              tdist = (x - maxc0) * C0_SCALE;
 
850
              max_dist = tdist * tdist;
 
851
            }
 
852
          else
 
853
            {
 
854
              tdist = (x - minc0) * C0_SCALE;
 
855
              max_dist = tdist * tdist;
 
856
            }
 
857
        }
 
858
 
 
859
      x = im->green[i];
 
860
      if (x < minc1)
 
861
        {
 
862
          tdist = (x - minc1) * C1_SCALE;
 
863
          min_dist += tdist * tdist;
 
864
          tdist = (x - maxc1) * C1_SCALE;
 
865
          max_dist += tdist * tdist;
 
866
        }
 
867
      else if (x > maxc1)
 
868
        {
 
869
          tdist = (x - maxc1) * C1_SCALE;
 
870
          min_dist += tdist * tdist;
 
871
          tdist = (x - minc1) * C1_SCALE;
 
872
          max_dist += tdist * tdist;
 
873
        }
 
874
      else
 
875
        {
 
876
          /* within cell range so no contribution to min_dist */
 
877
          if (x <= centerc1)
 
878
            {
 
879
              tdist = (x - maxc1) * C1_SCALE;
 
880
              max_dist += tdist * tdist;
 
881
            }
 
882
          else
 
883
            {
 
884
              tdist = (x - minc1) * C1_SCALE;
 
885
              max_dist += tdist * tdist;
 
886
            }
 
887
        }
 
888
 
 
889
      x = im->blue[i];
 
890
      if (x < minc2)
 
891
        {
 
892
          tdist = (x - minc2) * C2_SCALE;
 
893
          min_dist += tdist * tdist;
 
894
          tdist = (x - maxc2) * C2_SCALE;
 
895
          max_dist += tdist * tdist;
 
896
        }
 
897
      else if (x > maxc2)
 
898
        {
 
899
          tdist = (x - maxc2) * C2_SCALE;
 
900
          min_dist += tdist * tdist;
 
901
          tdist = (x - minc2) * C2_SCALE;
 
902
          max_dist += tdist * tdist;
 
903
        }
 
904
      else
 
905
        {
 
906
          /* within cell range so no contribution to min_dist */
 
907
          if (x <= centerc2)
 
908
            {
 
909
              tdist = (x - maxc2) * C2_SCALE;
 
910
              max_dist += tdist * tdist;
 
911
            }
 
912
          else
 
913
            {
 
914
              tdist = (x - minc2) * C2_SCALE;
 
915
              max_dist += tdist * tdist;
 
916
            }
 
917
        }
 
918
 
 
919
      x = im->alpha[i];
 
920
      if (x < minc3)
 
921
        {
 
922
          tdist = (x - minc3) * C3_SCALE;
 
923
          min_dist += tdist * tdist;
 
924
          tdist = (x - maxc3) * C3_SCALE;
 
925
          max_dist += tdist * tdist;
 
926
        }
 
927
      else if (x > maxc3)
 
928
        {
 
929
          tdist = (x - maxc3) * C3_SCALE;
 
930
          min_dist += tdist * tdist;
 
931
          tdist = (x - minc3) * C3_SCALE;
 
932
          max_dist += tdist * tdist;
 
933
        }
 
934
      else
 
935
        {
 
936
          /* within cell range so no contribution to min_dist */
 
937
          if (x <= centerc3)
 
938
            {
 
939
              tdist = (x - maxc3) * C3_SCALE;
 
940
              max_dist += tdist * tdist;
 
941
            }
 
942
          else
 
943
            {
 
944
              tdist = (x - minc3) * C3_SCALE;
 
945
              max_dist += tdist * tdist;
 
946
            }
 
947
        }
 
948
 
 
949
      mindist[i] = min_dist;    /* save away the results */
 
950
      if (max_dist < minmaxdist)
 
951
        minmaxdist = max_dist;
 
952
    }
 
953
 
 
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.
 
957
   */
 
958
  ncolors = 0;
 
959
  for (i = 0; i < numcolors; i++)
 
960
    {
 
961
      if (mindist[i] <= minmaxdist)
 
962
        colorlist[ncolors++] = i;
 
963
    }
 
964
  return ncolors;
 
965
}
 
966
 
 
967
 
 
968
static void
 
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.
 
977
 */
 
978
{
 
979
  int ic0, ic1, ic2, ic3;
 
980
  int i, icolor;
 
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 */
 
986
  register int xx3;
 
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];
 
990
 
 
991
  /* Initialize best-distance for each cell of the update box */
 
992
  bptr = bestdist;
 
993
  for (i = BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS * BOX_C3_ELEMS - 1; i >= 0; i--)
 
994
    *bptr++ = 0x7FFFFFFFL;
 
995
 
 
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.
 
999
   */
 
1000
 
 
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)
 
1006
 
 
1007
  for (i = 0; i < numcolors; i++)
 
1008
    {
 
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 */
 
1025
      bptr = bestdist;
 
1026
      cptr = bestcolor;
 
1027
      xx0 = inc0;
 
1028
      for (ic0 = BOX_C0_ELEMS - 1; ic0 >= 0; ic0--)
 
1029
        {
 
1030
          dist1 = dist0;
 
1031
          xx1 = inc1;
 
1032
          for (ic1 = BOX_C1_ELEMS - 1; ic1 >= 0; ic1--)
 
1033
            {
 
1034
              dist2 = dist1;
 
1035
              xx2 = inc2;
 
1036
              for (ic2 = BOX_C2_ELEMS - 1; ic2 >= 0; ic2--)
 
1037
                {
 
1038
                  for (ic3 = BOX_C3_ELEMS - 1; ic3 >= 0; ic3--)
 
1039
                    {
 
1040
                      if (dist3 < *bptr)
 
1041
                        {
 
1042
                          *bptr = dist3;
 
1043
                          *cptr = icolor;
 
1044
                        }
 
1045
                      dist3 += xx3;
 
1046
                      xx3 += 2 * STEP_C3 * STEP_C3;
 
1047
                      bptr++;
 
1048
                      cptr++;
 
1049
                    }
 
1050
                  dist2 += xx2;
 
1051
                  xx2 += 2 * STEP_C2 * STEP_C2;
 
1052
                }
 
1053
              dist1 += xx1;
 
1054
              xx1 += 2 * STEP_C1 * STEP_C1;
 
1055
            }
 
1056
          dist0 += xx0;
 
1057
          xx0 += 2 * STEP_C0 * STEP_C0;
 
1058
        }
 
1059
    }
 
1060
}
 
1061
 
 
1062
 
 
1063
static void
 
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.) */
 
1069
{
 
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];
 
1080
 
 
1081
  /* Convert cell coordinates to update box ID */
 
1082
  c0 >>= BOX_C0_LOG;
 
1083
  c1 >>= BOX_C1_LOG;
 
1084
  c2 >>= BOX_C2_LOG;
 
1085
  c3 >>= BOX_C3_LOG;
 
1086
 
 
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.
 
1090
   */
 
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.
 
1097
   */
 
1098
  numcolors = find_nearby_colors (im, cquantize, minc0, minc1, minc2, minc3, colorlist);
 
1099
 
 
1100
  /* Determine the actually nearest colors. */
 
1101
  find_best_colors (im, cquantize, minc0, minc1, minc2, minc3, numcolors, colorlist,
 
1102
                    bestcolor);
 
1103
 
 
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 */
 
1106
  c1 <<= BOX_C1_LOG;
 
1107
  c2 <<= BOX_C2_LOG;
 
1108
  c3 <<= BOX_C3_LOG;
 
1109
  cptr = bestcolor;
 
1110
  for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++)
 
1111
    {
 
1112
      for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++)
 
1113
        {
 
1114
          for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++)
 
1115
            {
 
1116
              cachep = &histogram[c0 + ic0][c1 + ic1][c2 + ic2][c3];
 
1117
              for (ic3 = 0; ic3 < BOX_C3_ELEMS; ic3++)
 
1118
                {
 
1119
                  *cachep++ = (histcell) ((*cptr++) + 1);
 
1120
                }
 
1121
            }
 
1122
        }
 
1123
    }
 
1124
}
 
1125
 
 
1126
 
 
1127
/*
 
1128
 * Map some rows of pixels to the output colormapped representation.
 
1129
 */
 
1130
 
 
1131
void
 
1132
pass2_no_dither (gdImagePtr im, my_cquantize_ptr cquantize)
 
1133
/* This version performs no dithering */
 
1134
{
 
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;
 
1140
  int row;
 
1141
  int col;
 
1142
  int width = im->sx;
 
1143
  int num_rows = im->sy;
 
1144
  for (row = 0; row < num_rows; row++)
 
1145
    {
 
1146
      inptr = im->tpixels[row];
 
1147
      outptr = im->pixels[row];
 
1148
      for (col = 0; col < width; col++)
 
1149
        {
 
1150
          int r, g, b, a;
 
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++);
 
1156
          c0 = r >> C0_SHIFT;
 
1157
          c1 = g >> C1_SHIFT;
 
1158
          c2 = b >> C2_SHIFT;
 
1159
          c3 = a >> C3_SHIFT;
 
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 */
 
1163
          if (*cachep == 0)
 
1164
            {
 
1165
#if 0
 
1166
              /* TBB: quick and dirty approach for use when testing
 
1167
                 fill_inverse_cmap for errors */
 
1168
              int i;
 
1169
              int best = -1;
 
1170
              int mindist = 0x7FFFFFFF;
 
1171
              for (i = 0; (i < im->colorsTotal); i++)
 
1172
                {
 
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;
 
1181
                  if (dist < mindist)
 
1182
                    {
 
1183
                      best = i;
 
1184
                      mindist = dist;
 
1185
                    }
 
1186
                }
 
1187
              *cachep = best + 1;
 
1188
#endif
 
1189
              fill_inverse_cmap (im, cquantize, c0, c1, c2, c3);
 
1190
            }
 
1191
          /* Now emit the colormap index for this cell */
 
1192
          *outptr++ = (*cachep - 1);
 
1193
        }
 
1194
    }
 
1195
}
 
1196
 
 
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.
 
1205
 */
 
1206
 
 
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)))
 
1213
#else
 
1214
#define SHIFT_TEMPS
 
1215
#define RIGHT_SHIFT(x,shft)     ((x) >> (shft))
 
1216
#endif
 
1217
 
 
1218
 
 
1219
void
 
1220
pass2_fs_dither (gdImagePtr im, my_cquantize_ptr cquantize)
 
1221
 
 
1222
/* This version performs Floyd-Steinberg dithering */
 
1223
{
 
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 */
 
1231
  histptr cachep;
 
1232
  int dir;                      /* +1 or -1 depending on direction */
 
1233
  int dir4;                     /* 4*dir, for advancing errorptr */
 
1234
  int row;
 
1235
  int col;
 
1236
  int width = im->sx;
 
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;
 
1243
  SHIFT_TEMPS
 
1244
 
 
1245
    for (row = 0; row < num_rows; row++)
 
1246
    {
 
1247
      inptr = im->tpixels[row];
 
1248
      outptr = im->pixels[row];
 
1249
      if (cquantize->on_odd_row)
 
1250
        {
 
1251
          /* work right to left in this row */
 
1252
          inptr += (width - 1); /* so point to rightmost pixel */
 
1253
          outptr += width - 1;
 
1254
          dir = -1;
 
1255
          dir4 = -4;
 
1256
          errorptr = cquantize->fserrors + (width + 1) * 4;     /* => entry after last column */
 
1257
          cquantize->on_odd_row = FALSE;        /* flip for next time */
 
1258
        }
 
1259
      else
 
1260
        {
 
1261
          /* work left to right in this row */
 
1262
          dir = 1;
 
1263
          dir4 = 4;
 
1264
          errorptr = cquantize->fserrors;       /* => entry before first real column */
 
1265
          cquantize->on_odd_row = TRUE;         /* flip for next time */
 
1266
        }
 
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;
 
1272
 
 
1273
      for (col = width; col > 0; col--)
 
1274
        {
 
1275
          int a;
 
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.
 
1283
           */
 
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.
 
1290
           */
 
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).
 
1298
           */
 
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);
 
1305
          if (cur0 < 0)
 
1306
            {
 
1307
              cur0 = 0;
 
1308
            }
 
1309
          if (cur0 > 255)
 
1310
            {
 
1311
              cur0 = 255;
 
1312
            }
 
1313
          if (cur1 < 0)
 
1314
            {
 
1315
              cur1 = 0;
 
1316
            }
 
1317
          if (cur1 > 255)
 
1318
            {
 
1319
              cur1 = 255;
 
1320
            }
 
1321
          if (cur2 < 0)
 
1322
            {
 
1323
              cur2 = 0;
 
1324
            }
 
1325
          if (cur2 > 255)
 
1326
            {
 
1327
              cur2 = 255;
 
1328
            }
 
1329
          if (cur3 < 0)
 
1330
            {
 
1331
              cur3 = 0;
 
1332
            }
 
1333
          if (cur3 > 255)
 
1334
            {
 
1335
              cur3 = 255;
 
1336
            }
 
1337
          /* Index into the cache with adjusted pixel value */
 
1338
          cachep = &histogram
 
1339
            [cur0 >> C0_SHIFT]
 
1340
            [cur1 >> C1_SHIFT]
 
1341
            [cur2 >> C2_SHIFT]
 
1342
            [cur3 >> (C3_SHIFT + 1)];
 
1343
          /* If we have not seen this color before, find nearest colormap */
 
1344
          /* entry and update the cache */
 
1345
          if (*cachep == 0)
 
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 */
 
1350
          {
 
1351
            register int pixcode = *cachep - 1;
 
1352
            *outptr = pixcode;
 
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));
 
1358
          }
 
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.
 
1362
           */
 
1363
          {
 
1364
            register LOCFSERROR bnexterr, delta;
 
1365
 
 
1366
            bnexterr = cur0;    /* Process component 0 */
 
1367
            delta = cur0 * 2;
 
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 */
 
1375
            delta = cur1 * 2;
 
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 */
 
1383
            delta = cur2 * 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 */
 
1391
            delta = cur3 * 2;
 
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 */
 
1398
          }
 
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.
 
1402
           */
 
1403
          inptr += dir;         /* Advance pixel pointers to next column */
 
1404
          outptr += dir;
 
1405
          errorptr += dir4;     /* advance errorptr to current column */
 
1406
        }
 
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.
 
1410
       */
 
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;
 
1415
    }
 
1416
}
 
1417
 
 
1418
 
 
1419
/*
 
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.
 
1434
 */
 
1435
 
 
1436
static int
 
1437
init_error_limit (gdImagePtr im, my_cquantize_ptr cquantize)
 
1438
/* Allocate and fill in the error_limiter table */
 
1439
{
 
1440
  int *table;
 
1441
  int in, out;
 
1442
 
 
1443
  cquantize->error_limiter_storage = (int *) gdMalloc ((255 * 2 + 1) * sizeof (int));
 
1444
  if (!cquantize->error_limiter_storage)
 
1445
    {
 
1446
      return 0;
 
1447
    }
 
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 */
 
1453
  out = 0;
 
1454
  for (in = 0; in < STEPSIZE; in++, out++)
 
1455
    {
 
1456
      table[in] = out;
 
1457
      table[-in] = -out;
 
1458
    }
 
1459
  /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
 
1460
  for (; in < STEPSIZE * 3; in++, out += (in & 1) ? 0 : 1)
 
1461
    {
 
1462
      table[in] = out;
 
1463
      table[-in] = -out;
 
1464
    }
 
1465
  /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
 
1466
  for (; in <= 255; in++)
 
1467
    {
 
1468
      table[in] = out;
 
1469
      table[-in] = -out;
 
1470
    }
 
1471
#undef STEPSIZE
 
1472
  return 1;
 
1473
}
 
1474
 
 
1475
static void
 
1476
zeroHistogram (hist4d histogram)
 
1477
{
 
1478
  int i;
 
1479
  int j;
 
1480
  /* Zero the histogram or inverse color map */
 
1481
  for (i = 0; i < HIST_C0_ELEMS; i++)
 
1482
    {
 
1483
      for (j = 0; j < HIST_C1_ELEMS; j++)
 
1484
        {
 
1485
          memset (histogram[i][j],
 
1486
                  0,
 
1487
                  HIST_C2_ELEMS * HIST_C3_ELEMS * sizeof (histcell));
 
1488
        }
 
1489
    }
 
1490
}
 
1491
 
 
1492
/* Here we go at last. */
 
1493
void
 
1494
gdImageTrueColorToPalette (gdImagePtr im, int dither, int colorsWanted)
 
1495
{
 
1496
  my_cquantize_ptr cquantize = 0;
 
1497
  int i;
 
1498
  size_t arraysize;
 
1499
  if (!im->trueColor)
 
1500
    {
 
1501
      /* Nothing to do! */
 
1502
      return;
 
1503
    }
 
1504
  if (colorsWanted > gdMaxColors)
 
1505
    {
 
1506
      colorsWanted = gdMaxColors;
 
1507
    }
 
1508
  im->pixels = gdCalloc (sizeof (unsigned char *), im->sy);
 
1509
  if (!im->pixels)
 
1510
    {
 
1511
      /* No can do */
 
1512
      goto outOfMemory;
 
1513
    }
 
1514
  for (i = 0; (i < im->sy); i++)
 
1515
    {
 
1516
      im->pixels[i] = gdCalloc (sizeof (unsigned char *), im->sx);
 
1517
      if (!im->pixels[i])
 
1518
        {
 
1519
          goto outOfMemory;
 
1520
        }
 
1521
    }
 
1522
  cquantize = (my_cquantize_ptr) gdCalloc (sizeof (my_cquantizer), 1);
 
1523
  if (!cquantize)
 
1524
    {
 
1525
      /* No can do */
 
1526
      goto outOfMemory;
 
1527
    }
 
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++)
 
1531
    {
 
1532
      int j;
 
1533
      cquantize->histogram[i] = (hist3d) gdCalloc (HIST_C1_ELEMS,
 
1534
                                                   sizeof (hist2d));
 
1535
      if (!cquantize->histogram[i])
 
1536
        {
 
1537
          goto outOfMemory;
 
1538
        }
 
1539
      for (j = 0; (j < HIST_C1_ELEMS); j++)
 
1540
        {
 
1541
          cquantize->histogram[i][j] = (hist2d) gdCalloc (HIST_C2_ELEMS * HIST_C3_ELEMS,
 
1542
                                                          sizeof (histcell));
 
1543
          if (!cquantize->histogram[i][j])
 
1544
            {
 
1545
              goto outOfMemory;
 
1546
            }
 
1547
        }
 
1548
    }
 
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)
 
1556
    {
 
1557
      goto outOfMemory;
 
1558
    }
 
1559
  cquantize->on_odd_row = FALSE;
 
1560
 
 
1561
  /* Do the work! */
 
1562
  zeroHistogram (cquantize->histogram);
 
1563
  prescan_quantize (im, cquantize);
 
1564
  select_colors (im, cquantize, 256);
 
1565
  /* TBB HACK REMOVE */
 
1566
  {
 
1567
    FILE *out = fopen ("palettemap.png", "wb");
 
1568
    int i;
 
1569
    gdImagePtr im2 = gdImageCreateTrueColor (256, 256);
 
1570
    for (i = 0; (i < 256); i++)
 
1571
      {
 
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]));
 
1576
      }
 
1577
    gdImagePng (im2, out);
 
1578
    fclose (out);
 
1579
    gdImageDestroy (im2);
 
1580
  }
 
1581
  zeroHistogram (cquantize->histogram);
 
1582
  if (dither)
 
1583
    {
 
1584
      pass2_fs_dither (im, cquantize);
 
1585
    }
 
1586
  else
 
1587
    {
 
1588
      pass2_no_dither (im, cquantize);
 
1589
    }
 
1590
  if (cquantize->transparentIsPresent)
 
1591
    {
 
1592
      int mt = -1;
 
1593
      int mtIndex = -1;
 
1594
      for (i = 0; (i < im->colorsTotal); i++)
 
1595
        {
 
1596
          if (im->alpha[i] > mt)
 
1597
            {
 
1598
              mtIndex = i;
 
1599
              mt = im->alpha[i];
 
1600
            }
 
1601
        }
 
1602
      for (i = 0; (i < im->colorsTotal); i++)
 
1603
        {
 
1604
          if (im->alpha[i] == mt)
 
1605
            {
 
1606
              im->alpha[i] = gdAlphaTransparent;
 
1607
            }
 
1608
        }
 
1609
    }
 
1610
  if (cquantize->opaqueIsPresent)
 
1611
    {
 
1612
      int mo = 128;
 
1613
      int moIndex = -1;
 
1614
      for (i = 0; (i < im->colorsTotal); i++)
 
1615
        {
 
1616
          if (im->alpha[i] < mo)
 
1617
            {
 
1618
              moIndex = i;
 
1619
              mo = im->alpha[i];
 
1620
            }
 
1621
        }
 
1622
      for (i = 0; (i < im->colorsTotal); i++)
 
1623
        {
 
1624
          if (im->alpha[i] == mo)
 
1625
            {
 
1626
              im->alpha[i] = gdAlphaOpaque;
 
1627
            }
 
1628
        }
 
1629
    }
 
1630
  /* Success! Get rid of the truecolor image data. */
 
1631
  im->trueColor = 0;
 
1632
  /* Junk the truecolor pixels */
 
1633
  for (i = 0; i < im->sy; i++)
 
1634
    {
 
1635
      gdFree (im->tpixels[i]);
 
1636
    }
 
1637
  gdFree (im->tpixels);
 
1638
  im->tpixels = 0;
 
1639
  /* Tediously free stuff. */
 
1640
outOfMemory:
 
1641
  if (im->trueColor)
 
1642
    {
 
1643
      /* On failure only */
 
1644
      for (i = 0; i < im->sy; i++)
 
1645
        {
 
1646
          if (im->pixels[i])
 
1647
            {
 
1648
              gdFree (im->pixels[i]);
 
1649
            }
 
1650
        }
 
1651
      if (im->pixels)
 
1652
        {
 
1653
          gdFree (im->pixels);
 
1654
        }
 
1655
      im->pixels = 0;
 
1656
    }
 
1657
  for (i = 0; i < HIST_C0_ELEMS; i++)
 
1658
    {
 
1659
      if (cquantize->histogram[i])
 
1660
        {
 
1661
          int j;
 
1662
          for (j = 0; j < HIST_C1_ELEMS; j++)
 
1663
            {
 
1664
              if (cquantize->histogram[i][j])
 
1665
                {
 
1666
                  gdFree (cquantize->histogram[i][j]);
 
1667
                }
 
1668
            }
 
1669
          gdFree (cquantize->histogram[i]);
 
1670
        }
 
1671
    }
 
1672
  if (cquantize->histogram)
 
1673
    {
 
1674
      gdFree (cquantize->histogram);
 
1675
    }
 
1676
  if (cquantize->fserrors)
 
1677
    {
 
1678
      gdFree (cquantize->fserrors);
 
1679
    }
 
1680
  if (cquantize->error_limiter_storage)
 
1681
    {
 
1682
      gdFree (cquantize->error_limiter_storage);
 
1683
    }
 
1684
  if (cquantize)
 
1685
    {
 
1686
      gdFree (cquantize);
 
1687
    }
 
1688
}