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



Page generated by Doxygen 1.8.14 for MRPT 1.9.9 Git: ae4571287 Thu Nov 23 00:06:53 2017 +0100 at dom oct 27 23:51:55 CET 2019