new function swf_OptimizeTagOrder.
[swftools.git] / lib / rfxswf.c
1 /* vi: set sts=2 sw=2 :*/
2
3 /* rfxswf.c 
4
5    Library for creating and reading SWF files or parts of it.
6    There's a module directory which provides some extended functionality.
7    Most modules are included at the bottom of this file.
8
9    Part of the swftools package.
10
11    Copyright (c) 2000, 2001 Rainer Böhme <rfxswf@reflex-studio.de>
12  
13    This file is distributed under the GPL, see file COPYING for details 
14
15 */
16
17 #include "rfxswf.h"
18
19 #ifdef HAVE_LIBJPEG
20 #ifdef HAVE_JPEGLIB_H
21 #define HAVE_BOOLEAN
22 #include <jpeglib.h>
23 #define _JPEGLIB_INCLUDED_
24 #endif // HAVE_JPEGLIB_H
25 #endif // HAVE_LIBJPEG
26
27 #ifdef HAVE_LIBZ
28 #ifdef HAVE_ZLIB_H
29 #include <zlib.h>
30 #define _ZLIB_INCLUDED_
31 #endif // HAVE_ZLIB_H
32 #endif // HAVE_LIBZ
33
34 #define LAME
35 #include "lame/lame.h"
36
37 #include "./bitio.h"
38
39 // internal constants
40
41 #define MALLOC_SIZE     128
42 #define INSERT_RFX_TAG
43
44 #define MEMSIZE(l) (((l/MALLOC_SIZE)+1)*MALLOC_SIZE)
45
46
47 // inline wrapper functions
48
49 TAG * swf_NextTag(TAG * t) { return t->next; }
50 TAG * swf_PrevTag(TAG * t) { return t->prev; }
51 int   swf_GetFrameNo(TAG * t)  { return t->frame; }
52 U16   swf_GetTagID(TAG * t)    { return t->id; }
53 U32   swf_GetTagLen(TAG * t) { return t->len; }
54 U8*   swf_GetTagLenPtr(TAG * t) { return &(t->data[t->len]); }
55 U32   swf_GetTagPos(TAG * t)   { return t->pos; }
56
57 // Basic Data Access Functions
58
59 #define swf_ResetReadBits(tag)   if (tag->readBit)  { tag->pos++; tag->readBit = 0; }
60 #define swf_ResetWriteBits(tag)  if (tag->writeBit) { tag->writeBit = 0; }
61
62 // for future purpose: avoid high level lib functions to change tagpos/bitpos
63
64 #define swf_SaveTagPos(tag)
65 #define swf_RestoreTagPos(tag)
66
67 void swf_SetTagPos(TAG * t,U32 pos)
68 { swf_ResetReadBits(t);
69   if (pos<=t->len) t->pos = pos;
70   #ifdef DEBUG_RFXSWF
71   else fprintf(stderr,"SetTagPos() out of bounds: TagID = %i\n",t->id);
72   #endif
73 }
74
75 U8 swf_GetU8(TAG * t)
76 { swf_ResetReadBits(t);
77   #ifdef DEBUG_RFXSWF
78     if (t->pos>=t->len) 
79     { fprintf(stderr,"GetU8() out of bounds: TagID = %i\n",t->id);
80       return 0;
81     }
82   #endif
83   return t->data[t->pos++];
84 }
85
86 U16 swf_GetU16(TAG * t)
87 { U16 res;
88   swf_ResetReadBits(t);
89   #ifdef DEBUG_RFXSWF
90     if (t->pos>(t->len-2)) 
91     { fprintf(stderr,"GetU16() out of bounds: TagID = %i\n",t->id);
92       return 0;
93     }
94   #endif
95   res = t->data[t->pos] | (t->data[t->pos+1]<<8);
96   t->pos+=2;
97   return res;
98 }
99
100 U32 swf_GetU32(TAG * t)
101 { U32 res;
102   swf_ResetReadBits(t);
103   #ifdef DEBUG_RFXSWF
104     if (t->pos>(t->len-4)) 
105     { fprintf(stderr,"GetU32() out of bounds: TagID = %i\n",t->id);
106       return 0;
107     }
108   #endif
109   res = t->data[t->pos]        | (t->data[t->pos+1]<<8) | 
110        (t->data[t->pos+2]<<16) | (t->data[t->pos+3]<<24);
111   t->pos+=4;
112   return res;
113 }
114
115 int swf_GetBlock(TAG * t,U8 * b,int l)
116 // returns number of bytes written (<=l)
117 // b = NULL -> skip data
118 { swf_ResetReadBits(t);
119   if ((t->len-t->pos)<l) l=t->len-t->pos;
120   if (b && l) memcpy(b,&t->data[t->pos],l);
121   t->pos+=l;
122   return l;
123 }
124
125 int swf_SetBlock(TAG * t,U8 * b,int l)
126 // Appends Block to the end of Tagdata, returns size
127 { U32 newlen = t->len + l;
128   swf_ResetWriteBits(t);
129   if (newlen>t->memsize)
130   { U32  newmem  = MEMSIZE(newlen);  
131     U8 * newdata = (U8*)((t->data)?realloc(t->data,newmem):malloc(newmem));
132     if (!newdata)
133     {
134       #ifdef DEBUG_RFXSWF
135         fprintf(stderr,"Fatal Error: malloc()/realloc() failed (1). (%d bytes)\n", newmem);
136         *(int*)0=0;
137       #endif
138       return 0;
139     }
140     t->memsize = newmem;
141     t->data    = newdata;
142   }
143   if (b) memcpy(&t->data[t->len],b,l);
144   else memset(&t->data[t->len],0x00,l);
145   t->len+=l;
146   return l;
147 }
148
149 int swf_SetU8(TAG * t,U8 v)
150 { swf_ResetWriteBits(t);
151   if ((t->len+1)>t->memsize) return (swf_SetBlock(t,&v,1)==1)?0:-1;
152   t->data[t->len++] = v;
153   return 0;
154 }
155
156 int swf_SetU16(TAG * t,U16 v)
157 { U8 a[2];
158   a[0] = v&0xff;
159   a[1] = v>>8;
160   
161   swf_ResetWriteBits(t);
162   if ((t->len+2)>t->memsize) return (swf_SetBlock(t,a,2)==2)?0:-1;
163   t->data[t->len++] = a[0];
164   t->data[t->len++] = a[1];
165   return 0;
166 }
167
168 int swf_SetU32(TAG * t,U32 v)
169 { U8 a[4];
170   a[0] = v&0xff;        // to ensure correct handling of non-intel byteorder
171   a[1] = (v>>8)&0xff;
172   a[2] = (v>>16)&0xff;
173   a[3] = (v>>24)&0xff;
174   
175   swf_ResetWriteBits(t);
176   if ((t->len+4)>t->memsize) return (swf_SetBlock(t,a,4)==4)?0:-1;
177   t->data[t->len++] = a[0];
178   t->data[t->len++] = a[1];
179   t->data[t->len++] = a[2];
180   t->data[t->len++] = a[3];
181   return 0;
182 }
183
184 U32 swf_GetBits(TAG * t,int nbits)
185 { U32 res = 0;
186   if (!nbits) return 0;
187   if (!t->readBit) t->readBit = 0x80;
188   while (nbits)
189   { res<<=1;
190     if (t->data[t->pos]&t->readBit) res|=1;
191     t->readBit>>=1;
192     nbits--;
193     if (!t->readBit)
194     { if (nbits) t->readBit = 0x80;
195       #ifdef DEBUG_RFXSWF
196       if (t->pos>=t->len) 
197       { fprintf(stderr,"GetBits() out of bounds: TagID = %i\n",t->id);
198         return res;
199       }
200       #endif
201       t->pos++;
202     }
203   }
204   return res;
205 }
206
207 S32 swf_GetSBits(TAG * t,int nbits)
208 { U32 res = swf_GetBits(t,nbits);
209   if (res&(1<<(nbits-1))) res|=(0xffffffff<<nbits);  
210   return (S32)res;
211 }
212
213 U32 reader_GetBits(struct reader_t*reader, int nbits)
214 { return reader_readbits(reader, nbits);
215 }
216 S32 reader_GetSBits(struct reader_t*reader, int nbits)
217 { U32 res = reader_readbits(reader, nbits);
218   if (res&(1<<(nbits-1))) res|=(0xffffffff<<nbits);  
219   return (S32)res;
220 }
221
222 int swf_SetBits(TAG * t,U32 v,int nbits)
223 { U32 bm = 1<<(nbits-1);
224
225   while (nbits)
226   { if (!t->writeBit)
227     { if (FAILED(swf_SetU8(t,0))) return -1;
228       t->writeBit = 0x80;
229     }
230     if (v&bm) t->data[t->len-1] |= t->writeBit;
231     bm>>=1;
232     t->writeBit>>=1;
233     nbits--;
234   }
235   return 0;
236 }
237
238 // Advanced Data Access Functions
239
240 int swf_SetRGB(TAG * t,RGBA * col)
241 { if (!t) return -1;
242   if (col)
243   { swf_SetU8(t,col->r);
244     swf_SetU8(t,col->g);
245     swf_SetU8(t,col->b);
246   } else swf_SetBlock(t,NULL,3);
247   return 0;
248 }
249 void swf_GetRGB(TAG * t, RGBA * col)
250 {
251     RGBA dummy;
252     if(!col);
253         col = &dummy;
254     col->r = swf_GetU8(t);
255     col->g = swf_GetU8(t);
256     col->b = swf_GetU8(t);
257     col->a = 255;
258 }
259
260 int swf_SetRGBA(TAG * t,RGBA * col)
261 { if (!t) return -1;
262   if (col)
263   { swf_SetU8(t,col->r);
264     swf_SetU8(t,col->g);
265     swf_SetU8(t,col->b);
266     swf_SetU8(t,col->a);
267   } else swf_SetBlock(t,NULL,4);
268   return 0;
269 }
270 void swf_GetRGBA(TAG * t, RGBA * col)
271 {
272     RGBA dummy;
273     if(!col);
274         col = &dummy;
275     col->r = swf_GetU8(t);
276     col->g = swf_GetU8(t);
277     col->b = swf_GetU8(t);
278     col->a = swf_GetU8(t);
279 }
280
281 void swf_GetGradient(TAG * tag, GRADIENT * gradient, char alpha)
282 {
283     GRADIENT dummy;
284     int t;
285     if(!gradient)
286         gradient = &dummy;
287     gradient->num = swf_GetU8(tag);
288     for(t=0;t<gradient->num;t++)
289     {
290         int s=t;
291         if(s>=8) //FIXME
292             s=7;
293         gradient->ratios[t] = swf_GetU8(tag);
294         if(!alpha)
295             swf_GetRGB(tag, &gradient->rgba[t]);
296         else
297             swf_GetRGBA(tag, &gradient->rgba[t]);
298     }
299 }
300
301 int swf_CountBits(U32 v,int nbits)
302 { int n = 33;
303   U32 m = 0x80000000;
304   if (!v) n = 0; else
305   if (v&m)
306   { while (v&m)
307     { n--;
308       m>>=1;
309       if (!m) break;
310     } 
311   }
312   else
313   { while (!(v&m))
314     { n--;
315       m>>=1;
316       if (!m) break;
317     } 
318   }
319   return (n>nbits)?n:nbits;
320 }
321
322 int swf_GetRect(TAG * t,SRECT * r)
323 { int nbits;
324   SRECT dummy;
325   if (!r) r = &dummy;
326   nbits = (int) swf_GetBits(t,5);
327   r->xmin = swf_GetSBits(t,nbits);
328   r->xmax = swf_GetSBits(t,nbits);
329   r->ymin = swf_GetSBits(t,nbits);
330   r->ymax = swf_GetSBits(t,nbits);
331   return 0;
332 }
333
334 int reader_GetRect(struct reader_t*reader,SRECT * r)
335 { int nbits;
336   SRECT dummy;
337   if (!r) r = &dummy;
338   nbits = (int) reader_GetBits(reader,5);
339   r->xmin = reader_GetSBits(reader,nbits);
340   r->xmax = reader_GetSBits(reader,nbits);
341   r->ymin = reader_GetSBits(reader,nbits);
342   r->ymax = reader_GetSBits(reader,nbits);
343   return 0;
344 }
345
346 int swf_SetRect(TAG * t,SRECT * r)
347 { int nbits;
348     
349   nbits = swf_CountBits(r->xmin,0);
350   nbits = swf_CountBits(r->xmax,nbits);
351   nbits = swf_CountBits(r->ymin,nbits);
352   nbits = swf_CountBits(r->ymax,nbits);
353   if(nbits>=32) {
354     fprintf(stderr, "rfxswf: Warning: num_bits overflow in swf_SetRect\n");
355     nbits=31;
356   }
357
358   swf_SetBits(t,nbits,5);
359   swf_SetBits(t,r->xmin,nbits);
360   swf_SetBits(t,r->xmax,nbits);
361   swf_SetBits(t,r->ymin,nbits);
362   swf_SetBits(t,r->ymax,nbits);
363
364   return 0;
365 }
366
367 int swf_GetMatrix(TAG * t,MATRIX * m)
368 { MATRIX dummy;
369   int nbits;
370     
371   if (!m) m = &dummy;
372   
373   if (!t)
374   { m->sx = m->sy = 0x10000;
375     m->r0 = m->r1 = 0;
376     m->tx = m->ty = 0;
377     return -1;
378   }
379
380   swf_ResetReadBits(t);
381   
382   if (swf_GetBits(t,1))
383   { nbits = swf_GetBits(t,5);
384     m->sx = swf_GetSBits(t,nbits);
385     m->sy = swf_GetSBits(t,nbits);
386   }
387   else m->sx = m->sy = 0x10000;
388   
389   if (swf_GetBits(t,1))
390   { nbits = swf_GetBits(t,5);
391     m->r0 = swf_GetSBits(t,nbits);
392     m->r1 = swf_GetSBits(t,nbits);
393   }
394   else m->r0 = m->r1 = 0x0;
395
396   nbits = swf_GetBits(t,5);
397   m->tx = swf_GetSBits(t,nbits);
398   m->ty = swf_GetSBits(t,nbits);
399   
400   return 0;
401 }
402
403 int swf_SetMatrix(TAG * t,MATRIX * m)
404 { int nbits;
405   MATRIX ma;
406
407   if (!m)
408   { m = &ma;
409     ma.sx = ma.sy = 0x10000;
410     ma.r0 = ma.r1 = 0;
411     ma.tx = ma.ty = 0;
412   }
413
414   swf_ResetWriteBits(t);
415
416   if ((m->sx==0x10000)&&(m->sy==0x10000)) swf_SetBits(t,0,1);
417   else
418   { swf_SetBits(t,1,1);
419     nbits = swf_CountBits(m->sx,0);
420     nbits = swf_CountBits(m->sy,nbits);
421     if(nbits>=32) {
422         fprintf(stderr,"rfxswf: Error: matrix values too large\n");
423         nbits = 31;
424     }
425     swf_SetBits(t,nbits,5);
426     swf_SetBits(t,m->sx,nbits);
427     swf_SetBits(t,m->sy,nbits);
428   }
429
430   if ((!m->r0)&&(!m->r1)) swf_SetBits(t,0,1);
431   else
432   { swf_SetBits(t,1,1);
433     nbits = swf_CountBits(m->r0,0);
434     nbits = swf_CountBits(m->r1,nbits);
435     if(nbits>=32) {
436         fprintf(stderr,"rfxswf: Error: matrix values too large\n");
437         nbits = 31;
438     }
439     swf_SetBits(t,nbits,5);
440     swf_SetBits(t,m->r0,nbits);
441     swf_SetBits(t,m->r1,nbits);
442   }
443
444   nbits = swf_CountBits(m->tx,0);
445   nbits = swf_CountBits(m->ty,nbits);
446   if(nbits>=32) {
447       fprintf(stderr,"rfxswf: Error: matrix values too large\n");
448       nbits = 31;
449   }
450   swf_SetBits(t,nbits,5);
451   swf_SetBits(t,m->tx,nbits);
452   swf_SetBits(t,m->ty,nbits);
453
454   return 0;
455 }
456
457 int swf_GetCXForm(TAG * t,CXFORM * cx,U8 alpha) //FIXME: alpha should be type bool
458 { CXFORM cxf;
459   int hasadd;
460   int hasmul;
461   int nbits;
462     
463   if (!cx) cx = &cxf;
464   
465   cx->a0 = cx->r0 = cx->g0 = cx->b0 = 256;
466   cx->a1 = cx->r1 = cx->g1 = cx->b1 = 0;
467
468   if (!t) return 0;
469   
470   swf_ResetReadBits(t);
471   hasadd = swf_GetBits(t,1);
472   hasmul = swf_GetBits(t,1);
473   nbits  = swf_GetBits(t,4);
474
475   if (hasmul)
476   { cx->r0 = (S16)swf_GetSBits(t,nbits);
477     cx->g0 = (S16)swf_GetSBits(t,nbits);
478     cx->b0 = (S16)swf_GetSBits(t,nbits);
479     if (alpha)
480       cx->a0 = (S16)swf_GetSBits(t,nbits);
481   }
482
483   if (hasadd)
484   { cx->r1 = (S16)swf_GetSBits(t,nbits);
485     cx->g1 = (S16)swf_GetSBits(t,nbits);
486     cx->b1 = (S16)swf_GetSBits(t,nbits);
487     if (alpha)
488       cx->a1 = (S16)swf_GetSBits(t,nbits);
489   }
490   
491   return 0;
492 }
493
494 int swf_SetCXForm(TAG * t,CXFORM * cx,U8 alpha)
495 { CXFORM cxf;
496   int hasadd;
497   int hasmul;
498   int nbits;
499     
500   if (!cx)
501   { cx = &cxf;
502     cx->a0 = cx->r0 = cx->g0 = cx->b0 = 256;
503     cx->a1 = cx->r1 = cx->g1 = cx->b1 = 0;
504   }
505
506   if (!alpha)
507   { cx->a0 = 256;
508     cx->a1 = 0;
509   }
510
511   nbits = 0;
512
513   hasmul = (cx->a0!=256)||(cx->r0!=256)||(cx->g0!=256)||(cx->b0!=256);
514   hasadd = cx->a1|cx->r1|cx->g1|cx->b1;
515
516   if (hasmul)
517   { if (alpha) nbits = swf_CountBits((S32)cx->a0,nbits);
518     nbits = swf_CountBits((S32)cx->r0,nbits);
519     nbits = swf_CountBits((S32)cx->g0,nbits);
520     nbits = swf_CountBits((S32)cx->b0,nbits);
521   }
522
523   if (hasadd)
524   { if (alpha) nbits = swf_CountBits((S32)cx->a1,nbits);
525     nbits = swf_CountBits((S32)cx->r1,nbits);
526     nbits = swf_CountBits((S32)cx->g1,nbits);
527     nbits = swf_CountBits((S32)cx->b1,nbits);
528   }
529   
530   swf_ResetWriteBits(t);
531   swf_SetBits(t,hasadd?1:0,1);
532   swf_SetBits(t,hasmul?1:0,1);
533   swf_SetBits(t,nbits,4);
534
535   if (hasmul)
536   { swf_SetBits(t,cx->r0,nbits);
537     swf_SetBits(t,cx->g0,nbits);
538     swf_SetBits(t,cx->b0,nbits);
539     if (alpha) swf_SetBits(t,cx->a0,nbits);
540   }
541
542   if (hasadd)
543   { swf_SetBits(t,cx->r1,nbits);
544     swf_SetBits(t,cx->g1,nbits);
545     swf_SetBits(t,cx->b1,nbits);
546     if (alpha) swf_SetBits(t,cx->a1,nbits);
547   }
548   
549   return 0;
550 }
551
552 int swf_GetPoint(TAG * t,SPOINT * p) { return 0; }
553 int swf_SetPoint(TAG * t,SPOINT * p) { return 0; }
554
555 // Tag List Manipulating Functions
556
557 int swf_UpdateFrame(TAG * t,S8 delta)
558 // returns number of frames
559 { int res = -1;
560   while (t)
561   { t->frame+=delta;
562     res = t->frame;
563     t = t->next;
564   }
565   return res;
566 }
567
568 TAG * swf_InsertTag(TAG * after,U16 id)     // updates frames, if nescessary
569 { TAG * t;
570
571   t = (TAG *)malloc(sizeof(TAG));
572   if (t)
573   { memset(t,0x00,sizeof(TAG));
574     t->id = id;
575     
576     if (after)
577     { t->frame = after->frame;
578       t->prev  = after;
579       t->next  = after->next;
580       after->next = t;
581       if (t->next) t->next->prev = t;
582       
583       if (id==ST_SHOWFRAME) swf_UpdateFrame(t->next,+1);
584     }
585   }
586   return t;
587 }
588
589 int swf_DeleteTag(TAG * t)
590 { if (!t) return -1;
591
592   if (t->id==ST_SHOWFRAME) swf_UpdateFrame(t->next,-1);
593     
594   if (t->prev) t->prev->next = t->next;
595   if (t->next) t->next->prev = t->prev;
596
597   if (t->data) free(t->data);
598   free(t);
599   return 0;
600 }
601
602 TAG * swf_ReadTag(struct reader_t*reader, TAG * prev)
603 { TAG * t;
604   U16 raw;
605   U32 len;
606   int id;
607
608   if (reader->read(reader, &raw, 2) !=2 ) return NULL;
609   raw = SWAP16(raw);
610
611   len = raw&0x3f;
612   id  = raw>>6;
613
614   if (len==0x3f)
615   {
616       if (reader->read(reader, &len, 4) != 4) return NULL;
617       len = SWAP32(len);
618   }
619
620   if (id==ST_DEFINESPRITE) len = 2*sizeof(U16);
621   // Sprite handling fix: Flaten sprite tree
622
623   t = (TAG *)malloc(sizeof(TAG));
624   
625   if (!t)
626   {
627     #ifdef DEBUG_RFXSWF
628       fprintf(stderr,"Fatal Error: malloc()/realloc() failed (2). (%d bytes)\n", sizeof(TAG));
629     #endif
630     return NULL;
631   }
632
633   memset(t,0x00,sizeof(TAG));
634   
635   t->len = len;
636   t->id  = id;
637
638   if (t->len)
639   { t->data = (U8*)malloc(t->len);
640     if (!t->data)
641     {
642       #ifdef DEBUG_RFXSWF
643         fprintf(stderr,"Fatal Error: malloc()/realloc() failed (3). (%d bytes)\n", t->len);
644       #endif
645       return NULL;
646     }
647     t->memsize = t->len;
648     if (reader->read(reader, t->data, t->len) != t->len) return NULL;
649   }
650
651   if (prev)
652   { t->frame = prev->frame+((prev->id==ST_SHOWFRAME)?1:0);
653     t->prev  = prev;
654     prev->next = t;
655   }
656
657   return t;
658 }
659
660 int swf_DefineSprite_GetRealSize(TAG * t);
661
662 int swf_WriteTag2(struct writer_t*writer, TAG * t)
663 // returns tag length in bytes (incl. Header), -1 = Error
664 // writer = 0 -> no output
665 { U16 raw[3];
666   U32 len;
667   int short_tag;
668
669   if (!t) return -1;
670
671   len = (t->id==ST_DEFINESPRITE)?swf_DefineSprite_GetRealSize(t):t->len;
672
673   short_tag = len<0x3f;
674
675   if (writer)
676   { if (short_tag)
677     { raw[0] = SWAP16(len|((t->id&0x3ff)<<6));
678       if (writer->write(writer,raw,2)!=2)
679       {
680         #ifdef DEBUG_RFXSWF
681           fprintf(stderr,"WriteTag() failed: Short Header.\n");
682         #endif
683         return -1;
684       }
685     }
686     else
687     {
688       raw[0] = SWAP16((t->id<<6)|0x3f);
689       if (writer->write(writer,raw,2)!=2)
690       {
691 #ifdef DEBUG_RFXSWF
692           fprintf(stderr,"WriteTag() failed: Long Header (1).\n");
693 #endif
694           return -1;
695       }
696       
697       len = SWAP32(len);
698       if (writer->write(writer,&len,4)!=4)
699       {
700         #ifdef DEBUG_RFXSWF
701           fprintf(stderr,"WriteTag() failed: Long Header (2).\n");
702         #endif
703         return -1;
704       }
705     }
706     
707     if (t->data)
708     { if (writer->write(writer,t->data,t->len)!=t->len)
709       {
710         #ifdef DEBUG_RFXSWF
711           fprintf(stderr,"WriteTag() failed: Data.\n");
712         #endif
713         return -1;
714       }
715     }
716     #ifdef DEBUG_RFXSWF
717       else if (t->len) fprintf(stderr,"WriteTag(): Tag Data Error, id=%i\n",t->id);
718     #endif
719   }
720
721   return t->len+(short_tag?2:6);
722 }
723
724 int swf_WriteTag(int handle, TAG * t)
725 {
726   struct writer_t writer;
727   if(handle<0)
728     return swf_WriteTag2(0, t);
729   writer_init_filewriter(&writer, handle);
730   return swf_WriteTag2(&writer, t);
731 }
732
733 int swf_DefineSprite_GetRealSize(TAG * t)
734 // Sprite Handling: Helper function to pack DefineSprite-Tag
735 { U32 len = t->len;
736   if(len>4) { // folded sprite
737       return t->len;
738   }
739   do
740   { t = swf_NextTag(t);
741     if (t->id!=ST_DEFINESPRITE) len += swf_WriteTag(-1, t);
742     else t = NULL;
743   } while (t&&(t->id!=ST_END));
744   return len;
745 }
746
747 void swf_UnFoldSprite(TAG * t)
748 {
749   U16 id,tmp;
750   U32 len;
751   TAG*next = t;
752   U16 spriteid,spriteframes;
753   if(t->id!=ST_DEFINESPRITE)
754     return;
755   if(t->len<=4) // not folded
756     return;
757
758   swf_SetTagPos(t,0);
759
760   spriteid = swf_GetU16(t); //id
761   spriteframes = swf_GetU16(t); //frames
762
763   tmp = swf_GetU16(t);
764   len = tmp&0x3f;
765   id  = tmp>>6;
766   while(id)
767   {
768     TAG*it = 0;
769     if (len==0x3f)
770         len = swf_GetU32(t);
771     it = swf_InsertTag(next, id);
772     next = it;
773     it->len = len;
774     it->id  = id;
775     if (it->len)
776     { it->data = (U8*)malloc(t->len);
777       it->memsize = it->len;
778       swf_GetBlock(t, it->data, it->len);
779     }
780     tmp = swf_GetU16(t);
781     len = tmp&0x3f;
782     id  = tmp>>6;
783   }
784   
785   free(t->data); t->data = 0;
786   t->memsize = t->len = t->pos = 0;
787
788   swf_SetU16(t, spriteid);
789   swf_SetU16(t, spriteframes);
790 }
791
792 void swf_FoldSprite(TAG * t)
793 {
794   TAG*sprtag=t,*tmp;
795   U16 id,frames,tmpid;
796   if(t->id!=ST_DEFINESPRITE)
797       return;
798   if(!t->len) {
799       fprintf(stderr, "Error: Sprite has no ID!");
800       return;
801   }
802   if(t->len>4) {
803     /* sprite is already folded */
804       return;
805   }
806
807   t->pos = 0;
808   id = swf_GetU16(t);
809   //frames = swf_GetU16(t);
810   free(t->data);
811   t->len = t->pos = t->memsize = 0;
812   t->data = 0;
813
814   frames = 0;
815
816   do 
817   { 
818     if(t->id==ST_SHOWFRAME) frames++;
819     t = swf_NextTag(t);
820   } while(t&&t!=ST_END);
821
822   t = swf_NextTag(sprtag);
823   swf_SetU16(sprtag, id);
824   swf_SetU16(sprtag, frames);
825
826   do
827   { 
828     tmpid= t->id;
829     if(t->len<0x3f) {
830         swf_SetU16(sprtag,t->len|(t->id<<6));
831     } else {
832         swf_SetU16(sprtag,0x3f|(t->id<<6));
833         swf_SetU32(sprtag,t->len);
834     }
835     if(t->len)
836         swf_SetBlock(sprtag,t->data, t->len);
837     tmp = t;
838     t = swf_NextTag(t);
839     swf_DeleteTag(tmp);
840   } 
841   while (t&&(tmpid!=ST_END));
842
843 //  sprtag->next = t;
844 //  t->prev = sprtag;
845 }
846
847 void swf_FoldAll(SWF*swf)
848 {
849     TAG*tag = swf->firstTag;
850     while(tag) {
851         if(tag->id == ST_DEFINESPRITE)
852             swf_FoldSprite(tag);
853         tag = swf_NextTag(tag);
854     }
855 }
856
857 void swf_UnFoldAll(SWF*swf)
858 {
859     TAG*tag = swf->firstTag;
860     while(tag) {
861         TAG*next = swf_NextTag(tag);
862         if(tag->id == ST_DEFINESPRITE)
863             swf_UnFoldSprite(tag);
864         tag = next;
865     }
866 }
867
868 void swf_OptimizeTagOrder(SWF*swf)
869 {
870   TAG*tag,*next;
871   TAG*level0;
872   int level;
873   int changes;
874   swf_UnFoldAll(swf);
875   /* at the moment, we don't actually do optimizing,
876      only fixing of non-spec-conformant things like
877      sprite tags */
878
879   do {
880     changes = 0;
881     level = 0;
882     level0 = 0;
883     tag = swf->firstTag;
884     while(tag) {
885       next = tag->next;
886       if(tag->id == ST_DEFINESPRITE) {
887         level++;
888         if(level==1) {
889           level0 = tag;
890           tag = next;
891           continue;
892         }
893       }
894       if(level>=1) {
895         /* move non-sprite tags out of sprite */
896         if(!swf_isAllowedSpriteTag(tag) || level>=2) {
897           /* remove tag from current position */
898           tag->prev->next = tag->next;
899           tag->next->prev = tag->prev;
900
901           /* insert before tag level0 */
902           tag->next = level0;
903           tag->prev = level0->prev;
904           level0->prev = tag;
905           tag->prev->next = tag;
906           changes = 1;
907         }
908       }
909       if(tag->id == ST_END) {
910         level--;
911       }
912
913       tag = next;
914     }
915   } while(changes);
916 }
917
918 // Movie Functions
919
920 int swf_ReadSWF2(struct reader_t*reader, SWF * swf)   // Reads SWF to memory (malloc'ed), returns length or <0 if fails
921 {     
922   if (!swf) return -1;
923   memset(swf,0x00,sizeof(SWF));
924
925   { char b[32];                         // read Header
926     int len;
927     TAG * t;
928     TAG t1;
929     struct reader_t zreader;
930     
931     if ((len = reader->read(reader ,b,8))<8) return -1;
932
933     if (b[0]!='F' && b[0]!='C') return -1;
934     if (b[1]!='W') return -1;
935     if (b[2]!='S') return -1;
936     swf->fileVersion = b[3];
937     swf->compressed  = (b[0]=='C')?1:0;
938     swf->fileSize    = GET32(&b[4]);
939     
940     if(swf->compressed) {
941         reader_init_zlibinflate(&zreader, reader);
942         reader = &zreader;
943     }
944
945     reader_GetRect(reader, &swf->movieSize);
946     reader->read(reader, &swf->frameRate, 2);
947     swf->frameRate = SWAP16(swf->frameRate);
948     reader->read(reader, &swf->frameCount, 2);
949     swf->frameCount = SWAP16(swf->frameCount);
950
951     /* read tags and connect to list */
952     t = &t1;
953     while (t) t = swf_ReadTag(reader,t);
954     swf->firstTag = t1.next;
955     t1.next->prev = NULL;
956   }
957   
958   return reader->pos;
959 }
960
961 int swf_ReadSWF(int handle, SWF * swf)
962 {
963   struct reader_t reader;
964   reader_init_filereader(&reader, handle);
965   return swf_ReadSWF2(&reader, swf);
966 }
967
968 int  swf_WriteSWF2(struct writer_t*writer, SWF * swf)     // Writes SWF to file, returns length or <0 if fails
969 { U32 len;
970   TAG * t;
971   int frameCount=0;
972   struct writer_t zwriter;
973   int fileSize = 0;
974     
975   if (!swf) return -1;
976
977   // Insert REFLEX Tag
978
979 #ifdef INSERT_RFX_TAG
980
981   if (swf->firstTag && swf_NextTag(swf->firstTag))
982     if (swf_GetTagID(swf_NextTag(swf->firstTag))!=ST_REFLEX)
983       swf_SetBlock(swf_InsertTag(swf->firstTag,ST_REFLEX),"rfx",3);
984
985 #endif // INSERT_RFX_TAG
986
987   // Count Frames + File Size
988
989   len = 0;
990   t = swf->firstTag;
991   frameCount = 0;
992
993   while(t)
994   { len += swf_WriteTag(-1, t);
995     if (t->id==ST_SHOWFRAME) frameCount++;
996     t = swf_NextTag(t);
997   }
998   
999   { TAG t1;
1000     char b[64],b4[4];
1001     U32 l;
1002
1003     memset(&t1,0x00,sizeof(TAG));
1004     t1.data    = (U8*)b;
1005     t1.memsize = 64;
1006     
1007     { // measure header file size
1008       TAG t2;
1009       char b2[64];
1010       memset(&t2,0x00,sizeof(TAG));
1011       t2.data    = (U8*)b2;
1012       t2.memsize = 64;
1013       swf_SetRect(&t2, &swf->movieSize);
1014       swf_SetU16(&t2, swf->frameRate);
1015       swf_SetU16(&t2, swf->frameCount);
1016       l = swf_GetTagLen(&t2)+8;
1017     }
1018
1019     fileSize = l+len;
1020     if(len) {// don't touch headers without tags
1021         swf->fileSize = fileSize;
1022         swf->frameCount = frameCount;
1023     }
1024    
1025     if(swf->compressed) {
1026       char*id = "CWS";
1027       writer->write(writer, id, 3);
1028     }
1029     else {
1030       char*id = "FWS";
1031       writer->write(writer, id, 3);
1032     }
1033
1034     writer->write(writer, &swf->fileVersion, 1);
1035     PUT32(b4, swf->fileSize);
1036     writer->write(writer, b4, 4);
1037
1038     if(swf->compressed) {
1039       writer_init_zlibdeflate(&zwriter, writer);
1040       writer = &zwriter;
1041     }
1042
1043     swf_SetRect(&t1,&swf->movieSize);
1044     swf_SetU16(&t1,swf->frameRate);
1045     swf_SetU16(&t1,swf->frameCount);
1046
1047     if (writer)
1048     { 
1049       int ret = writer->write(writer,b,swf_GetTagLen(&t1));
1050       if (ret!=swf_GetTagLen(&t1))
1051       {
1052         #ifdef DEBUG_RFXSWF
1053           printf("ret:%d\n",ret);
1054           perror("write:");
1055           fprintf(stderr,"WriteSWF() failed: Header.\n");
1056         #endif
1057         return -1;
1058       }
1059
1060       t = swf->firstTag;
1061       while (t)
1062       { if (swf_WriteTag2(writer, t)<0) return -1;
1063         t = swf_NextTag(t);
1064       }
1065       writer->finish(writer); //e.g. flush zlib buffers
1066     }
1067   }
1068   return (int)fileSize;
1069 }
1070
1071 int  swf_WriteSWF(int handle, SWF * swf)     // Writes SWF to file, returns length or <0 if fails
1072 {
1073   struct writer_t writer;
1074   swf->compressed = 0;
1075   if(handle<0)
1076     return swf_WriteSWF2(&writer, swf);
1077   writer_init_filewriter(&writer, handle);
1078   return swf_WriteSWF2(&writer, swf);
1079 }
1080
1081 int  swf_WriteSWC(int handle, SWF * swf)     // Writes SWF to file, returns length or <0 if fails
1082 {
1083   struct writer_t writer;
1084   swf->compressed = 1;
1085   if(handle<0)
1086     return swf_WriteSWF2(&writer, swf);
1087   writer_init_filewriter(&writer, handle);
1088   return swf_WriteSWF2(&writer, swf);
1089 }
1090
1091 int swf_WriteHeader2(struct writer_t*writer,SWF * swf)
1092 {
1093   SWF myswf;
1094   memcpy(&myswf,swf,sizeof(SWF));
1095   myswf.firstTag = 0;
1096   return swf_WriteSWF2(writer, &myswf);
1097 }
1098
1099 int swf_WriteHeader(int handle,SWF * swf)
1100 {
1101   SWF myswf;
1102   memcpy(&myswf,swf,sizeof(SWF));
1103   myswf.firstTag = 0;
1104   return swf_WriteSWF(handle, &myswf);
1105 }
1106
1107 int swf_WriteCGI(SWF * swf)
1108 { int len;
1109   char s[1024];
1110     
1111   len = swf_WriteSWF(-1,swf);
1112
1113   if (len<0) return -1;
1114
1115   sprintf(s,"Content-type: application/x-shockwave-flash\n"
1116             "Accept-Ranges: bytes\n"
1117             "Content-Length: %lu\n"
1118             "Expires: Thu, 13 Apr 2000 23:59:59 GMT\n"
1119             "\n",len);
1120             
1121   write(fileno(stdout),s,strlen(s));
1122   return swf_WriteSWF(fileno(stdout),swf);
1123 }
1124
1125 void swf_FreeTags(SWF * swf)                 // Frees all malloc'ed memory for tags
1126 { TAG * t = swf->firstTag;
1127
1128   while (t)
1129   { TAG * tnew = t->next;
1130     if (t->data) free(t->data);
1131     free(t);
1132     t = tnew;
1133   }
1134 }
1135
1136 // include advanced functions
1137
1138 #include "modules/swfdump.c"
1139 #include "modules/swfshape.c"
1140 #include "modules/swftext.c"
1141 #include "modules/swfobject.c"
1142 #include "modules/swfbutton.c"
1143 #include "modules/swftools.c"
1144 #include "modules/swfcgi.c"
1145 #include "modules/swfbits.c"
1146 #include "modules/swfaction.c"
1147 #include "modules/swfsound.c"
1148