Quant.c 44 KB

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