fixed two bugs in swfcombine
[swftools.git] / src / swfcombine.c
1 /* swfcombine.c
2    main routine for swfcombine(1), a tool for merging .swf-files.
3
4    Part of the swftools package.
5    
6    Copyright (c) 2001,2002,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 <stdlib.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include "../lib/rfxswf.h"
26 #include "../lib/args.h"
27 #include "../lib/log.h"
28 #include "../config.h"
29
30 struct config_t
31 {
32    char overlay;
33    char alloctest;
34    char clip;
35    char stack;
36    char stack1;
37    char antistream;
38    char dummy;
39    char zlib;
40    char cat;
41    char merge;
42    char isframe;
43    char local_with_networking;
44    char local_with_filesystem;
45    int loglevel;
46    int sizex;
47    char hassizex;
48    int sizey;
49    char hassizey;
50    int flashversion;
51    int framerate;
52    int movex;
53    int movey;
54    float scalex;
55    float scaley;
56    int mastermovex;
57    int mastermovey;
58    float masterscalex;
59    float masterscaley;
60 };
61 struct config_t config;
62
63 char * master_filename = 0;
64 char * master_name = 0;
65 char * slave_filename[128];
66 char * slave_name[128];
67 int slave_movex[128];
68 int slave_movey[128];
69 float slave_scalex[128];
70 float slave_scaley[128];
71 char slave_isframe[128];
72 int numslaves = 0;
73
74 char * outputname = "output.swf";
75
76 int args_callback_option(char*name,char*val) {
77     if(!strcmp(name,"c"))
78     {
79         config.clip = 1;
80         return 0;
81     }
82     else if(!strcmp(name,"l"))
83     {
84         config.overlay = 1;
85         return 0;
86     }
87     else if (!strcmp(name, "o"))
88     {
89         outputname = val;
90         return 1;
91     }
92     else if (!strcmp(name, "v"))
93     {
94         config.loglevel ++;
95         return 0;
96     }
97     else if (!strcmp(name, "a"))
98     {
99         config.cat = 1;
100         return 0;
101     }
102     else if (!strcmp(name, "A"))
103     {
104         config.alloctest = 1;
105         return 0;
106     }
107     else if (!strcmp(name, "x"))
108     {
109         float x = atof(val);
110         config.movex = (int)(x*20+0.5);
111         return 1;
112     }
113     else if (!strcmp(name, "y"))
114     {
115         float y = atof(val);
116         config.movey = (int)(y*20+0.5);
117         return 1;
118     }
119     else if (!strcmp(name, "m"))
120     {
121         config.merge = 1;
122         return 0;
123     }
124     else if (!strcmp(name, "f"))
125     {
126         config.isframe = 1;
127         return 0;
128     }
129     else if (!strcmp(name, "d"))
130     {
131         config.dummy = 1;
132         return 0;
133     }
134     else if (!strcmp(name, "z"))
135     {
136         config.zlib = 1;
137         return 0;
138     }
139     else if (!strcmp(name, "r"))
140     {
141
142         float rate = atof(val);
143         if ((rate < 0) ||(rate >= 256.0)) {
144             fprintf(stderr, "Error: You must specify a valid framerate between 1/256 and 255.\n");
145             exit(1);
146         }
147         config.framerate = (int)(rate*256);
148         return 1;
149     }
150     else if (!strcmp(name, "X"))
151     {
152         config.sizex = atoi(val)*20;
153         config.hassizex = 1;
154         return 1;
155     }
156     else if (!strcmp(name, "Y"))
157     {
158         config.sizey = atoi(val)*20;
159         config.hassizey = 1;
160         return 1;
161     }
162     else if (!strcmp(name, "s"))
163     {
164         config.scalex = config.scaley = atoi(val)/100.0;
165         return 1;
166     }
167     else if (!strcmp(name, "w"))
168     {
169         config.scalex = atoi(val)/100.0;
170         return 1;
171     }
172     else if (!strcmp(name, "h"))
173     {
174         config.scaley = atoi(val)/100.0;
175         return 1;
176     }
177     else if (!strcmp(name, "N"))
178     {
179         config.local_with_networking = 1;
180         return 0;
181     }
182     else if (!strcmp(name, "L"))
183     {
184         config.local_with_filesystem = 1;
185         return 0;
186     }
187     else if (!strcmp(name, "t") || !strcmp(name, "T"))
188     {
189         if(master_filename) {
190             fprintf(stderr, "error with arguments. Try --help.\n");
191             exit(1);
192         }
193         config.stack = 1;
194         if(!strcmp(name,"T"))
195             config.stack1 = 1;
196         master_filename = "__none__";
197         return 0;
198     }
199     else if (!strcmp(name, "V"))
200     {   
201         printf("swfcombine - part of %s %s\n", PACKAGE, VERSION);
202         exit(0);
203     }
204     else 
205     {
206         fprintf(stderr, "Unknown option: -%s\n", name);
207         exit(1);
208     }
209 }
210
211 static struct options_t options[] = {
212 {"o", "output"},
213 {"t", "stack"},
214 {"T", "stack1"},
215 {"F", "version"},
216 {"m", "merge"},
217 {"a", "cat"},
218 {"l", "overlay"},
219 {"c", "clip"},
220 {"v", "verbose"},
221 {"d", "dummy"},
222 {"f", "frame"},
223 {"x", "movex"},
224 {"y", "movey"},
225 {"s", "scale"},
226 {"r", "rate"},
227 {"X", "width"},
228 {"Y", "height"},
229 {"N", "local-with-network"},
230 {"L", "local-with-filesystem"},
231 {"z", "zlib"},
232 {0,0}
233 };
234
235 int args_callback_longoption(char*name,char*val) {
236     return args_long2shortoption(options, name, val);
237 }
238
239 int args_callback_command(char*name, char*val) {
240     char*myname = strdup(name);
241     char*filename;
242     filename = strchr(myname, '=');
243     if(filename) {
244         *filename = 0;
245         filename++;
246     } else {
247         // argument has no explicit name field. guess one from the file name
248         char*path = strrchr(myname, '/');
249         char*ext = strrchr(myname, '.');
250         if(!path) path = myname;
251         else path ++;
252         if(ext) *ext = 0;
253         myname = path;
254         filename = name;
255     }
256
257     if(!master_filename) {
258         master_filename = filename;
259         master_name = myname;
260         config.mastermovex = config.movex;
261         config.mastermovey = config.movey;
262         config.masterscalex = config.scalex;
263         config.masterscaley = config.scaley;
264         config.movex = config.movey = 0;
265         config.scalex = config.scaley = 1.0;
266     } else {             
267         msg("<verbose> slave entity %s (named \"%s\")\n", filename, myname);
268
269         slave_filename[numslaves] = filename;
270         slave_name[numslaves] = myname;
271         slave_movex[numslaves] = config.movex;
272         slave_movey[numslaves] = config.movey;
273         slave_scalex[numslaves] = config.scalex;
274         slave_scaley[numslaves] = config.scaley;
275         slave_isframe[numslaves] = config.isframe; 
276         config.isframe = 0;
277         config.movex = config.movey = 0;
278         config.scalex = config.scaley = 1.0;
279         numslaves ++;
280     }
281     return 0;
282 }
283
284 void args_callback_usage(char *name)
285 {
286     printf("\n");
287     printf("Usage: %s [-rXYomlcv] [-f] masterfile [-xysf] [(name1|#id1)=]slavefile1 .. [-xysf] [(nameN|#idN)=]slavefileN\n", name);
288     printf("OR:    %s [-rXYomv] --stack[1] [-xysf] [(name1|#id1)=]slavefile1 .. [-xysf] [(nameN|#idN)=]slavefileN\n", name);
289     printf("OR:    %s [-rXYov] --cat [-xysf] [(name1|#id1)=]slavefile1 .. [-xysf] [(nameN|#idN)=]slavefileN\n", name);
290     printf("OR:    %s [-rXYomlcv] --dummy [-xys] [file]\n", name);
291     printf("\n");
292     printf("-o , --output <outputfile>      explicitly specify output file. (otherwise, output.swf will be used)\n");
293     printf("-t , --stack                   place each slave in a seperate frame (no master movie)\n");
294     printf("-T , --stack1                  place each slave in the first frame (no master movie)\n");
295     printf("-m , --merge                   Don't store the slaves in Sprites/MovieClips\n");
296     printf("-a , --cat                     concatenate all slave files (no master movie)\n");
297     printf("-l , --overlay                 Don't remove any master objects, only overlay new objects\n");
298     printf("-c , --clip                    Clip the slave objects by the corresponding master objects\n");
299     printf("-v , --verbose                 Be verbose. Use more than one -v for greater effect \n");
300     printf("-d , --dummy                   Don't require slave objects (for changing movie attributes)\n");
301     printf("-f , --frame                   The following identifier is a frame or framelabel, not an id or objectname\n");
302     printf("-x , --movex <xpos>            x Adjust position of slave by <xpos> pixels\n");
303     printf("-y , --movey <ypos>            y Adjust position of slave by <ypos> pixels\n");
304     printf("-s , --scale <scale>           Adjust size of slave by <scale> percent (e.g. 100% = original size)\n");
305     printf("-r , --rate <fps>              Set movie framerate to <fps> (frames/sec)\n");
306     printf("-X , --width <width>           Force movie bbox width to <width> (default: use master width (not with -t))\n");
307     printf("-Y , --height <height>          Force movie bbox height to <height> (default: use master height (not with -t))\n");
308     printf("-N , --local-with-networking     Make output file \"local-with-networking\"\n");
309     printf("-L , --local-with-filesystem     Make output file \"local-with-filesystem\"\n");
310     printf("-z , --zlib <zlib>             Enable Flash 6 (MX) Zlib Compression\n");
311     printf("\n");
312 }
313
314 void removeCommonTags(SWF * swf)
315 {
316     TAG*tag = swf->firstTag;
317     while(tag) {
318         if(tag->id == ST_SCENEDESCRIPTION ||
319            tag->id == ST_FILEATTRIBUTES ||
320            tag->id == ST_REFLEX) {
321             tag = swf_DeleteTag(swf, tag);
322         } else {
323             tag = tag->next;
324         }
325     }
326 }
327
328 static void makestackmaster(SWF*swf)
329 {
330     TAG*tag;
331     int t;
332     SRECT box;
333     int fileversion = config.zlib?6:3;
334     int frameRate = 256;
335     U32 fileAttributes = 0;
336     RGBA rgb;
337     rgb.r=rgb.b=rgb.g=0;
338     memset(&box, 0, sizeof(box));
339
340     /* scan all slaves for bounding box */
341     for(t=numslaves-1;t>=0;t--)
342     {
343         SWF head;
344         int ret;
345         int fi=open(slave_filename[t],O_RDONLY|O_BINARY);
346         TAG*tag;
347         if(fi<0 || swf_ReadSWF(fi, &head)<0) {
348             msg("<fatal> Couldn't open/read %s.", slave_filename[t]);
349             exit(1);
350         }
351         close(fi);
352         swf_RemoveJPEGTables(&head);
353         fileAttributes |= head.fileAttributes;
354         removeCommonTags(&head);
355
356         msg("<verbose> File %s has bounding box %d:%d:%d:%d\n",
357                 slave_filename[t], 
358                 head.movieSize.xmin, head.movieSize.ymin,
359                 head.movieSize.xmax, head.movieSize.ymax);
360
361         tag = head.firstTag;
362         while(tag) {
363             if(tag->id == ST_SETBACKGROUNDCOLOR && tag->len>=3) {
364                 rgb.r = tag->data[0];
365                 rgb.g = tag->data[1];
366                 rgb.b = tag->data[2];
367             }
368             tag=tag->next;
369         }
370         frameRate = head.frameRate;
371         if(head.fileVersion > fileversion)
372             fileversion = head.fileVersion;
373         if(!t)
374             box = head.movieSize;
375         else {
376             if(head.movieSize.xmin < box.xmin)
377                 box.xmin = head.movieSize.xmin;
378             if(head.movieSize.ymin < box.ymin)
379                 box.ymin = head.movieSize.ymin;
380             if(head.movieSize.xmax > box.xmax)
381                 box.xmax = head.movieSize.xmax;
382             if(head.movieSize.ymax > box.ymax)
383                 box.ymax = head.movieSize.ymax;
384         }
385         msg("<verbose> New master bounding box is %d:%d:%d:%d\n",
386                 box.xmin, box.ymin,
387                 box.xmax, box.ymax);
388         swf_FreeTags(&head);
389     }
390
391     memset(swf, 0, sizeof(SWF));
392     swf->fileVersion = fileversion;
393     swf->movieSize = box;
394     swf->frameRate = frameRate;
395     swf->fileAttributes = fileAttributes;
396
397     swf->firstTag = swf_InsertTag(0, ST_SETBACKGROUNDCOLOR);
398     tag = swf->firstTag;
399     swf_SetRGB(tag, &rgb);
400     
401     for(t=0;t<numslaves;t++)
402     {
403         char buf[128];
404         sprintf(buf, "Frame%02d", t);
405         slave_name[t] = strdup(buf);
406
407         tag = swf_InsertTag(tag, ST_DEFINESPRITE);
408         swf_SetU16(tag, t+1);
409         swf_SetU16(tag, 0);
410         tag = swf_InsertTag(tag, ST_END);
411         tag = swf_InsertTag(tag, ST_PLACEOBJECT2);
412         swf_ObjectPlace(tag, t+1, 1+t,0,0, slave_name[t]);
413
414         if(!config.stack1 || t == numslaves-1) {
415             tag = swf_InsertTag(tag, ST_SHOWFRAME);
416         }
417         if(!config.stack)
418         if(t!=numslaves-1)
419         {
420             tag = swf_InsertTag(tag, ST_REMOVEOBJECT2);
421             swf_SetU16(tag, 1+t);
422         }
423     }
424     tag = swf_InsertTag(tag, ST_END);
425     msg("<verbose> temporary SWF created");
426 }
427
428 static char* slavename = 0;
429 static int slaveid = -1;
430 static int slaveframe = -1;
431 static char masterbitmap[65536];
432 static char depthbitmap[65536];
433
434 #define FLAGS_WRITEDEFINES 1
435 #define FLAGS_WRITENONDEFINES 2
436 #define FLAGS_WRITESPRITE 4
437 #define FLAGS_WRITESLAVE 8
438
439 int get_free_id(char*bitmap)
440 {
441     int t;
442     for(t=1;t<65536;t++)
443         if(!bitmap[t]) {
444             bitmap[t] = 1;
445             return t;
446         }
447     return -1;
448 }
449
450 void jpeg_assert(SWF*master, SWF*slave)
451 {
452     /* TODO: if there's a jpegtable found, store it
453        and handle it together with the flash file
454        headers */
455
456     /* check that master and slave don't have both
457        jpegtables (which would be fatal) */
458     int pos;
459     TAG *mpos=0, *spos=0;
460     TAG *mtag,*stag;
461     pos = 0;
462     mtag = master->firstTag;
463     stag = slave->firstTag;
464     while(mtag)
465     {
466         if(mtag->id  == ST_JPEGTABLES)
467             mpos = mtag;
468         mtag = mtag->next;
469     }
470     while(stag)
471     {
472         if(stag->id == ST_JPEGTABLES)
473             spos = stag;
474         stag = stag->next;
475     }
476     if(mpos && spos)
477     {
478         if(spos->len == mpos->len &&
479         !memcmp(spos->data, mpos->data, mpos->len))
480         {
481             // ok, both have jpegtables, but they're identical.
482             // delete one and don't throw an error
483             swf_DeleteTag(slave, spos);
484             spos = 0;
485         }
486     }
487     if(spos && mpos) {
488         msg("<error> Master and slave have incompatible JPEGTABLES.");
489     }
490 }
491
492 TAG* write_sprite_defines(TAG*tag, SWF*sprite)
493 {
494     TAG*rtag = sprite->firstTag;
495     while(rtag && rtag->id!=ST_END) {
496         if(!swf_isAllowedSpriteTag(rtag)) {
497             msg("<debug> processing sprite tag %02x", tag->id);
498             if(swf_isDefiningTag(rtag))
499             {
500                 msg("<debug> [sprite defs] write tag %02x (%d bytes in body)", 
501                         tag->id, tag->len);
502                 tag = swf_InsertTag(tag, rtag->id);
503                 swf_SetBlock(tag, rtag->data, rtag->len);
504             }
505             else if(swf_isPseudoDefiningTag(rtag))
506             {
507                 msg("<debug> [sprite defs] write tag %02x (%d bytes in body)", 
508                         tag->id, tag->len);
509                 tag = swf_InsertTag(tag, rtag->id);
510                 swf_SetBlock(tag, rtag->data, rtag->len);
511             }
512             else {
513                 switch(rtag->id)
514                 {
515                     case ST_JPEGTABLES:
516                            /* if we get here, jpeg_assert has already run,
517                               ensuring this is the only one of it's kind,
518                               so we may safely write it out */
519                            tag = swf_InsertTag(tag, rtag->id);
520                            swf_SetBlock(tag, rtag->data, rtag->len);
521                        break;
522                     case ST_EXPORTASSETS:
523                        msg("<debug> deliberately ignoring EXPORTASSETS tag");
524                        break;
525                     case ST_ENABLEDEBUGGER:
526                        msg("<debug> deliberately ignoring ENABLEDEBUGGER tag");
527                        break;
528                     case ST_SETBACKGROUNDCOLOR:
529                        msg("<debug> deliberately ignoring BACKGROUNDCOLOR tag");
530                        break;
531                     case ST_SHOWFRAME:
532                        msg("<debug> deliberately ignoring SHOWFRAME tag");
533                        break;
534                     case ST_REFLEX:
535                        msg("<debug> deliberately ignoring REFLEX tag");
536                        break;
537                     case 40:
538                     case 49:
539                     case 51:
540                        msg("<notice> found tag %d. This is a Generator template, isn't it?", rtag->id);
541                        break;
542                     default:
543                        msg("<notice> funny tag: %d is neither defining nor sprite", rtag->id);
544                 }
545             }
546         }
547         rtag = rtag->next;
548     }
549     return tag;
550 }
551
552 void changedepth(TAG*tag, int add)
553 {
554     if(tag->id == ST_PLACEOBJECT)
555         PUT16(&tag->data[2],GET16(&tag->data[2])+add);
556     if(tag->id == ST_PLACEOBJECT2)
557         PUT16(&tag->data[1],GET16(&tag->data[1])+add);
558     if(tag->id == ST_REMOVEOBJECT)
559         PUT16(&tag->data[2],GET16(&tag->data[2])+add);
560     if(tag->id == ST_REMOVEOBJECT2)
561         PUT16(&tag->data[0],GET16(&tag->data[0])+add);
562     if(tag->id == ST_PLACEOBJECT2) {
563         SWFPLACEOBJECT obj;
564         U8 flags;
565         swf_SetTagPos(tag, 0);
566         flags = swf_GetU8(tag);
567         if(flags&2) swf_GetU16(tag); //id
568         if(flags&4) swf_GetMatrix(tag, 0);
569         if(flags&8) swf_GetCXForm(tag, 0,1);
570         if(flags&16) swf_GetU16(tag); //ratio
571         if(flags&64) {
572             swf_ResetReadBits(tag);
573             printf("%d->%d\n", GET16(&tag->data[tag->pos]),
574                                GET16(&tag->data[tag->pos])+add);
575             PUT16(&tag->data[tag->pos],GET16(&tag->data[tag->pos])+add);
576         }
577         msg("<warning> Depth relocation not fully working yet with clipdepths", tag->id);
578     }
579 }
580
581 void matrix_adjust(MATRIX*m, int movex, int movey, float scalex, float scaley, int scalepos)
582 {
583     m->sx = (int)(m->sx*scalex);
584     m->sy = (int)(m->sy*scaley);
585     m->r1 = (int)(m->r1*scalex);
586     m->r0 = (int)(m->r0*scaley);
587     if(scalepos) {
588         m->tx *= scalex;
589         m->ty *= scaley;
590     }
591     m->tx += movex;
592     m->ty += movey;
593 }
594
595 void write_changepos(TAG*output, TAG*tag, int movex, int movey, float scalex, float scaley, int scalepos)
596 {
597     if(movex || movey || scalex != 1.0 || scaley != 1.0)
598     {
599         switch(tag->id)
600         {
601             case ST_PLACEOBJECT2: {
602                 MATRIX m;
603                 U8 flags;
604                 swf_GetMatrix(0, &m);
605                 tag->pos = 0;
606                 tag->readBit = 0;
607
608                 flags = swf_GetU8(tag);
609                 swf_SetU8(output, flags|4);
610                 swf_SetU16(output, swf_GetU16(tag)); //depth
611                 //flags&1: move
612                 if(flags&2) {
613                     swf_SetU16(output, swf_GetU16(tag)); //id
614                 }
615                 // flags & 4
616                 if(flags&4) {
617                     swf_GetMatrix(tag, &m);
618                 } else {
619                     swf_GetMatrix(0, &m);
620                 }
621                 matrix_adjust(&m, movex, movey, scalex, scaley, scalepos);
622                 swf_SetMatrix(output, &m);
623
624                 if (tag->readBit)  { tag->pos++; tag->readBit = 0; } //swf_ResetReadBits(tag);
625
626                 swf_SetBlock(output, &tag->data[tag->pos], tag->len - tag->pos);
627                 break;
628             }
629             case ST_PLACEOBJECT: {
630                 MATRIX m;
631                 swf_SetU16(output, swf_GetU16(tag)); //id
632                 swf_SetU16(output, swf_GetU16(tag)); //depth
633                 
634                 swf_GetMatrix(tag, &m);
635                 matrix_adjust(&m, movex, movey, scalex, scaley, scalepos);
636                 swf_SetMatrix(output, &m);
637                 
638                 if (tag->readBit)  { tag->pos++; tag->readBit = 0; } //swf_ResetReadBits(tag);
639
640                 swf_SetBlock(output, &tag->data[tag->pos], tag->len - tag->pos);
641                 break;
642             }
643             default:
644             swf_SetBlock(output, tag->data, tag->len);
645         }
646     } 
647     else 
648     {
649             swf_SetBlock(output, tag->data, tag->len);
650     }
651 }
652
653 TAG* write_sprite(TAG*tag, SWF*sprite, int spriteid, int replaceddefine)
654 {
655     TAG* definespritetag;
656     TAG* rtag;
657     int tmp;
658
659     definespritetag = tag = swf_InsertTag(tag, ST_DEFINESPRITE);
660     swf_SetU16(tag, spriteid);
661     swf_SetU16(tag, sprite->frameCount);
662     msg ("<notice> sprite id is %d", spriteid);
663
664     tmp = sprite->frameCount;
665     msg("<debug> %d frames to go",tmp);
666
667     if(config.clip) {
668         tag = swf_InsertTag(tag, ST_PLACEOBJECT2);
669         swf_SetU8(tag, 2+64); //flags: character+clipdepth
670         swf_SetU16(tag, 0); //depth
671         swf_SetU16(tag, replaceddefine); //id
672         swf_SetU16(tag, 65535); //clipdepth
673     }
674
675     if(config.overlay && !config.isframe) {
676         tag = swf_InsertTag(tag, ST_PLACEOBJECT2);
677         swf_SetU8(tag, 2); //flags: character
678         swf_SetU16(tag, 1); //depth
679         swf_SetU16(tag, replaceddefine); //id
680     }
681
682     rtag = sprite->firstTag;
683     while(rtag && rtag->id!=ST_END)
684     {
685         if (swf_isAllowedSpriteTag(rtag)) {
686
687             msg("<debug> [sprite main] write tag %02x (%d bytes in body)", 
688                     rtag->id, rtag->len);
689             tag = swf_InsertTag(tag, rtag->id);
690             write_changepos(tag, rtag, config.movex, config.movey, config.scalex, config.scaley, 0);
691
692             if(config.clip || (config.overlay && !config.isframe))
693                 changedepth(tag, +2);
694
695             if(tag->id == ST_SHOWFRAME)
696             {
697                 tmp--;
698                 msg("<debug> %d frames to go",tmp);
699             }
700         }
701         rtag = rtag->next;
702     }
703     tag = swf_InsertTag(tag, ST_END);
704     return tag;
705 }
706
707 static char tag_ok_for_slave(int id)
708 {
709     if(id == ST_SETBACKGROUNDCOLOR)
710         return 0;
711     return 1;
712 }
713
714 TAG* write_master(TAG*tag, SWF*master, SWF*slave, int spriteid, int replaceddefine, int flags)
715 {
716     int outputslave = 0;
717     int frame = 1;
718     int sframe = 0;
719     int slavewritten = 0;
720     int deletedepth = -1;
721
722     TAG* rtag = master->firstTag;
723     TAG* stag = slave->firstTag;
724
725     while(rtag && rtag->id!=ST_END)
726     {
727         if(rtag->id == ST_SHOWFRAME && outputslave)
728         {
729             while(stag && stag->id!=ST_END) {
730                 if(stag->id == ST_SHOWFRAME) {
731                     stag = stag->next;
732                     sframe++;
733                     break;
734                 }
735                 if(tag_ok_for_slave(stag->id)) {
736                     tag = swf_InsertTag(tag, stag->id);
737                     write_changepos(tag, stag, config.movex, config.movey, config.scalex, config.scaley, 0);
738                 }
739                 stag = stag->next;
740             }
741         }
742         if(rtag->id == ST_SHOWFRAME)
743         {
744             frame ++;
745             tag = swf_InsertTag(tag, ST_SHOWFRAME);
746             if(deletedepth>=0) {
747                 tag = swf_InsertTag(tag, ST_REMOVEOBJECT2);
748                 swf_SetU16(tag, deletedepth);
749                 deletedepth=-1;
750             }
751             rtag = rtag->next;
752             continue;
753         }
754
755         if(swf_isDefiningTag(rtag) && (flags&FLAGS_WRITEDEFINES))
756         {
757             msg("<debug> [master] write tag %02x (%d bytes in body)", 
758                     rtag->id, rtag->len);
759             if(swf_GetDefineID(rtag) == spriteid && !config.isframe)
760             {
761                 if(config.overlay)
762                 {
763                     tag = swf_InsertTag(tag, rtag->id);
764                     swf_SetBlock(tag, rtag->data, rtag->len);
765                     swf_SetDefineID(tag, replaceddefine);
766                 } else {
767                     /* don't write this tag */
768                     msg("<verbose> replacing tag %d ID %d with sprite", rtag->id ,spriteid);
769                 }
770
771                 if(flags&FLAGS_WRITESPRITE)
772                 {
773                     msg("<debug> writing sprite defines");
774                     tag = write_sprite_defines(tag, slave);
775                     msg("<debug> writing sprite");
776                     tag = write_sprite(tag, slave, spriteid, replaceddefine);
777                 }
778                 if(flags&FLAGS_WRITESLAVE)
779                 {
780                     msg("<debug> writing slave");
781                     outputslave = 1;
782                 }
783             } else { 
784                 tag = swf_InsertTag(tag, rtag->id);
785                 swf_SetBlock(tag, rtag->data, rtag->len);
786             }
787         }
788         if(frame == slaveframe) /* only happens with config.isframe: put slave at specific frame */
789         {
790             if(flags&FLAGS_WRITESLAVE) {
791                 outputslave = 1;
792                 slavewritten = 1;
793             }
794             if((flags&FLAGS_WRITESPRITE) && !slavewritten)
795             {
796                 int id = get_free_id(masterbitmap);
797                 int depth = 65535;
798                 deletedepth = 65535;
799                 if(config.clip) {
800                     msg("<fatal> Can't combine --clip and --frame");
801                 }
802                 
803                 tag = write_sprite_defines(tag, slave);
804                 tag = write_sprite(tag, slave, id, -1);
805
806                 tag = swf_InsertTag(tag, ST_PLACEOBJECT2);
807                     swf_SetU8(tag, 2); //flags: id
808                     swf_SetU16(tag, depth);
809                     swf_SetU16(tag, id);
810
811                 slavewritten = 1;
812             }
813         }
814         if(!swf_isDefiningTag(rtag) && (flags&FLAGS_WRITENONDEFINES))
815         {
816             int dontwrite = 0;
817             switch(rtag->id) {
818                 case ST_PLACEOBJECT:
819                 case ST_PLACEOBJECT2:
820                     if(frame == slaveframe && !config.overlay)
821                         dontwrite = 1;
822                 case ST_REMOVEOBJECT:
823                     /* place/removetags for the object we replaced
824                        should be discarded, too, as the object to insert 
825                        isn't a sprite 
826                      */
827                     if(spriteid>=0 && swf_GetPlaceID(rtag) == spriteid && 
828                             !config.isframe && config.merge)
829                         dontwrite = 1;
830                 break;
831                 case ST_REMOVEOBJECT2:
832                 break;
833             }
834             if(!dontwrite) {
835                 msg("<debug> [master] write tag %02x (%d bytes in body)", 
836                         rtag->id, rtag->len);
837                 tag = swf_InsertTag(tag, rtag->id);
838                 write_changepos(tag, rtag, config.mastermovex, config.mastermovey, config.masterscalex, config.masterscaley, 1);
839                 
840             }
841         }
842         rtag = rtag->next;
843     }
844    
845     if(outputslave) 
846     while(stag && stag->id!=ST_END)
847     {
848             if(tag_ok_for_slave(stag->id)) {
849                 msg("<debug> [slave] write tag %02x (%d bytes in body), %.2f %.2f", rtag->id, rtag->len, config.movex /20.0, config.movey /20.0);
850                 tag = swf_InsertTag(tag, stag->id);
851                 write_changepos(tag, stag, config.movex, config.movey, config.scalex, config.scaley, 0);
852             }
853             stag = stag->next;
854     }
855     if(!slavewritten && config.isframe && (flags&(FLAGS_WRITESLAVE|FLAGS_WRITESPRITE)))
856     {
857         if(slaveframe>=0)
858             msg("<warning> Frame %d doesn't exist in file. No substitution will occur",
859                     slaveframe);
860         else
861             msg("<warning> Frame \"%s\" doesn't exist in file. No substitution will occur",
862                     slavename);
863     }
864     tag = swf_InsertTag(tag, ST_END);
865     return tag;
866 }
867
868 void adjustheader(SWF*swf)
869 {
870     if(config.framerate)
871         swf->frameRate = config.framerate;
872     if(config.hassizex) {
873         swf->movieSize.xmax = 
874         swf->movieSize.xmin + config.sizex;
875     }
876     if(config.hassizey) {
877         swf->movieSize.ymax = 
878         swf->movieSize.ymin + config.sizey;
879     }
880     if(config.flashversion)
881         swf->fileVersion = config.flashversion;
882 }
883
884 void catcombine(SWF*master, char*slave_name, SWF*slave, SWF*newswf)
885 {
886     char* depths;
887     int t;
888     TAG*tag;
889     TAG*mtag,*stag;
890     if(config.isframe) {
891         msg("<fatal> Can't combine --cat and --frame");
892         exit(1);
893     }
894     if(config.flashversion)
895         master->fileVersion = config.flashversion;
896    
897     tag = master->firstTag;
898     while(tag)
899     {
900         if(swf_isDefiningTag(tag)) {
901             int defineid = swf_GetDefineID(tag);
902             msg("<debug> tagid %02x defines object %d", tag->id, defineid);
903             masterbitmap[defineid] = 1;
904         }
905         tag = tag->next;
906     }
907     
908     swf_Relocate(slave, masterbitmap);
909     jpeg_assert(master, slave);
910     
911     memcpy(newswf, master, sizeof(SWF));
912     adjustheader(newswf);
913
914     tag = newswf->firstTag = swf_InsertTag(0, ST_REFLEX); // to be removed later
915
916     depths = malloc(65536);
917     if(!depths) {
918         msg("<fatal> Couldn't allocate %d bytes of memory", 65536);
919         return;
920     }
921     memset(depths, 0, 65536);
922     mtag = master->firstTag;
923     while(mtag && mtag->id!=ST_END)
924     {
925         int num=1;
926         U16 depth;
927         msg("<debug> [master] write tag %02x (%d bytes in body)", 
928                 mtag->id, mtag->len);
929         switch(mtag->id) {
930             case ST_PLACEOBJECT2:
931                 num++;
932             case ST_PLACEOBJECT: {
933                depth = swf_GetDepth(mtag);
934                depths[depth] = 1;
935             }
936             break;
937             case ST_REMOVEOBJECT: {
938                depth = swf_GetDepth(mtag);
939                depths[depth] = 0;
940             }
941             break;
942             case ST_REMOVEOBJECT2: {
943                depth = swf_GetDepth(mtag);
944                depths[depth] = 0;
945             }
946             break;
947         }
948         tag = swf_InsertTag(tag, mtag->id);
949         swf_SetBlock(tag, mtag->data, mtag->len);
950
951         mtag = mtag->next;
952     }
953
954     for(t=0;t<65536;t++) 
955     if(depths[t])
956     {
957         char data[16];
958         int len;
959         tag = swf_InsertTag(tag, ST_REMOVEOBJECT2);
960         swf_SetU16(tag, t);
961     }
962     free(depths);
963
964     stag = slave->firstTag;
965     while(stag && stag->id!=ST_END)
966     {
967         msg("<debug> [slave] write tag %02x (%d bytes in body)", 
968                 stag->id, stag->len);
969         tag = swf_InsertTag(tag, stag->id);
970         swf_SetBlock(tag, stag->data, stag->len);
971         stag = stag->next;
972     }
973     tag = swf_InsertTag(tag, ST_END);
974
975     swf_DeleteTag(newswf, tag);
976 }
977
978 void normalcombine(SWF*master, char*slave_name, SWF*slave, SWF*newswf)
979 {
980     int spriteid = -1;
981     int replaceddefine = -1;
982     int frame = 0;
983     char*framelabel;
984     TAG * tag = master->firstTag;
985
986     memset(depthbitmap, 0, sizeof(depthbitmap));
987     
988     // set the idtab
989     while(tag)
990     {
991         int depth = swf_GetDepth(tag);
992         if(depth>=0) {
993             depthbitmap[depth] = 1;
994         }
995         if(swf_isDefiningTag(tag)) {
996             int defineid = swf_GetDefineID(tag);
997             msg("<debug> tagid %02x defines object %d", tag->id, defineid);
998             masterbitmap[defineid] = 1;
999
1000             if (!slavename && defineid==slaveid) {
1001                 if(defineid>=0) {
1002                   spriteid = defineid;
1003                   msg("<notice> Slave file attached to object %d.", defineid);
1004                 }
1005             }
1006         } else if(tag->id == ST_EXPORTASSETS) {
1007             int t;
1008             int num = swf_GetU16(tag);
1009             for(t=0;t<num;t++)
1010             {
1011                 U16 id = swf_GetU16(tag);
1012                 char*name = swf_GetString(tag);
1013                 if(spriteid<0 && slavename && !strcmp(name,slavename)) {
1014                     spriteid = id;
1015                     msg("<notice> Slave file attached to object %d exported as %s.", id, name);
1016                 }
1017             }
1018         } else if(tag->id == ST_SYMBOLCLASS) {
1019             /* a symbolclass tag is like a define tag: it defines id 0000 */
1020             int num = swf_GetU16(tag);
1021             int t;
1022             for(t=0;t<num;t++) {
1023                 U16 id = swf_GetU16(tag);
1024                 if(!id) {
1025                     masterbitmap[id] = 1;
1026                 }
1027                 swf_GetString(tag);
1028             }
1029         } else if(tag->id == ST_PLACEOBJECT2) {
1030             char * name = swf_GetName(tag);
1031             int id = swf_GetPlaceID(tag);
1032
1033             {
1034                 SWFPLACEOBJECT obj;
1035                 swf_GetPlaceObject(tag, &obj);
1036                 swf_PlaceObjectFree(&obj);
1037                 if(obj.clipdepth) {
1038                     depthbitmap[obj.clipdepth] = 1;
1039                 }
1040             }
1041
1042             if(name)
1043               msg("<verbose> tagid %02x places object %d named \"%s\"", tag->id, id, name);
1044             else
1045               msg("<verbose> tagid %02x places object %d (no name)", tag->id, id);
1046
1047             if (name && slavename && !strcmp(name,slavename)) {
1048                 if(id>=0) {
1049                   spriteid = id;
1050                   msg("<notice> Slave file attached to named object %s (%d).", name, id);
1051                 }
1052             }
1053         } else if(tag->id == ST_SHOWFRAME) {
1054             if(slaveframe>=0 && frame==slaveframe) {
1055                 msg("<notice> Slave file attached to frame %d.", frame);
1056             }
1057             frame++;
1058         } else if(tag->id == ST_FRAMELABEL) {
1059             char * name = tag->data;
1060             if(name && slavename && config.isframe && !strcmp(name, slavename)) {
1061                 slaveframe = frame;
1062                 msg("<notice> Slave file attached to frame %d (%s).", frame, name);
1063             }
1064         }
1065         tag = tag->next;
1066     };
1067
1068     if (spriteid<0 && !config.isframe) {
1069         if(slavename) {
1070             if(strcmp(slavename,"!!dummy!!")) {
1071                 msg("<warning> Didn't find anything named %s in file. No substitutions will occur.", slavename);
1072                 if(!strcmp(slavename, "swf")) {
1073                     msg("<warning> (If you were trying to combine rfxview with a document, try replacing 'swf' with 'viewport'.");
1074                 }
1075             }
1076         }
1077         else
1078             msg("<warning> Didn't find id %d in file. No substitutions will occur.", slaveid);
1079         spriteid = get_free_id(masterbitmap);
1080     }
1081
1082     swf_Relocate (slave, masterbitmap);
1083     
1084     if(config.merge)
1085         swf_RelocateDepth (slave, depthbitmap);
1086     jpeg_assert(slave, master);
1087     
1088     if (config.overlay)
1089         replaceddefine = get_free_id(masterbitmap);
1090     
1091     // write file 
1092
1093     memcpy(newswf, master, sizeof(SWF));
1094     adjustheader(newswf);
1095
1096     newswf->firstTag = tag = swf_InsertTag(0, ST_REFLEX); // to be removed later
1097
1098     if (config.antistream) {
1099         if (config.merge) {
1100             msg("<fatal> Can't combine --antistream and --merge");
1101         }
1102         tag = write_sprite_defines(tag, slave);
1103         tag = write_sprite(tag, slave, spriteid, replaceddefine);
1104         tag = write_master(tag, master, slave, spriteid, replaceddefine, FLAGS_WRITEDEFINES);
1105         tag = write_master(tag, master, slave, spriteid, replaceddefine, FLAGS_WRITENONDEFINES);
1106     } else {
1107         if (config.merge)
1108             tag = write_master(tag, master, slave, spriteid, replaceddefine, 
1109                 FLAGS_WRITEDEFINES|FLAGS_WRITENONDEFINES|   FLAGS_WRITESLAVE    );
1110         else
1111             tag = write_master(tag, master, slave, spriteid, replaceddefine, 
1112                 FLAGS_WRITEDEFINES|FLAGS_WRITENONDEFINES|   FLAGS_WRITESPRITE   );
1113     }
1114
1115     swf_DeleteTag(newswf, newswf->firstTag);
1116 }
1117
1118 void combine(SWF*master, char*slave_name, SWF*slave, SWF*newswf)
1119 {
1120     slavename = slave_name;
1121     slaveid = -1;
1122     slaveframe = -1;
1123
1124     if(!master->fileVersion && slave)
1125         master->fileVersion = slave->fileVersion;
1126         
1127     master->fileAttributes |= slave->fileAttributes;
1128
1129     swf_FoldAll(master);
1130     swf_FoldAll(slave);
1131
1132     if(slavename[0] == '#')
1133     {
1134         slaveid = atoi(&slavename[1]);
1135         slavename = 0;
1136     }
1137
1138     if(config.isframe)
1139     {
1140         if(slavename && slavename[0]!='#') {
1141             int tmp;
1142             int len;
1143             sscanf(slavename, "%d%n", &tmp, &len);
1144             if(len == strlen(slavename)) {
1145             /* if the name the slave should replace 
1146                consists only of digits and the -f
1147                option is given, it probably is not
1148                a frame name but a frame number.
1149              */
1150                 slaveid = tmp;
1151                 slavename = 0;
1152             }
1153         }
1154
1155         if(slaveid>=0) {
1156             slaveframe = slaveid;
1157             slaveid = -1;
1158         } else {
1159         /* if id wasn't given as either #number or number,
1160            the name is a frame label. BTW: The user wouldn't necessarily have
1161            needed to supply the -f option in this case */
1162         }
1163     }
1164
1165     msg("<debug> move x (%d)", config.movex);
1166     msg("<debug> move y (%d)", config.movey);
1167     msg("<debug> scale x (%f)", config.scalex);
1168     msg("<debug> scale y (%f)", config.scaley);
1169     msg("<debug> master move x (%d)", config.mastermovex);
1170     msg("<debug> master move y (%d)", config.mastermovey);
1171     msg("<debug> master scale x (%f)", config.masterscalex);
1172     msg("<debug> master scale y (%f)", config.masterscaley);
1173     msg("<debug> is frame (%d)", config.isframe);
1174     
1175     memset(masterbitmap, 0, sizeof(masterbitmap));
1176
1177     if(config.cat) 
1178         return catcombine(master, slave_name, slave, newswf);
1179     else
1180         return normalcombine(master, slave_name, slave, newswf);
1181 }
1182
1183 int main(int argn, char *argv[])
1184 {
1185     int fi;
1186     SWF master;
1187     SWF slave;
1188     SWF newswf;
1189     int t;
1190
1191     config.overlay = 0; 
1192     config.antistream = 0; 
1193     config.alloctest = 0;
1194     config.cat = 0;
1195     config.merge = 0;
1196     config.clip = 0;
1197     config.loglevel = 2; 
1198     config.movex = 0;
1199     config.movey = 0;
1200     config.scalex = 1.0;
1201     config.scaley = 1.0;
1202     config.sizex = 0;
1203     config.sizey = 0;
1204     config.masterscalex = 1.0;
1205     config.masterscaley = 1.0;
1206     config.mastermovex = 0;
1207     config.mastermovey = 0;
1208     config.hassizex = 0;
1209     config.hassizey = 0;
1210     config.framerate = 0;
1211     config.stack = 0;
1212     config.stack1 = 0;
1213     config.dummy = 0;
1214     config.zlib = 0;
1215
1216     processargs(argn, argv);
1217     initLog(0,-1,0,0,-1,config.loglevel);
1218
1219     if(config.merge && config.cat) {
1220         msg("<error> Can't combine --cat and --merge");
1221         exit(1);
1222     }
1223     
1224     if(config.stack && config.cat) {
1225         msg("<error> Can't combine --cat and --stack");
1226         exit(1);
1227     }
1228
1229     if(config.stack) {
1230         if(config.overlay) {
1231             msg("<error> Can't combine -l and -t");
1232             exit(1);
1233         }
1234         if(config.clip) {
1235             msg("<error> Can't combine -c and -t");
1236             exit(1);
1237         }
1238         msg("<verbose> (stacking) %d files found\n", numslaves);
1239
1240         makestackmaster(&master);
1241     }
1242     else {
1243         int ret;
1244         msg("<verbose> master entity %s (named \"%s\")\n", master_filename, master_name);
1245         fi = open(master_filename, O_RDONLY|O_BINARY);
1246         if(fi<0) {
1247             msg("<fatal> Failed to open %s\n", master_filename);
1248             exit(1);
1249         }
1250         ret = swf_ReadSWF(fi, &master);
1251         if(ret<0) {
1252             msg("<fatal> Failed to read from %s\n", master_filename);
1253             exit(1);
1254         }
1255         swf_RemoveJPEGTables(&master);
1256         removeCommonTags(&master);
1257         msg("<debug> Read %d bytes from masterfile\n", ret);
1258         close(fi);
1259     }
1260
1261     for(t=0;t<numslaves;t++) {
1262             msg("<verbose> slave entity(%d) %s (%s \"%s\")\n", t+1, slave_filename[t], 
1263                     slave_isframe[t]?"frame":"object", slave_name[t]);
1264     }
1265
1266     if(config.dummy)
1267     {
1268         if(numslaves)
1269         {
1270             msg("<error> --dummy (-d) implies there are zero slave objects. You supplied %d.", numslaves);
1271             exit(1);
1272         }
1273         numslaves = 1;
1274         slave_filename[0] = "!!dummy!!";
1275         slave_name[0] = "!!dummy!!";
1276         slave_isframe[0] = 0;
1277     }
1278
1279     if (config.alloctest)
1280     {
1281         char*bitmap = malloc(sizeof(char)*65536);
1282         memset(bitmap, 0, 65536*sizeof(char));
1283         memset(bitmap, 1, 101*sizeof(char));
1284         swf_Relocate(&master, bitmap);
1285         newswf = master;
1286         free(bitmap);
1287 //      makestackmaster(&newswf);
1288     }
1289     else
1290     {
1291         if (!numslaves)
1292         {
1293             if(config.cat)
1294                 msg("<error> You must have at least two objects.");
1295             else
1296                 msg("<error> You must have at least one slave entity.");
1297             return 0;
1298         }
1299         for(t = 0; t < numslaves; t++)
1300         {
1301             config.movex = slave_movex[t];
1302             config.movey = slave_movey[t];
1303             config.scalex = slave_scalex[t];
1304             config.scaley = slave_scaley[t];
1305             config.isframe = slave_isframe[t];
1306
1307             msg("<notice> Combine [%s]%s and [%s]%s", master_name, master_filename,
1308                     slave_name[t], slave_filename[t]);
1309             if(!config.dummy)
1310             {
1311                 int ret;
1312                 fi = open(slave_filename[t], O_RDONLY|O_BINARY);
1313                 if(!fi) {
1314                     msg("<fatal> Failed to open %s\n", slave_filename[t]);
1315                     exit(1);
1316                 }
1317                 ret = swf_ReadSWF(fi, &slave);
1318                 if(ret<0) {
1319                     msg("<fatal> Failed to read from %s\n", slave_filename[t]);
1320                     exit(1);
1321                 }
1322                 msg("<debug> Read %d bytes from slavefile\n", ret);
1323                 close(fi);
1324                 swf_RemoveJPEGTables(&slave);
1325                 removeCommonTags(&slave);
1326             }
1327             else
1328             {
1329                 memset(&slave, 0, sizeof(slave));
1330                 slave.firstTag = swf_InsertTag(0, ST_END);
1331                 slave.frameRate = 0;
1332                 slave.fileVersion = 0;
1333                 slave.frameCount = 0;
1334             }
1335
1336             combine(&master, slave_name[t], &slave, &newswf);
1337             master = newswf;
1338         }
1339         if(config.dummy && !config.hassizex && !config.hassizey && !config.mastermovex && !config.mastermovey) {
1340             newswf.movieSize.xmin = newswf.movieSize.xmin*config.masterscalex;
1341             newswf.movieSize.ymin = newswf.movieSize.ymin*config.masterscaley;
1342             newswf.movieSize.xmax = newswf.movieSize.xmax*config.masterscalex;
1343             newswf.movieSize.ymax = newswf.movieSize.ymax*config.masterscaley;
1344         }
1345     }
1346
1347     if(!newswf.fileVersion)
1348         newswf.fileVersion = 4;
1349
1350     if(config.local_with_filesystem)
1351         newswf.fileAttributes &= ~FILEATTRIBUTE_USENETWORK;
1352     if(config.local_with_networking)
1353         newswf.fileAttributes |= FILEATTRIBUTE_USENETWORK;
1354
1355     fi = open(outputname, O_BINARY|O_RDWR|O_TRUNC|O_CREAT, 0777);
1356
1357     if(config.zlib) {
1358         if(newswf.fileVersion < 6)
1359             newswf.fileVersion = 6;
1360         newswf.compressed = 1;
1361         swf_WriteSWF(fi, &newswf);
1362     } else {
1363         newswf.compressed = -1; // don't compress
1364         swf_WriteSWF(fi, &newswf);
1365     }
1366     close(fi);
1367     return 0;
1368 }
1369