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