istereo

annotate libs/libjpeg/jquant2.c @ 43:73813c1176de

better hgignore
author John Tsiombikas <nuclear@member.fsf.org>
date Fri, 14 Aug 2015 04:33:42 +0300
parents
children
rev   line source
nuclear@26 1 /*
nuclear@26 2 * jquant2.c
nuclear@26 3 *
nuclear@26 4 * Copyright (C) 1991-1996, Thomas G. Lane.
nuclear@26 5 * This file is part of the Independent JPEG Group's software.
nuclear@26 6 * For conditions of distribution and use, see the accompanying README file.
nuclear@26 7 *
nuclear@26 8 * This file contains 2-pass color quantization (color mapping) routines.
nuclear@26 9 * These routines provide selection of a custom color map for an image,
nuclear@26 10 * followed by mapping of the image to that color map, with optional
nuclear@26 11 * Floyd-Steinberg dithering.
nuclear@26 12 * It is also possible to use just the second pass to map to an arbitrary
nuclear@26 13 * externally-given color map.
nuclear@26 14 *
nuclear@26 15 * Note: ordered dithering is not supported, since there isn't any fast
nuclear@26 16 * way to compute intercolor distances; it's unclear that ordered dither's
nuclear@26 17 * fundamental assumptions even hold with an irregularly spaced color map.
nuclear@26 18 */
nuclear@26 19
nuclear@26 20 #define JPEG_INTERNALS
nuclear@26 21 #include "jinclude.h"
nuclear@26 22 #include "jpeglib.h"
nuclear@26 23
nuclear@26 24 #ifdef QUANT_2PASS_SUPPORTED
nuclear@26 25
nuclear@26 26
nuclear@26 27 /*
nuclear@26 28 * This module implements the well-known Heckbert paradigm for color
nuclear@26 29 * quantization. Most of the ideas used here can be traced back to
nuclear@26 30 * Heckbert's seminal paper
nuclear@26 31 * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
nuclear@26 32 * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
nuclear@26 33 *
nuclear@26 34 * In the first pass over the image, we accumulate a histogram showing the
nuclear@26 35 * usage count of each possible color. To keep the histogram to a reasonable
nuclear@26 36 * size, we reduce the precision of the input; typical practice is to retain
nuclear@26 37 * 5 or 6 bits per color, so that 8 or 4 different input values are counted
nuclear@26 38 * in the same histogram cell.
nuclear@26 39 *
nuclear@26 40 * Next, the color-selection step begins with a box representing the whole
nuclear@26 41 * color space, and repeatedly splits the "largest" remaining box until we
nuclear@26 42 * have as many boxes as desired colors. Then the mean color in each
nuclear@26 43 * remaining box becomes one of the possible output colors.
nuclear@26 44 *
nuclear@26 45 * The second pass over the image maps each input pixel to the closest output
nuclear@26 46 * color (optionally after applying a Floyd-Steinberg dithering correction).
nuclear@26 47 * This mapping is logically trivial, but making it go fast enough requires
nuclear@26 48 * considerable care.
nuclear@26 49 *
nuclear@26 50 * Heckbert-style quantizers vary a good deal in their policies for choosing
nuclear@26 51 * the "largest" box and deciding where to cut it. The particular policies
nuclear@26 52 * used here have proved out well in experimental comparisons, but better ones
nuclear@26 53 * may yet be found.
nuclear@26 54 *
nuclear@26 55 * In earlier versions of the IJG code, this module quantized in YCbCr color
nuclear@26 56 * space, processing the raw upsampled data without a color conversion step.
nuclear@26 57 * This allowed the color conversion math to be done only once per colormap
nuclear@26 58 * entry, not once per pixel. However, that optimization precluded other
nuclear@26 59 * useful optimizations (such as merging color conversion with upsampling)
nuclear@26 60 * and it also interfered with desired capabilities such as quantizing to an
nuclear@26 61 * externally-supplied colormap. We have therefore abandoned that approach.
nuclear@26 62 * The present code works in the post-conversion color space, typically RGB.
nuclear@26 63 *
nuclear@26 64 * To improve the visual quality of the results, we actually work in scaled
nuclear@26 65 * RGB space, giving G distances more weight than R, and R in turn more than
nuclear@26 66 * B. To do everything in integer math, we must use integer scale factors.
nuclear@26 67 * The 2/3/1 scale factors used here correspond loosely to the relative
nuclear@26 68 * weights of the colors in the NTSC grayscale equation.
nuclear@26 69 * If you want to use this code to quantize a non-RGB color space, you'll
nuclear@26 70 * probably need to change these scale factors.
nuclear@26 71 */
nuclear@26 72
nuclear@26 73 #define R_SCALE 2 /* scale R distances by this much */
nuclear@26 74 #define G_SCALE 3 /* scale G distances by this much */
nuclear@26 75 #define B_SCALE 1 /* and B by this much */
nuclear@26 76
nuclear@26 77 /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
nuclear@26 78 * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
nuclear@26 79 * and B,G,R orders. If you define some other weird order in jmorecfg.h,
nuclear@26 80 * you'll get compile errors until you extend this logic. In that case
nuclear@26 81 * you'll probably want to tweak the histogram sizes too.
nuclear@26 82 */
nuclear@26 83
nuclear@26 84 #if RGB_RED == 0
nuclear@26 85 #define C0_SCALE R_SCALE
nuclear@26 86 #endif
nuclear@26 87 #if RGB_BLUE == 0
nuclear@26 88 #define C0_SCALE B_SCALE
nuclear@26 89 #endif
nuclear@26 90 #if RGB_GREEN == 1
nuclear@26 91 #define C1_SCALE G_SCALE
nuclear@26 92 #endif
nuclear@26 93 #if RGB_RED == 2
nuclear@26 94 #define C2_SCALE R_SCALE
nuclear@26 95 #endif
nuclear@26 96 #if RGB_BLUE == 2
nuclear@26 97 #define C2_SCALE B_SCALE
nuclear@26 98 #endif
nuclear@26 99
nuclear@26 100
nuclear@26 101 /*
nuclear@26 102 * First we have the histogram data structure and routines for creating it.
nuclear@26 103 *
nuclear@26 104 * The number of bits of precision can be adjusted by changing these symbols.
nuclear@26 105 * We recommend keeping 6 bits for G and 5 each for R and B.
nuclear@26 106 * If you have plenty of memory and cycles, 6 bits all around gives marginally
nuclear@26 107 * better results; if you are short of memory, 5 bits all around will save
nuclear@26 108 * some space but degrade the results.
nuclear@26 109 * To maintain a fully accurate histogram, we'd need to allocate a "long"
nuclear@26 110 * (preferably unsigned long) for each cell. In practice this is overkill;
nuclear@26 111 * we can get by with 16 bits per cell. Few of the cell counts will overflow,
nuclear@26 112 * and clamping those that do overflow to the maximum value will give close-
nuclear@26 113 * enough results. This reduces the recommended histogram size from 256Kb
nuclear@26 114 * to 128Kb, which is a useful savings on PC-class machines.
nuclear@26 115 * (In the second pass the histogram space is re-used for pixel mapping data;
nuclear@26 116 * in that capacity, each cell must be able to store zero to the number of
nuclear@26 117 * desired colors. 16 bits/cell is plenty for that too.)
nuclear@26 118 * Since the JPEG code is intended to run in small memory model on 80x86
nuclear@26 119 * machines, we can't just allocate the histogram in one chunk. Instead
nuclear@26 120 * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
nuclear@26 121 * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
nuclear@26 122 * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
nuclear@26 123 * on 80x86 machines, the pointer row is in near memory but the actual
nuclear@26 124 * arrays are in far memory (same arrangement as we use for image arrays).
nuclear@26 125 */
nuclear@26 126
nuclear@26 127 #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
nuclear@26 128
nuclear@26 129 /* These will do the right thing for either R,G,B or B,G,R color order,
nuclear@26 130 * but you may not like the results for other color orders.
nuclear@26 131 */
nuclear@26 132 #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
nuclear@26 133 #define HIST_C1_BITS 6 /* bits of precision in G histogram */
nuclear@26 134 #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
nuclear@26 135
nuclear@26 136 /* Number of elements along histogram axes. */
nuclear@26 137 #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
nuclear@26 138 #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
nuclear@26 139 #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
nuclear@26 140
nuclear@26 141 /* These are the amounts to shift an input value to get a histogram index. */
nuclear@26 142 #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
nuclear@26 143 #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
nuclear@26 144 #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
nuclear@26 145
nuclear@26 146
nuclear@26 147 typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
nuclear@26 148
nuclear@26 149 typedef histcell FAR * histptr; /* for pointers to histogram cells */
nuclear@26 150
nuclear@26 151 typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
nuclear@26 152 typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
nuclear@26 153 typedef hist2d * hist3d; /* type for top-level pointer */
nuclear@26 154
nuclear@26 155
nuclear@26 156 /* Declarations for Floyd-Steinberg dithering.
nuclear@26 157 *
nuclear@26 158 * Errors are accumulated into the array fserrors[], at a resolution of
nuclear@26 159 * 1/16th of a pixel count. The error at a given pixel is propagated
nuclear@26 160 * to its not-yet-processed neighbors using the standard F-S fractions,
nuclear@26 161 * ... (here) 7/16
nuclear@26 162 * 3/16 5/16 1/16
nuclear@26 163 * We work left-to-right on even rows, right-to-left on odd rows.
nuclear@26 164 *
nuclear@26 165 * We can get away with a single array (holding one row's worth of errors)
nuclear@26 166 * by using it to store the current row's errors at pixel columns not yet
nuclear@26 167 * processed, but the next row's errors at columns already processed. We
nuclear@26 168 * need only a few extra variables to hold the errors immediately around the
nuclear@26 169 * current column. (If we are lucky, those variables are in registers, but
nuclear@26 170 * even if not, they're probably cheaper to access than array elements are.)
nuclear@26 171 *
nuclear@26 172 * The fserrors[] array has (#columns + 2) entries; the extra entry at
nuclear@26 173 * each end saves us from special-casing the first and last pixels.
nuclear@26 174 * Each entry is three values long, one value for each color component.
nuclear@26 175 *
nuclear@26 176 * Note: on a wide image, we might not have enough room in a PC's near data
nuclear@26 177 * segment to hold the error array; so it is allocated with alloc_large.
nuclear@26 178 */
nuclear@26 179
nuclear@26 180 #if BITS_IN_JSAMPLE == 8
nuclear@26 181 typedef INT16 FSERROR; /* 16 bits should be enough */
nuclear@26 182 typedef int LOCFSERROR; /* use 'int' for calculation temps */
nuclear@26 183 #else
nuclear@26 184 typedef INT32 FSERROR; /* may need more than 16 bits */
nuclear@26 185 typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
nuclear@26 186 #endif
nuclear@26 187
nuclear@26 188 typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
nuclear@26 189
nuclear@26 190
nuclear@26 191 /* Private subobject */
nuclear@26 192
nuclear@26 193 typedef struct {
nuclear@26 194 struct jpeg_color_quantizer pub; /* public fields */
nuclear@26 195
nuclear@26 196 /* Space for the eventually created colormap is stashed here */
nuclear@26 197 JSAMPARRAY sv_colormap; /* colormap allocated at init time */
nuclear@26 198 int desired; /* desired # of colors = size of colormap */
nuclear@26 199
nuclear@26 200 /* Variables for accumulating image statistics */
nuclear@26 201 hist3d histogram; /* pointer to the histogram */
nuclear@26 202
nuclear@26 203 boolean needs_zeroed; /* TRUE if next pass must zero histogram */
nuclear@26 204
nuclear@26 205 /* Variables for Floyd-Steinberg dithering */
nuclear@26 206 FSERRPTR fserrors; /* accumulated errors */
nuclear@26 207 boolean on_odd_row; /* flag to remember which row we are on */
nuclear@26 208 int * error_limiter; /* table for clamping the applied error */
nuclear@26 209 } my_cquantizer;
nuclear@26 210
nuclear@26 211 typedef my_cquantizer * my_cquantize_ptr;
nuclear@26 212
nuclear@26 213
nuclear@26 214 /*
nuclear@26 215 * Prescan some rows of pixels.
nuclear@26 216 * In this module the prescan simply updates the histogram, which has been
nuclear@26 217 * initialized to zeroes by start_pass.
nuclear@26 218 * An output_buf parameter is required by the method signature, but no data
nuclear@26 219 * is actually output (in fact the buffer controller is probably passing a
nuclear@26 220 * NULL pointer).
nuclear@26 221 */
nuclear@26 222
nuclear@26 223 METHODDEF(void)
nuclear@26 224 prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
nuclear@26 225 JSAMPARRAY output_buf, int num_rows)
nuclear@26 226 {
nuclear@26 227 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
nuclear@26 228 register JSAMPROW ptr;
nuclear@26 229 register histptr histp;
nuclear@26 230 register hist3d histogram = cquantize->histogram;
nuclear@26 231 int row;
nuclear@26 232 JDIMENSION col;
nuclear@26 233 JDIMENSION width = cinfo->output_width;
nuclear@26 234
nuclear@26 235 for (row = 0; row < num_rows; row++) {
nuclear@26 236 ptr = input_buf[row];
nuclear@26 237 for (col = width; col > 0; col--) {
nuclear@26 238 /* get pixel value and index into the histogram */
nuclear@26 239 histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
nuclear@26 240 [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
nuclear@26 241 [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
nuclear@26 242 /* increment, check for overflow and undo increment if so. */
nuclear@26 243 if (++(*histp) <= 0)
nuclear@26 244 (*histp)--;
nuclear@26 245 ptr += 3;
nuclear@26 246 }
nuclear@26 247 }
nuclear@26 248 }
nuclear@26 249
nuclear@26 250
nuclear@26 251 /*
nuclear@26 252 * Next we have the really interesting routines: selection of a colormap
nuclear@26 253 * given the completed histogram.
nuclear@26 254 * These routines work with a list of "boxes", each representing a rectangular
nuclear@26 255 * subset of the input color space (to histogram precision).
nuclear@26 256 */
nuclear@26 257
nuclear@26 258 typedef struct {
nuclear@26 259 /* The bounds of the box (inclusive); expressed as histogram indexes */
nuclear@26 260 int c0min, c0max;
nuclear@26 261 int c1min, c1max;
nuclear@26 262 int c2min, c2max;
nuclear@26 263 /* The volume (actually 2-norm) of the box */
nuclear@26 264 INT32 volume;
nuclear@26 265 /* The number of nonzero histogram cells within this box */
nuclear@26 266 long colorcount;
nuclear@26 267 } box;
nuclear@26 268
nuclear@26 269 typedef box * boxptr;
nuclear@26 270
nuclear@26 271
nuclear@26 272 LOCAL(boxptr)
nuclear@26 273 find_biggest_color_pop (boxptr boxlist, int numboxes)
nuclear@26 274 /* Find the splittable box with the largest color population */
nuclear@26 275 /* Returns NULL if no splittable boxes remain */
nuclear@26 276 {
nuclear@26 277 register boxptr boxp;
nuclear@26 278 register int i;
nuclear@26 279 register long maxc = 0;
nuclear@26 280 boxptr which = NULL;
nuclear@26 281
nuclear@26 282 for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
nuclear@26 283 if (boxp->colorcount > maxc && boxp->volume > 0) {
nuclear@26 284 which = boxp;
nuclear@26 285 maxc = boxp->colorcount;
nuclear@26 286 }
nuclear@26 287 }
nuclear@26 288 return which;
nuclear@26 289 }
nuclear@26 290
nuclear@26 291
nuclear@26 292 LOCAL(boxptr)
nuclear@26 293 find_biggest_volume (boxptr boxlist, int numboxes)
nuclear@26 294 /* Find the splittable box with the largest (scaled) volume */
nuclear@26 295 /* Returns NULL if no splittable boxes remain */
nuclear@26 296 {
nuclear@26 297 register boxptr boxp;
nuclear@26 298 register int i;
nuclear@26 299 register INT32 maxv = 0;
nuclear@26 300 boxptr which = NULL;
nuclear@26 301
nuclear@26 302 for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
nuclear@26 303 if (boxp->volume > maxv) {
nuclear@26 304 which = boxp;
nuclear@26 305 maxv = boxp->volume;
nuclear@26 306 }
nuclear@26 307 }
nuclear@26 308 return which;
nuclear@26 309 }
nuclear@26 310
nuclear@26 311
nuclear@26 312 LOCAL(void)
nuclear@26 313 update_box (j_decompress_ptr cinfo, boxptr boxp)
nuclear@26 314 /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
nuclear@26 315 /* and recompute its volume and population */
nuclear@26 316 {
nuclear@26 317 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
nuclear@26 318 hist3d histogram = cquantize->histogram;
nuclear@26 319 histptr histp;
nuclear@26 320 int c0,c1,c2;
nuclear@26 321 int c0min,c0max,c1min,c1max,c2min,c2max;
nuclear@26 322 INT32 dist0,dist1,dist2;
nuclear@26 323 long ccount;
nuclear@26 324
nuclear@26 325 c0min = boxp->c0min; c0max = boxp->c0max;
nuclear@26 326 c1min = boxp->c1min; c1max = boxp->c1max;
nuclear@26 327 c2min = boxp->c2min; c2max = boxp->c2max;
nuclear@26 328
nuclear@26 329 if (c0max > c0min)
nuclear@26 330 for (c0 = c0min; c0 <= c0max; c0++)
nuclear@26 331 for (c1 = c1min; c1 <= c1max; c1++) {
nuclear@26 332 histp = & histogram[c0][c1][c2min];
nuclear@26 333 for (c2 = c2min; c2 <= c2max; c2++)
nuclear@26 334 if (*histp++ != 0) {
nuclear@26 335 boxp->c0min = c0min = c0;
nuclear@26 336 goto have_c0min;
nuclear@26 337 }
nuclear@26 338 }
nuclear@26 339 have_c0min:
nuclear@26 340 if (c0max > c0min)
nuclear@26 341 for (c0 = c0max; c0 >= c0min; c0--)
nuclear@26 342 for (c1 = c1min; c1 <= c1max; c1++) {
nuclear@26 343 histp = & histogram[c0][c1][c2min];
nuclear@26 344 for (c2 = c2min; c2 <= c2max; c2++)
nuclear@26 345 if (*histp++ != 0) {
nuclear@26 346 boxp->c0max = c0max = c0;
nuclear@26 347 goto have_c0max;
nuclear@26 348 }
nuclear@26 349 }
nuclear@26 350 have_c0max:
nuclear@26 351 if (c1max > c1min)
nuclear@26 352 for (c1 = c1min; c1 <= c1max; c1++)
nuclear@26 353 for (c0 = c0min; c0 <= c0max; c0++) {
nuclear@26 354 histp = & histogram[c0][c1][c2min];
nuclear@26 355 for (c2 = c2min; c2 <= c2max; c2++)
nuclear@26 356 if (*histp++ != 0) {
nuclear@26 357 boxp->c1min = c1min = c1;
nuclear@26 358 goto have_c1min;
nuclear@26 359 }
nuclear@26 360 }
nuclear@26 361 have_c1min:
nuclear@26 362 if (c1max > c1min)
nuclear@26 363 for (c1 = c1max; c1 >= c1min; c1--)
nuclear@26 364 for (c0 = c0min; c0 <= c0max; c0++) {
nuclear@26 365 histp = & histogram[c0][c1][c2min];
nuclear@26 366 for (c2 = c2min; c2 <= c2max; c2++)
nuclear@26 367 if (*histp++ != 0) {
nuclear@26 368 boxp->c1max = c1max = c1;
nuclear@26 369 goto have_c1max;
nuclear@26 370 }
nuclear@26 371 }
nuclear@26 372 have_c1max:
nuclear@26 373 if (c2max > c2min)
nuclear@26 374 for (c2 = c2min; c2 <= c2max; c2++)
nuclear@26 375 for (c0 = c0min; c0 <= c0max; c0++) {
nuclear@26 376 histp = & histogram[c0][c1min][c2];
nuclear@26 377 for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
nuclear@26 378 if (*histp != 0) {
nuclear@26 379 boxp->c2min = c2min = c2;
nuclear@26 380 goto have_c2min;
nuclear@26 381 }
nuclear@26 382 }
nuclear@26 383 have_c2min:
nuclear@26 384 if (c2max > c2min)
nuclear@26 385 for (c2 = c2max; c2 >= c2min; c2--)
nuclear@26 386 for (c0 = c0min; c0 <= c0max; c0++) {
nuclear@26 387 histp = & histogram[c0][c1min][c2];
nuclear@26 388 for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
nuclear@26 389 if (*histp != 0) {
nuclear@26 390 boxp->c2max = c2max = c2;
nuclear@26 391 goto have_c2max;
nuclear@26 392 }
nuclear@26 393 }
nuclear@26 394 have_c2max:
nuclear@26 395
nuclear@26 396 /* Update box volume.
nuclear@26 397 * We use 2-norm rather than real volume here; this biases the method
nuclear@26 398 * against making long narrow boxes, and it has the side benefit that
nuclear@26 399 * a box is splittable iff norm > 0.
nuclear@26 400 * Since the differences are expressed in histogram-cell units,
nuclear@26 401 * we have to shift back to JSAMPLE units to get consistent distances;
nuclear@26 402 * after which, we scale according to the selected distance scale factors.
nuclear@26 403 */
nuclear@26 404 dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
nuclear@26 405 dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
nuclear@26 406 dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
nuclear@26 407 boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
nuclear@26 408
nuclear@26 409 /* Now scan remaining volume of box and compute population */
nuclear@26 410 ccount = 0;
nuclear@26 411 for (c0 = c0min; c0 <= c0max; c0++)
nuclear@26 412 for (c1 = c1min; c1 <= c1max; c1++) {
nuclear@26 413 histp = & histogram[c0][c1][c2min];
nuclear@26 414 for (c2 = c2min; c2 <= c2max; c2++, histp++)
nuclear@26 415 if (*histp != 0) {
nuclear@26 416 ccount++;
nuclear@26 417 }
nuclear@26 418 }
nuclear@26 419 boxp->colorcount = ccount;
nuclear@26 420 }
nuclear@26 421
nuclear@26 422
nuclear@26 423 LOCAL(int)
nuclear@26 424 median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
nuclear@26 425 int desired_colors)
nuclear@26 426 /* Repeatedly select and split the largest box until we have enough boxes */
nuclear@26 427 {
nuclear@26 428 int n,lb;
nuclear@26 429 int c0,c1,c2,cmax;
nuclear@26 430 register boxptr b1,b2;
nuclear@26 431
nuclear@26 432 while (numboxes < desired_colors) {
nuclear@26 433 /* Select box to split.
nuclear@26 434 * Current algorithm: by population for first half, then by volume.
nuclear@26 435 */
nuclear@26 436 if (numboxes*2 <= desired_colors) {
nuclear@26 437 b1 = find_biggest_color_pop(boxlist, numboxes);
nuclear@26 438 } else {
nuclear@26 439 b1 = find_biggest_volume(boxlist, numboxes);
nuclear@26 440 }
nuclear@26 441 if (b1 == NULL) /* no splittable boxes left! */
nuclear@26 442 break;
nuclear@26 443 b2 = &boxlist[numboxes]; /* where new box will go */
nuclear@26 444 /* Copy the color bounds to the new box. */
nuclear@26 445 b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
nuclear@26 446 b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
nuclear@26 447 /* Choose which axis to split the box on.
nuclear@26 448 * Current algorithm: longest scaled axis.
nuclear@26 449 * See notes in update_box about scaling distances.
nuclear@26 450 */
nuclear@26 451 c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
nuclear@26 452 c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
nuclear@26 453 c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
nuclear@26 454 /* We want to break any ties in favor of green, then red, blue last.
nuclear@26 455 * This code does the right thing for R,G,B or B,G,R color orders only.
nuclear@26 456 */
nuclear@26 457 #if RGB_RED == 0
nuclear@26 458 cmax = c1; n = 1;
nuclear@26 459 if (c0 > cmax) { cmax = c0; n = 0; }
nuclear@26 460 if (c2 > cmax) { n = 2; }
nuclear@26 461 #else
nuclear@26 462 cmax = c1; n = 1;
nuclear@26 463 if (c2 > cmax) { cmax = c2; n = 2; }
nuclear@26 464 if (c0 > cmax) { n = 0; }
nuclear@26 465 #endif
nuclear@26 466 /* Choose split point along selected axis, and update box bounds.
nuclear@26 467 * Current algorithm: split at halfway point.
nuclear@26 468 * (Since the box has been shrunk to minimum volume,
nuclear@26 469 * any split will produce two nonempty subboxes.)
nuclear@26 470 * Note that lb value is max for lower box, so must be < old max.
nuclear@26 471 */
nuclear@26 472 switch (n) {
nuclear@26 473 case 0:
nuclear@26 474 lb = (b1->c0max + b1->c0min) / 2;
nuclear@26 475 b1->c0max = lb;
nuclear@26 476 b2->c0min = lb+1;
nuclear@26 477 break;
nuclear@26 478 case 1:
nuclear@26 479 lb = (b1->c1max + b1->c1min) / 2;
nuclear@26 480 b1->c1max = lb;
nuclear@26 481 b2->c1min = lb+1;
nuclear@26 482 break;
nuclear@26 483 case 2:
nuclear@26 484 lb = (b1->c2max + b1->c2min) / 2;
nuclear@26 485 b1->c2max = lb;
nuclear@26 486 b2->c2min = lb+1;
nuclear@26 487 break;
nuclear@26 488 }
nuclear@26 489 /* Update stats for boxes */
nuclear@26 490 update_box(cinfo, b1);
nuclear@26 491 update_box(cinfo, b2);
nuclear@26 492 numboxes++;
nuclear@26 493 }
nuclear@26 494 return numboxes;
nuclear@26 495 }
nuclear@26 496
nuclear@26 497
nuclear@26 498 LOCAL(void)
nuclear@26 499 compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
nuclear@26 500 /* Compute representative color for a box, put it in colormap[icolor] */
nuclear@26 501 {
nuclear@26 502 /* Current algorithm: mean weighted by pixels (not colors) */
nuclear@26 503 /* Note it is important to get the rounding correct! */
nuclear@26 504 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
nuclear@26 505 hist3d histogram = cquantize->histogram;
nuclear@26 506 histptr histp;
nuclear@26 507 int c0,c1,c2;
nuclear@26 508 int c0min,c0max,c1min,c1max,c2min,c2max;
nuclear@26 509 long count;
nuclear@26 510 long total = 0;
nuclear@26 511 long c0total = 0;
nuclear@26 512 long c1total = 0;
nuclear@26 513 long c2total = 0;
nuclear@26 514
nuclear@26 515 c0min = boxp->c0min; c0max = boxp->c0max;
nuclear@26 516 c1min = boxp->c1min; c1max = boxp->c1max;
nuclear@26 517 c2min = boxp->c2min; c2max = boxp->c2max;
nuclear@26 518
nuclear@26 519 for (c0 = c0min; c0 <= c0max; c0++)
nuclear@26 520 for (c1 = c1min; c1 <= c1max; c1++) {
nuclear@26 521 histp = & histogram[c0][c1][c2min];
nuclear@26 522 for (c2 = c2min; c2 <= c2max; c2++) {
nuclear@26 523 if ((count = *histp++) != 0) {
nuclear@26 524 total += count;
nuclear@26 525 c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
nuclear@26 526 c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
nuclear@26 527 c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
nuclear@26 528 }
nuclear@26 529 }
nuclear@26 530 }
nuclear@26 531
nuclear@26 532 cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
nuclear@26 533 cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
nuclear@26 534 cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
nuclear@26 535 }
nuclear@26 536
nuclear@26 537
nuclear@26 538 LOCAL(void)
nuclear@26 539 select_colors (j_decompress_ptr cinfo, int desired_colors)
nuclear@26 540 /* Master routine for color selection */
nuclear@26 541 {
nuclear@26 542 boxptr boxlist;
nuclear@26 543 int numboxes;
nuclear@26 544 int i;
nuclear@26 545
nuclear@26 546 /* Allocate workspace for box list */
nuclear@26 547 boxlist = (boxptr) (*cinfo->mem->alloc_small)
nuclear@26 548 ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
nuclear@26 549 /* Initialize one box containing whole space */
nuclear@26 550 numboxes = 1;
nuclear@26 551 boxlist[0].c0min = 0;
nuclear@26 552 boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
nuclear@26 553 boxlist[0].c1min = 0;
nuclear@26 554 boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
nuclear@26 555 boxlist[0].c2min = 0;
nuclear@26 556 boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
nuclear@26 557 /* Shrink it to actually-used volume and set its statistics */
nuclear@26 558 update_box(cinfo, & boxlist[0]);
nuclear@26 559 /* Perform median-cut to produce final box list */
nuclear@26 560 numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
nuclear@26 561 /* Compute the representative color for each box, fill colormap */
nuclear@26 562 for (i = 0; i < numboxes; i++)
nuclear@26 563 compute_color(cinfo, & boxlist[i], i);
nuclear@26 564 cinfo->actual_number_of_colors = numboxes;
nuclear@26 565 TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
nuclear@26 566 }
nuclear@26 567
nuclear@26 568
nuclear@26 569 /*
nuclear@26 570 * These routines are concerned with the time-critical task of mapping input
nuclear@26 571 * colors to the nearest color in the selected colormap.
nuclear@26 572 *
nuclear@26 573 * We re-use the histogram space as an "inverse color map", essentially a
nuclear@26 574 * cache for the results of nearest-color searches. All colors within a
nuclear@26 575 * histogram cell will be mapped to the same colormap entry, namely the one
nuclear@26 576 * closest to the cell's center. This may not be quite the closest entry to
nuclear@26 577 * the actual input color, but it's almost as good. A zero in the cache
nuclear@26 578 * indicates we haven't found the nearest color for that cell yet; the array
nuclear@26 579 * is cleared to zeroes before starting the mapping pass. When we find the
nuclear@26 580 * nearest color for a cell, its colormap index plus one is recorded in the
nuclear@26 581 * cache for future use. The pass2 scanning routines call fill_inverse_cmap
nuclear@26 582 * when they need to use an unfilled entry in the cache.
nuclear@26 583 *
nuclear@26 584 * Our method of efficiently finding nearest colors is based on the "locally
nuclear@26 585 * sorted search" idea described by Heckbert and on the incremental distance
nuclear@26 586 * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
nuclear@26 587 * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
nuclear@26 588 * the distances from a given colormap entry to each cell of the histogram can
nuclear@26 589 * be computed quickly using an incremental method: the differences between
nuclear@26 590 * distances to adjacent cells themselves differ by a constant. This allows a
nuclear@26 591 * fairly fast implementation of the "brute force" approach of computing the
nuclear@26 592 * distance from every colormap entry to every histogram cell. Unfortunately,
nuclear@26 593 * it needs a work array to hold the best-distance-so-far for each histogram
nuclear@26 594 * cell (because the inner loop has to be over cells, not colormap entries).
nuclear@26 595 * The work array elements have to be INT32s, so the work array would need
nuclear@26 596 * 256Kb at our recommended precision. This is not feasible in DOS machines.
nuclear@26 597 *
nuclear@26 598 * To get around these problems, we apply Thomas' method to compute the
nuclear@26 599 * nearest colors for only the cells within a small subbox of the histogram.
nuclear@26 600 * The work array need be only as big as the subbox, so the memory usage
nuclear@26 601 * problem is solved. Furthermore, we need not fill subboxes that are never
nuclear@26 602 * referenced in pass2; many images use only part of the color gamut, so a
nuclear@26 603 * fair amount of work is saved. An additional advantage of this
nuclear@26 604 * approach is that we can apply Heckbert's locality criterion to quickly
nuclear@26 605 * eliminate colormap entries that are far away from the subbox; typically
nuclear@26 606 * three-fourths of the colormap entries are rejected by Heckbert's criterion,
nuclear@26 607 * and we need not compute their distances to individual cells in the subbox.
nuclear@26 608 * The speed of this approach is heavily influenced by the subbox size: too
nuclear@26 609 * small means too much overhead, too big loses because Heckbert's criterion
nuclear@26 610 * can't eliminate as many colormap entries. Empirically the best subbox
nuclear@26 611 * size seems to be about 1/512th of the histogram (1/8th in each direction).
nuclear@26 612 *
nuclear@26 613 * Thomas' article also describes a refined method which is asymptotically
nuclear@26 614 * faster than the brute-force method, but it is also far more complex and
nuclear@26 615 * cannot efficiently be applied to small subboxes. It is therefore not
nuclear@26 616 * useful for programs intended to be portable to DOS machines. On machines
nuclear@26 617 * with plenty of memory, filling the whole histogram in one shot with Thomas'
nuclear@26 618 * refined method might be faster than the present code --- but then again,
nuclear@26 619 * it might not be any faster, and it's certainly more complicated.
nuclear@26 620 */
nuclear@26 621
nuclear@26 622
nuclear@26 623 /* log2(histogram cells in update box) for each axis; this can be adjusted */
nuclear@26 624 #define BOX_C0_LOG (HIST_C0_BITS-3)
nuclear@26 625 #define BOX_C1_LOG (HIST_C1_BITS-3)
nuclear@26 626 #define BOX_C2_LOG (HIST_C2_BITS-3)
nuclear@26 627
nuclear@26 628 #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
nuclear@26 629 #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
nuclear@26 630 #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
nuclear@26 631
nuclear@26 632 #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
nuclear@26 633 #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
nuclear@26 634 #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
nuclear@26 635
nuclear@26 636
nuclear@26 637 /*
nuclear@26 638 * The next three routines implement inverse colormap filling. They could
nuclear@26 639 * all be folded into one big routine, but splitting them up this way saves
nuclear@26 640 * some stack space (the mindist[] and bestdist[] arrays need not coexist)
nuclear@26 641 * and may allow some compilers to produce better code by registerizing more
nuclear@26 642 * inner-loop variables.
nuclear@26 643 */
nuclear@26 644
nuclear@26 645 LOCAL(int)
nuclear@26 646 find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
nuclear@26 647 JSAMPLE colorlist[])
nuclear@26 648 /* Locate the colormap entries close enough to an update box to be candidates
nuclear@26 649 * for the nearest entry to some cell(s) in the update box. The update box
nuclear@26 650 * is specified by the center coordinates of its first cell. The number of
nuclear@26 651 * candidate colormap entries is returned, and their colormap indexes are
nuclear@26 652 * placed in colorlist[].
nuclear@26 653 * This routine uses Heckbert's "locally sorted search" criterion to select
nuclear@26 654 * the colors that need further consideration.
nuclear@26 655 */
nuclear@26 656 {
nuclear@26 657 int numcolors = cinfo->actual_number_of_colors;
nuclear@26 658 int maxc0, maxc1, maxc2;
nuclear@26 659 int centerc0, centerc1, centerc2;
nuclear@26 660 int i, x, ncolors;
nuclear@26 661 INT32 minmaxdist, min_dist, max_dist, tdist;
nuclear@26 662 INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
nuclear@26 663
nuclear@26 664 /* Compute true coordinates of update box's upper corner and center.
nuclear@26 665 * Actually we compute the coordinates of the center of the upper-corner
nuclear@26 666 * histogram cell, which are the upper bounds of the volume we care about.
nuclear@26 667 * Note that since ">>" rounds down, the "center" values may be closer to
nuclear@26 668 * min than to max; hence comparisons to them must be "<=", not "<".
nuclear@26 669 */
nuclear@26 670 maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
nuclear@26 671 centerc0 = (minc0 + maxc0) >> 1;
nuclear@26 672 maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
nuclear@26 673 centerc1 = (minc1 + maxc1) >> 1;
nuclear@26 674 maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
nuclear@26 675 centerc2 = (minc2 + maxc2) >> 1;
nuclear@26 676
nuclear@26 677 /* For each color in colormap, find:
nuclear@26 678 * 1. its minimum squared-distance to any point in the update box
nuclear@26 679 * (zero if color is within update box);
nuclear@26 680 * 2. its maximum squared-distance to any point in the update box.
nuclear@26 681 * Both of these can be found by considering only the corners of the box.
nuclear@26 682 * We save the minimum distance for each color in mindist[];
nuclear@26 683 * only the smallest maximum distance is of interest.
nuclear@26 684 */
nuclear@26 685 minmaxdist = 0x7FFFFFFFL;
nuclear@26 686
nuclear@26 687 for (i = 0; i < numcolors; i++) {
nuclear@26 688 /* We compute the squared-c0-distance term, then add in the other two. */
nuclear@26 689 x = GETJSAMPLE(cinfo->colormap[0][i]);
nuclear@26 690 if (x < minc0) {
nuclear@26 691 tdist = (x - minc0) * C0_SCALE;
nuclear@26 692 min_dist = tdist*tdist;
nuclear@26 693 tdist = (x - maxc0) * C0_SCALE;
nuclear@26 694 max_dist = tdist*tdist;
nuclear@26 695 } else if (x > maxc0) {
nuclear@26 696 tdist = (x - maxc0) * C0_SCALE;
nuclear@26 697 min_dist = tdist*tdist;
nuclear@26 698 tdist = (x - minc0) * C0_SCALE;
nuclear@26 699 max_dist = tdist*tdist;
nuclear@26 700 } else {
nuclear@26 701 /* within cell range so no contribution to min_dist */
nuclear@26 702 min_dist = 0;
nuclear@26 703 if (x <= centerc0) {
nuclear@26 704 tdist = (x - maxc0) * C0_SCALE;
nuclear@26 705 max_dist = tdist*tdist;
nuclear@26 706 } else {
nuclear@26 707 tdist = (x - minc0) * C0_SCALE;
nuclear@26 708 max_dist = tdist*tdist;
nuclear@26 709 }
nuclear@26 710 }
nuclear@26 711
nuclear@26 712 x = GETJSAMPLE(cinfo->colormap[1][i]);
nuclear@26 713 if (x < minc1) {
nuclear@26 714 tdist = (x - minc1) * C1_SCALE;
nuclear@26 715 min_dist += tdist*tdist;
nuclear@26 716 tdist = (x - maxc1) * C1_SCALE;
nuclear@26 717 max_dist += tdist*tdist;
nuclear@26 718 } else if (x > maxc1) {
nuclear@26 719 tdist = (x - maxc1) * C1_SCALE;
nuclear@26 720 min_dist += tdist*tdist;
nuclear@26 721 tdist = (x - minc1) * C1_SCALE;
nuclear@26 722 max_dist += tdist*tdist;
nuclear@26 723 } else {
nuclear@26 724 /* within cell range so no contribution to min_dist */
nuclear@26 725 if (x <= centerc1) {
nuclear@26 726 tdist = (x - maxc1) * C1_SCALE;
nuclear@26 727 max_dist += tdist*tdist;
nuclear@26 728 } else {
nuclear@26 729 tdist = (x - minc1) * C1_SCALE;
nuclear@26 730 max_dist += tdist*tdist;
nuclear@26 731 }
nuclear@26 732 }
nuclear@26 733
nuclear@26 734 x = GETJSAMPLE(cinfo->colormap[2][i]);
nuclear@26 735 if (x < minc2) {
nuclear@26 736 tdist = (x - minc2) * C2_SCALE;
nuclear@26 737 min_dist += tdist*tdist;
nuclear@26 738 tdist = (x - maxc2) * C2_SCALE;
nuclear@26 739 max_dist += tdist*tdist;
nuclear@26 740 } else if (x > maxc2) {
nuclear@26 741 tdist = (x - maxc2) * C2_SCALE;
nuclear@26 742 min_dist += tdist*tdist;
nuclear@26 743 tdist = (x - minc2) * C2_SCALE;
nuclear@26 744 max_dist += tdist*tdist;
nuclear@26 745 } else {
nuclear@26 746 /* within cell range so no contribution to min_dist */
nuclear@26 747 if (x <= centerc2) {
nuclear@26 748 tdist = (x - maxc2) * C2_SCALE;
nuclear@26 749 max_dist += tdist*tdist;
nuclear@26 750 } else {
nuclear@26 751 tdist = (x - minc2) * C2_SCALE;
nuclear@26 752 max_dist += tdist*tdist;
nuclear@26 753 }
nuclear@26 754 }
nuclear@26 755
nuclear@26 756 mindist[i] = min_dist; /* save away the results */
nuclear@26 757 if (max_dist < minmaxdist)
nuclear@26 758 minmaxdist = max_dist;
nuclear@26 759 }
nuclear@26 760
nuclear@26 761 /* Now we know that no cell in the update box is more than minmaxdist
nuclear@26 762 * away from some colormap entry. Therefore, only colors that are
nuclear@26 763 * within minmaxdist of some part of the box need be considered.
nuclear@26 764 */
nuclear@26 765 ncolors = 0;
nuclear@26 766 for (i = 0; i < numcolors; i++) {
nuclear@26 767 if (mindist[i] <= minmaxdist)
nuclear@26 768 colorlist[ncolors++] = (JSAMPLE) i;
nuclear@26 769 }
nuclear@26 770 return ncolors;
nuclear@26 771 }
nuclear@26 772
nuclear@26 773
nuclear@26 774 LOCAL(void)
nuclear@26 775 find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
nuclear@26 776 int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
nuclear@26 777 /* Find the closest colormap entry for each cell in the update box,
nuclear@26 778 * given the list of candidate colors prepared by find_nearby_colors.
nuclear@26 779 * Return the indexes of the closest entries in the bestcolor[] array.
nuclear@26 780 * This routine uses Thomas' incremental distance calculation method to
nuclear@26 781 * find the distance from a colormap entry to successive cells in the box.
nuclear@26 782 */
nuclear@26 783 {
nuclear@26 784 int ic0, ic1, ic2;
nuclear@26 785 int i, icolor;
nuclear@26 786 register INT32 * bptr; /* pointer into bestdist[] array */
nuclear@26 787 JSAMPLE * cptr; /* pointer into bestcolor[] array */
nuclear@26 788 INT32 dist0, dist1; /* initial distance values */
nuclear@26 789 register INT32 dist2; /* current distance in inner loop */
nuclear@26 790 INT32 xx0, xx1; /* distance increments */
nuclear@26 791 register INT32 xx2;
nuclear@26 792 INT32 inc0, inc1, inc2; /* initial values for increments */
nuclear@26 793 /* This array holds the distance to the nearest-so-far color for each cell */
nuclear@26 794 INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
nuclear@26 795
nuclear@26 796 /* Initialize best-distance for each cell of the update box */
nuclear@26 797 bptr = bestdist;
nuclear@26 798 for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
nuclear@26 799 *bptr++ = 0x7FFFFFFFL;
nuclear@26 800
nuclear@26 801 /* For each color selected by find_nearby_colors,
nuclear@26 802 * compute its distance to the center of each cell in the box.
nuclear@26 803 * If that's less than best-so-far, update best distance and color number.
nuclear@26 804 */
nuclear@26 805
nuclear@26 806 /* Nominal steps between cell centers ("x" in Thomas article) */
nuclear@26 807 #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
nuclear@26 808 #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
nuclear@26 809 #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
nuclear@26 810
nuclear@26 811 for (i = 0; i < numcolors; i++) {
nuclear@26 812 icolor = GETJSAMPLE(colorlist[i]);
nuclear@26 813 /* Compute (square of) distance from minc0/c1/c2 to this color */
nuclear@26 814 inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
nuclear@26 815 dist0 = inc0*inc0;
nuclear@26 816 inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
nuclear@26 817 dist0 += inc1*inc1;
nuclear@26 818 inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
nuclear@26 819 dist0 += inc2*inc2;
nuclear@26 820 /* Form the initial difference increments */
nuclear@26 821 inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
nuclear@26 822 inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
nuclear@26 823 inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
nuclear@26 824 /* Now loop over all cells in box, updating distance per Thomas method */
nuclear@26 825 bptr = bestdist;
nuclear@26 826 cptr = bestcolor;
nuclear@26 827 xx0 = inc0;
nuclear@26 828 for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
nuclear@26 829 dist1 = dist0;
nuclear@26 830 xx1 = inc1;
nuclear@26 831 for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
nuclear@26 832 dist2 = dist1;
nuclear@26 833 xx2 = inc2;
nuclear@26 834 for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
nuclear@26 835 if (dist2 < *bptr) {
nuclear@26 836 *bptr = dist2;
nuclear@26 837 *cptr = (JSAMPLE) icolor;
nuclear@26 838 }
nuclear@26 839 dist2 += xx2;
nuclear@26 840 xx2 += 2 * STEP_C2 * STEP_C2;
nuclear@26 841 bptr++;
nuclear@26 842 cptr++;
nuclear@26 843 }
nuclear@26 844 dist1 += xx1;
nuclear@26 845 xx1 += 2 * STEP_C1 * STEP_C1;
nuclear@26 846 }
nuclear@26 847 dist0 += xx0;
nuclear@26 848 xx0 += 2 * STEP_C0 * STEP_C0;
nuclear@26 849 }
nuclear@26 850 }
nuclear@26 851 }
nuclear@26 852
nuclear@26 853
nuclear@26 854 LOCAL(void)
nuclear@26 855 fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
nuclear@26 856 /* Fill the inverse-colormap entries in the update box that contains */
nuclear@26 857 /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
nuclear@26 858 /* we can fill as many others as we wish.) */
nuclear@26 859 {
nuclear@26 860 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
nuclear@26 861 hist3d histogram = cquantize->histogram;
nuclear@26 862 int minc0, minc1, minc2; /* lower left corner of update box */
nuclear@26 863 int ic0, ic1, ic2;
nuclear@26 864 register JSAMPLE * cptr; /* pointer into bestcolor[] array */
nuclear@26 865 register histptr cachep; /* pointer into main cache array */
nuclear@26 866 /* This array lists the candidate colormap indexes. */
nuclear@26 867 JSAMPLE colorlist[MAXNUMCOLORS];
nuclear@26 868 int numcolors; /* number of candidate colors */
nuclear@26 869 /* This array holds the actually closest colormap index for each cell. */
nuclear@26 870 JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
nuclear@26 871
nuclear@26 872 /* Convert cell coordinates to update box ID */
nuclear@26 873 c0 >>= BOX_C0_LOG;
nuclear@26 874 c1 >>= BOX_C1_LOG;
nuclear@26 875 c2 >>= BOX_C2_LOG;
nuclear@26 876
nuclear@26 877 /* Compute true coordinates of update box's origin corner.
nuclear@26 878 * Actually we compute the coordinates of the center of the corner
nuclear@26 879 * histogram cell, which are the lower bounds of the volume we care about.
nuclear@26 880 */
nuclear@26 881 minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
nuclear@26 882 minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
nuclear@26 883 minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
nuclear@26 884
nuclear@26 885 /* Determine which colormap entries are close enough to be candidates
nuclear@26 886 * for the nearest entry to some cell in the update box.
nuclear@26 887 */
nuclear@26 888 numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
nuclear@26 889
nuclear@26 890 /* Determine the actually nearest colors. */
nuclear@26 891 find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
nuclear@26 892 bestcolor);
nuclear@26 893
nuclear@26 894 /* Save the best color numbers (plus 1) in the main cache array */
nuclear@26 895 c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
nuclear@26 896 c1 <<= BOX_C1_LOG;
nuclear@26 897 c2 <<= BOX_C2_LOG;
nuclear@26 898 cptr = bestcolor;
nuclear@26 899 for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
nuclear@26 900 for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
nuclear@26 901 cachep = & histogram[c0+ic0][c1+ic1][c2];
nuclear@26 902 for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
nuclear@26 903 *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
nuclear@26 904 }
nuclear@26 905 }
nuclear@26 906 }
nuclear@26 907 }
nuclear@26 908
nuclear@26 909
nuclear@26 910 /*
nuclear@26 911 * Map some rows of pixels to the output colormapped representation.
nuclear@26 912 */
nuclear@26 913
nuclear@26 914 METHODDEF(void)
nuclear@26 915 pass2_no_dither (j_decompress_ptr cinfo,
nuclear@26 916 JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
nuclear@26 917 /* This version performs no dithering */
nuclear@26 918 {
nuclear@26 919 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
nuclear@26 920 hist3d histogram = cquantize->histogram;
nuclear@26 921 register JSAMPROW inptr, outptr;
nuclear@26 922 register histptr cachep;
nuclear@26 923 register int c0, c1, c2;
nuclear@26 924 int row;
nuclear@26 925 JDIMENSION col;
nuclear@26 926 JDIMENSION width = cinfo->output_width;
nuclear@26 927
nuclear@26 928 for (row = 0; row < num_rows; row++) {
nuclear@26 929 inptr = input_buf[row];
nuclear@26 930 outptr = output_buf[row];
nuclear@26 931 for (col = width; col > 0; col--) {
nuclear@26 932 /* get pixel value and index into the cache */
nuclear@26 933 c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
nuclear@26 934 c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
nuclear@26 935 c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
nuclear@26 936 cachep = & histogram[c0][c1][c2];
nuclear@26 937 /* If we have not seen this color before, find nearest colormap entry */
nuclear@26 938 /* and update the cache */
nuclear@26 939 if (*cachep == 0)
nuclear@26 940 fill_inverse_cmap(cinfo, c0,c1,c2);
nuclear@26 941 /* Now emit the colormap index for this cell */
nuclear@26 942 *outptr++ = (JSAMPLE) (*cachep - 1);
nuclear@26 943 }
nuclear@26 944 }
nuclear@26 945 }
nuclear@26 946
nuclear@26 947
nuclear@26 948 METHODDEF(void)
nuclear@26 949 pass2_fs_dither (j_decompress_ptr cinfo,
nuclear@26 950 JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
nuclear@26 951 /* This version performs Floyd-Steinberg dithering */
nuclear@26 952 {
nuclear@26 953 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
nuclear@26 954 hist3d histogram = cquantize->histogram;
nuclear@26 955 register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
nuclear@26 956 LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
nuclear@26 957 LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
nuclear@26 958 register FSERRPTR errorptr; /* => fserrors[] at column before current */
nuclear@26 959 JSAMPROW inptr; /* => current input pixel */
nuclear@26 960 JSAMPROW outptr; /* => current output pixel */
nuclear@26 961 histptr cachep;
nuclear@26 962 int dir; /* +1 or -1 depending on direction */
nuclear@26 963 int dir3; /* 3*dir, for advancing inptr & errorptr */
nuclear@26 964 int row;
nuclear@26 965 JDIMENSION col;
nuclear@26 966 JDIMENSION width = cinfo->output_width;
nuclear@26 967 JSAMPLE *range_limit = cinfo->sample_range_limit;
nuclear@26 968 int *error_limit = cquantize->error_limiter;
nuclear@26 969 JSAMPROW colormap0 = cinfo->colormap[0];
nuclear@26 970 JSAMPROW colormap1 = cinfo->colormap[1];
nuclear@26 971 JSAMPROW colormap2 = cinfo->colormap[2];
nuclear@26 972 SHIFT_TEMPS
nuclear@26 973
nuclear@26 974 for (row = 0; row < num_rows; row++) {
nuclear@26 975 inptr = input_buf[row];
nuclear@26 976 outptr = output_buf[row];
nuclear@26 977 if (cquantize->on_odd_row) {
nuclear@26 978 /* work right to left in this row */
nuclear@26 979 inptr += (width-1) * 3; /* so point to rightmost pixel */
nuclear@26 980 outptr += width-1;
nuclear@26 981 dir = -1;
nuclear@26 982 dir3 = -3;
nuclear@26 983 errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
nuclear@26 984 cquantize->on_odd_row = FALSE; /* flip for next time */
nuclear@26 985 } else {
nuclear@26 986 /* work left to right in this row */
nuclear@26 987 dir = 1;
nuclear@26 988 dir3 = 3;
nuclear@26 989 errorptr = cquantize->fserrors; /* => entry before first real column */
nuclear@26 990 cquantize->on_odd_row = TRUE; /* flip for next time */
nuclear@26 991 }
nuclear@26 992 /* Preset error values: no error propagated to first pixel from left */
nuclear@26 993 cur0 = cur1 = cur2 = 0;
nuclear@26 994 /* and no error propagated to row below yet */
nuclear@26 995 belowerr0 = belowerr1 = belowerr2 = 0;
nuclear@26 996 bpreverr0 = bpreverr1 = bpreverr2 = 0;
nuclear@26 997
nuclear@26 998 for (col = width; col > 0; col--) {
nuclear@26 999 /* curN holds the error propagated from the previous pixel on the
nuclear@26 1000 * current line. Add the error propagated from the previous line
nuclear@26 1001 * to form the complete error correction term for this pixel, and
nuclear@26 1002 * round the error term (which is expressed * 16) to an integer.
nuclear@26 1003 * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
nuclear@26 1004 * for either sign of the error value.
nuclear@26 1005 * Note: errorptr points to *previous* column's array entry.
nuclear@26 1006 */
nuclear@26 1007 cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
nuclear@26 1008 cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
nuclear@26 1009 cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
nuclear@26 1010 /* Limit the error using transfer function set by init_error_limit.
nuclear@26 1011 * See comments with init_error_limit for rationale.
nuclear@26 1012 */
nuclear@26 1013 cur0 = error_limit[cur0];
nuclear@26 1014 cur1 = error_limit[cur1];
nuclear@26 1015 cur2 = error_limit[cur2];
nuclear@26 1016 /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
nuclear@26 1017 * The maximum error is +- MAXJSAMPLE (or less with error limiting);
nuclear@26 1018 * this sets the required size of the range_limit array.
nuclear@26 1019 */
nuclear@26 1020 cur0 += GETJSAMPLE(inptr[0]);
nuclear@26 1021 cur1 += GETJSAMPLE(inptr[1]);
nuclear@26 1022 cur2 += GETJSAMPLE(inptr[2]);
nuclear@26 1023 cur0 = GETJSAMPLE(range_limit[cur0]);
nuclear@26 1024 cur1 = GETJSAMPLE(range_limit[cur1]);
nuclear@26 1025 cur2 = GETJSAMPLE(range_limit[cur2]);
nuclear@26 1026 /* Index into the cache with adjusted pixel value */
nuclear@26 1027 cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
nuclear@26 1028 /* If we have not seen this color before, find nearest colormap */
nuclear@26 1029 /* entry and update the cache */
nuclear@26 1030 if (*cachep == 0)
nuclear@26 1031 fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
nuclear@26 1032 /* Now emit the colormap index for this cell */
nuclear@26 1033 { register int pixcode = *cachep - 1;
nuclear@26 1034 *outptr = (JSAMPLE) pixcode;
nuclear@26 1035 /* Compute representation error for this pixel */
nuclear@26 1036 cur0 -= GETJSAMPLE(colormap0[pixcode]);
nuclear@26 1037 cur1 -= GETJSAMPLE(colormap1[pixcode]);
nuclear@26 1038 cur2 -= GETJSAMPLE(colormap2[pixcode]);
nuclear@26 1039 }
nuclear@26 1040 /* Compute error fractions to be propagated to adjacent pixels.
nuclear@26 1041 * Add these into the running sums, and simultaneously shift the
nuclear@26 1042 * next-line error sums left by 1 column.
nuclear@26 1043 */
nuclear@26 1044 { register LOCFSERROR bnexterr, delta;
nuclear@26 1045
nuclear@26 1046 bnexterr = cur0; /* Process component 0 */
nuclear@26 1047 delta = cur0 * 2;
nuclear@26 1048 cur0 += delta; /* form error * 3 */
nuclear@26 1049 errorptr[0] = (FSERROR) (bpreverr0 + cur0);
nuclear@26 1050 cur0 += delta; /* form error * 5 */
nuclear@26 1051 bpreverr0 = belowerr0 + cur0;
nuclear@26 1052 belowerr0 = bnexterr;
nuclear@26 1053 cur0 += delta; /* form error * 7 */
nuclear@26 1054 bnexterr = cur1; /* Process component 1 */
nuclear@26 1055 delta = cur1 * 2;
nuclear@26 1056 cur1 += delta; /* form error * 3 */
nuclear@26 1057 errorptr[1] = (FSERROR) (bpreverr1 + cur1);
nuclear@26 1058 cur1 += delta; /* form error * 5 */
nuclear@26 1059 bpreverr1 = belowerr1 + cur1;
nuclear@26 1060 belowerr1 = bnexterr;
nuclear@26 1061 cur1 += delta; /* form error * 7 */
nuclear@26 1062 bnexterr = cur2; /* Process component 2 */
nuclear@26 1063 delta = cur2 * 2;
nuclear@26 1064 cur2 += delta; /* form error * 3 */
nuclear@26 1065 errorptr[2] = (FSERROR) (bpreverr2 + cur2);
nuclear@26 1066 cur2 += delta; /* form error * 5 */
nuclear@26 1067 bpreverr2 = belowerr2 + cur2;
nuclear@26 1068 belowerr2 = bnexterr;
nuclear@26 1069 cur2 += delta; /* form error * 7 */
nuclear@26 1070 }
nuclear@26 1071 /* At this point curN contains the 7/16 error value to be propagated
nuclear@26 1072 * to the next pixel on the current line, and all the errors for the
nuclear@26 1073 * next line have been shifted over. We are therefore ready to move on.
nuclear@26 1074 */
nuclear@26 1075 inptr += dir3; /* Advance pixel pointers to next column */
nuclear@26 1076 outptr += dir;
nuclear@26 1077 errorptr += dir3; /* advance errorptr to current column */
nuclear@26 1078 }
nuclear@26 1079 /* Post-loop cleanup: we must unload the final error values into the
nuclear@26 1080 * final fserrors[] entry. Note we need not unload belowerrN because
nuclear@26 1081 * it is for the dummy column before or after the actual array.
nuclear@26 1082 */
nuclear@26 1083 errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
nuclear@26 1084 errorptr[1] = (FSERROR) bpreverr1;
nuclear@26 1085 errorptr[2] = (FSERROR) bpreverr2;
nuclear@26 1086 }
nuclear@26 1087 }
nuclear@26 1088
nuclear@26 1089
nuclear@26 1090 /*
nuclear@26 1091 * Initialize the error-limiting transfer function (lookup table).
nuclear@26 1092 * The raw F-S error computation can potentially compute error values of up to
nuclear@26 1093 * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
nuclear@26 1094 * much less, otherwise obviously wrong pixels will be created. (Typical
nuclear@26 1095 * effects include weird fringes at color-area boundaries, isolated bright
nuclear@26 1096 * pixels in a dark area, etc.) The standard advice for avoiding this problem
nuclear@26 1097 * is to ensure that the "corners" of the color cube are allocated as output
nuclear@26 1098 * colors; then repeated errors in the same direction cannot cause cascading
nuclear@26 1099 * error buildup. However, that only prevents the error from getting
nuclear@26 1100 * completely out of hand; Aaron Giles reports that error limiting improves
nuclear@26 1101 * the results even with corner colors allocated.
nuclear@26 1102 * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
nuclear@26 1103 * well, but the smoother transfer function used below is even better. Thanks
nuclear@26 1104 * to Aaron Giles for this idea.
nuclear@26 1105 */
nuclear@26 1106
nuclear@26 1107 LOCAL(void)
nuclear@26 1108 init_error_limit (j_decompress_ptr cinfo)
nuclear@26 1109 /* Allocate and fill in the error_limiter table */
nuclear@26 1110 {
nuclear@26 1111 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
nuclear@26 1112 int * table;
nuclear@26 1113 int in, out;
nuclear@26 1114
nuclear@26 1115 table = (int *) (*cinfo->mem->alloc_small)
nuclear@26 1116 ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
nuclear@26 1117 table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
nuclear@26 1118 cquantize->error_limiter = table;
nuclear@26 1119
nuclear@26 1120 #define STEPSIZE ((MAXJSAMPLE+1)/16)
nuclear@26 1121 /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
nuclear@26 1122 out = 0;
nuclear@26 1123 for (in = 0; in < STEPSIZE; in++, out++) {
nuclear@26 1124 table[in] = out; table[-in] = -out;
nuclear@26 1125 }
nuclear@26 1126 /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
nuclear@26 1127 for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
nuclear@26 1128 table[in] = out; table[-in] = -out;
nuclear@26 1129 }
nuclear@26 1130 /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
nuclear@26 1131 for (; in <= MAXJSAMPLE; in++) {
nuclear@26 1132 table[in] = out; table[-in] = -out;
nuclear@26 1133 }
nuclear@26 1134 #undef STEPSIZE
nuclear@26 1135 }
nuclear@26 1136
nuclear@26 1137
nuclear@26 1138 /*
nuclear@26 1139 * Finish up at the end of each pass.
nuclear@26 1140 */
nuclear@26 1141
nuclear@26 1142 METHODDEF(void)
nuclear@26 1143 finish_pass1 (j_decompress_ptr cinfo)
nuclear@26 1144 {
nuclear@26 1145 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
nuclear@26 1146
nuclear@26 1147 /* Select the representative colors and fill in cinfo->colormap */
nuclear@26 1148 cinfo->colormap = cquantize->sv_colormap;
nuclear@26 1149 select_colors(cinfo, cquantize->desired);
nuclear@26 1150 /* Force next pass to zero the color index table */
nuclear@26 1151 cquantize->needs_zeroed = TRUE;
nuclear@26 1152 }
nuclear@26 1153
nuclear@26 1154
nuclear@26 1155 METHODDEF(void)
nuclear@26 1156 finish_pass2 (j_decompress_ptr cinfo)
nuclear@26 1157 {
nuclear@26 1158 /* no work */
nuclear@26 1159 }
nuclear@26 1160
nuclear@26 1161
nuclear@26 1162 /*
nuclear@26 1163 * Initialize for each processing pass.
nuclear@26 1164 */
nuclear@26 1165
nuclear@26 1166 METHODDEF(void)
nuclear@26 1167 start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
nuclear@26 1168 {
nuclear@26 1169 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
nuclear@26 1170 hist3d histogram = cquantize->histogram;
nuclear@26 1171 int i;
nuclear@26 1172
nuclear@26 1173 /* Only F-S dithering or no dithering is supported. */
nuclear@26 1174 /* If user asks for ordered dither, give him F-S. */
nuclear@26 1175 if (cinfo->dither_mode != JDITHER_NONE)
nuclear@26 1176 cinfo->dither_mode = JDITHER_FS;
nuclear@26 1177
nuclear@26 1178 if (is_pre_scan) {
nuclear@26 1179 /* Set up method pointers */
nuclear@26 1180 cquantize->pub.color_quantize = prescan_quantize;
nuclear@26 1181 cquantize->pub.finish_pass = finish_pass1;
nuclear@26 1182 cquantize->needs_zeroed = TRUE; /* Always zero histogram */
nuclear@26 1183 } else {
nuclear@26 1184 /* Set up method pointers */
nuclear@26 1185 if (cinfo->dither_mode == JDITHER_FS)
nuclear@26 1186 cquantize->pub.color_quantize = pass2_fs_dither;
nuclear@26 1187 else
nuclear@26 1188 cquantize->pub.color_quantize = pass2_no_dither;
nuclear@26 1189 cquantize->pub.finish_pass = finish_pass2;
nuclear@26 1190
nuclear@26 1191 /* Make sure color count is acceptable */
nuclear@26 1192 i = cinfo->actual_number_of_colors;
nuclear@26 1193 if (i < 1)
nuclear@26 1194 ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
nuclear@26 1195 if (i > MAXNUMCOLORS)
nuclear@26 1196 ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
nuclear@26 1197
nuclear@26 1198 if (cinfo->dither_mode == JDITHER_FS) {
nuclear@26 1199 size_t arraysize = (size_t) ((cinfo->output_width + 2) *
nuclear@26 1200 (3 * SIZEOF(FSERROR)));
nuclear@26 1201 /* Allocate Floyd-Steinberg workspace if we didn't already. */
nuclear@26 1202 if (cquantize->fserrors == NULL)
nuclear@26 1203 cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
nuclear@26 1204 ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
nuclear@26 1205 /* Initialize the propagated errors to zero. */
nuclear@26 1206 jzero_far((void FAR *) cquantize->fserrors, arraysize);
nuclear@26 1207 /* Make the error-limit table if we didn't already. */
nuclear@26 1208 if (cquantize->error_limiter == NULL)
nuclear@26 1209 init_error_limit(cinfo);
nuclear@26 1210 cquantize->on_odd_row = FALSE;
nuclear@26 1211 }
nuclear@26 1212
nuclear@26 1213 }
nuclear@26 1214 /* Zero the histogram or inverse color map, if necessary */
nuclear@26 1215 if (cquantize->needs_zeroed) {
nuclear@26 1216 for (i = 0; i < HIST_C0_ELEMS; i++) {
nuclear@26 1217 jzero_far((void FAR *) histogram[i],
nuclear@26 1218 HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
nuclear@26 1219 }
nuclear@26 1220 cquantize->needs_zeroed = FALSE;
nuclear@26 1221 }
nuclear@26 1222 }
nuclear@26 1223
nuclear@26 1224
nuclear@26 1225 /*
nuclear@26 1226 * Switch to a new external colormap between output passes.
nuclear@26 1227 */
nuclear@26 1228
nuclear@26 1229 METHODDEF(void)
nuclear@26 1230 new_color_map_2_quant (j_decompress_ptr cinfo)
nuclear@26 1231 {
nuclear@26 1232 my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
nuclear@26 1233
nuclear@26 1234 /* Reset the inverse color map */
nuclear@26 1235 cquantize->needs_zeroed = TRUE;
nuclear@26 1236 }
nuclear@26 1237
nuclear@26 1238
nuclear@26 1239 /*
nuclear@26 1240 * Module initialization routine for 2-pass color quantization.
nuclear@26 1241 */
nuclear@26 1242
nuclear@26 1243 GLOBAL(void)
nuclear@26 1244 jinit_2pass_quantizer (j_decompress_ptr cinfo)
nuclear@26 1245 {
nuclear@26 1246 my_cquantize_ptr cquantize;
nuclear@26 1247 int i;
nuclear@26 1248
nuclear@26 1249 cquantize = (my_cquantize_ptr)
nuclear@26 1250 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
nuclear@26 1251 SIZEOF(my_cquantizer));
nuclear@26 1252 cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
nuclear@26 1253 cquantize->pub.start_pass = start_pass_2_quant;
nuclear@26 1254 cquantize->pub.new_color_map = new_color_map_2_quant;
nuclear@26 1255 cquantize->fserrors = NULL; /* flag optional arrays not allocated */
nuclear@26 1256 cquantize->error_limiter = NULL;
nuclear@26 1257
nuclear@26 1258 /* Make sure jdmaster didn't give me a case I can't handle */
nuclear@26 1259 if (cinfo->out_color_components != 3)
nuclear@26 1260 ERREXIT(cinfo, JERR_NOTIMPL);
nuclear@26 1261
nuclear@26 1262 /* Allocate the histogram/inverse colormap storage */
nuclear@26 1263 cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
nuclear@26 1264 ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
nuclear@26 1265 for (i = 0; i < HIST_C0_ELEMS; i++) {
nuclear@26 1266 cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
nuclear@26 1267 ((j_common_ptr) cinfo, JPOOL_IMAGE,
nuclear@26 1268 HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
nuclear@26 1269 }
nuclear@26 1270 cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
nuclear@26 1271
nuclear@26 1272 /* Allocate storage for the completed colormap, if required.
nuclear@26 1273 * We do this now since it is FAR storage and may affect
nuclear@26 1274 * the memory manager's space calculations.
nuclear@26 1275 */
nuclear@26 1276 if (cinfo->enable_2pass_quant) {
nuclear@26 1277 /* Make sure color count is acceptable */
nuclear@26 1278 int desired = cinfo->desired_number_of_colors;
nuclear@26 1279 /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
nuclear@26 1280 if (desired < 8)
nuclear@26 1281 ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
nuclear@26 1282 /* Make sure colormap indexes can be represented by JSAMPLEs */
nuclear@26 1283 if (desired > MAXNUMCOLORS)
nuclear@26 1284 ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
nuclear@26 1285 cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
nuclear@26 1286 ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
nuclear@26 1287 cquantize->desired = desired;
nuclear@26 1288 } else
nuclear@26 1289 cquantize->sv_colormap = NULL;
nuclear@26 1290
nuclear@26 1291 /* Only F-S dithering or no dithering is supported. */
nuclear@26 1292 /* If user asks for ordered dither, give him F-S. */
nuclear@26 1293 if (cinfo->dither_mode != JDITHER_NONE)
nuclear@26 1294 cinfo->dither_mode = JDITHER_FS;
nuclear@26 1295
nuclear@26 1296 /* Allocate Floyd-Steinberg workspace if necessary.
nuclear@26 1297 * This isn't really needed until pass 2, but again it is FAR storage.
nuclear@26 1298 * Although we will cope with a later change in dither_mode,
nuclear@26 1299 * we do not promise to honor max_memory_to_use if dither_mode changes.
nuclear@26 1300 */
nuclear@26 1301 if (cinfo->dither_mode == JDITHER_FS) {
nuclear@26 1302 cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
nuclear@26 1303 ((j_common_ptr) cinfo, JPOOL_IMAGE,
nuclear@26 1304 (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
nuclear@26 1305 /* Might as well create the error-limiting table too. */
nuclear@26 1306 init_error_limit(cinfo);
nuclear@26 1307 }
nuclear@26 1308 }
nuclear@26 1309
nuclear@26 1310 #endif /* QUANT_2PASS_SUPPORTED */