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