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