home *** CD-ROM | disk | FTP | other *** search
/ Graphics 16,000 / graphics-16000.iso / msdos / viewers / hv12 / src / jquant2.c < prev    next >
C/C++ Source or Header  |  1992-07-17  |  43KB  |  1,175 lines

  1. /*
  2.  * jquant2.c
  3.  *
  4.  * Copyright (C) 1991, 1992, 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 2-pass color quantization (color mapping) routines.
  9.  * These routines are invoked via the methods color_quant_prescan,
  10.  * color_quant_doit, and color_quant_init/term.
  11.  */
  12.  
  13. #include "jinclude.h"
  14. extern unsigned char *range_limit;
  15.  
  16. #ifdef QUANT_2PASS_SUPPORTED
  17.  
  18.  
  19. /*
  20.  * This module implements the well-known Heckbert paradigm for color
  21.  * quantization.  Most of the ideas used here can be traced back to
  22.  * Heckbert's seminal paper
  23.  *   Heckbert, Paul.  "Color Image Quantization for Frame Buffer Display",
  24.  *   Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  25.  *
  26.  * In the first pass over the image, we accumulate a histogram showing the
  27.  * usage count of each possible color.  (To keep the histogram to a reasonable
  28.  * size, we reduce the precision of the input; typical practice is to retain
  29.  * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  30.  * in the same histogram cell.)  Next, the color-selection step begins with a
  31.  * box representing the whole color space, and repeatedly splits the "largest"
  32.  * remaining box until we have as many boxes as desired colors.  Then the mean
  33.  * color in each remaining box becomes one of the possible output colors.
  34.  * The second pass over the image maps each input pixel to the closest output
  35.  * color (optionally after applying a Floyd-Steinberg dithering correction).
  36.  * This mapping is logically trivial, but making it go fast enough requires
  37.  * considerable care.
  38.  *
  39.  * Heckbert-style quantizers vary a good deal in their policies for choosing
  40.  * the "largest" box and deciding where to cut it.  The particular policies
  41.  * used here have proved out well in experimental comparisons, but better ones
  42.  * may yet be found.
  43.  *
  44.  * The most significant difference between this quantizer and others is that
  45.  * this one is intended to operate in YCbCr colorspace, rather than RGB space
  46.  * as is usually done.  Actually we work in scaled YCbCr colorspace, where
  47.  * Y distances are inflated by a factor of 2 relative to Cb or Cr distances.
  48.  * The empirical evidence is that distances in this space correspond to
  49.  * perceptual color differences more closely than do distances in RGB space;
  50.  * and working in this space is inexpensive within a JPEG decompressor, since
  51.  * the input data is already in YCbCr form.  (We could transform to an even
  52.  * more perceptually linear space such as Lab or Luv, but that is very slow
  53.  * and doesn't yield much better results than scaled YCbCr.)
  54.  */
  55.  
  56. #define Y_SCALE 2        /* scale Y distances up by this much */
  57.  
  58. #define MAXNUMCOLORS  (MAXJSAMPLE+1) /* maximum size of colormap */
  59.  
  60.  
  61. /*
  62.  * First we have the histogram data structure and routines for creating it.
  63.  *
  64.  * For work in YCbCr space, it is useful to keep more precision for Y than
  65.  * for Cb or Cr.  We recommend keeping 6 bits for Y and 5 bits each for Cb/Cr.
  66.  * If you have plenty of memory and cycles, 6 bits all around gives marginally
  67.  * better results; if you are short of memory, 5 bits all around will save
  68.  * some space but degrade the results.
  69.  * To maintain a fully accurate histogram, we'd need to allocate a "long"
  70.  * (preferably unsigned long) for each cell.  In practice this is overkill;
  71.  * we can get by with 16 bits per cell.  Few of the cell counts will overflow,
  72.  * and clamping those that do overflow to the maximum value will give close-
  73.  * enough results.  This reduces the recommended histogram size from 256Kb
  74.  * to 128Kb, which is a useful savings on PC-class machines.
  75.  * (In the second pass the histogram space is re-used for pixel mapping data;
  76.  * in that capacity, each cell must be able to store zero to the number of
  77.  * desired colors.  16 bits/cell is plenty for that too.)
  78.  * Since the JPEG code is intended to run in small memory model on 80x86
  79.  * machines, we can't just allocate the histogram in one chunk.  Instead
  80.  * of a true 3-D array, we use a row of pointers to 2-D arrays.  Each
  81.  * pointer corresponds to a Y value (typically 2^6 = 64 pointers) and
  82.  * each 2-D array has 2^5^2 = 1024 or 2^6^2 = 4096 entries.  Note that
  83.  * on 80x86 machines, the pointer row is in near memory but the actual
  84.  * arrays are in far memory (same arrangement as we use for image arrays).
  85.  */
  86.  
  87. #ifndef HIST_Y_BITS        /* so you can override from Makefile */
  88. #define HIST_Y_BITS  6        /* bits of precision in Y histogram */
  89. #endif
  90. #ifndef HIST_C_BITS        /* so you can override from Makefile */
  91. #define HIST_C_BITS  5      /* bits of precision in Cb/Cr histogram */
  92. #endif
  93.  
  94. #define HIST_Y_ELEMS  (1<<HIST_Y_BITS) /* # of elements along histogram axes */
  95. #define HIST_C_ELEMS  (1<<HIST_C_BITS)
  96.  
  97. /* These are the amounts to shift an input value to get a histogram index.
  98.  * For a combination 8/12 bit implementation, would need variables here...
  99.  */
  100.  
  101. #define Y_SHIFT  (BITS_IN_JSAMPLE-HIST_Y_BITS)
  102. #define C_SHIFT  (BITS_IN_JSAMPLE-HIST_C_BITS)
  103.  
  104.  
  105. typedef unsigned long histcell;    /* histogram cell; MUST be an unsigned type */
  106.  
  107. typedef histcell FAR * histptr;    /* for pointers to histogram cells */
  108.  
  109. typedef histcell hist1d[HIST_C_ELEMS]; /* typedefs for the array */
  110. typedef hist1d FAR * hist2d;    /* type for the Y-level pointers */
  111. typedef hist2d * hist3d;    /* type for top-level pointer */
  112.  
  113. static hist3d histogram;    /* pointer to the histogram */
  114.  
  115.  
  116. /*
  117.  * Prescan some rows of pixels.
  118.  * In this module the prescan simply updates the histogram, which has been
  119.  * initialized to zeroes by color_quant_init.
  120.  * Note: workspace is probably not useful for this routine, but it is passed
  121.  * anyway to allow some code sharing within the pipeline controller.
  122.  */
  123.  
  124. METHODDEF void
  125. color_quant_prescan (decompress_info_ptr cinfo, int num_rows,
  126.              JSAMPIMAGE image_data, JSAMPARRAY workspace)
  127. {
  128.   register JSAMPROW ptr0, ptr1, ptr2;
  129.   register histptr histp;
  130.   register int c0, c1, c2;
  131.   int row;
  132.   long col;
  133.   long width = cinfo->image_width;
  134.  
  135.   for (row = 0; row < num_rows; row++) {
  136.     ptr0 = image_data[0][row];
  137.     ptr1 = image_data[1][row];
  138.     ptr2 = image_data[2][row];
  139.     for (col = width; col > 0; col--) {
  140.       /* get pixel value and index into the histogram */
  141.       c0 = GETJSAMPLE(*ptr0++) >> Y_SHIFT;
  142.       c1 = GETJSAMPLE(*ptr1++) >> C_SHIFT;
  143.       c2 = GETJSAMPLE(*ptr2++) >> C_SHIFT;
  144.       histogram[c0][c1][c2]++;
  145.     }
  146.   }
  147. }
  148.  
  149.  
  150. /*
  151.  * Now we have the really interesting routines: selection of a colormap
  152.  * given the completed histogram.
  153.  * These routines work with a list of "boxes", each representing a rectangular
  154.  * subset of the input color space (to histogram precision).
  155.  */
  156.  
  157. typedef struct {
  158.     /* The bounds of the box (inclusive); expressed as histogram indexes */
  159.     int c0min, c0max;
  160.     int c1min, c1max;
  161.     int c2min, c2max;
  162.     /* The number of nonzero histogram cells within this box */
  163.     long colorcount;
  164.       } box;
  165. typedef box * boxptr;
  166.  
  167. static boxptr boxlist;        /* array with room for desired # of boxes */
  168. static int numboxes;        /* number of boxes currently in boxlist */
  169.  
  170. static JSAMPARRAY my_colormap;    /* the finished colormap (in YCbCr space) */
  171.  
  172.  
  173. LOCAL boxptr
  174. find_biggest_color_pop (void)
  175. /* Find the splittable box with the largest color population */
  176. /* Returns NULL if no splittable boxes remain */
  177. {
  178.   register boxptr boxp;
  179.   register int i;
  180.   register long max = 0;
  181.   boxptr which = NULL;
  182.   
  183.   for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  184.     if (boxp->colorcount > max) {
  185.       if (boxp->c0max > boxp->c0min || boxp->c1max > boxp->c1min ||
  186.       boxp->c2max > boxp->c2min) {
  187.     which = boxp;
  188.     max = boxp->colorcount;
  189.       }
  190.     }
  191.   }
  192.   return which;
  193. }
  194.  
  195.  
  196. LOCAL boxptr
  197. find_biggest_volume (void)
  198. /* Find the splittable box with the largest (scaled) volume */
  199. /* Returns NULL if no splittable boxes remain */
  200. {
  201.   register boxptr boxp;
  202.   register int i;
  203.   register INT32 max = 0;
  204.   register INT32 norm, c0,c1,c2;
  205.   boxptr which = NULL;
  206.   
  207.   /* We use 2-norm rather than real volume here.
  208.    * Some care is needed since the differences are expressed in
  209.    * histogram-cell units; if HIST_Y_BITS != HIST_C_BITS, we have to
  210.    * adjust the scaling to get the proper scaled-YCbCr-space distance.
  211.    * This code won't work right if HIST_Y_BITS < HIST_C_BITS,
  212.    * but that shouldn't ever be true.
  213.    * Note norm > 0 iff box is splittable, so need not check separately.
  214.    */
  215.   
  216.   for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  217.     c0 = (boxp->c0max - boxp->c0min) * Y_SCALE;
  218.     c1 = (boxp->c1max - boxp->c1min)  << (HIST_Y_BITS-HIST_C_BITS) ;
  219.     c2 = (boxp->c2max - boxp->c2min)  << (HIST_Y_BITS-HIST_C_BITS) ;
  220.     norm = c0*c0 + c1*c1 + c2*c2;
  221.     if (norm > max) {
  222.       which = boxp;
  223.       max = norm;
  224.     }
  225.   }
  226.   return which;
  227. }
  228.  
  229.  
  230. LOCAL void
  231. update_box (boxptr boxp)
  232. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  233. /* and recompute its population */
  234. {
  235.   histptr histp;
  236.   int c0,c1,c2;
  237.   int c0min,c0max,c1min,c1max,c2min,c2max;
  238.   long ccount;
  239.   
  240.   c0min = boxp->c0min;  c0max = boxp->c0max;
  241.   c1min = boxp->c1min;  c1max = boxp->c1max;                         
  242.   c2min = boxp->c2min;  c2max = boxp->c2max;
  243.   
  244.   if (c0max > c0min)
  245.     for (c0 = c0min; c0 <= c0max; c0++)
  246.       for (c1 = c1min; c1 <= c1max; c1++) {
  247.     histp = & histogram[c0][c1][c2min];
  248.     for (c2 = c2min; c2 <= c2max; c2++)
  249.       if (*histp++ != 0) {
  250.         boxp->c0min = c0min = c0;
  251.         goto have_c0min;
  252.       }
  253.       }
  254.  have_c0min:
  255.   if (c0max > c0min)
  256.     for (c0 = c0max; c0 >= c0min; c0--)
  257.       for (c1 = c1min; c1 <= c1max; c1++) {
  258.     histp = & histogram[c0][c1][c2min];
  259.     for (c2 = c2min; c2 <= c2max; c2++)
  260.       if (*histp++ != 0) {
  261.         boxp->c0max = c0max = c0;
  262.         goto have_c0max;
  263.       }
  264.       }
  265.  have_c0max:
  266.   if (c1max > c1min)
  267.     for (c1 = c1min; c1 <= c1max; c1++)
  268.       for (c0 = c0min; c0 <= c0max; c0++) {
  269.     histp = & histogram[c0][c1][c2min];
  270.     for (c2 = c2min; c2 <= c2max; c2++)
  271.       if (*histp++ != 0) {
  272.         boxp->c1min = c1min = c1;
  273.         goto have_c1min;
  274.       }
  275.       }
  276.  have_c1min:
  277.   if (c1max > c1min)
  278.     for (c1 = c1max; c1 >= c1min; c1--)
  279.       for (c0 = c0min; c0 <= c0max; c0++) {
  280.     histp = & histogram[c0][c1][c2min];
  281.     for (c2 = c2min; c2 <= c2max; c2++)
  282.       if (*histp++ != 0) {
  283.         boxp->c1max = c1max = c1;
  284.         goto have_c1max;
  285.       }
  286.       }
  287.  have_c1max:
  288.   if (c2max > c2min)
  289.     for (c2 = c2min; c2 <= c2max; c2++)
  290.       for (c0 = c0min; c0 <= c0max; c0++) {
  291.     histp = & histogram[c0][c1min][c2];
  292.     for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C_ELEMS)
  293.       if (*histp != 0) {
  294.         boxp->c2min = c2min = c2;
  295.         goto have_c2min;
  296.       }
  297.       }
  298.  have_c2min:
  299.   if (c2max > c2min)
  300.     for (c2 = c2max; c2 >= c2min; c2--)
  301.       for (c0 = c0min; c0 <= c0max; c0++) {
  302.     histp = & histogram[c0][c1min][c2];
  303.     for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C_ELEMS)
  304.       if (*histp != 0) {
  305.         boxp->c2max = c2max = c2;
  306.         goto have_c2max;
  307.       }
  308.       }
  309.  have_c2max:
  310.   
  311.   /* Now scan remaining volume of box and compute population */
  312.   ccount = 0;
  313.   for (c0 = c0min; c0 <= c0max; c0++)
  314.     for (c1 = c1min; c1 <= c1max; c1++) {
  315.       histp = & histogram[c0][c1][c2min];
  316.       for (c2 = c2min; c2 <= c2max; c2++, histp++)
  317.     if (*histp != 0) {
  318.       ccount++;
  319.     }
  320.     }
  321.   boxp->colorcount = ccount;
  322. }
  323.  
  324.  
  325. LOCAL void
  326. median_cut (int desired_colors)
  327. /* Repeatedly select and split the largest box until we have enough boxes */
  328. {
  329.   int n,lb;
  330.   int c0,c1,c2,cmax;
  331.   register boxptr b1,b2;
  332.  
  333.   while (numboxes < desired_colors) {
  334.     /* Select box to split */
  335.     /* Current algorithm: by population for first half, then by volume */
  336.     if (numboxes*2 <= desired_colors) {
  337.       b1 = find_biggest_color_pop();
  338.     } else {
  339.       b1 = find_biggest_volume();
  340.     }
  341.     if (b1 == NULL)        /* no splittable boxes left! */
  342.       break;
  343.     b2 = &boxlist[numboxes];    /* where new box will go */
  344.     /* Copy the color bounds to the new box. */
  345.     b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  346.     b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  347.     /* Choose which axis to split the box on.
  348.      * Current algorithm: longest scaled axis.
  349.      * See notes in find_biggest_volume about scaling...
  350.      */
  351.     c0 = (b1->c0max - b1->c0min) * Y_SCALE;
  352.     c1 = (b1->c1max - b1->c1min) << (HIST_Y_BITS-HIST_C_BITS);
  353.     c2 = (b1->c2max - b1->c2min) << (HIST_Y_BITS-HIST_C_BITS);
  354.     cmax = c0; n = 0;
  355.     if (c1 > cmax) { cmax = c1; n = 1; }
  356.     if (c2 > cmax) { n = 2; }
  357.     /* Choose split point along selected axis, and update box bounds.
  358.      * Current algorithm: split at halfway point.
  359.      * (Since the box has been shrunk to minimum volume,
  360.      * any split will produce two nonempty subboxes.)
  361.      * Note that lb value is max for lower box, so must be < old max.
  362.      */
  363.     switch (n) {
  364.     case 0:
  365.       lb = (b1->c0max + b1->c0min) / 2;
  366.       b1->c0max = lb;
  367.       b2->c0min = lb+1;
  368.       break;
  369.     case 1:
  370.       lb = (b1->c1max + b1->c1min) / 2;
  371.       b1->c1max = lb;
  372.       b2->c1min = lb+1;
  373.       break;
  374.     case 2:
  375.       lb = (b1->c2max + b1->c2min) / 2;
  376.       b1->c2max = lb;
  377.       b2->c2min = lb+1;
  378.       break;
  379.     }
  380.     /* Update stats for boxes */
  381.     update_box(b1);
  382.     update_box(b2);
  383.     numboxes++;
  384.   }
  385. }
  386.  
  387.  
  388. LOCAL void
  389. compute_color (boxptr boxp, int icolor)
  390. /* Compute representative color for a box, put it in my_colormap[icolor] */
  391. {
  392.   /* Current algorithm: mean weighted by pixels (not colors) */
  393.   /* Note it is important to get the rounding correct! */
  394.   histptr histp;
  395.   int c0,c1,c2;
  396.   int c0min,c0max,c1min,c1max,c2min,c2max;
  397.   long count;
  398.   long total = 0;
  399.   long c0total = 0;
  400.   long c1total = 0;
  401.   long c2total = 0;
  402.   
  403.   c0min = boxp->c0min;  c0max = boxp->c0max;
  404.   c1min = boxp->c1min;  c1max = boxp->c1max;
  405.   c2min = boxp->c2min;  c2max = boxp->c2max;
  406.   
  407.   for (c0 = c0min; c0 <= c0max; c0++)
  408.     for (c1 = c1min; c1 <= c1max; c1++) {
  409.       histp = & histogram[c0][c1][c2min];
  410.       for (c2 = c2min; c2 <= c2max; c2++) {
  411.     if ((count = *histp++) != 0) {
  412.       total += count;
  413.       c0total += ((c0 << Y_SHIFT) + ((1<<Y_SHIFT)>>1)) * count;
  414.       c1total += ((c1 << C_SHIFT) + ((1<<C_SHIFT)>>1)) * count;
  415.       c2total += ((c2 << C_SHIFT) + ((1<<C_SHIFT)>>1)) * count;
  416.     }
  417.       }
  418.     }
  419.   
  420.   my_colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  421.   my_colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  422.   my_colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  423. }
  424.  
  425.  
  426. LOCAL void
  427. remap_colormap (decompress_info_ptr cinfo)
  428. /* Remap the internal colormap to the output colorspace */
  429. {
  430.   /* This requires a little trickery since color_convert expects to
  431.    * deal with 3-D arrays (a 2-D sample array for each component).
  432.    * We must promote the colormaps into one-row 3-D arrays.
  433.    */
  434.   short ci;
  435.   JSAMPARRAY input_hack[3];
  436.   JSAMPARRAY output_hack[10];    /* assume no more than 10 output components */
  437.  
  438.   for (ci = 0; ci < 3; ci++)
  439.     input_hack[ci] = &(my_colormap[ci]);
  440.   for (ci = 0; ci < cinfo->color_out_comps; ci++)
  441.     output_hack[ci] = &(cinfo->colormap[ci]);
  442.  
  443.   (*cinfo->methods->color_convert) (cinfo, 1,
  444.                     (long) cinfo->actual_number_of_colors,
  445.                     input_hack, output_hack);
  446. }
  447.  
  448.  
  449. LOCAL void
  450. select_colors (decompress_info_ptr cinfo)
  451. /* Master routine for color selection */
  452. {
  453.   int desired = cinfo->desired_number_of_colors;
  454.   int i;
  455.  
  456.   /* Allocate workspace for box list */
  457.   boxlist = (boxptr) (*cinfo->emethods->alloc_small) (desired * SIZEOF(box));
  458.   /* Initialize one box containing whole space */
  459.   numboxes = 1;
  460.   boxlist[0].c0min = 0;
  461.   boxlist[0].c0max = MAXJSAMPLE >> Y_SHIFT;
  462.   boxlist[0].c1min = 0;
  463.   boxlist[0].c1max = MAXJSAMPLE >> C_SHIFT;
  464.   boxlist[0].c2min = 0;
  465.   boxlist[0].c2max = MAXJSAMPLE >> C_SHIFT;
  466.   /* Shrink it to actually-used volume and set its statistics */
  467.   update_box(& boxlist[0]);
  468.   /* Perform median-cut to produce final box list */
  469.   median_cut(desired);
  470.   /* Compute the representative color for each box, fill my_colormap[] */
  471.   for (i = 0; i < numboxes; i++)
  472.     compute_color(& boxlist[i], i);
  473.   cinfo->actual_number_of_colors = numboxes;
  474.   /* Produce an output colormap in the desired output colorspace */
  475.   remap_colormap(cinfo);
  476.   TRACEMS1(cinfo->emethods, 1, "Selected %d colors for quantization",
  477.        numboxes);
  478.   /* Done with the box list */
  479.   (*cinfo->emethods->free_small) ((void *) boxlist);
  480. }
  481.  
  482.  
  483. /*
  484.  * These routines are concerned with the time-critical task of mapping input
  485.  * colors to the nearest color in the selected colormap.
  486.  *
  487.  * We re-use the histogram space as an "inverse color map", essentially a
  488.  * cache for the results of nearest-color searches.  All colors within a
  489.  * histogram cell will be mapped to the same colormap entry, namely the one
  490.  * closest to the cell's center.  This may not be quite the closest entry to
  491.  * the actual input color, but it's almost as good.  A zero in the cache
  492.  * indicates we haven't found the nearest color for that cell yet; the array
  493.  * is cleared to zeroes before starting the mapping pass.  When we find the
  494.  * nearest color for a cell, its colormap index plus one is recorded in the
  495.  * cache for future use.  The pass2 scanning routines call fill_inverse_cmap
  496.  * when they need to use an unfilled entry in the cache.
  497.  *
  498.  * Our method of efficiently finding nearest colors is based on the "locally
  499.  * sorted search" idea described by Heckbert and on the incremental distance
  500.  * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  501.  * Gems II (James Arvo, ed.  Academic Press, 1991).  Thomas points out that
  502.  * the distances from a given colormap entry to each cell of the histogram can
  503.  * be computed quickly using an incremental method: the differences between
  504.  * distances to adjacent cells themselves differ by a constant.  This allows a
  505.  * fairly fast implementation of the "brute force" approach of computing the
  506.  * distance from every colormap entry to every histogram cell.  Unfortunately,
  507.  * it needs a work array to hold the best-distance-so-far for each histogram
  508.  * cell (because the inner loop has to be over cells, not colormap entries).
  509.  * The work array elements have to be INT32s, so the work array would need
  510.  * 256Kb at our recommended precision.  This is not feasible in DOS machines.
  511.  * Another disadvantage of the brute force approach is that it computes
  512.  * distances to every cell of the cubical histogram.  When working with YCbCr
  513.  * input, only about a quarter of the cube represents realizable colors, so
  514.  * many of the cells will never be used and filling them is wasted effort.
  515.  *
  516.  * To get around these problems, we apply Thomas' method to compute the
  517.  * nearest colors for only the cells within a small subbox of the histogram.
  518.  * The work array need be only as big as the subbox, so the memory usage
  519.  * problem is solved.  A subbox is processed only when some cell in it is
  520.  * referenced by the pass2 routines, so we will never bother with cells far
  521.  * outside the realizable color volume.  An additional advantage of this
  522.  * approach is that we can apply Heckbert's locality criterion to quickly
  523.  * eliminate colormap entries that are far away from the subbox; typically
  524.  * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  525.  * and we need not compute their distances to individual cells in the subbox.
  526.  * The speed of this approach is heavily influenced by the subbox size: too
  527.  * small means too much overhead, too big loses because Heckbert's criterion
  528.  * can't eliminate as many colormap entries.  Empirically the best subbox
  529.  * size seems to be about 1/512th of the histogram (1/8th in each direction).
  530.  *
  531.  * Thomas' article also describes a refined method which is asymptotically
  532.  * faster than the brute-force method, but it is also far more complex and
  533.  * cannot efficiently be applied to small subboxes.  It is therefore not
  534.  * useful for programs intended to be portable to DOS machines.  On machines
  535.  * with plenty of memory, filling the whole histogram in one shot with Thomas'
  536.  * refined method might be faster than the present code --- but then again,
  537.  * it might not be any faster, and it's certainly more complicated.
  538.  */
  539.  
  540.  
  541. #ifndef BOX_Y_LOG        /* so you can override from Makefile */
  542. #define BOX_Y_LOG  (HIST_Y_BITS-3) /* log2(hist cells in update box, Y axis) */
  543. #endif
  544. #ifndef BOX_C_LOG        /* so you can override from Makefile */
  545. #define BOX_C_LOG  (HIST_C_BITS-3) /* log2(hist cells in update box, C axes) */
  546. #endif
  547.  
  548. #define BOX_Y_ELEMS  (1<<BOX_Y_LOG) /* # of hist cells in update box */
  549. #define BOX_C_ELEMS  (1<<BOX_C_LOG)
  550.  
  551. #define BOX_Y_SHIFT  (Y_SHIFT + BOX_Y_LOG)
  552. #define BOX_C_SHIFT  (C_SHIFT + BOX_C_LOG)
  553.  
  554.  
  555. /*
  556.  * The next three routines implement inverse colormap filling.  They could
  557.  * all be folded into one big routine, but splitting them up this way saves
  558.  * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  559.  * and may allow some compilers to produce better code by registerizing more
  560.  * inner-loop variables.
  561.  */
  562.  
  563. LOCAL int
  564. find_nearby_colors (decompress_info_ptr cinfo, int minc0, int minc1, int minc2,
  565.             JSAMPLE colorlist[])
  566. /* Locate the colormap entries close enough to an update box to be candidates
  567.  * for the nearest entry to some cell(s) in the update box.  The update box
  568.  * is specified by the center coordinates of its first cell.  The number of
  569.  * candidate colormap entries is returned, and their colormap indexes are
  570.  * placed in colorlist[].
  571.  * This routine uses Heckbert's "locally sorted search" criterion to select
  572.  * the colors that need further consideration.
  573.  */
  574. {
  575.   int numcolors = cinfo->actual_number_of_colors;
  576.   int maxc0, maxc1, maxc2;
  577.   int centerc0, centerc1, centerc2;
  578.   int i, x, ncolors;
  579.   INT32 minmaxdist, min_dist, max_dist, tdist;
  580.   INT32 mindist[MAXNUMCOLORS];    /* min distance to colormap entry i */
  581.  
  582.   /* Compute true coordinates of update box's upper corner and center.
  583.    * Actually we compute the coordinates of the center of the upper-corner
  584.    * histogram cell, which are the upper bounds of the volume we care about.
  585.    * Note that since ">>" rounds down, the "center" values may be closer to
  586.    * min than to max; hence comparisons to them must be "<=", not "<".
  587.    */
  588.   maxc0 = minc0 + ((1 << BOX_Y_SHIFT) - (1 << Y_SHIFT));
  589.   centerc0 = (minc0 + maxc0) >> 1;
  590.   maxc1 = minc1 + ((1 << BOX_C_SHIFT) - (1 << C_SHIFT));
  591.   centerc1 = (minc1 + maxc1) >> 1;
  592.   maxc2 = minc2 + ((1 << BOX_C_SHIFT) - (1 << C_SHIFT));
  593.   centerc2 = (minc2 + maxc2) >> 1;
  594.  
  595.   /* For each color in colormap, find:
  596.    *  1. its minimum squared-distance to any point in the update box
  597.    *     (zero if color is within update box);
  598.    *  2. its maximum squared-distance to any point in the update box.
  599.    * Both of these can be found by considering only the corners of the box.
  600.    * We save the minimum distance for each color in mindist[];
  601.    * only the smallest maximum distance is of interest.
  602.    * Note we have to scale Y to get correct distance in scaled space.
  603.    */
  604.   minmaxdist = 0x7FFFFFFFL;
  605.  
  606.   for (i = 0; i < numcolors; i++) {
  607.     /* We compute the squared-c0-distance term, then add in the other two. */
  608.     x = GETJSAMPLE(my_colormap[0][i]);
  609.     if (x < minc0) {
  610.       tdist = (x - minc0) * Y_SCALE;
  611.       min_dist = tdist*tdist;
  612.       tdist = (x - maxc0) * Y_SCALE;
  613.       max_dist = tdist*tdist;
  614.     } else if (x > maxc0) {
  615.       tdist = (x - maxc0) * Y_SCALE;
  616.       min_dist = tdist*tdist;
  617.       tdist = (x - minc0) * Y_SCALE;
  618.       max_dist = tdist*tdist;
  619.     } else {
  620.       /* within cell range so no contribution to min_dist */
  621.       min_dist = 0;
  622.       if (x <= centerc0) {
  623.     tdist = (x - maxc0) * Y_SCALE;
  624.     max_dist = tdist*tdist;
  625.       } else {
  626.     tdist = (x - minc0) * Y_SCALE;
  627.     max_dist = tdist*tdist;
  628.       }
  629.     }
  630.  
  631.     x = GETJSAMPLE(my_colormap[1][i]);
  632.     if (x < minc1) {
  633.       tdist = x - minc1;
  634.       min_dist += tdist*tdist;
  635.       tdist = x - maxc1;
  636.       max_dist += tdist*tdist;
  637.     } else if (x > maxc1) {
  638.       tdist = x - maxc1;
  639.       min_dist += tdist*tdist;
  640.       tdist = x - minc1;
  641.       max_dist += tdist*tdist;
  642.     } else {
  643.       /* within cell range so no contribution to min_dist */
  644.       if (x <= centerc1) {
  645.     tdist = x - maxc1;
  646.     max_dist += tdist*tdist;
  647.       } else {
  648.     tdist = x - minc1;
  649.     max_dist += tdist*tdist;
  650.       }
  651.     }
  652.  
  653.     x = GETJSAMPLE(my_colormap[2][i]);
  654.     if (x < minc2) {
  655.       tdist = x - minc2;
  656.       min_dist += tdist*tdist;
  657.       tdist = x - maxc2;
  658.       max_dist += tdist*tdist;
  659.     } else if (x > maxc2) {
  660.       tdist = x - maxc2;
  661.       min_dist += tdist*tdist;
  662.       tdist = x - minc2;
  663.       max_dist += tdist*tdist;
  664.     } else {
  665.       /* within cell range so no contribution to min_dist */
  666.       if (x <= centerc2) {
  667.     tdist = x - maxc2;
  668.     max_dist += tdist*tdist;
  669.       } else {
  670.     tdist = x - minc2;
  671.     max_dist += tdist*tdist;
  672.       }
  673.     }
  674.  
  675.     mindist[i] = min_dist;    /* save away the results */
  676.     if (max_dist < minmaxdist)
  677.       minmaxdist = max_dist;
  678.   }
  679.  
  680.   /* Now we know that no cell in the update box is more than minmaxdist
  681.    * away from some colormap entry.  Therefore, only colors that are
  682.    * within minmaxdist of some part of the box need be considered.
  683.    */
  684.   ncolors = 0;
  685.   for (i = 0; i < numcolors; i++) {
  686.     if (mindist[i] <= minmaxdist)
  687.       colorlist[ncolors++] = (JSAMPLE) i;
  688.   }
  689.   return ncolors;
  690. }
  691.  
  692.  
  693. LOCAL void
  694. find_best_colors (decompress_info_ptr cinfo, int minc0, int minc1, int minc2,
  695.           int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  696. /* Find the closest colormap entry for each cell in the update box,
  697.  * given the list of candidate colors prepared by find_nearby_colors.
  698.  * Return the indexes of the closest entries in the bestcolor[] array.
  699.  * This routine uses Thomas' incremental distance calculation method to
  700.  * find the distance from a colormap entry to successive cells in the box.
  701.  */
  702. {
  703.   int ic0, ic1, ic2;
  704.   int i, icolor;
  705.   register INT32 * bptr;    /* pointer into bestdist[] array */
  706.   JSAMPLE * cptr;        /* pointer into bestcolor[] array */
  707.   INT32 dist0, dist1;        /* initial distance values */
  708.   register INT32 dist2;        /* current distance in inner loop */
  709.   INT32 xx0, xx1;        /* distance increments */
  710.   register INT32 xx2;
  711.   INT32 inc0, inc1, inc2;    /* initial values for increments */
  712.   /* This array holds the distance to the nearest-so-far color for each cell */
  713.   INT32 bestdist[BOX_Y_ELEMS * BOX_C_ELEMS * BOX_C_ELEMS];
  714.  
  715.   /* Initialize best-distance for each cell of the update box */
  716.   bptr = bestdist;
  717.   for (i = BOX_Y_ELEMS*BOX_C_ELEMS*BOX_C_ELEMS-1; i >= 0; i--)
  718.     *bptr++ = 0x7FFFFFFFL;
  719.   
  720.   /* For each color selected by find_nearby_colors,
  721.    * compute its distance to the center of each cell in the box.
  722.    * If that's less than best-so-far, update best distance and color number.
  723.    * Note we have to scale Y to get correct distance in scaled space.
  724.    */
  725.   
  726.   /* Nominal steps between cell centers ("x" in Thomas article) */
  727. #define STEP_Y  ((1 << Y_SHIFT) * Y_SCALE)
  728. #define STEP_C  (1 << C_SHIFT)
  729.   
  730.   for (i = 0; i < numcolors; i++) {
  731.     icolor = GETJSAMPLE(colorlist[i]);
  732.     /* Compute (square of) distance from minc0/c1/c2 to this color */
  733.     inc0 = (minc0 - (int) GETJSAMPLE(my_colormap[0][icolor])) * Y_SCALE;
  734.     dist0 = inc0*inc0;
  735.     inc1 = minc1 - (int) GETJSAMPLE(my_colormap[1][icolor]);
  736.     dist0 += inc1*inc1;
  737.     inc2 = minc2 - (int) GETJSAMPLE(my_colormap[2][icolor]);
  738.     dist0 += inc2*inc2;
  739.     /* Form the initial difference increments */
  740.     inc0 = inc0 * (2 * STEP_Y) + STEP_Y * STEP_Y;
  741.     inc1 = inc1 * (2 * STEP_C) + STEP_C * STEP_C;
  742.     inc2 = inc2 * (2 * STEP_C) + STEP_C * STEP_C;
  743.     /* Now loop over all cells in box, updating distance per Thomas method */
  744.     bptr = bestdist;
  745.     cptr = bestcolor;
  746.     xx0 = inc0;
  747.     for (ic0 = BOX_Y_ELEMS-1; ic0 >= 0; ic0--) {
  748.       dist1 = dist0;
  749.       xx1 = inc1;
  750.       for (ic1 = BOX_C_ELEMS-1; ic1 >= 0; ic1--) {
  751.     dist2 = dist1;
  752.     xx2 = inc2;
  753.     for (ic2 = BOX_C_ELEMS-1; ic2 >= 0; ic2--) {
  754.       if (dist2 < *bptr) {
  755.         *bptr = dist2;
  756.         *cptr = (JSAMPLE) icolor;
  757.       }
  758.       dist2 += xx2;
  759.       xx2 += 2 * STEP_C * STEP_C;
  760.       bptr++;
  761.       cptr++;
  762.     }
  763.     dist1 += xx1;
  764.     xx1 += 2 * STEP_C * STEP_C;
  765.       }
  766.       dist0 += xx0;
  767.       xx0 += 2 * STEP_Y * STEP_Y;
  768.     }
  769.   }
  770. }
  771.  
  772.  
  773. LOCAL void
  774. fill_inverse_cmap (decompress_info_ptr cinfo, int c0, int c1, int c2)
  775. /* Fill the inverse-colormap entries in the update box that contains */
  776. /* histogram cell c0/c1/c2.  (Only that one cell MUST be filled, but */
  777. /* we can fill as many others as we wish.) */
  778. {
  779.   int minc0, minc1, minc2;    /* lower left corner of update box */
  780.   int ic0, ic1, ic2;
  781.   register JSAMPLE * cptr;    /* pointer into bestcolor[] array */
  782.   register histptr cachep;    /* pointer into main cache array */
  783.   /* This array lists the candidate colormap indexes. */
  784.   JSAMPLE colorlist[MAXNUMCOLORS];
  785.   int numcolors;        /* number of candidate colors */
  786.   /* This array holds the actually closest colormap index for each cell. */
  787.   JSAMPLE bestcolor[BOX_Y_ELEMS * BOX_C_ELEMS * BOX_C_ELEMS];
  788.  
  789.   /* Convert cell coordinates to update box ID */
  790.   c0 >>= BOX_Y_LOG;
  791.   c1 >>= BOX_C_LOG;
  792.   c2 >>= BOX_C_LOG;
  793.  
  794.   /* Compute true coordinates of update box's origin corner.
  795.    * Actually we compute the coordinates of the center of the corner
  796.    * histogram cell, which are the lower bounds of the volume we care about.
  797.    */
  798.   minc0 = (c0 << BOX_Y_SHIFT) + ((1 << Y_SHIFT) >> 1);
  799.   minc1 = (c1 << BOX_C_SHIFT) + ((1 << C_SHIFT) >> 1);
  800.   minc2 = (c2 << BOX_C_SHIFT) + ((1 << C_SHIFT) >> 1);
  801.   
  802.   /* Determine which colormap entries are close enough to be candidates
  803.    * for the nearest entry to some cell in the update box.
  804.    */
  805.   numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  806.  
  807.   /* Determine the actually nearest colors. */
  808.   find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  809.            bestcolor);
  810.  
  811.   /* Save the best color numbers (plus 1) in the main cache array */
  812.   c0 <<= BOX_Y_LOG;        /* convert ID back to base cell indexes */
  813.   c1 <<= BOX_C_LOG;
  814.   c2 <<= BOX_C_LOG;
  815.   cptr = bestcolor;
  816.   for (ic0 = 0; ic0 < BOX_Y_ELEMS; ic0++) {
  817.     for (ic1 = 0; ic1 < BOX_C_ELEMS; ic1++) {
  818.       cachep = & histogram[c0+ic0][c1+ic1][c2];
  819.       for (ic2 = 0; ic2 < BOX_C_ELEMS; ic2++) {
  820.     *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  821.       }
  822.     }
  823.   }
  824. }
  825.  
  826.  
  827. /*
  828.  * These routines perform second-pass scanning of the image: map each pixel to
  829.  * the proper colormap index, and output the indexes to the output file.
  830.  *
  831.  * output_workspace is a one-component array of pixel dimensions at least
  832.  * as large as the input image strip; it can be used to hold the converted
  833.  * pixels' colormap indexes.
  834.  */
  835.  
  836. METHODDEF void
  837. pass2_nodither (decompress_info_ptr cinfo, int num_rows,
  838.         JSAMPIMAGE image_data, JSAMPARRAY output_workspace)
  839. /* This version performs no dithering */
  840. {
  841.   register JSAMPROW ptr0, ptr1, ptr2, outptr;
  842.   register histptr cachep;
  843.   register int c0, c1, c2;
  844.   int row;
  845.   long col;
  846.   long width = cinfo->image_width;
  847.  
  848.   /* Convert data to colormap indexes, which we save in output_workspace */
  849.   for (row = 0; row < num_rows; row++) {
  850.     ptr0 = image_data[0][row];
  851.     ptr1 = image_data[1][row];
  852.     ptr2 = image_data[2][row];
  853.     outptr = output_workspace[row];
  854.     for (col = width; col > 0; col--) {
  855.       /* get pixel value and index into the cache */
  856.       c0 = GETJSAMPLE(*ptr0++) >> Y_SHIFT;
  857.       c1 = GETJSAMPLE(*ptr1++) >> C_SHIFT;
  858.       c2 = GETJSAMPLE(*ptr2++) >> C_SHIFT;
  859.       cachep = & histogram[c0][c1][c2];
  860.       /* If we have not seen this color before, find nearest colormap entry */
  861.       /* and update the cache */
  862.       if (*cachep == 0)
  863.     fill_inverse_cmap(cinfo, c0,c1,c2);
  864.       /* Now emit the colormap index for this cell */
  865.       *outptr++ = (JSAMPLE) (*cachep - 1);
  866.     }
  867.   }
  868.   /* Emit converted rows to the output file */
  869.   (*cinfo->methods->put_pixel_rows) (cinfo, num_rows, &output_workspace);
  870. }
  871.  
  872.  
  873. /* Declarations for Floyd-Steinberg dithering.
  874.  *
  875.  * Errors are accumulated into the arrays evenrowerrs[] and oddrowerrs[].
  876.  * These have resolutions of 1/16th of a pixel count.  The error at a given
  877.  * pixel is propagated to its unprocessed neighbors using the standard F-S
  878.  * fractions,
  879.  *        ...    (here)    7/16
  880.  *        3/16    5/16    1/16
  881.  * We work left-to-right on even rows, right-to-left on odd rows.
  882.  *
  883.  * Each of the arrays has (#columns + 2) entries; the extra entry
  884.  * at each end saves us from special-casing the first and last pixels.
  885.  * Each entry is three values long.
  886.  * In evenrowerrs[], the entries for a component are stored left-to-right, but
  887.  * in oddrowerrs[] they are stored right-to-left.  This means we always
  888.  * process the current row's error entries in increasing order and the next
  889.  * row's error entries in decreasing order, regardless of whether we are
  890.  * working L-to-R or R-to-L in the pixel data!
  891.  *
  892.  * Note: on a wide image, we might not have enough room in a PC's near data
  893.  * segment to hold the error arrays; so they are allocated with alloc_medium.
  894.  */
  895.  
  896. #ifdef OLD_CODE
  897. #ifdef EIGHT_BIT_SAMPLES
  898. typedef INT16 FSERROR;        /* 16 bits should be enough */
  899. #else
  900. typedef INT32 FSERROR;        /* may need more than 16 bits? */
  901. #endif
  902. #endif
  903. typedef int FSERROR;
  904.  
  905. typedef FSERROR FAR *FSERRPTR;    /* pointer to error array (in FAR storage!) */
  906.  
  907. static FSERRPTR evenrowerrs, oddrowerrs; /* current-row and next-row errors */
  908. static boolean on_odd_row;    /* flag to remember which row we are on */
  909.  
  910.  
  911. METHODDEF void
  912. pass2_dither (decompress_info_ptr cinfo, int num_rows,
  913.           JSAMPIMAGE image_data, JSAMPARRAY output_workspace)
  914. /* This version performs Floyd-Steinberg dithering */
  915. {
  916.   register FSERROR val;
  917.   register FSERRPTR thisrowerr, nextrowerr;
  918.   register FSERROR c0, c1, c2;
  919.   register int pixcode;
  920.   JSAMPROW ptr0, ptr1, ptr2, outptr;
  921.   histptr cachep;
  922.   int dir;
  923.   long col;
  924.   int row;
  925.   long width = cinfo->image_width;
  926.  
  927.   /* Convert data to colormap indexes, which we save in output_workspace */
  928.   for (row = 0; row < num_rows; row++) {
  929.     ptr0 = image_data[0][row];
  930.     ptr1 = image_data[1][row];
  931.     ptr2 = image_data[2][row];
  932.     outptr = output_workspace[row];
  933.     if (on_odd_row) {
  934.       /* work right to left in this row */
  935.       ptr0 += width - 1;
  936.       ptr1 += width - 1;
  937.       ptr2 += width - 1;
  938.       outptr += width - 1;
  939.       dir = -1;
  940.       thisrowerr = oddrowerrs + 3;
  941.       nextrowerr = evenrowerrs + width*3;
  942.       on_odd_row = FALSE;    /* flip for next time */
  943.     } else {
  944.       /* work left to right in this row */
  945.       dir = 1;
  946.       thisrowerr = evenrowerrs + 3;
  947.       nextrowerr = oddrowerrs + width*3;
  948.       on_odd_row = TRUE;    /* flip for next time */
  949.     }
  950.     /* need only initialize this one entry in nextrowerr */
  951.     nextrowerr[0] = nextrowerr[1] = nextrowerr[2] = 0;
  952.     for (col = width; col > 0; col--) {
  953.       /* Get this pixel's value and add accumulated errors */
  954.       /* The errors are in units of 1/16th pixel value */
  955.       val = (GETJSAMPLE(*ptr0) << 4) + thisrowerr[0];
  956.       if (val <= 0) val = 0;    /* must watch for range overflow! */
  957.       else {
  958. #ifdef OLD_CODE
  959.     val += 8;       /* divide by 16 with proper rounding */
  960. #endif
  961.     val >>= 4;
  962. /*
  963.     printf("%d  %u \n",val,range_limit[val]);
  964. */
  965.       val =(FSERROR) range_limit[val];
  966.       }
  967.       c0 = val;
  968.       val = (GETJSAMPLE(*ptr1) << 4) + thisrowerr[1];
  969.       if (val <= 0) val = 0;    /* must watch for range overflow! */
  970.       else {
  971. #ifdef OLD_CODE
  972.     val += 8;       /* divide by 16 with proper rounding */
  973. #endif
  974.     val >>= 4;
  975.       val =(FSERROR) range_limit[val];
  976.       }
  977.       c1 = val;
  978.       val = (GETJSAMPLE(*ptr2) << 4) + thisrowerr[2];
  979.       if (val <= 0) val = 0;    /* must watch for range overflow! */
  980.       else {
  981. #ifdef OLD_CODE
  982.     val += 8;       /* divide by 16 with proper rounding */
  983. #endif
  984.     val >>= 4;
  985.       val =(FSERROR) range_limit[val];
  986.       }
  987.       c2 = val;
  988.       /* Index into the cache with adjusted value */
  989.       cachep = & histogram[c0 >> Y_SHIFT][c1 >> C_SHIFT][c2 >> C_SHIFT];
  990.       /* If we have not seen this color before, find nearest colormap */
  991.       /* entry and update the cache */
  992.       if (*cachep == 0)
  993.     fill_inverse_cmap(cinfo, c0 >> Y_SHIFT, c1 >> C_SHIFT, c2 >> C_SHIFT);
  994.       /* Now emit the colormap index for this cell */
  995.       pixcode = *cachep - 1;
  996.       *outptr = (JSAMPLE) pixcode;
  997.       /* Compute representation error for this pixel */
  998.       c0 -= (FSERROR) GETJSAMPLE(my_colormap[0][pixcode]);
  999.       c1 -= (FSERROR) GETJSAMPLE(my_colormap[1][pixcode]);
  1000.       c2 -= (FSERROR) GETJSAMPLE(my_colormap[2][pixcode]);
  1001.       /* Propagate error to adjacent pixels */
  1002.       /* Remember that nextrowerr entries are in reverse order! */
  1003.       val = c0 * 2;
  1004.       nextrowerr[0-3]  = c0;    /* not +=, since not initialized yet */
  1005.       c0 += val;        /* form error * 3 */
  1006.       nextrowerr[0+3] += c0;
  1007.       c0 += val;        /* form error * 5 */
  1008.       nextrowerr[0  ] += c0;
  1009.       c0 += val;        /* form error * 7 */
  1010.       thisrowerr[0+3] += c0;
  1011.       val = c1 * 2;
  1012.       nextrowerr[1-3]  = c1;    /* not +=, since not initialized yet */
  1013.       c1 += val;        /* form error * 3 */
  1014.       nextrowerr[1+3] += c1;
  1015.       c1 += val;        /* form error * 5 */
  1016.       nextrowerr[1  ] += c1;
  1017.       c1 += val;        /* form error * 7 */
  1018.       thisrowerr[1+3] += c1;
  1019.       val = c2 * 2;
  1020.       nextrowerr[2-3]  = c2;    /* not +=, since not initialized yet */
  1021.       c2 += val;        /* form error * 3 */
  1022.       nextrowerr[2+3] += c2;
  1023.       c2 += val;        /* form error * 5 */
  1024.       nextrowerr[2  ] += c2;
  1025.       c2 += val;        /* form error * 7 */
  1026.       thisrowerr[2+3] += c2;
  1027.       /* Advance to next column */
  1028.       ptr0 += dir;
  1029.       ptr1 += dir;
  1030.       ptr2 += dir;
  1031.       outptr += dir;
  1032.       thisrowerr += 3;        /* cur-row error ptr advances to right */
  1033.       nextrowerr -= 3;        /* next-row error ptr advances to left */
  1034.     }
  1035.   }
  1036.   /* Emit converted rows to the output file */
  1037.   (*cinfo->methods->put_pixel_rows) (cinfo, num_rows, &output_workspace);
  1038. }
  1039.  
  1040.  
  1041. /*
  1042.  * Initialize for two-pass color quantization.
  1043.  */
  1044.  
  1045. METHODDEF void
  1046. color_quant_init (decompress_info_ptr cinfo)
  1047. {
  1048.   int i;
  1049.  
  1050.   /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  1051.   if (cinfo->desired_number_of_colors < 8)
  1052.     ERREXIT(cinfo->emethods, "Cannot request less than 8 quantized colors");
  1053.   /* Make sure colormap indexes can be represented by JSAMPLEs */
  1054.   if (cinfo->desired_number_of_colors > MAXNUMCOLORS)
  1055.     ERREXIT1(cinfo->emethods, "Cannot request more than %d quantized colors",
  1056.          MAXNUMCOLORS);
  1057.  
  1058.   /* Allocate and zero the histogram */
  1059.   histogram = (hist3d) (*cinfo->emethods->alloc_small)
  1060.                 (HIST_Y_ELEMS * SIZEOF(hist2d));
  1061.   for (i = 0; i < HIST_Y_ELEMS; i++) {
  1062.     histogram[i] = (hist2d) (*cinfo->emethods->alloc_medium)
  1063.                 (HIST_C_ELEMS*HIST_C_ELEMS * SIZEOF(histcell));
  1064.     jzero_far((void FAR *) histogram[i],
  1065.           HIST_C_ELEMS*HIST_C_ELEMS * SIZEOF(histcell));
  1066.   }
  1067.  
  1068.   /* Allocate storage for the internal and external colormaps. */
  1069.   /* We do this now since it is FAR storage and may affect the memory */
  1070.   /* manager's space calculations. */
  1071.   my_colormap = (*cinfo->emethods->alloc_small_sarray)
  1072.             ((long) cinfo->desired_number_of_colors,
  1073.              (long) 3);
  1074.   cinfo->colormap = (*cinfo->emethods->alloc_small_sarray)
  1075.             ((long) cinfo->desired_number_of_colors,
  1076.              (long) cinfo->color_out_comps);
  1077.  
  1078.   /* Allocate Floyd-Steinberg workspace if necessary */
  1079.   /* This isn't needed until pass 2, but again it is FAR storage. */
  1080.   if (cinfo->use_dithering) {
  1081.     size_t arraysize = (size_t) ((cinfo->image_width + 2L) * 3L * SIZEOF(FSERROR));
  1082.  
  1083.     evenrowerrs = (FSERRPTR) (*cinfo->emethods->alloc_medium) (arraysize);
  1084.     oddrowerrs  = (FSERRPTR) (*cinfo->emethods->alloc_medium) (arraysize);
  1085.     /* we only need to zero the forward contribution for current row. */
  1086.     jzero_far((void FAR *) evenrowerrs, arraysize);
  1087.     on_odd_row = FALSE;
  1088.   }
  1089.  
  1090.   /* Indicate number of passes needed, excluding the prescan pass. */
  1091.   cinfo->total_passes++;    /* I always use one pass */
  1092. }
  1093.  
  1094.  
  1095. /*
  1096.  * Perform two-pass quantization: rescan the image data and output the
  1097.  * converted data via put_color_map and put_pixel_rows.
  1098.  * The source_method is a routine that can scan the image data; it can
  1099.  * be called as many times as desired.  The processing routine called by
  1100.  * source_method has the same interface as color_quantize does in the
  1101.  * one-pass case, except it must call put_pixel_rows itself.  (This allows
  1102.  * me to use multiple passes in which earlier passes don't output anything.)
  1103.  */
  1104.  
  1105. METHODDEF void
  1106. color_quant_doit (decompress_info_ptr cinfo, quantize_caller_ptr source_method)
  1107. {
  1108.   int i;
  1109.  
  1110.   /* Select the representative colors */
  1111.   select_colors(cinfo);
  1112.   /* Pass the external colormap to the output module. */
  1113.   /* NB: the output module may continue to use the colormap until shutdown. */
  1114.   (*cinfo->methods->put_color_map) (cinfo, cinfo->actual_number_of_colors,
  1115.                     cinfo->colormap);
  1116.   /* Re-zero the histogram so pass 2 can use it as nearest-color cache */
  1117.   for (i = 0; i < HIST_Y_ELEMS; i++) {
  1118.     jzero_far((void FAR *) histogram[i],
  1119.           HIST_C_ELEMS*HIST_C_ELEMS * SIZEOF(histcell));
  1120.   }
  1121.   /* Perform pass 2 */
  1122.   if (cinfo->use_dithering)
  1123.     (*source_method) (cinfo, pass2_dither);
  1124.   else
  1125.     (*source_method) (cinfo, pass2_nodither);
  1126. }
  1127.  
  1128.  
  1129. /*
  1130.  * Finish up at the end of the file.
  1131.  */
  1132.  
  1133. METHODDEF void
  1134. color_quant_term (decompress_info_ptr cinfo)
  1135. {
  1136.   /* no work (we let free_all release the histogram/cache and colormaps) */
  1137.   /* Note that we *mustn't* free the external colormap before free_all, */
  1138.   /* since output module may use it! */
  1139. }
  1140.  
  1141.  
  1142. /*
  1143.  * Map some rows of pixels to the output colormapped representation.
  1144.  * Not used in two-pass case.
  1145.  */
  1146.  
  1147. METHODDEF void
  1148. color_quantize (decompress_info_ptr cinfo, int num_rows,
  1149.         JSAMPIMAGE input_data, JSAMPARRAY output_data)
  1150. {
  1151.   ERREXIT(cinfo->emethods, "Should not get here!");
  1152. }
  1153.  
  1154.  
  1155. /*
  1156.  * The method selection routine for 2-pass color quantization.
  1157.  */
  1158.  
  1159. GLOBAL void
  1160. jsel2quantize (decompress_info_ptr cinfo)
  1161. {
  1162.   if (cinfo->two_pass_quantize) {
  1163.     /* Make sure jdmaster didn't give me a case I can't handle */
  1164.     if (cinfo->num_components != 3 || cinfo->jpeg_color_space != CS_YCbCr)
  1165.       ERREXIT(cinfo->emethods, "2-pass quantization only handles YCbCr input");
  1166.     cinfo->methods->color_quant_init = color_quant_init;
  1167.     cinfo->methods->color_quant_prescan = color_quant_prescan;
  1168.     cinfo->methods->color_quant_doit = color_quant_doit;
  1169.     cinfo->methods->color_quant_term = color_quant_term;
  1170.     cinfo->methods->color_quantize = color_quantize;
  1171.   }
  1172. }
  1173.  
  1174. #endif /* QUANT_2PASS_SUPPORTED */
  1175.