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