gd_topal.c 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070
  1. /* TODO: oim and nim in the lower level functions;
  2. correct use of stub (sigh). */
  3. /* 2.0.12: a new adaptation from the same original, this time
  4. by Barend Gehrels. My attempt to incorporate alpha channel
  5. into the result worked poorly and degraded the quality of
  6. palette conversion even when the source contained no
  7. alpha channel data. This version does not attempt to produce
  8. an output file with transparency in some of the palette
  9. indexes, which, in practice, doesn't look so hot anyway. TBB */
  10. /*
  11. * gd_topal, adapted from jquant2.c
  12. *
  13. * Copyright (C) 1991-1996, Thomas G. Lane.
  14. * This file is part of the Independent JPEG Group's software.
  15. * For conditions of distribution and use, see the accompanying README file.
  16. *
  17. * This file contains 2-pass color quantization (color mapping) routines.
  18. * These routines provide selection of a custom color map for an image,
  19. * followed by mapping of the image to that color map, with optional
  20. * Floyd-Steinberg dithering.
  21. * It is also possible to use just the second pass to map to an arbitrary
  22. * externally-given color map.
  23. *
  24. * Note: ordered dithering is not supported, since there isn't any fast
  25. * way to compute intercolor distances; it's unclear that ordered dither's
  26. * fundamental assumptions even hold with an irregularly spaced color map.
  27. */
  28. #ifdef ORIGINAL_LIB_JPEG
  29. #define JPEG_INTERNALS
  30. #include "jinclude.h"
  31. #include "jpeglib.h"
  32. #else
  33. /*
  34. * THOMAS BOUTELL & BAREND GEHRELS, february 2003
  35. * adapted the code to work within gd rather than within libjpeg.
  36. * If it is not working, it's not Thomas G. Lane's fault.
  37. */
  38. /*
  39. SETTING THIS ONE CAUSES STRIPED IMAGE
  40. to be done: solve this
  41. #define ORIGINAL_LIB_JPEG_REVERSE_ODD_ROWS
  42. */
  43. #include <string.h>
  44. #include "gd.h"
  45. #include "gdhelpers.h"
  46. /* (Re)define some defines known by libjpeg */
  47. #define QUANT_2PASS_SUPPORTED
  48. #define RGB_RED 0
  49. #define RGB_GREEN 1
  50. #define RGB_BLUE 2
  51. #define JSAMPLE unsigned char
  52. #define MAXJSAMPLE (gdMaxColors-1)
  53. #define BITS_IN_JSAMPLE 8
  54. #define JSAMPROW int*
  55. #define JDIMENSION int
  56. #define METHODDEF(type) static type
  57. #define LOCAL(type) static type
  58. /* We assume that right shift corresponds to signed division by 2 with
  59. * rounding towards minus infinity. This is correct for typical "arithmetic
  60. * shift" instructions that shift in copies of the sign bit. But some
  61. * C compilers implement >> with an unsigned shift. For these machines you
  62. * must define RIGHT_SHIFT_IS_UNSIGNED.
  63. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  64. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  65. * included in the variables of any routine using RIGHT_SHIFT.
  66. */
  67. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  68. #define SHIFT_TEMPS INT32 shift_temp;
  69. #define RIGHT_SHIFT(x,shft) \
  70. ((shift_temp = (x)) < 0 ? \
  71. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  72. (shift_temp >> (shft)))
  73. #else
  74. #define SHIFT_TEMPS
  75. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  76. #endif
  77. #define range_limit(x) { if(x<0) x=0; if (x>255) x=255; }
  78. #ifndef INT16
  79. #define INT16 short
  80. #endif
  81. #ifndef UINT16
  82. #define UINT16 unsigned short
  83. #endif
  84. #ifndef INT32
  85. #define INT32 int
  86. #endif
  87. #ifndef FAR
  88. #define FAR
  89. #endif
  90. #ifndef boolean
  91. #define boolean int
  92. #endif
  93. #ifndef TRUE
  94. #define TRUE 1
  95. #endif
  96. #ifndef FALSE
  97. #define FALSE 0
  98. #endif
  99. #define input_buf (oim->tpixels)
  100. #define output_buf (nim->pixels)
  101. #endif
  102. #ifdef QUANT_2PASS_SUPPORTED
  103. /*
  104. * This module implements the well-known Heckbert paradigm for color
  105. * quantization. Most of the ideas used here can be traced back to
  106. * Heckbert's seminal paper
  107. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  108. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  109. *
  110. * In the first pass over the image, we accumulate a histogram showing the
  111. * usage count of each possible color. To keep the histogram to a reasonable
  112. * size, we reduce the precision of the input; typical practice is to retain
  113. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  114. * in the same histogram cell.
  115. *
  116. * Next, the color-selection step begins with a box representing the whole
  117. * color space, and repeatedly splits the "largest" remaining box until we
  118. * have as many boxes as desired colors. Then the mean color in each
  119. * remaining box becomes one of the possible output colors.
  120. *
  121. * The second pass over the image maps each input pixel to the closest output
  122. * color (optionally after applying a Floyd-Steinberg dithering correction).
  123. * This mapping is logically trivial, but making it go fast enough requires
  124. * considerable care.
  125. *
  126. * Heckbert-style quantizers vary a good deal in their policies for choosing
  127. * the "largest" box and deciding where to cut it. The particular policies
  128. * used here have proved out well in experimental comparisons, but better ones
  129. * may yet be found.
  130. *
  131. * In earlier versions of the IJG code, this module quantized in YCbCr color
  132. * space, processing the raw upsampled data without a color conversion step.
  133. * This allowed the color conversion math to be done only once per colormap
  134. * entry, not once per pixel. However, that optimization precluded other
  135. * useful optimizations (such as merging color conversion with upsampling)
  136. * and it also interfered with desired capabilities such as quantizing to an
  137. * externally-supplied colormap. We have therefore abandoned that approach.
  138. * The present code works in the post-conversion color space, typically RGB.
  139. *
  140. * To improve the visual quality of the results, we actually work in scaled
  141. * RGB space, giving G distances more weight than R, and R in turn more than
  142. * B. To do everything in integer math, we must use integer scale factors.
  143. * The 2/3/1 scale factors used here correspond loosely to the relative
  144. * weights of the colors in the NTSC grayscale equation.
  145. * If you want to use this code to quantize a non-RGB color space, you'll
  146. * probably need to change these scale factors.
  147. */
  148. #define R_SCALE 2 /* scale R distances by this much */
  149. #define G_SCALE 3 /* scale G distances by this much */
  150. #define B_SCALE 1 /* and B by this much */
  151. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  152. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  153. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  154. * you'll get compile errors until you extend this logic. In that case
  155. * you'll probably want to tweak the histogram sizes too.
  156. */
  157. #if RGB_RED == 0
  158. #define C0_SCALE R_SCALE
  159. #endif
  160. #if RGB_BLUE == 0
  161. #define C0_SCALE B_SCALE
  162. #endif
  163. #if RGB_GREEN == 1
  164. #define C1_SCALE G_SCALE
  165. #endif
  166. #if RGB_RED == 2
  167. #define C2_SCALE R_SCALE
  168. #endif
  169. #if RGB_BLUE == 2
  170. #define C2_SCALE B_SCALE
  171. #endif
  172. /*
  173. * First we have the histogram data structure and routines for creating it.
  174. *
  175. * The number of bits of precision can be adjusted by changing these symbols.
  176. * We recommend keeping 6 bits for G and 5 each for R and B.
  177. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  178. * better results; if you are short of memory, 5 bits all around will save
  179. * some space but degrade the results.
  180. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  181. * (preferably unsigned long) for each cell. In practice this is overkill;
  182. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  183. * and clamping those that do overflow to the maximum value will give close-
  184. * enough results. This reduces the recommended histogram size from 256Kb
  185. * to 128Kb, which is a useful savings on PC-class machines.
  186. * (In the second pass the histogram space is re-used for pixel mapping data;
  187. * in that capacity, each cell must be able to store zero to the number of
  188. * desired colors. 16 bits/cell is plenty for that too.)
  189. * Since the JPEG code is intended to run in small memory model on 80x86
  190. * machines, we can't just allocate the histogram in one chunk. Instead
  191. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  192. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  193. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  194. * on 80x86 machines, the pointer row is in near memory but the actual
  195. * arrays are in far memory (same arrangement as we use for image arrays).
  196. */
  197. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  198. /* These will do the right thing for either R,G,B or B,G,R color order,
  199. * but you may not like the results for other color orders.
  200. */
  201. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  202. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  203. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  204. /* Number of elements along histogram axes. */
  205. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  206. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  207. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  208. /* These are the amounts to shift an input value to get a histogram index. */
  209. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  210. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  211. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  212. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  213. typedef histcell FAR *histptr; /* for pointers to histogram cells */
  214. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  215. typedef hist1d FAR *hist2d; /* type for the 2nd-level pointers */
  216. typedef hist2d *hist3d; /* type for top-level pointer */
  217. /* Declarations for Floyd-Steinberg dithering.
  218. *
  219. * Errors are accumulated into the array fserrors[], at a resolution of
  220. * 1/16th of a pixel count. The error at a given pixel is propagated
  221. * to its not-yet-processed neighbors using the standard F-S fractions,
  222. * ... (here) 7/16
  223. * 3/16 5/16 1/16
  224. * We work left-to-right on even rows, right-to-left on odd rows.
  225. *
  226. * We can get away with a single array (holding one row's worth of errors)
  227. * by using it to store the current row's errors at pixel columns not yet
  228. * processed, but the next row's errors at columns already processed. We
  229. * need only a few extra variables to hold the errors immediately around the
  230. * current column. (If we are lucky, those variables are in registers, but
  231. * even if not, they're probably cheaper to access than array elements are.)
  232. *
  233. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  234. * each end saves us from special-casing the first and last pixels.
  235. * Each entry is three values long, one value for each color component.
  236. *
  237. * Note: on a wide image, we might not have enough room in a PC's near data
  238. * segment to hold the error array; so it is allocated with alloc_large.
  239. */
  240. #if BITS_IN_JSAMPLE == 8
  241. typedef INT16 FSERROR; /* 16 bits should be enough */
  242. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  243. #else
  244. typedef INT32 FSERROR; /* may need more than 16 bits */
  245. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  246. #endif
  247. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  248. /* Private subobject */
  249. typedef struct
  250. {
  251. #ifdef ORIGINAL_LIB_JPEG
  252. struct jpeg_color_quantizer pub; /* public fields */
  253. /* Space for the eventually created colormap is stashed here */
  254. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  255. int desired; /* desired # of colors = size of colormap */
  256. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  257. #endif
  258. /* Variables for accumulating image statistics */
  259. hist3d histogram; /* pointer to the histogram */
  260. /* Variables for Floyd-Steinberg dithering */
  261. FSERRPTR fserrors; /* accumulated errors */
  262. boolean on_odd_row; /* flag to remember which row we are on */
  263. int *error_limiter; /* table for clamping the applied error */
  264. #ifndef ORIGINAL_LIB_JPEG
  265. int *error_limiter_storage; /* gdMalloc'd storage for the above */
  266. #endif
  267. }
  268. my_cquantizer;
  269. typedef my_cquantizer *my_cquantize_ptr;
  270. /*
  271. * Prescan some rows of pixels.
  272. * In this module the prescan simply updates the histogram, which has been
  273. * initialized to zeroes by start_pass.
  274. * An output_buf parameter is required by the method signature, but no data
  275. * is actually output (in fact the buffer controller is probably passing a
  276. * NULL pointer).
  277. */
  278. METHODDEF (void)
  279. #ifndef ORIGINAL_LIB_JPEG
  280. prescan_quantize (gdImagePtr oim, gdImagePtr nim, my_cquantize_ptr cquantize)
  281. {
  282. #else
  283. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  284. JSAMPARRAY output_buf, int num_rows)
  285. {
  286. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  287. #endif
  288. register JSAMPROW ptr;
  289. register histptr histp;
  290. register hist3d histogram = cquantize->histogram;
  291. int row;
  292. JDIMENSION col;
  293. #ifdef ORIGINAL_LIB_JPEG
  294. JDIMENSION width = cinfo->output_width;
  295. #else
  296. int width = oim->sx;
  297. int num_rows = oim->sy;
  298. #endif
  299. for (row = 0; row < num_rows; row++)
  300. {
  301. ptr = input_buf[row];
  302. for (col = width; col > 0; col--)
  303. {
  304. #ifdef ORIGINAL_LIB_JPEG
  305. int r = GETJSAMPLE (ptr[0]) >> C0_SHIFT;
  306. int g = GETJSAMPLE (ptr[1]) >> C1_SHIFT;
  307. int b = GETJSAMPLE (ptr[2]) >> C2_SHIFT;
  308. #else
  309. int r = gdTrueColorGetRed (*ptr) >> C0_SHIFT;
  310. int g = gdTrueColorGetGreen (*ptr) >> C1_SHIFT;
  311. int b = gdTrueColorGetBlue (*ptr) >> C2_SHIFT;
  312. /* 2.0.12: Steven Brown: support a single totally transparent
  313. color in the original. */
  314. if ((oim->transparent >= 0) && (*ptr == oim->transparent))
  315. {
  316. ptr++;
  317. continue;
  318. }
  319. #endif
  320. /* get pixel value and index into the histogram */
  321. histp = &histogram[r][g][b];
  322. /* increment, check for overflow and undo increment if so. */
  323. if (++(*histp) == 0)
  324. (*histp)--;
  325. #ifdef ORIGINAL_LIB_JPEG
  326. ptr += 3;
  327. #else
  328. ptr++;
  329. #endif
  330. }
  331. }
  332. }
  333. /*
  334. * Next we have the really interesting routines: selection of a colormap
  335. * given the completed histogram.
  336. * These routines work with a list of "boxes", each representing a rectangular
  337. * subset of the input color space (to histogram precision).
  338. */
  339. typedef struct
  340. {
  341. /* The bounds of the box (inclusive); expressed as histogram indexes */
  342. int c0min, c0max;
  343. int c1min, c1max;
  344. int c2min, c2max;
  345. /* The volume (actually 2-norm) of the box */
  346. INT32 volume;
  347. /* The number of nonzero histogram cells within this box */
  348. long colorcount;
  349. }
  350. box;
  351. typedef box *boxptr;
  352. LOCAL (boxptr) find_biggest_color_pop (boxptr boxlist, int numboxes)
  353. /* Find the splittable box with the largest color population */
  354. /* Returns NULL if no splittable boxes remain */
  355. {
  356. register boxptr boxp;
  357. register int i;
  358. register long maxc = 0;
  359. boxptr which = NULL;
  360. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++)
  361. {
  362. if (boxp->colorcount > maxc && boxp->volume > 0)
  363. {
  364. which = boxp;
  365. maxc = boxp->colorcount;
  366. }
  367. }
  368. return which;
  369. }
  370. LOCAL (boxptr) find_biggest_volume (boxptr boxlist, int numboxes)
  371. /* Find the splittable box with the largest (scaled) volume */
  372. /* Returns NULL if no splittable boxes remain */
  373. {
  374. register boxptr boxp;
  375. register int i;
  376. register INT32 maxv = 0;
  377. boxptr which = NULL;
  378. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++)
  379. {
  380. if (boxp->volume > maxv)
  381. {
  382. which = boxp;
  383. maxv = boxp->volume;
  384. }
  385. }
  386. return which;
  387. }
  388. LOCAL (void)
  389. #ifndef ORIGINAL_LIB_JPEG
  390. update_box (gdImagePtr oim, gdImagePtr nim, my_cquantize_ptr cquantize, boxptr boxp)
  391. {
  392. #else
  393. update_box (j_decompress_ptr cinfo, boxptr boxp)
  394. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  395. /* and recompute its volume and population */
  396. {
  397. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  398. #endif
  399. hist3d histogram = cquantize->histogram;
  400. histptr histp;
  401. int c0, c1, c2;
  402. int c0min, c0max, c1min, c1max, c2min, c2max;
  403. INT32 dist0, dist1, dist2;
  404. long ccount;
  405. c0min = boxp->c0min;
  406. c0max = boxp->c0max;
  407. c1min = boxp->c1min;
  408. c1max = boxp->c1max;
  409. c2min = boxp->c2min;
  410. c2max = boxp->c2max;
  411. if (c0max > c0min)
  412. for (c0 = c0min; c0 <= c0max; c0++)
  413. for (c1 = c1min; c1 <= c1max; c1++)
  414. {
  415. histp = &histogram[c0][c1][c2min];
  416. for (c2 = c2min; c2 <= c2max; c2++)
  417. if (*histp++ != 0)
  418. {
  419. boxp->c0min = c0min = c0;
  420. goto have_c0min;
  421. }
  422. }
  423. have_c0min:
  424. if (c0max > c0min)
  425. for (c0 = c0max; c0 >= c0min; c0--)
  426. for (c1 = c1min; c1 <= c1max; c1++)
  427. {
  428. histp = &histogram[c0][c1][c2min];
  429. for (c2 = c2min; c2 <= c2max; c2++)
  430. if (*histp++ != 0)
  431. {
  432. boxp->c0max = c0max = c0;
  433. goto have_c0max;
  434. }
  435. }
  436. have_c0max:
  437. if (c1max > c1min)
  438. for (c1 = c1min; c1 <= c1max; c1++)
  439. for (c0 = c0min; c0 <= c0max; c0++)
  440. {
  441. histp = &histogram[c0][c1][c2min];
  442. for (c2 = c2min; c2 <= c2max; c2++)
  443. if (*histp++ != 0)
  444. {
  445. boxp->c1min = c1min = c1;
  446. goto have_c1min;
  447. }
  448. }
  449. have_c1min:
  450. if (c1max > c1min)
  451. for (c1 = c1max; c1 >= c1min; c1--)
  452. for (c0 = c0min; c0 <= c0max; c0++)
  453. {
  454. histp = &histogram[c0][c1][c2min];
  455. for (c2 = c2min; c2 <= c2max; c2++)
  456. if (*histp++ != 0)
  457. {
  458. boxp->c1max = c1max = c1;
  459. goto have_c1max;
  460. }
  461. }
  462. have_c1max:
  463. if (c2max > c2min)
  464. for (c2 = c2min; c2 <= c2max; c2++)
  465. for (c0 = c0min; c0 <= c0max; c0++)
  466. {
  467. histp = &histogram[c0][c1min][c2];
  468. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  469. if (*histp != 0)
  470. {
  471. boxp->c2min = c2min = c2;
  472. goto have_c2min;
  473. }
  474. }
  475. have_c2min:
  476. if (c2max > c2min)
  477. for (c2 = c2max; c2 >= c2min; c2--)
  478. for (c0 = c0min; c0 <= c0max; c0++)
  479. {
  480. histp = &histogram[c0][c1min][c2];
  481. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  482. if (*histp != 0)
  483. {
  484. boxp->c2max = c2max = c2;
  485. goto have_c2max;
  486. }
  487. }
  488. have_c2max:
  489. /* Update box volume.
  490. * We use 2-norm rather than real volume here; this biases the method
  491. * against making long narrow boxes, and it has the side benefit that
  492. * a box is splittable iff norm > 0.
  493. * Since the differences are expressed in histogram-cell units,
  494. * we have to shift back to JSAMPLE units to get consistent distances;
  495. * after which, we scale according to the selected distance scale factors.
  496. */
  497. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  498. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  499. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  500. boxp->volume = dist0 * dist0 + dist1 * dist1 + dist2 * dist2;
  501. /* Now scan remaining volume of box and compute population */
  502. ccount = 0;
  503. for (c0 = c0min; c0 <= c0max; c0++)
  504. for (c1 = c1min; c1 <= c1max; c1++)
  505. {
  506. histp = &histogram[c0][c1][c2min];
  507. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  508. if (*histp != 0)
  509. {
  510. ccount++;
  511. }
  512. }
  513. boxp->colorcount = ccount;
  514. }
  515. LOCAL (int)
  516. #ifdef ORIGINAL_LIB_JPEG
  517. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  518. int desired_colors)
  519. #else
  520. median_cut (gdImagePtr oim, gdImagePtr nim, my_cquantize_ptr cquantize,
  521. boxptr boxlist, int numboxes, int desired_colors)
  522. #endif
  523. /* Repeatedly select and split the largest box until we have enough boxes */
  524. {
  525. int n, lb;
  526. int c0, c1, c2, cmax;
  527. register boxptr b1, b2;
  528. while (numboxes < desired_colors)
  529. {
  530. /* Select box to split.
  531. * Current algorithm: by population for first half, then by volume.
  532. */
  533. if (numboxes * 2 <= desired_colors)
  534. {
  535. b1 = find_biggest_color_pop (boxlist, numboxes);
  536. }
  537. else
  538. {
  539. b1 = find_biggest_volume (boxlist, numboxes);
  540. }
  541. if (b1 == NULL) /* no splittable boxes left! */
  542. break;
  543. b2 = &boxlist[numboxes]; /* where new box will go */
  544. /* Copy the color bounds to the new box. */
  545. b2->c0max = b1->c0max;
  546. b2->c1max = b1->c1max;
  547. b2->c2max = b1->c2max;
  548. b2->c0min = b1->c0min;
  549. b2->c1min = b1->c1min;
  550. b2->c2min = b1->c2min;
  551. /* Choose which axis to split the box on.
  552. * Current algorithm: longest scaled axis.
  553. * See notes in update_box about scaling distances.
  554. */
  555. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  556. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  557. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  558. /* We want to break any ties in favor of green, then red, blue last.
  559. * This code does the right thing for R,G,B or B,G,R color orders only.
  560. */
  561. #if RGB_RED == 0
  562. cmax = c1;
  563. n = 1;
  564. if (c0 > cmax)
  565. {
  566. cmax = c0;
  567. n = 0;
  568. }
  569. if (c2 > cmax)
  570. {
  571. n = 2;
  572. }
  573. #else
  574. cmax = c1;
  575. n = 1;
  576. if (c2 > cmax)
  577. {
  578. cmax = c2;
  579. n = 2;
  580. }
  581. if (c0 > cmax)
  582. {
  583. n = 0;
  584. }
  585. #endif
  586. /* Choose split point along selected axis, and update box bounds.
  587. * Current algorithm: split at halfway point.
  588. * (Since the box has been shrunk to minimum volume,
  589. * any split will produce two nonempty subboxes.)
  590. * Note that lb value is max for lower box, so must be < old max.
  591. */
  592. switch (n)
  593. {
  594. case 0:
  595. lb = (b1->c0max + b1->c0min) / 2;
  596. b1->c0max = lb;
  597. b2->c0min = lb + 1;
  598. break;
  599. case 1:
  600. lb = (b1->c1max + b1->c1min) / 2;
  601. b1->c1max = lb;
  602. b2->c1min = lb + 1;
  603. break;
  604. case 2:
  605. lb = (b1->c2max + b1->c2min) / 2;
  606. b1->c2max = lb;
  607. b2->c2min = lb + 1;
  608. break;
  609. }
  610. /* Update stats for boxes */
  611. #ifdef ORIGINAL_LIB_JPEG
  612. update_box (cinfo, b1);
  613. update_box (cinfo, b2);
  614. #else
  615. update_box (oim, nim, cquantize, b1);
  616. update_box (oim, nim, cquantize, b2);
  617. #endif
  618. numboxes++;
  619. }
  620. return numboxes;
  621. }
  622. LOCAL (void)
  623. #ifndef ORIGINAL_LIB_JPEG
  624. compute_color (gdImagePtr oim, gdImagePtr nim, my_cquantize_ptr cquantize,
  625. boxptr boxp, int icolor)
  626. {
  627. #else
  628. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  629. /* Compute representative color for a box, put it in colormap[icolor] */
  630. {
  631. /* Current algorithm: mean weighted by pixels (not colors) */
  632. /* Note it is important to get the rounding correct! */
  633. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  634. #endif
  635. hist3d histogram = cquantize->histogram;
  636. histptr histp;
  637. int c0, c1, c2;
  638. int c0min, c0max, c1min, c1max, c2min, c2max;
  639. long count = 0; /* 2.0.28: = 0 */
  640. long total = 0;
  641. long c0total = 0;
  642. long c1total = 0;
  643. long c2total = 0;
  644. c0min = boxp->c0min;
  645. c0max = boxp->c0max;
  646. c1min = boxp->c1min;
  647. c1max = boxp->c1max;
  648. c2min = boxp->c2min;
  649. c2max = boxp->c2max;
  650. for (c0 = c0min; c0 <= c0max; c0++)
  651. for (c1 = c1min; c1 <= c1max; c1++)
  652. {
  653. histp = &histogram[c0][c1][c2min];
  654. for (c2 = c2min; c2 <= c2max; c2++)
  655. {
  656. if ((count = *histp++) != 0)
  657. {
  658. total += count;
  659. c0total +=
  660. ((c0 << C0_SHIFT) + ((1 << C0_SHIFT) >> 1)) * count;
  661. c1total +=
  662. ((c1 << C1_SHIFT) + ((1 << C1_SHIFT) >> 1)) * count;
  663. c2total +=
  664. ((c2 << C2_SHIFT) + ((1 << C2_SHIFT) >> 1)) * count;
  665. }
  666. }
  667. }
  668. #ifdef ORIGINAL_LIB_JPEG
  669. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total >> 1)) / total);
  670. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total >> 1)) / total);
  671. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total >> 1)) / total);
  672. #else
  673. /* 2.0.16: Paul den Dulk found an occasion where total can be 0 */
  674. if (total)
  675. {
  676. nim->red[icolor] = (int) ((c0total + (total >> 1)) / total);
  677. nim->green[icolor] = (int) ((c1total + (total >> 1)) / total);
  678. nim->blue[icolor] = (int) ((c2total + (total >> 1)) / total);
  679. }
  680. else
  681. {
  682. nim->red[icolor] = 255;
  683. nim->green[icolor] = 255;
  684. nim->blue[icolor] = 255;
  685. }
  686. nim->open[icolor] = 0;
  687. #endif
  688. }
  689. LOCAL (void)
  690. #ifdef ORIGINAL_LIB_JPEG
  691. select_colors (j_decompress_ptr cinfo, int desired_colors)
  692. #else
  693. select_colors (gdImagePtr oim, gdImagePtr nim, my_cquantize_ptr cquantize, int desired_colors)
  694. #endif
  695. /* Master routine for color selection */
  696. {
  697. boxptr boxlist;
  698. int numboxes;
  699. int i;
  700. /* Allocate workspace for box list */
  701. #ifdef ORIGINAL_LIB_JPEG
  702. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  703. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF (box));
  704. #else
  705. boxlist = (boxptr) safe_emalloc(desired_colors, sizeof (box), 1);
  706. #endif
  707. /* Initialize one box containing whole space */
  708. numboxes = 1;
  709. boxlist[0].c0min = 0;
  710. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  711. boxlist[0].c1min = 0;
  712. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  713. boxlist[0].c2min = 0;
  714. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  715. #ifdef ORIGINAL_LIB_JPEG
  716. /* Shrink it to actually-used volume and set its statistics */
  717. update_box (cinfo, &boxlist[0]);
  718. /* Perform median-cut to produce final box list */
  719. numboxes = median_cut (cinfo, boxlist, numboxes, desired_colors);
  720. /* Compute the representative color for each box, fill colormap */
  721. for (i = 0; i < numboxes; i++)
  722. compute_color (cinfo, &boxlist[i], i);
  723. cinfo->actual_number_of_colors = numboxes;
  724. TRACEMS1 (cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  725. #else
  726. /* Shrink it to actually-used volume and set its statistics */
  727. update_box (oim, nim, cquantize, &boxlist[0]);
  728. /* Perform median-cut to produce final box list */
  729. numboxes = median_cut (oim, nim, cquantize, boxlist, numboxes, desired_colors);
  730. /* Compute the representative color for each box, fill colormap */
  731. for (i = 0; i < numboxes; i++)
  732. compute_color (oim, nim, cquantize, &boxlist[i], i);
  733. nim->colorsTotal = numboxes;
  734. /* If we had a pure transparency color, add it as the last palette entry.
  735. * Skip incrementing the color count so that the dither / matching phase
  736. * won't use it on pixels that shouldn't have been transparent. We'll
  737. * increment it after all that finishes. */
  738. if (oim->transparent >= 0)
  739. {
  740. /* Save the transparent color. */
  741. nim->red[nim->colorsTotal] = gdTrueColorGetRed (oim->transparent);
  742. nim->green[nim->colorsTotal] = gdTrueColorGetGreen (oim->transparent);
  743. nim->blue[nim->colorsTotal] = gdTrueColorGetBlue (oim->transparent);
  744. nim->alpha[nim->colorsTotal] = gdAlphaTransparent;
  745. nim->open[nim->colorsTotal] = 0;
  746. }
  747. gdFree (boxlist);
  748. #endif
  749. }
  750. /*
  751. * These routines are concerned with the time-critical task of mapping input
  752. * colors to the nearest color in the selected colormap.
  753. *
  754. * We re-use the histogram space as an "inverse color map", essentially a
  755. * cache for the results of nearest-color searches. All colors within a
  756. * histogram cell will be mapped to the same colormap entry, namely the one
  757. * closest to the cell's center. This may not be quite the closest entry to
  758. * the actual input color, but it's almost as good. A zero in the cache
  759. * indicates we haven't found the nearest color for that cell yet; the array
  760. * is cleared to zeroes before starting the mapping pass. When we find the
  761. * nearest color for a cell, its colormap index plus one is recorded in the
  762. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  763. * when they need to use an unfilled entry in the cache.
  764. *
  765. * Our method of efficiently finding nearest colors is based on the "locally
  766. * sorted search" idea described by Heckbert and on the incremental distance
  767. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  768. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  769. * the distances from a given colormap entry to each cell of the histogram can
  770. * be computed quickly using an incremental method: the differences between
  771. * distances to adjacent cells themselves differ by a constant. This allows a
  772. * fairly fast implementation of the "brute force" approach of computing the
  773. * distance from every colormap entry to every histogram cell. Unfortunately,
  774. * it needs a work array to hold the best-distance-so-far for each histogram
  775. * cell (because the inner loop has to be over cells, not colormap entries).
  776. * The work array elements have to be INT32s, so the work array would need
  777. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  778. *
  779. * To get around these problems, we apply Thomas' method to compute the
  780. * nearest colors for only the cells within a small subbox of the histogram.
  781. * The work array need be only as big as the subbox, so the memory usage
  782. * problem is solved. Furthermore, we need not fill subboxes that are never
  783. * referenced in pass2; many images use only part of the color gamut, so a
  784. * fair amount of work is saved. An additional advantage of this
  785. * approach is that we can apply Heckbert's locality criterion to quickly
  786. * eliminate colormap entries that are far away from the subbox; typically
  787. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  788. * and we need not compute their distances to individual cells in the subbox.
  789. * The speed of this approach is heavily influenced by the subbox size: too
  790. * small means too much overhead, too big loses because Heckbert's criterion
  791. * can't eliminate as many colormap entries. Empirically the best subbox
  792. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  793. *
  794. * Thomas' article also describes a refined method which is asymptotically
  795. * faster than the brute-force method, but it is also far more complex and
  796. * cannot efficiently be applied to small subboxes. It is therefore not
  797. * useful for programs intended to be portable to DOS machines. On machines
  798. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  799. * refined method might be faster than the present code --- but then again,
  800. * it might not be any faster, and it's certainly more complicated.
  801. */
  802. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  803. #define BOX_C0_LOG (HIST_C0_BITS-3)
  804. #define BOX_C1_LOG (HIST_C1_BITS-3)
  805. #define BOX_C2_LOG (HIST_C2_BITS-3)
  806. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  807. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  808. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  809. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  810. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  811. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  812. /*
  813. * The next three routines implement inverse colormap filling. They could
  814. * all be folded into one big routine, but splitting them up this way saves
  815. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  816. * and may allow some compilers to produce better code by registerizing more
  817. * inner-loop variables.
  818. */
  819. LOCAL (int)
  820. find_nearby_colors (
  821. #ifdef ORIGINAL_LIB_JPEG
  822. j_decompress_ptr cinfo,
  823. #else
  824. gdImagePtr oim, gdImagePtr nim, my_cquantize_ptr cquantize,
  825. #endif
  826. int minc0, int minc1, int minc2, JSAMPLE colorlist[])
  827. /* Locate the colormap entries close enough to an update box to be candidates
  828. * for the nearest entry to some cell(s) in the update box. The update box
  829. * is specified by the center coordinates of its first cell. The number of
  830. * candidate colormap entries is returned, and their colormap indexes are
  831. * placed in colorlist[].
  832. * This routine uses Heckbert's "locally sorted search" criterion to select
  833. * the colors that need further consideration.
  834. */
  835. {
  836. #ifdef ORIGINAL_LIB_JPEG
  837. int numcolors = cinfo->actual_number_of_colors;
  838. #else
  839. int numcolors = nim->colorsTotal;
  840. #endif
  841. int maxc0, maxc1, maxc2;
  842. int centerc0, centerc1, centerc2;
  843. int i, x, ncolors;
  844. INT32 minmaxdist, min_dist, max_dist, tdist;
  845. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  846. /* Compute true coordinates of update box's upper corner and center.
  847. * Actually we compute the coordinates of the center of the upper-corner
  848. * histogram cell, which are the upper bounds of the volume we care about.
  849. * Note that since ">>" rounds down, the "center" values may be closer to
  850. * min than to max; hence comparisons to them must be "<=", not "<".
  851. */
  852. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  853. centerc0 = (minc0 + maxc0) >> 1;
  854. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  855. centerc1 = (minc1 + maxc1) >> 1;
  856. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  857. centerc2 = (minc2 + maxc2) >> 1;
  858. /* For each color in colormap, find:
  859. * 1. its minimum squared-distance to any point in the update box
  860. * (zero if color is within update box);
  861. * 2. its maximum squared-distance to any point in the update box.
  862. * Both of these can be found by considering only the corners of the box.
  863. * We save the minimum distance for each color in mindist[];
  864. * only the smallest maximum distance is of interest.
  865. */
  866. minmaxdist = 0x7FFFFFFFL;
  867. for (i = 0; i < numcolors; i++)
  868. {
  869. /* We compute the squared-c0-distance term, then add in the other two. */
  870. #ifdef ORIGINAL_LIB_JPEG
  871. x = GETJSAMPLE (cinfo->colormap[0][i]);
  872. #else
  873. x = nim->red[i];
  874. #endif
  875. if (x < minc0)
  876. {
  877. tdist = (x - minc0) * C0_SCALE;
  878. min_dist = tdist * tdist;
  879. tdist = (x - maxc0) * C0_SCALE;
  880. max_dist = tdist * tdist;
  881. }
  882. else if (x > maxc0)
  883. {
  884. tdist = (x - maxc0) * C0_SCALE;
  885. min_dist = tdist * tdist;
  886. tdist = (x - minc0) * C0_SCALE;
  887. max_dist = tdist * tdist;
  888. }
  889. else
  890. {
  891. /* within cell range so no contribution to min_dist */
  892. min_dist = 0;
  893. if (x <= centerc0)
  894. {
  895. tdist = (x - maxc0) * C0_SCALE;
  896. max_dist = tdist * tdist;
  897. }
  898. else
  899. {
  900. tdist = (x - minc0) * C0_SCALE;
  901. max_dist = tdist * tdist;
  902. }
  903. }
  904. #ifdef ORIGINAL_LIB_JPEG
  905. x = GETJSAMPLE (cinfo->colormap[1][i]);
  906. #else
  907. x = nim->green[i];
  908. #endif
  909. if (x < minc1)
  910. {
  911. tdist = (x - minc1) * C1_SCALE;
  912. min_dist += tdist * tdist;
  913. tdist = (x - maxc1) * C1_SCALE;
  914. max_dist += tdist * tdist;
  915. }
  916. else if (x > maxc1)
  917. {
  918. tdist = (x - maxc1) * C1_SCALE;
  919. min_dist += tdist * tdist;
  920. tdist = (x - minc1) * C1_SCALE;
  921. max_dist += tdist * tdist;
  922. }
  923. else
  924. {
  925. /* within cell range so no contribution to min_dist */
  926. if (x <= centerc1)
  927. {
  928. tdist = (x - maxc1) * C1_SCALE;
  929. max_dist += tdist * tdist;
  930. }
  931. else
  932. {
  933. tdist = (x - minc1) * C1_SCALE;
  934. max_dist += tdist * tdist;
  935. }
  936. }
  937. #ifdef ORIGINAL_LIB_JPEG
  938. x = GETJSAMPLE (cinfo->colormap[2][i]);
  939. #else
  940. x = nim->blue[i];
  941. #endif
  942. if (x < minc2)
  943. {
  944. tdist = (x - minc2) * C2_SCALE;
  945. min_dist += tdist * tdist;
  946. tdist = (x - maxc2) * C2_SCALE;
  947. max_dist += tdist * tdist;
  948. }
  949. else if (x > maxc2)
  950. {
  951. tdist = (x - maxc2) * C2_SCALE;
  952. min_dist += tdist * tdist;
  953. tdist = (x - minc2) * C2_SCALE;
  954. max_dist += tdist * tdist;
  955. }
  956. else
  957. {
  958. /* within cell range so no contribution to min_dist */
  959. if (x <= centerc2)
  960. {
  961. tdist = (x - maxc2) * C2_SCALE;
  962. max_dist += tdist * tdist;
  963. }
  964. else
  965. {
  966. tdist = (x - minc2) * C2_SCALE;
  967. max_dist += tdist * tdist;
  968. }
  969. }
  970. mindist[i] = min_dist; /* save away the results */
  971. if (max_dist < minmaxdist)
  972. minmaxdist = max_dist;
  973. }
  974. /* Now we know that no cell in the update box is more than minmaxdist
  975. * away from some colormap entry. Therefore, only colors that are
  976. * within minmaxdist of some part of the box need be considered.
  977. */
  978. ncolors = 0;
  979. for (i = 0; i < numcolors; i++)
  980. {
  981. if (mindist[i] <= minmaxdist)
  982. colorlist[ncolors++] = (JSAMPLE) i;
  983. }
  984. return ncolors;
  985. }
  986. LOCAL (void) find_best_colors (
  987. #ifdef ORIGINAL_LIB_JPEG
  988. j_decompress_ptr cinfo,
  989. #else
  990. gdImagePtr oim, gdImagePtr nim, my_cquantize_ptr cquantize,
  991. #endif
  992. int minc0, int minc1, int minc2,
  993. int numcolors, JSAMPLE colorlist[],
  994. JSAMPLE bestcolor[])
  995. /* Find the closest colormap entry for each cell in the update box,
  996. * given the list of candidate colors prepared by find_nearby_colors.
  997. * Return the indexes of the closest entries in the bestcolor[] array.
  998. * This routine uses Thomas' incremental distance calculation method to
  999. * find the distance from a colormap entry to successive cells in the box.
  1000. */
  1001. {
  1002. int ic0, ic1, ic2;
  1003. int i, icolor;
  1004. register INT32 *bptr; /* pointer into bestdist[] array */
  1005. JSAMPLE *cptr; /* pointer into bestcolor[] array */
  1006. INT32 dist0, dist1; /* initial distance values */
  1007. register INT32 dist2; /* current distance in inner loop */
  1008. INT32 xx0, xx1; /* distance increments */
  1009. register INT32 xx2;
  1010. INT32 inc0, inc1, inc2; /* initial values for increments */
  1011. /* This array holds the distance to the nearest-so-far color for each cell */
  1012. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  1013. /* Initialize best-distance for each cell of the update box */
  1014. bptr = bestdist;
  1015. for (i = BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS - 1; i >= 0; i--)
  1016. *bptr++ = 0x7FFFFFFFL;
  1017. /* For each color selected by find_nearby_colors,
  1018. * compute its distance to the center of each cell in the box.
  1019. * If that's less than best-so-far, update best distance and color number.
  1020. */
  1021. /* Nominal steps between cell centers ("x" in Thomas article) */
  1022. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  1023. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  1024. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  1025. for (i = 0; i < numcolors; i++)
  1026. {
  1027. int r, g, b;
  1028. #ifdef ORIGINAL_LIB_JPEG
  1029. icolor = GETJSAMPLE (colorlist[i]);
  1030. r = GETJSAMPLE (cinfo->colormap[0][icolor]);
  1031. g = GETJSAMPLE (cinfo->colormap[1][icolor]);
  1032. b = GETJSAMPLE (cinfo->colormap[2][icolor]);
  1033. #else
  1034. icolor = colorlist[i];
  1035. r = nim->red[icolor];
  1036. g = nim->green[icolor];
  1037. b = nim->blue[icolor];
  1038. #endif
  1039. /* Compute (square of) distance from minc0/c1/c2 to this color */
  1040. inc0 = (minc0 - r) * C0_SCALE;
  1041. dist0 = inc0 * inc0;
  1042. inc1 = (minc1 - g) * C1_SCALE;
  1043. dist0 += inc1 * inc1;
  1044. inc2 = (minc2 - b) * C2_SCALE;
  1045. dist0 += inc2 * inc2;
  1046. /* Form the initial difference increments */
  1047. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  1048. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  1049. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  1050. /* Now loop over all cells in box, updating distance per Thomas method */
  1051. bptr = bestdist;
  1052. cptr = bestcolor;
  1053. xx0 = inc0;
  1054. for (ic0 = BOX_C0_ELEMS - 1; ic0 >= 0; ic0--)
  1055. {
  1056. dist1 = dist0;
  1057. xx1 = inc1;
  1058. for (ic1 = BOX_C1_ELEMS - 1; ic1 >= 0; ic1--)
  1059. {
  1060. dist2 = dist1;
  1061. xx2 = inc2;
  1062. for (ic2 = BOX_C2_ELEMS - 1; ic2 >= 0; ic2--)
  1063. {
  1064. if (dist2 < *bptr)
  1065. {
  1066. *bptr = dist2;
  1067. *cptr = (JSAMPLE) icolor;
  1068. }
  1069. dist2 += xx2;
  1070. xx2 += 2 * STEP_C2 * STEP_C2;
  1071. bptr++;
  1072. cptr++;
  1073. }
  1074. dist1 += xx1;
  1075. xx1 += 2 * STEP_C1 * STEP_C1;
  1076. }
  1077. dist0 += xx0;
  1078. xx0 += 2 * STEP_C0 * STEP_C0;
  1079. }
  1080. }
  1081. }
  1082. LOCAL (void)
  1083. fill_inverse_cmap (
  1084. #ifdef ORIGINAL_LIB_JPEG
  1085. j_decompress_ptr cinfo,
  1086. #else
  1087. gdImagePtr oim, gdImagePtr nim, my_cquantize_ptr cquantize,
  1088. #endif
  1089. int c0, int c1, int c2)
  1090. /* Fill the inverse-colormap entries in the update box that contains */
  1091. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  1092. /* we can fill as many others as we wish.) */
  1093. {
  1094. #ifdef ORIGINAL_LIB_JPEG
  1095. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  1096. #endif
  1097. hist3d histogram = cquantize->histogram;
  1098. int minc0, minc1, minc2; /* lower left corner of update box */
  1099. int ic0, ic1, ic2;
  1100. register JSAMPLE *cptr; /* pointer into bestcolor[] array */
  1101. register histptr cachep; /* pointer into main cache array */
  1102. /* This array lists the candidate colormap indexes. */
  1103. JSAMPLE colorlist[MAXNUMCOLORS];
  1104. int numcolors; /* number of candidate colors */
  1105. /* This array holds the actually closest colormap index for each cell. */
  1106. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  1107. /* Convert cell coordinates to update box ID */
  1108. c0 >>= BOX_C0_LOG;
  1109. c1 >>= BOX_C1_LOG;
  1110. c2 >>= BOX_C2_LOG;
  1111. /* Compute true coordinates of update box's origin corner.
  1112. * Actually we compute the coordinates of the center of the corner
  1113. * histogram cell, which are the lower bounds of the volume we care about.
  1114. */
  1115. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  1116. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  1117. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  1118. /* Determine which colormap entries are close enough to be candidates
  1119. * for the nearest entry to some cell in the update box.
  1120. */
  1121. #ifdef ORIGINAL_LIB_JPEG
  1122. numcolors = find_nearby_colors (cinfo, minc0, minc1, minc2, colorlist);
  1123. /* Determine the actually nearest colors. */
  1124. find_best_colors (cinfo, minc0, minc1, minc2, numcolors, colorlist,
  1125. bestcolor);
  1126. #else
  1127. numcolors =
  1128. find_nearby_colors (oim, nim, cquantize, minc0, minc1, minc2, colorlist);
  1129. find_best_colors (oim, nim, cquantize, minc0, minc1, minc2, numcolors,
  1130. colorlist, bestcolor);
  1131. #endif
  1132. /* Save the best color numbers (plus 1) in the main cache array */
  1133. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  1134. c1 <<= BOX_C1_LOG;
  1135. c2 <<= BOX_C2_LOG;
  1136. cptr = bestcolor;
  1137. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++)
  1138. {
  1139. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++)
  1140. {
  1141. cachep = &histogram[c0 + ic0][c1 + ic1][c2];
  1142. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++)
  1143. {
  1144. #ifdef ORIGINAL_LIB_JPEG
  1145. *cachep++ = (histcell) (GETJSAMPLE (*cptr++) + 1);
  1146. #else
  1147. *cachep++ = (histcell) ((*cptr++) + 1);
  1148. #endif
  1149. }
  1150. }
  1151. }
  1152. }
  1153. /*
  1154. * Map some rows of pixels to the output colormapped representation.
  1155. */
  1156. METHODDEF (void)
  1157. #ifndef ORIGINAL_LIB_JPEG
  1158. pass2_no_dither (gdImagePtr oim, gdImagePtr nim, my_cquantize_ptr cquantize)
  1159. {
  1160. register int *inptr;
  1161. register unsigned char *outptr;
  1162. int width = oim->sx;
  1163. int num_rows = oim->sy;
  1164. #else
  1165. pass2_no_dither (j_decompress_ptr cinfo,
  1166. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  1167. /* This version performs no dithering */
  1168. {
  1169. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  1170. register JSAMPROW inptr, outptr;
  1171. JDIMENSION width = cinfo->output_width;
  1172. #endif
  1173. hist3d histogram = cquantize->histogram;
  1174. register int c0, c1, c2;
  1175. int row;
  1176. JDIMENSION col;
  1177. register histptr cachep;
  1178. for (row = 0; row < num_rows; row++)
  1179. {
  1180. inptr = input_buf[row];
  1181. outptr = output_buf[row];
  1182. for (col = width; col > 0; col--)
  1183. {
  1184. /* get pixel value and index into the cache */
  1185. int r, g, b;
  1186. #ifdef ORIGINAL_LIB_JPEG
  1187. r = GETJSAMPLE (*inptr++);
  1188. g = GETJSAMPLE (*inptr++);
  1189. b = GETJSAMPLE (*inptr++);
  1190. #else
  1191. r = gdTrueColorGetRed (*inptr);
  1192. g = gdTrueColorGetGreen (*inptr);
  1193. /*
  1194. 2.0.24: inptr must not be incremented until after
  1195. transparency check, if any. Thanks to "Super Pikeman."
  1196. */
  1197. b = gdTrueColorGetBlue (*inptr);
  1198. /* If the pixel is transparent, we assign it the palette index that
  1199. * will later be added at the end of the palette as the transparent
  1200. * index. */
  1201. if ((oim->transparent >= 0) && (oim->transparent == *inptr))
  1202. {
  1203. *outptr++ = nim->colorsTotal;
  1204. inptr++;
  1205. continue;
  1206. }
  1207. inptr++;
  1208. #endif
  1209. c0 = r >> C0_SHIFT;
  1210. c1 = g >> C1_SHIFT;
  1211. c2 = b >> C2_SHIFT;
  1212. cachep = &histogram[c0][c1][c2];
  1213. /* If we have not seen this color before, find nearest colormap entry */
  1214. /* and update the cache */
  1215. if (*cachep == 0)
  1216. #ifdef ORIGINAL_LIB_JPEG
  1217. fill_inverse_cmap (cinfo, c0, c1, c2);
  1218. #else
  1219. fill_inverse_cmap (oim, nim, cquantize, c0, c1, c2);
  1220. #endif
  1221. /* Now emit the colormap index for this cell */
  1222. #ifdef ORIGINAL_LIB_JPEG
  1223. *outptr++ = (JSAMPLE) (*cachep - 1);
  1224. #else
  1225. *outptr++ = (*cachep - 1);
  1226. #endif
  1227. }
  1228. }
  1229. }
  1230. METHODDEF (void)
  1231. #ifndef ORIGINAL_LIB_JPEG
  1232. pass2_fs_dither (gdImagePtr oim, gdImagePtr nim, my_cquantize_ptr cquantize)
  1233. {
  1234. #else
  1235. pass2_fs_dither (j_decompress_ptr cinfo,
  1236. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  1237. /* This version performs Floyd-Steinberg dithering */
  1238. {
  1239. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  1240. JSAMPROW inptr; /* => current input pixel */
  1241. #endif
  1242. hist3d histogram = cquantize->histogram;
  1243. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  1244. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  1245. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  1246. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  1247. histptr cachep;
  1248. int dir; /* +1 or -1 depending on direction */
  1249. int dir3; /* 3*dir, for advancing inptr & errorptr */
  1250. int row;
  1251. JDIMENSION col;
  1252. #ifdef ORIGINAL_LIB_JPEG
  1253. JSAMPROW outptr; /* => current output pixel */
  1254. JDIMENSION width = cinfo->output_width;
  1255. JSAMPLE *range_limit = cinfo->sample_range_limit;
  1256. JSAMPROW colormap0 = cinfo->colormap[0];
  1257. JSAMPROW colormap1 = cinfo->colormap[1];
  1258. JSAMPROW colormap2 = cinfo->colormap[2];
  1259. #else
  1260. int *inptr; /* => current input pixel */
  1261. unsigned char *outptr; /* => current output pixel */
  1262. int width = oim->sx;
  1263. int num_rows = oim->sy;
  1264. int *colormap0 = nim->red;
  1265. int *colormap1 = nim->green;
  1266. int *colormap2 = nim->blue;
  1267. #endif
  1268. int *error_limit = cquantize->error_limiter;
  1269. SHIFT_TEMPS for (row = 0; row < num_rows; row++)
  1270. {
  1271. inptr = input_buf[row];
  1272. outptr = output_buf[row];
  1273. if (cquantize->on_odd_row)
  1274. {
  1275. /* work right to left in this row */
  1276. inptr += (width - 1) * 3; /* so point to rightmost pixel */
  1277. outptr += width - 1;
  1278. dir = -1;
  1279. dir3 = -3;
  1280. errorptr = cquantize->fserrors + (width + 1) * 3; /* => entry after last column */
  1281. #ifdef ORIGINAL_LIB_JPEG_REVERSE_ODD_ROWS
  1282. cquantize->on_odd_row = FALSE; /* flip for next time */
  1283. #endif
  1284. }
  1285. else
  1286. {
  1287. /* work left to right in this row */
  1288. dir = 1;
  1289. dir3 = 3;
  1290. errorptr = cquantize->fserrors; /* => entry before first real column */
  1291. #ifdef ORIGINAL_LIB_JPEG_REVERSE_ODD_ROWS
  1292. cquantize->on_odd_row = TRUE; /* flip for next time */
  1293. #endif
  1294. }
  1295. /* Preset error values: no error propagated to first pixel from left */
  1296. cur0 = cur1 = cur2 = 0;
  1297. /* and no error propagated to row below yet */
  1298. belowerr0 = belowerr1 = belowerr2 = 0;
  1299. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  1300. for (col = width; col > 0; col--)
  1301. {
  1302. /* If this pixel is transparent, we want to assign it to the special
  1303. * transparency color index past the end of the palette rather than
  1304. * go through matching / dithering. */
  1305. if ((oim->transparent >= 0) && (*inptr == oim->transparent))
  1306. {
  1307. *outptr = nim->colorsTotal;
  1308. errorptr[0] = 0;
  1309. errorptr[1] = 0;
  1310. errorptr[2] = 0;
  1311. errorptr[3] = 0;
  1312. inptr += dir;
  1313. outptr += dir;
  1314. errorptr += dir3;
  1315. continue;
  1316. }
  1317. /* curN holds the error propagated from the previous pixel on the
  1318. * current line. Add the error propagated from the previous line
  1319. * to form the complete error correction term for this pixel, and
  1320. * round the error term (which is expressed * 16) to an integer.
  1321. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  1322. * for either sign of the error value.
  1323. * Note: errorptr points to *previous* column's array entry.
  1324. */
  1325. cur0 = RIGHT_SHIFT (cur0 + errorptr[dir3 + 0] + 8, 4);
  1326. cur1 = RIGHT_SHIFT (cur1 + errorptr[dir3 + 1] + 8, 4);
  1327. cur2 = RIGHT_SHIFT (cur2 + errorptr[dir3 + 2] + 8, 4);
  1328. /* Limit the error using transfer function set by init_error_limit.
  1329. * See comments with init_error_limit for rationale.
  1330. */
  1331. cur0 = error_limit[cur0];
  1332. cur1 = error_limit[cur1];
  1333. cur2 = error_limit[cur2];
  1334. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  1335. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  1336. * this sets the required size of the range_limit array.
  1337. */
  1338. #ifdef ORIGINAL_LIB_JPEG
  1339. cur0 += GETJSAMPLE (inptr[0]);
  1340. cur1 += GETJSAMPLE (inptr[1]);
  1341. cur2 += GETJSAMPLE (inptr[2]);
  1342. cur0 = GETJSAMPLE (range_limit[cur0]);
  1343. cur1 = GETJSAMPLE (range_limit[cur1]);
  1344. cur2 = GETJSAMPLE (range_limit[cur2]);
  1345. #else
  1346. cur0 += gdTrueColorGetRed (*inptr);
  1347. cur1 += gdTrueColorGetGreen (*inptr);
  1348. cur2 += gdTrueColorGetBlue (*inptr);
  1349. range_limit (cur0);
  1350. range_limit (cur1);
  1351. range_limit (cur2);
  1352. #endif
  1353. /* Index into the cache with adjusted pixel value */
  1354. cachep =
  1355. &histogram[cur0 >> C0_SHIFT][cur1 >> C1_SHIFT][cur2 >> C2_SHIFT];
  1356. /* If we have not seen this color before, find nearest colormap */
  1357. /* entry and update the cache */
  1358. if (*cachep == 0)
  1359. #ifdef ORIGINAL_LIB_JPEG
  1360. fill_inverse_cmap (cinfo, cur0 >> C0_SHIFT, cur1 >> C1_SHIFT,
  1361. cur2 >> C2_SHIFT);
  1362. #else
  1363. fill_inverse_cmap (oim, nim, cquantize, cur0 >> C0_SHIFT,
  1364. cur1 >> C1_SHIFT, cur2 >> C2_SHIFT);
  1365. #endif
  1366. /* Now emit the colormap index for this cell */
  1367. {
  1368. register int pixcode = *cachep - 1;
  1369. *outptr = (JSAMPLE) pixcode;
  1370. /* Compute representation error for this pixel */
  1371. #define GETJSAMPLE
  1372. cur0 -= GETJSAMPLE (colormap0[pixcode]);
  1373. cur1 -= GETJSAMPLE (colormap1[pixcode]);
  1374. cur2 -= GETJSAMPLE (colormap2[pixcode]);
  1375. #undef GETJSAMPLE
  1376. }
  1377. /* Compute error fractions to be propagated to adjacent pixels.
  1378. * Add these into the running sums, and simultaneously shift the
  1379. * next-line error sums left by 1 column.
  1380. */
  1381. {
  1382. register LOCFSERROR bnexterr, delta;
  1383. bnexterr = cur0; /* Process component 0 */
  1384. delta = cur0 * 2;
  1385. cur0 += delta; /* form error * 3 */
  1386. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  1387. cur0 += delta; /* form error * 5 */
  1388. bpreverr0 = belowerr0 + cur0;
  1389. belowerr0 = bnexterr;
  1390. cur0 += delta; /* form error * 7 */
  1391. bnexterr = cur1; /* Process component 1 */
  1392. delta = cur1 * 2;
  1393. cur1 += delta; /* form error * 3 */
  1394. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  1395. cur1 += delta; /* form error * 5 */
  1396. bpreverr1 = belowerr1 + cur1;
  1397. belowerr1 = bnexterr;
  1398. cur1 += delta; /* form error * 7 */
  1399. bnexterr = cur2; /* Process component 2 */
  1400. delta = cur2 * 2;
  1401. cur2 += delta; /* form error * 3 */
  1402. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  1403. cur2 += delta; /* form error * 5 */
  1404. bpreverr2 = belowerr2 + cur2;
  1405. belowerr2 = bnexterr;
  1406. cur2 += delta; /* form error * 7 */
  1407. }
  1408. /* At this point curN contains the 7/16 error value to be propagated
  1409. * to the next pixel on the current line, and all the errors for the
  1410. * next line have been shifted over. We are therefore ready to move on.
  1411. */
  1412. #ifdef ORIGINAL_LIB_JPEG
  1413. inptr += dir3; /* Advance pixel pointers to next column */
  1414. #else
  1415. inptr += dir; /* Advance pixel pointers to next column */
  1416. #endif
  1417. outptr += dir;
  1418. errorptr += dir3; /* advance errorptr to current column */
  1419. }
  1420. /* Post-loop cleanup: we must unload the final error values into the
  1421. * final fserrors[] entry. Note we need not unload belowerrN because
  1422. * it is for the dummy column before or after the actual array.
  1423. */
  1424. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  1425. errorptr[1] = (FSERROR) bpreverr1;
  1426. errorptr[2] = (FSERROR) bpreverr2;
  1427. }
  1428. }
  1429. /*
  1430. * Initialize the error-limiting transfer function (lookup table).
  1431. * The raw F-S error computation can potentially compute error values of up to
  1432. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  1433. * much less, otherwise obviously wrong pixels will be created. (Typical
  1434. * effects include weird fringes at color-area boundaries, isolated bright
  1435. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  1436. * is to ensure that the "corners" of the color cube are allocated as output
  1437. * colors; then repeated errors in the same direction cannot cause cascading
  1438. * error buildup. However, that only prevents the error from getting
  1439. * completely out of hand; Aaron Giles reports that error limiting improves
  1440. * the results even with corner colors allocated.
  1441. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  1442. * well, but the smoother transfer function used below is even better. Thanks
  1443. * to Aaron Giles for this idea.
  1444. */
  1445. LOCAL (void)
  1446. #ifdef ORIGINAL_LIB_JPEG
  1447. init_error_limit (j_decompress_ptr cinfo)
  1448. #else
  1449. init_error_limit (gdImagePtr oim, gdImagePtr nim, my_cquantize_ptr cquantize)
  1450. #endif
  1451. /* Allocate and fill in the error_limiter table */
  1452. {
  1453. int *table;
  1454. int in, out;
  1455. #ifdef ORIGINAL_LIB_JPEG
  1456. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  1457. table = (int *) (*cinfo->mem->alloc_small)
  1458. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE * 2 + 1) * SIZEOF (int));
  1459. #else
  1460. cquantize->error_limiter_storage =
  1461. (int *) safe_emalloc ((MAXJSAMPLE * 2 + 1), sizeof (int), 0);
  1462. if (!cquantize->error_limiter_storage)
  1463. {
  1464. return;
  1465. }
  1466. table = cquantize->error_limiter_storage;
  1467. #endif
  1468. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  1469. cquantize->error_limiter = table;
  1470. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  1471. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  1472. out = 0;
  1473. for (in = 0; in < STEPSIZE; in++, out++)
  1474. {
  1475. table[in] = out;
  1476. table[-in] = -out;
  1477. }
  1478. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  1479. for (; in < STEPSIZE * 3; in++, out += (in & 1) ? 0 : 1)
  1480. {
  1481. table[in] = out;
  1482. table[-in] = -out;
  1483. }
  1484. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  1485. for (; in <= MAXJSAMPLE; in++)
  1486. {
  1487. table[in] = out;
  1488. table[-in] = -out;
  1489. }
  1490. #undef STEPSIZE
  1491. }
  1492. /*
  1493. * Finish up at the end of each pass.
  1494. */
  1495. #ifdef ORIGINAL_LIB_JPEG
  1496. METHODDEF (void)
  1497. finish_pass1 (j_decompress_ptr cinfo)
  1498. {
  1499. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  1500. /* Select the representative colors and fill in cinfo->colormap */
  1501. cinfo->colormap = cquantize->sv_colormap;
  1502. select_colors (cinfo, cquantize->desired);
  1503. /* Force next pass to zero the color index table */
  1504. cquantize->needs_zeroed = TRUE;
  1505. }
  1506. METHODDEF (void)
  1507. finish_pass2 (j_decompress_ptr cinfo)
  1508. {
  1509. /* no work */
  1510. }
  1511. /*
  1512. * Initialize for each processing pass.
  1513. */
  1514. METHODDEF (void)
  1515. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  1516. {
  1517. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  1518. hist3d histogram = cquantize->histogram;
  1519. int i;
  1520. /* Only F-S dithering or no dithering is supported. */
  1521. /* If user asks for ordered dither, give him F-S. */
  1522. if (cinfo->dither_mode != JDITHER_NONE)
  1523. cinfo->dither_mode = JDITHER_FS;
  1524. if (is_pre_scan)
  1525. {
  1526. /* Set up method pointers */
  1527. cquantize->pub.color_quantize = prescan_quantize;
  1528. cquantize->pub.finish_pass = finish_pass1;
  1529. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  1530. }
  1531. else
  1532. {
  1533. /* Set up method pointers */
  1534. if (cinfo->dither_mode == JDITHER_FS)
  1535. cquantize->pub.color_quantize = pass2_fs_dither;
  1536. else
  1537. cquantize->pub.color_quantize = pass2_no_dither;
  1538. cquantize->pub.finish_pass = finish_pass2;
  1539. /* Make sure color count is acceptable */
  1540. i = cinfo->actual_number_of_colors;
  1541. if (i < 1)
  1542. ERREXIT1 (cinfo, JERR_QUANT_FEW_COLORS, 1);
  1543. if (i > MAXNUMCOLORS)
  1544. ERREXIT1 (cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  1545. if (cinfo->dither_mode == JDITHER_FS)
  1546. {
  1547. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  1548. (3 * SIZEOF (FSERROR)));
  1549. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  1550. if (cquantize->fserrors == NULL)
  1551. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  1552. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  1553. /* Initialize the propagated errors to zero. */
  1554. jzero_far ((void FAR *) cquantize->fserrors, arraysize);
  1555. /* Make the error-limit table if we didn't already. */
  1556. if (cquantize->error_limiter == NULL)
  1557. init_error_limit (cinfo);
  1558. cquantize->on_odd_row = FALSE;
  1559. }
  1560. }
  1561. /* Zero the histogram or inverse color map, if necessary */
  1562. if (cquantize->needs_zeroed)
  1563. {
  1564. for (i = 0; i < HIST_C0_ELEMS; i++)
  1565. {
  1566. jzero_far ((void FAR *) histogram[i],
  1567. HIST_C1_ELEMS * HIST_C2_ELEMS * SIZEOF (histcell));
  1568. }
  1569. cquantize->needs_zeroed = FALSE;
  1570. }
  1571. }
  1572. /*
  1573. * Switch to a new external colormap between output passes.
  1574. */
  1575. METHODDEF (void)
  1576. new_color_map_2_quant (j_decompress_ptr cinfo)
  1577. {
  1578. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  1579. /* Reset the inverse color map */
  1580. cquantize->needs_zeroed = TRUE;
  1581. }
  1582. #else
  1583. static void
  1584. zeroHistogram (hist3d histogram)
  1585. {
  1586. int i;
  1587. /* Zero the histogram or inverse color map */
  1588. for (i = 0; i < HIST_C0_ELEMS; i++)
  1589. {
  1590. memset (histogram[i],
  1591. 0, HIST_C1_ELEMS * HIST_C2_ELEMS * sizeof (histcell));
  1592. }
  1593. }
  1594. #endif
  1595. static void gdImageTrueColorToPaletteBody (gdImagePtr oim, int dither, int colorsWanted, gdImagePtr *cimP);
  1596. gdImagePtr gdImageCreatePaletteFromTrueColor (gdImagePtr im, int dither, int colorsWanted)
  1597. {
  1598. gdImagePtr nim;
  1599. gdImageTrueColorToPaletteBody(im, dither, colorsWanted, &nim);
  1600. return nim;
  1601. }
  1602. void gdImageTrueColorToPalette (gdImagePtr im, int dither, int colorsWanted)
  1603. {
  1604. gdImageTrueColorToPaletteBody(im, dither, colorsWanted, 0);
  1605. }
  1606. /*
  1607. * Module initialization routine for 2-pass color quantization.
  1608. */
  1609. #ifdef ORIGINAL_LIB_JPEG
  1610. GLOBAL (void)
  1611. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  1612. #else
  1613. static void gdImageTrueColorToPaletteBody (gdImagePtr oim, int dither, int colorsWanted, gdImagePtr *cimP)
  1614. #endif
  1615. {
  1616. my_cquantize_ptr cquantize = NULL;
  1617. int i;
  1618. #ifndef ORIGINAL_LIB_JPEG
  1619. /* Allocate the JPEG palette-storage */
  1620. size_t arraysize;
  1621. int maxColors = gdMaxColors;
  1622. gdImagePtr nim;
  1623. if (cimP) {
  1624. nim = gdImageCreate(oim->sx, oim->sy);
  1625. *cimP = nim;
  1626. if (!nim) {
  1627. return;
  1628. }
  1629. } else {
  1630. nim = oim;
  1631. }
  1632. if (!oim->trueColor)
  1633. {
  1634. /* (Almost) nothing to do! */
  1635. if (cimP) {
  1636. gdImageCopy(nim, oim, 0, 0, 0, 0, oim->sx, oim->sy);
  1637. *cimP = nim;
  1638. }
  1639. return;
  1640. }
  1641. /* If we have a transparent color (the alphaless mode of transparency), we
  1642. * must reserve a palette entry for it at the end of the palette. */
  1643. if (oim->transparent >= 0)
  1644. {
  1645. maxColors--;
  1646. }
  1647. if (colorsWanted > maxColors)
  1648. {
  1649. colorsWanted = maxColors;
  1650. }
  1651. if (!cimP) {
  1652. nim->pixels = gdCalloc (sizeof (unsigned char *), oim->sy);
  1653. if (!nim->pixels)
  1654. {
  1655. /* No can do */
  1656. goto outOfMemory;
  1657. }
  1658. for (i = 0; (i < nim->sy); i++)
  1659. {
  1660. nim->pixels[i] = gdCalloc (sizeof (unsigned char *), oim->sx);
  1661. if (!nim->pixels[i])
  1662. {
  1663. goto outOfMemory;
  1664. }
  1665. }
  1666. }
  1667. #endif
  1668. #ifdef ORIGINAL_LIB_JPEG
  1669. cquantize = (my_cquantize_ptr)
  1670. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  1671. SIZEOF (my_cquantizer));
  1672. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  1673. cquantize->pub.start_pass = start_pass_2_quant;
  1674. cquantize->pub.new_color_map = new_color_map_2_quant;
  1675. /* Make sure jdmaster didn't give me a case I can't handle */
  1676. if (cinfo->out_color_components != 3)
  1677. ERREXIT (cinfo, JERR_NOTIMPL);
  1678. #else
  1679. cquantize = (my_cquantize_ptr) gdCalloc (sizeof (my_cquantizer), 1);
  1680. if (!cquantize)
  1681. {
  1682. /* No can do */
  1683. goto outOfMemory;
  1684. }
  1685. #endif
  1686. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  1687. cquantize->error_limiter = NULL;
  1688. /* Allocate the histogram/inverse colormap storage */
  1689. #ifdef ORIGINAL_LIB_JPEG
  1690. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  1691. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF (hist2d));
  1692. for (i = 0; i < HIST_C0_ELEMS; i++)
  1693. {
  1694. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  1695. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  1696. HIST_C1_ELEMS * HIST_C2_ELEMS * SIZEOF (histcell));
  1697. }
  1698. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  1699. #else
  1700. cquantize->histogram = (hist3d) safe_emalloc (HIST_C0_ELEMS, sizeof (hist2d), 0);
  1701. for (i = 0; i < HIST_C0_ELEMS; i++)
  1702. {
  1703. cquantize->histogram[i] =
  1704. (hist2d) safe_emalloc (HIST_C1_ELEMS * HIST_C2_ELEMS, sizeof (histcell), 0);
  1705. if (!cquantize->histogram[i])
  1706. {
  1707. goto outOfMemory;
  1708. }
  1709. }
  1710. #endif
  1711. #ifdef ORIGINAL_LIB_JPEG
  1712. /* Allocate storage for the completed colormap, if required.
  1713. * We do this now since it is FAR storage and may affect
  1714. * the memory manager's space calculations.
  1715. */
  1716. if (cinfo->enable_2pass_quant)
  1717. {
  1718. /* Make sure color count is acceptable */
  1719. int desired = cinfo->desired_number_of_colors;
  1720. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  1721. if (desired < 8)
  1722. ERREXIT1 (cinfo, JERR_QUANT_FEW_COLORS, 8);
  1723. /* Make sure colormap indexes can be represented by JSAMPLEs */
  1724. if (desired > MAXNUMCOLORS)
  1725. ERREXIT1 (cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  1726. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  1727. ((j_common_ptr) cinfo, JPOOL_IMAGE, (JDIMENSION) desired,
  1728. (JDIMENSION) 3);
  1729. cquantize->desired = desired;
  1730. }
  1731. else
  1732. cquantize->sv_colormap = NULL;
  1733. /* Only F-S dithering or no dithering is supported. */
  1734. /* If user asks for ordered dither, give him F-S. */
  1735. if (cinfo->dither_mode != JDITHER_NONE)
  1736. cinfo->dither_mode = JDITHER_FS;
  1737. /* Allocate Floyd-Steinberg workspace if necessary.
  1738. * This isn't really needed until pass 2, but again it is FAR storage.
  1739. * Although we will cope with a later change in dither_mode,
  1740. * we do not promise to honor max_memory_to_use if dither_mode changes.
  1741. */
  1742. if (cinfo->dither_mode == JDITHER_FS)
  1743. {
  1744. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  1745. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  1746. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF (FSERROR))));
  1747. /* Might as well create the error-limiting table too. */
  1748. init_error_limit (cinfo);
  1749. }
  1750. #else
  1751. cquantize->fserrors = (FSERRPTR) safe_emalloc (3, sizeof (FSERROR), 0);
  1752. init_error_limit (oim, nim, cquantize);
  1753. arraysize = (size_t) ((nim->sx + 2) * (3 * sizeof (FSERROR)));
  1754. /* Allocate Floyd-Steinberg workspace. */
  1755. cquantize->fserrors = gdRealloc(cquantize->fserrors, arraysize);
  1756. memset(cquantize->fserrors, 0, arraysize);
  1757. if (!cquantize->fserrors)
  1758. {
  1759. goto outOfMemory;
  1760. }
  1761. cquantize->on_odd_row = FALSE;
  1762. /* Do the work! */
  1763. zeroHistogram (cquantize->histogram);
  1764. prescan_quantize (oim, nim, cquantize);
  1765. /* TBB 2.0.5: pass colorsWanted, not 256! */
  1766. select_colors (oim, nim, cquantize, colorsWanted);
  1767. zeroHistogram (cquantize->histogram);
  1768. if (dither)
  1769. {
  1770. pass2_fs_dither (oim, nim, cquantize);
  1771. }
  1772. else
  1773. {
  1774. pass2_no_dither (oim, nim, cquantize);
  1775. }
  1776. #if 0 /* 2.0.12; we no longer attempt full alpha in palettes */
  1777. if (cquantize->transparentIsPresent)
  1778. {
  1779. int mt = -1;
  1780. int mtIndex = -1;
  1781. for (i = 0; (i < im->colorsTotal); i++)
  1782. {
  1783. if (im->alpha[i] > mt)
  1784. {
  1785. mtIndex = i;
  1786. mt = im->alpha[i];
  1787. }
  1788. }
  1789. for (i = 0; (i < im->colorsTotal); i++)
  1790. {
  1791. if (im->alpha[i] == mt)
  1792. {
  1793. im->alpha[i] = gdAlphaTransparent;
  1794. }
  1795. }
  1796. }
  1797. if (cquantize->opaqueIsPresent)
  1798. {
  1799. int mo = 128;
  1800. int moIndex = -1;
  1801. for (i = 0; (i < im->colorsTotal); i++)
  1802. {
  1803. if (im->alpha[i] < mo)
  1804. {
  1805. moIndex = i;
  1806. mo = im->alpha[i];
  1807. }
  1808. }
  1809. for (i = 0; (i < im->colorsTotal); i++)
  1810. {
  1811. if (im->alpha[i] == mo)
  1812. {
  1813. im->alpha[i] = gdAlphaOpaque;
  1814. }
  1815. }
  1816. }
  1817. #endif
  1818. /* If we had a 'transparent' color, increment the color count so it's
  1819. * officially in the palette and convert the transparent variable to point to
  1820. * an index rather than a color (Its data already exists and transparent
  1821. * pixels have already been mapped to it by this point, it is done late as to
  1822. * avoid color matching / dithering with it). */
  1823. if (oim->transparent >= 0)
  1824. {
  1825. nim->transparent = nim->colorsTotal;
  1826. nim->colorsTotal++;
  1827. }
  1828. /* Success! Get rid of the truecolor image data. */
  1829. if (!cimP) {
  1830. oim->trueColor = 0;
  1831. /* Junk the truecolor pixels */
  1832. for (i = 0; i < oim->sy; i++)
  1833. {
  1834. gdFree (oim->tpixels[i]);
  1835. }
  1836. gdFree (oim->tpixels);
  1837. oim->tpixels = 0;
  1838. }
  1839. goto success;
  1840. /* Tediously free stuff. */
  1841. outOfMemory:
  1842. if (oim->trueColor)
  1843. {
  1844. if (!cimP) {
  1845. /* On failure only */
  1846. for (i = 0; i < nim->sy; i++)
  1847. {
  1848. if (nim->pixels[i])
  1849. {
  1850. gdFree (nim->pixels[i]);
  1851. }
  1852. }
  1853. if (nim->pixels)
  1854. {
  1855. gdFree (nim->pixels);
  1856. }
  1857. nim->pixels = 0;
  1858. } else {
  1859. gdImageDestroy(nim);
  1860. *cimP = 0;
  1861. }
  1862. }
  1863. success:
  1864. for (i = 0; i < HIST_C0_ELEMS; i++)
  1865. {
  1866. if (cquantize->histogram[i])
  1867. {
  1868. gdFree (cquantize->histogram[i]);
  1869. }
  1870. }
  1871. if (cquantize->histogram)
  1872. {
  1873. gdFree (cquantize->histogram);
  1874. }
  1875. if (cquantize->fserrors)
  1876. {
  1877. gdFree (cquantize->fserrors);
  1878. }
  1879. if (cquantize->error_limiter_storage)
  1880. {
  1881. gdFree (cquantize->error_limiter_storage);
  1882. }
  1883. if (cquantize)
  1884. {
  1885. gdFree (cquantize);
  1886. }
  1887. #endif
  1888. }
  1889. #endif