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