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