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