fixed framerate calculation.
[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]->id==ST_DEFINESPRITE) {
289                  TAG*tag = tags[t];
290                  while(tag->id != ST_END)
291                  {
292                      enumerateIDs(tag, idcallback);
293                      tag = tag->next;
294                  }
295              }
296              else 
297                enumerateIDs(tags[t], idcallback);
298              used[t] |= 2;
299            }
300        }
301     }
302     while(changed);
303
304     srctag = swf->firstTag;
305     tagnum = 0;
306     sprite = 0;
307     while(srctag && (srctag->id || sprite)) {
308         int reset = 0;
309         if(!sprite) {
310             copy = 0;
311         }
312         if(srctag->id == ST_END) {
313             sprite = 0;
314         }
315         if(srctag->id == ST_DEFINESPRITE)
316             sprite = 1;
317         if(swf_isDefiningTag(srctag)) {
318             int id = swf_GetDefineID(srctag);
319             if(used[id])  {
320                 SRECT b;
321                 copy = 1;
322                 b = swf_GetDefineBBox(srctag);
323                 swf_ExpandRect2(&objectbbox, &b);
324             }
325         } else 
326         if (((((srctag->id == ST_PLACEOBJECT || srctag->id == ST_PLACEOBJECT2) && originalplaceobjects)
327               || srctag->id == ST_STARTSOUND) && (used[swf_GetPlaceID(srctag)]&4) ) ||
328               (swf_isPseudoDefiningTag(srctag) && used[swf_GetDefineID(srctag)]) ||
329               (tagused[tagnum])) 
330         {
331                 if(copy == 0)
332                     reset = 1;
333                 copy = 1;
334         } 
335         if(srctag->id == ST_REMOVEOBJECT) {
336             if(!used[swf_GetPlaceID(srctag)])
337                 copy = 0;
338         }
339
340         if(copy) {
341             TAG*ttag = (TAG*)malloc(sizeof(TAG));
342             desttag = swf_InsertTag(desttag, srctag->id);
343             desttag->len = desttag->memsize = srctag->len;
344             desttag->data = malloc(srctag->len);
345             memcpy(desttag->data, srctag->data, srctag->len);
346             if(reset)
347                 copy = 0;
348         }
349         
350         srctag = srctag->next;
351         tagnum ++;
352     }
353     if(!extractframes && !hollow) {
354         if(!originalplaceobjects && (extractids||extractname_id>=0)) {
355             int t;
356             int s=0;
357             if((objectbbox.xmin|objectbbox.ymin|objectbbox.xmax|objectbbox.ymax)!=0)
358                 newswf.movieSize = objectbbox;
359             if(extractname_id>=0) {
360                 desttag = swf_InsertTag(desttag, ST_PLACEOBJECT2);
361                 swf_ObjectPlace(desttag, extractname_id, extractname_id, 0,0,extractname);
362             } else {
363                 for(t=0;t<65536;t++) {
364                     if(is_in_range(t, extractids)) {
365                         desttag = swf_InsertTag(desttag, ST_PLACEOBJECT2);
366                         swf_ObjectPlace(desttag, t, t, 0,0,0);
367                         s++;
368                         if(s==2)
369                             printf("warning! You should use the -P when extracting multiple objects\n");
370                     }
371                 }
372             }
373         }
374         desttag = swf_InsertTag(desttag,ST_SHOWFRAME);
375     }
376     desttag = swf_InsertTag(desttag,ST_END);
377     
378     f = open(filename, O_TRUNC|O_WRONLY|O_CREAT|O_BINARY, 0644);
379     if FAILED(swf_WriteSWF(f,&newswf)) fprintf(stderr,"WriteSWF() failed.\n");
380     close(f);
381
382     swf_FreeTags(&newswf);                       // cleanup
383 }
384
385 void listObjects(SWF*swf)
386 {
387     TAG*tag;
388     char first;
389     int t;
390     int frame = 0;
391     char*names[] = {"Shapes","MovieClips","JPEGs","PNGs","Sounds","Fonts"};
392     printf("Objects in file %s:\n",filename);
393     for(t=0;t<sizeof(names)/sizeof(names[0]);t++) {
394         tag = swf->firstTag;
395         first = 1;
396         while(tag) {
397             char show = 0;
398             char text[80];
399             if(t == 0 &&
400                (tag->id == ST_DEFINESHAPE ||
401                 tag->id == ST_DEFINESHAPE2 ||
402                 tag->id == ST_DEFINESHAPE3)) {
403                 show = 1;
404                 sprintf(text,"%d", swf_GetDefineID(tag));
405             }
406
407             if(tag->id == ST_DEFINESPRITE) {
408                 if (t == 1)  {
409                     show = 1;
410                     sprintf(text,"%d", swf_GetDefineID(tag));
411                 }
412
413                 while(tag->id != ST_END)
414                     tag = tag->next;
415             }
416
417             if(t == 2 && (tag->id == ST_DEFINEBITS ||
418                 tag->id == ST_DEFINEBITSJPEG2 ||
419                 tag->id == ST_DEFINEBITSJPEG3)) {
420                 show = 1;
421                 sprintf(text,"%d", swf_GetDefineID(tag));
422             }
423
424             if(t == 3 && (tag->id == ST_DEFINEBITSLOSSLESS ||
425                 tag->id == ST_DEFINEBITSLOSSLESS2)) {
426                 show = 1;
427                 sprintf(text,"%d", swf_GetDefineID(tag));
428             }
429
430
431             if(t == 4 && (tag->id == ST_DEFINESOUND)) {
432                 show = 1;
433                 sprintf(text,"%d", swf_GetDefineID(tag));
434             }
435             
436             if(t == 5 && (tag->id == ST_DEFINEFONT || tag->id == ST_DEFINEFONT2)) {
437                 show = 1;
438                 sprintf(text,"%d", swf_GetDefineID(tag));
439             }
440             
441             if(show) {
442                 if(!first)
443                     printf(", ");
444                 else
445                     printf("%s: ", names[t]);
446                 printf("%s", text);
447                 first = 0;
448             }
449             tag=tag->next;
450         }
451         if(!first)
452             printf("\n");
453     }
454
455     if(frame)
456         printf("Frames: 0-%d\n", frame);
457     else
458         printf("Frames: 0\n");
459 }
460
461 void handlefont(SWF*swf, TAG*tag)
462 {
463     SWFFONT* f=0;
464     U16 id;
465     char name[80];
466     char*filename = name;
467     int t;
468
469     id = swf_GetDefineID(tag);
470     sprintf(name, "font%d.swf", id);
471     if(numextracts==1) {
472         filename = destfilename;
473     }
474
475     swf_FontExtract(swf, id, &f);
476     if(!f) {
477         printf("Couldn't extract font %d\n", id);
478         return;
479     }
480     if(!f->layout)
481         swf_FontCreateLayout(f);
482
483     swf_WriteFont(f, filename);
484     swf_FontFree(f);
485 }
486
487 U8*jpegtables = 0;
488 int jpegtablessize;
489
490 void handlejpegtables(TAG*tag)
491 {
492     if(tag->id == ST_JPEGTABLES) {
493         jpegtables = tag->data;
494         jpegtablessize = tag->len;
495     }
496 }
497
498 FILE* save_fopen(char* name, char* mode)
499 {
500     FILE*fi = fopen(name, mode);
501     if(!fi) {
502         fprintf(stderr, "Error: Couldn't open %s\n", name);
503         exit(1);
504     }
505     return fi;
506 }
507
508 int findjpegboundary(U8*data, int len)
509 {
510     int t;
511     int pos=-1;
512     for(t=0;t<len;t++) {
513         if(data[t  ]==0xff &&
514            data[t+1]==0xd9 &&
515            data[t+2]==0xff &&
516            data[t+3]==0xd8) {
517             pos = t;
518         }
519     }
520     return pos;
521 }
522
523 /* extract jpeg data out of a tag */
524 void handlejpeg(TAG*tag)
525 {
526     char name[80];
527     char*filename = name;
528     FILE*fi;
529     
530     sprintf(name, "pic%d.jpg", GET16(tag->data));
531     if(numextracts==1) {
532         filename = destfilename;
533         if(!strcmp(filename,"output.swf"))
534             filename = "output.jpg";
535     }
536     /* swf jpeg images have two streams, which both start with ff d8 and
537        end with ff d9. The following code handles sorting the middle
538        <ff d9 ff d8> bytes out, so that one stream remains */
539     if(tag->id == ST_DEFINEBITS && tag->len>2 && jpegtables) {
540         fi = save_fopen(filename, "wb");
541         fwrite(jpegtables, 1, jpegtablessize-2, fi); //don't write end tag (ff,d8)
542         fwrite(&tag->data[2+2], tag->len-2-2, 1, fi); //don't write start tag (ff,d9)
543         fclose(fi);
544     }
545     else if(tag->id == ST_DEFINEBITSJPEG2 && tag->len>2) {
546         int end = tag->len;
547         int pos = findjpegboundary(&tag->data[2], tag->len-2);
548         if(pos<0)
549             return;
550         pos+=2;
551         fi = save_fopen(filename, "wb");
552         fwrite(&tag->data[2], pos-2, 1, fi);
553         fwrite(&tag->data[pos+4], end-(pos+4), 1, fi);
554         fclose(fi);
555     }
556     else if(tag->id == ST_DEFINEBITSJPEG3 && tag->len>6) {
557         U32 end = GET32(&tag->data[2])+6;
558         int pos = findjpegboundary(&tag->data[6], tag->len-6);
559         if(pos<0)
560             return;
561         pos+=6;
562         fi = save_fopen(filename, "wb");
563         fwrite(&tag->data[6], pos-6, 1, fi);
564         fwrite(&tag->data[pos+4], end-(pos+4), 1, fi);
565         fclose(fi);
566     }
567     else {
568         int id = GET16(tag->data);
569         fprintf(stderr, "Object %d is not a JPEG picture!\n",id);
570         exit(1);
571     }
572 }
573
574 #ifdef _ZLIB_INCLUDED_
575 static U32 mycrc32;
576
577 static U32*crc32_table = 0;
578 static void make_crc32_table(void)
579 {
580   int t;
581   if(crc32_table) 
582       return;
583   crc32_table = (U32*)malloc(1024);
584
585   for (t = 0; t < 256; t++) {
586     U32 c = t;
587     int s;
588     for (s = 0; s < 8; s++) {
589       c = (0xedb88320L*(c&1)) ^ (c >> 1);
590     }
591     crc32_table[t] = c;
592   }
593 }
594 static void png_write_byte(FILE*fi, U8 byte)
595 {
596     fwrite(&byte,1,1,fi);
597     mycrc32 = crc32_table[(mycrc32 ^ byte) & 0xff] ^ (mycrc32 >> 8);
598 }
599 static void png_start_chunk(FILE*fi, char*type, int len)
600 {
601     U8 mytype[4]={0,0,0,0};
602     U32 mylen = REVERSESWAP32(len);
603     memcpy(mytype,type,strlen(type));
604     fwrite(&mylen, 4, 1, fi);
605     mycrc32=0xffffffff;
606     png_write_byte(fi,mytype[0]);
607     png_write_byte(fi,mytype[1]);
608     png_write_byte(fi,mytype[2]);
609     png_write_byte(fi,mytype[3]);
610 }
611 static void png_write_bytes(FILE*fi, U8*bytes, int len)
612 {
613     int t;
614     for(t=0;t<len;t++)
615         png_write_byte(fi,bytes[t]);
616 }
617 static void png_write_dword(FILE*fi, U32 dword)
618 {
619     png_write_byte(fi,dword>>24);
620     png_write_byte(fi,dword>>16);
621     png_write_byte(fi,dword>>8);
622     png_write_byte(fi,dword);
623 }
624 static void png_end_chunk(FILE*fi)
625 {
626     U32 tmp = REVERSESWAP32((mycrc32^0xffffffff));
627     fwrite(&tmp,4,1,fi);
628 }
629
630
631 /* extract a lossless image (png) out of a tag 
632    This routine was originally meant to be a one-pager. I just
633    didn't know png is _that_ much fun. :) -mk
634  */
635 void handlelossless(TAG*tag)
636 {
637     char name[80];
638     char*filename = name;
639     FILE*fi;
640     int width, height;
641     int crc;
642     int id;
643     int t;
644     U8 bpp = 1;
645     U8 format;
646     U8 tmp;
647     U8* data=0;
648     U8* data2=0;
649     U8* data3=0;
650     U32 datalen;
651     U32 datalen2;
652     U32 datalen3;
653     U8 head[] = {137,80,78,71,13,10,26,10};
654     int cols;
655     char alpha = tag->id == ST_DEFINEBITSLOSSLESS2;
656     RGBA* palette;
657     int pos;
658     int error;
659     U32 tmp32;
660
661     make_crc32_table();
662
663     if(tag->id != ST_DEFINEBITSLOSSLESS &&
664        tag->id != ST_DEFINEBITSLOSSLESS2) {
665         int id = GET16(tag->data);
666         fprintf(stderr, "Object %d is not a PNG picture!\n",id);
667         exit(1);
668     }
669
670     id =swf_GetU16(tag);
671     format = swf_GetU8(tag);
672     if(format == 3) bpp = 8;
673     if(format == 4) bpp = 16;
674     if(format == 5) bpp = 32;
675     if(format!=3 && format!=5) {
676         if(format==4)
677         fprintf(stderr, "Can't handle 16-bit palette images yet (image %d)\n",id);
678         else 
679         fprintf(stderr, "Unknown image type %d in image %d\n", format, id);
680         return;
681     }
682     width = swf_GetU16(tag);
683     height = swf_GetU16(tag);
684     if(format == 3) cols = swf_GetU8(tag) + 1;
685 // this is what format means according to the flash specification. (which is
686 // clearly wrong)
687 //    if(format == 4) cols = swf_GetU16(tag) + 1;
688 //    if(format == 5) cols = swf_GetU32(tag) + 1;
689     else cols = 0;
690
691     msg("<verbose> Width %d", width);
692     msg("<verbose> Height %d", height);
693     msg("<verbose> Format %d", format);
694     msg("<verbose> Cols %d", cols);
695     msg("<verbose> Bpp %d", bpp);
696
697     datalen = (width*height*bpp/8+cols*8);
698     do {
699         if(data)
700             free(data);
701         datalen+=4096;
702         data = malloc(datalen);
703         error = uncompress (data, &datalen, &tag->data[tag->pos], tag->len-tag->pos);
704     } while(error == Z_BUF_ERROR);
705     if(error != Z_OK) {
706         fprintf(stderr, "Zlib error %d (image %d)\n", error, id);
707         return;
708     }
709     msg("<verbose> Uncompressed image is %d bytes (%d colormap)", datalen, (3+alpha)*cols);
710     pos = 0;
711     datalen2 = datalen;
712     data2 = malloc(datalen2);
713     palette = (RGBA*)malloc(cols*sizeof(RGBA));
714
715     for(t=0;t<cols;t++) {
716         palette[t].r = data[pos++];
717         palette[t].g = data[pos++];
718         palette[t].b = data[pos++];
719         if(alpha) {
720             palette[t].a = data[pos++];
721         }
722     }
723
724     sprintf(name, "pic%d.png", id);
725     if(numextracts==1) {
726         filename = destfilename;
727         if(!strcmp(filename,"output.swf"))
728             filename = "output.png";
729     }
730     fi = save_fopen(filename, "wb");
731     fwrite(head,sizeof(head),1,fi);     
732
733     png_start_chunk(fi, "IHDR", 13);
734      png_write_dword(fi,width);
735      png_write_dword(fi,height);
736      png_write_byte(fi,8);
737      if(format == 3)
738      png_write_byte(fi,3); //indexed
739      else if(format == 5)
740      png_write_byte(fi,2); //rgb
741      else return;
742
743      png_write_byte(fi,0); //compression mode
744      png_write_byte(fi,0); //filter mode
745      png_write_byte(fi,0); //interlace mode
746     png_end_chunk(fi);
747    
748     if(format == 3) {
749         png_start_chunk(fi, "PLTE", 768);
750          for(t=0;t<256;t++) {
751              png_write_byte(fi,palette[t].r);
752              png_write_byte(fi,palette[t].g);
753              png_write_byte(fi,palette[t].b);
754          }
755         png_end_chunk(fi);
756     }
757     {
758         int pos2 = 0;
759         int x,y;
760         int srcwidth = width * (bpp/8);
761         datalen3 = width*height*4;
762         data3 = (U8*)malloc(datalen3);
763         for(y=0;y<height;y++)
764         {
765            data3[pos2++]=0; //filter type
766            if(bpp==32) {
767             // 32 bit to 24 bit "conversion"
768             for(x=0;x<width;x++) {
769                 data3[pos2++]=data[pos+1];
770                 data3[pos2++]=data[pos+2];
771                 data3[pos2++]=data[pos+3];
772                 pos+=4; //ignore padding byte
773             }
774            }
775            else {
776                 for(x=0;x<srcwidth;x++)
777                     data3[pos2++]=data[pos++];
778            }
779            
780            pos+=((srcwidth+3)&~3)-srcwidth; //align
781         }
782         datalen3=pos2;
783     }
784
785     if(compress (data2, &datalen2, data3, datalen3) != Z_OK) {
786         fprintf(stderr, "zlib error in pic %d\n", id);
787         return;
788     }
789     msg("<verbose> Compressed data is %d bytes", datalen2);
790     png_start_chunk(fi, "IDAT", datalen2);
791     png_write_bytes(fi,data2,datalen2);
792     png_end_chunk(fi);
793     png_start_chunk(fi, "IEND", 0);
794     png_end_chunk(fi);
795
796     free(data);
797     free(data2);
798     free(data3);
799 }
800 #endif
801
802 FILE*mp3file;
803 void handlesoundstream(TAG*tag)
804 {
805     char*filename = "output.mp3";
806     if(numextracts==1) {
807         filename = destfilename;
808         if(!strcmp(filename,"output.swf"))
809             filename = "output.mp3";
810     }
811     switch(tag->id) {
812         case ST_SOUNDSTREAMHEAD:
813             if((tag->data[1]&0x30) == 0x20) { //mp3 compression
814                 mp3file = fopen(filename, "wb");
815                 msg("<notice> Writing mp3 data to %s",filename);
816             }
817             else
818                 msg("<error> Soundstream is not mp3");
819         break;
820         case ST_SOUNDSTREAMHEAD2:
821             if((tag->data[1]&0x30) == 0x20) {//mp3 compression
822                 mp3file = fopen(filename, "wb");
823                 msg("<notice> Writing mp3 data to %s",filename);
824             }
825             else
826                 msg("<error> Soundstream is not mp3 (2)");
827         break;
828         case ST_SOUNDSTREAMBLOCK:
829             if(mp3file)
830                 fwrite(&tag->data[4],tag->len-4,1,mp3file);
831         break;
832     }
833 }
834
835 void handledefinesound(TAG*tag)
836 {
837     U8 flags;
838     U32 samples;
839     char buf[128];
840     char*filename = buf;
841     FILE*fi;
842     U16 id;
843     id = swf_GetU16(tag); //id
844     sprintf(buf, "sound%d.mp3", id);
845
846     if(numextracts==1) {
847         filename = destfilename;
848         if(!strcmp(filename,"output.swf"))
849             filename = "output.mp3";
850     }
851     flags = swf_GetU8(tag);
852     if((flags>>4)!=2) {
853         printf("Sorry, can only extract MP3 sounds. Sound %d is ADPCM or RAW.\n", id);
854         /* not mp3 */
855         return;
856     }
857     samples = swf_GetU32(tag);
858     
859     swf_GetU16(tag); //(only for mp3) numsamples_seek
860
861     fi = save_fopen(filename, "wb");
862     fwrite(&tag->data[tag->pos], tag->len - tag->pos, 1, fi);
863     fclose(fi);
864 }
865
866 int main (int argc,char ** argv)
867
868     TAG*tag;
869     SWF swf;
870     int f;
871     int found = 0;
872     int frame = 0;
873     int tagnum = 0;
874     char depths[65536];
875     char listavailable = 0;
876     processargs(argc, argv);
877
878     if(!extractframes && !extractids && ! extractname && !extractjpegids && !extractpngids
879         && !extractmp3 && !extractsoundids && !extractfontids)
880         listavailable = 1;
881
882     if(!filename)
883     {
884         fprintf(stderr, "You must supply a filename.\n");
885         return 1;
886     }
887     initLog(0,-1,0,0,-1, verbose);
888
889     f = open(filename,O_RDONLY|O_BINARY);
890
891     if (f<0)
892     { 
893         perror("Couldn't open file: ");
894         exit(1);
895     }
896     if (swf_ReadSWF(f,&swf) < 0)
897     { 
898         fprintf(stderr, "%s is not a valid SWF file or contains errors.\n",filename);
899         close(f);
900         exit(1);
901     }
902     close(f);
903
904     if(listavailable) {
905         listObjects(&swf);
906         swf_FreeTags(&swf);
907         return 0;
908     }
909
910     tag = swf.firstTag;
911     tagnum = 0;
912     while(tag) {
913         tagnum ++;
914         tag = tag->next;
915     }
916
917     tagused = (char*)malloc(tagnum);
918     memset(tagused, 0, tagnum);
919     memset(used, 0, 65536);
920     memset(depths, 0, 65536);
921
922     tag = swf.firstTag;
923     tagnum = 0;
924     while(tag) {
925         if(swf_isAllowedSpriteTag(tag)) {
926             int write = 0;
927             if(extractframes && is_in_range(frame, extractframes)) {
928                 write = 1;
929                 if(tag->id == ST_PLACEOBJECT || tag->id == ST_PLACEOBJECT2) {
930                     depths[swf_GetDepth(tag)] = 1;
931                 }
932                 if(tag->id == ST_REMOVEOBJECT || tag->id == ST_REMOVEOBJECT2) {
933                     int depth = swf_GetDepth(tag);
934                     if(!depths[depth]) 
935                         write = 0;
936                     depths[swf_GetDepth(tag)] = 0;
937                 }
938             } else {
939                 if((tag->id == ST_REMOVEOBJECT || tag->id == ST_REMOVEOBJECT2) && 
940                     (depths[swf_GetDepth(tag)]) && hollow) {
941                     write = 1;
942                     depths[swf_GetDepth(tag)] = 0;
943                 }
944             }
945             if(write) {
946                 enumerateIDs(tag, idcallback);
947                 found = 1;
948                 tagused[tagnum] = 1;
949             }
950         }
951
952         if(tag->id == ST_SOUNDSTREAMHEAD ||
953            tag->id == ST_SOUNDSTREAMHEAD2 ||
954            tag->id == ST_SOUNDSTREAMBLOCK) {
955             if(extractmp3)
956                 handlesoundstream(tag);
957         }
958
959         if(tag->id == ST_JPEGTABLES)
960             handlejpegtables(tag);
961
962         if(swf_isDefiningTag(tag)) {
963             int id = swf_GetDefineID(tag);
964             tags[id] = tag;
965             if(extractids && is_in_range(id, extractids)) {
966                 used[id] = 5;
967                 found = 1;
968             }
969             if(extractfontids && is_in_range(id, extractfontids)) {
970                 handlefont(&swf, tag);
971             }
972             if(extractjpegids && is_in_range(id, extractjpegids)) {
973                 handlejpeg(tag);
974             }
975             if(extractsoundids && is_in_range(id, extractsoundids)) {
976                 handledefinesound(tag);
977             }
978 #ifdef _ZLIB_INCLUDED_
979             if(extractpngids && is_in_range(id, extractpngids)) {
980                 handlelossless(tag);
981             }
982 #endif
983         }
984         else if (tag->id == ST_SETBACKGROUNDCOLOR) {
985             mainr = tag->data[0];
986             maing = tag->data[1];
987             mainb = tag->data[2];
988         }
989         else if(tag->id == ST_PLACEOBJECT2) {
990             char*name = swf_GetName(tag);
991             if(name && extractname && !strcmp(name, extractname)) {
992                 int id = swf_GetPlaceID(tag); 
993                 used[id] = 5;
994                 found = 1;
995                 tagused[tagnum] = 1;
996                 depths[swf_GetDepth(tag)] = 1;
997                 extractname_id = id;
998             }
999         }
1000         else if(tag->id == ST_SHOWFRAME) {
1001             frame ++;
1002             if(hollow) {
1003                 tagused[tagnum] = 1;
1004                 found = 1;
1005             }
1006         }
1007         
1008         if(tag->id == ST_DEFINESPRITE) {
1009             while(tag->id != ST_END) { 
1010                 tag = tag->next;
1011                 tagnum ++;
1012             }
1013         }
1014         tag = tag->next;
1015         tagnum ++;
1016     }
1017     if (found)
1018         extractTag(&swf, destfilename);
1019
1020     if(mp3file)
1021         fclose(mp3file);
1022
1023     swf_FreeTags(&swf);
1024     return 0;
1025 }
1026