0N/A/*
0N/A * reserved comment block
0N/A * DO NOT REMOVE OR ALTER!
0N/A */
0N/A/*
0N/A * jquant2.c
0N/A *
0N/A * Copyright (C) 1991-1996, Thomas G. Lane.
0N/A * This file is part of the Independent JPEG Group's software.
0N/A * For conditions of distribution and use, see the accompanying README file.
0N/A *
0N/A * This file contains 2-pass color quantization (color mapping) routines.
0N/A * These routines provide selection of a custom color map for an image,
0N/A * followed by mapping of the image to that color map, with optional
0N/A * Floyd-Steinberg dithering.
0N/A * It is also possible to use just the second pass to map to an arbitrary
0N/A * externally-given color map.
0N/A *
0N/A * Note: ordered dithering is not supported, since there isn't any fast
0N/A * way to compute intercolor distances; it's unclear that ordered dither's
0N/A * fundamental assumptions even hold with an irregularly spaced color map.
0N/A */
0N/A
0N/A#define JPEG_INTERNALS
0N/A#include "jinclude.h"
0N/A#include "jpeglib.h"
0N/A
0N/A#ifdef QUANT_2PASS_SUPPORTED
0N/A
0N/A
0N/A/*
0N/A * This module implements the well-known Heckbert paradigm for color
0N/A * quantization. Most of the ideas used here can be traced back to
0N/A * Heckbert's seminal paper
0N/A * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
0N/A * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
0N/A *
0N/A * In the first pass over the image, we accumulate a histogram showing the
0N/A * usage count of each possible color. To keep the histogram to a reasonable
0N/A * size, we reduce the precision of the input; typical practice is to retain
0N/A * 5 or 6 bits per color, so that 8 or 4 different input values are counted
0N/A * in the same histogram cell.
0N/A *
0N/A * Next, the color-selection step begins with a box representing the whole
0N/A * color space, and repeatedly splits the "largest" remaining box until we
0N/A * have as many boxes as desired colors. Then the mean color in each
0N/A * remaining box becomes one of the possible output colors.
0N/A *
0N/A * The second pass over the image maps each input pixel to the closest output
0N/A * color (optionally after applying a Floyd-Steinberg dithering correction).
0N/A * This mapping is logically trivial, but making it go fast enough requires
0N/A * considerable care.
0N/A *
0N/A * Heckbert-style quantizers vary a good deal in their policies for choosing
0N/A * the "largest" box and deciding where to cut it. The particular policies
0N/A * used here have proved out well in experimental comparisons, but better ones
0N/A * may yet be found.
0N/A *
0N/A * In earlier versions of the IJG code, this module quantized in YCbCr color
0N/A * space, processing the raw upsampled data without a color conversion step.
0N/A * This allowed the color conversion math to be done only once per colormap
0N/A * entry, not once per pixel. However, that optimization precluded other
0N/A * useful optimizations (such as merging color conversion with upsampling)
0N/A * and it also interfered with desired capabilities such as quantizing to an
0N/A * externally-supplied colormap. We have therefore abandoned that approach.
0N/A * The present code works in the post-conversion color space, typically RGB.
0N/A *
0N/A * To improve the visual quality of the results, we actually work in scaled
0N/A * RGB space, giving G distances more weight than R, and R in turn more than
0N/A * B. To do everything in integer math, we must use integer scale factors.
0N/A * The 2/3/1 scale factors used here correspond loosely to the relative
0N/A * weights of the colors in the NTSC grayscale equation.
0N/A * If you want to use this code to quantize a non-RGB color space, you'll
0N/A * probably need to change these scale factors.
0N/A */
0N/A
0N/A#define R_SCALE 2 /* scale R distances by this much */
0N/A#define G_SCALE 3 /* scale G distances by this much */
0N/A#define B_SCALE 1 /* and B by this much */
0N/A
0N/A/* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
0N/A * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
0N/A * and B,G,R orders. If you define some other weird order in jmorecfg.h,
0N/A * you'll get compile errors until you extend this logic. In that case
0N/A * you'll probably want to tweak the histogram sizes too.
0N/A */
0N/A
0N/A#if RGB_RED == 0
0N/A#define C0_SCALE R_SCALE
0N/A#endif
0N/A#if RGB_BLUE == 0
0N/A#define C0_SCALE B_SCALE
0N/A#endif
0N/A#if RGB_GREEN == 1
0N/A#define C1_SCALE G_SCALE
0N/A#endif
0N/A#if RGB_RED == 2
0N/A#define C2_SCALE R_SCALE
0N/A#endif
0N/A#if RGB_BLUE == 2
0N/A#define C2_SCALE B_SCALE
0N/A#endif
0N/A
0N/A
0N/A/*
0N/A * First we have the histogram data structure and routines for creating it.
0N/A *
0N/A * The number of bits of precision can be adjusted by changing these symbols.
0N/A * We recommend keeping 6 bits for G and 5 each for R and B.
0N/A * If you have plenty of memory and cycles, 6 bits all around gives marginally
0N/A * better results; if you are short of memory, 5 bits all around will save
0N/A * some space but degrade the results.
0N/A * To maintain a fully accurate histogram, we'd need to allocate a "long"
0N/A * (preferably unsigned long) for each cell. In practice this is overkill;
0N/A * we can get by with 16 bits per cell. Few of the cell counts will overflow,
0N/A * and clamping those that do overflow to the maximum value will give close-
0N/A * enough results. This reduces the recommended histogram size from 256Kb
0N/A * to 128Kb, which is a useful savings on PC-class machines.
0N/A * (In the second pass the histogram space is re-used for pixel mapping data;
0N/A * in that capacity, each cell must be able to store zero to the number of
0N/A * desired colors. 16 bits/cell is plenty for that too.)
0N/A * Since the JPEG code is intended to run in small memory model on 80x86
0N/A * machines, we can't just allocate the histogram in one chunk. Instead
0N/A * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
0N/A * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
0N/A * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
0N/A * on 80x86 machines, the pointer row is in near memory but the actual
0N/A * arrays are in far memory (same arrangement as we use for image arrays).
0N/A */
0N/A
0N/A#define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
0N/A
0N/A/* These will do the right thing for either R,G,B or B,G,R color order,
0N/A * but you may not like the results for other color orders.
0N/A */
0N/A#define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
0N/A#define HIST_C1_BITS 6 /* bits of precision in G histogram */
0N/A#define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
0N/A
0N/A/* Number of elements along histogram axes. */
0N/A#define HIST_C0_ELEMS (1<<HIST_C0_BITS)
0N/A#define HIST_C1_ELEMS (1<<HIST_C1_BITS)
0N/A#define HIST_C2_ELEMS (1<<HIST_C2_BITS)
0N/A
0N/A/* These are the amounts to shift an input value to get a histogram index. */
0N/A#define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
0N/A#define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
0N/A#define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
0N/A
0N/A
0N/Atypedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
0N/A
0N/Atypedef histcell FAR * histptr; /* for pointers to histogram cells */
0N/A
0N/Atypedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
0N/Atypedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
0N/Atypedef hist2d * hist3d; /* type for top-level pointer */
0N/A
0N/A
0N/A/* Declarations for Floyd-Steinberg dithering.
0N/A *
0N/A * Errors are accumulated into the array fserrors[], at a resolution of
0N/A * 1/16th of a pixel count. The error at a given pixel is propagated
0N/A * to its not-yet-processed neighbors using the standard F-S fractions,
0N/A * ... (here) 7/16
0N/A * 3/16 5/16 1/16
0N/A * We work left-to-right on even rows, right-to-left on odd rows.
0N/A *
0N/A * We can get away with a single array (holding one row's worth of errors)
0N/A * by using it to store the current row's errors at pixel columns not yet
0N/A * processed, but the next row's errors at columns already processed. We
0N/A * need only a few extra variables to hold the errors immediately around the
0N/A * current column. (If we are lucky, those variables are in registers, but
0N/A * even if not, they're probably cheaper to access than array elements are.)
0N/A *
0N/A * The fserrors[] array has (#columns + 2) entries; the extra entry at
0N/A * each end saves us from special-casing the first and last pixels.
0N/A * Each entry is three values long, one value for each color component.
0N/A *
0N/A * Note: on a wide image, we might not have enough room in a PC's near data
0N/A * segment to hold the error array; so it is allocated with alloc_large.
0N/A */
0N/A
0N/A#if BITS_IN_JSAMPLE == 8
0N/Atypedef INT16 FSERROR; /* 16 bits should be enough */
0N/Atypedef int LOCFSERROR; /* use 'int' for calculation temps */
0N/A#else
0N/Atypedef INT32 FSERROR; /* may need more than 16 bits */
0N/Atypedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
0N/A#endif
0N/A
0N/Atypedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
0N/A
0N/A
0N/A/* Private subobject */
0N/A
0N/Atypedef struct {
0N/A struct jpeg_color_quantizer pub; /* public fields */
0N/A
0N/A /* Space for the eventually created colormap is stashed here */
0N/A JSAMPARRAY sv_colormap; /* colormap allocated at init time */
0N/A int desired; /* desired # of colors = size of colormap */
0N/A
0N/A /* Variables for accumulating image statistics */
0N/A hist3d histogram; /* pointer to the histogram */
0N/A
0N/A boolean needs_zeroed; /* TRUE if next pass must zero histogram */
0N/A
0N/A /* Variables for Floyd-Steinberg dithering */
0N/A FSERRPTR fserrors; /* accumulated errors */
0N/A boolean on_odd_row; /* flag to remember which row we are on */
0N/A int * error_limiter; /* table for clamping the applied error */
0N/A} my_cquantizer;
0N/A
0N/Atypedef my_cquantizer * my_cquantize_ptr;
0N/A
0N/A
0N/A/*
0N/A * Prescan some rows of pixels.
0N/A * In this module the prescan simply updates the histogram, which has been
0N/A * initialized to zeroes by start_pass.
0N/A * An output_buf parameter is required by the method signature, but no data
0N/A * is actually output (in fact the buffer controller is probably passing a
0N/A * NULL pointer).
0N/A */
0N/A
0N/AMETHODDEF(void)
0N/Aprescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
0N/A JSAMPARRAY output_buf, int num_rows)
0N/A{
0N/A my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
0N/A register JSAMPROW ptr;
0N/A register histptr histp;
0N/A register hist3d histogram = cquantize->histogram;
0N/A int row;
0N/A JDIMENSION col;
0N/A JDIMENSION width = cinfo->output_width;
0N/A
0N/A for (row = 0; row < num_rows; row++) {
0N/A ptr = input_buf[row];
0N/A for (col = width; col > 0; col--) {
0N/A /* get pixel value and index into the histogram */
0N/A histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
0N/A [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
0N/A [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
0N/A /* increment, check for overflow and undo increment if so. */
0N/A if (++(*histp) <= 0)
0N/A (*histp)--;
0N/A ptr += 3;
0N/A }
0N/A }
0N/A}
0N/A
0N/A
0N/A/*
0N/A * Next we have the really interesting routines: selection of a colormap
0N/A * given the completed histogram.
0N/A * These routines work with a list of "boxes", each representing a rectangular
0N/A * subset of the input color space (to histogram precision).
0N/A */
0N/A
0N/Atypedef struct {
0N/A /* The bounds of the box (inclusive); expressed as histogram indexes */
0N/A int c0min, c0max;
0N/A int c1min, c1max;
0N/A int c2min, c2max;
0N/A /* The volume (actually 2-norm) of the box */
0N/A INT32 volume;
0N/A /* The number of nonzero histogram cells within this box */
0N/A long colorcount;
0N/A} box;
0N/A
0N/Atypedef box * boxptr;
0N/A
0N/A
0N/ALOCAL(boxptr)
0N/Afind_biggest_color_pop (boxptr boxlist, int numboxes)
0N/A/* Find the splittable box with the largest color population */
0N/A/* Returns NULL if no splittable boxes remain */
0N/A{
0N/A register boxptr boxp;
0N/A register int i;
0N/A register long maxc = 0;
0N/A boxptr which = NULL;
0N/A
0N/A for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
0N/A if (boxp->colorcount > maxc && boxp->volume > 0) {
0N/A which = boxp;
0N/A maxc = boxp->colorcount;
0N/A }
0N/A }
0N/A return which;
0N/A}
0N/A
0N/A
0N/ALOCAL(boxptr)
0N/Afind_biggest_volume (boxptr boxlist, int numboxes)
0N/A/* Find the splittable box with the largest (scaled) volume */
0N/A/* Returns NULL if no splittable boxes remain */
0N/A{
0N/A register boxptr boxp;
0N/A register int i;
0N/A register INT32 maxv = 0;
0N/A boxptr which = NULL;
0N/A
0N/A for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
0N/A if (boxp->volume > maxv) {
0N/A which = boxp;
0N/A maxv = boxp->volume;
0N/A }
0N/A }
0N/A return which;
0N/A}
0N/A
0N/A
0N/ALOCAL(void)
0N/Aupdate_box (j_decompress_ptr cinfo, boxptr boxp)
0N/A/* Shrink the min/max bounds of a box to enclose only nonzero elements, */
0N/A/* and recompute its volume and population */
0N/A{
0N/A my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
0N/A hist3d histogram = cquantize->histogram;
0N/A histptr histp;
0N/A int c0,c1,c2;
0N/A int c0min,c0max,c1min,c1max,c2min,c2max;
0N/A INT32 dist0,dist1,dist2;
0N/A long ccount;
0N/A
0N/A c0min = boxp->c0min; c0max = boxp->c0max;
0N/A c1min = boxp->c1min; c1max = boxp->c1max;
0N/A c2min = boxp->c2min; c2max = boxp->c2max;
0N/A
0N/A if (c0max > c0min)
0N/A for (c0 = c0min; c0 <= c0max; c0++)
0N/A for (c1 = c1min; c1 <= c1max; c1++) {
0N/A histp = & histogram[c0][c1][c2min];
0N/A for (c2 = c2min; c2 <= c2max; c2++)
0N/A if (*histp++ != 0) {
0N/A boxp->c0min = c0min = c0;
0N/A goto have_c0min;
0N/A }
0N/A }
0N/A have_c0min:
0N/A if (c0max > c0min)
0N/A for (c0 = c0max; c0 >= c0min; c0--)
0N/A for (c1 = c1min; c1 <= c1max; c1++) {
0N/A histp = & histogram[c0][c1][c2min];
0N/A for (c2 = c2min; c2 <= c2max; c2++)
0N/A if (*histp++ != 0) {
0N/A boxp->c0max = c0max = c0;
0N/A goto have_c0max;
0N/A }
0N/A }
0N/A have_c0max:
0N/A if (c1max > c1min)
0N/A for (c1 = c1min; c1 <= c1max; c1++)
0N/A for (c0 = c0min; c0 <= c0max; c0++) {
0N/A histp = & histogram[c0][c1][c2min];
0N/A for (c2 = c2min; c2 <= c2max; c2++)
0N/A if (*histp++ != 0) {
0N/A boxp->c1min = c1min = c1;
0N/A goto have_c1min;
0N/A }
0N/A }
0N/A have_c1min:
0N/A if (c1max > c1min)
0N/A for (c1 = c1max; c1 >= c1min; c1--)
0N/A for (c0 = c0min; c0 <= c0max; c0++) {
0N/A histp = & histogram[c0][c1][c2min];
0N/A for (c2 = c2min; c2 <= c2max; c2++)
0N/A if (*histp++ != 0) {
0N/A boxp->c1max = c1max = c1;
0N/A goto have_c1max;
0N/A }
0N/A }
0N/A have_c1max:
0N/A if (c2max > c2min)
0N/A for (c2 = c2min; c2 <= c2max; c2++)
0N/A for (c0 = c0min; c0 <= c0max; c0++) {
0N/A histp = & histogram[c0][c1min][c2];
0N/A for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
0N/A if (*histp != 0) {
0N/A boxp->c2min = c2min = c2;
0N/A goto have_c2min;
0N/A }
0N/A }
0N/A have_c2min:
0N/A if (c2max > c2min)
0N/A for (c2 = c2max; c2 >= c2min; c2--)
0N/A for (c0 = c0min; c0 <= c0max; c0++) {
0N/A histp = & histogram[c0][c1min][c2];
0N/A for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
0N/A if (*histp != 0) {
0N/A boxp->c2max = c2max = c2;
0N/A goto have_c2max;
0N/A }
0N/A }
0N/A have_c2max:
0N/A
0N/A /* Update box volume.
0N/A * We use 2-norm rather than real volume here; this biases the method
0N/A * against making long narrow boxes, and it has the side benefit that
0N/A * a box is splittable iff norm > 0.
0N/A * Since the differences are expressed in histogram-cell units,
0N/A * we have to shift back to JSAMPLE units to get consistent distances;
0N/A * after which, we scale according to the selected distance scale factors.
0N/A */
0N/A dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
0N/A dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
0N/A dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
0N/A boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
0N/A
0N/A /* Now scan remaining volume of box and compute population */
0N/A ccount = 0;
0N/A for (c0 = c0min; c0 <= c0max; c0++)
0N/A for (c1 = c1min; c1 <= c1max; c1++) {
0N/A histp = & histogram[c0][c1][c2min];
0N/A for (c2 = c2min; c2 <= c2max; c2++, histp++)
0N/A if (*histp != 0) {
0N/A ccount++;
0N/A }
0N/A }
0N/A boxp->colorcount = ccount;
0N/A}
0N/A
0N/A
0N/ALOCAL(int)
0N/Amedian_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
0N/A int desired_colors)
0N/A/* Repeatedly select and split the largest box until we have enough boxes */
0N/A{
0N/A int n,lb;
0N/A int c0,c1,c2,cmax;
0N/A register boxptr b1,b2;
0N/A
0N/A while (numboxes < desired_colors) {
0N/A /* Select box to split.
0N/A * Current algorithm: by population for first half, then by volume.
0N/A */
0N/A if (numboxes*2 <= desired_colors) {
0N/A b1 = find_biggest_color_pop(boxlist, numboxes);
0N/A } else {
0N/A b1 = find_biggest_volume(boxlist, numboxes);
0N/A }
0N/A if (b1 == NULL) /* no splittable boxes left! */
0N/A break;
0N/A b2 = &boxlist[numboxes]; /* where new box will go */
0N/A /* Copy the color bounds to the new box. */
0N/A b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
0N/A b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
0N/A /* Choose which axis to split the box on.
0N/A * Current algorithm: longest scaled axis.
0N/A * See notes in update_box about scaling distances.
0N/A */
0N/A c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
0N/A c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
0N/A c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
0N/A /* We want to break any ties in favor of green, then red, blue last.
0N/A * This code does the right thing for R,G,B or B,G,R color orders only.
0N/A */
0N/A#if RGB_RED == 0
0N/A cmax = c1; n = 1;
0N/A if (c0 > cmax) { cmax = c0; n = 0; }
0N/A if (c2 > cmax) { n = 2; }
0N/A#else
0N/A cmax = c1; n = 1;
0N/A if (c2 > cmax) { cmax = c2; n = 2; }
0N/A if (c0 > cmax) { n = 0; }
0N/A#endif
0N/A /* Choose split point along selected axis, and update box bounds.
0N/A * Current algorithm: split at halfway point.
0N/A * (Since the box has been shrunk to minimum volume,
0N/A * any split will produce two nonempty subboxes.)
0N/A * Note that lb value is max for lower box, so must be < old max.
0N/A */
0N/A switch (n) {
0N/A case 0:
0N/A lb = (b1->c0max + b1->c0min) / 2;
0N/A b1->c0max = lb;
0N/A b2->c0min = lb+1;
0N/A break;
0N/A case 1:
0N/A lb = (b1->c1max + b1->c1min) / 2;
0N/A b1->c1max = lb;
0N/A b2->c1min = lb+1;
0N/A break;
0N/A case 2:
0N/A lb = (b1->c2max + b1->c2min) / 2;
0N/A b1->c2max = lb;
0N/A b2->c2min = lb+1;
0N/A break;
0N/A }
0N/A /* Update stats for boxes */
0N/A update_box(cinfo, b1);
0N/A update_box(cinfo, b2);
0N/A numboxes++;
0N/A }
0N/A return numboxes;
0N/A}
0N/A
0N/A
0N/ALOCAL(void)
0N/Acompute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
0N/A/* Compute representative color for a box, put it in colormap[icolor] */
0N/A{
0N/A /* Current algorithm: mean weighted by pixels (not colors) */
0N/A /* Note it is important to get the rounding correct! */
0N/A my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
0N/A hist3d histogram = cquantize->histogram;
0N/A histptr histp;
0N/A int c0,c1,c2;
0N/A int c0min,c0max,c1min,c1max,c2min,c2max;
0N/A long count;
0N/A long total = 0;
0N/A long c0total = 0;
0N/A long c1total = 0;
0N/A long c2total = 0;
0N/A
0N/A c0min = boxp->c0min; c0max = boxp->c0max;
0N/A c1min = boxp->c1min; c1max = boxp->c1max;
0N/A c2min = boxp->c2min; c2max = boxp->c2max;
0N/A
0N/A for (c0 = c0min; c0 <= c0max; c0++)
0N/A for (c1 = c1min; c1 <= c1max; c1++) {
0N/A histp = & histogram[c0][c1][c2min];
0N/A for (c2 = c2min; c2 <= c2max; c2++) {
0N/A if ((count = *histp++) != 0) {
0N/A total += count;
0N/A c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
0N/A c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
0N/A c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
0N/A }
0N/A }
0N/A }
0N/A
0N/A cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
0N/A cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
0N/A cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
0N/A}
0N/A
0N/A
0N/ALOCAL(void)
0N/Aselect_colors (j_decompress_ptr cinfo, int desired_colors)
0N/A/* Master routine for color selection */
0N/A{
0N/A boxptr boxlist;
0N/A int numboxes;
0N/A int i;
0N/A
0N/A /* Allocate workspace for box list */
0N/A boxlist = (boxptr) (*cinfo->mem->alloc_small)
0N/A ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
0N/A /* Initialize one box containing whole space */
0N/A numboxes = 1;
0N/A boxlist[0].c0min = 0;
0N/A boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
0N/A boxlist[0].c1min = 0;
0N/A boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
0N/A boxlist[0].c2min = 0;
0N/A boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
0N/A /* Shrink it to actually-used volume and set its statistics */
0N/A update_box(cinfo, & boxlist[0]);
0N/A /* Perform median-cut to produce final box list */
0N/A numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
0N/A /* Compute the representative color for each box, fill colormap */
0N/A for (i = 0; i < numboxes; i++)
0N/A compute_color(cinfo, & boxlist[i], i);
0N/A cinfo->actual_number_of_colors = numboxes;
0N/A TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
0N/A}
0N/A
0N/A
0N/A/*
0N/A * These routines are concerned with the time-critical task of mapping input
0N/A * colors to the nearest color in the selected colormap.
0N/A *
0N/A * We re-use the histogram space as an "inverse color map", essentially a
0N/A * cache for the results of nearest-color searches. All colors within a
0N/A * histogram cell will be mapped to the same colormap entry, namely the one
0N/A * closest to the cell's center. This may not be quite the closest entry to
0N/A * the actual input color, but it's almost as good. A zero in the cache
0N/A * indicates we haven't found the nearest color for that cell yet; the array
0N/A * is cleared to zeroes before starting the mapping pass. When we find the
0N/A * nearest color for a cell, its colormap index plus one is recorded in the
0N/A * cache for future use. The pass2 scanning routines call fill_inverse_cmap
0N/A * when they need to use an unfilled entry in the cache.
0N/A *
0N/A * Our method of efficiently finding nearest colors is based on the "locally
0N/A * sorted search" idea described by Heckbert and on the incremental distance
0N/A * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
0N/A * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
0N/A * the distances from a given colormap entry to each cell of the histogram can
0N/A * be computed quickly using an incremental method: the differences between
0N/A * distances to adjacent cells themselves differ by a constant. This allows a
0N/A * fairly fast implementation of the "brute force" approach of computing the
0N/A * distance from every colormap entry to every histogram cell. Unfortunately,
0N/A * it needs a work array to hold the best-distance-so-far for each histogram
0N/A * cell (because the inner loop has to be over cells, not colormap entries).
0N/A * The work array elements have to be INT32s, so the work array would need
0N/A * 256Kb at our recommended precision. This is not feasible in DOS machines.
0N/A *
0N/A * To get around these problems, we apply Thomas' method to compute the
0N/A * nearest colors for only the cells within a small subbox of the histogram.
0N/A * The work array need be only as big as the subbox, so the memory usage
0N/A * problem is solved. Furthermore, we need not fill subboxes that are never
0N/A * referenced in pass2; many images use only part of the color gamut, so a
0N/A * fair amount of work is saved. An additional advantage of this
0N/A * approach is that we can apply Heckbert's locality criterion to quickly
0N/A * eliminate colormap entries that are far away from the subbox; typically
0N/A * three-fourths of the colormap entries are rejected by Heckbert's criterion,
0N/A * and we need not compute their distances to individual cells in the subbox.
0N/A * The speed of this approach is heavily influenced by the subbox size: too
0N/A * small means too much overhead, too big loses because Heckbert's criterion
0N/A * can't eliminate as many colormap entries. Empirically the best subbox
0N/A * size seems to be about 1/512th of the histogram (1/8th in each direction).
0N/A *
0N/A * Thomas' article also describes a refined method which is asymptotically
0N/A * faster than the brute-force method, but it is also far more complex and
0N/A * cannot efficiently be applied to small subboxes. It is therefore not
0N/A * useful for programs intended to be portable to DOS machines. On machines
0N/A * with plenty of memory, filling the whole histogram in one shot with Thomas'
0N/A * refined method might be faster than the present code --- but then again,
0N/A * it might not be any faster, and it's certainly more complicated.
0N/A */
0N/A
0N/A
0N/A/* log2(histogram cells in update box) for each axis; this can be adjusted */
0N/A#define BOX_C0_LOG (HIST_C0_BITS-3)
0N/A#define BOX_C1_LOG (HIST_C1_BITS-3)
0N/A#define BOX_C2_LOG (HIST_C2_BITS-3)
0N/A
0N/A#define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
0N/A#define BOX_C1_ELEMS (1<<BOX_C1_LOG)
0N/A#define BOX_C2_ELEMS (1<<BOX_C2_LOG)
0N/A
0N/A#define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
0N/A#define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
0N/A#define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
0N/A
0N/A
0N/A/*
0N/A * The next three routines implement inverse colormap filling. They could
0N/A * all be folded into one big routine, but splitting them up this way saves
0N/A * some stack space (the mindist[] and bestdist[] arrays need not coexist)
0N/A * and may allow some compilers to produce better code by registerizing more
0N/A * inner-loop variables.
0N/A */
0N/A
0N/ALOCAL(int)
0N/Afind_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
0N/A JSAMPLE colorlist[])
0N/A/* Locate the colormap entries close enough to an update box to be candidates
0N/A * for the nearest entry to some cell(s) in the update box. The update box
0N/A * is specified by the center coordinates of its first cell. The number of
0N/A * candidate colormap entries is returned, and their colormap indexes are
0N/A * placed in colorlist[].
0N/A * This routine uses Heckbert's "locally sorted search" criterion to select
0N/A * the colors that need further consideration.
0N/A */
0N/A{
0N/A int numcolors = cinfo->actual_number_of_colors;
0N/A int maxc0, maxc1, maxc2;
0N/A int centerc0, centerc1, centerc2;
0N/A int i, x, ncolors;
0N/A INT32 minmaxdist, min_dist, max_dist, tdist;
0N/A INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
0N/A
0N/A /* Compute true coordinates of update box's upper corner and center.
0N/A * Actually we compute the coordinates of the center of the upper-corner
0N/A * histogram cell, which are the upper bounds of the volume we care about.
0N/A * Note that since ">>" rounds down, the "center" values may be closer to
0N/A * min than to max; hence comparisons to them must be "<=", not "<".
0N/A */
0N/A maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
0N/A centerc0 = (minc0 + maxc0) >> 1;
0N/A maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
0N/A centerc1 = (minc1 + maxc1) >> 1;
0N/A maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
0N/A centerc2 = (minc2 + maxc2) >> 1;
0N/A
0N/A /* For each color in colormap, find:
0N/A * 1. its minimum squared-distance to any point in the update box
0N/A * (zero if color is within update box);
0N/A * 2. its maximum squared-distance to any point in the update box.
0N/A * Both of these can be found by considering only the corners of the box.
0N/A * We save the minimum distance for each color in mindist[];
0N/A * only the smallest maximum distance is of interest.
0N/A */
0N/A minmaxdist = 0x7FFFFFFFL;
0N/A
0N/A for (i = 0; i < numcolors; i++) {
0N/A /* We compute the squared-c0-distance term, then add in the other two. */
0N/A x = GETJSAMPLE(cinfo->colormap[0][i]);
0N/A if (x < minc0) {
0N/A tdist = (x - minc0) * C0_SCALE;
0N/A min_dist = tdist*tdist;
0N/A tdist = (x - maxc0) * C0_SCALE;
0N/A max_dist = tdist*tdist;
0N/A } else if (x > maxc0) {
0N/A tdist = (x - maxc0) * C0_SCALE;
0N/A min_dist = tdist*tdist;
0N/A tdist = (x - minc0) * C0_SCALE;
0N/A max_dist = tdist*tdist;
0N/A } else {
0N/A /* within cell range so no contribution to min_dist */
0N/A min_dist = 0;
0N/A if (x <= centerc0) {
0N/A tdist = (x - maxc0) * C0_SCALE;
0N/A max_dist = tdist*tdist;
0N/A } else {
0N/A tdist = (x - minc0) * C0_SCALE;
0N/A max_dist = tdist*tdist;
0N/A }
0N/A }
0N/A
0N/A x = GETJSAMPLE(cinfo->colormap[1][i]);
0N/A if (x < minc1) {
0N/A tdist = (x - minc1) * C1_SCALE;
0N/A min_dist += tdist*tdist;
0N/A tdist = (x - maxc1) * C1_SCALE;
0N/A max_dist += tdist*tdist;
0N/A } else if (x > maxc1) {
0N/A tdist = (x - maxc1) * C1_SCALE;
0N/A min_dist += tdist*tdist;
0N/A tdist = (x - minc1) * C1_SCALE;
0N/A max_dist += tdist*tdist;
0N/A } else {
0N/A /* within cell range so no contribution to min_dist */
0N/A if (x <= centerc1) {
0N/A tdist = (x - maxc1) * C1_SCALE;
0N/A max_dist += tdist*tdist;
0N/A } else {
0N/A tdist = (x - minc1) * C1_SCALE;
0N/A max_dist += tdist*tdist;
0N/A }
0N/A }
0N/A
0N/A x = GETJSAMPLE(cinfo->colormap[2][i]);
0N/A if (x < minc2) {
0N/A tdist = (x - minc2) * C2_SCALE;
0N/A min_dist += tdist*tdist;
0N/A tdist = (x - maxc2) * C2_SCALE;
0N/A max_dist += tdist*tdist;
0N/A } else if (x > maxc2) {
0N/A tdist = (x - maxc2) * C2_SCALE;
0N/A min_dist += tdist*tdist;
0N/A tdist = (x - minc2) * C2_SCALE;
0N/A max_dist += tdist*tdist;
0N/A } else {
0N/A /* within cell range so no contribution to min_dist */
0N/A if (x <= centerc2) {
0N/A tdist = (x - maxc2) * C2_SCALE;
0N/A max_dist += tdist*tdist;
0N/A } else {
0N/A tdist = (x - minc2) * C2_SCALE;
0N/A max_dist += tdist*tdist;
0N/A }
0N/A }
0N/A
0N/A mindist[i] = min_dist; /* save away the results */
0N/A if (max_dist < minmaxdist)
0N/A minmaxdist = max_dist;
0N/A }
0N/A
0N/A /* Now we know that no cell in the update box is more than minmaxdist
0N/A * away from some colormap entry. Therefore, only colors that are
0N/A * within minmaxdist of some part of the box need be considered.
0N/A */
0N/A ncolors = 0;
0N/A for (i = 0; i < numcolors; i++) {
0N/A if (mindist[i] <= minmaxdist)
0N/A colorlist[ncolors++] = (JSAMPLE) i;
0N/A }
0N/A return ncolors;
0N/A}
0N/A
0N/A
0N/ALOCAL(void)
0N/Afind_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
0N/A int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
0N/A/* Find the closest colormap entry for each cell in the update box,
0N/A * given the list of candidate colors prepared by find_nearby_colors.
0N/A * Return the indexes of the closest entries in the bestcolor[] array.
0N/A * This routine uses Thomas' incremental distance calculation method to
0N/A * find the distance from a colormap entry to successive cells in the box.
0N/A */
0N/A{
0N/A int ic0, ic1, ic2;
0N/A int i, icolor;
0N/A register INT32 * bptr; /* pointer into bestdist[] array */
0N/A JSAMPLE * cptr; /* pointer into bestcolor[] array */
0N/A INT32 dist0, dist1; /* initial distance values */
0N/A register INT32 dist2; /* current distance in inner loop */
0N/A INT32 xx0, xx1; /* distance increments */
0N/A register INT32 xx2;
0N/A INT32 inc0, inc1, inc2; /* initial values for increments */
0N/A /* This array holds the distance to the nearest-so-far color for each cell */
0N/A INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
0N/A
0N/A /* Initialize best-distance for each cell of the update box */
0N/A bptr = bestdist;
0N/A for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
0N/A *bptr++ = 0x7FFFFFFFL;
0N/A
0N/A /* For each color selected by find_nearby_colors,
0N/A * compute its distance to the center of each cell in the box.
0N/A * If that's less than best-so-far, update best distance and color number.
0N/A */
0N/A
0N/A /* Nominal steps between cell centers ("x" in Thomas article) */
0N/A#define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
0N/A#define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
0N/A#define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
0N/A
0N/A for (i = 0; i < numcolors; i++) {
0N/A icolor = GETJSAMPLE(colorlist[i]);
0N/A /* Compute (square of) distance from minc0/c1/c2 to this color */
0N/A inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
0N/A dist0 = inc0*inc0;
0N/A inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
0N/A dist0 += inc1*inc1;
0N/A inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
0N/A dist0 += inc2*inc2;
0N/A /* Form the initial difference increments */
0N/A inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
0N/A inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
0N/A inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
0N/A /* Now loop over all cells in box, updating distance per Thomas method */
0N/A bptr = bestdist;
0N/A cptr = bestcolor;
0N/A xx0 = inc0;
0N/A for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
0N/A dist1 = dist0;
0N/A xx1 = inc1;
0N/A for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
0N/A dist2 = dist1;
0N/A xx2 = inc2;
0N/A for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
0N/A if (dist2 < *bptr) {
0N/A *bptr = dist2;
0N/A *cptr = (JSAMPLE) icolor;
0N/A }
0N/A dist2 += xx2;
0N/A xx2 += 2 * STEP_C2 * STEP_C2;
0N/A bptr++;
0N/A cptr++;
0N/A }
0N/A dist1 += xx1;
0N/A xx1 += 2 * STEP_C1 * STEP_C1;
0N/A }
0N/A dist0 += xx0;
0N/A xx0 += 2 * STEP_C0 * STEP_C0;
0N/A }
0N/A }
0N/A}
0N/A
0N/A
0N/ALOCAL(void)
0N/Afill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
0N/A/* Fill the inverse-colormap entries in the update box that contains */
0N/A/* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
0N/A/* we can fill as many others as we wish.) */
0N/A{
0N/A my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
0N/A hist3d histogram = cquantize->histogram;
0N/A int minc0, minc1, minc2; /* lower left corner of update box */
0N/A int ic0, ic1, ic2;
0N/A register JSAMPLE * cptr; /* pointer into bestcolor[] array */
0N/A register histptr cachep; /* pointer into main cache array */
0N/A /* This array lists the candidate colormap indexes. */
0N/A JSAMPLE colorlist[MAXNUMCOLORS];
0N/A int numcolors; /* number of candidate colors */
0N/A /* This array holds the actually closest colormap index for each cell. */
0N/A JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
0N/A
0N/A /* Convert cell coordinates to update box ID */
0N/A c0 >>= BOX_C0_LOG;
0N/A c1 >>= BOX_C1_LOG;
0N/A c2 >>= BOX_C2_LOG;
0N/A
0N/A /* Compute true coordinates of update box's origin corner.
0N/A * Actually we compute the coordinates of the center of the corner
0N/A * histogram cell, which are the lower bounds of the volume we care about.
0N/A */
0N/A minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
0N/A minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
0N/A minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
0N/A
0N/A /* Determine which colormap entries are close enough to be candidates
0N/A * for the nearest entry to some cell in the update box.
0N/A */
0N/A numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
0N/A
0N/A /* Determine the actually nearest colors. */
0N/A find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
0N/A bestcolor);
0N/A
0N/A /* Save the best color numbers (plus 1) in the main cache array */
0N/A c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
0N/A c1 <<= BOX_C1_LOG;
0N/A c2 <<= BOX_C2_LOG;
0N/A cptr = bestcolor;
0N/A for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
0N/A for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
0N/A cachep = & histogram[c0+ic0][c1+ic1][c2];
0N/A for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
0N/A *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
0N/A }
0N/A }
0N/A }
0N/A}
0N/A
0N/A
0N/A/*
0N/A * Map some rows of pixels to the output colormapped representation.
0N/A */
0N/A
0N/AMETHODDEF(void)
0N/Apass2_no_dither (j_decompress_ptr cinfo,
0N/A JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
0N/A/* This version performs no dithering */
0N/A{
0N/A my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
0N/A hist3d histogram = cquantize->histogram;
0N/A register JSAMPROW inptr, outptr;
0N/A register histptr cachep;
0N/A register int c0, c1, c2;
0N/A int row;
0N/A JDIMENSION col;
0N/A JDIMENSION width = cinfo->output_width;
0N/A
0N/A for (row = 0; row < num_rows; row++) {
0N/A inptr = input_buf[row];
0N/A outptr = output_buf[row];
0N/A for (col = width; col > 0; col--) {
0N/A /* get pixel value and index into the cache */
0N/A c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
0N/A c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
0N/A c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
0N/A cachep = & histogram[c0][c1][c2];
0N/A /* If we have not seen this color before, find nearest colormap entry */
0N/A /* and update the cache */
0N/A if (*cachep == 0)
0N/A fill_inverse_cmap(cinfo, c0,c1,c2);
0N/A /* Now emit the colormap index for this cell */
0N/A *outptr++ = (JSAMPLE) (*cachep - 1);
0N/A }
0N/A }
0N/A}
0N/A
0N/A
0N/AMETHODDEF(void)
0N/Apass2_fs_dither (j_decompress_ptr cinfo,
0N/A JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
0N/A/* This version performs Floyd-Steinberg dithering */
0N/A{
0N/A my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
0N/A hist3d histogram = cquantize->histogram;
0N/A register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
0N/A LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
0N/A LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
0N/A register FSERRPTR errorptr; /* => fserrors[] at column before current */
0N/A JSAMPROW inptr; /* => current input pixel */
0N/A JSAMPROW outptr; /* => current output pixel */
0N/A histptr cachep;
0N/A int dir; /* +1 or -1 depending on direction */
0N/A int dir3; /* 3*dir, for advancing inptr & errorptr */
0N/A int row;
0N/A JDIMENSION col;
0N/A JDIMENSION width = cinfo->output_width;
0N/A JSAMPLE *range_limit = cinfo->sample_range_limit;
0N/A int *error_limit = cquantize->error_limiter;
0N/A JSAMPROW colormap0 = cinfo->colormap[0];
0N/A JSAMPROW colormap1 = cinfo->colormap[1];
0N/A JSAMPROW colormap2 = cinfo->colormap[2];
0N/A SHIFT_TEMPS
0N/A
0N/A for (row = 0; row < num_rows; row++) {
0N/A inptr = input_buf[row];
0N/A outptr = output_buf[row];
0N/A if (cquantize->on_odd_row) {
0N/A /* work right to left in this row */
0N/A inptr += (width-1) * 3; /* so point to rightmost pixel */
0N/A outptr += width-1;
0N/A dir = -1;
0N/A dir3 = -3;
0N/A errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
0N/A cquantize->on_odd_row = FALSE; /* flip for next time */
0N/A } else {
0N/A /* work left to right in this row */
0N/A dir = 1;
0N/A dir3 = 3;
0N/A errorptr = cquantize->fserrors; /* => entry before first real column */
0N/A cquantize->on_odd_row = TRUE; /* flip for next time */
0N/A }
0N/A /* Preset error values: no error propagated to first pixel from left */
0N/A cur0 = cur1 = cur2 = 0;
0N/A /* and no error propagated to row below yet */
0N/A belowerr0 = belowerr1 = belowerr2 = 0;
0N/A bpreverr0 = bpreverr1 = bpreverr2 = 0;
0N/A
0N/A for (col = width; col > 0; col--) {
0N/A /* curN holds the error propagated from the previous pixel on the
0N/A * current line. Add the error propagated from the previous line
0N/A * to form the complete error correction term for this pixel, and
0N/A * round the error term (which is expressed * 16) to an integer.
0N/A * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
0N/A * for either sign of the error value.
0N/A * Note: errorptr points to *previous* column's array entry.
0N/A */
0N/A cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
0N/A cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
0N/A cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
0N/A /* Limit the error using transfer function set by init_error_limit.
0N/A * See comments with init_error_limit for rationale.
0N/A */
0N/A cur0 = error_limit[cur0];
0N/A cur1 = error_limit[cur1];
0N/A cur2 = error_limit[cur2];
0N/A /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
0N/A * The maximum error is +- MAXJSAMPLE (or less with error limiting);
0N/A * this sets the required size of the range_limit array.
0N/A */
0N/A cur0 += GETJSAMPLE(inptr[0]);
0N/A cur1 += GETJSAMPLE(inptr[1]);
0N/A cur2 += GETJSAMPLE(inptr[2]);
0N/A cur0 = GETJSAMPLE(range_limit[cur0]);
0N/A cur1 = GETJSAMPLE(range_limit[cur1]);
0N/A cur2 = GETJSAMPLE(range_limit[cur2]);
0N/A /* Index into the cache with adjusted pixel value */
0N/A cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
0N/A /* If we have not seen this color before, find nearest colormap */
0N/A /* entry and update the cache */
0N/A if (*cachep == 0)
0N/A fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
0N/A /* Now emit the colormap index for this cell */
0N/A { register int pixcode = *cachep - 1;
0N/A *outptr = (JSAMPLE) pixcode;
0N/A /* Compute representation error for this pixel */
0N/A cur0 -= GETJSAMPLE(colormap0[pixcode]);
0N/A cur1 -= GETJSAMPLE(colormap1[pixcode]);
0N/A cur2 -= GETJSAMPLE(colormap2[pixcode]);
0N/A }
0N/A /* Compute error fractions to be propagated to adjacent pixels.
0N/A * Add these into the running sums, and simultaneously shift the
0N/A * next-line error sums left by 1 column.
0N/A */
0N/A { register LOCFSERROR bnexterr, delta;
0N/A
0N/A bnexterr = cur0; /* Process component 0 */
0N/A delta = cur0 * 2;
0N/A cur0 += delta; /* form error * 3 */
0N/A errorptr[0] = (FSERROR) (bpreverr0 + cur0);
0N/A cur0 += delta; /* form error * 5 */
0N/A bpreverr0 = belowerr0 + cur0;
0N/A belowerr0 = bnexterr;
0N/A cur0 += delta; /* form error * 7 */
0N/A bnexterr = cur1; /* Process component 1 */
0N/A delta = cur1 * 2;
0N/A cur1 += delta; /* form error * 3 */
0N/A errorptr[1] = (FSERROR) (bpreverr1 + cur1);
0N/A cur1 += delta; /* form error * 5 */
0N/A bpreverr1 = belowerr1 + cur1;
0N/A belowerr1 = bnexterr;
0N/A cur1 += delta; /* form error * 7 */
0N/A bnexterr = cur2; /* Process component 2 */
0N/A delta = cur2 * 2;
0N/A cur2 += delta; /* form error * 3 */
0N/A errorptr[2] = (FSERROR) (bpreverr2 + cur2);
0N/A cur2 += delta; /* form error * 5 */
0N/A bpreverr2 = belowerr2 + cur2;
0N/A belowerr2 = bnexterr;
0N/A cur2 += delta; /* form error * 7 */
0N/A }
0N/A /* At this point curN contains the 7/16 error value to be propagated
0N/A * to the next pixel on the current line, and all the errors for the
0N/A * next line have been shifted over. We are therefore ready to move on.
0N/A */
0N/A inptr += dir3; /* Advance pixel pointers to next column */
0N/A outptr += dir;
0N/A errorptr += dir3; /* advance errorptr to current column */
0N/A }
0N/A /* Post-loop cleanup: we must unload the final error values into the
0N/A * final fserrors[] entry. Note we need not unload belowerrN because
0N/A * it is for the dummy column before or after the actual array.
0N/A */
0N/A errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
0N/A errorptr[1] = (FSERROR) bpreverr1;
0N/A errorptr[2] = (FSERROR) bpreverr2;
0N/A }
0N/A}
0N/A
0N/A
0N/A/*
0N/A * Initialize the error-limiting transfer function (lookup table).
0N/A * The raw F-S error computation can potentially compute error values of up to
0N/A * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
0N/A * much less, otherwise obviously wrong pixels will be created. (Typical
0N/A * effects include weird fringes at color-area boundaries, isolated bright
0N/A * pixels in a dark area, etc.) The standard advice for avoiding this problem
0N/A * is to ensure that the "corners" of the color cube are allocated as output
0N/A * colors; then repeated errors in the same direction cannot cause cascading
0N/A * error buildup. However, that only prevents the error from getting
0N/A * completely out of hand; Aaron Giles reports that error limiting improves
0N/A * the results even with corner colors allocated.
0N/A * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
0N/A * well, but the smoother transfer function used below is even better. Thanks
0N/A * to Aaron Giles for this idea.
0N/A */
0N/A
0N/ALOCAL(void)
0N/Ainit_error_limit (j_decompress_ptr cinfo)
0N/A/* Allocate and fill in the error_limiter table */
0N/A{
0N/A my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
0N/A int * table;
0N/A int in, out;
0N/A
0N/A table = (int *) (*cinfo->mem->alloc_small)
0N/A ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
0N/A table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
0N/A cquantize->error_limiter = table;
0N/A
0N/A#define STEPSIZE ((MAXJSAMPLE+1)/16)
0N/A /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
0N/A out = 0;
0N/A for (in = 0; in < STEPSIZE; in++, out++) {
0N/A table[in] = out; table[-in] = -out;
0N/A }
0N/A /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
0N/A for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
0N/A table[in] = out; table[-in] = -out;
0N/A }
0N/A /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
0N/A for (; in <= MAXJSAMPLE; in++) {
0N/A table[in] = out; table[-in] = -out;
0N/A }
0N/A#undef STEPSIZE
0N/A}
0N/A
0N/A
0N/A/*
0N/A * Finish up at the end of each pass.
0N/A */
0N/A
0N/AMETHODDEF(void)
0N/Afinish_pass1 (j_decompress_ptr cinfo)
0N/A{
0N/A my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
0N/A
0N/A /* Select the representative colors and fill in cinfo->colormap */
0N/A cinfo->colormap = cquantize->sv_colormap;
0N/A select_colors(cinfo, cquantize->desired);
0N/A /* Force next pass to zero the color index table */
0N/A cquantize->needs_zeroed = TRUE;
0N/A}
0N/A
0N/A
0N/AMETHODDEF(void)
0N/Afinish_pass2 (j_decompress_ptr cinfo)
0N/A{
0N/A /* no work */
0N/A}
0N/A
0N/A
0N/A/*
0N/A * Initialize for each processing pass.
0N/A */
0N/A
0N/AMETHODDEF(void)
0N/Astart_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
0N/A{
0N/A my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
0N/A hist3d histogram = cquantize->histogram;
0N/A int i;
0N/A
0N/A /* Only F-S dithering or no dithering is supported. */
0N/A /* If user asks for ordered dither, give him F-S. */
0N/A if (cinfo->dither_mode != JDITHER_NONE)
0N/A cinfo->dither_mode = JDITHER_FS;
0N/A
0N/A if (is_pre_scan) {
0N/A /* Set up method pointers */
0N/A cquantize->pub.color_quantize = prescan_quantize;
0N/A cquantize->pub.finish_pass = finish_pass1;
0N/A cquantize->needs_zeroed = TRUE; /* Always zero histogram */
0N/A } else {
0N/A /* Set up method pointers */
0N/A if (cinfo->dither_mode == JDITHER_FS)
0N/A cquantize->pub.color_quantize = pass2_fs_dither;
0N/A else
0N/A cquantize->pub.color_quantize = pass2_no_dither;
0N/A cquantize->pub.finish_pass = finish_pass2;
0N/A
0N/A /* Make sure color count is acceptable */
0N/A i = cinfo->actual_number_of_colors;
0N/A if (i < 1)
0N/A ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
0N/A if (i > MAXNUMCOLORS)
0N/A ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
0N/A
0N/A if (cinfo->dither_mode == JDITHER_FS) {
0N/A size_t arraysize = (size_t) ((cinfo->output_width + 2) *
0N/A (3 * SIZEOF(FSERROR)));
0N/A /* Allocate Floyd-Steinberg workspace if we didn't already. */
0N/A if (cquantize->fserrors == NULL)
0N/A cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
0N/A ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
0N/A /* Initialize the propagated errors to zero. */
0N/A jzero_far((void FAR *) cquantize->fserrors, arraysize);
0N/A /* Make the error-limit table if we didn't already. */
0N/A if (cquantize->error_limiter == NULL)
0N/A init_error_limit(cinfo);
0N/A cquantize->on_odd_row = FALSE;
0N/A }
0N/A
0N/A }
0N/A /* Zero the histogram or inverse color map, if necessary */
0N/A if (cquantize->needs_zeroed) {
0N/A for (i = 0; i < HIST_C0_ELEMS; i++) {
0N/A jzero_far((void FAR *) histogram[i],
0N/A HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
0N/A }
0N/A cquantize->needs_zeroed = FALSE;
0N/A }
0N/A}
0N/A
0N/A
0N/A/*
0N/A * Switch to a new external colormap between output passes.
0N/A */
0N/A
0N/AMETHODDEF(void)
0N/Anew_color_map_2_quant (j_decompress_ptr cinfo)
0N/A{
0N/A my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
0N/A
0N/A /* Reset the inverse color map */
0N/A cquantize->needs_zeroed = TRUE;
0N/A}
0N/A
0N/A
0N/A/*
0N/A * Module initialization routine for 2-pass color quantization.
0N/A */
0N/A
0N/AGLOBAL(void)
0N/Ajinit_2pass_quantizer (j_decompress_ptr cinfo)
0N/A{
0N/A my_cquantize_ptr cquantize;
0N/A int i;
0N/A
0N/A cquantize = (my_cquantize_ptr)
0N/A (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
0N/A SIZEOF(my_cquantizer));
0N/A cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
0N/A cquantize->pub.start_pass = start_pass_2_quant;
0N/A cquantize->pub.new_color_map = new_color_map_2_quant;
0N/A cquantize->fserrors = NULL; /* flag optional arrays not allocated */
0N/A cquantize->error_limiter = NULL;
0N/A
0N/A /* Make sure jdmaster didn't give me a case I can't handle */
0N/A if (cinfo->out_color_components != 3)
0N/A ERREXIT(cinfo, JERR_NOTIMPL);
0N/A
0N/A /* Allocate the histogram/inverse colormap storage */
0N/A cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
0N/A ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
0N/A for (i = 0; i < HIST_C0_ELEMS; i++) {
0N/A cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
0N/A ((j_common_ptr) cinfo, JPOOL_IMAGE,
0N/A HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
0N/A }
0N/A cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
0N/A
0N/A /* Allocate storage for the completed colormap, if required.
0N/A * We do this now since it is FAR storage and may affect
0N/A * the memory manager's space calculations.
0N/A */
0N/A if (cinfo->enable_2pass_quant) {
0N/A /* Make sure color count is acceptable */
0N/A int desired = cinfo->desired_number_of_colors;
0N/A /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
0N/A if (desired < 8)
0N/A ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
0N/A /* Make sure colormap indexes can be represented by JSAMPLEs */
0N/A if (desired > MAXNUMCOLORS)
0N/A ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
0N/A cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
0N/A ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
0N/A cquantize->desired = desired;
0N/A } else
0N/A cquantize->sv_colormap = NULL;
0N/A
0N/A /* Only F-S dithering or no dithering is supported. */
0N/A /* If user asks for ordered dither, give him F-S. */
0N/A if (cinfo->dither_mode != JDITHER_NONE)
0N/A cinfo->dither_mode = JDITHER_FS;
0N/A
0N/A /* Allocate Floyd-Steinberg workspace if necessary.
0N/A * This isn't really needed until pass 2, but again it is FAR storage.
0N/A * Although we will cope with a later change in dither_mode,
0N/A * we do not promise to honor max_memory_to_use if dither_mode changes.
0N/A */
0N/A if (cinfo->dither_mode == JDITHER_FS) {
0N/A cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
0N/A ((j_common_ptr) cinfo, JPOOL_IMAGE,
0N/A (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
0N/A /* Might as well create the error-limiting table too. */
0N/A init_error_limit(cinfo);
0N/A }
0N/A}
0N/A
0N/A#endif /* QUANT_2PASS_SUPPORTED */