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