home *** CD-ROM | disk | FTP | other *** search
/ Encyclopedia of Graphics File Formats Companion / GFF_CD.ISO / software / unix / jpeg / jpegv4a.tar / jquant1.c < prev    next >
C/C++ Source or Header  |  1993-01-25  |  23KB  |  618 lines

  1. /*
  2.  * jquant1.c
  3.  *
  4.  * Copyright (C) 1991, 1992, 1993, Thomas G. Lane.
  5.  * This file is part of the Independent JPEG Group's software.
  6.  * For conditions of distribution and use, see the accompanying README file.
  7.  *
  8.  * This file contains 1-pass color quantization (color mapping) routines.
  9.  * These routines are invoked via the methods color_quantize
  10.  * and color_quant_init/term.
  11.  */
  12.  
  13. #include "jinclude.h"
  14.  
  15. #ifdef QUANT_1PASS_SUPPORTED
  16.  
  17.  
  18. /*
  19.  * The main purpose of 1-pass quantization is to provide a fast, if not very
  20.  * high quality, colormapped output capability.  A 2-pass quantizer usually
  21.  * gives better visual quality; however, for quantized grayscale output this
  22.  * quantizer is perfectly adequate.  Dithering is highly recommended with this
  23.  * quantizer, though you can turn it off if you really want to.
  24.  *
  25.  * This implementation quantizes in the output colorspace.  This has a couple
  26.  * of disadvantages: each pixel must be individually color-converted, and if
  27.  * the color conversion includes gamma correction then quantization is done in
  28.  * a nonlinear space, which is less desirable.  The major advantage is that
  29.  * with the usual output color spaces (RGB, grayscale) an orthogonal grid of
  30.  * representative colors can be used, thus permitting the very simple and fast
  31.  * color lookup scheme used here.  The standard JPEG colorspace (YCbCr) cannot
  32.  * be effectively handled this way, because only about a quarter of an
  33.  * orthogonal grid would fall within the gamut of realizable colors.  Another
  34.  * advantage is that when the user wants quantized grayscale output from a
  35.  * color JPEG file, this quantizer can provide a high-quality result with no
  36.  * special hacking.
  37.  *
  38.  * The gamma-correction problem could be eliminated by adjusting the grid
  39.  * spacing to counteract the gamma correction applied by color_convert.
  40.  * At this writing, gamma correction is not implemented by jdcolor, so
  41.  * nothing is done here.
  42.  *
  43.  * In 1-pass quantization the colormap must be chosen in advance of seeing the
  44.  * image.  We use a map consisting of all combinations of Ncolors[i] color
  45.  * values for the i'th component.  The Ncolors[] values are chosen so that
  46.  * their product, the total number of colors, is no more than that requested.
  47.  * (In most cases, the product will be somewhat less.)
  48.  *
  49.  * Since the colormap is orthogonal, the representative value for each color
  50.  * component can be determined without considering the other components;
  51.  * then these indexes can be combined into a colormap index by a standard
  52.  * N-dimensional-array-subscript calculation.  Most of the arithmetic involved
  53.  * can be precalculated and stored in the lookup table colorindex[].
  54.  * colorindex[i][j] maps pixel value j in component i to the nearest
  55.  * representative value (grid plane) for that component; this index is
  56.  * multiplied by the array stride for component i, so that the
  57.  * index of the colormap entry closest to a given pixel value is just
  58.  *    sum( colorindex[component-number][pixel-component-value] )
  59.  * Aside from being fast, this scheme allows for variable spacing between
  60.  * representative values with no additional lookup cost.
  61.  */
  62.  
  63.  
  64. #define MAX_COMPONENTS 4    /* max components I can handle */
  65.  
  66. static JSAMPARRAY colormap;    /* The actual color map */
  67. /* colormap[i][j] = value of i'th color component for output pixel value j */
  68.  
  69. static JSAMPARRAY colorindex;    /* Precomputed mapping for speed */
  70. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  71.  * premultiplied as described above.  Since colormap indexes must fit into
  72.  * JSAMPLEs, the entries of this array will too.
  73.  */
  74.  
  75. static JSAMPARRAY input_buffer;    /* color conversion workspace */
  76. /* Since our input data is presented in the JPEG colorspace, we have to call
  77.  * color_convert to get it into the output colorspace.  input_buffer is a
  78.  * one-row-high workspace for the result of color_convert.
  79.  */
  80.  
  81.  
  82. /* Declarations for Floyd-Steinberg dithering.
  83.  *
  84.  * Errors are accumulated into the array fserrors[], at a resolution of
  85.  * 1/16th of a pixel count.  The error at a given pixel is propagated
  86.  * to its not-yet-processed neighbors using the standard F-S fractions,
  87.  *        ...    (here)    7/16
  88.  *        3/16    5/16    1/16
  89.  * We work left-to-right on even rows, right-to-left on odd rows.
  90.  *
  91.  * We can get away with a single array (holding one row's worth of errors)
  92.  * by using it to store the current row's errors at pixel columns not yet
  93.  * processed, but the next row's errors at columns already processed.  We
  94.  * need only a few extra variables to hold the errors immediately around the
  95.  * current column.  (If we are lucky, those variables are in registers, but
  96.  * even if not, they're probably cheaper to access than array elements are.)
  97.  *
  98.  * The fserrors[] array is indexed [component#][position].
  99.  * We provide (#columns + 2) entries per component; the extra entry at each
  100.  * end saves us from special-casing the first and last pixels.
  101.  *
  102.  * Note: on a wide image, we might not have enough room in a PC's near data
  103.  * segment to hold the error array; so it is allocated with alloc_medium.
  104.  */
  105.  
  106. #ifdef EIGHT_BIT_SAMPLES
  107. typedef INT16 FSERROR;        /* 16 bits should be enough */
  108. typedef int LOCFSERROR;        /* use 'int' for calculation temps */
  109. #else
  110. typedef INT32 FSERROR;        /* may need more than 16 bits */
  111. typedef INT32 LOCFSERROR;    /* be sure calculation temps are big enough */
  112. #endif
  113.  
  114. typedef FSERROR FAR *FSERRPTR;    /* pointer to error array (in FAR storage!) */
  115.  
  116. static FSERRPTR fserrors[MAX_COMPONENTS]; /* accumulated errors */
  117. static boolean on_odd_row;    /* flag to remember which row we are on */
  118.  
  119.  
  120. /*
  121.  * Policy-making subroutines for color_quant_init: these routines determine
  122.  * the colormap to be used.  The rest of the module only assumes that the
  123.  * colormap is orthogonal.
  124.  *
  125.  *  * select_ncolors decides how to divvy up the available colors
  126.  *    among the components.
  127.  *  * output_value defines the set of representative values for a component.
  128.  *  * largest_input_value defines the mapping from input values to
  129.  *    representative values for a component.
  130.  * Note that the latter two routines may impose different policies for
  131.  * different components, though this is not currently done.
  132.  */
  133.  
  134.  
  135. LOCAL int
  136. select_ncolors (decompress_info_ptr cinfo, int Ncolors[])
  137. /* Determine allocation of desired colors to components, */
  138. /* and fill in Ncolors[] array to indicate choice. */
  139. /* Return value is total number of colors (product of Ncolors[] values). */
  140. {
  141.   int nc = cinfo->color_out_comps; /* number of color components */
  142.   int max_colors = cinfo->desired_number_of_colors;
  143.   int total_colors, iroot, i;
  144.   long temp;
  145.   boolean changed;
  146.  
  147.   /* We can allocate at least the nc'th root of max_colors per component. */
  148.   /* Compute floor(nc'th root of max_colors). */
  149.   iroot = 1;
  150.   do {
  151.     iroot++;
  152.     temp = iroot;        /* set temp = iroot ** nc */
  153.     for (i = 1; i < nc; i++)
  154.       temp *= iroot;
  155.   } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  156.   iroot--;            /* now iroot = floor(root) */
  157.  
  158.   /* Must have at least 2 color values per component */
  159.   if (iroot < 2)
  160.     ERREXIT1(cinfo->emethods, "Cannot quantize to fewer than %d colors",
  161.          (int) temp);
  162.  
  163.   if (cinfo->out_color_space == CS_RGB && nc == 3) {
  164.     /* We provide a special policy for quantizing in RGB space.
  165.      * If 256 colors are requested, we allocate 8 red, 8 green, 4 blue levels;
  166.      * this corresponds to the common 3/3/2-bit scheme.  For other totals,
  167.      * the counts are set so that the number of colors allocated to each
  168.      * component are roughly in the proportion R 3, G 4, B 2.
  169.      * For low color counts, it's easier to hardwire the optimal choices
  170.      * than try to tweak the algorithm to generate them.
  171.      */
  172.     if (max_colors == 256) {
  173.       Ncolors[0] = 8;  Ncolors[1] = 8;  Ncolors[2] = 4;
  174.       return 256;
  175.     }
  176.     if (max_colors < 12) {
  177.       /* Fixed mapping for 8 colors */
  178.       Ncolors[0] = Ncolors[1] = Ncolors[2] = 2;
  179.     } else if (max_colors < 18) {
  180.       /* Fixed mapping for 12 colors */
  181.       Ncolors[0] = 2;  Ncolors[1] = 3;  Ncolors[2] = 2;
  182.     } else if (max_colors < 24) {
  183.       /* Fixed mapping for 18 colors */
  184.       Ncolors[0] = 3;  Ncolors[1] = 3;  Ncolors[2] = 2;
  185.     } else if (max_colors < 27) {
  186.       /* Fixed mapping for 24 colors */
  187.       Ncolors[0] = 3;  Ncolors[1] = 4;  Ncolors[2] = 2;
  188.     } else if (max_colors < 36) {
  189.       /* Fixed mapping for 27 colors */
  190.       Ncolors[0] = 3;  Ncolors[1] = 3;  Ncolors[2] = 3;
  191.     } else {
  192.       /* these weights are readily derived with a little algebra */
  193.       Ncolors[0] = (iroot * 266) >> 8; /* R weight is 1.0400 */
  194.       Ncolors[1] = (iroot * 355) >> 8; /* G weight is 1.3867 */
  195.       Ncolors[2] = (iroot * 177) >> 8; /* B weight is 0.6934 */
  196.     }
  197.     total_colors = Ncolors[0] * Ncolors[1] * Ncolors[2];
  198.     /* The above computation produces "floor" values, so we may be able to
  199.      * increment the count for one or more components without exceeding
  200.      * max_colors.  We try in the order B, G, R.
  201.      */
  202.     do {
  203.       changed = FALSE;
  204.       for (i = 2; i >= 0; i--) {
  205.     /* calculate new total_colors if Ncolors[i] is incremented */
  206.     temp = total_colors / Ncolors[i];
  207.     temp *= Ncolors[i]+1;    /* done in long arith to avoid oflo */
  208.     if (temp <= (long) max_colors) {
  209.       Ncolors[i]++;        /* OK, apply the increment */
  210.       total_colors = (int) temp;
  211.       changed = TRUE;
  212.     }
  213.       }
  214.     } while (changed);        /* loop until no increment is possible */
  215.   } else {
  216.     /* For any colorspace besides RGB, treat all the components equally. */
  217.  
  218.     /* Initialize to iroot color values for each component */
  219.     total_colors = 1;
  220.     for (i = 0; i < nc; i++) {
  221.       Ncolors[i] = iroot;
  222.       total_colors *= iroot;
  223.     }
  224.     /* We may be able to increment the count for one or more components without
  225.      * exceeding max_colors, though we know not all can be incremented.
  226.      */
  227.     for (i = 0; i < nc; i++) {
  228.       /* calculate new total_colors if Ncolors[i] is incremented */
  229.       temp = total_colors / Ncolors[i];
  230.       temp *= Ncolors[i]+1;    /* done in long arith to avoid oflo */
  231.       if (temp > (long) max_colors)
  232.     break;            /* won't fit, done */
  233.       Ncolors[i]++;        /* OK, apply the increment */
  234.       total_colors = (int) temp;
  235.     }
  236.   }
  237.  
  238.   return total_colors;
  239. }
  240.  
  241.  
  242. LOCAL int
  243. output_value (decompress_info_ptr cinfo, int ci, int j, int maxj)
  244. /* Return j'th output value, where j will range from 0 to maxj */
  245. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  246. {
  247.   /* We always provide values 0 and MAXJSAMPLE for each component;
  248.    * any additional values are equally spaced between these limits.
  249.    * (Forcing the upper and lower values to the limits ensures that
  250.    * dithering can't produce a color outside the selected gamut.)
  251.    */
  252.   return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  253. }
  254.  
  255.  
  256. LOCAL int
  257. largest_input_value (decompress_info_ptr cinfo, int ci, int j, int maxj)
  258. /* Return largest input value that should map to j'th output value */
  259. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  260. {
  261.   /* Breakpoints are halfway between values returned by output_value */
  262.   return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  263. }
  264.  
  265.  
  266. /*
  267.  * Initialize for one-pass color quantization.
  268.  */
  269.  
  270. METHODDEF void
  271. color_quant_init (decompress_info_ptr cinfo)
  272. {
  273.   int total_colors;        /* Number of distinct output colors */
  274.   int Ncolors[MAX_COMPONENTS];    /* # of values alloced to each component */
  275.   int i,j,k, nci, blksize, blkdist, ptr, val;
  276.  
  277.   /* Make sure my internal arrays won't overflow */
  278.   if (cinfo->num_components > MAX_COMPONENTS ||
  279.       cinfo->color_out_comps > MAX_COMPONENTS)
  280.     ERREXIT1(cinfo->emethods, "Cannot quantize more than %d color components",
  281.          MAX_COMPONENTS);
  282.   /* Make sure colormap indexes can be represented by JSAMPLEs */
  283.   if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  284.     ERREXIT1(cinfo->emethods, "Cannot request more than %d quantized colors",
  285.          MAXJSAMPLE+1);
  286.  
  287.   /* Select number of colors for each component */
  288.   total_colors = select_ncolors(cinfo, Ncolors);
  289.  
  290.   /* Report selected color counts */
  291.   if (cinfo->color_out_comps == 3)
  292.     TRACEMS4(cinfo->emethods, 1, "Quantizing to %d = %d*%d*%d colors",
  293.          total_colors, Ncolors[0], Ncolors[1], Ncolors[2]);
  294.   else
  295.     TRACEMS1(cinfo->emethods, 1, "Quantizing to %d colors", total_colors);
  296.  
  297.   /* Allocate and fill in the colormap and color index. */
  298.   /* The colors are ordered in the map in standard row-major order, */
  299.   /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  300.  
  301.   colormap = (*cinfo->emethods->alloc_small_sarray)
  302.         ((long) total_colors, (long) cinfo->color_out_comps);
  303.   colorindex = (*cinfo->emethods->alloc_small_sarray)
  304.         ((long) (MAXJSAMPLE+1), (long) cinfo->color_out_comps);
  305.  
  306.   /* blksize is number of adjacent repeated entries for a component */
  307.   /* blkdist is distance between groups of identical entries for a component */
  308.   blkdist = total_colors;
  309.  
  310.   for (i = 0; i < cinfo->color_out_comps; i++) {
  311.     /* fill in colormap entries for i'th color component */
  312.     nci = Ncolors[i];        /* # of distinct values for this color */
  313.     blksize = blkdist / nci;
  314.     for (j = 0; j < nci; j++) {
  315.       /* Compute j'th output value (out of nci) for component */
  316.       val = output_value(cinfo, i, j, nci-1);
  317.       /* Fill in all colormap entries that have this value of this component */
  318.       for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  319.     /* fill in blksize entries beginning at ptr */
  320.     for (k = 0; k < blksize; k++)
  321.       colormap[i][ptr+k] = (JSAMPLE) val;
  322.       }
  323.     }
  324.     blkdist = blksize;        /* blksize of this color is blkdist of next */
  325.  
  326.     /* fill in colorindex entries for i'th color component */
  327.     /* in loop, val = index of current output value, */
  328.     /* and k = largest j that maps to current val */
  329.     val = 0;
  330.     k = largest_input_value(cinfo, i, 0, nci-1);
  331.     for (j = 0; j <= MAXJSAMPLE; j++) {
  332.       while (j > k)        /* advance val if past boundary */
  333.     k = largest_input_value(cinfo, i, ++val, nci-1);
  334.       /* premultiply so that no multiplication needed in main processing */
  335.       colorindex[i][j] = (JSAMPLE) (val * blksize);
  336.     }
  337.   }
  338.  
  339.   /* Pass the colormap to the output module. */
  340.   /* NB: the output module may continue to use the colormap until shutdown. */
  341.   cinfo->colormap = colormap;
  342.   cinfo->actual_number_of_colors = total_colors;
  343.   (*cinfo->methods->put_color_map) (cinfo, total_colors, colormap);
  344.  
  345.   /* Allocate workspace to hold one row of color-converted data */
  346.   input_buffer = (*cinfo->emethods->alloc_small_sarray)
  347.             (cinfo->image_width, (long) cinfo->color_out_comps);
  348.  
  349.   /* Allocate Floyd-Steinberg workspace if necessary */
  350.   if (cinfo->use_dithering) {
  351.     size_t arraysize = (size_t) ((cinfo->image_width + 2L) * SIZEOF(FSERROR));
  352.  
  353.     for (i = 0; i < cinfo->color_out_comps; i++) {
  354.       fserrors[i] = (FSERRPTR) (*cinfo->emethods->alloc_medium) (arraysize);
  355.       /* Initialize the propagated errors to zero. */
  356.       jzero_far((void FAR *) fserrors[i], arraysize);
  357.     }
  358.     on_odd_row = FALSE;
  359.   }
  360. }
  361.  
  362.  
  363. /*
  364.  * Subroutines for color conversion methods.
  365.  */
  366.  
  367. LOCAL void
  368. do_color_conversion (decompress_info_ptr cinfo, JSAMPIMAGE input_data, int row)
  369. /* Convert the indicated row of the input data into output colorspace */
  370. /* in input_buffer.  This requires a little trickery since color_convert */
  371. /* expects to deal with 3-D arrays; fortunately we can fake it out */
  372. /* at fairly low cost. */
  373. {
  374.   short ci;
  375.   JSAMPARRAY input_hack[MAX_COMPONENTS];
  376.   JSAMPARRAY output_hack[MAX_COMPONENTS];
  377.  
  378.   /* create JSAMPIMAGE pointing at specified row of input_data */
  379.   for (ci = 0; ci < cinfo->num_components; ci++)
  380.     input_hack[ci] = input_data[ci] + row;
  381.   /* Create JSAMPIMAGE pointing at input_buffer */
  382.   for (ci = 0; ci < cinfo->color_out_comps; ci++)
  383.     output_hack[ci] = &(input_buffer[ci]);
  384.  
  385.   (*cinfo->methods->color_convert) (cinfo, 1, cinfo->image_width,
  386.                     input_hack, output_hack);
  387. }
  388.  
  389.  
  390. /*
  391.  * Map some rows of pixels to the output colormapped representation.
  392.  */
  393.  
  394. METHODDEF void
  395. color_quantize (decompress_info_ptr cinfo, int num_rows,
  396.         JSAMPIMAGE input_data, JSAMPARRAY output_data)
  397. /* General case, no dithering */
  398. {
  399.   register int pixcode, ci;
  400.   register JSAMPROW ptrout;
  401.   register long col;
  402.   int row;
  403.   long width = cinfo->image_width;
  404.   register int nc = cinfo->color_out_comps;  
  405.  
  406.   for (row = 0; row < num_rows; row++) {
  407.     do_color_conversion(cinfo, input_data, row);
  408.     ptrout = output_data[row];
  409.     for (col = 0; col < width; col++) {
  410.       pixcode = 0;
  411.       for (ci = 0; ci < nc; ci++) {
  412.     pixcode += GETJSAMPLE(colorindex[ci]
  413.                   [GETJSAMPLE(input_buffer[ci][col])]);
  414.       }
  415.       *ptrout++ = (JSAMPLE) pixcode;
  416.     }
  417.   }
  418. }
  419.  
  420.  
  421. METHODDEF void
  422. color_quantize3 (decompress_info_ptr cinfo, int num_rows,
  423.          JSAMPIMAGE input_data, JSAMPARRAY output_data)
  424. /* Fast path for color_out_comps==3, no dithering */
  425. {
  426.   register int pixcode;
  427.   register JSAMPROW ptr0, ptr1, ptr2, ptrout;
  428.   register long col;
  429.   int row;
  430.   JSAMPROW colorindex0 = colorindex[0];
  431.   JSAMPROW colorindex1 = colorindex[1];
  432.   JSAMPROW colorindex2 = colorindex[2];
  433.   long width = cinfo->image_width;
  434.  
  435.   for (row = 0; row < num_rows; row++) {
  436.     do_color_conversion(cinfo, input_data, row);
  437.     ptr0 = input_buffer[0];
  438.     ptr1 = input_buffer[1];
  439.     ptr2 = input_buffer[2];
  440.     ptrout = output_data[row];
  441.     for (col = width; col > 0; col--) {
  442.       pixcode  = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptr0++)]);
  443.       pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptr1++)]);
  444.       pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptr2++)]);
  445.       *ptrout++ = (JSAMPLE) pixcode;
  446.     }
  447.   }
  448. }
  449.  
  450.  
  451. METHODDEF void
  452. color_quantize_dither (decompress_info_ptr cinfo, int num_rows,
  453.                JSAMPIMAGE input_data, JSAMPARRAY output_data)
  454. /* General case, with Floyd-Steinberg dithering */
  455. {
  456.   register LOCFSERROR cur;    /* current error or pixel value */
  457.   LOCFSERROR belowerr;        /* error for pixel below cur */
  458.   LOCFSERROR bpreverr;        /* error for below/prev col */
  459.   LOCFSERROR bnexterr;        /* error for below/next col */
  460.   LOCFSERROR delta;
  461.   register FSERRPTR errorptr;    /* => fserrors[] at column before current */
  462.   register JSAMPROW input_ptr;
  463.   register JSAMPROW output_ptr;
  464.   JSAMPROW colorindex_ci;
  465.   JSAMPROW colormap_ci;
  466.   int pixcode;
  467.   int dir;            /* 1 for left-to-right, -1 for right-to-left */
  468.   int ci;
  469.   int nc = cinfo->color_out_comps;
  470.   int row;
  471.   long col_counter;
  472.   long width = cinfo->image_width;
  473.   JSAMPLE *range_limit = cinfo->sample_range_limit;
  474.   SHIFT_TEMPS
  475.  
  476.   for (row = 0; row < num_rows; row++) {
  477.     do_color_conversion(cinfo, input_data, row);
  478.     /* Initialize output values to 0 so can process components separately */
  479.     jzero_far((void FAR *) output_data[row],
  480.           (size_t) (width * SIZEOF(JSAMPLE)));
  481.     for (ci = 0; ci < nc; ci++) {
  482.       input_ptr = input_buffer[ci];
  483.       output_ptr = output_data[row];
  484.       if (on_odd_row) {
  485.     /* work right to left in this row */
  486.     input_ptr += width - 1;    /* so point to rightmost pixel */
  487.     output_ptr += width - 1;
  488.     dir = -1;
  489.     errorptr = fserrors[ci] + (width+1); /* point to entry after last column */
  490.       } else {
  491.     /* work left to right in this row */
  492.     dir = 1;
  493.     errorptr = fserrors[ci]; /* point to entry before first real column */
  494.       }
  495.       colorindex_ci = colorindex[ci];
  496.       colormap_ci = colormap[ci];
  497.       /* Preset error values: no error propagated to first pixel from left */
  498.       cur = 0;
  499.       /* and no error propagated to row below yet */
  500.       belowerr = bpreverr = 0;
  501.  
  502.       for (col_counter = width; col_counter > 0; col_counter--) {
  503.     /* cur holds the error propagated from the previous pixel on the
  504.      * current line.  Add the error propagated from the previous line
  505.      * to form the complete error correction term for this pixel, and
  506.      * round the error term (which is expressed * 16) to an integer.
  507.      * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  508.      * for either sign of the error value.
  509.      * Note: errorptr points to *previous* column's array entry.
  510.      */
  511.     cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  512.     /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  513.      * The maximum error is +- MAXJSAMPLE; this sets the required size
  514.      * of the range_limit array.
  515.      */
  516.     cur += GETJSAMPLE(*input_ptr);
  517.     cur = GETJSAMPLE(range_limit[cur]);
  518.     /* Select output value, accumulate into output code for this pixel */
  519.     pixcode = GETJSAMPLE(colorindex_ci[cur]);
  520.     *output_ptr += (JSAMPLE) pixcode;
  521.     /* Compute actual representation error at this pixel */
  522.     /* Note: we can do this even though we don't have the final */
  523.     /* pixel code, because the colormap is orthogonal. */
  524.     cur -= GETJSAMPLE(colormap_ci[pixcode]);
  525.     /* Compute error fractions to be propagated to adjacent pixels.
  526.      * Add these into the running sums, and simultaneously shift the
  527.      * next-line error sums left by 1 column.
  528.      */
  529.     bnexterr = cur;
  530.     delta = cur * 2;
  531.     cur += delta;        /* form error * 3 */
  532.     errorptr[0] = (FSERROR) (bpreverr + cur);
  533.     cur += delta;        /* form error * 5 */
  534.     bpreverr = belowerr + cur;
  535.     belowerr = bnexterr;
  536.     cur += delta;        /* form error * 7 */
  537.     /* At this point cur contains the 7/16 error value to be propagated
  538.      * to the next pixel on the current line, and all the errors for the
  539.      * next line have been shifted over. We are therefore ready to move on.
  540.      */
  541.     input_ptr += dir;    /* advance input ptr to next column */
  542.     output_ptr += dir;    /* advance output ptr to next column */
  543.     errorptr += dir;    /* advance errorptr to current column */
  544.       }
  545.       /* Post-loop cleanup: we must unload the final error value into the
  546.        * final fserrors[] entry.  Note we need not unload belowerr because
  547.        * it is for the dummy column before or after the actual array.
  548.        */
  549.       errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  550.     }
  551.     on_odd_row = (on_odd_row ? FALSE : TRUE);
  552.   }
  553. }
  554.  
  555.  
  556. /*
  557.  * Finish up at the end of the file.
  558.  */
  559.  
  560. METHODDEF void
  561. color_quant_term (decompress_info_ptr cinfo)
  562. {
  563.   /* no work (we let free_all release the workspace) */
  564.   /* Note that we *mustn't* free the colormap before free_all, */
  565.   /* since output module may use it! */
  566. }
  567.  
  568.  
  569. /*
  570.  * Prescan some rows of pixels.
  571.  * Not used in one-pass case.
  572.  */
  573.  
  574. METHODDEF void
  575. color_quant_prescan (decompress_info_ptr cinfo, int num_rows,
  576.              JSAMPIMAGE image_data, JSAMPARRAY workspace)
  577. {
  578.   ERREXIT(cinfo->emethods, "Should not get here!");
  579. }
  580.  
  581.  
  582. /*
  583.  * Do two-pass quantization.
  584.  * Not used in one-pass case.
  585.  */
  586.  
  587. METHODDEF void
  588. color_quant_doit (decompress_info_ptr cinfo, quantize_caller_ptr source_method)
  589. {
  590.   ERREXIT(cinfo->emethods, "Should not get here!");
  591. }
  592.  
  593.  
  594. /*
  595.  * The method selection routine for 1-pass color quantization.
  596.  */
  597.  
  598. GLOBAL void
  599. jsel1quantize (decompress_info_ptr cinfo)
  600. {
  601.   if (! cinfo->two_pass_quantize) {
  602.     cinfo->methods->color_quant_init = color_quant_init;
  603.     if (cinfo->use_dithering) {
  604.       cinfo->methods->color_quantize = color_quantize_dither;
  605.     } else {
  606.       if (cinfo->color_out_comps == 3)
  607.     cinfo->methods->color_quantize = color_quantize3;
  608.       else
  609.     cinfo->methods->color_quantize = color_quantize;
  610.     }
  611.     cinfo->methods->color_quant_prescan = color_quant_prescan;
  612.     cinfo->methods->color_quant_doit = color_quant_doit;
  613.     cinfo->methods->color_quant_term = color_quant_term;
  614.   }
  615. }
  616.  
  617. #endif /* QUANT_1PASS_SUPPORTED */
  618.