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