3 Copyright (c) 2003/2004/2005 Matthias Kramm <kramm@quiss.org>
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.
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.
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 */
32 #ifdef PNG_INLINE_EXPORTS
42 unsigned char a,r,g,b;
45 static int png_read_chunk(char (*head)[4], int*destlen, unsigned char**destdata, FILE*fi)
48 unsigned char blen[4];
49 if(destlen) *destlen=0;
50 if(destdata) *destdata=0;
51 if(!fread(&blen, 4, 1, fi)) {
54 if(!fread(head, 4, 1, fi)) {
57 len = blen[0]<<24|blen[1]<<16|blen[2]<<8|blen[3];
58 if(destlen) *destlen = len;
63 *destdata = (unsigned char*)malloc(len);
64 if(!fread(*destdata, len, 1, fi)) {
66 if(destlen) *destlen=0;
70 fseek(fi, 4, SEEK_CUR);
73 fseek(fi, len+4, SEEK_CUR);
78 static unsigned int png_get_dword(FILE*fi)
83 return b[0]<<24|b[1]<<16|b[2]<<8|b[3];
94 static int png_read_header(FILE*fi, struct png_header*header)
99 unsigned char head[8] = {137,80,78,71,13,10,26,10};
100 unsigned char head2[8];
103 if(strncmp((const char*)head,(const char*)head2,4))
104 return 0; // not a png file
106 while(png_read_chunk(&id, &len, &data, fi))
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)) {
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)
117 c = data[10]; // compression mode (0)
118 f = data[11]; // filter mode (0)
119 i = data[12]; // interlace mode (0)
121 if(b!=0 && b!=4 && b!=2 && b!=3 && b!=6) {
122 fprintf(stderr, "Image mode %d not supported!\n", b);
125 if(a!=8 && (b==2 || b==6)) {
126 printf("Bpp %d in mode %d not supported!\n", b, a);
130 printf("Compression mode %d not supported!\n", c);
134 printf("Filter mode %d not supported!\n", f);
138 printf("Interlace mode %d not supported!\n", i);
141 //printf("%dx%d bpp:%d mode:%d comp:%d filter:%d interlace:%d\n",header->width, header->height, a,b,c,f,i);
152 typedef unsigned char byte;
153 #define ABS(a) ((a)>0?(a):(-(a)))
154 static inline byte PaethPredictor (byte a,byte b,byte c)
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
161 // return nearest of a,b,c,
162 // breaking ties in order a,b,c.
163 if (pa <= pb && pa <= pc)
170 static void applyfilter1(int mode, unsigned char*src, unsigned char*old, unsigned char*dest, int width)
173 unsigned char last=0;
174 unsigned char upperlast=0;
177 for(x=0;x<width;x++) {
184 for(x=0;x<width;x++) {
192 for(x=0;x<width;x++) {
200 for(x=0;x<width;x++) {
201 *dest = *src+(*old+last)/2;
209 for(x=0;x<width;x++) {
210 *dest = *src+PaethPredictor(last,*old,upperlast);
221 static void applyfilter2(int mode, unsigned char*src, unsigned char*old, unsigned char*dest, int width)
224 unsigned char lasta=0;
225 unsigned char lastb=0;
226 unsigned char upperlasta=0;
227 unsigned char upperlastb=0;
230 for(x=0;x<width;x++) {
238 for(x=0;x<width;x++) {
239 dest[0] = src[0]+lasta;
240 dest[1] = src[1]+lastb;
248 for(x=0;x<width;x++) {
249 dest[0] = src[0]+old[0];
250 dest[1] = src[1]+old[1];
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;
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);
283 /* also performs 24 bit conversion! */
284 static void applyfilter3(int mode, unsigned char*src, unsigned char*old, unsigned char*dest, int width)
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;
295 for(x=0;x<width;x++) {
305 for(x=0;x<width;x++) {
307 dest[1] = src[0]+lastr;
308 dest[2] = src[1]+lastg;
309 dest[3] = src[2]+lastb;
318 for(x=0;x<width;x++) {
320 dest[1] = src[0]+old[1];
321 dest[2] = src[1]+old[2];
322 dest[3] = src[2]+old[3];
329 for(x=0;x<width;x++) {
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;
343 for(x=0;x<width;x++) {
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);
361 void png_inverse_filter_32(int mode, unsigned char*src, unsigned char*old, unsigned char*dest, int width)
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;
374 for(x=0;x<width;x++) {
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;
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];
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;
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);
444 EXPORT int getPNGdimensions(const char*sname, int*destwidth, int*destheight)
447 struct png_header header;
448 if ((fi = fopen(sname, "rb")) == NULL) {
449 fprintf(stderr, "Couldn't open %s\n", sname);
452 if(!png_read_header(fi, &header)) {
456 *destwidth = header.width;
457 *destheight = header.height;
461 EXPORT int getPNG(const char*sname, int*destwidth, int*destheight, unsigned char**destdata)
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;
472 unsigned char*alphapalette = 0;
473 int alphapalettelen = 0;
474 struct png_header header;
476 unsigned char*data2 = 0;
477 unsigned char alphacolor[3];
481 unsigned char *scanline;
483 if ((fi = fopen(sname, "rb")) == NULL) {
484 printf("Couldn't open %s\n", sname);
488 if(!png_read_header(fi, &header)) {
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;
498 printf("ERROR: mode:%d\n", header.mode);
502 imagedatalen = bypp * header.width * header.height + 65536;
503 imagedata = (unsigned char*)malloc(imagedatalen);
505 fseek(fi,8,SEEK_SET);
508 if(!png_read_chunk(&tagid, &len, &data, fi))
510 if(!strncmp(tagid, "IEND", 4)) {
513 if(!strncmp(tagid, "PLTE", 4)) {
516 data = 0; //don't free data
517 //printf("%d colors in palette\n", palettelen);
519 if(!strncmp(tagid, "tRNS", 4)) {
520 if(header.mode == 3) {
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) {
527 if(header.mode == 2) {
528 alphacolor[0] = data[1];
529 alphacolor[1] = data[3];
530 alphacolor[2] = data[5];
532 alphacolor[0] = alphacolor[1] = alphacolor[2] = data[1];
537 if(!strncmp(tagid, "IDAT", 4)) {
540 zimagedata = (unsigned char*)malloc(len);
541 memcpy(zimagedata,data,len);
543 zimagedata = (unsigned char*)realloc(zimagedata, zimagedatalen+len);
544 memcpy(&zimagedata[zimagedatalen], data, len);
545 zimagedatalen += len;
548 if(!strncmp(tagid, "tEXt", 4)) {
550 printf("Image Text: ");
552 if(data[t]>=32 && data[t]<128)
553 printf("%c", data[t]);
564 if(!zimagedata || uncompress(imagedata, &imagedatalen, zimagedata, zimagedatalen) != Z_OK) {
565 printf("Couldn't uncompress %s!\n", sname);
573 *destwidth = header.width;
574 *destheight = header.height;
576 data2 = (unsigned char*)malloc(header.width*header.height*4);
583 unsigned char* old= (unsigned char*)malloc(header.width*2);
584 memset(old, 0, header.width*2);
586 for(y=0;y<header.height;y++) {
587 int mode = imagedata[pos++]; //filter mode
591 dest = &data2[(y*header.width)*4];
593 if(header.bpp == 8) {
594 /* one byte per pixel */
595 src = &imagedata[pos];
598 /* not implemented yet */
599 fprintf(stderr, "ERROR: mode=4 bpp:%d\n", header.bpp);
604 applyfilter2(mode, src, old, dest, header.width);
605 memcpy(old, dest, header.width*2);
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];
618 } else if(header.mode == 6 || header.mode == 2) {
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
631 dest = &data2[(y*header.width)*4];
635 /* one byte per pixel */
636 src = &imagedata[pos];
637 pos+=header.width*(header.mode==6?4:3);
639 /* not implemented yet */
640 fprintf(stderr, "ERROR: bpp:%d\n", header.bpp);
648 old = &data2[(y-1)*header.width*4];
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 */
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;
669 } else if(header.mode == 0 || header.mode == 3) {
671 unsigned char*tmpline = (unsigned char*)malloc(header.width+1);
672 unsigned char*destline = (unsigned char*)malloc(header.width+1);
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++) {
688 if(rgba[i].r == alphacolor[0])
694 fprintf(stderr, "Error: No palette found!\n");
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;*/
712 if(rgba[i].r == alphacolor[0] &&
713 rgba[i].g == alphacolor[1] &&
714 rgba[i].b == alphacolor[2])
720 for(y=0;y<header.height;y++) {
721 int mode = imagedata[pos++]; //filter mode
725 src = &imagedata[pos];
726 if(header.bpp == 8) {
731 u32 v = (1<<header.bpp)-1;
732 for(x=0;x<header.width;x++) {
733 u32 r = src[s/8]<<8 |
736 tmpline[x] = (r>>(16-header.bpp-(s&7)))&v;
740 pos+=(header.width*header.bpp+7)/8;
744 memset(destline,0,header.width);
745 old = &destline[y*header.width];
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]];
760 printf("expected PNG mode to be 2, 3 or 6 (is:%d)\n", header.mode);
767 static char hasAlpha(unsigned char*_image, int size)
769 COL*image = (COL*)_image;
771 for(t=0;t<size;t++) {
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;
789 static colornum_t* getColors(COL*image, int size, int*num)
791 unsigned char*colexists = malloc((256*256*256)/8);
792 memset(colexists, 0, (256*256*256)/8);
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)))) {
801 colexists[index/8]|=(1<<(index&7));
805 /* now store them in an array */
806 colornum_t*colors=(colornum_t*)malloc(sizeof(colornum_t)*count);
808 for(t=0;t<256*256*256;t++) {
809 if(colexists[t/8]&(1<<(t&7))) {
810 colors[pos].color = t;
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;
820 for(min=0, max=count, i=count/2, l=count; i != l; l=i,i=(min+max)/2) {
822 if(colors[i].color >= col) max=i;
825 assert(colors[i].color==col);
833 static void getOptimalPalette(COL*image, int size, int palettesize, COL*palette)
836 memset(palette, 0, sizeof(COL)*256);
837 colornum_t*colors = getColors(image, size, &num);
839 assert(palettesize<=256);
841 qsort(colors, num, sizeof(colornum_t), compare_colors);
843 if(num<=palettesize) {
844 /* if there are not more than palettesize different colors in
845 the image anyway, we are done */
848 palette[t].r = colors[t].color;
849 palette[t].g = colors[t].color>>8;
850 palette[t].b = colors[t].color>>16;
857 /* if there are too many different colors, pick the ones that
862 colornum_t*centers = malloc(sizeof(colornum_t)*palettesize);
864 for(t=0;t<palettesize;t++) {
865 centers[t].color = colors[t].color;
867 unsigned char*belongsto = (unsigned char*)malloc(num);
868 memset(belongsto, 0, num);
869 /* do a k-means clustering on the colors */
873 if(tries++ >= (palettesize+num)*2) {
874 fprintf(stderr, "Warning: didn't find optimal palette\n");
879 for(s=0;s<palettesize;s++) {
885 for(s=0;s<palettesize;s++) {
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;
896 if(bestpos!=belongsto[t])
898 belongsto[t] = bestpos;
900 for(s=0;s<palettesize;s++) {
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;
914 int random = rand()%num;
915 centers[s].color = colors[random].color;
922 centers[s].color = r|g<<8|b<<16;
923 centers[s].num = count;
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;
938 static int sqr(const int x) {return x*x;}
940 static void png_quantize_image(unsigned char*_image, int size, int numcolors, unsigned char**newimage, COL*palette)
942 COL*image = (COL*)_image;
943 getOptimalPalette(image, size, numcolors, palette);
944 *newimage = (unsigned char*)malloc(size);
946 for(t=0;t<size;t++) {
950 for(s=0;s<numcolors;s++) {
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;
960 (*newimage)[t] = bestcol;
966 static u32*crc32_table = 0;
967 static void make_crc32_table(void)
972 crc32_table = (u32*)malloc(1024);
974 for (t = 0; t < 256; t++) {
977 for (s = 0; s < 8; s++) {
978 c = (0xedb88320L*(c&1)) ^ (c >> 1);
983 static inline void png_write_byte(FILE*fi, unsigned char byte)
985 fwrite(&byte,1,1,fi);
986 mycrc32 = crc32_table[(mycrc32 ^ byte) & 0xff] ^ (mycrc32 >> 8);
988 static long png_start_chunk(FILE*fi, char*type, int len)
990 unsigned char mytype[4]={0,0,0,0};
991 unsigned char mylen[4];
997 memcpy(mytype,type,strlen(type));
999 fwrite(&mylen, 4, 1, fi);
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]);
1007 static void png_patch_len(FILE*fi, int pos, int len)
1009 unsigned char mylen[4];
1015 fseek(fi, pos, SEEK_SET);
1016 fwrite(&mylen, 4, 1, fi);
1017 fseek(fi, 0, SEEK_END);
1019 static void png_write_bytes(FILE*fi, unsigned char*bytes, int len)
1023 png_write_byte(fi,bytes[t]);
1025 static void png_write_dword(FILE*fi, u32 dword)
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);
1032 static void png_end_chunk(FILE*fi)
1034 u32 tmp = mycrc32^0xffffffff;
1035 unsigned char tmp2[4];
1040 fwrite(&tmp2,4,1,fi);
1043 #define ZLIB_BUFFER_SIZE 16384
1045 static long compress_line(z_stream*zs, Bytef*line, int len, FILE*fi)
1052 int ret = deflate(zs, Z_NO_FLUSH);
1054 fprintf(stderr, "error in deflate(): %s", zs->msg?zs->msg:"unknown");
1057 if(zs->avail_out != ZLIB_BUFFER_SIZE) {
1058 int consumed = ZLIB_BUFFER_SIZE - zs->avail_out;
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;
1071 static int test_line(z_stream*zs_orig, Bytef*line, int linelen)
1074 int ret = deflateCopy(&zs, zs_orig);
1076 fprintf(stderr, "Couldn't copy stream\n");
1081 zs.avail_in = linelen;
1085 int mode = Z_SYNC_FLUSH;
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);
1093 if(zs.avail_out != ZLIB_BUFFER_SIZE) {
1094 int consumed = ZLIB_BUFFER_SIZE - zs.avail_out;
1096 zs.next_out = zs.next_out - consumed;
1097 zs.avail_out = ZLIB_BUFFER_SIZE;
1099 if (ret == Z_STREAM_END) {
1106 ret = deflateEnd(&zs);
1108 fprintf(stderr, "error in deflateEnd(): %s\n", zs.msg?zs.msg:"unknown");
1114 static int finishzlib(z_stream*zs, FILE*fi)
1119 ret = deflate(zs, Z_FINISH);
1121 ret != Z_STREAM_END) {
1122 fprintf(stderr, "error in deflate(finish): %s\n", zs->msg?zs->msg:"unknown");
1126 if(zs->avail_out != ZLIB_BUFFER_SIZE) {
1127 int consumed = ZLIB_BUFFER_SIZE - zs->avail_out;
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;
1133 if (ret == Z_STREAM_END) {
1137 ret = deflateEnd(zs);
1139 fprintf(stderr, "error in deflateEnd(): %s\n", zs->msg?zs->msg:"unknown");
1145 static inline u32 color_hash(COL*col)
1147 u32 col32 = *(u32*)col;
1148 u32 hash = (col32 >> 17) ^ col32;
1149 hash ^= ((hash>>8) + 1) ^ hash;
1153 static int png_get_number_of_palette_entries(COL*img, int width, int height, COL*palette, char*has_alpha)
1155 int len = width*height;
1159 int palette_overflow = 0;
1162 memset(size, 0, sizeof(size));
1164 u32*pal = (u32*)malloc(65536*sizeof(u32));
1165 int*count = (int*)malloc(65536*sizeof(int));
1167 assert(sizeof(COL)==sizeof(u32));
1168 assert(width && height);
1170 lastcol32 = (*(u32*)&img[0])^0xffffffff; // don't match
1172 for(t=0;t<len;t++) {
1173 u32 col32 = *(u32*)&img[t];
1174 if(col32 == lastcol32)
1181 u32 hash = color_hash(&img[t])&255;
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]) {
1194 palette_overflow = 1;
1197 count[size[hash]] = 1;
1198 cpal[size[hash]++] = col32;
1203 if(palette_overflow) {
1206 return width*height;
1210 int occurences[256];
1211 for(t=0;t<256;t++) {
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]);
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];
1228 occurences[i] = occurences[j];
1229 palette[i] = palette[j];
1241 static void png_map_to_palette(COL*src, unsigned char*dest, int size, COL*palette, int palette_size)
1244 int palette_hash[1024];
1245 memset(palette_hash, 0, sizeof(int)*1024);
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;
1254 for(t=0;t<size;t++) {
1255 u32 hash = color_hash(&src[t]);
1259 index = palette_hash[hash];
1260 if(!memcmp(&palette[index], &src[t], sizeof(COL)))
1264 dest[t] = palette_hash[hash];
1268 static int png_apply_specific_filter_8(int filtermode, unsigned char*dest, unsigned char*src, int width)
1272 int srcwidth = width;
1274 if(filtermode == 0) {
1275 for(x=0;x<width;x++) {
1276 dest[pos2++]=src[pos++]; //alpha
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];
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
1291 } else if(filtermode == 3) {
1292 dest[pos2++]=src[pos+0] - src[pos-srcwidth+0]/2;
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
1299 } else if(filtermode == 4) {
1300 dest[pos2++]=src[pos+0] - PaethPredictor(0, src[pos-srcwidth+0], 0);
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]);
1311 static int png_apply_specific_filter_32(int filtermode, unsigned char*dest, unsigned char*src, int width)
1315 int srcwidth = width*4;
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
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];
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
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
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;
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
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);
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]);
1380 static int*num_bits_table = 0;
1382 static void make_num_bits_table()
1384 if(num_bits_table) return;
1385 num_bits_table = malloc(sizeof(num_bits_table[0])*256);
1387 for(t=0;t<256;t++) {
1394 num_bits_table[t]=bits;
1398 static int png_find_best_filter(unsigned char*src, int width, int bpp, int y)
1400 make_num_bits_table();
1402 int num_filters = y>0?5:2; //don't apply y-direction filter in first line
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;
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);
1416 unsigned char old[5];
1417 int l = bytes_per_pixel - 1;
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);
1424 int different_pairs[5] = {0,0,0,0,0};
1427 for(x=bytes_per_pixel;x<w;x++) {
1428 unsigned char dest[5];
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]);
1437 int v = dest[i]<<8|old[i];
1440 if(!pairs[i][p]&b) {
1442 different_pairs[i]++;
1445 memcpy(old, dest, sizeof(old));
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) {
1454 best_energy = energy;
1466 static int png_apply_filter(unsigned char*dest, unsigned char*src, int width, int y, int bpp)
1470 make_num_bits_table();
1471 int num_filters = y>0?5:2; //don't apply y-direction filter in first line
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++) {
1479 png_apply_specific_filter_8(f, dest, src, width);
1481 png_apply_specific_filter_32(f, dest, src, width);
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];
1497 int energy = different_pairs;
1498 if(energy<best_energy) {
1500 best_energy = energy;
1505 best_nr = png_find_best_filter(src, width, bpp, y);
1508 png_apply_specific_filter_8(best_nr, dest, src, width);
1510 png_apply_specific_filter_32(best_nr, dest, src, width);
1514 int png_apply_filter_8(unsigned char*dest, unsigned char*src, int width, int y)
1516 png_apply_filter(dest, src, width, y, 8);
1518 int png_apply_filter_32(unsigned char*dest, unsigned char*src, int width, int y)
1520 png_apply_filter(dest, src, width, y, 32);
1523 EXPORT void savePNG(const char*filename, unsigned char*data, int width, int height, int numcolors)
1528 unsigned char format;
1530 unsigned char* data2=0;
1533 unsigned char head[] = {137,80,78,71,13,10,26,10}; // PNG header
1548 int num = png_get_number_of_palette_entries((COL*)data, width, height, palette, &has_alpha);
1550 //printf("image has %d different colors (alpha=%d)\n", num, has_alpha);
1551 data2 = malloc(width*height);
1552 png_map_to_palette((COL*)data, data2, width*height, palette, num);
1566 png_quantize_image(data, width*height, numcolors, &data, palette);
1569 datalen = (width*height*bpp/8+cols*8);
1571 fi = fopen(filename, "wb");
1576 fwrite(head,sizeof(head),1,fi);
1578 png_start_chunk(fi, "IHDR", 13);
1579 png_write_dword(fi,width);
1580 png_write_dword(fi,height);
1581 png_write_byte(fi,8);
1583 png_write_byte(fi,3); //indexed
1584 else if(format == 5 && alpha==0)
1585 png_write_byte(fi,2); //rgb
1586 else if(format == 5 && alpha==1)
1587 png_write_byte(fi,6); //rgba
1590 png_write_byte(fi,0); //compression mode
1591 png_write_byte(fi,0); //filter mode
1592 png_write_byte(fi,0); //interlace mode
1596 png_start_chunk(fi, "PLTE", cols*3);
1597 for(t=0;t<cols;t++) {
1598 png_write_byte(fi,palette[t].r);
1599 png_write_byte(fi,palette[t].g);
1600 png_write_byte(fi,palette[t].b);
1605 png_start_chunk(fi, "tRNS", cols);
1606 for(t=0;t<cols;t++) {
1607 png_write_byte(fi,palette[t].a);
1613 long idatpos = png_start_chunk(fi, "IDAT", 0);
1615 memset(&zs,0,sizeof(z_stream));
1616 Bytef*writebuf = (Bytef*)malloc(ZLIB_BUFFER_SIZE);
1620 zs.next_out = writebuf;
1621 zs.avail_out = ZLIB_BUFFER_SIZE;
1622 ret = deflateInit(&zs, Z_BEST_COMPRESSION);
1624 fprintf(stderr, "error in deflateInit(): %s", zs.msg?zs.msg:"unknown");
1632 int srcwidth = width * bypp;
1633 int linelen = 1 + srcwidth;
1635 linelen = 1 + ((srcwidth+1)&~1);
1637 linelen = 1 + ((srcwidth+2)/3)*3;
1639 linelen = 1 + ((srcwidth+3)&~3);
1640 unsigned char* line = (unsigned char*)malloc(linelen);
1641 memset(line, 0, linelen);
1643 unsigned char* bestline = (unsigned char*)malloc(linelen);
1644 memset(bestline, 0, linelen);
1645 for(y=0;y<height;y++)
1648 int bestsize = 0x7fffffff;
1649 for(filtermode=0;filtermode<=4;filtermode++) {
1650 if(!y && filtermode>=2)
1651 continue; // don't do y direction filters in the first row
1653 line[0]=filtermode; //filter type
1655 png_apply_specific_filter_8(filtermode, line+1, &data[y*srcwidth], width);
1657 png_apply_specific_filter_32(filtermode, line+1, &data[y*srcwidth], width);
1659 int size = test_line(&zs, line, linelen);
1660 if(size < bestsize) {
1661 memcpy(bestline, line, linelen);
1665 idatsize += compress_line(&zs, bestline, linelen, fi);
1669 for(y=0;y<height;y++) {
1671 line[0] = png_apply_filter_8(line+1, &data[y*srcwidth], width, y);
1673 line[0] = png_apply_filter_32(line+1, &data[y*srcwidth], width, y);
1675 idatsize += compress_line(&zs, line, linelen, fi);
1680 idatsize += finishzlib(&zs, fi);
1681 png_patch_len(fi, idatpos, idatsize);
1684 png_start_chunk(fi, "IEND", 0);
1693 EXPORT void writePNG(const char*filename, unsigned char*data, int width, int height)
1695 savePNG(filename, data, width, height, 0);
1697 EXPORT void writePalettePNG(const char*filename, unsigned char*data, int width, int height)
1699 savePNG(filename, data, width, height, 256);