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