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