contributed by Daichi Shinozaki.
[swftools.git] / src / gif2swf.c
1 /* gif2swf.c
2
3    GIF to SWF converter tool
4
5    Copyright (c) 2005 Daichi Shinozaki <dseg@shield.jp>
6  
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
20
21 #include <stdio.h>
22 #include <fcntl.h>
23 #include <zlib.h>
24 #include <gif_lib.h>
25 #include "../lib/rfxswf.h"
26 #include "../lib/args.h"
27
28 #define MAX_INPUT_FILES 1024
29 #define VERBOSE(x) (global.verbose>=x)
30
31 #define PROGRAM_NAME "gif2swf"
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 } global;
45
46 struct {
47     char *filename;
48 } image[MAX_INPUT_FILES];
49
50 struct gif_header {
51    int width;
52    int height;
53 };
54
55 // Get transparency color from graphic extension block
56 //
57 // Return: transparency color or -1
58
59 int getTransparentColor(GifFileType * gft)
60 {
61   int i;
62   ExtensionBlock* ext = gft->SavedImages[0].ExtensionBlocks;
63  
64   for (i=0; i < gft->SavedImages[0].ExtensionBlockCount; i++, ext++)
65     if ((ext->Function == GRAPHICS_EXT_FUNC_CODE) &&
66         (ext->Bytes[0] & 1)) { // there is a transparent color
67       return ext->Bytes[3] == 0 ?
68         255 :                  // exception
69         ext->Bytes[3];
70     }
71
72   return -1;
73 }
74
75 TAG *MovieStart(SWF * swf, float framerate, int dx, int dy)
76 {
77     TAG *t;
78     RGBA rgb;
79
80     memset(swf, 0x00, sizeof(SWF));
81
82     swf->fileVersion = global.version;
83     swf->frameRate = (int)(256.0 * framerate);
84     swf->movieSize.xmax = dx * 20;
85     swf->movieSize.ymax = dy * 20;
86
87     t = swf->firstTag = swf_InsertTag(NULL, ST_SETBACKGROUNDCOLOR);
88     
89     rgb.r = rgb.g = rgb.b = rgb.a = 0x00;
90   
91     //rgb.g = 0xff; //<--- handy for testing alpha conversion
92     swf_SetRGB(t, &rgb);
93
94     return t;
95 }
96
97 int MovieFinish(SWF * swf, TAG * t, char *sname)
98 {
99     int f, so = fileno(stdout);
100     t = swf_InsertTag(t, ST_END);
101
102     if ((!isatty(so)) && (!sname))
103         f = so;
104     else {
105         if (!sname)
106             sname = "output.swf";
107         f = open(sname,O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0644);
108     }
109
110     if(global.do_cgi) {
111         if FAILED(swf_WriteCGI(swf)) fprintf(stderr,"WriteCGI() failed.\n");
112     } else {
113         if(global.version >= 6) {
114             if (swf_WriteSWC(f, swf)<0) 
115                 fprintf(stderr, "Unable to write output file: %s\n", sname);
116         } else {
117             if (swf_WriteSWF(f, swf)<0)
118                 fprintf(stderr, "Unable to write output file: %s\n", sname);
119         }
120         if (f != so)
121             close(f);
122     }
123
124     swf_FreeTags(swf);
125     return 0;
126 }
127
128 TAG *MovieAddFrame(SWF * swf, TAG * t, char *sname, int id)
129 {
130     SHAPE *s;
131     SRECT r;
132     MATRIX m;
133     int fs;
134
135     U8 *imagedata, *from, *to;
136     RGBA* pal;
137   
138     struct gif_header header;
139
140     int i, j, bgcolor, numcolors = 0, alphapalette = 0;
141     int bpp; // byte per pixel
142     int swf_width, padlen;
143   
144     ColorMapObject* colormap;
145     GifColorType c;
146     int interlacedOffset[] = { 0, 4, 2, 1 }; // The way Interlaced image should
147     int interlacedJumps[] = { 8, 8, 4, 2 };  // be read - offsets and jumps...
148   
149     FILE *fi;
150     GifFileType* gft; 
151   
152     if ((fi = fopen(sname, "rb")) == NULL) {
153         if (VERBOSE(1))
154             fprintf(stderr, "Read access failed: %s\n", sname);
155         return t;
156     }
157   
158     if((gft = DGifOpenFileName(sname)) == NULL) {  
159         fprintf(stderr, "%s is not a GIF file!\n", sname);
160         return t;
161     }
162     if(DGifSlurp(gft) != GIF_OK) {
163         PrintGifError();
164         return t;
165     }
166
167     header.width  = gft->SWidth;
168     header.height = gft->SHeight;
169
170     pal = (RGBA*)malloc(256*sizeof(RGBA));
171     memset(pal,0,256*sizeof(RGBA));
172   
173     // Local colormap has precedence over Global colormap
174     colormap = gft->Image.ColorMap ? gft->Image.ColorMap : gft->SColorMap;
175     numcolors = colormap->ColorCount;
176     alphapalette = getTransparentColor(gft);
177     bpp = (alphapalette >= 0 ? 4 : 3);
178
179     // bgColor is the background color to fill the bitmap with
180     // if an image is smaller than screen coordinates
181     if (gft->SColorMap) {               // There is a GlobalColorMap
182       bgcolor = gft->SBackGroundColor;  // The BackGroundColor is meaningful
183     } else {
184       if (alphapalette >= 0)            // There is a transparency color
185         bgcolor = alphapalette;         // set the bgColor to tranparent
186       else
187         bgcolor = 0;                    // Don't know what to do here.
188                                         // If this doesn't work, we could
189                                         // create a new color and set the
190                                         // alpha-channel to transparent
191                                         // (unless we are using all the 256
192                                         // colors, in which case either we
193                                         // give up, or move to 16-bits palette
194     }
195
196     for(i=0; i<numcolors; i++) {
197         c = colormap->Colors[i];
198         if(i == alphapalette)
199             pal[i].r = pal[i].g = pal[i].b = pal[i].a = 0; // Fully transparent
200         else {
201             pal[i].r = c.Red;
202             pal[i].g = c.Green;
203             pal[i].b = c.Blue;
204             pal[i].a = 255; // Fully opaque
205         }
206     }
207     
208     if(alphapalette >= 0)
209       t = swf_InsertTag(t, ST_DEFINEBITSLOSSLESS2);
210     else
211       t = swf_InsertTag(t, ST_DEFINEBITSLOSSLESS);
212
213   swf_SetU16(t, id); // id
214   
215   // Ah! The Flash specs says scanlines must be DWORD ALIGNED!
216   // (but image width is the correct number of pixels)
217   swf_width = BYTES_PER_SCANLINE(header.width);
218
219   if ((imagedata = (U8 *)malloc(swf_width*header.height)) == NULL) {
220     fprintf(stderr, "Failed to allocate memory required, aborted.");
221     exit(2);
222   }
223   to = imagedata;
224   from = (U8 *)gft->SavedImages[0].RasterBits;
225   
226   if (swf_width == header.width) {
227     // we are all nicely aligned and don't need to move the bitmap around.
228     // Just copy the bits into the image buffer.*/
229     if (!gft->Image.Interlace)
230       memcpy(to, from, header.width*header.height);
231     else // Need to perform 4 passes on the interlaced images
232         for (i = 0; i < 4; i++) 
233             for (j = interlacedOffset[i]; j < header.height; 
234                  j += interlacedJumps[i], from += header.width)
235                 memcpy(to + header.width*j, from, header.width);
236   } else {
237     padlen = swf_width - header.width;
238     
239     // here we need to pad the scanline
240     if (!gft->Image.Interlace) {
241       for (i=0; i < header.height; i++, from+=header.width, to+=swf_width) {
242         memcpy(to, from, header.width);
243         memset(to + header.width, bgcolor, padlen);
244       }
245     } else { // Need to perform 4 passes on the interlaced images
246       for (i = 0; i < 4; i++) 
247         for (j = interlacedOffset[i]; j < header.height; 
248              j += interlacedJumps[i], from += header.width) {
249           memcpy(to + swf_width*j, from, header.width);
250           memset(to + swf_width*j, bgcolor, padlen);
251         }
252     }
253   }
254
255     swf_SetLosslessBitsIndexed(t,header.width,header.height,imagedata,pal,256);
256     t = swf_InsertTag(t, ST_DEFINESHAPE);
257
258     swf_ShapeNew(&s);
259     swf_GetMatrix(NULL, &m);
260     m.sx = 20 * 0x10000;
261     m.sy = 20 * 0x10000;
262     fs = swf_ShapeAddBitmapFillStyle(s, &m, id, 0);
263
264     swf_SetU16(t, id + 1);      // id
265
266     r.xmin = r.ymin = 0;
267     r.xmax = header.width * 20;
268     r.ymax = header.height * 20;
269     swf_SetRect(t, &r);
270
271     swf_SetShapeHeader(t, s);
272
273     swf_ShapeSetAll(t, s, 0, 0, 0, fs, 0);
274     swf_ShapeSetLine(t, s, r.xmax, 0);
275     swf_ShapeSetLine(t, s, 0, r.ymax);
276     swf_ShapeSetLine(t, s, -r.xmax, 0);
277     swf_ShapeSetLine(t, s, 0, -r.ymax);
278
279     swf_ShapeSetEnd(t);
280   
281     t = swf_InsertTag(t, ST_PLACEOBJECT2);
282
283     swf_GetMatrix(NULL, &m);
284     m.tx = (swf->movieSize.xmax - (int) header.width * 20) / 2;
285     m.ty = (swf->movieSize.ymax - (int) header.height * 20) / 2;
286     swf_ObjectPlace(t, id + 1, 1, &m, NULL, NULL);
287
288     t = swf_InsertTag(t, ST_SHOWFRAME);
289
290     fclose(fi);
291     free(pal);
292     free(imagedata);
293     DGifCloseFile(gft);
294   
295     return t;
296 }
297
298
299 int CheckInputFile(char *fname, char **realname)
300 {
301     FILE *fi;
302     char *s = malloc(strlen(fname) + 5);
303     GifFileType* gft;
304
305     if (!s)
306         exit(2);
307     (*realname) = s;
308     strcpy(s, fname);
309
310     // Check whether file exists (with typical extensions)
311
312     if ((fi = fopen(s, "rb")) == NULL) {
313         sprintf(s, "%s.gif", fname);
314         if ((fi = fopen(s, "rb")) == NULL) {
315             sprintf(s, "%s.GIF", fname);
316             if ((fi = fopen(s, "rb")) == NULL) {
317                 sprintf(s, "%s.Gif", fname);
318                 if ((fi = fopen(s, "rb")) == NULL)
319                     fprintf(stderr, "Couldn't open %s!\n", fname);
320                     return -1;
321             }
322         }
323     }
324     fclose(fi);
325   
326     if((gft = DGifOpenFileName(s)) == NULL) {  
327         fprintf(stderr, "%s is not a GIF file!\n", fname);
328         return -1;
329     }
330     if(DGifSlurp(gft) != GIF_OK) {
331         PrintGifError();
332         return -1;
333     }
334   
335     if (global.max_image_width < gft->SWidth)
336         global.max_image_width = gft->SWidth;
337     if (global.max_image_height < gft->SHeight)
338         global.max_image_height = gft->SHeight;
339
340     DGifCloseFile(gft);  
341
342     return 0;
343 }
344
345 int args_callback_option(char *arg, char *val)
346 {
347     int res = 0;
348     if (arg[1])
349         res = -1;
350     else
351         switch (arg[0]) {
352         case 'r':
353             if (val)
354                 global.framerate = atof(val);
355             if ((global.framerate < 1.0/256) ||(global.framerate >= 256.0)) {
356                 if (VERBOSE(1))
357                     fprintf(stderr,
358                             "Error: You must specify a valid framerate between 1/256 and 255.\n");
359                 exit(1);
360             }
361             res = 1;
362             break;
363
364         case 'o':
365             if (val)
366                 global.outfile = val;
367             res = 1;
368             break;
369
370         case 'z':
371             global.version = 6;
372             res = 0;
373             break;
374
375         case 'C':
376             global.do_cgi = 1;
377             break;
378
379         case 'v':
380             if (val)
381                 global.verbose = atoi(val);
382             res = 1;
383             break;
384
385         case 'X':
386             if (val)
387                 global.force_width = atoi(val);
388             res = 1;
389             break;
390
391         case 'Y':
392             if (val)
393                 global.force_height = atoi(val);
394             res = 1;
395             break;
396
397         case 'V':
398             printf("gif2swf - part of %s %s\n", PACKAGE, VERSION);
399             exit(0);
400
401         default:
402             res = -1;
403             break;
404         }
405
406     if (res < 0) {
407         if (VERBOSE(1))
408             fprintf(stderr, "Unknown option: -%s\n", arg);
409         exit(1);
410         return 0;
411     }
412     return res;
413 }
414
415 static struct options_t options[] = {
416 {"r", "rate"},
417 {"o", "output"},
418 {"z", "zlib"},
419 {"X", "pixel"},
420 {"Y", "pixel"},
421 {"v", "verbose"},
422 {"C", "cgi"},
423 {"V", "version"},
424 {0,0}
425 };
426
427 int args_callback_longoption(char *name, char *val)
428 {
429     return args_long2shortoption(options, name, val);
430 }
431
432 int args_callback_command(char *arg, char *next)        // actually used as filename
433 {
434     char *s;
435     if (CheckInputFile(arg, &s) < 0) {
436         if (VERBOSE(1))
437             fprintf(stderr, "Error opening input file: %s\n", arg);
438         free(s);
439
440     } else {
441         image[global.nfiles].filename = s;
442         global.nfiles++;
443         if (global.nfiles >= MAX_INPUT_FILES) {
444             if (VERBOSE(1))
445                 fprintf(stderr, "Error: Too many input files.\n");
446             exit(1);
447         }
448     }
449   
450     return 0;
451 }
452
453 void args_callback_usage(char *name)
454 {
455     printf("\n");
456     printf("Usage: %s [-X width] [-Y height] [-o file.swf] [-r rate] file1.gif [file2.gif...]\n", name);
457     printf("\n");
458     printf("-r , --rate <framerate>        Set movie framerate (frames per second)\n");
459     printf("-o , --output <filename>       Set name for SWF output file.\n");
460     printf("-z , --zlib <zlib>             Enable Flash 6 (MX) Zlib Compression\n");
461     printf("-X , --pixel <width>           Force movie width to <width> (default: autodetect)\n");
462     printf("-Y , --pixel <height>          Force movie height to <height> (default: autodetect)\n");
463     printf("-v , --verbose <level>         Set verbose level (0=quiet, 1=default, 2=debug)\n");
464     printf("-C , --cgi                     For use as CGI- prepend http header, write to stdout\n");
465     printf("-V , --version                 Print version information and exit\n");
466     printf("\n");
467 }
468
469 int main(int argc, char **argv)
470 {
471     SWF swf;
472     TAG *t;
473   
474     memset(&global, 0x00, sizeof(global));
475
476     global.framerate = 1.0;
477     global.verbose = 1;
478     global.version = 4;
479
480     processargs(argc, argv);
481     
482     if(global.nfiles<=0) {
483         fprintf(stderr, "No gif files found in arguments\n");
484         return 1;
485     }
486
487     if (VERBOSE(2))
488         fprintf(stderr, "Processing %i file(s)...\n", global.nfiles);
489
490     t = MovieStart(&swf, global.framerate,
491                    global.force_width  ? global.force_width  : global.max_image_width,
492                    global.force_height ? global.force_height : global.max_image_height);
493     {
494         int i;
495         for (i = 0; i < global.nfiles; i++) {
496             if (VERBOSE(3))
497                 fprintf(stderr, "[%03i] %s\n", i,
498                         image[i].filename);
499             t = MovieAddFrame(&swf, t, image[i].filename, (i * 2) + 1);
500             free(image[i].filename);
501         }
502     }
503
504     MovieFinish(&swf, t, global.outfile);
505
506     return 0;
507 }