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