small improvement in error logging
[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,2003 Matthias Kramm <kramm@quiss.org>
8  
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
22  
23 #include <stdio.h>
24 #include <math.h>
25 #include <fcntl.h>
26 #include <zlib.h>
27 #include "../lib/rfxswf.h"
28 #include "../lib/args.h"
29
30 #define MAX_INPUT_FILES 1024
31 #define VERBOSE(x) (global.verbose>=x)
32
33 struct {
34     float framerate;
35     int max_image_width;
36     int max_image_height;
37     int force_width;
38     int force_height;
39     int nfiles;
40     int verbose;
41     int do_cgi;
42     int version;
43     char *outfile;
44     float scale;
45 } global;
46
47 struct {
48     char *filename;
49 } image[MAX_INPUT_FILES];
50
51 static int custom_move=0;
52 static int move_x=0;
53 static int move_y=0;
54 static int clip_x1=0,clip_y1=0,clip_x2=0,clip_y2=0;
55 static int custom_clip = 0;
56
57 TAG *MovieStart(SWF * swf, float framerate, int dx, int dy)
58 {
59     TAG *t;
60     RGBA rgb;
61
62     memset(swf, 0x00, sizeof(SWF));
63
64     swf->fileVersion = global.version;
65     swf->frameRate = (int)(256.0 * framerate);
66     if(custom_clip) {
67         swf->movieSize.xmin = clip_x1 * 20;
68         swf->movieSize.ymin = clip_y1 * 20;
69         swf->movieSize.xmax = clip_x2 * 20;
70         swf->movieSize.ymax = clip_y2 * 20;
71     } else {
72         swf->movieSize.xmax = dx * 20;
73         swf->movieSize.ymax = dy * 20;
74     }
75
76     t = swf->firstTag = swf_InsertTag(NULL, ST_SETBACKGROUNDCOLOR);
77
78     rgb.r = rgb.g = rgb.b = rgb.a = 0x00;
79     rgb.g = 0xff; //<--- handy for testing alpha conversion
80     swf_SetRGB(t, &rgb);
81
82     return t;
83 }
84
85 int MovieFinish(SWF * swf, TAG * t, char *sname)
86 {
87     int f, so = fileno(stdout);
88     t = swf_InsertTag(t, ST_END);
89
90     if ((!isatty(so)) && (!sname))
91         f = so;
92     else {
93         if (!sname)
94             sname = "output.swf";
95         f = open(sname,O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0644);
96     }
97
98     if(global.do_cgi) {
99         if FAILED(swf_WriteCGI(swf)) fprintf(stderr,"WriteCGI() failed.\n");
100     } else {
101         if(global.version >= 6) {
102             if (swf_WriteSWC(f, swf)<0) 
103                     fprintf(stderr, "Unable to write output file: %s\n", sname);
104         } else {
105             if (swf_WriteSWF(f, swf)<0) 
106                     fprintf(stderr, "Unable to write output file: %s\n", sname);
107         }
108         if (f != so)
109             close(f);
110     }
111
112     swf_FreeTags(swf);
113     return 0;
114 }
115
116 int png_read_chunk(char (*head)[4], int*destlen, U8**destdata, FILE*fi)
117 {
118     unsigned int len;
119     if(destlen) *destlen=0;
120     if(destdata) *destdata=0;
121     if(!fread(&len, 4, 1, fi))
122         return 0;
123     if(!fread(head, 4, 1, fi))
124         return 0;
125     len = REVERSESWAP32(len);
126     if(destlen) *destlen = len;
127     if(destdata) {
128         if(len)
129             *destdata = malloc(len);
130         else 
131             *destdata = 0;
132         if(!fread(*destdata, len, 1, fi)) {
133             *destdata = 0;
134             if(destlen) *destlen=0;
135             return 0;
136         }
137         fseek(fi, 4, SEEK_CUR);
138
139     } else {
140         fseek(fi, len+4, SEEK_CUR);
141     }
142     return 1;
143 }
144
145 unsigned int png_get_dword(FILE*fi)
146 {
147     unsigned int a;
148     fread(&a,4,1,fi);
149     return REVERSESWAP32(a);
150 }
151
152 struct png_header
153 {
154     int width;
155     int height;
156     int bpp;
157     int mode;
158 };
159
160 int png_read_header(FILE*fi, struct png_header*header)
161 {
162     char id[4];
163     int len;
164     int ok=0;
165     U8 head[8] = {137,80,78,71,13,10,26,10};
166     U8 head2[8];
167     U8*data;
168     fread(head2,8,1,fi);
169     if(strncmp(head,head2,4))
170         return 0;
171    
172     while(png_read_chunk(&id, &len, &data, fi))
173     {
174         if(VERBOSE(2))
175             printf("%c%c%c%c %d\n", id[0],id[1],id[2],id[3],len);
176         if(!strncasecmp(id, "IHDR", 4)) {
177             char a,b,c,f,i;
178             if(len < 8) exit(1);
179             header->width = REVERSESWAP32(*(U32*)&data[0]);
180             header->height = REVERSESWAP32(*(U32*)&data[4]);
181             a = data[8];      // should be 8
182             b = data[9];      // should be 3(indexed), 2(rgb), 0(grayscale) or 6(truecolor+alpha)
183
184             c = data[10];     // compression mode (0)
185             f = data[11];     // filter mode (0)
186             i = data[12];     // interlace mode (0)
187         
188             if(VERBOSE(2)) printf("image mode:%d\n", b);
189             if(VERBOSE(2)) printf("bpp: %d\n", a);
190             if(VERBOSE(2)) printf("compression: %d\n", c);
191             if(VERBOSE(2)) printf("filter: %d\n", f);
192             if(VERBOSE(2)) printf("interlace: %d\n", i);
193
194             if(b!=0 && b!=2 && b!=3 && b!=6) {
195                 fprintf(stderr, "Image mode %d not supported!\n", b);
196                 if(b == 4) {
197                     fprintf(stderr, "(This is a grayscale image with alpha channel-\n");
198                     fprintf(stderr, " try converting it into an RGB image with alpha channel)\n");
199                 }
200                 exit(1);
201             }
202             if(a!=8 && (b==2 || b==6)) {
203                 fprintf(stderr, "Bpp %d in mode %d not supported!\n", a);
204                 exit(1);
205             }
206             if(c!=0) {
207                 fprintf(stderr, "Compression mode %d not supported!\n", c);
208                 exit(1);
209             }
210             if(f!=0) {
211                 fprintf(stderr, "Filter mode %d not supported!\n", f);
212                 exit(1);
213             }
214             if(i!=0) {
215                 fprintf(stderr, "Interlace mode %d not supported!\n", i);
216                 exit(1);
217             }
218             if(VERBOSE(2))
219                 printf("%dx%d %d %d %d %d %d\n",header->width, header->height, a,b,c,f,i);
220             header->bpp = a;
221             header->mode = b;
222             ok = 1;
223         } 
224         
225         free(data);
226     }
227     return ok;
228 }
229
230 typedef unsigned char byte;
231 #define ABS(a) ((a)>0?(a):(-(a)))
232 byte inline PaethPredictor (byte a,byte b,byte c)
233 {
234         // a = left, b = above, c = upper left
235         int p = a + b - c;        // initial estimate
236         int pa = ABS(p - a);      // distances to a, b, c
237         int pb = ABS(p - b);
238         int pc = ABS(p - c);
239         // return nearest of a,b,c,
240         // breaking ties in order a,b,c.
241         if (pa <= pb && pa <= pc) 
242                 return a;
243         else if (pb <= pc) 
244                 return b;
245         else return c;
246 }
247
248 void applyfilter3(int mode, U8*src, U8*old, U8*dest, int width)
249 {
250     int x;
251     unsigned char lastr=0;
252     unsigned char lastg=0;
253     unsigned char lastb=0;
254     unsigned char upperlastr=0;
255     unsigned char upperlastg=0;
256     unsigned char upperlastb=0;
257
258     if(mode==0) {
259         for(x=0;x<width;x++) {
260             dest[0] = 255;
261             dest[1] = src[0];
262             dest[2] = src[1];
263             dest[3] = src[2];
264             dest+=4;
265             src+=3;
266         }
267     }
268     else if(mode==1) {
269         for(x=0;x<width;x++) {
270             dest[0] = 255;
271             dest[1] = src[0]+lastr;
272             dest[2] = src[1]+lastg;
273             dest[3] = src[2]+lastb;
274             lastr = dest[1];
275             lastg = dest[2];
276             lastb = dest[3];
277             dest+=4;
278             src+=3;
279         }
280     }
281     else if(mode==2) {
282         for(x=0;x<width;x++) {
283             dest[0] = 255;
284             dest[1] = src[0]+old[1];
285             dest[2] = src[1]+old[2];
286             dest[3] = src[2]+old[3];
287             dest+=4;
288             old+=4;
289             src+=3;
290         }
291     }
292     else if(mode==3) {
293         for(x=0;x<width;x++) {
294             dest[0] = 255;
295             dest[1] = src[0]+(old[1]+lastr)/2;
296             dest[2] = src[1]+(old[2]+lastg)/2;
297             dest[3] = src[2]+(old[3]+lastb)/2;
298             lastr = dest[1];
299             lastg = dest[2];
300             lastb = dest[3];
301             dest+=4;
302             old+=4;
303             src+=3;
304         }
305     }
306     else if(mode==4) {
307         for(x=0;x<width;x++) {
308             dest[0] = 255;
309             dest[1] = src[0]+PaethPredictor(lastr,old[1],upperlastr);
310             dest[2] = src[1]+PaethPredictor(lastg,old[2],upperlastg);
311             dest[3] = src[2]+PaethPredictor(lastb,old[3],upperlastb);
312             lastr = dest[1];
313             lastg = dest[2];
314             lastb = dest[3];
315             upperlastr = old[1];
316             upperlastg = old[2];
317             upperlastb = old[3];
318             dest+=4;
319             old+=4;
320             src+=3;
321         }
322     }    
323
324 }
325
326 void applyfilter4(int mode, U8*src, U8*old, U8*dest, int width)
327 {
328     int x;
329     unsigned char lastr=0;
330     unsigned char lastg=0;
331     unsigned char lastb=0;
332     unsigned char lasta=0; //TODO: 255?
333     unsigned char upperlastr=0;
334     unsigned char upperlastg=0;
335     unsigned char upperlastb=0;
336     unsigned char upperlasta=0; //TODO: 255?
337
338     if(mode==0) {
339         for(x=0;x<width;x++) {
340             dest[0] = src[3];
341             dest[1] = src[0];
342             dest[2] = src[1];
343             dest[3] = src[2];
344             dest+=4;
345             src+=4;
346         }
347     }
348     else if(mode==1) {
349         for(x=0;x<width;x++) {
350             dest[0] = src[3]+lasta;
351             dest[1] = src[0]+lastr;
352             dest[2] = src[1]+lastg;
353             dest[3] = src[2]+lastb;
354             lasta = dest[0];
355             lastr = dest[1];
356             lastg = dest[2];
357             lastb = dest[3];
358             dest+=4;
359             src+=4;
360         }
361     }
362     else if(mode==2) {
363         for(x=0;x<width;x++) {
364             dest[0] = src[3]+old[0];
365             dest[1] = src[0]+old[1];
366             dest[2] = src[1]+old[2];
367             dest[3] = src[2]+old[3];
368             dest+=4;
369             old+=4;
370             src+=4;
371         }
372     }
373     else if(mode==3) {
374         for(x=0;x<width;x++) {
375             dest[0] = src[3]+(old[0]+lasta)/2;
376             dest[1] = src[0]+(old[1]+lastr)/2;
377             dest[2] = src[1]+(old[2]+lastg)/2;
378             dest[3] = src[2]+(old[3]+lastb)/2;
379             lasta = dest[0];
380             lastr = dest[1];
381             lastg = dest[2];
382             lastb = dest[3];
383             dest+=4;
384             old+=4;
385             src+=4;
386         }
387     }
388     else if(mode==4) {
389         for(x=0;x<width;x++) {
390             dest[0] = src[3]+PaethPredictor(lasta,old[0],upperlasta);
391             dest[1] = src[0]+PaethPredictor(lastr,old[1],upperlastr);
392             dest[2] = src[1]+PaethPredictor(lastg,old[2],upperlastg);
393             dest[3] = src[2]+PaethPredictor(lastb,old[3],upperlastb);
394             lasta = dest[0];
395             lastr = dest[1];
396             lastg = dest[2];
397             lastb = dest[3];
398             upperlasta = old[0];
399             upperlastr = old[1];
400             upperlastg = old[2];
401             upperlastb = old[3];
402             dest+=4;
403             old+=4;
404             src+=4;
405         }
406     }    
407
408 }
409
410 void applyfilter1(int mode, U8*src, U8*old, U8*dest, int width)
411 {
412     int x;
413     unsigned char last=0;
414     unsigned char upperlast=0;
415
416     if(mode==0) {
417         for(x=0;x<width;x++) {
418             *dest = *src;
419             dest++;
420             src++;
421         }
422     }
423     else if(mode==1) {
424         for(x=0;x<width;x++) {
425             *dest = *src+last;
426             last = *dest;
427             dest++;
428             src++;
429         }
430     }
431     else if(mode==2) {
432         for(x=0;x<width;x++) {
433             *dest = *src+*old;
434             dest++;
435             old++;
436             src++;
437         }
438     }
439     else if(mode==3) {
440         for(x=0;x<width;x++) {
441             *dest = *src+(*old+last)/2;
442             last = *dest;
443             dest++;
444             old++;
445             src++;
446         }
447     }
448     else if(mode==4) {
449         for(x=0;x<width;x++) {
450             *dest = *src+PaethPredictor(last,*old,upperlast);
451             last = *dest;
452             upperlast = *old;
453             dest++;
454             old++;
455             src++;
456         }
457     }    
458
459 }
460
461 TAG *MovieAddFrame(SWF * swf, TAG * t, char *sname, int id)
462 {
463     SHAPE *s;
464     SRECT r;
465     MATRIX m;
466     int fs;
467
468     char tagid[4];
469     int len;
470     U8*data;
471     U8*imagedata;
472     U8*zimagedata=0;
473     unsigned long int imagedatalen;
474     unsigned long int zimagedatalen=0;
475     U8*palette = 0;
476     int palettelen = 0;
477     U8*alphapalette = 0;
478     int alphapalettelen = 0;
479     struct png_header header;
480     int bypp;
481     U8 alphacolor[3];
482     int hasalphacolor=0;
483
484     FILE *fi;
485     U8 *scanline;
486
487     if ((fi = fopen(sname, "rb")) == NULL) {
488         if (VERBOSE(1))
489             fprintf(stderr, "Read access failed: %s\n", sname);
490         return t;
491     }
492
493     if(!png_read_header(fi, &header))
494         return 0;
495
496     if(header.mode == 3 || header.mode == 0) bypp = 1;
497     else
498     if(header.mode == 2) bypp = 3;
499     else
500     if(header.mode == 6) bypp = 4;
501     else
502         return 0;
503     imagedatalen = bypp * header.width * header.height + 65536;
504     imagedata = malloc(imagedatalen);
505
506     fseek(fi,8,SEEK_SET);
507     while(!feof(fi))
508     {
509         if(!png_read_chunk(&tagid, &len, &data, fi))
510             break;
511         if(!strncmp(tagid, "IEND", 4)) {
512             break;
513         }
514         if(!strncmp(tagid, "PLTE", 4)) {
515             palette = data;
516             palettelen = len/3;
517             data = 0; //don't free data
518             if(VERBOSE(2))
519                 printf("%d colors in palette\n", palettelen);
520         }
521         if(!strncmp(tagid, "tRNS", 4)) {
522             if(header.mode == 3) {
523                 alphapalette = data;
524                 alphapalettelen = len;
525                 data = 0; //don't free data
526                 if(VERBOSE(2))
527                     printf("found %d alpha colors\n", alphapalettelen);
528             } else if(header.mode == 0 || header.mode == 2) {
529                 int t;
530                 if(header.mode == 2) { // palette or grayscale?
531                     alphacolor[0] = data[1];
532                     alphacolor[1] = data[3];
533                     alphacolor[2] = data[5];
534                 } else {
535                     alphacolor[0] = alphacolor[1] = alphacolor[2] = data[1];
536                 }
537                 if(VERBOSE(2))
538                     printf("found alpha color: %02x%02x%02x\n", alphacolor[0], alphacolor[1], alphacolor[2]);
539                 hasalphacolor = 1;
540             } else {
541                 if(VERBOSE(2))
542                     printf("ignoring tRNS %d entry (%d bytes)\n", header.mode, len);
543             }
544         }
545         if(!strncmp(tagid, "IDAT", 4)) {
546             if(!zimagedata) {
547                 zimagedatalen = len;
548                 zimagedata = malloc(len);
549                 memcpy(zimagedata,data,len);
550             } else {
551                 zimagedata = realloc(zimagedata, zimagedatalen+len);
552                 memcpy(&zimagedata[zimagedatalen], data, len);
553                 zimagedatalen += len;
554             }
555         }
556         if(data)
557             free(data);
558     }
559     
560     if(!zimagedata || uncompress(imagedata, &imagedatalen, zimagedata, zimagedatalen) != Z_OK) {
561         fprintf(stderr, "Couldn't uncompress IDAT chunk (%d bytes) in %s!\n", imagedatalen, sname);
562         if(zimagedata)
563             free(zimagedata);
564         return 0;
565     }
566     free(zimagedata);
567
568     if(alphapalette || hasalphacolor)
569         t = swf_InsertTag(t, ST_DEFINEBITSLOSSLESS2);
570     else
571         t = swf_InsertTag(t, ST_DEFINEBITSLOSSLESS);
572
573     swf_SetU16(t, id);          // id
574     if(header.mode == 2 || header.mode == 6) {
575         U8*data2 = malloc(header.width*header.height*4);
576         int i,s=0;
577         int x,y;
578         int pos=0;
579         int opaque=0;
580         int transparent=0;
581         int semitransparent=0;
582         /* in case for mode 2, the following also performs 24->32 bit conversion */
583         unsigned char* firstline = malloc(header.width*4);
584
585         for(y=0;y<header.height;y++) {
586             int mode = imagedata[pos++]; //filter mode
587             U8*src;
588             U8*dest;
589             U8*old;
590             dest = &data2[(y*header.width)*4];
591
592             if(header.bpp == 8)
593             {
594                 /* one byte per pixel */
595                 src = &imagedata[pos];
596                 pos+=header.width*(header.mode==6?4:3);
597             } else {
598                 /* not implemented yet */
599                 exit(1);
600             }
601
602             if(!y) {
603                 old = firstline;
604                 memset(old, 0, header.width*4); //TODO: fill alpha with 255?
605             } else {
606                 old = &data2[(y-1)*header.width*4];
607             }
608             if(header.mode==6) {
609                 applyfilter4(mode, src, old, dest, header.width);
610             } else if(header.mode==2) {
611                 applyfilter3(mode, src, old, dest, header.width);
612                 /* replace alpha color */
613                 if(hasalphacolor) {
614                     int x;
615                     for(x=0;x<header.width;x++) {
616                         if(dest[x*4+1] == alphacolor[0] &&
617                            dest[x*4+2] == alphacolor[1] &&
618                            dest[x*4+3] == alphacolor[2]) {
619                             *(U32*)&dest[x*4] = 0;
620                         }
621                     }
622                 }
623             }
624         }
625         free(firstline);
626
627         /* the image is now compressed and stored in data. Now let's take
628            a look at the alpha values */
629         if(header.mode == 6) {
630             for(y=0;y<header.height;y++) {
631                 U8*l = &data2[(y*header.width)*4];
632                 for(x=0;x<header.width;x++) {
633                     U8 a = l[x*4];
634                     U8 b = l[x*4+1];
635                     U8 g = l[x*4+2];
636                     U8 r = l[x*4+3];
637                     if(a==255) transparent++;
638                     else {
639                         if(a==0) opaque++;
640                         else semitransparent++;
641                         l[x*4+3]=(int)r*a/255;
642                         l[x*4+2]=(int)g*a/255;
643                         l[x*4+1]=(int)b*a/255;
644                     }
645                 }
646             }
647             if(semitransparent || opaque) {
648                 t->id = ST_DEFINEBITSLOSSLESS2;
649             }
650         }
651         swf_SetLosslessBits(t, header.width, header.height, data2, BMF_32BIT);
652         free(data2);
653     } else if(header.mode == 0 || header.mode == 3) {
654         RGBA*rgba;
655         int swf_width = BYTES_PER_SCANLINE(header.width);
656         U8*data2 = malloc(swf_width*header.height);
657         U8*tmpline = malloc(header.width);
658         int i,x,y;
659         int pos=0;
660         if(header.mode == 3) { // palette or grayscale?
661             rgba = (RGBA*)malloc(palettelen*sizeof(RGBA));
662             if(!palette) {
663                 fprintf(stderr, "Error: No palette found!\n");
664                 exit(1);
665             }
666             /* 24->32 bit conversion */
667             for(i=0;i<palettelen;i++) {
668                 rgba[i].r = palette[i*3+0];
669                 rgba[i].g = palette[i*3+1];
670                 rgba[i].b = palette[i*3+2];
671                 if(alphapalette && i<alphapalettelen) {
672                     rgba[i].a = alphapalette[i];
673                     rgba[i].r = ((int)rgba[i].r*rgba[i].a)/255;
674                     rgba[i].g = ((int)rgba[i].g*rgba[i].a)/255;
675                     rgba[i].b = ((int)rgba[i].b*rgba[i].a)/255;
676                 } else {
677                     rgba[i].a = 255;
678                 }
679                 if(hasalphacolor) {
680                     if(rgba[i].r == alphacolor[0] &&
681                        rgba[i].g == alphacolor[1] &&
682                        rgba[i].b == alphacolor[2]) {
683                         rgba[i].r = 0;
684                         rgba[i].g = 0;
685                         rgba[i].b = 0;
686                         rgba[i].a = 0;
687                     }
688                 }
689             }
690         } else {
691             int mult = (0x1ff>>header.bpp);
692             palettelen = 1<<header.bpp;
693             rgba = (RGBA*)malloc(palettelen*sizeof(RGBA));
694             for(i=0;i<palettelen;i++) {
695                 rgba[i].r = i*mult;
696                 rgba[i].g = i*mult;
697                 rgba[i].b = i*mult;
698                 rgba[i].a = 255;
699                 if(hasalphacolor) {
700                     if(rgba[i].r == alphacolor[0]) {
701                         rgba[i].r = 0;
702                         rgba[i].g = 0;
703                         rgba[i].b = 0;
704                         rgba[i].a = 0;
705                     }
706                 }
707             }
708         }
709
710         for(y=0;y<header.height;y++) {
711             int mode = imagedata[pos++]; //filter mode
712             U8*old;
713             U8*dest = &data2[y*swf_width];
714             U8*src;
715             src = &imagedata[pos];
716             if(header.bpp == 8) {
717                 pos+=header.width;
718             } else {
719                 int x,s=0;
720                 int bitpos = 0;
721                 U32 v = (1<<header.bpp)-1;
722                 for(x=0;x<header.width;x++) {
723                     U32 r = src[s/8]<<8 | 
724                             src[s/8+1];
725                     int t;
726                     tmpline[x] = (r>>(16-header.bpp-(s&7)))&v;
727                     s+=header.bpp;
728                 }
729                 src = tmpline;
730                 pos+=(header.width*header.bpp+7)/8;
731             }
732
733             if(!y) {
734                 memset(data2,0,swf_width);
735                 old = &data2[y*swf_width];
736             } else {
737                 old = &data2[(y-1)*swf_width];
738             }
739             applyfilter1(mode, src, old, dest, header.width);
740         }
741         swf_SetLosslessBitsIndexed(t, header.width, header.height, data2, rgba, palettelen);
742         free(tmpline);
743         free(rgba);
744         free(data2);
745     }
746
747     t = swf_InsertTag(t, ST_DEFINESHAPE3);
748
749     swf_ShapeNew(&s);
750     swf_GetMatrix(NULL, &m);
751     m.sx = (int)(20 * 0x10000);
752     m.sy = (int)(20 * 0x10000);
753     m.tx = -10;
754     m.ty = -10;
755     fs = swf_ShapeAddBitmapFillStyle(s, &m, id, 1);
756
757     swf_SetU16(t, id + 1);      // id
758
759     r.xmin = r.ymin = 0;
760     r.xmax = header.width * 20;
761     r.ymax = header.height * 20;
762     swf_SetRect(t, &r);
763
764     swf_SetShapeHeader(t, s);
765
766     swf_ShapeSetAll(t, s, 0, 0, 0, fs, 0);
767     swf_ShapeSetLine(t, s, r.xmax, 0);
768     swf_ShapeSetLine(t, s, 0, r.ymax);
769     swf_ShapeSetLine(t, s, -r.xmax, 0);
770     swf_ShapeSetLine(t, s, 0, -r.ymax);
771
772     swf_ShapeSetEnd(t);
773
774     t = swf_InsertTag(t, ST_REMOVEOBJECT2);
775     swf_SetU16(t, 50);          // depth
776
777     t = swf_InsertTag(t, ST_PLACEOBJECT2);
778
779     swf_GetMatrix(NULL, &m);
780     m.sx = (int)(0x10000 * global.scale);
781     m.sy = (int)(0x10000 * global.scale);
782
783     if(custom_move) {
784         m.tx = move_x*20;
785         m.ty = move_y*20;
786     } else {
787         m.tx = (swf->movieSize.xmax - (int) (header.width * global.scale * 20)) / 2;
788         m.ty = (swf->movieSize.ymax - (int) (header.height * global.scale * 20)) / 2;
789     }
790     swf_ObjectPlace(t, id + 1, 50, &m, NULL, NULL);
791
792     t = swf_InsertTag(t, ST_SHOWFRAME);
793
794     fclose(fi);
795
796     return t;
797 }
798
799
800 int CheckInputFile(char *fname, char **realname)
801 {
802     FILE *fi;
803     char *s = malloc(strlen(fname) + 5);
804     struct png_header head;
805
806     if (!s)
807         exit(2);
808     (*realname) = s;
809     strcpy(s, fname);
810
811     // Check whether file exists (with typical extensions)
812
813     if ((fi = fopen(s, "rb")) == NULL) {
814         sprintf(s, "%s.png", fname);
815         if ((fi = fopen(s, "rb")) == NULL) {
816             sprintf(s, "%s.PNG", fname);
817             if ((fi = fopen(s, "rb")) == NULL) {
818                 sprintf(s, "%s.Png", fname);
819                 if ((fi = fopen(s, "rb")) == NULL) {
820                     fprintf(stderr, "Couldn't open %s!\n", fname);
821                     return -1;
822                 }
823             }
824         }
825     }
826
827     if(!png_read_header(fi, &head)) {
828         fprintf(stderr, "%s is not a PNG file!\n", fname);
829         return -1;
830     }
831
832     if (global.max_image_width < head.width)
833         global.max_image_width = head.width;
834     if (global.max_image_height < head.height)
835         global.max_image_height = head.height;
836
837     fclose(fi);
838
839     return 0;
840 }
841
842 int args_callback_option(char *arg, char *val)
843 {
844     int res = 0;
845     if (arg[1])
846         res = -1;
847     else
848         switch (arg[0]) {
849         case 'r':
850             if (val)
851                 global.framerate = atof(val);
852             /* removed framerate>0 restriction in order to make
853                Flash Communication Server compatible SWFs */
854             if ((global.framerate < 0) ||(global.framerate >= 256.0)) {
855                 if (VERBOSE(1))
856                     fprintf(stderr,
857                             "Error: You must specify a valid framerate between 1/256 and 255.\n");
858                 exit(1);
859             }
860             res = 1;
861             break;
862
863         case 'o':
864             if (val)
865                 global.outfile = val;
866             res = 1;
867             break;
868
869         case 's':
870             global.scale = atof(val)/100;
871             res = 1;
872             break;
873
874         case 'z':
875             if(global.version<6)
876                 global.version = 6;
877             res = 0;
878             break;
879
880         case 'T':
881             global.version = atoi(val);
882             res = 1;
883             break;
884
885         case 'C':
886             global.do_cgi = 1;
887             break;
888
889         case 'v':
890             global.verbose++;
891             res = 0;
892             break;
893
894         case 'q':
895             global.verbose--;
896             if(global.verbose<0)
897                 global.verbose = 0;
898             res = 0;
899             break;
900
901         case 'X':
902             if (val)
903                 global.force_width = atoi(val);
904             res = 1;
905             break;
906
907         case 'Y':
908             if (val)
909                 global.force_height = atoi(val);
910             res = 1;
911             break;
912         
913         case 'V':
914             printf("png2swf - part of %s %s\n", PACKAGE, VERSION);
915             exit(0);
916    
917         case 'c': {
918             char*s = strdup(val);
919             char*x1 = strtok(s, ":");
920             char*y1 = strtok(0, ":");
921             char*x2 = strtok(0, ":");
922             char*y2 = strtok(0, ":");
923             if(!(x1 && y1 && x2 && y2)) {
924                 fprintf(stderr, "-m option requires four arguments, <x1>:<y1>:<x2>:<y2>\n");
925                 exit(1);
926             }
927             custom_clip = 1;
928             clip_x1 = atoi(x1);
929             clip_y1 = atoi(y1);
930             clip_x2 = atoi(x2);
931             clip_y2 = atoi(y2);
932             free(s);
933
934             res = 1;
935             break;
936         }
937
938         case 'm': {
939             char*s = strdup(val);
940             char*c = strchr(s, ':');
941             if(!c) {
942                 fprintf(stderr, "-m option requires two arguments, <x>:<y>\n");
943                 exit(1);
944             }
945             *c = 0;
946             custom_move = 1;
947             move_x = atoi(val);
948             move_y = atoi(c+1);
949             free(s);
950
951             res = 1;
952             break;
953         }
954
955         default:
956             res = -1;
957             break;
958         }
959
960     if (res < 0) {
961         if (VERBOSE(1))
962             fprintf(stderr, "Unknown option: -%s\n", arg);
963         exit(1);
964         return 0;
965     }
966     return res;
967 }
968
969 static struct options_t options[] = {
970 {"r", "rate"},
971 {"o", "output"},
972 {"z", "zlib"},
973 {"T", "flashversion"},
974 {"X", "pixel"},
975 {"Y", "pixel"},
976 {"v", "verbose"},
977 {"q", "quiet"},
978 {"C", "cgi"},
979 {"V", "version"},
980 {"s", "scale"},
981 {0,0}
982 };
983
984 int args_callback_longoption(char *name, char *val)
985 {
986     return args_long2shortoption(options, name, val);
987 }
988
989 int args_callback_command(char *arg, char *next)        // actually used as filename
990 {
991     char *s;
992     if (CheckInputFile(arg, &s) < 0) {
993         if (VERBOSE(1))
994             fprintf(stderr, "Error opening input file: %s\n", arg);
995         free(s);
996     } else {
997         image[global.nfiles].filename = s;
998         global.nfiles++;
999         if (global.nfiles >= MAX_INPUT_FILES) {
1000             if (VERBOSE(1))
1001                 fprintf(stderr, "Error: Too many input files.\n");
1002             exit(1);
1003         }
1004     }
1005     return 0;
1006 }
1007
1008 void args_callback_usage(char *name)
1009 {
1010     printf("\n");
1011     printf("Usage: %s [-X width] [-Y height] [-o file.swf] [-r rate] file1.png [file2.png...]\n", name);
1012     printf("\n");
1013     printf("-r , --rate <framerate>        Set movie framerate (frames per second)\n");
1014     printf("-o , --output <filename>       Set name for SWF output file.\n");
1015     printf("-z , --zlib <zlib>             Enable Flash 6 (MX) Zlib Compression\n");
1016     printf("-T , --flashversion            Set the flash version to generate\n");
1017     printf("-X , --pixel <width>           Force movie width to <width> (default: autodetect)\n");
1018     printf("-Y , --pixel <height>          Force movie height to <height> (default: autodetect)\n");
1019     printf("-v , --verbose <level>         Set verbose level (0=quiet, 1=default, 2=debug)\n");
1020     printf("-q , --quiet                   Omit normal log messages, only log errors\n");
1021     printf("-C , --cgi                     For use as CGI- prepend http header, write to stdout\n");
1022     printf("-V , --version                 Print version information and exit\n");
1023     printf("-s , --scale <percent>         Scale image to <percent>% size.\n");
1024     printf("\n");
1025 }
1026
1027 int main(int argc, char **argv)
1028 {
1029     SWF swf;
1030     TAG *t;
1031
1032     memset(&global, 0x00, sizeof(global));
1033
1034     global.framerate = 1.0;
1035     global.verbose = 1;
1036     global.version = 4;
1037     global.scale = 1.0;
1038
1039     processargs(argc, argv);
1040     
1041     if(global.nfiles<=0) {
1042         fprintf(stderr, "No png files found in arguments\n");
1043         return 1;
1044     }
1045
1046     if (VERBOSE(2))
1047         fprintf(stderr, "Processing %i file(s)...\n", global.nfiles);
1048
1049     t = MovieStart(&swf, global.framerate,
1050                    global.force_width ? global.force_width : (int)(global.max_image_width*global.scale),
1051                    global.force_height ? global.force_height : (int)(global.max_image_height*global.scale));
1052
1053     {
1054         int i;
1055         for (i = 0; i < global.nfiles; i++) {
1056             if (VERBOSE(3))
1057                 fprintf(stderr, "[%03i] %s\n", i,
1058                         image[i].filename);
1059             t = MovieAddFrame(&swf, t, image[i].filename, (i * 2) + 1);
1060             free(image[i].filename);
1061         }
1062     }
1063
1064     MovieFinish(&swf, t, global.outfile);
1065
1066     return 0;
1067 }