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