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