source: golgotha/src/i4/loaders/jpg/jquant2.cc @ 608

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