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