can now extract jpeg images (into jpeg files).
[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 file is distributed under the GPL, see file COPYING for details */
9
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <fcntl.h>
13 #include "../lib/rfxswf.h"
14 #include "../lib/args.h"
15 #include "reloc.h"
16
17 char * filename = 0;
18 char * destfilename = "output.swf";
19 int verbose = 2;
20
21 char* extractids = 0;
22 char* extractframes = 0;
23 char* extractjpegids = 0;
24
25 char* extractname = 0;
26
27 char hollow = 0;
28
29 struct options_t options[] =
30 {
31  {"o","output"},
32  {"w","hollow"},
33  {"v","verbose"},
34  {"i","id"},
35  {"j","jpegs"},
36  {"n","name"},
37  {"f","frame"},
38  {"V","version"},
39  {0,0}
40 };
41
42 int args_callback_option(char*name,char*val)
43 {
44     if(!strcmp(name, "V")) {
45         printf("swfextract - part of %s %s\n", PACKAGE, VERSION);
46         exit(0);
47     } 
48     else if(!strcmp(name, "o")) {
49         destfilename = val;
50         return 1;
51     } 
52     else if(!strcmp(name, "i")) {
53         extractids = val;
54         if(extractname) {
55             fprintf(stderr, "You can only supply either name or id\n");
56             exit(1);
57         }
58         return 1;
59     } 
60     else if(!strcmp(name, "n")) {
61         extractname = val;
62         if(extractids) {
63             fprintf(stderr, "You can only supply either name or id\n");
64             exit(1);
65         }
66         return 1;
67     } 
68     else if(!strcmp(name, "v")) {
69         verbose ++;
70         return 0;
71     } 
72     else if(!strcmp(name, "j")) {
73         if(extractjpegids) {
74             fprintf(stderr, "Only one --jpegs argument is allowed. (Try to use a range, e.g. -j 1,2,3)\n");
75             exit(1);
76         }
77         extractjpegids = val;
78         return 1;
79     } 
80     else if(!strcmp(name, "f")) {
81         extractframes = val;
82         return 1;
83     }
84     else if(!strcmp(name, "w")) {
85         hollow = 1;
86         return 0;
87     }
88     else {
89         printf("Unknown option: -%s\n", name);
90         return 0;
91     }
92
93     return 0;
94 }
95 int args_callback_longoption(char*name,char*val)
96 {
97     return args_long2shortoption(options, name, val);
98 }
99 void args_callback_usage(char*name)
100 {    
101     printf("Usage: %s [-v] [-n name] [-ijf ids] file.swf\n", name);
102     printf("\t-v , --verbose\t\t\t Be more verbose\n");
103     printf("\t-o , --output filename\t\t set output filename\n");
104     printf("\t-n , --name name\t\t instance name of the object to extract\n");
105     printf("\t-i , --id IDs\t\t\t ID of the object to extract\n");
106     printf("\t-j , --jpeg IDs\t\t\t IDs of the jpeg pictures to extract\n");
107     printf("\t-f , --frame frames\t\t frame numbers to extract\n");
108     printf("\t-w , --hollow\t\t\t hollow mode: don't remove empty frames (use with -f)\n");
109     printf("\t-V , --version\t\t\t Print program version and exit\n");
110 }
111 int args_callback_command(char*name,char*val)
112 {
113     if(filename) {
114         fprintf(stderr, "Only one file allowed. You supplied at least two. (%s and %s)\n",
115                  filename, name);
116     }
117     filename = name;
118     return 0;
119 }
120
121 U8 mainr,maing,mainb;
122 /* 1 = used, not expanded,
123    3 = used, expanded
124    5 = wanted, not expanded
125    7 = wanted, expanded
126  */
127 char used[65536];
128 TAG*tags[65536];
129 int changed;
130 char * tagused;
131
132 void idcallback(void*data)
133 {
134     if(!(used[*(U16*)data]&1)) {
135         changed = 1;
136         used[*(U16*)data] |= 1;
137     }
138 }
139
140 void enumerateIDs(TAG*tag, void(*callback)(void*))
141 {
142     U8*data;
143     int len = tag->len;
144     if(tag->len>=64) {
145         len += 6;
146         data = (U8*)malloc(len);
147         *(U16*)data = (tag->id<<6)+63;
148         *(U32*)&data[2] = tag->len;
149         memcpy(&data[6], tag->data, tag->len);
150     } else {
151         len += 2;
152         data = (U8*)malloc(len);
153         *(U16*)data = (tag->id<<6)+tag->len;
154         memcpy(&data[2], tag->data, tag->len);
155     }
156     map_ids_mem(data, len, callback);
157 }
158
159 void extractTag(SWF*swf, char*filename)
160 {
161     SWF newswf;
162     TAG*desttag;
163     TAG*srctag;
164     RGBA rgb;
165     char sprite;
166     int f;
167     int t;
168     int tagnum;
169     int copy = 0;
170     memset(&newswf,0x00,sizeof(SWF));        // set global movie parameters
171
172     newswf.fileVersion    = swf->fileVersion;
173     newswf.frameRate      = swf->frameRate;
174     newswf.movieSize      = swf->movieSize;
175                 
176     newswf.firstTag = swf_InsertTag(NULL,ST_SETBACKGROUNDCOLOR);
177     desttag = newswf.firstTag;
178     rgb.r = mainr;
179     rgb.g = maing;
180     rgb.b = mainb;
181     swf_SetRGB(desttag,&rgb);
182
183     do {
184        changed = 0;
185        for(t=0;t<65536;t++) {
186            if(used[t] && !(used[t]&2)) {
187              if(tags[t]->id==ST_DEFINESPRITE) {
188                  TAG*tag = tags[t];
189                  while(tag->id != ST_END)
190                  {
191                      enumerateIDs(tag, idcallback);
192                      tag = tag->next;
193                  }
194              }
195              else 
196                enumerateIDs(tags[t], idcallback);
197              used[t] |= 2;
198            }
199        }
200     }
201     while(changed);
202
203     srctag = swf->firstTag;
204     tagnum = 0;
205     sprite = 0;
206     while(srctag && (srctag->id || sprite)) {
207         int reset = 0;
208         if(!sprite) {
209             copy = 0;
210         }
211         if(srctag->id == ST_END) {
212             sprite = 0;
213         }
214         if(srctag->id == ST_DEFINESPRITE)
215             sprite = 1;
216         if(swf_isDefiningTag(srctag)) {
217             int id = swf_GetDefineID(srctag);
218             if(used[id]) 
219                 copy = 1;
220         } else 
221         if (((srctag->id == ST_PLACEOBJECT ||
222               srctag->id == ST_PLACEOBJECT2 ||
223               srctag->id == ST_STARTSOUND) && (used[swf_GetPlaceID(srctag)]&4) ) ||
224               (swf_isPseudoDefiningTag(srctag) && used[swf_GetDefineID(srctag)]) ||
225               (tagused[tagnum])) 
226         {
227                 if(copy == 0)
228                     reset = 1;
229                 copy = 1;
230         } 
231         if(srctag->id == ST_REMOVEOBJECT) {
232             if(!used[swf_GetPlaceID(srctag)])
233                 copy = 0;
234         }
235
236         if(copy) {
237             TAG*ttag = (TAG*)malloc(sizeof(TAG));
238             desttag = swf_InsertTag(desttag, srctag->id);
239             desttag->len = desttag->memsize = srctag->len;
240             desttag->data = malloc(srctag->len);
241             memcpy(desttag->data, srctag->data, srctag->len);
242             if(reset)
243                 copy = 0;
244         }
245         
246         srctag = srctag->next;
247         tagnum ++;
248     }
249     if(!extractframes && !hollow)
250         desttag = swf_InsertTag(desttag,ST_SHOWFRAME);
251
252     desttag = swf_InsertTag(desttag,ST_END);
253     
254     f = open(filename, O_TRUNC|O_WRONLY|O_CREAT, 0644);
255     if FAILED(swf_WriteSWF(f,&newswf)) fprintf(stderr,"WriteSWF() failed.\n");
256     close(f);
257
258     swf_FreeTags(&newswf);                       // cleanup
259 }
260
261 void listObjects(SWF*swf)
262 {
263     TAG*tag;
264     char first;
265     int t;
266     int frame = 0;
267     char*names[] = {"Shapes","MovieClips","JPEGs","Sounds","Frames"};
268     printf("Objects in file %s:\n",filename);
269     for(t=0;t<5;t++) {
270         tag = swf->firstTag;
271         first = 1;
272         while(tag) {
273             char show = 0;
274             char text[80];
275             if(t == 0 &&
276                (tag->id == ST_DEFINESHAPE ||
277                 tag->id == ST_DEFINESHAPE2 ||
278                 tag->id == ST_DEFINESHAPE3)) {
279                 show = 1;
280                 sprintf(text,"%d", swf_GetDefineID(tag));
281             }
282
283             if(tag->id == ST_DEFINESPRITE) {
284                 if (t == 1)  {
285                     show = 1;
286                     sprintf(text,"%d", swf_GetDefineID(tag));
287                 }
288
289                 while(tag->id != ST_END)
290                     tag = tag->next;
291             }
292
293             if(t == 2 && (tag->id == ST_DEFINEBITS ||
294                 tag->id == ST_DEFINEBITSJPEG2 ||
295                 tag->id == ST_DEFINEBITSJPEG3)) {
296                 show = 1;
297                 sprintf(text,"%d", swf_GetDefineID(tag));
298             }
299
300             if(t == 3 && (tag->id == ST_DEFINESOUND)) {
301                 show = 1;
302                 sprintf(text,"%d", swf_GetDefineID(tag));
303             }
304             
305             if(t == 4 && (tag->id == ST_SHOWFRAME)) {
306                 show = 1;
307                 sprintf(text,"%d", frame);
308                 frame ++;
309             }
310
311             if(show) {
312                 if(!first)
313                     printf(", ");
314                 else
315                     printf("%s: ", names[t]);
316                 printf("%s", text);
317                 first = 0;
318             }
319             tag=tag->next;
320         }
321         if(!first)
322             printf("\n");
323     }
324 }
325
326 U8*jpegtables = 0;
327 int jpegtablessize;
328
329 void handlejpegtables(TAG*tag)
330 {
331     if(tag->id == ST_JPEGTABLES) {
332         jpegtables = tag->data;
333         jpegtablessize = tag->len;
334     }
335 }
336
337 FILE* save_fopen(char* name, char* mode)
338 {
339     FILE*fi = fopen(name, mode);
340     if(!fi) {
341         fprintf(stderr, "Error: Couldn't open %s\n", name);
342         exit(1);
343     }
344     return fi;
345 }
346
347 int findjpegboundary(U8*data, int len)
348 {
349     int t;
350     int pos=-1;
351     for(t=0;t<len;t++) {
352         if(data[t  ]==0xff &&
353            data[t+1]==0xd9 &&
354            data[t+2]==0xff &&
355            data[t+3]==0xd8) {
356             pos = t;
357         }
358     }
359     return pos;
360 }
361
362 /* extract jpeg data out of a tag */
363 void handlejpeg(TAG*tag)
364 {
365     char name[80];
366     FILE*fi;
367     sprintf(name, "pic%d.jpeg", *(U16*)tag->data);
368     /* swf jpeg images have two streams, which both start with ff d8 and
369        end with ff d9. The following code handles sorting the middle
370        <ff d9 ff d8> bytes out, so that one stream remains */
371     if(tag->id == ST_DEFINEBITS && tag->len>2 && jpegtables) {
372         fi = save_fopen(name, "wb");
373         fwrite(jpegtables, 1, jpegtablessize-2, fi); //don't write end tag (ff,d8)
374         fwrite(&tag->data[2+2], tag->len-2-2, 1, fi); //don't write start tag (ff,d9)
375         fclose(fi);
376     }
377     if(tag->id == ST_DEFINEBITSJPEG2 && tag->len>2) {
378         int end = tag->len;
379         int pos = findjpegboundary(&tag->data[2], tag->len-2);
380         if(pos<0)
381             return;
382         pos+=2;
383         fi = save_fopen(name, "wb");
384         fwrite(&tag->data[2], pos-2, 1, fi);
385         fwrite(&tag->data[pos+4], end-(pos+4), 1, fi);
386         fclose(fi);
387     }
388     if(tag->id == ST_DEFINEBITSJPEG3 && tag->len>6) {
389         U32 end = *(U32*)&tag->data[2]+6;
390         int pos = findjpegboundary(&tag->data[6], tag->len-6);
391         if(pos<0)
392             return;
393         pos+=6;
394         fi = save_fopen(name, "wb");
395         fwrite(&tag->data[6], pos-6, 1, fi);
396         fwrite(&tag->data[pos+4], end-(pos+4), 1, fi);
397         fclose(fi);
398     }
399 }
400
401 int main (int argc,char ** argv)
402
403     TAG*tag;
404     SWF swf;
405     int f;
406     int found = 0;
407     int frame = 0;
408     int tagnum = 0;
409     char depths[65536];
410     char listavailable = 0;
411     processargs(argc, argv);
412
413     if(!extractframes && !extractids && ! extractname && !extractjpegids)
414         listavailable = 1;
415
416     if(!filename)
417     {
418         fprintf(stderr, "You must supply a filename.\n");
419         return 1;
420     }
421     initLog(0,-1,0,0,-1, verbose);
422
423     f = open(filename,O_RDONLY);
424
425     if (f<0)
426     { 
427         perror("Couldn't open file: ");
428         exit(1);
429     }
430     if (swf_ReadSWF(f,&swf) < 0)
431     { 
432         fprintf(stderr, "%s is not a valid SWF file or contains errors.\n",filename);
433         close(f);
434         exit(1);
435     }
436     close(f);
437
438     if(listavailable) {
439         listObjects(&swf);
440         swf_FreeTags(&swf);
441         return 0;
442     }
443
444     tag = swf.firstTag;
445     tagnum = 0;
446     while(tag) {
447         tagnum ++;
448         tag = tag->next;
449     }
450
451     tagused = (char*)malloc(tagnum);
452     memset(tagused, 0, tagnum);
453     memset(used, 0, 65536);
454     memset(depths, 0, 65536);
455
456     tag = swf.firstTag;
457     tagnum = 0;
458     while(tag) {
459         if(swf_isAllowedSpriteTag(tag)) {
460             int write = 0;
461             if(extractframes && is_in_range(frame, extractframes)) {
462                 write = 1;
463                 if(tag->id == ST_PLACEOBJECT || tag->id == ST_PLACEOBJECT2) {
464                     depths[swf_GetDepth(tag)] = 1;
465                 }
466                 if(tag->id == ST_REMOVEOBJECT || tag->id == ST_REMOVEOBJECT2) {
467                     int depth = swf_GetDepth(tag);
468                     if(!depths[depth]) 
469                         write = 0;
470                     depths[swf_GetDepth(tag)] = 0;
471                 }
472             } else {
473                 if((tag->id == ST_REMOVEOBJECT || tag->id == ST_REMOVEOBJECT2) && 
474                     (depths[swf_GetDepth(tag)]) && hollow) {
475                     write = 1;
476                     depths[swf_GetDepth(tag)] = 0;
477                 }
478             }
479             if(write) {
480                 enumerateIDs(tag, idcallback);
481                 found = 1;
482                 tagused[tagnum] = 1;
483             }
484         }
485
486         if(tag->id == ST_JPEGTABLES)
487             handlejpegtables(tag);
488
489         if(swf_isDefiningTag(tag)) {
490             int id = swf_GetDefineID(tag);
491             tags[id] = tag;
492             if(extractids && is_in_range(id, extractids)) {
493                 used[id] = 5;
494                 found = 1;
495             }
496             if(extractjpegids && is_in_range(id, extractjpegids)) {
497                 handlejpeg(tag);
498             }
499         }
500         else if (tag->id == ST_SETBACKGROUNDCOLOR) {
501             mainr = tag->data[0];
502             maing = tag->data[1];
503             mainb = tag->data[2];
504         }
505         else if(tag->id == ST_PLACEOBJECT2) {
506             char*name = swf_GetName(tag);
507             if(name && extractname && !strcmp(name, extractname)) {
508                 int id = swf_GetPlaceID(tag); 
509                 used[id] = 5;
510                 found = 1;
511                 tagused[tagnum] = 1;
512                 depths[swf_GetDepth(tag)] = 1;
513             }
514         }
515         else if(tag->id == ST_SHOWFRAME) {
516             frame ++;
517             if(hollow) {
518                 tagused[tagnum] = 1;
519                 found = 1;
520             }
521         }
522         
523         if(tag->id == ST_DEFINESPRITE) {
524             while(tag->id != ST_END) { 
525                 tag = tag->next;
526                 tagnum ++;
527             }
528         }
529         tag = tag->next;
530         tagnum ++;
531     }
532     if (found)
533         extractTag(&swf, destfilename);
534
535     swf_FreeTags(&swf);
536     return 0;
537 }
538