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