added fontalign support in swfdump
[swftools.git] / lib / rfxswf.c
1 /* vi: set sts=2 sw=2 :*/
2 /* rfxswf.c 
3
4    Library for creating and reading SWF files or parts of it.
5    There's a module directory which provides some extended functionality.
6    Most modules are included at the bottom of this file.
7
8    Part of the swftools package.
9
10    Copyright (c) 2000-2003 Rainer Böhme <rfxswf@reflex-studio.de>
11    Copyright (c) 2003 Matthias Kramm <kramm@quiss.org> 
12
13    This program is free software; you can redistribute it and/or modify
14    it under the terms of the GNU General Public License as published by
15    the Free Software Foundation; either version 2 of the License, or
16    (at your option) any later version.
17
18    This program is distributed in the hope that it will be useful,
19    but WITHOUT ANY WARRANTY; without even the implied warranty of
20    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21    GNU General Public License for more details.
22
23    You should have received a copy of the GNU General Public License
24    along with this program; if not, write to the Free Software
25    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
26
27 #include "mem.h"
28 #include "rfxswf.h"
29 #ifdef HAVE_ZLIB
30 #include <zlib.h>
31 #endif // HAVE_ZLIB
32
33 #ifndef RFXSWF_DISABLESOUND
34 #ifdef HAVE_LAME
35 #include "lame/lame.h"
36 #endif
37 #endif
38
39 #ifdef HAVE_TIME_H
40 #include <time.h>
41 #endif
42
43 #ifdef HAVE_IO_H
44 #include <io.h>
45 #endif
46
47 #include "./bitio.h"
48 #include "./MD5.h"
49 #include "./os.h"
50
51 // internal constants
52
53 #define MALLOC_SIZE     128
54 #define INSERT_RFX_TAG
55
56 #define MEMSIZE(l) (((l/MALLOC_SIZE)+1)*MALLOC_SIZE)
57
58 // inline wrapper functions
59
60 TAG * swf_NextTag(TAG * t) { return t->next; }
61 TAG * swf_PrevTag(TAG * t) { return t->prev; }
62 U16   swf_GetTagID(TAG * t)    { return t->id; }
63 U32   swf_GetTagLen(TAG * t) { return t->len; }
64 U8*   swf_GetTagLenPtr(TAG * t) { return &(t->data[t->len]); }
65 U32   swf_GetTagPos(TAG * t)   { return t->pos; }
66
67 void swf_SetTagPos(TAG * t,U32 pos)
68 { swf_ResetReadBits(t);
69   if (pos<=t->len) t->pos = pos;
70   else { 
71 #ifdef DEBUG_RFXSWF
72     fprintf(stderr,"SetTagPos(%d) out of bounds: TagID = %i\n",pos, t->id);
73 #endif
74   }
75 }
76
77 char* swf_GetString(TAG*t)
78 {
79     int pos = t->pos;
80     while(t->pos < t->len && swf_GetU8(t));
81     /* make sure we always have a trailing zero byte */
82     if(t->pos == t->len) {
83       if(t->len == t->memsize) {
84         swf_ResetWriteBits(t);
85         swf_SetU8(t, 0);
86         t->len = t->pos;
87       }
88       t->data[t->len] = 0;
89     }
90     return (char*)&(t->data[pos]);
91 }
92
93 U8 swf_GetU8(TAG * t)
94 { swf_ResetReadBits(t);
95   #ifdef DEBUG_RFXSWF
96     if (t->pos>=t->len) 
97     { fprintf(stderr,"GetU8() out of bounds: TagID = %i\n",t->id);
98       return 0;
99     }
100   #endif
101   return t->data[t->pos++];
102 }
103
104 U16 swf_GetU16(TAG * t)
105 { U16 res;
106   swf_ResetReadBits(t);
107   #ifdef DEBUG_RFXSWF
108     if (t->pos>(t->len-2)) 
109     { fprintf(stderr,"GetU16() out of bounds: TagID = %i\n",t->id);
110       return 0;
111     }
112   #endif
113   res = t->data[t->pos] | (t->data[t->pos+1]<<8);
114   t->pos+=2;
115   return res;
116 }
117
118 U32 swf_GetU32(TAG * t)
119 { U32 res;
120   swf_ResetReadBits(t);
121   #ifdef DEBUG_RFXSWF
122     if (t->pos>(t->len-4)) 
123     { fprintf(stderr,"GetU32() out of bounds: TagID = %i\n",t->id);
124       return 0;
125     }
126   #endif
127   res = t->data[t->pos]        | (t->data[t->pos+1]<<8) | 
128        (t->data[t->pos+2]<<16) | (t->data[t->pos+3]<<24);
129   t->pos+=4;
130   return res;
131 }
132
133 int swf_GetBlock(TAG * t,U8 * b,int l)
134 // returns number of bytes written (<=l)
135 // b = NULL -> skip data
136 { swf_ResetReadBits(t);
137   if ((t->len-t->pos)<l) l=t->len-t->pos;
138   if (b && l) memcpy(b,&t->data[t->pos],l);
139   t->pos+=l;
140   return l;
141 }
142
143 int swf_SetBlock(TAG * t,const U8 * b,int l)
144 // Appends Block to the end of Tagdata, returns size
145 { U32 newlen = t->len + l;
146   swf_ResetWriteBits(t);
147   if (newlen>t->memsize)
148   { U32  newmem  = MEMSIZE(newlen);  
149     U8 * newdata = (U8*)(rfx_realloc(t->data,newmem));
150     t->memsize = newmem;
151     t->data    = newdata;
152   }
153   if (b) memcpy(&t->data[t->len],b,l);
154   else memset(&t->data[t->len],0x00,l);
155   t->len+=l;
156   return l;
157 }
158
159 int swf_SetU8(TAG * t,U8 v)
160 { swf_ResetWriteBits(t);
161   if ((t->len+1)>t->memsize) return (swf_SetBlock(t,&v,1)==1)?0:-1;
162   t->data[t->len++] = v;
163   return 0;
164 }
165
166 int swf_SetU16(TAG * t,U16 v)
167 { U8 a[2];
168   a[0] = v&0xff;
169   a[1] = v>>8;
170   
171   swf_ResetWriteBits(t);
172   if ((t->len+2)>t->memsize) return (swf_SetBlock(t,a,2)==2)?0:-1;
173   t->data[t->len++] = a[0];
174   t->data[t->len++] = a[1];
175   return 0;
176 }
177 void swf_SetS16(TAG * t,int v)
178 {
179     if(v>32767 || v<-32768) {
180         fprintf(stderr, "Warning: S16 overflow: %d\n", v);
181     }
182     swf_SetU16(t, (S16)v);
183 }
184
185 int swf_SetU32(TAG * t,U32 v)
186 { U8 a[4];
187   a[0] = v&0xff;        // to ensure correct handling of non-intel byteorder
188   a[1] = (v>>8)&0xff;
189   a[2] = (v>>16)&0xff;
190   a[3] = (v>>24)&0xff;
191   
192   swf_ResetWriteBits(t);
193   if ((t->len+4)>t->memsize) return (swf_SetBlock(t,a,4)==4)?0:-1;
194   t->data[t->len++] = a[0];
195   t->data[t->len++] = a[1];
196   t->data[t->len++] = a[2];
197   t->data[t->len++] = a[3];
198   return 0;
199 }
200
201 U32 swf_GetBits(TAG * t,int nbits)
202 { U32 res = 0;
203   if (!nbits) return 0;
204   if (!t->readBit) t->readBit = 0x80;
205   while (nbits)
206   { res<<=1;
207 #ifdef DEBUG_RFXSWF
208     if (t->pos>=t->len) 
209     { fprintf(stderr,"GetBits() out of bounds: TagID = %i, pos=%d, len=%d\n",t->id, t->pos, t->len);
210       int i,m=t->len>10?10:t->len;
211       for(i=-1;i<m;i++) {
212         fprintf(stderr, "(%d)%02x ", i, t->data[i]);
213       } 
214       fprintf(stderr, "\n");
215       return res;
216     }
217 #endif
218     if (t->data[t->pos]&t->readBit) res|=1;
219     t->readBit>>=1;
220     nbits--;
221     if (!t->readBit)
222     { if (nbits) t->readBit = 0x80;
223       t->pos++;
224     }
225   }
226   return res;
227 }
228
229 S32 swf_GetSBits(TAG * t,int nbits)
230 { U32 res = swf_GetBits(t,nbits);
231   if (res&(1<<(nbits-1))) res|=(0xffffffff<<nbits);  
232   return (S32)res;
233 }
234
235 U32 reader_GetBits(reader_t*reader, int nbits)
236 { return reader_readbits(reader, nbits);
237 }
238 S32 reader_GetSBits(reader_t*reader, int nbits)
239 { U32 res = reader_readbits(reader, nbits);
240   if (res&(1<<(nbits-1))) res|=(0xffffffff<<nbits);  
241   return (S32)res;
242 }
243
244 int swf_SetBits(TAG * t,U32 v,int nbits)
245 { U32 bm = 1<<(nbits-1);
246
247   while (nbits)
248   { if (!t->writeBit)
249     { if (FAILED(swf_SetU8(t,0))) return -1;
250       t->writeBit = 0x80;
251     }
252     if (v&bm) t->data[t->len-1] |= t->writeBit;
253     bm>>=1;
254     t->writeBit>>=1;
255     nbits--;
256   }
257   return 0;
258 }
259
260 // Advanced Data Access Functions
261
262 double swf_GetFixed(TAG * t)
263 {
264   U16 low =  swf_GetU16(t);
265   U16 high = swf_GetU16(t);
266   return high + low*(1/65536.0);
267 }
268 void swf_SetFixed(TAG * t, double f)
269 {
270   U16 fr = (U16)((f-(int)f)*65536);
271   swf_SetU16(t, fr);
272   swf_SetU16(t, (U16)f - (f<0 && fr!=0));
273 }
274 float swf_GetFixed8(TAG * t)
275 {
276   U8 low =  swf_GetU8(t);
277   U8 high = swf_GetU8(t);
278   return (float)(high + low*(1/256.0));
279 }
280 void swf_SetFixed8(TAG * t, float f)
281 {
282   U8 fr = (U8)((f-(int)f)*256);
283   swf_SetU8(t, fr);
284   swf_SetU8(t, (U8)f - (f<0 && fr!=0));
285 }
286
287 U32 swf_GetU30(TAG*tag)
288 {
289     U32 shift = 0;
290     U32 s = 0;
291     int nr=0;
292     while(1) {
293         U8 b = swf_GetU8(tag);
294         nr++;
295         s|=(b&127)<<shift;
296         shift+=7;
297         if(!(b&128) || shift>=32)
298             break;
299     }
300     /*int nr2= swf_SetU30(0, s);
301     if(nr!=nr2) {
302       printf("Unsigned value %d stored in %d bytes, I'd store it in %d bytes\n", s, nr, nr2);
303     }*/
304     return s;
305 }
306
307 int swf_SetU30(TAG*tag, U32 u)
308 {
309     int nr = 0;
310     do {
311         if(tag)
312           swf_SetU8(tag, (u&~0x7f?0x80:0) | (u&0x7F));
313         u>>=7;
314         nr++;
315     } while(u);
316     return nr;
317 }
318
319 void swf_SetABCU32(TAG*tag, U32 u)
320 {
321   do {
322       swf_SetU8(tag, (u&~0x7f?0x80:0) | (u&0x7F));
323       u>>=7;
324   } while(u);
325 }
326 U32 swf_GetABCU32(TAG*tag)
327 {
328   return swf_GetU30(tag);
329 }
330 void swf_SetABCS32(TAG*tag, S32 v)
331 {
332   swf_SetABCU32(tag, v);
333 }
334 S32 swf_GetABCS32(TAG*tag)
335 {
336   return swf_GetABCU32(tag);
337 }
338
339 #if 0
340
341 /*The AVM2 spec is just plain wrong, claiming that S32 values are sign
342 extended. They're not.
343 This wastes up to 4 bytes for every negative value. */
344
345 void swf_SetABCS32(TAG*tag, S32 s)
346 {
347   printf("write S32: %d\n", s);
348     S32 neg = s<0?-1:0;
349     U8 sign = s<0?0x40:0;
350     while(1) {
351         U8 val = s&0x7f;
352         U8 vsign = s&0x40;
353         s>>=7;
354         neg>>=7;
355         if(s==neg && vsign==sign) {
356             /* if the value we now write has the same sign as s
357                and all the remaining bits are equal to the sign of s
358                too, stop writing */
359             swf_SetU8(tag, val);
360             printf("put %02x\n", val);
361             break;
362         } else {
363             swf_SetU8(tag, 0x80 | val);
364             printf("put %02x\n", 0x80|val);
365         }
366     };
367 }
368 int swf_GetS30(TAG*tag)
369 {
370     U32 shift = 0;
371     U32 s = 0;
372     int nr=0;
373     while(1) {
374         U8 b = swf_GetU8(tag);
375         nr++;
376         nt i,m=t->len>10?10:t->len;
377                 for(i=0;i<m;i++) {
378                             fprintf(stderr, "%02x ", t->data[i]);
379                                     } 
380                         fprintf(stderr, "\n");
381                         s|=(b&127)<<shift;
382         shift+=7;
383         if(!(b&128) || shift>=32) {
384             if(b&64) {
385                 if(shift<32) 
386                   s|=0xffffffff<<shift;
387             }
388             break;
389         }
390     }
391     /* It's not uncommon for other applications (Flex for all negative numbers, and
392        Flash for -1) to generate a lot more bytes than would be necessary.
393        int nr2= swf_SetS30(0, s);
394     if(nr!=nr2) {
395       printf("Signed value %d stored in %d bytes, I'd store it in %d bytes\n", s, nr, nr2);
396     }*/
397     return s;
398 }
399 #endif
400
401 int swf_SetU30String(TAG*tag, const char*str, int l)
402 {
403     int len=0;
404     len+=swf_SetU30(tag, l);
405     len+=l;
406     swf_SetBlock(tag, (void*)str, l);
407     return len;
408 }
409 float swf_GetF16(TAG * t)
410 {
411     // D16 is 1-5-10
412     // D32 is 1-8-23
413     U16 f1 = swf_GetU16(t);
414     if(!f1) return 0;
415     U32 f2 = (f1&0x8000)<<16; //sign
416     f2 |= ((f1&0x7c00)<<13)+(0x40000000-(0x4000<<13)); //exp
417     f2 |= (f1&0x03ff)<<13; //mantissa
418     fprintf(stderr, "%f = %d-%d-%x\n", *(float*)&f2, f1>>15, (f1>>10)&31, f1&0x3ff);
419     return *(float*)&f2;
420 }
421 void swf_SetF16(TAG * t, float f)
422 {
423     U32 f1 = *(U32*)&f;
424     U16 f2 = (f1>>16)&0x8000;
425     int exp = ((f1>>23)&0xff)-0x80+0x10;
426     if(exp<0) {
427         exp = 0;
428         fprintf(stderr, "Exponent underflow in FLOAT16 encoding\n");
429     } else if(exp>=32) {
430         exp = 31;
431         fprintf(stderr, "Exponent overflow in FLOAT16 encoding\n");
432     }
433     f2 |= exp<<10;
434     f2 |= (f1>>13)&0x3ff;
435     swf_SetU16(t, f2);
436 }
437
438 double swf_GetD64(TAG*tag)
439 {
440     /* FIXME: this is not big-endian compatible */
441     double value = *(double*)&tag->data[tag->pos];
442     swf_GetU32(tag);
443     swf_GetU32(tag);
444     return value;
445 }
446 int swf_SetD64(TAG*tag, double v)
447 {
448     /* FIXME: this is not big-endian compatible */
449     swf_SetU32(tag, ((U32*)&v)[0]);
450     swf_SetU32(tag, ((U32*)&v)[1]);
451     return 8;
452 }
453 int swf_GetU24(TAG*tag)
454 {
455     int b1 = swf_GetU8(tag);
456     int b2 = swf_GetU8(tag);
457     int b3 = swf_GetU8(tag);
458     return b3<<16|b2<<8|b1;
459 }
460 int swf_GetS24(TAG*tag)
461 {
462     int b1 = swf_GetU8(tag);
463     int b2 = swf_GetU8(tag);
464     int b3 = swf_GetU8(tag);
465     if(b3&0x80) {
466         return -1-((b3<<16|b2<<8|b1)^0xffffff);
467     } else {
468         return b3<<16|b2<<8|b1;
469     }
470 }
471 int swf_SetU24(TAG*tag, U32 v)
472 {
473     if(tag) {
474         if(v&0xff000000)
475           fprintf(stderr, "Error: Overflow in swf_SetU24()\n");
476         swf_SetU8(tag, v);
477         swf_SetU8(tag, v>>8);
478         swf_SetU8(tag, v>>16);
479     }
480     return 3;
481 }
482 int swf_SetS24(TAG*tag, U32 v)
483 {
484     if(tag) {
485         if(!(v&0xff000000))
486           return swf_SetU24(tag, v);
487         if((v&0xff000000)!=0xff000000) {
488           fprintf(stderr, "Error: Overflow in swf_SetS24()\n");
489         }
490         swf_SetU8(tag, v);
491         swf_SetU8(tag, v>>8);
492         swf_SetU8(tag, v>>16);
493     }
494     return 3;
495 }
496
497
498 int swf_SetRGB(TAG * t,RGBA * col)
499 { if (!t) return -1;
500   if (col)
501   { swf_SetU8(t,col->r);
502     swf_SetU8(t,col->g);
503     swf_SetU8(t,col->b);
504   } else swf_SetBlock(t,NULL,3);
505   return 0;
506 }
507 void swf_GetRGB(TAG * t, RGBA * col)
508 {
509     RGBA dummy;
510     if(!col)
511         col = &dummy;
512     col->r = swf_GetU8(t);
513     col->g = swf_GetU8(t);
514     col->b = swf_GetU8(t);
515     col->a = 255;
516 }
517
518 int swf_SetRGBA(TAG * t,RGBA * col)
519 { if (!t) return -1;
520   if (col)
521   { swf_SetU8(t,col->r);
522     swf_SetU8(t,col->g);
523     swf_SetU8(t,col->b);
524     swf_SetU8(t,col->a);
525   } else swf_SetBlock(t,NULL,4);
526   return 0;
527 }
528 void swf_GetRGBA(TAG * t, RGBA * col)
529 {
530     RGBA dummy;
531     if(!col)
532         col = &dummy;
533     col->r = swf_GetU8(t);
534     col->g = swf_GetU8(t);
535     col->b = swf_GetU8(t);
536     col->a = swf_GetU8(t);
537 }
538
539 void swf_GetGradient(TAG * tag, GRADIENT * gradient, char alpha)
540 {
541     int t;
542     if(!tag) {
543       memset(gradient, 0, sizeof(GRADIENT));
544       return;
545     }
546     U8 num = swf_GetU8(tag) & 15;
547     if(gradient) {
548         gradient->num = num;
549         gradient->rgba = (RGBA*)rfx_calloc(sizeof(RGBA)*gradient->num);
550         gradient->ratios = (U8*)rfx_calloc(sizeof(gradient->ratios[0])*gradient->num);
551     }
552     for(t=0;t<num;t++)
553     {
554         U8 ratio = swf_GetU8(tag);
555         RGBA color;
556         if(!alpha)
557             swf_GetRGB(tag, &color);
558         else
559             swf_GetRGBA(tag, &color);
560         if(gradient) {
561           gradient->ratios[t] = ratio;
562           gradient->rgba[t] = color;
563         }
564     }
565 }
566
567 void swf_SetGradient(TAG * tag, GRADIENT * gradient, char alpha)
568 {
569     int t;
570     if(!tag) {
571       memset(gradient, 0, sizeof(GRADIENT));
572       return;
573     }
574     swf_SetU8(tag, gradient->num);
575     for(t=0; t<8 && t<gradient->num; t++)
576     {
577         swf_SetU8(tag, gradient->ratios[t]);
578         if(!alpha)
579             swf_SetRGB(tag, &gradient->rgba[t]);
580         else
581             swf_SetRGBA(tag, &gradient->rgba[t]);
582     }
583 }
584
585 void swf_FreeGradient(GRADIENT* gradient)
586 {
587   if(gradient->ratios)
588     rfx_free(gradient->ratios);
589   if(gradient->rgba)
590     rfx_free(gradient->rgba);
591   memset(gradient, 0, sizeof(GRADIENT));
592 }
593
594 int swf_CountUBits(U32 v,int nbits)
595 { int n = 32;
596   U32 m = 0x80000000;
597   if(v == 0x00000000) n = 0; 
598   else
599     while (!(v&m))
600     { n--;
601       m>>=1;
602     } 
603   return (n>nbits)?n:nbits;
604 }
605
606 int swf_CountBits(U32 v,int nbits)
607 { int n = 33;
608   U32 m = 0x80000000;
609   if (v&m)
610   { if(v == 0xffffffff) n = 1;
611     else 
612     while (v&m)
613     { n--;
614       m>>=1;
615     } 
616   }
617   else
618   { if(v == 0x00000000) n = 0; 
619     else
620     while (!(v&m))
621     { n--;
622       m>>=1;
623     } 
624   }
625   return (n>nbits)?n:nbits;
626 }
627
628 int swf_GetRect(TAG * t,SRECT * r)
629 { int nbits;
630   SRECT dummy;
631   if(!t) {r->xmin=r->xmax=r->ymin=r->ymax=0;return 0;}
632   if (!r) r = &dummy;
633   nbits = (int) swf_GetBits(t,5);
634   r->xmin = swf_GetSBits(t,nbits);
635   r->xmax = swf_GetSBits(t,nbits);
636   r->ymin = swf_GetSBits(t,nbits);
637   r->ymax = swf_GetSBits(t,nbits);
638   return 0;
639 }
640
641 int reader_GetRect(reader_t*reader,SRECT * r)
642 { int nbits;
643   SRECT dummy;
644   if (!r) r = &dummy;
645   nbits = (int) reader_GetBits(reader,5);
646   r->xmin = reader_GetSBits(reader,nbits);
647   r->xmax = reader_GetSBits(reader,nbits);
648   r->ymin = reader_GetSBits(reader,nbits);
649   r->ymax = reader_GetSBits(reader,nbits);
650   return 0;
651 }
652
653 int swf_SetRect(TAG * t,SRECT * r)
654 { int nbits;
655     
656   nbits = swf_CountBits(r->xmin,0);
657   nbits = swf_CountBits(r->xmax,nbits);
658   nbits = swf_CountBits(r->ymin,nbits);
659   nbits = swf_CountBits(r->ymax,nbits);
660   if(nbits>=32) {
661     fprintf(stderr, "rfxswf: Warning: num_bits overflow in swf_SetRect\n");
662     nbits=31;
663   }
664
665   swf_SetBits(t,nbits,5);
666   swf_SetBits(t,r->xmin,nbits);
667   swf_SetBits(t,r->xmax,nbits);
668   swf_SetBits(t,r->ymin,nbits);
669   swf_SetBits(t,r->ymax,nbits);
670
671   return 0;
672 }
673
674 SRECT swf_ClipRect(SRECT border, SRECT r)
675 {
676     if(r.xmax > border.xmax) r.xmax = border.xmax;
677     if(r.ymax > border.ymax) r.ymax = border.ymax;
678     if(r.xmax < border.xmin) r.xmax = border.xmin;
679     if(r.ymax < border.ymin) r.ymax = border.ymin;
680     
681     if(r.xmin > border.xmax) r.xmin = border.xmax;
682     if(r.ymin > border.ymax) r.ymin = border.ymax;
683     if(r.xmin < border.xmin) r.xmin = border.xmin;
684     if(r.ymin < border.ymin) r.ymin = border.ymin;
685     return r;
686 }
687
688 void swf_ExpandRect(SRECT*src, SPOINT add)
689 {
690     if((src->xmin | src->ymin | src->xmax | src->ymax)==0) {
691         src->xmin = add.x;
692         src->ymin = add.y;
693         src->xmax = add.x;
694         src->ymax = add.y;
695         if((add.x|add.y) == 0) src->xmax++; //make sure the bbox is not NULL anymore
696         return;
697     }
698     if(add.x < src->xmin)
699         src->xmin = add.x;
700     if(add.x > src->xmax)
701         src->xmax = add.x;
702     if(add.y < src->ymin)
703         src->ymin = add.y;
704     if(add.y > src->ymax)
705         src->ymax = add.y;
706 }
707 void swf_ExpandRect2(SRECT*src, SRECT*add)
708 {
709     if((add->xmin | add->ymin | add->xmax | add->ymax)==0)
710         return;
711     if((src->xmin | src->ymin | src->xmax | src->ymax)==0)
712         *src = *add;
713     if(add->xmin < src->xmin)
714         src->xmin = add->xmin;
715     if(add->ymin < src->ymin)
716         src->ymin = add->ymin;
717     if(add->xmax > src->xmax)
718         src->xmax = add->xmax;
719     if(add->ymax > src->ymax)
720         src->ymax = add->ymax;
721 }
722 void swf_ExpandRect3(SRECT*src, SPOINT center, int radius)
723 {
724     if((src->xmin | src->ymin | src->xmax | src->ymax)==0) {
725         src->xmin = center.x-radius;
726         src->ymin = center.y-radius;
727         src->xmax = center.x+radius;
728         src->ymax = center.y+radius;
729         if((center.x|center.y|radius) == 0) src->xmax++; //make sure the bbox is not NULL anymore
730         return;
731     }
732     if(center.x - radius < src->xmin)
733         src->xmin = center.x - radius;
734     if(center.x + radius > src->xmax)
735         src->xmax = center.x + radius;
736     if(center.y - radius < src->ymin)
737         src->ymin = center.y - radius;
738     if(center.y + radius > src->ymax)
739         src->ymax = center.y + radius;
740 }
741 SPOINT swf_TurnPoint(SPOINT p, MATRIX* m)
742 {
743     SPOINT r;
744     r.x = (int)(m->sx*(1/65536.0)*p.x + m->r1*(1/65536.0)*p.y + 0.5) + m->tx;
745     r.y = (int)(m->r0*(1/65536.0)*p.x + m->sy*(1/65536.0)*p.y + 0.5) + m->ty;
746     return r;
747 }
748 SRECT swf_TurnRect(SRECT r, MATRIX* m)
749 {
750     SRECT g;
751     SPOINT p1,p2,p3,p4,pp1,pp2,pp3,pp4;
752     if(!m)
753       return r;
754     p1.x = r.xmin;p1.y = r.ymin;
755     p2.x = r.xmax;p2.y = r.ymin;
756     p3.x = r.xmin;p3.y = r.ymax;
757     p4.x = r.xmax;p4.y = r.ymax;
758     pp1 = swf_TurnPoint(p1, m);
759     pp2 = swf_TurnPoint(p2, m);
760     pp3 = swf_TurnPoint(p3, m);
761     pp4 = swf_TurnPoint(p4, m);
762     g.xmin = g.xmax = pp1.x;
763     g.ymin = g.ymax = pp1.y;
764     swf_ExpandRect(&g, pp2);
765     swf_ExpandRect(&g, pp3);
766     swf_ExpandRect(&g, pp4);
767     return g;
768 }
769         
770
771 int swf_GetMatrix(TAG * t,MATRIX * m)
772 { MATRIX dummy;
773   int nbits;
774     
775   if (!m) m = &dummy;
776   
777   if (!t)
778   { m->sx = m->sy = 0x10000;
779     m->r0 = m->r1 = 0;
780     m->tx = m->ty = 0;
781     return -1;
782   }
783
784   swf_ResetReadBits(t);
785   
786   if (swf_GetBits(t,1))
787   { nbits = swf_GetBits(t,5);
788     m->sx = swf_GetSBits(t,nbits);
789     m->sy = swf_GetSBits(t,nbits);
790   }
791   else m->sx = m->sy = 0x10000;
792   
793   if (swf_GetBits(t,1))
794   { nbits = swf_GetBits(t,5);
795     m->r0 = swf_GetSBits(t,nbits);
796     m->r1 = swf_GetSBits(t,nbits);
797   }
798   else m->r0 = m->r1 = 0x0;
799
800   nbits = swf_GetBits(t,5);
801   m->tx = swf_GetSBits(t,nbits);
802   m->ty = swf_GetSBits(t,nbits);
803   
804   return 0;
805 }
806
807 int swf_SetMatrix(TAG * t,MATRIX * m)
808 { int nbits;
809   MATRIX ma;
810
811   if (!m)
812   { m = &ma;
813     ma.sx = ma.sy = 0x10000;
814     ma.r0 = ma.r1 = 0;
815     ma.tx = ma.ty = 0;
816   }
817
818   swf_ResetWriteBits(t);
819
820   if ((m->sx==0x10000)&&(m->sy==0x10000)) swf_SetBits(t,0,1);
821   else
822   { swf_SetBits(t,1,1);
823     nbits = swf_CountBits(m->sx,0);
824     nbits = swf_CountBits(m->sy,nbits);
825     if(nbits>=32) {
826         /* TODO: happens on AMD64 systems for normal values? */
827         fprintf(stderr,"rfxswf: Error: matrix values too large\n");
828         nbits = 31;
829     }
830     swf_SetBits(t,nbits,5);
831     swf_SetBits(t,m->sx,nbits);
832     swf_SetBits(t,m->sy,nbits);
833   }
834
835   if ((!m->r0)&&(!m->r1)) swf_SetBits(t,0,1);
836   else
837   { swf_SetBits(t,1,1);
838     nbits = swf_CountBits(m->r0,0);
839     nbits = swf_CountBits(m->r1,nbits);
840     if(nbits>=32) {
841         fprintf(stderr,"rfxswf: Error: matrix values too large\n");
842         nbits = 31;
843     }
844     swf_SetBits(t,nbits,5);
845     swf_SetBits(t,m->r0,nbits);
846     swf_SetBits(t,m->r1,nbits);
847   }
848
849   nbits = swf_CountBits(m->tx,0);
850   nbits = swf_CountBits(m->ty,nbits);
851   if(nbits>=32) {
852       fprintf(stderr,"rfxswf: Error: matrix values too large\n");
853       nbits = 31;
854   }
855   swf_SetBits(t,nbits,5);
856   swf_SetBits(t,m->tx,nbits);
857   swf_SetBits(t,m->ty,nbits);
858
859   return 0;
860 }
861
862 int swf_GetCXForm(TAG * t,CXFORM * cx,U8 alpha)
863 { CXFORM cxf;
864   int hasadd;
865   int hasmul;
866   int nbits;
867     
868   if (!cx) cx = &cxf;
869   
870   cx->a0 = cx->r0 = cx->g0 = cx->b0 = 256;
871   cx->a1 = cx->r1 = cx->g1 = cx->b1 = 0;
872
873   if (!t) return 0;
874   
875   swf_ResetReadBits(t);
876   hasadd = swf_GetBits(t,1);
877   hasmul = swf_GetBits(t,1);
878   nbits  = swf_GetBits(t,4);
879
880   if (hasmul)
881   { cx->r0 = (S16)swf_GetSBits(t,nbits);
882     cx->g0 = (S16)swf_GetSBits(t,nbits);
883     cx->b0 = (S16)swf_GetSBits(t,nbits);
884     if (alpha)
885       cx->a0 = (S16)swf_GetSBits(t,nbits);
886   }
887
888   if (hasadd)
889   { cx->r1 = (S16)swf_GetSBits(t,nbits);
890     cx->g1 = (S16)swf_GetSBits(t,nbits);
891     cx->b1 = (S16)swf_GetSBits(t,nbits);
892     if (alpha)
893       cx->a1 = (S16)swf_GetSBits(t,nbits);
894   }
895   
896   return 0;
897 }
898
899 int swf_SetCXForm(TAG * t,CXFORM * cx,U8 alpha)
900 { CXFORM cxf;
901   int hasadd;
902   int hasmul;
903   int nbits;
904     
905   if (!cx)
906   { cx = &cxf;
907     cx->a0 = cx->r0 = cx->g0 = cx->b0 = 256;
908     cx->a1 = cx->r1 = cx->g1 = cx->b1 = 0;
909   }
910
911   if (!alpha)
912   { cx->a0 = 256;
913     cx->a1 = 0;
914   }
915
916   nbits = 0;
917
918   hasmul = (cx->a0!=256)||(cx->r0!=256)||(cx->g0!=256)||(cx->b0!=256);
919   hasadd = cx->a1|cx->r1|cx->g1|cx->b1;
920
921   if (hasmul)
922   { if (alpha) nbits = swf_CountBits((S32)cx->a0,nbits);
923     nbits = swf_CountBits((S32)cx->r0,nbits);
924     nbits = swf_CountBits((S32)cx->g0,nbits);
925     nbits = swf_CountBits((S32)cx->b0,nbits);
926   }
927
928   if (hasadd)
929   { if (alpha) nbits = swf_CountBits((S32)cx->a1,nbits);
930     nbits = swf_CountBits((S32)cx->r1,nbits);
931     nbits = swf_CountBits((S32)cx->g1,nbits);
932     nbits = swf_CountBits((S32)cx->b1,nbits);
933   }
934   
935   swf_ResetWriteBits(t);
936   swf_SetBits(t,hasadd?1:0,1);
937   swf_SetBits(t,hasmul?1:0,1);
938   swf_SetBits(t,nbits,4);
939
940   if (hasmul)
941   { swf_SetBits(t,cx->r0,nbits);
942     swf_SetBits(t,cx->g0,nbits);
943     swf_SetBits(t,cx->b0,nbits);
944     if (alpha) swf_SetBits(t,cx->a0,nbits);
945   }
946
947   if (hasadd)
948   { swf_SetBits(t,cx->r1,nbits);
949     swf_SetBits(t,cx->g1,nbits);
950     swf_SetBits(t,cx->b1,nbits);
951     if (alpha) swf_SetBits(t,cx->a1,nbits);
952   }
953   
954   return 0;
955 }
956
957 //int swf_GetPoint(TAG * t,SPOINT * p) { return 0; }
958 //int swf_SetPoint(TAG * t,SPOINT * p) { return 0; }
959
960 void  swf_SetPassword(TAG * t, const char * password)
961 {
962     /* WARNING: crypt_md5 is not reentrant */
963     char salt[3];
964     char* md5string;
965
966 #if defined(HAVE_LRAND48) && defined(HAVE_SRAND48) && defined(HAVE_TIME_H) && defined(HAVE_TIME)
967     srand48(time(0));
968     salt[0] = "abcdefghijklmnopqrstuvwxyz0123456789"[lrand48()%36];
969     salt[1] = "abcdefghijklmnopqrstuvwxyz0123456789"[lrand48()%36];
970 #else
971     salt[0] = 'l';
972     salt[1] = '8';
973     fprintf(stderr, "rfxswf: Warning- no usable random generator found\n");
974     fprintf(stderr, "Your password will be vulnerable to dictionary attacks\n");
975 #endif
976     salt[2] = 0;
977     
978     md5string = crypt_md5(password, salt);
979
980     swf_SetU16(t,0);
981     swf_SetString(t, md5string);
982
983
984 void swf_SetString(TAG*t, const char* s) 
985 {
986     if(!s) {
987         swf_SetU8(t, 0);
988     } else {
989         swf_SetBlock(t,(U8*)s,strlen(s)+1);
990     }
991 }
992
993 int swf_VerifyPassword(TAG * t, const char * password)
994 {
995     char*md5string1, *md5string2;
996     char*x;
997     char*salt;
998     int n;
999
1000     if(t->len >= 5 && t->pos==0 && 
1001        t->data[0] == 0 &&
1002        t->data[1] == 0) {
1003       swf_GetU16(t);
1004     } else {
1005       printf("%d %d %d %d\n", t->len, t->pos, t->data[0], t->data[1]);
1006     }
1007
1008     md5string1 = swf_GetString(t);
1009
1010     if(strncmp(md5string1, "$1$",3 )) {
1011         fprintf(stderr, "rfxswf: no salt in pw string\n");
1012         return 0;
1013     }
1014     x = strchr(md5string1+3, '$');
1015     if(!x) {
1016         fprintf(stderr, "rfxswf: invalid salt format in pw string\n");
1017         return 0;
1018     }
1019     n = x-(md5string1+3);
1020     salt = (char*)rfx_alloc(n+1);
1021     memcpy(salt, md5string1+3, n);
1022     salt[n] = 0;
1023
1024     md5string2 = crypt_md5(password, salt);
1025     rfx_free(salt);
1026     if(strcmp(md5string1, md5string2) != 0)
1027         return 0;
1028     return 1;
1029 }
1030
1031 // Tag List Manipulating Functions
1032
1033 TAG * swf_InsertTag(TAG * after,U16 id)
1034 { TAG * t;
1035
1036   t = (TAG *)rfx_calloc(sizeof(TAG));
1037   t->id = id;
1038   
1039   if (after)
1040   {
1041     t->prev  = after;
1042     t->next  = after->next;
1043     after->next = t;
1044     if (t->next) t->next->prev = t;
1045   }
1046   return t;
1047 }
1048
1049 TAG * swf_InsertTagBefore(SWF* swf, TAG * before,U16 id)
1050 { TAG * t;
1051
1052   t = (TAG *)rfx_calloc(sizeof(TAG));
1053   t->id = id;
1054   
1055   if (before)
1056   {
1057     t->next  = before;
1058     t->prev  = before->prev;
1059     before->prev = t;
1060     if (t->prev) t->prev->next = t;
1061   }
1062   if(swf && swf->firstTag == before) {
1063     swf->firstTag = t;
1064   }
1065   return t;
1066 }
1067
1068 void swf_ClearTag(TAG * t)
1069 {
1070   if (t->data) rfx_free(t->data);
1071   t->data = 0;
1072   t->pos = 0;
1073   t->len = 0;
1074   t->readBit = 0;
1075   t->writeBit = 0;
1076   t->memsize = 0;
1077 }
1078
1079 void swf_ResetTag(TAG*tag, U16 id)
1080 {
1081     tag->len = tag->pos = tag->readBit = tag->writeBit = 0;
1082     tag->id = id;
1083 }
1084
1085 TAG* swf_CopyTag(TAG*tag, TAG*to_copy)
1086 {
1087     tag = swf_InsertTag(tag, to_copy->id);
1088     swf_SetBlock(tag, to_copy->data, to_copy->len);
1089     return tag;
1090 }
1091
1092 TAG* swf_DeleteTag(SWF*swf, TAG * t)
1093 {
1094   TAG*next = t->next;
1095
1096   if (swf && swf->firstTag==t) 
1097     swf->firstTag = t->next;
1098   if (t->prev) t->prev->next = t->next;
1099   if (t->next) t->next->prev = t->prev;
1100
1101   if (t->data) rfx_free(t->data);
1102   rfx_free(t);
1103   return next;
1104 }
1105
1106 TAG * swf_ReadTag(reader_t*reader, TAG * prev)
1107 { TAG * t;
1108   U16 raw;
1109   U32 len;
1110   int id;
1111
1112   if (reader->read(reader, &raw, 2) !=2 ) return NULL;
1113   raw = SWAP16(raw);
1114
1115   len = raw&0x3f;
1116   id  = raw>>6;
1117
1118   if (len==0x3f)
1119   {
1120       if (reader->read(reader, &len, 4) != 4) return NULL;
1121       len = SWAP32(len);
1122   }
1123
1124   if (id==ST_DEFINESPRITE) len = 2*sizeof(U16);
1125   // Sprite handling fix: Flatten sprite tree
1126
1127   t = (TAG *)rfx_calloc(sizeof(TAG));
1128   
1129   t->len = len;
1130   t->id  = id;
1131
1132   if (t->len)
1133   { t->data = (U8*)rfx_alloc(t->len);
1134     t->memsize = t->len;
1135     if (reader->read(reader, t->data, t->len) != t->len) {
1136       fprintf(stderr, "rfxswf: Warning: Short read (tagid %d). File truncated?\n", t->id);
1137       free(t->data);t->data=0;
1138       free(t);
1139       return NULL;
1140     }
1141   }
1142
1143   if (prev)
1144   {
1145     t->prev  = prev;
1146     prev->next = t;
1147   }
1148
1149   return t;
1150 }
1151
1152 int swf_DefineSprite_GetRealSize(TAG * t);
1153
1154 int swf_WriteTag2(writer_t*writer, TAG * t)
1155 // returns tag length in bytes (incl. Header), -1 = Error
1156 // writer = 0 -> no output
1157 { U16 raw[3];
1158   U32 len;
1159   int short_tag;
1160
1161   if (!t) return -1;
1162
1163   len = (t->id==ST_DEFINESPRITE)?swf_DefineSprite_GetRealSize(t):t->len;
1164
1165   short_tag = len<0x3f&&
1166     (t->id!=ST_DEFINEBITSLOSSLESS&&t->id!=ST_DEFINEBITSLOSSLESS2&&t->id!=ST_SOUNDSTREAMBLOCK&&
1167      t->id!=ST_DEFINEBITSJPEG&&t->id!=ST_DEFINEBITSJPEG2&&t->id!=ST_DEFINEBITSJPEG3);
1168
1169   if (writer)
1170   {
1171 #ifdef MEASURE
1172   int oldpos = writer->pos;
1173 #endif
1174     
1175     if (short_tag)
1176     { raw[0] = SWAP16(len|((t->id&0x3ff)<<6));
1177       if (writer->write(writer,raw,2)!=2)
1178       {
1179         #ifdef DEBUG_RFXSWF
1180           fprintf(stderr,"WriteTag() failed: Short Header.\n");
1181         #endif
1182         return -1;
1183       }
1184     }
1185     else
1186     {
1187       raw[0] = SWAP16((t->id<<6)|0x3f);
1188       if (writer->write(writer,raw,2)!=2)
1189       {
1190 #ifdef DEBUG_RFXSWF
1191           fprintf(stderr,"WriteTag() failed: Long Header (1).\n");
1192 #endif
1193           return -1;
1194       }
1195       
1196       len = SWAP32(len);
1197       if (writer->write(writer,&len,4)!=4)
1198       {
1199         #ifdef DEBUG_RFXSWF
1200           fprintf(stderr,"WriteTag() failed: Long Header (2).\n");
1201         #endif
1202         return -1;
1203       }
1204     }
1205     
1206     if (t->data)
1207     { if (writer->write(writer,t->data,t->len)!=t->len)
1208       {
1209         #ifdef DEBUG_RFXSWF
1210           fprintf(stderr,"WriteTag() failed: Data.\n");
1211         #endif
1212         return -1;
1213       }
1214     }
1215     #ifdef DEBUG_RFXSWF
1216       else if (t->len) fprintf(stderr,"WriteTag(): Tag Data Error, id=%i\n",t->id);
1217     #endif
1218
1219 #ifdef MEASURE
1220   writer->flush(writer);
1221   printf("TAG %s costs %d bytes\n", swf_TagGetName(t), writer->pos-oldpos);
1222 #endif
1223   }
1224
1225   return t->len+(short_tag?2:6);
1226 }
1227
1228 int swf_WriteTag(int handle, TAG * t)
1229 {
1230   writer_t writer;
1231   int len = 0;
1232   if(handle<0)
1233     return swf_WriteTag2(0, t);
1234   writer_init_filewriter(&writer, handle);
1235   len = swf_WriteTag2(&writer, t);
1236   writer.finish(&writer);
1237   return len;
1238 }
1239
1240 int swf_DefineSprite_GetRealSize(TAG * t)
1241 // Sprite Handling: Helper function to pack DefineSprite-Tag
1242 { U32 len = t->len;
1243   if(len>4) { // folded sprite
1244       return t->len;
1245   }
1246   do
1247   { t = swf_NextTag(t);
1248     if (t && t->id!=ST_DEFINESPRITE) len += swf_WriteTag(-1, t);
1249     else t = NULL;
1250   } while (t&&(t->id!=ST_END));
1251   return len;
1252 }
1253
1254 void swf_UnFoldSprite(TAG * t)
1255 {
1256   U16 id,tmp;
1257   U32 len;
1258   TAG*next = t;
1259   U16 spriteid,spriteframes;
1260   int level;
1261   if(t->id!=ST_DEFINESPRITE)
1262     return;
1263   if(t->len<=4) // not folded
1264     return;
1265
1266   swf_SetTagPos(t,0);
1267
1268   spriteid = swf_GetU16(t); //id
1269   spriteframes = swf_GetU16(t); //frames
1270
1271   level = 1;
1272
1273   while(1)
1274   {
1275     TAG*it = 0;
1276     tmp = swf_GetU16(t);
1277     len = tmp&0x3f;
1278     id  = tmp>>6;
1279     if(id == ST_END)
1280         level--;
1281     if(id == ST_DEFINESPRITE && len<=4)
1282         level++;
1283
1284     if (len==0x3f)
1285         len = swf_GetU32(t);
1286     it = swf_InsertTag(next, id);
1287     next = it;
1288     it->len = len;
1289     it->id  = id;
1290     if (it->len)
1291     { it->data = (U8*)rfx_alloc(it->len);
1292       it->memsize = it->len;
1293       swf_GetBlock(t, it->data, it->len);
1294     }
1295
1296     if(!level)
1297         break;
1298   }
1299   
1300   rfx_free(t->data); t->data = 0;
1301   t->memsize = t->len = t->pos = 0;
1302
1303   swf_SetU16(t, spriteid);
1304   swf_SetU16(t, spriteframes);
1305 }
1306
1307 void swf_FoldSprite(TAG * t)
1308 {
1309   TAG*sprtag=t,*tmp;
1310   U16 id,frames;
1311   int level;
1312   if(t->id!=ST_DEFINESPRITE)
1313       return;
1314   if(!t->len) {
1315       fprintf(stderr, "Error: Sprite has no ID!");
1316       return;
1317   }
1318   if(t->len>4) {
1319     /* sprite is already folded */
1320       return;
1321   }
1322
1323   t->pos = 0;
1324   id = swf_GetU16(t);
1325   rfx_free(t->data);
1326   t->len = t->pos = t->memsize = 0;
1327   t->data = 0;
1328
1329   frames = 0;
1330
1331   t = swf_NextTag(sprtag);
1332   level = 1;
1333
1334   do 
1335   { 
1336     if(t->id==ST_SHOWFRAME) frames++;
1337     if(t->id == ST_DEFINESPRITE && t->len<=4)
1338         level++;
1339     if(t->id == ST_END)
1340         level--;
1341     t = swf_NextTag(t);
1342   } while(t && level);
1343   if(level)
1344     fprintf(stderr, "rfxswf error: sprite doesn't end(1)\n");
1345
1346   swf_SetU16(sprtag, id);
1347   swf_SetU16(sprtag, frames);
1348
1349   t = swf_NextTag(sprtag);
1350   level = 1;
1351
1352   do
1353   { 
1354     if(t->len<0x3f&&
1355         (t->id!=ST_DEFINEBITSLOSSLESS&&t->id!=ST_DEFINEBITSLOSSLESS2&&t->id!=ST_SOUNDSTREAMBLOCK&&
1356          t->id!=ST_DEFINEBITSJPEG&&t->id!=ST_DEFINEBITSJPEG2&&t->id!=ST_DEFINEBITSJPEG3)
1357       ) {
1358         swf_SetU16(sprtag,t->len|(t->id<<6));
1359     } else {
1360         swf_SetU16(sprtag,0x3f|(t->id<<6));
1361         swf_SetU32(sprtag,t->len);
1362     }
1363     if(t->len)
1364         swf_SetBlock(sprtag,t->data, t->len);
1365     tmp = t;
1366     if(t->id == ST_DEFINESPRITE && t->len<=4)
1367         level++;
1368     if(t->id == ST_END)
1369         level--;
1370     t = swf_NextTag(t);
1371     swf_DeleteTag(0, tmp);
1372   } 
1373   while (t && level);
1374   if(level)
1375     fprintf(stderr, "rfxswf error: sprite doesn't end(2)\n");
1376
1377 //  sprtag->next = t;
1378 //  t->prev = sprtag;
1379 }
1380
1381 int swf_IsFolded(TAG * t)
1382 {
1383     return (t->id == ST_DEFINESPRITE && t->len>4);
1384 }
1385
1386 void swf_FoldAll(SWF*swf)
1387 {
1388     TAG*tag = swf->firstTag;
1389     //swf_DumpSWF(stdout, swf);
1390     while(tag) {
1391         if(tag->id == ST_DEFINESPRITE) {
1392             swf_FoldSprite(tag);
1393             //swf_DumpSWF(stdout, swf);
1394         }
1395         tag = swf_NextTag(tag);
1396     }
1397 }
1398
1399 void swf_UnFoldAll(SWF*swf)
1400 {
1401     TAG*tag = swf->firstTag;
1402     while(tag) {
1403         if(tag->id == ST_DEFINESPRITE)
1404             swf_UnFoldSprite(tag);
1405         tag = tag->next;
1406     }
1407 }
1408
1409 void swf_OptimizeTagOrder(SWF*swf)
1410 {
1411   TAG*tag,*next;
1412   TAG*level0;
1413   int level;
1414   int changes;
1415   swf_UnFoldAll(swf);
1416   /* at the moment, we don't actually do optimizing,
1417      only fixing of non-spec-conformant things like
1418      sprite tags */
1419
1420   do {
1421     changes = 0;
1422     level = 0;
1423     level0 = 0;
1424     tag = swf->firstTag;
1425     while(tag) {
1426       next = tag->next;
1427       if(tag->id == ST_DEFINESPRITE) {
1428         if(tag->len>4) {
1429           /* ??? all sprites are supposed to be unfolded */
1430           fprintf(stderr, "librfxswf error - internal error in OptimizeTagOrder/UnfoldAll\n");
1431         }
1432         level++;
1433         if(level==1) {
1434           level0 = tag;
1435           tag = next;
1436           continue;
1437         }
1438       }
1439       if(level>=1) {
1440         /* move non-sprite tags out of sprite */
1441         if(!swf_isAllowedSpriteTag(tag) || level>=2) {
1442           /* remove tag from current position */
1443           tag->prev->next = tag->next;
1444           if(tag->next)
1445             tag->next->prev = tag->prev;
1446
1447           /* insert before tag level0 */
1448           tag->next = level0;
1449           tag->prev = level0->prev;
1450           level0->prev = tag;
1451           if(tag->prev)
1452             tag->prev->next = tag;
1453           else
1454             swf->firstTag = tag;
1455           changes = 1;
1456         }
1457       }
1458       if(tag->id == ST_END) {
1459         level--;
1460       }
1461
1462       tag = next;
1463     }
1464   } while(changes);
1465 }
1466
1467 // Movie Functions
1468
1469 int swf_ReadSWF2(reader_t*reader, SWF * swf)   // Reads SWF to memory (malloc'ed), returns length or <0 if fails
1470 {     
1471   if (!swf) return -1;
1472   memset(swf,0x00,sizeof(SWF));
1473
1474   { char b[32];                         // read Header
1475     int len;
1476     TAG * t;
1477     TAG t1;
1478     reader_t zreader;
1479     
1480     if ((len = reader->read(reader ,b,8))<8) return -1;
1481
1482     if (b[0]!='F' && b[0]!='C') return -1;
1483     if (b[1]!='W') return -1;
1484     if (b[2]!='S') return -1;
1485     swf->fileVersion = b[3];
1486     swf->compressed  = (b[0]=='C')?1:0;
1487     swf->fileSize    = GET32(&b[4]);
1488     
1489     if(swf->compressed) {
1490         reader_init_zlibinflate(&zreader, reader);
1491         reader = &zreader;
1492     }
1493     swf->compressed = 0; // derive from version number from now on
1494
1495     reader_GetRect(reader, &swf->movieSize);
1496     reader->read(reader, &swf->frameRate, 2);
1497     swf->frameRate = SWAP16(swf->frameRate);
1498     reader->read(reader, &swf->frameCount, 2);
1499     swf->frameCount = SWAP16(swf->frameCount);
1500
1501     /* read tags and connect to list */
1502     t1.next = 0;
1503     t = &t1;
1504     while (t) {
1505       t = swf_ReadTag(reader,t);
1506       if(t && t->id == ST_FILEATTRIBUTES) {
1507         swf->fileAttributes = swf_GetU32(t);
1508         swf_ResetReadBits(t);
1509       }
1510     }
1511     swf->firstTag = t1.next;
1512     if(t1.next)
1513       t1.next->prev = NULL;
1514   }
1515   
1516   return reader->pos;
1517 }
1518
1519 SWF* swf_OpenSWF(char*filename)
1520 {
1521   int fi = open(filename, O_RDONLY|O_BINARY);
1522   if(fi<0) {
1523       fprintf(stderr, "Failed to open %s\n", filename);
1524       return 0;
1525   }
1526   SWF* swf = rfx_alloc(sizeof(SWF));
1527   swf_ReadSWF(fi, swf);
1528   close(fi);
1529   return swf;
1530 }
1531
1532 int swf_ReadSWF(int handle, SWF * swf)
1533 {
1534   reader_t reader;
1535   reader_init_filereader(&reader, handle);
1536   return swf_ReadSWF2(&reader, swf);
1537 }
1538
1539 void swf_ReadABCfile(char*filename, SWF*swf)
1540 {
1541     memset(swf, 0, sizeof(SWF));
1542     swf->fileVersion=9;
1543     swf->fileAttributes=FILEATTRIBUTE_AS3; //as3
1544     TAG*tag = swf->firstTag = swf_InsertTag(0, ST_RAWABC);
1545     memfile_t*file = memfile_open(filename);
1546     swf_SetBlock(tag, file->data, file->len);
1547     memfile_close(file);
1548 }
1549
1550 int no_extra_tags = 0;
1551
1552 int WriteExtraTags(SWF*swf, writer_t*writer)
1553 {
1554     TAG*t = swf->firstTag;
1555     TAG* has_fileattributes=0;
1556     int has_scenedescription=0;
1557     int has_version_8_action=0;
1558     int has_version_9_action=0;
1559     int len = 0;
1560     while(t) {
1561         if(t->id == ST_FILEATTRIBUTES)
1562             has_fileattributes = t;
1563         if(t->id == ST_SCENEDESCRIPTION)
1564             has_scenedescription = 1;
1565         if(t->id == ST_DOABC) 
1566             has_version_9_action=1;
1567         /* FIXME: this doesn't yet find actionscript in buttons */
1568         if(t->id == ST_DOACTION || t->id == ST_DOINITACTION) 
1569             has_version_8_action=1;
1570         if(t->id == ST_PLACEOBJECT2 && t->len && (t->data[0]&0x80))
1571             has_version_8_action=1;
1572         t = t->next;
1573     }
1574     if(has_version_8_action && has_version_9_action) {
1575         fprintf(stderr, "Warning: File contains both flash 8 and flash 9 actionscript\n");
1576     }
1577
1578     if(swf->fileVersion >= 9) {
1579         if(!has_fileattributes) {
1580             U32 flags = swf->fileAttributes|FILEATTRIBUTE_AS3; // 16 = has symbolclass tag | 8 = actionscript3 | 1 = usenetwork
1581             if(has_version_8_action && !has_version_9_action)
1582                 flags &= ~FILEATTRIBUTE_AS3;
1583             TAG*fileattrib = swf_InsertTag(0, ST_FILEATTRIBUTES);
1584             swf_SetU32(fileattrib, flags);
1585             if(writer) {
1586                 if(swf_WriteTag2(writer, fileattrib)<0) 
1587                     return -1;
1588             } else {
1589                 len += swf_WriteTag(-1,fileattrib);
1590             }
1591             swf_DeleteTag(0, fileattrib);
1592         } else {
1593             if(swf->fileAttributes) {
1594               /* if we're writing a file out again where we might have possible
1595                  modified the fileattributes in the header, adjust the tag data */
1596               TAG*tt = swf_CopyTag(0,has_fileattributes);
1597               U32 flags = swf_GetU32(tt) | swf->fileAttributes;
1598               swf_ResetTag(tt, tt->id);
1599               swf_SetU32(tt, flags);
1600               if(swf_WriteTag2(writer, has_fileattributes)<0) return -1;
1601               swf_DeleteTag(0, tt);
1602             } else {
1603                 if(swf_WriteTag2(writer, has_fileattributes)<0) 
1604                     return -1;
1605             }
1606         }
1607         if(0 && !has_scenedescription) {
1608             TAG*scene = swf_InsertTag(0, ST_SCENEDESCRIPTION);
1609             swf_SetU16(scene, 1);
1610             swf_SetString(scene, "Scene 1");
1611             swf_SetU8(scene, 0);
1612             if(writer) {
1613                 if(swf_WriteTag2(writer, scene)<0) 
1614                     return -1;
1615             } else {
1616                 len += swf_WriteTag(-1,scene);
1617             }
1618             swf_DeleteTag(0, scene);
1619         }
1620     }
1621     return len;
1622 }
1623
1624 int  swf_WriteSWF2(writer_t*writer, SWF * swf)     // Writes SWF to file, returns length or <0 if fails
1625 { U32 len;
1626   TAG * t;
1627   int frameCount=0;
1628   writer_t zwriter;
1629   int fileSize = 0;
1630   int inSprite = 0;
1631   int ret;
1632   writer_t*original_writer = writer;
1633   int writer_lastpos = 0;
1634     
1635   if (!swf) return -1;
1636   if (!writer) return -1; // the caller should provide a nullwriter, not 0, for querying SWF size
1637
1638   if(original_writer) writer_lastpos = original_writer->pos;
1639
1640   // Count Frames + File Size
1641
1642   len = 0;
1643   t = swf->firstTag;
1644   frameCount = 0;
1645
1646   if(swf->firstTag && !no_extra_tags) {
1647     len += WriteExtraTags(swf, 0);
1648   }
1649   while(t) {
1650       len += swf_WriteTag(-1,t);
1651       if(t->id == ST_DEFINESPRITE && !swf_IsFolded(t)) inSprite++;
1652       else if(t->id == ST_END && inSprite) inSprite--;
1653       else if(t->id == ST_END && !inSprite) {
1654         if(t->prev && t->prev->id!=ST_SHOWFRAME)
1655           frameCount++;
1656       }
1657       else if(t->id == ST_SHOWFRAME && !inSprite) frameCount++;
1658       t = swf_NextTag(t);
1659   }
1660   
1661   { TAG t1;
1662     char b[64],b4[4];
1663     U32 l;
1664
1665     memset(&t1,0x00,sizeof(TAG));
1666     t1.data    = (U8*)b;
1667     t1.memsize = 64;
1668     
1669     { // measure header file size
1670       TAG t2;
1671       char b2[64];
1672       memset(&t2,0x00,sizeof(TAG));
1673       t2.data    = (U8*)b2;
1674       t2.memsize = 64;
1675       swf_SetRect(&t2, &swf->movieSize);
1676       swf_SetU16(&t2, swf->frameRate);
1677       swf_SetU16(&t2, swf->frameCount);
1678       l = swf_GetTagLen(&t2)+8;
1679     }
1680     if(swf->compressed == 8) {
1681       l -= 8;
1682     }
1683
1684     fileSize = l+len;
1685     if(len) {// don't touch headers without tags
1686         swf->fileSize = fileSize;
1687         swf->frameCount = frameCount;
1688     }
1689
1690     if(swf->compressed != 8) {
1691     /* compressed flag set to 8 means "skip first 8 
1692        header bytes". This is necessary if the caller wants to
1693        create compressed SWFs himself .
1694        It also means that we don't initialize our own zlib
1695        writer, but assume the caller provided one.
1696      */
1697       if(swf->compressed==1 || (swf->compressed==0 && swf->fileVersion>=6)) {
1698         char*id = "CWS";
1699         writer->write(writer, id, 3);
1700       } else {
1701         char*id = "FWS";
1702         writer->write(writer, id, 3);
1703       }
1704
1705       writer->write(writer, &swf->fileVersion, 1);
1706       PUT32(b4, swf->fileSize);
1707       writer->write(writer, b4, 4);
1708       
1709       if(swf->compressed==1 || (swf->compressed==0 && swf->fileVersion>=6)) {
1710         writer_init_zlibdeflate(&zwriter, writer);
1711         writer = &zwriter;
1712       }
1713     }
1714
1715     swf_SetRect(&t1,&swf->movieSize);
1716     swf_SetU16(&t1,swf->frameRate);
1717     swf_SetU16(&t1,swf->frameCount);
1718
1719     ret = writer->write(writer,b,swf_GetTagLen(&t1));
1720     if (ret!=swf_GetTagLen(&t1))
1721     {
1722       #ifdef DEBUG_RFXSWF
1723         fprintf(stderr, "ret:%d\n",ret);
1724         perror("write:");
1725         fprintf(stderr,"WriteSWF() failed: Header.\n");
1726       #endif
1727       return -1;
1728     }
1729
1730     if(swf->firstTag && !no_extra_tags) {
1731         WriteExtraTags(swf, writer);
1732     }
1733     t = swf->firstTag;
1734
1735     while (t) { 
1736         if(no_extra_tags || t->id != ST_FILEATTRIBUTES) {
1737           if(swf_WriteTag2(writer, t)<0) 
1738             return -1;
1739         }
1740         t = t->next;
1741     }
1742     if(swf->compressed==1 || (swf->compressed==0 && swf->fileVersion>=6) || swf->compressed==8) {
1743       if(swf->compressed != 8) {
1744         zwriter.finish(&zwriter);
1745         return original_writer->pos - writer_lastpos;
1746       }
1747       return (int)fileSize;
1748     } else {
1749       return (int)fileSize;
1750     }
1751   }
1752 }
1753
1754 int swf_SaveSWF(SWF * swf, char*filename)
1755 {
1756     int fi = open(filename, O_BINARY|O_RDWR|O_TRUNC|O_CREAT, 0777);
1757     if(fi<0) {
1758         perror(filename);
1759         return 0;
1760     }
1761     if(swf_WriteSWF(fi, swf)<0) {
1762         fprintf(stderr, "Unable to write output file: %s\n", filename);
1763         return 0;
1764     }
1765     close(fi);
1766     return 1;
1767 }
1768
1769 int  swf_WriteSWF(int handle, SWF * swf)     // Writes SWF to file, returns length or <0 if fails
1770 {
1771   writer_t writer;
1772   int len = 0;
1773   
1774   if(handle<0) {
1775     writer_init_nullwriter(&writer);
1776     len = swf_WriteSWF2(&writer, swf);
1777     return len;
1778   }
1779   writer_init_filewriter(&writer, handle);
1780   len = swf_WriteSWF2(&writer, swf);
1781   writer.finish(&writer);
1782   return len;
1783 }
1784
1785 int swf_WriteHeader2(writer_t*writer,SWF * swf)
1786 {
1787   SWF myswf;
1788   memcpy(&myswf,swf,sizeof(SWF));
1789   myswf.firstTag = 0;
1790   return swf_WriteSWF2(writer, &myswf);
1791 }
1792
1793 int swf_WriteHeader(int handle,SWF * swf)
1794 {
1795   SWF myswf;
1796   memcpy(&myswf,swf,sizeof(SWF));
1797   myswf.firstTag = 0;
1798   return swf_WriteSWF(handle, &myswf);
1799 }
1800
1801 int swf_WriteCGI(SWF * swf)
1802 { int len;
1803   char s[1024];
1804     
1805   len = swf_WriteSWF(-1,swf);
1806
1807   if (len<0) return -1;
1808
1809   sprintf(s,"Content-type: application/x-shockwave-flash\n"
1810             "Accept-Ranges: bytes\n"
1811             "Content-Length: %lu\n"
1812             "Expires: Thu, 13 Apr 2000 23:59:59 GMT\n"
1813             "\n",len);
1814             
1815   write(fileno(stdout),s,strlen(s));
1816   return swf_WriteSWF(fileno(stdout),swf);
1817 }
1818
1819 SWF* swf_CopySWF(SWF*swf)
1820 {
1821     SWF*nswf = (SWF*)rfx_alloc(sizeof(SWF));
1822     TAG*tag, *ntag;
1823     memcpy(nswf, swf, sizeof(SWF));
1824     nswf->firstTag = 0;
1825     tag = swf->firstTag;
1826     ntag = 0;
1827     while(tag) {
1828         ntag = swf_CopyTag(ntag, tag);
1829         if(!nswf->firstTag)
1830             nswf->firstTag = ntag;
1831         tag = tag->next;
1832     }
1833     return nswf;
1834 }
1835
1836 void swf_FreeTags(SWF * swf)                 // Frees all malloc'ed memory for tags
1837 { TAG * t = swf->firstTag;
1838
1839   while (t)
1840   { TAG * tnew = t->next;
1841     if (t->data) rfx_free(t->data);
1842     rfx_free(t);
1843     t = tnew;
1844   }
1845   swf->firstTag = 0;
1846 }
1847
1848 // include advanced functions
1849
1850 //#include "modules/swfdump.c"
1851 //#include "modules/swfshape.c"
1852 //#include "modules/swftext.c"
1853 //#include "modules/swffont.c"
1854 //#include "modules/swfobject.c"
1855 //#include "modules/swfbutton.c"
1856 //#include "modules/swftools.c"
1857 //#include "modules/swfcgi.c"
1858 //#include "modules/swfbits.c"
1859 //#include "modules/swfaction.c"
1860 //#include "modules/swfabc.c"
1861 //#include "modules/swfsound.c"
1862 //#include "modules/swfdraw.c"
1863 //#include "modules/swfrender.c"
1864 //#include "modules/swffilter.c"