jquant2.c 47 KB

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