added -C doc
[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 = 0;
40 static int clip = 0;
41
42 static struct options_t options[] = {
43 {"h", "help"},
44 {"b", "bbox"},
45 {"B", "newbbox"},
46 {"e", "expand"},
47 {"O", "optimize"},
48 {"S", "swifty"},
49 {"c", "clip"},
50 {"o", "output"},
51 {"v", "verbose"},
52 {"V", "version"},
53 {0,0}
54 };
55
56 int args_callback_option(char*name,char*val)
57 {
58     if(!strcmp(name, "V")) {
59         printf("swfbbox - part of %s %s\n", PACKAGE, VERSION);
60         exit(0);
61     } 
62     else if(!strcmp(name, "b")) {
63         showorigbbox = 2;
64         if(showbbox == 1) showbbox = 0;
65         return 0;
66     } 
67     else if(!strcmp(name, "B")) {
68         showbbox = 2;
69         return 0;
70     } 
71     else if(!strcmp(name, "O")) {
72         optimize = 1;
73         if(showorigbbox == 1) showorigbbox = 0;
74         return 0;
75     } 
76     else if(!strcmp(name, "S")) {
77         swifty = 1;
78         if(showorigbbox == 1) showorigbbox = 0;
79         return 0;
80     } 
81     else if(!strcmp(name, "c")) {
82         if(showorigbbox == 1) showorigbbox = 0;
83         optimize = 1;
84         clip = 1;
85         return 0;
86     } 
87     else if(!strcmp(name, "v")) {
88         verbose ++;
89         return 0;
90     } 
91     else if(!strcmp(name, "q")) {
92         verbose --;
93         return 0;
94     } 
95     else if(!strcmp(name, "e")) {
96         expand = 1;
97         return 0;
98     } 
99     else if(!strcmp(name, "o")) {
100         outfilename = val;
101         return 1;
102     } 
103     else {
104         printf("Unknown option: -%s\n", name);
105         exit(1);
106     }
107
108     return 0;
109 }
110 int args_callback_longoption(char*name,char*val)
111 {
112     return args_long2shortoption(options, name, val);
113 }
114 void args_callback_usage(char *name)
115 {
116     printf("\n");
117     printf("Usage: %s [-OS] file.swf\n", name);
118     printf("\n");
119     printf("-h , --help                    Print help and exit\n");
120     printf("-b , --bbox                    Show movie bounding box (default)\n");
121     printf("-B , --newbbox                 Show recalculated (optimized/expanded) bounding box\n");
122     printf("-e , --expand                  Write out a new file using the recalculated bounding box\n");
123     printf("-O , --optimize                Recalculate bounding boxes\n");
124     printf("-S , --swifty                  Print out transformed bounding boxes\n");
125     printf("-c , --clip                    Clip bounding boxes to movie size\n");
126     printf("-o , --output <filename>       Set output filename to <filename> (for -O)\n");
127     printf("-v , --verbose                 Be more verbose\n");
128     printf("-V , --version                 Print program version and exit\n");
129     printf("\n");
130 }
131 int args_callback_command(char*name,char*val)
132 {
133     if(filename) {
134         fprintf(stderr, "Only one file allowed. You supplied at least two. (%s and %s)\n",
135                  filename, name);
136     }
137     filename = name;
138     return 0;
139 }
140
141 #define swf_ResetReadBits(tag)   if (tag->readBit)  { tag->pos++; tag->readBit = 0; }
142
143 void swf_Shape2Optimize(SHAPE2*shape)
144 {
145     if(!shape->bbox)
146         shape->bbox = malloc(sizeof(SRECT));
147     *(shape->bbox) = swf_GetShapeBoundingBox(shape);
148 }
149
150 /*
151    {char {x1 y1 x2 y2 x3 y3 x4 y4]]
152 */
153
154 SRECT bboxes[65536];
155 U16 depth2id[65536];
156 char*depth2name[65536];
157
158 int hasid(TAG*tag)
159 {
160     if(tag->id == ST_PLACEOBJECT)
161         return 1;
162     if(tag->id == ST_PLACEOBJECT2 && (tag->data[0] & 2))
163         return 1;
164     return 0;
165 }
166
167 int hasname(TAG*tag)
168 {
169     if(tag->id == ST_PLACEOBJECT)
170         return 0;
171     if(tag->id == ST_PLACEOBJECT2 && (tag->data[0] & 0x20))
172         return 1;
173     return 0;
174 }
175
176 char* getname(TAG*tag)
177 {
178     if(tag->id == ST_PLACEOBJECT)
179         return 0;
180     if(tag->id == ST_PLACEOBJECT2 && (tag->data[0] & 0x20)) {
181         SWFPLACEOBJECT o;
182         tag->pos = 0;tag->readBit = 0;
183         swf_GetPlaceObject(tag, &o);
184         return o.name;
185     }
186     return 0;
187 }
188
189 MATRIX getmatrix(TAG*tag)
190 {
191     SWFPLACEOBJECT o;
192     tag->pos = 0;tag->readBit = 0;
193     swf_GetPlaceObject(tag, &o);
194     return o.matrix;
195 }
196
197
198 static int fontnum = -1;
199 static SWFFONT**fonts;
200 static SWF*c_swf;
201 static void fontcallback1(void*self, U16 id,U8 * name)
202 { fontnum++;
203 }
204 static void fontcallback2(void*self, U16 id,U8 * name)
205
206     fonts[fontnum] = 0;
207     swf_FontExtract(c_swf,id,&fonts[fontnum]);
208     if(verbose) {
209         if(fonts[fontnum]) printf("Extracting font %d (%s)\n", id, name);
210         else               printf("Extracting font %d (%s) failed\n", id, name);
211         fflush(stdout);
212     }
213     fontnum++;
214 }
215 typedef struct _textbounds
216 {
217     SRECT r;
218     MATRIX m; // character transform matrix
219 } textbounds_t;
220
221 typedef struct _placement
222 {
223     SWFPLACEOBJECT* po;
224     int num;
225 } placement_t;
226
227 static placement_t* placements;
228
229 static placement_t* readPlacements(SWF*swf)
230 {
231     placement_t* p = (placement_t*)rfx_calloc(sizeof(placement_t)*65536);
232     TAG*tag = swf->firstTag;
233     while(tag) {
234         if(tag->id == ST_PLACEOBJECT || tag->id == ST_PLACEOBJECT2) {
235             SWFPLACEOBJECT*po = rfx_alloc(sizeof(SWFPLACEOBJECT));
236             int id;
237             swf_GetPlaceObject(tag, po);
238             id = po->id;
239             if(po->move) {
240                 fprintf(stderr, "MOVE tags not supported with -c");
241             }
242             p[id].po = po;
243             p[id].num++;
244         }
245         tag = tag->next;
246     }
247
248     return p;
249 }
250
251 static void freePlacements(placement_t*p)
252 {
253     int t;
254     for(t=0;t<65536;t++) {
255         if(p[t].po) {
256             swf_PlaceObjectFree(p[t].po); p[t].po = 0;
257         }
258     }
259     rfx_free(p);
260 }
261
262 SRECT swf_ClipRect(SRECT border, SRECT r)
263 {
264     if(r.xmax > border.xmax) r.xmax = border.xmax;
265     if(r.ymax > border.ymax) r.ymax = border.ymax;
266     if(r.xmax < border.xmin) r.xmax = border.xmin;
267     if(r.ymax < border.ymin) r.ymax = border.ymin;
268     
269     if(r.xmin > border.xmax) r.xmin = border.xmax;
270     if(r.ymin > border.ymax) r.ymin = border.ymax;
271     if(r.xmin < border.xmin) r.xmin = border.xmin;
272     if(r.ymin < border.ymin) r.ymin = border.ymin;
273     return r;
274 }
275
276 static SRECT clipBBox(TAG*tag, SRECT mbbox, SRECT r)
277 {
278     int id = swf_GetDefineID(tag);
279     MATRIX m;
280     if(!placements[id].po) {
281         if(verbose)
282             printf("Id %d is never set\n", id);
283         return r;
284     }
285     if(placements[id].num>1) {
286         if(verbose)
287             printf("Id %d is set more than once\n", id);
288         return r;
289     }
290     m = placements[id].po->matrix;
291     if(m.r0 || m.r1)  {
292         fprintf(stderr, "Rotating PLACEOBJECTS are not supported with -c\n");
293         return r;
294     }
295
296     printf("ID %d\n", id);
297     swf_DumpMatrix(stdout, &m);
298     mbbox.xmin -= m.tx;
299     mbbox.ymin -= m.ty;
300     mbbox.xmax -= m.tx;
301     mbbox.ymax -= m.ty;
302     mbbox.xmin *= 65536.0/m.sx;
303     mbbox.xmax *= 65536.0/m.sx;
304     mbbox.ymin *= 65536.0/m.sy;
305     mbbox.ymax *= 65536.0/m.sy;
306     
307     printf("border: %f/%f/%f/%f - rect: %f/%f/%f/%f\n",
308             mbbox.xmin /20.0,
309             mbbox.ymin /20.0,
310             mbbox.xmax /20.0,
311             mbbox.ymax /20.0,
312             r.xmin /20.0,
313             r.ymin /20.0,
314             r.xmax /20.0,
315             r.ymax /20.0);
316     
317
318     r = swf_ClipRect(mbbox, r);
319     
320     printf("new rect: %f/%f/%f/%f\n",
321             r.xmin /20.0,
322             r.ymin /20.0,
323             r.xmax /20.0,
324             r.ymax /20.0);
325
326     return r;
327 }
328
329
330 static void textcallback(void*self, int*chars, int*xpos, int nr, int fontid, int fontsize, 
331                     int xstart, int ystart, RGBA* color)
332 {
333     textbounds_t * bounds = (textbounds_t*)self;
334     SWFFONT*font = 0;
335     int t;
336     for(t=0;t<fontnum;t++) {
337         if(fonts[t]->id == fontid) {
338             font = fonts[t];
339             break;
340         }
341     }
342     if(!font) {
343         fprintf(stderr, "Font %d unknown\n", fontid);
344         exit(1);
345     }
346     if(!font->layout) {
347         /* This is an expensive operation- but what should we do, we
348            need the glyph's bounding boxes */
349         swf_FontCreateLayout(font);
350     }
351
352     if(verbose)
353         printf("%d chars, font %d, size %d, at (%d,%d)\n", nr, fontid, fontsize, xstart, ystart);
354
355     for(t=0;t<nr;t++) {
356         /* not tested yet- the matrix/fontsize calculation is probably all wrong */
357         int x = xstart + xpos[t];
358         int y = ystart;
359         int ch = 0;
360         SRECT newglyphbbox, glyphbbox = font->layout->bounds[chars[t]];
361         MATRIX m = bounds->m;
362         SPOINT p;
363
364         if(chars[t] < font->numchars && font->glyph2ascii) {
365             ch = font->glyph2ascii[chars[t]];
366         }
367
368         p.x = x; p.y = y;
369         p = swf_TurnPoint(p, &m);
370
371         m.sx = (m.sx * fontsize) / 1024;
372         m.sy = (m.sy * fontsize) / 1024;
373         m.r0 = (m.r0 * fontsize) / 1024;
374         m.r1 = (m.r1 * fontsize) / 1024;
375
376         m.tx += p.x;
377         m.ty += p.y;
378         newglyphbbox = swf_TurnRect(glyphbbox, &m);
379
380         if(ch<32) ch='?';
381             
382         swf_ExpandRect2(&(bounds->r), &newglyphbbox);
383         if(verbose >= 2) {
384             printf("%5d %c, %d %d %d %d (%d %d %d %d) -> %d %d %d %d\n", 
385                 xpos[t], ch, 
386                 glyphbbox.xmin, glyphbbox.ymin, glyphbbox.xmax, glyphbbox.ymax,
387                 newglyphbbox.xmin, newglyphbbox.ymin, newglyphbbox.xmax, newglyphbbox.ymax,
388                 bounds->r.xmin, bounds->r.ymin, bounds->r.xmax, bounds->r.ymax);
389         }
390
391     }
392 }
393
394 static void swf_OptimizeBoundingBoxes(SWF*swf)
395 {
396     TAG* tag = swf->firstTag;
397     
398     while (tag) {
399         if (tag->id == ST_DEFINESHAPE ||
400             tag->id == ST_DEFINESHAPE2 ||
401             tag->id == ST_DEFINESHAPE3) {
402             SHAPE2 s;
403             if(verbose) printf("%s\n", swf_TagGetName(tag));
404             swf_ParseDefineShape(tag, &s);
405             swf_Shape2Optimize(&s);
406             tag->len = 2;
407             tag->pos = 0;
408             if(!s.bbox) {
409                 fprintf(stderr, "Internal error (5)\n");
410                 exit(1);
411             }
412             if(clip) {
413                 *s.bbox = clipBBox(tag, swf->movieSize, *s.bbox);
414             }
415             swf_SetShape2(tag, &s);
416         }
417         if (tag->id == ST_DEFINETEXT || tag->id == ST_DEFINETEXT2) {
418             SRECT oldbox;
419             int matrix_offset;
420             int len;
421             U8*data;
422             textbounds_t bounds;
423             if(verbose) printf("%s\n", swf_TagGetName(tag));
424             if(fontnum < 0) {
425                 if(verbose) printf("Extracting fonts...\n");
426                 c_swf = swf;
427                 fontnum = 0;
428                 swf_FontEnumerate(swf,&fontcallback1,0);
429                 fonts = (SWFFONT**)malloc(fontnum*sizeof(SWFFONT*));
430                 memset(fonts, 0, fontnum*sizeof(SWFFONT*));
431                 fontnum = 0;
432                 swf_FontEnumerate(swf,&fontcallback2,0);
433             }
434
435             memset(&bounds, 0, sizeof(bounds));
436
437             swf_SetTagPos(tag, 0);
438             swf_GetU16(tag);
439             swf_GetRect(tag,&oldbox);
440             swf_ResetReadBits(tag);
441             matrix_offset = tag->pos;
442             swf_GetMatrix(tag,&bounds.m);
443             swf_ParseDefineText(tag, textcallback, &bounds);
444             if(verbose) {
445                 printf("\n");
446                 swf_DumpMatrix(stdout, &bounds.m);
447                 printf("old: %d %d %d %d\n", oldbox.xmin, oldbox.ymin, oldbox.xmax, oldbox.ymax);
448                 printf("new: %d %d %d %d\n", bounds.r.xmin, bounds.r.ymin, bounds.r.xmax, bounds.r.ymax);
449             }
450             if(clip) {
451                 bounds.r = clipBBox(tag, swf->movieSize, bounds.r);
452             }
453             
454             /* now comes the tricky part: 
455                we have to fiddle the data back in 
456                thank heavens that the bbox is follow by a matrix
457                struct, which always starts on a byte boundary.
458              */
459             len = tag->len - matrix_offset;
460             data = malloc(len);
461             memcpy(data, &tag->data[matrix_offset], len);
462             tag->writeBit = 0;
463             tag->len = 2;
464             swf_SetRect(tag, &bounds.r);
465             swf_SetBlock(tag, data, len);
466             free(data);
467             tag->pos = tag->readBit = 0;
468         }
469         tag = tag->next;
470     }
471 }
472
473 static void showSwiftyOutput(SWF*swf) 
474 {
475     TAG*tag = swf->firstTag;
476     int frame=0;
477     printf("{\n\t{frame %d}\n", frame++);
478
479     while (tag) {
480         if (tag->id == ST_SHOWFRAME) {
481             printf("}\n{\n\t{frame %d}\n", frame++);
482         }
483         if (tag->id == ST_PLACEOBJECT || tag->id == ST_PLACEOBJECT2) {
484             if(hasid(tag)) {
485                 depth2id[swf_GetDepth(tag)] = swf_GetPlaceID(tag);
486             }
487             if(hasname(tag)) {
488                 depth2name[swf_GetDepth(tag)] = getname(tag);
489             }
490         }
491         if (tag->id == ST_PLACEOBJECT || tag->id == ST_PLACEOBJECT2) {
492             MATRIX m = getmatrix(tag);
493             U16 id = depth2id[swf_GetDepth(tag)];
494             char*name = depth2name[swf_GetDepth(tag)];
495             char buf[40];
496             SRECT bbox = bboxes[id];
497             SPOINT p1,p2,p3,p4;
498             p1.x = bbox.xmin; p1.y = bbox.ymin;
499             p2.x = bbox.xmax; p2.y = bbox.ymin;
500             p3.x = bbox.xmin; p3.y = bbox.ymax;
501             p4.x = bbox.xmax; p4.y = bbox.ymax;
502             p1 = swf_TurnPoint(p1, &m);
503             p2 = swf_TurnPoint(p2, &m);
504             p3 = swf_TurnPoint(p3, &m);
505             p4 = swf_TurnPoint(p4, &m);
506             if(!name) {
507                 sprintf(buf, "ID%d", id);name = buf;
508             }
509             //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);
510             printf("\t{%s {%.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f}}\n", name, 
511                     p1.x/20.0, p1.y/20.0, p2.x/20.0, p2.y/20.0,
512                     p3.x/20.0, p3.y/20.0, p4.x/20.0, p4.y/20.0);
513         }
514         tag = tag->next;
515     }
516     printf("}\n");
517 }
518 static SRECT getMovieClipBBox(TAG*tag) 
519 {
520     //TAG*tag = swf->firstTag;
521     int frame=0;
522     SRECT movieSize;
523     U16 depth2id[65536];
524     memset(depth2id, 0, sizeof(depth2id));
525
526     memset(&movieSize,0,sizeof(SRECT));
527
528     while (tag->id != ST_END) {
529         if (tag->id == ST_PLACEOBJECT || tag->id == ST_PLACEOBJECT2) {
530             if(hasid(tag)) {
531                 depth2id[swf_GetDepth(tag)] = swf_GetPlaceID(tag);
532             }
533         }
534         if (tag->id == ST_PLACEOBJECT || tag->id == ST_PLACEOBJECT2) {
535             MATRIX m = getmatrix(tag);
536             U16 id = depth2id[swf_GetDepth(tag)];
537             SRECT bbox = bboxes[id];
538             
539             SRECT tbbox = swf_TurnRect(bbox, &m);
540             swf_ExpandRect2(&movieSize, &tbbox);
541         }
542         tag = tag->next;
543     }
544     return movieSize;
545 }
546
547 static SRECT getSWFBBox(SWF*swf)
548 {
549     SRECT movieSize = getMovieClipBBox(swf->firstTag);
550     
551     return movieSize;
552 }
553
554 int main (int argc,char ** argv)
555
556     TAG*tag;
557     SWF swf;
558     int fi;
559     SRECT oldMovieSize;
560     SRECT newMovieSize;
561     memset(bboxes, 0, sizeof(bboxes));
562     memset(depth2name, 0, sizeof(depth2name));
563
564     processargs(argc, argv);
565     initLog(0,0,0,0,0,verbose?LOGLEVEL_DEBUG:LOGLEVEL_WARNING);
566
567     if(!filename) {
568         fprintf(stderr, "You must supply a filename.\n");
569         return 1;
570     }
571
572     fi = open(filename,O_RDONLY|O_BINARY);
573
574     if (fi<0)
575     { 
576         perror("Couldn't open file: ");
577         exit(1);
578     }
579     if FAILED(swf_ReadSWF(fi,&swf))
580     { 
581         fprintf(stderr, "%s is not a valid SWF file or contains errors.\n",filename);
582         close(fi);
583         exit(1);
584     }
585     close(fi);
586
587     swf_OptimizeTagOrder(&swf);
588
589     if(clip) {
590         placements = readPlacements(&swf);
591     }
592
593     swf_FoldAll(&swf);
594
595     /* Optimize bounding boxes in case -O flag was set */
596     if(optimize) {
597         swf_OptimizeBoundingBoxes(&swf);
598     }
599     
600     /* Create an ID to Bounding Box table */
601     tag = swf.firstTag;
602     while (tag) {
603         if(swf_isDefiningTag(tag)) {
604             int id = swf_GetDefineID(tag);
605             if(tag->id != ST_DEFINESPRITE) {
606                 bboxes[id] = swf_GetDefineBBox(tag);
607             } else {
608                 swf_UnFoldSprite(tag);
609                 bboxes[id] = getMovieClipBBox(tag);
610                 swf_FoldSprite(tag);
611                 if(verbose) {
612                     printf("sprite %d is %.2fx%.2f\n", id, 
613                             (bboxes[id].xmax - bboxes[id].xmin)/20.0,
614                             (bboxes[id].ymax - bboxes[id].ymin)/20.0);
615                 }
616             }
617         }
618         tag = tag->next;
619     }
620     
621     /* Create an ID->Bounding Box table for all bounding boxes */
622     if(swifty) {
623         showSwiftyOutput(&swf);
624     }
625
626     oldMovieSize = swf.movieSize;
627     newMovieSize = getSWFBBox(&swf);
628
629     if(optimize || expand) {
630
631         if(expand)
632             swf.movieSize = newMovieSize;
633
634         fi = open(outfilename, O_BINARY | O_RDWR | O_CREAT | O_TRUNC, 0666);
635         if(swf_WriteSWF(fi, &swf) < 0) {
636             fprintf(stderr, "Error writing file %s", outfilename);
637             close(fi);
638             exit(1);
639         }
640         close(fi);
641     }
642     
643     if(showbbox) {
644         if(verbose>=0)
645             printf("Real Movie Size: ");
646         printf("%.2f x %.2f :%.2f :%.2f\n", 
647                 (newMovieSize.xmax-newMovieSize.xmin)/20.0,
648                 (newMovieSize.ymax-newMovieSize.ymin)/20.0,
649                 (newMovieSize.xmin)/20.0,
650                 (newMovieSize.ymin)/20.0
651                 );
652     }
653     if(showorigbbox) {
654         if(verbose>=0)
655             printf("Original Movie Size: ");
656         printf("%.2f x %.2f :%.2f :%.2f\n", 
657                 (oldMovieSize.xmax-oldMovieSize.xmin)/20.0,
658                 (oldMovieSize.ymax-oldMovieSize.ymin)/20.0,
659                 (oldMovieSize.xmin)/20.0,
660                 (oldMovieSize.ymin)/20.0
661                 );
662     }
663
664     swf_FreeTags(&swf);
665
666     if(placements) {
667         freePlacements(placements);
668     }
669     return 0;
670 }