Repo for the search and displace ingest module that takes odf, docx and pdf and transforms it into .md to be used with search and displace operations
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1551 lines
52 KiB

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