seed random from ruby interface
[swftools.git] / lib / png.c
1 /*  png.c
2    
3    Copyright (c) 2003/2004/2005 Matthias Kramm <kramm@quiss.org>
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <assert.h>
23 #include <math.h>
24 #include <fcntl.h>
25 #include <zlib.h>
26 #include <limits.h>
27
28 #ifdef EXPORT
29 #undef EXPORT
30 #endif
31
32 #ifdef PNG_INLINE_EXPORTS
33 #define EXPORT static
34 #else
35 #define EXPORT
36 #include "png.h"
37 #endif
38
39 typedef unsigned u32;
40
41 typedef struct _COL {
42     unsigned char a,r,g,b;
43 } COL;
44
45 static int png_read_chunk(char (*head)[4], int*destlen, unsigned char**destdata, FILE*fi)
46 {
47     unsigned int len;
48     unsigned char blen[4];
49     if(destlen) *destlen=0;
50     if(destdata) *destdata=0;
51     if(!fread(&blen, 4, 1, fi)) {
52         return 0;
53     }
54     if(!fread(head, 4, 1, fi)) {
55         return 0;
56     }
57     len = blen[0]<<24|blen[1]<<16|blen[2]<<8|blen[3];
58     if(destlen) *destlen = len;
59     if(destdata) {
60         if(!len) {
61             *destdata = 0;
62         } else {
63             *destdata = (unsigned char*)malloc(len);
64             if(!fread(*destdata, len, 1, fi)) {
65                 *destdata = 0;
66                 if(destlen) *destlen=0;
67                 return 0;
68             }
69         }
70         fseek(fi, 4, SEEK_CUR);
71
72     } else {
73         fseek(fi, len+4, SEEK_CUR);
74     }
75     return 1;
76 }
77
78 static unsigned int png_get_dword(FILE*fi)
79 {
80     unsigned int a;
81     unsigned char b[4];
82     fread(&b,4,1,fi);
83     return b[0]<<24|b[1]<<16|b[2]<<8|b[3];
84 }
85
86 struct png_header
87 {
88     int width;
89     int height;
90     int bpp;
91     int mode;
92 };
93
94 static int png_read_header(FILE*fi, struct png_header*header)
95 {
96     char id[4];
97     int len;
98     int ok=0;
99     unsigned char head[8] = {137,80,78,71,13,10,26,10};
100     unsigned char head2[8];
101     unsigned char*data;
102     fread(head2,8,1,fi);
103     if(strncmp((const char*)head,(const char*)head2,4))
104         return 0; // not a png file
105     
106     while(png_read_chunk(&id, &len, &data, fi))
107     {
108         //printf("Chunk: %c%c%c%c (len:%d)\n", id[0],id[1],id[2],id[3], len);
109         if(!strncmp(id, "IHDR", 4)) {
110             char a,b,c,f,i;
111             if(len < 8) exit(1);
112             header->width = data[0]<<24|data[1]<<16|data[2]<<8|data[3];
113             header->height = data[4]<<24|data[5]<<16|data[6]<<8|data[7];
114             a = data[8];      // should be 8
115             b = data[9];      // should be 3(indexed) or 2(rgb)
116
117             c = data[10];     // compression mode (0)
118             f = data[11];     // filter mode (0)
119             i = data[12];     // interlace mode (0)
120
121             if(b!=0 && b!=4 && b!=2 && b!=3 && b!=6) {
122                 fprintf(stderr, "Image mode %d not supported!\n", b);
123                 return 0;
124             }
125             if(a!=8 && (b==2 || b==6)) {
126                 printf("Bpp %d in mode %d not supported!\n", b, a);
127                 return 0;
128             }
129             if(c!=0) {
130                 printf("Compression mode %d not supported!\n", c);
131                 return 0;
132             }
133             if(f!=0) {
134                 printf("Filter mode %d not supported!\n", f);
135                 return 0;
136             }
137             if(i!=0) {
138                 printf("Interlace mode %d not supported!\n", i);
139                 return 0;
140             }
141             //printf("%dx%d bpp:%d mode:%d comp:%d filter:%d interlace:%d\n",header->width, header->height, a,b,c,f,i);
142             header->bpp = a;
143             header->mode = b;
144             ok = 1;
145         } 
146         
147         free(data);
148     }
149     return ok;
150 }
151
152 typedef unsigned char byte;
153 #define ABS(a) ((a)>0?(a):(-(a)))
154 static inline byte PaethPredictor (byte a,byte b,byte c)
155 {
156         // a = left, b = above, c = upper left
157         int p = a + b - c;        // initial estimate
158         int pa = ABS(p - a);      // distances to a, b, c
159         int pb = ABS(p - b);
160         int pc = ABS(p - c);
161         // return nearest of a,b,c,
162         // breaking ties in order a,b,c.
163         if (pa <= pb && pa <= pc) 
164                 return a;
165         else if (pb <= pc) 
166                 return b;
167         else return c;
168 }
169
170 static void applyfilter1(int mode, unsigned char*src, unsigned char*old, unsigned char*dest, int width)
171 {
172     int x;
173     unsigned char last=0;
174     unsigned char upperlast=0;
175
176     if(mode==0) {
177         for(x=0;x<width;x++) {
178             *dest = *src;
179             dest++;
180             src++;
181         }
182     }
183     else if(mode==1) {
184         for(x=0;x<width;x++) {
185             *dest = *src+last;
186             last = *dest;
187             dest++;
188             src++;
189         }
190     }
191     else if(mode==2) {
192         for(x=0;x<width;x++) {
193             *dest = *src+*old;
194             dest++;
195             old++;
196             src++;
197         }
198     }
199     else if(mode==3) {
200         for(x=0;x<width;x++) {
201             *dest = *src+(*old+last)/2;
202             last = *dest;
203             dest++;
204             old++;
205             src++;
206         }
207     }
208     else if(mode==4) {
209         for(x=0;x<width;x++) {
210             *dest = *src+PaethPredictor(last,*old,upperlast);
211             last = *dest;
212             upperlast = *old;
213             dest++;
214             old++;
215             src++;
216         }
217     }    
218
219 }
220
221 static void applyfilter2(int mode, unsigned char*src, unsigned char*old, unsigned char*dest, int width)
222 {
223     int x;
224     unsigned char lasta=0;
225     unsigned char lastb=0;
226     unsigned char upperlasta=0;
227     unsigned char upperlastb=0;
228
229     if(mode==0) {
230         for(x=0;x<width;x++) {
231             dest[0] = src[0];
232             dest[1] = src[1];
233             dest+=2;
234             src+=2;
235         }
236     }
237     else if(mode==1) {
238         for(x=0;x<width;x++) {
239             dest[0] = src[0]+lasta;
240             dest[1] = src[1]+lastb;
241             lasta = dest[0];
242             lastb = dest[1];
243             dest+=2;
244             src+=2;
245         }
246     }
247     else if(mode==2) {
248         for(x=0;x<width;x++) {
249             dest[0] = src[0]+old[0];
250             dest[1] = src[1]+old[1];
251             dest+=2;
252             old+=2;
253             src+=2;
254         }
255     }
256     else if(mode==3) {
257         for(x=0;x<width;x++) {
258             dest[0] = src[0]+(old[0]+lasta)/2;
259             dest[1] = src[1]+(old[1]+lastb)/2;
260             lasta = dest[0];
261             lastb = dest[1];
262             dest+=2;
263             old+=2;
264             src+=2;
265         }
266     }
267     else if(mode==4) {
268         for(x=0;x<width;x++) {
269             dest[0] = src[0]+PaethPredictor(lasta,old[0],upperlasta);
270             dest[1] = src[1]+PaethPredictor(lastb,old[1],upperlastb);
271             lasta = dest[0];
272             lastb = dest[1];
273             upperlasta = old[0];
274             upperlastb = old[1];
275             dest+=2;
276             old+=2;
277             src+=2;
278         }
279     }    
280 }
281
282
283 /* also performs 24 bit conversion! */
284 static void applyfilter3(int mode, unsigned char*src, unsigned char*old, unsigned char*dest, int width)
285 {
286     int x;
287     unsigned char lastr=0;
288     unsigned char lastg=0;
289     unsigned char lastb=0;
290     unsigned char upperlastr=0;
291     unsigned char upperlastg=0;
292     unsigned char upperlastb=0;
293
294     if(mode==0) {
295         for(x=0;x<width;x++) {
296             dest[0] = 255;
297             dest[1] = src[0];
298             dest[2] = src[1];
299             dest[3] = src[2];
300             dest+=4;
301             src+=3;
302         }
303     }
304     else if(mode==1) {
305         for(x=0;x<width;x++) {
306             dest[0] = 255;
307             dest[1] = src[0]+lastr;
308             dest[2] = src[1]+lastg;
309             dest[3] = src[2]+lastb;
310             lastr = dest[1];
311             lastg = dest[2];
312             lastb = dest[3];
313             dest+=4;
314             src+=3;
315         }
316     }
317     else if(mode==2) {
318         for(x=0;x<width;x++) {
319             dest[0] = 255;
320             dest[1] = src[0]+old[1];
321             dest[2] = src[1]+old[2];
322             dest[3] = src[2]+old[3];
323             dest+=4;
324             old+=4;
325             src+=3;
326         }
327     }
328     else if(mode==3) {
329         for(x=0;x<width;x++) {
330             dest[0] = 255;
331             dest[1] = src[0]+(old[1]+lastr)/2;
332             dest[2] = src[1]+(old[2]+lastg)/2;
333             dest[3] = src[2]+(old[3]+lastb)/2;
334             lastr = dest[1];
335             lastg = dest[2];
336             lastb = dest[3];
337             dest+=4;
338             old+=4;
339             src+=3;
340         }
341     }
342     else if(mode==4) {
343         for(x=0;x<width;x++) {
344             dest[0] = 255;
345             dest[1] = src[0]+PaethPredictor(lastr,old[1],upperlastr);
346             dest[2] = src[1]+PaethPredictor(lastg,old[2],upperlastg);
347             dest[3] = src[2]+PaethPredictor(lastb,old[3],upperlastb);
348             lastr = dest[1];
349             lastg = dest[2];
350             lastb = dest[3];
351             upperlastr = old[1];
352             upperlastg = old[2];
353             upperlastb = old[3];
354             dest+=4;
355             old+=4;
356             src+=3;
357         }
358     }    
359 }
360
361 void png_inverse_filter_32(int mode, unsigned char*src, unsigned char*old, unsigned char*dest, int width)
362 {
363     int x;
364     unsigned char lastr=0;
365     unsigned char lastg=0;
366     unsigned char lastb=0;
367     unsigned char lasta=0;
368     unsigned char upperlastr=0;
369     unsigned char upperlastg=0;
370     unsigned char upperlastb=0;
371     unsigned char upperlasta=0;
372
373     if(mode==0) {
374         for(x=0;x<width;x++) {
375             dest[0] = src[3];
376             dest[1] = src[0];
377             dest[2] = src[1];
378             dest[3] = src[2];
379             dest+=4;
380             src+=4;
381         }
382     }
383     else if(mode==1) {
384         for(x=0;x<width;x++) {
385             dest[0] = src[3]+lasta;
386             dest[1] = src[0]+lastr;
387             dest[2] = src[1]+lastg;
388             dest[3] = src[2]+lastb;
389             lasta = dest[0];
390             lastr = dest[1];
391             lastg = dest[2];
392             lastb = dest[3];
393             dest+=4;
394             src+=4;
395         }
396     }
397     else if(mode==2) {
398         for(x=0;x<width;x++) {
399             dest[0] = src[3]+old[0];
400             dest[1] = src[0]+old[1];
401             dest[2] = src[1]+old[2];
402             dest[3] = src[2]+old[3];
403             dest+=4;
404             old+=4;
405             src+=4;
406         }
407     }
408     else if(mode==3) {
409         for(x=0;x<width;x++) {
410             dest[0] = src[3]+(old[0]+lasta)/2;
411             dest[1] = src[0]+(old[1]+lastr)/2;
412             dest[2] = src[1]+(old[2]+lastg)/2;
413             dest[3] = src[2]+(old[3]+lastb)/2;
414             lasta = dest[0];
415             lastr = dest[1];
416             lastg = dest[2];
417             lastb = dest[3];
418             dest+=4;
419             old+=4;
420             src+=4;
421         }
422     }
423     else if(mode==4) {
424         for(x=0;x<width;x++) {
425             dest[0] = src[3]+PaethPredictor(lasta,old[0],upperlasta);
426             dest[1] = src[0]+PaethPredictor(lastr,old[1],upperlastr);
427             dest[2] = src[1]+PaethPredictor(lastg,old[2],upperlastg);
428             dest[3] = src[2]+PaethPredictor(lastb,old[3],upperlastb);
429             lasta = dest[0];
430             lastr = dest[1];
431             lastg = dest[2];
432             lastb = dest[3];
433             upperlasta = old[0];
434             upperlastr = old[1];
435             upperlastg = old[2];
436             upperlastb = old[3];
437             dest+=4;
438             old+=4;
439             src+=4;
440         }
441     }    
442 }
443
444 EXPORT int getPNGdimensions(const char*sname, int*destwidth, int*destheight)
445 {
446     FILE*fi;
447     struct png_header header;
448     if ((fi = fopen(sname, "rb")) == NULL) {
449         fprintf(stderr, "Couldn't open %s\n", sname);
450         return 0;
451     }
452     if(!png_read_header(fi, &header)) {
453         return 0;
454     }
455
456     *destwidth = header.width;
457     *destheight = header.height;
458     return 1;
459 }
460
461 EXPORT int getPNG(const char*sname, int*destwidth, int*destheight, unsigned char**destdata)
462 {
463     char tagid[4];
464     int len;
465     unsigned char*data;
466     unsigned char*imagedata;
467     unsigned char*zimagedata=0;
468     unsigned long int imagedatalen;
469     unsigned long int zimagedatalen=0;
470     unsigned char*palette = 0;
471     int palettelen = 0;
472     unsigned char*alphapalette = 0;
473     int alphapalettelen = 0;
474     struct png_header header;
475     int bypp;
476     unsigned char*data2 = 0;
477     unsigned char alphacolor[3];
478     int hasalphacolor=0;
479
480     FILE *fi;
481     unsigned char *scanline;
482
483     if ((fi = fopen(sname, "rb")) == NULL) {
484         printf("Couldn't open %s\n", sname);
485         return 0;
486     }
487
488     if(!png_read_header(fi, &header)) {
489         fclose(fi);
490         return 0;
491     }
492
493     if(header.mode == 3 || header.mode == 0) bypp = 1;
494     else if(header.mode == 4) bypp = 2;
495     else if(header.mode == 2) bypp = 3;
496     else if(header.mode == 6) bypp = 4;
497     else {
498         printf("ERROR: mode:%d\n", header.mode);
499         return 0;
500     }
501
502     imagedatalen = bypp * header.width * header.height + 65536;
503     imagedata = (unsigned char*)malloc(imagedatalen);
504
505     fseek(fi,8,SEEK_SET);
506     while(!feof(fi))
507     {
508         if(!png_read_chunk(&tagid, &len, &data, fi))
509             break;
510         if(!strncmp(tagid, "IEND", 4)) {
511             break;
512         }
513         if(!strncmp(tagid, "PLTE", 4)) {
514             palette = data;
515             palettelen = len/3;
516             data = 0; //don't free data
517             //printf("%d colors in palette\n", palettelen);
518         }
519         if(!strncmp(tagid, "tRNS", 4)) {
520             if(header.mode == 3) {
521                 alphapalette = data;
522                 alphapalettelen = len;
523                 data = 0; //don't free data
524                 //printf("found %d alpha colors\n", alphapalettelen);
525             } else if(header.mode == 0 || header.mode == 2) {
526                 int t;
527                 if(header.mode == 2) {
528                     alphacolor[0] = data[1];
529                     alphacolor[1] = data[3];
530                     alphacolor[2] = data[5];
531                 } else {
532                     alphacolor[0] = alphacolor[1] = alphacolor[2] = data[1];
533                 }
534                 hasalphacolor = 1;
535             }
536         }
537         if(!strncmp(tagid, "IDAT", 4)) {
538             if(!zimagedata) {
539                 zimagedatalen = len;
540                 zimagedata = (unsigned char*)malloc(len);
541                 memcpy(zimagedata,data,len);
542             } else {
543                 zimagedata = (unsigned char*)realloc(zimagedata, zimagedatalen+len);
544                 memcpy(&zimagedata[zimagedatalen], data, len);
545                 zimagedatalen += len;
546             }
547         }
548         if(!strncmp(tagid, "tEXt", 4)) {
549             /*int t;
550             printf("Image Text: ");
551             for(t=0;t<len;t++) {
552                 if(data[t]>=32 && data[t]<128)
553                     printf("%c", data[t]);
554                 else
555                     printf("?");
556             }
557             printf("\n");*/
558         }
559         if(data) {
560             free(data); data=0;
561         }
562     }
563     
564     if(!zimagedata || uncompress(imagedata, &imagedatalen, zimagedata, zimagedatalen) != Z_OK) {
565         printf("Couldn't uncompress %s!\n", sname);
566         if(zimagedata)
567             free(zimagedata);
568         return 0;
569     }
570     free(zimagedata);
571     fclose(fi);
572
573     *destwidth = header.width;
574     *destheight = header.height;
575         
576     data2 = (unsigned char*)malloc(header.width*header.height*4);
577
578     if(header.mode == 4)
579     {
580         int i,s=0;
581         int x,y;
582         int pos=0;
583         unsigned char* old= (unsigned char*)malloc(header.width*2);
584         memset(old, 0, header.width*2);
585         *destdata = data2;
586         for(y=0;y<header.height;y++) {
587             int mode = imagedata[pos++]; //filter mode
588             unsigned char*src;
589             unsigned char*dest;
590             int x;
591             dest = &data2[(y*header.width)*4];
592
593             if(header.bpp == 8) {
594                 /* one byte per pixel */
595                 src = &imagedata[pos];
596                 pos+=header.width*2;
597             } else {
598                 /* not implemented yet */
599                 fprintf(stderr, "ERROR: mode=4 bpp:%d\n", header.bpp);
600                 free(data2);
601                 return 0;
602             }
603
604             applyfilter2(mode, src, old, dest, header.width);
605             memcpy(old, dest, header.width*2);
606
607             for(x=header.width-1;x>=0;x--) {
608                 unsigned char gray = dest[x*2+0];
609                 unsigned char alpha = dest[x*2+1];
610                 dest[x*4+0] = alpha;
611                 dest[x*4+1] = gray;
612                 dest[x*4+2] = gray;
613                 dest[x*4+3] = gray;
614             }
615         }
616         free(old);
617         free(imagedata);
618     } else if(header.mode == 6 || header.mode == 2) {
619         int i,s=0;
620         int x,y;
621         int pos=0;
622         *destdata = data2;
623         
624         unsigned char* firstline = malloc(header.width*4);
625         memset(firstline,0,header.width*4);
626         for(y=0;y<header.height;y++) {
627             int mode = imagedata[pos++]; //filter mode
628             unsigned char*src;
629             unsigned char*dest;
630             unsigned char*old;
631             dest = &data2[(y*header.width)*4];
632
633             if(header.bpp == 8)
634             {
635                 /* one byte per pixel */
636                 src = &imagedata[pos];
637                 pos+=header.width*(header.mode==6?4:3);
638             } else {
639                 /* not implemented yet */
640                 fprintf(stderr, "ERROR: bpp:%d\n", header.bpp);
641                 free(data2);
642                 return 0;
643             }
644
645             if(!y) {
646                 old = firstline;
647             } else {
648                 old = &data2[(y-1)*header.width*4];
649             }
650             if(header.mode == 6) { 
651                 png_inverse_filter_32(mode, src, old, dest, header.width);
652             } else { // header.mode = 2
653                 applyfilter3(mode, src, old, dest, header.width);
654                 /* replace alpha color */
655                 if(hasalphacolor) {
656                     int x;
657                     for(x=0;x<header.width;x++) {
658                         if(dest[x*4+1] == alphacolor[0] &&
659                            dest[x*4+2] == alphacolor[1] &&
660                            dest[x*4+3] == alphacolor[2]) {
661                             *(u32*)&dest[x*4] = 0;
662                         }
663                     }
664                 }
665             }
666         }
667         free(firstline);
668         free(imagedata);
669     } else if(header.mode == 0 || header.mode == 3) {
670         COL*rgba = 0;
671         unsigned char*tmpline = (unsigned char*)malloc(header.width+1);
672         unsigned char*destline = (unsigned char*)malloc(header.width+1);
673         int i,x,y;
674         int pos=0;
675         
676         *destdata = data2;
677         
678         if(header.mode == 0) { // grayscale palette
679             int mult = (0x1ff>>header.bpp);
680             palettelen = 1<<header.bpp;
681             rgba = (COL*)malloc(palettelen*sizeof(COL));
682             for(i=0;i<palettelen;i++) {
683                 rgba[i].a = 255;
684                 rgba[i].r = i*mult;
685                 rgba[i].g = i*mult;
686                 rgba[i].b = i*mult;
687                 if(hasalphacolor) {
688                     if(rgba[i].r == alphacolor[0])
689                         rgba[i].a = 0;
690                 }
691             }
692         } else {
693             if(!palette) {
694                 fprintf(stderr, "Error: No palette found!\n");
695                 exit(1);
696             }
697             rgba = (COL*)malloc(palettelen*4);
698             /* 24->32 bit conversion */
699             for(i=0;i<palettelen;i++) {
700                 rgba[i].r = palette[i*3+0];
701                 rgba[i].g = palette[i*3+1];
702                 rgba[i].b = palette[i*3+2];
703                 if(alphapalette && i<alphapalettelen) {
704                     rgba[i].a = alphapalette[i];
705                     /*rgba[i].r = ((int)rgba[i].r*rgba[i].a)/255;
706                     rgba[i].g = ((int)rgba[i].g*rgba[i].a)/255;
707                     rgba[i].b = ((int)rgba[i].b*rgba[i].a)/255;*/
708                 } else {
709                     rgba[i].a = 255;
710                 }
711                 if(hasalphacolor) {
712                     if(rgba[i].r == alphacolor[0] &&
713                        rgba[i].g == alphacolor[1] &&
714                        rgba[i].b == alphacolor[2])
715                         rgba[i].a = 0;
716                 }
717             }
718         }
719
720         for(y=0;y<header.height;y++) {
721             int mode = imagedata[pos++]; //filter mode
722             int x;
723             unsigned char*old;
724             unsigned char*src;
725             src = &imagedata[pos];
726             if(header.bpp == 8) {
727                 pos+=header.width;
728             } else {
729                 int x,s=0;
730                 int bitpos = 0;
731                 u32 v = (1<<header.bpp)-1;
732                 for(x=0;x<header.width;x++) {
733                     u32 r = src[s/8]<<8 | 
734                             src[s/8+1];
735                     int t;
736                     tmpline[x] = (r>>(16-header.bpp-(s&7)))&v;
737                     s+=header.bpp;
738                 }
739                 src = tmpline;
740                 pos+=(header.width*header.bpp+7)/8;
741             }
742
743             if(!y) {
744                 memset(destline,0,header.width);
745                 old = &destline[y*header.width];
746             } else {
747                 old = tmpline;
748             }
749             applyfilter1(mode, src, old, destline, header.width);
750             memcpy(tmpline,destline,header.width);
751             for(x=0;x<header.width;x++) {
752                 *(COL*)&data2[y*header.width*4+x*4+0] = rgba[destline[x]];
753             }
754         }
755         free(tmpline);
756         free(destline);
757         free(rgba);
758         free(imagedata);
759     } else {
760         printf("expected PNG mode to be 2, 3 or 6 (is:%d)\n", header.mode);
761         return 0;
762     }
763
764     return 1;
765 }
766
767 static char hasAlpha(unsigned char*_image, int size)
768 {
769     COL*image = (COL*)_image;
770     int t;
771     for(t=0;t<size;t++) {
772         if(image[t].a!=255)
773             return 1;
774     }
775     return 0;
776 }
777
778 typedef struct {
779     u32 num;
780     u32 color;
781 } colornum_t;
782
783 static int compare_colors(const void*_c1, const void*_c2) {
784     colornum_t*c1 = (colornum_t*)_c1;
785     colornum_t*c2 = (colornum_t*)_c2;
786     return c2->num - c1->num;
787 }
788
789 static colornum_t* getColors(COL*image, int size, int*num)
790 {
791     unsigned char*colexists = malloc((256*256*256)/8);
792     memset(colexists, 0, (256*256*256)/8);
793     int t;
794     int count=0;
795
796     /* find all different colors in the image */
797     for(t=0;t<size;t++) {
798         int index = (image[t].r)|(image[t].g)<<8|(image[t].b)<<16;
799         if(!(colexists[index/8]&(1<<(index&7)))) {
800             count++;
801             colexists[index/8]|=(1<<(index&7));
802         }
803     }
804     
805     /* now store them in an array */
806     colornum_t*colors=(colornum_t*)malloc(sizeof(colornum_t)*count);
807     int pos=0;
808     for(t=0;t<256*256*256;t++) {
809         if(colexists[t/8]&(1<<(t&7))) {
810             colors[pos].color = t;
811             colors[pos].num = 0;
812             pos++;
813         }
814     }
815
816     /* next, count how often each color occurs */
817     for(t=0;t<size;t++) {
818         int col = (image[t].r)|(image[t].g)<<8|(image[t].b)<<16;
819         int min,max,i,l;
820         for(min=0, max=count, i=count/2, l=count; i != l; l=i,i=(min+max)/2) {
821             // binary search
822             if(colors[i].color >= col) max=i;
823             else min=i+1;
824         }
825         assert(colors[i].color==col);
826         colors[i].num++;
827     }
828     free(colexists);
829     *num = count;
830     return colors;
831 }
832
833 static void getOptimalPalette(COL*image, int size, int palettesize, COL*palette)
834 {
835     int num;
836     memset(palette, 0, sizeof(COL)*256);
837     colornum_t*colors = getColors(image, size, &num);
838
839     assert(palettesize<=256);
840
841     qsort(colors, num, sizeof(colornum_t), compare_colors);
842
843     if(num<=palettesize) {
844         /* if there are not more than palettesize different colors in 
845            the image anyway, we are done */
846         int t;
847         for(t=0;t<num;t++) {
848             palette[t].r = colors[t].color;
849             palette[t].g = colors[t].color>>8;
850             palette[t].b = colors[t].color>>16;
851             palette[t].a = 255;
852         }
853         return;
854     }
855
856     if(num>2048) {
857         /* if there are too many different colors, pick the ones that
858            occur most often */
859         num = 2048;
860     }
861
862     colornum_t*centers = malloc(sizeof(colornum_t)*palettesize);
863     int t;
864     for(t=0;t<palettesize;t++) {
865         centers[t].color = colors[t].color;
866     }
867     unsigned char*belongsto = (unsigned char*)malloc(num);
868     memset(belongsto, 0, num);
869     /* do a k-means clustering on the colors */
870     char change = 1;
871     int tries = 0;
872     while(change) {
873         if(tries++ >= (palettesize+num)*2) {
874             fprintf(stderr, "Warning: didn't find optimal palette\n");
875             break;
876         }
877         change = 0;
878         int s,t;
879         for(s=0;s<palettesize;s++) {
880             centers[s].num = 0;
881         }
882         for(t=0;t<num;t++) {
883             int best=0x7fffffff;
884             int bestpos=0;
885             for(s=0;s<palettesize;s++) {
886                 int distance = 0;
887                 distance += abs((centers[s].color>>0&0xff) - (colors[t].color>>0&0xff));
888                 distance += abs((centers[s].color>>8&0xff) - (colors[t].color>>8&0xff));
889                 distance += abs((centers[s].color>>16&0xff) - (colors[t].color>>16&0xff));
890                 distance *= colors[t].num;
891                 if(distance<best) {
892                     best = distance;
893                     bestpos = s;
894                 }
895             }
896             if(bestpos!=belongsto[t])
897                 change = 1;
898             belongsto[t] = bestpos;
899         }
900         for(s=0;s<palettesize;s++) {
901             int r=0;
902             int g=0;
903             int b=0;
904             int count=0;
905             for(t=0;t<num;t++) {
906                 if(belongsto[t]==s) {
907                     r += ((colors[t].color>>0)&0xff)*colors[t].num;
908                     g += ((colors[t].color>>8)&0xff)*colors[t].num;
909                     b += ((colors[t].color>>16)&0xff)*colors[t].num;
910                     count+=colors[t].num;
911                 }
912             }
913             if(!count) {
914                 int random = rand()%num;
915                 centers[s].color = colors[random].color;
916                 centers[s].num = 0;
917                 change = 1;
918             } else {
919                 r /= count;
920                 g /= count;
921                 b /= count;
922                 centers[s].color = r|g<<8|b<<16;
923                 centers[s].num = count;
924             }
925         }
926     }
927     free(belongsto);
928     free(colors);
929     for(t=0;t<palettesize;t++) {
930         palette[t].r = centers[t].color;
931         palette[t].g = centers[t].color>>8;
932         palette[t].b = centers[t].color>>16;
933         palette[t].a = 255;
934     }
935     free(centers);
936 }
937
938 static int sqr(const int x) {return x*x;}
939
940 static void png_quantize_image(unsigned char*_image, int size, int numcolors, unsigned char**newimage, COL*palette) 
941 {
942     COL*image = (COL*)_image;
943     getOptimalPalette(image, size, numcolors, palette);
944     *newimage = (unsigned char*)malloc(size);
945     int t;
946     for(t=0;t<size;t++) {
947         int best=0x7fffffff;
948         int bestcol = 0;
949         int s;
950         for(s=0;s<numcolors;s++) {
951             int distance = 0;
952             distance += sqr((palette[s].r) - (image[t].r))*5;
953             distance += sqr((palette[s].g) - (image[t].g))*6;
954             distance += sqr((palette[s].b) - (image[t].b))*4;
955             if(distance<best) {
956                 best = distance;
957                 bestcol = s;
958             }
959         }
960         (*newimage)[t] = bestcol;
961     }
962 }
963
964 static u32 mycrc32;
965
966 static u32*crc32_table = 0;
967 static void make_crc32_table(void)
968 {
969   int t;
970   if(crc32_table) 
971       return;
972   crc32_table = (u32*)malloc(1024);
973
974   for (t = 0; t < 256; t++) {
975     u32 c = t;
976     int s;
977     for (s = 0; s < 8; s++) {
978       c = (0xedb88320L*(c&1)) ^ (c >> 1);
979     }
980     crc32_table[t] = c;
981   }
982 }
983 static inline void png_write_byte(FILE*fi, unsigned char byte)
984 {
985     fwrite(&byte,1,1,fi);
986     mycrc32 = crc32_table[(mycrc32 ^ byte) & 0xff] ^ (mycrc32 >> 8);
987 }
988 static long png_start_chunk(FILE*fi, char*type, int len)
989 {
990     unsigned char mytype[4]={0,0,0,0};
991     unsigned char mylen[4];
992     long filepos;
993     mylen[0] = len>>24;
994     mylen[1] = len>>16;
995     mylen[2] = len>>8;
996     mylen[3] = len;
997     memcpy(mytype,type,strlen(type));
998     filepos = ftell(fi);
999     fwrite(&mylen, 4, 1, fi);
1000     mycrc32=0xffffffff;
1001     png_write_byte(fi,mytype[0]);
1002     png_write_byte(fi,mytype[1]);
1003     png_write_byte(fi,mytype[2]);
1004     png_write_byte(fi,mytype[3]);
1005     return filepos;
1006 }
1007 static void png_patch_len(FILE*fi, int pos, int len)
1008 {
1009     unsigned char mylen[4];
1010     long filepos;
1011     mylen[0] = len>>24;
1012     mylen[1] = len>>16;
1013     mylen[2] = len>>8;
1014     mylen[3] = len;
1015     fseek(fi, pos, SEEK_SET);
1016     fwrite(&mylen, 4, 1, fi);
1017     fseek(fi, 0, SEEK_END);
1018 }
1019 static void png_write_bytes(FILE*fi, unsigned char*bytes, int len)
1020 {
1021     int t;
1022     for(t=0;t<len;t++)
1023         png_write_byte(fi,bytes[t]);
1024 }
1025 static void png_write_dword(FILE*fi, u32 dword)
1026 {
1027     png_write_byte(fi,dword>>24);
1028     png_write_byte(fi,dword>>16);
1029     png_write_byte(fi,dword>>8);
1030     png_write_byte(fi,dword);
1031 }
1032 static void png_end_chunk(FILE*fi)
1033 {
1034     u32 tmp = mycrc32^0xffffffff;
1035     unsigned char tmp2[4];
1036     tmp2[0] = tmp>>24;
1037     tmp2[1] = tmp>>16;
1038     tmp2[2] = tmp>>8;
1039     tmp2[3] = tmp;
1040     fwrite(&tmp2,4,1,fi);
1041 }
1042
1043 #define ZLIB_BUFFER_SIZE 16384
1044
1045 static long compress_line(z_stream*zs, Bytef*line, int len, FILE*fi)
1046 {
1047     long size = 0;
1048     zs->next_in = line;
1049     zs->avail_in = len;
1050
1051     while(1) {
1052         int ret = deflate(zs, Z_NO_FLUSH);
1053         if (ret != Z_OK) {
1054             fprintf(stderr, "error in deflate(): %s", zs->msg?zs->msg:"unknown");
1055             return 0;
1056         }
1057         if(zs->avail_out != ZLIB_BUFFER_SIZE) {
1058             int consumed = ZLIB_BUFFER_SIZE - zs->avail_out;
1059             size += consumed;
1060             png_write_bytes(fi, zs->next_out - consumed , consumed);
1061             zs->next_out = zs->next_out - consumed;
1062             zs->avail_out = ZLIB_BUFFER_SIZE;
1063         }
1064         if(!zs->avail_in) {
1065             break;
1066         }
1067     }
1068     return size;
1069 }
1070
1071 static int test_line(z_stream*zs_orig, Bytef*line, int linelen)
1072 {
1073     z_stream zs;
1074     int ret = deflateCopy(&zs, zs_orig);
1075     if(ret != Z_OK) {
1076         fprintf(stderr, "Couldn't copy stream\n");
1077         return 0;
1078     }
1079
1080     zs.next_in = line;
1081     zs.avail_in = linelen;
1082
1083     long size = 0;
1084
1085     int mode = Z_SYNC_FLUSH;
1086     while(1) {
1087         int ret = deflate(&zs, mode);
1088         if (ret != Z_OK && ret != Z_STREAM_END) {
1089             fprintf(stderr, "error in deflate(): %s (mode %s, %d bytes remaining)\n", zs.msg?zs.msg:"unknown", 
1090                     mode==Z_SYNC_FLUSH?"Z_SYNC_FLUSH":"Z_FINISH", zs.avail_in);
1091             return 0;
1092         }
1093         if(zs.avail_out != ZLIB_BUFFER_SIZE) {
1094             int consumed = ZLIB_BUFFER_SIZE - zs.avail_out;
1095             size += consumed;
1096             zs.next_out = zs.next_out - consumed;
1097             zs.avail_out = ZLIB_BUFFER_SIZE;
1098         }
1099         if (ret == Z_STREAM_END) {
1100             break;
1101         }
1102         if(!zs.avail_in) {
1103             mode = Z_FINISH;
1104         }
1105     }
1106     ret = deflateEnd(&zs);
1107     if (ret != Z_OK) {
1108         fprintf(stderr, "error in deflateEnd(): %s\n", zs.msg?zs.msg:"unknown");
1109         return 0;
1110     }
1111     return size;
1112 }
1113
1114 static int finishzlib(z_stream*zs, FILE*fi)
1115 {
1116     int size = 0;
1117     int ret;
1118     while(1) {
1119         ret = deflate(zs, Z_FINISH);
1120         if (ret != Z_OK &&
1121             ret != Z_STREAM_END) {
1122             fprintf(stderr, "error in deflate(finish): %s\n", zs->msg?zs->msg:"unknown");
1123             return 0;
1124         }
1125
1126         if(zs->avail_out != ZLIB_BUFFER_SIZE) {
1127             int consumed = ZLIB_BUFFER_SIZE - zs->avail_out;
1128             size += consumed;
1129             png_write_bytes(fi, zs->next_out - consumed , consumed);
1130             zs->next_out = zs->next_out - consumed;
1131             zs->avail_out = ZLIB_BUFFER_SIZE;
1132         }
1133         if (ret == Z_STREAM_END) {
1134             break;
1135         }
1136     }
1137     ret = deflateEnd(zs);
1138     if (ret != Z_OK) {
1139         fprintf(stderr, "error in deflateEnd(): %s\n", zs->msg?zs->msg:"unknown");
1140         return 0;
1141     }
1142     return size;
1143 }
1144
1145 static inline u32 color_hash(COL*col)
1146 {
1147     u32 col32 = *(u32*)col;
1148     u32 hash = (col32 >> 17) ^ col32;
1149     hash ^= ((hash>>8) + 1) ^ hash;
1150     return hash;
1151 }
1152
1153 static int png_get_number_of_palette_entries(COL*img, int width, int height, COL*palette, char*has_alpha)
1154 {
1155     int len = width*height;
1156     int t;
1157     int palsize = 0;
1158     int size[256];
1159     int palette_overflow = 0;
1160     u32 lastcol32 = 0;
1161     
1162     memset(size, 0, sizeof(size));
1163
1164     u32*pal = (u32*)malloc(65536*sizeof(u32));
1165     int*count = (int*)malloc(65536*sizeof(int));
1166
1167     assert(sizeof(COL)==sizeof(u32));
1168     assert(width && height);
1169
1170     lastcol32 = (*(u32*)&img[0])^0xffffffff; // don't match
1171
1172     for(t=0;t<len;t++) {
1173         u32 col32 = *(u32*)&img[t];
1174         if(col32 == lastcol32)
1175             continue;
1176         
1177         if(img[t].a!=255)
1178             *has_alpha=1;
1179         int i;
1180         
1181         u32 hash = color_hash(&img[t])&255;
1182
1183         int csize = size[hash];
1184         u32*cpal = &pal[hash*256];
1185         int*ccount = &count[hash*256];
1186         for(i=0;i<csize;i++) {
1187             if(col32 == cpal[i]) {
1188                 ccount[i]++;
1189                 break;
1190             }
1191         }
1192         if(i==csize) {
1193             if(palsize==256) {
1194                 palette_overflow = 1;
1195                 break;
1196             }
1197             count[size[hash]] = 1;
1198             cpal[size[hash]++] = col32;
1199             palsize++;
1200         }
1201         lastcol32 = col32;
1202     }
1203     if(palette_overflow) {
1204         free(pal);
1205         *has_alpha=1;
1206         return width*height;
1207     }
1208     if(palette) {
1209         int i = 0;
1210         int occurences[256];
1211         for(t=0;t<256;t++) {
1212             int s;
1213             int csize = size[t];
1214             u32* cpal = &pal[t*256];
1215             int* ccount = &count[t*256];
1216             for(s=0;s<csize;s++) {
1217                 occurences[i] = ccount[s];
1218                 palette[i++] = *(COL*)(&cpal[s]);
1219             }
1220         }
1221         assert(i==palsize);
1222         int j;
1223         for(i=0;i<palsize-1;i++) {
1224             for(j=i+1;j<palsize;j++) {
1225                 if(occurences[j] < occurences[i]) {
1226                     int o = occurences[i];
1227                     COL c = palette[i];
1228                     occurences[i] = occurences[j];
1229                     palette[i] = palette[j];
1230                     occurences[j] = o;
1231                     palette[j] = c;
1232                 }
1233             }
1234         }
1235     }
1236     free(pal);
1237     free(count);
1238     return palsize;
1239 }
1240
1241 static void png_map_to_palette(COL*src, unsigned char*dest, int size, COL*palette, int palette_size)
1242 {
1243     int t;
1244     int palette_hash[1024];
1245     memset(palette_hash, 0, sizeof(int)*1024);
1246     
1247     for(t=0;t<palette_size;t++) {
1248         u32 hash = color_hash(&palette[t])&1023;
1249         while(palette_hash[hash])
1250             hash = (hash+1)&1023;
1251         palette_hash[hash] = t;
1252     }
1253
1254     for(t=0;t<size;t++) {
1255         u32 hash = color_hash(&src[t]);
1256         int index = 0;
1257         while(1) {
1258             hash&=1023;
1259             index = palette_hash[hash];
1260             if(!memcmp(&palette[index], &src[t], sizeof(COL)))
1261                 break;
1262             hash++;
1263         }
1264         dest[t] = palette_hash[hash];
1265     }
1266 }
1267
1268 static int png_apply_specific_filter_8(int filtermode, unsigned char*dest, unsigned char*src, int width)
1269 {
1270     int pos2 = 0;
1271     int pos = 0;
1272     int srcwidth = width;
1273     int x;
1274     if(filtermode == 0) {
1275         for(x=0;x<width;x++) {
1276             dest[pos2++]=src[pos++]; //alpha
1277         }
1278     } else if(filtermode == 1) {
1279         /* x difference filter */
1280         dest[pos2++]=src[pos++];
1281         for(x=1;x<width;x++) {
1282             dest[pos2++]=src[pos] - src[pos-1];
1283             pos++;
1284         }
1285     } else if(filtermode == 2) {
1286         /* y difference filter */
1287         for(x=0;x<width;x++) {
1288             dest[pos2++]=src[pos+0] - src[pos-srcwidth+0]; //alpha
1289             pos++;
1290         }
1291     } else if(filtermode == 3) {
1292         dest[pos2++]=src[pos+0] - src[pos-srcwidth+0]/2;
1293         pos++;
1294         /* x+y difference filter */
1295         for(x=1;x<width;x++) {
1296             dest[pos2++]=src[pos+0] - (src[pos-1+0] + src[pos-srcwidth+0])/2; //alpha
1297             pos++;
1298         }
1299     } else if(filtermode == 4) {
1300         dest[pos2++]=src[pos+0] - PaethPredictor(0, src[pos-srcwidth+0], 0);
1301         pos++;
1302         /* paeth difference filter */
1303         for(x=1;x<width;x++) {
1304             dest[pos2++]=src[pos+0] - PaethPredictor(src[pos-1+0], src[pos-srcwidth+0], src[pos-1-srcwidth+0]);
1305             pos++;
1306         }
1307     }
1308     return filtermode;
1309 }
1310
1311 static int png_apply_specific_filter_32(int filtermode, unsigned char*dest, unsigned char*src, int width)
1312 {
1313     int pos2 = 0;
1314     int pos = 0;
1315     int srcwidth = width*4;
1316     int x;
1317     if(filtermode == 0) {
1318         for(x=0;x<width;x++) {
1319             dest[pos2++]=src[pos+1];
1320             dest[pos2++]=src[pos+2];
1321             dest[pos2++]=src[pos+3];
1322             dest[pos2++]=src[pos+0]; //alpha
1323             pos+=4;
1324         }
1325     } else if(filtermode == 1) {
1326         /* x difference filter */
1327         dest[pos2++]=src[pos+1];
1328         dest[pos2++]=src[pos+2];
1329         dest[pos2++]=src[pos+3];
1330         dest[pos2++]=src[pos+0];
1331         pos+=4;
1332         for(x=1;x<width;x++) {
1333             dest[pos2++]=src[pos+1] - src[pos-4+1];
1334             dest[pos2++]=src[pos+2] - src[pos-4+2];
1335             dest[pos2++]=src[pos+3] - src[pos-4+3];
1336             dest[pos2++]=src[pos+0] - src[pos-4+0]; //alpha
1337             pos+=4;
1338         }
1339     } else if(filtermode == 2) {
1340         /* y difference filter */
1341         for(x=0;x<width;x++) {
1342             dest[pos2++]=src[pos+1] - src[pos-srcwidth+1];
1343             dest[pos2++]=src[pos+2] - src[pos-srcwidth+2];
1344             dest[pos2++]=src[pos+3] - src[pos-srcwidth+3];
1345             dest[pos2++]=src[pos+0] - src[pos-srcwidth+0]; //alpha
1346             pos+=4;
1347         }
1348     } else if(filtermode == 3) {
1349         dest[pos2++]=src[pos+1] - src[pos-srcwidth+1]/2;
1350         dest[pos2++]=src[pos+2] - src[pos-srcwidth+2]/2;
1351         dest[pos2++]=src[pos+3] - src[pos-srcwidth+3]/2;
1352         dest[pos2++]=src[pos+0] - src[pos-srcwidth+0]/2;
1353         pos+=4;
1354         /* x+y difference filter */
1355         for(x=1;x<width;x++) {
1356             dest[pos2++]=src[pos+1] - (src[pos-4+1] + src[pos-srcwidth+1])/2;
1357             dest[pos2++]=src[pos+2] - (src[pos-4+2] + src[pos-srcwidth+2])/2;
1358             dest[pos2++]=src[pos+3] - (src[pos-4+3] + src[pos-srcwidth+3])/2;
1359             dest[pos2++]=src[pos+0] - (src[pos-4+0] + src[pos-srcwidth+0])/2; //alpha
1360             pos+=4;
1361         }
1362     } else if(filtermode == 4) {
1363         dest[pos2++]=src[pos+1] - PaethPredictor(0, src[pos-srcwidth+1], 0);
1364         dest[pos2++]=src[pos+2] - PaethPredictor(0, src[pos-srcwidth+2], 0);
1365         dest[pos2++]=src[pos+3] - PaethPredictor(0, src[pos-srcwidth+3], 0);
1366         dest[pos2++]=src[pos+0] - PaethPredictor(0, src[pos-srcwidth+0], 0);
1367         pos+=4;
1368         /* paeth difference filter */
1369         for(x=1;x<width;x++) {
1370             dest[pos2++]=src[pos+1] - PaethPredictor(src[pos-4+1], src[pos-srcwidth+1], src[pos-4-srcwidth+1]);
1371             dest[pos2++]=src[pos+2] - PaethPredictor(src[pos-4+2], src[pos-srcwidth+2], src[pos-4-srcwidth+2]);
1372             dest[pos2++]=src[pos+3] - PaethPredictor(src[pos-4+3], src[pos-srcwidth+3], src[pos-4-srcwidth+3]);
1373             dest[pos2++]=src[pos+0] - PaethPredictor(src[pos-4+0], src[pos-srcwidth+0], src[pos-4-srcwidth+0]);
1374             pos+=4;
1375         }
1376     }
1377     return filtermode;
1378 }
1379
1380 static int*num_bits_table = 0;
1381
1382 static void make_num_bits_table()
1383 {
1384     if(num_bits_table) return;
1385     num_bits_table = malloc(sizeof(num_bits_table[0])*256);
1386     int t;
1387     for(t=0;t<256;t++) {
1388         int bits=0;
1389         int v = t;
1390         while(v) {
1391             bits++;
1392             v&=v-1;
1393         }
1394         num_bits_table[t]=bits;
1395     }
1396 }
1397
1398 static int png_find_best_filter(unsigned char*src, int width, int bpp, int y)
1399 {
1400     make_num_bits_table();
1401     
1402     int num_filters = y>0?5:2; //don't apply y-direction filter in first line
1403
1404     int bytes_per_pixel = bpp>>3;
1405     int w = width*bytes_per_pixel;
1406     int back_x = bytes_per_pixel;
1407     int back_y = y?width*bytes_per_pixel:0;
1408
1409     unsigned char*pairs[5];
1410     pairs[0] = calloc(1, 8192);
1411     pairs[1] = calloc(1, 8192);
1412     pairs[2] = calloc(1, 8192);
1413     pairs[3] = calloc(1, 8192);
1414     pairs[4] = calloc(1, 8192);
1415     
1416     unsigned char old[5];
1417     int l = bytes_per_pixel - 1;
1418     old[0] = src[l];
1419     old[1] = src[l];
1420     old[2] = src[l] - src[l-back_y];
1421     old[3] = src[l] - src[l-back_y];
1422     old[4] = src[l] - PaethPredictor(0, src[l-back_y], 0);
1423
1424     int different_pairs[5] = {0,0,0,0,0};
1425
1426     int x;
1427     for(x=bytes_per_pixel;x<w;x++) {
1428         unsigned char dest[5];
1429         dest[0] = src[x];
1430         dest[1] = src[x] - src[x-back_x];
1431         dest[2] = src[x] - src[x-back_y];
1432         dest[3] = src[x] - (src[x-back_x] + src[x-back_y])/2;
1433         dest[4] = src[x] - PaethPredictor(src[x-back_x], src[x-back_y], src[x-back_x-back_y]);
1434
1435         int i;
1436         for(i=0;i<5;i++) {
1437             int v = dest[i]<<8|old[i];
1438             int p = v>>3;
1439             int b = 1<<(v&7);
1440             if(!pairs[i][p]&b) {
1441                 pairs[i][p]|=b;
1442                 different_pairs[i]++;
1443             }
1444         }
1445         memcpy(old, dest, sizeof(old));
1446     }
1447     int f;
1448     int best_nr = 0;
1449     int best_energy = INT_MAX;
1450     for(f=0;f<num_filters;f++) {
1451         int energy = different_pairs[f];
1452         if(energy<best_energy) {
1453             best_nr = f;
1454             best_energy = energy;
1455         }
1456     }
1457     free(pairs[0]);
1458     free(pairs[1]);
1459     free(pairs[2]);
1460     free(pairs[3]);
1461     free(pairs[4]);
1462     return best_nr;
1463 }
1464     
1465     
1466 static int png_apply_filter(unsigned char*dest, unsigned char*src, int width, int y, int bpp)
1467 {
1468     int best_nr = 0;
1469 #if 0
1470     make_num_bits_table();
1471     int num_filters = y>0?5:2; //don't apply y-direction filter in first line
1472     int f;
1473     int best_energy = INT_MAX;
1474     int w = width*(bpp/8);
1475     unsigned char* pairs = malloc(8192);
1476     assert(bpp==8 || bpp==32);
1477     for(f=0;f<num_filters;f++) {
1478         if(bpp==8)
1479             png_apply_specific_filter_8(f, dest, src, width);
1480         else
1481             png_apply_specific_filter_32(f, dest, src, width);
1482         int x;
1483
1484         /* approximation for zlib compressability: test how many different
1485            (byte1,byte2) occur */
1486         memset(pairs, 0, 8192);
1487         int different_pairs = 0;
1488         for(x=0;x<w-1;x++) {
1489             int v = dest[x+1]<<8|dest[x];
1490             int p = v>>3;
1491             int b = 1<<(v&7);
1492             if(!pairs[p]&b) {
1493                 pairs[p]|=b;
1494                 different_pairs ++;
1495             }
1496         }
1497         int energy = different_pairs;
1498         if(energy<best_energy) {
1499             best_nr = f;
1500             best_energy = energy;
1501         }
1502     }
1503     free(pairs);
1504 #else
1505     best_nr = png_find_best_filter(src, width, bpp, y);
1506 #endif
1507     if(bpp==8)
1508         png_apply_specific_filter_8(best_nr, dest, src, width);
1509     else
1510         png_apply_specific_filter_32(best_nr, dest, src, width);
1511     return best_nr;
1512 }
1513
1514 int png_apply_filter_8(unsigned char*dest, unsigned char*src, int width, int y)
1515 {
1516     return png_apply_filter(dest, src, width, y, 8);
1517 }
1518 int png_apply_filter_32(unsigned char*dest, unsigned char*src, int width, int y)
1519 {
1520     return png_apply_filter(dest, src, width, y, 32);
1521 }
1522
1523 EXPORT void savePNG(const char*filename, unsigned char*data, int width, int height, int numcolors)
1524 {
1525     FILE*fi;
1526     int crc;
1527     int t;
1528     unsigned char format;
1529     unsigned char tmp;
1530     unsigned char* data2=0;
1531     unsigned char head[] = {137,80,78,71,13,10,26,10}; // PNG header
1532     int cols;
1533     char alpha = 1;
1534     int pos = 0;
1535     int error;
1536     u32 tmp32;
1537     int bpp;
1538     int ret;
1539     char has_alpha=0;
1540     z_stream zs;
1541     COL palette[256];
1542
1543     make_crc32_table();
1544
1545     if(!numcolors) {
1546         int num = png_get_number_of_palette_entries((COL*)data, width, height, palette, &has_alpha);
1547         if(num<=255) {
1548             //printf("image has %d different colors (alpha=%d)\n", num, has_alpha);
1549             data2 = malloc(width*height);
1550             png_map_to_palette((COL*)data, data2, width*height, palette, num);
1551             data = data2;
1552             bpp = 8;
1553             cols = num;
1554             format = 3;
1555         } else {
1556             bpp = 32;
1557             cols = 0;
1558             format = 5;
1559         }
1560     } else {
1561         bpp = 8;
1562         cols = numcolors;
1563         format = 3;
1564         png_quantize_image(data, width*height, numcolors, &data, palette);
1565     }
1566
1567     fi = fopen(filename, "wb");
1568     if(!fi) {
1569         perror("open");
1570         return;
1571     }
1572     fwrite(head,sizeof(head),1,fi);     
1573
1574     png_start_chunk(fi, "IHDR", 13);
1575      png_write_dword(fi,width);
1576      png_write_dword(fi,height);
1577      png_write_byte(fi,8);
1578      if(format == 3)
1579      png_write_byte(fi,3); //indexed
1580      else if(format == 5 && alpha==0)
1581      png_write_byte(fi,2); //rgb
1582      else if(format == 5 && alpha==1)
1583      png_write_byte(fi,6); //rgba
1584      else return;
1585
1586      png_write_byte(fi,0); //compression mode
1587      png_write_byte(fi,0); //filter mode
1588      png_write_byte(fi,0); //interlace mode
1589     png_end_chunk(fi);
1590
1591     if(format == 3) {
1592         png_start_chunk(fi, "PLTE", cols*3);
1593         for(t=0;t<cols;t++) {
1594             png_write_byte(fi,palette[t].r);
1595             png_write_byte(fi,palette[t].g);
1596             png_write_byte(fi,palette[t].b);
1597         }
1598         png_end_chunk(fi);
1599
1600         if(has_alpha) {
1601             png_start_chunk(fi, "tRNS", cols);
1602             for(t=0;t<cols;t++) {
1603                 png_write_byte(fi,palette[t].a);
1604             }
1605             png_end_chunk(fi);
1606         }
1607     }
1608
1609     long idatpos = png_start_chunk(fi, "IDAT", 0);
1610     
1611     memset(&zs,0,sizeof(z_stream));
1612     Bytef*writebuf = (Bytef*)malloc(ZLIB_BUFFER_SIZE);
1613     zs.zalloc = Z_NULL;
1614     zs.zfree  = Z_NULL;
1615     zs.opaque = Z_NULL;
1616     zs.next_out = writebuf;
1617     zs.avail_out = ZLIB_BUFFER_SIZE;
1618     ret = deflateInit(&zs, Z_BEST_COMPRESSION);
1619     if (ret != Z_OK) {
1620         fprintf(stderr, "error in deflateInit(): %s", zs.msg?zs.msg:"unknown");
1621         return;
1622     }
1623
1624     long idatsize = 0;
1625     {
1626         int x,y;
1627         int bypp = bpp/8;
1628         int srcwidth = width * bypp;
1629         int linelen = 1 + srcwidth;
1630         if(bypp==2) 
1631             linelen = 1 + ((srcwidth+1)&~1);
1632         else if(bypp==3) 
1633             linelen = 1 + ((srcwidth+2)/3)*3;
1634         else if(bypp==4) 
1635             linelen = 1 + ((srcwidth+3)&~3);
1636         unsigned char* line = (unsigned char*)malloc(linelen);
1637         memset(line, 0, linelen);
1638 #if 0
1639         unsigned char* bestline = (unsigned char*)malloc(linelen);
1640         memset(bestline, 0, linelen);
1641         for(y=0;y<height;y++)
1642         {
1643             int filtermode;
1644             int bestsize = 0x7fffffff;
1645             for(filtermode=0;filtermode<=4;filtermode++) {
1646                 if(!y && filtermode>=2)
1647                     continue; // don't do y direction filters in the first row
1648                 
1649                 line[0]=filtermode; //filter type
1650                 if(bpp==8)
1651                     png_apply_specific_filter_8(filtermode, line+1, &data[y*srcwidth], width);
1652                 else
1653                     png_apply_specific_filter_32(filtermode, line+1, &data[y*srcwidth], width);
1654
1655                 int size = test_line(&zs, line, linelen);
1656                 if(size < bestsize) {
1657                     memcpy(bestline, line, linelen);
1658                     bestsize = size;
1659                 }
1660             }
1661             idatsize += compress_line(&zs, bestline, linelen, fi);
1662         }
1663         free(bestline);
1664 #else
1665         for(y=0;y<height;y++) {
1666             if(bpp==8)
1667                 line[0] = png_apply_filter_8(line+1, &data[y*srcwidth], width, y);
1668             else
1669                 line[0] = png_apply_filter_32(line+1, &data[y*srcwidth], width, y);
1670
1671             idatsize += compress_line(&zs, line, linelen, fi);
1672         }
1673 #endif
1674         free(line);
1675     }
1676     idatsize += finishzlib(&zs, fi);
1677     png_patch_len(fi, idatpos, idatsize);
1678     png_end_chunk(fi);
1679
1680     png_start_chunk(fi, "IEND", 0);
1681     png_end_chunk(fi);
1682
1683     free(writebuf);
1684     if(data2)
1685         free(data2);
1686     fclose(fi);
1687 }
1688
1689 EXPORT void writePNG(const char*filename, unsigned char*data, int width, int height)
1690 {
1691     savePNG(filename, data, width, height, 0);
1692 }
1693 EXPORT void writePalettePNG(const char*filename, unsigned char*data, int width, int height)
1694 {
1695     savePNG(filename, data, width, height, 256);
1696 }