gcc 2.95.x fix.
[swftools.git] / lib / h.263 / swfvideo.c
1 /* swfvideo.c
2    Routines for handling h.263 video tags
3
4    Part of the swftools package.
5
6    Copyright (c) 2003 Matthias Kramm <kramm@quiss.org>
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
21
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <assert.h>
25 #include <math.h>
26 #include "../rfxswf.h"
27 #include "h263tables.h"
28 #include "dct.h"
29
30 /* TODO:
31    - use prepare* / write* in encode_IFrame_block
32    - check whether mvd steps of 2 lead to (much) smaller results
33 */ 
34
35 #ifdef MAIN
36 U16 totalframes = 0;
37 #endif
38 void swf_SetVideoStreamDefine(TAG*tag, VIDEOSTREAM*stream, U16 frames, U16 width, U16 height)
39 {
40     swf_SetU16(tag, frames);
41     swf_SetU16(tag, width);
42     swf_SetU16(tag, height);
43     //swf_SetU8(tag, 1); /* smoothing on */
44     swf_SetU8(tag, 0); /* smoothing off */
45     swf_SetU8(tag, 2); /* codec = h.263 sorenson spark */
46
47 #ifdef MAIN
48     totalframes = frames;
49 #endif
50     memset(stream, 0, sizeof(VIDEOSTREAM));
51     stream->olinex = width;
52     stream->owidth = width;
53     stream->oheight = height;
54     width+=15;width&=~15;
55     height+=15;height&=~15;
56     stream->linex = width;
57     stream->width = width;
58     stream->height = height;
59     stream->bbx = width/16;
60     stream->bby = height/16;
61     stream->current = (YUV*)malloc(width*height*sizeof(YUV));
62     stream->oldpic = (YUV*)malloc(width*height*sizeof(YUV));
63     stream->mvdx = (int*)malloc(stream->bbx*stream->bby*sizeof(int));
64     stream->mvdy = (int*)malloc(stream->bbx*stream->bby*sizeof(int));
65     stream->do_motion = 0;
66
67     memset(stream->oldpic, 0, width*height*sizeof(YUV));
68     memset(stream->current, 0, width*height*sizeof(YUV));
69
70     assert((stream->width&15) == 0);
71     assert((stream->height&15) == 0);
72     assert((stream->bbx*16) == stream->width);
73     assert((stream->bby*16) == stream->height);
74 }
75 void swf_VideoStreamClear(VIDEOSTREAM*stream)
76 {
77     free(stream->oldpic);stream->oldpic = 0;
78     free(stream->current);stream->current = 0;
79     free(stream->mvdx);stream->mvdx=0;
80     free(stream->mvdy);stream->mvdy=0;
81 }
82
83 typedef struct _block_t
84 {
85     int y1[64];
86     int y2[64];
87     int y3[64];
88     int y4[64];
89     int u[64];
90     int v[64];
91 } block_t;
92
93 static inline int truncate256(int a)
94 {
95     if(a>255) return 255;
96     if(a<0) return 0;
97     return a;
98 }
99
100 static void getregion(block_t* bb, YUV*pic, int posx, int posy, int linex)
101 {
102     YUV*p1;
103     YUV*p2;
104     int i=0;
105     int x,y;
106     posx*=16;
107     posy*=16;
108     p1 = &pic[posy*linex+posx];
109     p2 = p1;
110     for(y=0;y<8;y++) {
111         for(x=0;x<8;x++) {
112             bb->u[i] = (p2[x*2].u + p2[x*2+1].u + p2[linex+x*2].u + p2[linex+x*2+1].u)/4;
113             bb->v[i] = (p2[x*2].v + p2[x*2+1].v + p2[linex+x*2].v + p2[linex+x*2+1].v)/4;
114             bb->y1[i] = p1[x].y;
115             bb->y2[i] = p1[x+8].y;
116             bb->y3[i] = p1[linex*8+x].y;
117             bb->y4[i] = p1[linex*8+x+8].y;
118             i++;
119         }
120         p1+=linex;
121         p2+=linex*2;
122     }
123 }
124
125 /* This function is pretty complex. Let's hope it works correctly */
126 static void getmvdregion(block_t* bb, YUV*pic, int posx, int posy, int mvdx, int mvdy, int linex)
127 {
128     YUV*p1;
129     YUV*p2;
130     int yy=0,uv=0;
131     int x,y;
132     int yhp = 0, uvhp=0;
133     int uvposx, uvposy;
134     posx = posx*16 + ((mvdx&~1)/2); //works also for negative mvdx (unlike mvdx/2)
135     posy = posy*16 + ((mvdy&~1)/2);
136     p1 = &pic[posy*linex+posx];
137     p2 = &pic[(posy&~1)*linex+(posx&~1)];
138     uvhp = ((mvdx&1)|((mvdx>>1)&1))|((mvdy&2)|((mvdy&1)<<1));
139     yhp = ((mvdy&1)<<1|(mvdx&1));
140
141     /* y */
142     if(yhp==0 || yhp==2) {
143         for(y=0;y<8;y++) {
144             for(x=0;x<8;x++) {
145                 bb->y1[yy] = p1[x].y;
146                 bb->y2[yy] = p1[x+8].y;
147                 bb->y3[yy] = p1[linex*8+x].y;
148                 bb->y4[yy] = p1[linex*8+x+8].y;
149                 yy++;
150             }
151             p1+=linex;
152
153             if(yhp==2) {
154                 yy-=8;
155                 for(x=0;x<8;x++) {
156                     bb->y1[yy] += p1[x].y; bb->y1[yy] /= 2;
157                     bb->y2[yy] += p1[x+8].y; bb->y2[yy] /= 2;
158                     bb->y3[yy] += p1[linex*8+x].y; bb->y3[yy] /= 2;
159                     bb->y4[yy] += p1[linex*8+x+8].y; bb->y4[yy] /= 2;
160                     yy++;
161                 }
162             }
163         }
164     } else if(yhp==1 || yhp==3) {
165         for(y=0;y<8;y++) {
166             for(x=0;x<8;x++) {
167                 bb->y1[yy] = (p1[x].y + p1[x+1].y);
168                 bb->y2[yy] = (p1[x+8].y + p1[x+8+1].y);
169                 bb->y3[yy] = (p1[linex*8+x].y + p1[linex*8+x+1].y);
170                 bb->y4[yy] = (p1[linex*8+x+8].y + p1[linex*8+x+8+1].y);
171                 yy++;
172             }
173             yy-=8;
174             p1+=linex;
175             if(yhp==3) {
176                 for(x=0;x<8;x++) {
177                     bb->y1[yy] += (p1[x].y + p1[x+1].y); bb->y1[yy]/=4;
178                     bb->y2[yy] += (p1[x+8].y + p1[x+8+1].y); bb->y2[yy]/=4;
179                     bb->y3[yy] += (p1[linex*8+x].y + p1[linex*8+x+1].y); bb->y3[yy]/=4;
180                     bb->y4[yy] += (p1[linex*8+x+8].y + p1[linex*8+x+8+1].y); bb->y4[yy]/=4;
181                     yy++;
182                 }
183             } else {
184                 for(x=0;x<8;x++) {
185                     bb->y1[yy]/=2; bb->y2[yy]/=2; bb->y3[yy]/=2; bb->y4[yy]/=2;
186                     yy++;
187                 }
188             }
189         }
190     }
191
192     /* u,v */
193     if(uvhp==0 || uvhp==2) {
194         for(y=0;y<8;y++) {
195             for(x=0;x<8;x++) {
196                 bb->u[uv] = (p2[x*2].u + p2[x*2+1].u + p2[linex+x*2].u + p2[linex+x*2+1].u)/4;
197                 bb->v[uv] = (p2[x*2].v + p2[x*2+1].v + p2[linex+x*2].v + p2[linex+x*2+1].v)/4;
198                 uv++;
199             }
200             p2+=linex*2;
201             if(uvhp==2) {
202                 uv-=8;
203                 for(x=0;x<8;x++) {
204                     bb->u[uv] += (p2[x*2].u + p2[x*2+1].u + p2[linex+x*2].u + p2[linex+x*2+1].u)/4;
205                     bb->v[uv] += (p2[x*2].v + p2[x*2+1].v + p2[linex+x*2].v + p2[linex+x*2+1].v)/4;
206                     bb->u[uv] /= 2;
207                     bb->v[uv] /= 2;
208                     uv++;
209                 }
210             }
211         }
212     } else /* uvhp==1 || uvhp==3 */ {
213         for(y=0;y<8;y++) {
214             for(x=0;x<8;x++) {
215                 bb->u[uv] = ((p2[x*2].u + p2[x*2+1].u + p2[linex+x*2].u + p2[linex+x*2+1].u)/4+
216                              (p2[x*2+2].u + p2[x*2+1+2].u + p2[linex+x*2+2].u + p2[linex+x*2+1+2].u)/4);
217                 bb->v[uv] = ((p2[x*2].v + p2[x*2+1].v + p2[linex+x*2].v + p2[linex+x*2+1].v)/4+
218                              (p2[x*2+2].v + p2[x*2+1+2].v + p2[linex+x*2+2].v + p2[linex+x*2+1+2].v)/4);
219                 uv++;
220             }
221             uv-=8;
222             p2+=linex*2;
223             if(uvhp==3) {
224                 for(x=0;x<8;x++) {
225                     bb->u[uv] += ((p2[x*2].u + p2[x*2+1].u + p2[linex+x*2].u + p2[linex+x*2+1].u)/4+
226                                   (p2[x*2+2].u + p2[x*2+1+2].u + p2[linex+x*2+2].u + p2[linex+x*2+1+2].u)/4);
227                     bb->v[uv] += ((p2[x*2].v + p2[x*2+1].v + p2[linex+x*2].v + p2[linex+x*2+1].v)/4+
228                                   (p2[x*2+2].v + p2[x*2+1+2].v + p2[linex+x*2+2].v + p2[linex+x*2+1+2].v)/4);
229                     bb->u[uv] /= 4;
230                     bb->v[uv] /= 4;
231                     uv++;
232                 }
233             } else {
234                 for(x=0;x<8;x++) {
235                     bb->u[uv] /= 2;
236                     bb->v[uv] /= 2;
237                     uv++;
238                 }
239             }
240         }
241     }
242 }
243
244 static void rgb2yuv(YUV*dest, RGBA*src, int dlinex, int slinex, int width, int height)
245 {
246     int x,y;
247     for(y=0;y<height;y++) {
248         for(x=0;x<width;x++) {
249             int r,g,b;
250             r = src[y*slinex+x].r;
251             g = src[y*slinex+x].g;
252             b = src[y*slinex+x].b;
253             /*dest[y*dlinex+x].y = (r*0.299 + g*0.587 + b*0.114);
254             dest[y*dlinex+x].u = (r*-0.169 + g*-0.332 + b*0.500 + 128.0);
255             dest[y*dlinex+x].v = (r*0.500 + g*-0.419 + b*-0.0813 + 128.0);*/
256
257             //dest[y*dlinex+x].y = 128;//(r*((int)( 0.299*256)) + g*((int)( 0.587*256)) + b*((int)( 0.114 *256)))>>8;
258
259             dest[y*dlinex+x].y = (r*((int)( 0.299*256)) + g*((int)( 0.587*256)) + b*((int)( 0.114 *256)))>>8;
260             dest[y*dlinex+x].u = (r*((int)(-0.169*256)) + g*((int)(-0.332*256)) + b*((int)( 0.500 *256))+ 128*256)>>8;
261             dest[y*dlinex+x].v = (r*((int)( 0.500*256)) + g*((int)(-0.419*256)) + b*((int)(-0.0813*256))+ 128*256)>>8;
262         }
263     }
264 }
265
266 static void copyregion(VIDEOSTREAM*s, YUV*dest, YUV*src, int bx, int by)
267 {
268     YUV*p1 = &dest[by*s->linex*16+bx*16];
269     YUV*p2 = &src[by*s->linex*16+bx*16];
270     int y;
271     for(y=0;y<16;y++) {
272         memcpy(p1, p2, 16*sizeof(YUV));
273         p1+=s->linex;p2+=s->linex;
274     }
275 }
276
277 static void yuv2rgb(RGBA*dest, YUV*src, int linex, int width, int height)
278 {
279     int x,y;
280     for(y=0;y<height;y++) {
281         for(x=0;x<width;x++) {
282             int u,v,yy;
283             u = src[y*linex+x].u;
284             v = src[y*linex+x].v;
285             yy = src[y*linex+x].y;
286             dest[y*linex+x].r = truncate256(yy + ((360*(v-128))>>8));
287             dest[y*linex+x].g = truncate256(yy - ((88*(u-128)+183*(v-128))>>8));
288             dest[y*linex+x].b = truncate256(yy + ((455 * (u-128))>>8));
289         }
290     }
291 }
292 static void copy_block_pic(VIDEOSTREAM*s, YUV*dest, block_t*b, int bx, int by)
293 {
294     YUV*p1 = &dest[(by*16)*s->linex+bx*16];
295     YUV*p2 = &dest[(by*16+8)*s->linex+bx*16];
296     int x,y;
297     for(y=0;y<8;y++) {
298         for(x=0;x<8;x++) {
299             int u,v,yy;
300             p1[x+0].u = b->u[(y/2)*8+(x/2)];
301             p1[x+0].v = b->v[(y/2)*8+(x/2)];
302             p1[x+0].y = b->y1[y*8+x];
303             p1[x+8].u = b->u[(y/2)*8+(x/2)+4];
304             p1[x+8].v = b->v[(y/2)*8+(x/2)+4];
305             p1[x+8].y = b->y2[y*8+x];
306             p2[x+0].u = b->u[(y/2+4)*8+(x/2)];
307             p2[x+0].v = b->v[(y/2+4)*8+(x/2)];
308             p2[x+0].y = b->y3[y*8+x];
309             p2[x+8].u = b->u[(y/2+4)*8+(x/2)+4];
310             p2[x+8].v = b->v[(y/2+4)*8+(x/2)+4];
311             p2[x+8].y = b->y4[y*8+x];
312         }
313         p1+=s->linex;
314         p2+=s->linex;
315     }
316 }
317
318 static int compare_pic_pic(VIDEOSTREAM*s, YUV*pp1, YUV*pp2, int bx, int by)
319 {
320     int linex = s->width;
321     YUV*p1 = &pp1[by*linex*16+bx*16];
322     YUV*p2 = &pp2[by*linex*16+bx*16];
323     int diffy=0, diffuv = 0;
324     int x,y;
325     for(y=0;y<16;y++) {
326         for(x=0;x<16;x++) {
327             YUV*m = &p1[x];
328             YUV*n = &p2[x];
329             int y = m->y - n->y;
330             int u = m->u - n->u;
331             int v = m->v - n->v;
332             diffy += abs(y);
333             diffuv += abs(u)+abs(v);
334         }
335         p1+=linex;
336         p2+=linex;
337     }
338     return diffy + diffuv/4;
339 }
340
341 static int compare_pic_block(VIDEOSTREAM*s, block_t* b, YUV*pic, int bx, int by)
342 {
343     int linex = s->width;
344     YUV*y1 = &pic[(by*2)*linex*8+bx*16];
345     YUV*y2 = &pic[(by*2)*linex*8+bx*16+8];
346     YUV*y3 = &pic[(by*2+1)*linex*8+bx*16];
347     YUV*y4 = &pic[(by*2+1)*linex*8+bx*16+8];
348     YUV*uv1 = y1;
349     YUV*uv2 = &y1[linex];
350     int diffy=0, diffuv = 0;
351     int x,y;
352     for(y=0;y<8;y++) {
353         for(x=0;x<8;x++) {
354             int yy,u1,v1,u2,v2,u3,v3,u4,v4;
355             int y8x = y*8+x;
356             yy = y1[x].y - b->y1[y8x];
357             diffy += abs(yy);
358             yy = y2[x].y - b->y2[y8x];
359             diffy += abs(yy);
360             yy = y3[x].y - b->y3[y8x];
361             diffy += abs(yy);
362             yy = y4[x].y - b->y4[y8x];
363             diffy += abs(yy);
364             u1 = uv1[x*2].u - b->u[y8x];
365             v1 = uv1[x*2].v - b->v[y8x];
366             u2 = uv1[x*2+1].u - b->u[y8x];
367             v2 = uv1[x*2+1].v - b->v[y8x];
368             u3 = uv2[x*2].u - b->u[y8x];
369             v3 = uv2[x*2].v - b->v[y8x];
370             u4 = uv2[x*2+1].u - b->u[y8x];
371             v4 = uv2[x*2+1].v - b->v[y8x];
372             diffuv += (abs(u1)+abs(v1));
373             diffuv += (abs(u2)+abs(v2));
374             diffuv += (abs(u3)+abs(v3));
375             diffuv += (abs(u4)+abs(v4));
376         }
377         y1+=linex;
378         y2+=linex;
379         y3+=linex;
380         y4+=linex;
381         uv1+=linex*2;
382         uv2+=linex*2;
383     }
384     return diffy + diffuv/4;
385 }
386
387 static inline int valtodc(int val)
388 {
389     assert(val>=0);
390
391     /* table 12/h.263 */
392
393     //val+=4; //round
394     val/=8;
395     /* TODO: what to do for zero values? skip the block? */
396     if(val==0)
397         return 1;
398     if(val==128)
399         return 255;
400     if(val>254)
401         return 254;
402     return val;
403 }
404 static int dctoval(int dc)
405 {
406     int val;
407     assert(dc>0);
408     assert(dc!=128);
409     assert(dc<256);
410     /* table 12/h.263 */
411     val = dc*8;
412     if(val == 255*8)
413         val = 128*8;
414     return val;
415 }
416
417 /* TODO: we could also just let the caller pass only the string table[index] here */
418 static int codehuffman(TAG*tag, struct huffcode*table, int index)
419 {
420     /* TODO: !optimize! */
421     int i=0;
422     while(table[index].code[i]) {
423         if(table[index].code[i]=='0')
424             swf_SetBits(tag, 0, 1);
425         else
426             swf_SetBits(tag, 1, 1);
427         i++;
428     }
429     return i;
430 }
431
432 static void quantize8x8(int*src, int*dest, int has_dc, int quant)
433 {
434     int t,pos=0;
435     double q = 1.0/(quant*2);
436     if(has_dc) {
437         dest[0] = valtodc((int)src[0]); /*DC*/
438         pos++;
439     }
440     for(t=pos;t<64;t++)
441     {
442         //dest[t] = (int)src[t];
443     /* exact: if(quant&1){dest[t] = (dest[t]/quant - 1)/2;}else{dest[t] = ((dest[t]+1)/quant - 1)/2;} */
444         //if(quant&1){dest[t] = (dest[t]/quant - 1)/2;}else{dest[t] = ((dest[t]+1)/quant - 1)/2;}
445         //dest[t] = dest[t]/(quant*2);
446         dest[t] = (int)(src[t]*q);
447         /* TODO: warn if this happens- the video will be buggy */
448         if(dest[t]>127) dest[t]=127;
449         if(dest[t]<-127) dest[t]=-127;
450     }
451 }
452
453 static void dequantize8x8(int*b, int has_dc, int quant)
454 {
455     int t,pos=0;
456     if(has_dc) {
457         b[0] = dctoval(b[0]); //DC
458         pos++;
459     }
460     for(t=pos;t<64;t++) {
461         if(b[t]) {
462             int sign = 0;
463             if(b[t]<0) {
464                 b[t] = -b[t];
465                 sign = 1;
466             }
467
468             if(quant&1) {
469                 b[t] = quant*(2*b[t]+1); //-7,8,24,40
470             } else {
471                 b[t] = quant*(2*b[t]+1)-1; //-8,7,23,39
472             }
473
474             if(sign)
475                 b[t] = -b[t];
476         }
477
478         /* paragraph 6.2.2, "clipping of reconstruction levels": */
479         if(b[t]>2047) b[t]=2047;
480         if(b[t]<-2048) b[t]=-2048;
481     }
482 }
483
484 static int hascoef(int*b, int has_dc)
485 {
486     int t;
487     int pos=0;
488     if(has_dc)
489         pos++;
490     for(t=pos;t<64;t++) {
491         if(b[t])
492             return 1;
493     }
494     return 0;
495 }
496
497 static int coefbits8x8(int*bb, int has_dc)
498 {
499     int t;
500     int pos=0;
501     int bits=0;
502     int last;
503
504     if(has_dc) {
505         bits+=8;
506         pos++;
507     }
508     for(last=63;last>=pos;last--) {
509         if(bb[last])
510             break;
511     }
512     if(last < pos)
513         return bits;
514     while(1) {
515         int run=0, level=0, islast=0,t;
516         while(!bb[pos] && pos<last) {
517             pos++;
518             run++;
519         }
520         if(pos==last)
521             islast=1;
522         level=bb[pos];
523         if(level<0) level=-level;
524         assert(level);
525         for(t=0;t<RLE_ESCAPE;t++) {
526             if(rle_params[t].run == run &&
527                rle_params[t].level == level &&
528                rle_params[t].last == islast) {
529                 bits += rle[t].len + 1;
530                 break;
531             }
532         }
533         if(t==RLE_ESCAPE) {
534             bits += rle[RLE_ESCAPE].len + 1 + 6 + 8;
535         }
536         if(islast)
537             break;
538         pos++;
539     }
540     return bits;
541 }
542
543 static int encode8x8(TAG*tag, int*bb, int has_dc, int has_tcoef)
544 {
545     int t;
546     int pos=0;
547     int bits=0;
548
549     if(has_dc) {
550         swf_SetBits(tag, bb[0], 8);
551         bits += 8;
552         pos++;
553     }
554
555     if(has_tcoef) {
556         int last;
557         /* determine last non-null coefficient */
558         for(last=63;last>=pos;last--) {
559             /* TODO: we could leave out small coefficients
560                      after a certain point (32?) */
561             if(bb[last])
562                 break;
563         }
564         /* blocks without coefficients should not be included
565            in the cbpy/cbpc patterns: */
566         assert(bb[last]);
567
568         while(1) {
569             int run=0;
570             int level=0;
571             int islast=0;
572             int sign=0;
573             int t;
574             while(!bb[pos] && pos<last) {
575                 pos++;
576                 run++;
577             }
578             if(pos==last)
579                 islast=1;
580             level=bb[pos];
581             assert(level);
582             if(level<0) {
583                 level = -level;
584                 sign = 1;
585             }
586             for(t=0;t<RLE_ESCAPE;t++) {
587                 /* TODO: lookup table */
588                 if(rle_params[t].run == run &&
589                    rle_params[t].level == level &&
590                    rle_params[t].last == islast) {
591                     bits += codehuffman(tag, rle, t);
592                     swf_SetBits(tag, sign, 1);
593                     bits += 1;
594                     break;
595                 }
596             }
597             if(t==RLE_ESCAPE) {
598                 bits += codehuffman(tag, rle, RLE_ESCAPE);
599                 level=bb[pos];
600                 /* table 14/h.263 */
601                 if(!level || level<-127 || level>127) {
602                     fprintf(stderr, "Warning: Overflow- Level %d at pos %d\n", level, pos);
603                     if(level<-127) level=-127;
604                     if(level>127) level=127;
605                 }
606
607                 assert(level);
608                 assert(level>=-127);
609                 assert(level<=127); //TODO: known to fail for pos=0 (with custom frames?)
610
611                 swf_SetBits(tag, islast, 1);
612                 swf_SetBits(tag, run, 6);
613                 swf_SetBits(tag, level, 8); //FIXME: fixme??
614                 bits += 1 + 6 + 8;
615             }
616
617             if(islast)
618                 break;
619             pos++;
620         }
621     }
622     return bits;
623 }
624
625 static void quantize(block_t*fb, block_t*b, int has_dc, int quant)
626 {
627     quantize8x8(fb->y1, b->y1, has_dc, quant);
628     quantize8x8(fb->y2, b->y2, has_dc, quant);
629     quantize8x8(fb->y3, b->y3, has_dc, quant);
630     quantize8x8(fb->y4, b->y4, has_dc, quant);
631     quantize8x8(fb->u, b->u, has_dc, quant);
632     quantize8x8(fb->v, b->v, has_dc, quant);
633 }
634
635 static void dodct(block_t*fb)
636 {
637     dct(fb->y1); dct(fb->y2); dct(fb->y3); dct(fb->y4);
638     dct(fb->u);  dct(fb->v);
639     zigzag(fb->y1);
640     zigzag(fb->y2);
641     zigzag(fb->y3);
642     zigzag(fb->y4);
643     zigzag(fb->u);
644     zigzag(fb->v);
645 }
646
647 static void dodctandquant(block_t*fb, block_t*b, int has_dc, int quant)
648 {
649     int t;
650     if(has_dc) {
651         dodct(fb);
652         quantize(fb,b,has_dc,quant);
653         return;
654     }
655     preparequant(quant);
656     dct2(fb->y1,b->y1); dct2(fb->y2,b->y2); dct2(fb->y3,b->y3); dct2(fb->y4,b->y4);
657     dct2(fb->u,b->u);  dct2(fb->v,b->v);
658
659     for(t=0;t<64;t++) {
660         /* prepare for encoding (only values in (-127..-1,1..127) are
661            allowed as non-zero, non-dc values */
662         if(b->y1[t]<-127) b->y1[t]=-127;
663         if(b->y2[t]<-127) b->y2[t]=-127;
664         if(b->y3[t]<-127) b->y3[t]=-127;
665         if(b->y4[t]<-127) b->y4[t]=-127;
666         if(b->u[t]<-127) b->u[t]=-127;
667         if(b->v[t]<-127) b->v[t]=-127;
668
669         if(b->y1[t]>127) b->y1[t]=127;
670         if(b->y2[t]>127) b->y2[t]=127;
671         if(b->y3[t]>127) b->y3[t]=127;
672         if(b->y4[t]>127) b->y4[t]=127;
673         if(b->u[t]>127) b->u[t]=127;
674         if(b->v[t]>127) b->v[t]=127;
675     }
676 }
677
678 static void doidct(block_t*b)
679 {
680     block_t fb;
681     int t;
682     for(t=0;t<64;t++) {
683         fb.y1[t] = b->y1[zigzagtable[t]];
684         fb.y2[t] = b->y2[zigzagtable[t]];
685         fb.y3[t] = b->y3[zigzagtable[t]];
686         fb.y4[t] = b->y4[zigzagtable[t]];
687         fb.u[t] = b->u[zigzagtable[t]];
688         fb.v[t] = b->v[zigzagtable[t]];
689     }
690     idct(fb.y1); idct(fb.y2); idct(fb.y3); idct(fb.y4);
691     idct(fb.u);  idct(fb.v);
692
693     memcpy(b, &fb, sizeof(block_t));
694 }
695
696 static void truncateblock(block_t*b)
697 {
698     int t;
699     for(t=0;t<64;t++) {
700         b->y1[t] = truncate256(b->y1[t]);
701         b->y2[t] = truncate256(b->y2[t]);
702         b->y3[t] = truncate256(b->y3[t]);
703         b->y4[t] = truncate256(b->y4[t]);
704         b->u[t] = truncate256(b->u[t]);
705         b->v[t] = truncate256(b->v[t]);
706     }
707 }
708
709 static void dequantize(block_t*b, int has_dc, int quant)
710 {
711     dequantize8x8(b->y1, has_dc, quant);
712     dequantize8x8(b->y2, has_dc, quant);
713     dequantize8x8(b->y3, has_dc, quant);
714     dequantize8x8(b->y4, has_dc, quant);
715     dequantize8x8(b->u, has_dc, quant);
716     dequantize8x8(b->v, has_dc, quant);
717 }
718
719 static void getblockpatterns(block_t*b, int*cbpybits,int*cbpcbits, int has_dc)
720 {
721     *cbpybits = 0;
722     *cbpcbits = 0;
723
724     *cbpybits|=hascoef(b->y1, has_dc)*8;
725     *cbpybits|=hascoef(b->y2, has_dc)*4;
726     *cbpybits|=hascoef(b->y3, has_dc)*2;
727     *cbpybits|=hascoef(b->y4, has_dc)*1;
728
729     *cbpcbits|=hascoef(b->u, has_dc)*2;
730     *cbpcbits|=hascoef(b->v, has_dc)*1;
731 }
732
733 static void setQuant(TAG*tag, int dquant)
734 {
735     int code = 0;
736     /* 00 01 10 11
737        -1 -2 +1 +2
738     */
739     if(dquant == -1) {
740         swf_SetBits(tag, 0x0, 2);
741     } else if(dquant == -2) {
742         swf_SetBits(tag, 0x1, 2);
743     } else if(dquant == +1) {
744         swf_SetBits(tag, 0x2, 2);
745     } else if(dquant == +2) {
746         swf_SetBits(tag, 0x3, 2);
747     } else {
748         assert(0*strlen("invalid dquant"));
749     }
750 }
751
752 static void change_quant(int quant, int*dquant)
753 {
754     /* TODO */
755     *dquant = 0;
756 }
757
758 static void yuvdiff(block_t*a, block_t*b)
759 {
760     int t;
761     for(t=0;t<64;t++) {
762         a->y1[t] = (a->y1[t] - b->y1[t]);
763         a->y2[t] = (a->y2[t] - b->y2[t]);
764         a->y3[t] = (a->y3[t] - b->y3[t]);
765         a->y4[t] = (a->y4[t] - b->y4[t]);
766         a->u[t]  = (a->u[t] - b->u[t]);
767         a->v[t]  = (a->v[t] - b->v[t]);
768     }
769 }
770
771 static void predictmvd(VIDEOSTREAM*s, int bx, int by, int*px, int*py)
772 {
773     int i1,i2;
774     int x1,y1,x2,y2,x3,y3;
775     int x4,y4,p;
776     if(bx) {x1=s->mvdx[by*s->bbx+bx-1];
777             y1=s->mvdy[by*s->bbx+bx-1];
778     } else {x1=y1=0;}
779
780     if(by) {x2=s->mvdx[(by-1)*s->bbx+bx];
781             y2=s->mvdy[(by-1)*s->bbx+bx];
782             if(bx<s->bbx-1) {
783                 x3=s->mvdx[(by-1)*s->bbx+bx+1];
784                 y3=s->mvdy[(by-1)*s->bbx+bx+1];
785             } else {
786                 x3=y3=0;
787             }
788            }
789     else   {x2=x3=x1;y2=y3=y1;}
790
791            if((x1 <= x2 && x2 <= x3) ||
792               (x3 <= x2 && x2 <= x1)) {
793         x4=x2;
794     } else if((x2 <= x1 && x1 <= x3) ||
795               (x3 <= x1 && x1 <= x2)) {
796         x4=x1;
797     } else if((x1 <= x3 && x3 <= x2) ||
798               (x2 <= x3 && x3 <= x1)) {
799         x4=x3;
800     } else {
801         x4=0;
802         assert(x4);
803     }
804
805            if((y1 <= y2 && y2 <= y3) ||
806               (y3 <= y2 && y2 <= y1)) {
807         y4=y2;
808     } else if((y2 <= y1 && y1 <= y3) ||
809               (y3 <= y1 && y1 <= y2)) {
810         y4=y1;
811     } else if((y1 <= y3 && y3 <= y2) ||
812               (y2 <= y3 && y3 <= y1)) {
813         y4=y3;
814     } else {
815         y4=0;
816         assert(y4);
817     }
818
819     *px = x4;
820     *py = y4;
821     assert((x4>=-32 && x4<=31) && (y4>=-32 && y4<=31));
822 }
823
824 static inline int mvd2index(int px, int py, int x, int y, int xy)
825 {
826
827     if((x<-32 && x>31) || (y<-32 && y>31)) 
828         fprintf(stderr, "(%d,%d)\n", x,y);
829     assert((x>=-32 && x<=31) && (y>=-32 && y<=31));
830     //assert((x&1)==0 && (y&1)==0);//for now
831     //assert((x&2)==0 && (y&2)==0);//for now(2)
832
833     x-=px;
834     y-=py;
835
836     if(xy)
837         x=y;
838     x+=32;
839
840     /* (x&63) */
841     if(x>63)
842         x-=64;
843     if(x<0)
844         x+=64;
845
846     assert(x>=0 && x<64);
847     return x;
848 }
849
850 typedef struct _iblockdata_t
851 {
852     block_t b; //transformed quantized coefficients
853     block_t reconstruction;
854     int bits;
855     int bx,by;
856     struct huffcode*ctable; //table to use for chrominance encoding (different for i-frames)
857     int iframe; // 1 if this is part of an iframe
858 } iblockdata_t;
859
860 typedef struct _mvdblockdata_t
861 {
862     block_t b;
863     block_t fbold;
864     block_t reconstruction;
865     int xindex;
866     int yindex;
867     int movex;
868     int movey;
869     int bits;
870     int bx,by;
871 } mvdblockdata_t;
872
873 void prepareIBlock(VIDEOSTREAM*s, iblockdata_t*data, int bx, int by, block_t* fb, int*bits, int iframe)
874 {
875     /* consider I-block */
876     block_t fb_i;
877     block_t b;
878     int y,c;
879     struct huffcode*ctable;
880
881     data->bx = bx;
882     data->by = by;
883
884     data->iframe = iframe;
885     if(!iframe) {
886         data->ctable = &mcbpc_inter[3*4];
887     } else {
888         data->ctable = &mcbpc_intra[0];
889     }
890
891     memcpy(&fb_i, fb, sizeof(block_t));
892     dodctandquant(&fb_i, &data->b, 1, s->quant);
893     getblockpatterns(&data->b, &y, &c, 1);
894     *bits = 0;
895     if(!data->iframe) {
896         *bits += 1; //cod
897     }
898     *bits += data->ctable[c].len;
899     *bits += cbpy[y].len;
900     *bits += coefbits8x8(data->b.y1, 1);
901     *bits += coefbits8x8(data->b.y2, 1);
902     *bits += coefbits8x8(data->b.y3, 1);
903     *bits += coefbits8x8(data->b.y4, 1);
904     *bits += coefbits8x8(data->b.u, 1);
905     *bits += coefbits8x8(data->b.v, 1);
906     data->bits = *bits;
907     
908     /* -- reconstruction -- */
909     memcpy(&data->reconstruction,&data->b,sizeof(block_t));
910     dequantize(&data->reconstruction, 1, s->quant);
911     doidct(&data->reconstruction);
912     truncateblock(&data->reconstruction);
913 }
914
915 int writeIBlock(VIDEOSTREAM*s, TAG*tag, iblockdata_t*data)
916 {
917     int c = 0, y = 0;
918     int has_dc=1;
919     int bits = 0;
920     block_t b;
921
922     getblockpatterns(&data->b, &y, &c, has_dc);
923     if(!data->iframe) {
924         swf_SetBits(tag,0,1); bits += 1; // COD
925     }
926     bits += codehuffman(tag, data->ctable, c);
927     bits += codehuffman(tag, cbpy, y);
928
929     /* luminance */
930     bits += encode8x8(tag, data->b.y1, has_dc, y&8);
931     bits += encode8x8(tag, data->b.y2, has_dc, y&4);
932     bits += encode8x8(tag, data->b.y3, has_dc, y&2);
933     bits += encode8x8(tag, data->b.y4, has_dc, y&1);
934
935     /* chrominance */
936     bits += encode8x8(tag, data->b.u, has_dc, c&2);
937     bits += encode8x8(tag, data->b.v, has_dc, c&1);
938
939     copy_block_pic(s, s->current, &data->reconstruction, data->bx, data->by);
940     assert(data->bits == bits);
941     return bits;
942 }
943
944 int getmvdbits(VIDEOSTREAM*s,block_t*fb, int bx,int by,int hx,int hy)
945 {
946     block_t b;
947     block_t fbold;
948     block_t fbdiff;
949     int bits = 0;
950     memcpy(&fbdiff, fb, sizeof(block_t));
951     getmvdregion(&fbold, s->oldpic, bx, by, hx, hy, s->linex);
952     yuvdiff(&fbdiff, &fbold);
953     dodctandquant(&fbdiff, &b, 0, s->quant);
954     bits += coefbits8x8(b.y1, 0);
955     bits += coefbits8x8(b.y2, 0);
956     bits += coefbits8x8(b.y3, 0);
957     bits += coefbits8x8(b.y4, 0);
958     bits += coefbits8x8(b.u, 0);
959     bits += coefbits8x8(b.v, 0);
960     return bits;
961 }
962
963 void prepareMVDBlock(VIDEOSTREAM*s, mvdblockdata_t*data, int bx, int by, block_t* fb, int*bits)
964 { /* consider mvd(x,y)-block */
965
966     int t;
967     int y,c;
968     block_t fbdiff;
969     int predictmvdx;
970     int predictmvdy;
971
972     data->bx = bx;
973     data->by = by;
974     predictmvd(s,bx,by,&predictmvdx,&predictmvdy);
975
976     data->bits = 65535;
977     data->movex=0;
978     data->movey=0;
979
980     if(s->do_motion) {
981         int hx,hy;
982         int bestx=0,besty=0,bestbits=65536;
983         int startx=-32,endx=31;
984         int starty=-32,endy=31;
985
986         if(!bx) startx=0;
987         if(!by) starty=0;
988         if(bx==s->bbx-1) endx=0;
989         if(by==s->bby-1) endy=0;
990
991         for(hx=startx;hx<=endx;hx+=4)
992         for(hy=starty;hy<=endy;hy+=4)
993         {
994             int bits = 0;
995             bits = getmvdbits(s,fb,bx,by,hx,hy);
996             if(bits<bestbits) {
997                 bestbits = bits;
998                 bestx = hx;
999                 besty = hy;
1000             }
1001         }
1002         
1003         if(bestx-3 > startx) startx = bestx-3;
1004         if(besty-3 > starty) starty = besty-3;
1005         if(bestx+3 < endx) endx = bestx+3;
1006         if(besty+3 < endy) endy = besty+3;
1007
1008         for(hx=startx;hx<=endx;hx++)
1009         for(hy=starty;hy<=endy;hy++)
1010         {
1011             int bits = 0;
1012             bits = getmvdbits(s,fb,bx,by,hx,hy);
1013             if(bits<bestbits) {
1014                 bestbits = bits;
1015                 bestx = hx;
1016                 besty = hy;
1017             }
1018         }
1019         data->movex = bestx;
1020         data->movey = besty;
1021     }
1022
1023     memcpy(&fbdiff, fb, sizeof(block_t));
1024     getmvdregion(&data->fbold, s->oldpic, bx, by, data->movex, data->movey, s->linex);
1025     yuvdiff(&fbdiff, &data->fbold);
1026     dodctandquant(&fbdiff, &data->b, 0, s->quant);
1027     getblockpatterns(&data->b, &y, &c, 0);
1028
1029     data->xindex = mvd2index(predictmvdx, predictmvdy, data->movex, data->movey, 0);
1030     data->yindex = mvd2index(predictmvdx, predictmvdy, data->movex, data->movey, 1);
1031
1032     *bits = 1; //cod
1033     *bits += mcbpc_inter[0*4+c].len;
1034     *bits += cbpy[y^15].len;
1035     *bits += mvd[data->xindex].len; // (0,0)
1036     *bits += mvd[data->yindex].len;
1037     *bits += coefbits8x8(data->b.y1, 0);
1038     *bits += coefbits8x8(data->b.y2, 0);
1039     *bits += coefbits8x8(data->b.y3, 0);
1040     *bits += coefbits8x8(data->b.y4, 0);
1041     *bits += coefbits8x8(data->b.u, 0);
1042     *bits += coefbits8x8(data->b.v, 0);
1043     data->bits = *bits;
1044
1045     /* -- reconstruction -- */
1046     memcpy(&data->reconstruction, &data->b, sizeof(block_t));
1047     dequantize(&data->reconstruction, 0, s->quant);
1048     doidct(&data->reconstruction);
1049     for(t=0;t<64;t++) {
1050         data->reconstruction.y1[t] = 
1051             truncate256(data->reconstruction.y1[t] + (int)data->fbold.y1[t]);
1052         data->reconstruction.y2[t] = 
1053             truncate256(data->reconstruction.y2[t] + (int)data->fbold.y2[t]);
1054         data->reconstruction.y3[t] = 
1055             truncate256(data->reconstruction.y3[t] + (int)data->fbold.y3[t]);
1056         data->reconstruction.y4[t] = 
1057             truncate256(data->reconstruction.y4[t] + (int)data->fbold.y4[t]);
1058         data->reconstruction.u[t] = 
1059             truncate256(data->reconstruction.u[t] + (int)data->fbold.u[t]);
1060         data->reconstruction.v[t] = 
1061             truncate256(data->reconstruction.v[t] + (int)data->fbold.v[t]);
1062     }
1063 }
1064
1065 int writeMVDBlock(VIDEOSTREAM*s, TAG*tag, mvdblockdata_t*data)
1066 {
1067     int c = 0, y = 0;
1068     int t;
1069     int has_dc=0; // mvd w/o mvd24
1070     /* mvd (0,0) block (mode=0) */
1071     int mode = 0;
1072     int bx = data->bx;
1073     int by = data->by;
1074     int bits = 0;
1075
1076     getblockpatterns(&data->b, &y, &c, has_dc);
1077     swf_SetBits(tag,0,1); bits += 1; // COD
1078     bits += codehuffman(tag, mcbpc_inter, mode*4+c);
1079     bits += codehuffman(tag, cbpy, y^15);
1080
1081     /* vector */
1082     bits += codehuffman(tag, mvd, data->xindex);
1083     bits += codehuffman(tag, mvd, data->yindex);
1084
1085     /* luminance */
1086     bits += encode8x8(tag, data->b.y1, has_dc, y&8);
1087     bits += encode8x8(tag, data->b.y2, has_dc, y&4);
1088     bits += encode8x8(tag, data->b.y3, has_dc, y&2);
1089     bits += encode8x8(tag, data->b.y4, has_dc, y&1);
1090
1091     /* chrominance */
1092     bits += encode8x8(tag, data->b.u, has_dc, c&2);
1093     bits += encode8x8(tag, data->b.v, has_dc, c&1);
1094
1095     s->mvdx[by*s->bbx+bx] = data->movex;
1096     s->mvdy[by*s->bbx+bx] = data->movey;
1097
1098     copy_block_pic(s, s->current, &data->reconstruction, data->bx, data->by);
1099     assert(data->bits == bits);
1100     return bits;
1101 }
1102
1103 static int encode_PFrame_block(TAG*tag, VIDEOSTREAM*s, int bx, int by)
1104 {
1105     block_t fb;
1106     int diff1,diff2;
1107     int bits_i;
1108     int bits_vxy;
1109
1110     iblockdata_t iblock;
1111     mvdblockdata_t mvdblock;
1112     
1113     getregion(&fb, s->current, bx, by, s->linex);
1114     prepareIBlock(s, &iblock, bx, by, &fb, &bits_i, 0);
1115
1116     /* encoded last frame <=> original current block: */
1117     diff1 = compare_pic_pic(s, s->current, s->oldpic, bx, by);
1118     /* encoded current frame <=> original current block: */
1119     diff2 = compare_pic_block(s, &iblock.reconstruction, s->current, bx, by);
1120
1121     if(diff1 <= diff2) {
1122         swf_SetBits(tag, 1,1); /* cod=1, block skipped */
1123         /* copy the region from the last frame so that we have a complete reconstruction */
1124         copyregion(s, s->current, s->oldpic, bx, by);
1125         return 1;
1126     }
1127     prepareMVDBlock(s, &mvdblock, bx, by, &fb, &bits_vxy);
1128
1129     if(bits_i > bits_vxy) {
1130         return writeMVDBlock(s, tag, &mvdblock);
1131     } else {
1132         return writeIBlock(s, tag, &iblock);
1133     }
1134 }
1135
1136 /* should be called encode_IFrameBlock */
1137 static void encode_IFrame_block(TAG*tag, VIDEOSTREAM*s, int bx, int by)
1138 {
1139     block_t fb;
1140     iblockdata_t data;
1141     int bits;
1142
1143     getregion(&fb, s->current, bx, by, s->width);
1144     prepareIBlock(s, &data, bx, by, &fb, &bits, 1);
1145     writeIBlock(s, tag, &data);
1146 }
1147
1148 #ifdef MAIN
1149 static int bmid = 0;
1150
1151 void setdbgpic(TAG*tag, RGBA*pic, int width, int height)
1152 {
1153     MATRIX m;
1154     tag = tag->prev;
1155
1156     tag = swf_InsertTag(tag,ST_REMOVEOBJECT2);
1157     swf_SetU16(tag, 133);
1158
1159     tag = swf_InsertTag(tag, ST_DEFINEBITSLOSSLESS);
1160     swf_SetU16(tag, 1000+bmid);
1161     swf_SetLosslessBits(tag, width, height, (void*)pic, BMF_32BIT);
1162
1163     tag = swf_InsertTag(tag, ST_DEFINESHAPE);
1164     swf_SetU16(tag, 2000+bmid);
1165     swf_ShapeSetBitmapRect(tag, 1000+bmid, width, height);
1166
1167     tag = swf_InsertTag(tag,ST_PLACEOBJECT2);
1168     swf_GetMatrix(0,&m);
1169     m.tx = width*20;
1170     swf_ObjectPlace(tag, 2000+bmid, 133, &m, 0, 0);
1171
1172     bmid++;
1173 }
1174 #endif
1175
1176 #define TYPE_IFRAME 0
1177 #define TYPE_PFRAME 1
1178
1179 static void writeHeader(TAG*tag, int width, int height, int frame, int quant, int type)
1180 {
1181     U32 i32;
1182     swf_SetU16(tag, frame);
1183     swf_SetBits(tag, 1, 17); /* picture start code*/
1184     swf_SetBits(tag, 0, 5); /* version=0, version 1 would optimize rle behaviour*/
1185     swf_SetBits(tag, frame, 8); /* time reference */
1186
1187     /* write dimensions, taking advantage of some predefined sizes
1188        if the opportunity presents itself */
1189     i32 = width<<16|height;
1190     switch(i32)
1191     {
1192         case 352<<16|288: swf_SetBits(tag, 2, 3);break;
1193         case 176<<16|144: swf_SetBits(tag, 3, 3);break;
1194         case 128<<16|96: swf_SetBits(tag, 4, 3);break;
1195         case 320<<16|240: swf_SetBits(tag, 5, 3);break;
1196         case 160<<16|120: swf_SetBits(tag, 6, 3);break;
1197         default:
1198             if(width>255 || height>255) {
1199                 swf_SetBits(tag, 1, 3);
1200                 swf_SetBits(tag, width, 16);
1201                 swf_SetBits(tag, height, 16);
1202             } else {
1203                 swf_SetBits(tag, 0, 3);
1204                 swf_SetBits(tag, width, 8);
1205                 swf_SetBits(tag, height, 8);
1206             }
1207     }
1208
1209     swf_SetBits(tag, type, 2); /* I-Frame or P-Frame */
1210     swf_SetBits(tag, 0, 1); /* No deblock filter */
1211     assert(quant>0);
1212     assert(quant<32);
1213     swf_SetBits(tag, quant, 5); /* quantizer (1-31), may be updated later on*/
1214     swf_SetBits(tag, 0, 1); /* No extra info */
1215 }
1216
1217 void swf_SetVideoStreamIFrame(TAG*tag, VIDEOSTREAM*s, RGBA*pic, int quant)
1218 {
1219     int bx, by;
1220
1221     if(quant<1) quant=1;
1222     if(quant>31) quant=31;
1223     s->quant = quant;
1224
1225     writeHeader(tag, s->width, s->height, s->frame, quant, TYPE_IFRAME);
1226
1227     /* fixme: should fill with 0,128,128, not 0,0,0 */
1228     memset(s->current, 0, s->linex*s->height*sizeof(YUV));
1229
1230     rgb2yuv(s->current, pic, s->linex, s->olinex, s->owidth, s->oheight);
1231
1232     for(by=0;by<s->bby;by++)
1233     {
1234         for(bx=0;bx<s->bbx;bx++)
1235         {
1236             encode_IFrame_block(tag, s, bx, by);
1237         }
1238     }
1239     s->frame++;
1240     memcpy(s->oldpic, s->current, s->width*s->height*sizeof(YUV));
1241 }
1242 void swf_SetVideoStreamBlackFrame(TAG*tag, VIDEOSTREAM*s)
1243 {
1244     int bx, by;
1245     int quant = 31;
1246     int x,y;
1247     s->quant = quant;
1248
1249     writeHeader(tag, s->width, s->height, s->frame, quant, TYPE_IFRAME);
1250
1251     for(y=0;y<s->height;y++)
1252     for(x=0;x<s->width;x++) {
1253         s->current[y*s->width+x].y = 0;
1254         s->current[y*s->width+x].u = 128;
1255         s->current[y*s->width+x].v = 128;
1256     }
1257     for(x=0;x<16;x++)
1258     for(y=0;y<16;y++) {
1259         s->current[y*s->width+x].y = 64; 
1260         s->current[y*s->width+x].u = 128; 
1261         s->current[y*s->width+x].v = 128;
1262     }
1263
1264     for(by=0;by<s->bby;by++)
1265     {
1266         for(bx=0;bx<s->bbx;bx++)
1267         {
1268             encode_IFrame_block(tag, s, bx, by);
1269         }
1270     }
1271     s->frame++;
1272     memcpy(s->oldpic, s->current, s->width*s->height*sizeof(YUV));
1273 }
1274
1275 void swf_SetVideoStreamPFrame(TAG*tag, VIDEOSTREAM*s, RGBA*pic, int quant)
1276 {
1277     int bx, by;
1278
1279     if(quant<1) quant=1;
1280     if(quant>31) quant=31;
1281     s->quant = quant;
1282
1283     writeHeader(tag, s->width, s->height, s->frame, quant, TYPE_PFRAME);
1284
1285     /* fixme: should fill with 0,128,128, not 0,0,0 */
1286     memset(s->current, 0, s->linex*s->height*sizeof(YUV));
1287
1288     rgb2yuv(s->current, pic, s->linex, s->olinex, s->owidth, s->oheight);
1289     memset(s->mvdx, 0, s->bbx*s->bby*sizeof(int));
1290     memset(s->mvdy, 0, s->bbx*s->bby*sizeof(int));
1291
1292     for(by=0;by<s->bby;by++)
1293     {
1294         for(bx=0;bx<s->bbx;bx++)
1295         {
1296             encode_PFrame_block(tag, s, bx, by);
1297         }
1298     }
1299     s->frame++;
1300     memcpy(s->oldpic, s->current, s->width*s->height*sizeof(YUV));
1301
1302 #ifdef MAIN
1303 #ifdef PNG
1304     yuv2rgb(pic, s->current, s->linex, s->width, s->height);
1305     setdbgpic(tag, pic, s->width, s->height);
1306 #endif
1307 #endif
1308 }
1309
1310 void swf_SetVideoStreamMover(TAG*tag, VIDEOSTREAM*s, signed char* movex, signed char* movey, void**pictures, int quant)
1311 {
1312     int bx, by;
1313     YUV pic[16*16];
1314
1315     if(quant<1) quant=1;
1316     if(quant>31) quant=31;
1317     s->quant = quant;
1318
1319     writeHeader(tag, s->width, s->height, s->frame, quant, TYPE_PFRAME);
1320
1321     memset(s->mvdx, 0, s->bbx*s->bby*sizeof(int));
1322     memset(s->mvdy, 0, s->bbx*s->bby*sizeof(int));
1323
1324     for(by=0;by<s->bby;by++)
1325     {
1326         for(bx=0;bx<s->bbx;bx++)
1327         {
1328             int predictmvdx=0, predictmvdy=0;
1329             int mvx=movex[by*s->bbx+bx];
1330             int mvy=movey[by*s->bbx+bx];
1331             void*picture = pictures?pictures[by*s->bbx+bx]:0;
1332     
1333             if(mvx<-32) mvx=-32;
1334             if(mvx>31) mvx=31;
1335             if(mvy<-32) mvy=-32;
1336             if(mvy>31) mvy=31;
1337
1338             if(mvx == 0 && mvy == 0 && picture == 0) {
1339                 swf_SetBits(tag,1,1); // COD skip
1340             } else {
1341                 int mode = 0;
1342                 int has_dc=0;
1343                 int y=0,c=0;
1344                 block_t b;
1345                 block_t b2;
1346                 
1347                 swf_SetBits(tag,0,1); // COD
1348
1349                 if(mvx==0 && mvy==0 && picture) { // only picture
1350                     mode = 3;
1351                     has_dc = 1;
1352                 }
1353
1354                 if(picture) {
1355                     RGBA* picblock = (RGBA*)picture;
1356                     rgb2yuv(pic, picblock,16,16,16,16);
1357                     /* TODO: if has_dc!=1, subtract 128 from rgb values */
1358                     getregion(&b, pic, 0,0,16);
1359                     dodctandquant(&b, &b2, 1, s->quant);
1360                     getblockpatterns(&b2, &y, &c, 1);
1361                 } else {
1362                     y=0;c=0;
1363                 }
1364
1365                 codehuffman(tag, mcbpc_inter, mode*4+c);
1366                 codehuffman(tag, cbpy, mode==3?y:y^15);
1367                 
1368                 if(mode < 3) {
1369                     /* has motion vector */
1370                     predictmvd(s,bx,by,&predictmvdx,&predictmvdy);
1371                     codehuffman(tag, mvd, mvd2index(predictmvdx, predictmvdy, mvx, mvy, 0));
1372                     codehuffman(tag, mvd, mvd2index(predictmvdx, predictmvdy, mvx, mvy, 1));
1373                     s->mvdx[by*s->bbx+bx] = mvx;
1374                     s->mvdy[by*s->bbx+bx] = mvy;
1375                 }
1376
1377                 if(has_dc||y||c) {
1378                     encode8x8(tag, b2.y1, has_dc, y&8);
1379                     encode8x8(tag, b2.y2, has_dc, y&4);
1380                     encode8x8(tag, b2.y3, has_dc, y&2);
1381                     encode8x8(tag, b2.y4, has_dc, y&1);
1382                     encode8x8(tag, b2.u, has_dc, c&2);
1383                     encode8x8(tag, b2.v, has_dc, c&1);
1384                 }
1385             }
1386         }
1387     }
1388     s->frame++;
1389 }
1390
1391 #define TESTS
1392 #ifdef TESTS
1393 void test_copy_diff()
1394 {
1395     VIDEOSTREAM stream;
1396     VIDEOSTREAM* s = &stream;
1397     TAG*tag;
1398     RGBA*pic = malloc(256*256*sizeof(RGBA));
1399     block_t fb;
1400     int x,y;
1401     int bx,by;
1402     for(x=0;x<256;x++)
1403     for(y=0;y<256;y++) {
1404         pic[y*256+x].r = x*y;
1405         pic[y*256+x].g = x+y;
1406         pic[y*256+x].b = (x+1)%(y+1);
1407     }
1408     tag = swf_InsertTag(0, ST_DEFINEVIDEOSTREAM);
1409     swf_SetU16(tag, 33);
1410     swf_SetVideoStreamDefine(tag, s, 10, 256, 256);
1411     
1412     rgb2yuv(s->current, pic, s->linex, s->olinex, s->owidth, s->oheight);
1413     for(by=0;by<16;by++)
1414     for(bx=0;bx<16;bx++) {
1415         int diff1,diff2;
1416         /* test1: does compare pic pic return zero for identical blocks? */
1417         diff1 = compare_pic_pic(s, s->current, s->current, bx, by);
1418         assert(!diff1);
1419         /* test2: do blocks which are copied back return zero diff? */
1420         getregion(&fb, s->current, bx, by, s->linex);
1421         copy_block_pic(s, s->oldpic, &fb, bx, by);
1422         diff1 = compare_pic_block(s, &fb, s->oldpic, bx, by);
1423         assert(!diff1);
1424         /* test3: does compare_pic_block return the same result as compare_pic_pic? */
1425         getregion(&fb, s->current, 15-bx, 15-by, s->linex);
1426         copy_block_pic(s, s->oldpic, &fb, bx, by);
1427         diff1 = compare_pic_block(s, &fb, s->current, bx, by);
1428         diff2 = compare_pic_pic(s, s->current, s->oldpic, bx, by);
1429         assert(diff1 == diff2);
1430     }
1431 }
1432
1433 #endif
1434
1435 #ifdef MAIN
1436 #include "png.h"
1437
1438 int compileSWFActionCode(const char *script, int version, void**data, int*len) {return 0;}
1439
1440 void mkblack()
1441 {
1442     SWF swf;
1443     SWFPLACEOBJECT obj;
1444     int frames = 88;
1445     int width = 160;
1446     int height = 112;
1447     int x,y;
1448     TAG*tag = 0;
1449     RGBA rgb;
1450     RGBA* pic = 0;
1451     VIDEOSTREAM stream;
1452    
1453     pic = malloc(width*height*4);
1454     memset(pic, 0, width*height*4);
1455
1456     memset(&swf,0,sizeof(SWF));
1457     memset(&obj,0,sizeof(obj));
1458
1459     swf.fileVersion    = 6;
1460     swf.frameRate      = 15*256;
1461     swf.movieSize.xmax = 20*width;
1462     swf.movieSize.ymax = 20*height;
1463
1464     swf.firstTag = swf_InsertTag(NULL,ST_SETBACKGROUNDCOLOR);
1465     tag = swf.firstTag;
1466     rgb.r = 0x00;rgb.g = 0x30;rgb.b = 0xff;
1467     swf_SetRGB(tag,&rgb);
1468
1469     tag = swf_InsertTag(tag, ST_DEFINEVIDEOSTREAM);
1470     swf_SetU16(tag, 1);
1471     swf_SetVideoStreamDefine(tag, &stream, frames, width, height);
1472     stream.do_motion = 0;
1473
1474     for(y=0;y<height;y++)  {
1475         for(x=0;x<width;x++) {
1476             int dx = x/16;
1477             int dy = y/16;
1478
1479             pic[y*width+x].r = 0;
1480             pic[y*width+x].g = 0;
1481             pic[y*width+x].b = 0;
1482             pic[y*width+x].a = 0;
1483         }
1484     }
1485     tag = swf_InsertTag(tag, ST_VIDEOFRAME);
1486     swf_SetU16(tag, 1);
1487     
1488     swf_SetVideoStreamIFrame(tag, &stream, pic, 7);
1489
1490     tag = swf_InsertTag(tag, ST_PLACEOBJECT2);
1491     swf_GetPlaceObject(0, &obj);
1492     
1493     obj.depth = 4;
1494     obj.id = 1;
1495     
1496     swf_SetPlaceObject(tag,&obj);
1497
1498     tag = swf_InsertTag(tag, ST_SHOWFRAME);
1499     
1500     swf_VideoStreamClear(&stream);
1501
1502     tag = swf_InsertTag(tag, ST_END);
1503
1504     int fi = open("black.swf", O_WRONLY|O_CREAT|O_TRUNC, 0644);
1505     if(swf_WriteSWC(fi,&swf)<0) {
1506         fprintf(stderr,"WriteSWF() failed.\n");
1507     }
1508     close(fi);
1509     swf_FreeTags(&swf);
1510 }
1511
1512 int main(int argn, char*argv[])
1513 {
1514     int fi;
1515     int t;
1516     SWF swf;
1517     TAG * tag;
1518     RGBA* pic, *pic2, rgb;
1519     SWFPLACEOBJECT obj;
1520     int width = 0;
1521     int height = 0;
1522     int frames = 10;
1523     int framerate = 29;
1524     unsigned char*data;
1525     char* fname = "/home/kramm/pics/peppers_fromjpg.png";
1526     //char* fname = "/home/kramm/pics/baboon.png";
1527     VIDEOSTREAM stream;
1528     double d = 1.0;
1529
1530 #ifdef TESTS
1531     test_copy_diff();
1532 #endif
1533
1534     mkblack();
1535
1536     memset(&stream, 0, sizeof(stream));
1537
1538     getPNG(fname, &width, &height, &data);
1539     pic = (RGBA*)malloc(width*height*sizeof(RGBA));
1540     pic2 = (RGBA*)malloc(width*height*sizeof(RGBA));
1541     memcpy(pic, data, width*height*sizeof(RGBA));
1542     free(data);
1543
1544     printf("Compressing %s, size %dx%d\n", fname, width, height);
1545
1546     memset(&swf,0,sizeof(SWF));
1547     memset(&obj,0,sizeof(obj));
1548
1549     swf.fileVersion    = 6;
1550     swf.frameRate      = framerate*256;
1551     swf.movieSize.xmax = 20*width*2;
1552     swf.movieSize.ymax = 20*height;
1553
1554     swf.firstTag = swf_InsertTag(NULL,ST_SETBACKGROUNDCOLOR);
1555     tag = swf.firstTag;
1556     rgb.r = 0x00;rgb.g = 0x30;rgb.b = 0xff;
1557     swf_SetRGB(tag,&rgb);
1558
1559     tag = swf_InsertTag(tag, ST_DEFINEVIDEOSTREAM);
1560     swf_SetU16(tag, 33);
1561     swf_SetVideoStreamDefine(tag, &stream, frames, width, height);
1562     stream.do_motion = 0;
1563
1564     //srand48(time(0));
1565
1566     for(t=0;t<frames;t++)
1567     {
1568         int x,y;
1569         double xx,yy;
1570         for(y=0,yy=0;y<height;y++,yy+=d)  {
1571             RGBA*line = &pic[((int)yy)*width];
1572             for(x=0,xx=0;x<width;x++,xx+=d) {
1573                 int dx = x/16;
1574                 int dy = y/16;
1575                 if(dx==0 && dy==0) {
1576                     pic2[y*width+x] = line[((int)xx)];
1577                     pic2[y*width+x].r+=2;
1578                     pic2[y*width+x].g+=2;
1579                     pic2[y*width+x].b+=2;
1580                 } else {
1581                     //pic2[y*width+x] = line[((int)xx)];
1582                     //pic2[y*width+x].r = lrand48();//line[((int)xx)];
1583                     //pic2[y*width+x].g = lrand48();//line[((int)xx)];
1584                     //pic2[y*width+x].b = lrand48();//line[((int)xx)];
1585                     pic2[y*width+x].r = 0;
1586                     pic2[y*width+x].g = 0;
1587                     pic2[y*width+x].b = 0;
1588                 }
1589                 /*if(dx==16 && dy==16) 
1590                     pic2[y*width+x] = pic[(y-16*16)*width+(x-16*16)];*/
1591                 /*if(dx<=0 && dy<=0) {
1592                     pic2[y*width+x] = line[((int)xx)];*/
1593                 /*if(x==0 && y==0) {
1594                     RGBA color;
1595                     memset(&color, 0, sizeof(RGBA));
1596                     pic2[y*width+x] = color;*/
1597                 /*} else  {
1598                     RGBA color;
1599                     color.r = lrand48();
1600                     color.g = lrand48();
1601                     color.b = lrand48();
1602                     color.a = 0;
1603                     pic2[y*width+x] = color;
1604                 }*/
1605             }
1606         }
1607         printf("frame:%d\n", t);fflush(stdout);
1608
1609         if(t==1)
1610             break;
1611
1612         tag = swf_InsertTag(tag, ST_VIDEOFRAME);
1613         swf_SetU16(tag, 33);
1614         if(t==0)
1615             swf_SetVideoStreamIFrame(tag, &stream, pic2, 7);
1616         else {
1617             swf_SetVideoStreamPFrame(tag, &stream, pic2, 7);
1618         }
1619
1620         tag = swf_InsertTag(tag, ST_PLACEOBJECT2);
1621         swf_GetPlaceObject(0, &obj);
1622         if(t==0) {
1623             obj.depth = 1;
1624             obj.id = 33;
1625         } else {
1626             obj.move = 1;
1627             obj.depth = 1;
1628             obj.ratio = t;
1629         }
1630         swf_SetPlaceObject(tag,&obj);
1631
1632         tag = swf_InsertTag(tag, ST_SHOWFRAME);
1633         d-=0.015;
1634     }
1635     swf_VideoStreamClear(&stream);
1636
1637     tag = swf_InsertTag(tag, ST_END);
1638
1639     fi = open("video3.swf", O_WRONLY|O_CREAT|O_TRUNC, 0644);
1640     if(swf_WriteSWC(fi,&swf)<0) {
1641         fprintf(stderr,"WriteSWF() failed.\n");
1642     }
1643     close(fi);
1644     swf_FreeTags(&swf);
1645     return 0;
1646 }
1647 #undef MAIN
1648 #endif