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