mpeg4 b-frames :)
[ffmpeg.git] / libavcodec / h263.c
1 /*
2  * H263/MPEG4 backend for ffmpeg encoder and decoder
3  * Copyright (c) 2000,2001 Gerard Lantau.
4  * H263+ support.
5  * Copyright (c) 2001 Juan J. Sierralta P.
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20  */
21 #include "common.h"
22 #include "dsputil.h"
23 #include "avcodec.h"
24 #include "mpegvideo.h"
25 #include "h263data.h"
26 #include "mpeg4data.h"
27
28 //rounded divison & shift
29 #define RDIV(a,b) ((a) > 0 ? ((a)+((b)>>1))/(b) : ((a)-((b)>>1))/(b))
30 #define RSHIFT(a,b) ((a) > 0 ? ((a) + (1<<((b)-1)))>>(b) : ((a) + (1<<((b)-1))-1)>>(b))
31
32 static void h263_encode_block(MpegEncContext * s, DCTELEM * block,
33                               int n);
34 static void h263_encode_motion(MpegEncContext * s, int val);
35 static void h263p_encode_umotion(MpegEncContext * s, int val);
36 static void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block,
37                                int n);
38 static int h263_decode_motion(MpegEncContext * s, int pred, int fcode);
39 static int h263p_decode_umotion(MpegEncContext * s, int pred);
40 static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
41                              int n, int coded);
42 static int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
43                               int n, int coded);
44
45 int h263_get_picture_format(int width, int height)
46 {
47     int format;
48
49     if (width == 128 && height == 96)
50         format = 1;
51     else if (width == 176 && height == 144)
52         format = 2;
53     else if (width == 352 && height == 288)
54         format = 3;
55     else if (width == 704 && height == 576)
56         format = 4;
57     else if (width == 1408 && height == 1152)
58         format = 5;
59     else
60         format = 7;
61     return format;
62 }
63
64 void h263_encode_picture_header(MpegEncContext * s, int picture_number)
65 {
66     int format;
67
68     align_put_bits(&s->pb);
69
70     /* Update the pointer to last GOB */
71     s->ptr_lastgob = pbBufPtr(&s->pb);
72     s->gob_number = 0;
73
74     put_bits(&s->pb, 22, 0x20); /* PSC */
75     put_bits(&s->pb, 8, (((INT64)s->picture_number * 30 * FRAME_RATE_BASE) / 
76                          s->frame_rate) & 0xff);
77
78     put_bits(&s->pb, 1, 1);     /* marker */
79     put_bits(&s->pb, 1, 0);     /* h263 id */
80     put_bits(&s->pb, 1, 0);     /* split screen off */
81     put_bits(&s->pb, 1, 0);     /* camera  off */
82     put_bits(&s->pb, 1, 0);     /* freeze picture release off */
83     
84     format = h263_get_picture_format(s->width, s->height);
85     if (!s->h263_plus) {
86         /* H.263v1 */
87         put_bits(&s->pb, 3, format);
88         put_bits(&s->pb, 1, (s->pict_type == P_TYPE));
89         /* By now UMV IS DISABLED ON H.263v1, since the restrictions
90         of H.263v1 UMV implies to check the predicted MV after
91         calculation of the current MB to see if we're on the limits */
92         put_bits(&s->pb, 1, 0); /* unrestricted motion vector: off */
93         put_bits(&s->pb, 1, 0); /* SAC: off */
94         put_bits(&s->pb, 1, 0); /* advanced prediction mode: off */
95         put_bits(&s->pb, 1, 0); /* not PB frame */
96         put_bits(&s->pb, 5, s->qscale);
97         put_bits(&s->pb, 1, 0); /* Continuous Presence Multipoint mode: off */
98     } else {
99         /* H.263v2 */
100         /* H.263 Plus PTYPE */
101         put_bits(&s->pb, 3, 7);
102         put_bits(&s->pb,3,1); /* Update Full Extended PTYPE */
103         if (format == 7)
104             put_bits(&s->pb,3,6); /* Custom Source Format */
105         else
106             put_bits(&s->pb, 3, format);
107             
108         put_bits(&s->pb,1,0); /* Custom PCF: off */
109         s->umvplus = (s->pict_type == P_TYPE) && s->unrestricted_mv;
110         put_bits(&s->pb, 1, s->umvplus); /* Unrestricted Motion Vector */
111         put_bits(&s->pb,1,0); /* SAC: off */
112         put_bits(&s->pb,1,0); /* Advanced Prediction Mode: off */
113         put_bits(&s->pb,1,0); /* Advanced Intra Coding: off */
114         put_bits(&s->pb,1,0); /* Deblocking Filter: off */
115         put_bits(&s->pb,1,0); /* Slice Structured: off */
116         put_bits(&s->pb,1,0); /* Reference Picture Selection: off */
117         put_bits(&s->pb,1,0); /* Independent Segment Decoding: off */
118         put_bits(&s->pb,1,0); /* Alternative Inter VLC: off */
119         put_bits(&s->pb,1,0); /* Modified Quantization: off */
120         put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
121         put_bits(&s->pb,3,0); /* Reserved */
122                 
123         put_bits(&s->pb, 3, s->pict_type == P_TYPE);
124                 
125         put_bits(&s->pb,1,0); /* Reference Picture Resampling: off */
126         put_bits(&s->pb,1,0); /* Reduced-Resolution Update: off */
127         put_bits(&s->pb,1,0); /* Rounding Type */
128         put_bits(&s->pb,2,0); /* Reserved */
129         put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
130                 
131         /* This should be here if PLUSPTYPE */
132         put_bits(&s->pb, 1, 0); /* Continuous Presence Multipoint mode: off */
133                 
134                 if (format == 7) {
135             /* Custom Picture Format (CPFMT) */
136                 
137             put_bits(&s->pb,4,2); /* Aspect ratio: CIF 12:11 (4:3) picture */
138             put_bits(&s->pb,9,(s->width >> 2) - 1);
139             put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
140             put_bits(&s->pb,9,(s->height >> 2));
141         }
142         
143         /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
144         if (s->umvplus)
145             put_bits(&s->pb,1,1); /* Limited according tables of Annex D */
146         put_bits(&s->pb, 5, s->qscale);
147     }
148
149     put_bits(&s->pb, 1, 0);     /* no PEI */
150 }
151
152 int h263_encode_gob_header(MpegEncContext * s, int mb_line)
153 {
154     int pdif=0;
155     
156     /* Check to see if we need to put a new GBSC */
157     /* for RTP packetization                    */
158     if (s->rtp_mode) {
159         pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
160         if (pdif >= s->rtp_payload_size) {
161             /* Bad luck, packet must be cut before */
162             align_put_bits(&s->pb);
163             flush_put_bits(&s->pb);
164             /* Call the RTP callback to send the last GOB */
165             if (s->rtp_callback) {
166                 pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
167                 s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
168             }
169             s->ptr_lastgob = pbBufPtr(&s->pb);
170             put_bits(&s->pb, 17, 1); /* GBSC */
171             s->gob_number = mb_line / s->gob_index;
172             put_bits(&s->pb, 5, s->gob_number); /* GN */
173             put_bits(&s->pb, 2, s->pict_type == I_TYPE); /* GFID */
174             put_bits(&s->pb, 5, s->qscale); /* GQUANT */
175             //fprintf(stderr,"\nGOB: %2d size: %d", s->gob_number - 1, pdif);
176             return pdif;
177        } else if (pdif + s->mb_line_avgsize >= s->rtp_payload_size) {
178            /* Cut the packet before we can't */
179            align_put_bits(&s->pb);
180            flush_put_bits(&s->pb);
181            /* Call the RTP callback to send the last GOB */
182            if (s->rtp_callback) {
183                pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
184                s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
185            }
186            s->ptr_lastgob = pbBufPtr(&s->pb);
187            put_bits(&s->pb, 17, 1); /* GBSC */
188            s->gob_number = mb_line / s->gob_index;
189            put_bits(&s->pb, 5, s->gob_number); /* GN */
190            put_bits(&s->pb, 2, s->pict_type == I_TYPE); /* GFID */
191            put_bits(&s->pb, 5, s->qscale); /* GQUANT */
192            //fprintf(stderr,"\nGOB: %2d size: %d", s->gob_number - 1, pdif);
193            return pdif;
194        }
195    }
196    return 0;
197 }
198     
199 void h263_encode_mb(MpegEncContext * s,
200                     DCTELEM block[6][64],
201                     int motion_x, int motion_y)
202 {
203     int cbpc, cbpy, i, cbp, pred_x, pred_y;
204    
205     //    printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
206    if (!s->mb_intra) {
207            /* compute cbp */
208            cbp = 0;
209            for (i = 0; i < 6; i++) {
210               if (s->block_last_index[i] >= 0)
211                    cbp |= 1 << (5 - i);
212            }
213            if ((cbp | motion_x | motion_y) == 0) {
214               /* skip macroblock */
215               put_bits(&s->pb, 1, 1);
216               return;
217            }
218            put_bits(&s->pb, 1, 0);      /* mb coded */
219            cbpc = cbp & 3;
220            put_bits(&s->pb,
221                 inter_MCBPC_bits[cbpc],
222                 inter_MCBPC_code[cbpc]);
223            cbpy = cbp >> 2;
224            cbpy ^= 0xf;
225            put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
226
227            /* motion vectors: 16x16 mode only now */
228       h263_pred_motion(s, 0, &pred_x, &pred_y);
229       
230       if (!s->umvplus) {  
231          h263_encode_motion(s, motion_x - pred_x);
232          h263_encode_motion(s, motion_y - pred_y);
233       }
234       else {
235          h263p_encode_umotion(s, motion_x - pred_x);
236          h263p_encode_umotion(s, motion_y - pred_y);
237          if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
238             /* To prevent Start Code emulation */
239             put_bits(&s->pb,1,1);
240       }
241    } else {
242         /* compute cbp */
243         cbp = 0;
244         for (i = 0; i < 6; i++) {
245             if (s->block_last_index[i] >= 1)
246                 cbp |= 1 << (5 - i);
247         }
248
249         cbpc = cbp & 3;
250         if (s->pict_type == I_TYPE) {
251             put_bits(&s->pb,
252                      intra_MCBPC_bits[cbpc],
253                      intra_MCBPC_code[cbpc]);
254         } else {
255             put_bits(&s->pb, 1, 0);     /* mb coded */
256             put_bits(&s->pb,
257                      inter_MCBPC_bits[cbpc + 4],
258                      inter_MCBPC_code[cbpc + 4]);
259         }
260         if (s->h263_pred) {
261             /* XXX: currently, we do not try to use ac prediction */
262             put_bits(&s->pb, 1, 0);     /* no ac prediction */
263         }
264         cbpy = cbp >> 2;
265         put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
266     }
267
268     /* encode each block */
269     if (s->h263_pred) {
270         for (i = 0; i < 6; i++) {
271             mpeg4_encode_block(s, block[i], i);
272         }
273     } else {
274         for (i = 0; i < 6; i++) {
275             h263_encode_block(s, block[i], i);
276         }
277     }
278 }
279
280
281 void h263_pred_acdc(MpegEncContext * s, INT16 *block, int n)
282 {
283     int x, y, wrap, a, c, pred_dc, scale, i;
284     INT16 *dc_val, *ac_val, *ac_val1;
285
286     /* find prediction */
287     if (n < 4) {
288         x = 2 * s->mb_x + 1 + (n & 1);
289         y = 2 * s->mb_y + 1 + ((n & 2) >> 1);
290         wrap = s->mb_width * 2 + 2;
291         dc_val = s->dc_val[0];
292         ac_val = s->ac_val[0][0];
293         scale = s->y_dc_scale;
294     } else {
295         x = s->mb_x + 1;
296         y = s->mb_y + 1;
297         wrap = s->mb_width + 2;
298         dc_val = s->dc_val[n - 4 + 1];
299         ac_val = s->ac_val[n - 4 + 1][0];
300         scale = s->c_dc_scale;
301     }
302     
303     ac_val += ((y) * wrap + (x)) * 16;
304     ac_val1 = ac_val;
305     
306     /* B C
307      * A X 
308      */
309     a = dc_val[(x - 1) + (y) * wrap];
310     c = dc_val[(x) + (y - 1) * wrap];
311     
312     pred_dc = 1024;
313     if (s->ac_pred) {
314         if (s->h263_aic_dir) {
315             /* left prediction */
316             if (a != 1024) {
317                 ac_val -= 16;
318                 for(i=1;i<8;i++) {
319                     block[block_permute_op(i*8)] += ac_val[i];
320                 }
321                 pred_dc = a;
322             }
323         } else {
324             /* top prediction */
325             if (c != 1024) {
326                 ac_val -= 16 * wrap;
327                 for(i=1;i<8;i++) {
328                     block[block_permute_op(i)] += ac_val[i + 8];
329                 }
330                 pred_dc = c;
331             }
332         }
333     } else {
334         /* just DC prediction */
335         if (a != 1024 && c != 1024)
336             pred_dc = (a + c) >> 1;
337         else if (a != 1024)
338             pred_dc = a;
339         else
340             pred_dc = c;
341     }
342     
343     /* we assume pred is positive */
344     block[0]=block[0]*scale + pred_dc;
345     
346     if (block[0] < 0)
347         block[0] = 0;
348     else if (!(block[0] & 1))
349         block[0]++;
350     
351     /* Update AC/DC tables */
352     dc_val[(x) + (y) * wrap] = block[0];
353     
354     /* left copy */
355     for(i=1;i<8;i++)
356         ac_val1[i] = block[block_permute_op(i * 8)];
357     /* top copy */
358     for(i=1;i<8;i++)
359         ac_val1[8 + i] = block[block_permute_op(i)];
360 }
361
362
363 static inline int mid_pred(int a, int b, int c)
364 {
365     int vmin, vmax;
366     vmax = vmin = a;
367     if (b < vmin)
368         vmin = b;
369     else
370         vmax = b;
371
372     if (c < vmin)
373         vmin = c;
374     else if (c > vmax)
375         vmax = c;
376
377     return a + b + c - vmin - vmax;
378 }
379
380 INT16 *h263_pred_motion(MpegEncContext * s, int block, 
381                         int *px, int *py)
382 {
383     int xy, y, wrap;
384     INT16 *A, *B, *C, *mot_val;
385
386     wrap = 2 * s->mb_width + 2;
387     y = xy = 2 * s->mb_y + 1 + ((block >> 1) & 1); // y
388     xy *= wrap; // y * wrap
389     xy += 2 * s->mb_x + 1 + (block & 1); // x + y * wrap
390
391     mot_val = s->motion_val[xy];
392
393     /* special case for first line */
394     if (y == 1 || s->first_slice_line || s->first_gob_line) {
395         A = s->motion_val[xy - 1];
396         *px = A[0];
397         *py = A[1];
398     } else {
399         switch(block) {
400         default:
401         case 0:
402             A = s->motion_val[xy - 1];
403             B = s->motion_val[xy - wrap];
404             C = s->motion_val[xy + 2 - wrap];
405             break;
406         case 1:
407         case 2:
408             A = s->motion_val[xy - 1];
409             B = s->motion_val[xy - wrap];
410             C = s->motion_val[xy + 1 - wrap];
411             break;
412         case 3:
413             A = s->motion_val[xy - 1];
414             B = s->motion_val[xy - 1 - wrap];
415             C = s->motion_val[xy - wrap];
416             break;
417         }
418         *px = mid_pred(A[0], B[0], C[0]);
419         *py = mid_pred(A[1], B[1], C[1]);
420     }
421     return mot_val;
422 }
423
424 static void h263_encode_motion(MpegEncContext * s, int val)
425 {
426     int range, l, m, bit_size, sign, code, bits;
427
428     if (val == 0) {
429         /* zero vector */
430         code = 0;
431         put_bits(&s->pb, mvtab[code][1], mvtab[code][0]);
432     } else {
433         bit_size = s->f_code - 1;
434         range = 1 << bit_size;
435         /* modulo encoding */
436         l = range * 32;
437         m = 2 * l;
438         if (val < -l) {
439             val += m;
440         } else if (val >= l) {
441             val -= m;
442         }
443
444         if (val >= 0) {
445             val--;
446             code = (val >> bit_size) + 1;
447             bits = val & (range - 1);
448             sign = 0;
449         } else {
450             val = -val;
451             val--;
452             code = (val >> bit_size) + 1;
453             bits = val & (range - 1);
454             sign = 1;
455         }
456
457         put_bits(&s->pb, mvtab[code][1] + 1, (mvtab[code][0] << 1) | sign); 
458         if (bit_size > 0) {
459             put_bits(&s->pb, bit_size, bits);
460         }
461     }
462 }
463
464 /* Encode MV differences on H.263+ with Unrestricted MV mode */
465 static void h263p_encode_umotion(MpegEncContext * s, int val)
466 {
467     short sval = 0; 
468     short i = 0;
469     short n_bits = 0;
470     short temp_val;
471     int code = 0;
472     int tcode;
473     
474     if ( val == 0)
475         put_bits(&s->pb, 1, 1);
476     else if (val == 1)
477         put_bits(&s->pb, 3, 0);
478     else if (val == -1)
479         put_bits(&s->pb, 3, 2);
480     else {
481         
482         sval = ((val < 0) ? (short)(-val):(short)val);
483         temp_val = sval;
484         
485         while (temp_val != 0) {
486             temp_val = temp_val >> 1;
487             n_bits++;
488         }
489         
490         i = n_bits - 1;
491         while (i > 0) {
492             tcode = (sval & (1 << (i-1))) >> (i-1);
493             tcode = (tcode << 1) | 1;
494             code = (code << 2) | tcode;
495             i--;
496         }
497         code = ((code << 1) | (val < 0)) << 1;
498         put_bits(&s->pb, (2*n_bits)+1, code);
499         //printf("\nVal = %d\tCode = %d", sval, code);
500     }
501 }
502
503 void h263_encode_init_vlc(MpegEncContext *s)
504 {
505     static int done = 0;
506
507     if (!done) {
508         done = 1;
509         init_rl(&rl_inter);
510         init_rl(&rl_intra);
511     }
512 }
513
514 static void h263_encode_block(MpegEncContext * s, DCTELEM * block, int n)
515 {
516     int level, run, last, i, j, last_index, last_non_zero, sign, slevel;
517     int code;
518     RLTable *rl = &rl_inter;
519
520     if (s->mb_intra) {
521         /* DC coef */
522             level = block[0];
523         /* 255 cannot be represented, so we clamp */
524         if (level > 254) {
525             level = 254;
526             block[0] = 254;
527         }
528         /* 0 cannot be represented also */
529         else if (!level) {
530             level = 1;
531             block[0] = 1;
532         }
533             if (level == 128)
534                 put_bits(&s->pb, 8, 0xff);
535             else
536                 put_bits(&s->pb, 8, level & 0xff);
537             i = 1;
538     } else {
539             i = 0;
540     }
541
542     /* AC coefs */
543     last_index = s->block_last_index[n];
544     last_non_zero = i - 1;
545     for (; i <= last_index; i++) {
546         j = zigzag_direct[i];
547         level = block[j];
548         if (level) {
549             run = i - last_non_zero - 1;
550             last = (i == last_index);
551             sign = 0;
552             slevel = level;
553             if (level < 0) {
554                 sign = 1;
555                 level = -level;
556             }
557             code = get_rl_index(rl, last, run, level);
558             put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
559             if (code == rl->n) {
560                 put_bits(&s->pb, 1, last);
561                 put_bits(&s->pb, 6, run);
562                 put_bits(&s->pb, 8, slevel & 0xff);
563             } else {
564                 put_bits(&s->pb, 1, sign);
565             }
566             last_non_zero = i;
567         }
568     }
569 }
570
571 /***************************************************/
572
573 static void mpeg4_stuffing(PutBitContext * pbc)
574 {
575     int length;
576     put_bits(pbc, 1, 0);
577     length= (-get_bit_count(pbc))&7;
578     put_bits(pbc, length, (1<<length)-1);
579 }
580
581 static void put_string(PutBitContext * pbc, char *s)
582 {
583     while(*s){
584         put_bits(pbc, 8, *s);
585         s++;
586     }
587     put_bits(pbc, 8, 0);
588 }
589
590 /* write mpeg4 VOP header */
591 void mpeg4_encode_picture_header(MpegEncContext * s, int picture_number)
592 {
593     mpeg4_stuffing(&s->pb);
594     put_bits(&s->pb, 16, 0);
595     put_bits(&s->pb, 16, 0x1B2);        /* user_data */
596     put_string(&s->pb, "ffmpeg"); //FIXME append some version ...
597     
598     mpeg4_stuffing(&s->pb);
599     put_bits(&s->pb, 16, 0);            /* vop header */
600     put_bits(&s->pb, 16, 0x1B6);        /* vop header */
601     put_bits(&s->pb, 2, s->pict_type - 1);      /* pict type: I = 0 , P = 1 */
602     /* XXX: time base + 1 not always correct */
603     put_bits(&s->pb, 1, 1);
604     put_bits(&s->pb, 1, 0);
605
606     put_bits(&s->pb, 1, 1);     /* marker */
607     put_bits(&s->pb, 4, 1);     /* XXX: correct time increment */
608     put_bits(&s->pb, 1, 1);     /* marker */
609     put_bits(&s->pb, 1, 1);     /* vop coded */
610     if (s->pict_type == P_TYPE) {
611         s->no_rounding = 0;
612         put_bits(&s->pb, 1, s->no_rounding);    /* rounding type */
613     }
614     put_bits(&s->pb, 3, 0);     /* intra dc VLC threshold */
615
616     put_bits(&s->pb, 5, s->qscale);
617
618     if (s->pict_type != I_TYPE)
619         put_bits(&s->pb, 3, s->f_code); /* fcode_for */
620     //    printf("****frame %d\n", picture_number);
621 }
622
623 void h263_dc_scale(MpegEncContext * s)
624 {
625     int quant;
626
627     quant = s->qscale;
628     /* luminance */
629     if (quant < 5)
630         s->y_dc_scale = 8;
631     else if (quant > 4 && quant < 9)
632         s->y_dc_scale = (2 * quant);
633     else if (quant > 8 && quant < 25)
634         s->y_dc_scale = (quant + 8);
635     else
636         s->y_dc_scale = (2 * quant - 16);
637     /* chrominance */
638     if (quant < 5)
639         s->c_dc_scale = 8;
640     else if (quant > 4 && quant < 25)
641         s->c_dc_scale = ((quant + 13) / 2);
642     else
643         s->c_dc_scale = (quant - 6);
644 }
645
646 static int mpeg4_pred_dc(MpegEncContext * s, int n, UINT16 **dc_val_ptr, int *dir_ptr)
647 {
648     int a, b, c, xy, wrap, pred, scale;
649     UINT16 *dc_val;
650
651     /* find prediction */
652     if (n < 4) {
653         wrap = s->mb_width * 2 + 2;
654         xy = 2 * s->mb_y + 1 + ((n & 2) >> 1);
655         xy *= wrap;
656         xy += 2 * s->mb_x + 1 + (n & 1);
657         dc_val = s->dc_val[0];
658         scale = s->y_dc_scale;
659     } else {
660         wrap = s->mb_width + 2;
661         xy = s->mb_y + 1;
662         xy *= wrap;
663         xy += s->mb_x + 1;
664         dc_val = s->dc_val[n - 4 + 1];
665         scale = s->c_dc_scale;
666     }
667
668     /* B C
669      * A X 
670      */
671     a = dc_val[xy - 1];
672     b = dc_val[xy - 1 - wrap];
673     c = dc_val[xy - wrap];
674
675     if (abs(a - b) < abs(b - c)) {
676         pred = c;
677         *dir_ptr = 1; /* top */
678     } else {
679         pred = a;
680         *dir_ptr = 0; /* left */
681     }
682     /* we assume pred is positive */
683     pred = (pred + (scale >> 1)) / scale;
684
685     /* prepare address for prediction update */
686     *dc_val_ptr = &dc_val[xy];
687
688     return pred;
689 }
690
691 void mpeg4_pred_ac(MpegEncContext * s, INT16 *block, int n,
692                    int dir)
693 {
694     int x, y, wrap, i;
695     INT16 *ac_val, *ac_val1;
696
697     /* find prediction */
698     if (n < 4) {
699         x = 2 * s->mb_x + 1 + (n & 1);
700         y = 2 * s->mb_y + 1 + ((n & 2) >> 1);
701         wrap = s->mb_width * 2 + 2;
702         ac_val = s->ac_val[0][0];
703     } else {
704         x = s->mb_x + 1;
705         y = s->mb_y + 1;
706         wrap = s->mb_width + 2;
707         ac_val = s->ac_val[n - 4 + 1][0];
708     }
709     ac_val += ((y) * wrap + (x)) * 16;
710     ac_val1 = ac_val;
711     if (s->ac_pred) {
712         if (dir == 0) {
713             /* left prediction */
714             ac_val -= 16;
715             for(i=1;i<8;i++) {
716                 block[block_permute_op(i*8)] += ac_val[i];
717             }
718         } else {
719             /* top prediction */
720             ac_val -= 16 * wrap;
721             for(i=1;i<8;i++) {
722                 block[block_permute_op(i)] += ac_val[i + 8];
723             }
724         }
725     }
726     /* left copy */
727     for(i=1;i<8;i++)
728         ac_val1[i] = block[block_permute_op(i * 8)];
729     /* top copy */
730     for(i=1;i<8;i++)
731         ac_val1[8 + i] = block[block_permute_op(i)];
732 }
733
734 static inline void mpeg4_encode_dc(MpegEncContext * s, int level, int n, int *dir_ptr)
735 {
736     int size, v, pred;
737     UINT16 *dc_val;
738
739     pred = mpeg4_pred_dc(s, n, &dc_val, dir_ptr);
740     if (n < 4) {
741         *dc_val = level * s->y_dc_scale;
742     } else {
743         *dc_val = level * s->c_dc_scale;
744     }
745
746     /* do the prediction */
747     level -= pred;
748     /* find number of bits */
749     size = 0;
750     v = abs(level);
751     while (v) {
752         v >>= 1;
753         size++;
754     }
755
756     if (n < 4) {
757         /* luminance */
758         put_bits(&s->pb, DCtab_lum[size][1], DCtab_lum[size][0]);
759     } else {
760         /* chrominance */
761         put_bits(&s->pb, DCtab_chrom[size][1], DCtab_chrom[size][0]);
762     }
763
764     /* encode remaining bits */
765     if (size > 0) {
766         if (level < 0)
767             level = (-level) ^ ((1 << size) - 1);
768         put_bits(&s->pb, size, level);
769         if (size > 8)
770             put_bits(&s->pb, 1, 1);
771     }
772 }
773
774 static void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block, int n)
775 {
776     int level, run, last, i, j, last_index, last_non_zero, sign, slevel;
777     int code, dc_pred_dir;
778     const RLTable *rl;
779
780     if (s->mb_intra) {
781         /* mpeg4 based DC predictor */
782         mpeg4_encode_dc(s, block[0], n, &dc_pred_dir);
783         i = 1;
784         rl = &rl_intra;
785     } else {
786         i = 0;
787         rl = &rl_inter;
788     }
789
790     /* AC coefs */
791     last_index = s->block_last_index[n];
792     last_non_zero = i - 1;
793     for (; i <= last_index; i++) {
794         j = zigzag_direct[i];
795         level = block[j];
796         if (level) {
797             run = i - last_non_zero - 1;
798             last = (i == last_index);
799             sign = 0;
800             slevel = level;
801             if (level < 0) {
802                 sign = 1;
803                 level = -level;
804             }
805             code = get_rl_index(rl, last, run, level);
806             put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
807             if (code == rl->n) {
808                 int level1, run1;
809                 level1 = level - rl->max_level[last][run];
810                 if (level1 < 1) 
811                     goto esc2;
812                 code = get_rl_index(rl, last, run, level1);
813                 if (code == rl->n) {
814                 esc2:
815                     put_bits(&s->pb, 1, 1);
816                     if (level > MAX_LEVEL)
817                         goto esc3;
818                     run1 = run - rl->max_run[last][level] - 1;
819                     if (run1 < 0)
820                         goto esc3;
821                     code = get_rl_index(rl, last, run1, level);
822                     if (code == rl->n) {
823                     esc3:
824                         /* third escape */
825                         put_bits(&s->pb, 1, 1);
826                         put_bits(&s->pb, 1, last);
827                         put_bits(&s->pb, 6, run);
828                         put_bits(&s->pb, 1, 1);
829                         put_bits(&s->pb, 12, slevel & 0xfff);
830                         put_bits(&s->pb, 1, 1);
831                     } else {
832                         /* second escape */
833                         put_bits(&s->pb, 1, 0);
834                         put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
835                         put_bits(&s->pb, 1, sign);
836                     }
837                 } else {
838                     /* first escape */
839                     put_bits(&s->pb, 1, 0);
840                     put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
841                     put_bits(&s->pb, 1, sign);
842                 }
843             } else {
844                 put_bits(&s->pb, 1, sign);
845             }
846             last_non_zero = i;
847         }
848     }
849 }
850
851
852
853 /***********************************************/
854 /* decoding */
855
856 static VLC intra_MCBPC_vlc;
857 static VLC inter_MCBPC_vlc;
858 static VLC cbpy_vlc;
859 static VLC mv_vlc;
860 static VLC dc_lum, dc_chrom;
861 static VLC sprite_trajectory;
862 static VLC mb_type_b_vlc;
863
864 void init_rl(RLTable *rl)
865 {
866     INT8 max_level[MAX_RUN+1], max_run[MAX_LEVEL+1];
867     UINT8 index_run[MAX_RUN+1];
868     int last, run, level, start, end, i;
869
870     /* compute max_level[], max_run[] and index_run[] */
871     for(last=0;last<2;last++) {
872         if (last == 0) {
873             start = 0;
874             end = rl->last;
875         } else {
876             start = rl->last;
877             end = rl->n;
878         }
879
880         memset(max_level, 0, MAX_RUN + 1);
881         memset(max_run, 0, MAX_LEVEL + 1);
882         memset(index_run, rl->n, MAX_RUN + 1);
883         for(i=start;i<end;i++) {
884             run = rl->table_run[i];
885             level = rl->table_level[i];
886             if (index_run[run] == rl->n)
887                 index_run[run] = i;
888             if (level > max_level[run])
889                 max_level[run] = level;
890             if (run > max_run[level])
891                 max_run[level] = run;
892         }
893         rl->max_level[last] = malloc(MAX_RUN + 1);
894         memcpy(rl->max_level[last], max_level, MAX_RUN + 1);
895         rl->max_run[last] = malloc(MAX_LEVEL + 1);
896         memcpy(rl->max_run[last], max_run, MAX_LEVEL + 1);
897         rl->index_run[last] = malloc(MAX_RUN + 1);
898         memcpy(rl->index_run[last], index_run, MAX_RUN + 1);
899     }
900 }
901
902 void init_vlc_rl(RLTable *rl)
903 {
904     init_vlc(&rl->vlc, 9, rl->n + 1, 
905              &rl->table_vlc[0][1], 4, 2,
906              &rl->table_vlc[0][0], 4, 2);
907 }
908
909 /* init vlcs */
910
911 /* XXX: find a better solution to handle static init */
912 void h263_decode_init_vlc(MpegEncContext *s)
913 {
914     static int done = 0;
915
916     if (!done) {
917         done = 1;
918
919         init_vlc(&intra_MCBPC_vlc, 6, 8, 
920                  intra_MCBPC_bits, 1, 1,
921                  intra_MCBPC_code, 1, 1);
922         init_vlc(&inter_MCBPC_vlc, 9, 25, 
923                  inter_MCBPC_bits, 1, 1,
924                  inter_MCBPC_code, 1, 1);
925         init_vlc(&cbpy_vlc, 6, 16,
926                  &cbpy_tab[0][1], 2, 1,
927                  &cbpy_tab[0][0], 2, 1);
928         init_vlc(&mv_vlc, 9, 33,
929                  &mvtab[0][1], 2, 1,
930                  &mvtab[0][0], 2, 1);
931         init_rl(&rl_inter);
932         init_rl(&rl_intra);
933         init_rl(&rl_intra_aic);
934         init_vlc_rl(&rl_inter);
935         init_vlc_rl(&rl_intra);
936         init_vlc_rl(&rl_intra_aic);
937         init_vlc(&dc_lum, 9, 13,
938                  &DCtab_lum[0][1], 2, 1,
939                  &DCtab_lum[0][0], 2, 1);
940         init_vlc(&dc_chrom, 9, 13,
941                  &DCtab_chrom[0][1], 2, 1,
942                  &DCtab_chrom[0][0], 2, 1);
943         init_vlc(&sprite_trajectory, 9, 15,
944                  &sprite_trajectory_tab[0][1], 4, 2,
945                  &sprite_trajectory_tab[0][0], 4, 2);
946         init_vlc(&mb_type_b_vlc, 4, 4,
947                  &mb_type_b_tab[0][1], 2, 1,
948                  &mb_type_b_tab[0][0], 2, 1);
949     }
950 }
951
952 int h263_decode_gob_header(MpegEncContext *s)
953 {
954     unsigned int val, gfid;
955     
956     /* Check for GOB Start Code */
957     val = show_bits(&s->gb, 16);
958     if (val == 0) {
959         /* We have a GBSC probably with GSTUFF */
960         skip_bits(&s->gb, 16); /* Drop the zeros */
961         while (get_bits1(&s->gb) == 0); /* Seek the '1' bit */
962 #ifdef DEBUG
963         fprintf(stderr,"\nGOB Start Code at MB %d\n", (s->mb_y * s->mb_width) + s->mb_x);
964 #endif
965         s->gob_number = get_bits(&s->gb, 5); /* GN */
966         gfid = get_bits(&s->gb, 2); /* GFID */
967         s->qscale = get_bits(&s->gb, 5); /* GQUANT */
968 #ifdef DEBUG
969         fprintf(stderr, "\nGN: %u GFID: %u Quant: %u\n", s->gob_number, gfid, s->qscale);
970 #endif
971         return 1;
972     }
973     return 0;
974             
975 }
976
977 int h263_decode_mb(MpegEncContext *s,
978                    DCTELEM block[6][64])
979 {
980     int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
981     INT16 *mot_val;
982     static INT8 quant_tab[4] = { -1, -2, 1, 2 };
983     
984     if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
985         if (get_bits1(&s->gb)) {
986             /* skip mb */
987             s->mb_intra = 0;
988             for(i=0;i<6;i++)
989                 s->block_last_index[i] = -1;
990             s->mv_dir = MV_DIR_FORWARD;
991             s->mv_type = MV_TYPE_16X16;
992             if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
993                 const int a= s->sprite_warping_accuracy;
994 //                int l = (1 << (s->f_code - 1)) * 32;
995
996                 s->mcsel=1;
997                 s->mv[0][0][0] = RSHIFT(s->sprite_offset[0][0], a-s->quarter_sample);
998                 s->mv[0][0][1] = RSHIFT(s->sprite_offset[0][1], a-s->quarter_sample);
999 /*                if (s->mv[0][0][0] < -l) s->mv[0][0][0]= -l;
1000                 else if (s->mv[0][0][0] >= l) s->mv[0][0][0]= l-1;
1001                 if (s->mv[0][0][1] < -l) s->mv[0][0][1]= -l;
1002                 else if (s->mv[0][0][1] >= l) s->mv[0][0][1]= l-1;*/
1003
1004                 s->mb_skiped = 0;
1005             }else{
1006                 s->mcsel=0;
1007                 s->mv[0][0][0] = 0;
1008                 s->mv[0][0][1] = 0;
1009                 s->mb_skiped = 1;
1010             }
1011             return 0;
1012         }
1013         cbpc = get_vlc(&s->gb, &inter_MCBPC_vlc);
1014         //fprintf(stderr, "\tCBPC: %d", cbpc);
1015         if (cbpc < 0)
1016             return -1;
1017         if (cbpc > 20)
1018             cbpc+=3;
1019         else if (cbpc == 20)
1020             fprintf(stderr, "Stuffing !");
1021         
1022         dquant = cbpc & 8;
1023         s->mb_intra = ((cbpc & 4) != 0);
1024         if (s->mb_intra) goto intra;
1025         
1026         if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
1027             s->mcsel= get_bits1(&s->gb);
1028         else s->mcsel= 0;
1029         cbpy = get_vlc(&s->gb, &cbpy_vlc);
1030         cbp = (cbpc & 3) | ((cbpy ^ 0xf) << 2);
1031         if (dquant) {
1032             s->qscale += quant_tab[get_bits(&s->gb, 2)];
1033             if (s->qscale < 1)
1034                 s->qscale = 1;
1035             else if (s->qscale > 31)
1036                 s->qscale = 31;
1037         }
1038         s->mv_dir = MV_DIR_FORWARD;
1039         if ((cbpc & 16) == 0) {
1040             /* 16x16 motion prediction */
1041             s->mv_type = MV_TYPE_16X16;
1042             h263_pred_motion(s, 0, &pred_x, &pred_y);
1043             if (s->umvplus_dec)
1044                mx = h263p_decode_umotion(s, pred_x);
1045             else if(!s->mcsel)
1046                mx = h263_decode_motion(s, pred_x, s->f_code);
1047             else {
1048                const int a= s->sprite_warping_accuracy;
1049 //        int l = (1 << (s->f_code - 1)) * 32;
1050                mx= RSHIFT(s->sprite_offset[0][0], a-s->quarter_sample);
1051 //        if (mx < -l) mx= -l;
1052 //        else if (mx >= l) mx= l-1;
1053             }
1054             if (mx >= 0xffff)
1055                 return -1;
1056             
1057             if (s->umvplus_dec)
1058                my = h263p_decode_umotion(s, pred_y);
1059             else if(!s->mcsel)
1060                my = h263_decode_motion(s, pred_y, s->f_code);
1061             else{
1062                const int a= s->sprite_warping_accuracy;
1063 //       int l = (1 << (s->f_code - 1)) * 32;
1064                my= RSHIFT(s->sprite_offset[0][1], a-s->quarter_sample);
1065 //       if (my < -l) my= -l;
1066 //       else if (my >= l) my= l-1;
1067             }
1068             if (my >= 0xffff)
1069                 return -1;
1070             s->mv[0][0][0] = mx;
1071             s->mv[0][0][1] = my;
1072             /*fprintf(stderr, "\n MB %d", (s->mb_y * s->mb_width) + s->mb_x);
1073             fprintf(stderr, "\n\tmvx: %d\t\tpredx: %d", mx, pred_x);
1074             fprintf(stderr, "\n\tmvy: %d\t\tpredy: %d", my, pred_y);*/
1075             if (s->umvplus_dec && (mx - pred_x) == 1 && (my - pred_y) == 1)
1076                skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
1077                            
1078         } else {
1079             s->mv_type = MV_TYPE_8X8;
1080             for(i=0;i<4;i++) {
1081                 mot_val = h263_pred_motion(s, i, &pred_x, &pred_y);
1082                 if (s->umvplus_dec)
1083                   mx = h263p_decode_umotion(s, pred_x);
1084                 else
1085                   mx = h263_decode_motion(s, pred_x, s->f_code);
1086                 if (mx >= 0xffff)
1087                     return -1;
1088                 
1089                 if (s->umvplus_dec)
1090                   my = h263p_decode_umotion(s, pred_y);
1091                 else    
1092                   my = h263_decode_motion(s, pred_y, s->f_code);
1093                 if (my >= 0xffff)
1094                     return -1;
1095                 s->mv[0][i][0] = mx;
1096                 s->mv[0][i][1] = my;
1097                 if (s->umvplus_dec && (mx - pred_x) == 1 && (my - pred_y) == 1)
1098                   skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
1099                 mot_val[0] = mx;
1100                 mot_val[1] = my;
1101             }
1102         }
1103     } else if(s->pict_type==B_TYPE) {
1104         int modb1; // first bit of modb
1105         int modb2; // second bit of modb
1106         int mb_type;
1107         int time_pp;
1108         int time_pb;
1109         int xy;
1110
1111         s->mb_intra = 0; //B-frames never contain intra blocks
1112         s->mcsel=0;      //     ...               true gmc blocks
1113
1114         if(s->mb_x==0){
1115             s->last_mv[0][0][0]= 
1116             s->last_mv[0][0][1]= 
1117             s->last_mv[1][0][0]= 
1118             s->last_mv[1][0][1]= 0;
1119         }
1120
1121         /* if we skipped it in the future P Frame than skip it now too */
1122         s->mb_skiped= s->mbskip_table[s->mb_y * s->mb_width + s->mb_x]; // Note, skiptab=0 if last was GMC
1123
1124         if(s->mb_skiped){
1125                 /* skip mb */
1126             for(i=0;i<6;i++)
1127                 s->block_last_index[i] = -1;
1128
1129             s->mv_dir = MV_DIR_FORWARD;
1130             s->mv_type = MV_TYPE_16X16;
1131             s->mv[0][0][0] = 0;
1132             s->mv[0][0][1] = 0;
1133             s->mv[1][0][0] = 0;
1134             s->mv[1][0][1] = 0;
1135             s->last_mv[0][0][0]=
1136             s->last_mv[0][0][1]= 
1137             s->last_mv[1][0][0]= 
1138             s->last_mv[1][0][1]= 0;
1139             s->mb_skiped = 1;
1140             return 0;
1141         }
1142
1143         modb1= get_bits1(&s->gb);
1144         if(modb1==0){
1145             modb2= get_bits1(&s->gb);
1146             mb_type= get_vlc(&s->gb, &mb_type_b_vlc);
1147             if(modb2==0) cbp= get_bits(&s->gb, 6);
1148             else cbp=0;
1149             if (mb_type && cbp) {
1150                 if(get_bits1(&s->gb)){
1151                     s->qscale +=get_bits1(&s->gb)*4 - 2;
1152                     if (s->qscale < 1)
1153                         s->qscale = 1;
1154                     else if (s->qscale > 31)
1155                         s->qscale = 31;
1156                 }
1157             }
1158         }else{
1159             mb_type=4; //like 0 but no vectors coded
1160             cbp=0;
1161         }
1162         s->mv_type = MV_TYPE_16X16; // we'll switch to 8x8 only if the last P frame had 8x8 for this MB and mb_type=0 here
1163         mx=my=0; //for case 4, we could put this to the mb_type=4 but than gcc compains about uninitalized mx/my
1164         switch(mb_type)
1165         {
1166         case 0: 
1167             mx = h263_decode_motion(s, 0, 1);
1168             my = h263_decode_motion(s, 0, 1);
1169         case 4: 
1170             s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
1171             xy= (2*s->mb_width + 2)*(2*s->mb_y + 1) + 2*s->mb_x + 1;
1172             time_pp= s->last_non_b_time[0] - s->last_non_b_time[1];
1173             time_pb= s->time - s->last_non_b_time[1];
1174 //if(time_pp>3000 )printf("%d %d  ", time_pp, time_pb);
1175             //FIXME 4MV
1176             //FIXME avoid divides
1177             s->mv[0][0][0] = s->motion_val[xy][0]*time_pb/time_pp + mx;
1178             s->mv[0][0][1] = s->motion_val[xy][1]*time_pb/time_pp + my;
1179             s->mv[1][0][0] = mx ? s->mv[0][0][0] - s->motion_val[xy][0]
1180                                 : s->motion_val[xy][0]*(time_pb - time_pp)/time_pp + mx;
1181             s->mv[1][0][1] = my ? s->mv[0][0][1] - s->motion_val[xy][1] 
1182                                 : s->motion_val[xy][1]*(time_pb - time_pp)/time_pp + my;
1183 /*            s->mv[0][0][0] = 
1184             s->mv[0][0][1] = 
1185             s->mv[1][0][0] = 
1186             s->mv[1][0][1] = 1000;*/
1187             break;
1188         case 1: 
1189             s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
1190             mx = h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
1191             my = h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
1192             s->last_mv[0][0][0]= s->mv[0][0][0] = mx;
1193             s->last_mv[0][0][1]= s->mv[0][0][1] = my;
1194
1195             mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
1196             my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
1197             s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
1198             s->last_mv[1][0][1]= s->mv[1][0][1] = my;
1199             break;
1200         case 2: 
1201             s->mv_dir = MV_DIR_BACKWARD;
1202             mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
1203             my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
1204             s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
1205             s->last_mv[1][0][1]= s->mv[1][0][1] = my;
1206             break;
1207         case 3:
1208             s->mv_dir = MV_DIR_FORWARD;
1209             mx = h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
1210             my = h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
1211             s->last_mv[0][0][0]= s->mv[0][0][0] = mx;
1212             s->last_mv[0][0][1]= s->mv[0][0][1] = my;
1213             break;
1214         default: return -1;
1215         }
1216     } else { /* I-Frame */
1217         cbpc = get_vlc(&s->gb, &intra_MCBPC_vlc);
1218         if (cbpc < 0)
1219             return -1;
1220         dquant = cbpc & 4;
1221         s->mb_intra = 1;
1222 intra:
1223         s->ac_pred = 0;
1224         if (s->h263_pred || s->h263_aic) {
1225             s->ac_pred = get_bits1(&s->gb);
1226             if (s->ac_pred && s->h263_aic)
1227                 s->h263_aic_dir = get_bits1(&s->gb);
1228         }
1229         if (s->h263_aic) {
1230             s->y_dc_scale = 2 * s->qscale;
1231             s->c_dc_scale = 2 * s->qscale;
1232         }
1233         cbpy = get_vlc(&s->gb, &cbpy_vlc);
1234         cbp = (cbpc & 3) | (cbpy << 2);
1235         if (dquant) {
1236             s->qscale += quant_tab[get_bits(&s->gb, 2)];
1237             if (s->qscale < 1)
1238                 s->qscale = 1;
1239             else if (s->qscale > 31)
1240                 s->qscale = 31;
1241         }
1242     }
1243
1244     /* decode each block */
1245     if (s->h263_pred) {
1246         for (i = 0; i < 6; i++) {
1247             if (mpeg4_decode_block(s, block[i], i, (cbp >> (5 - i)) & 1) < 0)
1248                 return -1;
1249         }
1250     } else {
1251         for (i = 0; i < 6; i++) {
1252             if (h263_decode_block(s, block[i], i, (cbp >> (5 - i)) & 1) < 0)
1253                 return -1;
1254         }
1255     }
1256     return 0;
1257 }
1258
1259 static int h263_decode_motion(MpegEncContext * s, int pred, int f_code)
1260 {
1261     int code, val, sign, shift, l, m;
1262
1263     code = get_vlc(&s->gb, &mv_vlc);
1264     if (code < 0)
1265         return 0xffff;
1266
1267     if (code == 0)
1268         return pred;
1269     sign = get_bits1(&s->gb);
1270     shift = f_code - 1;
1271     val = (code - 1) << shift;
1272     if (shift > 0)
1273         val |= get_bits(&s->gb, shift);
1274     val++;
1275     if (sign)
1276         val = -val;
1277     val += pred;
1278     
1279     /* modulo decoding */
1280     if (!s->h263_long_vectors) {
1281         l = (1 << (f_code - 1)) * 32;
1282         m = 2 * l;
1283         if (val < -l) {
1284             val += m;
1285         } else if (val >= l) {
1286             val -= m;
1287         }
1288     } else {
1289         /* horrible h263 long vector mode */
1290         if (pred < -31 && val < -63)
1291             val += 64;
1292         if (pred > 32 && val > 63)
1293             val -= 64;
1294         
1295     }
1296     return val;
1297 }
1298
1299 /* Decodes RVLC of H.263+ UMV */
1300 static int h263p_decode_umotion(MpegEncContext * s, int pred)
1301 {
1302    int code = 0, sign;
1303    
1304    if (get_bits1(&s->gb)) /* Motion difference = 0 */
1305       return pred;
1306    
1307    code = 2 + get_bits1(&s->gb);
1308    
1309    while (get_bits1(&s->gb))
1310    {
1311       code <<= 1;
1312       code += get_bits1(&s->gb);
1313    }
1314    sign = code & 1;
1315    code >>= 1;
1316    
1317    code = (sign) ? (pred - code) : (pred + code);
1318 #ifdef DEBUG
1319    fprintf(stderr,"H.263+ UMV Motion = %d\n", code);
1320 #endif
1321    return code;   
1322
1323 }
1324
1325 static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
1326                              int n, int coded)
1327 {
1328     int code, level, i, j, last, run;
1329     RLTable *rl = &rl_inter;
1330     const UINT8 *scan_table;
1331
1332     scan_table = zigzag_direct;
1333     if (s->h263_aic && s->mb_intra) {
1334         rl = &rl_intra_aic;
1335         i = 0;
1336         if (s->ac_pred) {
1337             if (s->h263_aic_dir) 
1338                 scan_table = ff_alternate_vertical_scan; /* left */
1339             else
1340                 scan_table = ff_alternate_horizontal_scan; /* top */
1341         }
1342     } else if (s->mb_intra) {
1343         /* DC coef */
1344         if (s->h263_rv10 && s->rv10_version == 3 && s->pict_type == I_TYPE) {
1345             int component, diff;
1346             component = (n <= 3 ? 0 : n - 4 + 1);
1347             level = s->last_dc[component];
1348             if (s->rv10_first_dc_coded[component]) {
1349                 diff = rv_decode_dc(s, n);
1350                 if (diff == 0xffff)
1351                     return -1;
1352                 level += diff;
1353                 level = level & 0xff; /* handle wrap round */
1354                 s->last_dc[component] = level;
1355             } else {
1356                 s->rv10_first_dc_coded[component] = 1;
1357             }
1358         } else {
1359             level = get_bits(&s->gb, 8);
1360             if (level == 255)
1361                 level = 128;
1362         }
1363         block[0] = level;
1364         i = 1;
1365     } else {
1366         i = 0;
1367     }
1368     if (!coded) {
1369         if (s->mb_intra && s->h263_aic)
1370             goto not_coded;
1371         s->block_last_index[n] = i - 1;
1372         return 0;
1373     }
1374
1375     for(;;) {
1376         code = get_vlc(&s->gb, &rl->vlc);
1377         if (code < 0)
1378             return -1;
1379         if (code == rl->n) {
1380             /* escape */
1381             last = get_bits1(&s->gb);
1382             run = get_bits(&s->gb, 6);
1383             level = (INT8)get_bits(&s->gb, 8);
1384             if (s->h263_rv10 && level == -128) {
1385                 /* XXX: should patch encoder too */
1386                 level = get_bits(&s->gb, 12);
1387                 level = (level << 20) >> 20;
1388             }
1389         } else {
1390             run = rl->table_run[code];
1391             level = rl->table_level[code];
1392             last = code >= rl->last;
1393             if (get_bits1(&s->gb))
1394                 level = -level;
1395         }
1396         i += run;
1397         if (i >= 64)
1398             return -1;
1399         j = scan_table[i];
1400         block[j] = level;
1401         if (last)
1402             break;
1403         i++;
1404     }
1405 not_coded:    
1406     if (s->mb_intra && s->h263_aic) {
1407         h263_pred_acdc(s, block, n);
1408         i = 64;
1409     }
1410     s->block_last_index[n] = i;
1411     return 0;
1412 }
1413
1414 static int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr)
1415 {
1416     int level, pred, code;
1417     UINT16 *dc_val;
1418
1419     if (n < 4) 
1420         code = get_vlc(&s->gb, &dc_lum);
1421     else 
1422         code = get_vlc(&s->gb, &dc_chrom);
1423     if (code < 0)
1424         return -1;
1425     if (code == 0) {
1426         level = 0;
1427     } else {
1428         level = get_bits(&s->gb, code);
1429         if ((level >> (code - 1)) == 0) /* if MSB not set it is negative*/
1430             level = - (level ^ ((1 << code) - 1));
1431         if (code > 8)
1432             skip_bits1(&s->gb); /* marker */
1433     }
1434
1435     pred = mpeg4_pred_dc(s, n, &dc_val, dir_ptr);
1436     level += pred;
1437     if (level < 0)
1438         level = 0;
1439     if (n < 4) {
1440         *dc_val = level * s->y_dc_scale;
1441     } else {
1442         *dc_val = level * s->c_dc_scale;
1443     }
1444     return level;
1445 }
1446
1447 static int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
1448                               int n, int coded)
1449 {
1450     int code, level, i, j, last, run;
1451     int dc_pred_dir;
1452     RLTable *rl;
1453     const UINT8 *scan_table;
1454
1455     if (s->mb_intra) {
1456         /* DC coef */
1457         level = mpeg4_decode_dc(s, n, &dc_pred_dir);
1458         if (level < 0)
1459             return -1;
1460         block[0] = level;
1461         i = 1;
1462         if (!coded) 
1463             goto not_coded;
1464         rl = &rl_intra;
1465         if (s->ac_pred) {
1466             if (dc_pred_dir == 0) 
1467                 scan_table = ff_alternate_vertical_scan; /* left */
1468             else
1469                 scan_table = ff_alternate_horizontal_scan; /* top */
1470         } else {
1471             scan_table = zigzag_direct;
1472         }
1473     } else {
1474         i = 0;
1475         if (!coded) {
1476             s->block_last_index[n] = i - 1;
1477             return 0;
1478         }
1479         rl = &rl_inter;
1480         scan_table = zigzag_direct;
1481     }
1482
1483     for(;;) {
1484         code = get_vlc(&s->gb, &rl->vlc);
1485         if (code < 0)
1486             return -1;
1487         if (code == rl->n) {
1488             /* escape */
1489             if (get_bits1(&s->gb) != 0) {
1490                 if (get_bits1(&s->gb) != 0) {
1491                     /* third escape */
1492                     last = get_bits1(&s->gb);
1493                     run = get_bits(&s->gb, 6);
1494                     get_bits1(&s->gb); /* marker */
1495                     level = get_bits(&s->gb, 12);
1496                     level = (level << 20) >> 20; /* sign extend */
1497                     skip_bits1(&s->gb); /* marker */
1498                 } else {
1499                     /* second escape */
1500                     code = get_vlc(&s->gb, &rl->vlc);
1501                     if (code < 0 || code >= rl->n)
1502                         return -1;
1503                     run = rl->table_run[code];
1504                     level = rl->table_level[code];
1505                     last = code >= rl->last;
1506                     run += rl->max_run[last][level] + 1;
1507                     if (get_bits1(&s->gb))
1508                         level = -level;
1509                 }
1510             } else {
1511                 /* first escape */
1512                 code = get_vlc(&s->gb, &rl->vlc);
1513                 if (code < 0 || code >= rl->n)
1514                     return -1;
1515                 run = rl->table_run[code];
1516                 level = rl->table_level[code];
1517                 last = code >= rl->last;
1518                 level += rl->max_level[last][run];
1519                 if (get_bits1(&s->gb))
1520                     level = -level;
1521             }
1522         } else {
1523             run = rl->table_run[code];
1524             level = rl->table_level[code];
1525             last = code >= rl->last;
1526             if (get_bits1(&s->gb))
1527                 level = -level;
1528         }
1529         i += run;
1530         if (i >= 64)
1531             return -1;
1532         j = scan_table[i];
1533         block[j] = level;
1534         i++;
1535         if (last)
1536             break;
1537     }
1538  not_coded:
1539     if (s->mb_intra) {
1540         mpeg4_pred_ac(s, block, n, dc_pred_dir);
1541         if (s->ac_pred) {
1542             i = 64; /* XXX: not optimal */
1543         }
1544     }
1545     s->block_last_index[n] = i - 1;
1546     return 0;
1547 }
1548
1549 /* most is hardcoded. should extend to handle all h263 streams */
1550 int h263_decode_picture_header(MpegEncContext *s)
1551 {
1552     int format, width, height;
1553
1554     /* picture header */
1555     if (get_bits(&s->gb, 22) != 0x20)
1556         return -1;
1557     s->picture_number = get_bits(&s->gb, 8); /* picture timestamp */
1558     
1559     if (get_bits1(&s->gb) != 1)
1560         return -1;      /* marker */
1561     if (get_bits1(&s->gb) != 0)
1562         return -1;      /* h263 id */
1563     skip_bits1(&s->gb); /* split screen off */
1564     skip_bits1(&s->gb); /* camera  off */
1565     skip_bits1(&s->gb); /* freeze picture release off */
1566
1567     /* Reset GOB number */
1568     s->gob_number = 0;
1569         
1570     format = get_bits(&s->gb, 3);
1571
1572     if (format != 7 && format != 6) {
1573         s->h263_plus = 0;
1574         /* H.263v1 */
1575         width = h263_format[format][0];
1576         height = h263_format[format][1];
1577         if (!width)
1578             return -1;
1579         
1580         s->width = width;
1581         s->height = height;
1582         s->pict_type = I_TYPE + get_bits1(&s->gb);
1583
1584         s->unrestricted_mv = get_bits1(&s->gb); 
1585         s->h263_long_vectors = s->unrestricted_mv;
1586
1587         if (get_bits1(&s->gb) != 0)
1588             return -1;  /* SAC: off */
1589         if (get_bits1(&s->gb) != 0) {
1590             s->mv_type = MV_TYPE_8X8; /* Advanced prediction mode */
1591         }   
1592         
1593         if (get_bits1(&s->gb) != 0)
1594             return -1;  /* not PB frame */
1595
1596         s->qscale = get_bits(&s->gb, 5);
1597         skip_bits1(&s->gb);     /* Continuous Presence Multipoint mode: off */
1598     } else {
1599         int ufep;
1600         
1601         /* H.263v2 */
1602         s->h263_plus = 1;
1603         ufep = get_bits(&s->gb, 3); /* Update Full Extended PTYPE */
1604         
1605         if (ufep == 1) {
1606             /* OPPTYPE */       
1607             format = get_bits(&s->gb, 3);
1608             skip_bits(&s->gb,1); /* Custom PCF */
1609             s->umvplus_dec = get_bits(&s->gb, 1); /* Unrestricted Motion Vector */
1610             skip_bits1(&s->gb); /* Syntax-based Arithmetic Coding (SAC) */
1611             if (get_bits1(&s->gb) != 0) {
1612                 s->mv_type = MV_TYPE_8X8; /* Advanced prediction mode */
1613             }
1614             if (get_bits1(&s->gb) != 0) { /* Advanced Intra Coding (AIC) */
1615                 s->h263_aic = 1;
1616             }
1617             skip_bits(&s->gb, 7);
1618             skip_bits(&s->gb, 3); /* Reserved */
1619         } else if (ufep != 0)
1620             return -1;
1621             
1622         /* MPPTYPE */
1623         s->pict_type = get_bits(&s->gb, 3) + 1;
1624         if (s->pict_type != I_TYPE &&
1625             s->pict_type != P_TYPE)
1626             return -1;
1627         skip_bits(&s->gb, 2);
1628         s->no_rounding = get_bits1(&s->gb);
1629         //fprintf(stderr, "\nRTYPE: %d", s->no_rounding);
1630         skip_bits(&s->gb, 4);
1631         
1632         /* Get the picture dimensions */
1633         if (ufep) {
1634             if (format == 6) {
1635                 /* Custom Picture Format (CPFMT) */
1636                 skip_bits(&s->gb, 4); /* aspect ratio */
1637                 width = (get_bits(&s->gb, 9) + 1) * 4;
1638                 skip_bits1(&s->gb);
1639                 height = get_bits(&s->gb, 9) * 4;
1640 #ifdef DEBUG 
1641                 fprintf(stderr,"\nH.263+ Custom picture: %dx%d\n",width,height);
1642 #endif            
1643             }
1644             else {
1645                 width = h263_format[format][0];
1646                 height = h263_format[format][1];
1647             }
1648             if ((width == 0) || (height == 0))
1649                 return -1;
1650             s->width = width;
1651             s->height = height;
1652             if (s->umvplus_dec) {
1653                 skip_bits1(&s->gb); /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
1654             }
1655         }
1656             
1657         s->qscale = get_bits(&s->gb, 5);
1658     }
1659     /* PEI */
1660     while (get_bits1(&s->gb) != 0) {
1661         skip_bits(&s->gb, 8);
1662     }
1663     s->f_code = 1;
1664     return 0;
1665 }
1666
1667 static void mpeg4_decode_sprite_trajectory(MpegEncContext * s)
1668 {
1669     int i;
1670     int a= 2<<s->sprite_warping_accuracy;
1671     int rho= 3-s->sprite_warping_accuracy;
1672     int r=16/a;
1673     const int vop_ref[4][2]= {{0,0}, {s->width,0}, {0, s->height}, {s->width, s->height}}; // only true for rectangle shapes
1674     int d[4][2]={{0,0}, {0,0}, {0,0}, {0,0}};
1675     int sprite_ref[4][2];
1676     int virtual_ref[2][2];
1677     int w2, h2;
1678     int alpha=0, beta=0;
1679     int w= s->width;
1680     int h= s->height;
1681 //printf("SP %d\n", s->sprite_warping_accuracy);
1682     for(i=0; i<s->num_sprite_warping_points; i++){
1683         int length;
1684         int x=0, y=0;
1685
1686         length= get_vlc(&s->gb, &sprite_trajectory);
1687         if(length){
1688             x= get_bits(&s->gb, length);
1689 //printf("lx %d %d\n", length, x);
1690             if ((x >> (length - 1)) == 0) /* if MSB not set it is negative*/
1691                 x = - (x ^ ((1 << length) - 1));
1692         }
1693         if(!(s->divx_version==500 && s->divx_build==413)) skip_bits1(&s->gb); /* marker bit */
1694         
1695         length= get_vlc(&s->gb, &sprite_trajectory);
1696         if(length){
1697             y=get_bits(&s->gb, length);
1698 //printf("ly %d %d\n", length, y);
1699             if ((y >> (length - 1)) == 0) /* if MSB not set it is negative*/
1700                 y = - (y ^ ((1 << length) - 1));
1701         }
1702         skip_bits1(&s->gb); /* marker bit */
1703 //printf("%d %d %d %d\n", x, y, i, s->sprite_warping_accuracy);
1704 //if(i>0 && (x!=0 || y!=0)) printf("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n");
1705 //x=y=0;
1706         d[i][0]= x;
1707         d[i][1]= y;
1708     }
1709
1710     while((1<<alpha)<w) alpha++;
1711     while((1<<beta )<h) beta++; // there seems to be a typo in the mpeg4 std for the definition of w' and h'
1712     w2= 1<<alpha;
1713     h2= 1<<beta;
1714
1715 // Note, the 4th point isnt used for GMC
1716     if(s->divx_version==500 && s->divx_build==413){
1717         sprite_ref[0][0]= a*vop_ref[0][0] + d[0][0];
1718         sprite_ref[0][1]= a*vop_ref[0][1] + d[0][1];
1719         sprite_ref[1][0]= a*vop_ref[1][0] + d[0][0] + d[1][0];
1720         sprite_ref[1][1]= a*vop_ref[1][1] + d[0][1] + d[1][1];
1721         sprite_ref[2][0]= a*vop_ref[2][0] + d[0][0] + d[2][0];
1722         sprite_ref[2][1]= a*vop_ref[2][1] + d[0][1] + d[2][1];
1723     } else {
1724         sprite_ref[0][0]= (a>>1)*(2*vop_ref[0][0] + d[0][0]);
1725         sprite_ref[0][1]= (a>>1)*(2*vop_ref[0][1] + d[0][1]);
1726         sprite_ref[1][0]= (a>>1)*(2*vop_ref[1][0] + d[0][0] + d[1][0]);
1727         sprite_ref[1][1]= (a>>1)*(2*vop_ref[1][1] + d[0][1] + d[1][1]);
1728         sprite_ref[2][0]= (a>>1)*(2*vop_ref[2][0] + d[0][0] + d[2][0]);
1729         sprite_ref[2][1]= (a>>1)*(2*vop_ref[2][1] + d[0][1] + d[2][1]);
1730     }
1731 /*    sprite_ref[3][0]= (a>>1)*(2*vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);
1732     sprite_ref[3][1]= (a>>1)*(2*vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */
1733     
1734 // this is mostly identical to the mpeg4 std (and is totally unreadable because of that ...)
1735 // perhaps it should be reordered to be more readable ...
1736 // the idea behind this virtual_ref mess is to be able to use shifts later per pixel instead of divides
1737 // so the distance between points is converted from w&h based to w2&h2 based which are of the 2^x form
1738     virtual_ref[0][0]= 16*(vop_ref[0][0] + w2) 
1739         + RDIV(((w - w2)*(r*sprite_ref[0][0] - 16*vop_ref[0][0]) + w2*(r*sprite_ref[1][0] - 16*vop_ref[1][0])),w);
1740     virtual_ref[0][1]= 16*vop_ref[0][1] 
1741         + RDIV(((w - w2)*(r*sprite_ref[0][1] - 16*vop_ref[0][1]) + w2*(r*sprite_ref[1][1] - 16*vop_ref[1][1])),w);
1742     virtual_ref[1][0]= 16*vop_ref[0][0] 
1743         + RDIV(((h - h2)*(r*sprite_ref[0][0] - 16*vop_ref[0][0]) + h2*(r*sprite_ref[2][0] - 16*vop_ref[2][0])),h);
1744     virtual_ref[1][1]= 16*(vop_ref[0][1] + h2) 
1745         + RDIV(((h - h2)*(r*sprite_ref[0][1] - 16*vop_ref[0][1]) + h2*(r*sprite_ref[2][1] - 16*vop_ref[2][1])),h);
1746
1747     switch(s->num_sprite_warping_points)
1748     {
1749         case 0:
1750             s->sprite_offset[0][0]= 0;
1751             s->sprite_offset[0][1]= 0;
1752             s->sprite_offset[1][0]= 0;
1753             s->sprite_offset[1][1]= 0;
1754             s->sprite_delta[0][0][0]= a;
1755             s->sprite_delta[0][0][1]= 0;
1756             s->sprite_delta[0][1][0]= 0;
1757             s->sprite_delta[0][1][1]= a;
1758             s->sprite_delta[1][0][0]= a;
1759             s->sprite_delta[1][0][1]= 0;
1760             s->sprite_delta[1][1][0]= 0;
1761             s->sprite_delta[1][1][1]= a;
1762             s->sprite_shift[0][0]= 0;
1763             s->sprite_shift[0][1]= 0;
1764             s->sprite_shift[1][0]= 0;
1765             s->sprite_shift[1][1]= 0;
1766             break;
1767         case 1: //GMC only
1768             s->sprite_offset[0][0]= sprite_ref[0][0] - a*vop_ref[0][0];
1769             s->sprite_offset[0][1]= sprite_ref[0][1] - a*vop_ref[0][1];
1770             s->sprite_offset[1][0]= ((sprite_ref[0][0]>>1)|(sprite_ref[0][0]&1)) - a*(vop_ref[0][0]/2);
1771             s->sprite_offset[1][1]= ((sprite_ref[0][1]>>1)|(sprite_ref[0][1]&1)) - a*(vop_ref[0][1]/2);
1772             s->sprite_delta[0][0][0]= a;
1773             s->sprite_delta[0][0][1]= 0;
1774             s->sprite_delta[0][1][0]= 0;
1775             s->sprite_delta[0][1][1]= a;
1776             s->sprite_delta[1][0][0]= a;
1777             s->sprite_delta[1][0][1]= 0;
1778             s->sprite_delta[1][1][0]= 0;
1779             s->sprite_delta[1][1][1]= a;
1780             s->sprite_shift[0][0]= 0;
1781             s->sprite_shift[0][1]= 0;
1782             s->sprite_shift[1][0]= 0;
1783             s->sprite_shift[1][1]= 0;
1784             break;
1785         case 2:
1786         case 3: //FIXME
1787             s->sprite_offset[0][0]= (sprite_ref[0][0]<<(alpha+rho))
1788                                                   + ((-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][0])
1789                                                     +( r*sprite_ref[0][1] - virtual_ref[0][1])*(-vop_ref[0][1]));
1790             s->sprite_offset[0][1]= (sprite_ref[0][1]<<(alpha+rho))
1791                                                   + ((-r*sprite_ref[0][1] + virtual_ref[0][1])*(-vop_ref[0][0])
1792                                                     +(-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][1]));
1793             s->sprite_offset[1][0]= ((-r*sprite_ref[0][0] + virtual_ref[0][0])*(-2*vop_ref[0][0] + 1)
1794                                  +( r*sprite_ref[0][1] - virtual_ref[0][1])*(-2*vop_ref[0][1] + 1)
1795                                  +2*w2*r*sprite_ref[0][0] - 16*w2);
1796             s->sprite_offset[1][1]= ((-r*sprite_ref[0][1] + virtual_ref[0][1])*(-2*vop_ref[0][0] + 1) 
1797                                  +(-r*sprite_ref[0][0] + virtual_ref[0][0])*(-2*vop_ref[0][1] + 1)
1798                                  +2*w2*r*sprite_ref[0][1] - 16*w2);
1799             s->sprite_delta[0][0][0]=   (-r*sprite_ref[0][0] + virtual_ref[0][0]);
1800             s->sprite_delta[0][0][1]=   ( r*sprite_ref[0][1] - virtual_ref[0][1]);
1801             s->sprite_delta[0][1][0]=   (-r*sprite_ref[0][1] + virtual_ref[0][1]);
1802             s->sprite_delta[0][1][1]=   (-r*sprite_ref[0][0] + virtual_ref[0][0]);
1803             s->sprite_delta[1][0][0]= 4*(-r*sprite_ref[0][0] + virtual_ref[0][0]);
1804             s->sprite_delta[1][0][1]= 4*( r*sprite_ref[0][1] - virtual_ref[0][1]);
1805             s->sprite_delta[1][1][0]= 4*(-r*sprite_ref[0][1] + virtual_ref[0][1]);
1806             s->sprite_delta[1][1][1]= 4*(-r*sprite_ref[0][0] + virtual_ref[0][0]);
1807             s->sprite_shift[0][0]= alpha+rho;
1808             s->sprite_shift[0][1]= alpha+rho;
1809             s->sprite_shift[1][0]= alpha+rho+2;
1810             s->sprite_shift[1][1]= alpha+rho+2;
1811             break;
1812 //        case 3:
1813             break;
1814     }
1815 /*printf("%d %d\n", s->sprite_delta[0][0][0], a<<s->sprite_shift[0][0]);
1816 printf("%d %d\n", s->sprite_delta[0][0][1], 0);
1817 printf("%d %d\n", s->sprite_delta[0][1][0], 0);
1818 printf("%d %d\n", s->sprite_delta[0][1][1], a<<s->sprite_shift[0][1]);
1819 printf("%d %d\n", s->sprite_delta[1][0][0], a<<s->sprite_shift[1][0]);
1820 printf("%d %d\n", s->sprite_delta[1][0][1], 0);
1821 printf("%d %d\n", s->sprite_delta[1][1][0], 0);
1822 printf("%d %d\n", s->sprite_delta[1][1][1], a<<s->sprite_shift[1][1]);*/
1823     /* try to simplify the situation */ 
1824     if(   s->sprite_delta[0][0][0] == a<<s->sprite_shift[0][0]
1825        && s->sprite_delta[0][0][1] == 0
1826        && s->sprite_delta[0][1][0] == 0
1827        && s->sprite_delta[0][1][1] == a<<s->sprite_shift[0][1]
1828        && s->sprite_delta[1][0][0] == a<<s->sprite_shift[1][0]
1829        && s->sprite_delta[1][0][1] == 0
1830        && s->sprite_delta[1][1][0] == 0
1831        && s->sprite_delta[1][1][1] == a<<s->sprite_shift[1][1])
1832     {
1833         s->sprite_offset[0][0]>>=s->sprite_shift[0][0];
1834         s->sprite_offset[0][1]>>=s->sprite_shift[0][1];
1835         s->sprite_offset[1][0]>>=s->sprite_shift[1][0];
1836         s->sprite_offset[1][1]>>=s->sprite_shift[1][1];
1837         s->sprite_delta[0][0][0]= a;
1838         s->sprite_delta[0][0][1]= 0;
1839         s->sprite_delta[0][1][0]= 0;
1840         s->sprite_delta[0][1][1]= a;
1841         s->sprite_delta[1][0][0]= a;
1842         s->sprite_delta[1][0][1]= 0;
1843         s->sprite_delta[1][1][0]= 0;
1844         s->sprite_delta[1][1][1]= a;
1845         s->sprite_shift[0][0]= 0;
1846         s->sprite_shift[0][1]= 0;
1847         s->sprite_shift[1][0]= 0;
1848         s->sprite_shift[1][1]= 0;
1849         s->real_sprite_warping_points=1;
1850     }
1851     else
1852         s->real_sprite_warping_points= s->num_sprite_warping_points;
1853
1854 }
1855
1856 /* decode mpeg4 VOP header */
1857 int mpeg4_decode_picture_header(MpegEncContext * s)
1858 {
1859     int time_incr, startcode, state, v;
1860
1861  redo:
1862     /* search next start code */
1863     align_get_bits(&s->gb);
1864     state = 0xff;
1865     for(;;) {
1866         v = get_bits(&s->gb, 8);
1867         if (state == 0x000001) {
1868             state = ((state << 8) | v) & 0xffffff;
1869             startcode = state;
1870             break;
1871         }
1872         state = ((state << 8) | v) & 0xffffff;
1873         /* XXX: really detect end of frame */
1874         if (state == 0)
1875             return -1;
1876     }
1877 //printf("startcode %X %d\n", startcode, get_bits_count(&s->gb));
1878     if (startcode == 0x120) { // Video Object Layer
1879         int width, height, vo_ver_id;
1880
1881         /* vol header */
1882         skip_bits(&s->gb, 1); /* random access */
1883         skip_bits(&s->gb, 8); /* vo_type */
1884         if (get_bits1(&s->gb) != 0) { /* is_ol_id */
1885             vo_ver_id = get_bits(&s->gb, 4); /* vo_ver_id */
1886             skip_bits(&s->gb, 3); /* vo_priority */
1887         } else {
1888             vo_ver_id = 1;
1889         }
1890         
1891         s->aspect_ratio_info= get_bits(&s->gb, 4);
1892         if(s->aspect_ratio_info == EXTENDET_PAR){
1893             skip_bits(&s->gb, 8); //par_width
1894             skip_bits(&s->gb, 8); // par_height
1895         }
1896         if(get_bits1(&s->gb)){ /* vol control parameter */
1897             printf("vol control parameter not supported\n");
1898             return -1;   
1899         }
1900         s->shape = get_bits(&s->gb, 2); /* vol shape */
1901         if(s->shape == GRAY_SHAPE && vo_ver_id != 1){
1902             printf("Gray shape not supported\n");
1903             skip_bits(&s->gb, 4);  //video_object_layer_shape_extension
1904         }
1905
1906         skip_bits1(&s->gb);   /* marker */
1907         
1908         s->time_increment_resolution = get_bits(&s->gb, 16);
1909         s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;
1910         if (s->time_increment_bits < 1)
1911             s->time_increment_bits = 1;
1912         skip_bits1(&s->gb);   /* marker */
1913
1914         if (get_bits1(&s->gb) != 0) {   /* fixed_vop_rate  */
1915             skip_bits(&s->gb, s->time_increment_bits);
1916         }
1917
1918         if (s->shape != BIN_ONLY_SHAPE) {
1919             if (s->shape == RECT_SHAPE) {
1920                 skip_bits1(&s->gb);   /* marker */
1921                 width = get_bits(&s->gb, 13);
1922                 skip_bits1(&s->gb);   /* marker */
1923                 height = get_bits(&s->gb, 13);
1924                 skip_bits1(&s->gb);   /* marker */
1925             }
1926             
1927             skip_bits1(&s->gb);   /* interlaced */
1928             if(!get_bits1(&s->gb)) printf("OBMC not supported\n");   /* OBMC Disable */
1929             if (vo_ver_id == 1) {
1930                 s->vol_sprite_usage = get_bits1(&s->gb); /* vol_sprite_usage */
1931             } else {
1932                 s->vol_sprite_usage = get_bits(&s->gb, 2); /* vol_sprite_usage */
1933             }
1934             if(s->vol_sprite_usage==STATIC_SPRITE) printf("Static Sprites not supported\n");
1935             if(s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE){
1936                 if(s->vol_sprite_usage==STATIC_SPRITE){
1937                     s->sprite_width = get_bits(&s->gb, 13);
1938                     skip_bits1(&s->gb); /* marker */
1939                     s->sprite_height= get_bits(&s->gb, 13);
1940                     skip_bits1(&s->gb); /* marker */
1941                     s->sprite_left  = get_bits(&s->gb, 13);
1942                     skip_bits1(&s->gb); /* marker */
1943                     s->sprite_top   = get_bits(&s->gb, 13);
1944                     skip_bits1(&s->gb); /* marker */
1945                 }
1946                 s->num_sprite_warping_points= get_bits(&s->gb, 6);
1947                 s->sprite_warping_accuracy = get_bits(&s->gb, 2);
1948                 s->sprite_brightness_change= get_bits1(&s->gb);
1949                 if(s->vol_sprite_usage==STATIC_SPRITE)
1950                     s->low_latency_sprite= get_bits1(&s->gb);            
1951             }
1952             // FIXME sadct disable bit if verid!=1 && shape not rect
1953             
1954             if (get_bits1(&s->gb) == 1) {   /* not_8_bit */
1955                 s->quant_precision = get_bits(&s->gb, 4); /* quant_precision */
1956                 skip_bits(&s->gb, 4); /* bits_per_pixel */
1957             } else {
1958                 s->quant_precision = 5;
1959             }
1960             
1961             // FIXME a bunch of grayscale shape things
1962             if(get_bits1(&s->gb)) printf("Quant-Type not supported\n");  /* vol_quant_type */ //FIXME
1963             if(vo_ver_id != 1)
1964                  s->quarter_sample= get_bits1(&s->gb);
1965             else s->quarter_sample=0;
1966 #if 0
1967             if(get_bits1(&s->gb)) printf("Complexity est disabled\n");
1968             if(get_bits1(&s->gb)) printf("resync disable\n");
1969 #else
1970             skip_bits1(&s->gb);   /* complexity_estimation_disabled */
1971             skip_bits1(&s->gb);   /* resync_marker_disabled */
1972 #endif
1973             s->data_partioning= get_bits1(&s->gb);
1974             if(s->data_partioning){
1975                 printf("data partitioning not supported\n");
1976                 skip_bits1(&s->gb); // reversible vlc
1977             }
1978             
1979             if(vo_ver_id != 1) {
1980                 s->new_pred= get_bits1(&s->gb);
1981                 if(s->new_pred){
1982                     printf("new pred not supported\n");
1983                     skip_bits(&s->gb, 2); /* requested upstream message type */
1984                     skip_bits1(&s->gb); /* newpred segment type */
1985                 }
1986                 s->reduced_res_vop= get_bits1(&s->gb);
1987                 if(s->reduced_res_vop) printf("reduced resolution VOP not supported\n");
1988             }
1989             else{
1990                 s->new_pred=0;
1991                 s->reduced_res_vop= 0;
1992             }
1993
1994             s->scalability= get_bits1(&s->gb);
1995             if (s->scalability) {
1996                 printf("bad scalability!!!\n");
1997                 return -1;
1998             }
1999         }
2000 //printf("end Data %X %d\n", show_bits(&s->gb, 32), get_bits_count(&s->gb)&0x7);
2001         goto redo;
2002     } else if (startcode == 0x1b2) { //userdata
2003         char buf[256];
2004         int i;
2005         int e;
2006         int ver, build;
2007
2008 //printf("user Data %X\n", show_bits(&s->gb, 32));
2009         buf[0]= show_bits(&s->gb, 8);
2010         for(i=1; i<256; i++){
2011             buf[i]= show_bits(&s->gb, 16)&0xFF;
2012             if(buf[i]==0) break;
2013             skip_bits(&s->gb, 8);
2014         }
2015         buf[255]=0;
2016         e=sscanf(buf, "DivX%dBuild%d", &ver, &build);
2017         if(e==2){
2018             s->divx_version= ver;
2019             s->divx_build= build;
2020             if(s->picture_number==0){
2021                 printf("This file was encoded with DivX%d Build%d\n", ver, build);
2022                 if(ver==500 && build==413){ //most likely all version are indeed totally buggy but i dunno for sure ...
2023                     printf("WARNING: this version of DivX is not MPEG4 compatible, trying to workaround these bugs...\n");
2024                 }else{
2025                     printf("hmm, i havnt seen that version of divx yet, lets assume they fixed these bugs ...\n"
2026                            "using mpeg4 decoder, if it fails contact the developers (of ffmpeg)\n");
2027                 }
2028             }
2029         }
2030 //printf("User Data: %s\n", buf);
2031         goto redo;
2032     } else if (startcode != 0x1b6) { //VOP
2033         goto redo;
2034     }
2035
2036     s->pict_type = get_bits(&s->gb, 2) + 1;     /* pict type: I = 0 , P = 1 */
2037  
2038     time_incr=0;
2039     while (get_bits1(&s->gb) != 0) 
2040         time_incr++;
2041
2042     skip_bits1(&s->gb);         /* marker */
2043     s->time_increment= get_bits(&s->gb, s->time_increment_bits);
2044     if(s->pict_type!=B_TYPE){
2045         s->time_base+= time_incr;
2046         s->last_non_b_time[1]= s->last_non_b_time[0];
2047         s->last_non_b_time[0]= s->time_base*s->time_increment_resolution + s->time_increment;
2048     }else{
2049         s->time= (s->last_non_b_time[1]/s->time_increment_resolution + time_incr)*s->time_increment_resolution;
2050         s->time+= s->time_increment;
2051     }
2052     skip_bits1(&s->gb);         /* marker */
2053     /* vop coded */
2054     if (get_bits1(&s->gb) != 1)
2055         goto redo;
2056 //printf("time %d %d %d || %d %d %d\n", s->time_increment_bits, s->time_increment, s->time_base,
2057 //s->time, s->last_non_b_time[0], s->last_non_b_time[1]);  
2058     if (s->shape != BIN_ONLY_SHAPE && ( s->pict_type == P_TYPE
2059                           || (s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE))) {
2060         /* rounding type for motion estimation */
2061         s->no_rounding = get_bits1(&s->gb);
2062     } else {
2063         s->no_rounding = 0;
2064     }
2065 //FIXME reduced res stuff
2066
2067      if (s->shape != RECT_SHAPE) {
2068          if (s->vol_sprite_usage != 1 || s->pict_type != I_TYPE) {
2069              int width, height, hor_spat_ref, ver_spat_ref;
2070  
2071              width = get_bits(&s->gb, 13);
2072              skip_bits1(&s->gb);   /* marker */
2073              height = get_bits(&s->gb, 13);
2074              skip_bits1(&s->gb);   /* marker */
2075              hor_spat_ref = get_bits(&s->gb, 13); /* hor_spat_ref */
2076              skip_bits1(&s->gb);   /* marker */
2077              ver_spat_ref = get_bits(&s->gb, 13); /* ver_spat_ref */
2078          }
2079          skip_bits1(&s->gb); /* change_CR_disable */
2080  
2081          if (get_bits1(&s->gb) != 0) {
2082              skip_bits(&s->gb, 8); /* constant_alpha_value */
2083          }
2084      }
2085 //FIXME complexity estimation stuff
2086      
2087      if (s->shape != BIN_ONLY_SHAPE) {
2088          skip_bits(&s->gb, 3); /* intra dc VLC threshold */
2089          //FIXME interlaced specific bits
2090      }
2091
2092      if(s->pict_type == S_TYPE && (s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE)){
2093          if(s->num_sprite_warping_points){
2094              mpeg4_decode_sprite_trajectory(s);
2095          }
2096          if(s->sprite_brightness_change) printf("sprite_brightness_change not supported\n");
2097          if(s->vol_sprite_usage==STATIC_SPRITE) printf("static sprite not supported\n");
2098      }
2099
2100      if (s->shape != BIN_ONLY_SHAPE) {
2101          /* note: we do not use quant_precision to avoid problem if no
2102             MPEG4 vol header as it is found on some old opendivx
2103             movies */
2104          s->qscale = get_bits(&s->gb, 5);
2105   
2106          if (s->pict_type != I_TYPE) {
2107              s->f_code = get_bits(&s->gb, 3);   /* fcode_for */
2108 //printf("f-code %d\n", s->f_code);
2109          }
2110          if (s->pict_type == B_TYPE) {
2111              s->b_code = get_bits(&s->gb, 3);
2112 //printf("b-code %d\n", s->b_code);
2113          }
2114 //printf("quant:%d fcode:%d\n", s->qscale, s->f_code);
2115          if(!s->scalability){
2116              if (s->shape!=RECT_SHAPE && s->pict_type!=I_TYPE) {
2117                  skip_bits1(&s->gb); // vop shape coding type
2118              }
2119          }
2120      }
2121 //printf("end Data %X %d\n", show_bits(&s->gb, 32), get_bits_count(&s->gb)&0x7);
2122      s->picture_number++; // better than pic number==0 allways ;)
2123      return 0;
2124 }
2125
2126 /* don't understand why they choose a different header ! */
2127 int intel_h263_decode_picture_header(MpegEncContext *s)
2128 {
2129     int format;
2130
2131     /* picture header */
2132     if (get_bits(&s->gb, 22) != 0x20)
2133         return -1;
2134     skip_bits(&s->gb, 8); /* picture timestamp */
2135
2136     if (get_bits1(&s->gb) != 1)
2137         return -1;      /* marker */
2138     if (get_bits1(&s->gb) != 0)
2139         return -1;      /* h263 id */
2140     skip_bits1(&s->gb); /* split screen off */
2141     skip_bits1(&s->gb); /* camera  off */
2142     skip_bits1(&s->gb); /* freeze picture release off */
2143
2144     format = get_bits(&s->gb, 3);
2145     if (format != 7)
2146         return -1;
2147
2148     s->h263_plus = 0;
2149
2150     s->pict_type = I_TYPE + get_bits1(&s->gb);
2151     
2152     s->unrestricted_mv = get_bits1(&s->gb); 
2153     s->h263_long_vectors = s->unrestricted_mv;
2154
2155     if (get_bits1(&s->gb) != 0)
2156         return -1;      /* SAC: off */
2157     if (get_bits1(&s->gb) != 0)
2158         return -1;      /* advanced prediction mode: off */
2159     if (get_bits1(&s->gb) != 0)
2160         return -1;      /* not PB frame */
2161
2162     /* skip unknown header garbage */
2163     skip_bits(&s->gb, 41);
2164
2165     s->qscale = get_bits(&s->gb, 5);
2166     skip_bits1(&s->gb); /* Continuous Presence Multipoint mode: off */
2167
2168     /* PEI */
2169     while (get_bits1(&s->gb) != 0) {
2170         skip_bits(&s->gb, 8);
2171     }
2172     s->f_code = 1;
2173     return 0;
2174 }
2175