jquant2.c 47 KB

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