reworked compression handling logic
[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
51 #ifdef HAVE_TIME_H
52 #include <time.h>
53 #endif
54
55 #ifdef HAVE_IO_H
56 #include <io.h>
57 #endif
58
59 #include "./bitio.h"
60 #include "./MD5.h"
61
62 // internal constants
63
64 #define MALLOC_SIZE     128
65 #define INSERT_RFX_TAG
66
67 #define MEMSIZE(l) (((l/MALLOC_SIZE)+1)*MALLOC_SIZE)
68
69 // inline wrapper functions
70
71 TAG * swf_NextTag(TAG * t) { return t->next; }
72 TAG * swf_PrevTag(TAG * t) { return t->prev; }
73 U16   swf_GetTagID(TAG * t)    { return t->id; }
74 U32   swf_GetTagLen(TAG * t) { return t->len; }
75 U8*   swf_GetTagLenPtr(TAG * t) { return &(t->data[t->len]); }
76 U32   swf_GetTagPos(TAG * t)   { return t->pos; }
77
78 // for future purpose: avoid high level lib functions to change tagpos/bitpos
79
80 #define swf_SaveTagPos(tag)
81 #define swf_RestoreTagPos(tag)
82
83 void swf_SetTagPos(TAG * t,U32 pos)
84 { swf_ResetReadBits(t);
85   if (pos<=t->len) t->pos = pos;
86   else { 
87 #ifdef DEBUG_RFXSWF
88     fprintf(stderr,"SetTagPos(%d) out of bounds: TagID = %i\n",pos, t->id);
89 #endif
90   }
91 }
92
93 char* swf_GetString(TAG*t)
94 {
95     int pos = t->pos;
96     while(t->pos < t->len && swf_GetU8(t));
97     /* make sure we always have a trailing zero byte */
98     if(t->pos == t->len) {
99       if(t->len == t->memsize) {
100         swf_ResetWriteBits(t);
101         swf_SetU8(t, 0);
102         t->len = t->pos;
103       }
104       t->data[t->len] = 0;
105     }
106     return (char*)&(t->data[pos]);
107 }
108
109 U8 swf_GetU8(TAG * t)
110 { swf_ResetReadBits(t);
111   #ifdef DEBUG_RFXSWF
112     if (t->pos>=t->len) 
113     { fprintf(stderr,"GetU8() out of bounds: TagID = %i\n",t->id);
114       return 0;
115     }
116   #endif
117   return t->data[t->pos++];
118 }
119
120 U16 swf_GetU16(TAG * t)
121 { U16 res;
122   swf_ResetReadBits(t);
123   #ifdef DEBUG_RFXSWF
124     if (t->pos>(t->len-2)) 
125     { fprintf(stderr,"GetU16() out of bounds: TagID = %i\n",t->id);
126       return 0;
127     }
128   #endif
129   res = t->data[t->pos] | (t->data[t->pos+1]<<8);
130   t->pos+=2;
131   return res;
132 }
133
134 U32 swf_GetU32(TAG * t)
135 { U32 res;
136   swf_ResetReadBits(t);
137   #ifdef DEBUG_RFXSWF
138     if (t->pos>(t->len-4)) 
139     { fprintf(stderr,"GetU32() out of bounds: TagID = %i\n",t->id);
140       return 0;
141     }
142   #endif
143   res = t->data[t->pos]        | (t->data[t->pos+1]<<8) | 
144        (t->data[t->pos+2]<<16) | (t->data[t->pos+3]<<24);
145   t->pos+=4;
146   return res;
147 }
148
149 int swf_GetBlock(TAG * t,U8 * b,int l)
150 // returns number of bytes written (<=l)
151 // b = NULL -> skip data
152 { swf_ResetReadBits(t);
153   if ((t->len-t->pos)<l) l=t->len-t->pos;
154   if (b && l) memcpy(b,&t->data[t->pos],l);
155   t->pos+=l;
156   return l;
157 }
158
159 int swf_SetBlock(TAG * t,U8 * b,int l)
160 // Appends Block to the end of Tagdata, returns size
161 { U32 newlen = t->len + l;
162   swf_ResetWriteBits(t);
163   if (newlen>t->memsize)
164   { U32  newmem  = MEMSIZE(newlen);  
165     U8 * newdata = (U8*)(rfx_realloc(t->data,newmem));
166     t->memsize = newmem;
167     t->data    = newdata;
168   }
169   if (b) memcpy(&t->data[t->len],b,l);
170   else memset(&t->data[t->len],0x00,l);
171   t->len+=l;
172   return l;
173 }
174
175 int swf_SetU8(TAG * t,U8 v)
176 { swf_ResetWriteBits(t);
177   if ((t->len+1)>t->memsize) return (swf_SetBlock(t,&v,1)==1)?0:-1;
178   t->data[t->len++] = v;
179   return 0;
180 }
181
182 int swf_SetU16(TAG * t,U16 v)
183 { U8 a[2];
184   a[0] = v&0xff;
185   a[1] = v>>8;
186   
187   swf_ResetWriteBits(t);
188   if ((t->len+2)>t->memsize) return (swf_SetBlock(t,a,2)==2)?0:-1;
189   t->data[t->len++] = a[0];
190   t->data[t->len++] = a[1];
191   return 0;
192 }
193 void swf_SetS16(TAG * t,int v)
194 {
195     if(v>32767 || v<-32768) {
196         fprintf(stderr, "Warning: S16 overflow: %d\n", v);
197     }
198     swf_SetU16(t, (S16)v);
199 }
200
201 int swf_SetU32(TAG * t,U32 v)
202 { U8 a[4];
203   a[0] = v&0xff;        // to ensure correct handling of non-intel byteorder
204   a[1] = (v>>8)&0xff;
205   a[2] = (v>>16)&0xff;
206   a[3] = (v>>24)&0xff;
207   
208   swf_ResetWriteBits(t);
209   if ((t->len+4)>t->memsize) return (swf_SetBlock(t,a,4)==4)?0:-1;
210   t->data[t->len++] = a[0];
211   t->data[t->len++] = a[1];
212   t->data[t->len++] = a[2];
213   t->data[t->len++] = a[3];
214   return 0;
215 }
216
217 U32 swf_GetBits(TAG * t,int nbits)
218 { U32 res = 0;
219   if (!nbits) return 0;
220   if (!t->readBit) t->readBit = 0x80;
221   while (nbits)
222   { res<<=1;
223     if (t->data[t->pos]&t->readBit) res|=1;
224     t->readBit>>=1;
225     nbits--;
226     if (!t->readBit)
227     { if (nbits) t->readBit = 0x80;
228       #ifdef DEBUG_RFXSWF
229       if (t->pos>=t->len) 
230       { fprintf(stderr,"GetBits() out of bounds: TagID = %i\n",t->id);
231         return res;
232       }
233       #endif
234       t->pos++;
235     }
236   }
237   return res;
238 }
239
240 S32 swf_GetSBits(TAG * t,int nbits)
241 { U32 res = swf_GetBits(t,nbits);
242   if (res&(1<<(nbits-1))) res|=(0xffffffff<<nbits);  
243   return (S32)res;
244 }
245
246 U32 reader_GetBits(reader_t*reader, int nbits)
247 { return reader_readbits(reader, nbits);
248 }
249 S32 reader_GetSBits(reader_t*reader, int nbits)
250 { U32 res = reader_readbits(reader, nbits);
251   if (res&(1<<(nbits-1))) res|=(0xffffffff<<nbits);  
252   return (S32)res;
253 }
254
255 int swf_SetBits(TAG * t,U32 v,int nbits)
256 { U32 bm = 1<<(nbits-1);
257
258   while (nbits)
259   { if (!t->writeBit)
260     { if (FAILED(swf_SetU8(t,0))) return -1;
261       t->writeBit = 0x80;
262     }
263     if (v&bm) t->data[t->len-1] |= t->writeBit;
264     bm>>=1;
265     t->writeBit>>=1;
266     nbits--;
267   }
268   return 0;
269 }
270
271 // Advanced Data Access Functions
272
273 double swf_GetFixed(TAG * t)
274 {
275   U16 low =  swf_GetU16(t);
276   U16 high = swf_GetU16(t);
277   return high + low*(1/65536.0);
278 }
279 void swf_SetFixed(TAG * t, double f)
280 {
281   U16 fr = (U16)(f-(int)f)*65536;
282   swf_SetU16(t, fr);
283   swf_SetU16(t, (U16)f - (f<0 && fr!=0));
284 }
285 float swf_GetFixed8(TAG * t)
286 {
287   U8 low =  swf_GetU8(t);
288   U8 high = swf_GetU8(t);
289   return (float)(high + low*(1/256.0));
290 }
291 void swf_SetFixed8(TAG * t, float f)
292 {
293   U8 fr = (U8)(f-(int)f)*256;
294   swf_SetU8(t, fr);
295   swf_SetU8(t, (U8)f - (f<0 && fr!=0));
296 }
297
298 int swf_SetRGB(TAG * t,RGBA * col)
299 { if (!t) return -1;
300   if (col)
301   { swf_SetU8(t,col->r);
302     swf_SetU8(t,col->g);
303     swf_SetU8(t,col->b);
304   } else swf_SetBlock(t,NULL,3);
305   return 0;
306 }
307 void swf_GetRGB(TAG * t, RGBA * col)
308 {
309     RGBA dummy;
310     if(!col)
311         col = &dummy;
312     col->r = swf_GetU8(t);
313     col->g = swf_GetU8(t);
314     col->b = swf_GetU8(t);
315     col->a = 255;
316 }
317
318 int swf_SetRGBA(TAG * t,RGBA * col)
319 { if (!t) return -1;
320   if (col)
321   { swf_SetU8(t,col->r);
322     swf_SetU8(t,col->g);
323     swf_SetU8(t,col->b);
324     swf_SetU8(t,col->a);
325   } else swf_SetBlock(t,NULL,4);
326   return 0;
327 }
328 void swf_GetRGBA(TAG * t, RGBA * col)
329 {
330     RGBA dummy;
331     if(!col)
332         col = &dummy;
333     col->r = swf_GetU8(t);
334     col->g = swf_GetU8(t);
335     col->b = swf_GetU8(t);
336     col->a = swf_GetU8(t);
337 }
338
339 void swf_GetGradient(TAG * tag, GRADIENT * gradient, char alpha)
340 {
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*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;
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     swf->compressed = 0; // derive from version number from now on
1258
1259     reader_GetRect(reader, &swf->movieSize);
1260     reader->read(reader, &swf->frameRate, 2);
1261     swf->frameRate = SWAP16(swf->frameRate);
1262     reader->read(reader, &swf->frameCount, 2);
1263     swf->frameCount = SWAP16(swf->frameCount);
1264
1265     /* read tags and connect to list */
1266     t = &t1;
1267     while (t) t = swf_ReadTag(reader,t);
1268     swf->firstTag = t1.next;
1269     t1.next->prev = NULL;
1270   }
1271   
1272   return reader->pos;
1273 }
1274
1275 int swf_ReadSWF(int handle, SWF * swf)
1276 {
1277   reader_t reader;
1278   reader_init_filereader(&reader, handle);
1279   return swf_ReadSWF2(&reader, swf);
1280 }
1281
1282 int  swf_WriteSWF2(writer_t*writer, SWF * swf)     // Writes SWF to file, returns length or <0 if fails
1283 { U32 len;
1284   TAG * t;
1285   int frameCount=0;
1286   writer_t zwriter;
1287   int fileSize = 0;
1288   int inSprite = 0;
1289   int writer_lastpos = 0;
1290   int ret;
1291     
1292   if (!swf) return -1;
1293   if (!writer) return -1; // the caller should provide a nullwriter, not 0, for querying SWF size
1294
1295   if(writer) writer_lastpos = writer->pos;
1296
1297   // Insert REFLEX Tag
1298
1299 #ifdef INSERT_RFX_TAG
1300
1301   if ((swf->firstTag && swf->firstTag->id != ST_REFLEX) &&
1302       (!swf->firstTag->next || swf->firstTag->next->id != ST_REFLEX)) 
1303   {
1304       swf_SetBlock(swf_InsertTagBefore(swf, swf->firstTag,ST_REFLEX),(U8*)"rfx",3);
1305   }
1306
1307 #endif // INSERT_RFX_TAG
1308
1309   if(swf->fileVersion >= 9) {
1310     if ((!swf->firstTag || swf->firstTag->id != ST_SCENEDESCRIPTION) &&
1311         (!swf->firstTag || 
1312          !swf->firstTag->next || swf->firstTag->next->id != ST_SCENEDESCRIPTION) &&
1313         (!swf->firstTag || 
1314          !swf->firstTag->next || 
1315          !swf->firstTag->next->next || swf->firstTag->next->next->id != ST_SCENEDESCRIPTION))
1316     {
1317         TAG*scene = swf_InsertTagBefore(swf, swf->firstTag,ST_SCENEDESCRIPTION);
1318         swf_SetU16(scene, 1);
1319         swf_SetString(scene, (U8*)"Scene 1");
1320         swf_SetU8(scene, 0);
1321     }
1322   }
1323   
1324   if(swf->fileVersion >= 9) {
1325       if (swf->firstTag && swf->firstTag->id != ST_FILEATTRIBUTES)
1326       {
1327           U32 flags = 0x8; // | 128 = usenetwork, | 16 = Actionscript3 | 8 = hasmetadata
1328           swf_SetU32(swf_InsertTagBefore(swf, swf->firstTag,ST_FILEATTRIBUTES),flags);
1329       }
1330   }
1331
1332   // Count Frames + File Size
1333
1334   len = 0;
1335   t = swf->firstTag;
1336   frameCount = 0;
1337
1338   while(t) {
1339       len += swf_WriteTag(-1,t);
1340       if(t->id == ST_DEFINESPRITE && !swf_IsFolded(t)) inSprite++;
1341       else if(t->id == ST_END && inSprite) inSprite--;
1342       else if(t->id == ST_END && !inSprite) {
1343         if(t->prev && t->prev->id!=ST_SHOWFRAME)
1344           frameCount++;
1345       }
1346       else if(t->id == ST_SHOWFRAME && !inSprite) frameCount++;
1347       t = swf_NextTag(t);
1348   }
1349   
1350   { TAG t1;
1351     char b[64],b4[4];
1352     U32 l;
1353
1354     memset(&t1,0x00,sizeof(TAG));
1355     t1.data    = (U8*)b;
1356     t1.memsize = 64;
1357     
1358     { // measure header file size
1359       TAG t2;
1360       char b2[64];
1361       memset(&t2,0x00,sizeof(TAG));
1362       t2.data    = (U8*)b2;
1363       t2.memsize = 64;
1364       swf_SetRect(&t2, &swf->movieSize);
1365       swf_SetU16(&t2, swf->frameRate);
1366       swf_SetU16(&t2, swf->frameCount);
1367       l = swf_GetTagLen(&t2)+8;
1368     }
1369     if(swf->compressed == 8) {
1370       l -= 8;
1371     }
1372
1373     fileSize = l+len;
1374     if(len) {// don't touch headers without tags
1375         swf->fileSize = fileSize;
1376         swf->frameCount = frameCount;
1377     }
1378
1379     if(swf->compressed != 8) {
1380     /* compressed flag set to 8 means "skip first 8 
1381        header bytes". This is necessary if the caller wants to
1382        create compressed SWFs himself .
1383        It also means that we don't initialize our own zlib
1384        writer, but assume the caller provided one.
1385      */
1386       if(swf->compressed==1 || (swf->compressed==0 && swf->fileVersion>=6)) {
1387         char*id = "CWS";
1388         writer->write(writer, id, 3);
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==1 || (swf->compressed==0 && swf->fileVersion>=6)) {
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==1 || (swf->compressed==0 && swf->fileVersion>=6) || swf->compressed==8) {
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   
1441   if(handle<0) {
1442     writer_init_nullwriter(&writer);
1443     len = swf_WriteSWF2(&writer, swf);
1444     return len;
1445   }
1446   writer_init_filewriter(&writer, handle);
1447   len = swf_WriteSWF2(&writer, swf);
1448   writer.finish(&writer);
1449   return len;
1450 }
1451
1452 int swf_WriteHeader2(writer_t*writer,SWF * swf)
1453 {
1454   SWF myswf;
1455   memcpy(&myswf,swf,sizeof(SWF));
1456   myswf.firstTag = 0;
1457   return swf_WriteSWF2(writer, &myswf);
1458 }
1459
1460 int swf_WriteHeader(int handle,SWF * swf)
1461 {
1462   SWF myswf;
1463   memcpy(&myswf,swf,sizeof(SWF));
1464   myswf.firstTag = 0;
1465   return swf_WriteSWF(handle, &myswf);
1466 }
1467
1468 int swf_WriteCGI(SWF * swf)
1469 { int len;
1470   char s[1024];
1471     
1472   len = swf_WriteSWF(-1,swf);
1473
1474   if (len<0) return -1;
1475
1476   sprintf(s,"Content-type: application/x-shockwave-flash\n"
1477             "Accept-Ranges: bytes\n"
1478             "Content-Length: %lu\n"
1479             "Expires: Thu, 13 Apr 2000 23:59:59 GMT\n"
1480             "\n",len);
1481             
1482   write(fileno(stdout),s,strlen(s));
1483   return swf_WriteSWF(fileno(stdout),swf);
1484 }
1485
1486 SWF* swf_CopySWF(SWF*swf)
1487 {
1488     SWF*nswf = (SWF*)rfx_alloc(sizeof(SWF));
1489     TAG*tag, *ntag;
1490     memcpy(nswf, swf, sizeof(SWF));
1491     nswf->firstTag = 0;
1492     tag = swf->firstTag;
1493     ntag = 0;
1494     while(tag) {
1495         ntag = swf_CopyTag(ntag, tag);
1496         if(!nswf->firstTag)
1497             nswf->firstTag = ntag;
1498         tag = tag->next;
1499     }
1500     return nswf;
1501 }
1502
1503 void swf_FreeTags(SWF * swf)                 // Frees all malloc'ed memory for tags
1504 { TAG * t = swf->firstTag;
1505
1506   while (t)
1507   { TAG * tnew = t->next;
1508     if (t->data) rfx_free(t->data);
1509     rfx_free(t);
1510     t = tnew;
1511   }
1512   swf->firstTag = 0;
1513 }
1514
1515 // include advanced functions
1516
1517 #include "modules/swfdump.c"
1518 #include "modules/swfshape.c"
1519 #include "modules/swftext.c"
1520 #include "modules/swffont.c"
1521 #include "modules/swfobject.c"
1522 #include "modules/swfbutton.c"
1523 #include "modules/swftools.c"
1524 #include "modules/swfcgi.c"
1525 #include "modules/swfbits.c"
1526 #include "modules/swfaction.c"
1527 #include "modules/swfabc.c"
1528 #include "modules/swfsound.c"
1529 #include "modules/swfdraw.c"
1530 #include "modules/swfrender.c"
1531 #include "modules/swffilter.c"