fixed default behaviour
[swftools.git] / src / swfbbox.c
1 /* swfbbox.c
2    Tool for playing around with SWF bounding boxes.
3
4    Part of the swftools package.
5    
6    Copyright (c) 2003 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 #include <stdio.h>
24 #include <stdarg.h>
25 #include <assert.h>
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include "../lib/rfxswf.h"
29 #include "../lib/args.h"
30 #include "../lib/log.h"
31
32 static char * filename = 0;
33 static char * outfilename = "output.swf";
34 static int optimize = 0;
35 static int swifty = 0;
36 static int verbose = 0;
37 static int showbbox = 0;
38 static int showorigbbox = 1;
39 static int expand = 1;
40
41 static struct options_t options[] = {
42 {"h", "help"},
43 {"b", "bbox"},
44 {"B", "newbbox"},
45 {"e", "expand"},
46 {"O", "optimize"},
47 {"S", "swifty"},
48 {"o", "output"},
49 {"v", "verbose"},
50 {"V", "version"},
51 {0,0}
52 };
53
54 int args_callback_option(char*name,char*val)
55 {
56     if(!strcmp(name, "V")) {
57         printf("swfbbox - part of %s %s\n", PACKAGE, VERSION);
58         exit(0);
59     } 
60     else if(!strcmp(name, "b")) {
61         showorigbbox = 1;
62         if(showbbox == 1) showbbox = 0;
63         return 0;
64     } 
65     else if(!strcmp(name, "B")) {
66         showbbox = 2;
67         return 0;
68     } 
69     else if(!strcmp(name, "O")) {
70         optimize = 1;
71         if(showbbox == 1) showbbox = 0;
72         return 0;
73     } 
74     else if(!strcmp(name, "S")) {
75         swifty = 1;
76         if(showbbox == 1) showbbox = 0;
77         return 0;
78     } 
79     else if(!strcmp(name, "v")) {
80         verbose ++;
81         return 0;
82     } 
83     else if(!strcmp(name, "q")) {
84         verbose --;
85         return 0;
86     } 
87     else if(!strcmp(name, "e")) {
88         expand = 1;
89         return 0;
90     } 
91     else if(!strcmp(name, "o")) {
92         outfilename = val;
93         return 1;
94     } 
95     else {
96         printf("Unknown option: -%s\n", name);
97         exit(1);
98     }
99
100     return 0;
101 }
102 int args_callback_longoption(char*name,char*val)
103 {
104     return args_long2shortoption(options, name, val);
105 }
106 void args_callback_usage(char *name)
107 {
108     printf("\n");
109     printf("Usage: %s [-OS] file.swf\n", name);
110     printf("\n");
111     printf("-h , --help                    Print help and exit\n");
112     printf("-b , --bbox                    Show movie bounding box (default)\n");
113     printf("-B , --newbbox                 Show recalculated (optimized/expanded) bounding box\n");
114     printf("-e , --expand                  Write out a new file using the recalculated bounding box\n");
115     printf("-O , --optimize                Recalculate bounding boxes\n");
116     printf("-S , --swifty                  Print out transformed bounding boxes\n");
117     printf("-o , --output <filename>       Set output filename to <filename> (for -O)\n");
118     printf("-v , --verbose                 Be more verbose\n");
119     printf("-V , --version                 Print program version and exit\n");
120     printf("\n");
121 }
122 int args_callback_command(char*name,char*val)
123 {
124     if(filename) {
125         fprintf(stderr, "Only one file allowed. You supplied at least two. (%s and %s)\n",
126                  filename, name);
127     }
128     filename = name;
129     return 0;
130 }
131
132 #define swf_ResetReadBits(tag)   if (tag->readBit)  { tag->pos++; tag->readBit = 0; }
133
134 void swf_Shape2Optimize(SHAPE2*shape)
135 {
136     if(!shape->bbox)
137         shape->bbox = malloc(sizeof(SRECT));
138     *(shape->bbox) = swf_GetShapeBoundingBox(shape);
139 }
140
141 /*
142    {char {x1 y1 x2 y2 x3 y3 x4 y4]]
143 */
144
145 SRECT bboxes[65536];
146 U16 depth2id[65536];
147 char*depth2name[65536];
148
149 int hasid(TAG*tag)
150 {
151     if(tag->id == ST_PLACEOBJECT)
152         return 1;
153     if(tag->id == ST_PLACEOBJECT2 && (tag->data[0] & 2))
154         return 1;
155     return 0;
156 }
157
158 int hasname(TAG*tag)
159 {
160     if(tag->id == ST_PLACEOBJECT)
161         return 0;
162     if(tag->id == ST_PLACEOBJECT2 && (tag->data[0] & 0x20))
163         return 1;
164     return 0;
165 }
166
167 char* getname(TAG*tag)
168 {
169     if(tag->id == ST_PLACEOBJECT)
170         return 0;
171     if(tag->id == ST_PLACEOBJECT2 && (tag->data[0] & 0x20)) {
172         SWFPLACEOBJECT o;
173         tag->pos = 0;tag->readBit = 0;
174         swf_GetPlaceObject(tag, &o);
175         return o.name;
176     }
177     return 0;
178 }
179
180 MATRIX getmatrix(TAG*tag)
181 {
182     SWFPLACEOBJECT o;
183     tag->pos = 0;tag->readBit = 0;
184     swf_GetPlaceObject(tag, &o);
185     return o.matrix;
186 }
187
188
189 static int fontnum = -1;
190 static SWFFONT**fonts;
191 static SWF*c_swf;
192 static void fontcallback1(void*self, U16 id,U8 * name)
193 { fontnum++;
194 }
195 static void fontcallback2(void*self, U16 id,U8 * name)
196
197     fonts[fontnum] = 0;
198     swf_FontExtract(c_swf,id,&fonts[fontnum]);
199     if(verbose) {
200         if(fonts[fontnum]) printf("Extracting font %d (%s)\n", id, name);
201         else               printf("Extracting font %d (%s) failed\n", id, name);
202         fflush(stdout);
203     }
204     fontnum++;
205 }
206 typedef struct _textbounds
207 {
208     SRECT r;
209     MATRIX m; // character transform matrix
210 } textbounds_t;
211
212 static void textcallback(void*self, int*chars, int*xpos, int nr, int fontid, int fontsize, 
213                     int xstart, int ystart, RGBA* color)
214 {
215     textbounds_t * bounds = (textbounds_t*)self;
216     SWFFONT*font = 0;
217     int t;
218     for(t=0;t<fontnum;t++) {
219         if(fonts[t]->id == fontid) {
220             font = fonts[t];
221             break;
222         }
223     }
224     if(!font) {
225         fprintf(stderr, "Font %d unknown\n", fontid);
226         exit(1);
227     }
228     if(!font->layout) {
229         /* This is an expensive operation- but what should we do, we
230            need the glyph's bounding boxes */
231         swf_FontCreateLayout(font);
232     }
233
234     if(verbose)
235         printf("%d chars, font %d, size %d, at (%d,%d)\n", nr, fontid, fontsize, xstart, ystart);
236
237     for(t=0;t<nr;t++) {
238         /* not tested yet- the matrix/fontsize calculation is probably all wrong */
239         int x = xstart + xpos[t];
240         int y = ystart;
241         int ch;
242         SRECT newglyphbbox, glyphbbox = font->layout->bounds[chars[t]];
243         MATRIX m = bounds->m;
244         
245         if(chars[t] < font->numchars && font->glyph2ascii) {
246             ch = font->glyph2ascii[chars[t]];
247         }
248
249         m.sx = (m.sx * fontsize) / 1024;
250         m.sy = (m.sy * fontsize) / 1024;
251         m.r0 = (m.r0 * fontsize) / 1024;
252         m.r1 = (m.r1 * fontsize) / 1024;
253
254         m.tx += x;
255         m.ty += y;
256         newglyphbbox = swf_TurnRect(glyphbbox, &m);
257
258         if(ch<32) ch='?';
259             
260         swf_ExpandRect2(&(bounds->r), &newglyphbbox);
261         if(verbose >= 2) {
262             printf("%5d %c, %d %d %d %d (%d %d %d %d) -> %d %d %d %d\n", 
263                 xpos[t], ch, 
264                 glyphbbox.xmin, glyphbbox.ymin, glyphbbox.xmax, glyphbbox.ymax,
265                 newglyphbbox.xmin, newglyphbbox.ymin, newglyphbbox.xmax, newglyphbbox.ymax,
266                 bounds->r.xmin, bounds->r.ymin, bounds->r.xmax, bounds->r.ymax);
267         }
268
269     }
270 }
271
272 static void swf_OptimizeBoundingBoxes(SWF*swf)
273 {
274     TAG* tag = swf->firstTag;
275     
276     while (tag) {
277         if (tag->id == ST_DEFINESHAPE ||
278             tag->id == ST_DEFINESHAPE2 ||
279             tag->id == ST_DEFINESHAPE3) {
280             SHAPE2 s;
281             if(verbose) printf("%s\n", swf_TagGetName(tag));
282             swf_ParseDefineShape(tag, &s);
283             swf_Shape2Optimize(&s);
284             tag->len = 2;
285             tag->pos = 0;
286             swf_SetShape2(tag, &s);
287         }
288         if (tag->id == ST_DEFINETEXT || tag->id == ST_DEFINETEXT2) {
289             SRECT oldbox;
290             int matrix_offset;
291             int len;
292             U8*data;
293             textbounds_t bounds;
294             if(verbose) printf("%s\n", swf_TagGetName(tag));
295             if(fontnum < 0) {
296                 if(verbose) printf("Extracting fonts...\n");
297                 c_swf = swf;
298                 fontnum = 0;
299                 swf_FontEnumerate(swf,&fontcallback1,0);
300                 fonts = (SWFFONT**)malloc(fontnum*sizeof(SWFFONT*));
301                 memset(fonts, 0, fontnum*sizeof(SWFFONT*));
302                 fontnum = 0;
303                 swf_FontEnumerate(swf,&fontcallback2,0);
304             }
305
306             memset(&bounds, 0, sizeof(bounds));
307
308             swf_SetTagPos(tag, 0);
309             swf_GetU16(tag);
310             swf_GetRect(tag,&oldbox);
311             swf_ResetReadBits(tag);
312             matrix_offset = tag->pos;
313             swf_GetMatrix(tag,&bounds.m);
314             swf_ParseDefineText(tag, textcallback, &bounds);
315             if(verbose) {
316                 printf("\n");
317                 swf_DumpMatrix(stdout, &bounds.m);
318                 printf("old: %d %d %d %d\n", oldbox.xmin, oldbox.ymin, oldbox.xmax, oldbox.ymax);
319                 printf("new: %d %d %d %d\n", bounds.r.xmin, bounds.r.ymin, bounds.r.xmax, bounds.r.ymax);
320             }
321             
322             /* now comes the tricky part: 
323                we have to fiddle the data back in 
324                thank heavens that the bbox is follow by a matrix
325                struct, which always starts on a byte boundary.
326              */
327             len = tag->len - matrix_offset;
328             data = malloc(len);
329             memcpy(data, &tag->data[matrix_offset], len);
330             tag->writeBit = 0;
331             tag->len = 2;
332             swf_SetRect(tag, &bounds.r);
333             swf_SetBlock(tag, data, len);
334             free(data);
335             tag->pos = tag->readBit = 0;
336         }
337         tag = tag->next;
338     }
339 }
340
341 static void showSwiftyOutput(SWF*swf) 
342 {
343     TAG*tag = swf->firstTag;
344     int frame=0;
345     printf("{\n\t{frame %d}\n", frame++);
346
347     while (tag) {
348         if (tag->id == ST_SHOWFRAME) {
349             printf("}\n{\n\t{frame %d}\n", frame++);
350         }
351         if (tag->id == ST_PLACEOBJECT || tag->id == ST_PLACEOBJECT2) {
352             if(hasid(tag)) {
353                 depth2id[swf_GetDepth(tag)] = swf_GetPlaceID(tag);
354             }
355             if(hasname(tag)) {
356                 depth2name[swf_GetDepth(tag)] = getname(tag);
357             }
358         }
359         if (tag->id == ST_PLACEOBJECT || tag->id == ST_PLACEOBJECT2) {
360             MATRIX m = getmatrix(tag);
361             U16 id = depth2id[swf_GetDepth(tag)];
362             char*name = depth2name[swf_GetDepth(tag)];
363             char buf[40];
364             SRECT bbox = bboxes[id];
365             SPOINT p1,p2,p3,p4;
366             p1.x = bbox.xmin; p1.y = bbox.ymin;
367             p2.x = bbox.xmax; p2.y = bbox.ymin;
368             p3.x = bbox.xmin; p3.y = bbox.ymax;
369             p4.x = bbox.xmax; p4.y = bbox.ymax;
370             p1 = swf_TurnPoint(p1, &m);
371             p2 = swf_TurnPoint(p2, &m);
372             p3 = swf_TurnPoint(p3, &m);
373             p4 = swf_TurnPoint(p4, &m);
374             if(!name) {
375                 sprintf(buf, "ID%d", id);name = buf;
376             }
377             //printf("\t#%.4f %.4f %.4f %.4f | %.4f %.4f\n", m.sx/65536.0, m.r1/65536.0, m.r0/65536.0, m.sy/65536.0, m.tx/20.0, m.ty/20.0);
378             printf("\t{%s {%.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f}}\n", name, 
379                     p1.x/20.0, p1.y/20.0, p2.x/20.0, p2.y/20.0,
380                     p3.x/20.0, p3.y/20.0, p4.x/20.0, p4.y/20.0);
381         }
382         tag = tag->next;
383     }
384     printf("}\n");
385 }
386 static SRECT getMovieClipBBox(TAG*tag) 
387 {
388     //TAG*tag = swf->firstTag;
389     int frame=0;
390     SRECT movieSize;
391     U16 depth2id[65536];
392     memset(depth2id, 0, sizeof(depth2id));
393
394     memset(&movieSize,0,sizeof(SRECT));
395
396     while (tag->id != ST_END) {
397         if (tag->id == ST_PLACEOBJECT || tag->id == ST_PLACEOBJECT2) {
398             if(hasid(tag)) {
399                 depth2id[swf_GetDepth(tag)] = swf_GetPlaceID(tag);
400             }
401         }
402         if (tag->id == ST_PLACEOBJECT || tag->id == ST_PLACEOBJECT2) {
403             MATRIX m = getmatrix(tag);
404             U16 id = depth2id[swf_GetDepth(tag)];
405             SRECT bbox = bboxes[id];
406             
407             SRECT tbbox = swf_TurnRect(bbox, &m);
408             swf_ExpandRect2(&movieSize, &tbbox);
409         }
410         tag = tag->next;
411     }
412     return movieSize;
413 }
414
415 static SRECT getSWFBBox(SWF*swf)
416 {
417     SRECT movieSize = getMovieClipBBox(swf->firstTag);
418     
419     return movieSize;
420 }
421
422 int main (int argc,char ** argv)
423
424     TAG*tag;
425     SWF swf;
426     int fi;
427     SRECT oldMovieSize;
428     SRECT newMovieSize;
429     memset(bboxes, 0, sizeof(bboxes));
430     memset(depth2name, 0, sizeof(depth2name));
431
432     processargs(argc, argv);
433     initLog(0,0,0,0,0,verbose?LOGLEVEL_DEBUG:LOGLEVEL_WARNING);
434
435     if(!filename) {
436         fprintf(stderr, "You must supply a filename.\n");
437         return 1;
438     }
439
440     fi = open(filename,O_RDONLY|O_BINARY);
441
442     if (fi<0)
443     { 
444         perror("Couldn't open file: ");
445         exit(1);
446     }
447     if FAILED(swf_ReadSWF(fi,&swf))
448     { 
449         fprintf(stderr, "%s is not a valid SWF file or contains errors.\n",filename);
450         close(fi);
451         exit(1);
452     }
453     close(fi);
454
455     swf_OptimizeTagOrder(&swf);
456     swf_FoldAll(&swf);
457
458     /* Optimize bounding boxes in case -O flag was set */
459     if(optimize) {
460         swf_OptimizeBoundingBoxes(&swf);
461     }
462     
463     /* Create an ID to Bounding Box table */
464     tag = swf.firstTag;
465     while (tag) {
466         if(swf_isDefiningTag(tag)) {
467             int id = swf_GetDefineID(tag);
468             if(tag->id != ST_DEFINESPRITE) {
469                 bboxes[id] = swf_GetDefineBBox(tag);
470             } else {
471                 swf_UnFoldSprite(tag);
472                 bboxes[id] = getMovieClipBBox(tag);
473                 swf_FoldSprite(tag);
474                 if(verbose) {
475                     printf("sprite %d is %.2fx%.2f\n", id, 
476                             (bboxes[id].xmax - bboxes[id].xmin)/20.0,
477                             (bboxes[id].ymax - bboxes[id].ymin)/20.0);
478                 }
479             }
480         }
481         tag = tag->next;
482     }
483     
484     /* Create an ID->Bounding Box table for all bounding boxes */
485     if(swifty) {
486         showSwiftyOutput(&swf);
487     }
488
489     oldMovieSize = swf.movieSize;
490     newMovieSize = getSWFBBox(&swf);
491
492     if(optimize || expand) {
493
494         if(expand)
495             swf.movieSize = newMovieSize;
496
497         fi = open(outfilename, O_BINARY | O_RDWR | O_CREAT | O_TRUNC, 0666);
498         if(swf_WriteSWF(fi, &swf) < 0) {
499             fprintf(stderr, "Error writing file %s", outfilename);
500             close(fi);
501             exit(1);
502         }
503         close(fi);
504     }
505     
506     if(showbbox) {
507         if(verbose>=0)
508             printf("Real Movie Size: ");
509         printf("%.2f x %.2f :%.2f :%.2f\n", 
510                 (newMovieSize.xmax-newMovieSize.xmin)/20.0,
511                 (newMovieSize.ymax-newMovieSize.ymin)/20.0,
512                 (newMovieSize.xmin)/20.0,
513                 (newMovieSize.ymin)/20.0
514                 );
515     }
516     if(showorigbbox) {
517         if(verbose>=0)
518             printf("Original Movie Size: ");
519         printf("%.2f x %.2f :%.2f :%.2f\n", 
520                 (oldMovieSize.xmax-oldMovieSize.xmin)/20.0,
521                 (oldMovieSize.ymax-oldMovieSize.ymin)/20.0,
522                 (oldMovieSize.xmin)/20.0,
523                 (oldMovieSize.ymin)/20.0
524                 );
525     }
526
527     swf_FreeTags(&swf);
528     return 0;
529 }