* bugfixes
[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 handleEditText(TAG*tag)
254 {
255     U16 id ;
256     U16 flags;
257     int t;
258     id = swf_GetU16(tag);
259     swf_GetRect(tag,0);
260     //swf_ResetReadBits(tag);
261     if (tag->readBit)  
262     { tag->pos++; 
263       tag->readBit = 0; 
264     }
265     flags = swf_GetBits(tag,16);
266     if(flags & ET_HASFONT) {
267         swf_GetU16(tag); //font
268         swf_GetU16(tag); //fontheight
269     }
270     if(flags & ET_HASTEXTCOLOR) {
271         swf_GetU8(tag); //rgba
272         swf_GetU8(tag);
273         swf_GetU8(tag);
274         swf_GetU8(tag);
275     }
276     if(flags & ET_HASMAXLENGTH) {
277         swf_GetU16(tag); //maxlength
278     }
279     if(flags & ET_HASLAYOUT) {
280         swf_GetU8(tag); //align
281         swf_GetU16(tag); //left margin
282         swf_GetU16(tag); //right margin
283         swf_GetU16(tag); //indent
284         swf_GetU16(tag); //leading
285     }
286     printf(" variable \"%s\"", &tag->data[tag->pos]);
287
288     if(flags & (ET_X1 | ET_X2 | ET_X3 | ET_X0))
289     {
290         printf(" undefined flags: %d%d%d%d", 
291                 (flags&ET_X0?1:0),
292                 (flags&ET_X1?1:0),
293                 (flags&ET_X2?1:0),
294                 (flags&ET_X3?1:0));
295     }
296     
297     while(tag->data[tag->pos++]);
298     if(flags & ET_HASTEXT)
299    //  printf(" text \"%s\"\n", &tag->data[tag->pos])
300         ;
301 }
302 void printhandlerflags(U16 handlerflags) 
303 {
304     if(handlerflags&1) printf("[on load]");
305     if(handlerflags&2) printf("[enter frame]");
306     if(handlerflags&4) printf("[unload]");
307     if(handlerflags&8) printf("[mouse move]");
308     if(handlerflags&16) printf("[mouse down]");
309     if(handlerflags&32) printf("[mouse up]");
310     if(handlerflags&64) printf("[key down]");
311     if(handlerflags&128) printf("[key up]");
312     if(handlerflags&256) printf("[data]");
313     if(handlerflags&0xfe00) printf("[???]");
314 }
315 void handlePlaceObject2(TAG*tag, char*prefix)
316 {
317     U8 flags = swf_GetU8(tag);
318     swf_GetU16(tag); //depth
319     //flags&1: move
320     if(flags&2) swf_GetU16(tag); //id
321     if(flags&4) swf_GetMatrix(tag,0);
322     if(flags&8) swf_GetCXForm(tag,0,1);
323     if(flags&16) swf_GetU16(tag); //ratio
324     if(flags&32) { while(swf_GetU8(tag)); }
325     if(flags&64) swf_GetU16(tag); //clip
326     if(flags&128) {
327       if (action) {
328         U16 unknown;
329         U32 globalflags;
330         U32 handlerflags;
331         char is32 = 0;
332         printf("\n");
333         unknown = swf_GetU16(tag);
334         globalflags = swf_GetU16(tag);
335         if(unknown) {
336             printf("Unknown parameter field not zero: %04x\n", unknown);
337             return;
338         }
339         printf("global flags: %04x\n", globalflags);
340         handlerflags = swf_GetU16(tag);
341         if(!handlerflags) {
342             handlerflags = swf_GetU32(tag);
343             is32 = 1;
344         }
345         while(handlerflags)  {
346             int length;
347             int t;
348             ActionTAG*a;
349
350             globalflags &= ~handlerflags;
351             printf("%s flags %08x ",prefix, handlerflags);
352             printhandlerflags(handlerflags);
353             length = swf_GetU32(tag);
354             printf(", %d bytes actioncode\n",length);
355             a = swf_ActionGet(tag);
356             swf_DumpActions(a,prefix);
357             swf_ActionFree(a);
358
359             handlerflags = is32?swf_GetU32(tag):swf_GetU16(tag);
360         }
361         if(globalflags) // should go to sterr.
362             printf("ERROR: unsatisfied handlerflags: %02x\n", globalflags);
363     } else {
364       printf(" has action code\n");
365     }
366     } else printf("\n");
367 }
368     
369 void fontcallback1(U16 id,U8 * name)
370 { fontnum++;
371 }
372
373 void fontcallback2(U16 id,U8 * name)
374
375   swf_FontExtract(&swf,id,&fonts[fontnum]);
376   fontnum++;
377 }
378
379 void dumperror(const char* format, ...)
380 {
381     char buf[1024];
382     va_list arglist;
383
384     va_start(arglist, format);
385     vsprintf(buf, format, arglist);
386     va_end(arglist);
387
388     printf("==== Error: %s ====\n", buf);
389 }
390
391 int main (int argc,char ** argv)
392
393     TAG*tag;
394 #ifdef HAVE_STAT
395     struct stat statbuf;
396 #endif
397     int f;
398     int xsize,ysize;
399     char issprite = 0; // are we inside a sprite definition?
400     int spriteframe = 0;
401     int mainframe=0;
402     char* spriteframelabel = 0;
403     char* framelabel = 0;
404     char prefix[128];
405     int filesize = 0;
406     prefix[0] = 0;
407     memset(idtab,0,65536);
408
409     processargs(argc, argv);
410
411     if(!filename)
412     {
413         fprintf(stderr, "You must supply a filename.\n");
414         return 1;
415     }
416
417     f = open(filename,O_RDONLY);
418
419     if (f<0)
420     { 
421         perror("Couldn't open file: ");
422         exit(1);
423     }
424     if FAILED(swf_ReadSWF(f,&swf))
425     { 
426         fprintf(stderr, "%s is not a valid SWF file or contains errors.\n",filename);
427         close(f);
428         exit(1);
429     }
430
431 #ifdef HAVE_STAT
432     fstat(f, &statbuf);
433     if(statbuf.st_size != swf.fileSize && !swf.compressed)
434         dumperror("Real Filesize (%d) doesn't match header Filesize (%d)",
435                 statbuf.st_size, swf.fileSize);
436     filesize = statbuf.st_size;
437 #endif
438
439     close(f);
440
441     xsize = (swf.movieSize.xmax-swf.movieSize.xmin)/20;
442     ysize = (swf.movieSize.ymax-swf.movieSize.ymin)/20;
443     if(xy)
444     {
445         if(xy&1)
446         printf("-X %d", xsize);
447
448         if((xy&1) && (xy&6))
449         printf(" ");
450
451         if(xy&2)
452         printf("-Y %d", ysize);
453         
454         if((xy&3) && (xy&4))
455         printf(" ");
456
457         if(xy&4)
458         printf("-r %d", swf.frameRate*100/256);
459         
460         printf("\n");
461         return 0;
462     }
463     if(html)
464     {
465         char*fileversions[] = {"","1,0,0,0", "2,0,0,0","3,0,0,0","4,0,0,0",
466                                "5,0,0,0","6,0,23,0","7,0,0,0","8,0,0,0"};
467         if(swf.fileVersion>8) {
468             fprintf(stderr, "Fileversion>8\n");
469             exit(1);
470         }
471         printf("<OBJECT CLASSID=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\"\n"
472                " WIDTH=\"%d\"\n"
473                //" BGCOLOR=#ffffffff\n"
474                " HEIGHT=\"%d\"\n"
475                " CODEBASE=\"http://active.macromedia.com/flash5/cabs/swflash.cab#version=%s\">\n"
476                "  <PARAM NAME=\"MOVIE\" VALUE=\"%s\">\n"
477                "  <PARAM NAME=\"PLAY\" VALUE=\"true\">\n" 
478                "  <PARAM NAME=\"LOOP\" VALUE=\"true\">\n"
479                "  <PARAM NAME=\"QUALITY\" VALUE=\"high\">\n"
480                "  <EMBED SRC=\"%s\" WIDTH=\"%d\" HEIGHT=\"%d\"\n" //bgcolor=#ffffff
481                "   PLAY=\"true\" ALIGN=\"\" LOOP=\"true\" QUALITY=\"high\"\n"
482                "   TYPE=\"application/x-shockwave-flash\"\n"
483                "   PLUGINSPAGE=\"http://www.macromedia.com/go/getflashplayer\">\n"
484                "  </EMBED>\n" 
485                "</OBJECT>\n", xsize, ysize, fileversions[swf.fileVersion], 
486                               filename, filename, xsize, ysize);
487         return 0;
488     } 
489     printf("[HEADER]        File version: %d\n", swf.fileVersion);
490     if(swf.compressed) {
491         printf("[HEADER]        File is zlib compressed.");
492         if(filesize && swf.fileSize)
493             printf(" Ratio: %02d%%\n", filesize*100/(swf.fileSize));
494         else
495             printf("\n");
496     }
497     printf("[HEADER]        File size: %ld%s\n", swf.fileSize, swf.compressed?" (Depacked)":"");
498     printf("[HEADER]        Frame rate: %f\n",swf.frameRate/256.0);
499     printf("[HEADER]        Frame count: %d\n",swf.frameCount);
500     printf("[HEADER]        Movie width: %.3f\n",(swf.movieSize.xmax-swf.movieSize.xmin)/20.0);
501     printf("[HEADER]        Movie height: %.3f\n",(swf.movieSize.ymax-swf.movieSize.ymin)/20.0);
502
503     tag = swf.firstTag;
504    
505     if(showtext) {
506         fontnum = 0;
507         swf_FontEnumerate(&swf,&fontcallback1);
508         fonts = (SWFFONT**)malloc(fontnum*sizeof(SWFFONT*));
509         fontnum = 0;
510         swf_FontEnumerate(&swf,&fontcallback2);
511     }
512
513     while(tag) {
514         char*name = swf_TagGetName(tag);
515         char myprefix[128];
516         if(!name) {
517             dumperror("Unknown tag:0x%03x", tag->id);
518             tag = tag->next;
519             continue;
520         }
521         printf("[%03x] %9ld %s%s", tag->id, tag->len, prefix, swf_TagGetName(tag));
522         
523         if(tag->id == ST_FREECHARACTER) {
524             U16 id = swf_GetU16(tag);
525             idtab[id] = 0;
526         }
527
528         if(swf_isDefiningTag(tag)) {
529             U16 id = swf_GetDefineID(tag);
530             printf(" defines id %04d", id);
531             if(idtab[id])
532                 dumperror("Id %04d is defined more than once.", id);
533             idtab[id] = 1;
534         }
535         else if(swf_isPseudoDefiningTag(tag)) {
536             U16 id = swf_GetDefineID(tag);
537             printf(" adds information to id %04d", id);
538             if(!idtab[id])
539                 dumperror("Id %04d is not yet defined.\n", id);
540         }
541         else if(tag->id == ST_PLACEOBJECT) {
542             printf(" places id %04d at depth %04x", swf_GetPlaceID(tag), swf_GetDepth(tag));
543             if(swf_GetName(tag))
544                 printf(" name \"%s\"",swf_GetName(tag));
545         }
546         else if(tag->id == ST_PLACEOBJECT2) {
547             if(tag->data[0]&1)
548                 printf(" moves");
549             else
550                 printf(" places");
551             
552             if(tag->data[0]&2)
553                 printf(" id %04d",swf_GetPlaceID(tag));
554             else
555                 printf(" object");
556
557             printf(" at depth %04d", swf_GetDepth(tag));
558             if(swf_GetName(tag))
559                 printf(" name \"%s\"",swf_GetName(tag));
560         }
561         else if(tag->id == ST_REMOVEOBJECT) {
562             printf(" removes id %04d from depth %04d", swf_GetPlaceID(tag), swf_GetDepth(tag));
563         }
564         else if(tag->id == ST_REMOVEOBJECT2) {
565             printf(" removes object from depth %04d", swf_GetDepth(tag));
566         }
567         else if(tag->id == ST_STARTSOUND) {
568             printf(" starts id %04d", swf_GetPlaceID(tag));
569         }
570         else if(tag->id == ST_FRAMELABEL) {
571             int l = strlen(tag->data);
572             printf(" \"%s\"", tag->data);
573             if(l < tag->len-1) {
574                 printf(" has %d extra bytes", tag->len-1-l);
575                 if(tag ->len-1-l == 1 && tag->data[tag->len-1] == 1)
576                     printf(" (ANCHOR)");
577             }
578             if((framelabel && !issprite) ||
579                (spriteframelabel && issprite)) {
580                 dumperror("Frame %d has more than one label", 
581                         issprite?spriteframe:mainframe);
582             }
583             if(issprite) spriteframelabel = tag->data;
584             else framelabel = tag->data;
585         }
586         else if(tag->id == ST_SHOWFRAME) {
587             char*label = issprite?spriteframelabel:framelabel;
588             int frame = issprite?spriteframe:mainframe;
589             int nframe = frame;
590             if(!label) {
591                 while(tag->next && tag->next->id == ST_SHOWFRAME && tag->next->len == 0) {
592                     tag = tag->next;
593                     if(issprite) spriteframe++;
594                     else mainframe++;
595                     nframe++;
596                 }
597             }
598             if(nframe == frame)
599                 printf(" %d", frame);
600             else
601                 printf(" %d-%d", frame, nframe);
602             if(label)
603                 printf(" (label \"%s\")", label);
604             if(issprite) {spriteframe++; spriteframelabel = 0;}
605             if(!issprite) {mainframe++; framelabel = 0;}
606         }
607
608         if(tag->id == ST_DEFINEEDITTEXT) {
609             handleEditText(tag);
610             printf("\n");
611         }
612         else if(tag->id == ST_DEFINETEXT || tag->id == ST_DEFINETEXT2) {
613             if(showtext)
614                 handleText(tag);
615             else
616                 printf("\n");
617         }
618         else if(tag->id == ST_PLACEOBJECT2) {
619         }
620         else {
621             printf("\n");
622         }
623         
624         sprintf(myprefix, "                %s", prefix);
625
626         if(tag->id == ST_DEFINESPRITE) {
627             sprintf(prefix, "         ");
628             if(issprite) {
629                 dumperror("Sprite definition inside a sprite definition");
630             }
631             issprite = 1;
632             spriteframe = 0;
633             spriteframelabel = 0;
634         }
635         else if(tag->id == ST_END) {
636             *prefix = 0;
637             issprite = 0;
638             spriteframelabel = 0;
639             if(tag->len)
640                 dumperror("End Tag not empty");
641         }
642         else if(tag->id == ST_DOACTION && action) {
643             ActionTAG*actions;
644             actions = swf_ActionGet(tag);
645             swf_DumpActions(actions, myprefix);
646         }
647         else if(tag->id == ST_DEFINEBUTTON && action) {
648             dumpButtonActions(tag, myprefix);
649         }
650         else if(tag->id == ST_DEFINEBUTTON2 && action) {
651             dumpButton2Actions(tag, myprefix);
652         }
653         else if(tag->id == ST_PLACEOBJECT2) {
654             if((*(U8*)tag->data)&0x80)
655                 handlePlaceObject2(tag, myprefix);
656             else
657                 printf("\n");
658         }
659
660         if(tag->len && used) {
661             int num = swf_GetNumUsedIDs(tag);
662             int* used;
663             int t;
664             if(num) {
665                 used = (int*)malloc(sizeof(int)*num);
666                 swf_GetUsedIDs(tag, used);
667                 printf("%s%suses IDs: ", indent, prefix);
668                 for(t=0;t<num;t++) {
669                     tag->pos = used[t];
670                     printf("%d%s", swf_GetU16(tag), t<num-1?", ":"");
671                 }
672                 printf("\n");
673             }
674         }
675
676         if(tag->len && hex) {
677             int t;
678             printf("                %s-=> ",prefix);
679             for(t=0;t<tag->len;t++) {
680                 printf("%02x ", tag->data[t]);
681                 if((t && ((t&15)==15)) || (t==tag->len-1))
682                 {
683                     if(t==tag->len-1)
684                         printf("\n");
685                     else
686                         printf("\n                %s-=> ",prefix);
687                 }
688             }
689         }
690         tag = tag->next;
691         fflush(stdout);
692     }
693
694     swf_FreeTags(&swf);
695     return 0;
696 }
697
698