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 "mem.h"
28 #include "rfxswf.h"
29 #ifdef HAVE_ZLIB
30 #include <zlib.h>
31 #endif // HAVE_ZLIB
32 
33 #ifndef RFXSWF_DISABLESOUND
34 #ifdef HAVE_LAME
35 #include "lame/lame.h"
36 #endif
37 #endif
38 
39 #ifdef HAVE_TIME_H
40 #include <time.h>
41 #endif
42 
43 #ifdef HAVE_IO_H
44 #include <io.h>
45 #endif
46 
47 #include "./bitio.h"
48 #include "./os.h"
49 
50 // internal constants
51 
52 #define MALLOC_SIZE     128
53 #define INSERT_RFX_TAG
54 
55 #define MEMSIZE(l) (((l/MALLOC_SIZE)+1)*MALLOC_SIZE)
56 
57 // inline wrapper functions
58 
swf_NextTag(TAG * t)59 TAG * swf_NextTag(TAG * t) { return t->next; }
swf_PrevTag(TAG * t)60 TAG * swf_PrevTag(TAG * t) { return t->prev; }
swf_GetTagID(TAG * t)61 U16   swf_GetTagID(TAG * t)    { return t->id; }
swf_GetTagLen(TAG * t)62 U32   swf_GetTagLen(TAG * t) { return t->len; }
swf_GetTagLenPtr(TAG * t)63 U8*   swf_GetTagLenPtr(TAG * t) { return &(t->data[t->len]); }
swf_GetTagPos(TAG * t)64 U32   swf_GetTagPos(TAG * t)   { return t->pos; }
65 
swf_SetTagPos(TAG * t,U32 pos)66 void swf_SetTagPos(TAG * t,U32 pos)
67 { swf_ResetReadBits(t);
68   if (pos<=t->len) t->pos = pos;
69   else {
70 #ifdef DEBUG_RFXSWF
71     fprintf(stderr,"SetTagPos(%d) out of bounds: TagID = %i\n",pos, t->id);
72 #endif
73   }
74 }
75 
swf_GetString(TAG * t)76 char* swf_GetString(TAG*t)
77 {
78     int pos = t->pos;
79     while(t->pos < t->len && swf_GetU8(t));
80     /* make sure we always have a trailing zero byte */
81     if(t->pos == t->len) {
82       if(t->len == t->memsize) {
83 	swf_ResetWriteBits(t);
84 	swf_SetU8(t, 0);
85 	t->len = t->pos;
86       }
87       t->data[t->len] = 0;
88     }
89     return (char*)&(t->data[pos]);
90 }
91 
swf_GetU8(TAG * t)92 U8 swf_GetU8(TAG * t)
93 { swf_ResetReadBits(t);
94   #ifdef DEBUG_RFXSWF
95     if ((int)t->pos>=(int)t->len)
96     { fprintf(stderr,"GetU8() out of bounds: TagID = %i\n",t->id);
97       *(int*)0=0;
98       return 0;
99     }
100   #endif
101   return t->data[t->pos++];
102 }
103 
swf_GetU16(TAG * t)104 U16 swf_GetU16(TAG * t)
105 { U16 res;
106   swf_ResetReadBits(t);
107   #ifdef DEBUG_RFXSWF
108     if ((int)t->pos>((int)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 
swf_GetU32(TAG * t)118 U32 swf_GetU32(TAG * t)
119 { U32 res;
120   swf_ResetReadBits(t);
121   #ifdef DEBUG_RFXSWF
122     if ((int)t->pos>((int)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 
swf_GetBlock(TAG * t,U8 * b,int l)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 
swf_SetBlock(TAG * t,const U8 * b,int l)143 int swf_SetBlock(TAG * t,const 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*)(rfx_realloc(t->data,newmem));
150     t->memsize = newmem;
151     t->data    = newdata;
152   }
153   if (b) memcpy(&t->data[t->len],b,l);
154   else memset(&t->data[t->len],0x00,l);
155   t->len+=l;
156   return l;
157 }
158 
swf_SetU8(TAG * t,U8 v)159 int swf_SetU8(TAG * t,U8 v)
160 { swf_ResetWriteBits(t);
161   if ((t->len+1)>t->memsize) return (swf_SetBlock(t,&v,1)==1)?0:-1;
162   t->data[t->len++] = v;
163   return 0;
164 }
165 
swf_SetU16(TAG * t,U16 v)166 int swf_SetU16(TAG * t,U16 v)
167 { U8 a[2];
168   a[0] = v&0xff;
169   a[1] = v>>8;
170 
171   swf_ResetWriteBits(t);
172   if ((t->len+2)>t->memsize) return (swf_SetBlock(t,a,2)==2)?0:-1;
173   t->data[t->len++] = a[0];
174   t->data[t->len++] = a[1];
175   return 0;
176 }
swf_SetS16(TAG * t,int v)177 void swf_SetS16(TAG * t,int v)
178 {
179     if(v>32767 || v<-32768) {
180       #ifdef DEBUG_RFXSWF
181 	fprintf(stderr, "Warning: S16 overflow: %d\n", v);
182       #endif
183     }
184     swf_SetU16(t, (S16)v);
185 }
186 
swf_SetU32(TAG * t,U32 v)187 int swf_SetU32(TAG * t,U32 v)
188 { U8 a[4];
189   a[0] = v&0xff;        // to ensure correct handling of non-intel byteorder
190   a[1] = (v>>8)&0xff;
191   a[2] = (v>>16)&0xff;
192   a[3] = (v>>24)&0xff;
193 
194   swf_ResetWriteBits(t);
195   if ((t->len+4)>t->memsize) return (swf_SetBlock(t,a,4)==4)?0:-1;
196   t->data[t->len++] = a[0];
197   t->data[t->len++] = a[1];
198   t->data[t->len++] = a[2];
199   t->data[t->len++] = a[3];
200   return 0;
201 }
202 
swf_GetBits(TAG * t,int nbits)203 U32 swf_GetBits(TAG * t,int nbits)
204 { U32 res = 0;
205   if (!nbits) return 0;
206   if (!t->readBit) t->readBit = 0x80;
207   while (nbits)
208   { res<<=1;
209 #ifdef DEBUG_RFXSWF
210     if (t->pos>=t->len)
211     { fprintf(stderr,"GetBits() out of bounds: TagID = %i, pos=%d, len=%d\n",t->id, t->pos, t->len);
212       int i,m=t->len>10?10:t->len;
213       for(i=-1;i<m;i++) {
214         fprintf(stderr, "(%d)%02x ", i, t->data[i]);
215       }
216       fprintf(stderr, "\n");
217       return res;
218     }
219 #endif
220     if (t->data[t->pos]&t->readBit) res|=1;
221     t->readBit>>=1;
222     nbits--;
223     if (!t->readBit)
224     { if (nbits) t->readBit = 0x80;
225       t->pos++;
226     }
227   }
228   return res;
229 }
230 
swf_GetSBits(TAG * t,int nbits)231 S32 swf_GetSBits(TAG * t,int nbits)
232 { U32 res = swf_GetBits(t,nbits);
233   if (res&(1<<(nbits-1))) res|=(0xffffffff<<nbits);
234   return (S32)res;
235 }
236 
reader_GetBits(reader_t * reader,int nbits)237 U32 reader_GetBits(reader_t*reader, int nbits)
238 { return reader_readbits(reader, nbits);
239 }
reader_GetSBits(reader_t * reader,int nbits)240 S32 reader_GetSBits(reader_t*reader, int nbits)
241 { U32 res = reader_readbits(reader, nbits);
242   if (res&(1<<(nbits-1))) res|=(0xffffffff<<nbits);
243   return (S32)res;
244 }
245 
swf_SetBits(TAG * t,U32 v,int nbits)246 int swf_SetBits(TAG * t,U32 v,int nbits)
247 { U32 bm = 1<<(nbits-1);
248 
249   while (nbits)
250   { if (!t->writeBit)
251     { if (FAILED(swf_SetU8(t,0))) return -1;
252       t->writeBit = 0x80;
253     }
254     if (v&bm) t->data[t->len-1] |= t->writeBit;
255     bm>>=1;
256     t->writeBit>>=1;
257     nbits--;
258   }
259   return 0;
260 }
261 
262 // Advanced Data Access Functions
263 
swf_GetFixed(TAG * t)264 double swf_GetFixed(TAG * t)
265 {
266   U16 low =  swf_GetU16(t);
267   U16 high = swf_GetU16(t);
268   return high + low*(1/65536.0);
269 }
swf_SetFixed(TAG * t,double f)270 void swf_SetFixed(TAG * t, double f)
271 {
272   U16 fr = (U16)((f-(int)f)*65536);
273   swf_SetU16(t, fr);
274   swf_SetU16(t, (U16)f - (f<0 && fr!=0));
275 }
swf_GetFixed8(TAG * t)276 float swf_GetFixed8(TAG * t)
277 {
278   U8 low =  swf_GetU8(t);
279   U8 high = swf_GetU8(t);
280   return (float)(high + low*(1/256.0));
281 }
swf_SetFixed8(TAG * t,float f)282 void swf_SetFixed8(TAG * t, float f)
283 {
284   U8 fr = (U8)((f-(int)f)*256);
285   swf_SetU8(t, fr);
286   swf_SetU8(t, (U8)f - (f<0 && fr!=0));
287 }
288 
swf_GetU30(TAG * tag)289 U32 swf_GetU30(TAG*tag)
290 {
291     U32 shift = 0;
292     U32 s = 0;
293     int nr=0;
294     while(1) {
295 	U8 b = swf_GetU8(tag);
296         nr++;
297 	s|=(b&127)<<shift;
298 	shift+=7;
299 	if(!(b&128) || shift>=32)
300 	    break;
301     }
302     /*int nr2= swf_SetU30(0, s);
303     if(nr!=nr2) {
304       printf("Unsigned value %d stored in %d bytes, I'd store it in %d bytes\n", s, nr, nr2);
305     }*/
306     return s;
307 }
308 
swf_SetU30(TAG * tag,U32 u)309 int swf_SetU30(TAG*tag, U32 u)
310 {
311     int nr = 0;
312     do {
313         if(tag)
314 	  swf_SetU8(tag, (u&~0x7f?0x80:0) | (u&0x7F));
315 	u>>=7;
316         nr++;
317     } while(u);
318     return nr;
319 }
320 
swf_SetABCU32(TAG * tag,U32 u)321 void swf_SetABCU32(TAG*tag, U32 u)
322 {
323   do {
324       swf_SetU8(tag, (u&~0x7f?0x80:0) | (u&0x7F));
325       u>>=7;
326   } while(u);
327 }
swf_GetABCU32(TAG * tag)328 U32 swf_GetABCU32(TAG*tag)
329 {
330   return swf_GetU30(tag);
331 }
swf_SetABCS32(TAG * tag,S32 v)332 void swf_SetABCS32(TAG*tag, S32 v)
333 {
334   swf_SetABCU32(tag, v);
335 }
swf_GetABCS32(TAG * tag)336 S32 swf_GetABCS32(TAG*tag)
337 {
338   return swf_GetABCU32(tag);
339 }
340 
341 #if 0
342 
343 /*The AVM2 spec is just plain wrong, claiming that S32 values are sign
344 extended. They're not.
345 This wastes up to 4 bytes for every negative value. */
346 
347 void swf_SetABCS32(TAG*tag, S32 s)
348 {
349   printf("write S32: %d\n", s);
350     S32 neg = s<0?-1:0;
351     U8 sign = s<0?0x40:0;
352     while(1) {
353         U8 val = s&0x7f;
354         U8 vsign = s&0x40;
355 	s>>=7;
356         neg>>=7;
357         if(s==neg && vsign==sign) {
358             /* if the value we now write has the same sign as s
359                and all the remaining bits are equal to the sign of s
360                too, stop writing */
361 	    swf_SetU8(tag, val);
362             printf("put %02x\n", val);
363             break;
364         } else {
365             swf_SetU8(tag, 0x80 | val);
366             printf("put %02x\n", 0x80|val);
367         }
368     };
369 }
370 int swf_GetS30(TAG*tag)
371 {
372     U32 shift = 0;
373     U32 s = 0;
374     int nr=0;
375     while(1) {
376 	U8 b = swf_GetU8(tag);
377         nr++;
378 	nt i,m=t->len>10?10:t->len;
379                 for(i=0;i<m;i++) {
380                             fprintf(stderr, "%02x ", t->data[i]);
381                                     }
382                         fprintf(stderr, "\n");
383                         s|=(b&127)<<shift;
384 	shift+=7;
385 	if(!(b&128) || shift>=32) {
386             if(b&64) {
387                 if(shift<32)
388                   s|=0xffffffff<<shift;
389             }
390 	    break;
391         }
392     }
393     /* It's not uncommon for other applications (Flex for all negative numbers, and
394        Flash for -1) to generate a lot more bytes than would be necessary.
395        int nr2= swf_SetS30(0, s);
396     if(nr!=nr2) {
397       printf("Signed value %d stored in %d bytes, I'd store it in %d bytes\n", s, nr, nr2);
398     }*/
399     return s;
400 }
401 #endif
402 
swf_SetU30String(TAG * tag,const char * str,int l)403 int swf_SetU30String(TAG*tag, const char*str, int l)
404 {
405     int len=0;
406     len+=swf_SetU30(tag, l);
407     len+=l;
408     swf_SetBlock(tag, (void*)str, l);
409     return len;
410 }
411 
swf_GetF16(TAG * t)412 float swf_GetF16(TAG * t)
413 {
414     U16 f1 = swf_GetU16(t);
415     if(!(f1&0x3ff)) return 0.0;
416 
417     // IEEE 16 is 1-5-10
418     // IEEE 32 is 1-8-23
419     /* gcc 4.1.2 seems to require a union here. *(float*)u doesn't work */
420     union {
421       U32 u;
422       float f;
423     } f2;
424 
425     U16 e = (f1>>10)&0x1f;
426     U16 m = f1&0x3ff;
427     /* find highest bit in mantissa */
428     int h=0;
429     while(!(m&0x400)) {
430 	m<<=1;
431 	h++;
432     }
433     m&=0x3ff;
434     e -= h;
435     e += 0x6f;
436 
437     f2.u = (f1&0x8000)<<16; //sign
438     f2.u |= e<<23; //exponent
439     f2.u |= m<<13; //mantissa
440     return *(float*)&f2;
441 }
442 
swf_SetF16(TAG * t,float f)443 void swf_SetF16(TAG * t, float f)
444 {
445     union {
446       U32 u;
447       float f;
448     } v;
449     v.f = f;
450 
451     U16 result = (v.u>>16)&0x8000; //sign
452     int exp = ((v.u>>23)&0xff)-0x7f+0x10;
453     U16 m = (v.u>>13)&0x3ff;
454     //fprintf(stderr, "%f: %04x sign, %d exp, %04x mantissa\n", f, result, exp, m);
455     if(exp<-10) {
456 	// underflow (clamp to 0.0)
457 	exp = 0;
458 	m = 0;
459     } else if(exp<0) {
460         // partial underflow- strip some bits
461 	m = (m|0x400)>>-exp;
462 	exp = 0;
463     } else if(exp>=32) {
464 	exp = 31;
465 	m = 0x3ff;
466 	fprintf(stderr, "Exponent overflow in FLOAT16 encoding\n");
467     } else {
468 	exp++;
469 	m = (m>>1)|0x200;
470     }
471     result |= exp<<10;
472     result |= m;
473     swf_SetU16(t, result);
474 }
475 
F16toFloat(U16 x)476 float F16toFloat(U16 x)
477 {
478     TAG t;
479     t.data = (void*)&x;
480     t.readBit = 0;
481     t.pos = 0;
482     t.len = 2;
483     return swf_GetF16(&t);
484 }
485 
floatToF16(float f)486 float floatToF16(float f)
487 {
488     U16 u = 0;
489     TAG t;
490     t.data = (void*)&u;
491     t.len = 0;
492     t.memsize = 2;
493     t.writeBit = 0;
494     swf_SetF16(&t, f);
495     return u;
496 }
497 
swf_GetD64(TAG * tag)498 double swf_GetD64(TAG*tag)
499 {
500     /* FIXME: this is not big-endian compatible */
501     double value = *(double*)&tag->data[tag->pos];
502     swf_GetU32(tag);
503     swf_GetU32(tag);
504     return value;
505 }
swf_SetD64(TAG * tag,double v)506 int swf_SetD64(TAG*tag, double v)
507 {
508     /* FIXME: this is not big-endian compatible */
509     swf_SetU32(tag, ((U32*)&v)[0]);
510     swf_SetU32(tag, ((U32*)&v)[1]);
511     return 8;
512 }
swf_GetU24(TAG * tag)513 int swf_GetU24(TAG*tag)
514 {
515     int b1 = swf_GetU8(tag);
516     int b2 = swf_GetU8(tag);
517     int b3 = swf_GetU8(tag);
518     return b3<<16|b2<<8|b1;
519 }
swf_GetS24(TAG * tag)520 int swf_GetS24(TAG*tag)
521 {
522     int b1 = swf_GetU8(tag);
523     int b2 = swf_GetU8(tag);
524     int b3 = swf_GetU8(tag);
525     if(b3&0x80) {
526         return -1-((b3<<16|b2<<8|b1)^0xffffff);
527     } else {
528         return b3<<16|b2<<8|b1;
529     }
530 }
swf_SetU24(TAG * tag,U32 v)531 int swf_SetU24(TAG*tag, U32 v)
532 {
533     if(tag) {
534         if(v&0xff000000)
535           fprintf(stderr, "Error: Overflow in swf_SetU24()\n");
536         swf_SetU8(tag, v);
537         swf_SetU8(tag, v>>8);
538         swf_SetU8(tag, v>>16);
539     }
540     return 3;
541 }
swf_SetS24(TAG * tag,U32 v)542 int swf_SetS24(TAG*tag, U32 v)
543 {
544     if(tag) {
545         if(!(v&0xff000000))
546           return swf_SetU24(tag, v);
547         if((v&0xff000000)!=0xff000000) {
548           fprintf(stderr, "Error: Overflow in swf_SetS24()\n");
549         }
550         swf_SetU8(tag, v);
551         swf_SetU8(tag, v>>8);
552         swf_SetU8(tag, v>>16);
553     }
554     return 3;
555 }
556 
557 
swf_SetRGB(TAG * t,RGBA * col)558 int swf_SetRGB(TAG * t,RGBA * col)
559 { if (!t) return -1;
560   if (col)
561   { swf_SetU8(t,col->r);
562     swf_SetU8(t,col->g);
563     swf_SetU8(t,col->b);
564   } else swf_SetBlock(t,NULL,3);
565   return 0;
566 }
swf_GetRGB(TAG * t,RGBA * col)567 void swf_GetRGB(TAG * t, RGBA * col)
568 {
569     RGBA dummy;
570     if(!col)
571 	col = &dummy;
572     col->r = swf_GetU8(t);
573     col->g = swf_GetU8(t);
574     col->b = swf_GetU8(t);
575     col->a = 255;
576 }
577 
swf_SetRGBA(TAG * t,RGBA * col)578 int swf_SetRGBA(TAG * t,RGBA * col)
579 { if (!t) return -1;
580   if (col)
581   { swf_SetU8(t,col->r);
582     swf_SetU8(t,col->g);
583     swf_SetU8(t,col->b);
584     swf_SetU8(t,col->a);
585   } else swf_SetBlock(t,NULL,4);
586   return 0;
587 }
swf_GetRGBA(TAG * t,RGBA * col)588 void swf_GetRGBA(TAG * t, RGBA * col)
589 {
590     RGBA dummy;
591     if(!col)
592 	col = &dummy;
593     col->r = swf_GetU8(t);
594     col->g = swf_GetU8(t);
595     col->b = swf_GetU8(t);
596     col->a = swf_GetU8(t);
597 }
598 
swf_GetGradient(TAG * tag,GRADIENT * gradient,char alpha)599 void swf_GetGradient(TAG * tag, GRADIENT * gradient, char alpha)
600 {
601     int t;
602     if(!tag) {
603       memset(gradient, 0, sizeof(GRADIENT));
604       return;
605     }
606     U8 num = swf_GetU8(tag) & 15;
607     if(gradient) {
608 	gradient->num = num;
609 	gradient->rgba = (RGBA*)rfx_calloc(sizeof(RGBA)*gradient->num);
610 	gradient->ratios = (U8*)rfx_calloc(sizeof(gradient->ratios[0])*gradient->num);
611     }
612     for(t=0;t<num;t++)
613     {
614 	U8 ratio = swf_GetU8(tag);
615 	RGBA color;
616 	if(!alpha)
617 	    swf_GetRGB(tag, &color);
618 	else
619 	    swf_GetRGBA(tag, &color);
620 	if(gradient) {
621 	  gradient->ratios[t] = ratio;
622 	  gradient->rgba[t] = color;
623 	}
624     }
625 }
626 
swf_SetGradient(TAG * tag,GRADIENT * gradient,char alpha)627 void swf_SetGradient(TAG * tag, GRADIENT * gradient, char alpha)
628 {
629     int t;
630     if(!tag) {
631       memset(gradient, 0, sizeof(GRADIENT));
632       return;
633     }
634     swf_SetU8(tag, gradient->num);
635     for(t=0; t<8 && t<gradient->num; t++)
636     {
637 	swf_SetU8(tag, gradient->ratios[t]);
638 	if(!alpha)
639 	    swf_SetRGB(tag, &gradient->rgba[t]);
640 	else
641 	    swf_SetRGBA(tag, &gradient->rgba[t]);
642     }
643 }
644 
swf_FreeGradient(GRADIENT * gradient)645 void swf_FreeGradient(GRADIENT* gradient)
646 {
647   if(gradient->ratios)
648     rfx_free(gradient->ratios);
649   if(gradient->rgba)
650     rfx_free(gradient->rgba);
651   memset(gradient, 0, sizeof(GRADIENT));
652 }
653 
swf_CountUBits(U32 v,int nbits)654 int swf_CountUBits(U32 v,int nbits)
655 { int n = 32;
656   U32 m = 0x80000000;
657   if(v == 0x00000000) n = 0;
658   else
659     while (!(v&m))
660     { n--;
661       m>>=1;
662     }
663   return (n>nbits)?n:nbits;
664 }
665 
swf_CountBits(U32 v,int nbits)666 int swf_CountBits(U32 v,int nbits)
667 { int n = 33;
668   U32 m = 0x80000000;
669   if (v&m)
670   { if(v == 0xffffffff) n = 1;
671     else
672     while (v&m)
673     { n--;
674       m>>=1;
675     }
676   }
677   else
678   { if(v == 0x00000000) n = 0;
679     else
680     while (!(v&m))
681     { n--;
682       m>>=1;
683     }
684   }
685   return (n>nbits)?n:nbits;
686 }
687 
swf_GetRect(TAG * t,SRECT * r)688 int swf_GetRect(TAG * t,SRECT * r)
689 { int nbits;
690   SRECT dummy;
691   if(!t) {r->xmin=r->xmax=r->ymin=r->ymax=0;return 0;}
692   if (!r) r = &dummy;
693   nbits = (int) swf_GetBits(t,5);
694   r->xmin = swf_GetSBits(t,nbits);
695   r->xmax = swf_GetSBits(t,nbits);
696   r->ymin = swf_GetSBits(t,nbits);
697   r->ymax = swf_GetSBits(t,nbits);
698   return 0;
699 }
700 
reader_GetRect(reader_t * reader,SRECT * r)701 int reader_GetRect(reader_t*reader,SRECT * r)
702 { int nbits;
703   SRECT dummy;
704   if (!r) r = &dummy;
705   nbits = (int) reader_GetBits(reader,5);
706   r->xmin = reader_GetSBits(reader,nbits);
707   r->xmax = reader_GetSBits(reader,nbits);
708   r->ymin = reader_GetSBits(reader,nbits);
709   r->ymax = reader_GetSBits(reader,nbits);
710   return 0;
711 }
712 
swf_SetRect(TAG * t,SRECT * r)713 int swf_SetRect(TAG * t,SRECT * r)
714 { int nbits;
715 
716   nbits = swf_CountBits(r->xmin,0);
717   nbits = swf_CountBits(r->xmax,nbits);
718   nbits = swf_CountBits(r->ymin,nbits);
719   nbits = swf_CountBits(r->ymax,nbits);
720   if(nbits>=32) {
721     #ifdef DEBUG_RFXSWF
722     fprintf(stderr, "rfxswf: Warning: num_bits overflow in swf_SetRect\n");
723     #endif
724     nbits=31;
725   }
726 
727   swf_SetBits(t,nbits,5);
728   swf_SetBits(t,r->xmin,nbits);
729   swf_SetBits(t,r->xmax,nbits);
730   swf_SetBits(t,r->ymin,nbits);
731   swf_SetBits(t,r->ymax,nbits);
732 
733   return 0;
734 }
735 
swf_ClipRect(SRECT border,SRECT r)736 SRECT swf_ClipRect(SRECT border, SRECT r)
737 {
738     if(r.xmax > border.xmax) r.xmax = border.xmax;
739     if(r.ymax > border.ymax) r.ymax = border.ymax;
740     if(r.xmax < border.xmin) r.xmax = border.xmin;
741     if(r.ymax < border.ymin) r.ymax = border.ymin;
742 
743     if(r.xmin > border.xmax) r.xmin = border.xmax;
744     if(r.ymin > border.ymax) r.ymin = border.ymax;
745     if(r.xmin < border.xmin) r.xmin = border.xmin;
746     if(r.ymin < border.ymin) r.ymin = border.ymin;
747     return r;
748 }
749 
swf_ExpandRect(SRECT * src,SPOINT add)750 void swf_ExpandRect(SRECT*src, SPOINT add)
751 {
752     if((src->xmin | src->ymin | src->xmax | src->ymax)==0) {
753 	src->xmin = add.x;
754 	src->ymin = add.y;
755 	src->xmax = add.x;
756 	src->ymax = add.y;
757 	if((add.x|add.y) == 0) src->xmax++; //make sure the bbox is not NULL anymore
758 	return;
759     }
760     if(add.x < src->xmin)
761 	src->xmin = add.x;
762     if(add.x > src->xmax)
763 	src->xmax = add.x;
764     if(add.y < src->ymin)
765 	src->ymin = add.y;
766     if(add.y > src->ymax)
767 	src->ymax = add.y;
768 }
swf_ExpandRect2(SRECT * src,SRECT * add)769 void swf_ExpandRect2(SRECT*src, SRECT*add)
770 {
771     if((add->xmin | add->ymin | add->xmax | add->ymax)==0)
772 	return;
773     if((src->xmin | src->ymin | src->xmax | src->ymax)==0)
774 	*src = *add;
775     if(add->xmin < src->xmin)
776 	src->xmin = add->xmin;
777     if(add->ymin < src->ymin)
778 	src->ymin = add->ymin;
779     if(add->xmax > src->xmax)
780 	src->xmax = add->xmax;
781     if(add->ymax > src->ymax)
782 	src->ymax = add->ymax;
783 }
swf_ExpandRect3(SRECT * src,SPOINT center,int radius)784 void swf_ExpandRect3(SRECT*src, SPOINT center, int radius)
785 {
786     if((src->xmin | src->ymin | src->xmax | src->ymax)==0) {
787 	src->xmin = center.x-radius;
788 	src->ymin = center.y-radius;
789 	src->xmax = center.x+radius;
790 	src->ymax = center.y+radius;
791 	if((center.x|center.y|radius) == 0) src->xmax++; //make sure the bbox is not NULL anymore
792 	return;
793     }
794     if(center.x - radius < src->xmin)
795 	src->xmin = center.x - radius;
796     if(center.x + radius > src->xmax)
797 	src->xmax = center.x + radius;
798     if(center.y - radius < src->ymin)
799 	src->ymin = center.y - radius;
800     if(center.y + radius > src->ymax)
801 	src->ymax = center.y + radius;
802 }
swf_TurnPoint(SPOINT p,MATRIX * m)803 SPOINT swf_TurnPoint(SPOINT p, MATRIX* m)
804 {
805     SPOINT r;
806     r.x = (int)(m->sx*(1/65536.0)*p.x + m->r1*(1/65536.0)*p.y + 0.5) + m->tx;
807     r.y = (int)(m->r0*(1/65536.0)*p.x + m->sy*(1/65536.0)*p.y + 0.5) + m->ty;
808     return r;
809 }
swf_TurnRect(SRECT r,MATRIX * m)810 SRECT swf_TurnRect(SRECT r, MATRIX* m)
811 {
812     SRECT g;
813     SPOINT p1,p2,p3,p4,pp1,pp2,pp3,pp4;
814     if(!m)
815       return r;
816     p1.x = r.xmin;p1.y = r.ymin;
817     p2.x = r.xmax;p2.y = r.ymin;
818     p3.x = r.xmin;p3.y = r.ymax;
819     p4.x = r.xmax;p4.y = r.ymax;
820     pp1 = swf_TurnPoint(p1, m);
821     pp2 = swf_TurnPoint(p2, m);
822     pp3 = swf_TurnPoint(p3, m);
823     pp4 = swf_TurnPoint(p4, m);
824     g.xmin = g.xmax = pp1.x;
825     g.ymin = g.ymax = pp1.y;
826     swf_ExpandRect(&g, pp2);
827     swf_ExpandRect(&g, pp3);
828     swf_ExpandRect(&g, pp4);
829     return g;
830 }
831 
832 
swf_GetMatrix(TAG * t,MATRIX * m)833 int swf_GetMatrix(TAG * t,MATRIX * m)
834 { MATRIX dummy;
835   int nbits;
836 
837   if (!m) m = &dummy;
838 
839   if (!t)
840   { m->sx = m->sy = 0x10000;
841     m->r0 = m->r1 = 0;
842     m->tx = m->ty = 0;
843     return -1;
844   }
845 
846   swf_ResetReadBits(t);
847 
848   if (swf_GetBits(t,1))
849   { nbits = swf_GetBits(t,5);
850     m->sx = swf_GetSBits(t,nbits);
851     m->sy = swf_GetSBits(t,nbits);
852   }
853   else m->sx = m->sy = 0x10000;
854 
855   if (swf_GetBits(t,1))
856   { nbits = swf_GetBits(t,5);
857     m->r0 = swf_GetSBits(t,nbits);
858     m->r1 = swf_GetSBits(t,nbits);
859   }
860   else m->r0 = m->r1 = 0x0;
861 
862   nbits = swf_GetBits(t,5);
863   m->tx = swf_GetSBits(t,nbits);
864   m->ty = swf_GetSBits(t,nbits);
865 
866   return 0;
867 }
868 
swf_SetMatrix(TAG * t,MATRIX * m)869 int swf_SetMatrix(TAG * t,MATRIX * m)
870 { int nbits;
871   MATRIX ma;
872 
873   if (!m)
874   { m = &ma;
875     ma.sx = ma.sy = 0x10000;
876     ma.r0 = ma.r1 = 0;
877     ma.tx = ma.ty = 0;
878   }
879 
880   swf_ResetWriteBits(t);
881 
882   if ((m->sx==0x10000)&&(m->sy==0x10000)) swf_SetBits(t,0,1);
883   else
884   { swf_SetBits(t,1,1);
885     nbits = swf_CountBits(m->sx,0);
886     nbits = swf_CountBits(m->sy,nbits);
887     if(nbits>=32) {
888         /* TODO: happens on AMD64 systems for normal values? */
889         #ifdef DEBUG_RFXSWF
890 	fprintf(stderr,"rfxswf: Error: matrix values too large\n");
891         #endif
892 	nbits = 31;
893     }
894     swf_SetBits(t,nbits,5);
895     swf_SetBits(t,m->sx,nbits);
896     swf_SetBits(t,m->sy,nbits);
897   }
898 
899   if ((!m->r0)&&(!m->r1)) swf_SetBits(t,0,1);
900   else
901   { swf_SetBits(t,1,1);
902     nbits = swf_CountBits(m->r0,0);
903     nbits = swf_CountBits(m->r1,nbits);
904     if(nbits>=32) {
905         #ifdef DEBUG_RFXSWF
906 	fprintf(stderr,"rfxswf: Error: matrix values too large\n");
907         #endif
908 	nbits = 31;
909     }
910     swf_SetBits(t,nbits,5);
911     swf_SetBits(t,m->r0,nbits);
912     swf_SetBits(t,m->r1,nbits);
913   }
914 
915   nbits = swf_CountBits(m->tx,0);
916   nbits = swf_CountBits(m->ty,nbits);
917   if(nbits>=32) {
918       #ifdef DEBUG_RFXSWF
919       fprintf(stderr,"rfxswf: Error: matrix values too large\n");
920       #endif
921       nbits = 31;
922   }
923   swf_SetBits(t,nbits,5);
924   swf_SetBits(t,m->tx,nbits);
925   swf_SetBits(t,m->ty,nbits);
926 
927   return 0;
928 }
929 
swf_GetCXForm(TAG * t,CXFORM * cx,U8 alpha)930 int swf_GetCXForm(TAG * t,CXFORM * cx,U8 alpha)
931 { CXFORM cxf;
932   int hasadd;
933   int hasmul;
934   int nbits;
935 
936   if (!cx) cx = &cxf;
937 
938   cx->a0 = cx->r0 = cx->g0 = cx->b0 = 256;
939   cx->a1 = cx->r1 = cx->g1 = cx->b1 = 0;
940 
941   if (!t) return 0;
942 
943   swf_ResetReadBits(t);
944   hasadd = swf_GetBits(t,1);
945   hasmul = swf_GetBits(t,1);
946   nbits  = swf_GetBits(t,4);
947 
948   if (hasmul)
949   { cx->r0 = (S16)swf_GetSBits(t,nbits);
950     cx->g0 = (S16)swf_GetSBits(t,nbits);
951     cx->b0 = (S16)swf_GetSBits(t,nbits);
952     if (alpha)
953       cx->a0 = (S16)swf_GetSBits(t,nbits);
954   }
955 
956   if (hasadd)
957   { cx->r1 = (S16)swf_GetSBits(t,nbits);
958     cx->g1 = (S16)swf_GetSBits(t,nbits);
959     cx->b1 = (S16)swf_GetSBits(t,nbits);
960     if (alpha)
961       cx->a1 = (S16)swf_GetSBits(t,nbits);
962   }
963 
964   return 0;
965 }
966 
swf_SetCXForm(TAG * t,CXFORM * cx,U8 alpha)967 int swf_SetCXForm(TAG * t,CXFORM * cx,U8 alpha)
968 { CXFORM cxf;
969   int hasadd;
970   int hasmul;
971   int nbits;
972 
973   if (!cx)
974   { cx = &cxf;
975     cx->a0 = cx->r0 = cx->g0 = cx->b0 = 256;
976     cx->a1 = cx->r1 = cx->g1 = cx->b1 = 0;
977   }
978 
979   if (!alpha)
980   { cx->a0 = 256;
981     cx->a1 = 0;
982   }
983 
984   nbits = 0;
985 
986   hasmul = (cx->a0!=256)||(cx->r0!=256)||(cx->g0!=256)||(cx->b0!=256);
987   hasadd = cx->a1|cx->r1|cx->g1|cx->b1;
988 
989   if (hasmul)
990   { if (alpha) nbits = swf_CountBits((S32)cx->a0,nbits);
991     nbits = swf_CountBits((S32)cx->r0,nbits);
992     nbits = swf_CountBits((S32)cx->g0,nbits);
993     nbits = swf_CountBits((S32)cx->b0,nbits);
994   }
995 
996   if (hasadd)
997   { if (alpha) nbits = swf_CountBits((S32)cx->a1,nbits);
998     nbits = swf_CountBits((S32)cx->r1,nbits);
999     nbits = swf_CountBits((S32)cx->g1,nbits);
1000     nbits = swf_CountBits((S32)cx->b1,nbits);
1001   }
1002 
1003   swf_ResetWriteBits(t);
1004   swf_SetBits(t,hasadd?1:0,1);
1005   swf_SetBits(t,hasmul?1:0,1);
1006   swf_SetBits(t,nbits,4);
1007 
1008   if (hasmul)
1009   { swf_SetBits(t,cx->r0,nbits);
1010     swf_SetBits(t,cx->g0,nbits);
1011     swf_SetBits(t,cx->b0,nbits);
1012     if (alpha) swf_SetBits(t,cx->a0,nbits);
1013   }
1014 
1015   if (hasadd)
1016   { swf_SetBits(t,cx->r1,nbits);
1017     swf_SetBits(t,cx->g1,nbits);
1018     swf_SetBits(t,cx->b1,nbits);
1019     if (alpha) swf_SetBits(t,cx->a1,nbits);
1020   }
1021 
1022   return 0;
1023 }
1024 
1025 //int swf_GetPoint(TAG * t,SPOINT * p) { return 0; }
1026 //int swf_SetPoint(TAG * t,SPOINT * p) { return 0; }
1027 
swf_SetPassword(TAG * t,const char * password)1028 void  swf_SetPassword(TAG * t, const char * password)
1029 {
1030 #ifdef HAVE_MD5
1031     /* WARNING: crypt_md5 is not reentrant */
1032     char salt[3];
1033     char* md5string;
1034 
1035 #if defined(HAVE_LRAND48) && defined(HAVE_SRAND48) && defined(HAVE_TIME_H) && defined(HAVE_TIME)
1036     srand48(time(0));
1037     salt[0] = "abcdefghijklmnopqrstuvwxyz0123456789"[lrand48()%36];
1038     salt[1] = "abcdefghijklmnopqrstuvwxyz0123456789"[lrand48()%36];
1039 #else
1040     salt[0] = 'l';
1041     salt[1] = '8';
1042     fprintf(stderr, "rfxswf: Warning- no usable random generator found\n");
1043     fprintf(stderr, "Your password will be vulnerable to dictionary attacks\n");
1044 #endif
1045     salt[2] = 0;
1046 
1047     md5string = crypt_md5(password, salt);
1048 
1049     swf_SetU16(t,0);
1050     swf_SetString(t, md5string);
1051 #else
1052     fprintf(stderr, "Error: No MD5 compiled in");
1053 #endif
1054 }
1055 
swf_SetString(TAG * t,const char * s)1056 void swf_SetString(TAG*t, const char* s)
1057 {
1058     if(!s) {
1059         swf_SetU8(t, 0);
1060     } else {
1061         swf_SetBlock(t,(U8*)s,strlen(s)+1);
1062     }
1063 }
1064 
swf_VerifyPassword(TAG * t,const char * password)1065 int swf_VerifyPassword(TAG * t, const char * password)
1066 {
1067 #ifdef HAVE_MD5
1068     char*md5string1, *md5string2;
1069     char*x;
1070     char*salt;
1071     int n;
1072 
1073     if(t->len >= 5 && t->pos==0 &&
1074        t->data[0] == 0 &&
1075        t->data[1] == 0) {
1076       swf_GetU16(t);
1077     } else {
1078       printf("%d %d %d %d\n", t->len, t->pos, t->data[0], t->data[1]);
1079     }
1080 
1081     md5string1 = swf_GetString(t);
1082 
1083     if(strncmp(md5string1, "$1$",3 )) {
1084         fprintf(stderr, "rfxswf: no salt in pw string\n");
1085 	return 0;
1086     }
1087     x = strchr(md5string1+3, '$');
1088     if(!x) {
1089         fprintf(stderr, "rfxswf: invalid salt format in pw string\n");
1090 	return 0;
1091     }
1092     n = x-(md5string1+3);
1093     salt = (char*)rfx_alloc(n+1);
1094     memcpy(salt, md5string1+3, n);
1095     salt[n] = 0;
1096 
1097     md5string2 = crypt_md5(password, salt);
1098     rfx_free(salt);
1099     if(strcmp(md5string1, md5string2) != 0)
1100 	return 0;
1101     return 1;
1102 #else
1103     fprintf(stderr, "Error: No MD5 compiled in");
1104     return 1;
1105 #endif
1106 }
1107 
1108 // Tag List Manipulating Functions
1109 
swf_InsertTag(TAG * after,U16 id)1110 TAG * swf_InsertTag(TAG * after,U16 id)
1111 { TAG * t;
1112 
1113   t = (TAG *)rfx_calloc(sizeof(TAG));
1114   t->id = id;
1115 
1116   if (after)
1117   {
1118     t->prev  = after;
1119     t->next  = after->next;
1120     after->next = t;
1121     if (t->next) t->next->prev = t;
1122   }
1123   return t;
1124 }
1125 
swf_InsertTagBefore(SWF * swf,TAG * before,U16 id)1126 TAG * swf_InsertTagBefore(SWF* swf, TAG * before,U16 id)
1127 { TAG * t;
1128 
1129   t = (TAG *)rfx_calloc(sizeof(TAG));
1130   t->id = id;
1131 
1132   if (before)
1133   {
1134     t->next  = before;
1135     t->prev  = before->prev;
1136     before->prev = t;
1137     if (t->prev) t->prev->next = t;
1138   }
1139   if(swf && swf->firstTag == before) {
1140     swf->firstTag = t;
1141   }
1142   return t;
1143 }
1144 
swf_ClearTag(TAG * t)1145 void swf_ClearTag(TAG * t)
1146 {
1147   if (t->data) rfx_free(t->data);
1148   t->data = 0;
1149   t->pos = 0;
1150   t->len = 0;
1151   t->readBit = 0;
1152   t->writeBit = 0;
1153   t->memsize = 0;
1154 }
1155 
swf_ResetTag(TAG * tag,U16 id)1156 void swf_ResetTag(TAG*tag, U16 id)
1157 {
1158     tag->len = tag->pos = tag->readBit = tag->writeBit = 0;
1159     tag->id = id;
1160 }
1161 
swf_CopyTag(TAG * tag,TAG * to_copy)1162 TAG* swf_CopyTag(TAG*tag, TAG*to_copy)
1163 {
1164     tag = swf_InsertTag(tag, to_copy->id);
1165     swf_SetBlock(tag, to_copy->data, to_copy->len);
1166     return tag;
1167 }
1168 
swf_DeleteTag(SWF * swf,TAG * t)1169 TAG* swf_DeleteTag(SWF*swf, TAG * t)
1170 {
1171   TAG*next = t->next;
1172 
1173   if (swf && swf->firstTag==t)
1174     swf->firstTag = t->next;
1175   if (t->prev) t->prev->next = t->next;
1176   if (t->next) t->next->prev = t->prev;
1177 
1178   if (t->data) rfx_free(t->data);
1179   rfx_free(t);
1180   return next;
1181 }
1182 
swf_ReadTag(reader_t * reader,TAG * prev)1183 TAG * swf_ReadTag(reader_t*reader, TAG * prev)
1184 { TAG * t;
1185   U16 raw;
1186   U32 len;
1187   int id;
1188 
1189   if (reader->read(reader, &raw, 2) !=2 ) return NULL;
1190   raw = LE_16_TO_NATIVE(raw);
1191 
1192   len = raw&0x3f;
1193   id  = raw>>6;
1194 
1195   if (len==0x3f)
1196   {
1197       len = reader_readU32(reader);
1198   }
1199 
1200   if (id==ST_DEFINESPRITE) len = 2*sizeof(U16);
1201   // Sprite handling fix: Flatten sprite tree
1202 
1203   t = (TAG *)rfx_calloc(sizeof(TAG));
1204 
1205   t->len = len;
1206   t->id  = id;
1207 
1208   if (t->len)
1209   { t->data = (U8*)rfx_alloc(t->len);
1210     t->memsize = t->len;
1211     if (reader->read(reader, t->data, t->len) != t->len) {
1212       #ifdef DEBUG_RFXSWF
1213       fprintf(stderr, "rfxswf: Warning: Short read (tagid %d). File truncated?\n", t->id);
1214       #endif
1215       free(t->data);t->data=0;
1216       free(t);
1217       return NULL;
1218     }
1219   }
1220 
1221   if (prev)
1222   {
1223     t->prev  = prev;
1224     prev->next = t;
1225   }
1226 
1227   return t;
1228 }
1229 
1230 int swf_DefineSprite_GetRealSize(TAG * t);
1231 
swf_WriteTag2(writer_t * writer,TAG * t)1232 int swf_WriteTag2(writer_t*writer, TAG * t)
1233 // returns tag length in bytes (incl. Header), -1 = Error
1234 // writer = 0 -> no output
1235 { U16 raw[3];
1236   U32 len;
1237   int short_tag;
1238 
1239   if (!t) return -1;
1240 
1241   len = (t->id==ST_DEFINESPRITE)?swf_DefineSprite_GetRealSize(t):t->len;
1242 
1243   short_tag = len<0x3f&&
1244     (t->id!=ST_DEFINEBITSLOSSLESS&&t->id!=ST_DEFINEBITSLOSSLESS2&&t->id!=ST_SOUNDSTREAMBLOCK&&
1245      t->id!=ST_DEFINEBITSJPEG&&t->id!=ST_DEFINEBITSJPEG2&&t->id!=ST_DEFINEBITSJPEG3);
1246 
1247   if (writer)
1248   {
1249 #ifdef MEASURE
1250   int oldpos = writer->pos;
1251 #endif
1252 
1253     if (short_tag)
1254     { raw[0] = LE_16_TO_NATIVE(len|((t->id&0x3ff)<<6));
1255       if (writer->write(writer,raw,2)!=2)
1256       {
1257         #ifdef DEBUG_RFXSWF
1258           fprintf(stderr,"WriteTag() failed: Short Header.\n");
1259         #endif
1260         return -1;
1261       }
1262     }
1263     else
1264     {
1265       raw[0] = LE_16_TO_NATIVE((t->id<<6)|0x3f);
1266       if (writer->write(writer,raw,2)!=2)
1267       {
1268 #ifdef DEBUG_RFXSWF
1269           fprintf(stderr,"WriteTag() failed: Long Header (1).\n");
1270 #endif
1271 	  return -1;
1272       }
1273 
1274       writer_writeU32(writer, len);
1275     }
1276 
1277     if (t->data)
1278     { if (writer->write(writer,t->data,t->len)!=t->len)
1279       {
1280         #ifdef DEBUG_RFXSWF
1281           fprintf(stderr,"WriteTag() failed: Data.\n");
1282         #endif
1283         return -1;
1284       }
1285     }
1286     #ifdef DEBUG_RFXSWF
1287       else if (t->len) fprintf(stderr,"WriteTag(): Tag Data Error, id=%i\n",t->id);
1288     #endif
1289 
1290 #ifdef MEASURE
1291   writer->flush(writer);
1292   printf("TAG %s costs %d bytes\n", swf_TagGetName(t), writer->pos-oldpos);
1293 #endif
1294   }
1295 
1296   return t->len+(short_tag?2:6);
1297 }
1298 
swf_WriteTag(int handle,TAG * t)1299 int swf_WriteTag(int handle, TAG * t)
1300 {
1301   writer_t writer;
1302   int len = 0;
1303   if(handle<0)
1304     return swf_WriteTag2(0, t);
1305   writer_init_filewriter(&writer, handle);
1306   len = swf_WriteTag2(&writer, t);
1307   writer.finish(&writer);
1308   return len;
1309 }
1310 
swf_DefineSprite_GetRealSize(TAG * t)1311 int swf_DefineSprite_GetRealSize(TAG * t)
1312 // Sprite Handling: Helper function to pack DefineSprite-Tag
1313 { U32 len = t->len;
1314   if(len>4) { // folded sprite
1315       return t->len;
1316   }
1317   do
1318   { t = swf_NextTag(t);
1319     if (t && t->id!=ST_DEFINESPRITE) len += swf_WriteTag(-1, t);
1320     else t = NULL;
1321   } while (t&&(t->id!=ST_END));
1322   return len;
1323 }
1324 
swf_UnFoldSprite(TAG * t)1325 void swf_UnFoldSprite(TAG * t)
1326 {
1327   U16 id,tmp;
1328   U32 len;
1329   TAG*next = t;
1330   U16 spriteid,spriteframes;
1331   int level;
1332   if(t->id!=ST_DEFINESPRITE)
1333     return;
1334   if(t->len<=4) // not folded
1335     return;
1336 
1337   swf_SetTagPos(t,0);
1338 
1339   spriteid = swf_GetU16(t); //id
1340   spriteframes = swf_GetU16(t); //frames
1341 
1342   level = 1;
1343 
1344   while(1)
1345   {
1346     TAG*it = 0;
1347     tmp = swf_GetU16(t);
1348     len = tmp&0x3f;
1349     id  = tmp>>6;
1350     if(id == ST_END)
1351 	level--;
1352     if(id == ST_DEFINESPRITE && len<=4)
1353 	level++;
1354 
1355     if (len==0x3f)
1356 	len = swf_GetU32(t);
1357     it = swf_InsertTag(next, id);
1358     next = it;
1359     it->len = len;
1360     it->id  = id;
1361     if (it->len)
1362     { it->data = (U8*)rfx_alloc(it->len);
1363       it->memsize = it->len;
1364       swf_GetBlock(t, it->data, it->len);
1365     }
1366 
1367     if(!level)
1368 	break;
1369   }
1370 
1371   rfx_free(t->data); t->data = 0;
1372   t->memsize = t->len = t->pos = 0;
1373 
1374   swf_SetU16(t, spriteid);
1375   swf_SetU16(t, spriteframes);
1376 }
1377 
swf_FoldSprite(TAG * t)1378 void swf_FoldSprite(TAG * t)
1379 {
1380   TAG*sprtag=t,*tmp;
1381   U16 id,frames;
1382   int level;
1383   if(t->id!=ST_DEFINESPRITE)
1384       return;
1385   if(!t->len) {
1386     #ifdef DEBUG_RFXSWF
1387       fprintf(stderr, "Error: Sprite has no ID!");
1388     #endif
1389       return;
1390   }
1391   if(t->len>4) {
1392     /* sprite is already folded */
1393       return;
1394   }
1395 
1396   t->pos = 0;
1397   id = swf_GetU16(t);
1398   rfx_free(t->data);
1399   t->len = t->pos = t->memsize = 0;
1400   t->data = 0;
1401 
1402   frames = 0;
1403 
1404   t = swf_NextTag(sprtag);
1405   level = 1;
1406 
1407   do
1408   {
1409     if(t->id==ST_SHOWFRAME) frames++;
1410     if(t->id == ST_DEFINESPRITE && t->len<=4)
1411 	level++;
1412     if(t->id == ST_END)
1413 	level--;
1414     t = swf_NextTag(t);
1415   } while(t && level);
1416   if(level)
1417     fprintf(stderr, "rfxswf error: sprite doesn't end(1)\n");
1418 
1419   swf_SetU16(sprtag, id);
1420   swf_SetU16(sprtag, frames);
1421 
1422   t = swf_NextTag(sprtag);
1423   level = 1;
1424 
1425   do
1426   {
1427     if(t->len<0x3f&&
1428 	(t->id!=ST_DEFINEBITSLOSSLESS&&t->id!=ST_DEFINEBITSLOSSLESS2&&t->id!=ST_SOUNDSTREAMBLOCK&&
1429 	 t->id!=ST_DEFINEBITSJPEG&&t->id!=ST_DEFINEBITSJPEG2&&t->id!=ST_DEFINEBITSJPEG3)
1430       ) {
1431 	swf_SetU16(sprtag,t->len|(t->id<<6));
1432     } else {
1433 	swf_SetU16(sprtag,0x3f|(t->id<<6));
1434 	swf_SetU32(sprtag,t->len);
1435     }
1436     if(t->len)
1437 	swf_SetBlock(sprtag,t->data, t->len);
1438     tmp = t;
1439     if(t->id == ST_DEFINESPRITE && t->len<=4)
1440 	level++;
1441     if(t->id == ST_END)
1442 	level--;
1443     t = swf_NextTag(t);
1444     swf_DeleteTag(0, tmp);
1445   }
1446   while (t && level);
1447   if(level)
1448     fprintf(stderr, "rfxswf error: sprite doesn't end(2)\n");
1449 
1450 //  sprtag->next = t;
1451 //  t->prev = sprtag;
1452 }
1453 
swf_IsFolded(TAG * t)1454 int swf_IsFolded(TAG * t)
1455 {
1456     return (t->id == ST_DEFINESPRITE && t->len>4);
1457 }
1458 
swf_FoldAll(SWF * swf)1459 void swf_FoldAll(SWF*swf)
1460 {
1461     TAG*tag = swf->firstTag;
1462     //swf_DumpSWF(stdout, swf);
1463     while(tag) {
1464 	if(tag->id == ST_DEFINESPRITE) {
1465 	    swf_FoldSprite(tag);
1466 	    //swf_DumpSWF(stdout, swf);
1467 	}
1468 	tag = swf_NextTag(tag);
1469     }
1470 }
1471 
swf_UnFoldAll(SWF * swf)1472 void swf_UnFoldAll(SWF*swf)
1473 {
1474     TAG*tag = swf->firstTag;
1475     while(tag) {
1476 	if(tag->id == ST_DEFINESPRITE)
1477 	    swf_UnFoldSprite(tag);
1478 	tag = tag->next;
1479     }
1480 }
1481 
swf_OptimizeTagOrder(SWF * swf)1482 void swf_OptimizeTagOrder(SWF*swf)
1483 {
1484   TAG*tag,*next;
1485   TAG*level0;
1486   int level;
1487   int changes;
1488   swf_UnFoldAll(swf);
1489   /* at the moment, we don't actually do optimizing,
1490      only fixing of non-spec-conformant things like
1491      sprite tags */
1492 
1493   do {
1494     changes = 0;
1495     level = 0;
1496     level0 = 0;
1497     tag = swf->firstTag;
1498     while(tag) {
1499       next = tag->next;
1500       if(tag->id == ST_DEFINESPRITE) {
1501 	if(tag->len>4) {
1502 	  /* ??? all sprites are supposed to be unfolded */
1503 	  fprintf(stderr, "librfxswf error - internal error in OptimizeTagOrder/UnfoldAll\n");
1504 	}
1505 	level++;
1506 	if(level==1) {
1507 	  level0 = tag;
1508 	  tag = next;
1509 	  continue;
1510 	}
1511       }
1512       if(level>=1) {
1513 	/* move non-sprite tags out of sprite */
1514 	if(!swf_isAllowedSpriteTag(tag) || level>=2) {
1515 	  /* remove tag from current position */
1516 	  tag->prev->next = tag->next;
1517 	  if(tag->next)
1518 	    tag->next->prev = tag->prev;
1519 
1520 	  /* insert before tag level0 */
1521 	  tag->next = level0;
1522 	  tag->prev = level0->prev;
1523 	  level0->prev = tag;
1524           if(tag->prev)
1525 	    tag->prev->next = tag;
1526           else
1527             swf->firstTag = tag;
1528 	  changes = 1;
1529 	}
1530       }
1531       if(tag->id == ST_END) {
1532 	level--;
1533       }
1534 
1535       tag = next;
1536     }
1537   } while(changes);
1538 }
1539 
1540 // Movie Functions
1541 
swf_ReadSWF2(reader_t * reader,SWF * swf)1542 int swf_ReadSWF2(reader_t*reader, SWF * swf)   // Reads SWF to memory (malloc'ed), returns length or <0 if fails
1543 {
1544   if (!swf) return -1;
1545   memset(swf,0x00,sizeof(SWF));
1546 
1547   { char b[32];                         // read Header
1548     int len;
1549     TAG * t;
1550     TAG t1;
1551     reader_t zreader;
1552 
1553     if ((len = reader->read(reader ,b,8))<8) return -1;
1554 
1555     if (b[0]!='F' && b[0]!='C') return -1;
1556     if (b[1]!='W') return -1;
1557     if (b[2]!='S') return -1;
1558     swf->fileVersion = b[3];
1559     swf->compressed  = (b[0]=='C')?1:0;
1560     swf->fileSize    = GET32(&b[4]);
1561 
1562     if(swf->compressed) {
1563 	reader_init_zlibinflate(&zreader, reader);
1564 	reader = &zreader;
1565     }
1566     swf->compressed = 0; // derive from version number from now on
1567 
1568     reader_GetRect(reader, &swf->movieSize);
1569     reader->read(reader, &swf->frameRate, 2);
1570     swf->frameRate = LE_16_TO_NATIVE(swf->frameRate);
1571     reader->read(reader, &swf->frameCount, 2);
1572     swf->frameCount = LE_16_TO_NATIVE(swf->frameCount);
1573 
1574     /* read tags and connect to list */
1575     t1.next = 0;
1576     t = &t1;
1577     while (t) {
1578       t = swf_ReadTag(reader,t);
1579       if(t && t->id == ST_FILEATTRIBUTES) {
1580         swf->fileAttributes = swf_GetU32(t);
1581         swf_ResetReadBits(t);
1582       }
1583     }
1584     swf->firstTag = t1.next;
1585     if(t1.next)
1586       t1.next->prev = NULL;
1587   }
1588 
1589   return reader->pos;
1590 }
1591 
swf_OpenSWF(char * filename)1592 SWF* swf_OpenSWF(char*filename)
1593 {
1594   int fi = open(filename, O_RDONLY|O_BINARY);
1595   if(fi<0) {
1596       fprintf(stderr, "Failed to open %s\n", filename);
1597       return 0;
1598   }
1599   SWF* swf = rfx_alloc(sizeof(SWF));
1600   swf_ReadSWF(fi, swf);
1601   close(fi);
1602   return swf;
1603 }
1604 
swf_ReadSWF(int handle,SWF * swf)1605 int swf_ReadSWF(int handle, SWF * swf)
1606 {
1607   reader_t reader;
1608   reader_init_filereader(&reader, handle);
1609   return swf_ReadSWF2(&reader, swf);
1610 }
1611 
swf_ReadABCfile(char * filename,SWF * swf)1612 void swf_ReadABCfile(char*filename, SWF*swf)
1613 {
1614     memset(swf, 0, sizeof(SWF));
1615     swf->fileVersion=9;
1616     swf->fileAttributes=FILEATTRIBUTE_AS3; //as3
1617     TAG*tag = swf->firstTag = swf_InsertTag(0, ST_RAWABC);
1618     memfile_t*file = memfile_open(filename);
1619     swf_SetBlock(tag, file->data, file->len);
1620     memfile_close(file);
1621 }
1622 
1623 int no_extra_tags = 0;
1624 
WriteExtraTags(SWF * swf,writer_t * writer)1625 int WriteExtraTags(SWF*swf, writer_t*writer)
1626 {
1627     TAG*t = swf->firstTag;
1628     TAG* has_fileattributes=0;
1629     int has_scenedescription=0;
1630     int has_version_8_action=0;
1631     int has_version_9_action=0;
1632     int len = 0;
1633     while(t) {
1634         if(t->id == ST_FILEATTRIBUTES)
1635             has_fileattributes = t;
1636         if(t->id == ST_SCENEDESCRIPTION)
1637             has_scenedescription = 1;
1638         if(t->id == ST_DOABC)
1639             has_version_9_action=1;
1640         /* FIXME: this doesn't yet find actionscript in buttons */
1641         if(t->id == ST_DOACTION || t->id == ST_DOINITACTION)
1642             has_version_8_action=1;
1643         if(t->id == ST_PLACEOBJECT2 && t->len && (t->data[0]&0x80))
1644             has_version_8_action=1;
1645         t = t->next;
1646     }
1647     if(has_version_8_action && has_version_9_action) {
1648         fprintf(stderr, "Warning: File contains both flash 8 and flash 9 actionscript\n");
1649     }
1650 
1651     if(swf->fileVersion >= 9) {
1652         if(!has_fileattributes) {
1653             U32 flags = swf->fileAttributes|FILEATTRIBUTE_AS3; // 16 = has symbolclass tag | 8 = actionscript3 | 1 = usenetwork
1654             if(has_version_8_action && !has_version_9_action)
1655                 flags &= ~FILEATTRIBUTE_AS3;
1656             TAG*fileattrib = swf_InsertTag(0, ST_FILEATTRIBUTES);
1657             swf_SetU32(fileattrib, flags);
1658             if(writer) {
1659                 if(swf_WriteTag2(writer, fileattrib)<0)
1660                     return -1;
1661             } else {
1662                 len += swf_WriteTag(-1,fileattrib);
1663             }
1664             swf_DeleteTag(0, fileattrib);
1665         } else {
1666 	    if(swf->fileAttributes) {
1667 	      /* if we're writing a file out again where we might have possible
1668 		 modified the fileattributes in the header, adjust the tag data */
1669 	      TAG*tt = swf_CopyTag(0,has_fileattributes);
1670 	      U32 flags = swf_GetU32(tt) | swf->fileAttributes;
1671 	      swf_ResetTag(tt, tt->id);
1672 	      swf_SetU32(tt, flags);
1673 	      if(swf_WriteTag2(writer, has_fileattributes)<0) return -1;
1674 	      swf_DeleteTag(0, tt);
1675 	    } else {
1676 		if(swf_WriteTag2(writer, has_fileattributes)<0)
1677 		    return -1;
1678 	    }
1679         }
1680         if(0 && !has_scenedescription) {
1681             TAG*scene = swf_InsertTag(0, ST_SCENEDESCRIPTION);
1682             swf_SetU16(scene, 1);
1683             swf_SetString(scene, "Scene 1");
1684             swf_SetU8(scene, 0);
1685             if(writer) {
1686                 if(swf_WriteTag2(writer, scene)<0)
1687                     return -1;
1688             } else {
1689                 len += swf_WriteTag(-1,scene);
1690             }
1691             swf_DeleteTag(0, scene);
1692         }
1693     }
1694     return len;
1695 }
1696 
swf_WriteSWF2(writer_t * writer,SWF * swf)1697 int  swf_WriteSWF2(writer_t*writer, SWF * swf)     // Writes SWF to file, returns length or <0 if fails
1698 { U32 len;
1699   TAG * t;
1700   int frameCount=0;
1701   writer_t zwriter;
1702   int fileSize = 0;
1703   int inSprite = 0;
1704   int ret;
1705   writer_t*original_writer = writer;
1706   int writer_lastpos = 0;
1707 
1708   if (!swf) return -1;
1709   if (!writer) return -1; // the caller should provide a nullwriter, not 0, for querying SWF size
1710 
1711   if(original_writer) writer_lastpos = original_writer->pos;
1712 
1713   // Count Frames + File Size
1714 
1715   len = 0;
1716   t = swf->firstTag;
1717   frameCount = 0;
1718 
1719   if(swf->firstTag && !no_extra_tags) {
1720     len += WriteExtraTags(swf, 0);
1721   }
1722   while(t) {
1723       len += swf_WriteTag(-1,t);
1724       if(t->id == ST_DEFINESPRITE && !swf_IsFolded(t)) inSprite++;
1725       else if(t->id == ST_END && inSprite) inSprite--;
1726       else if(t->id == ST_END && !inSprite) {
1727 	if(t->prev && t->prev->id!=ST_SHOWFRAME)
1728 	  frameCount++;
1729       }
1730       else if(t->id == ST_SHOWFRAME && !inSprite) frameCount++;
1731       t = swf_NextTag(t);
1732   }
1733 
1734   { TAG t1;
1735     char b[64],b4[4];
1736     U32 l;
1737 
1738     memset(&t1,0x00,sizeof(TAG));
1739     t1.data    = (U8*)b;
1740     t1.memsize = 64;
1741 
1742     { // measure header file size
1743       TAG t2;
1744       char b2[64];
1745       memset(&t2,0x00,sizeof(TAG));
1746       t2.data    = (U8*)b2;
1747       t2.memsize = 64;
1748       swf_SetRect(&t2, &swf->movieSize);
1749       swf_SetU16(&t2, swf->frameRate);
1750       swf_SetU16(&t2, swf->frameCount);
1751       l = swf_GetTagLen(&t2)+8;
1752     }
1753     if(swf->compressed == 8) {
1754       l -= 8;
1755     }
1756 
1757     fileSize = l+len;
1758     if(len) {// don't touch headers without tags
1759 	swf->fileSize = fileSize;
1760 	swf->frameCount = frameCount;
1761     }
1762 
1763     if(swf->compressed != 8) {
1764     /* compressed flag set to 8 means "skip first 8
1765        header bytes". This is necessary if the caller wants to
1766        create compressed SWFs himself .
1767        It also means that we don't initialize our own zlib
1768        writer, but assume the caller provided one.
1769      */
1770       if(swf->compressed==1 || (swf->compressed==0 && swf->fileVersion>=6)) {
1771 	char*id = "CWS";
1772 	writer->write(writer, id, 3);
1773       } else {
1774 	char*id = "FWS";
1775 	writer->write(writer, id, 3);
1776       }
1777 
1778       writer->write(writer, &swf->fileVersion, 1);
1779       PUT32(b4, swf->fileSize);
1780       writer->write(writer, b4, 4);
1781 
1782       if(swf->compressed==1 || (swf->compressed==0 && swf->fileVersion>=6)) {
1783 	writer_init_zlibdeflate(&zwriter, writer);
1784 	writer = &zwriter;
1785       }
1786     }
1787 
1788     swf_SetRect(&t1,&swf->movieSize);
1789     swf_SetU16(&t1,swf->frameRate);
1790     swf_SetU16(&t1,swf->frameCount);
1791 
1792     ret = writer->write(writer,b,swf_GetTagLen(&t1));
1793     if (ret!=swf_GetTagLen(&t1))
1794     {
1795       #ifdef DEBUG_RFXSWF
1796 	fprintf(stderr, "ret:%d\n",ret);
1797 	perror("write:");
1798 	fprintf(stderr,"WriteSWF() failed: Header.\n");
1799       #endif
1800       return -1;
1801     }
1802 
1803     if(swf->firstTag && !no_extra_tags) {
1804         WriteExtraTags(swf, writer);
1805     }
1806     t = swf->firstTag;
1807 
1808     while (t) {
1809         if(no_extra_tags || t->id != ST_FILEATTRIBUTES) {
1810           if(swf_WriteTag2(writer, t)<0)
1811             return -1;
1812         }
1813         t = t->next;
1814     }
1815     if(swf->compressed==1 || (swf->compressed==0 && swf->fileVersion>=6) || swf->compressed==8) {
1816       if(swf->compressed != 8) {
1817 	zwriter.finish(&zwriter);
1818 	return original_writer->pos - writer_lastpos;
1819       }
1820       return (int)fileSize;
1821     } else {
1822       return (int)fileSize;
1823     }
1824   }
1825 }
1826 
swf_SaveSWF(SWF * swf,char * filename)1827 int swf_SaveSWF(SWF * swf, char*filename)
1828 {
1829     int fi = open(filename, O_BINARY|O_RDWR|O_TRUNC|O_CREAT, 0777);
1830     if(fi<0) {
1831         perror(filename);
1832         return 0;
1833     }
1834     if(swf_WriteSWF(fi, swf)<0) {
1835         fprintf(stderr, "Unable to write output file: %s\n", filename);
1836         return 0;
1837     }
1838     close(fi);
1839     return 1;
1840 }
1841 
swf_WriteSWF(int handle,SWF * swf)1842 int  swf_WriteSWF(int handle, SWF * swf)     // Writes SWF to file, returns length or <0 if fails
1843 {
1844   writer_t writer;
1845   int len = 0;
1846 
1847   if(handle<0) {
1848     writer_init_nullwriter(&writer);
1849     len = swf_WriteSWF2(&writer, swf);
1850     return len;
1851   }
1852   writer_init_filewriter(&writer, handle);
1853   len = swf_WriteSWF2(&writer, swf);
1854   writer.finish(&writer);
1855   return len;
1856 }
1857 
swf_WriteHeader2(writer_t * writer,SWF * swf)1858 int swf_WriteHeader2(writer_t*writer,SWF * swf)
1859 {
1860   SWF myswf;
1861   memcpy(&myswf,swf,sizeof(SWF));
1862   myswf.firstTag = 0;
1863   return swf_WriteSWF2(writer, &myswf);
1864 }
1865 
swf_WriteHeader(int handle,SWF * swf)1866 int swf_WriteHeader(int handle,SWF * swf)
1867 {
1868   SWF myswf;
1869   memcpy(&myswf,swf,sizeof(SWF));
1870   myswf.firstTag = 0;
1871   return swf_WriteSWF(handle, &myswf);
1872 }
1873 
swf_WriteCGI(SWF * swf)1874 int swf_WriteCGI(SWF * swf)
1875 { int len;
1876   char s[1024];
1877 
1878   len = swf_WriteSWF(-1,swf);
1879 
1880   if (len<0) return -1;
1881 
1882   sprintf(s,"Content-type: application/x-shockwave-flash\n"
1883             "Accept-Ranges: bytes\n"
1884             "Content-Length: %d\n"
1885             "Expires: Thu, 13 Apr 2000 23:59:59 GMT\n"
1886             "\n",len);
1887 
1888   write(fileno(stdout),s,strlen(s));
1889   return swf_WriteSWF(fileno(stdout),swf);
1890 }
1891 
swf_CopySWF(SWF * swf)1892 SWF* swf_CopySWF(SWF*swf)
1893 {
1894     SWF*nswf = (SWF*)rfx_alloc(sizeof(SWF));
1895     TAG*tag, *ntag;
1896     memcpy(nswf, swf, sizeof(SWF));
1897     nswf->firstTag = 0;
1898     tag = swf->firstTag;
1899     ntag = 0;
1900     while(tag) {
1901         ntag = swf_CopyTag(ntag, tag);
1902         if(!nswf->firstTag)
1903             nswf->firstTag = ntag;
1904         tag = tag->next;
1905     }
1906     return nswf;
1907 }
1908 
swf_FreeTags(SWF * swf)1909 void swf_FreeTags(SWF * swf)                 // Frees all malloc'ed memory for tags
1910 { TAG * t = swf->firstTag;
1911 
1912   while (t)
1913   { TAG * tnew = t->next;
1914     if (t->data) rfx_free(t->data);
1915     rfx_free(t);
1916     t = tnew;
1917   }
1918   swf->firstTag = 0;
1919 }
1920 
1921 // include advanced functions
1922 
1923 //#include "modules/swfdump.c"
1924 //#include "modules/swfshape.c"
1925 //#include "modules/swftext.c"
1926 //#include "modules/swffont.c"
1927 //#include "modules/swfobject.c"
1928 //#include "modules/swfbutton.c"
1929 //#include "modules/swftools.c"
1930 //#include "modules/swfcgi.c"
1931 //#include "modules/swfbits.c"
1932 //#include "modules/swfaction.c"
1933 //#include "modules/swfabc.c"
1934 //#include "modules/swfsound.c"
1935 //#include "modules/swfdraw.c"
1936 //#include "modules/swfrender.c"
1937 //#include "modules/swffilter.c"
1938