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