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