updated/corrected documentation
[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 = 1;
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         swf_ResetReadBits(tag);
132         type = swf_GetU8(tag); //type
133         shape->fillstyles[t].type = type;
134         if(type == 0) {
135             /* plain color */
136             if(num == 3)
137                 swf_GetRGBA(tag, &dest->color);
138             else 
139                 swf_GetRGB(tag, &dest->color);
140         }
141         else if(type == 0x10 || type == 0x12)
142         {
143             /* linear/radial gradient fill */
144             swf_ResetReadBits(tag);
145             swf_GetMatrix(tag, &dest->m);
146             swf_ResetReadBits(tag);
147             swf_GetGradient(tag, &dest->gradient, num>=3?1:0);
148         }
149         else if(type == 0x40 || type == 0x41)
150         {
151             /* bitmap fill */
152             swf_ResetReadBits(tag);
153             dest->id_bitmap = swf_GetU16(tag); //id
154             swf_ResetReadBits(tag); //?
155             swf_GetMatrix(tag, &dest->m);
156         }
157         else {
158             fprintf(stderr, "rfxswf:swftools.c Unknown fillstyle:0x%02x\n",type);
159         }
160     }
161     swf_ResetReadBits(tag);
162     count = swf_GetU8(tag); // line style array
163     if(count == 0xff)
164         count = swf_GetU16(tag);
165
166     if(verbose) printf("lnum: %d\n", count);
167
168     shape->numlinestyles = count;
169     shape->linestyles = malloc(sizeof(LINESTYLE)*count);
170     /* TODO: should we start with 1 and insert a correct definition of the
171        "built in" linestyle 0? */
172     for(t=0;t<count;t++) 
173     {
174         shape->linestyles[t].width = swf_GetU16(tag);
175         if(num == 3)
176             swf_GetRGBA(tag, &shape->linestyles[t].color);
177         else
178             swf_GetRGB(tag, &shape->linestyles[t].color);
179     }
180     return;
181 }
182
183 void swf_ParseDefineShape(TAG*tag, SHAPE2*shape)
184 {
185     int num = 0, id;
186     U16 fill,line;
187     SRECT r;
188     SRECT r2;
189     SHAPELINE*l;
190     if(tag->id == ST_DEFINESHAPE)
191         num = 1;
192     else if(tag->id == ST_DEFINESHAPE2)
193         num = 2;
194     else if(tag->id == ST_DEFINESHAPE3)
195         num = 3;
196     else {
197         fprintf(stderr, "parseDefineShape must be called with a shape tag");
198     }
199
200     id = swf_GetU16(tag); //id
201     memset(shape, 0, sizeof(SHAPE2));
202     shape->bbox = malloc(sizeof(SRECT));
203     swf_GetRect(tag, &r);
204
205     memcpy(shape->bbox, &r, sizeof(SRECT));
206     parseFillStyleArray(tag, shape);
207
208     swf_ResetReadBits(tag); 
209     fill = (U16)swf_GetBits(tag,4);
210     line = (U16)swf_GetBits(tag,4);
211
212     shape->lines = swf_ParseShapeData(&tag->data[tag->pos], (tag->len - tag->pos)*8, fill, line);
213
214     l = shape->lines;
215 }
216
217 void swf_Shape2Optimize(SHAPE2*shape)
218 {
219     if(!shape->bbox)
220         shape->bbox = malloc(sizeof(SRECT));
221     *(shape->bbox) = swf_GetShapeBoundingBox(shape);
222 }
223
224 void swf_Shape2ToShape(SHAPE2*shape2, SHAPE*shape)
225 {
226     TAG*tag = swf_InsertTag(0,0);
227     SHAPELINE*l,*next;
228     int newx=0,newy=0,lastx=0,lasty=0,oldls=0,oldfs0=0,oldfs1=0;
229
230     memset(shape, 0, sizeof(SHAPE));
231
232     shape->linestyle.n = shape2->numlinestyles;
233     shape->linestyle.data = (LINESTYLE*)malloc(sizeof(LINESTYLE)*shape->linestyle.n);
234     memcpy(shape->linestyle.data, shape2->linestyles, sizeof(LINESTYLE)*shape->linestyle.n);
235     
236     shape->fillstyle.n =  shape2->numfillstyles;
237     shape->fillstyle.data = (FILLSTYLE*)malloc(sizeof(FILLSTYLE)*shape->fillstyle.n);
238     memcpy(shape->fillstyle.data, shape2->fillstyles, sizeof(FILLSTYLE)*shape->fillstyle.n);
239
240     swf_ShapeCountBits(shape,NULL,NULL);
241
242     l = shape2->lines;
243
244     while(l) {
245         int ls=0,fs0=0,fs1=0;
246
247         if(l->type != moveTo) {
248             if(oldls != l->linestyle) {oldls = ls = l->linestyle;if(!ls) ls=0x8000;}
249             if(oldfs0 != l->fillstyle0) {oldfs0 = fs0 = l->fillstyle0;if(!fs0) fs0=0x8000;}
250             if(oldfs1 != l->fillstyle1) {oldfs1 = fs1 = l->fillstyle1;if(!fs1) fs1=0x8000;}
251
252             if(ls || fs0 || fs1 || newx!=0x7fffffff || newy!=0x7fffffff) {
253                 swf_ShapeSetAll(tag,shape,newx,newy,ls,fs0,fs1);
254                 newx = 0x7fffffff;
255                 newy = 0x7fffffff;
256             }
257         }
258
259         if(l->type == lineTo) {
260             swf_ShapeSetLine(tag,shape,l->x-lastx,l->y-lasty);
261         } else if(l->type == splineTo) {
262             swf_ShapeSetCurve(tag,shape, l->sx-lastx,l->sy-lasty, l->x-l->sx,l->y-l->sy);
263         }
264         if(l->type == moveTo) {
265             newx = l->x;
266             newy = l->y;
267         }
268
269         lastx = l->x;
270         lasty = l->y;
271         l = l->next;
272     }
273     swf_ShapeSetEnd(tag);
274     shape->data = tag->data;
275     shape->bitlen = tag->len*8;
276 }
277
278 void swf_SetShape2(TAG*tag, SHAPE2*shape2)
279 {
280     SHAPE shape;
281     swf_Shape2ToShape(shape2, &shape);
282
283     swf_SetRect(tag,shape2->bbox);
284     swf_SetShapeStyles(tag, &shape);
285     swf_ShapeCountBits(&shape,NULL,NULL);
286     swf_SetShapeBits(tag,&shape);
287
288     swf_SetBlock(tag, shape.data, (shape.bitlen+7)/8);
289 }
290
291 /*
292    {char {x1 y1 x2 y2 x3 y3 x4 y4]]
293 */
294
295 SRECT bboxes[65536];
296 U16 depth2id[65536];
297 char*depth2name[65536];
298
299 int hasid(TAG*tag)
300 {
301     if(tag->id == ST_PLACEOBJECT)
302         return 1;
303     if(tag->id == ST_PLACEOBJECT2 && (tag->data[0] & 2))
304         return 1;
305     return 0;
306 }
307
308 int hasname(TAG*tag)
309 {
310     if(tag->id == ST_PLACEOBJECT)
311         return 0;
312     if(tag->id == ST_PLACEOBJECT2 && (tag->data[0] & 0x20))
313         return 1;
314     return 0;
315 }
316
317 char* getname(TAG*tag)
318 {
319     if(tag->id == ST_PLACEOBJECT)
320         return 0;
321     if(tag->id == ST_PLACEOBJECT2 && (tag->data[0] & 0x20)) {
322         SWFPLACEOBJECT o;
323         tag->pos = 0;tag->readBit = 0;
324         swf_GetPlaceObject(tag, &o);
325         return o.name;
326     }
327     return 0;
328 }
329
330 MATRIX getmatrix(TAG*tag)
331 {
332     SWFPLACEOBJECT o;
333     tag->pos = 0;tag->readBit = 0;
334     swf_GetPlaceObject(tag, &o);
335     return o.matrix;
336 }
337
338 static void swf_OptimizeBoundingBoxes(SWF*swf)
339 {
340     TAG* tag = swf->firstTag;
341     while (tag) {
342         if (tag->id == ST_DEFINESHAPE ||
343             tag->id == ST_DEFINESHAPE2 ||
344             tag->id == ST_DEFINESHAPE3) {
345             SHAPE2 s;
346             if(verbose) printf("%s\n", swf_TagGetName(tag));
347             swf_ParseDefineShape(tag, &s);
348             swf_Shape2Optimize(&s);
349             tag->len = 2;
350             tag->pos = 0;
351             swf_SetShape2(tag, &s);
352         }
353     }
354 }
355
356 static void showSwiftyOutput(SWF*swf) 
357 {
358     TAG*tag = swf->firstTag;
359     int frame=0;
360     printf("{\n\t{frame %d}\n", frame++);
361
362     while (tag) {
363         if (tag->id == ST_SHOWFRAME) {
364             printf("}\n{\n\t{frame %d}\n", frame++);
365         }
366         if (tag->id == ST_PLACEOBJECT || tag->id == ST_PLACEOBJECT2) {
367             if(hasid(tag)) {
368                 depth2id[swf_GetDepth(tag)] = swf_GetPlaceID(tag);
369             }
370             if(hasname(tag)) {
371                 depth2name[swf_GetDepth(tag)] = getname(tag);
372             }
373         }
374         if (tag->id == ST_PLACEOBJECT || tag->id == ST_PLACEOBJECT2) {
375             MATRIX m = getmatrix(tag);
376             U16 id = depth2id[swf_GetDepth(tag)];
377             char*name = depth2name[swf_GetDepth(tag)];
378             char buf[40];
379             SRECT bbox = bboxes[id];
380             SPOINT p1,p2,p3,p4;
381             p1.x = bbox.xmin; p1.y = bbox.ymin;
382             p2.x = bbox.xmax; p2.y = bbox.ymin;
383             p3.x = bbox.xmin; p3.y = bbox.ymax;
384             p4.x = bbox.xmax; p4.y = bbox.ymax;
385             p1 = swf_TurnPoint(p1, &m);
386             p2 = swf_TurnPoint(p2, &m);
387             p3 = swf_TurnPoint(p3, &m);
388             p4 = swf_TurnPoint(p4, &m);
389             if(!name) {
390                 sprintf(buf, "ID%d", id);name = buf;
391             }
392             //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);
393             printf("\t{%s {%.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f}}\n", name, 
394                     p1.x/20.0, p1.y/20.0, p2.x/20.0, p2.y/20.0,
395                     p3.x/20.0, p3.y/20.0, p4.x/20.0, p4.y/20.0);
396         }
397         tag = tag->next;
398     }
399     printf("}\n");
400 }
401
402     
403 int main (int argc,char ** argv)
404
405     TAG*tag;
406     SWF swf;
407     int fi;
408     memset(bboxes, 0, sizeof(bboxes));
409     memset(depth2name, 0, sizeof(depth2name));
410
411     processargs(argc, argv);
412     initLog(0,0,0,0,0,verbose?LOGLEVEL_DEBUG:LOGLEVEL_WARNING);
413
414     if(!filename) {
415         fprintf(stderr, "You must supply a filename.\n");
416         return 1;
417     }
418
419     fi = open(filename,O_RDONLY|O_BINARY);
420
421     if (fi<0)
422     { 
423         perror("Couldn't open file: ");
424         exit(1);
425     }
426     if FAILED(swf_ReadSWF(fi,&swf))
427     { 
428         fprintf(stderr, "%s is not a valid SWF file or contains errors.\n",filename);
429         close(fi);
430         exit(1);
431     }
432     close(fi);
433
434     swf_OptimizeTagOrder(&swf);
435     swf_FoldAll(&swf);
436
437     /* Optimize bounding boxes in case -O flag was set */
438     if(optimize) {
439         swf_OptimizeBoundingBoxes(&swf);
440     }
441     
442     /* Create an ID to Bounding Box table */
443     tag = swf.firstTag;
444     while (tag) {
445         if(swf_isDefiningTag(tag) && tag->id != ST_DEFINESPRITE) {
446             bboxes[swf_GetDefineID(tag)] = swf_GetDefineBBox(tag);
447         }
448         tag = tag->next;
449     }
450     
451     /* Create an ID->Bounding Box table for all bounding boxes */
452     if(swifty) {
453         showSwiftyOutput(&swf);
454     }
455
456     if(optimize) {
457         fi = open(outfilename, O_BINARY | O_RDWR | O_CREAT | O_TRUNC, 0666);
458         if(swf_WriteSWF(fi, &swf) < 0) {
459             fprintf(stderr, "Error writing file %s", outfilename);
460             close(fi);
461             exit(1);
462         }
463         close(fi);
464     }
465
466     swf_FreeTags(&swf);
467     return 0;
468 }