Update to MPlayer SVN rev 29978 and FFmpeg SVN rev 20757.
[vaapi:challenzhous-mplayer.git] / libavcodec / .svn / text-base / h263.c.svn-base
1 /*
2  * H263/MPEG4 backend for ffmpeg encoder and decoder
3  * Copyright (c) 2000,2001 Fabrice Bellard
4  * H263+ support.
5  * Copyright (c) 2001 Juan J. Sierralta P
6  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
7  *
8  * ac prediction encoding, B-frame support, error resilience, optimizations,
9  * qpel decoding, gmc decoding, interlaced decoding
10  * by Michael Niedermayer <michaelni@gmx.at>
11  *
12  * This file is part of FFmpeg.
13  *
14  * FFmpeg is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU Lesser General Public
16  * License as published by the Free Software Foundation; either
17  * version 2.1 of the License, or (at your option) any later version.
18  *
19  * FFmpeg is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22  * Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public
25  * License along with FFmpeg; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27  */
28
29 /**
30  * @file libavcodec/h263.c
31  * h263/mpeg4 codec.
32  */
33
34 //#define DEBUG
35 #include <limits.h>
36
37 #include "dsputil.h"
38 #include "avcodec.h"
39 #include "mpegvideo.h"
40 #include "h263data.h"
41 #include "mpeg4data.h"
42 #include "mathops.h"
43 #include "unary.h"
44
45 //#undef NDEBUG
46 //#include <assert.h>
47
48 #define INTRA_MCBPC_VLC_BITS 6
49 #define INTER_MCBPC_VLC_BITS 7
50 #define CBPY_VLC_BITS 6
51 #define MV_VLC_BITS 9
52 #define DC_VLC_BITS 9
53 #define SPRITE_TRAJ_VLC_BITS 6
54 #define MB_TYPE_B_VLC_BITS 4
55 #define TEX_VLC_BITS 9
56 #define H263_MBTYPE_B_VLC_BITS 6
57 #define CBPC_B_VLC_BITS 3
58
59 static void h263_encode_block(MpegEncContext * s, DCTELEM * block,
60                               int n);
61 static void h263p_encode_umotion(MpegEncContext * s, int val);
62 static inline void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block,
63                                int n, int dc, uint8_t *scan_table,
64                                PutBitContext *dc_pb, PutBitContext *ac_pb);
65 static int mpeg4_get_block_length(MpegEncContext * s, DCTELEM * block, int n, int intra_dc,
66                                   uint8_t *scan_table);
67
68 static int h263_decode_motion(MpegEncContext * s, int pred, int fcode);
69 static int h263p_decode_umotion(MpegEncContext * s, int pred);
70 static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
71                              int n, int coded);
72 static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr);
73 static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
74                               int n, int coded, int intra, int rvlc);
75
76 static int h263_pred_dc(MpegEncContext * s, int n, int16_t **dc_val_ptr);
77 static void mpeg4_encode_visual_object_header(MpegEncContext * s);
78 static void mpeg4_encode_vol_header(MpegEncContext * s, int vo_number, int vol_number);
79
80 static void mpeg4_decode_sprite_trajectory(MpegEncContext * s, GetBitContext *gb);
81 static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, int level, int *dir_ptr, int encoding);
82
83 #if CONFIG_ENCODERS
84 static uint8_t uni_DCtab_lum_len[512];
85 static uint8_t uni_DCtab_chrom_len[512];
86 static uint16_t uni_DCtab_lum_bits[512];
87 static uint16_t uni_DCtab_chrom_bits[512];
88
89 static uint8_t mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
90 static uint8_t fcode_tab[MAX_MV*2+1];
91 static uint8_t umv_fcode_tab[MAX_MV*2+1];
92
93 static uint32_t uni_mpeg4_intra_rl_bits[64*64*2*2];
94 static uint8_t  uni_mpeg4_intra_rl_len [64*64*2*2];
95 static uint32_t uni_mpeg4_inter_rl_bits[64*64*2*2];
96 static uint8_t  uni_mpeg4_inter_rl_len [64*64*2*2];
97 static uint8_t  uni_h263_intra_aic_rl_len [64*64*2*2];
98 static uint8_t  uni_h263_inter_rl_len [64*64*2*2];
99 //#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128 + (run)*256 + (level))
100 //#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run) + (level)*64)
101 #define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run)*128 + (level))
102
103 /* mpeg4
104 inter
105 max level: 24/6
106 max run: 53/63
107
108 intra
109 max level: 53/16
110 max run: 29/41
111 */
112 #endif
113
114 static uint8_t static_rl_table_store[5][2][2*MAX_RUN + MAX_LEVEL + 3];
115
116 #if 0 //3IV1 is quite rare and it slows things down a tiny bit
117 #define IS_3IV1 s->codec_tag == AV_RL32("3IV1")
118 #else
119 #define IS_3IV1 0
120 #endif
121
122 int h263_get_picture_format(int width, int height)
123 {
124     int format;
125
126     if (width == 128 && height == 96)
127         format = 1;
128     else if (width == 176 && height == 144)
129         format = 2;
130     else if (width == 352 && height == 288)
131         format = 3;
132     else if (width == 704 && height == 576)
133         format = 4;
134     else if (width == 1408 && height == 1152)
135         format = 5;
136     else
137         format = 7;
138     return format;
139 }
140
141 static void show_pict_info(MpegEncContext *s){
142     av_log(s->avctx, AV_LOG_DEBUG, "qp:%d %c size:%d rnd:%d%s%s%s%s%s%s%s%s%s %d/%d\n",
143          s->qscale, av_get_pict_type_char(s->pict_type),
144          s->gb.size_in_bits, 1-s->no_rounding,
145          s->obmc ? " AP" : "",
146          s->umvplus ? " UMV" : "",
147          s->h263_long_vectors ? " LONG" : "",
148          s->h263_plus ? " +" : "",
149          s->h263_aic ? " AIC" : "",
150          s->alt_inter_vlc ? " AIV" : "",
151          s->modified_quant ? " MQ" : "",
152          s->loop_filter ? " LOOP" : "",
153          s->h263_slice_structured ? " SS" : "",
154          s->avctx->time_base.den, s->avctx->time_base.num
155     );
156 }
157
158 #if CONFIG_ENCODERS
159
160 static void aspect_to_info(MpegEncContext * s, AVRational aspect){
161     int i;
162
163     if(aspect.num==0) aspect= (AVRational){1,1};
164
165     for(i=1; i<6; i++){
166         if(av_cmp_q(pixel_aspect[i], aspect) == 0){
167             s->aspect_ratio_info=i;
168             return;
169         }
170     }
171
172     s->aspect_ratio_info= FF_ASPECT_EXTENDED;
173 }
174
175 void ff_flv_encode_picture_header(MpegEncContext * s, int picture_number)
176 {
177       int format;
178
179       align_put_bits(&s->pb);
180
181       put_bits(&s->pb, 17, 1);
182       put_bits(&s->pb, 5, (s->h263_flv-1)); /* 0: h263 escape codes 1: 11-bit escape codes */
183       put_bits(&s->pb, 8, (((int64_t)s->picture_number * 30 * s->avctx->time_base.num) / //FIXME use timestamp
184                            s->avctx->time_base.den) & 0xff); /* TemporalReference */
185       if (s->width == 352 && s->height == 288)
186         format = 2;
187       else if (s->width == 176 && s->height == 144)
188         format = 3;
189       else if (s->width == 128 && s->height == 96)
190         format = 4;
191       else if (s->width == 320 && s->height == 240)
192         format = 5;
193       else if (s->width == 160 && s->height == 120)
194         format = 6;
195       else if (s->width <= 255 && s->height <= 255)
196         format = 0; /* use 1 byte width & height */
197       else
198         format = 1; /* use 2 bytes width & height */
199       put_bits(&s->pb, 3, format); /* PictureSize */
200       if (format == 0) {
201         put_bits(&s->pb, 8, s->width);
202         put_bits(&s->pb, 8, s->height);
203       } else if (format == 1) {
204         put_bits(&s->pb, 16, s->width);
205         put_bits(&s->pb, 16, s->height);
206       }
207       put_bits(&s->pb, 2, s->pict_type == FF_P_TYPE); /* PictureType */
208       put_bits(&s->pb, 1, 1); /* DeblockingFlag: on */
209       put_bits(&s->pb, 5, s->qscale); /* Quantizer */
210       put_bits(&s->pb, 1, 0); /* ExtraInformation */
211
212       if(s->h263_aic){
213         s->y_dc_scale_table=
214           s->c_dc_scale_table= ff_aic_dc_scale_table;
215       }else{
216         s->y_dc_scale_table=
217           s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
218       }
219 }
220
221 void h263_encode_picture_header(MpegEncContext * s, int picture_number)
222 {
223     int format, coded_frame_rate, coded_frame_rate_base, i, temp_ref;
224     int best_clock_code=1;
225     int best_divisor=60;
226     int best_error= INT_MAX;
227
228     if(s->h263_plus){
229         for(i=0; i<2; i++){
230             int div, error;
231             div= (s->avctx->time_base.num*1800000LL + 500LL*s->avctx->time_base.den) / ((1000LL+i)*s->avctx->time_base.den);
232             div= av_clip(div, 1, 127);
233             error= FFABS(s->avctx->time_base.num*1800000LL - (1000LL+i)*s->avctx->time_base.den*div);
234             if(error < best_error){
235                 best_error= error;
236                 best_divisor= div;
237                 best_clock_code= i;
238             }
239         }
240     }
241     s->custom_pcf= best_clock_code!=1 || best_divisor!=60;
242     coded_frame_rate= 1800000;
243     coded_frame_rate_base= (1000+best_clock_code)*best_divisor;
244
245     align_put_bits(&s->pb);
246
247     /* Update the pointer to last GOB */
248     s->ptr_lastgob = put_bits_ptr(&s->pb);
249     put_bits(&s->pb, 22, 0x20); /* PSC */
250     temp_ref= s->picture_number * (int64_t)coded_frame_rate * s->avctx->time_base.num / //FIXME use timestamp
251                          (coded_frame_rate_base * (int64_t)s->avctx->time_base.den);
252     put_sbits(&s->pb, 8, temp_ref); /* TemporalReference */
253
254     put_bits(&s->pb, 1, 1);     /* marker */
255     put_bits(&s->pb, 1, 0);     /* h263 id */
256     put_bits(&s->pb, 1, 0);     /* split screen off */
257     put_bits(&s->pb, 1, 0);     /* camera  off */
258     put_bits(&s->pb, 1, 0);     /* freeze picture release off */
259
260     format = h263_get_picture_format(s->width, s->height);
261     if (!s->h263_plus) {
262         /* H.263v1 */
263         put_bits(&s->pb, 3, format);
264         put_bits(&s->pb, 1, (s->pict_type == FF_P_TYPE));
265         /* By now UMV IS DISABLED ON H.263v1, since the restrictions
266         of H.263v1 UMV implies to check the predicted MV after
267         calculation of the current MB to see if we're on the limits */
268         put_bits(&s->pb, 1, 0);         /* Unrestricted Motion Vector: off */
269         put_bits(&s->pb, 1, 0);         /* SAC: off */
270         put_bits(&s->pb, 1, s->obmc);   /* Advanced Prediction */
271         put_bits(&s->pb, 1, 0);         /* only I/P frames, no PB frame */
272         put_bits(&s->pb, 5, s->qscale);
273         put_bits(&s->pb, 1, 0);         /* Continuous Presence Multipoint mode: off */
274     } else {
275         int ufep=1;
276         /* H.263v2 */
277         /* H.263 Plus PTYPE */
278
279         put_bits(&s->pb, 3, 7);
280         put_bits(&s->pb,3,ufep); /* Update Full Extended PTYPE */
281         if (format == 7)
282             put_bits(&s->pb,3,6); /* Custom Source Format */
283         else
284             put_bits(&s->pb, 3, format);
285
286         put_bits(&s->pb,1, s->custom_pcf);
287         put_bits(&s->pb,1, s->umvplus); /* Unrestricted Motion Vector */
288         put_bits(&s->pb,1,0); /* SAC: off */
289         put_bits(&s->pb,1,s->obmc); /* Advanced Prediction Mode */
290         put_bits(&s->pb,1,s->h263_aic); /* Advanced Intra Coding */
291         put_bits(&s->pb,1,s->loop_filter); /* Deblocking Filter */
292         put_bits(&s->pb,1,s->h263_slice_structured); /* Slice Structured */
293         put_bits(&s->pb,1,0); /* Reference Picture Selection: off */
294         put_bits(&s->pb,1,0); /* Independent Segment Decoding: off */
295         put_bits(&s->pb,1,s->alt_inter_vlc); /* Alternative Inter VLC */
296         put_bits(&s->pb,1,s->modified_quant); /* Modified Quantization: */
297         put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
298         put_bits(&s->pb,3,0); /* Reserved */
299
300         put_bits(&s->pb, 3, s->pict_type == FF_P_TYPE);
301
302         put_bits(&s->pb,1,0); /* Reference Picture Resampling: off */
303         put_bits(&s->pb,1,0); /* Reduced-Resolution Update: off */
304         put_bits(&s->pb,1,s->no_rounding); /* Rounding Type */
305         put_bits(&s->pb,2,0); /* Reserved */
306         put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
307
308         /* This should be here if PLUSPTYPE */
309         put_bits(&s->pb, 1, 0); /* Continuous Presence Multipoint mode: off */
310
311                 if (format == 7) {
312             /* Custom Picture Format (CPFMT) */
313             aspect_to_info(s, s->avctx->sample_aspect_ratio);
314
315             put_bits(&s->pb,4,s->aspect_ratio_info);
316             put_bits(&s->pb,9,(s->width >> 2) - 1);
317             put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
318             put_bits(&s->pb,9,(s->height >> 2));
319             if (s->aspect_ratio_info == FF_ASPECT_EXTENDED){
320                 put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.num);
321                 put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.den);
322             }
323         }
324         if(s->custom_pcf){
325             if(ufep){
326                 put_bits(&s->pb, 1, best_clock_code);
327                 put_bits(&s->pb, 7, best_divisor);
328             }
329             put_sbits(&s->pb, 2, temp_ref>>8);
330         }
331
332         /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
333         if (s->umvplus)
334 //            put_bits(&s->pb,1,1); /* Limited according tables of Annex D */
335 //FIXME check actual requested range
336             put_bits(&s->pb,2,1); /* unlimited */
337         if(s->h263_slice_structured)
338             put_bits(&s->pb,2,0); /* no weird submodes */
339
340         put_bits(&s->pb, 5, s->qscale);
341     }
342
343     put_bits(&s->pb, 1, 0);     /* no PEI */
344
345     if(s->h263_slice_structured){
346         put_bits(&s->pb, 1, 1);
347
348         assert(s->mb_x == 0 && s->mb_y == 0);
349         ff_h263_encode_mba(s);
350
351         put_bits(&s->pb, 1, 1);
352     }
353
354     if(s->h263_aic){
355          s->y_dc_scale_table=
356          s->c_dc_scale_table= ff_aic_dc_scale_table;
357     }else{
358         s->y_dc_scale_table=
359         s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
360     }
361 }
362
363 /**
364  * Encodes a group of blocks header.
365  */
366 void h263_encode_gob_header(MpegEncContext * s, int mb_line)
367 {
368     put_bits(&s->pb, 17, 1); /* GBSC */
369
370     if(s->h263_slice_structured){
371         put_bits(&s->pb, 1, 1);
372
373         ff_h263_encode_mba(s);
374
375         if(s->mb_num > 1583)
376             put_bits(&s->pb, 1, 1);
377         put_bits(&s->pb, 5, s->qscale); /* GQUANT */
378         put_bits(&s->pb, 1, 1);
379         put_bits(&s->pb, 2, s->pict_type == FF_I_TYPE); /* GFID */
380     }else{
381         int gob_number= mb_line / s->gob_index;
382
383         put_bits(&s->pb, 5, gob_number); /* GN */
384         put_bits(&s->pb, 2, s->pict_type == FF_I_TYPE); /* GFID */
385         put_bits(&s->pb, 5, s->qscale); /* GQUANT */
386     }
387 }
388
389 static inline int get_block_rate(MpegEncContext * s, DCTELEM block[64], int block_last_index, uint8_t scantable[64]){
390     int last=0;
391     int j;
392     int rate=0;
393
394     for(j=1; j<=block_last_index; j++){
395         const int index= scantable[j];
396         int level= block[index];
397         if(level){
398             level+= 64;
399             if((level&(~127)) == 0){
400                 if(j<block_last_index) rate+= s->intra_ac_vlc_length     [UNI_AC_ENC_INDEX(j-last-1, level)];
401                 else                   rate+= s->intra_ac_vlc_last_length[UNI_AC_ENC_INDEX(j-last-1, level)];
402             }else
403                 rate += s->ac_esc_length;
404
405             last= j;
406         }
407     }
408
409     return rate;
410 }
411
412 static inline int decide_ac_pred(MpegEncContext * s, DCTELEM block[6][64], int dir[6], uint8_t *st[6], int zigzag_last_index[6])
413 {
414     int score= 0;
415     int i, n;
416     int8_t * const qscale_table= s->current_picture.qscale_table;
417
418     memcpy(zigzag_last_index, s->block_last_index, sizeof(int)*6);
419
420     for(n=0; n<6; n++){
421         int16_t *ac_val, *ac_val1;
422
423         score -= get_block_rate(s, block[n], s->block_last_index[n], s->intra_scantable.permutated);
424
425         ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
426         ac_val1= ac_val;
427         if(dir[n]){
428             const int xy= s->mb_x + s->mb_y*s->mb_stride - s->mb_stride;
429             /* top prediction */
430             ac_val-= s->block_wrap[n]*16;
431             if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
432                 /* same qscale */
433                 for(i=1; i<8; i++){
434                     const int level= block[n][s->dsp.idct_permutation[i   ]];
435                     block[n][s->dsp.idct_permutation[i   ]] = level - ac_val[i+8];
436                     ac_val1[i  ]=    block[n][s->dsp.idct_permutation[i<<3]];
437                     ac_val1[i+8]= level;
438                 }
439             }else{
440                 /* different qscale, we must rescale */
441                 for(i=1; i<8; i++){
442                     const int level= block[n][s->dsp.idct_permutation[i   ]];
443                     block[n][s->dsp.idct_permutation[i   ]] = level - ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale);
444                     ac_val1[i  ]=    block[n][s->dsp.idct_permutation[i<<3]];
445                     ac_val1[i+8]= level;
446                 }
447             }
448             st[n]= s->intra_h_scantable.permutated;
449         }else{
450             const int xy= s->mb_x-1 + s->mb_y*s->mb_stride;
451             /* left prediction */
452             ac_val-= 16;
453             if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
454                 /* same qscale */
455                 for(i=1; i<8; i++){
456                     const int level= block[n][s->dsp.idct_permutation[i<<3]];
457                     block[n][s->dsp.idct_permutation[i<<3]]= level - ac_val[i];
458                     ac_val1[i  ]= level;
459                     ac_val1[i+8]=    block[n][s->dsp.idct_permutation[i   ]];
460                 }
461             }else{
462                 /* different qscale, we must rescale */
463                 for(i=1; i<8; i++){
464                     const int level= block[n][s->dsp.idct_permutation[i<<3]];
465                     block[n][s->dsp.idct_permutation[i<<3]]= level - ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale);
466                     ac_val1[i  ]= level;
467                     ac_val1[i+8]=    block[n][s->dsp.idct_permutation[i   ]];
468                 }
469             }
470             st[n]= s->intra_v_scantable.permutated;
471         }
472
473         for(i=63; i>0; i--) //FIXME optimize
474             if(block[n][ st[n][i] ]) break;
475         s->block_last_index[n]= i;
476
477         score += get_block_rate(s, block[n], s->block_last_index[n], st[n]);
478     }
479
480     return score < 0;
481 }
482
483 static inline void restore_ac_coeffs(MpegEncContext * s, DCTELEM block[6][64], int dir[6], uint8_t *st[6], int zigzag_last_index[6])
484 {
485     int i, n;
486     memcpy(s->block_last_index, zigzag_last_index, sizeof(int)*6);
487
488     for(n=0; n<6; n++){
489         int16_t *ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
490
491         st[n]= s->intra_scantable.permutated;
492         if(dir[n]){
493             /* top prediction */
494             for(i=1; i<8; i++){
495                 block[n][s->dsp.idct_permutation[i   ]] = ac_val[i+8];
496             }
497         }else{
498             /* left prediction */
499             for(i=1; i<8; i++){
500                 block[n][s->dsp.idct_permutation[i<<3]]= ac_val[i  ];
501             }
502         }
503     }
504 }
505
506 /**
507  * modify qscale so that encoding is acually possible in h263 (limit difference to -2..2)
508  */
509 void ff_clean_h263_qscales(MpegEncContext *s){
510     int i;
511     int8_t * const qscale_table= s->current_picture.qscale_table;
512
513     ff_init_qscale_tab(s);
514
515     for(i=1; i<s->mb_num; i++){
516         if(qscale_table[ s->mb_index2xy[i] ] - qscale_table[ s->mb_index2xy[i-1] ] >2)
517             qscale_table[ s->mb_index2xy[i] ]= qscale_table[ s->mb_index2xy[i-1] ]+2;
518     }
519     for(i=s->mb_num-2; i>=0; i--){
520         if(qscale_table[ s->mb_index2xy[i] ] - qscale_table[ s->mb_index2xy[i+1] ] >2)
521             qscale_table[ s->mb_index2xy[i] ]= qscale_table[ s->mb_index2xy[i+1] ]+2;
522     }
523
524     if(s->codec_id != CODEC_ID_H263P){
525         for(i=1; i<s->mb_num; i++){
526             int mb_xy= s->mb_index2xy[i];
527
528             if(qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i-1]] && (s->mb_type[mb_xy]&CANDIDATE_MB_TYPE_INTER4V)){
529                 s->mb_type[mb_xy]|= CANDIDATE_MB_TYPE_INTER;
530             }
531         }
532     }
533 }
534
535 /**
536  * modify mb_type & qscale so that encoding is acually possible in mpeg4
537  */
538 void ff_clean_mpeg4_qscales(MpegEncContext *s){
539     int i;
540     int8_t * const qscale_table= s->current_picture.qscale_table;
541
542     ff_clean_h263_qscales(s);
543
544     if(s->pict_type== FF_B_TYPE){
545         int odd=0;
546         /* ok, come on, this isn't funny anymore, there's more code for handling this mpeg4 mess than for the actual adaptive quantization */
547
548         for(i=0; i<s->mb_num; i++){
549             int mb_xy= s->mb_index2xy[i];
550             odd += qscale_table[mb_xy]&1;
551         }
552
553         if(2*odd > s->mb_num) odd=1;
554         else                  odd=0;
555
556         for(i=0; i<s->mb_num; i++){
557             int mb_xy= s->mb_index2xy[i];
558             if((qscale_table[mb_xy]&1) != odd)
559                 qscale_table[mb_xy]++;
560             if(qscale_table[mb_xy] > 31)
561                 qscale_table[mb_xy]= 31;
562         }
563
564         for(i=1; i<s->mb_num; i++){
565             int mb_xy= s->mb_index2xy[i];
566             if(qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i-1]] && (s->mb_type[mb_xy]&CANDIDATE_MB_TYPE_DIRECT)){
567                 s->mb_type[mb_xy]|= CANDIDATE_MB_TYPE_BIDIR;
568             }
569         }
570     }
571 }
572
573 #endif //CONFIG_ENCODERS
574
575 #define tab_size ((signed)FF_ARRAY_ELEMS(s->direct_scale_mv[0]))
576 #define tab_bias (tab_size/2)
577
578 void ff_mpeg4_init_direct_mv(MpegEncContext *s){
579     int i;
580     for(i=0; i<tab_size; i++){
581         s->direct_scale_mv[0][i] = (i-tab_bias)*s->pb_time/s->pp_time;
582         s->direct_scale_mv[1][i] = (i-tab_bias)*(s->pb_time-s->pp_time)/s->pp_time;
583     }
584 }
585
586 static inline void ff_mpeg4_set_one_direct_mv(MpegEncContext *s, int mx, int my, int i){
587     int xy= s->block_index[i];
588     uint16_t time_pp= s->pp_time;
589     uint16_t time_pb= s->pb_time;
590     int p_mx, p_my;
591
592     p_mx= s->next_picture.motion_val[0][xy][0];
593     if((unsigned)(p_mx + tab_bias) < tab_size){
594         s->mv[0][i][0] = s->direct_scale_mv[0][p_mx + tab_bias] + mx;
595         s->mv[1][i][0] = mx ? s->mv[0][i][0] - p_mx
596                             : s->direct_scale_mv[1][p_mx + tab_bias];
597     }else{
598         s->mv[0][i][0] = p_mx*time_pb/time_pp + mx;
599         s->mv[1][i][0] = mx ? s->mv[0][i][0] - p_mx
600                             : p_mx*(time_pb - time_pp)/time_pp;
601     }
602     p_my= s->next_picture.motion_val[0][xy][1];
603     if((unsigned)(p_my + tab_bias) < tab_size){
604         s->mv[0][i][1] = s->direct_scale_mv[0][p_my + tab_bias] + my;
605         s->mv[1][i][1] = my ? s->mv[0][i][1] - p_my
606                             : s->direct_scale_mv[1][p_my + tab_bias];
607     }else{
608         s->mv[0][i][1] = p_my*time_pb/time_pp + my;
609         s->mv[1][i][1] = my ? s->mv[0][i][1] - p_my
610                             : p_my*(time_pb - time_pp)/time_pp;
611     }
612 }
613
614 #undef tab_size
615 #undef tab_bias
616
617 /**
618  *
619  * @return the mb_type
620  */
621 int ff_mpeg4_set_direct_mv(MpegEncContext *s, int mx, int my){
622     const int mb_index= s->mb_x + s->mb_y*s->mb_stride;
623     const int colocated_mb_type= s->next_picture.mb_type[mb_index];
624     uint16_t time_pp;
625     uint16_t time_pb;
626     int i;
627
628     //FIXME avoid divides
629     // try special case with shifts for 1 and 3 B-frames?
630
631     if(IS_8X8(colocated_mb_type)){
632         s->mv_type = MV_TYPE_8X8;
633         for(i=0; i<4; i++){
634             ff_mpeg4_set_one_direct_mv(s, mx, my, i);
635         }
636         return MB_TYPE_DIRECT2 | MB_TYPE_8x8 | MB_TYPE_L0L1;
637     } else if(IS_INTERLACED(colocated_mb_type)){
638         s->mv_type = MV_TYPE_FIELD;
639         for(i=0; i<2; i++){
640             int field_select= s->next_picture.ref_index[0][s->block_index[2*i]];
641             s->field_select[0][i]= field_select;
642             s->field_select[1][i]= i;
643             if(s->top_field_first){
644                 time_pp= s->pp_field_time - field_select + i;
645                 time_pb= s->pb_field_time - field_select + i;
646             }else{
647                 time_pp= s->pp_field_time + field_select - i;
648                 time_pb= s->pb_field_time + field_select - i;
649             }
650             s->mv[0][i][0] = s->p_field_mv_table[i][0][mb_index][0]*time_pb/time_pp + mx;
651             s->mv[0][i][1] = s->p_field_mv_table[i][0][mb_index][1]*time_pb/time_pp + my;
652             s->mv[1][i][0] = mx ? s->mv[0][i][0] - s->p_field_mv_table[i][0][mb_index][0]
653                                 : s->p_field_mv_table[i][0][mb_index][0]*(time_pb - time_pp)/time_pp;
654             s->mv[1][i][1] = my ? s->mv[0][i][1] - s->p_field_mv_table[i][0][mb_index][1]
655                                 : s->p_field_mv_table[i][0][mb_index][1]*(time_pb - time_pp)/time_pp;
656         }
657         return MB_TYPE_DIRECT2 | MB_TYPE_16x8 | MB_TYPE_L0L1 | MB_TYPE_INTERLACED;
658     }else{
659         ff_mpeg4_set_one_direct_mv(s, mx, my, 0);
660         s->mv[0][1][0] = s->mv[0][2][0] = s->mv[0][3][0] = s->mv[0][0][0];
661         s->mv[0][1][1] = s->mv[0][2][1] = s->mv[0][3][1] = s->mv[0][0][1];
662         s->mv[1][1][0] = s->mv[1][2][0] = s->mv[1][3][0] = s->mv[1][0][0];
663         s->mv[1][1][1] = s->mv[1][2][1] = s->mv[1][3][1] = s->mv[1][0][1];
664         if((s->avctx->workaround_bugs & FF_BUG_DIRECT_BLOCKSIZE) || !s->quarter_sample)
665             s->mv_type= MV_TYPE_16X16;
666         else
667             s->mv_type= MV_TYPE_8X8;
668         return MB_TYPE_DIRECT2 | MB_TYPE_16x16 | MB_TYPE_L0L1; //Note see prev line
669     }
670 }
671
672 void ff_h263_update_motion_val(MpegEncContext * s){
673     const int mb_xy = s->mb_y * s->mb_stride + s->mb_x;
674                //FIXME a lot of that is only needed for !low_delay
675     const int wrap = s->b8_stride;
676     const int xy = s->block_index[0];
677
678     s->current_picture.mbskip_table[mb_xy]= s->mb_skipped;
679
680     if(s->mv_type != MV_TYPE_8X8){
681         int motion_x, motion_y;
682         if (s->mb_intra) {
683             motion_x = 0;
684             motion_y = 0;
685         } else if (s->mv_type == MV_TYPE_16X16) {
686             motion_x = s->mv[0][0][0];
687             motion_y = s->mv[0][0][1];
688         } else /*if (s->mv_type == MV_TYPE_FIELD)*/ {
689             int i;
690             motion_x = s->mv[0][0][0] + s->mv[0][1][0];
691             motion_y = s->mv[0][0][1] + s->mv[0][1][1];
692             motion_x = (motion_x>>1) | (motion_x&1);
693             for(i=0; i<2; i++){
694                 s->p_field_mv_table[i][0][mb_xy][0]= s->mv[0][i][0];
695                 s->p_field_mv_table[i][0][mb_xy][1]= s->mv[0][i][1];
696             }
697             s->current_picture.ref_index[0][xy           ]=
698             s->current_picture.ref_index[0][xy        + 1]= s->field_select[0][0];
699             s->current_picture.ref_index[0][xy + wrap    ]=
700             s->current_picture.ref_index[0][xy + wrap + 1]= s->field_select[0][1];
701         }
702
703         /* no update if 8X8 because it has been done during parsing */
704         s->current_picture.motion_val[0][xy][0] = motion_x;
705         s->current_picture.motion_val[0][xy][1] = motion_y;
706         s->current_picture.motion_val[0][xy + 1][0] = motion_x;
707         s->current_picture.motion_val[0][xy + 1][1] = motion_y;
708         s->current_picture.motion_val[0][xy + wrap][0] = motion_x;
709         s->current_picture.motion_val[0][xy + wrap][1] = motion_y;
710         s->current_picture.motion_val[0][xy + 1 + wrap][0] = motion_x;
711         s->current_picture.motion_val[0][xy + 1 + wrap][1] = motion_y;
712     }
713
714     if(s->encoding){ //FIXME encoding MUST be cleaned up
715         if (s->mv_type == MV_TYPE_8X8)
716             s->current_picture.mb_type[mb_xy]= MB_TYPE_L0 | MB_TYPE_8x8;
717         else if(s->mb_intra)
718             s->current_picture.mb_type[mb_xy]= MB_TYPE_INTRA;
719         else
720             s->current_picture.mb_type[mb_xy]= MB_TYPE_L0 | MB_TYPE_16x16;
721     }
722 }
723
724 #if CONFIG_ENCODERS
725
726 static inline int h263_get_motion_length(MpegEncContext * s, int val, int f_code){
727     int l, bit_size, code;
728
729     if (val == 0) {
730         return mvtab[0][1];
731     } else {
732         bit_size = f_code - 1;
733         /* modulo encoding */
734         l= INT_BIT - 6 - bit_size;
735         val = (val<<l)>>l;
736         val--;
737         code = (val >> bit_size) + 1;
738
739         return mvtab[code][1] + 1 + bit_size;
740     }
741 }
742
743 static inline void ff_h263_encode_motion_vector(MpegEncContext * s, int x, int y, int f_code){
744     if(s->flags2 & CODEC_FLAG2_NO_OUTPUT){
745         skip_put_bits(&s->pb,
746             h263_get_motion_length(s, x, f_code)
747            +h263_get_motion_length(s, y, f_code));
748     }else{
749         ff_h263_encode_motion(s, x, f_code);
750         ff_h263_encode_motion(s, y, f_code);
751     }
752 }
753
754 static inline int get_p_cbp(MpegEncContext * s,
755                       DCTELEM block[6][64],
756                       int motion_x, int motion_y){
757     int cbp, i;
758
759     if(s->flags & CODEC_FLAG_CBP_RD){
760         int best_cbpy_score= INT_MAX;
761         int best_cbpc_score= INT_MAX;
762         int cbpc = (-1), cbpy= (-1);
763         const int offset= (s->mv_type==MV_TYPE_16X16 ? 0 : 16) + (s->dquant ? 8 : 0);
764         const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
765
766         for(i=0; i<4; i++){
767             int score= inter_MCBPC_bits[i + offset] * lambda;
768             if(i&1) score += s->coded_score[5];
769             if(i&2) score += s->coded_score[4];
770
771             if(score < best_cbpc_score){
772                 best_cbpc_score= score;
773                 cbpc= i;
774             }
775         }
776
777         for(i=0; i<16; i++){
778             int score= cbpy_tab[i ^ 0xF][1] * lambda;
779             if(i&1) score += s->coded_score[3];
780             if(i&2) score += s->coded_score[2];
781             if(i&4) score += s->coded_score[1];
782             if(i&8) score += s->coded_score[0];
783
784             if(score < best_cbpy_score){
785                 best_cbpy_score= score;
786                 cbpy= i;
787             }
788         }
789         cbp= cbpc + 4*cbpy;
790         if ((motion_x | motion_y | s->dquant) == 0 && s->mv_type==MV_TYPE_16X16){
791             if(best_cbpy_score + best_cbpc_score + 2*lambda >= 0)
792                 cbp= 0;
793         }
794
795         for (i = 0; i < 6; i++) {
796             if (s->block_last_index[i] >= 0 && ((cbp >> (5 - i))&1)==0 ){
797                 s->block_last_index[i]= -1;
798                 s->dsp.clear_block(s->block[i]);
799             }
800         }
801     }else{
802         cbp= 0;
803         for (i = 0; i < 6; i++) {
804             if (s->block_last_index[i] >= 0)
805                 cbp |= 1 << (5 - i);
806         }
807     }
808     return cbp;
809 }
810
811 static inline int get_b_cbp(MpegEncContext * s, DCTELEM block[6][64],
812                             int motion_x, int motion_y, int mb_type){
813     int cbp=0, i;
814
815     if(s->flags & CODEC_FLAG_CBP_RD){
816         int score=0;
817         const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
818
819         for(i=0; i<6; i++){
820             if(s->coded_score[i] < 0){
821                 score += s->coded_score[i];
822                 cbp |= 1 << (5 - i);
823             }
824         }
825
826         if(cbp){
827             int zero_score= -6;
828             if ((motion_x | motion_y | s->dquant | mb_type) == 0){
829                 zero_score-= 4; //2*MV + mb_type + cbp bit
830             }
831
832             zero_score*= lambda;
833             if(zero_score <= score){
834                 cbp=0;
835             }
836         }
837
838         for (i = 0; i < 6; i++) {
839             if (s->block_last_index[i] >= 0 && ((cbp >> (5 - i))&1)==0 ){
840                 s->block_last_index[i]= -1;
841                 s->dsp.clear_block(s->block[i]);
842             }
843         }
844     }else{
845         for (i = 0; i < 6; i++) {
846             if (s->block_last_index[i] >= 0)
847                 cbp |= 1 << (5 - i);
848         }
849     }
850     return cbp;
851 }
852
853 static inline void mpeg4_encode_blocks(MpegEncContext * s, DCTELEM block[6][64], int intra_dc[6],
854                                uint8_t **scan_table, PutBitContext *dc_pb, PutBitContext *ac_pb){
855     int i;
856
857     if(scan_table){
858         if(s->flags2 & CODEC_FLAG2_NO_OUTPUT){
859             for (i = 0; i < 6; i++) {
860                 skip_put_bits(&s->pb, mpeg4_get_block_length(s, block[i], i, intra_dc[i], scan_table[i]));
861             }
862         }else{
863             /* encode each block */
864             for (i = 0; i < 6; i++) {
865                 mpeg4_encode_block(s, block[i], i, intra_dc[i], scan_table[i], dc_pb, ac_pb);
866             }
867         }
868     }else{
869         if(s->flags2 & CODEC_FLAG2_NO_OUTPUT){
870             for (i = 0; i < 6; i++) {
871                 skip_put_bits(&s->pb, mpeg4_get_block_length(s, block[i], i, 0, s->intra_scantable.permutated));
872             }
873         }else{
874             /* encode each block */
875             for (i = 0; i < 6; i++) {
876                 mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, dc_pb, ac_pb);
877             }
878         }
879     }
880 }
881
882 static const int dquant_code[5]= {1,0,9,2,3};
883
884 void mpeg4_encode_mb(MpegEncContext * s,
885                     DCTELEM block[6][64],
886                     int motion_x, int motion_y)
887 {
888     int cbpc, cbpy, pred_x, pred_y;
889     PutBitContext * const pb2    = s->data_partitioning                         ? &s->pb2    : &s->pb;
890     PutBitContext * const tex_pb = s->data_partitioning && s->pict_type!=FF_B_TYPE ? &s->tex_pb : &s->pb;
891     PutBitContext * const dc_pb  = s->data_partitioning && s->pict_type!=FF_I_TYPE ? &s->pb2    : &s->pb;
892     const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1) && !s->data_partitioning ? 1 : 0;
893
894     //    printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
895     if (!s->mb_intra) {
896         int i, cbp;
897
898         if(s->pict_type==FF_B_TYPE){
899             static const int mb_type_table[8]= {-1, 3, 2, 1,-1,-1,-1, 0}; /* convert from mv_dir to type */
900             int mb_type=  mb_type_table[s->mv_dir];
901
902             if(s->mb_x==0){
903                 for(i=0; i<2; i++){
904                     s->last_mv[i][0][0]=
905                     s->last_mv[i][0][1]=
906                     s->last_mv[i][1][0]=
907                     s->last_mv[i][1][1]= 0;
908                 }
909             }
910
911             assert(s->dquant>=-2 && s->dquant<=2);
912             assert((s->dquant&1)==0);
913             assert(mb_type>=0);
914
915             /* nothing to do if this MB was skipped in the next P Frame */
916             if(s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]){ //FIXME avoid DCT & ...
917                 s->skip_count++;
918                 s->mv[0][0][0]=
919                 s->mv[0][0][1]=
920                 s->mv[1][0][0]=
921                 s->mv[1][0][1]= 0;
922                 s->mv_dir= MV_DIR_FORWARD; //doesn't matter
923                 s->qscale -= s->dquant;
924 //                s->mb_skipped=1;
925
926                 return;
927             }
928
929             cbp= get_b_cbp(s, block, motion_x, motion_y, mb_type);
930
931             if ((cbp | motion_x | motion_y | mb_type) ==0) {
932                 /* direct MB with MV={0,0} */
933                 assert(s->dquant==0);
934
935                 put_bits(&s->pb, 1, 1); /* mb not coded modb1=1 */
936
937                 if(interleaved_stats){
938                     s->misc_bits++;
939                     s->last_bits++;
940                 }
941                 s->skip_count++;
942                 return;
943             }
944
945             put_bits(&s->pb, 1, 0);     /* mb coded modb1=0 */
946             put_bits(&s->pb, 1, cbp ? 0 : 1); /* modb2 */ //FIXME merge
947             put_bits(&s->pb, mb_type+1, 1); // this table is so simple that we don't need it :)
948             if(cbp) put_bits(&s->pb, 6, cbp);
949
950             if(cbp && mb_type){
951                 if(s->dquant)
952                     put_bits(&s->pb, 2, (s->dquant>>2)+3);
953                 else
954                     put_bits(&s->pb, 1, 0);
955             }else
956                 s->qscale -= s->dquant;
957
958             if(!s->progressive_sequence){
959                 if(cbp)
960                     put_bits(&s->pb, 1, s->interlaced_dct);
961                 if(mb_type) // not direct mode
962                     put_bits(&s->pb, 1, s->mv_type == MV_TYPE_FIELD);
963             }
964
965             if(interleaved_stats){
966                 s->misc_bits+= get_bits_diff(s);
967             }
968
969             if(mb_type == 0){
970                 assert(s->mv_dir & MV_DIRECT);
971                 ff_h263_encode_motion_vector(s, motion_x, motion_y, 1);
972                 s->b_count++;
973                 s->f_count++;
974             }else{
975                 assert(mb_type > 0 && mb_type < 4);
976                 if(s->mv_type != MV_TYPE_FIELD){
977                     if(s->mv_dir & MV_DIR_FORWARD){
978                         ff_h263_encode_motion_vector(s, s->mv[0][0][0] - s->last_mv[0][0][0],
979                                                         s->mv[0][0][1] - s->last_mv[0][0][1], s->f_code);
980                         s->last_mv[0][0][0]= s->last_mv[0][1][0]= s->mv[0][0][0];
981                         s->last_mv[0][0][1]= s->last_mv[0][1][1]= s->mv[0][0][1];
982                         s->f_count++;
983                     }
984                     if(s->mv_dir & MV_DIR_BACKWARD){
985                         ff_h263_encode_motion_vector(s, s->mv[1][0][0] - s->last_mv[1][0][0],
986                                                         s->mv[1][0][1] - s->last_mv[1][0][1], s->b_code);
987                         s->last_mv[1][0][0]= s->last_mv[1][1][0]= s->mv[1][0][0];
988                         s->last_mv[1][0][1]= s->last_mv[1][1][1]= s->mv[1][0][1];
989                         s->b_count++;
990                     }
991                 }else{
992                     if(s->mv_dir & MV_DIR_FORWARD){
993                         put_bits(&s->pb, 1, s->field_select[0][0]);
994                         put_bits(&s->pb, 1, s->field_select[0][1]);
995                     }
996                     if(s->mv_dir & MV_DIR_BACKWARD){
997                         put_bits(&s->pb, 1, s->field_select[1][0]);
998                         put_bits(&s->pb, 1, s->field_select[1][1]);
999                     }
1000                     if(s->mv_dir & MV_DIR_FORWARD){
1001                         for(i=0; i<2; i++){
1002                             ff_h263_encode_motion_vector(s, s->mv[0][i][0] - s->last_mv[0][i][0]  ,
1003                                                             s->mv[0][i][1] - s->last_mv[0][i][1]/2, s->f_code);
1004                             s->last_mv[0][i][0]= s->mv[0][i][0];
1005                             s->last_mv[0][i][1]= s->mv[0][i][1]*2;
1006                         }
1007                         s->f_count++;
1008                     }
1009                     if(s->mv_dir & MV_DIR_BACKWARD){
1010                         for(i=0; i<2; i++){
1011                             ff_h263_encode_motion_vector(s, s->mv[1][i][0] - s->last_mv[1][i][0]  ,
1012                                                             s->mv[1][i][1] - s->last_mv[1][i][1]/2, s->b_code);
1013                             s->last_mv[1][i][0]= s->mv[1][i][0];
1014                             s->last_mv[1][i][1]= s->mv[1][i][1]*2;
1015                         }
1016                         s->b_count++;
1017                     }
1018                 }
1019             }
1020
1021             if(interleaved_stats){
1022                 s->mv_bits+= get_bits_diff(s);
1023             }
1024
1025             mpeg4_encode_blocks(s, block, NULL, NULL, NULL, &s->pb);
1026
1027             if(interleaved_stats){
1028                 s->p_tex_bits+= get_bits_diff(s);
1029             }
1030
1031         }else{ /* s->pict_type==FF_B_TYPE */
1032             cbp= get_p_cbp(s, block, motion_x, motion_y);
1033
1034             if ((cbp | motion_x | motion_y | s->dquant) == 0 && s->mv_type==MV_TYPE_16X16) {
1035                 /* check if the B frames can skip it too, as we must skip it if we skip here
1036                    why didn't they just compress the skip-mb bits instead of reusing them ?! */
1037                 if(s->max_b_frames>0){
1038                     int i;
1039                     int x,y, offset;
1040                     uint8_t *p_pic;
1041
1042                     x= s->mb_x*16;
1043                     y= s->mb_y*16;
1044                     if(x+16 > s->width)  x= s->width-16;
1045                     if(y+16 > s->height) y= s->height-16;
1046
1047                     offset= x + y*s->linesize;
1048                     p_pic= s->new_picture.data[0] + offset;
1049
1050                     s->mb_skipped=1;
1051                     for(i=0; i<s->max_b_frames; i++){
1052                         uint8_t *b_pic;
1053                         int diff;
1054                         Picture *pic= s->reordered_input_picture[i+1];
1055
1056                         if(pic==NULL || pic->pict_type!=FF_B_TYPE) break;
1057
1058                         b_pic= pic->data[0] + offset;
1059                         if(pic->type != FF_BUFFER_TYPE_SHARED)
1060                             b_pic+= INPLACE_OFFSET;
1061                         diff= s->dsp.sad[0](NULL, p_pic, b_pic, s->linesize, 16);
1062                         if(diff>s->qscale*70){ //FIXME check that 70 is optimal
1063                             s->mb_skipped=0;
1064                             break;
1065                         }
1066                     }
1067                 }else
1068                     s->mb_skipped=1;
1069
1070                 if(s->mb_skipped==1){
1071                     /* skip macroblock */
1072                     put_bits(&s->pb, 1, 1);
1073
1074                     if(interleaved_stats){
1075                         s->misc_bits++;
1076                         s->last_bits++;
1077                     }
1078                     s->skip_count++;
1079
1080                     return;
1081                 }
1082             }
1083
1084             put_bits(&s->pb, 1, 0);     /* mb coded */
1085             cbpc = cbp & 3;
1086             cbpy = cbp >> 2;
1087             cbpy ^= 0xf;
1088             if(s->mv_type==MV_TYPE_16X16){
1089                 if(s->dquant) cbpc+= 8;
1090                 put_bits(&s->pb,
1091                         inter_MCBPC_bits[cbpc],
1092                         inter_MCBPC_code[cbpc]);
1093
1094                 put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1095                 if(s->dquant)
1096                     put_bits(pb2, 2, dquant_code[s->dquant+2]);
1097
1098                 if(!s->progressive_sequence){
1099                     if(cbp)
1100                         put_bits(pb2, 1, s->interlaced_dct);
1101                     put_bits(pb2, 1, 0);
1102                 }
1103
1104                 if(interleaved_stats){
1105                     s->misc_bits+= get_bits_diff(s);
1106                 }
1107
1108                 /* motion vectors: 16x16 mode */
1109                 h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1110
1111                 ff_h263_encode_motion_vector(s, motion_x - pred_x,
1112                                                 motion_y - pred_y, s->f_code);
1113             }else if(s->mv_type==MV_TYPE_FIELD){
1114                 if(s->dquant) cbpc+= 8;
1115                 put_bits(&s->pb,
1116                         inter_MCBPC_bits[cbpc],
1117                         inter_MCBPC_code[cbpc]);
1118
1119                 put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1120                 if(s->dquant)
1121                     put_bits(pb2, 2, dquant_code[s->dquant+2]);
1122
1123                 assert(!s->progressive_sequence);
1124                 if(cbp)
1125                     put_bits(pb2, 1, s->interlaced_dct);
1126                 put_bits(pb2, 1, 1);
1127
1128                 if(interleaved_stats){
1129                     s->misc_bits+= get_bits_diff(s);
1130                 }
1131
1132                 /* motion vectors: 16x8 interlaced mode */
1133                 h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1134                 pred_y /=2;
1135
1136                 put_bits(&s->pb, 1, s->field_select[0][0]);
1137                 put_bits(&s->pb, 1, s->field_select[0][1]);
1138
1139                 ff_h263_encode_motion_vector(s, s->mv[0][0][0] - pred_x,
1140                                                 s->mv[0][0][1] - pred_y, s->f_code);
1141                 ff_h263_encode_motion_vector(s, s->mv[0][1][0] - pred_x,
1142                                                 s->mv[0][1][1] - pred_y, s->f_code);
1143             }else{
1144                 assert(s->mv_type==MV_TYPE_8X8);
1145                 put_bits(&s->pb,
1146                         inter_MCBPC_bits[cbpc+16],
1147                         inter_MCBPC_code[cbpc+16]);
1148                 put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1149
1150                 if(!s->progressive_sequence){
1151                     if(cbp)
1152                         put_bits(pb2, 1, s->interlaced_dct);
1153                 }
1154
1155                 if(interleaved_stats){
1156                     s->misc_bits+= get_bits_diff(s);
1157                 }
1158
1159                 for(i=0; i<4; i++){
1160                     /* motion vectors: 8x8 mode*/
1161                     h263_pred_motion(s, i, 0, &pred_x, &pred_y);
1162
1163                     ff_h263_encode_motion_vector(s, s->current_picture.motion_val[0][ s->block_index[i] ][0] - pred_x,
1164                                                     s->current_picture.motion_val[0][ s->block_index[i] ][1] - pred_y, s->f_code);
1165                 }
1166             }
1167
1168             if(interleaved_stats){
1169                 s->mv_bits+= get_bits_diff(s);
1170             }
1171
1172             mpeg4_encode_blocks(s, block, NULL, NULL, NULL, tex_pb);
1173
1174             if(interleaved_stats){
1175                 s->p_tex_bits+= get_bits_diff(s);
1176             }
1177             s->f_count++;
1178         }
1179     } else {
1180         int cbp;
1181         int dc_diff[6];   //dc values with the dc prediction subtracted
1182         int dir[6];  //prediction direction
1183         int zigzag_last_index[6];
1184         uint8_t *scan_table[6];
1185         int i;
1186
1187         for(i=0; i<6; i++){
1188             dc_diff[i]= ff_mpeg4_pred_dc(s, i, block[i][0], &dir[i], 1);
1189         }
1190
1191         if(s->flags & CODEC_FLAG_AC_PRED){
1192             s->ac_pred= decide_ac_pred(s, block, dir, scan_table, zigzag_last_index);
1193             if(!s->ac_pred)
1194                 restore_ac_coeffs(s, block, dir, scan_table, zigzag_last_index);
1195         }else{
1196             for(i=0; i<6; i++)
1197                 scan_table[i]= s->intra_scantable.permutated;
1198         }
1199
1200         /* compute cbp */
1201         cbp = 0;
1202         for (i = 0; i < 6; i++) {
1203             if (s->block_last_index[i] >= 1)
1204                 cbp |= 1 << (5 - i);
1205         }
1206
1207         cbpc = cbp & 3;
1208         if (s->pict_type == FF_I_TYPE) {
1209             if(s->dquant) cbpc+=4;
1210             put_bits(&s->pb,
1211                 intra_MCBPC_bits[cbpc],
1212                 intra_MCBPC_code[cbpc]);
1213         } else {
1214             if(s->dquant) cbpc+=8;
1215             put_bits(&s->pb, 1, 0);     /* mb coded */
1216             put_bits(&s->pb,
1217                 inter_MCBPC_bits[cbpc + 4],
1218                 inter_MCBPC_code[cbpc + 4]);
1219         }
1220         put_bits(pb2, 1, s->ac_pred);
1221         cbpy = cbp >> 2;
1222         put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1223         if(s->dquant)
1224             put_bits(dc_pb, 2, dquant_code[s->dquant+2]);
1225
1226         if(!s->progressive_sequence){
1227             put_bits(dc_pb, 1, s->interlaced_dct);
1228         }
1229
1230         if(interleaved_stats){
1231             s->misc_bits+= get_bits_diff(s);
1232         }
1233
1234         mpeg4_encode_blocks(s, block, dc_diff, scan_table, dc_pb, tex_pb);
1235
1236         if(interleaved_stats){
1237             s->i_tex_bits+= get_bits_diff(s);
1238         }
1239         s->i_count++;
1240
1241         /* restore ac coeffs & last_index stuff if we messed them up with the prediction */
1242         if(s->ac_pred)
1243             restore_ac_coeffs(s, block, dir, scan_table, zigzag_last_index);
1244     }
1245 }
1246
1247 void h263_encode_mb(MpegEncContext * s,
1248                     DCTELEM block[6][64],
1249                     int motion_x, int motion_y)
1250 {
1251     int cbpc, cbpy, i, cbp, pred_x, pred_y;
1252     int16_t pred_dc;
1253     int16_t rec_intradc[6];
1254     int16_t *dc_ptr[6];
1255     const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1);
1256
1257     //printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
1258     if (!s->mb_intra) {
1259         /* compute cbp */
1260         cbp= get_p_cbp(s, block, motion_x, motion_y);
1261
1262         if ((cbp | motion_x | motion_y | s->dquant | (s->mv_type - MV_TYPE_16X16)) == 0) {
1263             /* skip macroblock */
1264             put_bits(&s->pb, 1, 1);
1265             if(interleaved_stats){
1266                 s->misc_bits++;
1267                 s->last_bits++;
1268             }
1269             s->skip_count++;
1270
1271             return;
1272         }
1273         put_bits(&s->pb, 1, 0);         /* mb coded */
1274
1275         cbpc = cbp & 3;
1276         cbpy = cbp >> 2;
1277         if(s->alt_inter_vlc==0 || cbpc!=3)
1278             cbpy ^= 0xF;
1279         if(s->dquant) cbpc+= 8;
1280         if(s->mv_type==MV_TYPE_16X16){
1281             put_bits(&s->pb,
1282                     inter_MCBPC_bits[cbpc],
1283                     inter_MCBPC_code[cbpc]);
1284
1285             put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1286             if(s->dquant)
1287                 put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
1288
1289             if(interleaved_stats){
1290                 s->misc_bits+= get_bits_diff(s);
1291             }
1292
1293             /* motion vectors: 16x16 mode */
1294             h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1295
1296             if (!s->umvplus) {
1297                 ff_h263_encode_motion_vector(s, motion_x - pred_x,
1298                                                 motion_y - pred_y, 1);
1299             }
1300             else {
1301                 h263p_encode_umotion(s, motion_x - pred_x);
1302                 h263p_encode_umotion(s, motion_y - pred_y);
1303                 if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
1304                     /* To prevent Start Code emulation */
1305                     put_bits(&s->pb,1,1);
1306             }
1307         }else{
1308             put_bits(&s->pb,
1309                     inter_MCBPC_bits[cbpc+16],
1310                     inter_MCBPC_code[cbpc+16]);
1311             put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1312             if(s->dquant)
1313                 put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
1314
1315             if(interleaved_stats){
1316                 s->misc_bits+= get_bits_diff(s);
1317             }
1318
1319             for(i=0; i<4; i++){
1320                 /* motion vectors: 8x8 mode*/
1321                 h263_pred_motion(s, i, 0, &pred_x, &pred_y);
1322
1323                 motion_x= s->current_picture.motion_val[0][ s->block_index[i] ][0];
1324                 motion_y= s->current_picture.motion_val[0][ s->block_index[i] ][1];
1325                 if (!s->umvplus) {
1326                     ff_h263_encode_motion_vector(s, motion_x - pred_x,
1327                                                     motion_y - pred_y, 1);
1328                 }
1329                 else {
1330                     h263p_encode_umotion(s, motion_x - pred_x);
1331                     h263p_encode_umotion(s, motion_y - pred_y);
1332                     if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
1333                         /* To prevent Start Code emulation */
1334                         put_bits(&s->pb,1,1);
1335                 }
1336             }
1337         }
1338
1339         if(interleaved_stats){
1340             s->mv_bits+= get_bits_diff(s);
1341         }
1342     } else {
1343         assert(s->mb_intra);
1344
1345         cbp = 0;
1346         if (s->h263_aic) {
1347             /* Predict DC */
1348             for(i=0; i<6; i++) {
1349                 int16_t level = block[i][0];
1350                 int scale;
1351
1352                 if(i<4) scale= s->y_dc_scale;
1353                 else    scale= s->c_dc_scale;
1354
1355                 pred_dc = h263_pred_dc(s, i, &dc_ptr[i]);
1356                 level -= pred_dc;
1357                 /* Quant */
1358                 if (level >= 0)
1359                     level = (level + (scale>>1))/scale;
1360                 else
1361                     level = (level - (scale>>1))/scale;
1362
1363                 /* AIC can change CBP */
1364                 if (level == 0 && s->block_last_index[i] == 0)
1365                     s->block_last_index[i] = -1;
1366
1367                 if(!s->modified_quant){
1368                     if (level < -127)
1369                         level = -127;
1370                     else if (level > 127)
1371                         level = 127;
1372                 }
1373
1374                 block[i][0] = level;
1375                 /* Reconstruction */
1376                 rec_intradc[i] = scale*level + pred_dc;
1377                 /* Oddify */
1378                 rec_intradc[i] |= 1;
1379                 //if ((rec_intradc[i] % 2) == 0)
1380                 //    rec_intradc[i]++;
1381                 /* Clipping */
1382                 if (rec_intradc[i] < 0)
1383                     rec_intradc[i] = 0;
1384                 else if (rec_intradc[i] > 2047)
1385                     rec_intradc[i] = 2047;
1386
1387                 /* Update AC/DC tables */
1388                 *dc_ptr[i] = rec_intradc[i];
1389                 if (s->block_last_index[i] >= 0)
1390                     cbp |= 1 << (5 - i);
1391             }
1392         }else{
1393             for(i=0; i<6; i++) {
1394                 /* compute cbp */
1395                 if (s->block_last_index[i] >= 1)
1396                     cbp |= 1 << (5 - i);
1397             }
1398         }
1399
1400         cbpc = cbp & 3;
1401         if (s->pict_type == FF_I_TYPE) {
1402             if(s->dquant) cbpc+=4;
1403             put_bits(&s->pb,
1404                 intra_MCBPC_bits[cbpc],
1405                 intra_MCBPC_code[cbpc]);
1406         } else {
1407             if(s->dquant) cbpc+=8;
1408             put_bits(&s->pb, 1, 0);     /* mb coded */
1409             put_bits(&s->pb,
1410                 inter_MCBPC_bits[cbpc + 4],
1411                 inter_MCBPC_code[cbpc + 4]);
1412         }
1413         if (s->h263_aic) {
1414             /* XXX: currently, we do not try to use ac prediction */
1415             put_bits(&s->pb, 1, 0);     /* no AC prediction */
1416         }
1417         cbpy = cbp >> 2;
1418         put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
1419         if(s->dquant)
1420             put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
1421
1422         if(interleaved_stats){
1423             s->misc_bits+= get_bits_diff(s);
1424         }
1425     }
1426
1427     for(i=0; i<6; i++) {
1428         /* encode each block */
1429         h263_encode_block(s, block[i], i);
1430
1431         /* Update INTRADC for decoding */
1432         if (s->h263_aic && s->mb_intra) {
1433             block[i][0] = rec_intradc[i];
1434
1435         }
1436     }
1437
1438     if(interleaved_stats){
1439         if (!s->mb_intra) {
1440             s->p_tex_bits+= get_bits_diff(s);
1441             s->f_count++;
1442         }else{
1443             s->i_tex_bits+= get_bits_diff(s);
1444             s->i_count++;
1445         }
1446     }
1447 }
1448 #endif
1449
1450 void ff_h263_loop_filter(MpegEncContext * s){
1451     int qp_c;
1452     const int linesize  = s->linesize;
1453     const int uvlinesize= s->uvlinesize;
1454     const int xy = s->mb_y * s->mb_stride + s->mb_x;
1455     uint8_t *dest_y = s->dest[0];
1456     uint8_t *dest_cb= s->dest[1];
1457     uint8_t *dest_cr= s->dest[2];
1458
1459 //    if(s->pict_type==FF_B_TYPE && !s->readable) return;
1460
1461     /*
1462        Diag Top
1463        Left Center
1464     */
1465     if(!IS_SKIP(s->current_picture.mb_type[xy])){
1466         qp_c= s->qscale;
1467         s->dsp.h263_v_loop_filter(dest_y+8*linesize  , linesize, qp_c);
1468         s->dsp.h263_v_loop_filter(dest_y+8*linesize+8, linesize, qp_c);
1469     }else
1470         qp_c= 0;
1471
1472     if(s->mb_y){
1473         int qp_dt, qp_tt, qp_tc;
1474
1475         if(IS_SKIP(s->current_picture.mb_type[xy-s->mb_stride]))
1476             qp_tt=0;
1477         else
1478             qp_tt= s->current_picture.qscale_table[xy-s->mb_stride];
1479
1480         if(qp_c)
1481             qp_tc= qp_c;
1482         else
1483             qp_tc= qp_tt;
1484
1485         if(qp_tc){
1486             const int chroma_qp= s->chroma_qscale_table[qp_tc];
1487             s->dsp.h263_v_loop_filter(dest_y  ,   linesize, qp_tc);
1488             s->dsp.h263_v_loop_filter(dest_y+8,   linesize, qp_tc);
1489
1490             s->dsp.h263_v_loop_filter(dest_cb , uvlinesize, chroma_qp);
1491             s->dsp.h263_v_loop_filter(dest_cr , uvlinesize, chroma_qp);
1492         }
1493
1494         if(qp_tt)
1495             s->dsp.h263_h_loop_filter(dest_y-8*linesize+8  ,   linesize, qp_tt);
1496
1497         if(s->mb_x){
1498             if(qp_tt || IS_SKIP(s->current_picture.mb_type[xy-1-s->mb_stride]))
1499                 qp_dt= qp_tt;
1500             else
1501                 qp_dt= s->current_picture.qscale_table[xy-1-s->mb_stride];
1502
1503             if(qp_dt){
1504                 const int chroma_qp= s->chroma_qscale_table[qp_dt];
1505                 s->dsp.h263_h_loop_filter(dest_y -8*linesize  ,   linesize, qp_dt);
1506                 s->dsp.h263_h_loop_filter(dest_cb-8*uvlinesize, uvlinesize, chroma_qp);
1507                 s->dsp.h263_h_loop_filter(dest_cr-8*uvlinesize, uvlinesize, chroma_qp);
1508             }
1509         }
1510     }
1511
1512     if(qp_c){
1513         s->dsp.h263_h_loop_filter(dest_y +8,   linesize, qp_c);
1514         if(s->mb_y + 1 == s->mb_height)
1515             s->dsp.h263_h_loop_filter(dest_y+8*linesize+8,   linesize, qp_c);
1516     }
1517
1518     if(s->mb_x){
1519         int qp_lc;
1520         if(qp_c || IS_SKIP(s->current_picture.mb_type[xy-1]))
1521             qp_lc= qp_c;
1522         else
1523             qp_lc= s->current_picture.qscale_table[xy-1];
1524
1525         if(qp_lc){
1526             s->dsp.h263_h_loop_filter(dest_y,   linesize, qp_lc);
1527             if(s->mb_y + 1 == s->mb_height){
1528                 const int chroma_qp= s->chroma_qscale_table[qp_lc];
1529                 s->dsp.h263_h_loop_filter(dest_y +8*  linesize,   linesize, qp_lc);
1530                 s->dsp.h263_h_loop_filter(dest_cb             , uvlinesize, chroma_qp);
1531                 s->dsp.h263_h_loop_filter(dest_cr             , uvlinesize, chroma_qp);
1532             }
1533         }
1534     }
1535 }
1536
1537 #if CONFIG_ENCODERS
1538 static int h263_pred_dc(MpegEncContext * s, int n, int16_t **dc_val_ptr)
1539 {
1540     int x, y, wrap, a, c, pred_dc;
1541     int16_t *dc_val;
1542
1543     /* find prediction */
1544     if (n < 4) {
1545         x = 2 * s->mb_x + (n & 1);
1546         y = 2 * s->mb_y + ((n & 2) >> 1);
1547         wrap = s->b8_stride;
1548         dc_val = s->dc_val[0];
1549     } else {
1550         x = s->mb_x;
1551         y = s->mb_y;
1552         wrap = s->mb_stride;
1553         dc_val = s->dc_val[n - 4 + 1];
1554     }
1555     /* B C
1556      * A X
1557      */
1558     a = dc_val[(x - 1) + (y) * wrap];
1559     c = dc_val[(x) + (y - 1) * wrap];
1560
1561     /* No prediction outside GOB boundary */
1562     if(s->first_slice_line && n!=3){
1563         if(n!=2) c= 1024;
1564         if(n!=1 && s->mb_x == s->resync_mb_x) a= 1024;
1565     }
1566     /* just DC prediction */
1567     if (a != 1024 && c != 1024)
1568         pred_dc = (a + c) >> 1;
1569     else if (a != 1024)
1570         pred_dc = a;
1571     else
1572         pred_dc = c;
1573
1574     /* we assume pred is positive */
1575     *dc_val_ptr = &dc_val[x + y * wrap];
1576     return pred_dc;
1577 }
1578 #endif /* CONFIG_ENCODERS */
1579
1580 static void h263_pred_acdc(MpegEncContext * s, DCTELEM *block, int n)
1581 {
1582     int x, y, wrap, a, c, pred_dc, scale, i;
1583     int16_t *dc_val, *ac_val, *ac_val1;
1584
1585     /* find prediction */
1586     if (n < 4) {
1587         x = 2 * s->mb_x + (n & 1);
1588         y = 2 * s->mb_y + (n>> 1);
1589         wrap = s->b8_stride;
1590         dc_val = s->dc_val[0];
1591         ac_val = s->ac_val[0][0];
1592         scale = s->y_dc_scale;
1593     } else {
1594         x = s->mb_x;
1595         y = s->mb_y;
1596         wrap = s->mb_stride;
1597         dc_val = s->dc_val[n - 4 + 1];
1598         ac_val = s->ac_val[n - 4 + 1][0];
1599         scale = s->c_dc_scale;
1600     }
1601
1602     ac_val += ((y) * wrap + (x)) * 16;
1603     ac_val1 = ac_val;
1604
1605     /* B C
1606      * A X
1607      */
1608     a = dc_val[(x - 1) + (y) * wrap];
1609     c = dc_val[(x) + (y - 1) * wrap];
1610
1611     /* No prediction outside GOB boundary */
1612     if(s->first_slice_line && n!=3){
1613         if(n!=2) c= 1024;
1614         if(n!=1 && s->mb_x == s->resync_mb_x) a= 1024;
1615     }
1616
1617     if (s->ac_pred) {
1618         pred_dc = 1024;
1619         if (s->h263_aic_dir) {
1620             /* left prediction */
1621             if (a != 1024) {
1622                 ac_val -= 16;
1623                 for(i=1;i<8;i++) {
1624                     block[s->dsp.idct_permutation[i<<3]] += ac_val[i];
1625                 }
1626                 pred_dc = a;
1627             }
1628         } else {
1629             /* top prediction */
1630             if (c != 1024) {
1631                 ac_val -= 16 * wrap;
1632                 for(i=1;i<8;i++) {
1633                     block[s->dsp.idct_permutation[i   ]] += ac_val[i + 8];
1634                 }
1635                 pred_dc = c;
1636             }
1637         }
1638     } else {
1639         /* just DC prediction */
1640         if (a != 1024 && c != 1024)
1641             pred_dc = (a + c) >> 1;
1642         else if (a != 1024)
1643             pred_dc = a;
1644         else
1645             pred_dc = c;
1646     }
1647
1648     /* we assume pred is positive */
1649     block[0]=block[0]*scale + pred_dc;
1650
1651     if (block[0] < 0)
1652         block[0] = 0;
1653     else
1654         block[0] |= 1;
1655
1656     /* Update AC/DC tables */
1657     dc_val[(x) + (y) * wrap] = block[0];
1658
1659     /* left copy */
1660     for(i=1;i<8;i++)
1661         ac_val1[i    ] = block[s->dsp.idct_permutation[i<<3]];
1662     /* top copy */
1663     for(i=1;i<8;i++)
1664         ac_val1[8 + i] = block[s->dsp.idct_permutation[i   ]];
1665 }
1666
1667 int16_t *h263_pred_motion(MpegEncContext * s, int block, int dir,
1668                         int *px, int *py)
1669 {
1670     int wrap;
1671     int16_t *A, *B, *C, (*mot_val)[2];
1672     static const int off[4]= {2, 1, 1, -1};
1673
1674     wrap = s->b8_stride;
1675     mot_val = s->current_picture.motion_val[dir] + s->block_index[block];
1676
1677     A = mot_val[ - 1];
1678     /* special case for first (slice) line */
1679     if (s->first_slice_line && block<3) {
1680         // we can't just change some MVs to simulate that as we need them for the B frames (and ME)
1681         // and if we ever support non rectangular objects than we need to do a few ifs here anyway :(
1682         if(block==0){ //most common case
1683             if(s->mb_x  == s->resync_mb_x){ //rare
1684                 *px= *py = 0;
1685             }else if(s->mb_x + 1 == s->resync_mb_x && s->h263_pred){ //rare
1686                 C = mot_val[off[block] - wrap];
1687                 if(s->mb_x==0){
1688                     *px = C[0];
1689                     *py = C[1];
1690                 }else{
1691                     *px = mid_pred(A[0], 0, C[0]);
1692                     *py = mid_pred(A[1], 0, C[1]);
1693                 }
1694             }else{
1695                 *px = A[0];
1696                 *py = A[1];
1697             }
1698         }else if(block==1){
1699             if(s->mb_x + 1 == s->resync_mb_x && s->h263_pred){ //rare
1700                 C = mot_val[off[block] - wrap];
1701                 *px = mid_pred(A[0], 0, C[0]);
1702                 *py = mid_pred(A[1], 0, C[1]);
1703             }else{
1704                 *px = A[0];
1705                 *py = A[1];
1706             }
1707         }else{ /* block==2*/
1708             B = mot_val[ - wrap];
1709             C = mot_val[off[block] - wrap];
1710             if(s->mb_x == s->resync_mb_x) //rare
1711                 A[0]=A[1]=0;
1712
1713             *px = mid_pred(A[0], B[0], C[0]);
1714             *py = mid_pred(A[1], B[1], C[1]);
1715         }
1716     } else {
1717         B = mot_val[ - wrap];
1718         C = mot_val[off[block] - wrap];
1719         *px = mid_pred(A[0], B[0], C[0]);
1720         *py = mid_pred(A[1], B[1], C[1]);
1721     }
1722     return *mot_val;
1723 }
1724
1725 #if CONFIG_ENCODERS
1726 void ff_h263_encode_motion(MpegEncContext * s, int val, int f_code)
1727 {
1728     int range, l, bit_size, sign, code, bits;
1729
1730     if (val == 0) {
1731         /* zero vector */
1732         code = 0;
1733         put_bits(&s->pb, mvtab[code][1], mvtab[code][0]);
1734     } else {
1735         bit_size = f_code - 1;
1736         range = 1 << bit_size;
1737         /* modulo encoding */
1738         l= INT_BIT - 6 - bit_size;
1739         val = (val<<l)>>l;
1740         sign = val>>31;
1741         val= (val^sign)-sign;
1742         sign&=1;
1743
1744         val--;
1745         code = (val >> bit_size) + 1;
1746         bits = val & (range - 1);
1747
1748         put_bits(&s->pb, mvtab[code][1] + 1, (mvtab[code][0] << 1) | sign);
1749         if (bit_size > 0) {
1750             put_bits(&s->pb, bit_size, bits);
1751         }
1752     }
1753 }
1754
1755 /* Encode MV differences on H.263+ with Unrestricted MV mode */
1756 static void h263p_encode_umotion(MpegEncContext * s, int val)
1757 {
1758     short sval = 0;
1759     short i = 0;
1760     short n_bits = 0;
1761     short temp_val;
1762     int code = 0;
1763     int tcode;
1764
1765     if ( val == 0)
1766         put_bits(&s->pb, 1, 1);
1767     else if (val == 1)
1768         put_bits(&s->pb, 3, 0);
1769     else if (val == -1)
1770         put_bits(&s->pb, 3, 2);
1771     else {
1772
1773         sval = ((val < 0) ? (short)(-val):(short)val);
1774         temp_val = sval;
1775
1776         while (temp_val != 0) {
1777             temp_val = temp_val >> 1;
1778             n_bits++;
1779         }
1780
1781         i = n_bits - 1;
1782         while (i > 0) {
1783             tcode = (sval & (1 << (i-1))) >> (i-1);
1784             tcode = (tcode << 1) | 1;
1785             code = (code << 2) | tcode;
1786             i--;
1787         }
1788         code = ((code << 1) | (val < 0)) << 1;
1789         put_bits(&s->pb, (2*n_bits)+1, code);
1790         //printf("\nVal = %d\tCode = %d", sval, code);
1791     }
1792 }
1793
1794 static void init_mv_penalty_and_fcode(MpegEncContext *s)
1795 {
1796     int f_code;
1797     int mv;
1798
1799     for(f_code=1; f_code<=MAX_FCODE; f_code++){
1800         for(mv=-MAX_MV; mv<=MAX_MV; mv++){
1801             int len;
1802
1803             if(mv==0) len= mvtab[0][1];
1804             else{
1805                 int val, bit_size, code;
1806
1807                 bit_size = f_code - 1;
1808
1809                 val=mv;
1810                 if (val < 0)
1811                     val = -val;
1812                 val--;
1813                 code = (val >> bit_size) + 1;
1814                 if(code<33){
1815                     len= mvtab[code][1] + 1 + bit_size;
1816                 }else{
1817                     len= mvtab[32][1] + av_log2(code>>5) + 2 + bit_size;
1818                 }
1819             }
1820
1821             mv_penalty[f_code][mv+MAX_MV]= len;
1822         }
1823     }
1824
1825     for(f_code=MAX_FCODE; f_code>0; f_code--){
1826         for(mv=-(16<<f_code); mv<(16<<f_code); mv++){
1827             fcode_tab[mv+MAX_MV]= f_code;
1828         }
1829     }
1830
1831     for(mv=0; mv<MAX_MV*2+1; mv++){
1832         umv_fcode_tab[mv]= 1;
1833     }
1834 }
1835
1836 static void init_uni_dc_tab(void)
1837 {
1838     int level, uni_code, uni_len;
1839
1840     for(level=-256; level<256; level++){
1841         int size, v, l;
1842         /* find number of bits */
1843         size = 0;
1844         v = abs(level);
1845         while (v) {
1846             v >>= 1;
1847             size++;
1848         }
1849
1850         if (level < 0)
1851             l= (-level) ^ ((1 << size) - 1);
1852         else
1853             l= level;
1854
1855         /* luminance */
1856         uni_code= DCtab_lum[size][0];
1857         uni_len = DCtab_lum[size][1];
1858
1859         if (size > 0) {
1860             uni_code<<=size; uni_code|=l;
1861             uni_len+=size;
1862             if (size > 8){
1863                 uni_code<<=1; uni_code|=1;
1864                 uni_len++;
1865             }
1866         }
1867         uni_DCtab_lum_bits[level+256]= uni_code;
1868         uni_DCtab_lum_len [level+256]= uni_len;
1869
1870         /* chrominance */
1871         uni_code= DCtab_chrom[size][0];
1872         uni_len = DCtab_chrom[size][1];
1873
1874         if (size > 0) {
1875             uni_code<<=size; uni_code|=l;
1876             uni_len+=size;
1877             if (size > 8){
1878                 uni_code<<=1; uni_code|=1;
1879                 uni_len++;
1880             }
1881         }
1882         uni_DCtab_chrom_bits[level+256]= uni_code;
1883         uni_DCtab_chrom_len [level+256]= uni_len;
1884
1885     }
1886 }
1887
1888 static void init_uni_mpeg4_rl_tab(RLTable *rl, uint32_t *bits_tab, uint8_t *len_tab){
1889     int slevel, run, last;
1890
1891     assert(MAX_LEVEL >= 64);
1892     assert(MAX_RUN   >= 63);
1893
1894     for(slevel=-64; slevel<64; slevel++){
1895         if(slevel==0) continue;
1896         for(run=0; run<64; run++){
1897             for(last=0; last<=1; last++){
1898                 const int index= UNI_MPEG4_ENC_INDEX(last, run, slevel+64);
1899                 int level= slevel < 0 ? -slevel : slevel;
1900                 int sign= slevel < 0 ? 1 : 0;
1901                 int bits, len, code;
1902                 int level1, run1;
1903
1904                 len_tab[index]= 100;
1905
1906                 /* ESC0 */
1907                 code= get_rl_index(rl, last, run, level);
1908                 bits= rl->table_vlc[code][0];
1909                 len=  rl->table_vlc[code][1];
1910                 bits=bits*2+sign; len++;
1911
1912                 if(code!=rl->n && len < len_tab[index]){
1913                     bits_tab[index]= bits;
1914                     len_tab [index]= len;
1915                 }
1916 #if 1
1917                 /* ESC1 */
1918                 bits= rl->table_vlc[rl->n][0];
1919                 len=  rl->table_vlc[rl->n][1];
1920                 bits=bits*2;    len++; //esc1
1921                 level1= level - rl->max_level[last][run];
1922                 if(level1>0){
1923                     code= get_rl_index(rl, last, run, level1);
1924                     bits<<= rl->table_vlc[code][1];
1925                     len  += rl->table_vlc[code][1];
1926                     bits += rl->table_vlc[code][0];
1927                     bits=bits*2+sign; len++;
1928
1929                     if(code!=rl->n && len < len_tab[index]){
1930                         bits_tab[index]= bits;
1931                         len_tab [index]= len;
1932                     }
1933                 }
1934 #endif
1935 #if 1
1936                 /* ESC2 */
1937                 bits= rl->table_vlc[rl->n][0];
1938                 len=  rl->table_vlc[rl->n][1];
1939                 bits=bits*4+2;    len+=2; //esc2
1940                 run1 = run - rl->max_run[last][level] - 1;
1941                 if(run1>=0){
1942                     code= get_rl_index(rl, last, run1, level);
1943                     bits<<= rl->table_vlc[code][1];
1944                     len  += rl->table_vlc[code][1];
1945                     bits += rl->table_vlc[code][0];
1946                     bits=bits*2+sign; len++;
1947
1948                     if(code!=rl->n && len < len_tab[index]){
1949                         bits_tab[index]= bits;
1950                         len_tab [index]= len;
1951                     }
1952                 }
1953 #endif
1954                 /* ESC3 */
1955                 bits= rl->table_vlc[rl->n][0];
1956                 len = rl->table_vlc[rl->n][1];
1957                 bits=bits*4+3;    len+=2; //esc3
1958                 bits=bits*2+last; len++;
1959                 bits=bits*64+run; len+=6;
1960                 bits=bits*2+1;    len++;  //marker
1961                 bits=bits*4096+(slevel&0xfff); len+=12;
1962                 bits=bits*2+1;    len++;  //marker
1963
1964                 if(len < len_tab[index]){
1965                     bits_tab[index]= bits;
1966                     len_tab [index]= len;
1967                 }
1968             }
1969         }
1970     }
1971 }
1972
1973 static void init_uni_h263_rl_tab(RLTable *rl, uint32_t *bits_tab, uint8_t *len_tab){
1974     int slevel, run, last;
1975
1976     assert(MAX_LEVEL >= 64);
1977     assert(MAX_RUN   >= 63);
1978
1979     for(slevel=-64; slevel<64; slevel++){
1980         if(slevel==0) continue;
1981         for(run=0; run<64; run++){
1982             for(last=0; last<=1; last++){
1983                 const int index= UNI_MPEG4_ENC_INDEX(last, run, slevel+64);
1984                 int level= slevel < 0 ? -slevel : slevel;
1985                 int sign= slevel < 0 ? 1 : 0;
1986                 int bits, len, code;
1987
1988                 len_tab[index]= 100;
1989
1990                 /* ESC0 */
1991                 code= get_rl_index(rl, last, run, level);
1992                 bits= rl->table_vlc[code][0];
1993                 len=  rl->table_vlc[code][1];
1994                 bits=bits*2+sign; len++;
1995
1996                 if(code!=rl->n && len < len_tab[index]){
1997                     if(bits_tab) bits_tab[index]= bits;
1998                     len_tab [index]= len;
1999                 }
2000                 /* ESC */
2001                 bits= rl->table_vlc[rl->n][0];
2002                 len = rl->table_vlc[rl->n][1];
2003                 bits=bits*2+last; len++;
2004                 bits=bits*64+run; len+=6;
2005                 bits=bits*256+(level&0xff); len+=8;
2006
2007                 if(len < len_tab[index]){
2008                     if(bits_tab) bits_tab[index]= bits;
2009                     len_tab [index]= len;
2010                 }
2011             }
2012         }
2013     }
2014 }
2015
2016 void h263_encode_init(MpegEncContext *s)
2017 {
2018     static int done = 0;
2019
2020     if (!done) {
2021         done = 1;
2022
2023         init_uni_dc_tab();
2024
2025         init_rl(&rl_inter, static_rl_table_store[0]);
2026         init_rl(&rl_intra, static_rl_table_store[1]);
2027         init_rl(&rl_intra_aic, static_rl_table_store[2]);
2028
2029         init_uni_mpeg4_rl_tab(&rl_intra, uni_mpeg4_intra_rl_bits, uni_mpeg4_intra_rl_len);
2030         init_uni_mpeg4_rl_tab(&rl_inter, uni_mpeg4_inter_rl_bits, uni_mpeg4_inter_rl_len);
2031
2032         init_uni_h263_rl_tab(&rl_intra_aic, NULL, uni_h263_intra_aic_rl_len);
2033         init_uni_h263_rl_tab(&rl_inter    , NULL, uni_h263_inter_rl_len);
2034
2035         init_mv_penalty_and_fcode(s);
2036     }
2037     s->me.mv_penalty= mv_penalty; //FIXME exact table for msmpeg4 & h263p
2038
2039     s->intra_ac_vlc_length     =s->inter_ac_vlc_length     = uni_h263_inter_rl_len;
2040     s->intra_ac_vlc_last_length=s->inter_ac_vlc_last_length= uni_h263_inter_rl_len + 128*64;
2041     if(s->h263_aic){
2042         s->intra_ac_vlc_length     = uni_h263_intra_aic_rl_len;
2043         s->intra_ac_vlc_last_length= uni_h263_intra_aic_rl_len + 128*64;
2044     }
2045     s->ac_esc_length= 7+1+6+8;
2046
2047     // use fcodes >1 only for mpeg4 & h263 & h263p FIXME
2048     switch(s->codec_id){
2049     case CODEC_ID_MPEG4:
2050         s->fcode_tab= fcode_tab;
2051         s->min_qcoeff= -2048;
2052         s->max_qcoeff=  2047;
2053         s->intra_ac_vlc_length     = uni_mpeg4_intra_rl_len;
2054         s->intra_ac_vlc_last_length= uni_mpeg4_intra_rl_len + 128*64;
2055         s->inter_ac_vlc_length     = uni_mpeg4_inter_rl_len;
2056         s->inter_ac_vlc_last_length= uni_mpeg4_inter_rl_len + 128*64;
2057         s->luma_dc_vlc_length= uni_DCtab_lum_len;
2058         s->chroma_dc_vlc_length= uni_DCtab_chrom_len;
2059         s->ac_esc_length= 7+2+1+6+1+12+1;
2060         s->y_dc_scale_table= ff_mpeg4_y_dc_scale_table;
2061         s->c_dc_scale_table= ff_mpeg4_c_dc_scale_table;
2062
2063         if(s->flags & CODEC_FLAG_GLOBAL_HEADER){
2064
2065             s->avctx->extradata= av_malloc(1024);
2066             init_put_bits(&s->pb, s->avctx->extradata, 1024);
2067
2068             if(!(s->workaround_bugs & FF_BUG_MS))
2069                 mpeg4_encode_visual_object_header(s);
2070             mpeg4_encode_vol_header(s, 0, 0);
2071
2072 //            ff_mpeg4_stuffing(&s->pb); ?
2073             flush_put_bits(&s->pb);
2074             s->avctx->extradata_size= (put_bits_count(&s->pb)+7)>>3;
2075         }
2076
2077         break;
2078     case CODEC_ID_H263P:
2079         if(s->umvplus)
2080             s->fcode_tab= umv_fcode_tab;
2081         if(s->modified_quant){
2082             s->min_qcoeff= -2047;
2083             s->max_qcoeff=  2047;
2084         }else{
2085             s->min_qcoeff= -127;
2086             s->max_qcoeff=  127;
2087         }
2088         break;
2089         //Note for mpeg4 & h263 the dc-scale table will be set per frame as needed later
2090     case CODEC_ID_FLV1:
2091         if (s->h263_flv > 1) {
2092             s->min_qcoeff= -1023;
2093             s->max_qcoeff=  1023;
2094         } else {
2095             s->min_qcoeff= -127;
2096             s->max_qcoeff=  127;
2097         }
2098         s->y_dc_scale_table=
2099         s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
2100         break;
2101     default: //nothing needed - default table already set in mpegvideo.c
2102         s->min_qcoeff= -127;
2103         s->max_qcoeff=  127;
2104         s->y_dc_scale_table=
2105         s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
2106     }
2107 }
2108
2109 /**
2110  * encodes a 8x8 block.
2111  * @param block the 8x8 block
2112  * @param n block index (0-3 are luma, 4-5 are chroma)
2113  */
2114 static void h263_encode_block(MpegEncContext * s, DCTELEM * block, int n)
2115 {
2116     int level, run, last, i, j, last_index, last_non_zero, sign, slevel, code;
2117     RLTable *rl;
2118
2119     rl = &rl_inter;
2120     if (s->mb_intra && !s->h263_aic) {
2121         /* DC coef */
2122         level = block[0];
2123         /* 255 cannot be represented, so we clamp */
2124         if (level > 254) {
2125             level = 254;
2126             block[0] = 254;
2127         }
2128         /* 0 cannot be represented also */
2129         else if (level < 1) {
2130             level = 1;
2131             block[0] = 1;
2132         }
2133         if (level == 128) //FIXME check rv10
2134             put_bits(&s->pb, 8, 0xff);
2135         else
2136             put_bits(&s->pb, 8, level);
2137         i = 1;
2138     } else {
2139         i = 0;
2140         if (s->h263_aic && s->mb_intra)
2141             rl = &rl_intra_aic;
2142
2143         if(s->alt_inter_vlc && !s->mb_intra){
2144             int aic_vlc_bits=0;
2145             int inter_vlc_bits=0;
2146             int wrong_pos=-1;
2147             int aic_code;
2148
2149             last_index = s->block_last_index[n];
2150             last_non_zero = i - 1;
2151             for (; i <= last_index; i++) {
2152                 j = s->intra_scantable.permutated[i];
2153                 level = block[j];
2154                 if (level) {
2155                     run = i - last_non_zero - 1;
2156                     last = (i == last_index);
2157
2158                     if(level<0) level= -level;
2159
2160                     code = get_rl_index(rl, last, run, level);
2161                     aic_code = get_rl_index(&rl_intra_aic, last, run, level);
2162                     inter_vlc_bits += rl->table_vlc[code][1]+1;
2163                     aic_vlc_bits   += rl_intra_aic.table_vlc[aic_code][1]+1;
2164
2165                     if (code == rl->n) {
2166                         inter_vlc_bits += 1+6+8-1;
2167                     }
2168                     if (aic_code == rl_intra_aic.n) {
2169                         aic_vlc_bits += 1+6+8-1;
2170                         wrong_pos += run + 1;
2171                     }else
2172                         wrong_pos += wrong_run[aic_code];
2173                     last_non_zero = i;
2174                 }
2175             }
2176             i = 0;
2177             if(aic_vlc_bits < inter_vlc_bits && wrong_pos > 63)
2178                 rl = &rl_intra_aic;
2179         }
2180     }
2181
2182     /* AC coefs */
2183     last_index = s->block_last_index[n];
2184     last_non_zero = i - 1;
2185     for (; i <= last_index; i++) {
2186         j = s->intra_scantable.permutated[i];
2187         level = block[j];
2188         if (level) {
2189             run = i - last_non_zero - 1;
2190             last = (i == last_index);
2191             sign = 0;
2192             slevel = level;
2193             if (level < 0) {
2194                 sign = 1;
2195                 level = -level;
2196             }
2197             code = get_rl_index(rl, last, run, level);
2198             put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2199             if (code == rl->n) {
2200               if(s->h263_flv <= 1){
2201                 put_bits(&s->pb, 1, last);
2202                 put_bits(&s->pb, 6, run);
2203
2204                 assert(slevel != 0);
2205
2206                 if(level < 128)
2207                     put_sbits(&s->pb, 8, slevel);
2208                 else{
2209                     put_bits(&s->pb, 8, 128);
2210                     put_sbits(&s->pb, 5, slevel);
2211                     put_sbits(&s->pb, 6, slevel>>5);
2212                 }
2213               }else{
2214                 if(level < 64) { // 7-bit level
2215                         put_bits(&s->pb, 1, 0);
2216                         put_bits(&s->pb, 1, last);
2217                         put_bits(&s->pb, 6, run);
2218
2219                         put_sbits(&s->pb, 7, slevel);
2220                     } else {
2221                         /* 11-bit level */
2222                         put_bits(&s->pb, 1, 1);
2223                         put_bits(&s->pb, 1, last);
2224                         put_bits(&s->pb, 6, run);
2225
2226                         put_sbits(&s->pb, 11, slevel);
2227                     }
2228               }
2229             } else {
2230                 put_bits(&s->pb, 1, sign);
2231             }
2232             last_non_zero = i;
2233         }
2234     }
2235 }
2236
2237 /***************************************************/
2238 /**
2239  * add mpeg4 stuffing bits (01...1)
2240  */
2241 void ff_mpeg4_stuffing(PutBitContext * pbc)
2242 {
2243     int length;
2244     put_bits(pbc, 1, 0);
2245     length= (-put_bits_count(pbc))&7;
2246     if(length) put_bits(pbc, length, (1<<length)-1);
2247 }
2248
2249 /* must be called before writing the header */
2250 void ff_set_mpeg4_time(MpegEncContext * s){
2251     if(s->pict_type==FF_B_TYPE){
2252         ff_mpeg4_init_direct_mv(s);
2253     }else{
2254         s->last_time_base= s->time_base;
2255         s->time_base= s->time/s->avctx->time_base.den;
2256     }
2257 }
2258
2259 static void mpeg4_encode_gop_header(MpegEncContext * s){
2260     int hours, minutes, seconds;
2261     int64_t time;
2262
2263     put_bits(&s->pb, 16, 0);
2264     put_bits(&s->pb, 16, GOP_STARTCODE);
2265
2266     time= s->current_picture_ptr->pts;
2267     if(s->reordered_input_picture[1])
2268         time= FFMIN(time, s->reordered_input_picture[1]->pts);
2269     time= time*s->avctx->time_base.num;
2270
2271     seconds= time/s->avctx->time_base.den;
2272     minutes= seconds/60; seconds %= 60;
2273     hours= minutes/60; minutes %= 60;
2274     hours%=24;
2275
2276     put_bits(&s->pb, 5, hours);
2277     put_bits(&s->pb, 6, minutes);
2278     put_bits(&s->pb, 1, 1);
2279     put_bits(&s->pb, 6, seconds);
2280
2281     put_bits(&s->pb, 1, !!(s->flags&CODEC_FLAG_CLOSED_GOP));
2282     put_bits(&s->pb, 1, 0); //broken link == NO
2283
2284     s->last_time_base= time / s->avctx->time_base.den;
2285
2286     ff_mpeg4_stuffing(&s->pb);
2287 }
2288
2289 static void mpeg4_encode_visual_object_header(MpegEncContext * s){
2290     int profile_and_level_indication;
2291     int vo_ver_id;
2292
2293     if(s->avctx->profile != FF_PROFILE_UNKNOWN){
2294         profile_and_level_indication = s->avctx->profile << 4;
2295     }else if(s->max_b_frames || s->quarter_sample){
2296         profile_and_level_indication= 0xF0; // adv simple
2297     }else{
2298         profile_and_level_indication= 0x00; // simple
2299     }
2300
2301     if(s->avctx->level != FF_LEVEL_UNKNOWN){
2302         profile_and_level_indication |= s->avctx->level;
2303     }else{
2304         profile_and_level_indication |= 1; //level 1
2305     }
2306
2307     if(profile_and_level_indication>>4 == 0xF){
2308         vo_ver_id= 5;
2309     }else{
2310         vo_ver_id= 1;
2311     }
2312
2313     //FIXME levels
2314
2315     put_bits(&s->pb, 16, 0);
2316     put_bits(&s->pb, 16, VOS_STARTCODE);
2317
2318     put_bits(&s->pb, 8, profile_and_level_indication);
2319
2320     put_bits(&s->pb, 16, 0);
2321     put_bits(&s->pb, 16, VISUAL_OBJ_STARTCODE);
2322
2323     put_bits(&s->pb, 1, 1);
2324         put_bits(&s->pb, 4, vo_ver_id);
2325         put_bits(&s->pb, 3, 1); //priority
2326
2327     put_bits(&s->pb, 4, 1); //visual obj type== video obj
2328
2329     put_bits(&s->pb, 1, 0); //video signal type == no clue //FIXME
2330
2331     ff_mpeg4_stuffing(&s->pb);
2332 }
2333
2334 static void mpeg4_encode_vol_header(MpegEncContext * s, int vo_number, int vol_number)
2335 {
2336     int vo_ver_id;
2337
2338     if (!CONFIG_MPEG4_ENCODER)  return;
2339
2340     if(s->max_b_frames || s->quarter_sample){
2341         vo_ver_id= 5;
2342         s->vo_type= ADV_SIMPLE_VO_TYPE;
2343     }else{
2344         vo_ver_id= 1;
2345         s->vo_type= SIMPLE_VO_TYPE;
2346     }
2347
2348     put_bits(&s->pb, 16, 0);
2349     put_bits(&s->pb, 16, 0x100 + vo_number);        /* video obj */
2350     put_bits(&s->pb, 16, 0);
2351     put_bits(&s->pb, 16, 0x120 + vol_number);       /* video obj layer */
2352
2353     put_bits(&s->pb, 1, 0);             /* random access vol */
2354     put_bits(&s->pb, 8, s->vo_type);    /* video obj type indication */
2355     if(s->workaround_bugs & FF_BUG_MS) {
2356         put_bits(&s->pb, 1, 0);         /* is obj layer id= no */
2357     } else {
2358         put_bits(&s->pb, 1, 1);         /* is obj layer id= yes */
2359         put_bits(&s->pb, 4, vo_ver_id); /* is obj layer ver id */
2360         put_bits(&s->pb, 3, 1);         /* is obj layer priority */
2361     }
2362
2363     aspect_to_info(s, s->avctx->sample_aspect_ratio);
2364
2365     put_bits(&s->pb, 4, s->aspect_ratio_info);/* aspect ratio info */
2366     if (s->aspect_ratio_info == FF_ASPECT_EXTENDED){
2367         put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.num);
2368         put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.den);
2369     }
2370
2371     if(s->workaround_bugs & FF_BUG_MS) { //
2372         put_bits(&s->pb, 1, 0);         /* vol control parameters= no @@@ */
2373     } else {
2374         put_bits(&s->pb, 1, 1);         /* vol control parameters= yes */
2375         put_bits(&s->pb, 2, 1);         /* chroma format YUV 420/YV12 */
2376         put_bits(&s->pb, 1, s->low_delay);
2377         put_bits(&s->pb, 1, 0);         /* vbv parameters= no */
2378     }
2379
2380     put_bits(&s->pb, 2, RECT_SHAPE);    /* vol shape= rectangle */
2381     put_bits(&s->pb, 1, 1);             /* marker bit */
2382
2383     put_bits(&s->pb, 16, s->avctx->time_base.den);
2384     if (s->time_increment_bits < 1)
2385         s->time_increment_bits = 1;
2386     put_bits(&s->pb, 1, 1);             /* marker bit */
2387     put_bits(&s->pb, 1, 0);             /* fixed vop rate=no */
2388     put_bits(&s->pb, 1, 1);             /* marker bit */
2389     put_bits(&s->pb, 13, s->width);     /* vol width */
2390     put_bits(&s->pb, 1, 1);             /* marker bit */
2391     put_bits(&s->pb, 13, s->height);    /* vol height */
2392     put_bits(&s->pb, 1, 1);             /* marker bit */
2393     put_bits(&s->pb, 1, s->progressive_sequence ? 0 : 1);
2394     put_bits(&s->pb, 1, 1);             /* obmc disable */
2395     if (vo_ver_id == 1) {
2396         put_bits(&s->pb, 1, s->vol_sprite_usage);       /* sprite enable */
2397     }else{
2398         put_bits(&s->pb, 2, s->vol_sprite_usage);       /* sprite enable */
2399     }
2400
2401     put_bits(&s->pb, 1, 0);             /* not 8 bit == false */
2402     put_bits(&s->pb, 1, s->mpeg_quant); /* quant type= (0=h263 style)*/
2403
2404     if(s->mpeg_quant){
2405         ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);
2406         ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);
2407     }
2408
2409     if (vo_ver_id != 1)
2410         put_bits(&s->pb, 1, s->quarter_sample);
2411     put_bits(&s->pb, 1, 1);             /* complexity estimation disable */
2412     s->resync_marker= s->rtp_mode;
2413     put_bits(&s->pb, 1, s->resync_marker ? 0 : 1);/* resync marker disable */
2414     put_bits(&s->pb, 1, s->data_partitioning ? 1 : 0);
2415     if(s->data_partitioning){
2416         put_bits(&s->pb, 1, 0);         /* no rvlc */
2417     }
2418
2419     if (vo_ver_id != 1){
2420         put_bits(&s->pb, 1, 0);         /* newpred */
2421         put_bits(&s->pb, 1, 0);         /* reduced res vop */
2422     }
2423     put_bits(&s->pb, 1, 0);             /* scalability */
2424
2425     ff_mpeg4_stuffing(&s->pb);
2426
2427     /* user data */
2428     if(!(s->flags & CODEC_FLAG_BITEXACT)){
2429         put_bits(&s->pb, 16, 0);
2430         put_bits(&s->pb, 16, 0x1B2);    /* user_data */
2431         ff_put_string(&s->pb, LIBAVCODEC_IDENT, 0);
2432     }
2433 }
2434
2435 /* write mpeg4 VOP header */
2436 void mpeg4_encode_picture_header(MpegEncContext * s, int picture_number)
2437 {
2438     int time_incr;
2439     int time_div, time_mod;
2440
2441     if(s->pict_type==FF_I_TYPE){
2442         if(!(s->flags&CODEC_FLAG_GLOBAL_HEADER)){
2443             if(s->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT) //HACK, the reference sw is buggy
2444                 mpeg4_encode_visual_object_header(s);
2445             if(s->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT || picture_number==0) //HACK, the reference sw is buggy
2446                 mpeg4_encode_vol_header(s, 0, 0);
2447         }
2448         if(!(s->workaround_bugs & FF_BUG_MS))
2449             mpeg4_encode_gop_header(s);
2450     }
2451
2452     s->partitioned_frame= s->data_partitioning && s->pict_type!=FF_B_TYPE;
2453
2454 //printf("num:%d rate:%d base:%d\n", s->picture_number, s->time_base.den, FRAME_RATE_BASE);
2455
2456     put_bits(&s->pb, 16, 0);                /* vop header */
2457     put_bits(&s->pb, 16, VOP_STARTCODE);    /* vop header */
2458     put_bits(&s->pb, 2, s->pict_type - 1);  /* pict type: I = 0 , P = 1 */
2459
2460     assert(s->time>=0);
2461     time_div= s->time/s->avctx->time_base.den;
2462     time_mod= s->time%s->avctx->time_base.den;
2463     time_incr= time_div - s->last_time_base;
2464     assert(time_incr >= 0);
2465     while(time_incr--)
2466         put_bits(&s->pb, 1, 1);
2467
2468     put_bits(&s->pb, 1, 0);
2469
2470     put_bits(&s->pb, 1, 1);                             /* marker */
2471     put_bits(&s->pb, s->time_increment_bits, time_mod); /* time increment */
2472     put_bits(&s->pb, 1, 1);                             /* marker */
2473     put_bits(&s->pb, 1, 1);                             /* vop coded */
2474     if (    s->pict_type == FF_P_TYPE
2475         || (s->pict_type == FF_S_TYPE && s->vol_sprite_usage==GMC_SPRITE)) {
2476         put_bits(&s->pb, 1, s->no_rounding);    /* rounding type */
2477     }
2478     put_bits(&s->pb, 3, 0);     /* intra dc VLC threshold */
2479     if(!s->progressive_sequence){
2480          put_bits(&s->pb, 1, s->current_picture_ptr->top_field_first);
2481          put_bits(&s->pb, 1, s->alternate_scan);
2482     }
2483     //FIXME sprite stuff
2484
2485     put_bits(&s->pb, 5, s->qscale);
2486
2487     if (s->pict_type != FF_I_TYPE)
2488         put_bits(&s->pb, 3, s->f_code); /* fcode_for */
2489     if (s->pict_type == FF_B_TYPE)
2490         put_bits(&s->pb, 3, s->b_code); /* fcode_back */
2491     //    printf("****frame %d\n", picture_number);
2492 }
2493
2494 #endif //CONFIG_ENCODERS
2495
2496 /**
2497  * predicts the dc.
2498  * encoding quantized level -> quantized diff
2499  * decoding quantized diff -> quantized level
2500  * @param n block index (0-3 are luma, 4-5 are chroma)
2501  * @param dir_ptr pointer to an integer where the prediction direction will be stored
2502  */
2503 static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, int level, int *dir_ptr, int encoding)
2504 {
2505     int a, b, c, wrap, pred, scale, ret;
2506     int16_t *dc_val;
2507
2508     /* find prediction */
2509     if (n < 4) {
2510         scale = s->y_dc_scale;
2511     } else {
2512         scale = s->c_dc_scale;
2513     }
2514     if(IS_3IV1)
2515         scale= 8;
2516
2517     wrap= s->block_wrap[n];
2518     dc_val = s->dc_val[0] + s->block_index[n];
2519
2520     /* B C
2521      * A X
2522      */
2523     a = dc_val[