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