added support for single-color alpha masking
[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) or 2(rgb)
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/bypp;
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) {
529                 int t;
530                 if(header.mode == 3) { // 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 %s!\n", 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         }
613         free(firstline);
614
615         /* the image is now compressed and stored in data. Now let's take
616            a look at the alpha values */
617         if(header.mode == 6) {
618             for(y=0;y<header.height;y++) {
619                 U8*l = &data2[(y*header.width)*4];
620                 for(x=0;x<header.width;x++) {
621                     U8 a = l[x*4];
622                     U8 b = l[x*4+1];
623                     U8 g = l[x*4+2];
624                     U8 r = l[x*4+3];
625                     if(a==255) transparent++;
626                     else {
627                         if(a==0) opaque++;
628                         else semitransparent++;
629                         l[x*4+3]=(int)r*a/255;
630                         l[x*4+2]=(int)g*a/255;
631                         l[x*4+1]=(int)b*a/255;
632                     }
633                 }
634             }
635             if(semitransparent || opaque) {
636                 t->id = ST_DEFINEBITSLOSSLESS2;
637             }
638         }
639         swf_SetLosslessBits(t, header.width, header.height, data2, BMF_32BIT);
640         free(data2);
641     } else if(header.mode == 0 || header.mode == 3) {
642         RGBA*rgba;
643         int swf_width = BYTES_PER_SCANLINE(header.width);
644         U8*data2 = malloc(swf_width*header.height);
645         U8*tmpline = malloc(header.width);
646         int i,x,y;
647         int pos=0;
648         if(header.mode == 3) { // palette or grayscale?
649             rgba = (RGBA*)malloc(palettelen*sizeof(RGBA));
650             if(!palette) {
651                 fprintf(stderr, "Error: No palette found!\n");
652                 exit(1);
653             }
654             /* 24->32 bit conversion */
655             for(i=0;i<palettelen;i++) {
656                 rgba[i].r = palette[i*3+0];
657                 rgba[i].g = palette[i*3+1];
658                 rgba[i].b = palette[i*3+2];
659                 if(alphapalette && i<alphapalettelen) {
660                     rgba[i].a = alphapalette[i];
661                     rgba[i].r = ((int)rgba[i].r*rgba[i].a)/255;
662                     rgba[i].g = ((int)rgba[i].g*rgba[i].a)/255;
663                     rgba[i].b = ((int)rgba[i].b*rgba[i].a)/255;
664                 } else {
665                     rgba[i].a = 255;
666                 }
667                 if(hasalphacolor) {
668                     if(rgba[i].r == alphacolor[0] &&
669                        rgba[i].g == alphacolor[1] &&
670                        rgba[i].b == alphacolor[2])
671                         rgba[i].a = 0;
672                 }
673             }
674         } else {
675             int mult = (0x1ff>>header.bpp);
676             palettelen = 1<<header.bpp;
677             rgba = (RGBA*)malloc(palettelen*sizeof(RGBA));
678             for(i=0;i<palettelen;i++) {
679                 rgba[i].r = i*mult;
680                 rgba[i].g = i*mult;
681                 rgba[i].b = i*mult;
682                 rgba[i].a = 255;
683                 if(hasalphacolor) {
684                     if(rgba[i].r == alphacolor[0])
685                         rgba[i].a = 0;
686                 }
687             }
688         }
689
690         for(y=0;y<header.height;y++) {
691             int mode = imagedata[pos++]; //filter mode
692             U8*old;
693             U8*dest = &data2[y*swf_width];
694             U8*src;
695             src = &imagedata[pos];
696             if(header.bpp == 8) {
697                 pos+=header.width;
698             } else {
699                 int x,s=0;
700                 int bitpos = 0;
701                 U32 v = (1<<header.bpp)-1;
702                 for(x=0;x<header.width;x++) {
703                     U32 r = src[s/8]<<8 | 
704                             src[s/8+1];
705                     int t;
706                     tmpline[x] = (r>>(16-header.bpp-(s&7)))&v;
707                     s+=header.bpp;
708                 }
709                 src = tmpline;
710                 pos+=(header.width*header.bpp+7)/8;
711             }
712
713             if(!y) {
714                 memset(data2,0,swf_width);
715                 old = &data2[y*swf_width];
716             } else {
717                 old = &data2[(y-1)*swf_width];
718             }
719             applyfilter1(mode, src, old, dest, header.width);
720         }
721         swf_SetLosslessBitsIndexed(t, header.width, header.height, data2, rgba, palettelen);
722         free(tmpline);
723         free(rgba);
724         free(data2);
725     }
726
727     t = swf_InsertTag(t, ST_DEFINESHAPE3);
728
729     swf_ShapeNew(&s);
730     swf_GetMatrix(NULL, &m);
731     m.sx = (int)(20 * 0x10000);
732     m.sy = (int)(20 * 0x10000);
733     m.tx = -10;
734     m.ty = -10;
735     fs = swf_ShapeAddBitmapFillStyle(s, &m, id, 1);
736
737     swf_SetU16(t, id + 1);      // id
738
739     r.xmin = r.ymin = 0;
740     r.xmax = header.width * 20;
741     r.ymax = header.height * 20;
742     swf_SetRect(t, &r);
743
744     swf_SetShapeHeader(t, s);
745
746     swf_ShapeSetAll(t, s, 0, 0, 0, fs, 0);
747     swf_ShapeSetLine(t, s, r.xmax, 0);
748     swf_ShapeSetLine(t, s, 0, r.ymax);
749     swf_ShapeSetLine(t, s, -r.xmax, 0);
750     swf_ShapeSetLine(t, s, 0, -r.ymax);
751
752     swf_ShapeSetEnd(t);
753
754     t = swf_InsertTag(t, ST_REMOVEOBJECT2);
755     swf_SetU16(t, 50);          // depth
756
757     t = swf_InsertTag(t, ST_PLACEOBJECT2);
758
759     swf_GetMatrix(NULL, &m);
760     m.sx = (int)(0x10000 * global.scale);
761     m.sy = (int)(0x10000 * global.scale);
762
763     if(custom_move) {
764         m.tx = move_x*20;
765         m.ty = move_y*20;
766     } else {
767         m.tx = (swf->movieSize.xmax - (int) (header.width * global.scale * 20)) / 2;
768         m.ty = (swf->movieSize.ymax - (int) (header.height * global.scale * 20)) / 2;
769     }
770     swf_ObjectPlace(t, id + 1, 50, &m, NULL, NULL);
771
772     t = swf_InsertTag(t, ST_SHOWFRAME);
773
774     fclose(fi);
775
776     return t;
777 }
778
779
780 int CheckInputFile(char *fname, char **realname)
781 {
782     FILE *fi;
783     char *s = malloc(strlen(fname) + 5);
784     struct png_header head;
785
786     if (!s)
787         exit(2);
788     (*realname) = s;
789     strcpy(s, fname);
790
791     // Check whether file exists (with typical extensions)
792
793     if ((fi = fopen(s, "rb")) == NULL) {
794         sprintf(s, "%s.png", fname);
795         if ((fi = fopen(s, "rb")) == NULL) {
796             sprintf(s, "%s.PNG", fname);
797             if ((fi = fopen(s, "rb")) == NULL) {
798                 sprintf(s, "%s.Png", fname);
799                 if ((fi = fopen(s, "rb")) == NULL) {
800                     fprintf(stderr, "Couldn't open %s!\n", fname);
801                     return -1;
802                 }
803             }
804         }
805     }
806
807     if(!png_read_header(fi, &head)) {
808         fprintf(stderr, "%s is not a PNG file!\n", fname);
809         return -1;
810     }
811
812     if (global.max_image_width < head.width)
813         global.max_image_width = head.width;
814     if (global.max_image_height < head.height)
815         global.max_image_height = head.height;
816
817     fclose(fi);
818
819     return 0;
820 }
821
822 int args_callback_option(char *arg, char *val)
823 {
824     int res = 0;
825     if (arg[1])
826         res = -1;
827     else
828         switch (arg[0]) {
829         case 'r':
830             if (val)
831                 global.framerate = atof(val);
832             /* removed framerate>0 restriction in order to make
833                Flash Communication Server compatible SWFs */
834             if ((global.framerate < 0) ||(global.framerate >= 256.0)) {
835                 if (VERBOSE(1))
836                     fprintf(stderr,
837                             "Error: You must specify a valid framerate between 1/256 and 255.\n");
838                 exit(1);
839             }
840             res = 1;
841             break;
842
843         case 'o':
844             if (val)
845                 global.outfile = val;
846             res = 1;
847             break;
848
849         case 's':
850             global.scale = atof(val)/100;
851             res = 1;
852             break;
853
854         case 'z':
855             global.version = 6;
856             res = 0;
857             break;
858
859         case 'T':
860             global.version = atoi(val);
861             res = 1;
862             break;
863
864         case 'C':
865             global.do_cgi = 1;
866             break;
867
868         case 'v':
869             global.verbose++;
870             res = 0;
871             break;
872
873         case 'q':
874             global.verbose--;
875             if(global.verbose<0)
876                 global.verbose = 0;
877             res = 0;
878             break;
879
880         case 'X':
881             if (val)
882                 global.force_width = atoi(val);
883             res = 1;
884             break;
885
886         case 'Y':
887             if (val)
888                 global.force_height = atoi(val);
889             res = 1;
890             break;
891
892         case 'V':
893             printf("png2swf - part of %s %s\n", PACKAGE, VERSION);
894             exit(0);
895    
896         case 'c': {
897             char*s = strdup(val);
898             char*x1 = strtok(s, ":");
899             char*y1 = strtok(0, ":");
900             char*x2 = strtok(0, ":");
901             char*y2 = strtok(0, ":");
902             if(!(x1 && y1 && x2 && y2)) {
903                 fprintf(stderr, "-m option requires four arguments, <x1>:<y1>:<x2>:<y2>\n");
904                 exit(1);
905             }
906             custom_clip = 1;
907             clip_x1 = atoi(x1);
908             clip_y1 = atoi(y1);
909             clip_x2 = atoi(x2);
910             clip_y2 = atoi(y2);
911             free(s);
912
913             res = 1;
914             break;
915         }
916
917         case 'm': {
918             char*s = strdup(val);
919             char*c = strchr(s, ':');
920             if(!c) {
921                 fprintf(stderr, "-m option requires two arguments, <x>:<y>\n");
922                 exit(1);
923             }
924             *c = 0;
925             custom_move = 1;
926             move_x = atoi(val);
927             move_y = atoi(c+1);
928             free(s);
929
930             res = 1;
931             break;
932         }
933
934         default:
935             res = -1;
936             break;
937         }
938
939     if (res < 0) {
940         if (VERBOSE(1))
941             fprintf(stderr, "Unknown option: -%s\n", arg);
942         exit(1);
943         return 0;
944     }
945     return res;
946 }
947
948 static struct options_t options[] = {
949 {"r", "rate"},
950 {"o", "output"},
951 {"z", "zlib"},
952 {"X", "pixel"},
953 {"Y", "pixel"},
954 {"v", "verbose"},
955 {"q", "quiet"},
956 {"C", "cgi"},
957 {"V", "version"},
958 {"s", "scale"},
959 {0,0}
960 };
961
962 int args_callback_longoption(char *name, char *val)
963 {
964     return args_long2shortoption(options, name, val);
965 }
966
967 int args_callback_command(char *arg, char *next)        // actually used as filename
968 {
969     char *s;
970     if (CheckInputFile(arg, &s) < 0) {
971         if (VERBOSE(1))
972             fprintf(stderr, "Error opening input file: %s\n", arg);
973         free(s);
974     } else {
975         image[global.nfiles].filename = s;
976         global.nfiles++;
977         if (global.nfiles >= MAX_INPUT_FILES) {
978             if (VERBOSE(1))
979                 fprintf(stderr, "Error: Too many input files.\n");
980             exit(1);
981         }
982     }
983     return 0;
984 }
985
986 void args_callback_usage(char *name)
987 {
988     printf("\n");
989     printf("Usage: %s [-X width] [-Y height] [-o file.swf] [-r rate] file1.png [file2.png...]\n", name);
990     printf("\n");
991     printf("-r , --rate <framerate>        Set movie framerate (frames per second)\n");
992     printf("-o , --output <filename>       Set name for SWF output file.\n");
993     printf("-z , --zlib <zlib>             Enable Flash 6 (MX) Zlib Compression\n");
994     printf("-X , --pixel <width>           Force movie width to <width> (default: autodetect)\n");
995     printf("-Y , --pixel <height>          Force movie height to <height> (default: autodetect)\n");
996     printf("-v , --verbose <level>         Set verbose level (0=quiet, 1=default, 2=debug)\n");
997     printf("-q , --quiet                   Omit normal log messages, only log errors\n");
998     printf("-C , --cgi                     For use as CGI- prepend http header, write to stdout\n");
999     printf("-V , --version                 Print version information and exit\n");
1000     printf("-s , --scale <percent>         Scale image to <percent>% size.\n");
1001     printf("\n");
1002 }
1003
1004 int main(int argc, char **argv)
1005 {
1006     SWF swf;
1007     TAG *t;
1008
1009     memset(&global, 0x00, sizeof(global));
1010
1011     global.framerate = 1.0;
1012     global.verbose = 1;
1013     global.version = 4;
1014     global.scale = 1.0;
1015
1016     processargs(argc, argv);
1017     
1018     if(global.nfiles<=0) {
1019         fprintf(stderr, "No png files found in arguments\n");
1020         return 1;
1021     }
1022
1023     if (VERBOSE(2))
1024         fprintf(stderr, "Processing %i file(s)...\n", global.nfiles);
1025
1026     t = MovieStart(&swf, global.framerate,
1027                    global.force_width ? global.force_width : (int)(global.max_image_width*global.scale),
1028                    global.force_height ? global.force_height : (int)(global.max_image_height*global.scale));
1029
1030     {
1031         int i;
1032         for (i = 0; i < global.nfiles; i++) {
1033             if (VERBOSE(3))
1034                 fprintf(stderr, "[%03i] %s\n", i,
1035                         image[i].filename);
1036             t = MovieAddFrame(&swf, t, image[i].filename, (i * 2) + 1);
1037             free(image[i].filename);
1038         }
1039     }
1040
1041     MovieFinish(&swf, t, global.outfile);
1042
1043     return 0;
1044 }