minor fixes.
[swftools.git] / src / swfdump.c
1 /* swfdump.c
2    Shows the structure of a swf 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 "../config.h"
11
12 #ifdef HAVE_SYS_STAT_H
13 #include <sys/stat.h>
14 #else
15 #undef HAVE_STAT
16 #endif
17
18 #ifdef HAVE_SYS_TYPES_H
19 #include <sys/types.h>
20 #else
21 #undef HAVE_STAT
22 #endif
23
24 #include <unistd.h>
25 #include <stdio.h>
26 #include <fcntl.h>
27 #include <stdarg.h>
28 #include "../lib/rfxswf.h"
29 #include "../lib/args.h"
30
31 char * filename = 0;
32
33 /* idtab stores the ids which are defined in the file. This allows us
34    to detect errors in the file. (i.e. ids which are defined more than 
35    once */
36 char idtab[65536];
37 char * indent = "                ";
38
39 int action = 0;
40 int html = 0;
41 int xy = 0;
42 int showtext = 0;
43 int hex = 0;
44 int used = 0;
45
46 struct options_t options[] =
47 {
48  {"a","action"},
49  {"t","text"},
50  {"X","width"},
51  {"Y","height"},
52  {"r","rate"},
53  {"e","html"},
54  {"u","used"},
55  {"v","verbose"},
56  {"V","version"},
57  {"d","hex"},
58  {0,0}
59 };
60
61
62 int args_callback_option(char*name,char*val)
63 {
64     if(!strcmp(name, "V")) {
65         printf("swfdump - part of %s %s\n", PACKAGE, VERSION);
66         exit(0);
67     } 
68     else if(name[0]=='a') {
69         action = 1;
70         return 0;
71     }
72     else if(name[0]=='t') {
73         showtext = 1;
74         return 0;
75     }
76     else if(name[0]=='e') {
77         html = 1;
78         return 0;
79     }
80     else if(name[0]=='X') {
81         xy |= 1;
82         return 0;
83     }
84     else if(name[0]=='Y') {
85         xy |= 2;
86         return 0;
87     }
88     else if(name[0]=='r') {
89         xy |= 4;
90         return 0;
91     }
92     else if(name[0]=='d') {
93         hex = 1;
94         return 0;
95     }
96     else if(name[0]=='u') {
97         used = 1;
98         return 0;
99     }
100     else {
101         printf("Unknown option: -%s\n", name);
102     }
103
104     return 0;
105 }
106 int args_callback_longoption(char*name,char*val)
107 {
108     return args_long2shortoption(options, name, val);
109 }
110 void args_callback_usage(char*name)
111 {    
112     printf("Usage: %s [-at] file.swf\n", name);
113     printf("\t-h , --help\t\t Print help and exit\n");
114     printf("\t-e , --html\t\t Create a html embedding the file (simple, but useful)\n");
115     printf("\t-X , --width\t\t Prints out a string of the form \"-X width\"\n");
116     printf("\t-Y , --height\t\t Prints out a string of the form \"-Y height\"\n");
117     printf("\t-r , --rate\t\t Prints out a string of the form \"-r rate\"\n");
118     printf("\t-a , --action\t\t Disassemble action tags\n");
119     printf("\t-t , --text\t\t Show text data\n");
120     printf("\t-d , --hex\t\t Print hex output of tag data, too\n");
121     printf("\t-u , --used\t\t Show referred IDs for each Tag\n");
122     printf("\t-V , --version\t\t Print program version and exit\n");
123 }
124 int args_callback_command(char*name,char*val)
125 {
126     if(filename) {
127         fprintf(stderr, "Only one file allowed. You supplied at least two. (%s and %s)\n",
128                  filename, name);
129     }
130     filename = name;
131     return 0;
132 }
133
134 char* what;
135 char* testfunc(char*str)
136 {
137     printf("%s: %s\n", what, str);
138     return 0;
139 }
140
141 void dumpButton2Actions(TAG*tag, char*prefix)
142 {
143     U32 oldTagPos;
144     U32 offsetpos;
145     U32 condition;
146
147     oldTagPos = swf_GetTagPos(tag);
148
149     // scan DefineButton2 Record
150     
151     swf_GetU16(tag);          // Character ID
152     swf_GetU8(tag);           // Flags;
153
154     offsetpos = swf_GetTagPos(tag);  // first offset
155     swf_GetU16(tag);
156
157     while (swf_GetU8(tag))      // state  -> parse ButtonRecord
158     { swf_GetU16(tag);          // id
159       swf_GetU16(tag);          // layer
160       swf_GetMatrix(tag,NULL);  // matrix
161       swf_GetCXForm(tag,NULL,1);  // cxform
162     }
163
164     while(offsetpos)
165     { U8 a;
166       ActionTAG*actions;
167
168       if(tag->pos >= tag->len)
169           break;
170         
171       offsetpos = swf_GetU16(tag);
172       condition = swf_GetU16(tag);                // condition
173       
174       actions = swf_ActionGet(tag);
175       printf("%s condition %04x\n", prefix, condition);
176       swf_DumpActions(actions, prefix);
177     }
178     
179     swf_SetTagPos(tag,oldTagPos);
180     return;
181 }
182
183 void dumpButtonActions(TAG*tag, char*prefix)
184 {
185     ActionTAG*actions;
186     swf_GetU16(tag); // id
187     while (swf_GetU8(tag))      // state  -> parse ButtonRecord
188     { swf_GetU16(tag);          // id
189       swf_GetU16(tag);          // layer
190       swf_GetMatrix(tag,NULL);  // matrix
191     }
192     actions = swf_ActionGet(tag);
193     swf_DumpActions(actions, prefix);
194 }
195
196 #define ET_HASTEXT 32768
197 #define ET_WORDWRAP 16384
198 #define ET_MULTILINE 8192
199 #define ET_PASSWORD 4096
200 #define ET_READONLY 2048
201 #define ET_HASTEXTCOLOR 1024
202 #define ET_HASMAXLENGTH 512
203 #define ET_HASFONT 256
204 #define ET_X3 128
205 #define ET_X2 64
206 #define ET_HASLAYOUT 32
207 #define ET_NOSELECT 16
208 #define ET_BORDER 8
209 #define ET_X1 4
210 #define ET_X0 2
211 #define ET_USEOUTLINES 1
212
213 SWF swf;
214 int fontnum = 0;
215 SWFFONT**fonts;
216
217 void textcallback(int*glyphs, int nr, int fontid) 
218 {
219     int font=-1,t;
220     printf("                <%2d glyphs in font %2d> ",nr, fontid);
221     for(t=0;t<fontnum;t++)
222     {
223         if(fonts[t]->id == fontid) {
224             font = t;
225             break;
226         }
227     }
228
229     for(t=0;t<nr;t++)
230     {
231         unsigned char a; 
232         if(font>=0) {
233             if(glyphs[t] >= fonts[font]->numchars)
234                 continue;
235             a = fonts[font]->glyph2ascii[glyphs[t]];
236         } else {
237             a = glyphs[t];
238         }
239         if(a>=32)
240             printf("%c", a);
241         else
242             printf("\\x%x", (int)a);
243     }
244     printf("\n");
245 }
246
247 void handleText(TAG*tag) 
248 {
249   printf("\n");
250   swf_FontExtract_DefineTextCallback(-1,0,tag,4, textcallback);
251 }
252             
253 void handleDefineBits(TAG*tag)
254 {
255     U16 id;
256     U8 mode;
257     U16 width,height;
258     int bpp;
259     id = swf_GetU16(tag);
260     mode = swf_GetU8(tag);
261     width = swf_GetU16(tag);
262     height = swf_GetU16(tag);
263     printf(" image %dx%d",width,height);
264     if(mode == 3) printf(" (8 bpp)");
265     else if(mode == 4) printf(" (16 bpp)");
266     else if(mode == 5) printf(" (32 bpp)");
267     else printf(" (? bpp)");
268 }
269
270 void handleEditText(TAG*tag)
271 {
272     U16 id ;
273     U16 flags;
274     int t;
275     id = swf_GetU16(tag);
276     swf_GetRect(tag,0);
277     //swf_ResetReadBits(tag);
278     if (tag->readBit)  
279     { tag->pos++; 
280       tag->readBit = 0; 
281     }
282     flags = swf_GetBits(tag,16);
283     if(flags & ET_HASFONT) {
284         swf_GetU16(tag); //font
285         swf_GetU16(tag); //fontheight
286     }
287     if(flags & ET_HASTEXTCOLOR) {
288         swf_GetU8(tag); //rgba
289         swf_GetU8(tag);
290         swf_GetU8(tag);
291         swf_GetU8(tag);
292     }
293     if(flags & ET_HASMAXLENGTH) {
294         swf_GetU16(tag); //maxlength
295     }
296     if(flags & ET_HASLAYOUT) {
297         swf_GetU8(tag); //align
298         swf_GetU16(tag); //left margin
299         swf_GetU16(tag); //right margin
300         swf_GetU16(tag); //indent
301         swf_GetU16(tag); //leading
302     }
303     printf(" variable \"%s\"", &tag->data[tag->pos]);
304
305     if(flags & (ET_X1 | ET_X2 | ET_X3 | ET_X0))
306     {
307         printf(" undefined flags: %d%d%d%d", 
308                 (flags&ET_X0?1:0),
309                 (flags&ET_X1?1:0),
310                 (flags&ET_X2?1:0),
311                 (flags&ET_X3?1:0));
312     }
313     
314     while(tag->data[tag->pos++]);
315     if(flags & ET_HASTEXT)
316    //  printf(" text \"%s\"\n", &tag->data[tag->pos])
317         ;
318 }
319 void printhandlerflags(U16 handlerflags) 
320 {
321     if(handlerflags&1) printf("[on load]");
322     if(handlerflags&2) printf("[enter frame]");
323     if(handlerflags&4) printf("[unload]");
324     if(handlerflags&8) printf("[mouse move]");
325     if(handlerflags&16) printf("[mouse down]");
326     if(handlerflags&32) printf("[mouse up]");
327     if(handlerflags&64) printf("[key down]");
328     if(handlerflags&128) printf("[key up]");
329     if(handlerflags&256) printf("[data]");
330     if(handlerflags&0xfe00) printf("[???]");
331 }
332 void handlePlaceObject2(TAG*tag, char*prefix)
333 {
334     U8 flags = swf_GetU8(tag);
335     swf_GetU16(tag); //depth
336     //flags&1: move
337     if(flags&2) swf_GetU16(tag); //id
338     if(flags&4) swf_GetMatrix(tag,0);
339     if(flags&8) swf_GetCXForm(tag,0,1);
340     if(flags&16) swf_GetU16(tag); //ratio
341     if(flags&32) { while(swf_GetU8(tag)); }
342     if(flags&64) swf_GetU16(tag); //clip
343     if(flags&128) {
344       if (action) {
345         U16 unknown;
346         U32 globalflags;
347         U32 handlerflags;
348         char is32 = 0;
349         printf("\n");
350         unknown = swf_GetU16(tag);
351         globalflags = swf_GetU16(tag);
352         if(unknown) {
353             printf("Unknown parameter field not zero: %04x\n", unknown);
354             return;
355         }
356         printf("global flags: %04x\n", globalflags);
357         handlerflags = swf_GetU16(tag);
358         if(!handlerflags) {
359             handlerflags = swf_GetU32(tag);
360             is32 = 1;
361         }
362         while(handlerflags)  {
363             int length;
364             int t;
365             ActionTAG*a;
366
367             globalflags &= ~handlerflags;
368             printf("%s flags %08x ",prefix, handlerflags);
369             printhandlerflags(handlerflags);
370             length = swf_GetU32(tag);
371             printf(", %d bytes actioncode\n",length);
372             a = swf_ActionGet(tag);
373             swf_DumpActions(a,prefix);
374             swf_ActionFree(a);
375
376             handlerflags = is32?swf_GetU32(tag):swf_GetU16(tag);
377         }
378         if(globalflags) // should go to sterr.
379             printf("ERROR: unsatisfied handlerflags: %02x\n", globalflags);
380     } else {
381       printf(" has action code\n");
382     }
383     } else printf("\n");
384 }
385     
386 void fontcallback1(U16 id,U8 * name)
387 { fontnum++;
388 }
389
390 void fontcallback2(U16 id,U8 * name)
391
392   swf_FontExtract(&swf,id,&fonts[fontnum]);
393   fontnum++;
394 }
395
396 void dumperror(const char* format, ...)
397 {
398     char buf[1024];
399     va_list arglist;
400
401     va_start(arglist, format);
402     vsprintf(buf, format, arglist);
403     va_end(arglist);
404
405     if(!html && !xy)
406         printf("==== Error: %s ====\n", buf);
407 }
408
409 int main (int argc,char ** argv)
410
411     TAG*tag;
412 #ifdef HAVE_STAT
413     struct stat statbuf;
414 #endif
415     int f;
416     int xsize,ysize;
417     char issprite = 0; // are we inside a sprite definition?
418     int spriteframe = 0;
419     int mainframe=0;
420     char* spriteframelabel = 0;
421     char* framelabel = 0;
422     char prefix[128];
423     int filesize = 0;
424     prefix[0] = 0;
425     memset(idtab,0,65536);
426
427     processargs(argc, argv);
428
429     if(!filename)
430     {
431         fprintf(stderr, "You must supply a filename.\n");
432         return 1;
433     }
434
435     f = open(filename,O_RDONLY);
436
437     if (f<0)
438     { 
439         perror("Couldn't open file: ");
440         exit(1);
441     }
442     if FAILED(swf_ReadSWF(f,&swf))
443     { 
444         fprintf(stderr, "%s is not a valid SWF file or contains errors.\n",filename);
445         close(f);
446         exit(1);
447     }
448
449 #ifdef HAVE_STAT
450     fstat(f, &statbuf);
451     if(statbuf.st_size != swf.fileSize && !swf.compressed)
452         dumperror("Real Filesize (%d) doesn't match header Filesize (%d)",
453                 statbuf.st_size, swf.fileSize);
454     filesize = statbuf.st_size;
455 #endif
456
457     close(f);
458
459     xsize = (swf.movieSize.xmax-swf.movieSize.xmin)/20;
460     ysize = (swf.movieSize.ymax-swf.movieSize.ymin)/20;
461     if(xy)
462     {
463         if(xy&1)
464         printf("-X %d", xsize);
465
466         if((xy&1) && (xy&6))
467         printf(" ");
468
469         if(xy&2)
470         printf("-Y %d", ysize);
471         
472         if((xy&3) && (xy&4))
473         printf(" ");
474
475         if(xy&4)
476         printf("-r %d", swf.frameRate*100/256);
477         
478         printf("\n");
479         return 0;
480     }
481     if(html)
482     {
483         char*fileversions[] = {"","1,0,0,0", "2,0,0,0","3,0,0,0","4,0,0,0",
484                                "5,0,0,0","6,0,23,0","7,0,0,0","8,0,0,0"};
485         if(swf.fileVersion>8) {
486             fprintf(stderr, "Fileversion>8\n");
487             exit(1);
488         }
489         printf("<OBJECT CLASSID=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\"\n"
490                " WIDTH=\"%d\"\n"
491                //" BGCOLOR=#ffffffff\n"?
492                " HEIGHT=\"%d\"\n"
493                //http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,23,0?
494                " CODEBASE=\"http://active.macromedia.com/flash5/cabs/swflash.cab#version=%s\">\n"
495                "  <PARAM NAME=\"MOVIE\" VALUE=\"%s\">\n"
496                "  <PARAM NAME=\"PLAY\" VALUE=\"true\">\n" 
497                "  <PARAM NAME=\"LOOP\" VALUE=\"true\">\n"
498                "  <PARAM NAME=\"QUALITY\" VALUE=\"high\">\n"
499                "  <EMBED SRC=\"%s\" WIDTH=\"%d\" HEIGHT=\"%d\"\n" //bgcolor=#ffffff?
500                "   PLAY=\"true\" ALIGN=\"\" LOOP=\"true\" QUALITY=\"high\"\n"
501                "   TYPE=\"application/x-shockwave-flash\"\n"
502                "   PLUGINSPAGE=\"http://www.macromedia.com/go/getflashplayer\">\n"
503                "  </EMBED>\n" 
504                "</OBJECT>\n", xsize, ysize, fileversions[swf.fileVersion], 
505                               filename, filename, xsize, ysize);
506         return 0;
507     } 
508     printf("[HEADER]        File version: %d\n", swf.fileVersion);
509     if(swf.compressed) {
510         printf("[HEADER]        File is zlib compressed.");
511         if(filesize && swf.fileSize)
512             printf(" Ratio: %02d%%\n", filesize*100/(swf.fileSize));
513         else
514             printf("\n");
515     }
516     printf("[HEADER]        File size: %ld%s\n", swf.fileSize, swf.compressed?" (Depacked)":"");
517     printf("[HEADER]        Frame rate: %f\n",swf.frameRate/256.0);
518     printf("[HEADER]        Frame count: %d\n",swf.frameCount);
519     printf("[HEADER]        Movie width: %.3f\n",(swf.movieSize.xmax-swf.movieSize.xmin)/20.0);
520     printf("[HEADER]        Movie height: %.3f\n",(swf.movieSize.ymax-swf.movieSize.ymin)/20.0);
521
522     tag = swf.firstTag;
523    
524     if(showtext) {
525         fontnum = 0;
526         swf_FontEnumerate(&swf,&fontcallback1);
527         fonts = (SWFFONT**)malloc(fontnum*sizeof(SWFFONT*));
528         fontnum = 0;
529         swf_FontEnumerate(&swf,&fontcallback2);
530     }
531
532     while(tag) {
533         char*name = swf_TagGetName(tag);
534         char myprefix[128];
535         if(!name) {
536             dumperror("Unknown tag:0x%03x", tag->id);
537             tag = tag->next;
538             continue;
539         }
540         printf("[%03x] %9ld %s%s", tag->id, tag->len, prefix, swf_TagGetName(tag));
541         
542         if(tag->id == ST_FREECHARACTER) {
543             U16 id = swf_GetU16(tag);
544             idtab[id] = 0;
545         }
546
547         if(swf_isDefiningTag(tag)) {
548             U16 id = swf_GetDefineID(tag);
549             printf(" defines id %04d", id);
550             if(idtab[id])
551                 dumperror("Id %04d is defined more than once.", id);
552             idtab[id] = 1;
553         }
554         else if(swf_isPseudoDefiningTag(tag)) {
555             U16 id = swf_GetDefineID(tag);
556             printf(" adds information to id %04d", id);
557             if(!idtab[id])
558                 dumperror("Id %04d is not yet defined.\n", id);
559         }
560         else if(tag->id == ST_PLACEOBJECT) {
561             printf(" places id %04d at depth %04x", swf_GetPlaceID(tag), swf_GetDepth(tag));
562             if(swf_GetName(tag))
563                 printf(" name \"%s\"",swf_GetName(tag));
564         }
565         else if(tag->id == ST_PLACEOBJECT2) {
566             if(tag->data[0]&1)
567                 printf(" moves");
568             else
569                 printf(" places");
570             
571             if(tag->data[0]&2)
572                 printf(" id %04d",swf_GetPlaceID(tag));
573             else
574                 printf(" object");
575
576             printf(" at depth %04d", swf_GetDepth(tag));
577             if(swf_GetName(tag))
578                 printf(" name \"%s\"",swf_GetName(tag));
579         }
580         else if(tag->id == ST_REMOVEOBJECT) {
581             printf(" removes id %04d from depth %04d", swf_GetPlaceID(tag), swf_GetDepth(tag));
582         }
583         else if(tag->id == ST_REMOVEOBJECT2) {
584             printf(" removes object from depth %04d", swf_GetDepth(tag));
585         }
586         else if(tag->id == ST_STARTSOUND) {
587             printf(" starts id %04d", swf_GetPlaceID(tag));
588         }
589         else if(tag->id == ST_FRAMELABEL) {
590             int l = strlen(tag->data);
591             printf(" \"%s\"", tag->data);
592             if(l < tag->len-1) {
593                 printf(" has %d extra bytes", tag->len-1-l);
594                 if(tag ->len-1-l == 1 && tag->data[tag->len-1] == 1)
595                     printf(" (ANCHOR)");
596             }
597             if((framelabel && !issprite) ||
598                (spriteframelabel && issprite)) {
599                 dumperror("Frame %d has more than one label", 
600                         issprite?spriteframe:mainframe);
601             }
602             if(issprite) spriteframelabel = tag->data;
603             else framelabel = tag->data;
604         }
605         else if(tag->id == ST_SHOWFRAME) {
606             char*label = issprite?spriteframelabel:framelabel;
607             int frame = issprite?spriteframe:mainframe;
608             int nframe = frame;
609             if(!label) {
610                 while(tag->next && tag->next->id == ST_SHOWFRAME && tag->next->len == 0) {
611                     tag = tag->next;
612                     if(issprite) spriteframe++;
613                     else mainframe++;
614                     nframe++;
615                 }
616             }
617             if(nframe == frame)
618                 printf(" %d", frame);
619             else
620                 printf(" %d-%d", frame, nframe);
621             if(label)
622                 printf(" (label \"%s\")", label);
623             if(issprite) {spriteframe++; spriteframelabel = 0;}
624             if(!issprite) {mainframe++; framelabel = 0;}
625         }
626
627         if(tag->id == ST_DEFINEBITSLOSSLESS ||
628            tag->id == ST_DEFINEBITSLOSSLESS2) {
629             handleDefineBits(tag);
630             printf("\n");
631         }
632         else if(tag->id == ST_DEFINEEDITTEXT) {
633             handleEditText(tag);
634             printf("\n");
635         }
636         else if(tag->id == ST_DEFINETEXT || tag->id == ST_DEFINETEXT2) {
637             if(showtext)
638                 handleText(tag);
639             else
640                 printf("\n");
641         }
642         else if(tag->id == ST_PLACEOBJECT2) {
643         }
644         else {
645             printf("\n");
646         }
647         
648         sprintf(myprefix, "                %s", prefix);
649
650         if(tag->id == ST_DEFINESPRITE) {
651             sprintf(prefix, "         ");
652             if(issprite) {
653                 dumperror("Sprite definition inside a sprite definition");
654             }
655             issprite = 1;
656             spriteframe = 0;
657             spriteframelabel = 0;
658         }
659         else if(tag->id == ST_END) {
660             *prefix = 0;
661             issprite = 0;
662             spriteframelabel = 0;
663             if(tag->len)
664                 dumperror("End Tag not empty");
665         }
666         else if(tag->id == ST_DOACTION && action) {
667             ActionTAG*actions;
668             actions = swf_ActionGet(tag);
669             swf_DumpActions(actions, myprefix);
670         }
671         else if(tag->id == ST_DEFINEBUTTON && action) {
672             dumpButtonActions(tag, myprefix);
673         }
674         else if(tag->id == ST_DEFINEBUTTON2 && action) {
675             dumpButton2Actions(tag, myprefix);
676         }
677         else if(tag->id == ST_PLACEOBJECT2) {
678             if((*(U8*)tag->data)&0x80)
679                 handlePlaceObject2(tag, myprefix);
680             else
681                 printf("\n");
682         }
683
684         if(tag->len && used) {
685             int num = swf_GetNumUsedIDs(tag);
686             int* used;
687             int t;
688             if(num) {
689                 used = (int*)malloc(sizeof(int)*num);
690                 swf_GetUsedIDs(tag, used);
691                 printf("%s%suses IDs: ", indent, prefix);
692                 for(t=0;t<num;t++) {
693                     tag->pos = used[t];
694                     printf("%d%s", swf_GetU16(tag), t<num-1?", ":"");
695                 }
696                 printf("\n");
697             }
698         }
699
700         if(tag->len && hex) {
701             int t;
702             printf("                %s-=> ",prefix);
703             for(t=0;t<tag->len;t++) {
704                 printf("%02x ", tag->data[t]);
705                 if((t && ((t&15)==15)) || (t==tag->len-1))
706                 {
707                     if(t==tag->len-1)
708                         printf("\n");
709                     else
710                         printf("\n                %s-=> ",prefix);
711                 }
712             }
713         }
714         tag = tag->next;
715         fflush(stdout);
716     }
717
718     swf_FreeTags(&swf);
719     return 0;
720 }
721
722