jquant2.pas 55 KB

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