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