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