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