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