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