Quant.c 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859
  1. /*
  2. * The Python Imaging Library
  3. * $Id$
  4. *
  5. * image quantizer
  6. *
  7. * history:
  8. * 1998-09-10 tjs Contributed
  9. * 1998-12-29 fl Added to PIL 1.0b1
  10. * 2004-02-21 fl Fixed bogus free() on quantization error
  11. * 2005-02-07 fl Limit number of colors to 256
  12. *
  13. * Written by Toby J Sargeant <tjs@longford.cs.monash.edu.au>.
  14. *
  15. * Copyright (c) 1998 by Toby J Sargeant
  16. * Copyright (c) 1998-2004 by Secret Labs AB. All rights reserved.
  17. *
  18. * See the README file for information on usage and redistribution.
  19. */
  20. #include "Imaging.h"
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. #include <memory.h>
  24. #include <time.h>
  25. #include "QuantTypes.h"
  26. #include "QuantOctree.h"
  27. #include "QuantPngQuant.h"
  28. #include "QuantHash.h"
  29. #include "QuantHeap.h"
  30. /* MSVC9.0 */
  31. #ifndef UINT32_MAX
  32. #define UINT32_MAX 0xffffffff
  33. #endif
  34. #define NO_OUTPUT
  35. typedef struct {
  36. uint32_t scale;
  37. } PixelHashData;
  38. typedef struct _PixelList {
  39. struct _PixelList *next[3], *prev[3];
  40. Pixel p;
  41. unsigned int flag : 1;
  42. int count;
  43. } PixelList;
  44. typedef struct _BoxNode {
  45. struct _BoxNode *l, *r;
  46. PixelList *head[3], *tail[3];
  47. int axis;
  48. int volume;
  49. uint32_t pixelCount;
  50. } BoxNode;
  51. #define _SQR(x) ((x) * (x))
  52. #define _DISTSQR(p1, p2) \
  53. _SQR((int)((p1)->c.r) - (int)((p2)->c.r)) + \
  54. _SQR((int)((p1)->c.g) - (int)((p2)->c.g)) + \
  55. _SQR((int)((p1)->c.b) - (int)((p2)->c.b))
  56. #define MAX_HASH_ENTRIES 65536
  57. #define PIXEL_HASH(r, g, b) \
  58. (((unsigned int)(r)) * 463 ^ ((unsigned int)(g) << 8) * 10069 ^ \
  59. ((unsigned int)(b) << 16) * 64997)
  60. #define PIXEL_UNSCALE(p, q, s) \
  61. ((q)->c.r = (p)->c.r << (s)), ((q)->c.g = (p)->c.g << (s)), \
  62. ((q)->c.b = (p)->c.b << (s))
  63. #define PIXEL_SCALE(p, q, s) \
  64. ((q)->c.r = (p)->c.r >> (s)), ((q)->c.g = (p)->c.g >> (s)), \
  65. ((q)->c.b = (p)->c.b >> (s))
  66. static uint32_t
  67. unshifted_pixel_hash(const HashTable *h, const Pixel pixel) {
  68. return PIXEL_HASH(pixel.c.r, pixel.c.g, pixel.c.b);
  69. }
  70. static int
  71. unshifted_pixel_cmp(const HashTable *h, const Pixel pixel1, const Pixel pixel2) {
  72. if (pixel1.c.r == pixel2.c.r) {
  73. if (pixel1.c.g == pixel2.c.g) {
  74. if (pixel1.c.b == pixel2.c.b) {
  75. return 0;
  76. } else {
  77. return (int)(pixel1.c.b) - (int)(pixel2.c.b);
  78. }
  79. } else {
  80. return (int)(pixel1.c.g) - (int)(pixel2.c.g);
  81. }
  82. } else {
  83. return (int)(pixel1.c.r) - (int)(pixel2.c.r);
  84. }
  85. }
  86. static uint32_t
  87. pixel_hash(const HashTable *h, const Pixel pixel) {
  88. PixelHashData *d = (PixelHashData *)hashtable_get_user_data(h);
  89. return PIXEL_HASH(
  90. pixel.c.r >> d->scale, pixel.c.g >> d->scale, pixel.c.b >> d->scale);
  91. }
  92. static int
  93. pixel_cmp(const HashTable *h, const Pixel pixel1, const Pixel pixel2) {
  94. PixelHashData *d = (PixelHashData *)hashtable_get_user_data(h);
  95. uint32_t A, B;
  96. A = PIXEL_HASH(
  97. pixel1.c.r >> d->scale, pixel1.c.g >> d->scale, pixel1.c.b >> d->scale);
  98. B = PIXEL_HASH(
  99. pixel2.c.r >> d->scale, pixel2.c.g >> d->scale, pixel2.c.b >> d->scale);
  100. return (A == B) ? 0 : ((A < B) ? -1 : 1);
  101. }
  102. static void
  103. exists_count_func(const HashTable *h, const Pixel key, uint32_t *val) {
  104. *val += 1;
  105. }
  106. static void
  107. new_count_func(const HashTable *h, const Pixel key, uint32_t *val) {
  108. *val = 1;
  109. }
  110. static void
  111. rehash_collide(
  112. const HashTable *h, Pixel *keyp, uint32_t *valp, Pixel newkey, uint32_t newval) {
  113. *valp += newval;
  114. }
  115. /* %% */
  116. static HashTable *
  117. create_pixel_hash(Pixel *pixelData, uint32_t nPixels) {
  118. PixelHashData *d;
  119. HashTable *hash;
  120. uint32_t i;
  121. #ifndef NO_OUTPUT
  122. uint32_t timer, timer2, timer3;
  123. #endif
  124. /* malloc check ok, small constant allocation */
  125. d = malloc(sizeof(PixelHashData));
  126. if (!d) {
  127. return NULL;
  128. }
  129. hash = hashtable_new(pixel_hash, pixel_cmp);
  130. hashtable_set_user_data(hash, d);
  131. d->scale = 0;
  132. #ifndef NO_OUTPUT
  133. timer = timer3 = clock();
  134. #endif
  135. for (i = 0; i < nPixels; i++) {
  136. if (!hashtable_insert_or_update_computed(
  137. hash, pixelData[i], new_count_func, exists_count_func)) {
  138. ;
  139. }
  140. while (hashtable_get_count(hash) > MAX_HASH_ENTRIES) {
  141. d->scale++;
  142. #ifndef NO_OUTPUT
  143. printf("rehashing - new scale: %d\n", (int)d->scale);
  144. timer2 = clock();
  145. #endif
  146. hashtable_rehash_compute(hash, rehash_collide);
  147. #ifndef NO_OUTPUT
  148. timer2 = clock() - timer2;
  149. printf("rehash took %f sec\n", timer2 / (double)CLOCKS_PER_SEC);
  150. timer += timer2;
  151. #endif
  152. }
  153. }
  154. #ifndef NO_OUTPUT
  155. printf("inserts took %f sec\n", (clock() - timer) / (double)CLOCKS_PER_SEC);
  156. #endif
  157. #ifndef NO_OUTPUT
  158. printf("total %f sec\n", (clock() - timer3) / (double)CLOCKS_PER_SEC);
  159. #endif
  160. return hash;
  161. }
  162. static void
  163. destroy_pixel_hash(HashTable *hash) {
  164. PixelHashData *d = (PixelHashData *)hashtable_get_user_data(hash);
  165. if (d) {
  166. free(d);
  167. }
  168. hashtable_free(hash);
  169. }
  170. /* 1. hash quantized pixels. */
  171. /* 2. create R,G,B lists of sorted quantized pixels. */
  172. /* 3. median cut. */
  173. /* 4. build hash table from median cut boxes. */
  174. /* 5. for each pixel, compute entry in hash table, and hence median cut box. */
  175. /* 6. compute median cut box pixel averages. */
  176. /* 7. map each pixel to nearest average. */
  177. static int
  178. compute_box_volume(BoxNode *b) {
  179. unsigned char rl, rh, gl, gh, bl, bh;
  180. if (b->volume >= 0) {
  181. return b->volume;
  182. }
  183. if (!b->head[0]) {
  184. b->volume = 0;
  185. } else {
  186. rh = b->head[0]->p.c.r;
  187. rl = b->tail[0]->p.c.r;
  188. gh = b->head[1]->p.c.g;
  189. gl = b->tail[1]->p.c.g;
  190. bh = b->head[2]->p.c.b;
  191. bl = b->tail[2]->p.c.b;
  192. b->volume = (rh - rl + 1) * (gh - gl + 1) * (bh - bl + 1);
  193. }
  194. return b->volume;
  195. }
  196. static void
  197. hash_to_list(const HashTable *h, const Pixel pixel, const uint32_t count, void *u) {
  198. PixelHashData *d = (PixelHashData *)hashtable_get_user_data(h);
  199. PixelList **pl = (PixelList **)u;
  200. PixelList *p;
  201. int i;
  202. Pixel q;
  203. PIXEL_SCALE(&pixel, &q, d->scale);
  204. /* malloc check ok, small constant allocation */
  205. p = malloc(sizeof(PixelList));
  206. if (!p) {
  207. return;
  208. }
  209. p->flag = 0;
  210. p->p = q;
  211. p->count = count;
  212. for (i = 0; i < 3; i++) {
  213. p->next[i] = pl[i];
  214. p->prev[i] = NULL;
  215. if (pl[i]) {
  216. pl[i]->prev[i] = p;
  217. }
  218. pl[i] = p;
  219. }
  220. }
  221. static PixelList *
  222. mergesort_pixels(PixelList *head, int i) {
  223. PixelList *c, *t, *a, *b, *p;
  224. if (!head || !head->next[i]) {
  225. if (head) {
  226. head->next[i] = NULL;
  227. head->prev[i] = NULL;
  228. }
  229. return head;
  230. }
  231. for (c = t = head; c && t;
  232. c = c->next[i], t = (t->next[i]) ? t->next[i]->next[i] : NULL)
  233. ;
  234. if (c) {
  235. if (c->prev[i]) {
  236. c->prev[i]->next[i] = NULL;
  237. }
  238. c->prev[i] = NULL;
  239. }
  240. a = mergesort_pixels(head, i);
  241. b = mergesort_pixels(c, i);
  242. head = NULL;
  243. p = NULL;
  244. while (a && b) {
  245. if (a->p.a.v[i] > b->p.a.v[i]) {
  246. c = a;
  247. a = a->next[i];
  248. } else {
  249. c = b;
  250. b = b->next[i];
  251. }
  252. c->prev[i] = p;
  253. c->next[i] = NULL;
  254. if (p) {
  255. p->next[i] = c;
  256. }
  257. p = c;
  258. if (!head) {
  259. head = c;
  260. }
  261. }
  262. if (a) {
  263. c->next[i] = a;
  264. a->prev[i] = c;
  265. } else if (b) {
  266. c->next[i] = b;
  267. b->prev[i] = c;
  268. }
  269. return head;
  270. }
  271. #if defined(TEST_MERGESORT) || defined(TEST_SORTED)
  272. static int
  273. test_sorted(PixelList *pl[3]) {
  274. int i, n, l;
  275. PixelList *t;
  276. for (i = 0; i < 3; i++) {
  277. n = 0;
  278. l = 256;
  279. for (t = pl[i]; t; t = t->next[i]) {
  280. if (l < t->p.a.v[i])
  281. return 0;
  282. l = t->p.a.v[i];
  283. }
  284. }
  285. return 1;
  286. }
  287. #endif
  288. static int
  289. box_heap_cmp(const Heap *h, const void *A, const void *B) {
  290. BoxNode *a = (BoxNode *)A;
  291. BoxNode *b = (BoxNode *)B;
  292. return (int)a->pixelCount - (int)b->pixelCount;
  293. }
  294. #define LUMINANCE(p) (77 * (p)->c.r + 150 * (p)->c.g + 29 * (p)->c.b)
  295. static int
  296. splitlists(
  297. PixelList *h[3],
  298. PixelList *t[3],
  299. PixelList *nh[2][3],
  300. PixelList *nt[2][3],
  301. uint32_t nCount[2],
  302. int axis,
  303. uint32_t pixelCount) {
  304. uint32_t left;
  305. PixelList *l, *r, *c, *n;
  306. int i;
  307. int nRight;
  308. #ifndef NO_OUTPUT
  309. int nLeft;
  310. #endif
  311. int splitColourVal;
  312. #ifdef TEST_SPLIT
  313. {
  314. PixelList *_prevTest, *_nextTest;
  315. int _i, _nextCount[3], _prevCount[3];
  316. for (_i = 0; _i < 3; _i++) {
  317. for (_nextCount[_i] = 0, _nextTest = h[_i];
  318. _nextTest && _nextTest->next[_i];
  319. _nextTest = _nextTest->next[_i], _nextCount[_i]++)
  320. ;
  321. for (_prevCount[_i] = 0, _prevTest = t[_i];
  322. _prevTest && _prevTest->prev[_i];
  323. _prevTest = _prevTest->prev[_i], _prevCount[_i]++)
  324. ;
  325. if (_nextTest != t[_i]) {
  326. printf("next-list of axis %d does not end at tail\n", _i);
  327. exit(1);
  328. }
  329. if (_prevTest != h[_i]) {
  330. printf("prev-list of axis %d does not end at head\n", _i);
  331. exit(1);
  332. }
  333. for (; _nextTest && _nextTest->prev[_i]; _nextTest = _nextTest->prev[_i])
  334. ;
  335. for (; _prevTest && _prevTest->next[_i]; _prevTest = _prevTest->next[_i])
  336. ;
  337. if (_nextTest != h[_i]) {
  338. printf("next-list of axis %d does not loop back to head\n", _i);
  339. exit(1);
  340. }
  341. if (_prevTest != t[_i]) {
  342. printf("prev-list of axis %d does not loop back to tail\n", _i);
  343. exit(1);
  344. }
  345. }
  346. for (_i = 1; _i < 3; _i++) {
  347. if (_prevCount[_i] != _prevCount[_i - 1] ||
  348. _nextCount[_i] != _nextCount[_i - 1] ||
  349. _prevCount[_i] != _nextCount[_i]) {
  350. printf(
  351. "{%d %d %d} {%d %d %d}\n",
  352. _prevCount[0],
  353. _prevCount[1],
  354. _prevCount[2],
  355. _nextCount[0],
  356. _nextCount[1],
  357. _nextCount[2]);
  358. exit(1);
  359. }
  360. }
  361. }
  362. #endif
  363. nCount[0] = nCount[1] = 0;
  364. nRight = 0;
  365. #ifndef NO_OUTPUT
  366. nLeft = 0;
  367. #endif
  368. for (left = 0, c = h[axis]; c;) {
  369. left = left + c->count;
  370. nCount[0] += c->count;
  371. c->flag = 0;
  372. #ifndef NO_OUTPUT
  373. nLeft++;
  374. #endif
  375. c = c->next[axis];
  376. if (left * 2 > pixelCount) {
  377. break;
  378. }
  379. }
  380. if (c) {
  381. splitColourVal = c->prev[axis]->p.a.v[axis];
  382. for (; c; c = c->next[axis]) {
  383. if (splitColourVal != c->p.a.v[axis]) {
  384. break;
  385. }
  386. c->flag = 0;
  387. #ifndef NO_OUTPUT
  388. nLeft++;
  389. #endif
  390. nCount[0] += c->count;
  391. }
  392. }
  393. for (; c; c = c->next[axis]) {
  394. c->flag = 1;
  395. nRight++;
  396. nCount[1] += c->count;
  397. }
  398. if (!nRight) {
  399. for (c = t[axis], splitColourVal = t[axis]->p.a.v[axis]; c; c = c->prev[axis]) {
  400. if (splitColourVal != c->p.a.v[axis]) {
  401. break;
  402. }
  403. c->flag = 1;
  404. nRight++;
  405. #ifndef NO_OUTPUT
  406. nLeft--;
  407. #endif
  408. nCount[0] -= c->count;
  409. nCount[1] += c->count;
  410. }
  411. }
  412. #ifndef NO_OUTPUT
  413. if (!nLeft) {
  414. for (c = h[axis]; c; c = c->next[axis]) {
  415. printf("[%d %d %d]\n", c->p.c.r, c->p.c.g, c->p.c.b);
  416. }
  417. printf("warning... trivial split\n");
  418. }
  419. #endif
  420. for (i = 0; i < 3; i++) {
  421. l = r = NULL;
  422. nh[0][i] = nt[0][i] = NULL;
  423. nh[1][i] = nt[1][i] = NULL;
  424. for (c = h[i]; c; c = n) {
  425. n = c->next[i];
  426. if (c->flag) { /* move pixel to right list*/
  427. if (r) {
  428. r->next[i] = c;
  429. } else {
  430. nh[1][i] = c;
  431. }
  432. c->prev[i] = r;
  433. r = c;
  434. } else { /* move pixel to left list */
  435. if (l) {
  436. l->next[i] = c;
  437. } else {
  438. nh[0][i] = c;
  439. }
  440. c->prev[i] = l;
  441. l = c;
  442. }
  443. }
  444. if (l) {
  445. l->next[i] = NULL;
  446. }
  447. if (r) {
  448. r->next[i] = NULL;
  449. }
  450. nt[0][i] = l;
  451. nt[1][i] = r;
  452. }
  453. return 1;
  454. }
  455. static int
  456. split(BoxNode *node) {
  457. unsigned char rl, rh, gl, gh, bl, bh;
  458. int f[3];
  459. int best, axis;
  460. int i;
  461. PixelList *heads[2][3];
  462. PixelList *tails[2][3];
  463. uint32_t newCounts[2];
  464. BoxNode *left, *right;
  465. rh = node->head[0]->p.c.r;
  466. rl = node->tail[0]->p.c.r;
  467. gh = node->head[1]->p.c.g;
  468. gl = node->tail[1]->p.c.g;
  469. bh = node->head[2]->p.c.b;
  470. bl = node->tail[2]->p.c.b;
  471. #ifdef TEST_SPLIT
  472. printf("splitting node [%d %d %d] [%d %d %d] ", rl, gl, bl, rh, gh, bh);
  473. #endif
  474. f[0] = (rh - rl) * 77;
  475. f[1] = (gh - gl) * 150;
  476. f[2] = (bh - bl) * 29;
  477. best = f[0];
  478. axis = 0;
  479. for (i = 1; i < 3; i++) {
  480. if (best < f[i]) {
  481. best = f[i];
  482. axis = i;
  483. }
  484. }
  485. #ifdef TEST_SPLIT
  486. printf("along axis %d\n", axis + 1);
  487. #endif
  488. #ifdef TEST_SPLIT
  489. {
  490. PixelList *_prevTest, *_nextTest;
  491. int _i, _nextCount[3], _prevCount[3];
  492. for (_i = 0; _i < 3; _i++) {
  493. if (node->tail[_i]->next[_i]) {
  494. printf("tail is not tail\n");
  495. printf(
  496. "node->tail[%d]->next[%d]=%p\n", _i, _i, node->tail[_i]->next[_i]);
  497. }
  498. if (node->head[_i]->prev[_i]) {
  499. printf("head is not head\n");
  500. printf(
  501. "node->head[%d]->prev[%d]=%p\n", _i, _i, node->head[_i]->prev[_i]);
  502. }
  503. }
  504. for (_i = 0; _i < 3; _i++) {
  505. for (_nextCount[_i] = 0, _nextTest = node->head[_i];
  506. _nextTest && _nextTest->next[_i];
  507. _nextTest = _nextTest->next[_i], _nextCount[_i]++)
  508. ;
  509. for (_prevCount[_i] = 0, _prevTest = node->tail[_i];
  510. _prevTest && _prevTest->prev[_i];
  511. _prevTest = _prevTest->prev[_i], _prevCount[_i]++)
  512. ;
  513. if (_nextTest != node->tail[_i]) {
  514. printf("next-list of axis %d does not end at tail\n", _i);
  515. }
  516. if (_prevTest != node->head[_i]) {
  517. printf("prev-list of axis %d does not end at head\n", _i);
  518. }
  519. for (; _nextTest && _nextTest->prev[_i]; _nextTest = _nextTest->prev[_i])
  520. ;
  521. for (; _prevTest && _prevTest->next[_i]; _prevTest = _prevTest->next[_i])
  522. ;
  523. if (_nextTest != node->head[_i]) {
  524. printf("next-list of axis %d does not loop back to head\n", _i);
  525. }
  526. if (_prevTest != node->tail[_i]) {
  527. printf("prev-list of axis %d does not loop back to tail\n", _i);
  528. }
  529. }
  530. for (_i = 1; _i < 3; _i++) {
  531. if (_prevCount[_i] != _prevCount[_i - 1] ||
  532. _nextCount[_i] != _nextCount[_i - 1] ||
  533. _prevCount[_i] != _nextCount[_i]) {
  534. printf(
  535. "{%d %d %d} {%d %d %d}\n",
  536. _prevCount[0],
  537. _prevCount[1],
  538. _prevCount[2],
  539. _nextCount[0],
  540. _nextCount[1],
  541. _nextCount[2]);
  542. }
  543. }
  544. }
  545. #endif
  546. node->axis = axis;
  547. if (!splitlists(
  548. node->head, node->tail, heads, tails, newCounts, axis, node->pixelCount)) {
  549. #ifndef NO_OUTPUT
  550. printf("list split failed.\n");
  551. #endif
  552. return 0;
  553. }
  554. #ifdef TEST_SPLIT
  555. if (!test_sorted(heads[0])) {
  556. printf("bug in split");
  557. exit(1);
  558. }
  559. if (!test_sorted(heads[1])) {
  560. printf("bug in split");
  561. exit(1);
  562. }
  563. #endif
  564. /* malloc check ok, small constant allocation */
  565. left = malloc(sizeof(BoxNode));
  566. right = malloc(sizeof(BoxNode));
  567. if (!left || !right) {
  568. free(left);
  569. free(right);
  570. return 0;
  571. }
  572. for (i = 0; i < 3; i++) {
  573. left->head[i] = heads[0][i];
  574. left->tail[i] = tails[0][i];
  575. right->head[i] = heads[1][i];
  576. right->tail[i] = tails[1][i];
  577. node->head[i] = NULL;
  578. node->tail[i] = NULL;
  579. }
  580. #ifdef TEST_SPLIT
  581. if (left->head[0]) {
  582. rh = left->head[0]->p.c.r;
  583. rl = left->tail[0]->p.c.r;
  584. gh = left->head[1]->p.c.g;
  585. gl = left->tail[1]->p.c.g;
  586. bh = left->head[2]->p.c.b;
  587. bl = left->tail[2]->p.c.b;
  588. printf(" left node [%3d %3d %3d] [%3d %3d %3d]\n", rl, gl, bl, rh, gh, bh);
  589. }
  590. if (right->head[0]) {
  591. rh = right->head[0]->p.c.r;
  592. rl = right->tail[0]->p.c.r;
  593. gh = right->head[1]->p.c.g;
  594. gl = right->tail[1]->p.c.g;
  595. bh = right->head[2]->p.c.b;
  596. bl = right->tail[2]->p.c.b;
  597. printf(" right node [%3d %3d %3d] [%3d %3d %3d]\n", rl, gl, bl, rh, gh, bh);
  598. }
  599. #endif
  600. left->l = left->r = NULL;
  601. right->l = right->r = NULL;
  602. left->axis = right->axis = -1;
  603. left->volume = right->volume = -1;
  604. left->pixelCount = newCounts[0];
  605. right->pixelCount = newCounts[1];
  606. node->l = left;
  607. node->r = right;
  608. return 1;
  609. }
  610. static BoxNode *
  611. median_cut(PixelList *hl[3], uint32_t imPixelCount, int nPixels) {
  612. PixelList *tl[3];
  613. int i;
  614. BoxNode *root;
  615. Heap *h;
  616. BoxNode *thisNode;
  617. h = ImagingQuantHeapNew(box_heap_cmp);
  618. /* malloc check ok, small constant allocation */
  619. root = malloc(sizeof(BoxNode));
  620. if (!root) {
  621. ImagingQuantHeapFree(h);
  622. return NULL;
  623. }
  624. for (i = 0; i < 3; i++) {
  625. for (tl[i] = hl[i]; tl[i] && tl[i]->next[i]; tl[i] = tl[i]->next[i])
  626. ;
  627. root->head[i] = hl[i];
  628. root->tail[i] = tl[i];
  629. }
  630. root->l = root->r = NULL;
  631. root->axis = -1;
  632. root->volume = -1;
  633. root->pixelCount = imPixelCount;
  634. ImagingQuantHeapAdd(h, (void *)root);
  635. while (--nPixels) {
  636. do {
  637. if (!ImagingQuantHeapRemove(h, (void **)&thisNode)) {
  638. goto done;
  639. }
  640. } while (compute_box_volume(thisNode) == 1);
  641. if (!split(thisNode)) {
  642. #ifndef NO_OUTPUT
  643. printf("Oops, split failed...\n");
  644. #endif
  645. exit(1);
  646. }
  647. ImagingQuantHeapAdd(h, (void *)(thisNode->l));
  648. ImagingQuantHeapAdd(h, (void *)(thisNode->r));
  649. }
  650. done:
  651. ImagingQuantHeapFree(h);
  652. return root;
  653. }
  654. static void
  655. free_box_tree(BoxNode *n) {
  656. PixelList *p, *pp;
  657. if (n->l) {
  658. free_box_tree(n->l);
  659. }
  660. if (n->r) {
  661. free_box_tree(n->r);
  662. }
  663. for (p = n->head[0]; p; p = pp) {
  664. pp = p->next[0];
  665. free(p);
  666. }
  667. free(n);
  668. }
  669. #ifdef TEST_SPLIT_INTEGRITY
  670. static int
  671. checkContained(BoxNode *n, Pixel *pp) {
  672. if (n->l && n->r) {
  673. return checkContained(n->l, pp) + checkContained(n->r, pp);
  674. }
  675. if (n->l || n->r) {
  676. #ifndef NO_OUTPUT
  677. printf("box tree is dead\n");
  678. #endif
  679. return 0;
  680. }
  681. if (pp->c.r <= n->head[0]->p.c.r && pp->c.r >= n->tail[0]->p.c.r &&
  682. pp->c.g <= n->head[1]->p.c.g && pp->c.g >= n->tail[1]->p.c.g &&
  683. pp->c.b <= n->head[2]->p.c.b && pp->c.b >= n->tail[2]->p.c.b) {
  684. return 1;
  685. }
  686. return 0;
  687. }
  688. #endif
  689. static int
  690. annotate_hash_table(BoxNode *n, HashTable *h, uint32_t *box) {
  691. PixelList *p;
  692. PixelHashData *d = (PixelHashData *)hashtable_get_user_data(h);
  693. Pixel q;
  694. if (n->l && n->r) {
  695. return annotate_hash_table(n->l, h, box) && annotate_hash_table(n->r, h, box);
  696. }
  697. if (n->l || n->r) {
  698. #ifndef NO_OUTPUT
  699. printf("box tree is dead\n");
  700. #endif
  701. return 0;
  702. }
  703. for (p = n->head[0]; p; p = p->next[0]) {
  704. PIXEL_UNSCALE(&(p->p), &q, d->scale);
  705. if (!hashtable_insert(h, q, *box)) {
  706. #ifndef NO_OUTPUT
  707. printf("hashtable insert failed\n");
  708. #endif
  709. return 0;
  710. }
  711. }
  712. if (n->head[0]) {
  713. (*box)++;
  714. }
  715. return 1;
  716. }
  717. typedef struct {
  718. uint32_t *distance;
  719. uint32_t index;
  720. } DistanceWithIndex;
  721. static int
  722. _distance_index_cmp(const void *a, const void *b) {
  723. DistanceWithIndex *A = (DistanceWithIndex *)a;
  724. DistanceWithIndex *B = (DistanceWithIndex *)b;
  725. if (*A->distance == *B->distance) {
  726. return A->index < B->index ? -1 : +1;
  727. }
  728. return *A->distance < *B->distance ? -1 : +1;
  729. }
  730. static int
  731. resort_distance_tables(
  732. uint32_t *avgDist, uint32_t **avgDistSortKey, Pixel *p, uint32_t nEntries) {
  733. uint32_t i, j, k;
  734. uint32_t **skRow;
  735. uint32_t *skElt;
  736. for (i = 0; i < nEntries; i++) {
  737. avgDist[i * nEntries + i] = 0;
  738. for (j = 0; j < i; j++) {
  739. avgDist[j * nEntries + i] = avgDist[i * nEntries + j] =
  740. _DISTSQR(p + i, p + j);
  741. }
  742. }
  743. for (i = 0; i < nEntries; i++) {
  744. skRow = avgDistSortKey + i * nEntries;
  745. for (j = 1; j < nEntries; j++) {
  746. skElt = skRow[j];
  747. for (k = j; k && (*(skRow[k - 1]) > *(skRow[k])); k--) {
  748. skRow[k] = skRow[k - 1];
  749. }
  750. if (k != j) {
  751. skRow[k] = skElt;
  752. }
  753. }
  754. }
  755. return 1;
  756. }
  757. static int
  758. build_distance_tables(
  759. uint32_t *avgDist, uint32_t **avgDistSortKey, Pixel *p, uint32_t nEntries) {
  760. uint32_t i, j;
  761. DistanceWithIndex *dwi;
  762. for (i = 0; i < nEntries; i++) {
  763. avgDist[i * nEntries + i] = 0;
  764. avgDistSortKey[i * nEntries + i] = &(avgDist[i * nEntries + i]);
  765. for (j = 0; j < i; j++) {
  766. avgDist[j * nEntries + i] = avgDist[i * nEntries + j] =
  767. _DISTSQR(p + i, p + j);
  768. avgDistSortKey[j * nEntries + i] = &(avgDist[j * nEntries + i]);
  769. avgDistSortKey[i * nEntries + j] = &(avgDist[i * nEntries + j]);
  770. }
  771. }
  772. dwi = calloc(nEntries, sizeof(DistanceWithIndex));
  773. if (!dwi) {
  774. return 0;
  775. }
  776. for (i = 0; i < nEntries; i++) {
  777. for (j = 0; j < nEntries; j++) {
  778. dwi[j] = (DistanceWithIndex){
  779. &(avgDist[i * nEntries + j]),
  780. j
  781. };
  782. }
  783. qsort(
  784. dwi,
  785. nEntries,
  786. sizeof(DistanceWithIndex),
  787. _distance_index_cmp);
  788. for (j = 0; j < nEntries; j++) {
  789. avgDistSortKey[i * nEntries + j] = dwi[j].distance;
  790. }
  791. }
  792. free(dwi);
  793. return 1;
  794. }
  795. static int
  796. map_image_pixels(
  797. Pixel *pixelData,
  798. uint32_t nPixels,
  799. Pixel *paletteData,
  800. uint32_t nPaletteEntries,
  801. uint32_t *avgDist,
  802. uint32_t **avgDistSortKey,
  803. uint32_t *pixelArray) {
  804. uint32_t *aD, **aDSK;
  805. uint32_t idx;
  806. uint32_t i, j;
  807. uint32_t bestdist, bestmatch, dist;
  808. uint32_t initialdist;
  809. HashTable *h2;
  810. h2 = hashtable_new(unshifted_pixel_hash, unshifted_pixel_cmp);
  811. for (i = 0; i < nPixels; i++) {
  812. if (!hashtable_lookup(h2, pixelData[i], &bestmatch)) {
  813. bestmatch = 0;
  814. initialdist = _DISTSQR(paletteData + bestmatch, pixelData + i);
  815. bestdist = initialdist;
  816. initialdist <<= 2;
  817. aDSK = avgDistSortKey + bestmatch * nPaletteEntries;
  818. aD = avgDist + bestmatch * nPaletteEntries;
  819. for (j = 0; j < nPaletteEntries; j++) {
  820. idx = aDSK[j] - aD;
  821. if (*(aDSK[j]) <= initialdist) {
  822. dist = _DISTSQR(paletteData + idx, pixelData + i);
  823. if (dist < bestdist) {
  824. bestdist = dist;
  825. bestmatch = idx;
  826. }
  827. } else {
  828. break;
  829. }
  830. }
  831. hashtable_insert(h2, pixelData[i], bestmatch);
  832. }
  833. pixelArray[i] = bestmatch;
  834. }
  835. hashtable_free(h2);
  836. return 1;
  837. }
  838. static int
  839. map_image_pixels_from_quantized_pixels(
  840. Pixel *pixelData,
  841. uint32_t nPixels,
  842. Pixel *paletteData,
  843. uint32_t nPaletteEntries,
  844. uint32_t *avgDist,
  845. uint32_t **avgDistSortKey,
  846. uint32_t *pixelArray,
  847. uint32_t *avg[3],
  848. uint32_t *count) {
  849. uint32_t *aD, **aDSK;
  850. uint32_t idx;
  851. uint32_t i, j;
  852. uint32_t bestdist, bestmatch, dist;
  853. uint32_t initialdist;
  854. HashTable *h2;
  855. int changes = 0;
  856. h2 = hashtable_new(unshifted_pixel_hash, unshifted_pixel_cmp);
  857. for (i = 0; i < nPixels; i++) {
  858. if (!hashtable_lookup(h2, pixelData[i], &bestmatch)) {
  859. bestmatch = pixelArray[i];
  860. initialdist = _DISTSQR(paletteData + bestmatch, pixelData + i);
  861. bestdist = initialdist;
  862. initialdist <<= 2;
  863. aDSK = avgDistSortKey + bestmatch * nPaletteEntries;
  864. aD = avgDist + bestmatch * nPaletteEntries;
  865. for (j = 0; j < nPaletteEntries; j++) {
  866. idx = aDSK[j] - aD;
  867. if (*(aDSK[j]) <= initialdist) {
  868. dist = _DISTSQR(paletteData + idx, pixelData + i);
  869. if (dist < bestdist) {
  870. bestdist = dist;
  871. bestmatch = idx;
  872. }
  873. } else {
  874. break;
  875. }
  876. }
  877. hashtable_insert(h2, pixelData[i], bestmatch);
  878. }
  879. if (pixelArray[i] != bestmatch) {
  880. changes++;
  881. avg[0][bestmatch] += pixelData[i].c.r;
  882. avg[1][bestmatch] += pixelData[i].c.g;
  883. avg[2][bestmatch] += pixelData[i].c.b;
  884. avg[0][pixelArray[i]] -= pixelData[i].c.r;
  885. avg[1][pixelArray[i]] -= pixelData[i].c.g;
  886. avg[2][pixelArray[i]] -= pixelData[i].c.b;
  887. count[bestmatch]++;
  888. count[pixelArray[i]]--;
  889. pixelArray[i] = bestmatch;
  890. }
  891. }
  892. hashtable_free(h2);
  893. return changes;
  894. }
  895. static int
  896. map_image_pixels_from_median_box(
  897. Pixel *pixelData,
  898. uint32_t nPixels,
  899. Pixel *paletteData,
  900. uint32_t nPaletteEntries,
  901. HashTable *medianBoxHash,
  902. uint32_t *avgDist,
  903. uint32_t **avgDistSortKey,
  904. uint32_t *pixelArray) {
  905. uint32_t *aD, **aDSK;
  906. uint32_t idx;
  907. uint32_t i, j;
  908. uint32_t bestdist, bestmatch, dist;
  909. uint32_t initialdist;
  910. HashTable *h2;
  911. uint32_t pixelVal;
  912. h2 = hashtable_new(unshifted_pixel_hash, unshifted_pixel_cmp);
  913. for (i = 0; i < nPixels; i++) {
  914. if (hashtable_lookup(h2, pixelData[i], &pixelVal)) {
  915. pixelArray[i] = pixelVal;
  916. continue;
  917. }
  918. if (!hashtable_lookup(medianBoxHash, pixelData[i], &pixelVal)) {
  919. #ifndef NO_OUTPUT
  920. printf("pixel lookup failed\n");
  921. #endif
  922. return 0;
  923. }
  924. initialdist = _DISTSQR(paletteData + pixelVal, pixelData + i);
  925. bestdist = initialdist;
  926. bestmatch = pixelVal;
  927. initialdist <<= 2;
  928. aDSK = avgDistSortKey + pixelVal * nPaletteEntries;
  929. aD = avgDist + pixelVal * nPaletteEntries;
  930. for (j = 0; j < nPaletteEntries; j++) {
  931. idx = aDSK[j] - aD;
  932. if (*(aDSK[j]) <= initialdist) {
  933. dist = _DISTSQR(paletteData + idx, pixelData + i);
  934. if (dist < bestdist) {
  935. bestdist = dist;
  936. bestmatch = idx;
  937. }
  938. } else {
  939. break;
  940. }
  941. }
  942. pixelArray[i] = bestmatch;
  943. hashtable_insert(h2, pixelData[i], bestmatch);
  944. }
  945. hashtable_free(h2);
  946. return 1;
  947. }
  948. static int
  949. compute_palette_from_median_cut(
  950. Pixel *pixelData,
  951. uint32_t nPixels,
  952. HashTable *medianBoxHash,
  953. Pixel **palette,
  954. uint32_t nPaletteEntries) {
  955. uint32_t i;
  956. uint32_t paletteEntry;
  957. Pixel *p;
  958. uint32_t *avg[3];
  959. uint32_t *count;
  960. *palette = NULL;
  961. /* malloc check ok, using calloc */
  962. if (!(count = calloc(nPaletteEntries, sizeof(uint32_t)))) {
  963. return 0;
  964. }
  965. for (i = 0; i < 3; i++) {
  966. avg[i] = NULL;
  967. }
  968. for (i = 0; i < 3; i++) {
  969. /* malloc check ok, using calloc */
  970. if (!(avg[i] = calloc(nPaletteEntries, sizeof(uint32_t)))) {
  971. for (i = 0; i < 3; i++) {
  972. if (avg[i]) {
  973. free(avg[i]);
  974. }
  975. }
  976. free(count);
  977. return 0;
  978. }
  979. }
  980. for (i = 0; i < nPixels; i++) {
  981. #ifdef TEST_SPLIT_INTEGRITY
  982. if (!(i % 100)) {
  983. printf("%05d\r", i);
  984. fflush(stdout);
  985. }
  986. if (checkContained(root, pixelData + i) > 1) {
  987. printf("pixel in two boxes\n");
  988. for (i = 0; i < 3; i++) {
  989. free(avg[i]);
  990. }
  991. free(count);
  992. return 0;
  993. }
  994. #endif
  995. if (!hashtable_lookup(medianBoxHash, pixelData[i], &paletteEntry)) {
  996. #ifndef NO_OUTPUT
  997. printf("pixel lookup failed\n");
  998. #endif
  999. for (i = 0; i < 3; i++) {
  1000. free(avg[i]);
  1001. }
  1002. free(count);
  1003. return 0;
  1004. }
  1005. if (paletteEntry >= nPaletteEntries) {
  1006. #ifndef NO_OUTPUT
  1007. printf(
  1008. "panic - paletteEntry>=nPaletteEntries (%d>=%d)\n",
  1009. (int)paletteEntry,
  1010. (int)nPaletteEntries);
  1011. #endif
  1012. for (i = 0; i < 3; i++) {
  1013. free(avg[i]);
  1014. }
  1015. free(count);
  1016. return 0;
  1017. }
  1018. avg[0][paletteEntry] += pixelData[i].c.r;
  1019. avg[1][paletteEntry] += pixelData[i].c.g;
  1020. avg[2][paletteEntry] += pixelData[i].c.b;
  1021. count[paletteEntry]++;
  1022. }
  1023. /* malloc check ok, using calloc */
  1024. p = calloc(nPaletteEntries, sizeof(Pixel));
  1025. if (!p) {
  1026. for (i = 0; i < 3; i++) {
  1027. free(avg[i]);
  1028. }
  1029. free(count);
  1030. return 0;
  1031. }
  1032. for (i = 0; i < nPaletteEntries; i++) {
  1033. p[i].c.r = (int)(.5 + (double)avg[0][i] / (double)count[i]);
  1034. p[i].c.g = (int)(.5 + (double)avg[1][i] / (double)count[i]);
  1035. p[i].c.b = (int)(.5 + (double)avg[2][i] / (double)count[i]);
  1036. }
  1037. *palette = p;
  1038. for (i = 0; i < 3; i++) {
  1039. free(avg[i]);
  1040. }
  1041. free(count);
  1042. return 1;
  1043. }
  1044. static int
  1045. recompute_palette_from_averages(
  1046. Pixel *palette, uint32_t nPaletteEntries, uint32_t *avg[3], uint32_t *count) {
  1047. uint32_t i;
  1048. for (i = 0; i < nPaletteEntries; i++) {
  1049. palette[i].c.r = (int)(.5 + (double)avg[0][i] / (double)count[i]);
  1050. palette[i].c.g = (int)(.5 + (double)avg[1][i] / (double)count[i]);
  1051. palette[i].c.b = (int)(.5 + (double)avg[2][i] / (double)count[i]);
  1052. }
  1053. return 1;
  1054. }
  1055. static int
  1056. compute_palette_from_quantized_pixels(
  1057. Pixel *pixelData,
  1058. uint32_t nPixels,
  1059. Pixel *palette,
  1060. uint32_t nPaletteEntries,
  1061. uint32_t *avg[3],
  1062. uint32_t *count,
  1063. uint32_t *qp) {
  1064. uint32_t i;
  1065. memset(count, 0, sizeof(uint32_t) * nPaletteEntries);
  1066. for (i = 0; i < 3; i++) {
  1067. memset(avg[i], 0, sizeof(uint32_t) * nPaletteEntries);
  1068. }
  1069. for (i = 0; i < nPixels; i++) {
  1070. if (qp[i] >= nPaletteEntries) {
  1071. #ifndef NO_OUTPUT
  1072. printf("scream\n");
  1073. #endif
  1074. return 0;
  1075. }
  1076. avg[0][qp[i]] += pixelData[i].c.r;
  1077. avg[1][qp[i]] += pixelData[i].c.g;
  1078. avg[2][qp[i]] += pixelData[i].c.b;
  1079. count[qp[i]]++;
  1080. }
  1081. for (i = 0; i < nPaletteEntries; i++) {
  1082. palette[i].c.r = (int)(.5 + (double)avg[0][i] / (double)count[i]);
  1083. palette[i].c.g = (int)(.5 + (double)avg[1][i] / (double)count[i]);
  1084. palette[i].c.b = (int)(.5 + (double)avg[2][i] / (double)count[i]);
  1085. }
  1086. return 1;
  1087. }
  1088. static int
  1089. k_means(
  1090. Pixel *pixelData,
  1091. uint32_t nPixels,
  1092. Pixel *paletteData,
  1093. uint32_t nPaletteEntries,
  1094. uint32_t *qp,
  1095. int threshold) {
  1096. uint32_t *avg[3];
  1097. uint32_t *count;
  1098. uint32_t i;
  1099. uint32_t *avgDist;
  1100. uint32_t **avgDistSortKey;
  1101. int changes;
  1102. int built = 0;
  1103. if (nPaletteEntries > UINT32_MAX / (sizeof(uint32_t))) {
  1104. return 0;
  1105. }
  1106. /* malloc check ok, using calloc */
  1107. if (!(count = calloc(nPaletteEntries, sizeof(uint32_t)))) {
  1108. return 0;
  1109. }
  1110. for (i = 0; i < 3; i++) {
  1111. avg[i] = NULL;
  1112. }
  1113. for (i = 0; i < 3; i++) {
  1114. /* malloc check ok, using calloc */
  1115. if (!(avg[i] = calloc(nPaletteEntries, sizeof(uint32_t)))) {
  1116. goto error_1;
  1117. }
  1118. }
  1119. /* this is enough of a check, since the multiplication n*size is done above */
  1120. if (nPaletteEntries > UINT32_MAX / nPaletteEntries) {
  1121. goto error_1;
  1122. }
  1123. /* malloc check ok, using calloc, checking n*n above */
  1124. avgDist = calloc(nPaletteEntries * nPaletteEntries, sizeof(uint32_t));
  1125. if (!avgDist) {
  1126. goto error_1;
  1127. }
  1128. /* malloc check ok, using calloc, checking n*n above */
  1129. avgDistSortKey = calloc(nPaletteEntries * nPaletteEntries, sizeof(uint32_t *));
  1130. if (!avgDistSortKey) {
  1131. goto error_2;
  1132. }
  1133. #ifndef NO_OUTPUT
  1134. printf("[");
  1135. fflush(stdout);
  1136. #endif
  1137. while (1) {
  1138. if (!built) {
  1139. compute_palette_from_quantized_pixels(
  1140. pixelData, nPixels, paletteData, nPaletteEntries, avg, count, qp);
  1141. if (!build_distance_tables(
  1142. avgDist, avgDistSortKey, paletteData, nPaletteEntries)) {
  1143. goto error_3;
  1144. }
  1145. built = 1;
  1146. } else {
  1147. recompute_palette_from_averages(paletteData, nPaletteEntries, avg, count);
  1148. resort_distance_tables(
  1149. avgDist, avgDistSortKey, paletteData, nPaletteEntries);
  1150. }
  1151. changes = map_image_pixels_from_quantized_pixels(
  1152. pixelData,
  1153. nPixels,
  1154. paletteData,
  1155. nPaletteEntries,
  1156. avgDist,
  1157. avgDistSortKey,
  1158. qp,
  1159. avg,
  1160. count);
  1161. if (changes < 0) {
  1162. goto error_3;
  1163. }
  1164. #ifndef NO_OUTPUT
  1165. printf(".(%d)", changes);
  1166. fflush(stdout);
  1167. #endif
  1168. if (changes <= threshold) {
  1169. break;
  1170. }
  1171. }
  1172. #ifndef NO_OUTPUT
  1173. printf("]\n");
  1174. #endif
  1175. if (avgDistSortKey) {
  1176. free(avgDistSortKey);
  1177. }
  1178. if (avgDist) {
  1179. free(avgDist);
  1180. }
  1181. for (i = 0; i < 3; i++) {
  1182. if (avg[i]) {
  1183. free(avg[i]);
  1184. }
  1185. }
  1186. if (count) {
  1187. free(count);
  1188. }
  1189. return 1;
  1190. error_3:
  1191. if (avgDistSortKey) {
  1192. free(avgDistSortKey);
  1193. }
  1194. error_2:
  1195. if (avgDist) {
  1196. free(avgDist);
  1197. }
  1198. error_1:
  1199. for (i = 0; i < 3; i++) {
  1200. if (avg[i]) {
  1201. free(avg[i]);
  1202. }
  1203. }
  1204. if (count) {
  1205. free(count);
  1206. }
  1207. return 0;
  1208. }
  1209. static int
  1210. quantize(
  1211. Pixel *pixelData,
  1212. uint32_t nPixels,
  1213. uint32_t nQuantPixels,
  1214. Pixel **palette,
  1215. uint32_t *paletteLength,
  1216. uint32_t **quantizedPixels,
  1217. int kmeans) {
  1218. PixelList *hl[3];
  1219. HashTable *h;
  1220. BoxNode *root;
  1221. uint32_t i;
  1222. uint32_t *qp;
  1223. uint32_t nPaletteEntries;
  1224. uint32_t *avgDist;
  1225. uint32_t **avgDistSortKey;
  1226. Pixel *p;
  1227. #ifndef NO_OUTPUT
  1228. uint32_t timer, timer2;
  1229. #endif
  1230. #ifndef NO_OUTPUT
  1231. timer2 = clock();
  1232. printf("create hash table...");
  1233. fflush(stdout);
  1234. timer = clock();
  1235. #endif
  1236. h = create_pixel_hash(pixelData, nPixels);
  1237. #ifndef NO_OUTPUT
  1238. printf("done (%f)\n", (clock() - timer) / (double)CLOCKS_PER_SEC);
  1239. #endif
  1240. if (!h) {
  1241. goto error_0;
  1242. }
  1243. #ifndef NO_OUTPUT
  1244. printf("create lists from hash table...");
  1245. fflush(stdout);
  1246. timer = clock();
  1247. #endif
  1248. hl[0] = hl[1] = hl[2] = NULL;
  1249. hashtable_foreach(h, hash_to_list, hl);
  1250. #ifndef NO_OUTPUT
  1251. printf("done (%f)\n", (clock() - timer) / (double)CLOCKS_PER_SEC);
  1252. #endif
  1253. if (!hl[0]) {
  1254. goto error_1;
  1255. }
  1256. #ifndef NO_OUTPUT
  1257. printf("mergesort lists...");
  1258. fflush(stdout);
  1259. timer = clock();
  1260. #endif
  1261. for (i = 0; i < 3; i++) {
  1262. hl[i] = mergesort_pixels(hl[i], i);
  1263. }
  1264. #ifdef TEST_MERGESORT
  1265. if (!test_sorted(hl)) {
  1266. printf("bug in mergesort\n");
  1267. goto error_1;
  1268. }
  1269. #endif
  1270. #ifndef NO_OUTPUT
  1271. printf("done (%f)\n", (clock() - timer) / (double)CLOCKS_PER_SEC);
  1272. #endif
  1273. #ifndef NO_OUTPUT
  1274. printf("median cut...");
  1275. fflush(stdout);
  1276. timer = clock();
  1277. #endif
  1278. root = median_cut(hl, nPixels, nQuantPixels);
  1279. #ifndef NO_OUTPUT
  1280. printf("done (%f)\n", (clock() - timer) / (double)CLOCKS_PER_SEC);
  1281. #endif
  1282. if (!root) {
  1283. goto error_1;
  1284. }
  1285. nPaletteEntries = 0;
  1286. #ifndef NO_OUTPUT
  1287. printf("median cut tree to hash table...");
  1288. fflush(stdout);
  1289. timer = clock();
  1290. #endif
  1291. annotate_hash_table(root, h, &nPaletteEntries);
  1292. #ifndef NO_OUTPUT
  1293. printf("done (%f)\n", (clock() - timer) / (double)CLOCKS_PER_SEC);
  1294. #endif
  1295. #ifndef NO_OUTPUT
  1296. printf("compute palette...\n");
  1297. fflush(stdout);
  1298. timer = clock();
  1299. #endif
  1300. if (!compute_palette_from_median_cut(pixelData, nPixels, h, &p, nPaletteEntries)) {
  1301. goto error_3;
  1302. }
  1303. #ifndef NO_OUTPUT
  1304. printf("done (%f)\n", (clock() - timer) / (double)CLOCKS_PER_SEC);
  1305. #endif
  1306. free_box_tree(root);
  1307. root = NULL;
  1308. /* malloc check ok, using calloc for overflow */
  1309. qp = calloc(nPixels, sizeof(uint32_t));
  1310. if (!qp) {
  1311. goto error_4;
  1312. }
  1313. if (nPaletteEntries > UINT32_MAX / nPaletteEntries) {
  1314. goto error_5;
  1315. }
  1316. /* malloc check ok, using calloc for overflow, check of n*n above */
  1317. avgDist = calloc(nPaletteEntries * nPaletteEntries, sizeof(uint32_t));
  1318. if (!avgDist) {
  1319. goto error_5;
  1320. }
  1321. /* malloc check ok, using calloc for overflow, check of n*n above */
  1322. avgDistSortKey = calloc(nPaletteEntries * nPaletteEntries, sizeof(uint32_t *));
  1323. if (!avgDistSortKey) {
  1324. goto error_6;
  1325. }
  1326. if (!build_distance_tables(avgDist, avgDistSortKey, p, nPaletteEntries)) {
  1327. goto error_7;
  1328. }
  1329. if (!map_image_pixels_from_median_box(
  1330. pixelData, nPixels, p, nPaletteEntries, h, avgDist, avgDistSortKey, qp)) {
  1331. goto error_7;
  1332. }
  1333. #ifdef TEST_NEAREST_NEIGHBOUR
  1334. #include <math.h>
  1335. {
  1336. uint32_t bestmatch, bestdist, dist;
  1337. HashTable *h2;
  1338. printf("nearest neighbour search (full search)...");
  1339. fflush(stdout);
  1340. timer = clock();
  1341. h2 = hashtable_new(unshifted_pixel_hash, unshifted_pixel_cmp);
  1342. for (i = 0; i < nPixels; i++) {
  1343. if (hashtable_lookup(h2, pixelData[i], &paletteEntry)) {
  1344. bestmatch = paletteEntry;
  1345. } else {
  1346. bestmatch = 0;
  1347. bestdist = _SQR(pixelData[i].c.r - p[0].c.r) +
  1348. _SQR(pixelData[i].c.g - p[0].c.g) +
  1349. _SQR(pixelData[i].c.b - p[0].c.b);
  1350. for (j = 1; j < nPaletteEntries; j++) {
  1351. dist = _SQR(pixelData[i].c.r - p[j].c.r) +
  1352. _SQR(pixelData[i].c.g - p[j].c.g) +
  1353. _SQR(pixelData[i].c.b - p[j].c.b);
  1354. if (dist == bestdist && j == qp[i]) {
  1355. bestmatch = j;
  1356. }
  1357. if (dist < bestdist) {
  1358. bestdist = dist;
  1359. bestmatch = j;
  1360. }
  1361. }
  1362. hashtable_insert(h2, pixelData[i], bestmatch);
  1363. }
  1364. if (qp[i] != bestmatch) {
  1365. printf ("discrepancy in matching algorithms pixel %d [%d %d] %f %f\n",
  1366. i,qp[i],bestmatch,
  1367. sqrt((double)(_SQR(pixelData[i].c.r-p[qp[i]].c.r)+
  1368. _SQR(pixelData[i].c.g-p[qp[i]].c.g)+
  1369. _SQR(pixelData[i].c.b-p[qp[i]].c.b))),
  1370. sqrt((double)(_SQR(pixelData[i].c.r-p[bestmatch].c.r)+
  1371. _SQR(pixelData[i].c.g-p[bestmatch].c.g)+
  1372. _SQR(pixelData[i].c.b-p[bestmatch].c.b)))
  1373. );
  1374. }
  1375. }
  1376. hashtable_free(h2);
  1377. }
  1378. #endif
  1379. #ifndef NO_OUTPUT
  1380. printf("k means...\n");
  1381. fflush(stdout);
  1382. timer = clock();
  1383. #endif
  1384. if (kmeans) {
  1385. k_means(pixelData, nPixels, p, nPaletteEntries, qp, kmeans - 1);
  1386. }
  1387. #ifndef NO_OUTPUT
  1388. printf("done (%f)\n", (clock() - timer) / (double)CLOCKS_PER_SEC);
  1389. #endif
  1390. *quantizedPixels = qp;
  1391. *palette = p;
  1392. *paletteLength = nPaletteEntries;
  1393. #ifndef NO_OUTPUT
  1394. printf("cleanup...");
  1395. fflush(stdout);
  1396. timer = clock();
  1397. #endif
  1398. if (avgDist) {
  1399. free(avgDist);
  1400. }
  1401. if (avgDistSortKey) {
  1402. free(avgDistSortKey);
  1403. }
  1404. destroy_pixel_hash(h);
  1405. #ifndef NO_OUTPUT
  1406. printf("done (%f)\n", (clock() - timer) / (double)CLOCKS_PER_SEC);
  1407. printf("-----\ntotal time %f\n", (clock() - timer2) / (double)CLOCKS_PER_SEC);
  1408. #endif
  1409. return 1;
  1410. error_7:
  1411. if (avgDistSortKey) {
  1412. free(avgDistSortKey);
  1413. }
  1414. error_6:
  1415. if (avgDist) {
  1416. free(avgDist);
  1417. }
  1418. error_5:
  1419. if (qp) {
  1420. free(qp);
  1421. }
  1422. error_4:
  1423. if (p) {
  1424. free(p);
  1425. }
  1426. error_3:
  1427. if (root) {
  1428. free_box_tree(root);
  1429. }
  1430. error_1:
  1431. destroy_pixel_hash(h);
  1432. error_0:
  1433. *quantizedPixels = NULL;
  1434. *paletteLength = 0;
  1435. *palette = NULL;
  1436. return 0;
  1437. }
  1438. typedef struct {
  1439. Pixel new;
  1440. uint32_t furthestV;
  1441. uint32_t furthestDistance;
  1442. int secondPixel;
  1443. } DistanceData;
  1444. static void
  1445. compute_distances(const HashTable *h, const Pixel pixel, uint32_t *dist, void *u) {
  1446. DistanceData *data = (DistanceData *)u;
  1447. uint32_t oldDist = *dist;
  1448. uint32_t newDist;
  1449. newDist = _DISTSQR(&(data->new), &pixel);
  1450. if (data->secondPixel || newDist < oldDist) {
  1451. *dist = newDist;
  1452. oldDist = newDist;
  1453. }
  1454. if (oldDist > data->furthestDistance) {
  1455. data->furthestDistance = oldDist;
  1456. data->furthestV = pixel.v;
  1457. }
  1458. }
  1459. static int
  1460. quantize2(
  1461. Pixel *pixelData,
  1462. uint32_t nPixels,
  1463. uint32_t nQuantPixels,
  1464. Pixel **palette,
  1465. uint32_t *paletteLength,
  1466. uint32_t **quantizedPixels,
  1467. int kmeans) {
  1468. HashTable *h;
  1469. uint32_t i;
  1470. uint32_t mean[3];
  1471. Pixel *p;
  1472. DistanceData data;
  1473. uint32_t *qp;
  1474. uint32_t *avgDist;
  1475. uint32_t **avgDistSortKey;
  1476. /* malloc check ok, using calloc */
  1477. p = calloc(nQuantPixels, sizeof(Pixel));
  1478. if (!p) {
  1479. return 0;
  1480. }
  1481. mean[0] = mean[1] = mean[2] = 0;
  1482. h = hashtable_new(unshifted_pixel_hash, unshifted_pixel_cmp);
  1483. for (i = 0; i < nPixels; i++) {
  1484. hashtable_insert(h, pixelData[i], 0xffffffff);
  1485. mean[0] += pixelData[i].c.r;
  1486. mean[1] += pixelData[i].c.g;
  1487. mean[2] += pixelData[i].c.b;
  1488. }
  1489. data.new.c.r = (int)(.5 + (double)mean[0] / (double)nPixels);
  1490. data.new.c.g = (int)(.5 + (double)mean[1] / (double)nPixels);
  1491. data.new.c.b = (int)(.5 + (double)mean[2] / (double)nPixels);
  1492. for (i = 0; i < nQuantPixels; i++) {
  1493. data.furthestDistance = 0;
  1494. data.furthestV = pixelData[0].v;
  1495. data.secondPixel = (i == 1) ? 1 : 0;
  1496. hashtable_foreach_update(h, compute_distances, &data);
  1497. p[i].v = data.furthestV;
  1498. data.new.v = data.furthestV;
  1499. }
  1500. hashtable_free(h);
  1501. /* malloc check ok, using calloc */
  1502. qp = calloc(nPixels, sizeof(uint32_t));
  1503. if (!qp) {
  1504. goto error_1;
  1505. }
  1506. if (nQuantPixels > UINT32_MAX / nQuantPixels) {
  1507. goto error_2;
  1508. }
  1509. /* malloc check ok, using calloc for overflow, check of n*n above */
  1510. avgDist = calloc(nQuantPixels * nQuantPixels, sizeof(uint32_t));
  1511. if (!avgDist) {
  1512. goto error_2;
  1513. }
  1514. /* malloc check ok, using calloc for overflow, check of n*n above */
  1515. avgDistSortKey = calloc(nQuantPixels * nQuantPixels, sizeof(uint32_t *));
  1516. if (!avgDistSortKey) {
  1517. goto error_3;
  1518. }
  1519. if (!build_distance_tables(avgDist, avgDistSortKey, p, nQuantPixels)) {
  1520. goto error_4;
  1521. }
  1522. if (!map_image_pixels(
  1523. pixelData, nPixels, p, nQuantPixels, avgDist, avgDistSortKey, qp)) {
  1524. goto error_4;
  1525. }
  1526. if (kmeans) {
  1527. k_means(pixelData, nPixels, p, nQuantPixels, qp, kmeans - 1);
  1528. }
  1529. *paletteLength = nQuantPixels;
  1530. *palette = p;
  1531. *quantizedPixels = qp;
  1532. free(avgDistSortKey);
  1533. free(avgDist);
  1534. return 1;
  1535. error_4:
  1536. free(avgDistSortKey);
  1537. error_3:
  1538. free(avgDist);
  1539. error_2:
  1540. free(qp);
  1541. error_1:
  1542. free(p);
  1543. return 0;
  1544. }
  1545. Imaging
  1546. ImagingQuantize(Imaging im, int colors, int mode, int kmeans) {
  1547. int i, j;
  1548. int x, y, v;
  1549. UINT8 *pp;
  1550. Pixel *p;
  1551. Pixel *palette;
  1552. uint32_t paletteLength;
  1553. int result;
  1554. uint32_t *newData;
  1555. Imaging imOut;
  1556. int withAlpha = 0;
  1557. ImagingSectionCookie cookie;
  1558. if (!im) {
  1559. return ImagingError_ModeError();
  1560. }
  1561. if (colors < 1 || colors > 256) {
  1562. /* FIXME: for colors > 256, consider returning an RGB image
  1563. instead (see @PIL205) */
  1564. return (Imaging)ImagingError_ValueError("bad number of colors");
  1565. }
  1566. if (strcmp(im->mode, "L") != 0 && strcmp(im->mode, "P") != 0 &&
  1567. strcmp(im->mode, "RGB") != 0 && strcmp(im->mode, "RGBA") != 0) {
  1568. return ImagingError_ModeError();
  1569. }
  1570. /* only octree and imagequant supports RGBA */
  1571. if (!strcmp(im->mode, "RGBA") && mode != 2 && mode != 3) {
  1572. return ImagingError_ModeError();
  1573. }
  1574. if (im->xsize > INT_MAX / im->ysize) {
  1575. return ImagingError_MemoryError();
  1576. }
  1577. /* malloc check ok, using calloc for final overflow, x*y above */
  1578. p = calloc(im->xsize * im->ysize, sizeof(Pixel));
  1579. if (!p) {
  1580. return ImagingError_MemoryError();
  1581. }
  1582. /* collect statistics */
  1583. /* FIXME: maybe we could load the hash tables directly from the
  1584. image data? */
  1585. if (!strcmp(im->mode, "L")) {
  1586. /* grayscale */
  1587. /* FIXME: converting a "L" image to "P" with 256 colors
  1588. should be done by a simple copy... */
  1589. for (i = y = 0; y < im->ysize; y++) {
  1590. for (x = 0; x < im->xsize; x++, i++) {
  1591. p[i].c.r = p[i].c.g = p[i].c.b = im->image8[y][x];
  1592. p[i].c.a = 255;
  1593. }
  1594. }
  1595. } else if (!strcmp(im->mode, "P")) {
  1596. /* palette */
  1597. pp = im->palette->palette;
  1598. for (i = y = 0; y < im->ysize; y++) {
  1599. for (x = 0; x < im->xsize; x++, i++) {
  1600. v = im->image8[y][x];
  1601. p[i].c.r = pp[v * 4 + 0];
  1602. p[i].c.g = pp[v * 4 + 1];
  1603. p[i].c.b = pp[v * 4 + 2];
  1604. p[i].c.a = pp[v * 4 + 3];
  1605. }
  1606. }
  1607. } else if (!strcmp(im->mode, "RGB") || !strcmp(im->mode, "RGBA")) {
  1608. /* true colour */
  1609. withAlpha = !strcmp(im->mode, "RGBA");
  1610. int transparency = 0;
  1611. unsigned char r = 0, g = 0, b = 0;
  1612. for (i = y = 0; y < im->ysize; y++) {
  1613. for (x = 0; x < im->xsize; x++, i++) {
  1614. p[i].v = im->image32[y][x];
  1615. if (withAlpha && p[i].c.a == 0) {
  1616. if (transparency == 0) {
  1617. transparency = 1;
  1618. r = p[i].c.r;
  1619. g = p[i].c.g;
  1620. b = p[i].c.b;
  1621. } else {
  1622. /* Set all subsequent transparent pixels
  1623. to the same colour as the first */
  1624. p[i].c.r = r;
  1625. p[i].c.g = g;
  1626. p[i].c.b = b;
  1627. }
  1628. }
  1629. }
  1630. }
  1631. } else {
  1632. free(p);
  1633. return (Imaging)ImagingError_ValueError("internal error");
  1634. }
  1635. ImagingSectionEnter(&cookie);
  1636. switch (mode) {
  1637. case 0:
  1638. /* median cut */
  1639. result = quantize(
  1640. p,
  1641. im->xsize * im->ysize,
  1642. colors,
  1643. &palette,
  1644. &paletteLength,
  1645. &newData,
  1646. kmeans);
  1647. break;
  1648. case 1:
  1649. /* maximum coverage */
  1650. result = quantize2(
  1651. p,
  1652. im->xsize * im->ysize,
  1653. colors,
  1654. &palette,
  1655. &paletteLength,
  1656. &newData,
  1657. kmeans);
  1658. break;
  1659. case 2:
  1660. result = quantize_octree(
  1661. p,
  1662. im->xsize * im->ysize,
  1663. colors,
  1664. &palette,
  1665. &paletteLength,
  1666. &newData,
  1667. withAlpha);
  1668. break;
  1669. case 3:
  1670. #ifdef HAVE_LIBIMAGEQUANT
  1671. result = quantize_pngquant(
  1672. p,
  1673. im->xsize,
  1674. im->ysize,
  1675. colors,
  1676. &palette,
  1677. &paletteLength,
  1678. &newData,
  1679. withAlpha);
  1680. #else
  1681. result = -1;
  1682. #endif
  1683. break;
  1684. default:
  1685. result = 0;
  1686. break;
  1687. }
  1688. free(p);
  1689. ImagingSectionLeave(&cookie);
  1690. if (result > 0) {
  1691. imOut = ImagingNewDirty("P", im->xsize, im->ysize);
  1692. ImagingSectionEnter(&cookie);
  1693. for (i = y = 0; y < im->ysize; y++) {
  1694. for (x = 0; x < im->xsize; x++) {
  1695. imOut->image8[y][x] = (unsigned char)newData[i++];
  1696. }
  1697. }
  1698. free(newData);
  1699. imOut->palette->size = (int)paletteLength;
  1700. pp = imOut->palette->palette;
  1701. for (i = j = 0; i < (int)paletteLength; i++) {
  1702. *pp++ = palette[i].c.r;
  1703. *pp++ = palette[i].c.g;
  1704. *pp++ = palette[i].c.b;
  1705. if (withAlpha) {
  1706. *pp = palette[i].c.a;
  1707. }
  1708. pp++;
  1709. }
  1710. if (withAlpha) {
  1711. strcpy(imOut->palette->mode, "RGBA");
  1712. }
  1713. free(palette);
  1714. ImagingSectionLeave(&cookie);
  1715. return imOut;
  1716. } else {
  1717. if (result == -1) {
  1718. return (Imaging)ImagingError_ValueError(
  1719. "dependency required by this method was not "
  1720. "enabled at compile time");
  1721. }
  1722. return (Imaging)ImagingError_ValueError("quantization error");
  1723. }
  1724. }