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