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