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