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