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