implemented filter bytes.
[swftools.git] / src / png2swf.c
1 /* png2swf.c
2
3    PNG to SWF converter tool
4
5    Part of the swftools package.
6
7    Copyright (c) 2002 Matthias Kramm <kramm@quiss.org>
8  
9    This file is distributed under the GPL, see file COPYING for details 
10
11 */
12
13 #include <stdio.h>
14 #include <math.h>
15 #include <fcntl.h>
16 #include <zlib.h>
17 #include "../lib/rfxswf.h"
18 #include "../lib/args.h"
19
20 #define MAX_INPUT_FILES 1024
21 #define VERBOSE(x) (global.verbose>=x)
22
23 struct {
24     int framerate;
25     int max_image_width;
26     int max_image_height;
27     int force_width;
28     int force_height;
29     int nfiles;
30     int verbose;
31     char *outfile;
32 } global;
33
34 struct {
35     char *filename;
36 } image[MAX_INPUT_FILES];
37
38 TAG *MovieStart(SWF * swf, int framerate, int dx, int dy)
39 {
40     TAG *t;
41     RGBA rgb;
42
43     memset(swf, 0x00, sizeof(SWF));
44
45     swf->fileVersion = 4;
46     swf->frameRate = (25600 / framerate);
47     swf->movieSize.xmax = dx * 20;
48     swf->movieSize.ymax = dy * 20;
49
50     t = swf->firstTag = swf_InsertTag(NULL, ST_SETBACKGROUNDCOLOR);
51
52     rgb.r = rgb.g = rgb.b = rgb.a = 0x00;
53     swf_SetRGB(t, &rgb);
54
55     return t;
56 }
57
58 int MovieFinish(SWF * swf, TAG * t, char *sname)
59 {
60     int handle, so = fileno(stdout);
61     t = swf_InsertTag(t, ST_END);
62
63     if ((!isatty(so)) && (!sname))
64         handle = so;
65     else {
66         if (!sname)
67             sname = "output.swf";
68         handle = open(sname, O_RDWR | O_CREAT | O_TRUNC, 0666);
69     }
70     if FAILED
71         (swf_WriteSWF(handle, swf)) if (VERBOSE(1))
72             fprintf(stderr, "Unable to write output file: %s\n", sname);
73     if (handle != so)
74         close(handle);
75
76     swf_FreeTags(swf);
77     return 0;
78 }
79
80 int png_read_chunk(char (*head)[4], int*destlen, U8**destdata, FILE*fi)
81 {
82     unsigned int len;
83     if(destlen) *destlen=0;
84     if(destdata) *destdata=0;
85     if(!fread(&len, 4, 1, fi))
86         return 0;
87     if(!fread(head, 4, 1, fi))
88         return 0;
89     len = REVERSESWAP32(len);
90     printf("id: %.4s len: %d\n", head, len);
91     if(destlen) *destlen = len;
92     if(destdata) {
93         if(len)
94             *destdata = malloc(len);
95         else 
96             *destdata = 0;
97         if(!fread(*destdata, len, 1, fi)) {
98             *destdata = 0;
99             if(destlen) *destlen=0;
100             return 0;
101         }
102         fseek(fi, 4, SEEK_CUR);
103
104     } else {
105         fseek(fi, len+4, SEEK_CUR);
106     }
107     return 1;
108 }
109
110 unsigned int png_get_dword(FILE*fi)
111 {
112     unsigned int a;
113     fread(&a,4,1,fi);
114     return REVERSESWAP32(a);
115 }
116
117 struct png_header
118 {
119     int width;
120     int height;
121     int bpp;
122     int mode;
123 };
124
125 int png_read_header(FILE*fi, struct png_header*header)
126 {
127     char id[4];
128     int len;
129     U8 head[8] = {137,80,78,71,13,10,26,10};
130     U8 head2[8];
131     U8*data;
132     fread(head2,8,1,fi);
133     if(strncmp(head,head2,4))
134         return 0;
135    
136     while(png_read_chunk(&id, &len, &data, fi))
137     {
138         printf("%c%c%c%c %d\n", id[0],id[1],id[2],id[3],len);
139         if(!strncasecmp(id, "IHDR", 4)) {
140             char a,b,c,f,i;
141             if(len < 8) exit(1);
142             header->width = REVERSESWAP32(*(U32*)&data[0]);
143             header->height = REVERSESWAP32(*(U32*)&data[4]);
144             a = data[8];      // should be 8
145             b = data[9];      // should be 3(indexed) or 2(rgb)
146
147             c = data[10];     // compression mode (0)
148             f = data[11];     // filter mode (0)
149             i = data[12];     // interlace mode (0)
150             if(c!=0) {
151                 fprintf(stderr, "Compression mode %d not supported!\n", c);
152                 exit(1);
153             }
154             if(f!=0) {
155                 fprintf(stderr, "Filter mode %d not supported!\n", f);
156                 exit(1);
157             }
158             if(i!=0) {
159                 fprintf(stderr, "Interlace mode %d not supported!\n", i);
160                 exit(1);
161             }
162             printf("%dx%d %d %d %d %d %d\n",header->width, header->height, a,b,c,f,i);
163             header->bpp = a;
164             header->mode = b;
165             return 1;
166         } else {
167             fseek(fi, len, SEEK_CUR);
168         }
169         free(data);
170     }
171     return 0;
172 }
173
174 typedef unsigned char byte;
175 #define ABS(a) ((a)>0?(a):(-(a)))
176 byte inline PaethPredictor (byte a,byte b,byte c)
177 {
178         // a = left, b = above, c = upper left
179         int p = a + b - c;        // initial estimate
180         int pa = ABS(p - a);      // distances to a, b, c
181         int pb = ABS(p - b);
182         int pc = ABS(p - c);
183         // return nearest of a,b,c,
184         // breaking ties in order a,b,c.
185         if (pa <= pb && pa <= pc) 
186                 return a;
187         else if (pb <= pc) 
188                 return b;
189         else return c;
190 }
191
192 void applyfilter(int mode, U8*src, U8*old, U8*dest, int width)
193 {
194     int x;
195     unsigned char lastr=0;
196     unsigned char lastg=0;
197     unsigned char lastb=0;
198     unsigned char upperlastr=0;
199     unsigned char upperlastg=0;
200     unsigned char upperlastb=0;
201
202     if(mode==0) {
203         for(x=0;x<width;x++) {
204             dest[0] = 255;
205             dest[1] = src[0];
206             dest[2] = src[1];
207             dest[3] = src[2];
208             dest+=4;
209             src+=3;
210         }
211     }
212     else if(mode==1) {
213         for(x=0;x<width;x++) {
214             dest[0] = 255;
215             dest[1] = src[0]+lastr;
216             dest[2] = src[1]+lastg;
217             dest[3] = src[2]+lastb;
218             lastr = dest[1];
219             lastg = dest[2];
220             lastb = dest[3];
221             dest+=4;
222             src+=3;
223         }
224     }
225     else if(mode==2) {
226         for(x=0;x<width;x++) {
227             dest[0] = 255;
228             dest[1] = src[0]+old[1];
229             dest[2] = src[1]+old[2];
230             dest[3] = src[2]+old[3];
231             dest+=4;
232             old+=4;
233             src+=3;
234         }
235     }
236     else if(mode==3) {
237         for(x=0;x<width;x++) {
238             dest[0] = 255;
239             dest[1] = src[0]+(old[1]+lastr)/2;
240             dest[2] = src[1]+(old[2]+lastg)/2;
241             dest[3] = src[2]+(old[3]+lastb)/2;
242             lastr = dest[1];
243             lastg = dest[2];
244             lastb = dest[3];
245             dest+=4;
246             old+=4;
247             src+=3;
248         }
249     }
250     else if(mode==4) {
251         for(x=0;x<width;x++) {
252             dest[0] = 255;
253             dest[1] = src[0]+PaethPredictor(lastr,old[1],upperlastr);
254             dest[2] = src[1]+PaethPredictor(lastg,old[2],upperlastg);
255             dest[3] = src[2]+PaethPredictor(lastb,old[3],upperlastb);
256             lastr = dest[1];
257             lastg = dest[2];
258             lastb = dest[3];
259             upperlastr = old[1];
260             upperlastg = old[2];
261             upperlastb = old[3];
262             dest+=4;
263             old+=4;
264             src+=3;
265         }
266     }    
267
268 }
269
270 TAG *MovieAddFrame(SWF * swf, TAG * t, char *sname, int id)
271 {
272     SHAPE *s;
273     SRECT r;
274     MATRIX m;
275     int fs;
276
277     char tagid[4];
278     int len;
279     U8*data;
280     U8*imagedata;
281     unsigned long int imagedatalen;
282     U8*palette = 0;
283     int palettelen = 0;
284     struct png_header header;
285     int bypp;
286
287     FILE *fi;
288     U8 *scanline;
289
290     if ((fi = fopen(sname, "rb")) == NULL) {
291         if (VERBOSE(1))
292             fprintf(stderr, "Read access failed: %s\n", sname);
293         return t;
294     }
295
296     if(!png_read_header(fi, &header))
297         return 0;
298
299     if(header.mode == 3) bypp = 1;
300     else
301     if(header.mode == 2) bypp = 3;
302     else
303         return 0;
304     imagedatalen = bypp * header.width * header.height + 65536;
305     imagedata = malloc(imagedatalen);
306
307     fseek(fi,8,SEEK_SET);
308     while(!feof(fi))
309     {
310         if(!png_read_chunk(&tagid, &len, &data, fi))
311             break;
312         if(!strncmp(tagid, "IEND", 4)) {
313             break;
314         }
315         if(!strncmp(tagid, "PLTE", 4)) {
316             palette = data;
317             palettelen = len/3;
318             data = 0;
319             printf("%d palette\n", len);
320         }
321         if(!strncmp(tagid, "IDAT", 4)) {
322             if(uncompress(imagedata, &imagedatalen, data, len) != Z_OK) {
323                 fprintf(stderr, "Couldn't uncompress %s!\n", sname);
324                 return 0;
325             }
326             printf("IDAT %d -> %d\n", len, imagedatalen);
327         }
328         if(data)
329             free(data);
330     }
331
332     t = swf_InsertTag(t, ST_DEFINEBITSLOSSLESS);
333     swf_SetU16(t, id);          // id
334     if(header.mode == 2) {
335         U8*data2 = malloc(header.width*header.height*4);
336         int i,s=0;
337         int x,y;
338         int pos=0;
339         /* 24->32 bit conversion */
340         for(y=0;y<header.height;y++) {
341             int mode = imagedata[pos++]; //filter mode
342
343             U8*src = &imagedata[pos];
344             U8*dest = &data2[(y*header.width)*4];
345             U8*old;
346             if(!y) {
347                 memset(data2,0,header.width*4);
348                 old = &data2[y*header.width*4];
349             } else {
350                 old = &data2[(y-1)*header.width*4];
351             }
352             applyfilter(mode, src, old, dest, header.width);
353             pos+=header.width*3;
354         }
355         swf_SetLosslessBits(t, header.width, header.height, data2, BMF_32BIT);
356         free(data2);
357     }
358     else {
359         RGBA*rgba = (RGBA*)malloc(palettelen*sizeof(RGBA));
360         U8*data2 = malloc((header.width+4)*header.height);
361         int i,x,y;
362         int pos=0;
363         if(!palette) {
364             fprintf(stderr, "Error: No palette found!\n");
365             exit(1);
366         }
367         /* 24->32 bit conversion */
368         for(i=0;i<palettelen;i++) {
369             rgba[i].r = palette[i*3+0];
370             rgba[i].g = palette[i*3+1];
371             rgba[i].b = palette[i*3+2];
372             rgba[i].a = 255;
373         }
374         for(y=0;y<header.height;y++) {
375             int mode = imagedata[pos];
376             if(mode!=0) {
377                 fprintf(stderr, "Warning: Filter mode %d\n", mode);
378             }
379             pos++; //filter mode
380             for(x=0;x<header.width;x++) {
381                 data2[y*header.width+x] = 
382                     imagedata[pos++];
383             }
384         }
385         swf_SetLosslessBitsIndexed(t, header.width, header.height, data2, rgba, palettelen);
386         free(rgba);
387         free(data2);
388     }
389
390     t = swf_InsertTag(t, ST_DEFINESHAPE);
391
392     swf_ShapeNew(&s);
393     swf_GetMatrix(NULL, &m);
394     m.sx = 20 * 0x10000;
395     m.sy = 20 * 0x10000;
396     fs = swf_ShapeAddBitmapFillStyle(s, &m, id, 0);
397
398     swf_SetU16(t, id + 1);      // id
399
400     r.xmin = r.ymin = 0;
401     r.xmax = header.width * 20;
402     r.ymax = header.height * 20;
403     swf_SetRect(t, &r);
404
405     swf_SetShapeHeader(t, s);
406
407     swf_ShapeSetAll(t, s, 0, 0, 0, fs, 0);
408     swf_ShapeSetLine(t, s, r.xmax, 0);
409     swf_ShapeSetLine(t, s, 0, r.ymax);
410     swf_ShapeSetLine(t, s, -r.xmax, 0);
411     swf_ShapeSetLine(t, s, 0, -r.ymax);
412
413     swf_ShapeSetEnd(t);
414
415     t = swf_InsertTag(t, ST_REMOVEOBJECT2);
416     swf_SetU16(t, 1);           // depth
417
418     t = swf_InsertTag(t, ST_PLACEOBJECT2);
419
420     swf_GetMatrix(NULL, &m);
421     m.tx = (swf->movieSize.xmax - (int) header.width * 20) / 2;
422     m.ty = (swf->movieSize.ymax - (int) header.height * 20) / 2;
423     swf_ObjectPlace(t, id + 1, 1, &m, NULL, NULL);
424
425     t = swf_InsertTag(t, ST_SHOWFRAME);
426
427     fclose(fi);
428
429     return t;
430 }
431
432
433 int CheckInputFile(char *fname, char **realname)
434 {
435     FILE *fi;
436     char *s = malloc(strlen(fname) + 5);
437     struct png_header head;
438
439     if (!s)
440         exit(2);
441     (*realname) = s;
442     strcpy(s, fname);
443
444     // Check whether file exists (with typical extensions)
445
446     if ((fi = fopen(s, "rb")) == NULL) {
447         sprintf(s, "%s.png", fname);
448         if ((fi = fopen(s, "rb")) == NULL) {
449             sprintf(s, "%s.PNG", fname);
450             if ((fi = fopen(s, "rb")) == NULL) {
451                 sprintf(s, "%s.Png", fname);
452                 if ((fi = fopen(s, "rb")) == NULL)
453                     fprintf(stderr, "Couldn't open %s!\n", fname);
454                     return -1;
455             }
456         }
457     }
458
459     if(!png_read_header(fi, &head)) {
460         fprintf(stderr, "%s is not a PNG file!\n", fname);
461         return -1;
462     }
463     if(head.mode!=2 && head.mode!=3) {
464         fprintf(stderr, "%s has unsupported mode %d\n", head.mode);
465         return -1;
466     }
467     if(head.bpp!=8) {
468         fprintf(stderr, "%s has unsupported bpp %d\n", head.bpp);
469         return -1;
470     }
471
472     if (global.max_image_width < head.width)
473         global.max_image_width = head.width;
474     if (global.max_image_height < head.height)
475         global.max_image_height = head.height;
476
477     fclose(fi);
478
479     return 0;
480 }
481
482 int args_callback_option(char *arg, char *val)
483 {
484     int res = 0;
485     if (arg[1])
486         res = -1;
487     else
488         switch (arg[0]) {
489         case 'r':
490             if (val)
491                 global.framerate = atoi(val);
492             if ((global.framerate < 1) ||(global.framerate > 5000)) {
493                 if (VERBOSE(1))
494                     fprintf(stderr,
495                             "Error: You must specify a valid framerate between 1 and 10000.\n");
496                 exit(1);
497             }
498             res = 1;
499             break;
500
501         case 'o':
502             if (val)
503                 global.outfile = val;
504             res = 1;
505             break;
506
507         case 'v':
508             if (val)
509                 global.verbose = atoi(val);
510             res = 1;
511             break;
512
513         case 'X':
514             if (val)
515                 global.force_width = atoi(val);
516             res = 1;
517             break;
518
519         case 'Y':
520             if (val)
521                 global.force_height = atoi(val);
522             res = 1;
523             break;
524
525         case 'V':
526             printf("png2swf - part of %s %s\n", PACKAGE, VERSION);
527             exit(0);
528
529         default:
530             res = -1;
531             break;
532         }
533
534     if (res < 0) {
535         if (VERBOSE(1))
536             fprintf(stderr, "Unknown option: -%s\n", arg);
537         exit(1);
538         return 0;
539     }
540     return res;
541 }
542
543 struct options_t options[] = 
544
545 {"o", "output"},
546 {"r", "rate"},
547 {"v", "verbose"},
548 {"X", "width"},
549 {"Y", "height"},
550 {"V", "version"},
551 };
552
553 int args_callback_longoption(char *name, char *val)
554 {
555     return args_long2shortoption(options, name, val);
556 }
557
558 int args_callback_command(char *arg, char *next)        // actually used as filename
559 {
560     char *s;
561     if (CheckInputFile(arg, &s) < 0) {
562         if (VERBOSE(1))
563             fprintf(stderr, "Error opening input file: %s\n", arg);
564         free(s);
565     } else {
566         image[global.nfiles].filename = s;
567         global.nfiles++;
568         if (global.nfiles >= MAX_INPUT_FILES) {
569             if (VERBOSE(1))
570                 fprintf(stderr, "Error: Too many input files.\n");
571             exit(1);
572         }
573     }
574     return 0;
575 }
576
577 void args_callback_usage(char *name)
578 {
579     printf("Usage: %s  [-options [value]] imagefiles[.png] [...]\n", name);
580     printf("-r framerate          (rate) Set movie framerate (100/sec)\n");
581     printf("-o outputfile         (output) Set name for SWF output file\n");
582     printf("-X pixel              (width) Force movie width to pixel (default: autodetect)\n");
583     printf("-Y pixel              (height) Force movie height to pixel (default: autodetect)\n");
584     printf("-v level              (verbose) Set verbose level (0=quiet, 1=default, 2=debug)\n");
585     printf("-V                    (version) Print version information and exit\n");
586 }
587
588
589 int main(int argc, char **argv)
590 {
591     SWF swf;
592     TAG *t;
593
594     memset(&global, 0x00, sizeof(global));
595
596     global.framerate = 100;
597     global.verbose = 1;
598
599     processargs(argc, argv);
600
601     if (VERBOSE(2))
602         fprintf(stderr, "Processing %i file(s)...\n", global.nfiles);
603
604     t = MovieStart(&swf, global.framerate,
605                    global.force_width ? global.force_width : global.
606                    max_image_width,
607                    global.force_height ? global.force_height : global.
608                    max_image_height);
609
610     {
611         int i;
612         for (i = 0; i < global.nfiles; i++) {
613             if (VERBOSE(3))
614                 fprintf(stderr, "[%03i] %s\n", i,
615                         image[i].filename);
616             t = MovieAddFrame(&swf, t, image[i].filename, (i * 2) + 1);
617             free(image[i].filename);
618         }
619     }
620
621     MovieFinish(&swf, t, global.outfile);
622
623     return 0;
624 }