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