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