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