0N/A * reserved comment block 0N/A * DO NOT REMOVE OR ALTER! 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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#
define R_SCALE 2 /* scale R distances by this much */ 0N/A#
define G_SCALE 3 /* scale G distances by this much */ 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 * First we have the histogram data structure and routines for creating it. 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/* 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/* Number of elements along histogram axes. */ 0N/A/* These are the amounts to shift an input value to get a histogram index. */ 0N/A/* Declarations for Floyd-Steinberg dithering. 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 * We work left-to-right on even rows, right-to-left on odd rows. 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 * 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 * 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/* Private subobject */ 0N/A /* Space for the eventually created colormap is stashed here */ 0N/A int desired;
/* desired # of colors = size of colormap */ 0N/A /* Variables for accumulating image statistics */ 0N/A /* Variables for Floyd-Steinberg dithering */ 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 /* get pixel value and index into the histogram */ 0N/A /* increment, check for overflow and undo increment if so. */ 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 /* The bounds of the box (inclusive); expressed as histogram indexes */ 0N/A /* The volume (actually 2-norm) of the box */ 0N/A /* The number of nonzero histogram cells within this box */ 0N/A/* Find the splittable box with the largest color population */ 0N/A/* Returns NULL if no splittable boxes remain */ 0N/A/* Find the splittable box with the largest (scaled) volume */ 0N/A/* Returns NULL if no splittable boxes remain */ 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 /* 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 /* Now scan remaining volume of box and compute population */ 0N/A/* Repeatedly select and split the largest box until we have enough boxes */ 0N/A /* Select box to split. 0N/A * Current algorithm: by population for first half, then by volume. 0N/A if (
b1 ==
NULL)
/* no splittable boxes left! */ 0N/A /* Copy the color bounds to the new box. */ 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 /* 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 /* 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 /* Update stats for boxes */ 0N/A/* Compute representative color for a box, put it in colormap[icolor] */ 0N/A /* Current algorithm: mean weighted by pixels (not colors) */ 0N/A /* Note it is important to get the rounding correct! */ 0N/A/* Master routine for color selection */ 0N/A /* Allocate workspace for box list */ 0N/A /* Initialize one box containing whole space */ 0N/A /* Shrink it to actually-used volume and set its statistics */ 0N/A /* Perform median-cut to produce final box list */ 0N/A /* Compute the representative color for each box, fill colormap */ 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 * 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 * 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 * 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 * 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/* log2(histogram cells in update box) for each axis; this can be adjusted */ 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/* 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 /* 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 /* 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 /* We compute the squared-c0-distance term, then add in the other two. */ 0N/A /* within cell range so no contribution to min_dist */ 0N/A /* within cell range so no contribution to min_dist */ 0N/A /* within cell range so no contribution to min_dist */ 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/* 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 /* This array holds the distance to the nearest-so-far color for each cell */ 0N/A /* Initialize best-distance for each cell of the update box */ 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 /* Nominal steps between cell centers ("x" in Thomas article) */ 0N/A /* Compute (square of) distance from minc0/c1/c2 to this color */ 0N/A /* Form the initial difference increments */ 0N/A /* Now loop over all cells in box, updating distance per Thomas method */ 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 /* This array lists the candidate colormap indexes. */ 0N/A /* This array holds the actually closest colormap index for each cell. */ 0N/A /* Convert cell coordinates to update box ID */ 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 /* 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 /* Determine the actually nearest colors. */ 0N/A /* Save the best color numbers (plus 1) in the main cache array */ 0N/A * Map some rows of pixels to the output colormapped representation. 0N/A/* This version performs no dithering */ 0N/A /* get pixel value and index into the cache */ 0N/A /* If we have not seen this color before, find nearest colormap entry */ 0N/A /* and update the cache */ 0N/A /* Now emit the colormap index for this cell */ 0N/A/* This version performs Floyd-Steinberg dithering */ 0N/A int dir;
/* +1 or -1 depending on direction */ 0N/A int dir3;
/* 3*dir, for advancing inptr & errorptr */ 0N/A /* work right to left in this row */ 0N/A /* work left to right in this row */ 0N/A /* Preset error values: no error propagated to first pixel from left */ 0N/A /* and no error propagated to row below yet */ 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 /* Limit the error using transfer function set by init_error_limit. 0N/A * See comments with init_error_limit for rationale. 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 /* Index into the cache with adjusted pixel value */ 0N/A /* If we have not seen this color before, find nearest colormap */ 0N/A /* entry and update the cache */ 0N/A /* Now emit the colormap index for this cell */ 0N/A /* Compute representation error for this pixel */ 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 /* 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 /* 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 * 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/* Allocate and fill in the error_limiter table */ 0N/A /* Map errors 1:1 up to +- MAXJSAMPLE/16 */ 0N/A /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */ 0N/A /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */ 0N/A * Finish up at the end of each pass. 0N/A /* Select the representative colors and fill in cinfo->colormap */ 0N/A /* Force next pass to zero the color index table */ 0N/A * Initialize for each processing pass. 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 /* Set up method pointers */ 0N/A /* Set up method pointers */ 0N/A /* Make sure color count is acceptable */ 0N/A /* Allocate Floyd-Steinberg workspace if we didn't already. */ 0N/A /* Initialize the propagated errors to zero. */ 0N/A /* Make the error-limit table if we didn't already. */ 0N/A /* Zero the histogram or inverse color map, if necessary */ 0N/A * Switch to a new external colormap between output passes. 0N/A /* Reset the inverse color map */ 0N/A * Module initialization routine for 2-pass color quantization. 0N/A /* Make sure jdmaster didn't give me a case I can't handle */ 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 /* Make sure color count is acceptable */ 0N/A /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */ 0N/A /* Make sure colormap indexes can be represented by JSAMPLEs */ 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 /* 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 /* Might as well create the error-limiting table too. */ 0N/A#
endif /* QUANT_2PASS_SUPPORTED */