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