fb9eeb254563f7174cb32e6865a391cc71c20405
[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 6
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, 8, 
2432                  intra_MCBPC_bits, 1, 1,
2433                  intra_MCBPC_code, 1, 1);
2434         init_vlc(&inter_MCBPC_vlc, INTER_MCBPC_VLC_BITS, 25, 
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                 cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 1);
2875                 if (cbpc < 0){
2876
2877                     fprintf(stderr, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
2878                     return -1;
2879                 }
2880                 s->cbp_table[xy]= cbpc & 3;
2881                 s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
2882                 s->mb_intra = 1;
2883
2884                 if(cbpc & 4) {
2885                     change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
2886                 }
2887                 s->current_picture.qscale_table[xy]= s->qscale;
2888
2889                 s->mbintra_table[xy]= 1;
2890                 for(i=0; i<6; i++){
2891                     int dc_pred_dir;
2892                     int dc= mpeg4_decode_dc(s, i, &dc_pred_dir); 
2893                     if(dc < 0){
2894                         fprintf(stderr, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
2895                         return -1;
2896                     }
2897                     dir<<=1;
2898                     if(dc_pred_dir) dir|=1;
2899                 }
2900                 s->pred_dir_table[xy]= dir;
2901             }else{ /* P/S_TYPE */
2902                 int mx, my, pred_x, pred_y, bits;
2903                 int16_t * const mot_val= s->motion_val[s->block_index[0]];
2904                 const int stride= s->block_wrap[0]*2;
2905
2906                 bits= show_bits(&s->gb, 17);
2907                 if(bits==MOTION_MARKER){
2908                     return mb_num-1;
2909                 }
2910                 skip_bits1(&s->gb);
2911                 if(bits&0x10000){
2912                     /* skip mb */
2913                     if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
2914                         s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0;
2915                         mx= get_amv(s, 0);
2916                         my= get_amv(s, 1);
2917                     }else{
2918                         s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
2919                         mx=my=0;
2920                     }
2921                     mot_val[0       ]= mot_val[2       ]=
2922                     mot_val[0+stride]= mot_val[2+stride]= mx;
2923                     mot_val[1       ]= mot_val[3       ]=
2924                     mot_val[1+stride]= mot_val[3+stride]= my;
2925
2926                     if(s->mbintra_table[xy])
2927                         ff_clean_intra_table_entries(s);
2928                     continue;
2929                 }
2930                 cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
2931                 if (cbpc < 0){
2932                     fprintf(stderr, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
2933                     return -1;
2934                 }
2935                 if (cbpc > 20)
2936                     cbpc+=3;
2937                 else if (cbpc == 20)
2938                     fprintf(stderr, "Stuffing !");
2939                 s->cbp_table[xy]= cbpc&(8+3); //8 is dquant
2940     
2941                 s->mb_intra = ((cbpc & 4) != 0);
2942         
2943                 if(s->mb_intra){
2944                     s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
2945                     s->mbintra_table[xy]= 1;
2946                     mot_val[0       ]= mot_val[2       ]= 
2947                     mot_val[0+stride]= mot_val[2+stride]= 0;
2948                     mot_val[1       ]= mot_val[3       ]=
2949                     mot_val[1+stride]= mot_val[3+stride]= 0;
2950                 }else{
2951                     if(s->mbintra_table[xy])
2952                         ff_clean_intra_table_entries(s);
2953
2954                     if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
2955                         s->mcsel= get_bits1(&s->gb);
2956                     else s->mcsel= 0;
2957         
2958                     if ((cbpc & 16) == 0) {
2959                         /* 16x16 motion prediction */
2960
2961                         h263_pred_motion(s, 0, &pred_x, &pred_y);
2962                         if(!s->mcsel){
2963                             mx = h263_decode_motion(s, pred_x, s->f_code);
2964                             if (mx >= 0xffff)
2965                                 return -1;
2966
2967                             my = h263_decode_motion(s, pred_y, s->f_code);
2968                             if (my >= 0xffff)
2969                                 return -1;
2970                             s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0;
2971                         } else {
2972                             mx = get_amv(s, 0);
2973                             my = get_amv(s, 1);
2974                             s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0;
2975                         }
2976
2977                         mot_val[0       ]= mot_val[2       ] =
2978                         mot_val[0+stride]= mot_val[2+stride]= mx;
2979                         mot_val[1       ]= mot_val[3       ]=
2980                         mot_val[1+stride]= mot_val[3+stride]= my;
2981                     } else {
2982                         int i;
2983                         s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0;
2984                         for(i=0;i<4;i++) {
2985                             int16_t *mot_val= h263_pred_motion(s, i, &pred_x, &pred_y);
2986                             mx = h263_decode_motion(s, pred_x, s->f_code);
2987                             if (mx >= 0xffff)
2988                                 return -1;
2989                 
2990                             my = h263_decode_motion(s, pred_y, s->f_code);
2991                             if (my >= 0xffff)
2992                                 return -1;
2993                             mot_val[0] = mx;
2994                             mot_val[1] = my;
2995                         }
2996                     }
2997                 }
2998             }
2999         }
3000         s->mb_x= 0;
3001     }
3002
3003     return mb_num;
3004 }
3005
3006 /**
3007  * decode second partition.
3008  * @return <0 if an error occured
3009  */
3010 static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count){
3011     int mb_num=0;
3012     static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
3013
3014     s->mb_x= s->resync_mb_x;
3015     s->first_slice_line=1;
3016     for(s->mb_y= s->resync_mb_y; mb_num < mb_count; s->mb_y++){
3017         ff_init_block_index(s);
3018         for(; mb_num < mb_count && s->mb_x<s->mb_width; s->mb_x++){
3019             const int xy= s->mb_x + s->mb_y*s->mb_stride;
3020
3021             mb_num++;
3022             ff_update_block_index(s);
3023             if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
3024                 s->first_slice_line=0;
3025             
3026             if(s->pict_type==I_TYPE){
3027                 int ac_pred= get_bits1(&s->gb);
3028                 int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3029                 if(cbpy<0){
3030                     fprintf(stderr, "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
3031                     return -1;
3032                 }
3033                 
3034                 s->cbp_table[xy]|= cbpy<<2;
3035                 s->current_picture.mb_type[xy] |= ac_pred*MB_TYPE_ACPRED; 
3036             }else{ /* P || S_TYPE */
3037                 if(IS_INTRA(s->current_picture.mb_type[xy])){          
3038                     int dir=0,i;
3039                     int ac_pred = get_bits1(&s->gb);
3040                     int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3041
3042                     if(cbpy<0){
3043                         fprintf(stderr, "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
3044                         return -1;
3045                     }
3046                     
3047                     if(s->cbp_table[xy] & 8) {
3048                         change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
3049                     }
3050                     s->current_picture.qscale_table[xy]= s->qscale;
3051
3052                     for(i=0; i<6; i++){
3053                         int dc_pred_dir;
3054                         int dc= mpeg4_decode_dc(s, i, &dc_pred_dir); 
3055                         if(dc < 0){
3056                             fprintf(stderr, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
3057                             return -1;
3058                         }
3059                         dir<<=1;
3060                         if(dc_pred_dir) dir|=1;
3061                     }
3062                     s->cbp_table[xy]&= 3; //remove dquant
3063                     s->cbp_table[xy]|= cbpy<<2;
3064                     s->current_picture.mb_type[xy] |= ac_pred*MB_TYPE_ACPRED; 
3065                     s->pred_dir_table[xy]= dir;
3066                 }else if(IS_SKIP(s->current_picture.mb_type[xy])){
3067                     s->current_picture.qscale_table[xy]= s->qscale;
3068                     s->cbp_table[xy]= 0;
3069                 }else{
3070                     int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3071
3072                     if(cbpy<0){
3073                         fprintf(stderr, "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
3074                         return -1;
3075                     }
3076                     
3077                     if(s->cbp_table[xy] & 8) {
3078                         change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
3079                     }
3080                     s->current_picture.qscale_table[xy]= s->qscale;
3081
3082                     s->cbp_table[xy]&= 3; //remove dquant
3083                     s->cbp_table[xy]|= (cbpy^0xf)<<2;
3084                 }
3085             }
3086         }
3087         if(mb_num >= mb_count) return 0;
3088         s->mb_x= 0;
3089     }
3090     return 0;
3091 }
3092
3093 /**
3094  * decodes the first & second partition
3095  * @return <0 if error (and sets error type in the error_status_table)
3096  */
3097 int ff_mpeg4_decode_partitions(MpegEncContext *s)
3098 {
3099     int mb_num;
3100     const int part_a_error= s->pict_type==I_TYPE ? (DC_ERROR|MV_ERROR) : MV_ERROR;
3101     const int part_a_end  = s->pict_type==I_TYPE ? (DC_END  |MV_END)   : MV_END;
3102     
3103     mb_num= mpeg4_decode_partition_a(s);    
3104     if(mb_num<0){
3105         ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error);
3106         return -1;
3107     }
3108     
3109     if(s->resync_mb_x + s->resync_mb_y*s->mb_width + mb_num > s->mb_num){
3110         fprintf(stderr, "slice below monitor ...\n");
3111         ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error);
3112         return -1;
3113     }
3114
3115     s->mb_num_left= mb_num;
3116         
3117     if(s->pict_type==I_TYPE){
3118         if(get_bits_long(&s->gb, 19)!=DC_MARKER){
3119             fprintf(stderr, "marker missing after first I partition at %d %d\n", s->mb_x, s->mb_y);
3120             return -1;
3121         }
3122     }else{
3123         if(get_bits(&s->gb, 17)!=MOTION_MARKER){
3124             fprintf(stderr, "marker missing after first P partition at %d %d\n", s->mb_x, s->mb_y);
3125             return -1;
3126         }
3127     }
3128     ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, part_a_end);
3129     
3130     if( mpeg4_decode_partition_b(s, mb_num) < 0){
3131         if(s->pict_type==P_TYPE)
3132             ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, DC_ERROR);
3133         return -1;
3134     }else{
3135         if(s->pict_type==P_TYPE)
3136             ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, DC_END);
3137     }
3138
3139     return 0;        
3140 }
3141
3142 /**
3143  * decode partition C of one MB.
3144  * @return <0 if an error occured
3145  */
3146 static int mpeg4_decode_partitioned_mb(MpegEncContext *s, DCTELEM block[6][64])
3147 {
3148     int cbp, mb_type;
3149     const int xy= s->mb_x + s->mb_y*s->mb_stride;
3150
3151     mb_type= s->current_picture.mb_type[xy];
3152     cbp = s->cbp_table[xy];
3153
3154     if(s->current_picture.qscale_table[xy] != s->qscale){
3155         s->qscale= s->current_picture.qscale_table[xy];
3156         s->y_dc_scale= s->y_dc_scale_table[ s->qscale ];
3157         s->c_dc_scale= s->c_dc_scale_table[ s->qscale ];
3158     }
3159     
3160     if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
3161         int i;
3162         for(i=0; i<4; i++){
3163             s->mv[0][i][0] = s->motion_val[ s->block_index[i] ][0];
3164             s->mv[0][i][1] = s->motion_val[ s->block_index[i] ][1];
3165         }
3166         s->mb_intra = IS_INTRA(mb_type);
3167
3168         if (IS_SKIP(mb_type)) {
3169             /* skip mb */
3170             for(i=0;i<6;i++)
3171                 s->block_last_index[i] = -1;
3172             s->mv_dir = MV_DIR_FORWARD;
3173             s->mv_type = MV_TYPE_16X16;
3174             if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3175                 s->mcsel=1;
3176                 s->mb_skiped = 0;
3177             }else{
3178                 s->mcsel=0;
3179                 s->mb_skiped = 1;
3180             }
3181         }else if(s->mb_intra){
3182             s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
3183         }else if(!s->mb_intra){
3184 //            s->mcsel= 0; //FIXME do we need to init that
3185             
3186             s->mv_dir = MV_DIR_FORWARD;
3187             if (IS_8X8(mb_type)) {
3188                 s->mv_type = MV_TYPE_8X8;
3189             } else {
3190                 s->mv_type = MV_TYPE_16X16;
3191             }
3192         }
3193     } else { /* I-Frame */
3194         s->mb_intra = 1;
3195         s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
3196     }
3197
3198     if (!IS_SKIP(mb_type)) {
3199         int i;
3200         /* decode each block */
3201         for (i = 0; i < 6; i++) {
3202             if(mpeg4_decode_block(s, block[i], i, cbp&32, s->mb_intra, s->rvlc) < 0){
3203                 fprintf(stderr, "texture corrupted at %d %d %d\n", s->mb_x, s->mb_y, s->mb_intra);
3204                 return -1;
3205             }
3206             cbp+=cbp;
3207         }
3208     }
3209
3210     /* per-MB end of slice check */
3211
3212     if(--s->mb_num_left <= 0){
3213 //printf("%06X %d\n", show_bits(&s->gb, 24), s->gb.size_in_bits - get_bits_count(&s->gb));
3214         if(mpeg4_is_resync(s))
3215             return SLICE_END;
3216         else
3217             return SLICE_NOEND;     
3218     }else{
3219         if(mpeg4_is_resync(s)){
3220             const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
3221             if(s->cbp_table[xy+delta])
3222                 return SLICE_END;
3223         }
3224         return SLICE_OK;
3225     }
3226 }
3227
3228 int ff_h263_decode_mb(MpegEncContext *s,
3229                       DCTELEM block[6][64])
3230 {
3231     int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
3232     int16_t *mot_val;
3233     static int8_t quant_tab[4] = { -1, -2, 1, 2 };
3234     const int xy= s->mb_x + s->mb_y * s->mb_stride;
3235
3236     if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
3237         if (get_bits1(&s->gb)) {
3238             /* skip mb */
3239             s->mb_intra = 0;
3240             for(i=0;i<6;i++)
3241                 s->block_last_index[i] = -1;
3242             s->mv_dir = MV_DIR_FORWARD;
3243             s->mv_type = MV_TYPE_16X16;
3244             if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3245                 s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0;
3246                 s->mcsel=1;
3247                 s->mv[0][0][0]= get_amv(s, 0);
3248                 s->mv[0][0][1]= get_amv(s, 1);
3249
3250                 s->mb_skiped = 0;
3251             }else{
3252                 s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
3253                 s->mcsel=0;
3254                 s->mv[0][0][0] = 0;
3255                 s->mv[0][0][1] = 0;
3256                 s->mb_skiped = 1;
3257             }
3258             goto end;
3259         }
3260         cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
3261         //fprintf(stderr, "\tCBPC: %d", cbpc);
3262         if (cbpc < 0)
3263             return -1;
3264         if (cbpc > 20)
3265             cbpc+=3;
3266         else if (cbpc == 20)
3267             fprintf(stderr, "Stuffing !");
3268         
3269         dquant = cbpc & 8;
3270         s->mb_intra = ((cbpc & 4) != 0);
3271         if (s->mb_intra) goto intra;
3272         
3273         if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
3274             s->mcsel= get_bits1(&s->gb);
3275         else s->mcsel= 0;
3276         cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3277         cbp = (cbpc & 3) | ((cbpy ^ 0xf) << 2);
3278         if (dquant) {
3279             change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
3280         }
3281         if((!s->progressive_sequence) && (cbp || (s->workaround_bugs&FF_BUG_XVID_ILACE)))
3282             s->interlaced_dct= get_bits1(&s->gb);
3283         
3284         s->mv_dir = MV_DIR_FORWARD;
3285         if ((cbpc & 16) == 0) {
3286             if(s->mcsel){
3287                 s->current_picture.mb_type[xy]= MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0;
3288                 /* 16x16 global motion prediction */
3289                 s->mv_type = MV_TYPE_16X16;
3290                 mx= get_amv(s, 0);
3291                 my= get_amv(s, 1);
3292                 s->mv[0][0][0] = mx;
3293                 s->mv[0][0][1] = my;
3294             }else if((!s->progressive_sequence) && get_bits1(&s->gb)){
3295                 s->current_picture.mb_type[xy]= MB_TYPE_16x8 | MB_TYPE_L0 | MB_TYPE_INTERLACED; 
3296                 /* 16x8 field motion prediction */
3297                 s->mv_type= MV_TYPE_FIELD;
3298
3299                 s->field_select[0][0]= get_bits1(&s->gb);
3300                 s->field_select[0][1]= get_bits1(&s->gb);
3301
3302                 h263_pred_motion(s, 0, &pred_x, &pred_y);
3303                 
3304                 for(i=0; i<2; i++){
3305                     mx = h263_decode_motion(s, pred_x, s->f_code);
3306                     if (mx >= 0xffff)
3307                         return -1;
3308             
3309                     my = h263_decode_motion(s, pred_y/2, s->f_code);
3310                     if (my >= 0xffff)
3311                         return -1;
3312
3313                     s->mv[0][i][0] = mx;
3314                     s->mv[0][i][1] = my;
3315                 }
3316             }else{
3317                 s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0; 
3318                 /* 16x16 motion prediction */
3319                 s->mv_type = MV_TYPE_16X16;
3320                 h263_pred_motion(s, 0, &pred_x, &pred_y);
3321                 if (s->umvplus)
3322                    mx = h263p_decode_umotion(s, pred_x);
3323                 else
3324                    mx = h263_decode_motion(s, pred_x, s->f_code);
3325             
3326                 if (mx >= 0xffff)
3327                     return -1;
3328             
3329                 if (s->umvplus)
3330                    my = h263p_decode_umotion(s, pred_y);
3331                 else
3332                    my = h263_decode_motion(s, pred_y, s->f_code);
3333             
3334                 if (my >= 0xffff)
3335                     return -1;
3336                 s->mv[0][0][0] = mx;
3337                 s->mv[0][0][1] = my;
3338
3339                 if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
3340                    skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */                   
3341             }
3342         } else {
3343             s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0; 
3344             s->mv_type = MV_TYPE_8X8;
3345             for(i=0;i<4;i++) {
3346                 mot_val = h263_pred_motion(s, i, &pred_x, &pred_y);
3347                 if (s->umvplus)
3348                   mx = h263p_decode_umotion(s, pred_x);
3349                 else
3350                   mx = h263_decode_motion(s, pred_x, s->f_code);
3351                 if (mx >= 0xffff)
3352                     return -1;
3353                 
3354                 if (s->umvplus)
3355                   my = h263p_decode_umotion(s, pred_y);
3356                 else    
3357                   my = h263_decode_motion(s, pred_y, s->f_code);
3358                 if (my >= 0xffff)
3359                     return -1;
3360                 s->mv[0][i][0] = mx;
3361                 s->mv[0][i][1] = my;
3362                 if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
3363                   skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
3364                 mot_val[0] = mx;
3365                 mot_val[1] = my;
3366             }
3367         }
3368     } else if(s->pict_type==B_TYPE) {
3369         int modb1; // first bit of modb
3370         int modb2; // second bit of modb
3371         int mb_type;
3372
3373         s->mb_intra = 0; //B-frames never contain intra blocks
3374         s->mcsel=0;      //     ...               true gmc blocks
3375
3376         if(s->mb_x==0){
3377             for(i=0; i<2; i++){
3378                 s->last_mv[i][0][0]= 
3379                 s->last_mv[i][0][1]= 
3380                 s->last_mv[i][1][0]= 
3381                 s->last_mv[i][1][1]= 0;
3382             }
3383         }
3384
3385         /* if we skipped it in the future P Frame than skip it now too */
3386         s->mb_skiped= s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]; // Note, skiptab=0 if last was GMC
3387
3388         if(s->mb_skiped){
3389                 /* skip mb */
3390             for(i=0;i<6;i++)
3391                 s->block_last_index[i] = -1;
3392
3393             s->mv_dir = MV_DIR_FORWARD;
3394             s->mv_type = MV_TYPE_16X16;
3395             s->mv[0][0][0] = 0;
3396             s->mv[0][0][1] = 0;
3397             s->mv[1][0][0] = 0;
3398             s->mv[1][0][1] = 0;
3399             s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; 
3400             goto end;
3401         }
3402
3403         modb1= get_bits1(&s->gb); 
3404         if(modb1){
3405             mb_type= MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1; //like MB_TYPE_B_DIRECT but no vectors coded
3406             cbp=0;
3407         }else{
3408             modb2= get_bits1(&s->gb);
3409             mb_type= get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);
3410             if(mb_type<0){
3411                 printf("illegal MB_type\n");
3412                 return -1;
3413             }
3414             mb_type= mb_type_b_map[ mb_type ];
3415             if(modb2) cbp= 0;
3416             else      cbp= get_bits(&s->gb, 6);
3417
3418             if ((!IS_DIRECT(mb_type)) && cbp) {
3419                 if(get_bits1(&s->gb)){
3420                     change_qscale(s, get_bits1(&s->gb)*4 - 2);
3421                 }
3422             }
3423
3424             if(!s->progressive_sequence){
3425                 if(cbp)
3426                     s->interlaced_dct= get_bits1(&s->gb);
3427
3428                 if(!IS_DIRECT(mb_type) && get_bits1(&s->gb)){
3429                     mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
3430                     mb_type &= ~MB_TYPE_16x16;
3431
3432                     if(USES_LIST(mb_type, 0)){
3433                         s->field_select[0][0]= get_bits1(&s->gb);
3434                         s->field_select[0][1]= get_bits1(&s->gb);
3435                     }
3436                     if(USES_LIST(mb_type, 1)){
3437                         s->field_select[1][0]= get_bits1(&s->gb);
3438                         s->field_select[1][1]= get_bits1(&s->gb);
3439                     }
3440                 }
3441             }
3442
3443             s->mv_dir = 0;
3444             if((mb_type & (MB_TYPE_DIRECT2|MB_TYPE_INTERLACED)) == 0){
3445                 s->mv_type= MV_TYPE_16X16;
3446
3447                 if(USES_LIST(mb_type, 0)){
3448                     s->mv_dir = MV_DIR_FORWARD;
3449
3450                     mx = h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
3451                     my = h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
3452                     s->last_mv[0][1][0]= s->last_mv[0][0][0]= s->mv[0][0][0] = mx;
3453                     s->last_mv[0][1][1]= s->last_mv[0][0][1]= s->mv[0][0][1] = my;
3454                 }
3455     
3456                 if(USES_LIST(mb_type, 1)){
3457                     s->mv_dir |= MV_DIR_BACKWARD;
3458
3459                     mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
3460                     my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
3461                     s->last_mv[1][1][0]= s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
3462                     s->last_mv[1][1][1]= s->last_mv[1][0][1]= s->mv[1][0][1] = my;
3463                 }
3464             }else if(!IS_DIRECT(mb_type)){
3465                 s->mv_type= MV_TYPE_FIELD;
3466
3467                 if(USES_LIST(mb_type, 0)){
3468                     s->mv_dir = MV_DIR_FORWARD;
3469                 
3470                     for(i=0; i<2; i++){
3471                         mx = h263_decode_motion(s, s->last_mv[0][i][0]  , s->f_code);
3472                         my = h263_decode_motion(s, s->last_mv[0][i][1]/2, s->f_code);
3473                         s->last_mv[0][i][0]=  s->mv[0][i][0] = mx;
3474                         s->last_mv[0][i][1]= (s->mv[0][i][1] = my)*2;
3475                     }
3476                 }
3477     
3478                 if(USES_LIST(mb_type, 1)){
3479                     s->mv_dir |= MV_DIR_BACKWARD;
3480
3481                     for(i=0; i<2; i++){
3482                         mx = h263_decode_motion(s, s->last_mv[1][i][0]  , s->b_code);
3483                         my = h263_decode_motion(s, s->last_mv[1][i][1]/2, s->b_code);
3484                         s->last_mv[1][i][0]=  s->mv[1][i][0] = mx;
3485                         s->last_mv[1][i][1]= (s->mv[1][i][1] = my)*2;
3486                     }
3487                 }
3488             }
3489         }
3490           
3491         if(IS_DIRECT(mb_type)){
3492             if(IS_SKIP(mb_type))
3493                 mx=my=0;
3494             else{
3495                 mx = h263_decode_motion(s, 0, 1);
3496                 my = h263_decode_motion(s, 0, 1);
3497             }
3498  
3499             s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
3500             mb_type |= ff_mpeg4_set_direct_mv(s, mx, my);
3501         }
3502         s->current_picture.mb_type[xy]= mb_type;
3503     } else { /* I-Frame */
3504         cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 1);
3505         if (cbpc < 0)
3506             return -1;
3507         dquant = cbpc & 4;
3508         s->mb_intra = 1;
3509 intra:
3510         s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
3511         if (s->h263_pred || s->h263_aic) {
3512             s->ac_pred = get_bits1(&s->gb);
3513             if(s->ac_pred){
3514                 s->current_picture.mb_type[xy]= MB_TYPE_INTRA | MB_TYPE_ACPRED;
3515             
3516                 if (s->h263_aic)
3517                     s->h263_aic_dir = get_bits1(&s->gb);
3518             }
3519         }else
3520             s->ac_pred = 0;
3521         
3522         cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3523         if(cbpy<0) return -1;
3524         cbp = (cbpc & 3) | (cbpy << 2);
3525         if (dquant) {
3526             change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
3527         }
3528         
3529         if(!s->progressive_sequence)
3530             s->interlaced_dct= get_bits1(&s->gb);
3531
3532         /* decode each block */
3533         if (s->h263_pred) {
3534             for (i = 0; i < 6; i++) {
3535                 if (mpeg4_decode_block(s, block[i], i, cbp&32, 1, 0) < 0)
3536                     return -1;
3537                 cbp+=cbp;
3538             }
3539         } else {
3540             for (i = 0; i < 6; i++) {
3541                 if (h263_decode_block(s, block[i], i, cbp&32) < 0)
3542                     return -1;
3543                 cbp+=cbp;
3544             }
3545         }
3546         goto end;
3547     }
3548
3549     /* decode each block */
3550     if (s->h263_pred) {
3551         for (i = 0; i < 6; i++) {
3552             if (mpeg4_decode_block(s, block[i], i, cbp&32, 0, 0) < 0)
3553                 return -1;
3554             cbp+=cbp;
3555         }
3556     } else {
3557         for (i = 0; i < 6; i++) {
3558             if (h263_decode_block(s, block[i], i, cbp&32) < 0)
3559                 return -1;
3560             cbp+=cbp;
3561         }
3562     }
3563 end:
3564
3565         /* per-MB end of slice check */
3566     if(s->codec_id==CODEC_ID_MPEG4){
3567         if(mpeg4_is_resync(s)){
3568             const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
3569             if(s->pict_type==B_TYPE && s->next_picture.mbskip_table[xy + delta])
3570                 return SLICE_OK;
3571             return SLICE_END;
3572         }
3573     }else{
3574         int v= show_bits(&s->gb, 16);
3575     
3576         if(get_bits_count(&s->gb) + 16 > s->gb.size_in_bits){
3577             v>>= get_bits_count(&s->gb) + 16 - s->gb.size_in_bits;
3578         }
3579
3580         if(v==0)
3581             return SLICE_END;
3582     }
3583
3584     return SLICE_OK;     
3585 }
3586
3587 static int h263_decode_motion(MpegEncContext * s, int pred, int f_code)
3588 {
3589     int code, val, sign, shift, l;
3590     code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
3591
3592     if (code == 0)
3593         return pred;
3594     if (code < 0)
3595         return 0xffff;
3596
3597     sign = get_bits1(&s->gb);
3598     shift = f_code - 1;
3599     val = code;
3600     if (shift) {
3601         val = (val - 1) << shift;
3602         val |= get_bits(&s->gb, shift);
3603         val++;
3604     }
3605     if (sign)
3606         val = -val;
3607     val += pred;
3608
3609     /* modulo decoding */
3610     if (!s->h263_long_vectors) {
3611         l = 1 << (f_code + 4);
3612         val = ((val + l)&(l*2-1)) - l;
3613     } else {
3614         /* horrible h263 long vector mode */
3615         if (pred < -31 && val < -63)
3616             val += 64;
3617         if (pred > 32 && val > 63)
3618             val -= 64;
3619         
3620     }
3621     return val;
3622 }
3623
3624 /* Decodes RVLC of H.263+ UMV */
3625 static int h263p_decode_umotion(MpegEncContext * s, int pred)
3626 {
3627    int code = 0, sign;
3628    
3629    if (get_bits1(&s->gb)) /* Motion difference = 0 */
3630       return pred;
3631    
3632    code = 2 + get_bits1(&s->gb);
3633    
3634    while (get_bits1(&s->gb))
3635    {
3636       code <<= 1;
3637       code += get_bits1(&s->gb);
3638    }
3639    sign = code & 1;
3640    code >>= 1;
3641    
3642    code = (sign) ? (pred - code) : (pred + code);
3643 #ifdef DEBUG
3644    fprintf(stderr,"H.263+ UMV Motion = %d\n", code);
3645 #endif
3646    return code;   
3647
3648 }
3649
3650 static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
3651                              int n, int coded)
3652 {
3653     int code, level, i, j, last, run;
3654     RLTable *rl = &rl_inter;
3655     const uint8_t *scan_table;
3656
3657     scan_table = s->intra_scantable.permutated;
3658     if (s->h263_aic && s->mb_intra) {
3659         rl = &rl_intra_aic;
3660         i = 0;
3661         if (s->ac_pred) {
3662             if (s->h263_aic_dir) 
3663                 scan_table = s->intra_v_scantable.permutated; /* left */
3664             else
3665                 scan_table = s->intra_h_scantable.permutated; /* top */
3666         }
3667     } else if (s->mb_intra) {
3668         /* DC coef */
3669         if(s->h263_rv10){
3670           if (s->rv10_version == 3 && s->pict_type == I_TYPE) {
3671             int component, diff;
3672             component = (n <= 3 ? 0 : n - 4 + 1);
3673             level = s->last_dc[component];
3674             if (s->rv10_first_dc_coded[component]) {
3675                 diff = rv_decode_dc(s, n);
3676                 if (diff == 0xffff)
3677                     return -1;
3678                 level += diff;
3679                 level = level & 0xff; /* handle wrap round */
3680                 s->last_dc[component] = level;
3681             } else {
3682                 s->rv10_first_dc_coded[component] = 1;
3683             }
3684           } else {
3685                 level = get_bits(&s->gb, 8);
3686           }
3687         }else{
3688             level = get_bits(&s->gb, 8);
3689             if((level&0x7F) == 0){
3690                 fprintf(stderr, "illegal dc %d at %d %d\n", level, s->mb_x, s->mb_y);
3691                 return -1;
3692             }
3693             if (level == 255)
3694                 level = 128;
3695         }
3696         block[0] = level;
3697         i = 1;
3698     } else {
3699         i = 0;
3700     }
3701     if (!coded) {
3702         if (s->mb_intra && s->h263_aic)
3703             goto not_coded;
3704         s->block_last_index[n] = i - 1;
3705         return 0;
3706     }
3707
3708     for(;;) {
3709         code = get_vlc2(&s->gb, rl->vlc.table, TEX_VLC_BITS, 2);
3710         if (code < 0){
3711             fprintf(stderr, "illegal ac vlc code at %dx%d\n", s->mb_x, s->mb_y);
3712             return -1;
3713         }
3714         if (code == rl->n) {
3715             /* escape */
3716             if (s->h263_flv > 1) {
3717                 int is11 = get_bits1(&s->gb);
3718                 last = get_bits1(&s->gb);
3719                 run = get_bits(&s->gb, 6);
3720                 if(is11){
3721                     level = get_sbits(&s->gb, 11);
3722                 } else {
3723                     level = get_sbits(&s->gb, 7);
3724                 }
3725             } else {
3726                 last = get_bits1(&s->gb);
3727                 run = get_bits(&s->gb, 6);
3728                 level = (int8_t)get_bits(&s->gb, 8);
3729                 if(level == -128){
3730                     if (s->h263_rv10) {
3731                         /* XXX: should patch encoder too */
3732                         level = get_sbits(&s->gb, 12);
3733                     }else{
3734                         level = get_bits(&s->gb, 5);
3735                         level |= get_sbits(&s->gb, 6)<<5;
3736                     }
3737                 }
3738             }
3739         } else {
3740             run = rl->table_run[code];
3741             level = rl->table_level[code];
3742             last = code >= rl->last;
3743             if (get_bits1(&s->gb))
3744                 level = -level;
3745         }
3746         i += run;
3747         if (i >= 64){
3748             fprintf(stderr, "run overflow at %dx%d\n", s->mb_x, s->mb_y);
3749             return -1;
3750         }
3751         j = scan_table[i];
3752         block[j] = level;
3753         if (last)
3754             break;
3755         i++;
3756     }
3757 not_coded:    
3758     if (s->mb_intra && s->h263_aic) {
3759         h263_pred_acdc(s, block, n);
3760         i = 63;
3761     }
3762     s->block_last_index[n] = i;
3763     return 0;
3764 }
3765
3766 /**
3767  * decodes the dc value.
3768  * @param n block index (0-3 are luma, 4-5 are chroma)
3769  * @param dir_ptr the prediction direction will be stored here
3770  * @return the quantized dc
3771  */
3772 static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr)
3773 {
3774     int level, pred, code;
3775     uint16_t *dc_val;
3776
3777     if (n < 4) 
3778         code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1);
3779     else 
3780         code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1);
3781     if (code < 0 || code > 9 /* && s->nbit<9 */){
3782         fprintf(stderr, "illegal dc vlc\n");
3783         return -1;
3784     }
3785     if (code == 0) {
3786         level = 0;
3787     } else {
3788         if(IS_3IV1){
3789             if(code==1)
3790                 level= 2*get_bits1(&s->gb)-1;
3791             else{
3792                 if(get_bits1(&s->gb))
3793                     level = get_bits(&s->gb, code-1) + (1<<(code-1));
3794                 else
3795                     level = -get_bits(&s->gb, code-1) - (1<<(code-1));
3796             }
3797         }else{
3798             level = get_xbits(&s->gb, code);
3799         }
3800
3801         if (code > 8){
3802             if(get_bits1(&s->gb)==0){ /* marker */
3803                 if(s->error_resilience>=2){
3804                     fprintf(stderr, "dc marker bit missing\n");
3805                     return -1;
3806                 }
3807             }
3808         }
3809     }
3810     pred = ff_mpeg4_pred_dc(s, n, &dc_val, dir_ptr);
3811     level += pred;
3812     if (level < 0){
3813         if(s->error_resilience>=3){
3814             fprintf(stderr, "dc<0 at %dx%d\n", s->mb_x, s->mb_y);
3815             return -1;
3816         }
3817         level = 0;
3818     }
3819     if (n < 4) {
3820         *dc_val = level * s->y_dc_scale;
3821     } else {
3822         *dc_val = level * s->c_dc_scale;
3823     }
3824     if(IS_3IV1)
3825         *dc_val = level * 8;
3826     
3827     if(s->error_resilience>=3){
3828         if(*dc_val > 2048 + s->y_dc_scale + s->c_dc_scale){
3829             fprintf(stderr, "dc overflow at %dx%d\n", s->mb_x, s->mb_y);
3830             return -1;
3831         }
3832     }
3833     return level;
3834 }
3835
3836 /**
3837  * decodes a block.
3838  * @return <0 if an error occured
3839  */
3840 static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
3841                               int n, int coded, int intra, int rvlc)
3842 {
3843     int level, i, last, run;
3844     int dc_pred_dir;
3845     RLTable * rl;
3846     RL_VLC_ELEM * rl_vlc;
3847     const uint8_t * scan_table;
3848     int qmul, qadd;
3849
3850     //Note intra & rvlc should be optimized away if this is inlined
3851     
3852     if(intra) {
3853         /* DC coef */
3854         if(s->partitioned_frame){
3855             level = s->dc_val[0][ s->block_index[n] ];
3856             if(n<4) level= FASTDIV((level + (s->y_dc_scale>>1)), s->y_dc_scale);
3857             else    level= FASTDIV((level + (s->c_dc_scale>>1)), s->c_dc_scale);
3858             dc_pred_dir= (s->pred_dir_table[s->mb_x + s->mb_y*s->mb_stride]<<n)&32;
3859         }else{
3860             level = mpeg4_decode_dc(s, n, &dc_pred_dir);
3861             if (level < 0)
3862                 return -1;
3863         }
3864         block[0] = level;
3865         i = 0;
3866         if (!coded) 
3867             goto not_coded;
3868         
3869         if(rvlc){        
3870             rl = &rvlc_rl_intra;
3871             rl_vlc = rvlc_rl_intra.rl_vlc[0];
3872         }else{
3873             rl = &rl_intra;
3874             rl_vlc = rl_intra.rl_vlc[0];
3875         }
3876         if (s->ac_pred) {
3877             if (dc_pred_dir == 0) 
3878                 scan_table = s->intra_v_scantable.permutated; /* left */
3879             else
3880                 scan_table = s->intra_h_scantable.permutated; /* top */
3881         } else {
3882             scan_table = s->intra_scantable.permutated;
3883         }
3884         qmul=1;
3885         qadd=0;
3886     } else {
3887         i = -1;
3888         if (!coded) {
3889             s->block_last_index[n] = i;
3890             return 0;
3891         }
3892         if(rvlc) rl = &rvlc_rl_inter;
3893         else     rl = &rl_inter;
3894    
3895         scan_table = s->intra_scantable.permutated;
3896
3897         if(s->mpeg_quant){
3898             qmul=1;
3899             qadd=0;
3900             if(rvlc){        
3901                 rl_vlc = rvlc_rl_inter.rl_vlc[0];        
3902             }else{
3903                 rl_vlc = rl_inter.rl_vlc[0];        
3904             }
3905         }else{
3906             qmul = s->qscale << 1;
3907             qadd = (s->qscale - 1) | 1;
3908             if(rvlc){        
3909                 rl_vlc = rvlc_rl_inter.rl_vlc[s->qscale];        
3910             }else{
3911                 rl_vlc = rl_inter.rl_vlc[s->qscale];        
3912             }
3913         }
3914     }
3915   {
3916     OPEN_READER(re, &s->gb);
3917     for(;;) {
3918         UPDATE_CACHE(re, &s->gb);
3919         GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
3920         if (level==0) {
3921           /* escape */                
3922           if(rvlc){
3923                 if(SHOW_UBITS(re, &s->gb, 1)==0){
3924                     fprintf(stderr, "1. marker bit missing in rvlc esc\n");
3925                     return -1;
3926                 }; SKIP_CACHE(re, &s->gb, 1);
3927  
3928                 last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);
3929                 run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);
3930                 SKIP_COUNTER(re, &s->gb, 1+1+6);
3931                 UPDATE_CACHE(re, &s->gb);
3932               
3933                 if(SHOW_UBITS(re, &s->gb, 1)==0){
3934                     fprintf(stderr, "2. marker bit missing in rvlc esc\n");
3935                     return -1;
3936                 }; SKIP_CACHE(re, &s->gb, 1);
3937  
3938                 level= SHOW_UBITS(re, &s->gb, 11); SKIP_CACHE(re, &s->gb, 11);
3939  
3940                 if(SHOW_UBITS(re, &s->gb, 5)!=0x10){
3941                     fprintf(stderr, "reverse esc missing\n");
3942                     return -1;
3943                 }; SKIP_CACHE(re, &s->gb, 5);
3944
3945                 level=  level * qmul + qadd;
3946                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_CACHE(re, &s->gb, 1);
3947                 SKIP_COUNTER(re, &s->gb, 1+11+5+1);
3948
3949                 i+= run + 1;
3950                 if(last) i+=192;
3951           }else{
3952             int cache;
3953             cache= GET_CACHE(re, &s->gb);
3954
3955             if(IS_3IV1) 
3956                 cache ^= 0xC0000000;
3957
3958             if (cache&0x80000000) {
3959                 if (cache&0x40000000) {
3960                     /* third escape */
3961                     SKIP_CACHE(re, &s->gb, 2);
3962                     last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);
3963                     run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);
3964                     SKIP_COUNTER(re, &s->gb, 2+1+6);
3965                     UPDATE_CACHE(re, &s->gb);
3966
3967                     if(IS_3IV1){
3968                         level= SHOW_SBITS(re, &s->gb, 12); LAST_SKIP_BITS(re, &s->gb, 12);
3969                     }else{
3970                         if(SHOW_UBITS(re, &s->gb, 1)==0){
3971                             fprintf(stderr, "1. marker bit missing in 3. esc\n");
3972                             return -1;
3973                         }; SKIP_CACHE(re, &s->gb, 1);
3974
3975                         level= SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12);
3976
3977                         if(SHOW_UBITS(re, &s->gb, 1)==0){
3978                             fprintf(stderr, "2. marker bit missing in 3. esc\n");
3979                             return -1;
3980                         }; LAST_SKIP_CACHE(re, &s->gb, 1);
3981
3982                         SKIP_COUNTER(re, &s->gb, 1+12+1);
3983                     }
3984  
3985                     if(level*s->qscale>1024 || level*s->qscale<-1024){
3986                         fprintf(stderr, "|level| overflow in 3. esc, qp=%d\n", s->qscale);
3987                         return -1;
3988                     }
3989 #if 1 
3990                     {
3991                         const int abs_level= ABS(level);
3992                         if(abs_level<=MAX_LEVEL && run<=MAX_RUN && !(s->workaround_bugs&FF_BUG_AC_VLC)){
3993                             const int run1= run - rl->max_run[last][abs_level] - 1;
3994                             if(abs_level <= rl->max_level[last][run]){
3995                                 fprintf(stderr, "illegal 3. esc, vlc encoding possible\n");
3996                                 return -1;
3997                             }
3998                             if(s->error_resilience > FF_ER_COMPLIANT){
3999                                 if(abs_level <= rl->max_level[last][run]*2){
4000                                     fprintf(stderr, "illegal 3. esc, esc 1 encoding possible\n");
4001                                     return -1;
4002                                 }
4003                                 if(run1 >= 0 && abs_level <= rl->max_level[last][run1]){
4004                                     fprintf(stderr, "illegal 3. esc, esc 2 encoding possible\n");
4005                                     return -1;
4006                                 }
4007                             }
4008                         }
4009                     }
4010 #endif
4011                     if (level>0) level= level * qmul + qadd;
4012                     else         level= level * qmul - qadd;
4013
4014                     i+= run + 1;
4015                     if(last) i+=192;
4016                 } else {
4017                     /* second escape */
4018 #if MIN_CACHE_BITS < 20
4019                     LAST_SKIP_BITS(re, &s->gb, 2);
4020                     UPDATE_CACHE(re, &s->gb);
4021 #else
4022                     SKIP_BITS(re, &s->gb, 2);
4023 #endif
4024                     GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
4025                     i+= run + rl->max_run[run>>7][level/qmul] +1; //FIXME opt indexing
4026                     level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
4027                     LAST_SKIP_BITS(re, &s->gb, 1);
4028                 }
4029             } else {
4030                 /* first escape */
4031 #if MIN_CACHE_BITS < 19
4032                 LAST_SKIP_BITS(re, &s->gb, 1);
4033                 UPDATE_CACHE(re, &s->gb);
4034 #else
4035                 SKIP_BITS(re, &s->gb, 1);
4036 #endif
4037                 GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
4038                 i+= run;
4039                 level = level + rl->max_level[run>>7][(run-1)&63] * qmul;//FIXME opt indexing
4040                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
4041                 LAST_SKIP_BITS(re, &s->gb, 1);
4042             }
4043           }
4044         } else {
4045             i+= run;
4046             level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
4047             LAST_SKIP_BITS(re, &s->gb, 1);
4048         }
4049         if (i > 62){
4050             i-= 192;
4051             if(i&(~63)){
4052                 fprintf(stderr, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
4053                 return -1;
4054             }
4055
4056             block[scan_table[i]] = level;
4057             break;
4058         }
4059
4060         block[scan_table[i]] = level;
4061     }
4062     CLOSE_READER(re, &s->gb);
4063   }
4064  not_coded:
4065     if (s->mb_intra) {
4066         mpeg4_pred_ac(s, block, n, dc_pred_dir);
4067         if (s->ac_pred) {
4068             i = 63; /* XXX: not optimal */
4069         }
4070     }
4071     s->block_last_index[n] = i;
4072     return 0;
4073 }
4074
4075 /* most is hardcoded. should extend to handle all h263 streams */
4076 int h263_decode_picture_header(MpegEncContext *s)
4077 {
4078     int format, width, height, i;
4079     uint32_t startcode;
4080     
4081     align_get_bits(&s->gb);
4082
4083     startcode= get_bits(&s->gb, 22-8);
4084
4085     for(i= s->gb.size_in_bits - get_bits_count(&s->gb); i>24; i-=8) {
4086         startcode = ((startcode << 8) | get_bits(&s->gb, 8)) & 0x003FFFFF;
4087         
4088         if(startcode == 0x20)
4089             break;
4090     }
4091         
4092     if (startcode != 0x20) {
4093         fprintf(stderr, "Bad picture start code\n");
4094         return -1;
4095     }
4096     /* temporal reference */
4097     s->picture_number = get_bits(&s->gb, 8); /* picture timestamp */
4098
4099     /* PTYPE starts here */    
4100     if (get_bits1(&s->gb) != 1) {
4101         /* marker */
4102         fprintf(stderr, "Bad marker\n");
4103         return -1;
4104     }
4105     if (get_bits1(&s->gb) != 0) {
4106         fprintf(stderr, "Bad H263 id\n");
4107         return -1;      /* h263 id */
4108     }
4109     skip_bits1(&s->gb); /* split screen off */
4110     skip_bits1(&s->gb); /* camera  off */
4111     skip_bits1(&s->gb); /* freeze picture release off */
4112
4113     /* Reset GOB number */
4114     s->gob_number = 0;
4115         
4116     format = get_bits(&s->gb, 3);
4117     /*
4118         0    forbidden
4119         1    sub-QCIF
4120         10   QCIF
4121         7       extended PTYPE (PLUSPTYPE)
4122     */
4123
4124     if (format != 7 && format != 6) {
4125         s->h263_plus = 0;
4126         /* H.263v1 */
4127         width = h263_format[format][0];
4128         height = h263_format[format][1];
4129         if (!width)
4130             return -1;
4131         
4132         s->pict_type = I_TYPE + get_bits1(&s->gb);
4133
4134         s->unrestricted_mv = get_bits1(&s->gb); 
4135         s->h263_long_vectors = s->unrestricted_mv;
4136
4137         if (get_bits1(&s->gb) != 0) {
4138             fprintf(stderr, "H263 SAC not supported\n");
4139             return -1;  /* SAC: off */
4140         }
4141         if (get_bits1(&s->gb) != 0) {
4142             s->mv_type = MV_TYPE_8X8; /* Advanced prediction mode */
4143         }   
4144         
4145         if (get_bits1(&s->gb) != 0) {
4146             fprintf(stderr, "H263 PB frame not supported\n");
4147             return -1;  /* not PB frame */
4148         }
4149         s->qscale = get_bits(&s->gb, 5);
4150         skip_bits1(&s->gb);     /* Continuous Presence Multipoint mode: off */
4151
4152         s->width = width;
4153         s->height = height;
4154     } else {
4155         int ufep;
4156         
4157         /* H.263v2 */
4158         s->h263_plus = 1;
4159         ufep = get_bits(&s->gb, 3); /* Update Full Extende