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



Page generated by Doxygen 1.8.14 for MRPT 1.5.7 Git: 5902e14cc Wed Apr 24 15:04:01 2019 +0200 at lun oct 28 01:39:17 CET 2019