📄 jquant2.c
字号:
/* Note it is important to get the rounding correct! */
histptr histp;
int c0,c1,c2;
int c0min,c0max,c1min,c1max,c2min,c2max;
long count;
long total = 0;
long c0total = 0;
long c1total = 0;
long c2total = 0;
c0min = boxp->c0min; c0max = boxp->c0max;
c1min = boxp->c1min; c1max = boxp->c1max;
c2min = boxp->c2min; c2max = boxp->c2max;
for (c0 = c0min; c0 <= c0max; c0++)
for (c1 = c1min; c1 <= c1max; c1++) {
histp = & histogram[c0][c1][c2min];
for (c2 = c2min; c2 <= c2max; c2++) {
if ((count = *histp++) != 0) {
total += count;
c0total += ((c0 << Y_SHIFT) + ((1<<Y_SHIFT)>>1)) * count;
c1total += ((c1 << C_SHIFT) + ((1<<C_SHIFT)>>1)) * count;
c2total += ((c2 << C_SHIFT) + ((1<<C_SHIFT)>>1)) * count;
}
}
}
my_colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
my_colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
my_colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
}
LOCAL void
remap_colormap (decompress_info_ptr cinfo)
/* Remap the internal colormap to the output colorspace */
{
/* This requires a little trickery since color_convert expects to
* deal with 3-D arrays (a 2-D sample array for each component).
* We must promote the colormaps into one-row 3-D arrays.
*/
short ci;
JSAMPARRAY input_hack[3];
JSAMPARRAY output_hack[10]; /* assume no more than 10 output components */
for (ci = 0; ci < 3; ci++)
input_hack[ci] = &(my_colormap[ci]);
for (ci = 0; ci < cinfo->color_out_comps; ci++)
output_hack[ci] = &(cinfo->colormap[ci]);
(*cinfo->methods->color_convert) (cinfo, 1,
(long) cinfo->actual_number_of_colors,
input_hack, output_hack);
}
LOCAL void
select_colors (decompress_info_ptr cinfo)
/* Master routine for color selection */
{
int desired = cinfo->desired_number_of_colors;
int i;
/* Allocate workspace for box list */
boxlist = (boxptr) (*cinfo->emethods->alloc_small) (desired * SIZEOF(box));
/* Initialize one box containing whole space */
numboxes = 1;
boxlist[0].c0min = 0;
boxlist[0].c0max = MAXJSAMPLE >> Y_SHIFT;
boxlist[0].c1min = 0;
boxlist[0].c1max = MAXJSAMPLE >> C_SHIFT;
boxlist[0].c2min = 0;
boxlist[0].c2max = MAXJSAMPLE >> C_SHIFT;
/* Shrink it to actually-used volume and set its statistics */
update_box(& boxlist[0]);
/* Perform median-cut to produce final box list */
median_cut(desired);
/* Compute the representative color for each box, fill my_colormap[] */
for (i = 0; i < numboxes; i++)
compute_color(& boxlist[i], i);
cinfo->actual_number_of_colors = numboxes;
/* Produce an output colormap in the desired output colorspace */
remap_colormap(cinfo);
/* TRACEMS1(cinfo->emethods, 1, "Selected %d colors for quantization",
numboxes); */
send_command(ERR5);
/* Done with the box list */
(*cinfo->emethods->free_small) ((void *) boxlist);
}
/*
* These routines are concerned with the time-critical task of mapping input
* colors to the nearest color in the selected colormap.
*
* We re-use the histogram space as an "inverse color map", essentially a
* cache for the results of nearest-color searches. All colors within a
* histogram cell will be mapped to the same colormap entry, namely the one
* closest to the cell's center. This may not be quite the closest entry to
* the actual input color, but it's almost as good. A zero in the cache
* indicates we haven't found the nearest color for that cell yet; the array
* is cleared to zeroes before starting the mapping pass. When we find the
* nearest color for a cell, its colormap index plus one is recorded in the
* cache for future use. The pass2 scanning routines call fill_inverse_cmap
* when they need to use an unfilled entry in the cache.
*
* Our method of efficiently finding nearest colors is based on the "locally
* sorted search" idea described by Heckbert and on the incremental distance
* calculation described by Spencer W. Thomas in chapter III.1 of Graphics
* Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
* the distances from a given colormap entry to each cell of the histogram can
* be computed quickly using an incremental method: the differences between
* distances to adjacent cells themselves differ by a constant. This allows a
* fairly fast implementation of the "brute force" approach of computing the
* distance from every colormap entry to every histogram cell. Unfortunately,
* it needs a work array to hold the best-distance-so-far for each histogram
* cell (because the inner loop has to be over cells, not colormap entries).
* The work array elements have to be INT32s, so the work array would need
* 256Kb at our recommended precision. This is not feasible in DOS machines.
* Another disadvantage of the brute force approach is that it computes
* distances to every cell of the cubical histogram. When working with YCbCr
* input, only about a quarter of the cube represents realizable colors, so
* many of the cells will never be used and filling them is wasted effort.
*
* To get around these problems, we apply Thomas' method to compute the
* nearest colors for only the cells within a small subbox of the histogram.
* The work array need be only as big as the subbox, so the memory usage
* problem is solved. A subbox is processed only when some cell in it is
* referenced by the pass2 routines, so we will never bother with cells far
* outside the realizable color volume. An additional advantage of this
* approach is that we can apply Heckbert's locality criterion to quickly
* eliminate colormap entries that are far away from the subbox; typically
* three-fourths of the colormap entries are rejected by Heckbert's criterion,
* and we need not compute their distances to individual cells in the subbox.
* The speed of this approach is heavily influenced by the subbox size: too
* small means too much overhead, too big loses because Heckbert's criterion
* can't eliminate as many colormap entries. Empirically the best subbox
* size seems to be about 1/512th of the histogram (1/8th in each direction).
*
* Thomas' article also describes a refined method which is asymptotically
* faster than the brute-force method, but it is also far more complex and
* cannot efficiently be applied to small subboxes. It is therefore not
* useful for programs intended to be portable to DOS machines. On machines
* with plenty of memory, filling the whole histogram in one shot with Thomas'
* refined method might be faster than the present code --- but then again,
* it might not be any faster, and it's certainly more complicated.
*/
#ifndef BOX_Y_LOG /* so you can override from Makefile */
#define BOX_Y_LOG (HIST_Y_BITS-3) /* log2(hist cells in update box, Y axis) */
#endif
#ifndef BOX_C_LOG /* so you can override from Makefile */
#define BOX_C_LOG (HIST_C_BITS-3) /* log2(hist cells in update box, C axes) */
#endif
#define BOX_Y_ELEMS (1<<BOX_Y_LOG) /* # of hist cells in update box */
#define BOX_C_ELEMS (1<<BOX_C_LOG)
#define BOX_Y_SHIFT (Y_SHIFT + BOX_Y_LOG)
#define BOX_C_SHIFT (C_SHIFT + BOX_C_LOG)
/*
* The next three routines implement inverse colormap filling. They could
* all be folded into one big routine, but splitting them up this way saves
* some stack space (the mindist[] and bestdist[] arrays need not coexist)
* and may allow some compilers to produce better code by registerizing more
* inner-loop variables.
*/
LOCAL int
find_nearby_colors (decompress_info_ptr cinfo, int minc0, int minc1, int minc2,
JSAMPLE colorlist[])
/* Locate the colormap entries close enough to an update box to be candidates
* for the nearest entry to some cell(s) in the update box. The update box
* is specified by the center coordinates of its first cell. The number of
* candidate colormap entries is returned, and their colormap indexes are
* placed in colorlist[].
* This routine uses Heckbert's "locally sorted search" criterion to select
* the colors that need further consideration.
*/
{
int numcolors = cinfo->actual_number_of_colors;
int maxc0, maxc1, maxc2;
int centerc0, centerc1, centerc2;
int i, x, ncolors;
INT32 minmaxdist, min_dist, max_dist, tdist;
INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
/* Compute true coordinates of update box's upper corner and center.
* Actually we compute the coordinates of the center of the upper-corner
* histogram cell, which are the upper bounds of the volume we care about.
* Note that since ">>" rounds down, the "center" values may be closer to
* min than to max; hence comparisons to them must be "<=", not "<".
*/
maxc0 = minc0 + ((1 << BOX_Y_SHIFT) - (1 << Y_SHIFT));
centerc0 = (minc0 + maxc0) >> 1;
maxc1 = minc1 + ((1 << BOX_C_SHIFT) - (1 << C_SHIFT));
centerc1 = (minc1 + maxc1) >> 1;
maxc2 = minc2 + ((1 << BOX_C_SHIFT) - (1 << C_SHIFT));
centerc2 = (minc2 + maxc2) >> 1;
/* For each color in colormap, find:
* 1. its minimum squared-distance to any point in the update box
* (zero if color is within update box);
* 2. its maximum squared-distance to any point in the update box.
* Both of these can be found by considering only the corners of the box.
* We save the minimum distance for each color in mindist[];
* only the smallest maximum distance is of interest.
* Note we have to scale Y to get correct distance in scaled space.
*/
minmaxdist = 0x7FFFFFFFL;
for (i = 0; i < numcolors; i++) {
/* We compute the squared-c0-distance term, then add in the other two. */
x = GETJSAMPLE(my_colormap[0][i]);
if (x < minc0) {
tdist = (x - minc0) * Y_SCALE;
min_dist = tdist*tdist;
tdist = (x - maxc0) * Y_SCALE;
max_dist = tdist*tdist;
} else if (x > maxc0) {
tdist = (x - maxc0) * Y_SCALE;
min_dist = tdist*tdist;
tdist = (x - minc0) * Y_SCALE;
max_dist = tdist*tdist;
} else {
/* within cell range so no contribution to min_dist */
min_dist = 0;
if (x <= centerc0) {
tdist = (x - maxc0) * Y_SCALE;
max_dist = tdist*tdist;
} else {
tdist = (x - minc0) * Y_SCALE;
max_dist = tdist*tdist;
}
}
x = GETJSAMPLE(my_colormap[1][i]);
if (x < minc1) {
tdist = x - minc1;
min_dist += tdist*tdist;
tdist = x - maxc1;
max_dist += tdist*tdist;
} else if (x > maxc1) {
tdist = x - maxc1;
min_dist += tdist*tdist;
tdist = x - minc1;
max_dist += tdist*tdist;
} else {
/* within cell range so no contribution to min_dist */
if (x <= centerc1) {
tdist = x - maxc1;
max_dist += tdist*tdist;
} else {
tdist = x - minc1;
max_dist += tdist*tdist;
}
}
x = GETJSAMPLE(my_colormap[2][i]);
if (x < minc2) {
tdist = x - minc2;
min_dist += tdist*tdist;
tdist = x - maxc2;
max_dist += tdist*tdist;
} else if (x > maxc2) {
tdist = x - maxc2;
min_dist += tdist*tdist;
tdist = x - minc2;
max_dist += tdist*tdist;
} else {
/* within cell range so no contribution to min_dist */
if (x <= centerc2) {
tdist = x - maxc2;
max_dist += tdist*tdist;
} else {
tdist = x - minc2;
max_dist += tdist*tdist;
}
}
mindist[i] = min_dist; /* save away the results */
if (max_dist < minmaxdist)
minmaxdist = max_dist;
}
/* Now we know that no cell in the update box is more than minmaxdist
* away from some colormap entry. Therefore, only colors that are
* within minmaxdist of some part of the box need be considered.
*/
ncolors = 0;
for (i = 0; i < numcolors; i++) {
if (mindist[i] <= minmaxdist)
colorlist[ncolors++] = (JSAMPLE) i;
}
return ncolors;
}
LOCAL void
find_best_colors (decompress_info_ptr cinfo, int minc0, int minc1, int minc2,
int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
/* Find the closest colormap entry for each cell in the update box,
* given the list of candidate colors prepared by find_nearby_colors.
* Return the indexes of the closest entries in the bestcolor[] array.
* This routine uses Thomas' incremental distance calculation method to
* find the distance from a colormap entry to successive cells in the box.
*/
{
int ic0, ic1, ic2;
int i, icolor;
register INT32 * bptr; /* pointer into bestdist[] array */
JSAMPLE * cptr; /* pointer into bestcolor[] array */
INT32 dist0, dist1; /* initial distance values */
register INT32 dist2; /* current distance in inner loop */
INT32 xx0, xx1; /* distance increments */
register INT32 xx2;
INT32 inc0, inc1, inc2; /* initial values for increments */
/* This array holds the distance to the nearest-so-far color for each cell */
INT32 bestdist[BOX_Y_ELEMS * BOX_C_ELEMS * BOX_C_ELEMS];
/* Initialize best-distance for each cell of the update box */
bptr = bestdist;
for (i = BOX_Y_ELEMS*BOX_C_ELEMS*BOX_C_ELEMS-1; i >= 0; i--)
*bptr++ = 0x7FFFFFFFL;
/* For each color selected by find_nearby_colors,
* compute its distance to the center of each cell in the box.
* If that's less than best-so-far, update best distance and color number.
* Note we have to scale Y to get correct distance in scaled space.
*/
/* Nominal steps between cell centers ("x" in Thomas article) */
#define STEP_Y ((1 << Y_SHIFT) * Y_SCALE)
#define STEP_C (1 << C_SHIFT)
for (i = 0; i < numcolors; i++) {
icolor = GETJSAMPLE(colorlist[i]);
/* Compute (square of) distance from minc0/c1/c2 to this color */
inc0 = (minc0 - (int) GETJSAMPLE(my_colormap[0][icolor])) * Y_SCALE;
dist0 = inc0*inc0;
inc1 = minc1 - (int) GETJSAMPLE(my_colormap[1][icolor]);
dist0 += inc1*inc1;
inc2 = minc2 - (int) GETJSAMPLE(my_colormap[2][icolor]);
dist0 += inc2*inc2;
/* Form the initial difference increments */
inc0 = inc0 * (2 * STEP_Y) + STEP_Y * STEP_Y;
inc1 = inc1 * (2 * STEP_C) + STEP_C * STEP_C;
inc2 = inc2 * (2 * STEP_C) + STEP_C * STEP_C;
/* Now loop over all cells in box, updating distance per Thomas method */
bptr = bestdist;
cptr = bestcolor;
xx0 = inc0;
for (ic0 = BOX_Y_ELEMS-1; ic0 >= 0; ic0--) {
dist1 = dist0;
xx1 = inc1;
for (ic1 = BOX_C_ELEMS-1; ic1 >= 0; ic1--) {
dist2 = dist1;
xx2 = inc2;
for (ic2 = BOX_C_ELEMS-1; ic2 >= 0; ic2--) {
if (dist2 < *bptr) {
*bptr = dist2;
*cptr = (JSAMPLE) icolor;
}
dist2 += xx2;
xx2 += 2 * STEP_C * STEP_C;
bptr++;
cptr++;
}
dist1 += xx1;
xx1 += 2 * STEP_C * STEP_C;
}
dist0 += xx0;
xx0 += 2 * STEP_Y * STEP_Y;
}
}
}
LOCAL void
fill_inverse_cmap (decompress_info_ptr cinfo, int c0, int c1, int c2)
/* Fill the inverse-colormap entries in the update box that contains */
/* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
/* we can fill as many others as we wish.) */
{
int minc0, minc1, minc2; /* lower left corner of update box */
int ic0, ic1, ic2;
register JSAMPLE * cptr; /* pointer into bestcolor[] array */
register histptr cachep; /* pointer into main cache array */
/* This array lists the candidate colormap indexes. */
JSAMPLE colorlist[MAXNUMCOLORS];
int numcolors; /* number of candidate colors */
/* This array holds the actually closest colormap index for each cell. */
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -