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