jquant2.c 48 KB

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