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