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