- Versions defined for libav/libavcodec.
[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  * ac prediction encoding by Michael Niedermayer <michaelni@gmx.at>
22  */
23 #include "common.h"
24 #include "dsputil.h"
25 #include "avcodec.h"
26 #include "mpegvideo.h"
27 #include "h263data.h"
28 #include "mpeg4data.h"
29
30 //rounded divison & shift
31 #define RDIV(a,b) ((a) > 0 ? ((a)+((b)>>1))/(b) : ((a)-((b)>>1))/(b))
32 #define RSHIFT(a,b) ((a) > 0 ? ((a) + (1<<((b)-1)))>>(b) : ((a) + (1<<((b)-1))-1)>>(b))
33 #define ABS(a) (((a)>=0)?(a):(-(a)))
34 #define MAX(a,b) ((a) > (b) ? (a) : (b))
35 #define MIN(a,b) ((a) < (b) ? (a) : (b))
36
37 static void h263_encode_block(MpegEncContext * s, DCTELEM * block,
38                               int n);
39 static void h263_encode_motion(MpegEncContext * s, int val);
40 static void h263p_encode_umotion(MpegEncContext * s, int val);
41 static void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block,
42                                int n, int dc, UINT8 *scan_table);
43 static int h263_decode_motion(MpegEncContext * s, int pred, int fcode);
44 static int h263p_decode_umotion(MpegEncContext * s, int pred);
45 static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
46                              int n, int coded);
47 static int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
48                               int n, int coded);
49 static inline int mpeg4_pred_dc(MpegEncContext * s, int n, UINT16 **dc_val_ptr, int *dir_ptr);
50 static void mpeg4_inv_pred_ac(MpegEncContext * s, INT16 *block, int n,
51                               int dir);
52 static void mpeg4_decode_sprite_trajectory(MpegEncContext * s);
53
54 extern UINT32 inverse[256];
55
56 static UINT16 mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
57 static UINT8 fcode_tab[MAX_MV*2+1];
58 static UINT8 umv_fcode_tab[MAX_MV*2+1];
59
60 static UINT16 uni_DCtab_lum  [512][2];
61 static UINT16 uni_DCtab_chrom[512][2];
62
63 int h263_get_picture_format(int width, int height)
64 {
65     int format;
66
67     if (width == 128 && height == 96)
68         format = 1;
69     else if (width == 176 && height == 144)
70         format = 2;
71     else if (width == 352 && height == 288)
72         format = 3;
73     else if (width == 704 && height == 576)
74         format = 4;
75     else if (width == 1408 && height == 1152)
76         format = 5;
77     else
78         format = 7;
79     return format;
80 }
81
82 void h263_encode_picture_header(MpegEncContext * s, int picture_number)
83 {
84     int format;
85
86     align_put_bits(&s->pb);
87
88     /* Update the pointer to last GOB */
89     s->ptr_lastgob = pbBufPtr(&s->pb);
90     s->gob_number = 0;
91
92     put_bits(&s->pb, 22, 0x20); /* PSC */
93     put_bits(&s->pb, 8, (((INT64)s->picture_number * 30 * FRAME_RATE_BASE) / 
94                          s->frame_rate) & 0xff);
95
96     put_bits(&s->pb, 1, 1);     /* marker */
97     put_bits(&s->pb, 1, 0);     /* h263 id */
98     put_bits(&s->pb, 1, 0);     /* split screen off */
99     put_bits(&s->pb, 1, 0);     /* camera  off */
100     put_bits(&s->pb, 1, 0);     /* freeze picture release off */
101     
102     format = h263_get_picture_format(s->width, s->height);
103     if (!s->h263_plus) {
104         /* H.263v1 */
105         put_bits(&s->pb, 3, format);
106         put_bits(&s->pb, 1, (s->pict_type == P_TYPE));
107         /* By now UMV IS DISABLED ON H.263v1, since the restrictions
108         of H.263v1 UMV implies to check the predicted MV after
109         calculation of the current MB to see if we're on the limits */
110         put_bits(&s->pb, 1, 0); /* unrestricted motion vector: off */
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); /* not PB frame */
114         put_bits(&s->pb, 5, s->qscale);
115         put_bits(&s->pb, 1, 0); /* Continuous Presence Multipoint mode: off */
116     } else {
117         /* H.263v2 */
118         /* H.263 Plus PTYPE */
119         put_bits(&s->pb, 3, 7);
120         put_bits(&s->pb,3,1); /* Update Full Extended PTYPE */
121         if (format == 7)
122             put_bits(&s->pb,3,6); /* Custom Source Format */
123         else
124             put_bits(&s->pb, 3, format);
125             
126         put_bits(&s->pb,1,0); /* Custom PCF: off */
127         s->umvplus = (s->pict_type == P_TYPE) && s->unrestricted_mv;
128         put_bits(&s->pb, 1, s->umvplus); /* Unrestricted Motion Vector */
129         put_bits(&s->pb,1,0); /* SAC: off */
130         put_bits(&s->pb,1,0); /* Advanced Prediction Mode: off */
131         put_bits(&s->pb,1,0); /* Advanced Intra Coding: off */
132         put_bits(&s->pb,1,0); /* Deblocking Filter: off */
133         put_bits(&s->pb,1,0); /* Slice Structured: off */
134         put_bits(&s->pb,1,0); /* Reference Picture Selection: off */
135         put_bits(&s->pb,1,0); /* Independent Segment Decoding: off */
136         put_bits(&s->pb,1,0); /* Alternative Inter VLC: off */
137         put_bits(&s->pb,1,0); /* Modified Quantization: off */
138         put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
139         put_bits(&s->pb,3,0); /* Reserved */
140                 
141         put_bits(&s->pb, 3, s->pict_type == P_TYPE);
142                 
143         put_bits(&s->pb,1,0); /* Reference Picture Resampling: off */
144         put_bits(&s->pb,1,0); /* Reduced-Resolution Update: off */
145         put_bits(&s->pb,1,0); /* Rounding Type */
146         put_bits(&s->pb,2,0); /* Reserved */
147         put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
148                 
149         /* This should be here if PLUSPTYPE */
150         put_bits(&s->pb, 1, 0); /* Continuous Presence Multipoint mode: off */
151                 
152                 if (format == 7) {
153             /* Custom Picture Format (CPFMT) */
154                 
155             put_bits(&s->pb,4,2); /* Aspect ratio: CIF 12:11 (4:3) picture */
156             put_bits(&s->pb,9,(s->width >> 2) - 1);
157             put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
158             put_bits(&s->pb,9,(s->height >> 2));
159         }
160         
161         /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
162         if (s->umvplus)
163             put_bits(&s->pb,1,1); /* Limited according tables of Annex D */
164         put_bits(&s->pb, 5, s->qscale);
165     }
166
167     put_bits(&s->pb, 1, 0);     /* no PEI */
168 }
169
170 int h263_encode_gob_header(MpegEncContext * s, int mb_line)
171 {
172     int pdif=0;
173     
174     /* Check to see if we need to put a new GBSC */
175     /* for RTP packetization                    */
176     if (s->rtp_mode) {
177         pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
178         if (pdif >= s->rtp_payload_size) {
179             /* Bad luck, packet must be cut before */
180             align_put_bits(&s->pb);
181             flush_put_bits(&s->pb);
182             /* Call the RTP callback to send the last GOB */
183             if (s->rtp_callback) {
184                 pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
185                 s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
186             }
187             s->ptr_lastgob = pbBufPtr(&s->pb);
188             put_bits(&s->pb, 17, 1); /* GBSC */
189             s->gob_number = mb_line / s->gob_index;
190             put_bits(&s->pb, 5, s->gob_number); /* GN */
191             put_bits(&s->pb, 2, s->pict_type == I_TYPE); /* GFID */
192             put_bits(&s->pb, 5, s->qscale); /* GQUANT */
193             //fprintf(stderr,"\nGOB: %2d size: %d", s->gob_number - 1, pdif);
194             return pdif;
195        } else if (pdif + s->mb_line_avgsize >= s->rtp_payload_size) {
196            /* Cut the packet before we can't */
197            align_put_bits(&s->pb);
198            flush_put_bits(&s->pb);
199            /* Call the RTP callback to send the last GOB */
200            if (s->rtp_callback) {
201                pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
202                s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
203            }
204            s->ptr_lastgob = pbBufPtr(&s->pb);
205            put_bits(&s->pb, 17, 1); /* GBSC */
206            s->gob_number = mb_line / s->gob_index;
207            put_bits(&s->pb, 5, s->gob_number); /* GN */
208            put_bits(&s->pb, 2, s->pict_type == I_TYPE); /* GFID */
209            put_bits(&s->pb, 5, s->qscale); /* GQUANT */
210            //fprintf(stderr,"\nGOB: %2d size: %d", s->gob_number - 1, pdif);
211            return pdif;
212        }
213    }
214    return 0;
215 }
216
217 static inline int decide_ac_pred(MpegEncContext * s, DCTELEM block[6][64], int dir[6])
218 {
219     int score0=0, score1=0;
220     int i, n;
221
222     for(n=0; n<6; n++){
223         INT16 *ac_val, *ac_val1;
224
225         ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
226         ac_val1= ac_val;
227         if(dir[n]){
228             ac_val-= s->block_wrap[n]*16;
229             for(i=1; i<8; i++){
230                 const int level= block[n][block_permute_op(i   )];
231                 score0+= ABS(level);
232                 score1+= ABS(level - ac_val[i+8]);
233                 ac_val1[i  ]=    block[n][block_permute_op(i<<3)];
234                 ac_val1[i+8]= level;
235             }
236         }else{
237             ac_val-= 16;
238             for(i=1; i<8; i++){
239                 const int level= block[n][block_permute_op(i<<3)];
240                 score0+= ABS(level);
241                 score1+= ABS(level - ac_val[i]);
242                 ac_val1[i  ]= level;
243                 ac_val1[i+8]=    block[n][block_permute_op(i   )];
244             }
245         }
246     }
247
248     return score0 > score1 ? 1 : 0;    
249 }
250
251 void mpeg4_encode_mb(MpegEncContext * s,
252                     DCTELEM block[6][64],
253                     int motion_x, int motion_y)
254 {
255     int cbpc, cbpy, i, cbp, pred_x, pred_y;
256     int bits;
257     
258     //    printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
259     if (!s->mb_intra) {
260         /* compute cbp */
261         cbp = 0;
262         for (i = 0; i < 6; i++) {
263         if (s->block_last_index[i] >= 0)
264             cbp |= 1 << (5 - i);
265         }
266         if ((cbp | motion_x | motion_y) == 0 && s->mv_type==MV_TYPE_16X16) {
267             /* skip macroblock */
268             put_bits(&s->pb, 1, 1);
269             s->misc_bits++;
270             s->last_bits++;
271             s->skip_count++;
272             return;
273         }
274         put_bits(&s->pb, 1, 0); /* mb coded */
275         if(s->mv_type==MV_TYPE_16X16){
276             cbpc = cbp & 3;
277             put_bits(&s->pb,
278                     inter_MCBPC_bits[cbpc],
279                     inter_MCBPC_code[cbpc]);
280             cbpy = cbp >> 2;
281             cbpy ^= 0xf;
282             put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
283                 
284             bits= get_bit_count(&s->pb);
285             s->misc_bits+= bits - s->last_bits;
286             s->last_bits=bits;
287
288             /* motion vectors: 16x16 mode */
289             h263_pred_motion(s, 0, &pred_x, &pred_y);
290         
291             h263_encode_motion(s, motion_x - pred_x);
292             h263_encode_motion(s, motion_y - pred_y);
293         }else{
294             cbpc = (cbp & 3)+16;
295             put_bits(&s->pb,
296                     inter_MCBPC_bits[cbpc],
297                     inter_MCBPC_code[cbpc]);
298             cbpy = cbp >> 2;
299             cbpy ^= 0xf;
300             put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
301
302             bits= get_bit_count(&s->pb);
303             s->misc_bits+= bits - s->last_bits;
304             s->last_bits=bits;
305
306             for(i=0; i<4; i++){
307                 /* motion vectors: 8x8 mode*/
308                 h263_pred_motion(s, i, &pred_x, &pred_y);
309
310                 h263_encode_motion(s, s->motion_val[ s->block_index[i] ][0] - pred_x);
311                 h263_encode_motion(s, s->motion_val[ s->block_index[i] ][1] - pred_y);
312             }
313         }
314         bits= get_bit_count(&s->pb);
315         s->mv_bits+= bits - s->last_bits;
316         s->last_bits=bits;
317
318         /* encode each block */
319         for (i = 0; i < 6; i++) {
320             mpeg4_encode_block(s, block[i], i, 0, zigzag_direct);
321         }
322         bits= get_bit_count(&s->pb);
323         s->p_tex_bits+= bits - s->last_bits;
324         s->last_bits=bits;
325         s->p_count++;
326     } else {
327         int dc_diff[6];   //dc values with the dc prediction subtracted 
328         int dir[6];  //prediction direction
329         int zigzag_last_index[6];
330         UINT8 *scan_table[6];
331
332         for(i=0; i<6; i++){
333             const int level= block[i][0];
334             UINT16 *dc_ptr;
335
336             dc_diff[i]= level - mpeg4_pred_dc(s, i, &dc_ptr, &dir[i]);
337             if (i < 4) {
338                 *dc_ptr = level * s->y_dc_scale;
339             } else {
340                 *dc_ptr = level * s->c_dc_scale;
341             }
342         }
343
344         s->ac_pred= decide_ac_pred(s, block, dir);
345
346         if(s->ac_pred){
347             for(i=0; i<6; i++){
348                 UINT8 *st;
349                 int last_index;
350
351                 mpeg4_inv_pred_ac(s, block[i], i, dir[i]);
352                 if (dir[i]==0) st = ff_alternate_vertical_scan; /* left */
353                 else           st = ff_alternate_horizontal_scan; /* top */
354
355                 for(last_index=63; last_index>=0; last_index--) //FIXME optimize
356                     if(block[i][st[last_index]]) break;
357                 zigzag_last_index[i]= s->block_last_index[i];
358                 s->block_last_index[i]= last_index;
359                 scan_table[i]= st;
360             }
361         }else{
362             for(i=0; i<6; i++)
363                 scan_table[i]= zigzag_direct;
364         }
365
366         /* compute cbp */
367         cbp = 0;
368         for (i = 0; i < 6; i++) {
369             if (s->block_last_index[i] >= 1)
370                 cbp |= 1 << (5 - i);
371         }
372
373         cbpc = cbp & 3;
374         if (s->pict_type == I_TYPE) {
375             put_bits(&s->pb,
376                 intra_MCBPC_bits[cbpc],
377                 intra_MCBPC_code[cbpc]);
378         } else {
379             put_bits(&s->pb, 1, 0);     /* mb coded */
380             put_bits(&s->pb,
381                 inter_MCBPC_bits[cbpc + 4],
382                 inter_MCBPC_code[cbpc + 4]);
383         }
384         put_bits(&s->pb, 1, s->ac_pred);
385         cbpy = cbp >> 2;
386         put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
387
388         bits= get_bit_count(&s->pb);
389         s->misc_bits+= bits - s->last_bits;
390         s->last_bits=bits;
391
392         /* encode each block */
393         for (i = 0; i < 6; i++) {
394             mpeg4_encode_block(s, block[i], i, dc_diff[i], scan_table[i]);
395         }
396
397         bits= get_bit_count(&s->pb);
398         s->i_tex_bits+= bits - s->last_bits;
399         s->last_bits=bits;
400         s->i_count++;
401
402         /* restore ac coeffs & last_index stuff if we messed them up with the prediction */
403         if(s->ac_pred){
404             for(i=0; i<6; i++){
405                 int j;    
406                 INT16 *ac_val;
407
408                 ac_val = s->ac_val[0][0] + s->block_index[i] * 16;
409
410                 if(dir[i]){
411                     for(j=1; j<8; j++) 
412                         block[i][block_permute_op(j   )]= ac_val[j+8];
413                 }else{
414                     for(j=1; j<8; j++) 
415                         block[i][block_permute_op(j<<3)]= ac_val[j  ];
416                 }
417                 s->block_last_index[i]= zigzag_last_index[i];
418             }
419         }
420     }
421 }
422
423 void h263_encode_mb(MpegEncContext * s,
424                     DCTELEM block[6][64],
425                     int motion_x, int motion_y)
426 {
427     int cbpc, cbpy, i, cbp, pred_x, pred_y;
428    
429     //    printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
430    if (!s->mb_intra) {
431            /* compute cbp */
432            cbp = 0;
433            for (i = 0; i < 6; i++) {
434               if (s->block_last_index[i] >= 0)
435                    cbp |= 1 << (5 - i);
436            }
437            if ((cbp | motion_x | motion_y) == 0) {
438               /* skip macroblock */
439               put_bits(&s->pb, 1, 1);
440               return;
441            }
442            put_bits(&s->pb, 1, 0);      /* mb coded */
443            cbpc = cbp & 3;
444            put_bits(&s->pb,
445                 inter_MCBPC_bits[cbpc],
446                 inter_MCBPC_code[cbpc]);
447            cbpy = cbp >> 2;
448            cbpy ^= 0xf;
449            put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
450
451            /* motion vectors: 16x16 mode only now */
452       h263_pred_motion(s, 0, &pred_x, &pred_y);
453       
454       if (!s->umvplus) {  
455          h263_encode_motion(s, motion_x - pred_x);
456          h263_encode_motion(s, motion_y - pred_y);
457       }
458       else {
459          h263p_encode_umotion(s, motion_x - pred_x);
460          h263p_encode_umotion(s, motion_y - pred_y);
461          if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
462             /* To prevent Start Code emulation */
463             put_bits(&s->pb,1,1);
464       }
465    } else {
466         /* compute cbp */
467         cbp = 0;
468         for (i = 0; i < 6; i++) {
469             if (s->block_last_index[i] >= 1)
470                 cbp |= 1 << (5 - i);
471         }
472
473         cbpc = cbp & 3;
474         if (s->pict_type == I_TYPE) {
475             put_bits(&s->pb,
476                      intra_MCBPC_bits[cbpc],
477                      intra_MCBPC_code[cbpc]);
478         } else {
479             put_bits(&s->pb, 1, 0);     /* mb coded */
480             put_bits(&s->pb,
481                      inter_MCBPC_bits[cbpc + 4],
482                      inter_MCBPC_code[cbpc + 4]);
483         }
484         if (s->h263_pred) {
485             /* XXX: currently, we do not try to use ac prediction */
486             put_bits(&s->pb, 1, 0);     /* no ac prediction */
487         }
488         cbpy = cbp >> 2;
489         put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
490     }
491
492     /* encode each block */
493     for (i = 0; i < 6; i++) {
494         h263_encode_block(s, block[i], i);
495     }
496 }
497
498 void h263_pred_acdc(MpegEncContext * s, INT16 *block, int n)
499 {
500     int x, y, wrap, a, c, pred_dc, scale, i;
501     INT16 *dc_val, *ac_val, *ac_val1;
502
503     /* find prediction */
504     if (n < 4) {
505         x = 2 * s->mb_x + 1 + (n & 1);
506         y = 2 * s->mb_y + 1 + ((n & 2) >> 1);
507         wrap = s->mb_width * 2 + 2;
508         dc_val = s->dc_val[0];
509         ac_val = s->ac_val[0][0];
510         scale = s->y_dc_scale;
511     } else {
512         x = s->mb_x + 1;
513         y = s->mb_y + 1;
514         wrap = s->mb_width + 2;
515         dc_val = s->dc_val[n - 4 + 1];
516         ac_val = s->ac_val[n - 4 + 1][0];
517         scale = s->c_dc_scale;
518     }
519     
520     ac_val += ((y) * wrap + (x)) * 16;
521     ac_val1 = ac_val;
522     
523     /* B C
524      * A X 
525      */
526     a = dc_val[(x - 1) + (y) * wrap];
527     c = dc_val[(x) + (y - 1) * wrap];
528     
529     pred_dc = 1024;
530     if (s->ac_pred) {
531         if (s->h263_aic_dir) {
532             /* left prediction */
533             if (a != 1024) {
534                 ac_val -= 16;
535                 for(i=1;i<8;i++) {
536                     block[block_permute_op(i*8)] += ac_val[i];
537                 }
538                 pred_dc = a;
539             }
540         } else {
541             /* top prediction */
542             if (c != 1024) {
543                 ac_val -= 16 * wrap;
544                 for(i=1;i<8;i++) {
545                     block[block_permute_op(i)] += ac_val[i + 8];
546                 }
547                 pred_dc = c;
548             }
549         }
550     } else {
551         /* just DC prediction */
552         if (a != 1024 && c != 1024)
553             pred_dc = (a + c) >> 1;
554         else if (a != 1024)
555             pred_dc = a;
556         else
557             pred_dc = c;
558     }
559     
560     /* we assume pred is positive */
561     block[0]=block[0]*scale + pred_dc;
562     
563     if (block[0] < 0)
564         block[0] = 0;
565     else if (!(block[0] & 1))
566         block[0]++;
567     
568     /* Update AC/DC tables */
569     dc_val[(x) + (y) * wrap] = block[0];
570     
571     /* left copy */
572     for(i=1;i<8;i++)
573         ac_val1[i] = block[block_permute_op(i * 8)];
574     /* top copy */
575     for(i=1;i<8;i++)
576         ac_val1[8 + i] = block[block_permute_op(i)];
577 }
578
579 INT16 *h263_pred_motion(MpegEncContext * s, int block, 
580                         int *px, int *py)
581 {
582     int xy, wrap;
583     INT16 *A, *B, *C, *mot_val;
584     static const int off[4]= {2, 1, 1, -1};
585
586     wrap = s->block_wrap[0];
587     xy = s->block_index[block];
588
589     mot_val = s->motion_val[xy];
590
591     /* special case for first line */
592     if ((s->mb_y == 0 || s->first_slice_line || s->first_gob_line) && block<2) {
593         A = s->motion_val[xy - 1];
594         *px = A[0];
595         *py = A[1];
596     } else {
597         A = s->motion_val[xy - 1];
598         B = s->motion_val[xy - wrap];
599         C = s->motion_val[xy + off[block] - wrap];
600         *px = mid_pred(A[0], B[0], C[0]);
601         *py = mid_pred(A[1], B[1], C[1]);
602     }
603     return mot_val;
604 }
605
606 static void h263_encode_motion(MpegEncContext * s, int val)
607 {
608     int range, l, m, bit_size, sign, code, bits;
609
610     if (val == 0) {
611         /* zero vector */
612         code = 0;
613         put_bits(&s->pb, mvtab[code][1], mvtab[code][0]);
614     } else {
615         bit_size = s->f_code - 1;
616         range = 1 << bit_size;
617         /* modulo encoding */
618         l = range * 32;
619         m = 2 * l;
620         if (val < -l) {
621             val += m;
622         } else if (val >= l) {
623             val -= m;
624         }
625
626         if (val >= 0) {
627             sign = 0;
628         } else {
629             val = -val;
630             sign = 1;
631         }
632         val--;
633         code = (val >> bit_size) + 1;
634         bits = val & (range - 1);
635
636         put_bits(&s->pb, mvtab[code][1] + 1, (mvtab[code][0] << 1) | sign); 
637         if (bit_size > 0) {
638             put_bits(&s->pb, bit_size, bits);
639         }
640     }
641 }
642
643 /* Encode MV differences on H.263+ with Unrestricted MV mode */
644 static void h263p_encode_umotion(MpegEncContext * s, int val)
645 {
646     short sval = 0; 
647     short i = 0;
648     short n_bits = 0;
649     short temp_val;
650     int code = 0;
651     int tcode;
652     
653     if ( val == 0)
654         put_bits(&s->pb, 1, 1);
655     else if (val == 1)
656         put_bits(&s->pb, 3, 0);
657     else if (val == -1)
658         put_bits(&s->pb, 3, 2);
659     else {
660         
661         sval = ((val < 0) ? (short)(-val):(short)val);
662         temp_val = sval;
663         
664         while (temp_val != 0) {
665             temp_val = temp_val >> 1;
666             n_bits++;
667         }
668         
669         i = n_bits - 1;
670         while (i > 0) {
671             tcode = (sval & (1 << (i-1))) >> (i-1);
672             tcode = (tcode << 1) | 1;
673             code = (code << 2) | tcode;
674             i--;
675         }
676         code = ((code << 1) | (val < 0)) << 1;
677         put_bits(&s->pb, (2*n_bits)+1, code);
678         //printf("\nVal = %d\tCode = %d", sval, code);
679     }
680 }
681
682 static void init_mv_penalty_and_fcode(MpegEncContext *s)
683 {
684     int f_code;
685     int mv;
686     for(f_code=1; f_code<=MAX_FCODE; f_code++){
687         for(mv=-MAX_MV; mv<=MAX_MV; mv++){
688             int len;
689
690             if(mv==0) len= mvtab[0][1];
691             else{
692                 int val, bit_size, range, code;
693
694                 bit_size = s->f_code - 1;
695                 range = 1 << bit_size;
696
697                 val=mv;
698                 if (val < 0) 
699                     val = -val;
700                 val--;
701                 code = (val >> bit_size) + 1;
702                 if(code<33){
703                     len= mvtab[code][1] + 1 + bit_size;
704                 }else{
705                     len= mvtab[32][1] + 2 + bit_size;
706                 }
707             }
708
709             mv_penalty[f_code][mv+MAX_MV]= len;
710         }
711     }
712
713     for(f_code=MAX_FCODE; f_code>0; f_code--){
714         for(mv=-(16<<f_code); mv<(16<<f_code); mv++){
715             fcode_tab[mv+MAX_MV]= f_code;
716         }
717     }
718
719     for(mv=0; mv<MAX_MV*2+1; mv++){
720         umv_fcode_tab[mv]= 1;
721     }
722 }
723
724 static void init_uni_dc_tab()
725 {
726     int level, uni_code, uni_len;
727
728     for(level=-256; level<256; level++){
729         int size, v, l;
730         /* find number of bits */
731         size = 0;
732         v = abs(level);
733         while (v) {
734             v >>= 1;
735             size++;
736         }
737
738         if (level < 0)
739             l= (-level) ^ ((1 << size) - 1);
740         else
741             l= level;
742
743         /* luminance */
744         uni_code= DCtab_lum[size][0];
745         uni_len = DCtab_lum[size][1];
746
747         if (size > 0) {
748             uni_code<<=size; uni_code|=l;
749             uni_len+=size;
750             if (size > 8){
751                 uni_code<<=1; uni_code|=1;
752                 uni_len++;
753             }
754         }
755         uni_DCtab_lum[level+256][0]= uni_code;
756         uni_DCtab_lum[level+256][1]= uni_len;
757
758         /* chrominance */
759         uni_code= DCtab_chrom[size][0];
760         uni_len = DCtab_chrom[size][1];
761         
762         if (size > 0) {
763             uni_code<<=size; uni_code|=l;
764             uni_len+=size;
765             if (size > 8){
766                 uni_code<<=1; uni_code|=1;
767                 uni_len++;
768             }
769         }
770         uni_DCtab_chrom[level+256][0]= uni_code;
771         uni_DCtab_chrom[level+256][1]= uni_len;
772
773     }
774 }
775
776 void h263_encode_init(MpegEncContext *s)
777 {
778     static int done = 0;
779
780     if (!done) {
781         done = 1;
782
783         init_uni_dc_tab();
784
785         init_rl(&rl_inter);
786         init_rl(&rl_intra);
787
788         init_mv_penalty_and_fcode(s);
789     }
790     s->mv_penalty= mv_penalty; //FIXME exact table for msmpeg4 & h263p
791     
792     // use fcodes >1 only for mpeg4 & h263 & h263p FIXME
793     if(s->h263_plus) s->fcode_tab= umv_fcode_tab;
794     else if(s->h263_pred && !s->h263_msmpeg4) s->fcode_tab= fcode_tab;
795 }
796
797 static void h263_encode_block(MpegEncContext * s, DCTELEM * block, int n)
798 {
799     int level, run, last, i, j, last_index, last_non_zero, sign, slevel;
800     int code;
801     RLTable *rl = &rl_inter;
802
803     if (s->mb_intra) {
804         /* DC coef */
805             level = block[0];
806         /* 255 cannot be represented, so we clamp */
807         if (level > 254) {
808             level = 254;
809             block[0] = 254;
810         }
811         /* 0 cannot be represented also */
812         else if (!level) {
813             level = 1;
814             block[0] = 1;
815         }
816             if (level == 128)
817                 put_bits(&s->pb, 8, 0xff);
818             else
819                 put_bits(&s->pb, 8, level & 0xff);
820             i = 1;
821     } else {
822             i = 0;
823     }
824
825     /* AC coefs */
826     last_index = s->block_last_index[n];
827     last_non_zero = i - 1;
828     for (; i <= last_index; i++) {
829         j = zigzag_direct[i];
830         level = block[j];
831         if (level) {
832             run = i - last_non_zero - 1;
833             last = (i == last_index);
834             sign = 0;
835             slevel = level;
836             if (level < 0) {
837                 sign = 1;
838                 level = -level;
839             }
840             code = get_rl_index(rl, last, run, level);
841             put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
842             if (code == rl->n) {
843                 put_bits(&s->pb, 1, last);
844                 put_bits(&s->pb, 6, run);
845                 put_bits(&s->pb, 8, slevel & 0xff);
846             } else {
847                 put_bits(&s->pb, 1, sign);
848             }
849             last_non_zero = i;
850         }
851     }
852 }
853
854 /***************************************************/
855
856 static void mpeg4_stuffing(PutBitContext * pbc)
857 {
858     int length;
859     put_bits(pbc, 1, 0);
860     length= (-get_bit_count(pbc))&7;
861     put_bits(pbc, length, (1<<length)-1);
862 }
863
864 static void put_string(PutBitContext * pbc, char *s)
865 {
866     while(*s){
867         put_bits(pbc, 8, *s);
868         s++;
869     }
870     put_bits(pbc, 8, 0);
871 }
872
873 static void mpeg4_encode_vol_header(MpegEncContext * s)
874 {
875     int vo_ver_id=1; //must be 2 if we want GMC or q-pel
876     char buf[255];
877     
878     if(get_bit_count(&s->pb)!=0) mpeg4_stuffing(&s->pb);
879     put_bits(&s->pb, 16, 0);
880     put_bits(&s->pb, 16, 0x100);        /* video obj */
881     put_bits(&s->pb, 16, 0);
882     put_bits(&s->pb, 16, 0x120);        /* video obj layer */
883
884     put_bits(&s->pb, 1, 0);             /* random access vol */
885     put_bits(&s->pb, 8, 1);             /* video obj type indication= simple obj */
886     put_bits(&s->pb, 1, 1);             /* is obj layer id= yes */
887       put_bits(&s->pb, 4, vo_ver_id);   /* is obj layer ver id */
888       put_bits(&s->pb, 3, 1);           /* is obj layer priority */
889     if(s->aspect_ratio_info) 
890         put_bits(&s->pb, 4, s->aspect_ratio_info);/* aspect ratio info */
891     else
892         put_bits(&s->pb, 4, 1);         /* aspect ratio info= sqare pixel */
893     put_bits(&s->pb, 1, 0);             /* vol control parameters= no */
894     put_bits(&s->pb, 2, RECT_SHAPE);    /* vol shape= rectangle */
895     put_bits(&s->pb, 1, 1);             /* marker bit */
896     put_bits(&s->pb, 16, s->time_increment_resolution=30000);
897     s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;
898     if (s->time_increment_bits < 1)
899         s->time_increment_bits = 1;
900     put_bits(&s->pb, 1, 1);             /* marker bit */
901     put_bits(&s->pb, 1, 0);             /* fixed vop rate=no */
902     put_bits(&s->pb, 1, 1);             /* marker bit */
903     put_bits(&s->pb, 13, s->width);     /* vol width */
904     put_bits(&s->pb, 1, 1);             /* marker bit */
905     put_bits(&s->pb, 13, s->height);    /* vol height */
906     put_bits(&s->pb, 1, 1);             /* marker bit */
907     put_bits(&s->pb, 1, 0);             /* interlace */
908     put_bits(&s->pb, 1, 1);             /* obmc disable */
909     if (vo_ver_id == 1) {
910         put_bits(&s->pb, 1, s->vol_sprite_usage=0);             /* sprite enable */
911     }else{ /* vo_ver_id == 2 */
912         put_bits(&s->pb, 2, s->vol_sprite_usage=0);             /* sprite enable */
913     }
914     put_bits(&s->pb, 1, 0);             /* not 8 bit */
915     put_bits(&s->pb, 1, 0);             /* quant type= h263 style*/
916     if (vo_ver_id != 1)
917         put_bits(&s->pb, 1, s->quarter_sample=0);
918     put_bits(&s->pb, 1, 1);             /* complexity estimation disable */
919     put_bits(&s->pb, 1, 1);             /* resync marker disable */
920     put_bits(&s->pb, 1, 0);             /* data partitioned */
921     if (vo_ver_id != 1){
922         put_bits(&s->pb, 1, 0);         /* newpred */
923         put_bits(&s->pb, 1, 0);         /* reduced res vop */
924     }
925     put_bits(&s->pb, 1, 0);             /* scalability */
926
927     mpeg4_stuffing(&s->pb);
928     put_bits(&s->pb, 16, 0);
929     put_bits(&s->pb, 16, 0x1B2);        /* user_data */
930     sprintf(buf, "FFmpeg v%s / libavcodec build: %s", FFMPEG_VERSION, LIBAVCODEC_BUILD_STR);
931     put_string(&s->pb, buf);
932
933     s->no_rounding = 0;
934 }
935
936 /* write mpeg4 VOP header */
937 void mpeg4_encode_picture_header(MpegEncContext * s, int picture_number)
938 {
939     if(s->pict_type==I_TYPE) mpeg4_encode_vol_header(s);
940
941     if(get_bit_count(&s->pb)!=0) mpeg4_stuffing(&s->pb);
942     put_bits(&s->pb, 16, 0);            /* vop header */
943     put_bits(&s->pb, 16, 0x1B6);        /* vop header */
944     put_bits(&s->pb, 2, s->pict_type - 1);      /* pict type: I = 0 , P = 1 */
945     /* XXX: time base + 1 not always correct */
946     put_bits(&s->pb, 1, 1);
947     put_bits(&s->pb, 1, 0);
948
949     put_bits(&s->pb, 1, 1);     /* marker */
950     put_bits(&s->pb, s->time_increment_bits, 1);        /* XXX: correct time increment */
951     put_bits(&s->pb, 1, 1);     /* marker */
952     put_bits(&s->pb, 1, 1);     /* vop coded */
953     if (    s->pict_type == P_TYPE 
954         || (s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE)) {
955         s->no_rounding ^= 1;
956         put_bits(&s->pb, 1, s->no_rounding);    /* rounding type */
957     }
958     put_bits(&s->pb, 3, 0);     /* intra dc VLC threshold */
959     //FIXME sprite stuff
960
961     put_bits(&s->pb, 5, s->qscale);
962
963     if (s->pict_type != I_TYPE)
964         put_bits(&s->pb, 3, s->f_code); /* fcode_for */
965     if (s->pict_type == B_TYPE)
966         put_bits(&s->pb, 3, s->b_code); /* fcode_back */
967     //    printf("****frame %d\n", picture_number);
968 }
969
970 void h263_dc_scale(MpegEncContext * s)
971 {
972 #if 1
973     const static UINT8 y_tab[32]={
974     //  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
975         0, 8, 8, 8, 8,10,12,14,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,34,36,38,40,42,44,46
976     };
977     const static UINT8 c_tab[32]={
978     //  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
979         0, 8, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18,19,20,21,22,23,24,25
980     };
981     s->y_dc_scale = y_tab[s->qscale];
982     s->c_dc_scale = c_tab[s->qscale];
983 #else
984     int quant;
985     quant = s->qscale;
986     /* luminance */
987     if (quant < 5)
988         s->y_dc_scale = 8;
989     else if (quant > 4 && quant < 9)
990         s->y_dc_scale = (2 * quant);
991     else if (quant > 8 && quant < 25)
992         s->y_dc_scale = (quant + 8);
993     else
994         s->y_dc_scale = (2 * quant - 16);
995     /* chrominance */
996     if (quant < 5)
997         s->c_dc_scale = 8;
998     else if (quant > 4 && quant < 25)
999         s->c_dc_scale = ((quant + 13) / 2);
1000     else
1001         s->c_dc_scale = (quant - 6);
1002 #endif
1003 }
1004
1005 static inline int mpeg4_pred_dc(MpegEncContext * s, int n, UINT16 **dc_val_ptr, int *dir_ptr)
1006 {
1007     int a, b, c, wrap, pred, scale;
1008     UINT16 *dc_val;
1009     int dummy;
1010
1011     /* find prediction */
1012     if (n < 4) {
1013         scale = s->y_dc_scale;
1014     } else {
1015         scale = s->c_dc_scale;
1016     }
1017     wrap= s->block_wrap[n];
1018     dc_val = s->dc_val[0] + s->block_index[n];
1019
1020     /* B C
1021      * A X 
1022      */
1023     a = dc_val[ - 1];
1024     b = dc_val[ - 1 - wrap];
1025     c = dc_val[ - wrap];
1026
1027     if (abs(a - b) < abs(b - c)) {
1028         pred = c;
1029         *dir_ptr = 1; /* top */
1030     } else {
1031         pred = a;
1032         *dir_ptr = 0; /* left */
1033     }
1034     /* we assume pred is positive */
1035 #ifdef ARCH_X86
1036         asm volatile (
1037                 "xorl %%edx, %%edx      \n\t"
1038                 "mul %%ecx              \n\t"
1039                 : "=d" (pred), "=a"(dummy)
1040                 : "a" (pred + (scale >> 1)), "c" (inverse[scale])
1041         );
1042 #else
1043     pred = (pred + (scale >> 1)) / scale;
1044 #endif
1045
1046     /* prepare address for prediction update */
1047     *dc_val_ptr = &dc_val[0];
1048
1049     return pred;
1050 }
1051
1052 void mpeg4_pred_ac(MpegEncContext * s, INT16 *block, int n,
1053                    int dir)
1054 {
1055     int i;
1056     INT16 *ac_val, *ac_val1;
1057
1058     /* find prediction */
1059     ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
1060     ac_val1 = ac_val;
1061     if (s->ac_pred) {
1062         if (dir == 0) {
1063             /* left prediction */
1064             ac_val -= 16;
1065             for(i=1;i<8;i++) {
1066                 block[block_permute_op(i*8)] += ac_val[i];
1067             }
1068         } else {
1069             /* top prediction */
1070             ac_val -= 16 * s->block_wrap[n];
1071             for(i=1;i<8;i++) {
1072                 block[block_permute_op(i)] += ac_val[i + 8];
1073             }
1074         }
1075     }
1076     /* left copy */
1077     for(i=1;i<8;i++)
1078         ac_val1[i] = block[block_permute_op(i * 8)];
1079     /* top copy */
1080     for(i=1;i<8;i++)
1081         ac_val1[8 + i] = block[block_permute_op(i)];
1082 }
1083
1084 static void mpeg4_inv_pred_ac(MpegEncContext * s, INT16 *block, int n,
1085                               int dir)
1086 {
1087     int i;
1088     INT16 *ac_val;
1089
1090     /* find prediction */
1091     ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
1092  
1093     if (dir == 0) {
1094         /* left prediction */
1095         ac_val -= 16;
1096         for(i=1;i<8;i++) {
1097             block[block_permute_op(i*8)] -= ac_val[i];
1098         }
1099     } else {
1100         /* top prediction */
1101         ac_val -= 16 * s->block_wrap[n];
1102         for(i=1;i<8;i++) {
1103             block[block_permute_op(i)] -= ac_val[i + 8];
1104         }
1105     }
1106 }
1107
1108 static inline void mpeg4_encode_dc(MpegEncContext * s, int level, int n)
1109 {
1110 #if 1
1111     level+=256;
1112     if (n < 4) {
1113         /* luminance */
1114         put_bits(&s->pb, uni_DCtab_lum[level][1], uni_DCtab_lum[level][0]);
1115     } else {
1116         /* chrominance */
1117         put_bits(&s->pb, uni_DCtab_chrom[level][1], uni_DCtab_chrom[level][0]);
1118     }
1119 #else
1120     int size, v;
1121     /* find number of bits */
1122     size = 0;
1123     v = abs(level);
1124     while (v) {
1125         v >>= 1;
1126         size++;
1127     }
1128
1129     if (n < 4) {
1130         /* luminance */
1131         put_bits(&s->pb, DCtab_lum[size][1], DCtab_lum[size][0]);
1132     } else {
1133         /* chrominance */
1134         put_bits(&s->pb, DCtab_chrom[size][1], DCtab_chrom[size][0]);
1135     }
1136
1137     /* encode remaining bits */
1138     if (size > 0) {
1139         if (level < 0)
1140             level = (-level) ^ ((1 << size) - 1);
1141         put_bits(&s->pb, size, level);
1142         if (size > 8)
1143             put_bits(&s->pb, 1, 1);
1144     }
1145 #endif
1146 }
1147
1148 static void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block, int n, int intra_dc, UINT8 *scan_table)
1149 {
1150     int level, run, last, i, j, last_index, last_non_zero, sign, slevel;
1151     int code;
1152     const RLTable *rl;
1153
1154     if (s->mb_intra) {
1155         /* mpeg4 based DC predictor */
1156         mpeg4_encode_dc(s, intra_dc, n);
1157         i = 1;
1158         rl = &rl_intra;
1159     } else {
1160         i = 0;
1161         rl = &rl_inter;
1162     }
1163
1164     /* AC coefs */
1165     last_index = s->block_last_index[n];
1166     last_non_zero = i - 1;
1167     for (; i <= last_index; i++) {
1168         j = scan_table[i];
1169         level = block[j];
1170         if (level) {
1171             run = i - last_non_zero - 1;
1172             last = (i == last_index);
1173             sign = 0;
1174             slevel = level;
1175             if (level < 0) {
1176                 sign = 1;
1177                 level = -level;
1178             }
1179             code = get_rl_index(rl, last, run, level);
1180             put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
1181             if (code == rl->n) {
1182                 int level1, run1;
1183                 level1 = level - rl->max_level[last][run];
1184                 if (level1 < 1) 
1185                     goto esc2;
1186                 code = get_rl_index(rl, last, run, level1);
1187                 if (code == rl->n) {
1188                 esc2:
1189                     put_bits(&s->pb, 1, 1);
1190                     if (level > MAX_LEVEL)
1191                         goto esc3;
1192                     run1 = run - rl->max_run[last][level] - 1;
1193                     if (run1 < 0)
1194                         goto esc3;
1195                     code = get_rl_index(rl, last, run1, level);
1196                     if (code == rl->n) {
1197                     esc3:
1198                         /* third escape */
1199                         put_bits(&s->pb, 1, 1);
1200                         put_bits(&s->pb, 1, last);
1201                         put_bits(&s->pb, 6, run);
1202                         put_bits(&s->pb, 1, 1);
1203                         put_bits(&s->pb, 12, slevel & 0xfff);
1204                         put_bits(&s->pb, 1, 1);
1205                     } else {
1206                         /* second escape */
1207                         put_bits(&s->pb, 1, 0);
1208                         put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
1209                         put_bits(&s->pb, 1, sign);
1210                     }
1211                 } else {
1212                     /* first escape */
1213                     put_bits(&s->pb, 1, 0);
1214                     put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
1215                     put_bits(&s->pb, 1, sign);
1216                 }
1217             } else {
1218                 put_bits(&s->pb, 1, sign);
1219             }
1220             last_non_zero = i;
1221         }
1222     }
1223 }
1224
1225
1226
1227 /***********************************************/
1228 /* decoding */
1229
1230 static VLC intra_MCBPC_vlc;
1231 static VLC inter_MCBPC_vlc;
1232 static VLC cbpy_vlc;
1233 static VLC mv_vlc;
1234 static VLC dc_lum, dc_chrom;
1235 static VLC sprite_trajectory;
1236 static VLC mb_type_b_vlc;
1237
1238 void init_rl(RLTable *rl)
1239 {
1240     INT8 max_level[MAX_RUN+1], max_run[MAX_LEVEL+1];
1241     UINT8 index_run[MAX_RUN+1];
1242     int last, run, level, start, end, i;
1243
1244     /* compute max_level[], max_run[] and index_run[] */
1245     for(last=0;last<2;last++) {
1246         if (last == 0) {
1247             start = 0;
1248             end = rl->last;
1249         } else {
1250             start = rl->last;
1251             end = rl->n;
1252         }
1253
1254         memset(max_level, 0, MAX_RUN + 1);
1255         memset(max_run, 0, MAX_LEVEL + 1);
1256         memset(index_run, rl->n, MAX_RUN + 1);
1257         for(i=start;i<end;i++) {
1258             run = rl->table_run[i];
1259             level = rl->table_level[i];
1260             if (index_run[run] == rl->n)
1261                 index_run[run] = i;
1262             if (level > max_level[run])
1263                 max_level[run] = level;
1264             if (run > max_run[level])
1265                 max_run[level] = run;
1266         }
1267         rl->max_level[last] = malloc(MAX_RUN + 1);
1268         memcpy(rl->max_level[last], max_level, MAX_RUN + 1);
1269         rl->max_run[last] = malloc(MAX_LEVEL + 1);
1270         memcpy(rl->max_run[last], max_run, MAX_LEVEL + 1);
1271         rl->index_run[last] = malloc(MAX_RUN + 1);
1272         memcpy(rl->index_run[last], index_run, MAX_RUN + 1);
1273     }
1274 }
1275
1276 void init_vlc_rl(RLTable *rl)
1277 {
1278     init_vlc(&rl->vlc, 9, rl->n + 1, 
1279              &rl->table_vlc[0][1], 4, 2,
1280              &rl->table_vlc[0][0], 4, 2);
1281 }
1282
1283 /* init vlcs */
1284
1285 /* XXX: find a better solution to handle static init */
1286 void h263_decode_init_vlc(MpegEncContext *s)
1287 {
1288     static int done = 0;
1289
1290     if (!done) {
1291         done = 1;
1292
1293         init_vlc(&intra_MCBPC_vlc, 6, 8, 
1294                  intra_MCBPC_bits, 1, 1,
1295                  intra_MCBPC_code, 1, 1);
1296         init_vlc(&inter_MCBPC_vlc, 9, 25, 
1297                  inter_MCBPC_bits, 1, 1,
1298                  inter_MCBPC_code, 1, 1);
1299         init_vlc(&cbpy_vlc, 6, 16,
1300                  &cbpy_tab[0][1], 2, 1,
1301                  &cbpy_tab[0][0], 2, 1);
1302         init_vlc(&mv_vlc, 9, 33,
1303                  &mvtab[0][1], 2, 1,
1304                  &mvtab[0][0], 2, 1);
1305         init_rl(&rl_inter);
1306         init_rl(&rl_intra);
1307         init_rl(&rl_intra_aic);
1308         init_vlc_rl(&rl_inter);
1309         init_vlc_rl(&rl_intra);
1310         init_vlc_rl(&rl_intra_aic);
1311         init_vlc(&dc_lum, 9, 13,
1312                  &DCtab_lum[0][1], 2, 1,
1313                  &DCtab_lum[0][0], 2, 1);
1314         init_vlc(&dc_chrom, 9, 13,
1315                  &DCtab_chrom[0][1], 2, 1,
1316                  &DCtab_chrom[0][0], 2, 1);
1317         init_vlc(&sprite_trajectory, 9, 15,
1318                  &sprite_trajectory_tab[0][1], 4, 2,
1319                  &sprite_trajectory_tab[0][0], 4, 2);
1320         init_vlc(&mb_type_b_vlc, 4, 4,
1321                  &mb_type_b_tab[0][1], 2, 1,
1322                  &mb_type_b_tab[0][0], 2, 1);
1323     }
1324 }
1325
1326 int h263_decode_gob_header(MpegEncContext *s)
1327 {
1328     unsigned int val, gfid;
1329     
1330     /* Check for GOB Start Code */
1331     val = show_bits(&s->gb, 16);
1332     if (val == 0) {
1333         /* We have a GBSC probably with GSTUFF */
1334         skip_bits(&s->gb, 16); /* Drop the zeros */
1335         while (get_bits1(&s->gb) == 0); /* Seek the '1' bit */
1336 #ifdef DEBUG
1337         fprintf(stderr,"\nGOB Start Code at MB %d\n", (s->mb_y * s->mb_width) + s->mb_x);
1338 #endif
1339         s->gob_number = get_bits(&s->gb, 5); /* GN */
1340         gfid = get_bits(&s->gb, 2); /* GFID */
1341         s->qscale = get_bits(&s->gb, 5); /* GQUANT */
1342 #ifdef DEBUG
1343         fprintf(stderr, "\nGN: %u GFID: %u Quant: %u\n", s->gob_number, gfid, s->qscale);
1344 #endif
1345         return 1;
1346     }
1347     return 0;
1348             
1349 }
1350
1351 static inline void memsetw(short *tab, int val, int n)
1352 {
1353     int i;
1354     for(i=0;i<n;i++)
1355         tab[i] = val;
1356 }
1357
1358 static int mpeg4_resync(MpegEncContext *s)
1359 {
1360     int state, v, bits;
1361     int mb_num_bits= av_log2(s->mb_num - 1) + 1;
1362     int header_extension=0, mb_num;
1363     int c_wrap, c_xy, l_wrap, l_xy;
1364 //printf("resync at %d %d\n", s->mb_x, s->mb_y);
1365 //printf("%X\n", show_bits(&s->gb, 24));
1366
1367     if( get_bits_count(&s->gb) > s->gb.size*8-32)
1368         return 0;
1369
1370     align_get_bits(&s->gb);
1371     state = 0xff;
1372     for(;;) {
1373         v = get_bits(&s->gb, 8);
1374 //printf("%X ", v);
1375         state = ((state << 8) | v) & 0xffff;
1376         if (state == 0) break;
1377         if( get_bits_count(&s->gb) > s->gb.size*8-32){
1378             printf("resync failed\n");
1379             return -1;
1380         }
1381     }
1382 //printf("%X\n", show_bits(&s->gb, 24));
1383     bits=0;
1384     while(!get_bits1(&s->gb) && bits<30) bits++;
1385     if(s->pict_type == P_TYPE && bits != s->f_code-1)
1386         printf("marker does not match f_code\n");
1387     //FIXME check bits for B-framess
1388 //printf("%X\n", show_bits(&s->gb, 24));
1389
1390     if(s->shape != RECT_SHAPE){
1391         header_extension= get_bits1(&s->gb);
1392         //FIXME more stuff here
1393     }
1394
1395     mb_num= get_bits(&s->gb, mb_num_bits);
1396     if(mb_num != s->mb_x + s->mb_y*s->mb_width){
1397         printf("MB-num change not supported %d %d\n", mb_num, s->mb_x + s->mb_y*s->mb_width);
1398 //        s->mb_x= mb_num % s->mb_width;
1399 //        s->mb_y= mb_num / s->mb_width;
1400         //FIXME many vars are wrong now
1401     } 
1402
1403     if(s->shape != BIN_ONLY_SHAPE){
1404         s->qscale= get_bits(&s->gb, 5);
1405         h263_dc_scale(s);
1406     }
1407
1408     if(s->shape == RECT_SHAPE){
1409         header_extension= get_bits1(&s->gb);
1410     }
1411     if(header_extension){
1412         int time_incr=0;
1413         printf("header extension not really supported\n");
1414         while (get_bits1(&s->gb) != 0) 
1415             time_incr++;
1416
1417         check_marker(&s->gb, "before time_increment in video packed header");
1418         s->time_increment= get_bits(&s->gb, s->time_increment_bits);
1419         if(s->pict_type!=B_TYPE){
1420             s->time_base+= time_incr;
1421             s->last_non_b_time[1]= s->last_non_b_time[0];
1422             s->last_non_b_time[0]= s->time_base*s->time_increment_resolution + s->time_increment;
1423         }else{
1424             s->time= (s->last_non_b_time[1]/s->time_increment_resolution + time_incr)*s->time_increment_resolution;
1425             s->time+= s->time_increment;
1426         }
1427         check_marker(&s->gb, "before vop_coding_type in video packed header");
1428         
1429         skip_bits(&s->gb, 2); /* vop coding type */
1430         //FIXME not rect stuff here
1431
1432         if(s->shape != BIN_ONLY_SHAPE){
1433             skip_bits(&s->gb, 3); /* intra dc vlc threshold */
1434
1435             if(s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE && s->num_sprite_warping_points){
1436                 mpeg4_decode_sprite_trajectory(s);
1437             }
1438
1439             //FIXME reduced res stuff here
1440             
1441             if (s->pict_type != I_TYPE) {
1442                 s->f_code = get_bits(&s->gb, 3);        /* fcode_for */
1443                 if(s->f_code==0){
1444                     printf("Error, video packet header damaged or not MPEG4 header (f_code=0)\n");
1445                     return -1; // makes no sense to continue, as the MV decoding will break very quickly
1446                 }
1447             }
1448             if (s->pict_type == B_TYPE) {
1449                 s->b_code = get_bits(&s->gb, 3);
1450             }       
1451         }
1452
1453     }
1454     //FIXME new-pred stuff
1455
1456     l_wrap= s->block_wrap[0];
1457     l_xy= s->mb_y*l_wrap*2;
1458     c_wrap= s->block_wrap[4];
1459     c_xy= s->mb_y*c_wrap;
1460
1461     /* clean DC */
1462     memsetw(s->dc_val[0] + l_xy, 1024, l_wrap*3);
1463     memsetw(s->dc_val[1] + c_xy, 1024, c_wrap*2);
1464     memsetw(s->dc_val[2] + c_xy, 1024, c_wrap*2);
1465
1466     /* clean AC */
1467     memset(s->ac_val[0] + l_xy, 0, l_wrap*3*16*sizeof(INT16));
1468     memset(s->ac_val[1] + c_xy, 0, c_wrap*2*16*sizeof(INT16));
1469     memset(s->ac_val[2] + c_xy, 0, c_wrap*2*16*sizeof(INT16));
1470
1471     /* clean MV */
1472     memset(s->motion_val + l_xy, 0, l_wrap*3*2*sizeof(INT16));
1473 //    memset(s->motion_val, 0, 2*sizeof(INT16)*(2 + s->mb_width*2)*(2 + s->mb_height*2));
1474     s->resync_x_pos= s->mb_x;
1475     s->first_slice_line=1;
1476
1477     return 0;
1478 }
1479
1480 int h263_decode_mb(MpegEncContext *s,
1481                    DCTELEM block[6][64])
1482 {
1483     int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
1484     INT16 *mot_val;
1485     static INT8 quant_tab[4] = { -1, -2, 1, 2 };
1486
1487     if(s->resync_marker){
1488         if(   s->resync_x_pos == s->mb_x+1
1489            || s->resync_x_pos == s->mb_x){
1490             /* f*ck mpeg4
1491                this is here so we dont need to slowdown h263_pred_motion with it */
1492             if(s->resync_x_pos == s->mb_x+1 && s->mb_x==0){
1493                 int xy= s->block_index[0] - s->block_wrap[0];
1494                 s->motion_val[xy][0]= s->motion_val[xy+2][0];
1495                 s->motion_val[xy][1]= s->motion_val[xy+2][1];
1496             }
1497
1498             s->first_slice_line=0; 
1499             s->resync_x_pos=0; // isnt needed but for cleanness sake ;)
1500         }
1501
1502         if(show_aligned_bits(&s->gb, 1, 16) == 0){
1503             if( mpeg4_resync(s) < 0 ) return -1;
1504             
1505         }
1506     }
1507
1508     if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
1509         if (get_bits1(&s->gb)) {
1510             /* skip mb */
1511             s->mb_intra = 0;
1512             for(i=0;i<6;i++)
1513                 s->block_last_index[i] = -1;
1514             s->mv_dir = MV_DIR_FORWARD;
1515             s->mv_type = MV_TYPE_16X16;
1516             if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
1517                 const int a= s->sprite_warping_accuracy;
1518 //                int l = (1 << (s->f_code - 1)) * 32;
1519
1520                 s->mcsel=1;
1521                 if(s->divx_version==500 && s->divx_build==413){
1522                     s->mv[0][0][0] = s->sprite_offset[0][0] / (1<<(a-s->quarter_sample));
1523                     s->mv[0][0][1] = s->sprite_offset[0][1] / (1<<(a-s->quarter_sample));
1524                 }else{
1525                     s->mv[0][0][0] = RSHIFT(s->sprite_offset[0][0], a-s->quarter_sample);
1526                     s->mv[0][0][1] = RSHIFT(s->sprite_offset[0][1], a-s->quarter_sample);
1527                 }
1528 /*                if (s->mv[0][0][0] < -l) s->mv[0][0][0]= -l;
1529                 else if (s->mv[0][0][0] >= l) s->mv[0][0][0]= l-1;
1530                 if (s->mv[0][0][1] < -l) s->mv[0][0][1]= -l;
1531                 else if (s->mv[0][0][1] >= l) s->mv[0][0][1]= l-1;*/
1532
1533                 s->mb_skiped = 0;
1534             }else{
1535                 s->mcsel=0;
1536                 s->mv[0][0][0] = 0;
1537                 s->mv[0][0][1] = 0;
1538                 s->mb_skiped = 1;
1539             }
1540             return 0;
1541         }
1542         cbpc = get_vlc(&s->gb, &inter_MCBPC_vlc);
1543         //fprintf(stderr, "\tCBPC: %d", cbpc);
1544         if (cbpc < 0)
1545             return -1;
1546         if (cbpc > 20)
1547             cbpc+=3;
1548         else if (cbpc == 20)
1549             fprintf(stderr, "Stuffing !");
1550         
1551         dquant = cbpc & 8;
1552         s->mb_intra = ((cbpc & 4) != 0);
1553         if (s->mb_intra) goto intra;
1554         
1555         if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
1556             s->mcsel= get_bits1(&s->gb);
1557         else s->mcsel= 0;
1558         cbpy = get_vlc(&s->gb, &cbpy_vlc);
1559         cbp = (cbpc & 3) | ((cbpy ^ 0xf) << 2);
1560         if (dquant) {
1561             s->qscale += quant_tab[get_bits(&s->gb, 2)];
1562             if (s->qscale < 1)
1563                 s->qscale = 1;
1564             else if (s->qscale > 31)
1565                 s->qscale = 31;
1566             h263_dc_scale(s);
1567         }
1568         s->mv_dir = MV_DIR_FORWARD;
1569         if ((cbpc & 16) == 0) {
1570             /* 16x16 motion prediction */
1571             s->mv_type = MV_TYPE_16X16;
1572             h263_pred_motion(s, 0, &pred_x, &pred_y);
1573             if (s->umvplus_dec)
1574                mx = h263p_decode_umotion(s, pred_x);
1575             else if(!s->mcsel)
1576                mx = h263_decode_motion(s, pred_x, s->f_code);
1577             else {
1578                const int a= s->sprite_warping_accuracy;
1579 //        int l = (1 << (s->f_code - 1)) * 32;
1580                 if(s->divx_version==500 && s->divx_build==413){
1581                     mx = s->sprite_offset[0][0] / (1<<(a-s->quarter_sample));
1582                 }else{
1583                     mx = RSHIFT(s->sprite_offset[0][0], a-s->quarter_sample);
1584                 }
1585 //        if (mx < -l) mx= -l, printf("C");
1586 //        else if (mx >= l) mx= l-1, printf("C");
1587             }
1588             if (mx >= 0xffff)
1589                 return -1;
1590             
1591             if (s->umvplus_dec)
1592                my = h263p_decode_umotion(s, pred_y);
1593             else if(!s->mcsel)
1594                my = h263_decode_motion(s, pred_y, s->f_code);
1595             else{
1596                const int a= s->sprite_warping_accuracy;
1597 //       int l = (1 << (s->f_code - 1)) * 32;
1598                 if(s->divx_version==500 && s->divx_build==413){
1599                     my = s->sprite_offset[0][1] / (1<<(a-s->quarter_sample));
1600                 }else{
1601                     my = RSHIFT(s->sprite_offset[0][1], a-s->quarter_sample);
1602                 }
1603 //       if (my < -l) my= -l, printf("C");
1604 //       else if (my >= l) my= l-1, printf("C");
1605             }
1606             if (my >= 0xffff)
1607                 return -1;
1608             s->mv[0][0][0] = mx;
1609             s->mv[0][0][1] = my;
1610             /*fprintf(stderr, "\n MB %d", (s->mb_y * s->mb_width) + s->mb_x);
1611             fprintf(stderr, "\n\tmvx: %d\t\tpredx: %d", mx, pred_x);
1612             fprintf(stderr, "\n\tmvy: %d\t\tpredy: %d", my, pred_y);*/
1613             if (s->umvplus_dec && (mx - pred_x) == 1 && (my - pred_y) == 1)
1614                skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
1615                            
1616         } else {
1617             s->mv_type = MV_TYPE_8X8;
1618             for(i=0;i<4;i++) {
1619                 mot_val = h263_pred_motion(s, i, &pred_x, &pred_y);
1620                 if (s->umvplus_dec)
1621                   mx = h263p_decode_umotion(s, pred_x);
1622                 else
1623                   mx = h263_decode_motion(s, pred_x, s->f_code);
1624                 if (mx >= 0xffff)
1625                     return -1;
1626                 
1627                 if (s->umvplus_dec)
1628                   my = h263p_decode_umotion(s, pred_y);
1629                 else    
1630                   my = h263_decode_motion(s, pred_y, s->f_code);
1631                 if (my >= 0xffff)
1632                     return -1;
1633                 s->mv[0][i][0] = mx;
1634                 s->mv[0][i][1] = my;
1635                 if (s->umvplus_dec && (mx - pred_x) == 1 && (my - pred_y) == 1)
1636                   skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
1637                 mot_val[0] = mx;
1638                 mot_val[1] = my;
1639             }
1640         }
1641     } else if(s->pict_type==B_TYPE) {
1642         int modb1; // first bit of modb
1643         int modb2; // second bit of modb
1644         int mb_type;
1645         int time_pp;
1646         int time_pb;
1647         int xy;
1648
1649         s->mb_intra = 0; //B-frames never contain intra blocks
1650         s->mcsel=0;      //     ...               true gmc blocks
1651
1652         if(s->mb_x==0){
1653             s->last_mv[0][0][0]= 
1654             s->last_mv[0][0][1]= 
1655             s->last_mv[1][0][0]= 
1656             s->last_mv[1][0][1]= 0;
1657         }
1658
1659         /* if we skipped it in the future P Frame than skip it now too */
1660         s->mb_skiped= s->mbskip_table[s->mb_y * s->mb_width + s->mb_x]; // Note, skiptab=0 if last was GMC
1661
1662         if(s->mb_skiped){
1663                 /* skip mb */
1664             for(i=0;i<6;i++)
1665                 s->block_last_index[i] = -1;
1666
1667             s->mv_dir = MV_DIR_FORWARD;
1668             s->mv_type = MV_TYPE_16X16;
1669             s->mv[0][0][0] = 0;
1670             s->mv[0][0][1] = 0;
1671             s->mv[1][0][0] = 0;
1672             s->mv[1][0][1] = 0;
1673 //FIXME is this correct?
1674 /*            s->last_mv[0][0][0]=
1675             s->last_mv[0][0][1]=0;*/
1676             s->mb_skiped = 1;
1677             return 0;
1678         }
1679
1680         modb1= get_bits1(&s->gb);
1681         if(modb1==0){
1682             modb2= get_bits1(&s->gb);
1683             mb_type= get_vlc(&s->gb, &mb_type_b_vlc);
1684             if(modb2==0) cbp= get_bits(&s->gb, 6);
1685             else cbp=0;
1686             if (mb_type && cbp) {
1687                 if(get_bits1(&s->gb)){
1688                     s->qscale +=get_bits1(&s->gb)*4 - 2;
1689                     if (s->qscale < 1)
1690                         s->qscale = 1;
1691                     else if (s->qscale > 31)
1692                         s->qscale = 31;
1693                     h263_dc_scale(s);
1694                 }
1695             }
1696         }else{
1697             mb_type=4; //like 0 but no vectors coded
1698             cbp=0;
1699         }
1700         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
1701         mx=my=0; //for case 4, we could put this to the mb_type=4 but than gcc compains about uninitalized mx/my
1702         switch(mb_type)
1703         {
1704         case 0: 
1705             mx = h263_decode_motion(s, 0, 1);
1706             my = h263_decode_motion(s, 0, 1);
1707         case 4: 
1708             s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
1709             xy= s->block_index[0];
1710             time_pp= s->last_non_b_time[0] - s->last_non_b_time[1];
1711             time_pb= s->time - s->last_non_b_time[1];
1712 //if(time_pp>3000 )printf("%d %d  ", time_pp, time_pb);
1713             //FIXME 4MV
1714             //FIXME avoid divides
1715             s->mv[0][0][0] = s->motion_val[xy][0]*time_pb/time_pp + mx;
1716             s->mv[0][0][1] = s->motion_val[xy][1]*time_pb/time_pp + my;
1717             s->mv[1][0][0] = mx ? s->mv[0][0][0] - s->motion_val[xy][0]
1718                                 : s->motion_val[xy][0]*(time_pb - time_pp)/time_pp + mx;
1719             s->mv[1][0][1] = my ? s->mv[0][0][1] - s->motion_val[xy][1] 
1720                                 : s->motion_val[xy][1]*(time_pb - time_pp)/time_pp + my;
1721 /*            s->mv[0][0][0] = 
1722             s->mv[0][0][1] = 
1723             s->mv[1][0][0] = 
1724             s->mv[1][0][1] = 1000;*/
1725             break;
1726         case 1: 
1727             s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
1728             mx = h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
1729             my = h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
1730             s->last_mv[0][0][0]= s->mv[0][0][0] = mx;
1731             s->last_mv[0][0][1]= s->mv[0][0][1] = my;
1732
1733             mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
1734             my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
1735             s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
1736             s->last_mv[1][0][1]= s->mv[1][0][1] = my;
1737             break;
1738         case 2: 
1739             s->mv_dir = MV_DIR_BACKWARD;
1740             mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
1741             my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
1742             s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
1743             s->last_mv[1][0][1]= s->mv[1][0][1] = my;
1744             break;
1745         case 3:
1746             s->mv_dir = MV_DIR_FORWARD;
1747             mx = h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
1748             my = h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
1749             s->last_mv[0][0][0]= s->mv[0][0][0] = mx;
1750             s->last_mv[0][0][1]= s->mv[0][0][1] = my;
1751             break;
1752         default: return -1;
1753         }
1754     } else { /* I-Frame */
1755         cbpc = get_vlc(&s->gb, &intra_MCBPC_vlc);
1756         if (cbpc < 0)
1757             return -1;
1758         dquant = cbpc & 4;
1759         s->mb_intra = 1;
1760 intra:
1761         s->ac_pred = 0;
1762         if (s->h263_pred || s->h263_aic) {
1763             s->ac_pred = get_bits1(&s->gb);
1764             if (s->ac_pred && s->h263_aic)
1765                 s->h263_aic_dir = get_bits1(&s->gb);
1766         }
1767         if (s->h263_aic) {
1768             s->y_dc_scale = 2 * s->qscale;
1769             s->c_dc_scale = 2 * s->qscale;
1770         }
1771         cbpy = get_vlc(&s->gb, &cbpy_vlc);
1772         cbp = (cbpc & 3) | (cbpy << 2);
1773         if (dquant) {
1774             s->qscale += quant_tab[get_bits(&s->gb, 2)];
1775             if (s->qscale < 1)
1776                 s->qscale = 1;
1777             else if (s->qscale > 31)
1778                 s->qscale = 31;
1779             h263_dc_scale(s);
1780         }
1781     }
1782
1783     /* decode each block */
1784     if (s->h263_pred) {
1785         for (i = 0; i < 6; i++) {
1786             if (mpeg4_decode_block(s, block[i], i, (cbp >> (5 - i)) & 1) < 0)
1787                 return -1;
1788         }
1789     } else {
1790         for (i = 0; i < 6; i++) {
1791             if (h263_decode_block(s, block[i], i, (cbp >> (5 - i)) & 1) < 0)
1792                 return -1;
1793         }
1794     }
1795     return 0;
1796 }
1797
1798 static int h263_decode_motion(MpegEncContext * s, int pred, int f_code)
1799 {
1800     int code, val, sign, shift, l, m;
1801
1802     code = get_vlc(&s->gb, &mv_vlc);
1803     if (code < 0)
1804         return 0xffff;
1805
1806     if (code == 0)
1807         return pred;
1808     sign = get_bits1(&s->gb);
1809     shift = f_code - 1;
1810     val = (code - 1) << shift;
1811     if (shift > 0)
1812         val |= get_bits(&s->gb, shift);
1813     val++;
1814     if (sign)
1815         val = -val;
1816     val += pred;
1817     
1818     /* modulo decoding */
1819     if (!s->h263_long_vectors) {
1820         l = (1 << (f_code - 1)) * 32;
1821         m = 2 * l;
1822         if (val < -l) {
1823             val += m;
1824         } else if (val >= l) {
1825             val -= m;
1826         }
1827     } else {
1828         /* horrible h263 long vector mode */
1829         if (pred < -31 && val < -63)
1830             val += 64;
1831         if (pred > 32 && val > 63)
1832             val -= 64;
1833         
1834     }
1835     return val;
1836 }
1837
1838 /* Decodes RVLC of H.263+ UMV */
1839 static int h263p_decode_umotion(MpegEncContext * s, int pred)
1840 {
1841    int code = 0, sign;
1842    
1843    if (get_bits1(&s->gb)) /* Motion difference = 0 */
1844       return pred;
1845    
1846    code = 2 + get_bits1(&s->gb);
1847    
1848    while (get_bits1(&s->gb))
1849    {
1850       code <<= 1;
1851       code += get_bits1(&s->gb);
1852    }
1853    sign = code & 1;
1854    code >>= 1;
1855    
1856    code = (sign) ? (pred - code) : (pred + code);
1857 #ifdef DEBUG
1858    fprintf(stderr,"H.263+ UMV Motion = %d\n", code);
1859 #endif
1860    return code;   
1861
1862 }
1863
1864 static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
1865                              int n, int coded)
1866 {
1867     int code, level, i, j, last, run;
1868     RLTable *rl = &rl_inter;
1869     const UINT8 *scan_table;
1870
1871     scan_table = zigzag_direct;
1872     if (s->h263_aic && s->mb_intra) {
1873         rl = &rl_intra_aic;
1874         i = 0;
1875         if (s->ac_pred) {
1876             if (s->h263_aic_dir) 
1877                 scan_table = ff_alternate_vertical_scan; /* left */
1878             else
1879                 scan_table = ff_alternate_horizontal_scan; /* top */
1880         }
1881     } else if (s->mb_intra) {
1882         /* DC coef */
1883         if (s->h263_rv10 && s->rv10_version == 3 && s->pict_type == I_TYPE) {
1884             int component, diff;
1885             component = (n <= 3 ? 0 : n - 4 + 1);
1886             level = s->last_dc[component];
1887             if (s->rv10_first_dc_coded[component]) {
1888                 diff = rv_decode_dc(s, n);
1889                 if (diff == 0xffff)
1890                     return -1;
1891                 level += diff;
1892                 level = level & 0xff; /* handle wrap round */
1893                 s->last_dc[component] = level;
1894             } else {
1895                 s->rv10_first_dc_coded[component] = 1;
1896             }
1897         } else {
1898             level = get_bits(&s->gb, 8);
1899             if (level == 255)
1900                 level = 128;
1901         }
1902         block[0] = level;
1903         i = 1;
1904     } else {
1905         i = 0;
1906     }
1907     if (!coded) {
1908         if (s->mb_intra && s->h263_aic)
1909             goto not_coded;
1910         s->block_last_index[n] = i - 1;
1911         return 0;
1912     }
1913
1914     for(;;) {
1915         code = get_vlc(&s->gb, &rl->vlc);
1916         if (code < 0)
1917             return -1;
1918         if (code == rl->n) {
1919             /* escape */
1920             last = get_bits1(&s->gb);
1921             run = get_bits(&s->gb, 6);
1922             level = (INT8)get_bits(&s->gb, 8);
1923             if (s->h263_rv10 && level == -128) {
1924                 /* XXX: should patch encoder too */
1925                 level = get_bits(&s->gb, 12);
1926                 level = (level << 20) >> 20;
1927             }
1928         } else {
1929             run = rl->table_run[code];
1930             level = rl->table_level[code];
1931             last = code >= rl->last;
1932             if (get_bits1(&s->gb))
1933                 level = -level;
1934         }
1935         i += run;
1936         if (i >= 64)
1937             return -1;
1938         j = scan_table[i];
1939         block[j] = level;
1940         if (last)
1941             break;
1942         i++;
1943     }
1944 not_coded:    
1945     if (s->mb_intra && s->h263_aic) {
1946         h263_pred_acdc(s, block, n);
1947         i = 63;
1948     }
1949     s->block_last_index[n] = i;
1950     return 0;
1951 }
1952
1953 static int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr)
1954 {
1955     int level, pred, code;
1956     UINT16 *dc_val;
1957
1958     if (n < 4) 
1959         code = get_vlc(&s->gb, &dc_lum);
1960     else 
1961         code = get_vlc(&s->gb, &dc_chrom);
1962     if (code < 0)
1963         return -1;
1964     if (code == 0) {
1965         level = 0;
1966     } else {
1967         level = get_bits(&s->gb, code);
1968         if ((level >> (code - 1)) == 0) /* if MSB not set it is negative*/
1969             level = - (level ^ ((1 << code) - 1));
1970         if (code > 8)
1971             skip_bits1(&s->gb); /* marker */
1972     }
1973
1974     pred = mpeg4_pred_dc(s, n, &dc_val, dir_ptr);
1975     level += pred;
1976     if (level < 0)
1977         level = 0;
1978     if (n < 4) {
1979         *dc_val = level * s->y_dc_scale;
1980     } else {
1981         *dc_val = level * s->c_dc_scale;
1982     }
1983     return level;
1984 }
1985
1986 static int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
1987                               int n, int coded)
1988 {
1989     int code, level, i, j, last, run;
1990     int dc_pred_dir;
1991     RLTable *rl;
1992     const UINT8 *scan_table;
1993
1994     if (s->mb_intra) {
1995         /* DC coef */
1996         level = mpeg4_decode_dc(s, n, &dc_pred_dir);
1997         if (level < 0)
1998             return -1;
1999         block[0] = level;
2000         i = 1;
2001         if (!coded) 
2002             goto not_coded;
2003         rl = &rl_intra;
2004         if (s->ac_pred) {
2005             if (dc_pred_dir == 0) 
2006                 scan_table = ff_alternate_vertical_scan; /* left */
2007             else
2008                 scan_table = ff_alternate_horizontal_scan; /* top */
2009         } else {
2010             scan_table = zigzag_direct;
2011         }
2012     } else {
2013         i = 0;
2014         if (!coded) {
2015             s->block_last_index[n] = i - 1;
2016             return 0;
2017         }
2018         rl = &rl_inter;
2019         scan_table = zigzag_direct;
2020     }
2021
2022     for(;;) {
2023         code = get_vlc(&s->gb, &rl->vlc);
2024         if (code < 0)
2025             return -1;
2026         if (code == rl->n) {
2027             /* escape */
2028             if (get_bits1(&s->gb) != 0) {
2029                 if (get_bits1(&s->gb) != 0) {
2030                     /* third escape */
2031                     last = get_bits1(&s->gb);
2032                     run = get_bits(&s->gb, 6);
2033                     get_bits1(&s->gb); /* marker */
2034                     level = get_bits(&s->gb, 12);
2035                     level = (level << 20) >> 20; /* sign extend */
2036                     skip_bits1(&s->gb); /* marker */
2037                 } else {
2038                     /* second escape */
2039                     code = get_vlc(&s->gb, &rl->vlc);
2040                     if (code < 0 || code >= rl->n)
2041                         return -1;
2042                     run = rl->table_run[code];
2043                     level = rl->table_level[code];
2044                     last = code >= rl->last;
2045                     run += rl->max_run[last][level] + 1;
2046                     if (get_bits1(&s->gb))
2047                         level = -level;
2048                 }
2049             } else {
2050                 /* first escape */
2051                 code = get_vlc(&s->gb, &rl->vlc);
2052                 if (code < 0 || code >= rl->n)
2053                     return -1;
2054                 run = rl->table_run[code];
2055                 level = rl->table_level[code];
2056                 last = code >= rl->last;
2057                 level += rl->max_level[last][run];
2058                 if (get_bits1(&s->gb))
2059                     level = -level;
2060             }
2061         } else {
2062             run = rl->table_run[code];
2063             level = rl->table_level[code];
2064             last = code >= rl->last;
2065             if (get_bits1(&s->gb))
2066                 level = -level;
2067         }
2068         i += run;
2069         if (i >= 64)
2070             return -1;
2071         j = scan_table[i];
2072         block[j] = level;
2073         i++;
2074         if (last)
2075             break;
2076     }
2077  not_coded:
2078     if (s->mb_intra) {
2079         mpeg4_pred_ac(s, block, n, dc_pred_dir);
2080         if (s->ac_pred) {
2081             i = 64; /* XXX: not optimal */
2082         }
2083     }
2084     s->block_last_index[n] = i - 1;
2085     return 0;
2086 }
2087
2088 /* most is hardcoded. should extend to handle all h263 streams */
2089 int h263_decode_picture_header(MpegEncContext *s)
2090 {
2091     int format, width, height;
2092
2093     /* picture header */
2094     if (get_bits(&s->gb, 22) != 0x20)
2095         return -1;
2096     s->picture_number = get_bits(&s->gb, 8); /* picture timestamp */
2097     
2098     if (get_bits1(&s->gb) != 1)
2099         return -1;      /* marker */
2100     if (get_bits1(&s->gb) != 0)
2101         return -1;      /* h263 id */
2102     skip_bits1(&s->gb); /* split screen off */
2103     skip_bits1(&s->gb); /* camera  off */
2104     skip_bits1(&s->gb); /* freeze picture release off */
2105
2106     /* Reset GOB number */
2107     s->gob_number = 0;
2108         
2109     format = get_bits(&s->gb, 3);
2110
2111     if (format != 7 && format != 6) {
2112         s->h263_plus = 0;
2113         /* H.263v1 */
2114         width = h263_format[format][0];
2115         height = h263_format[format][1];
2116         if (!width)
2117             return -1;
2118         
2119         s->width = width;
2120         s->height = height;
2121         s->pict_type = I_TYPE + get_bits1(&s->gb);
2122
2123         s->unrestricted_mv = get_bits1(&s->gb); 
2124         s->h263_long_vectors = s->unrestricted_mv;
2125
2126         if (get_bits1(&s->gb) != 0)
2127             return -1;  /* SAC: off */
2128         if (get_bits1(&s->gb) != 0) {
2129             s->mv_type = MV_TYPE_8X8; /* Advanced prediction mode */
2130         }   
2131         
2132         if (get_bits1(&s->gb) != 0)
2133             return -1;  /* not PB frame */
2134
2135         s->qscale = get_bits(&s->gb, 5);
2136         skip_bits1(&s->gb);     /* Continuous Presence Multipoint mode: off */
2137     } else {
2138         int ufep;
2139         
2140         /* H.263v2 */
2141         s->h263_plus = 1;
2142         ufep = get_bits(&s->gb, 3); /* Update Full Extended PTYPE */
2143         
2144         if (ufep == 1) {
2145             /* OPPTYPE */       
2146             format = get_bits(&s->gb, 3);
2147             skip_bits(&s->gb,1); /* Custom PCF */
2148             s->umvplus_dec = get_bits(&s->gb, 1); /* Unrestricted Motion Vector */
2149             skip_bits1(&s->gb); /* Syntax-based Arithmetic Coding (SAC) */
2150             if (get_bits1(&s->gb) != 0) {
2151                 s->mv_type = MV_TYPE_8X8; /* Advanced prediction mode */
2152             }
2153             if (get_bits1(&s->gb) != 0) { /* Advanced Intra Coding (AIC) */
2154                 s->h263_aic = 1;
2155             }
2156             skip_bits(&s->gb, 7);
2157             skip_bits(&s->gb, 3); /* Reserved */
2158         } else if (ufep != 0)
2159             return -1;
2160             
2161         /* MPPTYPE */
2162         s->pict_type = get_bits(&s->gb, 3) + 1;
2163         if (s->pict_type != I_TYPE &&
2164             s->pict_type != P_TYPE)
2165             return -1;
2166         skip_bits(&s->gb, 2);
2167         s->no_rounding = get_bits1(&s->gb);
2168         //fprintf(stderr, "\nRTYPE: %d", s->no_rounding);
2169         skip_bits(&s->gb, 4);
2170         
2171         /* Get the picture dimensions */
2172         if (ufep) {
2173             if (format == 6) {
2174                 /* Custom Picture Format (CPFMT) */
2175                 skip_bits(&s->gb, 4); /* aspect ratio */
2176                 width = (get_bits(&s->gb, 9) + 1) * 4;
2177                 skip_bits1(&s->gb);
2178                 height = get_bits(&s->gb, 9) * 4;
2179 #ifdef DEBUG 
2180                 fprintf(stderr,"\nH.263+ Custom picture: %dx%d\n",width,height);
2181 #endif            
2182             }
2183             else {
2184                 width = h263_format[format][0];
2185                 height = h263_format[format][1];
2186             }
2187             if ((width == 0) || (height == 0))
2188                 return -1;
2189             s->width = width;
2190             s->height = height;
2191             if (s->umvplus_dec) {
2192                 skip_bits1(&s->gb); /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
2193             }
2194         }
2195             
2196         s->qscale = get_bits(&s->gb, 5);
2197     }
2198     /* PEI */
2199     while (get_bits1(&s->gb) != 0) {
2200         skip_bits(&s->gb, 8);
2201     }
2202     s->f_code = 1;
2203     return 0;
2204 }
2205
2206 static void mpeg4_decode_sprite_trajectory(MpegEncContext * s)
2207 {
2208     int i;
2209     int a= 2<<s->sprite_warping_accuracy;
2210     int rho= 3-s->sprite_warping_accuracy;
2211     int r=16/a;
2212     const int vop_ref[4][2]= {{0,0}, {s->width,0}, {0, s->height}, {s->width, s->height}}; // only true for rectangle shapes
2213     int d[4][2]={{0,0}, {0,0}, {0,0}, {0,0}};
2214     int sprite_ref[4][2];
2215     int virtual_ref[2][2];
2216     int w2, h2;
2217     int alpha=0, beta=0;
2218     int w= s->width;
2219     int h= s->height;
2220 //printf("SP %d\n", s->sprite_warping_accuracy);
2221     for(i=0; i<s->num_sprite_warping_points; i++){
2222         int length;
2223         int x=0, y=0;
2224
2225         length= get_vlc(&s->gb, &sprite_trajectory);
2226         if(length){
2227             x= get_bits(&s->gb, length);
2228 //printf("lx %d %d\n", length, x);
2229             if ((x >> (length - 1)) == 0) /* if MSB not set it is negative*/
2230                 x = - (x ^ ((1 << length) - 1));
2231         }
2232         if(!(s->divx_version==500 && s->divx_build==413)) skip_bits1(&s->gb); /* marker bit */
2233         
2234         length= get_vlc(&s->gb, &sprite_trajectory);
2235         if(length){
2236             y=get_bits(&s->gb, length);
2237 //printf("ly %d %d\n", length, y);
2238             if ((y >> (length - 1)) == 0) /* if MSB not set it is negative*/
2239                 y = - (y ^ ((1 << length) - 1));
2240         }
2241         skip_bits1(&s->gb); /* marker bit */
2242 //printf("%d %d %d %d\n", x, y, i, s->sprite_warping_accuracy);
2243 //if(i>0 && (x!=0 || y!=0)) printf("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n");
2244 //x=y=0;
2245         d[i][0]= x;
2246         d[i][1]= y;
2247     }
2248
2249     while((1<<alpha)<w) alpha++;
2250     while((1<<beta )<h) beta++; // there seems to be a typo in the mpeg4 std for the definition of w' and h'
2251     w2= 1<<alpha;
2252     h2= 1<<beta;
2253
2254 // Note, the 4th point isnt used for GMC
2255     if(s->divx_version==500 && s->divx_build==413){
2256         sprite_ref[0][0]= a*vop_ref[0][0] + d[0][0];
2257         sprite_ref[0][1]= a*vop_ref[0][1] + d[0][1];
2258         sprite_ref[1][0]= a*vop_ref[1][0] + d[0][0] + d[1][0];
2259         sprite_ref[1][1]= a*vop_ref[1][1] + d[0][1] + d[1][1];
2260         sprite_ref[2][0]= a*vop_ref[2][0] + d[0][0] + d[2][0];
2261         sprite_ref[2][1]= a*vop_ref[2][1] + d[0][1] + d[2][1];
2262     } else {
2263         sprite_ref[0][0]= (a>>1)*(2*vop_ref[0][0] + d[0][0]);
2264         sprite_ref[0][1]= (a>>1)*(2*vop_ref[0][1] + d[0][1]);
2265         sprite_ref[1][0]= (a>>1)*(2*vop_ref[1][0] + d[0][0] + d[1][0]);
2266         sprite_ref[1][1]= (a>>1)*(2*vop_ref[1][1] + d[0][1] + d[1][1]);
2267         sprite_ref[2][0]= (a>>1)*(2*vop_ref[2][0] + d[0][0] + d[2][0]);
2268         sprite_ref[2][1]= (a>>1)*(2*vop_ref[2][1] + d[0][1] + d[2][1]);
2269     }
2270 /*    sprite_ref[3][0]= (a>>1)*(2*vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);
2271     sprite_ref[3][1]= (a>>1)*(2*vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */
2272     
2273 // this is mostly identical to the mpeg4 std (and is totally unreadable because of that ...)
2274 // perhaps it should be reordered to be more readable ...
2275 // the idea behind this virtual_ref mess is to be able to use shifts later per pixel instead of divides
2276 // so the distance between points is converted from w&h based to w2&h2 based which are of the 2^x form
2277     virtual_ref[0][0]= 16*(vop_ref[0][0] + w2) 
2278         + 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);
2279     virtual_ref[0][1]= 16*vop_ref[0][1] 
2280         + 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);
2281     virtual_ref[1][0]= 16*vop_ref[0][0] 
2282         + 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);
2283     virtual_ref[1][1]= 16*(vop_ref[0][1] + h2) 
2284         + 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);
2285
2286     switch(s->num_sprite_warping_points)
2287     {
2288         case 0:
2289             s->sprite_offset[0][0]= 0;
2290             s->sprite_offset[0][1]= 0;
2291             s->sprite_offset[1][0]= 0;
2292             s->sprite_offset[1][1]= 0;
2293             s->sprite_delta[0][0][0]= a;
2294             s->sprite_delta[0][0][1]= 0;
2295             s->sprite_delta[0][1][0]= 0;
2296             s->sprite_delta[0][1][1]= a;
2297             s->sprite_delta[1][0][0]= a;
2298             s->sprite_delta[1][0][1]= 0;
2299             s->sprite_delta[1][1][0]= 0;
2300             s->sprite_delta[1][1][1]= a;
2301             s->sprite_shift[0][0]= 0;
2302             s->sprite_shift[0][1]= 0;
2303             s->sprite_shift[1][0]= 0;
2304             s->sprite_shift[1][1]= 0;
2305             break;
2306         case 1: //GMC only
2307             s->sprite_offset[0][0]= sprite_ref[0][0] - a*vop_ref[0][0];
2308             s->sprite_offset[0][1]= sprite_ref[0][1] - a*vop_ref[0][1];
2309             s->sprite_offset[1][0]= ((sprite_ref[0][0]>>1)|(sprite_ref[0][0]&1)) - a*(vop_ref[0][0]/2);
2310             s->sprite_offset[1][1]= ((sprite_ref[0][1]>>1)|(sprite_ref[0][1]&1)) - a*(vop_ref[0][1]/2);
2311             s->sprite_delta[0][0][0]= a;
2312             s->sprite_delta[0][0][1]= 0;
2313             s->sprite_delta[0][1][0]= 0;
2314             s->sprite_delta[0][1][1]= a;
2315             s->sprite_delta[1][0][0]= a;
2316             s->sprite_delta[1][0][1]= 0;
2317             s->sprite_delta[1][1][0]= 0;
2318             s->sprite_delta[1][1][1]= a;
2319             s->sprite_shift[0][0]= 0;
2320             s->sprite_shift[0][1]= 0;
2321             s->sprite_shift[1][0]= 0;
2322             s->sprite_shift[1][1]= 0;
2323             break;
2324         case 2:
2325         case 3: //FIXME
2326             s->sprite_offset[0][0]= (sprite_ref[0][0]<<(alpha+rho))
2327                                                   + ((-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][0])
2328                                                     +( r*sprite_ref[0][1] - virtual_ref[0][1])*(-vop_ref[0][1]));
2329             s->sprite_offset[0][1]= (sprite_ref[0][1]<<(alpha+rho))
2330                                                   + ((-r*sprite_ref[0][1] + virtual_ref[0][1])*(-vop_ref[0][0])
2331                                                     +(-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][1]));
2332             s->sprite_offset[1][0]= ((-r*sprite_ref[0][0] + virtual_ref[0][0])*(-2*vop_ref[0][0] + 1)
2333                                  +( r*sprite_ref[0][1] - virtual_ref[0][1])*(-2*vop_ref[0][1] + 1)
2334                                  +2*w2*r*sprite_ref[0][0] - 16*w2);
2335             s->sprite_offset[1][1]= ((-r*sprite_ref[0][1] + virtual_ref[0][1])*(-2*vop_ref[0][0] + 1) 
2336                                  +(-r*sprite_ref[0][0] + virtual_ref[0][0])*(-2*vop_ref[0][1] + 1)
2337                                  +2*w2*r*sprite_ref[0][1] - 16*w2);
2338             s->sprite_delta[0][0][0]=   (-r*sprite_ref[0][0] + virtual_ref[0][0]);
2339             s->sprite_delta[0][0][1]=   ( r*sprite_ref[0][1] - virtual_ref[0][1]);
2340             s->sprite_delta[0][1][0]=   (-r*sprite_ref[0][1] + virtual_ref[0][1]);
2341             s->sprite_delta[0][1][1]=   (-r*sprite_ref[0][0] + virtual_ref[0][0]);
2342             s->sprite_delta[1][0][0]= 4*(-r*sprite_ref[0][0] + virtual_ref[0][0]);
2343             s->sprite_delta[1][0][1]= 4*( r*sprite_ref[0][1] - virtual_ref[0][1]);
2344             s->sprite_delta[1][1][0]= 4*(-r*sprite_ref[0][1] + virtual_ref[0][1]);
2345             s->sprite_delta[1][1][1]= 4*(-r*sprite_ref[0][0] + virtual_ref[0][0]);
2346             s->sprite_shift[0][0]= alpha+rho;
2347             s->sprite_shift[0][1]= alpha+rho;
2348             s->sprite_shift[1][0]= alpha+rho+2;
2349             s->sprite_shift[1][1]= alpha+rho+2;
2350             break;
2351 //        case 3:
2352             break;
2353     }
2354 /*printf("%d %d\n", s->sprite_delta[0][0][0], a<<s->sprite_shift[0][0]);
2355 printf("%d %d\n", s->sprite_delta[0][0][1], 0);
2356 printf("%d %d\n", s->sprite_delta[0][1][0], 0);
2357 printf("%d %d\n", s->sprite_delta[0][1][1], a<<s->sprite_shift[0][1]);
2358 printf("%d %d\n", s->sprite_delta[1][0][0], a<<s->sprite_shift[1][0]);
2359 printf("%d %d\n", s->sprite_delta[1][0][1], 0);
2360 printf("%d %d\n", s->sprite_delta[1][1][0], 0);
2361 printf("%d %d\n", s->sprite_delta[1][1][1], a<<s->sprite_shift[1][1]);*/
2362     /* try to simplify the situation */ 
2363     if(   s->sprite_delta[0][0][0] == a<<s->sprite_shift[0][0]
2364        && s->sprite_delta[0][0][1] == 0
2365        && s->sprite_delta[0][1][0] == 0
2366        && s->sprite_delta[0][1][1] == a<<s->sprite_shift[0][1]
2367        && s->sprite_delta[1][0][0] == a<<s->sprite_shift[1][0]
2368        && s->sprite_delta[1][0][1] == 0
2369        && s->sprite_delta[1][1][0] == 0
2370        && s->sprite_delta[1][1][1] == a<<s->sprite_shift[1][1])
2371     {
2372         s->sprite_offset[0][0]>>=s->sprite_shift[0][0];
2373         s->sprite_offset[0][1]>>=s->sprite_shift[0][1];
2374         s->sprite_offset[1][0]>>=s->sprite_shift[1][0];
2375         s->sprite_offset[1][1]>>=s->sprite_shift[1][1];
2376         s->sprite_delta[0][0][0]= a;
2377         s->sprite_delta[0][0][1]= 0;
2378         s->sprite_delta[0][1][0]= 0;
2379         s->sprite_delta[0][1][1]= a;
2380         s->sprite_delta[1][0][0]= a;
2381         s->sprite_delta[1][0][1]= 0;
2382         s->sprite_delta[1][1][0]= 0;
2383         s->sprite_delta[1][1][1]= a;
2384         s->sprite_shift[0][0]= 0;
2385         s->sprite_shift[0][1]= 0;
2386         s->sprite_shift[1][0]= 0;
2387         s->sprite_shift[1][1]= 0;
2388         s->real_sprite_warping_points=1;
2389     }
2390     else
2391         s->real_sprite_warping_points= s->num_sprite_warping_points;
2392
2393 //printf("%d %d %d %d\n", d[0][0], d[0][1], s->sprite_offset[0][0], s->sprite_offset[0][1]);
2394 }
2395
2396 /* decode mpeg4 VOP header */
2397 int mpeg4_decode_picture_header(MpegEncContext * s)
2398 {
2399     int time_incr, startcode, state, v;
2400
2401  redo:
2402     /* search next start code */
2403     align_get_bits(&s->gb);
2404     state = 0xff;
2405     for(;;) {
2406         v = get_bits(&s->gb, 8);
2407         if (state == 0x000001) {
2408             state = ((state << 8) | v) & 0xffffff;
2409             startcode = state;
2410             break;
2411         }
2412         state = ((state << 8) | v) & 0xffffff;
2413         if( get_bits_count(&s->gb) > s->gb.size*8-32){
2414             printf("no VOP startcode found\n");
2415             return -1;
2416         }
2417     }
2418 //printf("startcode %X %d\n", startcode, get_bits_count(&s->gb));
2419     if (startcode == 0x120) { // Video Object Layer
2420         int width, height, vo_ver_id;
2421
2422         /* vol header */
2423         skip_bits(&s->gb, 1); /* random access */
2424         skip_bits(&s->gb, 8); /* vo_type */
2425         if (get_bits1(&s->gb) != 0) { /* is_ol_id */
2426             vo_ver_id = get_bits(&s->gb, 4); /* vo_ver_id */
2427             skip_bits(&s->gb, 3); /* vo_priority */
2428         } else {
2429             vo_ver_id = 1;
2430         }
2431         
2432         s->aspect_ratio_info= get_bits(&s->gb, 4);
2433         if(s->aspect_ratio_info == EXTENDET_PAR){
2434             skip_bits(&s->gb, 8); //par_width
2435             skip_bits(&s->gb, 8); // par_height
2436         }
2437
2438         if(get_bits1(&s->gb)){ /* vol control parameter */
2439             printf("vol control parameter not supported\n");
2440             return -1;   
2441         }
2442         s->shape = get_bits(&s->gb, 2); /* vol shape */
2443         if(s->shape != RECT_SHAPE) printf("only rectangular vol supported\n");
2444         if(s->shape == GRAY_SHAPE && vo_ver_id != 1){
2445             printf("Gray shape not supported\n");
2446             skip_bits(&s->gb, 4);  //video_object_layer_shape_extension
2447         }
2448
2449         skip_bits1(&s->gb);   /* marker */
2450         
2451         s->time_increment_resolution = get_bits(&s->gb, 16);
2452         s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;
2453         if (s->time_increment_bits < 1)
2454             s->time_increment_bits = 1;
2455         skip_bits1(&s->gb);   /* marker */
2456
2457         if (get_bits1(&s->gb) != 0) {   /* fixed_vop_rate  */
2458             skip_bits(&s->gb, s->time_increment_bits);
2459         }
2460
2461         if (s->shape != BIN_ONLY_SHAPE) {
2462             if (s->shape == RECT_SHAPE) {
2463                 skip_bits1(&s->gb);   /* marker */
2464                 width = get_bits(&s->gb, 13);
2465                 skip_bits1(&s->gb);   /* marker */
2466                 height = get_bits(&s->gb, 13);
2467                 skip_bits1(&s->gb);   /* marker */
2468                 if(width && height){ /* they should be non zero but who knows ... */
2469                     s->width = width;
2470                     s->height = height;
2471 //                    printf("%d %d\n", width, height);
2472                 }
2473             }
2474             
2475             if(get_bits1(&s->gb)) printf("interlaced not supported\n");   /* interlaced */
2476             if(!get_bits1(&s->gb)) printf("OBMC not supported\n");   /* OBMC Disable */
2477             if (vo_ver_id == 1) {
2478                 s->vol_sprite_usage = get_bits1(&s->gb); /* vol_sprite_usage */
2479             } else {
2480                 s->vol_sprite_usage = get_bits(&s->gb, 2); /* vol_sprite_usage */
2481             }
2482             if(s->vol_sprite_usage==STATIC_SPRITE) printf("Static Sprites not supported\n");
2483             if(s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE){
2484                 if(s->vol_sprite_usage==STATIC_SPRITE){
2485                     s->sprite_width = get_bits(&s->gb, 13);
2486                     skip_bits1(&s->gb); /* marker */
2487                     s->sprite_height= get_bits(&s->gb, 13);
2488                     skip_bits1(&s->gb); /* marker */
2489                     s->sprite_left  = get_bits(&s->gb, 13);
2490                     skip_bits1(&s->gb); /* marker */
2491                     s->sprite_top   = get_bits(&s->gb, 13);
2492                     skip_bits1(&s->gb); /* marker */
2493                 }
2494                 s->num_sprite_warping_points= get_bits(&s->gb, 6);
2495                 s->sprite_warping_accuracy = get_bits(&s->gb, 2);
2496                 s->sprite_brightness_change= get_bits1(&s->gb);
2497                 if(s->vol_sprite_usage==STATIC_SPRITE)
2498                     s->low_latency_sprite= get_bits1(&s->gb);            
2499             }
2500             // FIXME sadct disable bit if verid!=1 && shape not rect
2501             
2502             if (get_bits1(&s->gb) == 1) {   /* not_8_bit */
2503                 s->quant_precision = get_bits(&s->gb, 4); /* quant_precision */
2504                 if(get_bits(&s->gb, 4)!=8) printf("N-bit not supported\n"); /* bits_per_pixel */
2505                 if(s->quant_precision!=5) printf("quant precission %d\n", s->quant_precision);
2506             } else {
2507                 s->quant_precision = 5;
2508             }
2509             
2510             // FIXME a bunch of grayscale shape things
2511
2512             if(get_bits1(&s->gb)){ /* vol_quant_type */
2513                 int i, j, v;
2514                 /* load default matrixes */
2515                 for(i=0; i<64; i++){
2516                     v= ff_mpeg4_default_intra_matrix[i];
2517                     s->intra_matrix[i]= v;
2518                     s->chroma_intra_matrix[i]= v;
2519                     
2520                     v= ff_mpeg4_default_non_intra_matrix[i];
2521                     s->non_intra_matrix[i]= v;
2522                     s->chroma_non_intra_matrix[i]= v;
2523                 }
2524
2525                 /* load custom intra matrix */
2526                 if(get_bits1(&s->gb)){
2527                     for(i=0; i<64; i++){
2528                         v= get_bits(&s->gb, 8);
2529                         if(v==0) break;
2530
2531                         j= zigzag_direct[i];
2532                         s->intra_matrix[j]= v;
2533                         s->chroma_intra_matrix[j]= v;
2534                     }
2535                 }
2536
2537                 /* load custom non intra matrix */
2538                 if(get_bits1(&s->gb)){
2539                     for(i=0; i<64; i++){
2540                         v= get_bits(&s->gb, 8);
2541                         if(v==0) break;
2542
2543                         j= zigzag_direct[i];
2544                         s->non_intra_matrix[j]= v;
2545                         s->chroma_non_intra_matrix[j]= v;
2546                     }
2547
2548                     /* replicate last value */
2549                     for(; i<64; i++){
2550                         j= zigzag_direct[i];
2551                         s->non_intra_matrix[j]= v;
2552                         s->chroma_non_intra_matrix[j]= v;
2553                     }
2554                 }
2555
2556                 s->dct_unquantize= s->dct_unquantize_mpeg;
2557
2558                 // FIXME a bunch of grayscale shape things
2559             }else
2560                 s->dct_unquantize= s->dct_unquantize_h263;
2561
2562             if(vo_ver_id != 1)
2563                  s->quarter_sample= get_bits1(&s->gb);
2564             else s->quarter_sample=0;
2565
2566             if(!get_bits1(&s->gb)) printf("Complexity estimation not supported\n");
2567
2568             s->resync_marker= !get_bits1(&s->gb); /* resync_marker_disabled */
2569
2570             s->data_partioning= get_bits1(&s->gb);
2571             if(s->data_partioning){
2572                 printf("data partitioning not supported\n");
2573                 skip_bits1(&s->gb); // reversible vlc
2574             }
2575             
2576             if(vo_ver_id != 1) {
2577                 s->new_pred= get_bits1(&s->gb);
2578                 if(s->new_pred){
2579                     printf("new pred not supported\n");
2580                     skip_bits(&s->gb, 2); /* requested upstream message type */
2581                     skip_bits1(&s->gb); /* newpred segment type */
2582                 }
2583                 s->reduced_res_vop= get_bits1(&s->gb);
2584                 if(s->reduced_res_vop) printf("reduced resolution VOP not supported\n");
2585             }
2586             else{
2587                 s->new_pred=0;
2588                 s->reduced_res_vop= 0;
2589             }
2590
2591             s->scalability= get_bits1(&s->gb);
2592             if (s->scalability) {
2593                 printf("scalability not supported\n");
2594             }
2595         }
2596 //printf("end Data %X %d\n", show_bits(&s->gb, 32), get_bits_count(&s->gb)&0x7);
2597         goto redo;
2598     } else if (startcode == 0x1b2) { //userdata
2599         char buf[256];
2600         int i;
2601         int e;
2602         int ver, build;
2603
2604 //printf("user Data %X\n", show_bits(&s->gb, 32));
2605         buf[0]= show_bits(&s->gb, 8);
2606         for(i=1; i<256; i++){
2607             buf[i]= show_bits(&s->gb, 16)&0xFF;
2608             if(buf[i]==0) break;
2609             skip_bits(&s->gb, 8);
2610         }
2611         buf[255]=0;
2612         e=sscanf(buf, "DivX%dBuild%d", &ver, &build);
2613         if(e==2){
2614             s->divx_version= ver;
2615             s->divx_build= build;
2616             if(s->picture_number==0){
2617                 printf("This file was encoded with DivX%d Build%d\n", ver, build);
2618                 if(ver==500 && build==413){ //most likely all version are indeed totally buggy but i dunno for sure ...
2619                     printf("WARNING: this version of DivX is not MPEG4 compatible, trying to workaround these bugs...\n");
2620                 }else{
2621                     printf("hmm, i havnt seen that version of divx yet, lets assume they fixed these bugs ...\n"
2622                            "using mpeg4 decoder, if it fails contact the developers (of ffmpeg)\n");
2623                 }
2624             }
2625         }
2626 //printf("User Data: %s\n", buf);
2627         goto redo;
2628     } else if (startcode != 0x1b6) { //VOP
2629         goto redo;
2630     }
2631
2632     s->pict_type = get_bits(&s->gb, 2) + 1;     /* pict type: I = 0 , P = 1 */
2633 //printf("pic: %d, qpel:%d\n", s->pict_type, s->quarter_sample); 
2634     time_incr=0;
2635     while (get_bits1(&s->gb) != 0) 
2636         time_incr++;
2637
2638     check_marker(&s->gb, "before time_increment");
2639     s->time_increment= get_bits(&s->gb, s->time_increment_bits);
2640     if(s->pict_type!=B_TYPE){
2641         s->time_base+= time_incr;
2642         s->last_non_b_time[1]= s->last_non_b_time[0];
2643         s->last_non_b_time[0]= s->time_base*s->time_increment_resolution + s->time_increment;
2644     }else{
2645         s->time= (s->last_non_b_time[1]/s->time_increment_resolution + time_incr)*s->time_increment_resolution;
2646         s->time+= s->time_increment;
2647     }
2648
2649     if(check_marker(&s->gb, "before vop_coded")==0 && s->picture_number==0){
2650         printf("hmm, seems the headers arnt complete, trying to guess time_increment_bits\n");
2651         for(s->time_increment_bits++ ;s->time_increment_bits<16; s->time_increment_bits++){
2652             if(get_bits1(&s->gb)) break;
2653         }
2654         printf("my guess is %d bits ;)\n",s->time_increment_bits);
2655     }
2656     /* vop coded */
2657     if (get_bits1(&s->gb) != 1)
2658         goto redo;
2659 //printf("time %d %d %d || %d %d %d\n", s->time_increment_bits, s->time_increment, s->time_base,
2660 //s->time, s->last_non_b_time[0], s->last_non_b_time[1]);  
2661     if (s->shape != BIN_ONLY_SHAPE && ( s->pict_type == P_TYPE
2662                           || (s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE))) {
2663         /* rounding type for motion estimation */
2664         s->no_rounding = get_bits1(&s->gb);
2665     } else {
2666         s->no_rounding = 0;
2667     }
2668 //FIXME reduced res stuff
2669
2670      if (s->shape != RECT_SHAPE) {
2671          if (s->vol_sprite_usage != 1 || s->pict_type != I_TYPE) {
2672              int width, height, hor_spat_ref, ver_spat_ref;
2673  
2674              width = get_bits(&s->gb, 13);
2675              skip_bits1(&s->gb);   /* marker */
2676              height = get_bits(&s->gb, 13);
2677              skip_bits1(&s->gb);   /* marker */
2678              hor_spat_ref = get_bits(&s->gb, 13); /* hor_spat_ref */
2679              skip_bits1(&s->gb);   /* marker */
2680              ver_spat_ref = get_bits(&s->gb, 13); /* ver_spat_ref */
2681          }
2682          skip_bits1(&s->gb); /* change_CR_disable */
2683  
2684          if (get_bits1(&s->gb) != 0) {
2685              skip_bits(&s->gb, 8); /* constant_alpha_value */
2686          }
2687      }
2688 //FIXME complexity estimation stuff
2689      
2690      if (s->shape != BIN_ONLY_SHAPE) {
2691          int t;
2692          t=get_bits(&s->gb, 3); /* intra dc VLC threshold */
2693 //printf("threshold %d\n", t);
2694          //FIXME interlaced specific bits
2695      }
2696
2697      if(s->pict_type == S_TYPE && (s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE)){
2698          if(s->num_sprite_warping_points){
2699              mpeg4_decode_sprite_trajectory(s);
2700          }
2701          if(s->sprite_brightness_change) printf("sprite_brightness_change not supported\n");
2702          if(s->vol_sprite_usage==STATIC_SPRITE) printf("static sprite not supported\n");
2703      }
2704
2705      if (s->shape != BIN_ONLY_SHAPE) {
2706          /* note: we do not use quant_precision to avoid problem if no
2707             MPEG4 vol header as it is found on some old opendivx
2708             movies */
2709          s->qscale = get_bits(&s->gb, 5);
2710          if(s->qscale==0){
2711              printf("Error, header damaged or not MPEG4 header (qscale=0)\n");
2712              return -1; // makes no sense to continue, as there is nothing left from the image then
2713          }
2714   
2715          if (s->pict_type != I_TYPE) {
2716              s->f_code = get_bits(&s->gb, 3);   /* fcode_for */
2717              if(s->f_code==0){
2718                  printf("Error, header damaged or not MPEG4 header (f_code=0)\n");
2719                  return -1; // makes no sense to continue, as the MV decoding will break very quickly
2720              }
2721          }
2722          if (s->pict_type == B_TYPE) {
2723              s->b_code = get_bits(&s->gb, 3);
2724 //printf("b-code %d\n", s->b_code);
2725          }
2726 //printf("quant:%d fcode:%d\n", s->qscale, s->f_code);
2727          if(!s->scalability){
2728              if (s->shape!=RECT_SHAPE && s->pict_type!=I_TYPE) {
2729                  skip_bits1(&s->gb); // vop shape coding type
2730              }
2731          }
2732      }
2733      s->picture_number++; // better than pic number==0 allways ;)
2734      return 0;
2735 }
2736
2737 /* don't understand why they choose a different header ! */
2738 int intel_h263_decode_picture_header(MpegEncContext *s)
2739 {
2740     int format;
2741
2742     /* picture header */
2743     if (get_bits(&s->gb, 22) != 0x20)
2744         return -1;
2745     skip_bits(&s->gb, 8); /* picture timestamp */
2746
2747     if (get_bits1(&s->gb) != 1)
2748         return -1;      /* marker */
2749     if (get_bits1(&s->gb) != 0)
2750         return -1;      /* h263 id */
2751     skip_bits1(&s->gb); /* split screen off */
2752     skip_bits1(&s->gb); /* camera  off */
2753     skip_bits1(&s->gb); /* freeze picture release off */
2754
2755     format = get_bits(&s->gb, 3);
2756     if (format != 7)
2757         return -1;
2758
2759     s->h263_plus = 0;
2760
2761     s->pict_type = I_TYPE + get_bits1(&s->gb);
2762     
2763     s->unrestricted_mv = get_bits1(&s->gb); 
2764     s->h263_long_vectors = s->unrestricted_mv;
2765
2766     if (get_bits1(&s->gb) != 0)
2767         return -1;      /* SAC: off */
2768     if (get_bits1(&s->gb) != 0)
2769         return -1;      /* advanced prediction mode: off */
2770     if (get_bits1(&s->gb) != 0)
2771         return -1;      /* not PB frame */
2772
2773     /* skip unknown header garbage */
2774     skip_bits(&s->gb, 41);
2775
2776     s->qscale = get_bits(&s->gb, 5);
2777     skip_bits1(&s->gb); /* Continuous Presence Multipoint mode: off */
2778
2779     /* PEI */
2780     while (get_bits1(&s->gb) != 0) {
2781         skip_bits(&s->gb, 8);
2782     }
2783     s->f_code = 1;
2784     return 0;
2785 }
2786