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