e7ef981d77f382e1ff14ad17450d7c7ac93b5e34
[ffmpeg.git] / libavcodec / h263.c
1 /*
2  * H263/MPEG4 backend for ffmpeg encoder and decoder
3  * Copyright (c) 2000,2001 Fabrice Bellard
4  * H263+ support.
5  * Copyright (c) 2001 Juan J. Sierralta P
6  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
7  *
8  * ac prediction encoding, B-frame support, error resilience, optimizations,
9  * qpel decoding, gmc decoding, interlaced decoding
10  * by Michael Niedermayer <michaelni@gmx.at>
11  *
12  * This file is part of FFmpeg.
13  *
14  * FFmpeg is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU Lesser General Public
16  * License as published by the Free Software Foundation; either
17  * version 2.1 of the License, or (at your option) any later version.
18  *
19  * FFmpeg is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22  * Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public
25  * License along with FFmpeg; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27  */
28
29 /**
30  * @file libavcodec/h263.c
31  * h263/mpeg4 codec.
32  */
33
34 //#define DEBUG
35 #include <limits.h>
36
37 #include "dsputil.h"
38 #include "avcodec.h"
39 #include "mpegvideo.h"
40 #include "h263data.h"
41 #include "mpeg4data.h"
42 #include "mathops.h"
43 #include "unary.h"
44
45 //#undef NDEBUG
46 //#include <assert.h>
47
48 #define INTRA_MCBPC_VLC_BITS 6
49 #define INTER_MCBPC_VLC_BITS 7
50 #define CBPY_VLC_BITS 6
51 #define MV_VLC_BITS 9
52 #define DC_VLC_BITS 9
53 #define SPRITE_TRAJ_VLC_BITS 6
54 #define MB_TYPE_B_VLC_BITS 4
55 #define TEX_VLC_BITS 9
56 #define H263_MBTYPE_B_VLC_BITS 6
57 #define CBPC_B_VLC_BITS 3
58
59 static int h263_decode_motion(MpegEncContext * s, int pred, int fcode);
60 static int h263p_decode_umotion(MpegEncContext * s, int pred);
61 static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
62                              int n, int coded);
63 static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr);
64 static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
65                               int n, int coded, int intra, int rvlc);
66
67 static void mpeg4_decode_sprite_trajectory(MpegEncContext * s, GetBitContext *gb);
68 static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, int level, int *dir_ptr, int encoding);
69
70 #if CONFIG_ENCODERS
71 static void h263_encode_block(MpegEncContext *s, DCTELEM *block, int n);
72 static void h263p_encode_umotion(MpegEncContext *s, int val);
73 static int h263_pred_dc(MpegEncContext *s, int n, int16_t **dc_val_ptr);
74
75 static void mpeg4_encode_visual_object_header(MpegEncContext *s);
76 static void mpeg4_encode_vol_header(MpegEncContext *s, int vo_number,
77                                     int vol_number);
78 static inline void mpeg4_encode_block(MpegEncContext *s, DCTELEM *block,
79                                       int n, int dc, uint8_t *scan_table,
80                                       PutBitContext *dc_pb,
81                                       PutBitContext *ac_pb);
82 static int mpeg4_get_block_length(MpegEncContext *s, DCTELEM *block, int n,
83                                   int intra_dc, uint8_t *scan_table);
84
85 static uint8_t uni_DCtab_lum_len[512];
86 static uint8_t uni_DCtab_chrom_len[512];
87 static uint16_t uni_DCtab_lum_bits[512];
88 static uint16_t uni_DCtab_chrom_bits[512];
89
90 static uint8_t mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
91 static uint8_t fcode_tab[MAX_MV*2+1];
92 static uint8_t umv_fcode_tab[MAX_MV*2+1];
93
94 static uint32_t uni_mpeg4_intra_rl_bits[64*64*2*2];
95 static uint8_t  uni_mpeg4_intra_rl_len [64*64*2*2];
96 static uint32_t uni_mpeg4_inter_rl_bits[64*64*2*2];
97 static uint8_t  uni_mpeg4_inter_rl_len [64*64*2*2];
98 static uint8_t  uni_h263_intra_aic_rl_len [64*64*2*2];
99 static uint8_t  uni_h263_inter_rl_len [64*64*2*2];
100 //#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128 + (run)*256 + (level))
101 //#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run) + (level)*64)
102 #define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run)*128 + (level))
103
104 /* mpeg4
105 inter
106 max level: 24/6
107 max run: 53/63
108
109 intra
110 max level: 53/16
111 max run: 29/41
112 */
113 #endif
114
115 static uint8_t static_rl_table_store[5][2][2*MAX_RUN + MAX_LEVEL + 3];
116
117 #if 0 //3IV1 is quite rare and it slows things down a tiny bit
118 #define IS_3IV1 s->codec_tag == AV_RL32("3IV1")
119 #else
120 #define IS_3IV1 0
121 #endif
122
123 int h263_get_picture_format(int width, int height)
124 {
125     int format;
126
127     if (width == 128 && height == 96)
128         format = 1;
129     else if (width == 176 && height == 144)
130         format = 2;
131     else if (width == 352 && height == 288)
132         format = 3;
133     else if (width == 704 && height == 576)
134         format = 4;
135     else if (width == 1408 && height == 1152)
136         format = 5;
137     else
138         format = 7;
139     return format;
140 }
141
142 static void show_pict_info(MpegEncContext *s){
143     av_log(s->avctx, AV_LOG_DEBUG, "qp:%d %c size:%d rnd:%d%s%s%s%s%s%s%s%s%s %d/%d\n",
144          s->qscale, av_get_pict_type_char(s->pict_type),
145          s->gb.size_in_bits, 1-s->no_rounding,
146          s->obmc ? " AP" : "",
147          s->umvplus ? " UMV" : "",
148          s->h263_long_vectors ? " LONG" : "",
149          s->h263_plus ? " +" : "",
150          s->h263_aic ? " AIC" : "",
151          s->alt_inter_vlc ? " AIV" : "",
152          s->modified_quant ? " MQ" : "",
153          s->loop_filter ? " LOOP" : "",
154          s->h263_slice_structured ? " SS" : "",
155          s->avctx->time_base.den, s->avctx->time_base.num
156     );
157 }
158
159 #if CONFIG_ENCODERS
160
161 static void aspect_to_info(MpegEncContext * s, AVRational aspect){
162     int i;
163
164     if(aspect.num==0) aspect= (AVRational){1,1};
165
166     for(i=1; i<6; i++){
167         if(av_cmp_q(pixel_aspect[i], aspect) == 0){
168             s->aspect_ratio_info=i;
169             return;
170         }
171     }
172
173     s->aspect_ratio_info= FF_ASPECT_EXTENDED;
174 }
175
176 void ff_flv_encode_picture_header(MpegEncContext * s, int picture_number)
177 {
178       int format;
179
180       align_put_bits(&s->pb);
181
182       put_bits(&s->pb, 17, 1);
183       put_bits(&s->pb, 5, (s->h263_flv-1)); /* 0: h263 escape codes 1: 11-bit escape codes */
184       put_bits(&s->pb, 8, (((int64_t)s->picture_number * 30 * s->avctx->time_base.num) / //FIXME use timestamp
185                            s->avctx->time_base.den) & 0xff); /* TemporalReference */
186       if (s->width == 352 && s->height == 288)
187         format = 2;
188       else if (s->width == 176 && s->height == 144)
189         format = 3;
190       else if (s->width == 128 && s->height == 96)
191         format = 4;
192       else if (s->width == 320 && s->height == 240)
193         format = 5;
194       else if (s->width == 160 && s->height == 120)
195         format = 6;
196       else if (s->width <= 255 && s->height <= 255)
197         format = 0; /* use 1 byte width & height */
198       else
199         format = 1; /* use 2 bytes width & height */
200       put_bits(&s->pb, 3, format); /* PictureSize */
201       if (format == 0) {
202         put_bits(&s->pb, 8, s->width);
203         put_bits(&s->pb, 8, s->height);
204       } else if (format == 1) {
205         put_bits(&s->pb, 16, s->width);
206         put_bits(&s->pb, 16, s->height);
207       }
208       put_bits(&s->pb, 2, s->pict_type == FF_P_TYPE); /* PictureType */
209       put_bits(&s->pb, 1, 1); /* DeblockingFlag: on */
210       put_bits(&s->pb, 5, s->qscale); /* Quantizer */
211       put_bits(&s->pb, 1, 0); /* ExtraInformation */
212
213       if(s->h263_aic){
214         s->y_dc_scale_table=
215           s->c_dc_scale_table= ff_aic_dc_scale_table;
216       }else{
217         s->y_dc_scale_table=
218           s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
219       }
220 }
221
222 void h263_encode_picture_header(MpegEncContext * s, int picture_number)
223 {
224     int format, coded_frame_rate, coded_frame_rate_base, i, temp_ref;
225     int best_clock_code=1;
226     int best_divisor=60;
227     int best_error= INT_MAX;
228
229     if(s->h263_plus){
230         for(i=0; i<2; i++){
231             int div, error;
232             div= (s->avctx->time_base.num*1800000LL + 500LL*s->avctx->time_base.den) / ((1000LL+i)*s->avctx->time_base.den);
233             div= av_clip(div, 1, 127);
234             error= FFABS(s->avctx->time_base.num*1800000LL - (1000LL+i)*s->avctx->time_base.den*div);
235             if(error < best_error){
236                 best_error= error;
237                 best_divisor= div;
238                 best_clock_code= i;
239             }
240         }
241     }
242     s->custom_pcf= best_clock_code!=1 || best_divisor!=60;
243     coded_frame_rate= 1800000;
244     coded_frame_rate_base= (1000+best_clock_code)*best_divisor;
245
246     align_put_bits(&s->pb);
247
248     /* Update the pointer to last GOB */
249     s->ptr_lastgob = put_bits_ptr(&s->pb);
250     put_bits(&s->pb, 22, 0x20); /* PSC */
251     temp_ref= s->picture_number * (int64_t)coded_frame_rate * s->avctx->time_base.num / //FIXME use timestamp
252                          (coded_frame_rate_base * (int64_t)s->avctx->time_base.den);
253     put_sbits(&s->pb, 8, temp_ref); /* TemporalReference */
254
255     put_bits(&s->pb, 1, 1);     /* marker */
256     put_bits(&s->pb, 1, 0);     /* h263 id */
257     put_bits(&s->pb, 1, 0);     /* split screen off */
258     put_bits(&s->pb, 1, 0);     /* camera  off */
259     put_bits(&s->pb, 1, 0);     /* freeze picture release off */
260
261     format = h263_get_picture_format(s->width, s->height);
262     if (!s->h263_plus) {
263         /* H.263v1 */
264         put_bits(&s->pb, 3, format);
265         put_bits(&s->pb, 1, (s->pict_type == FF_P_TYPE));
266         /* By now UMV IS DISABLED ON H.263v1, since the restrictions
267         of H.263v1 UMV implies to check the predicted MV after
268         calculation of the current MB to see if we're on the limits */
269         put_bits(&s->pb, 1, 0);         /* Unrestricted Motion Vector: off */
270         put_bits(&s->pb, 1, 0);         /* SAC: off */
271         put_bits(&s->pb, 1, s->obmc);   /* Advanced Prediction */
272         put_bits(&s->pb, 1, 0);         /* only I/P frames, no PB frame */
273         put_bits(&s->pb, 5, s->qscale);
274         put_bits(&s->pb, 1, 0);         /* Continuous Presence Multipoint mode: off */
275     } else {
276         int ufep=1;
277         /* H.263v2 */
278         /* H.263 Plus PTYPE */
279
280         put_bits(&s->pb, 3, 7);
281         put_bits(&s->pb,3,ufep); /* Update Full Extended PTYPE */
282         if (format == 7)
283             put_bits(&s->pb,3,6); /* Custom Source Format */
284         else
285             put_bits(&s->pb, 3, format);
286
287         put_bits(&s->pb,1, s->custom_pcf);
288         put_bits(&s->pb,1, s->umvplus); /* Unrestricted Motion Vector */
289         put_bits(&s->pb,1,0); /* SAC: off */
290         put_bits(&s->pb,1,s->obmc); /* Advanced Prediction Mode */
291         put_bits(&s->pb,1,s->h263_aic); /* Advanced Intra Coding */
292         put_bits(&s->pb,1,s->loop_filter); /* Deblocking Filter */
293         put_bits(&s->pb,1,s->h263_slice_structured); /* Slice Structured */
294         put_bits(&s->pb,1,0); /* Reference Picture Selection: off */
295         put_bits(&s->pb,1,0); /* Independent Segment Decoding: off */
296         put_bits(&s->pb,1,s->alt_inter_vlc); /* Alternative Inter VLC */
297         put_bits(&s->pb,1,s->modified_quant); /* Modified Quantization: */
298         put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
299         put_bits(&s->pb,3,0); /* Reserved */
300
301         put_bits(&s->pb, 3, s->pict_type == FF_P_TYPE);
302
303         put_bits(&s->pb,1,0); /* Reference Picture Resampling: off */
304         put_bits(&s->pb,1,0); /* Reduced-Resolution Update: off */
305         put_bits(&s->pb,1,s->no_rounding); /* Rounding Type */
306         put_bits(&s->pb,2,0); /* Reserved */
307         put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
308
309         /* This should be here if PLUSPTYPE */
310         put_bits(&s->pb, 1, 0); /* Continuous Presence Multipoint mode: off */
311
312                 if (format == 7) {
313             /* Custom Picture Format (CPFMT) */
314             aspect_to_info(s, s->avctx->sample_aspect_ratio);
315
316             put_bits(&s->pb,4,s->aspect_ratio_info);
317             put_bits(&s->pb,9,(s->width >> 2) - 1);
318             put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
319             put_bits(&s->pb,9,(s->height >> 2));
320             if (s->aspect_ratio_info == FF_ASPECT_EXTENDED){
321                 put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.num);
322                 put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.den);
323             }
324         }
325         if(s->custom_pcf){
326             if(ufep){
327                 put_bits(&s->pb, 1, best_clock_code);
328                 put_bits(&s->pb, 7, best_divisor);
329             }
330             put_sbits(&s->pb, 2, temp_ref>>8);
331         }
332
333         /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
334         if (s->umvplus)
335 //            put_bits(&s->pb,1,1); /* Limited according tables of Annex D */
336 //FIXME check actual requested range
337             put_bits(&s->pb,2,1); /* unlimited */
338         if(s->h263_slice_structured)
339             put_bits(&s->pb,2,0); /* no weird submodes */
340
341         put_bits(&s->pb, 5, s->qscale);
342     }
343
344     put_bits(&s->pb, 1, 0);     /* no PEI */
345
346     if(s->h263_slice_structured){
347         put_bits(&s->pb, 1, 1);
348
349         assert(s->mb_x == 0 && s->mb_y == 0);
350         ff_h263_encode_mba(s);
351
352         put_bits(&s->pb, 1, 1);
353     }
354
355     if(s->h263_aic){
356          s->y_dc_scale_table=
357          s->c_dc_scale_table= ff_aic_dc_scale_table;
358     }else{
359         s->y_dc_scale_table=
360         s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
361     }
362 }
363
364 /**
365  * Encodes a group of blocks header.
366  */
367 void h263_encode_gob_header(MpegEncContext * s, int mb_line)
368 {
369     put_bits(&s->pb, 17, 1); /* GBSC */
370
371     if(s->h263_slice_structured){
372         put_bits(&s->pb, 1, 1);
373
374         ff_h263_encode_mba(s);
375
376         if(s->mb_num > 1583)
377             put_bits(&s->pb, 1, 1);
378         put_bits(&s->pb, 5, s->qscale); /* GQUANT */
379         put_bits(&s->pb, 1, 1);
380         put_bits(&s->pb, 2, s->pict_type == FF_I_TYPE); /* GFID */
381     }else{
382         int gob_number= mb_line / s->gob_index;
383
384         put_bits(&s->pb, 5, gob_number); /* GN */
385         put_bits(&s->pb, 2, s->pict_type == FF_I_TYPE); /* GFID */
386         put_bits(&s->pb, 5, s->qscale); /* GQUANT */
387     }
388 }
389
390 static inline int get_block_rate(MpegEncContext * s, DCTELEM block[64], int block_last_index, uint8_t scantable[64]){
391     int last=0;
392     int j;
393     int rate=0;
394
395     for(j=1; j<=block_last_index; j++){
396         const int index= scantable[j];
397         int level= block[index];
398         if(level){
399             level+= 64;
400             if((level&(~127)) == 0){
401                 if(j<block_last_index) rate+= s->intra_ac_vlc_length     [UNI_AC_ENC_INDEX(j-last-1, level)];
402                 else                   rate+= s->intra_ac_vlc_last_length[UNI_AC_ENC_INDEX(j-last-1, level)];
403             }else
404                 rate += s->ac_esc_length;
405
406             last= j;
407         }
408     }
409
410     return rate;
411 }
412
413 static inline int decide_ac_pred(MpegEncContext * s, DCTELEM block[6][64], int dir[6], uint8_t *st[6], int zigzag_last_index[6])
414 {
415     int score= 0;
416     int i, n;
417     int8_t * const qscale_table= s->current_picture.qscale_table;
418
419     memcpy(zigzag_last_index, s->block_last_index, sizeof(int)*6);
420
421     for(n=0; n<6; n++){
422         int16_t *ac_val, *ac_val1;
423
424         score -= get_block_rate(s, block[n], s->block_last_index[n], s->intra_scantable.permutated);
425
426         ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
427         ac_val1= ac_val;
428         if(dir[n]){
429             const int xy= s->mb_x + s->mb_y*s->mb_stride - s->mb_stride;
430             /* top prediction */
431             ac_val-= s->block_wrap[n]*16;
432             if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
433                 /* same qscale */
434                 for(i=1; i<8; i++){
435                     const int level= block[n][s->dsp.idct_permutation[i   ]];
436                     block[n][s->dsp.idct_permutation[i   ]] = level - ac_val[i+8];
437                     ac_val1[i  ]=    block[n][s->dsp.idct_permutation[i<<3]];
438                     ac_val1[i+8]= level;
439                 }
440             }else{
441                 /* different qscale, we must rescale */
442                 for(i=1; i<8; i++){
443                     const int level= block[n][s->dsp.idct_permutation[i   ]];
444                     block[n][s->dsp.idct_permutation[i   ]] = level - ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale);
445                     ac_val1[i  ]=    block[n][s->dsp.idct_permutation[i<<3]];
446                     ac_val1[i+8]= level;
447                 }
448             }
449             st[n]= s->intra_h_scantable.permutated;
450         }else{
451             const int xy= s->mb_x-1 + s->mb_y*s->mb_stride;
452             /* left prediction */
453             ac_val-= 16;
454             if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
455                 /* same qscale */
456                 for(i=1; i<8; i++){
457                     const int level= block[n][s->dsp.idct_permutation[i<<3]];
458                     block[n][s->dsp.idct_permutation[i<<3]]= level - ac_val[i];
459                     ac_val1[i  ]= level;
460                     ac_val1[i+8]=    block[n][s->dsp.idct_permutation[i   ]];
461                 }
462             }else{
463                 /* different qscale, we must rescale */
464                 for(i=1; i<8; i++){
465                     const int level= block[n][s->dsp.idct_permutation[i<<3]];
466                     block[n][s->dsp.idct_permutation[i<<3]]= level - ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale);
467                     ac_val1[i  ]= level;
468                     ac_val1[i+8]=    block[n][s->dsp.idct_permutation[i   ]];
469                 }
470             }
471             st[n]= s->intra_v_scantable.permutated;
472         }
473
474         for(i=63; i>0; i--) //FIXME optimize
475             if(block[n][ st[n][i] ]) break;
476         s->block_last_index[n]= i;
477
478         score += get_block_rate(s, block[n], s->block_last_index[n], st[n]);
479     }
480
481     return score < 0;
482 }
483
484 static inline void restore_ac_coeffs(MpegEncContext * s, DCTELEM block[6][64], int dir[6], uint8_t *st[6], int zigzag_last_index[6])
485 {
486     int i, n;
487     memcpy(s->block_last_index, zigzag_last_index, sizeof(int)*6);
488
489     for(n=0; n<6; n++){
490         int16_t *ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
491
492         st[n]= s->intra_scantable.permutated;
493         if(dir[n]){
494             /* top prediction */
495             for(i=1; i<8; i++){
496                 block[n][s->dsp.idct_permutation[i   ]] = ac_val[i+8];
497             }
498         }else{
499             /* left prediction */
500             for(i=1; i<8; i++){
501                 block[n][s->dsp.idct_permutation[i<<3]]= ac_val[i  ];
502             }
503         }
504     }
505 }
506
507 /**
508  * modify qscale so that encoding is acually possible in h263 (limit difference to -2..2)
509  */
510 void ff_clean_h263_qscales(MpegEncContext *s){
511     int i;
512     int8_t * const qscale_table= s->current_picture.qscale_table;
513
514     ff_init_qscale_tab(s);
515
516     for(i=1; i<s->mb_num; i++){
517         if(qscale_table[ s->mb_index2xy[i] ] - qscale_table[ s->mb_index2xy[i-1] ] >2)
518             qscale_table[ s->mb_index2xy[i] ]= qscale_table[ s->mb_index2xy[i-1] ]+2;
519     }
520     for(i=s->mb_num-2; i>=0; i--){
521         if(qscale_table[ s->mb_index2xy[i] ] - qscale_table[ s->mb_index2xy[i+1] ] >2)
522             qscale_table[ s->mb_index2xy[i] ]= qscale_table[ s->mb_index2xy[i+1] ]+2;
523     }
524
525     if(s->codec_id != CODEC_ID_H263P){
526         for(i=1; i<s->mb_num; i++){
527             int mb_xy= s->mb_index2xy[i];
528
529             if(qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i-1]] && (s->mb_type[mb_xy]&CANDIDATE_MB_TYPE_INTER4V)){
530                 s->mb_type[mb_xy]|= CANDIDATE_MB_TYPE_INTER;
531             }
532         }
533     }
534 }
535
536 /**
537  * modify mb_type & qscale so that encoding is acually possible in mpeg4
538  */
539 void ff_clean_mpeg4_qscales(MpegEncContext *s){
540     int i;
541     int8_t * const qscale_table= s->current_picture.qscale_table;
542
543     ff_clean_h263_qscales(s);
544
545     if(s->pict_type== FF_B_TYPE){
546         int odd=0;
547         /* ok, come on, this isn't funny anymore, there's more code for handling this mpeg4 mess than for the actual adaptive quantization */
548
549         for(i=0; i<s->mb_num; i++){
550             int mb_xy= s->mb_index2xy[i];
551             odd += qscale_table[mb_xy]&1;
552         }
553
554         if(2*odd > s->mb_num) odd=1;
555         else                  odd=0;
556
557         for(i=0; i<s->mb_num; i++){
558             int mb_xy= s->mb_index2xy[i];
559             if((qscale_table[mb_xy]&1) != odd)
560                 qscale_table[mb_xy]++;
561             if(qscale_table[mb_xy] > 31)
562                 qscale_table[mb_xy]= 31;
563         }
564
565         for(i=1; i<s->mb_num; i++){
566             int mb_xy= s->mb_index2xy[i];
567             if(qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i-1]] && (s->mb_type[mb_xy]&CANDIDATE_MB_TYPE_DIRECT)){
568                 s->mb_type[mb_xy]|= CANDIDATE_MB_TYPE_BIDIR;
569             }
570         }
571     }
572 }
573
574 #endif //CONFIG_ENCODERS
575
576 #define tab_size ((signed)FF_ARRAY_ELEMS(s->direct_scale_mv[0]))
577 #define tab_bias (tab_size/2)
578
579 void ff_mpeg4_init_direct_mv(MpegEncContext *s){
580     int i;
581     for(i=0; i<tab_size; i++){
582         s->direct_scale_mv[0][i] = (i-tab_bias)*s->pb_time/s->pp_time;
583         s->direct_scale_mv[1][i] = (i-tab_bias)*(s->pb_time-s->pp_time)/s->pp_time;
584     }
585 }
586
587 static inline void ff_mpeg4_set_one_direct_mv(MpegEncContext *s, int mx, int my, int i){
588     int xy= s->block_index[i];
589     uint16_t time_pp= s->pp_time;
590     uint16_t time_pb= s->pb_time;
591     int p_mx, p_my;
592
593     p_mx= s->next_picture.motion_val[0][xy][0];
594     if((unsigned)(p_mx + tab_bias) < tab_size){
595         s->mv[0][i][0] = s->direct_scale_mv[0][p_mx + tab_bias] + mx;
596         s->mv[1][i][0] = mx ? s->mv[0][i][0] - p_mx
597                             : s->direct_scale_mv[1][p_mx + tab_bias];
598     }else{
599         s->mv[0][i][0] = p_mx*time_pb/time_pp + mx;
600         s->mv[1][i][0] = mx ? s->mv[0][i][0] - p_mx
601                             : p_mx*(time_pb - time_pp)/time_pp;
602     }
603     p_my= s->next_picture.motion_val[0][xy][1];
604     if((unsigned)(p_my + tab_bias) < tab_size){
605         s->mv[0][i][1] = s->direct_scale_mv[0][p_my + tab_bias] + my;
606         s->mv[1][i][1] = my ? s->mv[0][i][1] - p_my
607                             : s->direct_scale_mv[1][p_my + tab_bias];
608     }else{
609         s->mv[0][i][1] = p_my*time_pb/time_pp + my;
610         s->mv[1][i][1] = my ? s->mv[0][i][1] - p_my
611                             : p_my*(time_pb - time_pp)/time_pp;
612     }
613 }
614
615 #undef tab_size
616 #undef tab_bias
617
618 /**
619  *
620  * @return the mb_type
621  */
622 int ff_mpeg4_set_direct_mv(MpegEncContext *s, int mx, int my){
623     const int mb_index= s->mb_x + s->mb_y*s->mb_stride;
624     const int colocated_mb_type= s->next_picture.mb_type[mb_index];
625     uint16_t time_pp;
626     uint16_t time_pb;
627     int i;
628
629     //FIXME avoid divides
630     // try special case with shifts for 1 and 3 B-frames?
631
632     if(IS_8X8(colocated_mb_type)){
633         s->mv_type = MV_TYPE_8X8;
634         for(i=0; i<4; i++){
635             ff_mpeg4_set_one_direct_mv(s, mx, my, i);
636         }
637         return MB_TYPE_DIRECT2 | MB_TYPE_8x8 | MB_TYPE_L0L1;
638     } else if(IS_INTERLACED(colocated_mb_type)){
639         s->mv_type = MV_TYPE_FIELD;
640         for(i=0; i<2; i++){
641             int field_select= s->next_picture.ref_index[0][s->block_index[2*i]];
642             s->field_select[0][i]= field_select;
643             s->field_select[1][i]= i;
644             if(s->top_field_first){
645                 time_pp= s->pp_field_time - field_select + i;
646                 time_pb= s->pb_field_time - field_select + i;
647             }else{
648                 time_pp= s->pp_field_time + field_select - i;
649                 time_pb= s->pb_field_time + field_select - i;
650             }
651             s->mv[0][i][0] = s->p_field_mv_table[i][0][mb_index][0]*time_pb/time_pp + mx;
652             s->mv[0][i][1] = s->p_field_mv_table[i][0][mb_index][1]*time_pb/time_pp + my;
653             s->mv[1][i][0] = mx ? s->mv[0][i][0] - s->p_field_mv_table[i][0][mb_index][0]
654                                 : s->p_field_mv_table[i][0][mb_index][0]*(time_pb - time_pp)/time_pp;
655             s->mv[1][i][1] = my ? s->mv[0][i][1] - s->p_field_mv_table[i][0][mb_index][1]
656                                 : s->p_field_mv_table[i][0][mb_index][1]*(time_pb - time_pp)/time_pp;
657         }
658         return MB_TYPE_DIRECT2 | MB_TYPE_16x8 | MB_TYPE_L0L1 | MB_TYPE_INTERLACED;
659     }else{
660         ff_mpeg4_set_one_direct_mv(s, mx, my, 0);
661         s->mv[0][1][0] = s->mv[0][2][0] = s->mv[0][3][0] = s->mv[0][0][0];
662         s->mv[0][1][1] = s->mv[0][2][1] = s->mv[0][3][1] = s->mv[0][0][1];
663         s->mv[1][1][0] = s->mv[1][2][0] = s->mv[1][3][0] = s->mv[1][0][0];
664         s->mv[1][1][1] = s->mv[1][2][1] = s->mv[1][3][1] = s->mv[1][0][1];
665         if((s->avctx->workaround_bugs & FF_BUG_DIRECT_BLOCKSIZE) || !s->quarter_sample)
666             s->mv_type= MV_TYPE_16X16;
667         else
668             s->mv_type= MV_TYPE_8X8;
669         return MB_TYPE_DIRECT2 | MB_TYPE_16x16 | MB_TYPE_L0L1; //Note see prev line
670     }
671 }
672
673 void ff_h263_update_motion_val(MpegEncContext * s){
674     const int mb_xy = s->mb_y * s->mb_stride + s->mb_x;
675                //FIXME a lot of that is only needed for !low_delay
676     const int wrap = s->b8_stride;
677     const int xy = s->block_index[0];
678
679     s->current_picture.mbskip_table[mb_xy]= s->mb_skipped;
680
681     if(s->mv_type != MV_TYPE_8X8){
682         int motion_x, motion_y;
683         if (s->mb_intra) {
684             motion_x = 0;
685             motion_y = 0;
686         } else if (s->mv_type == MV_TYPE_16X16) {
687             motion_x = s->mv[0][0][0];
688             motion_y = s->mv[0][0][1];
689         } else /*if (s->mv_type == MV_TYPE_FIELD)*/ {
690             int i;
691             motion_x = s->mv[0][0][0] + s->mv[0][1][0];
692             motion_y = s->mv[0][0][1] + s->mv[0][1][1];
693             motion_x = (motion_x>>1) | (motion_x&1);
694             for(i=0; i<2; i++){
695                 s->p_field_mv_table[i][0][mb_xy][0]= s->mv[0][i][0];
696                 s->p_field_mv_table[i][0][mb_xy][1]= s->mv[0][i][1];
697             }
698             s->current_picture.ref_index[0][xy           ]=
699             s->current_picture.ref_index[0][xy        + 1]= s->field_select[0][0];
700             s->current_picture.ref_index[0][xy + wrap    ]=
701             s->current_picture.ref_index[0][xy + wrap + 1]= s->field_select[0][1];
702         }
703
704         /* no update if 8X8 because it has been done during parsing */
705         s->current_picture.motion_val[0][xy][0] = motion_x;
706         s->current_picture.motion_val[0][xy][1] = motion_y;
707         s->current_picture.motion_val[0][xy + 1][0] = motion_x;
708         s->current_picture.motion_val[0][xy + 1][1] = motion_y;
709         s->current_picture.motion_val[0][xy + wrap][0] = motion_x;
710         s->current_picture.motion_val[0][xy + wrap][1] = motion_y;
711         s->current_picture.motion_val[0][xy + 1 + wrap][0] = motion_x;
712         s->current_picture.motion_val[0][xy + 1 + wrap][1] = motion_y;
713     }
714
715     if(s->encoding){ //FIXME encoding MUST be cleaned up
716         if (s->mv_type == MV_TYPE_8X8)
717             s->current_picture.mb_type[mb_xy]= MB_TYPE_L0 | MB_TYPE_8x8;
718         else if(s->mb_intra)
719             s->current_picture.mb_type[mb_xy]= MB_TYPE_INTRA;
720         else
721             s->current_picture.mb_type[mb_xy]= MB_TYPE_L0 | MB_TYPE_16x16;
722     }
723 }
724
725 #if CONFIG_ENCODERS
726
727 static inline int h263_get_motion_length(MpegEncContext * s, int val, int f_code){
728     int l, bit_size, code;
729
730     if (val == 0) {
731         return mvtab[0][1];
732     } else {
733         bit_size = f_code - 1;
734         /* modulo encoding */
735         l= INT_BIT - 6 - bit_size;
736         val = (val<<l)>>l;
737         val--;
738         code = (val >> bit_size) + 1;
739
740         return mvtab[code][1] + 1 + bit_size;
741     }
742 }
743
744 static inline void ff_h263_encode_motion_vector(MpegEncContext * s, int x, int y, int f_code){
745     if(s->flags2 & CODEC_FLAG2_NO_OUTPUT){
746         skip_put_bits(&s->pb,
747             h263_get_motion_length(s, x, f_code)
748            +h263_get_motion_length(s, y, f_code));
749     }else{
750         ff_h263_encode_motion(s, x, f_code);
751         ff_h263_encode_motion(s, y, f_code);
752     }
753 }
754
755 static inline int get_p_cbp(MpegEncContext * s,
756                       DCTELEM block[6][64],
757                       int motion_x, int motion_y){
758     int cbp, i;
759
760     if(s->flags & CODEC_FLAG_CBP_RD){
761         int best_cbpy_score= INT_MAX;
762         int best_cbpc_score= INT_MAX;
763         int cbpc = (-1), cbpy= (-1);
764         const int offset= (s->mv_type==MV_TYPE_16X16 ? 0 : 16) + (s->dquant ? 8 : 0);
765         const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
766
767         for(i=0; i<4; i++){
768             int score= inter_MCBPC_bits[i + offset] * lambda;
769             if(i&1) score += s->coded_score[5];
770             if(i&2) score += s->coded_score[4];
771
772             if(score < best_cbpc_score){
773                 best_cbpc_score= score;
774                 cbpc= i;
775             }
776         }
777
778         for(i=0; i<16; i++){
779             int score= cbpy_tab[i ^ 0xF][1] * lambda;
780             if(i&1) score += s->coded_score[3];
781             if(i&2) score += s->coded_score[2];
782             if(i&4) score += s->coded_score[1];
783             if(i&8) score += s->coded_score[0];
784
785             if(score < best_cbpy_score){
786                 best_cbpy_score= score;
787                 cbpy= i;
788             }
789         }
790         cbp= cbpc + 4*cbpy;
791         if ((motion_x | motion_y | s->dquant) == 0 && s->mv_type==MV_TYPE_16X16){
792             if(best_cbpy_score + best_cbpc_score + 2*lambda >= 0)
793                 cbp= 0;
794         }
795
796         for (i = 0; i < 6; i++) {
797             if (s->block_last_index[i] >= 0 && ((cbp >> (5 - i))&1)==0 ){
798                 s->block_last_index[i]= -1;
799                 s->dsp.clear_block(s->block[i]);
800             }
801         }
802     }else{
803         cbp= 0;
804         for (i = 0; i < 6; i++) {
805             if (s->block_last_index[i] >= 0)
806                 cbp |= 1 << (5 - i);
807         }
808     }
809     return cbp;
810 }
811
812 static inline int get_b_cbp(MpegEncContext * s, DCTELEM block[6][64],
813                             int motion_x, int motion_y, int mb_type){
814     int cbp=0, i;
815
816     if(s->flags & CODEC_FLAG_CBP_RD){
817         int score=0;
818         const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
819
820         for(i=0; i<6; i++){
821             if(s->coded_score[i] < 0){
822                 score += s->coded_score[i];
823                 cbp |= 1 << (5 - i);
824             }
825         }
826
827         if(cbp){
828             int zero_score= -6;
829             if ((motion_x | motion_y | s->dquant | mb_type) == 0){
830                 zero_score-= 4; //2*MV + mb_type + cbp bit
831             }
832
833             zero_score*= lambda;
834             if(zero_score <= score){
835                 cbp=0;
836             }
837         }
838
839         for (i = 0; i < 6; i++) {
840             if (s->block_last_index[i] >= 0 && ((cbp >> (5 - i))&1)==0 ){
841                 s->block_last_index[i]= -1;
842                 s->dsp.clear_block(s->block[i]);
843             }
844         }
845     }else{
846         for (i = 0; i < 6; i++) {
847             if (s->block_last_index[i] >= 0)
848                 cbp |= 1 << (5 - i);
849         }
850     }
851     return cbp;
852 }
853
854 static inline void mpeg4_encode_blocks(MpegEncContext * s, DCTELEM block[6][64], int intra_dc[6],
855                                uint8_t **scan_table, PutBitContext *dc_pb, PutBitContext *ac_pb){
856     int i;
857
858     if(scan_table){
859         if(s->flags2 & CODEC_FLAG2_NO_OUTPUT){
860             for (i = 0; i < 6; i++) {
861                 skip_put_bits(&s->pb, mpeg4_get_block_length(s, block[i], i, intra_dc[i], scan_table[i]));
862             }
863         }else{
864             /* encode each block */
865             for (i = 0; i < 6; i++) {
866                 mpeg4_encode_block(s, block[i], i, intra_dc[i], scan_table[i], dc_pb, ac_pb);
867             }
868         }
869     }else{
870         if(s->flags2 & CODEC_FLAG2_NO_OUTPUT){
871             for (i = 0; i < 6; i++) {
872                 skip_put_bits(&s->pb, mpeg4_get_block_length(s, block[i], i, 0, s->intra_scantable.permutated));
873             }
874         }else{
875             /* encode each block */
876             for (i = 0; i < 6; i++) {
877                 mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, dc_pb, ac_pb);
878             }
879         }
880     }
881 }
882
883 static const int dquant_code[5]= {1,0,9,2,3};
884
885 void mpeg4_encode_mb(MpegEncContext * s,
886                     DCTELEM block[6][64],
887                     int motion_x, int motion_y)
888 {
889     int cbpc, cbpy, pred_x, pred_y;
890     PutBitContext * const pb2    = s->data_partitioning                         ? &s->pb2    : &s->pb;
891     PutBitContext * const tex_pb = s->data_partitioning && s->pict_type!=FF_B_TYPE ? &s->tex_pb : &s->pb;
892     PutBitContext * const dc_pb  = s->data_partitioning && s->pict_type!=FF_I_TYPE ? &s->pb2    : &s->pb;
893     const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1) && !s->data_partitioning ? 1 : 0;
894
895     if (!s->mb_intra) {
896         int i, cbp;
897
898         if(s->pict_type==FF_B_TYPE){
899             static const int mb_type_table[8]= {-1, 3, 2, 1,-1,-1,-1, 0}; /* convert from mv_dir to type */
900             int mb_type=  mb_type_table[s->mv_dir];
901
902             if(s->mb_x==0){
903                 for(i=0; i<2; i++){
904                     s->last_mv[i][0][0]=
905                     s->last_mv[i][0][1]=
906                     s->last_mv[i][1][0]=
907                     s->last_mv[i][1][1]= 0;
908                 }
909             }
910
911             assert(s->dquant>=-2 && s->dquant<=2);
912             assert((s->dquant&1)==0);
913             assert(mb_type>=0);
914
915             /* nothing to do if this MB was skipped in the next P Frame */
916             if(s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]){ //FIXME avoid DCT & ...
917                 s->skip_count++;
918                 s->mv[0][0][0]=
919                 s->mv[0][0][1]=
920                 s->mv[1][0][0]=
921                 s->mv[1][0][1]= 0;
922                 s->mv_dir= MV_DIR_FORWARD; //doesn't matter
923                 s->qscale -= s->dquant;
924 //                s->mb_skipped=1;
925
926                 return;
927             }
928
929             cbp= get_b_cbp(s, block, motion_x, motion_y, mb_type);
930
931             if ((cbp | motion_x | motion_y | mb_type) ==0) {
932                 /* direct MB with MV={0,0} */
933                 assert(s->dquant==0);
934
935                 put_bits(&s->pb, 1, 1); /* mb not coded modb1=1 */
936
937                 if(interleaved_stats){
938                     s->misc_bits++;
939                     s->last_bits++;
940                 }
941                 s->skip_count++;
942                 return;
943             }
944
945             put_bits(&s->pb, 1, 0);     /* mb coded modb1=0 */
946             put_bits(&s->pb, 1, cbp ? 0 : 1); /* modb2 */ //FIXME merge
947             put_bits(&s->pb, mb_type+1, 1); // this table is so simple that we don't need it :)
948             if(cbp) put_bits(&s->pb, 6, cbp);
949
950             if(cbp && mb_type){
951                 if(s->dquant)
952                     put_bits(&s->pb, 2, (s->dquant>>2)+3);
953                 else
954                     put_bits(&s->pb, 1, 0);
955             }else
956                 s->qscale -= s->dquant;
957
958             if(!s->progressive_sequence){
959                 if(cbp)
960                     put_bits(&s->pb, 1, s->interlaced_dct);
961                 if(mb_type) // not direct mode
962                     put_bits(&s->pb, 1, s->mv_type == MV_TYPE_FIELD);
963             }
964
965             if(interleaved_stats){
966                 s->misc_bits+= get_bits_diff(s);
967             }
968
969             if(mb_type == 0){
970                 assert(s->mv_dir & MV_DIRECT);
971                 ff_h263_encode_motion_vector(s, motion_x, motion_y, 1);
972                 s->b_count++;
973                 s->f_count++;
974             }else{
975                 assert(mb_type > 0 && mb_type < 4);
976                 if(s->mv_type != MV_TYPE_FIELD){
977                     if(s->mv_dir & MV_DIR_FORWARD){
978                         ff_h263_encode_motion_vector(s, s->mv[0][0][0] - s->last_mv[0][0][0],
979                                                         s->mv[0][0][1] - s->last_mv[0][0][1], s->f_code);
980                         s->last_mv[0][0][0]= s->last_mv[0][1][0]= s->mv[0][0][0];
981                         s->last_mv[0][0][1]= s->last_mv[0][1][1]= s->mv[0][0][1];
982                         s->f_count++;
983                     }
984                     if(s->mv_dir & MV_DIR_BACKWARD){
985                         ff_h263_encode_motion_vector(s, s->mv[1][0][0] - s->last_mv[1][0][0],
986                                                         s->mv[1][0][1] - s->last_mv[1][0][1], s->b_code);
987                         s->last_mv[1][0][0]= s->last_mv[1][1][0]= s->mv[1][0][0];
988                         s->last_mv[1][0][1]= s->last_mv[1][1][1]= s->mv[1][0][1];
989                         s->b_count++;
990                     }
991                 }else{
992                     if(s->mv_dir & MV_DIR_FORWARD){
993                         put_bits(&s->pb, 1, s->field_select[0][0]);
994                         put_bits(&s->pb, 1, s->field_select[0][1]);
995                     }
996                     if(s->mv_dir & MV_DIR_BACKWARD){
997                         put_bits(&s->pb, 1, s->field_select[1][0]);
998                         put_bits(&s->pb, 1, s->field_select[1][1]);
999                     }
1000                     if(s->mv_dir & MV_DIR_FORWARD){
1001                         for(i=0; i<2; i++){
1002                             ff_h263_encode_motion_vector(s, s->mv[0][i][0] - s->last_mv[0][i][0]  ,
1003                                                             s->mv[0][i][1] - s->last_mv[0][i][1]/2, s->f_code);
1004                             s->last_mv[0][i][0]= s->mv[0][i][0];
1005                             s->last_mv[0][i][1]= s->mv[0][i][1]*2;
1006                         }
1007                         s->f_count++;
1008                     }
1009                     if(s->mv_dir & MV_DIR_BACKWARD){
1010                         for(i=0; i<2; i++){
1011                             ff_h263_encode_motion_vector(s, s->mv[1][i][0] - s->last_mv[1][i][0]  ,
1012                                                             s->mv[1][i][1] - s->last_mv[1][i][1]/2, s->b_code);
1013                             s->last_mv[1][i][0]= s->mv[1][i][0];
1014                             s->last_mv[1][i][1]= s->mv[1][i][1]*2;
1015                         }
1016                         s->b_count++;
1017                     }
1018                 }
1019             }
1020
1021             if(interleaved_stats){
1022                 s->mv_bits+= get_bits_diff(s);
1023             }
1024
1025             mpeg4_encode_blocks(s, block, NULL, NULL, NULL, &s->pb);
1026
1027             if(interleaved_stats){
1028                 s->p_tex_bits+= get_bits_diff(s);
1029             }
1030
1031         }else{ /* s->pict_type==FF_B_TYPE */
1032             cbp= get_p_cbp(s, block, motion_x, motion_y);
1033
1034             if ((cbp | motion_x | motion_y | s->dquant) == 0 && s->mv_type==MV_TYPE_16X16) {
1035                 /* check if the B frames can skip it too, as we must skip it if we skip here
1036                    why didn't they just compress the skip-mb bits instead of reusing them ?! */
1037                 if(s->max_b_frames>0){
1038                     int i;
1039                     int x,y, offset;
1040                     uint8_t *p_pic;
1041
1042                     x= s->mb_x*16;
1043                     y= s->mb_y*16;
1044                     if(x+16 > s->width)  x= s->width-16;
1045                     if(y+16 > s->height) y= s->height-16;
1046
1047                     offset= x + y*s->linesize;
1048                     p_pic= s->new_picture.data[0] + offset;
1049
1050                     s->mb_skipped=1;
1051                     for(i=0; i<s->max_b_frames; i++){
1052                         uint8_t *b_pic;
1053                         int diff;
1054                         Picture *pic= s->reordered_input_picture[i+1];
1055
1056                         if(pic==NULL || pic->pict_type!=FF_B_TYPE) break;
1057
1058                         b_pic= pic->data[0] + offset;
1059                         if(pic->type != FF_BUFFER_TYPE_SHARED)
1060                             b_pic+= INPLACE_OFFSET;
1061                         diff= s->dsp.sad[0](NULL, p_pic, b_pic, s->linesize, 16);
1062                         if(diff>s->qscale*70){ //FIXME check that 70 is optimal
1063                             s->mb_skipped=0;
1064                             break;
1065                         }
1066                     }
1067                 }else
1068                     s->mb_skipped=1;
1069
1070                 if(s->mb_skipped==1){
1071                     /* skip macroblock */
1072                     put_bits(&s->pb, 1, 1);
1073
1074                     if(interleaved_stats){
1075                         s->misc_bits++;
1076                         s->last_bits++;
1077                     }
1078                     s->skip_count++;
1079
1080                     return;
1081                 }
1082             }
1083
1084             put_bits(&s->pb, 1, 0);     /* mb coded */
1085             cbpc = cbp & 3;
1086             cbpy = cbp >> 2;
1087             cbpy ^= 0xf;
1088             if(s->mv_type==MV_TYPE_16X16){
1089                 if(s->dquant) cbpc+= 8;
1090                 put_bits(&s->pb,
1091                         inter_MCBPC_bits[cbpc],
1092                         inter_MCBPC_code[cbpc]);
1093
1094                 put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1095                 if(s->dquant)
1096                     put_bits(pb2, 2, dquant_code[s->dquant+2]);
1097
1098                 if(!s->progressive_sequence){
1099                     if(cbp)
1100                         put_bits(pb2, 1, s->interlaced_dct);
1101                     put_bits(pb2, 1, 0);
1102                 }
1103
1104                 if(interleaved_stats){
1105                     s->misc_bits+= get_bits_diff(s);
1106                 }
1107
1108                 /* motion vectors: 16x16 mode */
1109                 h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1110
1111                 ff_h263_encode_motion_vector(s, motion_x - pred_x,
1112                                                 motion_y - pred_y, s->f_code);
1113             }else if(s->mv_type==MV_TYPE_FIELD){
1114                 if(s->dquant) cbpc+= 8;
1115                 put_bits(&s->pb,
1116                         inter_MCBPC_bits[cbpc],
1117                         inter_MCBPC_code[cbpc]);
1118
1119                 put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1120                 if(s->dquant)
1121                     put_bits(pb2, 2, dquant_code[s->dquant+2]);
1122
1123                 assert(!s->progressive_sequence);
1124                 if(cbp)
1125                     put_bits(pb2, 1, s->interlaced_dct);
1126                 put_bits(pb2, 1, 1);
1127
1128                 if(interleaved_stats){
1129                     s->misc_bits+= get_bits_diff(s);
1130                 }
1131
1132                 /* motion vectors: 16x8 interlaced mode */
1133                 h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1134                 pred_y /=2;
1135
1136                 put_bits(&s->pb, 1, s->field_select[0][0]);
1137                 put_bits(&s->pb, 1, s->field_select[0][1]);
1138
1139                 ff_h263_encode_motion_vector(s, s->mv[0][0][0] - pred_x,
1140                                                 s->mv[0][0][1] - pred_y, s->f_code);
1141                 ff_h263_encode_motion_vector(s, s->mv[0][1][0] - pred_x,
1142                                                 s->mv[0][1][1] - pred_y, s->f_code);
1143             }else{
1144                 assert(s->mv_type==MV_TYPE_8X8);
1145                 put_bits(&s->pb,
1146                         inter_MCBPC_bits[cbpc+16],
1147                         inter_MCBPC_code[cbpc+16]);
1148                 put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1149
1150                 if(!s->progressive_sequence){
1151                     if(cbp)
1152                         put_bits(pb2, 1, s->interlaced_dct);
1153                 }
1154
1155                 if(interleaved_stats){
1156                     s->misc_bits+= get_bits_diff(s);
1157                 }
1158
1159                 for(i=0; i<4; i++){
1160                     /* motion vectors: 8x8 mode*/
1161                     h263_pred_motion(s, i, 0, &pred_x, &pred_y);
1162
1163                     ff_h263_encode_motion_vector(s, s->current_picture.motion_val[0][ s->block_index[i] ][0] - pred_x,
1164                                                     s->current_picture.motion_val[0][ s->block_index[i] ][1] - pred_y, s->f_code);
1165                 }
1166             }
1167
1168             if(interleaved_stats){
1169                 s->mv_bits+= get_bits_diff(s);
1170             }
1171
1172             mpeg4_encode_blocks(s, block, NULL, NULL, NULL, tex_pb);
1173
1174             if(interleaved_stats){
1175                 s->p_tex_bits+= get_bits_diff(s);
1176             }
1177             s->f_count++;
1178         }
1179     } else {
1180         int cbp;
1181         int dc_diff[6];   //dc values with the dc prediction subtracted
1182         int dir[6];  //prediction direction
1183         int zigzag_last_index[6];
1184         uint8_t *scan_table[6];
1185         int i;
1186
1187         for(i=0; i<6; i++){
1188             dc_diff[i]= ff_mpeg4_pred_dc(s, i, block[i][0], &dir[i], 1);
1189         }
1190
1191         if(s->flags & CODEC_FLAG_AC_PRED){
1192             s->ac_pred= decide_ac_pred(s, block, dir, scan_table, zigzag_last_index);
1193             if(!s->ac_pred)
1194                 restore_ac_coeffs(s, block, dir, scan_table, zigzag_last_index);
1195         }else{
1196             for(i=0; i<6; i++)
1197                 scan_table[i]= s->intra_scantable.permutated;
1198         }
1199
1200         /* compute cbp */
1201         cbp = 0;
1202         for (i = 0; i < 6; i++) {
1203             if (s->block_last_index[i] >= 1)
1204                 cbp |= 1 << (5 - i);
1205         }
1206
1207         cbpc = cbp & 3;
1208         if (s->pict_type == FF_I_TYPE) {
1209             if(s->dquant) cbpc+=4;
1210             put_bits(&s->pb,
1211                 intra_MCBPC_bits[cbpc],
1212                 intra_MCBPC_code[cbpc]);
1213         } else {
1214             if(s->dquant) cbpc+=8;
1215             put_bits(&s->pb, 1, 0);     /* mb coded */
1216             put_bits(&s->pb,
1217                 inter_MCBPC_bits[cbpc + 4],
1218                 inter_MCBPC_code[cbpc + 4]);
1219         }
1220         put_bits(pb2, 1, s->ac_pred);
1221         cbpy = cbp >> 2;
1222         put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1223         if(s->dquant)
1224             put_bits(dc_pb, 2, dquant_code[s->dquant+2]);
1225
1226         if(!s->progressive_sequence){
1227             put_bits(dc_pb, 1, s->interlaced_dct);
1228         }
1229
1230         if(interleaved_stats){
1231             s->misc_bits+= get_bits_diff(s);
1232         }
1233
1234         mpeg4_encode_blocks(s, block, dc_diff, scan_table, dc_pb, tex_pb);
1235
1236         if(interleaved_stats){
1237             s->i_tex_bits+= get_bits_diff(s);
1238         }
1239         s->i_count++;
1240
1241         /* restore ac coeffs & last_index stuff if we messed them up with the prediction */
1242         if(s->ac_pred)
1243             restore_ac_coeffs(s, block, dir, scan_table, zigzag_last_index);
1244     }
1245 }
1246
1247 void h263_encode_mb(MpegEncContext * s,
1248                     DCTELEM block[6][64],
1249                     int motion_x, int motion_y)
1250 {
1251     int cbpc, cbpy, i, cbp, pred_x, pred_y;
1252     int16_t pred_dc;
1253     int16_t rec_intradc[6];
1254     int16_t *dc_ptr[6];
1255     const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1);
1256
1257     if (!s->mb_intra) {
1258         /* compute cbp */
1259         cbp= get_p_cbp(s, block, motion_x, motion_y);
1260
1261         if ((cbp | motion_x | motion_y | s->dquant | (s->mv_type - MV_TYPE_16X16)) == 0) {
1262             /* skip macroblock */
1263             put_bits(&s->pb, 1, 1);
1264             if(interleaved_stats){
1265                 s->misc_bits++;
1266                 s->last_bits++;
1267             }
1268             s->skip_count++;
1269
1270             return;
1271         }
1272         put_bits(&s->pb, 1, 0);         /* mb coded */
1273
1274         cbpc = cbp & 3;
1275         cbpy = cbp >> 2;
1276         if(s->alt_inter_vlc==0 || cbpc!=3)
1277             cbpy ^= 0xF;
1278         if(s->dquant) cbpc+= 8;
1279         if(s->mv_type==MV_TYPE_16X16){
1280             put_bits(&s->pb,
1281                     inter_MCBPC_bits[cbpc],
1282                     inter_MCBPC_code[cbpc]);
1283
1284             put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1285             if(s->dquant)
1286                 put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
1287
1288             if(interleaved_stats){
1289                 s->misc_bits+= get_bits_diff(s);
1290             }
1291
1292             /* motion vectors: 16x16 mode */
1293             h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1294
1295             if (!s->umvplus) {
1296                 ff_h263_encode_motion_vector(s, motion_x - pred_x,
1297                                                 motion_y - pred_y, 1);
1298             }
1299             else {
1300                 h263p_encode_umotion(s, motion_x - pred_x);
1301                 h263p_encode_umotion(s, motion_y - pred_y);
1302                 if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
1303                     /* To prevent Start Code emulation */
1304                     put_bits(&s->pb,1,1);
1305             }
1306         }else{
1307             put_bits(&s->pb,
1308                     inter_MCBPC_bits[cbpc+16],
1309                     inter_MCBPC_code[cbpc+16]);
1310             put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1311             if(s->dquant)
1312                 put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
1313
1314             if(interleaved_stats){
1315                 s->misc_bits+= get_bits_diff(s);
1316             }
1317
1318             for(i=0; i<4; i++){
1319                 /* motion vectors: 8x8 mode*/
1320                 h263_pred_motion(s, i, 0, &pred_x, &pred_y);
1321
1322                 motion_x= s->current_picture.motion_val[0][ s->block_index[i] ][0];
1323                 motion_y= s->current_picture.motion_val[0][ s->block_index[i] ][1];
1324                 if (!s->umvplus) {
1325                     ff_h263_encode_motion_vector(s, motion_x - pred_x,
1326                                                     motion_y - pred_y, 1);
1327                 }
1328                 else {
1329                     h263p_encode_umotion(s, motion_x - pred_x);
1330                     h263p_encode_umotion(s, motion_y - pred_y);
1331                     if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
1332                         /* To prevent Start Code emulation */
1333                         put_bits(&s->pb,1,1);
1334                 }
1335             }
1336         }
1337
1338         if(interleaved_stats){
1339             s->mv_bits+= get_bits_diff(s);
1340         }
1341     } else {
1342         assert(s->mb_intra);
1343
1344         cbp = 0;
1345         if (s->h263_aic) {
1346             /* Predict DC */
1347             for(i=0; i<6; i++) {
1348                 int16_t level = block[i][0];
1349                 int scale;
1350
1351                 if(i<4) scale= s->y_dc_scale;
1352                 else    scale= s->c_dc_scale;
1353
1354                 pred_dc = h263_pred_dc(s, i, &dc_ptr[i]);
1355                 level -= pred_dc;
1356                 /* Quant */
1357                 if (level >= 0)
1358                     level = (level + (scale>>1))/scale;
1359                 else
1360                     level = (level - (scale>>1))/scale;
1361
1362                 /* AIC can change CBP */
1363                 if (level == 0 && s->block_last_index[i] == 0)
1364                     s->block_last_index[i] = -1;
1365
1366                 if(!s->modified_quant){
1367                     if (level < -127)
1368                         level = -127;
1369                     else if (level > 127)
1370                         level = 127;
1371                 }
1372
1373                 block[i][0] = level;
1374                 /* Reconstruction */
1375                 rec_intradc[i] = scale*level + pred_dc;
1376                 /* Oddify */
1377                 rec_intradc[i] |= 1;
1378                 //if ((rec_intradc[i] % 2) == 0)
1379                 //    rec_intradc[i]++;
1380                 /* Clipping */
1381                 if (rec_intradc[i] < 0)
1382                     rec_intradc[i] = 0;
1383                 else if (rec_intradc[i] > 2047)
1384                     rec_intradc[i] = 2047;
1385
1386                 /* Update AC/DC tables */
1387                 *dc_ptr[i] = rec_intradc[i];
1388                 if (s->block_last_index[i] >= 0)
1389                     cbp |= 1 << (5 - i);
1390             }
1391         }else{
1392             for(i=0; i<6; i++) {
1393                 /* compute cbp */
1394                 if (s->block_last_index[i] >= 1)
1395                     cbp |= 1 << (5 - i);
1396             }
1397         }
1398
1399         cbpc = cbp & 3;
1400         if (s->pict_type == FF_I_TYPE) {
1401             if(s->dquant) cbpc+=4;
1402             put_bits(&s->pb,
1403                 intra_MCBPC_bits[cbpc],
1404                 intra_MCBPC_code[cbpc]);
1405         } else {
1406             if(s->dquant) cbpc+=8;
1407             put_bits(&s->pb, 1, 0);     /* mb coded */
1408             put_bits(&s->pb,
1409                 inter_MCBPC_bits[cbpc + 4],
1410                 inter_MCBPC_code[cbpc + 4]);
1411         }
1412         if (s->h263_aic) {
1413             /* XXX: currently, we do not try to use ac prediction */
1414             put_bits(&s->pb, 1, 0);     /* no AC prediction */
1415         }
1416         cbpy = cbp >> 2;
1417         put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1418         if(s->dquant)
1419             put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
1420
1421         if(interleaved_stats){
1422             s->misc_bits+= get_bits_diff(s);
1423         }
1424     }
1425
1426     for(i=0; i<6; i++) {
1427         /* encode each block */
1428         h263_encode_block(s, block[i], i);
1429
1430         /* Update INTRADC for decoding */
1431         if (s->h263_aic && s->mb_intra) {
1432             block[i][0] = rec_intradc[i];
1433
1434         }
1435     }
1436
1437     if(interleaved_stats){
1438         if (!s->mb_intra) {
1439             s->p_tex_bits+= get_bits_diff(s);
1440             s->f_count++;
1441         }else{
1442             s->i_tex_bits+= get_bits_diff(s);
1443             s->i_count++;
1444         }
1445     }
1446 }
1447 #endif
1448
1449 void ff_h263_loop_filter(MpegEncContext * s){
1450     int qp_c;
1451     const int linesize  = s->linesize;
1452     const int uvlinesize= s->uvlinesize;
1453     const int xy = s->mb_y * s->mb_stride + s->mb_x;
1454     uint8_t *dest_y = s->dest[0];
1455     uint8_t *dest_cb= s->dest[1];
1456     uint8_t *dest_cr= s->dest[2];
1457
1458 //    if(s->pict_type==FF_B_TYPE && !s->readable) return;
1459
1460     /*
1461        Diag Top
1462        Left Center
1463     */
1464     if(!IS_SKIP(s->current_picture.mb_type[xy])){
1465         qp_c= s->qscale;
1466         s->dsp.h263_v_loop_filter(dest_y+8*linesize  , linesize, qp_c);
1467         s->dsp.h263_v_loop_filter(dest_y+8*linesize+8, linesize, qp_c);
1468     }else
1469         qp_c= 0;
1470
1471     if(s->mb_y){
1472         int qp_dt, qp_tt, qp_tc;
1473
1474         if(IS_SKIP(s->current_picture.mb_type[xy-s->mb_stride]))
1475             qp_tt=0;
1476         else
1477             qp_tt= s->current_picture.qscale_table[xy-s->mb_stride];
1478
1479         if(qp_c)
1480             qp_tc= qp_c;
1481         else
1482             qp_tc= qp_tt;
1483
1484         if(qp_tc){
1485             const int chroma_qp= s->chroma_qscale_table[qp_tc];
1486             s->dsp.h263_v_loop_filter(dest_y  ,   linesize, qp_tc);
1487             s->dsp.h263_v_loop_filter(dest_y+8,   linesize, qp_tc);
1488
1489             s->dsp.h263_v_loop_filter(dest_cb , uvlinesize, chroma_qp);
1490             s->dsp.h263_v_loop_filter(dest_cr , uvlinesize, chroma_qp);
1491         }
1492
1493         if(qp_tt)
1494             s->dsp.h263_h_loop_filter(dest_y-8*linesize+8  ,   linesize, qp_tt);
1495
1496         if(s->mb_x){
1497             if(qp_tt || IS_SKIP(s->current_picture.mb_type[xy-1-s->mb_stride]))
1498                 qp_dt= qp_tt;
1499             else
1500                 qp_dt= s->current_picture.qscale_table[xy-1-s->mb_stride];
1501
1502             if(qp_dt){
1503                 const int chroma_qp= s->chroma_qscale_table[qp_dt];
1504                 s->dsp.h263_h_loop_filter(dest_y -8*linesize  ,   linesize, qp_dt);
1505                 s->dsp.h263_h_loop_filter(dest_cb-8*uvlinesize, uvlinesize, chroma_qp);
1506                 s->dsp.h263_h_loop_filter(dest_cr-8*uvlinesize, uvlinesize, chroma_qp);
1507             }
1508         }
1509     }
1510
1511     if(qp_c){
1512         s->dsp.h263_h_loop_filter(dest_y +8,   linesize, qp_c);
1513         if(s->mb_y + 1 == s->mb_height)
1514             s->dsp.h263_h_loop_filter(dest_y+8*linesize+8,   linesize, qp_c);
1515     }
1516
1517     if(s->mb_x){
1518         int qp_lc;
1519         if(qp_c || IS_SKIP(s->current_picture.mb_type[xy-1]))
1520             qp_lc= qp_c;
1521         else
1522             qp_lc= s->current_picture.qscale_table[xy-1];
1523
1524         if(qp_lc){
1525             s->dsp.h263_h_loop_filter(dest_y,   linesize, qp_lc);
1526             if(s->mb_y + 1 == s->mb_height){
1527                 const int chroma_qp= s->chroma_qscale_table[qp_lc];
1528                 s->dsp.h263_h_loop_filter(dest_y +8*  linesize,   linesize, qp_lc);
1529                 s->dsp.h263_h_loop_filter(dest_cb             , uvlinesize, chroma_qp);
1530                 s->dsp.h263_h_loop_filter(dest_cr             , uvlinesize, chroma_qp);
1531             }
1532         }
1533     }
1534 }
1535
1536 #if CONFIG_ENCODERS
1537 static int h263_pred_dc(MpegEncContext * s, int n, int16_t **dc_val_ptr)
1538 {
1539     int x, y, wrap, a, c, pred_dc;
1540     int16_t *dc_val;
1541
1542     /* find prediction */
1543     if (n < 4) {
1544         x = 2 * s->mb_x + (n & 1);
1545         y = 2 * s->mb_y + ((n & 2) >> 1);
1546         wrap = s->b8_stride;
1547         dc_val = s->dc_val[0];
1548     } else {
1549         x = s->mb_x;
1550         y = s->mb_y;
1551         wrap = s->mb_stride;
1552         dc_val = s->dc_val[n - 4 + 1];
1553     }
1554     /* B C
1555      * A X
1556      */
1557     a = dc_val[(x - 1) + (y) * wrap];
1558     c = dc_val[(x) + (y - 1) * wrap];
1559
1560     /* No prediction outside GOB boundary */
1561     if(s->first_slice_line && n!=3){
1562         if(n!=2) c= 1024;
1563         if(n!=1 && s->mb_x == s->resync_mb_x) a= 1024;
1564     }
1565     /* just DC prediction */
1566     if (a != 1024 && c != 1024)
1567         pred_dc = (a + c) >> 1;
1568     else if (a != 1024)
1569         pred_dc = a;
1570     else
1571         pred_dc = c;
1572
1573     /* we assume pred is positive */
1574     *dc_val_ptr = &dc_val[x + y * wrap];
1575     return pred_dc;
1576 }
1577 #endif /* CONFIG_ENCODERS */
1578
1579 static void h263_pred_acdc(MpegEncContext * s, DCTELEM *block, int n)
1580 {
1581     int x, y, wrap, a, c, pred_dc, scale, i;
1582     int16_t *dc_val, *ac_val, *ac_val1;
1583
1584     /* find prediction */
1585     if (n < 4) {
1586         x = 2 * s->mb_x + (n & 1);
1587         y = 2 * s->mb_y + (n>> 1);
1588         wrap = s->b8_stride;
1589         dc_val = s->dc_val[0];
1590         ac_val = s->ac_val[0][0];
1591         scale = s->y_dc_scale;
1592     } else {
1593         x = s->mb_x;
1594         y = s->mb_y;
1595         wrap = s->mb_stride;
1596         dc_val = s->dc_val[n - 4 + 1];
1597         ac_val = s->ac_val[n - 4 + 1][0];
1598         scale = s->c_dc_scale;
1599     }
1600
1601     ac_val += ((y) * wrap + (x)) * 16;
1602     ac_val1 = ac_val;
1603
1604     /* B C
1605      * A X
1606      */
1607     a = dc_val[(x - 1) + (y) * wrap];
1608     c = dc_val[(x) + (y - 1) * wrap];
1609
1610     /* No prediction outside GOB boundary */
1611     if(s->first_slice_line && n!=3){
1612         if(n!=2) c= 1024;
1613         if(n!=1 && s->mb_x == s->resync_mb_x) a= 1024;
1614     }
1615
1616     if (s->ac_pred) {
1617         pred_dc = 1024;
1618         if (s->h263_aic_dir) {
1619             /* left prediction */
1620             if (a != 1024) {
1621                 ac_val -= 16;
1622                 for(i=1;i<8;i++) {
1623                     block[s->dsp.idct_permutation[i<<3]] += ac_val[i];
1624                 }
1625                 pred_dc = a;
1626             }
1627         } else {
1628             /* top prediction */
1629             if (c != 1024) {
1630                 ac_val -= 16 * wrap;
1631                 for(i=1;i<8;i++) {
1632                     block[s->dsp.idct_permutation[i   ]] += ac_val[i + 8];
1633                 }
1634                 pred_dc = c;
1635             }
1636         }
1637     } else {
1638         /* just DC prediction */
1639         if (a != 1024 && c != 1024)
1640             pred_dc = (a + c) >> 1;
1641         else if (a != 1024)
1642             pred_dc = a;
1643         else
1644             pred_dc = c;
1645     }
1646
1647     /* we assume pred is positive */
1648     block[0]=block[0]*scale + pred_dc;
1649
1650     if (block[0] < 0)
1651         block[0] = 0;
1652     else
1653         block[0] |= 1;
1654
1655     /* Update AC/DC tables */
1656     dc_val[(x) + (y) * wrap] = block[0];
1657
1658     /* left copy */
1659     for(i=1;i<8;i++)
1660         ac_val1[i    ] = block[s->dsp.idct_permutation[i<<3]];
1661     /* top copy */
1662     for(i=1;i<8;i++)
1663         ac_val1[8 + i] = block[s->dsp.idct_permutation[i   ]];
1664 }
1665
1666 int16_t *h263_pred_motion(MpegEncContext * s, int block, int dir,
1667                         int *px, int *py)
1668 {
1669     int wrap;
1670     int16_t *A, *B, *C, (*mot_val)[2];
1671     static const int off[4]= {2, 1, 1, -1};
1672
1673     wrap = s->b8_stride;
1674     mot_val = s->current_picture.motion_val[dir] + s->block_index[block];
1675
1676     A = mot_val[ - 1];
1677     /* special case for first (slice) line */
1678     if (s->first_slice_line && block<3) {
1679         // we can't just change some MVs to simulate that as we need them for the B frames (and ME)
1680         // and if we ever support non rectangular objects than we need to do a few ifs here anyway :(
1681         if(block==0){ //most common case
1682             if(s->mb_x  == s->resync_mb_x){ //rare
1683                 *px= *py = 0;
1684             }else if(s->mb_x + 1 == s->resync_mb_x && s->h263_pred){ //rare
1685                 C = mot_val[off[block] - wrap];
1686                 if(s->mb_x==0){
1687                     *px = C[0];
1688                     *py = C[1];
1689                 }else{
1690                     *px = mid_pred(A[0], 0, C[0]);
1691                     *py = mid_pred(A[1], 0, C[1]);
1692                 }
1693             }else{
1694                 *px = A[0];
1695                 *py = A[1];
1696             }
1697         }else if(block==1){
1698             if(s->mb_x + 1 == s->resync_mb_x && s->h263_pred){ //rare
1699                 C = mot_val[off[block] - wrap];
1700                 *px = mid_pred(A[0], 0, C[0]);
1701                 *py = mid_pred(A[1], 0, C[1]);
1702             }else{
1703                 *px = A[0];
1704                 *py = A[1];
1705             }
1706         }else{ /* block==2*/
1707             B = mot_val[ - wrap];
1708             C = mot_val[off[block] - wrap];
1709             if(s->mb_x == s->resync_mb_x) //rare
1710                 A[0]=A[1]=0;
1711
1712             *px = mid_pred(A[0], B[0], C[0]);
1713             *py = mid_pred(A[1], B[1], C[1]);
1714         }
1715     } else {
1716         B = mot_val[ - wrap];
1717         C = mot_val[off[block] - wrap];
1718         *px = mid_pred(A[0], B[0], C[0]);
1719         *py = mid_pred(A[1], B[1], C[1]);
1720     }
1721     return *mot_val;
1722 }
1723
1724 #if CONFIG_ENCODERS
1725 void ff_h263_encode_motion(MpegEncContext * s, int val, int f_code)
1726 {
1727     int range, l, bit_size, sign, code, bits;
1728
1729     if (val == 0) {
1730         /* zero vector */
1731         code = 0;
1732         put_bits(&s->pb, mvtab[code][1], mvtab[code][0]);
1733     } else {
1734         bit_size = f_code - 1;
1735         range = 1 << bit_size;
1736         /* modulo encoding */
1737         l= INT_BIT - 6 - bit_size;
1738         val = (val<<l)>>l;
1739         sign = val>>31;
1740         val= (val^sign)-sign;
1741         sign&=1;
1742
1743         val--;
1744         code = (val >> bit_size) + 1;
1745         bits = val & (range - 1);
1746
1747         put_bits(&s->pb, mvtab[code][1] + 1, (mvtab[code][0] << 1) | sign);
1748         if (bit_size > 0) {
1749             put_bits(&s->pb, bit_size, bits);
1750         }
1751     }
1752 }
1753
1754 /* Encode MV differences on H.263+ with Unrestricted MV mode */
1755 static void h263p_encode_umotion(MpegEncContext * s, int val)
1756 {
1757     short sval = 0;
1758     short i = 0;
1759     short n_bits = 0;
1760     short temp_val;
1761     int code = 0;
1762     int tcode;
1763
1764     if ( val == 0)
1765         put_bits(&s->pb, 1, 1);
1766     else if (val == 1)
1767         put_bits(&s->pb, 3, 0);
1768     else if (val == -1)
1769         put_bits(&s->pb, 3, 2);
1770     else {
1771
1772         sval = ((val < 0) ? (short)(-val):(short)val);
1773         temp_val = sval;
1774
1775         while (temp_val != 0) {
1776             temp_val = temp_val >> 1;
1777             n_bits++;
1778         }
1779
1780         i = n_bits - 1;
1781         while (i > 0) {
1782             tcode = (sval & (1 << (i-1))) >> (i-1);
1783             tcode = (tcode << 1) | 1;
1784             code = (code << 2) | tcode;
1785             i--;
1786         }
1787         code = ((code << 1) | (val < 0)) << 1;
1788         put_bits(&s->pb, (2*n_bits)+1, code);
1789     }
1790 }
1791
1792 static void init_mv_penalty_and_fcode(MpegEncContext *s)
1793 {
1794     int f_code;
1795     int mv;
1796
1797     for(f_code=1; f_code<=MAX_FCODE; f_code++){
1798         for(mv=-MAX_MV; mv<=MAX_MV; mv++){
1799             int len;
1800
1801             if(mv==0) len= mvtab[0][1];
1802             else{
1803                 int val, bit_size, code;
1804
1805                 bit_size = f_code - 1;
1806
1807                 val=mv;
1808                 if (val < 0)
1809                     val = -val;
1810                 val--;
1811                 code = (val >> bit_size) + 1;
1812                 if(code<33){
1813                     len= mvtab[code][1] + 1 + bit_size;
1814                 }else{
1815                     len= mvtab[32][1] + av_log2(code>>5) + 2 + bit_size;
1816                 }
1817             }
1818
1819             mv_penalty[f_code][mv+MAX_MV]= len;
1820         }
1821     }
1822
1823     for(f_code=MAX_FCODE; f_code>0; f_code--){
1824         for(mv=-(16<<f_code); mv<(16<<f_code); mv++){
1825             fcode_tab[mv+MAX_MV]= f_code;
1826         }
1827     }
1828
1829     for(mv=0; mv<MAX_MV*2+1; mv++){
1830         umv_fcode_tab[mv]= 1;
1831     }
1832 }
1833
1834 static void init_uni_dc_tab(void)
1835 {
1836     int level, uni_code, uni_len;
1837
1838     for(level=-256; level<256; level++){
1839         int size, v, l;
1840         /* find number of bits */
1841         size = 0;
1842         v = abs(level);
1843         while (v) {
1844             v >>= 1;
1845             size++;
1846         }
1847
1848         if (level < 0)
1849             l= (-level) ^ ((1 << size) - 1);
1850         else
1851             l= level;
1852
1853         /* luminance */
1854         uni_code= DCtab_lum[size][0];
1855         uni_len = DCtab_lum[size][1];
1856
1857         if (size > 0) {
1858             uni_code<<=size; uni_code|=l;
1859             uni_len+=size;
1860             if (size > 8){
1861                 uni_code<<=1; uni_code|=1;
1862                 uni_len++;
1863             }
1864         }
1865         uni_DCtab_lum_bits[level+256]= uni_code;
1866         uni_DCtab_lum_len [level+256]= uni_len;
1867
1868         /* chrominance */
1869         uni_code= DCtab_chrom[size][0];
1870         uni_len = DCtab_chrom[size][1];
1871
1872         if (size > 0) {
1873             uni_code<<=size; uni_code|=l;
1874             uni_len+=size;
1875             if (size > 8){
1876                 uni_code<<=1; uni_code|=1;
1877                 uni_len++;
1878             }
1879         }
1880         uni_DCtab_chrom_bits[level+256]= uni_code;
1881         uni_DCtab_chrom_len [level+256]= uni_len;
1882
1883     }
1884 }
1885
1886 static void init_uni_mpeg4_rl_tab(RLTable *rl, uint32_t *bits_tab, uint8_t *len_tab){
1887     int slevel, run, last;
1888
1889     assert(MAX_LEVEL >= 64);
1890     assert(MAX_RUN   >= 63);
1891
1892     for(slevel=-64; slevel<64; slevel++){
1893         if(slevel==0) continue;
1894         for(run=0; run<64; run++){
1895             for(last=0; last<=1; last++){
1896                 const int index= UNI_MPEG4_ENC_INDEX(last, run, slevel+64);
1897                 int level= slevel < 0 ? -slevel : slevel;
1898                 int sign= slevel < 0 ? 1 : 0;
1899                 int bits, len, code;
1900                 int level1, run1;
1901
1902                 len_tab[index]= 100;
1903
1904                 /* ESC0 */
1905                 code= get_rl_index(rl, last, run, level);
1906                 bits= rl->table_vlc[code][0];
1907                 len=  rl->table_vlc[code][1];
1908                 bits=bits*2+sign; len++;
1909
1910                 if(code!=rl->n && len < len_tab[index]){
1911                     bits_tab[index]= bits;
1912                     len_tab [index]= len;
1913                 }
1914                 /* ESC1 */
1915                 bits= rl->table_vlc[rl->n][0];
1916                 len=  rl->table_vlc[rl->n][1];
1917                 bits=bits*2;    len++; //esc1
1918                 level1= level - rl->max_level[last][run];
1919                 if(level1>0){
1920                     code= get_rl_index(rl, last, run, level1);
1921                     bits<<= rl->table_vlc[code][1];
1922                     len  += rl->table_vlc[code][1];
1923                     bits += rl->table_vlc[code][0];
1924                     bits=bits*2+sign; len++;
1925
1926                     if(code!=rl->n && len < len_tab[index]){
1927                         bits_tab[index]= bits;
1928                         len_tab [index]= len;
1929                     }
1930                 }
1931                 /* ESC2 */
1932                 bits= rl->table_vlc[rl->n][0];
1933                 len=  rl->table_vlc[rl->n][1];
1934                 bits=bits*4+2;    len+=2; //esc2
1935                 run1 = run - rl->max_run[last][level] - 1;
1936                 if(run1>=0){
1937                     code= get_rl_index(rl, last, run1, level);
1938                     bits<<= rl->table_vlc[code][1];
1939                     len  += rl->table_vlc[code][1];
1940                     bits += rl->table_vlc[code][0];
1941                     bits=bits*2+sign; len++;
1942
1943                     if(code!=rl->n && len < len_tab[index]){
1944                         bits_tab[index]= bits;
1945                         len_tab [index]= len;
1946                     }
1947                 }
1948                 /* ESC3 */
1949                 bits= rl->table_vlc[rl->n][0];
1950                 len = rl->table_vlc[rl->n][1];
1951                 bits=bits*4+3;    len+=2; //esc3
1952                 bits=bits*2+last; len++;
1953                 bits=bits*64+run; len+=6;
1954                 bits=bits*2+1;    len++;  //marker
1955                 bits=bits*4096+(slevel&0xfff); len+=12;
1956                 bits=bits*2+1;    len++;  //marker
1957
1958                 if(len < len_tab[index]){
1959                     bits_tab[index]= bits;
1960                     len_tab [index]= len;
1961                 }
1962             }
1963         }
1964     }
1965 }
1966
1967 static void init_uni_h263_rl_tab(RLTable *rl, uint32_t *bits_tab, uint8_t *len_tab){
1968     int slevel, run, last;
1969
1970     assert(MAX_LEVEL >= 64);
1971     assert(MAX_RUN   >= 63);
1972
1973     for(slevel=-64; slevel<64; slevel++){
1974         if(slevel==0) continue;
1975         for(run=0; run<64; run++){
1976             for(last=0; last<=1; last++){
1977                 const int index= UNI_MPEG4_ENC_INDEX(last, run, slevel+64);
1978                 int level= slevel < 0 ? -slevel : slevel;
1979                 int sign= slevel < 0 ? 1 : 0;
1980                 int bits, len, code;
1981
1982                 len_tab[index]= 100;
1983
1984                 /* ESC0 */
1985                 code= get_rl_index(rl, last, run, level);
1986                 bits= rl->table_vlc[code][0];
1987                 len=  rl->table_vlc[code][1];
1988                 bits=bits*2+sign; len++;
1989
1990                 if(code!=rl->n && len < len_tab[index]){
1991                     if(bits_tab) bits_tab[index]= bits;
1992                     len_tab [index]= len;
1993                 }
1994                 /* ESC */
1995                 bits= rl->table_vlc[rl->n][0];
1996                 len = rl->table_vlc[rl->n][1];
1997                 bits=bits*2+last; len++;
1998                 bits=bits*64+run; len+=6;
1999                 bits=bits*256+(level&0xff); len+=8;
2000
2001                 if(len < len_tab[index]){
2002                     if(bits_tab) bits_tab[index]= bits;
2003                     len_tab [index]= len;
2004                 }
2005             }
2006         }
2007     }
2008 }
2009
2010 void h263_encode_init(MpegEncContext *s)
2011 {
2012     static int done = 0;
2013
2014     if (!done) {
2015         done = 1;
2016
2017         init_uni_dc_tab();
2018
2019         init_rl(&rl_inter, static_rl_table_store[0]);
2020         init_rl(&rl_intra, static_rl_table_store[1]);
2021         init_rl(&rl_intra_aic, static_rl_table_store[2]);
2022
2023         init_uni_mpeg4_rl_tab(&rl_intra, uni_mpeg4_intra_rl_bits, uni_mpeg4_intra_rl_len);
2024         init_uni_mpeg4_rl_tab(&rl_inter, uni_mpeg4_inter_rl_bits, uni_mpeg4_inter_rl_len);
2025
2026         init_uni_h263_rl_tab(&rl_intra_aic, NULL, uni_h263_intra_aic_rl_len);
2027         init_uni_h263_rl_tab(&rl_inter    , NULL, uni_h263_inter_rl_len);
2028
2029         init_mv_penalty_and_fcode(s);
2030     }
2031     s->me.mv_penalty= mv_penalty; //FIXME exact table for msmpeg4 & h263p
2032
2033     s->intra_ac_vlc_length     =s->inter_ac_vlc_length     = uni_h263_inter_rl_len;
2034     s->intra_ac_vlc_last_length=s->inter_ac_vlc_last_length= uni_h263_inter_rl_len + 128*64;
2035     if(s->h263_aic){
2036         s->intra_ac_vlc_length     = uni_h263_intra_aic_rl_len;
2037         s->intra_ac_vlc_last_length= uni_h263_intra_aic_rl_len + 128*64;
2038     }
2039     s->ac_esc_length= 7+1+6+8;
2040
2041     // use fcodes >1 only for mpeg4 & h263 & h263p FIXME
2042     switch(s->codec_id){
2043     case CODEC_ID_MPEG4:
2044         s->fcode_tab= fcode_tab;
2045         s->min_qcoeff= -2048;
2046         s->max_qcoeff=  2047;
2047         s->intra_ac_vlc_length     = uni_mpeg4_intra_rl_len;
2048         s->intra_ac_vlc_last_length= uni_mpeg4_intra_rl_len + 128*64;
2049         s->inter_ac_vlc_length     = uni_mpeg4_inter_rl_len;
2050         s->inter_ac_vlc_last_length= uni_mpeg4_inter_rl_len + 128*64;
2051         s->luma_dc_vlc_length= uni_DCtab_lum_len;
2052         s->chroma_dc_vlc_length= uni_DCtab_chrom_len;
2053         s->ac_esc_length= 7+2+1+6+1+12+1;
2054         s->y_dc_scale_table= ff_mpeg4_y_dc_scale_table;
2055         s->c_dc_scale_table= ff_mpeg4_c_dc_scale_table;
2056
2057         if(s->flags & CODEC_FLAG_GLOBAL_HEADER){
2058
2059             s->avctx->extradata= av_malloc(1024);
2060             init_put_bits(&s->pb, s->avctx->extradata, 1024);
2061
2062             if(!(s->workaround_bugs & FF_BUG_MS))
2063                 mpeg4_encode_visual_object_header(s);
2064             mpeg4_encode_vol_header(s, 0, 0);
2065
2066 //            ff_mpeg4_stuffing(&s->pb); ?
2067             flush_put_bits(&s->pb);
2068             s->avctx->extradata_size= (put_bits_count(&s->pb)+7)>>3;
2069         }
2070
2071         break;
2072     case CODEC_ID_H263P:
2073         if(s->umvplus)
2074             s->fcode_tab= umv_fcode_tab;
2075         if(s->modified_quant){
2076             s->min_qcoeff= -2047;
2077             s->max_qcoeff=  2047;
2078         }else{
2079             s->min_qcoeff= -127;
2080             s->max_qcoeff=  127;
2081         }
2082         break;
2083         //Note for mpeg4 & h263 the dc-scale table will be set per frame as needed later
2084     case CODEC_ID_FLV1:
2085         if (s->h263_flv > 1) {
2086             s->min_qcoeff= -1023;
2087             s->max_qcoeff=  1023;
2088         } else {
2089             s->min_qcoeff= -127;
2090             s->max_qcoeff=  127;
2091         }
2092         s->y_dc_scale_table=
2093         s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
2094         break;
2095     default: //nothing needed - default table already set in mpegvideo.c
2096         s->min_qcoeff= -127;
2097         s->max_qcoeff=  127;
2098         s->y_dc_scale_table=
2099         s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
2100     }
2101 }
2102
2103 /**
2104  * encodes a 8x8 block.
2105  * @param block the 8x8 block
2106  * @param n block index (0-3 are luma, 4-5 are chroma)
2107  */
2108 static void h263_encode_block(MpegEncContext * s, DCTELEM * block, int n)
2109 {
2110     int level, run, last, i, j, last_index, last_non_zero, sign, slevel, code;
2111     RLTable *rl;
2112
2113     rl = &rl_inter;
2114     if (s->mb_intra && !s->h263_aic) {
2115         /* DC coef */
2116         level = block[0];
2117         /* 255 cannot be represented, so we clamp */
2118         if (level > 254) {
2119             level = 254;
2120             block[0] = 254;
2121         }
2122         /* 0 cannot be represented also */
2123         else if (level < 1) {
2124             level = 1;
2125             block[0] = 1;
2126         }
2127         if (level == 128) //FIXME check rv10
2128             put_bits(&s->pb, 8, 0xff);
2129         else
2130             put_bits(&s->pb, 8, level);
2131         i = 1;
2132     } else {
2133         i = 0;
2134         if (s->h263_aic && s->mb_intra)
2135             rl = &rl_intra_aic;
2136
2137         if(s->alt_inter_vlc && !s->mb_intra){
2138             int aic_vlc_bits=0;
2139             int inter_vlc_bits=0;
2140             int wrong_pos=-1;
2141             int aic_code;
2142
2143             last_index = s->block_last_index[n];
2144             last_non_zero = i - 1;
2145             for (; i <= last_index; i++) {
2146                 j = s->intra_scantable.permutated[i];
2147                 level = block[j];
2148                 if (level) {
2149                     run = i - last_non_zero - 1;
2150                     last = (i == last_index);
2151
2152                     if(level<0) level= -level;
2153
2154                     code = get_rl_index(rl, last, run, level);
2155                     aic_code = get_rl_index(&rl_intra_aic, last, run, level);
2156                     inter_vlc_bits += rl->table_vlc[code][1]+1;
2157                     aic_vlc_bits   += rl_intra_aic.table_vlc[aic_code][1]+1;
2158
2159                     if (code == rl->n) {
2160                         inter_vlc_bits += 1+6+8-1;
2161                     }
2162                     if (aic_code == rl_intra_aic.n) {
2163                         aic_vlc_bits += 1+6+8-1;
2164                         wrong_pos += run + 1;
2165                     }else
2166                         wrong_pos += wrong_run[aic_code];
2167                     last_non_zero = i;
2168                 }
2169             }
2170             i = 0;
2171             if(aic_vlc_bits < inter_vlc_bits && wrong_pos > 63)
2172                 rl = &rl_intra_aic;
2173         }
2174     }
2175
2176     /* AC coefs */
2177     last_index = s->block_last_index[n];
2178     last_non_zero = i - 1;
2179     for (; i <= last_index; i++) {
2180         j = s->intra_scantable.permutated[i];
2181         level = block[j];
2182         if (level) {
2183             run = i - last_non_zero - 1;
2184             last = (i == last_index);
2185             sign = 0;
2186             slevel = level;
2187             if (level < 0) {
2188                 sign = 1;
2189                 level = -level;
2190             }
2191             code = get_rl_index(rl, last, run, level);
2192             put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2193             if (code == rl->n) {
2194               if(s->h263_flv <= 1){
2195                 put_bits(&s->pb, 1, last);
2196                 put_bits(&s->pb, 6, run);
2197
2198                 assert(slevel != 0);
2199
2200                 if(level < 128)
2201                     put_sbits(&s->pb, 8, slevel);
2202                 else{
2203                     put_bits(&s->pb, 8, 128);
2204                     put_sbits(&s->pb, 5, slevel);
2205                     put_sbits(&s->pb, 6, slevel>>5);
2206                 }
2207               }else{
2208                 if(level < 64) { // 7-bit level
2209                         put_bits(&s->pb, 1, 0);
2210                         put_bits(&s->pb, 1, last);
2211                         put_bits(&s->pb, 6, run);
2212
2213                         put_sbits(&s->pb, 7, slevel);
2214                     } else {
2215                         /* 11-bit level */
2216                         put_bits(&s->pb, 1, 1);
2217                         put_bits(&s->pb, 1, last);
2218                         put_bits(&s->pb, 6, run);
2219
2220                         put_sbits(&s->pb, 11, slevel);
2221                     }
2222               }
2223             } else {
2224                 put_bits(&s->pb, 1, sign);
2225             }
2226             last_non_zero = i;
2227         }
2228     }
2229 }
2230
2231 /***************************************************/
2232 /**
2233  * add mpeg4 stuffing bits (01...1)
2234  */
2235 void ff_mpeg4_stuffing(PutBitContext * pbc)
2236 {
2237     int length;
2238     put_bits(pbc, 1, 0);
2239     length= (-put_bits_count(pbc))&7;
2240     if(length) put_bits(pbc, length, (1<<length)-1);
2241 }
2242
2243 /* must be called before writing the header */
2244 void ff_set_mpeg4_time(MpegEncContext * s){
2245     if(s->pict_type==FF_B_TYPE){
2246         ff_mpeg4_init_direct_mv(s);
2247     }else{
2248         s->last_time_base= s->time_base;
2249         s->time_base= s->time/s->avctx->time_base.den;
2250     }
2251 }
2252
2253 static void mpeg4_encode_gop_header(MpegEncContext * s){
2254     int hours, minutes, seconds;
2255     int64_t time;
2256
2257     put_bits(&s->pb, 16, 0);
2258     put_bits(&s->pb, 16, GOP_STARTCODE);
2259
2260     time= s->current_picture_ptr->pts;
2261     if(s->reordered_input_picture[1])
2262         time= FFMIN(time, s->reordered_input_picture[1]->pts);
2263     time= time*s->avctx->time_base.num;
2264
2265     seconds= time/s->avctx->time_base.den;
2266     minutes= seconds/60; seconds %= 60;
2267     hours= minutes/60; minutes %= 60;
2268     hours%=24;
2269
2270     put_bits(&s->pb, 5, hours);
2271     put_bits(&s->pb, 6, minutes);
2272     put_bits(&s->pb, 1, 1);
2273     put_bits(&s->pb, 6, seconds);
2274
2275     put_bits(&s->pb, 1, !!(s->flags&CODEC_FLAG_CLOSED_GOP));
2276     put_bits(&s->pb, 1, 0); //broken link == NO
2277
2278     s->last_time_base= time / s->avctx->time_base.den;
2279
2280     ff_mpeg4_stuffing(&s->pb);
2281 }
2282
2283 static void mpeg4_encode_visual_object_header(MpegEncContext * s){
2284     int profile_and_level_indication;
2285     int vo_ver_id;
2286
2287     if(s->avctx->profile != FF_PROFILE_UNKNOWN){
2288         profile_and_level_indication = s->avctx->profile << 4;
2289     }else if(s->max_b_frames || s->quarter_sample){
2290         profile_and_level_indication= 0xF0; // adv simple
2291     }else{
2292         profile_and_level_indication= 0x00; // simple
2293     }
2294
2295     if(s->avctx->level != FF_LEVEL_UNKNOWN){
2296         profile_and_level_indication |= s->avctx->level;
2297     }else{
2298         profile_and_level_indication |= 1; //level 1
2299     }
2300
2301     if(profile_and_level_indication>>4 == 0xF){
2302         vo_ver_id= 5;
2303     }else{
2304         vo_ver_id= 1;
2305     }
2306
2307     //FIXME levels
2308
2309     put_bits(&s->pb, 16, 0);
2310     put_bits(&s->pb, 16, VOS_STARTCODE);
2311
2312     put_bits(&s->pb, 8, profile_and_level_indication);
2313
2314     put_bits(&s->pb, 16, 0);
2315     put_bits(&s->pb, 16, VISUAL_OBJ_STARTCODE);
2316
2317     put_bits(&s->pb, 1, 1);
2318         put_bits(&s->pb, 4, vo_ver_id);
2319         put_bits(&s->pb, 3, 1); //priority
2320
2321     put_bits(&s->pb, 4, 1); //visual obj type== video obj
2322
2323     put_bits(&s->pb, 1, 0); //video signal type == no clue //FIXME
2324
2325     ff_mpeg4_stuffing(&s->pb);
2326 }
2327
2328 static void mpeg4_encode_vol_header(MpegEncContext * s, int vo_number, int vol_number)
2329 {
2330     int vo_ver_id;
2331
2332     if (!CONFIG_MPEG4_ENCODER)  return;
2333
2334     if(s->max_b_frames || s->quarter_sample){
2335         vo_ver_id= 5;
2336         s->vo_type= ADV_SIMPLE_VO_TYPE;
2337     }else{
2338         vo_ver_id= 1;
2339         s->vo_type= SIMPLE_VO_TYPE;
2340     }
2341
2342     put_bits(&s->pb, 16, 0);
2343     put_bits(&s->pb, 16, 0x100 + vo_number);        /* video obj */
2344     put_bits(&s->pb, 16, 0);
2345     put_bits(&s->pb, 16, 0x120 + vol_number);       /* video obj layer */
2346
2347     put_bits(&s->pb, 1, 0);             /* random access vol */
2348     put_bits(&s->pb, 8, s->vo_type);    /* video obj type indication */
2349     if(s->workaround_bugs & FF_BUG_MS) {
2350         put_bits(&s->pb, 1, 0);         /* is obj layer id= no */
2351     } else {
2352         put_bits(&s->pb, 1, 1);         /* is obj layer id= yes */
2353         put_bits(&s->pb, 4, vo_ver_id); /* is obj layer ver id */
2354         put_bits(&s->pb, 3, 1);         /* is obj layer priority */
2355     }
2356
2357     aspect_to_info(s, s->avctx->sample_aspect_ratio);
2358
2359     put_bits(&s->pb, 4, s->aspect_ratio_info);/* aspect ratio info */
2360     if (s->aspect_ratio_info == FF_ASPECT_EXTENDED){
2361         put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.num);
2362         put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.den);
2363     }
2364
2365     if(s->workaround_bugs & FF_BUG_MS) { //
2366         put_bits(&s->pb, 1, 0);         /* vol control parameters= no @@@ */
2367     } else {
2368         put_bits(&s->pb, 1, 1);         /* vol control parameters= yes */
2369         put_bits(&s->pb, 2, 1);         /* chroma format YUV 420/YV12 */
2370         put_bits(&s->pb, 1, s->low_delay);
2371         put_bits(&s->pb, 1, 0);         /* vbv parameters= no */
2372     }
2373
2374     put_bits(&s->pb, 2, RECT_SHAPE);    /* vol shape= rectangle */
2375     put_bits(&s->pb, 1, 1);             /* marker bit */
2376
2377     put_bits(&s->pb, 16, s->avctx->time_base.den);
2378     if (s->time_increment_bits < 1)
2379         s->time_increment_bits = 1;
2380     put_bits(&s->pb, 1, 1);             /* marker bit */
2381     put_bits(&s->pb, 1, 0);             /* fixed vop rate=no */
2382     put_bits(&s->pb, 1, 1);             /* marker bit */
2383     put_bits(&s->pb, 13, s->width);     /* vol width */
2384     put_bits(&s->pb, 1, 1);             /* marker bit */
2385     put_bits(&s->pb, 13, s->height);    /* vol height */
2386     put_bits(&s->pb, 1, 1);             /* marker bit */
2387     put_bits(&s->pb, 1, s->progressive_sequence ? 0 : 1);
2388     put_bits(&s->pb, 1, 1);             /* obmc disable */
2389     if (vo_ver_id == 1) {
2390         put_bits(&s->pb, 1, s->vol_sprite_usage);       /* sprite enable */
2391     }else{
2392         put_bits(&s->pb, 2, s->vol_sprite_usage);       /* sprite enable */
2393     }
2394
2395     put_bits(&s->pb, 1, 0);             /* not 8 bit == false */
2396     put_bits(&s->pb, 1, s->mpeg_quant); /* quant type= (0=h263 style)*/
2397
2398     if(s->mpeg_quant){
2399         ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);
2400         ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);
2401     }
2402
2403     if (vo_ver_id != 1)
2404         put_bits(&s->pb, 1, s->quarter_sample);
2405     put_bits(&s->pb, 1, 1);             /* complexity estimation disable */
2406     s->resync_marker= s->rtp_mode;
2407     put_bits(&s->pb, 1, s->resync_marker ? 0 : 1);/* resync marker disable */
2408     put_bits(&s->pb, 1, s->data_partitioning ? 1 : 0);
2409     if(s->data_partitioning){
2410         put_bits(&s->pb, 1, 0);         /* no rvlc */
2411     }
2412
2413     if (vo_ver_id != 1){
2414         put_bits(&s->pb, 1, 0);         /* newpred */
2415         put_bits(&s->pb, 1, 0);         /* reduced res vop */
2416     }
2417     put_bits(&s->pb, 1, 0);             /* scalability */
2418
2419     ff_mpeg4_stuffing(&s->pb);
2420
2421     /* user data */
2422     if(!(s->flags & CODEC_FLAG_BITEXACT)){
2423         put_bits(&s->pb, 16, 0);
2424         put_bits(&s->pb, 16, 0x1B2);    /* user_data */
2425         ff_put_string(&s->pb, LIBAVCODEC_IDENT, 0);
2426     }
2427 }
2428
2429 /* write mpeg4 VOP header */
2430 void mpeg4_encode_picture_header(MpegEncContext * s, int picture_number)
2431 {
2432     int time_incr;
2433     int time_div, time_mod;
2434
2435     if(s->pict_type==FF_I_TYPE){
2436         if(!(s->flags&CODEC_FLAG_GLOBAL_HEADER)){
2437             if(s->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT) //HACK, the reference sw is buggy
2438                 mpeg4_encode_visual_object_header(s);
2439             if(s->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT || picture_number==0) //HACK, the reference sw is buggy
2440                 mpeg4_encode_vol_header(s, 0, 0);
2441         }
2442         if(!(s->workaround_bugs & FF_BUG_MS))
2443             mpeg4_encode_gop_header(s);
2444     }
2445
2446     s->partitioned_frame= s->data_partitioning && s->pict_type!=FF_B_TYPE;
2447
2448     put_bits(&s->pb, 16, 0);                /* vop header */
2449     put_bits(&s->pb, 16, VOP_STARTCODE);    /* vop header */
2450     put_bits(&s->pb, 2, s->pict_type - 1);  /* pict type: I = 0 , P = 1 */
2451
2452     assert(s->time>=0);
2453     time_div= s->time/s->avctx->time_base.den;
2454     time_mod= s->time%s->avctx->time_base.den;
2455     time_incr= time_div - s->last_time_base;
2456     assert(time_incr >= 0);
2457     while(time_incr--)
2458         put_bits(&s->pb, 1, 1);
2459
2460     put_bits(&s->pb, 1, 0);
2461
2462     put_bits(&s->pb, 1, 1);                             /* marker */
2463     put_bits(&s->pb, s->time_increment_bits, time_mod); /* time increment */
2464     put_bits(&s->pb, 1, 1);                             /* marker */
2465     put_bits(&s->pb, 1, 1);                             /* vop coded */
2466     if (    s->pict_type == FF_P_TYPE
2467         || (s->pict_type == FF_S_TYPE && s->vol_sprite_usage==GMC_SPRITE)) {
2468         put_bits(&s->pb, 1, s->no_rounding);    /* rounding type */
2469     }
2470     put_bits(&s->pb, 3, 0);     /* intra dc VLC threshold */
2471     if(!s->progressive_sequence){
2472          put_bits(&s->pb, 1, s->current_picture_ptr->top_field_first);
2473          put_bits(&s->pb, 1, s->alternate_scan);
2474     }
2475     //FIXME sprite stuff
2476
2477     put_bits(&s->pb, 5, s->qscale);
2478
2479     if (s->pict_type != FF_I_TYPE)
2480         put_bits(&s->pb, 3, s->f_code); /* fcode_for */
2481     if (s->pict_type == FF_B_TYPE)
2482         put_bits(&s->pb, 3, s->b_code); /* fcode_back */
2483 }
2484
2485 #endif //CONFIG_ENCODERS
2486
2487 /**
2488  * predicts the dc.
2489  * encoding quantized level -> quantized diff
2490  * decoding quantized diff -> quantized level
2491  * @param n block index (0-3 are luma, 4-5 are chroma)
2492  * @param dir_ptr pointer to an integer where the prediction direction will be stored
2493  */
2494 static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, int level, int *dir_ptr, int encoding)
2495 {
2496     int a, b, c, wrap, pred, scale, ret;
2497     int16_t *dc_val;
2498
2499     /* find prediction */
2500     if (n < 4) {
2501         scale = s->y_dc_scale;
2502     } else {
2503         scale = s->c_dc_scale;
2504     }
2505     if(IS_3IV1)
2506         scale= 8;
2507
2508     wrap= s->block_wrap[n];
2509     dc_val = s->dc_val[0] + s->block_index[n];
2510
2511     /* B C
2512      * A X
2513      */
2514     a = dc_val[ - 1];
2515     b = dc_val[ - 1 - wrap];
2516     c = dc_val[ - wrap];
2517
2518     /* outside slice handling (we can't do that by memset as we need the dc for error resilience) */
2519     if(s->first_slice_line && n!=3){
2520         if(n!=2) b=c= 1024;
2521         if(n!=1 && s->mb_x == s->resync_mb_x) b=a= 1024;
2522     }
2523     if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1){
2524         if(n==0 || n==4 || n==5)
2525             b=1024;
2526     }
2527
2528     if (abs(a - b) < abs(b - c)) {
2529         pred = c;
2530         *dir_ptr = 1; /* top */
2531     } else {
2532         pred = a;
2533         *dir_ptr = 0; /* left */
2534     }
2535     /* we assume pred is positive */
2536     pred = FASTDIV((pred + (scale >> 1)), scale);
2537
2538     if(encoding){
2539         ret = level - pred;
2540     }else{
2541         level += pred;
2542         ret= level;
2543         if(s->error_recognition>=3){
2544             if(level<0){
2545                 av_log(s->avctx, AV_LOG_ERROR, "dc<0 at %dx%d\n", s->mb_x, s->mb_y);
2546                 return -1;
2547             }
2548             if(level*scale > 2048 + scale){
2549                 av_log(s->avctx, AV_LOG_ERROR, "dc overflow at %dx%d\n", s->mb_x, s->mb_y);
2550                 return -1;
2551             }
2552         }
2553     }
2554     level *=scale;
2555     if(level&(~2047)){
2556         if(level<0)
2557             level=0;
2558         else if(!(s->workaround_bugs&FF_BUG_DC_CLIP))
2559             level=2047;
2560     }
2561     dc_val[0]= level;
2562
2563     return ret;
2564 }
2565
2566 /**
2567  * predicts the ac.
2568  * @param n block index (0-3 are luma, 4-5 are chroma)
2569  * @param dir the ac prediction direction
2570  */
2571 void mpeg4_pred_ac(MpegEncContext * s, DCTELEM *block, int n,
2572                    int dir)
2573 {
2574     int i;
2575     int16_t *ac_val, *ac_val1;
2576     int8_t * const qscale_table= s->current_picture.qscale_table;
2577
2578     /* find prediction */
2579     ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
2580     ac_val1 = ac_val;
2581     if (s->ac_pred) {
2582         if (dir == 0) {
2583             const int xy= s->mb_x-1 + s->mb_y*s->mb_stride;
2584             /* left prediction */
2585             ac_val -= 16;
2586
2587             if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
2588                 /* same qscale */
2589                 for(i=1;i<8;i++) {
2590                     block[s->dsp.idct_permutation[i<<3]] += ac_val[i];
2591                 }
2592             }else{
2593                 /* different qscale, we must rescale */
2594                 for(i=1;i<8;i++) {
2595                     block[s->dsp.idct_permutation[i<<3]] += ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale);
2596                 }
2597             }
2598         } else {
2599             const int xy= s->mb_x + s->mb_y*s->mb_stride - s->mb_stride;
2600             /* top prediction */
2601             ac_val -= 16 * s->block_wrap[n];
2602
2603             if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
2604                 /* same qscale */
2605                 for(i=1;i<8;i++) {
2606                     block[s->dsp.idct_permutation[i]] += ac_val[i + 8];
2607                 }
2608             }else{
2609                 /* different qscale, we must rescale */
2610                 for(i=1;i<8;i++) {
2611                     block[s->dsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale);
2612                 }
2613             }
2614         }
2615     }
2616     /* left copy */
2617     for(i=1;i<8;i++)
2618         ac_val1[i    ] = block[s->dsp.idct_permutation[i<<3]];
2619
2620     /* top copy */
2621     for(i=1;i<8;i++)
2622         ac_val1[8 + i] = block[s->dsp.idct_permutation[i   ]];
2623
2624 }
2625
2626 #if CONFIG_ENCODERS
2627
2628 /**
2629  * encodes the dc value.
2630  * @param n block index (0-3 are luma, 4-5 are chroma)
2631  */
2632 static inline void mpeg4_encode_dc(PutBitContext * s, int level, int n)
2633 {
2634 #if 1
2635     level+=256;
2636     if (n < 4) {
2637         /* luminance */
2638         put_bits(s, uni_DCtab_lum_len[level], uni_DCtab_lum_bits[level]);
2639     } else {
2640         /* chrominance */
2641         put_bits(s, uni_DCtab_chrom_len[level], uni_DCtab_chrom_bits[level]);
2642     }
2643 #else
2644     int size, v;
2645     /* find number of bits */
2646     size = 0;
2647     v = abs(level);
2648     while (v) {
2649         v >>= 1;
2650         size++;
2651     }
2652
2653     if (n < 4) {
2654         /* luminance */
2655         put_bits(&s->pb, DCtab_lum[size][1], DCtab_lum[size][0]);
2656     } else {
2657         /* chrominance */
2658         put_bits(&s->pb, DCtab_chrom[size][1], DCtab_chrom[size][0]);
2659     }
2660
2661     /* encode remaining bits */
2662     if (size > 0) {
2663         if (level < 0)
2664             level = (-level) ^ ((1 << size) - 1);
2665         put_bits(&s->pb, size, level);
2666         if (size > 8)
2667             put_bits(&s->pb, 1, 1);
2668     }
2669 #endif
2670 }
2671
2672 static inline int mpeg4_get_dc_length(int level, int n){
2673     if (n < 4) {
2674         return uni_DCtab_lum_len[level + 256];
2675     } else {
2676         return uni_DCtab_chrom_len[level + 256];
2677     }
2678 }
2679
2680 /**
2681  * encodes a 8x8 block
2682  * @param n block index (0-3 are luma, 4-5 are chroma)
2683  */
2684 static inline void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block, int n, int intra_dc,
2685                                uint8_t *scan_table, PutBitContext *dc_pb, PutBitContext *ac_pb)
2686 {
2687     int i, last_non_zero;
2688 #if 0 //variables for the outcommented version
2689     int code, sign, last;
2690 #endif
2691     const RLTable *rl;
2692     uint32_t *bits_tab;
2693     uint8_t *len_tab;
2694     const int last_index = s->block_last_index[n];
2695
2696     if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
2697         /* mpeg4 based DC predictor */
2698         mpeg4_encode_dc(dc_pb, intra_dc, n);
2699         if(last_index<1) return;
2700         i = 1;
2701         rl = &rl_intra;
2702         bits_tab= uni_mpeg4_intra_rl_bits;
2703         len_tab = uni_mpeg4_intra_rl_len;
2704     } else {
2705         if(last_index<0) return;
2706         i = 0;
2707         rl = &rl_inter;
2708         bits_tab= uni_mpeg4_inter_rl_bits;
2709         len_tab = uni_mpeg4_inter_rl_len;
2710     }
2711
2712     /* AC coefs */
2713     last_non_zero = i - 1;
2714 #if 1
2715     for (; i < last_index; i++) {
2716         int level = block[ scan_table[i] ];
2717         if (level) {
2718             int run = i - last_non_zero - 1;
2719             level+=64;
2720             if((level&(~127)) == 0){
2721                 const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
2722                 put_bits(ac_pb, len_tab[index], bits_tab[index]);
2723             }else{ //ESC3
2724                 put_bits(ac_pb, 7+2+1+6+1+12+1, (3<<23)+(3<<21)+(0<<20)+(run<<14)+(1<<13)+(((level-64)&0xfff)<<1)+1);
2725             }
2726             last_non_zero = i;
2727         }
2728     }
2729     /*if(i<=last_index)*/{
2730         int level = block[ scan_table[i] ];
2731         int run = i - last_non_zero - 1;
2732         level+=64;
2733         if((level&(~127)) == 0){
2734             const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
2735             put_bits(ac_pb, len_tab[index], bits_tab[index]);
2736         }else{ //ESC3
2737             put_bits(ac_pb, 7+2+1+6+1+12+1, (3<<23)+(3<<21)+(1<<20)+(run<<14)+(1<<13)+(((level-64)&0xfff)<<1)+1);
2738         }
2739     }
2740 #else
2741     for (; i <= last_index; i++) {
2742         const int slevel = block[ scan_table[i] ];
2743         if (slevel) {
2744             int level;
2745             int run = i - last_non_zero - 1;
2746             last = (i == last_index);
2747             sign = 0;
2748             level = slevel;
2749             if (level < 0) {
2750                 sign = 1;
2751                 level = -level;
2752             }
2753             code = get_rl_index(rl, last, run, level);
2754             put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2755             if (code == rl->n) {
2756                 int level1, run1;
2757                 level1 = level - rl->max_level[last][run];
2758                 if (level1 < 1)
2759                     goto esc2;
2760                 code = get_rl_index(rl, last, run, level1);
2761                 if (code == rl->n) {
2762                 esc2:
2763                     put_bits(ac_pb, 1, 1);
2764                     if (level > MAX_LEVEL)
2765                         goto esc3;
2766                     run1 = run - rl->max_run[last][level] - 1;
2767                     if (run1 < 0)
2768                         goto esc3;
2769                     code = get_rl_index(rl, last, run1, level);
2770                     if (code == rl->n) {
2771                     esc3:
2772                         /* third escape */
2773                         put_bits(ac_pb, 1, 1);
2774                         put_bits(ac_pb, 1, last);
2775                         put_bits(ac_pb, 6, run);
2776                         put_bits(ac_pb, 1, 1);
2777                         put_sbits(ac_pb, 12, slevel);
2778                         put_bits(ac_pb, 1, 1);
2779                     } else {
2780                         /* second escape */
2781                         put_bits(ac_pb, 1, 0);
2782                         put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2783                         put_bits(ac_pb, 1, sign);
2784                     }
2785                 } else {
2786                     /* first escape */
2787                     put_bits(ac_pb, 1, 0);
2788                     put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2789                     put_bits(ac_pb, 1, sign);
2790                 }
2791             } else {
2792                 put_bits(ac_pb, 1, sign);
2793             }
2794             last_non_zero = i;
2795         }
2796     }
2797 #endif
2798 }
2799
2800 static int mpeg4_get_block_length(MpegEncContext * s, DCTELEM * block, int n, int intra_dc,
2801                                uint8_t *scan_table)
2802 {
2803     int i, last_non_zero;
2804     uint8_t *len_tab;
2805     const int last_index = s->block_last_index[n];
2806     int len=0;
2807
2808     if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
2809         /* mpeg4 based DC predictor */
2810         len += mpeg4_get_dc_length(intra_dc, n);
2811         if(last_index<1) return len;
2812         i = 1;
2813         len_tab = uni_mpeg4_intra_rl_len;
2814     } else {
2815         if(last_index<0) return 0;
2816         i = 0;
2817         len_tab = uni_mpeg4_inter_rl_len;
2818     }
2819
2820     /* AC coefs */
2821     last_non_zero = i - 1;
2822     for (; i < last_index; i++) {
2823         int level = block[ scan_table[i] ];
2824         if (level) {
2825             int run = i - last_non_zero - 1;
2826             level+=64;
2827             if((level&(~127)) == 0){
2828                 const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
2829                 len += len_tab[index];
2830             }else{ //ESC3
2831                 len += 7+2+1+6+1+12+1;
2832             }
2833             last_non_zero = i;
2834         }
2835     }
2836     /*if(i<=last_index)*/{
2837         int level = block[ scan_table[i] ];
2838         int run = i - last_non_zero - 1;
2839         level+=64;
2840         if((level&(~127)) == 0){
2841             const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
2842             len += len_tab[index];
2843         }else{ //ESC3
2844             len += 7+2+1+6+1+12+1;
2845         }
2846     }
2847
2848     return len;
2849 }
2850
2851 #endif
2852
2853
2854 /***********************************************/
2855 /* decoding */
2856
2857 static VLC intra_MCBPC_vlc;
2858 static VLC inter_MCBPC_vlc;
2859 static VLC cbpy_vlc;
2860 static VLC mv_vlc;
2861 static VLC dc_lum, dc_chrom;
2862 static VLC sprite_trajectory;
2863 static VLC mb_type_b_vlc;
2864 static VLC h263_mbtype_b_vlc;
2865 static VLC cbpc_b_vlc;
2866
2867 /* init vlcs */
2868
2869 /* XXX: find a better solution to handle static init */
2870 void h263_decode_init_vlc(MpegEncContext *s)
2871 {
2872     static int done = 0;
2873
2874     if (!done) {
2875         done = 1;
2876
2877         INIT_VLC_STATIC(&intra_MCBPC_vlc, INTRA_MCBPC_VLC_BITS, 9,
2878                  intra_MCBPC_bits, 1, 1,
2879                  intra_MCBPC_code, 1, 1, 72);
2880         INIT_VLC_STATIC(&inter_MCBPC_vlc, INTER_MCBPC_VLC_BITS, 28,
2881                  inter_MCBPC_bits, 1, 1,
2882                  inter_MCBPC_code, 1, 1, 198);
2883         INIT_VLC_STATIC(&cbpy_vlc, CBPY_VLC_BITS, 16,
2884                  &cbpy_tab[0][1], 2, 1,
2885                  &cbpy_tab[0][0], 2, 1, 64);
2886         INIT_VLC_STATIC(&mv_vlc, MV_VLC_BITS, 33,
2887                  &mvtab[0][1], 2, 1,
2888                  &mvtab[0][0], 2, 1, 538);
2889         init_rl(&rl_inter, static_rl_table_store[0]);
2890         init_rl(&rl_intra, static_rl_table_store[1]);
2891         init_rl(&rvlc_rl_inter, static_rl_table_store[3]);
2892         init_rl(&rvlc_rl_intra, static_rl_table_store[4]);
2893         init_rl(&rl_intra_aic, static_rl_table_store[2]);
2894         INIT_VLC_RL(rl_inter, 554);
2895         INIT_VLC_RL(rl_intra, 554);
2896         INIT_VLC_RL(rvlc_rl_inter, 1072);
2897         INIT_VLC_RL(rvlc_rl_intra, 1072);
2898         INIT_VLC_RL(rl_intra_aic, 554);
2899         INIT_VLC_STATIC(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
2900                  &DCtab_lum[0][1], 2, 1,
2901                  &DCtab_lum[0][0], 2, 1, 512);
2902         INIT_VLC_STATIC(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
2903                  &DCtab_chrom[0][1], 2, 1,
2904                  &DCtab_chrom[0][0], 2, 1, 512);
2905         INIT_VLC_STATIC(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
2906                  &sprite_trajectory_tab[0][1], 4, 2,
2907                  &sprite_trajectory_tab[0][0], 4, 2, 128);
2908         INIT_VLC_STATIC(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
2909                  &mb_type_b_tab[0][1], 2, 1,
2910                  &mb_type_b_tab[0][0], 2, 1, 16);
2911         INIT_VLC_STATIC(&h263_mbtype_b_vlc, H263_MBTYPE_B_VLC_BITS, 15,
2912                  &h263_mbtype_b_tab[0][1], 2, 1,
2913                  &h263_mbtype_b_tab[0][0], 2, 1, 80);
2914         INIT_VLC_STATIC(&cbpc_b_vlc, CBPC_B_VLC_BITS, 4,
2915                  &cbpc_b_tab[0][1], 2, 1,
2916                  &cbpc_b_tab[0][0], 2, 1, 8);
2917     }
2918 }
2919
2920 /**
2921  * Get the GOB height based on picture height.
2922  */
2923 int ff_h263_get_gob_height(MpegEncContext *s){
2924     if (s->height <= 400)
2925         return 1;
2926     else if (s->height <= 800)
2927         return  2;
2928     else
2929         return 4;
2930 }
2931
2932 int ff_h263_decode_mba(MpegEncContext *s)
2933 {
2934     int i, mb_pos;
2935
2936     for(i=0; i<6; i++){
2937         if(s->mb_num-1 <= ff_mba_max[i]) break;
2938     }
2939     mb_pos= get_bits(&s->gb, ff_mba_length[i]);
2940     s->mb_x= mb_pos % s->mb_width;
2941     s->mb_y= mb_pos / s->mb_width;
2942
2943     return mb_pos;
2944 }
2945
2946 void ff_h263_encode_mba(MpegEncContext *s)
2947 {
2948     int i, mb_pos;
2949
2950     for(i=0; i<6; i++){
2951         if(s->mb_num-1 <= ff_mba_max[i]) break;
2952     }
2953     mb_pos= s->mb_x + s->mb_width*s->mb_y;
2954     put_bits(&s->pb, ff_mba_length[i], mb_pos);
2955 }
2956
2957 /**
2958  * decodes the group of blocks header or slice header.
2959  * @return <0 if an error occurred
2960  */
2961 static int h263_decode_gob_header(MpegEncContext *s)
2962 {
2963     unsigned int val, gfid, gob_number;
2964     int left;
2965
2966     /* Check for GOB Start Code */
2967     val = show_bits(&s->gb, 16);
2968     if(val)
2969         return -1;
2970
2971         /* We have a GBSC probably with GSTUFF */
2972     skip_bits(&s->gb, 16); /* Drop the zeros */
2973     left= get_bits_left(&s->gb);
2974     //MN: we must check the bits left or we might end in a infinite loop (or segfault)
2975     for(;left>13; left--){
2976         if(get_bits1(&s->gb)) break; /* Seek the '1' bit */
2977     }
2978     if(left<=13)
2979         return -1;
2980
2981     if(s->h263_slice_structured){
2982         if(get_bits1(&s->gb)==0)
2983             return -1;
2984
2985         ff_h263_decode_mba(s);
2986
2987         if(s->mb_num > 1583)
2988             if(get_bits1(&s->gb)==0)
2989                 return -1;
2990
2991         s->qscale = get_bits(&s->gb, 5); /* SQUANT */
2992         if(get_bits1(&s->gb)==0)
2993             return -1;
2994         gfid = get_bits(&s->gb, 2); /* GFID */
2995     }else{
2996         gob_number = get_bits(&s->gb, 5); /* GN */
2997         s->mb_x= 0;
2998         s->mb_y= s->gob_index* gob_number;
2999         gfid = get_bits(&s->gb, 2); /* GFID */
3000         s->qscale = get_bits(&s->gb, 5); /* GQUANT */
3001     }
3002
3003     if(s->mb_y >= s->mb_height)
3004         return -1;
3005
3006     if(s->qscale==0)
3007         return -1;
3008
3009     return 0;
3010 }
3011
3012 static inline void memsetw(short *tab, int val, int n)
3013 {
3014     int i;
3015     for(i=0;i<n;i++)
3016         tab[i] = val;
3017 }
3018
3019 #if CONFIG_ENCODERS
3020
3021 void ff_mpeg4_init_partitions(MpegEncContext *s)
3022 {
3023     uint8_t *start= put_bits_ptr(&s->pb);
3024     uint8_t *end= s->pb.buf_end;
3025     int size= end - start;
3026     int pb_size = (((intptr_t)start + size/3)&(~3)) - (intptr_t)start;
3027     int tex_size= (size - 2*pb_size)&(~3);
3028
3029     set_put_bits_buffer_size(&s->pb, pb_size);
3030     init_put_bits(&s->tex_pb, start + pb_size           , tex_size);
3031     init_put_bits(&s->pb2   , start + pb_size + tex_size, pb_size);
3032 }
3033
3034 void ff_mpeg4_merge_partitions(MpegEncContext *s)
3035 {
3036     const int pb2_len   = put_bits_count(&s->pb2   );
3037     const int tex_pb_len= put_bits_count(&s->tex_pb);
3038     const int bits= put_bits_count(&s->pb);
3039
3040     if(s->pict_type==FF_I_TYPE){
3041         put_bits(&s->pb, 19, DC_MARKER);
3042         s->misc_bits+=19 + pb2_len + bits - s->last_bits;
3043         s->i_tex_bits+= tex_pb_len;
3044     }else{
3045         put_bits(&s->pb, 17, MOTION_MARKER);
3046         s->misc_bits+=17 + pb2_len;
3047         s->mv_bits+= bits - s->last_bits;
3048         s->p_tex_bits+= tex_pb_len;
3049     }
3050
3051     flush_put_bits(&s->pb2);
3052     flush_put_bits(&s->tex_pb);
3053
3054     set_put_bits_buffer_size(&s->pb, s->pb2.buf_end - s->pb.buf);
3055     ff_copy_bits(&s->pb, s->pb2.buf   , pb2_len);
3056     ff_copy_bits(&s->pb, s->tex_pb.buf, tex_pb_len);
3057     s->last_bits= put_bits_count(&s->pb);
3058 }
3059
3060 #endif //CONFIG_ENCODERS
3061
3062 int ff_mpeg4_get_video_packet_prefix_length(MpegEncContext *s){
3063     switch(s->pict_type){
3064         case FF_I_TYPE:
3065             return 16;
3066         case FF_P_TYPE:
3067         case FF_S_TYPE:
3068             return s->f_code+15;
3069         case FF_B_TYPE:
3070             return FFMAX3(s->f_code, s->b_code, 2) + 15;
3071         default:
3072             return -1;
3073     }
3074 }
3075
3076 #if CONFIG_ENCODERS
3077
3078 void ff_mpeg4_encode_video_packet_header(MpegEncContext *s)
3079 {
3080     int mb_num_bits= av_log2(s->mb_num - 1) + 1;
3081
3082     put_bits(&s->pb, ff_mpeg4_get_video_packet_prefix_length(s), 0);
3083     put_bits(&s->pb, 1, 1);
3084
3085     put_bits(&s->pb, mb_num_bits, s->mb_x + s->mb_y*s->mb_width);
3086     put_bits(&s->pb, s->quant_precision, s->qscale);
3087     put_bits(&s->pb, 1, 0); /* no HEC */
3088 }
3089
3090 #endif //CONFIG_ENCODERS
3091
3092 /**
3093  * check if the next stuff is a resync marker or the end.
3094  * @return 0 if not
3095  */
3096 static inline int mpeg4_is_resync(MpegEncContext *s){
3097     int bits_count= get_bits_count(&s->gb);
3098     int v= show_bits(&s->gb, 16);
3099
3100     if(s->workaround_bugs&FF_BUG_NO_PADDING){
3101         return 0;
3102     }
3103
3104     while(v<=0xFF){
3105         if(s->pict_type==FF_B_TYPE || (v>>(8-s->pict_type)!=1) || s->partitioned_frame)
3106             break;
3107         skip_bits(&s->gb, 8+s->pict_type);
3108         bits_count+= 8+s->pict_type;
3109         v= show_bits(&s->gb, 16);
3110     }
3111
3112     if(bits_count + 8 >= s->gb.size_in_bits){
3113         v>>=8;
3114         v|= 0x7F >> (7-(bits_count&7));
3115
3116         if(v==0x7F)
3117             return 1;
3118     }else{
3119         if(v == ff_mpeg4_resync_prefix[bits_count&7]){
3120             int len;
3121             GetBitContext gb= s->gb;
3122
3123             skip_bits(&s->gb, 1);
3124             align_get_bits(&s->gb);
3125
3126             for(len=0; len<32; len++){
3127                 if(get_bits1(&s->gb)) break;
3128             }
3129
3130             s->gb= gb;
3131
3132             if(len>=ff_mpeg4_get_video_packet_prefix_length(s))
3133                 return 1;
3134         }
3135     }
3136     return 0;
3137 }
3138
3139 /**
3140  * decodes the next video packet.
3141  * @return <0 if something went wrong
3142  */
3143 static int mpeg4_decode_video_packet_header(MpegEncContext *s)
3144 {
3145     int mb_num_bits= av_log2(s->mb_num - 1) + 1;
3146     int header_extension=0, mb_num, len;
3147
3148     /* is there enough space left for a video packet + header */
3149     if( get_bits_count(&s->gb) > s->gb.size_in_bits-20) return -1;
3150
3151     for(len=0; len<32; len++){
3152         if(get_bits1(&s->gb)) break;
3153     }
3154
3155     if(len!=ff_mpeg4_get_video_packet_prefix_length(s)){
3156         av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n");
3157         return -1;
3158     }
3159
3160     if(s->shape != RECT_SHAPE){
3161         header_extension= get_bits1(&s->gb);
3162         //FIXME more stuff here
3163     }
3164
3165     mb_num= get_bits(&s->gb, mb_num_bits);
3166     if(mb_num>=s->mb_num){
3167         av_log(s->avctx, AV_LOG_ERROR, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
3168         return -1;
3169     }
3170     if(s->pict_type == FF_B_TYPE){
3171         while(s->next_picture.mbskip_table[ s->mb_index2xy[ mb_num ] ]) mb_num++;
3172         if(mb_num >= s->mb_num) return -1; // slice contains just skipped MBs which where already decoded
3173     }
3174
3175     s->mb_x= mb_num % s->mb_width;
3176     s->mb_y= mb_num / s->mb_width;
3177
3178     if(s->shape != BIN_ONLY_SHAPE){
3179         int qscale= get_bits(&s->gb, s->quant_precision);
3180         if(qscale)
3181             s->chroma_qscale=s->qscale= qscale;
3182     }
3183
3184     if(s->shape == RECT_SHAPE){
3185         header_extension= get_bits1(&s->gb);
3186     }
3187     if(header_extension){
3188         int time_increment;
3189         int time_incr=0;
3190
3191         while (get_bits1(&s->gb) != 0)
3192             time_incr++;
3193
3194         check_marker(&s->gb, "before time_increment in video packed header");
3195         time_increment= get_bits(&s->gb, s->time_increment_bits);
3196         check_marker(&s->gb, "before vop_coding_type in video packed header");
3197
3198         skip_bits(&s->gb, 2); /* vop coding type */
3199         //FIXME not rect stuff here
3200
3201         if(s->shape != BIN_ONLY_SHAPE){
3202             skip_bits(&s->gb, 3); /* intra dc vlc threshold */
3203 //FIXME don't just ignore everything
3204             if(s->pict_type == FF_S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3205                 mpeg4_decode_sprite_trajectory(s, &s->gb);
3206                 av_log(s->avctx, AV_LOG_ERROR, "untested\n");
3207             }
3208
3209             //FIXME reduced res stuff here
3210
3211             if (s->pict_type != FF_I_TYPE) {
3212                 int f_code = get_bits(&s->gb, 3);       /* fcode_for */
3213                 if(f_code==0){
3214                     av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (f_code=0)\n");
3215                 }
3216             }
3217             if (s->pict_type == FF_B_TYPE) {
3218                 int b_code = get_bits(&s->gb, 3);
3219                 if(b_code==0){
3220                     av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (b_code=0)\n");
3221                 }
3222             }
3223         }
3224     }
3225     //FIXME new-pred stuff
3226
3227     return 0;
3228 }
3229
3230 void ff_mpeg4_clean_buffers(MpegEncContext *s)
3231 {
3232     int c_wrap, c_xy, l_wrap, l_xy;
3233
3234     l_wrap= s->b8_stride;
3235     l_xy= (2*s->mb_y-1)*l_wrap + s->mb_x*2 - 1;
3236     c_wrap= s->mb_stride;
3237     c_xy= (s->mb_y-1)*c_wrap + s->mb_x - 1;
3238
3239 #if 0
3240     /* clean DC */
3241     memsetw(s->dc_val[0] + l_xy, 1024, l_wrap*2+1);
3242     memsetw(s->dc_val[1] + c_xy, 1024, c_wrap+1);
3243     memsetw(s->dc_val[2] + c_xy, 1024, c_wrap+1);
3244 #endif
3245
3246     /* clean AC */
3247     memset(s->ac_val[0] + l_xy, 0, (l_wrap*2+1)*16*sizeof(int16_t));
3248     memset(s->ac_val[1] + c_xy, 0, (c_wrap  +1)*16*sizeof(int16_t));
3249     memset(s->ac_val[2] + c_xy, 0, (c_wrap  +1)*16*sizeof(int16_t));
3250
3251     /* clean MV */
3252     // we can't clear the MVs as they might be needed by a b frame
3253 //    memset(s->motion_val + l_xy, 0, (l_wrap*2+1)*2*sizeof(int16_t));
3254 //    memset(s->motion_val, 0, 2*sizeof(int16_t)*(2 + s->mb_width*2)*(2 + s->mb_height*2));
3255     s->last_mv[0][0][0]=
3256     s->last_mv[0][0][1]=
3257     s->last_mv[1][0][0]=
3258     s->last_mv[1][0][1]= 0;
3259 }
3260
3261 /**
3262  * finds the next resync_marker
3263  * @param p pointer to buffer to scan
3264  * @param end pointer to the end of the buffer
3265  * @return pointer to the next resync_marker, or \p end if none was found
3266  */
3267 const uint8_t *ff_h263_find_resync_marker(const uint8_t *restrict p, const uint8_t * restrict end)
3268 {
3269     assert(p < end);
3270
3271     end-=2;
3272     p++;
3273     for(;p<end; p+=2){
3274         if(!*p){
3275             if     (!p[-1] && p[1]) return p - 1;
3276             else if(!p[ 1] && p[2]) return p;
3277         }
3278     }
3279     return end+2;
3280 }
3281
3282 /**
3283  * decodes the group of blocks / video packet header.
3284  * @return bit position of the resync_marker, or <0 if none was found
3285  */
3286 int ff_h263_resync(MpegEncContext *s){
3287     int left, pos, ret;
3288
3289     if(s->codec_id==CODEC_ID_MPEG4){
3290         skip_bits1(&s->gb);
3291         align_get_bits(&s->gb);
3292     }
3293
3294     if(show_bits(&s->gb, 16)==0){
3295         pos= get_bits_count(&s->gb);
3296         if(s->codec_id==CODEC_ID_MPEG4)
3297             ret= mpeg4_decode_video_packet_header(s);
3298         else
3299             ret= h263_decode_gob_header(s);
3300         if(ret>=0)
3301             return pos;
3302     }
3303     //OK, it's not where it is supposed to be ...
3304     s->gb= s->last_resync_gb;
3305     align_get_bits(&s->gb);
3306     left= get_bits_left(&s->gb);
3307
3308     for(;left>16+1+5+5; left-=8){
3309         if(show_bits(&s->gb, 16)==0){
3310             GetBitContext bak= s->gb;
3311
3312             pos= get_bits_count(&s->gb);
3313             if(s->codec_id==CODEC_ID_MPEG4)
3314                 ret= mpeg4_decode_video_packet_header(s);
3315             else
3316                 ret= h263_decode_gob_header(s);
3317             if(ret>=0)
3318                 return pos;
3319
3320             s->gb= bak;
3321         }
3322         skip_bits(&s->gb, 8);
3323     }
3324
3325     return -1;
3326 }
3327
3328 /**
3329  * gets the average motion vector for a GMC MB.
3330  * @param n either 0 for the x component or 1 for y
3331  * @returns the average MV for a GMC MB
3332  */
3333 static inline int get_amv(MpegEncContext *s, int n){
3334     int x, y, mb_v, sum, dx, dy, shift;
3335     int len = 1 << (s->f_code + 4);
3336     const int a= s->sprite_warping_accuracy;
3337
3338     if(s->workaround_bugs & FF_BUG_AMV)
3339         len >>= s->quarter_sample;
3340
3341     if(s->real_sprite_warping_points==1){
3342         if(s->divx_version==500 && s->divx_build==413)
3343             sum= s->sprite_offset[0][n] / (1<<(a - s->quarter_sample));
3344         else
3345             sum= RSHIFT(s->sprite_offset[0][n]<<s->quarter_sample, a);
3346     }else{
3347         dx= s->sprite_delta[n][0];
3348         dy= s->sprite_delta[n][1];
3349         shift= s->sprite_shift[0];
3350         if(n) dy -= 1<<(shift + a + 1);
3351         else  dx -= 1<<(shift + a + 1);
3352         mb_v= s->sprite_offset[0][n] + dx*s->mb_x*16 + dy*s->mb_y*16;
3353
3354         sum=0;
3355         for(y=0; y<16; y++){
3356             int v;
3357
3358             v= mb_v + dy*y;
3359             //XXX FIXME optimize
3360             for(x=0; x<16; x++){
3361                 sum+= v>>shift;
3362                 v+= dx;
3363             }
3364         }
3365         sum= RSHIFT(sum, a+8-s->quarter_sample);
3366     }
3367
3368     if      (sum < -len) sum= -len;
3369     else if (sum >= len) sum= len-1;
3370
3371     return sum;
3372 }
3373
3374 /**
3375  * decodes first partition.
3376  * @return number of MBs decoded or <0 if an error occurred
3377  */
3378 static int mpeg4_decode_partition_a(MpegEncContext *s){
3379     int mb_num;
3380     static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
3381
3382     /* decode first partition */
3383     mb_num=0;
3384     s->first_slice_line=1;
3385     for(; s->mb_y<s->mb_height; s->mb_y++){
3386         ff_init_block_index(s);
3387         for(; s->mb_x<s->mb_width; s->mb_x++){
3388             const int xy= s->mb_x + s->mb_y*s->mb_stride;
3389             int cbpc;
3390             int dir=0;
3391
3392             mb_num++;
3393             ff_update_block_index(s);
3394             if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
3395                 s->first_slice_line=0;
3396
3397             if(s->pict_type==FF_I_TYPE){
3398                 int i;
3399
3400                 do{
3401                     if(show_bits_long(&s->gb, 19)==DC_MARKER){
3402                         return mb_num-1;
3403                     }
3404
3405                     cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
3406                     if (cbpc < 0){
3407                         av_log(s->avctx, AV_LOG_ERROR, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
3408                         return -1;
3409                     }
3410                 }while(cbpc == 8);
3411
3412                 s->cbp_table[xy]= cbpc & 3;
3413                 s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
3414                 s->mb_intra = 1;
3415
3416                 if(cbpc & 4) {
3417                     ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
3418                 }
3419                 s->current_picture.qscale_table[xy]= s->qscale;
3420
3421                 s->mbintra_table[xy]= 1;
3422                 for(i=0; i<6; i++){
3423                     int dc_pred_dir;
3424                     int dc= mpeg4_decode_dc(s, i, &dc_pred_dir);
3425                     if(dc < 0){
3426                         av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
3427                         return -1;
3428                     }
3429                     dir<<=1;
3430                     if(dc_pred_dir) dir|=1;
3431                 }
3432                 s->pred_dir_table[xy]= dir;
3433             }else{ /* P/S_TYPE */
3434                 int mx, my, pred_x, pred_y, bits;
3435                 int16_t * const mot_val= s->current_picture.motion_val[0][s->block_index[0]];
3436                 const int stride= s->b8_stride*2;
3437
3438 try_again:
3439                 bits= show_bits(&s->gb, 17);
3440                 if(bits==MOTION_MARKER){
3441                     return mb_num-1;
3442                 }
3443                 skip_bits1(&s->gb);
3444                 if(bits&0x10000){
3445                     /* skip mb */
3446                     if(s->pict_type==FF_S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3447                         s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0;
3448                         mx= get_amv(s, 0);
3449                         my= get_amv(s, 1);
3450                     }else{
3451                         s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
3452                         mx=my=0;
3453                     }
3454                     mot_val[0       ]= mot_val[2       ]=
3455                     mot_val[0+stride]= mot_val[2+stride]= mx;
3456                     mot_val[1       ]= mot_val[3       ]=
3457                     mot_val[1+stride]= mot_val[3+stride]= my;
3458
3459                     if(s->mbintra_table[xy])
3460                         ff_clean_intra_table_entries(s);
3461                     continue;
3462                 }
3463
3464                 cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
3465                 if (cbpc < 0){
3466                     av_log(s->avctx, AV_LOG_ERROR, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
3467                     return -1;
3468                 }
3469                 if(cbpc == 20)
3470                     goto try_again;
3471
3472                 s->cbp_table[xy]= cbpc&(8+3); //8 is dquant
3473
3474                 s->mb_intra = ((cbpc & 4) != 0);
3475
3476                 if(s->mb_intra){
3477                     s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
3478                     s->mbintra_table[xy]= 1;
3479                     mot_val[0       ]= mot_val[2       ]=
3480                     mot_val[0+stride]= mot_val[2+stride]= 0;
3481                     mot_val[1       ]= mot_val[3       ]=
3482                     mot_val[1+stride]= mot_val[3+stride]= 0;
3483                 }else{
3484                     if(s->mbintra_table[xy])
3485                         ff_clean_intra_table_entries(s);
3486
3487                     if(s->pict_type==FF_S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
3488                         s->mcsel= get_bits1(&s->gb);
3489                     else s->mcsel= 0;
3490
3491                     if ((cbpc & 16) == 0) {
3492                         /* 16x16 motion prediction */
3493
3494                         h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
3495                         if(!s->mcsel){
3496                             mx = h263_decode_motion(s, pred_x, s->f_code);
3497                             if (mx >= 0xffff)
3498                                 return -1;
3499
3500                             my = h263_decode_motion(s, pred_y, s->f_code);
3501                             if (my >= 0xffff)
3502                                 return -1;
3503                             s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0;
3504                         } else {
3505                             mx = get_amv(s, 0);
3506                             my = get_amv(s, 1);
3507                             s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0;
3508                         }
3509
3510                         mot_val[0       ]= mot_val[2       ] =
3511                         mot_val[0+stride]= mot_val[2+stride]= mx;
3512                         mot_val[1       ]= mot_val[3       ]=
3513                         mot_val[1+stride]= mot_val[3+stride]= my;
3514                     } else {
3515                         int i;
3516                         s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0;
3517                         for(i=0;i<4;i++) {
3518                             int16_t *mot_val= h263_pred_motion(s, i, 0, &pred_x, &pred_y);
3519                             mx = h263_decode_motion(s, pred_x, s->f_code);
3520                             if (mx >= 0xffff)
3521                                 return -1;
3522
3523                             my = h263_decode_motion(s, pred_y, s->f_code);
3524                             if (my >= 0xffff)
3525                                 return -1;
3526                             mot_val[0] = mx;
3527                             mot_val[1] = my;
3528                         }
3529                     }
3530                 }
3531             }
3532         }
3533         s->mb_x= 0;
3534     }
3535
3536     return mb_num;
3537 }
3538
3539 /**
3540  * decode second partition.
3541  * @return <0 if an error occurred
3542  */
3543 static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count){
3544     int mb_num=0;
3545     static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
3546
3547     s->mb_x= s->resync_mb_x;
3548     s->first_slice_line=1;
3549     for(s->mb_y= s->resync_mb_y; mb_num < mb_count; s->mb_y++){
3550         ff_init_block_index(s);
3551         for(; mb_num < mb_count && s->mb_x<s->mb_width; s->mb_x++){
3552             const int xy= s->mb_x + s->mb_y*s->mb_stride;
3553
3554             mb_num++;
3555             ff_update_block_index(s);
3556             if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
3557                 s->first_slice_line=0;
3558
3559             if(s->pict_type==FF_I_TYPE){
3560                 int ac_pred= get_bits1(&s->gb);
3561                 int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3562                 if(cbpy<0){
3563                     av_log(s->avctx, AV_LOG_ERROR, "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
3564                     return -1;
3565                 }
3566
3567                 s->cbp_table[xy]|= cbpy<<2;
3568                 s->current_picture.mb_type[xy] |= ac_pred*MB_TYPE_ACPRED;
3569             }else{ /* P || S_TYPE */
3570                 if(IS_INTRA(s->current_picture.mb_type[xy])){
3571                     int dir=0,i;
3572                     int ac_pred = get_bits1(&s->gb);
3573                     int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3574
3575                     if(cbpy<0){
3576                         av_log(s->avctx, AV_LOG_ERROR, "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
3577                         return -1;
3578                     }
3579
3580                     if(s->cbp_table[xy] & 8) {
3581                         ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
3582                     }
3583                     s->current_picture.qscale_table[xy]= s->qscale;
3584
3585                     for(i=0; i<6; i++){
3586                         int dc_pred_dir;
3587                         int dc= mpeg4_decode_dc(s, i, &dc_pred_dir);
3588                         if(dc < 0){
3589                             av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
3590                             return -1;
3591                         }
3592                         dir<<=1;
3593                         if(dc_pred_dir) dir|=1;
3594                     }
3595                     s->cbp_table[xy]&= 3; //remove dquant
3596                     s->cbp_table[xy]|= cbpy<<2;
3597                     s->current_picture.mb_type[xy] |= ac_pred*MB_TYPE_ACPRED;
3598                     s->pred_dir_table[xy]= dir;
3599                 }else if(IS_SKIP(s->current_picture.mb_type[xy])){
3600                     s->current_picture.qscale_table[xy]= s->qscale;
3601                     s->cbp_table[xy]= 0;
3602                 }else{
3603                     int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3604
3605                     if(cbpy<0){
3606                         av_log(s->avctx, AV_LOG_ERROR, "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
3607                         return -1;
3608                     }
3609
3610                     if(s->cbp_table[xy] & 8) {
3611                         ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
3612                     }
3613                     s->current_picture.qscale_table[xy]= s->qscale;
3614
3615                     s->cbp_table[xy]&= 3; //remove dquant
3616                     s->cbp_table[xy]|= (cbpy^0xf)<<2;
3617                 }
3618             }
3619         }
3620         if(mb_num >= mb_count) return 0;
3621         s->mb_x= 0;
3622     }
3623     return 0;
3624 }
3625
3626 /**
3627  * decodes the first & second partition
3628  * @return <0 if error (and sets error type in the error_status_table)
3629  */
3630 int ff_mpeg4_decode_partitions(MpegEncContext *s)
3631 {
3632     int mb_num;
3633     const int part_a_error= s->pict_type==FF_I_TYPE ? (DC_ERROR|MV_ERROR) : MV_ERROR;
3634     const int part_a_end  = s->pict_type==FF_I_TYPE ? (DC_END  |MV_END)   : MV_END;
3635
3636     mb_num= mpeg4_decode_partition_a(s);
3637     if(mb_num<0){
3638         ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error);
3639         return -1;
3640     }
3641
3642     if(s->resync_mb_x + s->resync_mb_y*s->mb_width + mb_num > s->mb_num){
3643         av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n");
3644         ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error);
3645         return -1;
3646     }
3647
3648     s->mb_num_left= mb_num;
3649
3650     if(s->pict_type==FF_I_TYPE){
3651         while(show_bits(&s->gb, 9) == 1)
3652             skip_bits(&s->gb, 9);
3653         if(get_bits_long(&s->gb, 19)!=DC_MARKER){
3654             av_log(s->avctx, AV_LOG_ERROR, "marker missing after first I partition at %d %d\n", s->mb_x, s->mb_y);
3655             return -1;
3656         }
3657     }else{
3658         while(show_bits(&s->gb, 10) == 1)
3659             skip_bits(&s->gb, 10);
3660         if(get_bits(&s->gb, 17)!=MOTION_MARKER){
3661             av_log(s->avctx, AV_LOG_ERROR, "marker missing after first P partition at %d %d\n", s->mb_x, s->mb_y);
3662             return -1;
3663         }
3664     }
3665     ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, part_a_end);
3666
3667     if( mpeg4_decode_partition_b(s, mb_num) < 0){
3668         if(s->pict_type==FF_P_TYPE)
3669             ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, DC_ERROR);
3670         return -1;
3671     }else{
3672         if(s->pict_type==FF_P_TYPE)
3673             ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, DC_END);
3674     }
3675
3676     return 0;
3677 }
3678
3679 /**
3680  * decode partition C of one MB.
3681  * @return <0 if an error occurred
3682  */
3683 static int mpeg4_decode_partitioned_mb(MpegEncContext *s, DCTELEM block[6][64])
3684 {
3685     int cbp, mb_type;
3686     const int xy= s->mb_x + s->mb_y*s->mb_stride;
3687
3688     mb_type= s->current_picture.mb_type[xy];
3689     cbp = s->cbp_table[xy];
3690
3691     s->use_intra_dc_vlc= s->qscale < s->intra_dc_threshold;
3692
3693     if(s->current_picture.qscale_table[xy] != s->qscale){
3694         ff_set_qscale(s, s->current_picture.qscale_table[xy] );
3695     }
3696
3697     if (s->pict_type == FF_P_TYPE || s->pict_type==FF_S_TYPE) {
3698         int i;
3699         for(i=0; i<4; i++){
3700             s->mv[0][i][0] = s->current_picture.motion_val[0][ s->block_index[i] ][0];
3701             s->mv[0][i][1] = s->current_picture.motion_val[0][ s->block_index[i] ][1];
3702         }
3703         s->mb_intra = IS_INTRA(mb_type);
3704
3705         if (IS_SKIP(mb_type)) {
3706             /* skip mb */
3707             for(i=0;i<6;i++)
3708                 s->block_last_index[i] = -1;
3709             s->mv_dir = MV_DIR_FORWARD;
3710             s->mv_type = MV_TYPE_16X16;
3711             if(s->pict_type==FF_S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3712                 s->mcsel=1;
3713                 s->mb_skipped = 0;
3714             }else{
3715                 s->mcsel=0;
3716                 s->mb_skipped = 1;
3717             }
3718         }else if(s->mb_intra){
3719             s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
3720         }else if(!s->mb_intra){
3721 //            s->mcsel= 0; //FIXME do we need to init that
3722
3723             s->mv_dir = MV_DIR_FORWARD;
3724             if (IS_8X8(mb_type)) {
3725                 s->mv_type = MV_TYPE_8X8;
3726             } else {
3727                 s->mv_type = MV_TYPE_16X16;
3728             }
3729         }
3730     } else { /* I-Frame */
3731         s->mb_intra = 1;
3732         s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
3733     }
3734
3735     if (!IS_SKIP(mb_type)) {
3736         int i;
3737         s->dsp.clear_blocks(s->block[0]);
3738         /* decode each block */
3739         for (i = 0; i < 6; i++) {
3740             if(mpeg4_decode_block(s, block[i], i, cbp&32, s->mb_intra, s->rvlc) < 0){
3741                 av_log(s->avctx, AV_LOG_ERROR, "texture corrupted at %d %d %d\n", s->mb_x, s->mb_y, s->mb_intra);
3742                 return -1;
3743             }
3744             cbp+=cbp;
3745         }
3746     }
3747
3748     /* per-MB end of slice check */
3749
3750     if(--s->mb_num_left <= 0){
3751         if(mpeg4_is_resync(s))
3752             return SLICE_END;
3753         else
3754             return SLICE_NOEND;
3755     }else{
3756         if(mpeg4_is_resync(s)){
3757             const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
3758             if(s->cbp_table[xy+delta])
3759                 return SLICE_END;
3760         }
3761         return SLICE_OK;
3762     }
3763 }
3764
3765 /**
3766  * read the next MVs for OBMC. yes this is a ugly hack, feel free to send a patch :)
3767  */
3768 static void preview_obmc(MpegEncContext *s){
3769     GetBitContext gb= s->gb;
3770
3771     int cbpc, i, pred_x, pred_y, mx, my;
3772     int16_t *mot_val;
3773     const int xy= s->mb_x + 1 + s->mb_y * s->mb_stride;
3774     const int stride= s->b8_stride*2;
3775
3776     for(i=0; i<4; i++)
3777         s->block_index[i]+= 2;
3778     for(i=4; i<6; i++)
3779         s->block_index[i]+= 1;
3780     s->mb_x++;
3781
3782     assert(s->pict_type == FF_P_TYPE);
3783
3784     do{
3785         if (get_bits1(&s->gb)) {
3786             /* skip mb */
3787             mot_val = s->current_picture.motion_val[0][ s->block_index[0] ];
3788             mot_val[0       ]= mot_val[2       ]=
3789             mot_val[0+stride]= mot_val[2+stride]= 0;
3790             mot_val[1       ]= mot_val[3       ]=
3791             mot_val[1+stride]= mot_val[3+stride]= 0;
3792
3793             s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
3794             goto end;
3795         }
3796         cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
3797     }while(cbpc == 20);
3798
3799     if(cbpc & 4){
3800         s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
3801     }else{
3802         get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3803         if (cbpc & 8) {
3804             if(s->modified_quant){
3805                 if(get_bits1(&s->gb)) skip_bits(&s->gb, 1);
3806                 else                  skip_bits(&s->gb, 5);
3807             }else
3808                 skip_bits(&s->gb, 2);
3809         }
3810
3811         if ((cbpc & 16) == 0) {
3812                 s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0;
3813                 /* 16x16 motion prediction */
3814                 mot_val= h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
3815                 if (s->umvplus)
3816                    mx = h263p_decode_umotion(s, pred_x);
3817                 else
3818                    mx = h263_decode_motion(s, pred_x, 1);
3819
3820                 if (s->umvplus)
3821                    my = h263p_decode_umotion(s, pred_y);
3822                 else
3823                    my = h263_decode_motion(s, pred_y, 1);
3824
3825                 mot_val[0       ]= mot_val[2       ]=
3826                 mot_val[0+stride]= mot_val[2+stride]= mx;
3827                 mot_val[1       ]= mot_val[3       ]=
3828                 mot_val[1+stride]= mot_val[3+stride]= my;
3829         } else {
3830             s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0;
3831             for(i=0;i<4;i++) {
3832                 mot_val = h263_pred_motion(s, i, 0, &pred_x, &pred_y);
3833                 if (s->umvplus)
3834                   mx = h263p_decode_umotion(s, pred_x);
3835                 else
3836                   mx = h263_decode_motion(s, pred_x, 1);
3837
3838                 if (s->umvplus)
3839                   my = h263p_decode_umotion(s, pred_y);
3840                 else
3841                   my = h263_decode_motion(s, pred_y, 1);
3842                 if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
3843                   skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
3844                 mot_val[0] = mx;
3845                 mot_val[1] = my;
3846             }
3847         }
3848     }
3849 end:
3850
3851     for(i=0; i<4; i++)
3852         s->block_index[i]-= 2;
3853     for(i=4; i<6; i++)
3854         s->block_index[i]-= 1;
3855     s->mb_x--;
3856
3857     s->gb= gb;
3858 }
3859
3860 static void h263_decode_dquant(MpegEncContext *s){
3861     static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
3862
3863     if(s->modified_quant){
3864         if(get_bits1(&s->gb))
3865             s->qscale= modified_quant_tab[get_bits1(&s->gb)][ s->qscale ];
3866         else
3867             s->qscale= get_bits(&s->gb, 5);
3868     }else
3869         s->qscale += quant_tab[get_bits(&s->gb, 2)];
3870     ff_set_qscale(s, s->qscale);
3871 }
3872
3873 static int h263_skip_b_part(MpegEncContext *s, int cbp)
3874 {
3875     DECLARE_ALIGNED(16, DCTELEM, dblock[64]);
3876     int i, mbi;
3877
3878     /* we have to set s->mb_intra to zero to decode B-part of PB-frame correctly
3879      * but real value should be restored in order to be used later (in OBMC condition)
3880      */
3881     mbi = s->mb_intra;
3882     s->mb_intra = 0;
3883     for (i = 0; i < 6; i++) {
3884         if (h263_decode_block(s, dblock, i, cbp&32) < 0)
3885             return -1;
3886         cbp+=cbp;
3887     }
3888     s->mb_intra = mbi;
3889     return 0;
3890 }
3891
3892 static int h263_get_modb(GetBitContext *gb, int pb_frame, int *cbpb)
3893 {
3894     int c, mv = 1;
3895
3896     if (pb_frame < 3) { // h.263 Annex G and i263 PB-frame
3897         c = get_bits1(gb);
3898         if (pb_frame == 2 && c)
3899             mv = !get_bits1(gb);
3900     } else { // h.263 Annex M improved PB-frame
3901         mv = get_unary(gb, 0, 4) + 1;
3902         c = mv & 1;
3903         mv = !!(mv & 2);
3904     }
3905     if(c)
3906         *cbpb = get_bits(gb, 6);
3907     return mv;
3908 }
3909
3910 int ff_h263_decode_mb(MpegEncContext *s,
3911                       DCTELEM block[6][64])
3912 {
3913     int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
3914     int16_t *mot_val;
3915     const int xy= s->mb_x + s->mb_y * s->mb_stride;
3916     int cbpb = 0, pb_mv_count = 0;
3917
3918     assert(!s->h263_pred);
3919
3920     if (s->pict_type == FF_P_TYPE) {
3921         do{
3922             if (get_bits1(&s->gb)) {
3923                 /* skip mb */
3924                 s->mb_intra = 0;
3925                 for(i=0;i<6;i++)
3926                     s->block_last_index[i] = -1;
3927                 s->mv_dir = MV_DIR_FORWARD;
3928                 s->mv_type = MV_TYPE_16X16;
3929                 s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
3930                 s->mv[0][0][0] = 0;
3931                 s->mv[0][0][1] = 0;
3932                 s->mb_skipped = !(s->obmc | s->loop_filter);
3933                 goto end;
3934             }
3935             cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
3936             if (cbpc < 0){
3937                 av_log(s->avctx, AV_LOG_ERROR, "cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
3938                 return -1;
3939             }
3940         }while(cbpc == 20);
3941
3942         s->dsp.clear_blocks(s->block[0]);
3943
3944         dquant = cbpc & 8;
3945         s->mb_intra = ((cbpc & 4) != 0);
3946         if (s->mb_intra) goto intra;
3947
3948         if(s->pb_frame && get_bits1(&s->gb))
3949             pb_mv_count = h263_get_modb(&s->gb, s->pb_frame, &cbpb);
3950         cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3951
3952         if(s->alt_inter_vlc==0 || (cbpc & 3)!=3)
3953             cbpy ^= 0xF;
3954
3955         cbp = (cbpc & 3) | (cbpy << 2);
3956         if (dquant) {
3957             h263_decode_dquant(s);
3958         }
3959
3960         s->mv_dir = MV_DIR_FORWARD;
3961         if ((cbpc & 16) == 0) {
3962             s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0;
3963             /* 16x16 motion prediction */
3964             s->mv_type = MV_TYPE_16X16;
3965             h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
3966             if (s->umvplus)
3967                mx = h263p_decode_umotion(s, pred_x);
3968             else
3969                mx = h263_decode_motion(s, pred_x, 1);
3970
3971             if (mx >= 0xffff)
3972                 return -1;
3973
3974             if (s->umvplus)
3975                my = h263p_decode_umotion(s, pred_y);
3976             else
3977                my = h263_decode_motion(s, pred_y, 1);
3978
3979             if (my >= 0xffff)
3980                 return -1;
3981             s->mv[0][0][0] = mx;
3982             s->mv[0][0][1] = my;
3983
3984             if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
3985                skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
3986         } else {
3987             s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0;
3988             s->mv_type = MV_TYPE_8X8;
3989             for(i=0;i<4;i++) {
3990                 mot_val = h263_pred_motion(s, i, 0, &pred_x, &pred_y);
3991                 if (s->umvplus)
3992                   mx = h263p_decode_umotion(s, pred_x);
3993                 else
3994                   mx = h263_decode_motion(s, pred_x, 1);
3995                 if (mx >= 0xffff)
3996                     return -1;
3997
3998                 if (s->umvplus)
3999                   my = h263p_decode_umotion(s, pred_y);
4000                 else
4001                   my = h263_decode_motion(s, pred_y, 1);
4002                 if (my >= 0xffff)
4003                     return -1;
4004                 s->mv[0][i][0] = mx;
4005                 s->mv[0][i][1] = my;
4006                 if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
4007                   skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
4008                 mot_val[0] = mx;
4009                 mot_val[1] = my;
4010             }
4011         }
4012     } else if(s->pict_type==FF_B_TYPE) {
4013         int mb_type;
4014         const int stride= s->b8_stride;
4015         int16_t *mot_val0 = s->current_picture.motion_val[0][ 2*(s->mb_x + s->mb_y*stride) ];
4016         int16_t *mot_val1 = s->current_picture.motion_val[1][ 2*(s->mb_x + s->mb_y*stride) ];
4017 //        const int mv_xy= s->mb_x + 1 + s->mb_y * s->mb_stride;
4018
4019         //FIXME ugly
4020         mot_val0[0       ]= mot_val0[2       ]= mot_val0[0+2*stride]= mot_val0[2+2*stride]=
4021         mot_val0[1       ]= mot_val0[3       ]= mot_val0[1+2*stride]= mot_val0[3+2*stride]=
4022         mot_val1[0       ]= mot_val1[2       ]= mot_val1[0+2*stride]= mot_val1[2+2*stride]=
4023         mot_val1[1       ]= mot_val1[3       ]= mot_val1[1+2*stride]= mot_val1[3+2*stride]= 0;
4024
4025         do{
4026             mb_type= get_vlc2(&s->gb, h263_mbtype_b_vlc.table, H263_MBTYPE_B_VLC_BITS, 2);
4027             if (mb_type < 0){
4028                 av_log(s->avctx, AV_LOG_ERROR, "b mb_type damaged at %d %d\n", s->mb_x, s->mb_y);
4029                 return -1;
4030             }
4031
4032             mb_type= h263_mb_type_b_map[ mb_type ];
4033         }while(!mb_type);
4034
4035         s->mb_intra = IS_INTRA(mb_type);
4036         if(HAS_CBP(mb_type)){
4037             s->dsp.clear_blocks(s->block[0]);
4038             cbpc = get_vlc2(&s->gb, cbpc_b_vlc.table, CBPC_B_VLC_BITS, 1);
4039             if(s->mb_intra){
4040                 dquant = IS_QUANT(mb_type);
4041                 goto intra;
4042             }
4043
4044             cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
4045
4046             if (cbpy < 0){
4047                 av_log(s->avctx, AV_LOG_ERROR, "b cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
4048                 return -1;
4049             }
4050
4051             if(s->alt_inter_vlc==0 || (cbpc & 3)!=3)
4052                 cbpy ^= 0xF;
4053
4054             cbp = (cbpc & 3) | (cbpy << 2);
4055         }else
4056             cbp=0;
4057
4058         assert(!s->mb_intra);
4059
4060         if(IS_QUANT(mb_type)){
4061             h263_decode_dquant(s);
4062         }
4063
4064         if(IS_DIRECT(mb_type)){
4065             s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
4066             mb_type |= ff_mpeg4_set_direct_mv(s, 0, 0);
4067         }else{
4068             s->mv_dir = 0;
4069             s->mv_type= MV_TYPE_16X16;
4070 //FIXME UMV
4071
4072             if(USES_LIST(mb_type, 0)){
4073                 int16_t *mot_val= h263_pred_motion(s, 0, 0, &mx, &my);
4074                 s->mv_dir = MV_DIR_FORWARD;
4075
4076                 mx = h263_decode_motion(s, mx, 1);
4077                 my = h263_decode_motion(s, my, 1);
4078
4079                 s->mv[0][0][0] = mx;
4080                 s->mv[0][0][1] = my;
4081                 mot_val[0       ]= mot_val[2       ]= mot_val[0+2*stride]= mot_val[2+2*stride]= mx;
4082                 mot_val[1       ]= mot_val[3       ]= mot_val[1+2*stride]= mot_val[3+2*stride]= my;
4083             }
4084
4085             if(USES_LIST(mb_type, 1)){
4086                 int16_t *mot_val= h263_pred_motion(s, 0, 1, &mx, &my);
4087                 s->mv_dir |= MV_DIR_BACKWARD;
4088
4089                 mx = h263_decode_motion(s, mx, 1);
4090                 my = h263_decode_motion(s, my, 1);
4091
4092                 s->mv[1][0][0] = mx;
4093                 s->mv[1][0][1] = my;
4094                 mot_val[0       ]= mot_val[2       ]= mot_val[0+2*stride]= mot_val[2+2*stride]= mx;
4095                 mot_val[1       ]= mot_val[3       ]= mot_val[1+2*stride]= mot_val[3+2*stride]= my;
4096             }
4097         }
4098
4099         s->current_picture.mb_type[xy]= mb_type;
4100     } else { /* I-Frame */
4101         do{
4102             cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
4103             if (cbpc < 0){
4104                 av_log(s->avctx, AV_LOG_ERROR, "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
4105                 return -1;
4106             }
4107         }while(cbpc == 8);
4108
4109         s->dsp.clear_blocks(s->block[0]);
4110
4111         dquant = cbpc & 4;
4112         s->mb_intra = 1;
4113 intra:
4114         s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
4115         if (s->h263_aic) {
4116             s->ac_pred = get_bits1(&s->gb);
4117             if(s->ac_pred){
4118                 s->current_picture.mb_type[xy]= MB_TYPE_INTRA | MB_TYPE_ACPRED;
4119
4120                 s->h263_aic_dir = get_bits1(&s->gb);
4121             }
4122         }else
4123             s->ac_pred = 0;
4124
4125         if(s->pb_frame && get_bits1(&s->gb))
4126             pb_mv_count = h263_get_modb(&s->gb, s->pb_frame, &cbpb);
4127         cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
4128         if(cbpy<0){
4129             av_log(s->avctx, AV_LOG_ERROR, "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
4130             return -1;
4131         }
4132         cbp = (cbpc & 3) | (cbpy << 2);
4133         if (dquant) {
4134             h263_decode_dquant(s);
4135         }
4136
4137         pb_mv_count += !!s->pb_frame;
4138     }
4139
4140     while(pb_mv_count--){
4141         h263_decode_motion(s, 0, 1);
4142         h263_decode_motion(s, 0, 1);
4143     }
4144
4145     /* decode each block */
4146     for (i = 0; i < 6; i++) {
4147         if (h263_decode_block(s, block[i], i, cbp&32) < 0)
4148             return -1;
4149         cbp+=cbp;
4150     }
4151
4152     if(s->pb_frame && h263_skip_b_part(s, cbpb) < 0)
4153         return -1;
4154     if(s->obmc && !s->mb_intra){
4155         if(s->pict_type == FF_P_TYPE && s->mb_x+1<s->mb_width && s->mb_num_left != 1)
4156             preview_obmc(s);
4157     }
4158 end:
4159
4160         /* per-MB end of slice check */
4161     {
4162         int v= show_bits(&s->gb, 16);
4163
4164         if(get_bits_count(&s->gb) + 16 > s->gb.size_in_bits){
4165             v>>= get_bits_count(&s->gb) + 16 - s->gb.size_in_bits;
4166         }
4167
4168         if(v==0)
4169             return SLICE_END;
4170     }
4171
4172     return SLICE_OK;
4173 }
4174
4175 int ff_mpeg4_decode_mb(MpegEncContext *s,
4176                       DCTELEM block[6][64])
4177 {
4178     int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
4179     int16_t *mot_val;
4180     static int8_t quant_tab[4] = { -1, -2, 1, 2 };
4181     const int xy= s->mb_x + s->mb_y * s->mb_stride;
4182
4183     assert(s->h263_pred);
4184
4185     if (s->pict_type == FF_P_TYPE || s->pict_type==FF_S_TYPE) {
4186         do{
4187             if (get_bits1(&s->gb)) {
4188                 /* skip mb */
4189                 s->mb_intra = 0;
4190                 for(i=0;i<6;i++)
4191                     s->block_last_index[i] = -1;
4192                 s->mv_dir = MV_DIR_FORWARD;
4193                 s->mv_type = MV_TYPE_16X16;
4194                 if(s->pict_type==FF_S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
4195                     s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0;
4196                     s->mcsel=1;
4197                     s->mv[0][0][0]= get_amv(s, 0);
4198                     s->mv[0][0][1]= get_amv(s, 1);
4199
4200                     s->mb_skipped = 0;
4201                 }else{
4202                     s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
4203                     s->mcsel=0;
4204                     s->mv[0][0][0] = 0;
4205                     s->mv[0][0][1] = 0;
4206                     s->mb_skipped = 1;
4207                 }
4208                 goto end;
4209             }
4210             cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
4211             if (cbpc < 0){
4212                 av_log(s->avctx, AV_LOG_ERROR, "cbpc damaged at %d %d\n", s->mb_x, s->mb_y);