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