implemented bit depths.
[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     if(destlen) *destlen = len;
91     if(destdata) {
92         if(len)
93             *destdata = malloc(len);
94         else 
95             *destdata = 0;
96         if(!fread(*destdata, len, 1, fi)) {
97             *destdata = 0;
98             if(destlen) *destlen=0;
99             return 0;
100         }
101         fseek(fi, 4, SEEK_CUR);
102
103     } else {
104         fseek(fi, len+4, SEEK_CUR);
105     }
106     return 1;
107 }
108
109 unsigned int png_get_dword(FILE*fi)
110 {
111     unsigned int a;
112     fread(&a,4,1,fi);
113     return REVERSESWAP32(a);
114 }
115
116 struct png_header
117 {
118     int width;
119     int height;
120     int bpp;
121     int mode;
122 };
123
124 int png_read_header(FILE*fi, struct png_header*header)
125 {
126     char id[4];
127     int len;
128     U8 head[8] = {137,80,78,71,13,10,26,10};
129     U8 head2[8];
130     U8*data;
131     fread(head2,8,1,fi);
132     if(strncmp(head,head2,4))
133         return 0;
134    
135     while(png_read_chunk(&id, &len, &data, fi))
136     {
137         if(VERBOSE(2))
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
151             if(b!=2 && b!=3) {
152                 fprintf(stderr, "Image mode %d not supported!\n", b);
153                 exit(1);
154             }
155             if(a!=8 && b==2) {
156                 fprintf(stderr, "Bpp %d in mode %d not supported!\n", a);
157                 exit(1);
158             }
159             if(c!=0) {
160                 fprintf(stderr, "Compression mode %d not supported!\n", c);
161                 exit(1);
162             }
163             if(f!=0) {
164                 fprintf(stderr, "Filter mode %d not supported!\n", f);
165                 exit(1);
166             }
167             if(i!=0) {
168                 fprintf(stderr, "Interlace mode %d not supported!\n", i);
169                 exit(1);
170             }
171             if(VERBOSE(2))
172                 printf("%dx%d %d %d %d %d %d\n",header->width, header->height, a,b,c,f,i);
173             header->bpp = a;
174             header->mode = b;
175             return 1;
176         } else {
177             fseek(fi, len, SEEK_CUR);
178         }
179         free(data);
180     }
181     return 0;
182 }
183
184 typedef unsigned char byte;
185 #define ABS(a) ((a)>0?(a):(-(a)))
186 byte inline PaethPredictor (byte a,byte b,byte c)
187 {
188         // a = left, b = above, c = upper left
189         int p = a + b - c;        // initial estimate
190         int pa = ABS(p - a);      // distances to a, b, c
191         int pb = ABS(p - b);
192         int pc = ABS(p - c);
193         // return nearest of a,b,c,
194         // breaking ties in order a,b,c.
195         if (pa <= pb && pa <= pc) 
196                 return a;
197         else if (pb <= pc) 
198                 return b;
199         else return c;
200 }
201
202 void applyfilter(int mode, U8*src, U8*old, U8*dest, int width)
203 {
204     int x;
205     unsigned char lastr=0;
206     unsigned char lastg=0;
207     unsigned char lastb=0;
208     unsigned char upperlastr=0;
209     unsigned char upperlastg=0;
210     unsigned char upperlastb=0;
211
212     if(mode==0) {
213         for(x=0;x<width;x++) {
214             dest[0] = 255;
215             dest[1] = src[0];
216             dest[2] = src[1];
217             dest[3] = src[2];
218             dest+=4;
219             src+=3;
220         }
221     }
222     else if(mode==1) {
223         for(x=0;x<width;x++) {
224             dest[0] = 255;
225             dest[1] = src[0]+lastr;
226             dest[2] = src[1]+lastg;
227             dest[3] = src[2]+lastb;
228             lastr = dest[1];
229             lastg = dest[2];
230             lastb = dest[3];
231             dest+=4;
232             src+=3;
233         }
234     }
235     else if(mode==2) {
236         for(x=0;x<width;x++) {
237             dest[0] = 255;
238             dest[1] = src[0]+old[1];
239             dest[2] = src[1]+old[2];
240             dest[3] = src[2]+old[3];
241             dest+=4;
242             old+=4;
243             src+=3;
244         }
245     }
246     else if(mode==3) {
247         for(x=0;x<width;x++) {
248             dest[0] = 255;
249             dest[1] = src[0]+(old[1]+lastr)/2;
250             dest[2] = src[1]+(old[2]+lastg)/2;
251             dest[3] = src[2]+(old[3]+lastb)/2;
252             lastr = dest[1];
253             lastg = dest[2];
254             lastb = dest[3];
255             dest+=4;
256             old+=4;
257             src+=3;
258         }
259     }
260     else if(mode==4) {
261         for(x=0;x<width;x++) {
262             dest[0] = 255;
263             dest[1] = src[0]+PaethPredictor(lastr,old[1],upperlastr);
264             dest[2] = src[1]+PaethPredictor(lastg,old[2],upperlastg);
265             dest[3] = src[2]+PaethPredictor(lastb,old[3],upperlastb);
266             lastr = dest[1];
267             lastg = dest[2];
268             lastb = dest[3];
269             upperlastr = old[1];
270             upperlastg = old[2];
271             upperlastb = old[3];
272             dest+=4;
273             old+=4;
274             src+=3;
275         }
276     }    
277
278 }
279
280 void applyfilter1(int mode, U8*src, U8*old, U8*dest, int width)
281 {
282     int x;
283     unsigned char last=0;
284     unsigned char upperlast=0;
285
286     if(mode==0) {
287         for(x=0;x<width;x++) {
288             *dest = *src;
289             dest++;
290             src++;
291         }
292     }
293     else if(mode==1) {
294         for(x=0;x<width;x++) {
295             *dest = *src+last;
296             last = *dest;
297             dest++;
298             src++;
299         }
300     }
301     else if(mode==2) {
302         for(x=0;x<width;x++) {
303             *dest = *src+*old;
304             dest++;
305             old++;
306             src++;
307         }
308     }
309     else if(mode==3) {
310         for(x=0;x<width;x++) {
311             *dest = *src+(*old+last)/2;
312             dest++;
313             old++;
314             src++;
315         }
316     }
317     else if(mode==4) {
318         for(x=0;x<width;x++) {
319             *dest = *src+PaethPredictor(last,*old,upperlast);
320             last = *dest;
321             upperlast = *old;
322             dest++;
323             old++;
324             src++;
325         }
326     }    
327
328 }
329
330 TAG *MovieAddFrame(SWF * swf, TAG * t, char *sname, int id)
331 {
332     SHAPE *s;
333     SRECT r;
334     MATRIX m;
335     int fs;
336
337     char tagid[4];
338     int len;
339     U8*data;
340     U8*imagedata;
341     unsigned long int imagedatalen;
342     U8*palette = 0;
343     int palettelen = 0;
344     struct png_header header;
345     int bypp;
346
347     FILE *fi;
348     U8 *scanline;
349
350     if ((fi = fopen(sname, "rb")) == NULL) {
351         if (VERBOSE(1))
352             fprintf(stderr, "Read access failed: %s\n", sname);
353         return t;
354     }
355
356     if(!png_read_header(fi, &header))
357         return 0;
358
359     if(header.mode == 3) bypp = 1;
360     else
361     if(header.mode == 2) bypp = 3;
362     else
363         return 0;
364     imagedatalen = bypp * header.width * header.height + 65536;
365     imagedata = malloc(imagedatalen);
366
367     fseek(fi,8,SEEK_SET);
368     while(!feof(fi))
369     {
370         if(!png_read_chunk(&tagid, &len, &data, fi))
371             break;
372         if(!strncmp(tagid, "IEND", 4)) {
373             break;
374         }
375         if(!strncmp(tagid, "PLTE", 4)) {
376             palette = data;
377             palettelen = len/3;
378             data = 0;
379             if(VERBOSE(2))
380                 printf("%d colors in palette\n", palettelen);
381         }
382         if(!strncmp(tagid, "IDAT", 4)) {
383             if(uncompress(imagedata, &imagedatalen, data, len) != Z_OK) {
384                 fprintf(stderr, "Couldn't uncompress %s!\n", sname);
385                 return 0;
386             }
387         }
388         if(data)
389             free(data);
390     }
391     t = swf_InsertTag(t, ST_DEFINEBITSLOSSLESS);
392     swf_SetU16(t, id);          // id
393     if(header.mode == 2) {
394         U8*data2 = malloc(header.width*header.height*4);
395         int i,s=0;
396         int x,y;
397         int pos=0;
398         /* 24->32 bit conversion */
399         for(y=0;y<header.height;y++) {
400             int mode = imagedata[pos++]; //filter mode
401             U8*src;
402             U8*dest;
403             U8*old;
404             dest = &data2[(y*header.width)*4];
405
406             if(header.bpp == 8)
407             {
408                 /* one byte per pixel */
409                 src = &imagedata[pos];
410                 pos+=header.width*3;
411             } else {
412                 /* not implemented yet */
413                 exit(1);
414             }
415
416             if(!y) {
417                 memset(data2,0,header.width*4);
418                 old = &data2[y*header.width*4];
419             } else {
420                 old = &data2[(y-1)*header.width*4];
421             }
422             applyfilter(mode, src, old, dest, header.width);
423         }
424         swf_SetLosslessBits(t, header.width, header.height, data2, BMF_32BIT);
425         free(data2);
426     }
427     else {
428         RGBA*rgba = (RGBA*)malloc(palettelen*sizeof(RGBA));
429         int swf_width = BYTES_PER_SCANLINE(header.width);
430         U8*data2 = malloc(swf_width*header.height);
431         U8*tmpline = malloc(header.width);
432         int i,x,y;
433         int pos=0;
434         if(!palette) {
435             fprintf(stderr, "Error: No palette found!\n");
436             exit(1);
437         }
438         /* 24->32 bit conversion */
439         for(i=0;i<palettelen;i++) {
440             rgba[i].r = palette[i*3+0];
441             rgba[i].g = palette[i*3+1];
442             rgba[i].b = palette[i*3+2];
443             rgba[i].a = 255;
444         }
445         for(y=0;y<header.height;y++) {
446             int mode = imagedata[pos++]; //filter mode
447             U8*old;
448             U8*dest = &data2[y*swf_width];
449             U8*src;
450             src = &imagedata[pos];
451             if(header.bpp == 8) {
452                 pos+=header.width;
453             } else {
454                 int x,s=0;
455                 int bitpos = 0;
456                 U32 v = (1<<header.bpp)-1;
457                 for(x=0;x<header.width;x++) {
458                     U32 r = src[s/8]<<8 | 
459                             src[s/8+1];
460                     int t;
461                     tmpline[x] = (r>>(16-header.bpp-(s&7)))&v;
462                     s+=header.bpp;
463                 }
464                 src = tmpline;
465                 pos+=(header.width*header.bpp+7)/8;
466             }
467
468             if(!y) {
469                 memset(data2,0,swf_width);
470                 old = &data2[y*swf_width];
471             } else {
472                 old = &data2[(y-1)*swf_width];
473             }
474             applyfilter1(mode, src, old, dest, header.width);
475         }
476         swf_SetLosslessBitsIndexed(t, header.width, header.height, data2, rgba, palettelen);
477         free(tmpline);
478         free(rgba);
479         free(data2);
480     }
481
482     t = swf_InsertTag(t, ST_DEFINESHAPE);
483
484     swf_ShapeNew(&s);
485     swf_GetMatrix(NULL, &m);
486     m.sx = 20 * 0x10000;
487     m.sy = 20 * 0x10000;
488     fs = swf_ShapeAddBitmapFillStyle(s, &m, id, 0);
489
490     swf_SetU16(t, id + 1);      // id
491
492     r.xmin = r.ymin = 0;
493     r.xmax = header.width * 20;
494     r.ymax = header.height * 20;
495     swf_SetRect(t, &r);
496
497     swf_SetShapeHeader(t, s);
498
499     swf_ShapeSetAll(t, s, 0, 0, 0, fs, 0);
500     swf_ShapeSetLine(t, s, r.xmax, 0);
501     swf_ShapeSetLine(t, s, 0, r.ymax);
502     swf_ShapeSetLine(t, s, -r.xmax, 0);
503     swf_ShapeSetLine(t, s, 0, -r.ymax);
504
505     swf_ShapeSetEnd(t);
506
507     t = swf_InsertTag(t, ST_REMOVEOBJECT2);
508     swf_SetU16(t, 1);           // depth
509
510     t = swf_InsertTag(t, ST_PLACEOBJECT2);
511
512     swf_GetMatrix(NULL, &m);
513     m.tx = (swf->movieSize.xmax - (int) header.width * 20) / 2;
514     m.ty = (swf->movieSize.ymax - (int) header.height * 20) / 2;
515     swf_ObjectPlace(t, id + 1, 1, &m, NULL, NULL);
516
517     t = swf_InsertTag(t, ST_SHOWFRAME);
518
519     fclose(fi);
520
521     return t;
522 }
523
524
525 int CheckInputFile(char *fname, char **realname)
526 {
527     FILE *fi;
528     char *s = malloc(strlen(fname) + 5);
529     struct png_header head;
530
531     if (!s)
532         exit(2);
533     (*realname) = s;
534     strcpy(s, fname);
535
536     // Check whether file exists (with typical extensions)
537
538     if ((fi = fopen(s, "rb")) == NULL) {
539         sprintf(s, "%s.png", fname);
540         if ((fi = fopen(s, "rb")) == NULL) {
541             sprintf(s, "%s.PNG", fname);
542             if ((fi = fopen(s, "rb")) == NULL) {
543                 sprintf(s, "%s.Png", fname);
544                 if ((fi = fopen(s, "rb")) == NULL)
545                     fprintf(stderr, "Couldn't open %s!\n", fname);
546                     return -1;
547             }
548         }
549     }
550
551     if(!png_read_header(fi, &head)) {
552         fprintf(stderr, "%s is not a PNG file!\n", fname);
553         return -1;
554     }
555
556     if (global.max_image_width < head.width)
557         global.max_image_width = head.width;
558     if (global.max_image_height < head.height)
559         global.max_image_height = head.height;
560
561     fclose(fi);
562
563     return 0;
564 }
565
566 int args_callback_option(char *arg, char *val)
567 {
568     int res = 0;
569     if (arg[1])
570         res = -1;
571     else
572         switch (arg[0]) {
573         case 'r':
574             if (val)
575                 global.framerate = atoi(val);
576             if ((global.framerate < 1) ||(global.framerate > 5000)) {
577                 if (VERBOSE(1))
578                     fprintf(stderr,
579                             "Error: You must specify a valid framerate between 1 and 10000.\n");
580                 exit(1);
581             }
582             res = 1;
583             break;
584
585         case 'o':
586             if (val)
587                 global.outfile = val;
588             res = 1;
589             break;
590
591         case 'v':
592             if (val)
593                 global.verbose = atoi(val);
594             res = 1;
595             break;
596
597         case 'X':
598             if (val)
599                 global.force_width = atoi(val);
600             res = 1;
601             break;
602
603         case 'Y':
604             if (val)
605                 global.force_height = atoi(val);
606             res = 1;
607             break;
608
609         case 'V':
610             printf("png2swf - part of %s %s\n", PACKAGE, VERSION);
611             exit(0);
612
613         default:
614             res = -1;
615             break;
616         }
617
618     if (res < 0) {
619         if (VERBOSE(1))
620             fprintf(stderr, "Unknown option: -%s\n", arg);
621         exit(1);
622         return 0;
623     }
624     return res;
625 }
626
627 struct options_t options[] = 
628
629 {"o", "output"},
630 {"r", "rate"},
631 {"v", "verbose"},
632 {"X", "width"},
633 {"Y", "height"},
634 {"V", "version"},
635 };
636
637 int args_callback_longoption(char *name, char *val)
638 {
639     return args_long2shortoption(options, name, val);
640 }
641
642 int args_callback_command(char *arg, char *next)        // actually used as filename
643 {
644     char *s;
645     if (CheckInputFile(arg, &s) < 0) {
646         if (VERBOSE(1))
647             fprintf(stderr, "Error opening input file: %s\n", arg);
648         free(s);
649     } else {
650         image[global.nfiles].filename = s;
651         global.nfiles++;
652         if (global.nfiles >= MAX_INPUT_FILES) {
653             if (VERBOSE(1))
654                 fprintf(stderr, "Error: Too many input files.\n");
655             exit(1);
656         }
657     }
658     return 0;
659 }
660
661 void args_callback_usage(char *name)
662 {
663     printf("Usage: %s  [-options [value]] imagefiles[.png] [...]\n", name);
664     printf("-r framerate          (rate) Set movie framerate (100/sec)\n");
665     printf("-o outputfile         (output) Set name for SWF output file\n");
666     printf("-X pixel              (width) Force movie width to pixel (default: autodetect)\n");
667     printf("-Y pixel              (height) Force movie height to pixel (default: autodetect)\n");
668     printf("-v level              (verbose) Set verbose level (0=quiet, 1=default, 2=debug)\n");
669     printf("-V                    (version) Print version information and exit\n");
670 }
671
672
673 int main(int argc, char **argv)
674 {
675     SWF swf;
676     TAG *t;
677
678     memset(&global, 0x00, sizeof(global));
679
680     global.framerate = 100;
681     global.verbose = 1;
682
683     processargs(argc, argv);
684
685     if(global.nfiles<=0)
686         return 1;
687
688     if (VERBOSE(2))
689         fprintf(stderr, "Processing %i file(s)...\n", global.nfiles);
690
691     t = MovieStart(&swf, global.framerate,
692                    global.force_width ? global.force_width : global.
693                    max_image_width,
694                    global.force_height ? global.force_height : global.
695                    max_image_height);
696
697     {
698         int i;
699         for (i = 0; i < global.nfiles; i++) {
700             if (VERBOSE(3))
701                 fprintf(stderr, "[%03i] %s\n", i,
702                         image[i].filename);
703             t = MovieAddFrame(&swf, t, image[i].filename, (i * 2) + 1);
704             free(image[i].filename);
705         }
706     }
707
708     MovieFinish(&swf, t, global.outfile);
709
710     return 0;
711 }