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