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