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