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