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