applied giflib patch from Jan Engelhardt
[swftools.git] / src / gif2swf.c
blob5e52ea8d3730b5e2f01c9f83b5eeb79b33c87ef4
1 /* -*- mode: c; tab-width: 4; -*- ---------------------------[for (x)emacs]--
3 $Id: gif2swf.c,v 1.7 2008/02/08 11:43:12 kramm Exp $
4 GIF to SWF converter tool
6 Part of the swftools package.
8 Copyright (c) 2005 Daichi Shinozaki <dseg@shield.jp>
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
24 This file is derived from png2swf.c */
26 #include <stdio.h>
27 #include <fcntl.h>
28 #include <gif_lib.h>
29 #include "../lib/rfxswf.h"
30 #include "../lib/args.h"
32 #define MAX_INPUT_FILES 1024
33 #define VERBOSE(x) (global.verbose>=x)
34 #define AS_FIRSTFRAME "if(!n) n=0;"
35 #define AS_LASTFRAME "if(n<%d){n=n+1;gotoAndPlay(1);}else stop();"
37 static struct {
38 float framerate;
39 int max_image_width;
40 int max_image_height;
41 int force_width;
42 int force_height;
43 int nfiles;
44 int verbose;
45 int do_cgi;
46 int version;
47 char *outfile;
48 int imagecount;
49 int loopcount;
50 } global;
52 struct {
53 char *filename;
54 } image[MAX_INPUT_FILES];
56 struct gif_header {
57 int width;
58 int height;
61 enum disposal_method {
62 NONE,
63 DO_NOT_DISPOSE,
64 RESTORE_TO_BGCOLOR,
65 RESTORE_TO_PREVIOUS
69 void SetFrameAction(TAG ** t, const char *src, int ver)
71 ActionTAG *as;
73 as = swf_ActionCompile(src, ver);
74 if (!as)
75 fprintf(stderr, "Couldn't compile ActionScript\n");
76 else {
77 *t = swf_InsertTag(*t, ST_DOACTION);
78 swf_ActionSet(*t, as);
79 swf_ActionFree(as);
83 int getGifDisposalMethod(GifFileType * gft, int framenum)
85 int i;
86 ExtensionBlock *ext = gft->SavedImages[framenum].ExtensionBlocks;
88 for (i = 0; i < gft->SavedImages[framenum].ExtensionBlockCount; i++, ext++)
89 if (ext->Function == GRAPHICS_EXT_FUNC_CODE)
90 return ((ext->Bytes[0] & 0x1C) >> 2);
92 return -1;
95 int getGifLoopCount(GifFileType * gft)
97 int i, loop = -1;
98 ExtensionBlock *ext = gft->SavedImages[0].ExtensionBlocks;
100 for (i = 0; i < gft->SavedImages[0].ExtensionBlockCount; i++, ext++)
101 if (ext->Function == APPLICATION_EXT_FUNC_CODE) {
102 // info: http://semmix.pl/color/exgraf/eeg24.htm
103 if (ext->ByteCount == 11 &&
104 (strncmp(&ext->Bytes[0], "NETSCAPE2.0", 11) == 0 ||
105 strncmp(&ext->Bytes[0], "ANIMEXTS1.0", 11) == 0)) {
106 // check for the subblock
107 ext++;
108 if (ext->ByteCount != 3)
109 ext--;
110 else {
111 loop = GET16(&ext->Bytes[1]);
112 break;
117 return loop;
120 U16 getGifDelayTime(GifFileType * gft, int framenum)
122 int i;
123 ExtensionBlock *ext = gft->SavedImages[framenum].ExtensionBlocks;
125 for (i = 0; i < gft->SavedImages[framenum].ExtensionBlockCount; i++, ext++)
126 if (ext->Function == GRAPHICS_EXT_FUNC_CODE)
127 return GET16(&ext->Bytes[1]);
129 return 0;
132 int getTransparentColor(GifFileType * gft, int framenum)
134 int i;
135 ExtensionBlock *ext = gft->SavedImages[framenum].ExtensionBlocks;
137 // Get transparency color from graphic extension block
138 for (i = 0; i < gft->SavedImages[framenum].ExtensionBlockCount; i++, ext++)
139 if ((ext->Function == GRAPHICS_EXT_FUNC_CODE) && (ext->Bytes[0] & 1)) {
140 // there is a transparent color
141 return ext->Bytes[3] == 0 ? 0 : // exception
142 (U8) ext->Bytes[3]; // transparency color
145 return -1;
148 TAG *MovieStart(SWF * swf, float framerate, int dx, int dy)
150 TAG *t;
151 RGBA rgb;
153 memset(swf, 0x00, sizeof(SWF));
155 swf->fileVersion = global.version;
156 swf->frameRate = (int) (256.0 * framerate);
157 swf->movieSize.xmax = dx * 20;
158 swf->movieSize.ymax = dy * 20;
160 t = swf->firstTag = swf_InsertTag(NULL, ST_SETBACKGROUNDCOLOR);
162 rgb.r = rgb.g = rgb.b = rgb.a = 0x00;
164 //rgb.g = 0xff; //<--- handy for testing alpha conversion
165 swf_SetRGB(t, &rgb);
167 return t;
170 int MovieFinish(SWF * swf, TAG * t, char *sname)
172 int f, so = fileno(stdout);
173 t = swf_InsertTag(t, ST_END);
175 if ((!isatty(so)) && (!sname))
176 f = so;
177 else {
178 if (!sname)
179 sname = "output.swf";
180 f = open(sname, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
183 if (global.do_cgi) {
184 if FAILED
185 (swf_WriteCGI(swf)) fprintf(stderr, "WriteCGI() failed.\n");
186 } else {
187 if (swf_WriteSWF(f, swf) < 0)
188 fprintf(stderr, "Unable to write output file: %s\n", sname);
189 if (f != so)
190 close(f);
193 swf_FreeTags(swf);
194 return 0;
197 TAG *MovieAddFrame(SWF * swf, TAG * t, char *sname, int id, int imgidx)
199 SHAPE *s;
200 SRECT r;
201 MATRIX m;
202 int fs;
204 U8 *imagedata, *from, *to;
205 GifImageDesc *img;
206 RGBA *pal;
208 struct gif_header header;
210 int i, j, numcolors, alphapalette;
211 U8 bgcolor;
212 int bpp; // byte per pixel
213 int swf_width, padlen;
215 ColorMapObject *colormap;
216 GifColorType c;
217 int interlacedOffset[] = { 0, 4, 2, 1 }; // The way Interlaced image should
218 int interlacedJumps[] = { 8, 8, 4, 2 }; // be read - offsets and jumps...
219 U16 delay, depth;
220 int disposal;
221 char *as_lastframe;
223 GifFileType *gft;
224 FILE *fi;
225 int ret;
227 if ((fi = fopen(sname, "rb")) == NULL) {
228 if (VERBOSE(1))
229 fprintf(stderr, "Read access failed: %s\n", sname);
230 return t;
232 fclose(fi);
234 #if defined(GIFLIB_MAJOR) && GIFLIB_MAJOR >= 5
235 gft = DGifOpenFileName(sname, NULL);
236 #else
237 gft = DGifOpenFileName(sname);
238 #endif
239 if (gft == NULL) {
240 fprintf(stderr, "%s is not a GIF file!\n", sname);
241 return t;
244 if ((ret = DGifSlurp(gft)) != GIF_OK) {
245 #if defined(GIFLIB_MAJOR) && GIFLIB_MAJOR >= 5
246 fprintf(stderr, "GIF-LIB: %s\n", GifErrorString(ret));
247 #else
248 PrintGifError();
249 #endif
250 return t;
253 header.width = gft->SWidth;
254 header.height = gft->SHeight;
256 pal = (RGBA *) malloc(256 * sizeof(RGBA));
257 memset(pal, 0, 256 * sizeof(RGBA));
259 img = &gft->SavedImages[imgidx].ImageDesc;
261 // Local colormap has precedence over Global colormap
262 colormap = img->ColorMap ? img->ColorMap : gft->SColorMap;
263 numcolors = colormap->ColorCount;
264 alphapalette = getTransparentColor(gft, imgidx);
265 if (VERBOSE(3))
266 fprintf(stderr, "transparent palette index => %d\n", alphapalette);
267 bpp = (alphapalette >= 0 ? 4 : 3);
269 // bgcolor is the background color to fill the bitmap
270 if (gft->SColorMap) // There is a GlobalColorMap
271 bgcolor = (U8) gft->SBackGroundColor; // The SBGColor is meaningful
272 else if (alphapalette >= 0) // There is a transparency color
273 bgcolor = alphapalette; // set the bgcolor to tranparent
274 else
275 bgcolor = 0;
276 // Don't know what to do here.
277 // If this doesn't work, we could
278 // create a new color and set the
279 // alpha-channel to transparent
280 // (unless we are using all the 256
281 // colors, in which case either we
282 // give up, or move to 16-bits palette
283 if (VERBOSE(3))
284 fprintf(stderr, "BG palette index => %u\n", bgcolor);
286 for (i = 0; i < numcolors; i++) {
287 c = colormap->Colors[i];
288 if (i == bgcolor || i == alphapalette)
289 pal[i].r = pal[i].g = pal[i].b = pal[i].a = 0; // Fully transparent
290 else {
291 pal[i].r = c.Red;
292 pal[i].g = c.Green;
293 pal[i].b = c.Blue;
294 pal[i].a = 255; // Fully opaque
298 t = swf_InsertTag(t, bpp == 4 ? ST_DEFINEBITSLOSSLESS2 : ST_DEFINEBITSLOSSLESS);
299 swf_SetU16(t, id); // id
301 // Ah! The Flash specs says scanlines must be DWORD ALIGNED!
302 // (but image width is the correct number of pixels)
303 swf_width = BYTES_PER_SCANLINE(header.width);
305 if ((imagedata = (U8 *) malloc(swf_width * header.height)) == NULL) {
306 fprintf(stderr, "Failed to allocate memory required, aborted.");
307 exit(2);
310 to = imagedata;
311 from = (U8 *) gft->SavedImages[imgidx].RasterBits;
313 if (swf_width == header.width) {
314 // we are all nicely aligned and don't need to move the bitmap around.
315 // Just copy the bits into the image buffer.
316 if (!gft->Image.Interlace)
317 if (header.width == img->Width && header.height == img->Height)
318 memcpy(to, from, header.width * header.height);
319 else { //small screen
320 for (i = 0; i < header.height; i++, to += header.width) {
321 memset(to, bgcolor, header.width);
322 if (i >= img->Top && i < img->Top + img->Height) {
323 memcpy(to + img->Left, from, img->Width);
324 from += img->Width;
329 else // Need to perform 4 passes on the interlaced images
330 for (i = 0; i < 4; i++)
331 for (j = interlacedOffset[i]; j < header.height;
332 j += interlacedJumps[i], from += header.width)
333 memcpy(to + header.width * j, from, header.width);
334 } else {
335 padlen = swf_width - header.width;
337 // here we need to pad the scanline
338 if (!gft->Image.Interlace) {
339 if (header.width == img->Width && header.height == img->Height) {
340 for (i = 0; i < header.height; i++, from += header.width, to += swf_width) {
341 memcpy(to, from, header.width);
342 memset(to + header.width, bgcolor, padlen);
344 } else { //small screen
345 for (i = 0; i < header.height; i++, to += swf_width) {
346 memset(to, bgcolor, swf_width);
347 if (i >= img->Top && i < img->Top + img->Height) {
348 memcpy(to + img->Left, from, img->Width);
349 from += img->Width;
353 } else { // Need to perform 4 passes on the interlaced images
354 for (i = 0; i < 4; i++)
355 for (j = interlacedOffset[i]; j < header.height;
356 j += interlacedJumps[i], from += header.width) {
357 memcpy(to + swf_width * j, from, header.width);
358 memset(to + swf_width * j, bgcolor, padlen);
362 swf_SetLosslessBitsIndexed(t, header.width, header.height, imagedata, pal, 256);
364 t = swf_InsertTag(t, ST_DEFINESHAPE);
366 swf_ShapeNew(&s);
367 swf_GetMatrix(NULL, &m);
368 m.sx = 20 * 0x10000;
369 m.sy = 20 * 0x10000;
370 fs = swf_ShapeAddBitmapFillStyle(s, &m, id, 0);
372 swf_SetU16(t, id + 1); // id
374 r.xmin = r.ymin = 0;
375 r.xmax = header.width * 20;
376 r.ymax = header.height * 20;
377 swf_SetRect(t, &r);
379 swf_SetShapeHeader(t, s);
381 swf_ShapeSetAll(t, s, 0, 0, 0, fs, 0);
382 swf_ShapeSetLine(t, s, r.xmax, 0);
383 swf_ShapeSetLine(t, s, 0, r.ymax);
384 swf_ShapeSetLine(t, s, -r.xmax, 0);
385 swf_ShapeSetLine(t, s, 0, -r.ymax);
387 swf_ShapeSetEnd(t);
389 depth = imgidx + 1;
390 if ((imgidx > 0) && // REMOVEOBJECT2 not needed at frame 1(imgidx==0)
391 (global.imagecount > 1)) {
392 // check last frame's disposal method
393 if ((disposal = getGifDisposalMethod(gft, imgidx - 1)) >= 0) {
394 switch (disposal) {
395 case NONE:
396 // [Replace one full-size, non-transparent frame with another]
397 t = swf_InsertTag(t, ST_REMOVEOBJECT2);
398 swf_SetU16(t, depth - 1);
399 if (VERBOSE(3))
400 fprintf(stdout, " [none]\n");
401 break;
402 case DO_NOT_DISPOSE:
403 // [Any pixels not covered up by the next frame continue to display]
404 if (VERBOSE(3))
405 fprintf(stdout, " [don't dispose]\n");
406 break;
407 case RESTORE_TO_BGCOLOR:
408 // [The background color or background tile -rather than a previous frame-
409 // shows through transparent pixels]
410 t = swf_InsertTag(t, ST_REMOVEOBJECT2);
411 swf_SetU16(t, depth - 2);
412 if (VERBOSE(3))
413 fprintf(stdout, " [restore to bg color]\n");
414 break;
415 case RESTORE_TO_PREVIOUS:
416 // [Restores to the state of a previous, undisposed frame]
417 // ** NOT IMPLEMENTED YET (same as "restore to bgcolor") **
418 t = swf_InsertTag(t, ST_REMOVEOBJECT2);
419 swf_SetU16(t, depth - 1);
420 if (VERBOSE(3))
421 fprintf(stdout, " [restore to previous]\n");
422 break;
423 default:
424 break;
429 swf_SetU16(t, depth);
430 t = swf_InsertTag(t, ST_PLACEOBJECT2);
432 swf_GetMatrix(NULL, &m);
433 m.tx = (swf->movieSize.xmax - (int) header.width * 20) / 2;
434 m.ty = (swf->movieSize.ymax - (int) header.height * 20) / 2;
435 swf_ObjectPlace(t, id + 1, depth, &m, NULL, NULL);
437 if ((global.imagecount > 1) && (global.loopcount > 0)) { // 0 means infinite loop
438 if (imgidx == 0)
439 SetFrameAction(&t, AS_FIRSTFRAME, global.version);
442 t = swf_InsertTag(t, ST_SHOWFRAME);
444 if (global.imagecount > 1) { // multi-frame GIF?
445 int framecnt;
446 delay = getGifDelayTime(gft, imgidx); // delay in 1/100 sec
447 framecnt = (int) (global.framerate * (delay / 100.0));
448 if (framecnt > 1) {
449 if (VERBOSE(2))
450 fprintf(stderr, "at frame %d: pad %d frames(%.3f sec)\n",
451 imgidx + 1, framecnt, delay / 100.0);
453 framecnt -= 1; // already inserted a frame
454 while (framecnt--)
455 t = swf_InsertTag(t, ST_SHOWFRAME);
457 if ((imgidx == global.imagecount - 1) &&global.loopcount > 0) { // last frame
458 as_lastframe = malloc(strlen(AS_LASTFRAME) + 5); // 0-99999
459 sprintf(as_lastframe, AS_LASTFRAME, global.loopcount);
460 SetFrameAction(&t, as_lastframe, global.version);
461 if (as_lastframe)
462 free(as_lastframe);
466 free(pal);
467 free(imagedata);
468 DGifCloseFile(gft);
470 return t;
473 int CheckInputFile(char *fname, char **realname)
475 FILE *fi;
476 char *s = malloc(strlen(fname) + 5);
477 GifFileType *gft;
478 int ret;
480 if (!s)
481 exit(2);
482 (*realname) = s;
483 strcpy(s, fname);
485 // Check whether file exists (with typical extensions)
487 if ((fi = fopen(s, "rb")) == NULL) {
488 sprintf(s, "%s.gif", fname);
489 if ((fi = fopen(s, "rb")) == NULL) {
490 sprintf(s, "%s.GIF", fname);
491 if ((fi = fopen(s, "rb")) == NULL) {
492 sprintf(s, "%s.Gif", fname);
493 if ((fi = fopen(s, "rb")) == NULL) {
494 fprintf(stderr, "Couldn't open %s!\n", fname);
495 return -1;
500 fclose(fi);
502 #if defined(GIFLIB_MAJOR) && GIFLIB_MAJOR >= 5
503 gft = DGifOpenFileName(s, NULL);
504 #else
505 gft = DGifOpenFileName(s);
506 #endif
507 if (gft == NULL) {
508 fprintf(stderr, "%s is not a GIF file!\n", fname);
509 return -1;
512 if (global.max_image_width < gft->SWidth)
513 global.max_image_width = gft->SWidth;
514 if (global.max_image_height < gft->SHeight)
515 global.max_image_height = gft->SHeight;
517 if ((ret = DGifSlurp(gft)) != GIF_OK) {
518 #if defined(GIFLIB_MAJOR) && GIFLIB_MAJOR >= 5
519 fprintf(stderr, "GIF-LIB: %s\n", GifErrorString(ret));
520 #else
521 PrintGifError();
522 #endif
523 return -1;
525 // After DGifSlurp() call, gft->ImageCount become available
526 if ((global.imagecount = gft->ImageCount) >1) {
527 if (global.loopcount < 0) {
528 global.loopcount = getGifLoopCount(gft);
529 if (VERBOSE(3))
530 fprintf(stderr, "Loops => %d\n", global.loopcount);
533 if (VERBOSE(2)) {
534 U8 i;
535 fprintf(stderr, "%d x %d, %d images total\n", gft->SWidth, gft->SHeight, gft->ImageCount);
537 for (i = 0; i < gft->ImageCount; i++)
538 fprintf(stderr, "frame: %u, delay: %.3f sec\n", i + 1, getGifDelayTime(gft, i) / 100.0);
541 DGifCloseFile(gft);
543 return 0;
546 int args_callback_option(char *arg, char *val)
548 int res = 0;
549 if (arg[1])
550 res = -1;
551 else
552 switch (arg[0]) {
553 case 'l':
554 if (val)
555 global.loopcount = atoi(val);
556 res = 1;
557 break;
559 case 'r':
560 if (val)
561 global.framerate = atof(val);
562 if ((global.framerate < 1.0 / 256) ||(global.framerate >= 256.0)) {
563 if (VERBOSE(1))
564 fprintf(stderr,
565 "Error: You must specify a valid framerate between 1/256 and 255.\n");
566 exit(1);
568 res = 1;
569 break;
571 case 'o':
572 if (val)
573 global.outfile = val;
574 res = 1;
575 break;
577 case 'z':
578 global.version = 6;
579 res = 0;
580 break;
582 case 'C':
583 global.do_cgi = 1;
584 break;
586 case 'v':
587 if (val)
588 global.verbose = atoi(val);
589 res = 1;
590 break;
592 case 'X':
593 if (val)
594 global.force_width = atoi(val);
595 res = 1;
596 break;
598 case 'Y':
599 if (val)
600 global.force_height = atoi(val);
601 res = 1;
602 break;
604 case 'V':
605 printf("gif2swf - part of %s %s\n", PACKAGE, VERSION);
606 exit(0);
608 default:
609 res = -1;
610 break;
613 if (res < 0) {
614 if (VERBOSE(1))
615 fprintf(stderr, "Unknown option: -%s\n", arg);
616 exit(1);
617 return 0;
619 return res;
622 static struct options_t options[] = {
623 {"r", "rate"},
624 {"o", "output"},
625 {"z", "zlib"},
626 {"l", "loop"},
627 {"X", "pixel"},
628 {"Y", "pixel"},
629 {"v", "verbose"},
630 {"C", "cgi"},
631 {"V", "version"},
632 {0,0}
635 int args_callback_longoption(char *name, char *val)
637 return args_long2shortoption(options, name, val);
640 int args_callback_command(char *arg, char *next) // actually used as filename
642 char *s;
643 if (CheckInputFile(arg, &s) < 0) {
644 if (VERBOSE(1))
645 fprintf(stderr, "Error opening input file: %s\n", arg);
646 free(s);
648 } else {
649 image[global.nfiles].filename = s;
650 global.nfiles++;
651 if (global.nfiles >= MAX_INPUT_FILES) {
652 if (VERBOSE(1))
653 fprintf(stderr, "Error: Too many input files.\n");
654 exit(1);
658 return 0;
661 void args_callback_usage(char *name)
663 printf("\n");
664 printf("Usage: %s [-X width] [-Y height] [-o file.swf] [-r rate] file1.gif [file2.gif ...]\n", name);
665 printf("\n");
666 printf("-r , --rate <framerate> Set movie framerate (frames per second)\n");
667 printf("-o , --output <filename> Set name for SWF output file.\n");
668 printf("-z , --zlib <zlib> Enable Flash 6 (MX) Zlib Compression\n");
669 printf("-l , --loop <loop count> Set loop count. (default: 0 [=infinite loop])\n");
670 printf("-X , --pixel <width> Force movie width to <width> (default: autodetect)\n");
671 printf("-Y , --pixel <height> Force movie height to <height> (default: autodetect)\n");
672 printf("-v , --verbose <level> Set verbose level (0=quiet, 1=default, 2=debug)\n");
673 printf("-C , --cgi For use as CGI- prepend http header, write to stdout\n");
674 printf("-V , --version Print version information and exit\n");
675 printf("\n");
678 int main(int argc, char **argv)
680 SWF swf;
681 TAG *t;
683 memset(&global, 0x00, sizeof(global));
685 global.framerate = 1.0;
686 global.verbose = 1;
687 global.version = 5;
688 global.loopcount = -1;
690 processargs(argc, argv);
692 if (global.nfiles <= 0) {
693 fprintf(stderr, "No gif files found in arguments\n");
694 return 1;
697 if (VERBOSE(2))
698 fprintf(stderr, "Processing %i file(s)...\n", global.nfiles);
700 if (global.imagecount > 1) // multi-frame GIF?
701 if (global.framerate == 1.0) // user not specified '-r' option?
702 global.framerate = 10.0;
704 t = MovieStart(&swf, global.framerate,
705 global.force_width ? global.force_width : global.max_image_width,
706 global.force_height ? global.force_height : global.max_image_height);
708 int i, j;
709 for (i = 0; i < global.nfiles; i++) {
710 if (VERBOSE(3))
711 fprintf(stderr, "[%03i] %s\n", i, image[i].filename);
712 t = MovieAddFrame(&swf, t, image[i].filename, (i * 2) + 1, 0);
713 for (j = 2; j <= global.imagecount; j++)
714 t = MovieAddFrame(&swf, t, image[i].filename, (j * 2) - 1, j - 1);
715 free(image[i].filename);
719 MovieFinish(&swf, t, global.outfile);
721 return 0;