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