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