Remove 'oldcode'
[oweals/cde.git] / cde / lib / DtHelp / jpeg / jquant1.c
1 /*
2  * CDE - Common Desktop Environment
3  *
4  * Copyright (c) 1993-2012, The Open Group. All rights reserved.
5  *
6  * These libraries and programs are free software; you can
7  * redistribute them and/or modify them under the terms of the GNU
8  * Lesser General Public License as published by the Free Software
9  * Foundation; either version 2 of the License, or (at your option)
10  * any later version.
11  *
12  * These libraries and programs are distributed in the hope that
13  * they will be useful, but WITHOUT ANY WARRANTY; without even the
14  * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15  * PURPOSE. See the GNU Lesser General Public License for more
16  * details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with these libraries and programs; if not, write
20  * to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
21  * Floor, Boston, MA 02110-1301 USA
22  */
23 /* $XConsortium: jquant1.c /main/2 1996/05/09 03:53:55 drk $ */
24 /*
25  * jquant1.c
26  *
27  * Copyright (C) 1991-1996, Thomas G. Lane.
28  * This file is part of the Independent JPEG Group's software.
29  * For conditions of distribution and use, see the accompanying README file.
30  *
31  * This file contains 1-pass color quantization (color mapping) routines.
32  * These routines provide mapping to a fixed color map using equally spaced
33  * color values.  Optional Floyd-Steinberg or ordered dithering is available.
34  */
35
36 #define JPEG_INTERNALS
37 #include "jinclude.h"
38 #include "jpeglib.h"
39
40 #ifdef QUANT_1PASS_SUPPORTED
41
42
43 /*
44  * The main purpose of 1-pass quantization is to provide a fast, if not very
45  * high quality, colormapped output capability.  A 2-pass quantizer usually
46  * gives better visual quality; however, for quantized grayscale output this
47  * quantizer is perfectly adequate.  Dithering is highly recommended with this
48  * quantizer, though you can turn it off if you really want to.
49  *
50  * In 1-pass quantization the colormap must be chosen in advance of seeing the
51  * image.  We use a map consisting of all combinations of Ncolors[i] color
52  * values for the i'th component.  The Ncolors[] values are chosen so that
53  * their product, the total number of colors, is no more than that requested.
54  * (In most cases, the product will be somewhat less.)
55  *
56  * Since the colormap is orthogonal, the representative value for each color
57  * component can be determined without considering the other components;
58  * then these indexes can be combined into a colormap index by a standard
59  * N-dimensional-array-subscript calculation.  Most of the arithmetic involved
60  * can be precalculated and stored in the lookup table colorindex[].
61  * colorindex[i][j] maps pixel value j in component i to the nearest
62  * representative value (grid plane) for that component; this index is
63  * multiplied by the array stride for component i, so that the
64  * index of the colormap entry closest to a given pixel value is just
65  *    sum( colorindex[component-number][pixel-component-value] )
66  * Aside from being fast, this scheme allows for variable spacing between
67  * representative values with no additional lookup cost.
68  *
69  * If gamma correction has been applied in color conversion, it might be wise
70  * to adjust the color grid spacing so that the representative colors are
71  * equidistant in linear space.  At this writing, gamma correction is not
72  * implemented by jdcolor, so nothing is done here.
73  */
74
75
76 /* Declarations for ordered dithering.
77  *
78  * We use a standard 16x16 ordered dither array.  The basic concept of ordered
79  * dithering is described in many references, for instance Dale Schumacher's
80  * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
81  * In place of Schumacher's comparisons against a "threshold" value, we add a
82  * "dither" value to the input pixel and then round the result to the nearest
83  * output value.  The dither value is equivalent to (0.5 - threshold) times
84  * the distance between output values.  For ordered dithering, we assume that
85  * the output colors are equally spaced; if not, results will probably be
86  * worse, since the dither may be too much or too little at a given point.
87  *
88  * The normal calculation would be to form pixel value + dither, range-limit
89  * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
90  * We can skip the separate range-limiting step by extending the colorindex
91  * table in both directions.
92  */
93
94 #define ODITHER_SIZE  16        /* dimension of dither matrix */
95 /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
96 #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE)       /* # cells in matrix */
97 #define ODITHER_MASK  (ODITHER_SIZE-1) /* mask for wrapping around counters */
98
99 typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
100 typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
101
102 static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
103   /* Bayer's order-4 dither array.  Generated by the code given in
104    * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
105    * The values in this array must range from 0 to ODITHER_CELLS-1.
106    */
107   {   0,192, 48,240, 12,204, 60,252,  3,195, 51,243, 15,207, 63,255 },
108   { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
109   {  32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
110   { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
111   {   8,200, 56,248,  4,196, 52,244, 11,203, 59,251,  7,199, 55,247 },
112   { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
113   {  40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
114   { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
115   {   2,194, 50,242, 14,206, 62,254,  1,193, 49,241, 13,205, 61,253 },
116   { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
117   {  34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
118   { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
119   {  10,202, 58,250,  6,198, 54,246,  9,201, 57,249,  5,197, 53,245 },
120   { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
121   {  42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
122   { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
123 };
124
125
126 /* Declarations for Floyd-Steinberg dithering.
127  *
128  * Errors are accumulated into the array fserrors[], at a resolution of
129  * 1/16th of a pixel count.  The error at a given pixel is propagated
130  * to its not-yet-processed neighbors using the standard F-S fractions,
131  *              ...     (here)  7/16
132  *              3/16    5/16    1/16
133  * We work left-to-right on even rows, right-to-left on odd rows.
134  *
135  * We can get away with a single array (holding one row's worth of errors)
136  * by using it to store the current row's errors at pixel columns not yet
137  * processed, but the next row's errors at columns already processed.  We
138  * need only a few extra variables to hold the errors immediately around the
139  * current column.  (If we are lucky, those variables are in registers, but
140  * even if not, they're probably cheaper to access than array elements are.)
141  *
142  * The fserrors[] array is indexed [component#][position].
143  * We provide (#columns + 2) entries per component; the extra entry at each
144  * end saves us from special-casing the first and last pixels.
145  *
146  * Note: on a wide image, we might not have enough room in a PC's near data
147  * segment to hold the error array; so it is allocated with alloc_large.
148  */
149
150 #if BITS_IN_JSAMPLE == 8
151 typedef INT16 FSERROR;          /* 16 bits should be enough */
152 typedef int LOCFSERROR;         /* use 'int' for calculation temps */
153 #else
154 typedef INT32 FSERROR;          /* may need more than 16 bits */
155 typedef INT32 LOCFSERROR;       /* be sure calculation temps are big enough */
156 #endif
157
158 typedef FSERROR FAR *FSERRPTR;  /* pointer to error array (in FAR storage!) */
159
160
161 /* Private subobject */
162
163 #define MAX_Q_COMPS 4           /* max components I can handle */
164
165 typedef struct {
166   struct jpeg_color_quantizer pub; /* public fields */
167
168   /* Initially allocated colormap is saved here */
169   JSAMPARRAY sv_colormap;       /* The color map as a 2-D pixel array */
170   int sv_actual;                /* number of entries in use */
171
172   JSAMPARRAY colorindex;        /* Precomputed mapping for speed */
173   /* colorindex[i][j] = index of color closest to pixel value j in component i,
174    * premultiplied as described above.  Since colormap indexes must fit into
175    * JSAMPLEs, the entries of this array will too.
176    */
177   boolean is_padded;            /* is the colorindex padded for odither? */
178
179   int Ncolors[MAX_Q_COMPS];     /* # of values alloced to each component */
180
181   /* Variables for ordered dithering */
182   int row_index;                /* cur row's vertical index in dither matrix */
183   ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
184
185   /* Variables for Floyd-Steinberg dithering */
186   FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
187   boolean on_odd_row;           /* flag to remember which row we are on */
188 } my_cquantizer;
189
190 typedef my_cquantizer * my_cquantize_ptr;
191
192
193 /*
194  * Policy-making subroutines for create_colormap and create_colorindex.
195  * These routines determine the colormap to be used.  The rest of the module
196  * only assumes that the colormap is orthogonal.
197  *
198  *  * select_ncolors decides how to divvy up the available colors
199  *    among the components.
200  *  * output_value defines the set of representative values for a component.
201  *  * largest_input_value defines the mapping from input values to
202  *    representative values for a component.
203  * Note that the latter two routines may impose different policies for
204  * different components, though this is not currently done.
205  */
206
207
208 LOCAL(int)
209 select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
210 /* Determine allocation of desired colors to components, */
211 /* and fill in Ncolors[] array to indicate choice. */
212 /* Return value is total number of colors (product of Ncolors[] values). */
213 {
214   int nc = cinfo->out_color_components; /* number of color components */
215   int max_colors = cinfo->desired_number_of_colors;
216   int total_colors, iroot, i, j;
217   boolean changed;
218   long temp;
219   static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
220
221   /* We can allocate at least the nc'th root of max_colors per component. */
222   /* Compute floor(nc'th root of max_colors). */
223   iroot = 1;
224   do {
225     iroot++;
226     temp = iroot;               /* set temp = iroot ** nc */
227     for (i = 1; i < nc; i++)
228       temp *= iroot;
229   } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
230   iroot--;                      /* now iroot = floor(root) */
231
232   /* Must have at least 2 color values per component */
233   if (iroot < 2)
234     ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
235
236   /* Initialize to iroot color values for each component */
237   total_colors = 1;
238   for (i = 0; i < nc; i++) {
239     Ncolors[i] = iroot;
240     total_colors *= iroot;
241   }
242   /* We may be able to increment the count for one or more components without
243    * exceeding max_colors, though we know not all can be incremented.
244    * Sometimes, the first component can be incremented more than once!
245    * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
246    * In RGB colorspace, try to increment G first, then R, then B.
247    */
248   do {
249     changed = FALSE;
250     for (i = 0; i < nc; i++) {
251       j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
252       /* calculate new total_colors if Ncolors[j] is incremented */
253       temp = total_colors / Ncolors[j];
254       temp *= Ncolors[j]+1;     /* done in long arith to avoid oflo */
255       if (temp > (long) max_colors)
256         break;                  /* won't fit, done with this pass */
257       Ncolors[j]++;             /* OK, apply the increment */
258       total_colors = (int) temp;
259       changed = TRUE;
260     }
261   } while (changed);
262
263   return total_colors;
264 }
265
266
267 LOCAL(int)
268 output_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
269 /* Return j'th output value, where j will range from 0 to maxj */
270 /* The output values must fall in 0..MAXJSAMPLE in increasing order */
271 {
272   /* We always provide values 0 and MAXJSAMPLE for each component;
273    * any additional values are equally spaced between these limits.
274    * (Forcing the upper and lower values to the limits ensures that
275    * dithering can't produce a color outside the selected gamut.)
276    */
277   return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
278 }
279
280
281 LOCAL(int)
282 largest_input_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
283 /* Return largest input value that should map to j'th output value */
284 /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
285 {
286   /* Breakpoints are halfway between values returned by output_value */
287   return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
288 }
289
290
291 /*
292  * Create the colormap.
293  */
294
295 LOCAL(void)
296 create_colormap (j_decompress_ptr cinfo)
297 {
298   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
299   JSAMPARRAY colormap;          /* Created colormap */
300   int total_colors;             /* Number of distinct output colors */
301   int i,j,k, nci, blksize, blkdist, ptr, val;
302
303   /* Select number of colors for each component */
304   total_colors = select_ncolors(cinfo, cquantize->Ncolors);
305
306   /* Report selected color counts */
307   if (cinfo->out_color_components == 3)
308     TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
309              total_colors, cquantize->Ncolors[0],
310              cquantize->Ncolors[1], cquantize->Ncolors[2]);
311   else
312     TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
313
314   /* Allocate and fill in the colormap. */
315   /* The colors are ordered in the map in standard row-major order, */
316   /* i.e. rightmost (highest-indexed) color changes most rapidly. */
317
318   colormap = (*cinfo->mem->alloc_sarray)
319     ((j_common_ptr) cinfo, JPOOL_IMAGE,
320      (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
321
322   /* blksize is number of adjacent repeated entries for a component */
323   /* blkdist is distance between groups of identical entries for a component */
324   blkdist = total_colors;
325
326   for (i = 0; i < cinfo->out_color_components; i++) {
327     /* fill in colormap entries for i'th color component */
328     nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
329     blksize = blkdist / nci;
330     for (j = 0; j < nci; j++) {
331       /* Compute j'th output value (out of nci) for component */
332       val = output_value(cinfo, i, j, nci-1);
333       /* Fill in all colormap entries that have this value of this component */
334       for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
335         /* fill in blksize entries beginning at ptr */
336         for (k = 0; k < blksize; k++)
337           colormap[i][ptr+k] = (JSAMPLE) val;
338       }
339     }
340     blkdist = blksize;          /* blksize of this color is blkdist of next */
341   }
342
343   /* Save the colormap in private storage,
344    * where it will survive color quantization mode changes.
345    */
346   cquantize->sv_colormap = colormap;
347   cquantize->sv_actual = total_colors;
348 }
349
350
351 /*
352  * Create the color index table.
353  */
354
355 LOCAL(void)
356 create_colorindex (j_decompress_ptr cinfo)
357 {
358   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
359   JSAMPROW indexptr;
360   int i,j,k, nci, blksize, val, pad;
361
362   /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
363    * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
364    * This is not necessary in the other dithering modes.  However, we
365    * flag whether it was done in case user changes dithering mode.
366    */
367   if (cinfo->dither_mode == JDITHER_ORDERED) {
368     pad = MAXJSAMPLE*2;
369     cquantize->is_padded = TRUE;
370   } else {
371     pad = 0;
372     cquantize->is_padded = FALSE;
373   }
374
375   cquantize->colorindex = (*cinfo->mem->alloc_sarray)
376     ((j_common_ptr) cinfo, JPOOL_IMAGE,
377      (JDIMENSION) (MAXJSAMPLE+1 + pad),
378      (JDIMENSION) cinfo->out_color_components);
379
380   /* blksize is number of adjacent repeated entries for a component */
381   blksize = cquantize->sv_actual;
382
383   for (i = 0; i < cinfo->out_color_components; i++) {
384     /* fill in colorindex entries for i'th color component */
385     nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
386     blksize = blksize / nci;
387
388     /* adjust colorindex pointers to provide padding at negative indexes. */
389     if (pad)
390       cquantize->colorindex[i] += MAXJSAMPLE;
391
392     /* in loop, val = index of current output value, */
393     /* and k = largest j that maps to current val */
394     indexptr = cquantize->colorindex[i];
395     val = 0;
396     k = largest_input_value(cinfo, i, 0, nci-1);
397     for (j = 0; j <= MAXJSAMPLE; j++) {
398       while (j > k)             /* advance val if past boundary */
399         k = largest_input_value(cinfo, i, ++val, nci-1);
400       /* premultiply so that no multiplication needed in main processing */
401       indexptr[j] = (JSAMPLE) (val * blksize);
402     }
403     /* Pad at both ends if necessary */
404     if (pad)
405       for (j = 1; j <= MAXJSAMPLE; j++) {
406         indexptr[-j] = indexptr[0];
407         indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
408       }
409   }
410 }
411
412
413 /*
414  * Create an ordered-dither array for a component having ncolors
415  * distinct output values.
416  */
417
418 LOCAL(ODITHER_MATRIX_PTR)
419 make_odither_array (j_decompress_ptr cinfo, int ncolors)
420 {
421   ODITHER_MATRIX_PTR odither;
422   int j,k;
423   INT32 num,den;
424
425   odither = (ODITHER_MATRIX_PTR)
426     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
427                                 SIZEOF(ODITHER_MATRIX));
428   /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
429    * Hence the dither value for the matrix cell with fill order f
430    * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
431    * On 16-bit-int machine, be careful to avoid overflow.
432    */
433   den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
434   for (j = 0; j < ODITHER_SIZE; j++) {
435     for (k = 0; k < ODITHER_SIZE; k++) {
436       num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
437             * MAXJSAMPLE;
438       /* Ensure round towards zero despite C's lack of consistency
439        * about rounding negative values in integer division...
440        */
441       odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
442     }
443   }
444   return odither;
445 }
446
447
448 /*
449  * Create the ordered-dither tables.
450  * Components having the same number of representative colors may 
451  * share a dither table.
452  */
453
454 LOCAL(void)
455 create_odither_tables (j_decompress_ptr cinfo)
456 {
457   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
458   ODITHER_MATRIX_PTR odither;
459   int i, j, nci;
460
461   for (i = 0; i < cinfo->out_color_components; i++) {
462     nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
463     odither = NULL;             /* search for matching prior component */
464     for (j = 0; j < i; j++) {
465       if (nci == cquantize->Ncolors[j]) {
466         odither = cquantize->odither[j];
467         break;
468       }
469     }
470     if (odither == NULL)        /* need a new table? */
471       odither = make_odither_array(cinfo, nci);
472     cquantize->odither[i] = odither;
473   }
474 }
475
476
477 /*
478  * Map some rows of pixels to the output colormapped representation.
479  */
480
481 METHODDEF(void)
482 color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
483                 JSAMPARRAY output_buf, int num_rows)
484 /* General case, no dithering */
485 {
486   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
487   JSAMPARRAY colorindex = cquantize->colorindex;
488   int pixcode, ci;
489   JSAMPROW ptrin, ptrout;
490   int row;
491   JDIMENSION col;
492   JDIMENSION width = cinfo->output_width;
493   int nc = cinfo->out_color_components;
494
495   for (row = 0; row < num_rows; row++) {
496     ptrin = input_buf[row];
497     ptrout = output_buf[row];
498     for (col = width; col > 0; col--) {
499       pixcode = 0;
500       for (ci = 0; ci < nc; ci++) {
501         pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
502       }
503       *ptrout++ = (JSAMPLE) pixcode;
504     }
505   }
506 }
507
508
509 METHODDEF(void)
510 color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
511                  JSAMPARRAY output_buf, int num_rows)
512 /* Fast path for out_color_components==3, no dithering */
513 {
514   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
515   int pixcode;
516   JSAMPROW ptrin, ptrout;
517   JSAMPROW colorindex0 = cquantize->colorindex[0];
518   JSAMPROW colorindex1 = cquantize->colorindex[1];
519   JSAMPROW colorindex2 = cquantize->colorindex[2];
520   int row;
521   JDIMENSION col;
522   JDIMENSION width = cinfo->output_width;
523
524   for (row = 0; row < num_rows; row++) {
525     ptrin = input_buf[row];
526     ptrout = output_buf[row];
527     for (col = width; col > 0; col--) {
528       pixcode  = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
529       pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
530       pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
531       *ptrout++ = (JSAMPLE) pixcode;
532     }
533   }
534 }
535
536
537 METHODDEF(void)
538 quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
539                      JSAMPARRAY output_buf, int num_rows)
540 /* General case, with ordered dithering */
541 {
542   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
543   JSAMPROW input_ptr;
544   JSAMPROW output_ptr;
545   JSAMPROW colorindex_ci;
546   int * dither;                 /* points to active row of dither matrix */
547   int row_index, col_index;     /* current indexes into dither matrix */
548   int nc = cinfo->out_color_components;
549   int ci;
550   int row;
551   JDIMENSION col;
552   JDIMENSION width = cinfo->output_width;
553
554   for (row = 0; row < num_rows; row++) {
555     /* Initialize output values to 0 so can process components separately */
556     jzero_far((void FAR *) output_buf[row],
557               (size_t) (width * SIZEOF(JSAMPLE)));
558     row_index = cquantize->row_index;
559     for (ci = 0; ci < nc; ci++) {
560       input_ptr = input_buf[row] + ci;
561       output_ptr = output_buf[row];
562       colorindex_ci = cquantize->colorindex[ci];
563       dither = cquantize->odither[ci][row_index];
564       col_index = 0;
565
566       for (col = width; col > 0; col--) {
567         /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
568          * select output value, accumulate into output code for this pixel.
569          * Range-limiting need not be done explicitly, as we have extended
570          * the colorindex table to produce the right answers for out-of-range
571          * inputs.  The maximum dither is +- MAXJSAMPLE; this sets the
572          * required amount of padding.
573          */
574         *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
575         input_ptr += nc;
576         output_ptr++;
577         col_index = (col_index + 1) & ODITHER_MASK;
578       }
579     }
580     /* Advance row index for next row */
581     row_index = (row_index + 1) & ODITHER_MASK;
582     cquantize->row_index = row_index;
583   }
584 }
585
586
587 METHODDEF(void)
588 quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
589                       JSAMPARRAY output_buf, int num_rows)
590 /* Fast path for out_color_components==3, with ordered dithering */
591 {
592   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
593   int pixcode;
594   JSAMPROW input_ptr;
595   JSAMPROW output_ptr;
596   JSAMPROW colorindex0 = cquantize->colorindex[0];
597   JSAMPROW colorindex1 = cquantize->colorindex[1];
598   JSAMPROW colorindex2 = cquantize->colorindex[2];
599   int * dither0;                /* points to active row of dither matrix */
600   int * dither1;
601   int * dither2;
602   int row_index, col_index;     /* current indexes into dither matrix */
603   int row;
604   JDIMENSION col;
605   JDIMENSION width = cinfo->output_width;
606
607   for (row = 0; row < num_rows; row++) {
608     row_index = cquantize->row_index;
609     input_ptr = input_buf[row];
610     output_ptr = output_buf[row];
611     dither0 = cquantize->odither[0][row_index];
612     dither1 = cquantize->odither[1][row_index];
613     dither2 = cquantize->odither[2][row_index];
614     col_index = 0;
615
616     for (col = width; col > 0; col--) {
617       pixcode  = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
618                                         dither0[col_index]]);
619       pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
620                                         dither1[col_index]]);
621       pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
622                                         dither2[col_index]]);
623       *output_ptr++ = (JSAMPLE) pixcode;
624       col_index = (col_index + 1) & ODITHER_MASK;
625     }
626     row_index = (row_index + 1) & ODITHER_MASK;
627     cquantize->row_index = row_index;
628   }
629 }
630
631
632 METHODDEF(void)
633 quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
634                     JSAMPARRAY output_buf, int num_rows)
635 /* General case, with Floyd-Steinberg dithering */
636 {
637   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
638   LOCFSERROR cur;       /* current error or pixel value */
639   LOCFSERROR belowerr;          /* error for pixel below cur */
640   LOCFSERROR bpreverr;          /* error for below/prev col */
641   LOCFSERROR bnexterr;          /* error for below/next col */
642   LOCFSERROR delta;
643   FSERRPTR errorptr;    /* => fserrors[] at column before current */
644   JSAMPROW input_ptr;
645   JSAMPROW output_ptr;
646   JSAMPROW colorindex_ci;
647   JSAMPROW colormap_ci;
648   int pixcode;
649   int nc = cinfo->out_color_components;
650   int dir;                      /* 1 for left-to-right, -1 for right-to-left */
651   int dirnc;                    /* dir * nc */
652   int ci;
653   int row;
654   JDIMENSION col;
655   JDIMENSION width = cinfo->output_width;
656   JSAMPLE *range_limit = cinfo->sample_range_limit;
657   SHIFT_TEMPS
658
659   for (row = 0; row < num_rows; row++) {
660     /* Initialize output values to 0 so can process components separately */
661     jzero_far((void FAR *) output_buf[row],
662               (size_t) (width * SIZEOF(JSAMPLE)));
663     for (ci = 0; ci < nc; ci++) {
664       input_ptr = input_buf[row] + ci;
665       output_ptr = output_buf[row];
666       if (cquantize->on_odd_row) {
667         /* work right to left in this row */
668         input_ptr += (width-1) * nc; /* so point to rightmost pixel */
669         output_ptr += width-1;
670         dir = -1;
671         dirnc = -nc;
672         errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
673       } else {
674         /* work left to right in this row */
675         dir = 1;
676         dirnc = nc;
677         errorptr = cquantize->fserrors[ci]; /* => entry before first column */
678       }
679       colorindex_ci = cquantize->colorindex[ci];
680       colormap_ci = cquantize->sv_colormap[ci];
681       /* Preset error values: no error propagated to first pixel from left */
682       cur = 0;
683       /* and no error propagated to row below yet */
684       belowerr = bpreverr = 0;
685
686       for (col = width; col > 0; col--) {
687         /* cur holds the error propagated from the previous pixel on the
688          * current line.  Add the error propagated from the previous line
689          * to form the complete error correction term for this pixel, and
690          * round the error term (which is expressed * 16) to an integer.
691          * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
692          * for either sign of the error value.
693          * Note: errorptr points to *previous* column's array entry.
694          */
695         cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
696         /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
697          * The maximum error is +- MAXJSAMPLE; this sets the required size
698          * of the range_limit array.
699          */
700         cur += GETJSAMPLE(*input_ptr);
701         cur = GETJSAMPLE(range_limit[cur]);
702         /* Select output value, accumulate into output code for this pixel */
703         pixcode = GETJSAMPLE(colorindex_ci[cur]);
704         *output_ptr += (JSAMPLE) pixcode;
705         /* Compute actual representation error at this pixel */
706         /* Note: we can do this even though we don't have the final */
707         /* pixel code, because the colormap is orthogonal. */
708         cur -= GETJSAMPLE(colormap_ci[pixcode]);
709         /* Compute error fractions to be propagated to adjacent pixels.
710          * Add these into the running sums, and simultaneously shift the
711          * next-line error sums left by 1 column.
712          */
713         bnexterr = cur;
714         delta = cur * 2;
715         cur += delta;           /* form error * 3 */
716         errorptr[0] = (FSERROR) (bpreverr + cur);
717         cur += delta;           /* form error * 5 */
718         bpreverr = belowerr + cur;
719         belowerr = bnexterr;
720         cur += delta;           /* form error * 7 */
721         /* At this point cur contains the 7/16 error value to be propagated
722          * to the next pixel on the current line, and all the errors for the
723          * next line have been shifted over. We are therefore ready to move on.
724          */
725         input_ptr += dirnc;     /* advance input ptr to next column */
726         output_ptr += dir;      /* advance output ptr to next column */
727         errorptr += dir;        /* advance errorptr to current column */
728       }
729       /* Post-loop cleanup: we must unload the final error value into the
730        * final fserrors[] entry.  Note we need not unload belowerr because
731        * it is for the dummy column before or after the actual array.
732        */
733       errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
734     }
735     cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
736   }
737 }
738
739
740 /*
741  * Allocate workspace for Floyd-Steinberg errors.
742  */
743
744 LOCAL(void)
745 alloc_fs_workspace (j_decompress_ptr cinfo)
746 {
747   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
748   size_t arraysize;
749   int i;
750
751   arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
752   for (i = 0; i < cinfo->out_color_components; i++) {
753     cquantize->fserrors[i] = (FSERRPTR)
754       (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
755   }
756 }
757
758
759 /*
760  * Initialize for one-pass color quantization.
761  */
762
763 METHODDEF(void)
764 start_pass_1_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
765 {
766   my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
767   size_t arraysize;
768   int i;
769
770   /* Install my colormap. */
771   cinfo->colormap = cquantize->sv_colormap;
772   cinfo->actual_number_of_colors = cquantize->sv_actual;
773
774   /* Initialize for desired dithering mode. */
775   switch (cinfo->dither_mode) {
776   case JDITHER_NONE:
777     if (cinfo->out_color_components == 3)
778       cquantize->pub.color_quantize = color_quantize3;
779     else
780       cquantize->pub.color_quantize = color_quantize;
781     break;
782   case JDITHER_ORDERED:
783     if (cinfo->out_color_components == 3)
784       cquantize->pub.color_quantize = quantize3_ord_dither;
785     else
786       cquantize->pub.color_quantize = quantize_ord_dither;
787     cquantize->row_index = 0;   /* initialize state for ordered dither */
788     /* If user changed to ordered dither from another mode,
789      * we must recreate the color index table with padding.
790      * This will cost extra space, but probably isn't very likely.
791      */
792     if (! cquantize->is_padded)
793       create_colorindex(cinfo);
794     /* Create ordered-dither tables if we didn't already. */
795     if (cquantize->odither[0] == NULL)
796       create_odither_tables(cinfo);
797     break;
798   case JDITHER_FS:
799     cquantize->pub.color_quantize = quantize_fs_dither;
800     cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
801     /* Allocate Floyd-Steinberg workspace if didn't already. */
802     if (cquantize->fserrors[0] == NULL)
803       alloc_fs_workspace(cinfo);
804     /* Initialize the propagated errors to zero. */
805     arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
806     for (i = 0; i < cinfo->out_color_components; i++)
807       jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
808     break;
809   default:
810     ERREXIT(cinfo, JERR_NOT_COMPILED);
811     break;
812   }
813 }
814
815
816 /*
817  * Finish up at the end of the pass.
818  */
819
820 METHODDEF(void)
821 finish_pass_1_quant (j_decompress_ptr cinfo)
822 {
823   /* no work in 1-pass case */
824 }
825
826
827 /*
828  * Switch to a new external colormap between output passes.
829  * Shouldn't get to this module!
830  */
831
832 METHODDEF(void)
833 new_color_map_1_quant (j_decompress_ptr cinfo)
834 {
835   ERREXIT(cinfo, JERR_MODE_CHANGE);
836 }
837
838
839 /*
840  * Module initialization routine for 1-pass color quantization.
841  */
842
843 GLOBAL(void)
844 jinit_1pass_quantizer (j_decompress_ptr cinfo)
845 {
846   my_cquantize_ptr cquantize;
847
848   cquantize = (my_cquantize_ptr)
849     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
850                                 SIZEOF(my_cquantizer));
851   cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
852   cquantize->pub.start_pass = start_pass_1_quant;
853   cquantize->pub.finish_pass = finish_pass_1_quant;
854   cquantize->pub.new_color_map = new_color_map_1_quant;
855   cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
856   cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
857
858   /* Make sure my internal arrays won't overflow */
859   if (cinfo->out_color_components > MAX_Q_COMPS)
860     ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
861   /* Make sure colormap indexes can be represented by JSAMPLEs */
862   if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
863     ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
864
865   /* Create the colormap and color index table. */
866   create_colormap(cinfo);
867   create_colorindex(cinfo);
868
869   /* Allocate Floyd-Steinberg workspace now if requested.
870    * We do this now since it is FAR storage and may affect the memory
871    * manager's space calculations.  If the user changes to FS dither
872    * mode in a later pass, we will allocate the space then, and will
873    * possibly overrun the max_memory_to_use setting.
874    */
875   if (cinfo->dither_mode == JDITHER_FS)
876     alloc_fs_workspace(cinfo);
877 }
878
879 #endif /* QUANT_1PASS_SUPPORTED */