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