clipdepth is now always shown.
[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 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 "../config.h"
23
24 #ifdef HAVE_SYS_STAT_H
25 #include <sys/stat.h>
26 #else
27 #undef HAVE_STAT
28 #endif
29
30 #ifdef HAVE_SYS_TYPES_H
31 #include <sys/types.h>
32 #else
33 #undef HAVE_STAT
34 #endif
35
36 #include <unistd.h>
37 #include <stdio.h>
38 #include <fcntl.h>
39 #include <stdarg.h>
40 #include "../lib/rfxswf.h"
41 #include "../lib/args.h"
42
43 static char * filename = 0;
44
45 /* idtab stores the ids which are defined in the file. This allows us
46    to detect errors in the file. (i.e. ids which are defined more than 
47    once */
48 static char idtab[65536];
49 static char * indent = "                ";
50
51 static int placements = 0;
52 static int action = 0;
53 static int html = 0;
54 static int xy = 0;
55 static int showtext = 0;
56 static int showshapes = 0;
57 static int hex = 0;
58 static int used = 0;
59 static int bbox = 0;
60
61 static struct options_t options[] = {
62 {"h", "help"},
63 {"D", "full"},
64 {"V", "version"},
65 {"e", "html"},
66 {"a", "action"},
67 {"t", "text"},
68 {"s", "shapes"},
69 {"p", "placements"},
70 {"b", "bbox"},
71 {"X", "width"},
72 {"Y", "height"},
73 {"r", "rate"},
74 {"f", "frames"},
75 {"d", "hex"},
76 {"u", "used"},
77 {0,0}
78 };
79
80 int args_callback_option(char*name,char*val)
81 {
82     if(!strcmp(name, "V")) {
83         printf("swfdump - part of %s %s\n", PACKAGE, VERSION);
84         exit(0);
85     } 
86     else if(name[0]=='a') {
87         action = 1;
88         return 0;
89     }
90     else if(name[0]=='p') {
91         placements = 1;
92         return 0;
93     }
94     else if(name[0]=='t') {
95         showtext = 1;
96         return 0;
97     }
98     else if(name[0]=='s') {
99         showshapes = 1;
100         return 0;
101     }
102     else if(name[0]=='e') {
103         html = 1;
104         return 0;
105     }
106     else if(name[0]=='X') {
107         xy |= 1;
108         return 0;
109     }
110     else if(name[0]=='Y') {
111         xy |= 2;
112         return 0;
113     }
114     else if(name[0]=='r') {
115         xy |= 4;
116         return 0;
117     }
118     else if(name[0]=='f') {
119         xy |= 8;
120         return 0;
121     }
122     else if(name[0]=='d') {
123         hex = 1;
124         return 0;
125     }
126     else if(name[0]=='u') {
127         used = 1;
128         return 0;
129     }
130     else if(name[0]=='b') {
131         bbox = 1;
132         return 0;
133     }
134     else if(name[0]=='D') {
135         action = placements = showtext = showshapes = 1;
136         return 0;
137     }
138     else {
139         printf("Unknown option: -%s\n", name);
140         exit(1);
141     }
142
143     return 0;
144 }
145 int args_callback_longoption(char*name,char*val)
146 {
147     return args_long2shortoption(options, name, val);
148 }
149 void args_callback_usage(char *name)
150 {
151     printf("\n");
152     printf("Usage: %s [-atpdu] file.swf\n", name);
153     printf("\n");
154     printf("-h , --help                    Print short help message and exit\n");
155     printf("-D , --full                    Show everything. Same as -atp\n");
156     printf("-V , --version                 Print version info and exit\n");
157     printf("-e , --html                    Print out html code for embedding the file\n");
158     printf("-a , --action                  Disassemble action tags\n");
159     printf("-t , --text                    Show text fields (like swfstrings).\n");
160     printf("-s , --shapes                  Show shape coordinates/styles\n");
161     printf("-p , --placements              Show placement information\n");
162     printf("-b , --bbox                    Print tag's bounding boxes\n");
163     printf("-X , --width                   Prints out a string of the form \"-X width\".\n");
164     printf("-Y , --height                  Prints out a string of the form \"-Y height\".\n");
165     printf("-r , --rate                    Prints out a string of the form \"-r rate\".\n");
166     printf("-f , --frames                  Prints out a string of the form \"-f framenum\".\n");
167     printf("-d , --hex                     Print hex output of tag data, too.\n");
168     printf("-u , --used                    Show referred IDs for each Tag.\n");
169     printf("\n");
170 }
171 int args_callback_command(char*name,char*val)
172 {
173     if(filename) {
174         fprintf(stderr, "Only one file allowed. You supplied at least two. (%s and %s)\n",
175                  filename, name);
176     }
177     filename = name;
178     return 0;
179 }
180
181 char* what;
182 char* testfunc(char*str)
183 {
184     printf("%s: %s\n", what, str);
185     return 0;
186 }
187
188 void dumpButton2Actions(TAG*tag, char*prefix)
189 {
190     U32 oldTagPos;
191     U32 offsetpos;
192     U32 condition;
193
194     oldTagPos = swf_GetTagPos(tag);
195
196     // scan DefineButton2 Record
197     
198     swf_GetU16(tag);          // Character ID
199     swf_GetU8(tag);           // Flags;
200
201     offsetpos = swf_GetTagPos(tag);  // first offset
202     swf_GetU16(tag);
203
204     while (swf_GetU8(tag))      // state  -> parse ButtonRecord
205     { swf_GetU16(tag);          // id
206       swf_GetU16(tag);          // layer
207       swf_GetMatrix(tag,NULL);  // matrix
208       swf_GetCXForm(tag,NULL,1);  // cxform
209     }
210
211     while(offsetpos)
212     { U8 a;
213       ActionTAG*actions;
214
215       if(tag->pos >= tag->len)
216           break;
217         
218       offsetpos = swf_GetU16(tag);
219       condition = swf_GetU16(tag);                // condition
220       
221       actions = swf_ActionGet(tag);
222       printf("%s condition %04x\n", prefix, condition);
223       swf_DumpActions(actions, prefix);
224     }
225     
226     swf_SetTagPos(tag,oldTagPos);
227     return;
228 }
229
230 void dumpButtonActions(TAG*tag, char*prefix)
231 {
232     ActionTAG*actions;
233     swf_GetU16(tag); // id
234     while (swf_GetU8(tag))      // state  -> parse ButtonRecord
235     { swf_GetU16(tag);          // id
236       swf_GetU16(tag);          // layer
237       swf_GetMatrix(tag,NULL);  // matrix
238     }
239     actions = swf_ActionGet(tag);
240     swf_DumpActions(actions, prefix);
241 }
242
243 SWF swf;
244 int fontnum = 0;
245 SWFFONT**fonts;
246
247 void textcallback(void*self, int*glyphs, int*ypos, int nr, int fontid, int fontsize, int startx, int starty, RGBA*color) 
248 {
249     int font=-1,t;
250     printf("                <%2d glyphs in font %2d, color #%02x%02x%02x%02x> ",nr, fontid, color->r, color->g, color->b, color->a);
251     for(t=0;t<fontnum;t++)
252     {
253         if(fonts[t]->id == fontid) {
254             font = t;
255             break;
256         }
257     }
258
259     for(t=0;t<nr;t++)
260     {
261         unsigned char a; 
262         if(font>=0) {
263             if(glyphs[t] >= fonts[font]->numchars  /*glyph is in range*/
264                     || !fonts[font]->glyph2ascii /* font has ascii<->glyph mapping */
265               ) a = glyphs[t];
266             else
267                 a = fonts[font]->glyph2ascii[glyphs[t]];
268         } else {
269             a = glyphs[t];
270         }
271         if(a>=32)
272             printf("%c", a);
273         else
274             printf("\\x%x", (int)a);
275     }
276     printf("\n");
277 }
278
279 void handleText(TAG*tag) 
280 {
281   printf("\n");
282   swf_ParseDefineText(tag,textcallback, 0);
283 }
284             
285 void handleDefineSound(TAG*tag)
286 {
287     U16 id = swf_GetU16(tag);
288     U8 flags = swf_GetU8(tag);
289     int compression = (flags>>4)&3;
290     int rate = (flags>>2)&3;
291     int bits = flags&2?16:8;
292     int stereo = flags&1;
293     printf(" (");
294     if(compression == 0) printf("Raw ");
295     else if(compression == 1) printf("ADPCM ");
296     else if(compression == 2) printf("MP3 ");
297     else printf("? ");
298     if(rate == 0) printf("5.5Khz ");
299     if(rate == 1) printf("11Khz ");
300     if(rate == 2) printf("22Khz ");
301     if(rate == 3) printf("44Khz ");
302     printf("%dBit ", bits);
303     if(stereo) printf("stereo");
304     else printf("mono");
305     printf(")");
306 }
307
308 void handleDefineBits(TAG*tag)
309 {
310     U16 id;
311     U8 mode;
312     U16 width,height;
313     int bpp;
314     id = swf_GetU16(tag);
315     mode = swf_GetU8(tag);
316     width = swf_GetU16(tag);
317     height = swf_GetU16(tag);
318     printf(" image %dx%d",width,height);
319     if(mode == 3) printf(" (8 bpp)");
320     else if(mode == 4) printf(" (16 bpp)");
321     else if(mode == 5) printf(" (32 bpp)");
322     else printf(" (? bpp)");
323 }
324
325 void handleEditText(TAG*tag)
326 {
327     U16 id ;
328     U16 flags;
329     int t;
330     id = swf_GetU16(tag);
331     swf_GetRect(tag,0);
332     
333     //swf_ResetReadBits(tag);
334
335     if (tag->readBit)  
336     { tag->pos++; 
337       tag->readBit = 0; 
338     }
339     flags = swf_GetBits(tag,16);
340     if(flags & ET_HASFONT) {
341         swf_GetU16(tag); //font
342         swf_GetU16(tag); //fontheight
343     }
344     if(flags & ET_HASTEXTCOLOR) {
345         swf_GetU8(tag); //rgba
346         swf_GetU8(tag);
347         swf_GetU8(tag);
348         swf_GetU8(tag);
349     }
350     if(flags & ET_HASMAXLENGTH) {
351         swf_GetU16(tag); //maxlength
352     }
353     if(flags & ET_HASLAYOUT) {
354         swf_GetU8(tag); //align
355         swf_GetU16(tag); //left margin
356         swf_GetU16(tag); //right margin
357         swf_GetU16(tag); //indent
358         swf_GetU16(tag); //leading
359     }
360     printf(" variable \"%s\" ", &tag->data[tag->pos]);
361     if(flags & ET_HTML) printf("(html)");
362     if(flags & ET_NOSELECT) printf("(noselect)");
363     if(flags & ET_PASSWORD) printf("(password)");
364     if(flags & ET_READONLY) printf("(readonly)");
365
366     if(flags & (ET_X1 | ET_X3 ))
367     {
368         printf(" undefined flags: %08x (%08x)", (flags&(ET_X1|ET_X3)), flags);
369     }
370     
371     while(tag->data[tag->pos++]);
372     if(flags & ET_HASTEXT)
373    //  printf(" text \"%s\"\n", &tag->data[tag->pos]) //TODO
374         ;
375 }
376 void printhandlerflags(U32 handlerflags) 
377 {
378     if(handlerflags&1) printf("[on load]");
379     if(handlerflags&2) printf("[enter frame]");
380     if(handlerflags&4) printf("[unload]");
381     if(handlerflags&8) printf("[mouse move]");
382     if(handlerflags&16) printf("[mouse down]");
383     if(handlerflags&32) printf("[mouse up]");
384     if(handlerflags&64) printf("[key down]");
385     if(handlerflags&128) printf("[key up]");
386
387     if(handlerflags&256) printf("[data]");
388     if(handlerflags&512) printf("[initialize]");
389     if(handlerflags&1024) printf("[mouse press]");
390     if(handlerflags&2048) printf("[mouse release]");
391     if(handlerflags&4096) printf("[mouse release outside]");
392     if(handlerflags&8192) printf("[mouse rollover]");
393     if(handlerflags&16384) printf("[mouse rollout]");
394     if(handlerflags&32768) printf("[mouse drag over]");
395
396     if(handlerflags&0x10000) printf("[mouse drag out]");
397     if(handlerflags&0x20000) printf("[key press]");
398     if(handlerflags&0x40000) printf("[construct even]");
399     if(handlerflags&0xfff80000) printf("[???]");
400 }
401 void handleVideoStream(TAG*tag, char*prefix)
402 {
403     U16 id = swf_GetU16(tag);
404     U16 frames = swf_GetU16(tag);
405     U16 width = swf_GetU16(tag);
406     U16 height = swf_GetU16(tag);
407     U8 flags = swf_GetU8(tag); //5-2(videopacket 01=off 10=on)-1(smoothing 1=on)
408     U8 codec = swf_GetU8(tag);
409     printf(" (%d frames, %dx%d", frames, width, height);
410     if(flags&1)
411         printf(" smoothed");
412     if(codec == 2)
413         printf(" sorenson h.263)");
414     else
415         printf(" codec 0x%02x)", codec);
416 }
417 void handleVideoFrame(TAG*tag, char*prefix)
418 {
419     U32 code, version, reference, sizeflags;
420     U32 width=0, height=0;
421     U8 type;
422     U16 id = swf_GetU16(tag);
423     U16 frame = swf_GetU16(tag);
424     U8 deblock,flags, tmp, bit;
425     U32 quantizer;
426     char*types[] = {"I-frame", "P-frame", "disposable P-frame", "<reserved>"};
427     printf(" (frame %d) ", frame);
428
429     /* video packet follows */
430     code = swf_GetBits(tag, 17);
431     version = swf_GetBits(tag, 5);
432     reference = swf_GetBits(tag, 8);
433
434     sizeflags = swf_GetBits(tag, 3);
435     switch(sizeflags)
436     {
437         case 0: width = swf_GetBits(tag, 8); height = swf_GetBits(tag, 8); break;
438         case 1: width = swf_GetBits(tag, 16); height = swf_GetBits(tag, 16); break;
439         case 2: width = 352; height = 288; break;
440         case 3: width = 176; height = 144; break;
441         case 4: width = 128; height = 96; break;
442         case 5: width = 320; height = 240; break;
443         case 6: width = 160; height = 120; break;
444         case 7: width = -1; height = -1;/*reserved*/ break;
445     }
446     printf("%dx%d ", width, height);
447     type = swf_GetBits(tag, 2);
448     printf("%s", types[type]);
449
450     deblock = swf_GetBits(tag, 1);
451     if(deblock)
452         printf(" deblock ", deblock);
453     quantizer = swf_GetBits(tag, 5);
454     printf(" quant: %d ", quantizer);
455 }
456
457 void handlePlaceObject2(TAG*tag, char*prefix)
458 {
459     U8 flags = swf_GetU8(tag);
460     MATRIX m;
461     CXFORM cx;
462     char pstr[3][160];
463     int ppos[3] = {0,0,0};
464     swf_GetU16(tag); //depth
465
466     //flags&1: move
467     if(flags&2) swf_GetU16(tag); //id
468     if(flags&4) {
469         swf_GetMatrix(tag,&m);
470         if(placements) {
471             ppos[0] += sprintf(pstr[0], "| Matrix             ");
472             ppos[1] += sprintf(pstr[1], "| %5.3f %5.3f %6.2f ", m.sx/65536.0, m.r1/65536.0, m.tx/20.0);
473             ppos[2] += sprintf(pstr[2], "| %5.3f %5.3f %6.2f ", m.r0/65536.0, m.sy/65536.0, m.ty/20.0);
474         }
475     }
476     if(flags&8) {
477         swf_GetCXForm(tag, &cx, 1);
478         if(placements) {
479             ppos[0] += sprintf(pstr[0]+ppos[0], "| CXForm    r    g    b    a ");
480             ppos[1] += sprintf(pstr[1]+ppos[1], "| mul    %4.1f %4.1f %4.1f %4.1f ", cx.r0/256.0, cx.g0/256.0, cx.b0/256.0, cx.a0/256.0);
481             ppos[2] += sprintf(pstr[2]+ppos[2], "| add    %4d %4d %4d %4d ", cx.r1, cx.g1, cx.b1, cx.a1);
482         }
483     }
484     if(flags&16) {
485         U16 ratio = swf_GetU16(tag); //ratio
486         if(placements) {
487             ppos[0] += sprintf(pstr[0]+ppos[0], "| Ratio ");
488             ppos[1] += sprintf(pstr[1]+ppos[1], "| %-5d ", ratio);
489             ppos[2] += sprintf(pstr[2]+ppos[2], "|       ");
490         }
491     }
492     if(flags&64) {
493         U16 clip = swf_GetU16(tag); //clip
494         if(placements) {
495             ppos[0] += sprintf(pstr[0]+ppos[0], "| Clip  ");
496             ppos[1] += sprintf(pstr[1]+ppos[1], "| %-5d ", clip);
497             ppos[2] += sprintf(pstr[2]+ppos[2], "|       ");
498         }
499     }
500     if(flags&32) { while(swf_GetU8(tag)); }
501     if(placements && ppos[0]) {
502         printf("\n");
503         printf("%s %s\n", prefix, pstr[0]);
504         printf("%s %s\n", prefix, pstr[1]);
505         printf("%s %s", prefix, pstr[2]);
506     }
507     if(flags&128) {
508       if (action) {
509         U16 reserved;
510         U32 globalflags;
511         U32 handlerflags;
512         char is32 = 0;
513         printf("\n");
514         reserved = swf_GetU16(tag); // must be 0
515         globalflags = swf_GetU16(tag); //TODO: 32 if version>=6
516         if(reserved) {
517             printf("Unknown parameter field not zero: %04x\n", reserved);
518             return;
519         }
520         printf("global flags: %04x\n", globalflags);
521
522         handlerflags = swf_GetU16(tag); //TODO: 32 if version>=6
523         if(!handlerflags) {
524             handlerflags = swf_GetU32(tag);
525             is32 = 1;
526         }
527         while(handlerflags)  {
528             int length;
529             int t;
530             ActionTAG*a;
531
532             globalflags &= ~handlerflags;
533             printf("%s flags %08x ",prefix, handlerflags);
534             printhandlerflags(handlerflags);
535             length = swf_GetU32(tag);
536             printf(", %d bytes actioncode\n",length);
537             a = swf_ActionGet(tag);
538             swf_DumpActions(a,prefix);
539             swf_ActionFree(a);
540
541             handlerflags = is32?swf_GetU32(tag):swf_GetU16(tag); //TODO: 32 if version>=6
542         }
543         if(globalflags) // should go to sterr.
544             printf("ERROR: unsatisfied handlerflags: %02x\n", globalflags);
545     } else {
546       printf(" has action code\n");
547     }
548     } else printf("\n");
549 }
550
551 void handlePlaceObject(TAG*tag, char*prefix)
552 {
553     TAG*tag2 = swf_InsertTag(0, ST_PLACEOBJECT2);
554
555     U16 id = swf_GetU16(tag);
556     U16 depth = swf_GetU16(tag);
557     MATRIX matrix; 
558     CXFORM cxform;
559     swf_GetMatrix(tag, &matrix);
560     swf_GetCXForm(tag, &cxform, 0);
561
562     swf_SetU8(tag2, 14);
563     swf_SetU16(tag2, depth);
564     swf_SetMatrix(tag2, &matrix);
565     swf_SetCXForm(tag2, &cxform, 1);
566
567     handlePlaceObject2(tag2, prefix);
568 }
569 char stylebuf[256];
570 char* fillstyle2str(FILLSTYLE*style)
571 {
572     switch(style->type) {
573         case 0x00:
574             sprintf(stylebuf, "SOLID %02x%02x%02x%02x", style->color.r, style->color.g, style->color.b, style->color.a);
575             break;
576         case 0x10: case 0x12:
577             sprintf(stylebuf, "GRADIENT (%d steps)", style->gradient.num);
578             break;
579         case 0x40: case 0x41:
580             /* TODO: display information about that bitmap */
581             sprintf(stylebuf, "BITMAP %d", style->id_bitmap);
582             break;
583         default:
584             sprintf(stylebuf, "UNKNOWN[%02x]",style->type);
585     }
586     return stylebuf;
587 }
588 char* linestyle2str(LINESTYLE*style)
589 {
590     sprintf(stylebuf, "%.2f %02x%02x%02x%02x", style->width/20.0, style->color.r, style->color.g, style->color.b, style->color.a);
591     return stylebuf;
592 }
593
594 void handleShape(TAG*tag, char*prefix)
595 {
596     SHAPE2 shape;
597     SHAPELINE*line;
598     int t,max;
599
600     tag->pos = 0;
601     tag->readBit = 0;
602     swf_ParseDefineShape(tag, &shape);
603
604     max = shape.numlinestyles > shape.numfillstyles?shape.numlinestyles:shape.numfillstyles;
605
606     if(max) printf("%s | fillstyles(%02d)        linestyles(%02d)\n", 
607             prefix,
608             shape.numfillstyles,
609             shape.numlinestyles
610             );
611     else    printf("%s | (Neither line nor fill styles)\n", prefix);
612
613     for(t=0;t<max;t++) {
614         printf("%s", prefix);
615         if(t < shape.numfillstyles) {
616             printf(" | %-2d) %-18.18s", t+1, fillstyle2str(&shape.fillstyles[t]));
617         } else {
618             printf("                         ");
619         }
620         if(t < shape.numlinestyles) {
621             printf("%-2d) %s", t+1, linestyle2str(&shape.linestyles[t]));
622         }
623         printf("\n");
624     }
625
626     printf("%s |\n", prefix);
627
628     line = shape.lines;
629     while(line) {
630         printf("%s | fill: %02d/%02d line:%02d - ",
631                 prefix, 
632                 line->fillstyle0,
633                 line->fillstyle1,
634                 line->linestyle);
635         if(line->type == moveTo) {
636             printf("moveTo %.2f %.2f\n", line->x/20.0, line->y/20.0);
637         } else if(line->type == lineTo) {
638             printf("lineTo %.2f %.2f\n", line->x/20.0, line->y/20.0);
639         } else if(line->type == splineTo) {
640             printf("splineTo (%.2f %.2f) %.2f %.2f\n", 
641                     line->sx/20.0, line->sy/20.0,
642                     line->x/20.0, line->y/20.0
643                     );
644         }
645         line = line->next;
646     }
647     printf("%s |\n", prefix);
648 }
649     
650 void fontcallback1(void*self, U16 id,U8 * name)
651 { fontnum++;
652 }
653
654 void fontcallback2(void*self, U16 id,U8 * name)
655
656   swf_FontExtract(&swf,id,&fonts[fontnum]);
657   fontnum++;
658 }
659
660 static U8 printable(U8 a)
661 {
662     if(a<32 || a==127) return '.';
663     else return a;
664 }
665 void hexdumpTag(TAG*tag, char* prefix)
666 {
667     int t;
668     char ascii[32];
669     printf("                %s-=> ",prefix);
670     for(t=0;t<tag->len;t++) {
671         printf("%02x ", tag->data[t]);
672         ascii[t&15] = printable(tag->data[t]);
673         if((t && ((t&15)==15)) || (t==tag->len-1))
674         {
675             int s,p=((t)&15)+1;
676             ascii[p] = 0;
677             for(s=p-1;s<16;s++) {
678                 printf("   ");
679             }
680             if(t==tag->len-1)
681                 printf(" %s\n", ascii);
682             else
683                 printf(" %s\n                %s-=> ",ascii,prefix);
684         }
685     }
686 }
687
688 void handleExportAssets(TAG*tag, char* prefix)
689 {
690     int num;
691     U16 id;
692     char* name;
693     int t;
694     num = swf_GetU16(tag);
695     for(t=0;t<num;t++)
696     {
697         id = swf_GetU16(tag);
698         name = swf_GetString(tag);
699         printf("%sexports %04d as \"%s\"\n", prefix, id, name);
700     }
701 }
702
703 void dumperror(const char* format, ...)
704 {
705     char buf[1024];
706     va_list arglist;
707
708     va_start(arglist, format);
709     vsprintf(buf, format, arglist);
710     va_end(arglist);
711
712     if(!html && !xy)
713         printf("==== Error: %s ====\n", buf);
714 }
715
716 static char strbuf[800];
717 static int bufpos=0;
718
719 char* timestring(double f)
720 {
721     int hours   = (int)(f/3600);
722     int minutes = (int)((f-hours*3600)/60);
723     int seconds = (int)((f-hours*3600-minutes*60));
724     int useconds = (int)((f-(int)f)*1000+0.5);
725     bufpos+=100;
726     bufpos%=800;
727     sprintf(&strbuf[bufpos], "%02d:%02d:%02d,%03d",hours,minutes,seconds,useconds);
728     return &strbuf[bufpos];
729 }
730
731 int main (int argc,char ** argv)
732
733     TAG*tag;
734 #ifdef HAVE_STAT
735     struct stat statbuf;
736 #endif
737     int f;
738     int xsize,ysize;
739     char issprite = 0; // are we inside a sprite definition?
740     int spriteframe = 0;
741     int mainframe=0;
742     char* spriteframelabel = 0;
743     char* framelabel = 0;
744     char prefix[128];
745     int filesize = 0;
746     prefix[0] = 0;
747     memset(idtab,0,65536);
748
749     processargs(argc, argv);
750
751     if(!filename)
752     {
753         fprintf(stderr, "You must supply a filename.\n");
754         return 1;
755     }
756
757     f = open(filename,O_RDONLY|O_BINARY);
758
759     if (f<0)
760     { 
761         char buffer[256];
762         sprintf(buffer, "Couldn't open %s", filename);
763         perror(buffer);
764         exit(1);
765     }
766     if FAILED(swf_ReadSWF(f,&swf))
767     { 
768         fprintf(stderr, "%s is not a valid SWF file or contains errors.\n",filename);
769         close(f);
770         exit(1);
771     }
772
773 #ifdef HAVE_STAT
774     fstat(f, &statbuf);
775     if(statbuf.st_size != swf.fileSize && !swf.compressed)
776         dumperror("Real Filesize (%d) doesn't match header Filesize (%d)",
777                 statbuf.st_size, swf.fileSize);
778     filesize = statbuf.st_size;
779 #endif
780
781     close(f);
782
783     xsize = (swf.movieSize.xmax-swf.movieSize.xmin)/20;
784     ysize = (swf.movieSize.ymax-swf.movieSize.ymin)/20;
785     if(xy)
786     {
787         if(xy&1)
788         printf("-X %d", xsize);
789
790         if((xy&1) && (xy&6))
791         printf(" ");
792
793         if(xy&2)
794         printf("-Y %d", ysize);
795         
796         if((xy&3) && (xy&4))
797         printf(" ");
798
799         if(xy&4)
800         printf("-r %.2f", swf.frameRate/256.0);
801         
802         if((xy&7) && (xy&8))
803         printf(" ");
804         
805         if(xy&8)
806         printf("-f %d", swf.frameCount);
807         
808         printf("\n");
809         return 0;
810     }
811     if(html)
812     {
813         char*fileversions[] = {"","1,0,0,0", "2,0,0,0","3,0,0,0","4,0,0,0",
814                                "5,0,0,0","6,0,23,0","7,0,0,0","8,0,0,0","9,0,0,0"};
815         if(swf.fileVersion>9) {
816             fprintf(stderr, "Fileversion>9\n");
817             exit(1);
818         }
819         printf("<OBJECT CLASSID=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\"\n"
820                " WIDTH=\"%d\"\n"
821                //" BGCOLOR=#ffffffff\n"?
822                " HEIGHT=\"%d\"\n"
823                //http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,23,0?
824                " CODEBASE=\"http://active.macromedia.com/flash5/cabs/swflash.cab#version=%s\">\n"
825                "  <PARAM NAME=\"MOVIE\" VALUE=\"%s\">\n"
826                "  <PARAM NAME=\"PLAY\" VALUE=\"true\">\n" 
827                "  <PARAM NAME=\"LOOP\" VALUE=\"true\">\n"
828                "  <PARAM NAME=\"QUALITY\" VALUE=\"high\">\n"
829                "  <EMBED SRC=\"%s\" WIDTH=\"%d\" HEIGHT=\"%d\"\n" //bgcolor=#ffffff?
830                "   PLAY=\"true\" ALIGN=\"\" LOOP=\"true\" QUALITY=\"high\"\n"
831                "   TYPE=\"application/x-shockwave-flash\"\n"
832                "   PLUGINSPAGE=\"http://www.macromedia.com/go/getflashplayer\">\n"
833                "  </EMBED>\n" 
834                "</OBJECT>\n", xsize, ysize, fileversions[swf.fileVersion], 
835                               filename, filename, xsize, ysize);
836         return 0;
837     } 
838     printf("[HEADER]        File version: %d\n", swf.fileVersion);
839     if(swf.compressed) {
840         printf("[HEADER]        File is zlib compressed.");
841         if(filesize && swf.fileSize)
842             printf(" Ratio: %02d%%\n", filesize*100/(swf.fileSize));
843         else
844             printf("\n");
845     }
846     printf("[HEADER]        File size: %ld%s\n", swf.fileSize, swf.compressed?" (Depacked)":"");
847     printf("[HEADER]        Frame rate: %f\n",swf.frameRate/256.0);
848     printf("[HEADER]        Frame count: %d\n",swf.frameCount);
849     printf("[HEADER]        Movie width: %.2f",(swf.movieSize.xmax-swf.movieSize.xmin)/20.0);
850     if(swf.movieSize.xmin)
851         printf(" (left offset: %.2f)\n", swf.movieSize.xmin/20.0);
852     else 
853         printf("\n");
854     printf("[HEADER]        Movie height: %.2f",(swf.movieSize.ymax-swf.movieSize.ymin)/20.0);
855     if(swf.movieSize.ymin)
856         printf(" (top offset: %.2f)\n", swf.movieSize.ymin/20.0);
857     else 
858         printf("\n");
859
860     tag = swf.firstTag;
861    
862     if(showtext) {
863         fontnum = 0;
864         swf_FontEnumerate(&swf,&fontcallback1, 0);
865         fonts = (SWFFONT**)malloc(fontnum*sizeof(SWFFONT*));
866         fontnum = 0;
867         swf_FontEnumerate(&swf,&fontcallback2, 0);
868     }
869
870     while(tag) {
871         char*name = swf_TagGetName(tag);
872         char myprefix[128];
873         if(!name) {
874             dumperror("Unknown tag:0x%03x", tag->id);
875             //tag = tag->next;
876             //continue;
877         }
878         if(swf_TagGetName(tag)) {
879             printf("[%03x] %9ld %s%s", tag->id, tag->len, prefix, swf_TagGetName(tag));
880         } else {
881             printf("[%03x] %9ld %sUNKNOWN TAG %03x", tag->id, tag->len, prefix, tag->id);
882         }
883         
884         if(tag->id == ST_FREECHARACTER) {
885             U16 id = swf_GetU16(tag);
886             idtab[id] = 0;
887         }
888
889         if(swf_isDefiningTag(tag)) {
890             U16 id = swf_GetDefineID(tag);
891             printf(" defines id %04d", id);
892             if(idtab[id])
893                 dumperror("Id %04d is defined more than once.", id);
894             idtab[id] = 1;
895         }
896         else if(swf_isPseudoDefiningTag(tag)) {
897             U16 id = swf_GetDefineID(tag);
898             printf(" adds information to id %04d", id);
899             if(!idtab[id])
900                 dumperror("Id %04d is not yet defined.\n", id);
901         }
902         else if(tag->id == ST_PLACEOBJECT) {
903             printf(" places id %04d at depth %04x", swf_GetPlaceID(tag), swf_GetDepth(tag));
904             if(swf_GetName(tag))
905                 printf(" name \"%s\"",swf_GetName(tag));
906         }
907         else if(tag->id == ST_PLACEOBJECT2) {
908             if(tag->data[0]&1)
909                 printf(" moves");
910             else
911                 printf(" places");
912             
913             if(tag->data[0]&2)
914                 printf(" id %04d",swf_GetPlaceID(tag));
915             else
916                 printf(" object");
917
918             printf(" at depth %04d", swf_GetDepth(tag));
919             
920             if(tag->data[0]&64) {
921                 SWFPLACEOBJECT po;
922                 swf_GetPlaceObject(tag, &po);
923                 printf(" (clip to %04d)", po.clipdepth);
924                 swf_PlaceObjectFree(&po);
925             }
926             if(swf_GetName(tag))
927                 printf(" name \"%s\"",swf_GetName(tag));
928
929         }
930         else if(tag->id == ST_REMOVEOBJECT) {
931             printf(" removes id %04d from depth %04d", swf_GetPlaceID(tag), swf_GetDepth(tag));
932         }
933         else if(tag->id == ST_REMOVEOBJECT2) {
934             printf(" removes object from depth %04d", swf_GetDepth(tag));
935         }
936         else if(tag->id == ST_FREECHARACTER) {
937             printf(" frees object %04d", swf_GetPlaceID(tag));
938         }
939         else if(tag->id == ST_STARTSOUND) {
940             U8 flags;
941             U16 id;
942             id = swf_GetU16(tag);
943             flags = swf_GetU8(tag);
944             if(flags & 32)
945                 printf(" stops sound with id %04d", id);
946             else
947                 printf(" starts sound with id %04d", id);
948             if(flags & 16)
949                 printf(" (if not already playing)");
950             if(flags & 1)
951                 swf_GetU32(tag);
952             if(flags & 2)
953                 swf_GetU32(tag);
954             if(flags & 4) {
955                 printf(" looping %d times", swf_GetU16(tag));
956             }
957         }
958         else if(tag->id == ST_FRAMELABEL) {
959             int l = strlen(tag->data);
960             printf(" \"%s\"", tag->data);
961             if(l < tag->len-1) {
962                 printf(" has %d extra bytes", tag->len-1-l);
963                 if(tag ->len-1-l == 1 && tag->data[tag->len-1] == 1)
964                     printf(" (ANCHOR)");
965             }
966             if((framelabel && !issprite) ||
967                (spriteframelabel && issprite)) {
968                 dumperror("Frame %d has more than one label", 
969                         issprite?spriteframe:mainframe);
970             }
971             if(issprite) spriteframelabel = tag->data;
972             else framelabel = tag->data;
973         }
974         else if(tag->id == ST_SHOWFRAME) {
975             char*label = issprite?spriteframelabel:framelabel;
976             int frame = issprite?spriteframe:mainframe;
977             int nframe = frame;
978             if(!label) {
979                 while(tag->next && tag->next->id == ST_SHOWFRAME && tag->next->len == 0) {
980                     tag = tag->next;
981                     if(issprite) spriteframe++;
982                     else mainframe++;
983                     nframe++;
984                 }
985             }
986             if(nframe == frame)
987                 printf(" %d (%s)", frame+1, timestring(frame*(256.0/(swf.frameRate+0.1))));
988             else
989                 printf(" %d-%d (%s-%s)", frame+1, nframe+1,
990                         timestring(frame*(256.0/(swf.frameRate+0.1))),
991                         timestring(nframe*(256.0/(swf.frameRate+0.1)))
992                         );
993             if(label)
994                 printf(" (label \"%s\")", label);
995             if(issprite) {spriteframe++; spriteframelabel = 0;}
996             if(!issprite) {mainframe++; framelabel = 0;}
997         }
998
999         if(tag->id == ST_SETBACKGROUNDCOLOR) {
1000             U8 r = swf_GetU8(tag);
1001             U8 g = swf_GetU8(tag);
1002             U8 b = swf_GetU8(tag);
1003             printf(" (%02x/%02x/%02x)\n",r,g,b);
1004         }
1005         else if(tag->id == ST_PROTECT) {
1006             if(tag->len>0) {
1007                 printf(" %s\n", swf_GetString(tag));
1008             } else {
1009                 printf("\n");
1010             }
1011         }
1012         else if(tag->id == ST_DEFINEBITSLOSSLESS ||
1013            tag->id == ST_DEFINEBITSLOSSLESS2) {
1014             handleDefineBits(tag);
1015             printf("\n");
1016         }
1017         else if(tag->id == ST_DEFINESOUND) {
1018             handleDefineSound(tag);
1019             printf("\n");
1020         }
1021         else if(tag->id == ST_VIDEOFRAME) {
1022             handleVideoFrame(tag, myprefix);
1023             printf("\n");
1024         }
1025         else if(tag->id == ST_DEFINEVIDEOSTREAM) {
1026             handleVideoStream(tag, myprefix);
1027             printf("\n");
1028         }
1029         else if(tag->id == ST_DEFINEEDITTEXT) {
1030             handleEditText(tag);
1031             printf("\n");
1032         }
1033         else if(tag->id == ST_DEFINEMOVIE) {
1034             U16 id = swf_GetU16(tag);
1035             char*s = swf_GetString(tag);
1036             printf(" URL: %s\n", s);
1037         }
1038         else if(tag->id == ST_DEFINETEXT || tag->id == ST_DEFINETEXT2) {
1039             if(showtext)
1040                 handleText(tag);
1041             else
1042                 printf("\n");
1043         }
1044         else if(tag->id == ST_PLACEOBJECT2) {
1045         }
1046         else if(tag->id == ST_NAMECHARACTER) {
1047             swf_GetU16(tag);
1048             printf(" \"%s\"\n", swf_GetString(tag));
1049         }
1050         else {
1051             printf("\n");
1052         }
1053
1054         if(bbox && swf_isDefiningTag(tag) && tag->id != ST_DEFINESPRITE) {
1055             SRECT r = swf_GetDefineBBox(tag);
1056             printf("                %s bbox [%.2f, %.2f, %.2f, %.2f]\n", prefix,
1057                     r.xmin/20.0,
1058                     r.ymin/20.0,
1059                     r.xmax/20.0,
1060                     r.ymax/20.0);
1061         }
1062         
1063         sprintf(myprefix, "                %s", prefix);
1064
1065         if(tag->id == ST_DEFINESPRITE) {
1066             sprintf(prefix, "         ");
1067             if(issprite) {
1068                 dumperror("Sprite definition inside a sprite definition");
1069             }
1070             issprite = 1;
1071             spriteframe = 0;
1072             spriteframelabel = 0;
1073         }
1074         else if(tag->id == ST_END) {
1075             *prefix = 0;
1076             issprite = 0;
1077             spriteframelabel = 0;
1078             if(tag->len)
1079                 dumperror("End Tag not empty");
1080         }
1081         else if(tag->id == ST_EXPORTASSETS) {
1082             handleExportAssets(tag, myprefix);
1083         }
1084         else if(tag->id == ST_DOACTION && action) {
1085             ActionTAG*actions;
1086             actions = swf_ActionGet(tag);
1087             swf_DumpActions(actions, myprefix);
1088         }
1089         else if(tag->id == ST_DOINITACTION && action) {
1090             ActionTAG*actions;
1091             swf_GetU16(tag); // id
1092             actions = swf_ActionGet(tag);
1093             swf_DumpActions(actions, myprefix);
1094         }
1095         else if(tag->id == ST_DEFINEBUTTON && action) {
1096             dumpButtonActions(tag, myprefix);
1097         }
1098         else if(tag->id == ST_DEFINEBUTTON2 && action) {
1099             dumpButton2Actions(tag, myprefix);
1100         }
1101         else if(tag->id == ST_PLACEOBJECT) {
1102             handlePlaceObject(tag, myprefix);
1103         }
1104         else if(tag->id == ST_PLACEOBJECT2) {
1105             handlePlaceObject2(tag, myprefix);
1106         }
1107         else if(tag->id == ST_DEFINESHAPE ||
1108                 tag->id == ST_DEFINESHAPE2 ||
1109                 tag->id == ST_DEFINESHAPE3) {
1110             if(showshapes)
1111                 handleShape(tag, myprefix);
1112         }
1113
1114         if(tag->len && used) {
1115             int num = swf_GetNumUsedIDs(tag);
1116             int* used;
1117             int t;
1118             if(num) {
1119                 used = (int*)malloc(sizeof(int)*num);
1120                 swf_GetUsedIDs(tag, used);
1121                 printf("%s%suses IDs: ", indent, prefix);
1122                 for(t=0;t<num;t++) {
1123                     int id;
1124                     swf_SetTagPos(tag, used[t]);
1125                     id = swf_GetU16(tag);
1126                     printf("%d%s", id, t<num-1?", ":"");
1127                     if(!idtab[id]) {
1128                         dumperror("Id %04d is not yet defined.\n", id);
1129                     }
1130                 }
1131                 printf("\n");
1132             }
1133         }
1134
1135         if(tag->len && hex) {
1136             hexdumpTag(tag, prefix);
1137         }
1138         tag = tag->next;
1139         fflush(stdout);
1140     }
1141
1142     swf_FreeTags(&swf);
1143     return 0;
1144 }
1145
1146