jquant2.c 48 KB

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