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