home *** CD-ROM | disk | FTP | other *** search
/ High Voltage Shareware / high1.zip / high1 / DIR2 / DVPG30FS.ZIP / JQUANT1.C < prev    next >
C/C++ Source or Header  |  1993-11-28  |  24KB  |  628 lines

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