gcc 2.95.* 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
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 swf_Shape2Optimize(SHAPE2*shape)
107 {
108     if(!shape->bbox)
109         shape->bbox = malloc(sizeof(SRECT));
110     *(shape->bbox) = swf_GetShapeBoundingBox(shape);
111 }
112
113 /*
114    {char {x1 y1 x2 y2 x3 y3 x4 y4]]
115 */
116
117 SRECT bboxes[65536];
118 U16 depth2id[65536];
119 char*depth2name[65536];
120
121 int hasid(TAG*tag)
122 {
123     if(tag->id == ST_PLACEOBJECT)
124         return 1;
125     if(tag->id == ST_PLACEOBJECT2 && (tag->data[0] & 2))
126         return 1;
127     return 0;
128 }
129
130 int hasname(TAG*tag)
131 {
132     if(tag->id == ST_PLACEOBJECT)
133         return 0;
134     if(tag->id == ST_PLACEOBJECT2 && (tag->data[0] & 0x20))
135         return 1;
136     return 0;
137 }
138
139 char* getname(TAG*tag)
140 {
141     if(tag->id == ST_PLACEOBJECT)
142         return 0;
143     if(tag->id == ST_PLACEOBJECT2 && (tag->data[0] & 0x20)) {
144         SWFPLACEOBJECT o;
145         tag->pos = 0;tag->readBit = 0;
146         swf_GetPlaceObject(tag, &o);
147         return o.name;
148     }
149     return 0;
150 }
151
152 MATRIX getmatrix(TAG*tag)
153 {
154     SWFPLACEOBJECT o;
155     tag->pos = 0;tag->readBit = 0;
156     swf_GetPlaceObject(tag, &o);
157     return o.matrix;
158 }
159
160
161 static int fontnum = -1;
162 static SWFFONT**fonts;
163 static SWF*c_swf;
164 static void fontcallback1(U16 id,U8 * name)
165 { fontnum++;
166 }
167 static void fontcallback2(U16 id,U8 * name)
168
169     fonts[fontnum] = 0;
170     swf_FontExtract(c_swf,id,&fonts[fontnum]);
171     if(verbose) {
172         if(fonts[fontnum]) printf("Extracting font %d (%s)\n", id, name);
173         else               printf("Extracting font %d (%s) failed\n", id, name);
174         fflush(stdout);
175     }
176     fontnum++;
177 }
178 typedef struct _textbounds
179 {
180     SRECT r;
181     MATRIX m; // character transform matrix
182 } textbounds_t;
183
184 static void textcallback(void*self, int*chars, int*xpos, int nr, int fontid, int fontsize, 
185                     int xstart, int ystart, RGBA* color)
186 {
187     textbounds_t * bounds = (textbounds_t*)self;
188     SWFFONT*font = 0;
189     int t;
190     for(t=0;t<fontnum;t++) {
191         if(fonts[t]->id == fontid) {
192             font = fonts[t];
193             break;
194         }
195     }
196     if(!font) {
197         fprintf(stderr, "Font %d unknown\n", fontid);
198         exit(1);
199     }
200     if(!font->layout) {
201         /* This is an expensive operation- but what should we do, we
202            need the glyph's bounding boxes */
203         swf_FontCreateLayout(font);
204     }
205
206     if(verbose)
207         printf("%d chars, font %d, size %d, at (%d,%d)\n", nr, fontid, fontsize, xstart, ystart);
208
209     for(t=0;t<nr;t++) {
210         /* not tested yet- the matrix/fontsize calculation is probably all wrong */
211         int x = xstart + xpos[t];
212         int y = ystart;
213         int ch;
214         SRECT newglyphbbox, glyphbbox = font->layout->bounds[chars[t]];
215         MATRIX m = bounds->m;
216         
217         if(ch < font->numchars && font->glyph2ascii) {
218             ch = font->glyph2ascii[ch];
219         }
220
221         m.sx = (m.sx * fontsize) / 1024;
222         m.sy = (m.sy * fontsize) / 1024;
223         m.r0 = (m.r0 * fontsize) / 1024;
224         m.r1 = (m.r1 * fontsize) / 1024;
225
226         m.tx += x;
227         m.ty += y;
228         newglyphbbox = swf_TurnRect(glyphbbox, &m);
229
230         if(ch<32) ch='?';
231             
232         swf_ExpandRect2(&(bounds->r), &newglyphbbox);
233         if(verbose >= 2) {
234             printf("%5d %c, %d %d %d %d (%d %d %d %d) -> %d %d %d %d\n", 
235                 xpos[t], ch, 
236                 glyphbbox.xmin, glyphbbox.ymin, glyphbbox.xmax, glyphbbox.ymax,
237                 newglyphbbox.xmin, newglyphbbox.ymin, newglyphbbox.xmax, newglyphbbox.ymax,
238                 bounds->r.xmin, bounds->r.ymin, bounds->r.xmax, bounds->r.ymax);
239         }
240
241     }
242 }
243
244 static void swf_OptimizeBoundingBoxes(SWF*swf)
245 {
246     TAG* tag = swf->firstTag;
247     
248     while (tag) {
249         if (tag->id == ST_DEFINESHAPE ||
250             tag->id == ST_DEFINESHAPE2 ||
251             tag->id == ST_DEFINESHAPE3) {
252             SHAPE2 s;
253             if(verbose) printf("%s\n", swf_TagGetName(tag));
254             swf_ParseDefineShape(tag, &s);
255             swf_Shape2Optimize(&s);
256             tag->len = 2;
257             tag->pos = 0;
258             swf_SetShape2(tag, &s);
259         }
260         if (tag->id == ST_DEFINETEXT || tag->id == ST_DEFINETEXT2) {
261             SRECT oldbox;
262             int matrix_offset;
263             int len;
264             U8*data;
265             textbounds_t bounds;
266             if(verbose) printf("%s\n", swf_TagGetName(tag));
267             if(fontnum < 0) {
268                 if(verbose) printf("Extracting fonts...\n");
269                 c_swf = swf;
270                 fontnum = 0;
271                 swf_FontEnumerate(swf,&fontcallback1);
272                 fonts = (SWFFONT**)malloc(fontnum*sizeof(SWFFONT*));
273                 memset(fonts, 0, fontnum*sizeof(SWFFONT*));
274                 fontnum = 0;
275                 swf_FontEnumerate(swf,&fontcallback2);
276             }
277
278             memset(&bounds, 0, sizeof(bounds));
279
280             swf_SetTagPos(tag, 0);
281             swf_GetU16(tag);
282             swf_GetRect(tag,&oldbox);
283             swf_ResetReadBits(tag);
284             matrix_offset = tag->pos;
285             swf_GetMatrix(tag,&bounds.m);
286             swf_ParseDefineText(tag, textcallback, &bounds);
287             if(verbose) {
288                 printf("\n");
289                 swf_DumpMatrix(stdout, &bounds.m);
290                 printf("old: %d %d %d %d\n", oldbox.xmin, oldbox.ymin, oldbox.xmax, oldbox.ymax);
291                 printf("new: %d %d %d %d\n", bounds.r.xmin, bounds.r.ymin, bounds.r.xmax, bounds.r.ymax);
292             }
293             
294             /* now comes the tricky part: 
295                we have to fiddle the data back in 
296                thank heavens that the bbox is follow by a matrix
297                struct, which always starts on a byte boundary.
298              */
299             len = tag->len - matrix_offset;
300             data = malloc(len);
301             memcpy(data, &tag->data[matrix_offset], len);
302             tag->writeBit = 0;
303             tag->len = 2;
304             swf_SetRect(tag, &bounds.r);
305             swf_SetBlock(tag, data, len);
306             free(data);
307             tag->pos = tag->readBit = 0;
308         }
309         tag = tag->next;
310     }
311 }
312
313 static void showSwiftyOutput(SWF*swf) 
314 {
315     TAG*tag = swf->firstTag;
316     int frame=0;
317     printf("{\n\t{frame %d}\n", frame++);
318
319     while (tag) {
320         if (tag->id == ST_SHOWFRAME) {
321             printf("}\n{\n\t{frame %d}\n", frame++);
322         }
323         if (tag->id == ST_PLACEOBJECT || tag->id == ST_PLACEOBJECT2) {
324             if(hasid(tag)) {
325                 depth2id[swf_GetDepth(tag)] = swf_GetPlaceID(tag);
326             }
327             if(hasname(tag)) {
328                 depth2name[swf_GetDepth(tag)] = getname(tag);
329             }
330         }
331         if (tag->id == ST_PLACEOBJECT || tag->id == ST_PLACEOBJECT2) {
332             MATRIX m = getmatrix(tag);
333             U16 id = depth2id[swf_GetDepth(tag)];
334             char*name = depth2name[swf_GetDepth(tag)];
335             char buf[40];
336             SRECT bbox = bboxes[id];
337             SPOINT p1,p2,p3,p4;
338             p1.x = bbox.xmin; p1.y = bbox.ymin;
339             p2.x = bbox.xmax; p2.y = bbox.ymin;
340             p3.x = bbox.xmin; p3.y = bbox.ymax;
341             p4.x = bbox.xmax; p4.y = bbox.ymax;
342             p1 = swf_TurnPoint(p1, &m);
343             p2 = swf_TurnPoint(p2, &m);
344             p3 = swf_TurnPoint(p3, &m);
345             p4 = swf_TurnPoint(p4, &m);
346             if(!name) {
347                 sprintf(buf, "ID%d", id);name = buf;
348             }
349             //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);
350             printf("\t{%s {%.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f}}\n", name, 
351                     p1.x/20.0, p1.y/20.0, p2.x/20.0, p2.y/20.0,
352                     p3.x/20.0, p3.y/20.0, p4.x/20.0, p4.y/20.0);
353         }
354         tag = tag->next;
355     }
356     printf("}\n");
357 }
358
359     
360 int main (int argc,char ** argv)
361
362     TAG*tag;
363     SWF swf;
364     int fi;
365     memset(bboxes, 0, sizeof(bboxes));
366     memset(depth2name, 0, sizeof(depth2name));
367
368     processargs(argc, argv);
369     initLog(0,0,0,0,0,verbose?LOGLEVEL_DEBUG:LOGLEVEL_WARNING);
370
371     if(!filename) {
372         fprintf(stderr, "You must supply a filename.\n");
373         return 1;
374     }
375
376     fi = open(filename,O_RDONLY|O_BINARY);
377
378     if (fi<0)
379     { 
380         perror("Couldn't open file: ");
381         exit(1);
382     }
383     if FAILED(swf_ReadSWF(fi,&swf))
384     { 
385         fprintf(stderr, "%s is not a valid SWF file or contains errors.\n",filename);
386         close(fi);
387         exit(1);
388     }
389     close(fi);
390
391     swf_OptimizeTagOrder(&swf);
392     swf_FoldAll(&swf);
393
394     /* Optimize bounding boxes in case -O flag was set */
395     if(optimize) {
396         swf_OptimizeBoundingBoxes(&swf);
397     }
398     
399     /* Create an ID to Bounding Box table */
400     tag = swf.firstTag;
401     while (tag) {
402         if(swf_isDefiningTag(tag) && tag->id != ST_DEFINESPRITE) {
403             bboxes[swf_GetDefineID(tag)] = swf_GetDefineBBox(tag);
404         }
405         tag = tag->next;
406     }
407     
408     /* Create an ID->Bounding Box table for all bounding boxes */
409     if(swifty) {
410         showSwiftyOutput(&swf);
411     }
412
413     if(optimize) {
414         fi = open(outfilename, O_BINARY | O_RDWR | O_CREAT | O_TRUNC, 0666);
415         if(swf_WriteSWF(fi, &swf) < 0) {
416             fprintf(stderr, "Error writing file %s", outfilename);
417             close(fi);
418             exit(1);
419         }
420         close(fi);
421     }
422
423     swf_FreeTags(&swf);
424     return 0;
425 }