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