fixed rescaling
[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 number = 0;
358             int id = 0;
359             int t;
360             TAG* objtag = 0;
361             SRECT bbox;
362             memset(&bbox, 0, sizeof(SRECT));
363             for(t=0;t<65536;t++) {
364                 if(is_in_range(t, extractids)) {
365                     id = t;
366                     number++;
367                 }
368             }
369             if(number>=2)
370                 printf("warning! You should use the -P when extracting multiple objects\n");
371
372             if(number == 1) {
373                 /* if there is only one object, we will scale it.
374                    So let's figure out it's bounding box */
375                 TAG*tag = swf->firstTag;
376                 while(tag) {
377                     if(swf_isDefiningTag(tag) && tag->id != ST_DEFINESPRITE) {
378                         if(swf_GetDefineID(tag) == id)
379                             bbox = swf_GetDefineBBox(tag);
380                         objtag = tag;
381                     }
382                     tag = tag->next;
383                 }
384                 newswf.movieSize.xmin = 0;
385                 newswf.movieSize.ymin = 0;
386                 newswf.movieSize.xmax = 512*20;
387                 newswf.movieSize.ymax = 512*20;
388             } else {
389                 if((objectbbox.xmin|objectbbox.ymin|objectbbox.xmax|objectbbox.ymax)!=0)
390                     newswf.movieSize = objectbbox;
391             }
392
393             if(extractname_id>=0) {
394                 desttag = swf_InsertTag(desttag, ST_PLACEOBJECT2);
395                 swf_ObjectPlace(desttag, extractname_id, extractname_id, 0,0,extractname);
396             } else {
397                 for(t=0;t<65536;t++) {
398                     if(is_in_range(t, extractids)) {
399                         MATRIX m;
400                         desttag = swf_InsertTag(desttag, ST_PLACEOBJECT2);
401                         swf_GetMatrix(0, &m);
402                         if(objtag) {
403                             int width = bbox.xmax - bbox.xmin;
404                             int height = bbox.ymax - bbox.ymin;
405                             int max = width>height?width:height;
406                             m.tx = -bbox.xmin;
407                             m.ty = -bbox.ymin;
408                             if(max) {
409                                 m.sx = (512*20*65536)/max;
410                                 m.sy = (512*20*65536)/max;
411                             }
412                             //newswf.movieSize = swf_TurnRect(newswf.movieSize, &m);
413                         }
414                         swf_ObjectPlace(desttag, t, t, &m,0,0);
415                     }
416                 }
417             }
418         }
419         desttag = swf_InsertTag(desttag,ST_SHOWFRAME);
420     }
421     desttag = swf_InsertTag(desttag,ST_END);
422     
423     f = open(filename, O_TRUNC|O_WRONLY|O_CREAT|O_BINARY, 0644);
424     if FAILED(swf_WriteSWF(f,&newswf)) fprintf(stderr,"WriteSWF() failed.\n");
425     close(f);
426
427     swf_FreeTags(&newswf);                       // cleanup
428 }
429
430 int isOfType(int t, TAG*tag)
431 {
432     int show = 0;
433     if(t == 0 && (tag->id == ST_DEFINESHAPE ||
434         tag->id == ST_DEFINESHAPE2 ||
435         tag->id == ST_DEFINESHAPE3)) {
436         show = 1;
437     }
438     if(t==1 && tag->id == ST_DEFINESPRITE) {
439         show = 1;
440     }
441     if(t == 2 && (tag->id == ST_DEFINEBITS ||
442         tag->id == ST_DEFINEBITSJPEG2 ||
443         tag->id == ST_DEFINEBITSJPEG3)) {
444         show = 1;
445     }
446     if(t == 3 && (tag->id == ST_DEFINEBITSLOSSLESS ||
447         tag->id == ST_DEFINEBITSLOSSLESS2)) {
448         show = 1;
449     }
450     if(t == 4 && (tag->id == ST_DEFINESOUND)) {
451         show = 1;
452     }
453     if(t == 5 && (tag->id == ST_DEFINEFONT || tag->id == ST_DEFINEFONT2)) {
454         show = 1;
455     }
456     return show;
457 }
458
459 void listObjects(SWF*swf)
460 {
461     TAG*tag;
462     char first;
463     int t;
464     int frame = 0;
465     char*names[] = {"Shape", "MovieClip", "JPEG", "PNG", "Sound", "Font"};
466     char*options[] = {"-i", "-i", "-j", "-p", "-s", "-F"};
467     int mp3=0;
468     printf("Objects in file %s:\n",filename);
469     swf_FoldAll(swf);
470     for(t=0;t<sizeof(names)/sizeof(names[0]);t++) {
471         int nr=0;
472         int lastid = -2, lastprint=-1;
473         int follow=0;
474         tag = swf->firstTag;
475         first = 1;
476         while(tag) {
477             if(tag->id == ST_SOUNDSTREAMHEAD || tag->id == ST_SOUNDSTREAMHEAD2)
478                 mp3 = 1;
479             if(isOfType(t,tag))
480                 nr++;
481             tag = tag->next;
482         }
483         if(!nr)
484             continue;
485         
486         printf(" [%s] %d %s%s: ID(s) ", options[t], nr, names[t], nr>1?"s":"");
487
488         tag = swf->firstTag;
489         while(tag) {
490             char text[80];
491             char show = isOfType(t,tag);
492             int id;
493             if(!show) {
494                 tag = tag->next;
495                 continue;
496             }
497             id = swf_GetDefineID(tag);
498
499             if(id == lastid+1) {
500                 follow=1;
501             } else {
502                 if(first || !follow) {
503                     if(!first)
504                         printf(", ");
505                     printf("%d", id);
506                 } else {
507                     if(lastprint + 1 == lastid) 
508                         printf(", %d, %d", lastid, id);
509                     else
510                         printf("-%d, %d", lastid, id);
511                 }
512                 lastprint = id;
513                 first = 0;
514                 follow = 0;
515             }
516             lastid = id;
517             tag=tag->next;
518         }
519         if(follow) {
520             if(lastprint + 1 == lastid)
521                 printf(", %d", lastid);
522             else
523                 printf("-%d", lastid);
524         }
525         printf("\n");
526     }
527
528     if(frame)
529         printf(" [-f] %d Frames: ID(s) 0-%d\n", frame, frame);
530     else
531         printf(" [-f] 1 Frame: ID(s) 0\n");
532
533     if(mp3)
534         printf(" [-m] 1 MP3 Soundstream\n");
535 }
536
537 void handlefont(SWF*swf, TAG*tag)
538 {
539     SWFFONT* f=0;
540     U16 id;
541     char name[80];
542     char*filename = name;
543     int t;
544
545     id = swf_GetDefineID(tag);
546     sprintf(name, "font%d.swf", id);
547     if(numextracts==1) {
548         filename = destfilename;
549     }
550
551     swf_FontExtract(swf, id, &f);
552     if(!f) {
553         printf("Couldn't extract font %d\n", id);
554         return;
555     }
556     if(!f->layout)
557         swf_FontCreateLayout(f);
558
559     swf_WriteFont(f, filename);
560     swf_FontFree(f);
561 }
562
563 U8*jpegtables = 0;
564 int jpegtablessize;
565
566 void handlejpegtables(TAG*tag)
567 {
568     if(tag->id == ST_JPEGTABLES) {
569         jpegtables = tag->data;
570         jpegtablessize = tag->len;
571     }
572 }
573
574 FILE* save_fopen(char* name, char* mode)
575 {
576     FILE*fi = fopen(name, mode);
577     if(!fi) {
578         fprintf(stderr, "Error: Couldn't open %s\n", name);
579         exit(1);
580     }
581     return fi;
582 }
583
584 int findjpegboundary(U8*data, int len)
585 {
586     int t;
587     int pos=-1;
588     for(t=0;t<len;t++) {
589         if(data[t  ]==0xff &&
590            data[t+1]==0xd9 &&
591            data[t+2]==0xff &&
592            data[t+3]==0xd8) {
593             pos = t;
594         }
595     }
596     return pos;
597 }
598
599 /* extract jpeg data out of a tag */
600 void handlejpeg(TAG*tag)
601 {
602     char name[80];
603     char*filename = name;
604     FILE*fi;
605     
606     sprintf(name, "pic%d.jpg", GET16(tag->data));
607     if(numextracts==1) {
608         filename = destfilename;
609         if(!strcmp(filename,"output.swf"))
610             filename = "output.jpg";
611     }
612     /* swf jpeg images have two streams, which both start with ff d8 and
613        end with ff d9. The following code handles sorting the middle
614        <ff d9 ff d8> bytes out, so that one stream remains */
615     if(tag->id == ST_DEFINEBITSJPEG && tag->len>2 && jpegtables) {
616         fi = save_fopen(filename, "wb");
617         fwrite(jpegtables, 1, jpegtablessize-2, fi); //don't write end tag (ff,d8)
618         fwrite(&tag->data[2+2], tag->len-2-2, 1, fi); //don't write start tag (ff,d9)
619         fclose(fi);
620     }
621     else if(tag->id == ST_DEFINEBITSJPEG2 && tag->len>2) {
622         int end = tag->len;
623         int pos = findjpegboundary(&tag->data[2], tag->len-2);
624         if(pos>=0) {
625             pos+=2;
626             fi = save_fopen(filename, "wb");
627             fwrite(&tag->data[2], pos-2, 1, fi);
628             fwrite(&tag->data[pos+4], end-(pos+4), 1, fi);
629             fclose(fi);
630         } else {
631             fi = save_fopen(filename, "wb");
632             fwrite(&tag->data[2], end-2, 1, fi);
633             fclose(fi);
634         }
635     }
636     else if(tag->id == ST_DEFINEBITSJPEG3 && tag->len>6) {
637         U32 end = GET32(&tag->data[2])+6;
638         int pos = findjpegboundary(&tag->data[6], tag->len-6);
639         if(pos<0)
640             return;
641         pos+=6;
642         fi = save_fopen(filename, "wb");
643         fwrite(&tag->data[6], pos-6, 1, fi);
644         fwrite(&tag->data[pos+4], end-(pos+4), 1, fi);
645         fclose(fi);
646     }
647     else {
648         int id = GET16(tag->data);
649         fprintf(stderr, "Object %d is not a JPEG picture!\n",id);
650         exit(1);
651     }
652 }
653
654 #ifdef _ZLIB_INCLUDED_
655 static U32 mycrc32;
656
657 static U32*crc32_table = 0;
658 static void make_crc32_table(void)
659 {
660   int t;
661   if(crc32_table) 
662       return;
663   crc32_table = (U32*)malloc(1024);
664
665   for (t = 0; t < 256; t++) {
666     U32 c = t;
667     int s;
668     for (s = 0; s < 8; s++) {
669       c = (0xedb88320L*(c&1)) ^ (c >> 1);
670     }
671     crc32_table[t] = c;
672   }
673 }
674 static inline void png_write_byte(FILE*fi, U8 byte)
675 {
676     fwrite(&byte,1,1,fi);
677     mycrc32 = crc32_table[(mycrc32 ^ byte) & 0xff] ^ (mycrc32 >> 8);
678 }
679 static void png_start_chunk(FILE*fi, char*type, int len)
680 {
681     U8 mytype[4]={0,0,0,0};
682     U32 mylen = REVERSESWAP32(len);
683     memcpy(mytype,type,strlen(type));
684     fwrite(&mylen, 4, 1, fi);
685     mycrc32=0xffffffff;
686     png_write_byte(fi,mytype[0]);
687     png_write_byte(fi,mytype[1]);
688     png_write_byte(fi,mytype[2]);
689     png_write_byte(fi,mytype[3]);
690 }
691 static void png_write_bytes(FILE*fi, U8*bytes, int len)
692 {
693     int t;
694     for(t=0;t<len;t++)
695         png_write_byte(fi,bytes[t]);
696 }
697 static void png_write_dword(FILE*fi, U32 dword)
698 {
699     png_write_byte(fi,dword>>24);
700     png_write_byte(fi,dword>>16);
701     png_write_byte(fi,dword>>8);
702     png_write_byte(fi,dword);
703 }
704 static void png_end_chunk(FILE*fi)
705 {
706     U32 tmp = REVERSESWAP32((mycrc32^0xffffffff));
707     fwrite(&tmp,4,1,fi);
708 }
709
710
711 /* extract a lossless image (png) out of a tag 
712    This routine was originally meant to be a one-pager. I just
713    didn't know png is _that_ much fun. :) -mk
714  */
715 void handlelossless(TAG*tag)
716 {
717     char name[80];
718     char*filename = name;
719     FILE*fi;
720     int width, height;
721     int crc;
722     int id;
723     int t;
724     U8 bpp = 1;
725     U8 format;
726     U8 tmp;
727     U8* data=0;
728     U8* data2=0;
729     U8* data3=0;
730     U32 datalen;
731     U32 datalen2;
732     U32 datalen3;
733     U8 head[] = {137,80,78,71,13,10,26,10};
734     int cols;
735     char alpha = tag->id == ST_DEFINEBITSLOSSLESS2;
736     RGBA* palette;
737     int pos;
738     int error;
739     U32 tmp32;
740
741     make_crc32_table();
742
743     if(tag->id != ST_DEFINEBITSLOSSLESS &&
744        tag->id != ST_DEFINEBITSLOSSLESS2) {
745         int id = GET16(tag->data);
746         fprintf(stderr, "Object %d is not a PNG picture!\n",id);
747         exit(1);
748     }
749
750     id =swf_GetU16(tag);
751     format = swf_GetU8(tag);
752     if(format == 3) bpp = 8;
753     if(format == 4) bpp = 16;
754     if(format == 5) bpp = 32;
755     if(format!=3 && format!=5) {
756         if(format==4)
757         fprintf(stderr, "Can't handle 16-bit palette images yet (image %d)\n",id);
758         else 
759         fprintf(stderr, "Unknown image type %d in image %d\n", format, id);
760         return;
761     }
762     width = swf_GetU16(tag);
763     height = swf_GetU16(tag);
764     if(format == 3) cols = swf_GetU8(tag) + 1;
765 // this is what format means according to the flash specification. (which is
766 // clearly wrong)
767 //    if(format == 4) cols = swf_GetU16(tag) + 1;
768 //    if(format == 5) cols = swf_GetU32(tag) + 1;
769     else cols = 0;
770
771     msg("<verbose> Width %d", width);
772     msg("<verbose> Height %d", height);
773     msg("<verbose> Format %d", format);
774     msg("<verbose> Cols %d", cols);
775     msg("<verbose> Bpp %d", bpp);
776
777     datalen = (width*height*bpp/8+cols*8);
778     do {
779         if(data)
780             free(data);
781         datalen+=4096;
782         data = malloc(datalen);
783         error = uncompress (data, &datalen, &tag->data[tag->pos], tag->len-tag->pos);
784     } while(error == Z_BUF_ERROR);
785     if(error != Z_OK) {
786         fprintf(stderr, "Zlib error %d (image %d)\n", error, id);
787         return;
788     }
789     msg("<verbose> Uncompressed image is %d bytes (%d colormap)", datalen, (3+alpha)*cols);
790     pos = 0;
791     datalen2 = datalen;
792     data2 = malloc(datalen2);
793     palette = (RGBA*)malloc(cols*sizeof(RGBA));
794
795     for(t=0;t<cols;t++) {
796         palette[t].r = data[pos++];
797         palette[t].g = data[pos++];
798         palette[t].b = data[pos++];
799         if(alpha) {
800             palette[t].a = data[pos++];
801         }
802     }
803
804     sprintf(name, "pic%d.png", id);
805     if(numextracts==1) {
806         filename = destfilename;
807         if(!strcmp(filename,"output.swf"))
808             filename = "output.png";
809     }
810     fi = save_fopen(filename, "wb");
811     fwrite(head,sizeof(head),1,fi);     
812
813     png_start_chunk(fi, "IHDR", 13);
814      png_write_dword(fi,width);
815      png_write_dword(fi,height);
816      png_write_byte(fi,8);
817      if(format == 3)
818      png_write_byte(fi,3); //indexed
819      else if(format == 5 && alpha==0)
820      png_write_byte(fi,2); //rgb
821      else if(format == 5 && alpha==1)
822      png_write_byte(fi,6); //rgba
823      else return;
824
825      png_write_byte(fi,0); //compression mode
826      png_write_byte(fi,0); //filter mode
827      png_write_byte(fi,0); //interlace mode
828     png_end_chunk(fi);
829    
830     if(format == 3) {
831         png_start_chunk(fi, "PLTE", 768);
832          
833          for(t=0;t<256;t++) {
834              png_write_byte(fi,palette[t].r);
835              png_write_byte(fi,palette[t].g);
836              png_write_byte(fi,palette[t].b);
837          }
838         png_end_chunk(fi);
839
840         if(alpha) {
841             /* write alpha palette */
842             png_start_chunk(fi, "tRNS", 256);
843             for(t=0;t<256;t++) {
844                 png_write_byte(fi,palette[t].a);
845             }
846             png_end_chunk(fi);
847         }
848     }
849     {
850         int pos2 = 0;
851         int x,y;
852         int srcwidth = width * (bpp/8);
853         datalen3 = (width*4+5)*height;
854         data3 = (U8*)malloc(datalen3);
855         for(y=0;y<height;y++)
856         {
857            data3[pos2++]=0; //filter type
858            if(bpp==32) {
859             if(!alpha) {
860                 // 32 bit to 24 bit "conversion"
861                 for(x=0;x<width;x++) {
862                     data3[pos2++]=data[pos+1];
863                     data3[pos2++]=data[pos+2];
864                     data3[pos2++]=data[pos+3];
865                     pos+=4; //ignore padding byte
866                 }
867             } else {
868                 for(x=0;x<width;x++) {
869                     data3[pos2++]=data[pos+1];
870                     data3[pos2++]=data[pos+2];
871                     data3[pos2++]=data[pos+3];
872                     data3[pos2++]=data[pos+0]; //alpha
873                     pos+=4;
874                 }
875             }
876            }
877            else {
878                 for(x=0;x<srcwidth;x++)
879                     data3[pos2++]=data[pos++];
880            }
881            
882            pos+=((srcwidth+3)&~3)-srcwidth; //align
883         }
884         datalen3=pos2;
885     }
886
887     if(compress (data2, &datalen2, data3, datalen3) != Z_OK) {
888         fprintf(stderr, "zlib error in pic %d\n", id);
889         return;
890     }
891     msg("<verbose> Compressed data is %d bytes", datalen2);
892     png_start_chunk(fi, "IDAT", datalen2);
893     png_write_bytes(fi,data2,datalen2);
894     png_end_chunk(fi);
895     png_start_chunk(fi, "IEND", 0);
896     png_end_chunk(fi);
897
898     free(data);
899     free(data2);
900     free(data3);
901 }
902 #endif
903
904 FILE*mp3file;
905 void handlesoundstream(TAG*tag)
906 {
907     char*filename = "output.mp3";
908     if(numextracts==1) {
909         filename = destfilename;
910         if(!strcmp(filename,"output.swf"))
911             filename = "output.mp3";
912     }
913     switch(tag->id) {
914         case ST_SOUNDSTREAMHEAD:
915             if((tag->data[1]&0x30) == 0x20) { //mp3 compression
916                 mp3file = fopen(filename, "wb");
917                 msg("<notice> Writing mp3 data to %s",filename);
918             }
919             else
920                 msg("<error> Soundstream is not mp3");
921         break;
922         case ST_SOUNDSTREAMHEAD2:
923             if((tag->data[1]&0x30) == 0x20) {//mp3 compression
924                 mp3file = fopen(filename, "wb");
925                 msg("<notice> Writing mp3 data to %s",filename);
926             }
927             else
928                 msg("<error> Soundstream is not mp3 (2)");
929         break;
930         case ST_SOUNDSTREAMBLOCK:
931             if(mp3file)
932                 fwrite(&tag->data[4],tag->len-4,1,mp3file);
933         break;
934     }
935 }
936
937 void handledefinesound(TAG*tag)
938 {
939     U8 flags;
940     U32 samples;
941     char buf[128];
942     char*filename = buf;
943     FILE*fi;
944     char*extension = 0;
945     int format;
946     U16 id;
947     int rate,bits,stereo;
948     char*rates[] = {"5500","11025","22050","44100"};
949     id = swf_GetU16(tag); //id
950     
951     flags = swf_GetU8(tag);
952     format = flags>>4;
953     rate = (flags>>2)&3;
954     bits = flags&2?16:8;
955     stereo = flags&1;
956     
957     samples = swf_GetU32(tag);
958
959     extension = "raw";
960
961     if(format == 2) { // mp3
962         swf_GetU16(tag); //numsamples_seek
963         extension = "mp3";
964     } else if(format == 0) { // raw
965         printf("Sound is RAW, format: %s samples/sec, %d bit, %s\n", rates[rate], bits, stereo?"stereo":"mono");
966         // TODO: convert to WAV
967         extension = "raw";
968     } else if(format == 1) { // adpcm
969         printf("Sound is ADPCM, format: %s samples/sec, %d bit, %s\n", rates[rate], bits, stereo?"stereo":"mono");
970         extension = "adpcm";
971     }
972     sprintf(buf, "sound%d.%s", id, extension);
973     if(numextracts==1) {
974         filename = destfilename;
975         if(!strcmp(filename,"output.swf")) {
976             sprintf(buf, "output.%s", extension);
977             filename = buf;
978         }
979     }
980     fi = save_fopen(filename, "wb");
981     fwrite(&tag->data[tag->pos], tag->len - tag->pos, 1, fi);
982     fclose(fi);
983 }
984
985 int main (int argc,char ** argv)
986
987     TAG*tag;
988     SWF swf;
989     int f;
990     int found = 0;
991     int frame = 0;
992     int tagnum = 0;
993     char depths[65536];
994     char listavailable = 0;
995     processargs(argc, argv);
996
997     if(!extractframes && !extractids && ! extractname && !extractjpegids && !extractpngids
998         && !extractmp3 && !extractsoundids && !extractfontids)
999         listavailable = 1;
1000
1001     if(!filename)
1002     {
1003         fprintf(stderr, "You must supply a filename.\n");
1004         return 1;
1005     }
1006     initLog(0,-1,0,0,-1, verbose);
1007
1008     f = open(filename,O_RDONLY|O_BINARY);
1009
1010     if (f<0)
1011     { 
1012         perror("Couldn't open file: ");
1013         exit(1);
1014     }
1015     if (swf_ReadSWF(f,&swf) < 0)
1016     { 
1017         fprintf(stderr, "%s is not a valid SWF file or contains errors.\n",filename);
1018         close(f);
1019         exit(1);
1020     }
1021     close(f);
1022
1023     if(listavailable) {
1024         listObjects(&swf);
1025         swf_FreeTags(&swf);
1026         return 0;
1027     }
1028
1029     tag = swf.firstTag;
1030     tagnum = 0;
1031     while(tag) {
1032         tagnum ++;
1033         tag = tag->next;
1034     }
1035
1036     tagused = (char*)malloc(tagnum);
1037     memset(tagused, 0, tagnum);
1038     memset(used, 0, 65536);
1039     memset(depths, 0, 65536);
1040
1041     tag = swf.firstTag;
1042     tagnum = 0;
1043     while(tag) {
1044         if(swf_isAllowedSpriteTag(tag)) {
1045             int write = 0;
1046             if(extractframes && is_in_range(frame, extractframes)) {
1047                 write = 1;
1048                 if(tag->id == ST_PLACEOBJECT || tag->id == ST_PLACEOBJECT2) {
1049                     depths[swf_GetDepth(tag)] = 1;
1050                 }
1051                 if(tag->id == ST_REMOVEOBJECT || tag->id == ST_REMOVEOBJECT2) {
1052                     int depth = swf_GetDepth(tag);
1053                     if(!depths[depth]) 
1054                         write = 0;
1055                     depths[swf_GetDepth(tag)] = 0;
1056                 }
1057             } else {
1058                 if((tag->id == ST_REMOVEOBJECT || tag->id == ST_REMOVEOBJECT2) && 
1059                     (depths[swf_GetDepth(tag)]) && hollow) {
1060                     write = 1;
1061                     depths[swf_GetDepth(tag)] = 0;
1062                 }
1063             }
1064             if(write) {
1065                 enumerateIDs(tag, idcallback);
1066                 found = 1;
1067                 tagused[tagnum] = 1;
1068             }
1069         }
1070
1071         if(tag->id == ST_SOUNDSTREAMHEAD ||
1072            tag->id == ST_SOUNDSTREAMHEAD2 ||
1073            tag->id == ST_SOUNDSTREAMBLOCK) {
1074             if(extractmp3)
1075                 handlesoundstream(tag);
1076         }
1077
1078         if(tag->id == ST_JPEGTABLES)
1079             handlejpegtables(tag);
1080
1081         if(swf_isDefiningTag(tag)) {
1082             int id = swf_GetDefineID(tag);
1083             tags[id] = tag;
1084             if(extractids && is_in_range(id, extractids)) {
1085                 used[id] = 5;
1086                 found = 1;
1087             }
1088             if(extractfontids && is_in_range(id, extractfontids)) {
1089                 handlefont(&swf, tag);
1090             }
1091             if(extractjpegids && is_in_range(id, extractjpegids)) {
1092                 handlejpeg(tag);
1093             }
1094             if(extractsoundids && is_in_range(id, extractsoundids)) {
1095                 handledefinesound(tag);
1096             }
1097 #ifdef _ZLIB_INCLUDED_
1098             if(extractpngids && is_in_range(id, extractpngids)) {
1099                 handlelossless(tag);
1100             }
1101 #endif
1102         }
1103         else if (tag->id == ST_SETBACKGROUNDCOLOR) {
1104             mainr = tag->data[0];
1105             maing = tag->data[1];
1106             mainb = tag->data[2];
1107         }
1108         else if(tag->id == ST_PLACEOBJECT2) {
1109             char*name = swf_GetName(tag);
1110             if(name && extractname && !strcmp(name, extractname)) {
1111                 int id = swf_GetPlaceID(tag); 
1112                 used[id] = 5;
1113                 found = 1;
1114                 tagused[tagnum] = 1;
1115                 depths[swf_GetDepth(tag)] = 1;
1116                 extractname_id = id;
1117             }
1118         }
1119         else if(tag->id == ST_SHOWFRAME) {
1120             frame ++;
1121             if(hollow) {
1122                 tagused[tagnum] = 1;
1123                 found = 1;
1124             }
1125         }
1126         
1127         if(tag->id == ST_DEFINESPRITE) {
1128             while(tag->id != ST_END) { 
1129                 tag = tag->next;
1130                 tagnum ++;
1131             }
1132         }
1133         tag = tag->next;
1134         tagnum ++;
1135     }
1136     if (found)
1137         extractTag(&swf, destfilename);
1138
1139     if(mp3file)
1140         fclose(mp3file);
1141
1142     swf_FreeTags(&swf);
1143     return 0;
1144 }
1145