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