updated/corrected documentation
[swftools.git] / src / swfextract.c
1 /* swfextract.c
2    Allows to extract parts of the swf into a new file.
3
4    Part of the swftools package.
5    
6    Copyright (c) 2001 Matthias Kramm <kramm@quiss.org>
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 #include <unistd.h>
23 #include <stdio.h>
24 #include <fcntl.h>
25 #include "../lib/rfxswf.h"
26 #include "../lib/args.h"
27 #include "../lib/log.h"
28 #ifdef HAVE_ZLIB_H
29 #ifdef HAVE_LIBZ
30 #include "zlib.h"
31 #define _ZLIB_INCLUDED_
32 #endif
33 #endif
34
35 char * filename = 0;
36 char * destfilename = "output.swf";
37 int verbose = 3;
38
39 char* extractids = 0;
40 char* extractframes = 0;
41 char* extractjpegids = 0;
42 char* extractfontids = 0;
43 char* extractpngids = 0;
44 char* extractsoundids = 0;
45 char extractmp3 = 0;
46
47 char* extractname = 0;
48
49 char hollow = 0;
50 char originalplaceobjects = 0;
51
52 int numextracts = 0;
53
54 struct options_t options[] =
55 {
56  {"o","output"},
57  {"w","hollow"},
58  {"v","verbose"},
59  {"i","id"},
60  {"j","jpegs"},
61  {"p","pngs"},
62  {"P","placeobject"},
63  {"m","mp3"},
64  {"s","sound"},
65  {"n","name"},
66  {"f","frame"},
67  {"F","font"},
68  {"V","version"},
69  {0,0}
70 };
71
72
73 int args_callback_option(char*name,char*val)
74 {
75     if(!strcmp(name, "V")) {
76         printf("swfextract - part of %s %s\n", PACKAGE, VERSION);
77         exit(0);
78     } 
79     else if(!strcmp(name, "o")) {
80         destfilename = val;
81         return 1;
82     } 
83     else if(!strcmp(name, "i")) {
84         extractids = val;
85         numextracts++;
86         if(extractname) {
87             fprintf(stderr, "You can only supply either name or id\n");
88             exit(1);
89         }
90         return 1;
91     } 
92     else if(!strcmp(name, "n")) {
93         extractname = val;
94         numextracts++;
95         if(extractids) {
96             fprintf(stderr, "You can only supply either name or id\n");
97             exit(1);
98         }
99         return 1;
100     } 
101     else if(!strcmp(name, "v")) {
102         verbose ++;
103         return 0;
104     } 
105     else if(!strcmp(name, "m")) {
106         extractmp3 = 1;
107         numextracts++;
108         return 0;
109     }
110     else if(!strcmp(name, "j")) {
111         if(extractjpegids) {
112             fprintf(stderr, "Only one --jpegs argument is allowed. (Try to use a range, e.g. -j 1,2,3)\n");
113             exit(1);
114         }
115         numextracts++;
116         extractjpegids = val;
117         return 1;
118     } 
119     else if(!strcmp(name, "F")) {
120         if(extractfontids) {
121             fprintf(stderr, "Only one --font argument is allowed. (Try to use a range, e.g. -s 1,2,3)\n");
122             exit(1);
123         }
124         numextracts++;
125         extractfontids = val;
126         return 1;
127     } 
128     else if(!strcmp(name, "s")) {
129         if(extractsoundids) {
130             fprintf(stderr, "Only one --sound argument is allowed. (Try to use a range, e.g. -s 1,2,3)\n");
131             exit(1);
132         }
133         numextracts++;
134         extractsoundids = val;
135         return 1;
136     } 
137 #ifdef _ZLIB_INCLUDED_
138     else if(!strcmp(name, "p")) {
139         if(extractpngids) {
140             fprintf(stderr, "Only one --png argument is allowed. (Try to use a range, e.g. -p 1,2,3)\n");
141             exit(1);
142         }
143         numextracts++;
144         extractpngids = val;
145         return 1;
146     } 
147 #endif
148     else if(!strcmp(name, "f")) {
149         numextracts++;
150         extractframes = val;
151         return 1;
152     }
153     else if(!strcmp(name, "P")) {
154         originalplaceobjects = 1;
155         return 0;
156     }
157     else if(!strcmp(name, "w")) {
158         hollow = 1;
159         return 0;
160     }
161     else {
162         printf("Unknown option: -%s\n", name);
163         exit(1);
164     }
165
166     return 0;
167 }
168 int args_callback_longoption(char*name,char*val)
169 {
170     return args_long2shortoption(options, name, val);
171 }
172 void args_callback_usage(char*name)
173 {    
174     printf("Usage: %s [-v] [-n name] [-ijf ids] file.swf\n", name);
175     printf("\t-v , --verbose\t\t\t Be more verbose\n");
176     printf("\t-o , --output filename\t\t set output filename\n");
177     printf("\t-V , --version\t\t\t Print program version and exit\n\n");
178     printf("SWF Subelement extraction:\n");
179     printf("\t-n , --name name\t\t instance name of the object (SWF Define) to extract\n");
180     printf("\t-i , --id ID\t\t\t ID of the object, shape or movieclip to extract\n");
181     printf("\t-f , --frame frames\t\t frame numbers to extract\n");
182     printf("\t-w , --hollow\t\t\t hollow mode: don't remove empty frames\n"); 
183     printf("\t             \t\t\t (use with -f)\n");
184     printf("\t-P , --placeobject\t\t\t Insert original placeobject into output file\n"); 
185     printf("\t             \t\t\t (use with -i)\n");
186     printf("SWF Font/Text extraction:\n");
187     printf("\t-F , --font ID\t\t\t Extract font(s)\n");
188     printf("Picture extraction:\n");
189     printf("\t-j , --jpeg ID\t\t\t Extract JPEG picture(s)\n");
190 #ifdef _ZLIB_INCLUDED_
191     printf("\t-p , --pngs ID\t\t\t Extract PNG picture(s)\n");
192 #endif
193     printf("\n");
194     printf("Sound extraction:\n");
195     printf("\t-m , --mp3\t\t\t Extract main mp3 stream\n");
196     printf("\t-s , --sound ID\t\t\t Extract Sound(s)\n");
197 }
198 int args_callback_command(char*name,char*val)
199 {
200     if(filename) {
201         fprintf(stderr, "Only one file allowed. You supplied at least two. (%s and %s)\n",
202                  filename, name);
203     }
204     filename = name;
205     return 0;
206 }
207
208 U8 mainr,maing,mainb;
209 /* 1 = used, not expanded,
210    3 = used, expanded
211    5 = wanted, not expanded
212    7 = wanted, expanded
213  */
214 char used[65536];
215 TAG*tags[65536];
216 int changed;
217 char * tagused;
218 int extractname_id = -1;
219
220 void idcallback(void*data)
221 {
222     if(!(used[GET16(data)]&1)) {
223         changed = 1;
224         used[GET16(data)] |= 1;
225     }
226 }
227
228 void enumerateIDs(TAG*tag, void(*callback)(void*))
229 {
230 /*    U8*data;
231     int len = tag->len;
232     if(tag->len>=64) {
233         len += 6;
234         data = (U8*)malloc(len);
235         PUT16(data, (tag->id<<6)+63);
236         *(U8*)&data[2] = tag->len;
237         *(U8*)&data[3] = tag->len>>8;
238         *(U8*)&data[4] = tag->len>>16;
239         *(U8*)&data[5] = tag->len>>24;
240         memcpy(&data[6], tag->data, tag->len);
241     } else {
242         len += 2;
243         data = (U8*)malloc(len);
244         PUT16(data, (tag->id<<6)+tag->len);
245         memcpy(&data[2], tag->data, tag->len);
246     }
247     map_ids_mem(data, len, callback);
248  */
249     int num = swf_GetNumUsedIDs(tag);
250     int *ptr = malloc(sizeof(int)*num);
251     int t;
252     swf_GetUsedIDs(tag, ptr);
253     for(t=0;t<num;t++)
254         callback(&tag->data[ptr[t]]);
255 }
256
257 void extractTag(SWF*swf, char*filename)
258 {
259     SWF newswf;
260     TAG*desttag;
261     TAG*srctag;
262     RGBA rgb;
263     SRECT objectbbox;
264     char sprite;
265     int f;
266     int t;
267     int tagnum;
268     int copy = 0;
269     memset(&newswf,0x00,sizeof(SWF));        // set global movie parameters
270
271     newswf.fileVersion    = swf->fileVersion;
272     newswf.frameRate      = swf->frameRate;
273     newswf.movieSize      = swf->movieSize;
274                 
275     newswf.firstTag = swf_InsertTag(NULL,ST_SETBACKGROUNDCOLOR);
276     desttag = newswf.firstTag;
277     rgb.r = mainr;
278     rgb.g = maing;
279     rgb.b = mainb;
280     swf_SetRGB(desttag,&rgb);
281
282     swf_GetRect(0, &objectbbox);
283
284     do {
285        changed = 0;
286        for(t=0;t<65536;t++) {
287            if(used[t] && !(used[t]&2)) {
288              if(tags[t]==0) {
289                  msg("<warning> ID %d is referenced, but never defined.", t);
290              } else if(tags[t]->id==ST_DEFINESPRITE) {
291                  TAG*tag = tags[t];
292                  while(tag->id != ST_END)
293                  {
294                      enumerateIDs(tag, idcallback);
295                      tag = tag->next;
296                  }
297              }
298              else 
299                enumerateIDs(tags[t], idcallback);
300              used[t] |= 2;
301            }
302        }
303     }
304     while(changed);
305
306     srctag = swf->firstTag;
307     tagnum = 0;
308     sprite = 0;
309     while(srctag && (srctag->id || sprite)) {
310         int reset = 0;
311         if(!sprite) {
312             copy = 0;
313         }
314         if(srctag->id == ST_END) {
315             sprite = 0;
316         }
317         if(srctag->id == ST_DEFINESPRITE)
318             sprite = 1;
319         if(swf_isDefiningTag(srctag)) {
320             int id = swf_GetDefineID(srctag);
321             if(used[id])  {
322                 SRECT b;
323                 copy = 1;
324                 b = swf_GetDefineBBox(srctag);
325                 swf_ExpandRect2(&objectbbox, &b);
326             }
327         } else 
328         if (((((srctag->id == ST_PLACEOBJECT || srctag->id == ST_PLACEOBJECT2) && originalplaceobjects)
329               || srctag->id == ST_STARTSOUND) && (used[swf_GetPlaceID(srctag)]&4) ) ||
330               (swf_isPseudoDefiningTag(srctag) && used[swf_GetDefineID(srctag)]) ||
331               (tagused[tagnum])) 
332         {
333                 if(copy == 0)
334                     reset = 1;
335                 copy = 1;
336         } 
337         if(srctag->id == ST_REMOVEOBJECT) {
338             if(!used[swf_GetPlaceID(srctag)])
339                 copy = 0;
340         }
341
342         if(copy) {
343             TAG*ttag = (TAG*)malloc(sizeof(TAG));
344             desttag = swf_InsertTag(desttag, srctag->id);
345             desttag->len = desttag->memsize = srctag->len;
346             desttag->data = malloc(srctag->len);
347             memcpy(desttag->data, srctag->data, srctag->len);
348             if(reset)
349                 copy = 0;
350         }
351         
352         srctag = srctag->next;
353         tagnum ++;
354     }
355     if(!extractframes && !hollow) {
356         if(!originalplaceobjects && (extractids||extractname_id>=0)) {
357             int t;
358             int s=0;
359             if((objectbbox.xmin|objectbbox.ymin|objectbbox.xmax|objectbbox.ymax)!=0)
360                 newswf.movieSize = objectbbox;
361             if(extractname_id>=0) {
362                 desttag = swf_InsertTag(desttag, ST_PLACEOBJECT2);
363                 swf_ObjectPlace(desttag, extractname_id, extractname_id, 0,0,extractname);
364             } else {
365                 for(t=0;t<65536;t++) {
366                     if(is_in_range(t, extractids)) {
367                         desttag = swf_InsertTag(desttag, ST_PLACEOBJECT2);
368                         swf_ObjectPlace(desttag, t, t, 0,0,0);
369                         s++;
370                         if(s==2)
371                             printf("warning! You should use the -P when extracting multiple objects\n");
372                     }
373                 }
374             }
375         }
376         desttag = swf_InsertTag(desttag,ST_SHOWFRAME);
377     }
378     desttag = swf_InsertTag(desttag,ST_END);
379     
380     f = open(filename, O_TRUNC|O_WRONLY|O_CREAT|O_BINARY, 0644);
381     if FAILED(swf_WriteSWF(f,&newswf)) fprintf(stderr,"WriteSWF() failed.\n");
382     close(f);
383
384     swf_FreeTags(&newswf);                       // cleanup
385 }
386
387 void listObjects(SWF*swf)
388 {
389     TAG*tag;
390     char first;
391     int t;
392     int frame = 0;
393     char*names[] = {"Shapes","MovieClips","JPEGs","PNGs","Sounds","Fonts"};
394     printf("Objects in file %s:\n",filename);
395     for(t=0;t<sizeof(names)/sizeof(names[0]);t++) {
396         tag = swf->firstTag;
397         first = 1;
398         while(tag) {
399             char show = 0;
400             char text[80];
401             if(t == 0 &&
402                (tag->id == ST_DEFINESHAPE ||
403                 tag->id == ST_DEFINESHAPE2 ||
404                 tag->id == ST_DEFINESHAPE3)) {
405                 show = 1;
406                 sprintf(text,"%d", swf_GetDefineID(tag));
407             }
408
409             if(tag->id == ST_DEFINESPRITE) {
410                 if (t == 1)  {
411                     show = 1;
412                     sprintf(text,"%d", swf_GetDefineID(tag));
413                 }
414
415                 while(tag->id != ST_END)
416                     tag = tag->next;
417             }
418
419             if(t == 2 && (tag->id == ST_DEFINEBITS ||
420                 tag->id == ST_DEFINEBITSJPEG2 ||
421                 tag->id == ST_DEFINEBITSJPEG3)) {
422                 show = 1;
423                 sprintf(text,"%d", swf_GetDefineID(tag));
424             }
425
426             if(t == 3 && (tag->id == ST_DEFINEBITSLOSSLESS ||
427                 tag->id == ST_DEFINEBITSLOSSLESS2)) {
428                 show = 1;
429                 sprintf(text,"%d", swf_GetDefineID(tag));
430             }
431
432
433             if(t == 4 && (tag->id == ST_DEFINESOUND)) {
434                 show = 1;
435                 sprintf(text,"%d", swf_GetDefineID(tag));
436             }
437             
438             if(t == 5 && (tag->id == ST_DEFINEFONT || tag->id == ST_DEFINEFONT2)) {
439                 show = 1;
440                 sprintf(text,"%d", swf_GetDefineID(tag));
441             }
442             
443             if(show) {
444                 if(!first)
445                     printf(", ");
446                 else
447                     printf("%s: ", names[t]);
448                 printf("%s", text);
449                 first = 0;
450             }
451             tag=tag->next;
452         }
453         if(!first)
454             printf("\n");
455     }
456
457     if(frame)
458         printf("Frames: 0-%d\n", frame);
459     else
460         printf("Frames: 0\n");
461 }
462
463 void handlefont(SWF*swf, TAG*tag)
464 {
465     SWFFONT* f=0;
466     U16 id;
467     char name[80];
468     char*filename = name;
469     int t;
470
471     id = swf_GetDefineID(tag);
472     sprintf(name, "font%d.swf", id);
473     if(numextracts==1) {
474         filename = destfilename;
475     }
476
477     swf_FontExtract(swf, id, &f);
478     if(!f) {
479         printf("Couldn't extract font %d\n", id);
480         return;
481     }
482     if(!f->layout)
483         swf_FontCreateLayout(f);
484
485     swf_WriteFont(f, filename);
486     swf_FontFree(f);
487 }
488
489 U8*jpegtables = 0;
490 int jpegtablessize;
491
492 void handlejpegtables(TAG*tag)
493 {
494     if(tag->id == ST_JPEGTABLES) {
495         jpegtables = tag->data;
496         jpegtablessize = tag->len;
497     }
498 }
499
500 FILE* save_fopen(char* name, char* mode)
501 {
502     FILE*fi = fopen(name, mode);
503     if(!fi) {
504         fprintf(stderr, "Error: Couldn't open %s\n", name);
505         exit(1);
506     }
507     return fi;
508 }
509
510 int findjpegboundary(U8*data, int len)
511 {
512     int t;
513     int pos=-1;
514     for(t=0;t<len;t++) {
515         if(data[t  ]==0xff &&
516            data[t+1]==0xd9 &&
517            data[t+2]==0xff &&
518            data[t+3]==0xd8) {
519             pos = t;
520         }
521     }
522     return pos;
523 }
524
525 /* extract jpeg data out of a tag */
526 void handlejpeg(TAG*tag)
527 {
528     char name[80];
529     char*filename = name;
530     FILE*fi;
531     
532     sprintf(name, "pic%d.jpg", GET16(tag->data));
533     if(numextracts==1) {
534         filename = destfilename;
535         if(!strcmp(filename,"output.swf"))
536             filename = "output.jpg";
537     }
538     /* swf jpeg images have two streams, which both start with ff d8 and
539        end with ff d9. The following code handles sorting the middle
540        <ff d9 ff d8> bytes out, so that one stream remains */
541     if(tag->id == ST_DEFINEBITS && tag->len>2 && jpegtables) {
542         fi = save_fopen(filename, "wb");
543         fwrite(jpegtables, 1, jpegtablessize-2, fi); //don't write end tag (ff,d8)
544         fwrite(&tag->data[2+2], tag->len-2-2, 1, fi); //don't write start tag (ff,d9)
545         fclose(fi);
546     }
547     else if(tag->id == ST_DEFINEBITSJPEG2 && tag->len>2) {
548         int end = tag->len;
549         int pos = findjpegboundary(&tag->data[2], tag->len-2);
550         if(pos<0)
551             return;
552         pos+=2;
553         fi = save_fopen(filename, "wb");
554         fwrite(&tag->data[2], pos-2, 1, fi);
555         fwrite(&tag->data[pos+4], end-(pos+4), 1, fi);
556         fclose(fi);
557     }
558     else if(tag->id == ST_DEFINEBITSJPEG3 && tag->len>6) {
559         U32 end = GET32(&tag->data[2])+6;
560         int pos = findjpegboundary(&tag->data[6], tag->len-6);
561         if(pos<0)
562             return;
563         pos+=6;
564         fi = save_fopen(filename, "wb");
565         fwrite(&tag->data[6], pos-6, 1, fi);
566         fwrite(&tag->data[pos+4], end-(pos+4), 1, fi);
567         fclose(fi);
568     }
569     else {
570         int id = GET16(tag->data);
571         fprintf(stderr, "Object %d is not a JPEG picture!\n",id);
572         exit(1);
573     }
574 }
575
576 #ifdef _ZLIB_INCLUDED_
577 static U32 mycrc32;
578
579 static U32*crc32_table = 0;
580 static void make_crc32_table(void)
581 {
582   int t;
583   if(crc32_table) 
584       return;
585   crc32_table = (U32*)malloc(1024);
586
587   for (t = 0; t < 256; t++) {
588     U32 c = t;
589     int s;
590     for (s = 0; s < 8; s++) {
591       c = (0xedb88320L*(c&1)) ^ (c >> 1);
592     }
593     crc32_table[t] = c;
594   }
595 }
596 static void png_write_byte(FILE*fi, U8 byte)
597 {
598     fwrite(&byte,1,1,fi);
599     mycrc32 = crc32_table[(mycrc32 ^ byte) & 0xff] ^ (mycrc32 >> 8);
600 }
601 static void png_start_chunk(FILE*fi, char*type, int len)
602 {
603     U8 mytype[4]={0,0,0,0};
604     U32 mylen = REVERSESWAP32(len);
605     memcpy(mytype,type,strlen(type));
606     fwrite(&mylen, 4, 1, fi);
607     mycrc32=0xffffffff;
608     png_write_byte(fi,mytype[0]);
609     png_write_byte(fi,mytype[1]);
610     png_write_byte(fi,mytype[2]);
611     png_write_byte(fi,mytype[3]);
612 }
613 static void png_write_bytes(FILE*fi, U8*bytes, int len)
614 {
615     int t;
616     for(t=0;t<len;t++)
617         png_write_byte(fi,bytes[t]);
618 }
619 static void png_write_dword(FILE*fi, U32 dword)
620 {
621     png_write_byte(fi,dword>>24);
622     png_write_byte(fi,dword>>16);
623     png_write_byte(fi,dword>>8);
624     png_write_byte(fi,dword);
625 }
626 static void png_end_chunk(FILE*fi)
627 {
628     U32 tmp = REVERSESWAP32((mycrc32^0xffffffff));
629     fwrite(&tmp,4,1,fi);
630 }
631
632
633 /* extract a lossless image (png) out of a tag 
634    This routine was originally meant to be a one-pager. I just
635    didn't know png is _that_ much fun. :) -mk
636  */
637 void handlelossless(TAG*tag)
638 {
639     char name[80];
640     char*filename = name;
641     FILE*fi;
642     int width, height;
643     int crc;
644     int id;
645     int t;
646     U8 bpp = 1;
647     U8 format;
648     U8 tmp;
649     U8* data=0;
650     U8* data2=0;
651     U8* data3=0;
652     U32 datalen;
653     U32 datalen2;
654     U32 datalen3;
655     U8 head[] = {137,80,78,71,13,10,26,10};
656     int cols;
657     char alpha = tag->id == ST_DEFINEBITSLOSSLESS2;
658     RGBA* palette;
659     int pos;
660     int error;
661     U32 tmp32;
662
663     make_crc32_table();
664
665     if(tag->id != ST_DEFINEBITSLOSSLESS &&
666        tag->id != ST_DEFINEBITSLOSSLESS2) {
667         int id = GET16(tag->data);
668         fprintf(stderr, "Object %d is not a PNG picture!\n",id);
669         exit(1);
670     }
671
672     id =swf_GetU16(tag);
673     format = swf_GetU8(tag);
674     if(format == 3) bpp = 8;
675     if(format == 4) bpp = 16;
676     if(format == 5) bpp = 32;
677     if(format!=3 && format!=5) {
678         if(format==4)
679         fprintf(stderr, "Can't handle 16-bit palette images yet (image %d)\n",id);
680         else 
681         fprintf(stderr, "Unknown image type %d in image %d\n", format, id);
682         return;
683     }
684     width = swf_GetU16(tag);
685     height = swf_GetU16(tag);
686     if(format == 3) cols = swf_GetU8(tag) + 1;
687 // this is what format means according to the flash specification. (which is
688 // clearly wrong)
689 //    if(format == 4) cols = swf_GetU16(tag) + 1;
690 //    if(format == 5) cols = swf_GetU32(tag) + 1;
691     else cols = 0;
692
693     msg("<verbose> Width %d", width);
694     msg("<verbose> Height %d", height);
695     msg("<verbose> Format %d", format);
696     msg("<verbose> Cols %d", cols);
697     msg("<verbose> Bpp %d", bpp);
698
699     datalen = (width*height*bpp/8+cols*8);
700     do {
701         if(data)
702             free(data);
703         datalen+=4096;
704         data = malloc(datalen);
705         error = uncompress (data, &datalen, &tag->data[tag->pos], tag->len-tag->pos);
706     } while(error == Z_BUF_ERROR);
707     if(error != Z_OK) {
708         fprintf(stderr, "Zlib error %d (image %d)\n", error, id);
709         return;
710     }
711     msg("<verbose> Uncompressed image is %d bytes (%d colormap)", datalen, (3+alpha)*cols);
712     pos = 0;
713     datalen2 = datalen;
714     data2 = malloc(datalen2);
715     palette = (RGBA*)malloc(cols*sizeof(RGBA));
716
717     for(t=0;t<cols;t++) {
718         palette[t].r = data[pos++];
719         palette[t].g = data[pos++];
720         palette[t].b = data[pos++];
721         if(alpha) {
722             palette[t].a = data[pos++];
723         }
724     }
725
726     sprintf(name, "pic%d.png", id);
727     if(numextracts==1) {
728         filename = destfilename;
729         if(!strcmp(filename,"output.swf"))
730             filename = "output.png";
731     }
732     fi = save_fopen(filename, "wb");
733     fwrite(head,sizeof(head),1,fi);     
734
735     png_start_chunk(fi, "IHDR", 13);
736      png_write_dword(fi,width);
737      png_write_dword(fi,height);
738      png_write_byte(fi,8);
739      if(format == 3)
740      png_write_byte(fi,3); //indexed
741      else if(format == 5)
742      png_write_byte(fi,2); //rgb
743      else return;
744
745      png_write_byte(fi,0); //compression mode
746      png_write_byte(fi,0); //filter mode
747      png_write_byte(fi,0); //interlace mode
748     png_end_chunk(fi);
749    
750     if(format == 3) {
751         png_start_chunk(fi, "PLTE", 768);
752          for(t=0;t<256;t++) {
753              png_write_byte(fi,palette[t].r);
754              png_write_byte(fi,palette[t].g);
755              png_write_byte(fi,palette[t].b);
756          }
757         png_end_chunk(fi);
758     }
759     {
760         int pos2 = 0;
761         int x,y;
762         int srcwidth = width * (bpp/8);
763         datalen3 = width*height*4;
764         data3 = (U8*)malloc(datalen3);
765         for(y=0;y<height;y++)
766         {
767            data3[pos2++]=0; //filter type
768            if(bpp==32) {
769             // 32 bit to 24 bit "conversion"
770             for(x=0;x<width;x++) {
771                 data3[pos2++]=data[pos+1];
772                 data3[pos2++]=data[pos+2];
773                 data3[pos2++]=data[pos+3];
774                 pos+=4; //ignore padding byte
775             }
776            }
777            else {
778                 for(x=0;x<srcwidth;x++)
779                     data3[pos2++]=data[pos++];
780            }
781            
782            pos+=((srcwidth+3)&~3)-srcwidth; //align
783         }
784         datalen3=pos2;
785     }
786
787     if(compress (data2, &datalen2, data3, datalen3) != Z_OK) {
788         fprintf(stderr, "zlib error in pic %d\n", id);
789         return;
790     }
791     msg("<verbose> Compressed data is %d bytes", datalen2);
792     png_start_chunk(fi, "IDAT", datalen2);
793     png_write_bytes(fi,data2,datalen2);
794     png_end_chunk(fi);
795     png_start_chunk(fi, "IEND", 0);
796     png_end_chunk(fi);
797
798     free(data);
799     free(data2);
800     free(data3);
801 }
802 #endif
803
804 FILE*mp3file;
805 void handlesoundstream(TAG*tag)
806 {
807     char*filename = "output.mp3";
808     if(numextracts==1) {
809         filename = destfilename;
810         if(!strcmp(filename,"output.swf"))
811             filename = "output.mp3";
812     }
813     switch(tag->id) {
814         case ST_SOUNDSTREAMHEAD:
815             if((tag->data[1]&0x30) == 0x20) { //mp3 compression
816                 mp3file = fopen(filename, "wb");
817                 msg("<notice> Writing mp3 data to %s",filename);
818             }
819             else
820                 msg("<error> Soundstream is not mp3");
821         break;
822         case ST_SOUNDSTREAMHEAD2:
823             if((tag->data[1]&0x30) == 0x20) {//mp3 compression
824                 mp3file = fopen(filename, "wb");
825                 msg("<notice> Writing mp3 data to %s",filename);
826             }
827             else
828                 msg("<error> Soundstream is not mp3 (2)");
829         break;
830         case ST_SOUNDSTREAMBLOCK:
831             if(mp3file)
832                 fwrite(&tag->data[4],tag->len-4,1,mp3file);
833         break;
834     }
835 }
836
837 void handledefinesound(TAG*tag)
838 {
839     U8 flags;
840     U32 samples;
841     char buf[128];
842     char*filename = buf;
843     FILE*fi;
844     U16 id;
845     id = swf_GetU16(tag); //id
846     sprintf(buf, "sound%d.mp3", id);
847
848     if(numextracts==1) {
849         filename = destfilename;
850         if(!strcmp(filename,"output.swf"))
851             filename = "output.mp3";
852     }
853     flags = swf_GetU8(tag);
854     if((flags>>4)!=2) {
855         printf("Sorry, can only extract MP3 sounds. Sound %d is ADPCM or RAW.\n", id);
856         /* not mp3 */
857         return;
858     }
859     samples = swf_GetU32(tag);
860     
861     swf_GetU16(tag); //(only for mp3) numsamples_seek
862
863     fi = save_fopen(filename, "wb");
864     fwrite(&tag->data[tag->pos], tag->len - tag->pos, 1, fi);
865     fclose(fi);
866 }
867
868 int main (int argc,char ** argv)
869
870     TAG*tag;
871     SWF swf;
872     int f;
873     int found = 0;
874     int frame = 0;
875     int tagnum = 0;
876     char depths[65536];
877     char listavailable = 0;
878     processargs(argc, argv);
879
880     if(!extractframes && !extractids && ! extractname && !extractjpegids && !extractpngids
881         && !extractmp3 && !extractsoundids && !extractfontids)
882         listavailable = 1;
883
884     if(!filename)
885     {
886         fprintf(stderr, "You must supply a filename.\n");
887         return 1;
888     }
889     initLog(0,-1,0,0,-1, verbose);
890
891     f = open(filename,O_RDONLY|O_BINARY);
892
893     if (f<0)
894     { 
895         perror("Couldn't open file: ");
896         exit(1);
897     }
898     if (swf_ReadSWF(f,&swf) < 0)
899     { 
900         fprintf(stderr, "%s is not a valid SWF file or contains errors.\n",filename);
901         close(f);
902         exit(1);
903     }
904     close(f);
905
906     if(listavailable) {
907         listObjects(&swf);
908         swf_FreeTags(&swf);
909         return 0;
910     }
911
912     tag = swf.firstTag;
913     tagnum = 0;
914     while(tag) {
915         tagnum ++;
916         tag = tag->next;
917     }
918
919     tagused = (char*)malloc(tagnum);
920     memset(tagused, 0, tagnum);
921     memset(used, 0, 65536);
922     memset(depths, 0, 65536);
923
924     tag = swf.firstTag;
925     tagnum = 0;
926     while(tag) {
927         if(swf_isAllowedSpriteTag(tag)) {
928             int write = 0;
929             if(extractframes && is_in_range(frame, extractframes)) {
930                 write = 1;
931                 if(tag->id == ST_PLACEOBJECT || tag->id == ST_PLACEOBJECT2) {
932                     depths[swf_GetDepth(tag)] = 1;
933                 }
934                 if(tag->id == ST_REMOVEOBJECT || tag->id == ST_REMOVEOBJECT2) {
935                     int depth = swf_GetDepth(tag);
936                     if(!depths[depth]) 
937                         write = 0;
938                     depths[swf_GetDepth(tag)] = 0;
939                 }
940             } else {
941                 if((tag->id == ST_REMOVEOBJECT || tag->id == ST_REMOVEOBJECT2) && 
942                     (depths[swf_GetDepth(tag)]) && hollow) {
943                     write = 1;
944                     depths[swf_GetDepth(tag)] = 0;
945                 }
946             }
947             if(write) {
948                 enumerateIDs(tag, idcallback);
949                 found = 1;
950                 tagused[tagnum] = 1;
951             }
952         }
953
954         if(tag->id == ST_SOUNDSTREAMHEAD ||
955            tag->id == ST_SOUNDSTREAMHEAD2 ||
956            tag->id == ST_SOUNDSTREAMBLOCK) {
957             if(extractmp3)
958                 handlesoundstream(tag);
959         }
960
961         if(tag->id == ST_JPEGTABLES)
962             handlejpegtables(tag);
963
964         if(swf_isDefiningTag(tag)) {
965             int id = swf_GetDefineID(tag);
966             tags[id] = tag;
967             if(extractids && is_in_range(id, extractids)) {
968                 used[id] = 5;
969                 found = 1;
970             }
971             if(extractfontids && is_in_range(id, extractfontids)) {
972                 handlefont(&swf, tag);
973             }
974             if(extractjpegids && is_in_range(id, extractjpegids)) {
975                 handlejpeg(tag);
976             }
977             if(extractsoundids && is_in_range(id, extractsoundids)) {
978                 handledefinesound(tag);
979             }
980 #ifdef _ZLIB_INCLUDED_
981             if(extractpngids && is_in_range(id, extractpngids)) {
982                 handlelossless(tag);
983             }
984 #endif
985         }
986         else if (tag->id == ST_SETBACKGROUNDCOLOR) {
987             mainr = tag->data[0];
988             maing = tag->data[1];
989             mainb = tag->data[2];
990         }
991         else if(tag->id == ST_PLACEOBJECT2) {
992             char*name = swf_GetName(tag);
993             if(name && extractname && !strcmp(name, extractname)) {
994                 int id = swf_GetPlaceID(tag); 
995                 used[id] = 5;
996                 found = 1;
997                 tagused[tagnum] = 1;
998                 depths[swf_GetDepth(tag)] = 1;
999                 extractname_id = id;
1000             }
1001         }
1002         else if(tag->id == ST_SHOWFRAME) {
1003             frame ++;
1004             if(hollow) {
1005                 tagused[tagnum] = 1;
1006                 found = 1;
1007             }
1008         }
1009         
1010         if(tag->id == ST_DEFINESPRITE) {
1011             while(tag->id != ST_END) { 
1012                 tag = tag->next;
1013                 tagnum ++;
1014             }
1015         }
1016         tag = tag->next;
1017         tagnum ++;
1018     }
1019     if (found)
1020         extractTag(&swf, destfilename);
1021
1022     if(mp3file)
1023         fclose(mp3file);
1024
1025     swf_FreeTags(&swf);
1026     return 0;
1027 }
1028