jquant2.cpp 53 KB

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