cc0c85e3e5f9964322e29afd0962c163f8118846
[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_rl(RLTable *rl)
2214 {
2215     INT8 max_level[MAX_RUN+1], max_run[MAX_LEVEL+1];
2216     UINT8 index_run[MAX_RUN+1];
2217     int last, run, level, start, end, i;
2218
2219     /* compute max_level[], max_run[] and index_run[] */
2220     for(last=0;last<2;last++) {
2221         if (last == 0) {
2222             start = 0;
2223             end = rl->last;
2224         } else {
2225             start = rl->last;
2226             end = rl->n;
2227         }
2228
2229         memset(max_level, 0, MAX_RUN + 1);
2230         memset(max_run, 0, MAX_LEVEL + 1);
2231         memset(index_run, rl->n, MAX_RUN + 1);
2232         for(i=start;i<end;i++) {
2233             run = rl->table_run[i];
2234             level = rl->table_level[i];
2235             if (index_run[run] == rl->n)
2236                 index_run[run] = i;
2237             if (level > max_level[run])
2238                 max_level[run] = level;
2239             if (run > max_run[level])
2240                 max_run[level] = run;
2241         }
2242         rl->max_level[last] = av_malloc(MAX_RUN + 1);
2243         memcpy(rl->max_level[last], max_level, MAX_RUN + 1);
2244         rl->max_run[last] = av_malloc(MAX_LEVEL + 1);
2245         memcpy(rl->max_run[last], max_run, MAX_LEVEL + 1);
2246         rl->index_run[last] = av_malloc(MAX_RUN + 1);
2247         memcpy(rl->index_run[last], index_run, MAX_RUN + 1);
2248     }
2249 }
2250
2251 void init_vlc_rl(RLTable *rl)
2252 {
2253     int i, q;
2254     
2255     init_vlc(&rl->vlc, 9, rl->n + 1, 
2256              &rl->table_vlc[0][1], 4, 2,
2257              &rl->table_vlc[0][0], 4, 2);
2258
2259     
2260     for(q=0; q<32; q++){
2261         int qmul= q*2;
2262         int qadd= (q-1)|1;
2263         
2264         if(q==0){
2265             qmul=1;
2266             qadd=0;
2267         }
2268         
2269         rl->rl_vlc[q]= av_malloc(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
2270         for(i=0; i<rl->vlc.table_size; i++){
2271             int code= rl->vlc.table[i][0];
2272             int len = rl->vlc.table[i][1];
2273             int level, run;
2274         
2275             if(len==0){ // illegal code
2276                 run= 66;
2277                 level= MAX_LEVEL;
2278             }else if(len<0){ //more bits needed
2279                 run= 0;
2280                 level= code;
2281             }else{
2282                 if(code==rl->n){ //esc
2283                     run= 66;
2284                     level= 0;
2285                 }else{
2286                     run=   rl->table_run  [code] + 1;
2287                     level= rl->table_level[code] * qmul + qadd;
2288                     if(code >= rl->last) run+=192;
2289                 }
2290             }
2291             rl->rl_vlc[q][i].len= len;
2292             rl->rl_vlc[q][i].level= level;
2293             rl->rl_vlc[q][i].run= run;
2294         }
2295     }
2296 }
2297
2298 /* init vlcs */
2299
2300 /* XXX: find a better solution to handle static init */
2301 void h263_decode_init_vlc(MpegEncContext *s)
2302 {
2303     static int done = 0;
2304
2305     if (!done) {
2306         done = 1;
2307
2308         init_vlc(&intra_MCBPC_vlc, INTRA_MCBPC_VLC_BITS, 8, 
2309                  intra_MCBPC_bits, 1, 1,
2310                  intra_MCBPC_code, 1, 1);
2311         init_vlc(&inter_MCBPC_vlc, INTER_MCBPC_VLC_BITS, 25, 
2312                  inter_MCBPC_bits, 1, 1,
2313                  inter_MCBPC_code, 1, 1);
2314         init_vlc(&cbpy_vlc, CBPY_VLC_BITS, 16,
2315                  &cbpy_tab[0][1], 2, 1,
2316                  &cbpy_tab[0][0], 2, 1);
2317         init_vlc(&mv_vlc, MV_VLC_BITS, 33,
2318                  &mvtab[0][1], 2, 1,
2319                  &mvtab[0][0], 2, 1);
2320         init_rl(&rl_inter);
2321         init_rl(&rl_intra);
2322         init_rl(&rl_intra_aic);
2323         init_vlc_rl(&rl_inter);
2324         init_vlc_rl(&rl_intra);
2325         init_vlc_rl(&rl_intra_aic);
2326         init_vlc(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
2327                  &DCtab_lum[0][1], 2, 1,
2328                  &DCtab_lum[0][0], 2, 1);
2329         init_vlc(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
2330                  &DCtab_chrom[0][1], 2, 1,
2331                  &DCtab_chrom[0][0], 2, 1);
2332         init_vlc(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
2333                  &sprite_trajectory_tab[0][1], 4, 2,
2334                  &sprite_trajectory_tab[0][0], 4, 2);
2335         init_vlc(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
2336                  &mb_type_b_tab[0][1], 2, 1,
2337                  &mb_type_b_tab[0][0], 2, 1);
2338     }
2339 }
2340
2341 /**
2342  * Get the GOB height based on picture height.
2343  */
2344 int ff_h263_get_gob_height(MpegEncContext *s){
2345     if (s->height <= 400)
2346         return 1;
2347     else if (s->height <= 800)
2348         return  2;
2349     else
2350         return 4;
2351 }
2352
2353 /**
2354  * decodes the group of blocks header.
2355  * @return <0 if an error occured
2356  */
2357 static int h263_decode_gob_header(MpegEncContext *s)
2358 {
2359     unsigned int val, gfid;
2360     int left;
2361     
2362     /* Check for GOB Start Code */
2363     val = show_bits(&s->gb, 16);
2364     if(val)
2365         return -1;
2366
2367         /* We have a GBSC probably with GSTUFF */
2368     skip_bits(&s->gb, 16); /* Drop the zeros */
2369     left= s->gb.size_in_bits - get_bits_count(&s->gb);
2370     //MN: we must check the bits left or we might end in a infinite loop (or segfault)
2371     for(;left>13; left--){
2372         if(get_bits1(&s->gb)) break; /* Seek the '1' bit */
2373     }
2374     if(left<=13) 
2375         return -1;
2376
2377 #ifdef DEBUG
2378     fprintf(stderr,"\nGOB Start Code at MB %d\n", (s->mb_y * s->mb_width) + s->mb_x);
2379 #endif
2380     s->gob_number = get_bits(&s->gb, 5); /* GN */
2381     gfid = get_bits(&s->gb, 2); /* GFID */
2382     s->qscale = get_bits(&s->gb, 5); /* GQUANT */
2383     if(s->qscale==0) 
2384         return -1;
2385     s->mb_x= 0;
2386     s->mb_y= s->gob_index* s->gob_number;
2387 #ifdef DEBUG
2388     fprintf(stderr, "\nGN: %u GFID: %u Quant: %u\n", s->gob_number, gfid, s->qscale);
2389 #endif
2390     return 0;
2391 }
2392
2393 static inline void memsetw(short *tab, int val, int n)
2394 {
2395     int i;
2396     for(i=0;i<n;i++)
2397         tab[i] = val;
2398 }
2399
2400 void ff_mpeg4_init_partitions(MpegEncContext *s)
2401 {
2402     init_put_bits(&s->tex_pb, s->tex_pb_buffer, PB_BUFFER_SIZE, NULL, NULL);
2403     init_put_bits(&s->pb2   , s->pb2_buffer   , PB_BUFFER_SIZE, NULL, NULL);
2404 }
2405
2406 void ff_mpeg4_merge_partitions(MpegEncContext *s)
2407 {
2408     const int pb2_len   = get_bit_count(&s->pb2   );
2409     const int tex_pb_len= get_bit_count(&s->tex_pb);
2410     const int bits= get_bit_count(&s->pb);
2411
2412     if(s->pict_type==I_TYPE){
2413         put_bits(&s->pb, 19, DC_MARKER);
2414         s->misc_bits+=19 + pb2_len + bits - s->last_bits;
2415         s->i_tex_bits+= tex_pb_len;
2416     }else{
2417         put_bits(&s->pb, 17, MOTION_MARKER);
2418         s->misc_bits+=17 + pb2_len;
2419         s->mv_bits+= bits - s->last_bits;
2420         s->p_tex_bits+= tex_pb_len;
2421     }
2422
2423     flush_put_bits(&s->pb2);
2424     flush_put_bits(&s->tex_pb);
2425
2426     ff_copy_bits(&s->pb, s->pb2_buffer   , pb2_len);
2427     ff_copy_bits(&s->pb, s->tex_pb_buffer, tex_pb_len);
2428     s->last_bits= get_bit_count(&s->pb);
2429 }
2430
2431 int ff_mpeg4_get_video_packet_prefix_length(MpegEncContext *s){
2432     switch(s->pict_type){
2433         case I_TYPE:
2434             return 16;
2435         case P_TYPE:
2436         case S_TYPE:
2437             return s->f_code+15;
2438         case B_TYPE:
2439             return FFMAX(FFMAX(s->f_code, s->b_code)+15, 17);
2440         default:
2441             return -1;
2442     }
2443 }
2444
2445 void ff_mpeg4_encode_video_packet_header(MpegEncContext *s)
2446 {
2447     int mb_num_bits= av_log2(s->mb_num - 1) + 1;
2448
2449     ff_mpeg4_stuffing(&s->pb);
2450     put_bits(&s->pb, ff_mpeg4_get_video_packet_prefix_length(s), 0);
2451     put_bits(&s->pb, 1, 1);
2452     
2453     put_bits(&s->pb, mb_num_bits, s->mb_x + s->mb_y*s->mb_width);
2454     put_bits(&s->pb, s->quant_precision, s->qscale);
2455     put_bits(&s->pb, 1, 0); /* no HEC */
2456 }
2457
2458 /**
2459  * check if the next stuff is a resync marker or the end.
2460  * @return 0 if not
2461  */
2462 static inline int mpeg4_is_resync(MpegEncContext *s){
2463     const int bits_count= get_bits_count(&s->gb);
2464     
2465     if(s->workaround_bugs&FF_BUG_NO_PADDING){
2466         return 0;
2467     }
2468
2469     if(bits_count + 8 >= s->gb.size_in_bits){
2470         int v= show_bits(&s->gb, 8);
2471         v|= 0x7F >> (7-(bits_count&7));
2472                 
2473         if(v==0x7F)
2474             return 1;
2475     }else{
2476         if(show_bits(&s->gb, 16) == ff_mpeg4_resync_prefix[bits_count&7]){
2477             int len;
2478             GetBitContext gb= s->gb;
2479         
2480             skip_bits(&s->gb, 1);
2481             align_get_bits(&s->gb);
2482         
2483             for(len=0; len<32; len++){
2484                 if(get_bits1(&s->gb)) break;
2485             }
2486
2487             s->gb= gb;
2488
2489             if(len>=ff_mpeg4_get_video_packet_prefix_length(s))
2490                 return 1;
2491         }
2492     }
2493     return 0;
2494 }
2495
2496 /**
2497  * decodes the next video packet.
2498  * @return <0 if something went wrong
2499  */
2500 static int mpeg4_decode_video_packet_header(MpegEncContext *s)
2501 {
2502     int mb_num_bits= av_log2(s->mb_num - 1) + 1;
2503     int header_extension=0, mb_num, len;
2504     
2505     /* is there enough space left for a video packet + header */
2506     if( get_bits_count(&s->gb) > s->gb.size_in_bits-20) return -1;
2507
2508     for(len=0; len<32; len++){
2509         if(get_bits1(&s->gb)) break;
2510     }
2511
2512     if(len!=ff_mpeg4_get_video_packet_prefix_length(s)){
2513         printf("marker does not match f_code\n");
2514         return -1;
2515     }
2516     
2517     if(s->shape != RECT_SHAPE){
2518         header_extension= get_bits1(&s->gb);
2519         //FIXME more stuff here
2520     }
2521
2522     mb_num= get_bits(&s->gb, mb_num_bits);
2523     if(mb_num>=s->mb_num){
2524         fprintf(stderr, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
2525         return -1;
2526     }
2527     s->mb_x= mb_num % s->mb_width;
2528     s->mb_y= mb_num / s->mb_width;
2529
2530     if(s->shape != BIN_ONLY_SHAPE){
2531         int qscale= get_bits(&s->gb, s->quant_precision); 
2532         if(qscale)
2533             s->qscale= qscale;
2534     }
2535
2536     if(s->shape == RECT_SHAPE){
2537         header_extension= get_bits1(&s->gb);
2538     }
2539     if(header_extension){
2540         int time_increment;
2541         int time_incr=0;
2542
2543         while (get_bits1(&s->gb) != 0) 
2544             time_incr++;
2545
2546         check_marker(&s->gb, "before time_increment in video packed header");
2547         time_increment= get_bits(&s->gb, s->time_increment_bits);
2548         check_marker(&s->gb, "before vop_coding_type in video packed header");
2549         
2550         skip_bits(&s->gb, 2); /* vop coding type */
2551         //FIXME not rect stuff here
2552
2553         if(s->shape != BIN_ONLY_SHAPE){
2554             skip_bits(&s->gb, 3); /* intra dc vlc threshold */
2555 //FIXME dont just ignore everything
2556             if(s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
2557                 mpeg4_decode_sprite_trajectory(s);
2558                 fprintf(stderr, "untested\n");
2559             }
2560
2561             //FIXME reduced res stuff here
2562             
2563             if (s->pict_type != I_TYPE) {
2564                 int f_code = get_bits(&s->gb, 3);       /* fcode_for */
2565                 if(f_code==0){
2566                     printf("Error, video packet header damaged (f_code=0)\n");
2567                 }
2568             }
2569             if (s->pict_type == B_TYPE) {
2570                 int b_code = get_bits(&s->gb, 3);
2571                 if(b_code==0){
2572                     printf("Error, video packet header damaged (b_code=0)\n");
2573                 }
2574             }       
2575         }
2576     }
2577     //FIXME new-pred stuff
2578     
2579 //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));
2580
2581     return 0;
2582 }
2583
2584 void ff_mpeg4_clean_buffers(MpegEncContext *s)
2585 {
2586     int c_wrap, c_xy, l_wrap, l_xy;
2587
2588     l_wrap= s->block_wrap[0];
2589     l_xy= s->mb_y*l_wrap*2 + s->mb_x*2;
2590     c_wrap= s->block_wrap[4];
2591     c_xy= s->mb_y*c_wrap + s->mb_x;
2592
2593 #if 0
2594     /* clean DC */
2595     memsetw(s->dc_val[0] + l_xy, 1024, l_wrap*2+1);
2596     memsetw(s->dc_val[1] + c_xy, 1024, c_wrap+1);
2597     memsetw(s->dc_val[2] + c_xy, 1024, c_wrap+1);
2598 #endif
2599
2600     /* clean AC */
2601     memset(s->ac_val[0] + l_xy, 0, (l_wrap*2+1)*16*sizeof(INT16));
2602     memset(s->ac_val[1] + c_xy, 0, (c_wrap  +1)*16*sizeof(INT16));
2603     memset(s->ac_val[2] + c_xy, 0, (c_wrap  +1)*16*sizeof(INT16));
2604
2605     /* clean MV */
2606     // we cant clear the MVs as they might be needed by a b frame
2607 //    memset(s->motion_val + l_xy, 0, (l_wrap*2+1)*2*sizeof(INT16));
2608 //    memset(s->motion_val, 0, 2*sizeof(INT16)*(2 + s->mb_width*2)*(2 + s->mb_height*2));
2609     s->last_mv[0][0][0]=
2610     s->last_mv[0][0][1]=
2611     s->last_mv[1][0][0]=
2612     s->last_mv[1][0][1]= 0;
2613 }
2614
2615 /**
2616  * decodes the group of blocks / video packet header.
2617  * @return <0 if no resync found
2618  */
2619 int ff_h263_resync(MpegEncContext *s){
2620     int left, ret;
2621     
2622     if(s->codec_id==CODEC_ID_MPEG4)
2623         skip_bits1(&s->gb);
2624     
2625     align_get_bits(&s->gb);
2626
2627     if(show_bits(&s->gb, 16)==0){
2628         if(s->codec_id==CODEC_ID_MPEG4)
2629             ret= mpeg4_decode_video_packet_header(s);
2630         else
2631             ret= h263_decode_gob_header(s);
2632         if(ret>=0)
2633             return 0;
2634     }
2635     //ok, its not where its supposed to be ...
2636     s->gb= s->last_resync_gb;
2637     align_get_bits(&s->gb);
2638     left= s->gb.size_in_bits - get_bits_count(&s->gb);
2639     
2640     for(;left>16+1+5+5; left-=8){ 
2641         if(show_bits(&s->gb, 16)==0){
2642             GetBitContext bak= s->gb;
2643
2644             if(s->codec_id==CODEC_ID_MPEG4)
2645                 ret= mpeg4_decode_video_packet_header(s);
2646             else
2647                 ret= h263_decode_gob_header(s);
2648             if(ret>=0)
2649                 return 0;
2650
2651             s->gb= bak;
2652         }
2653         skip_bits(&s->gb, 8);
2654     }
2655     
2656     return -1;
2657 }
2658
2659 /**
2660  * gets the average motion vector for a GMC MB.
2661  * @param n either 0 for the x component or 1 for y
2662  * @returns the average MV for a GMC MB
2663  */
2664 static inline int get_amv(MpegEncContext *s, int n){
2665     int x, y, mb_v, sum, dx, dy, shift;
2666     int len = 1 << (s->f_code + 4);
2667     const int a= s->sprite_warping_accuracy;
2668
2669     if(s->real_sprite_warping_points==1){
2670         if(s->divx_version==500 && s->divx_build==413)
2671             sum= s->sprite_offset[0][n] / (1<<(a - s->quarter_sample));
2672         else
2673             sum= RSHIFT(s->sprite_offset[0][n]<<s->quarter_sample, a);
2674     }else{
2675         dx= s->sprite_delta[n][0];
2676         dy= s->sprite_delta[n][1];
2677         shift= s->sprite_shift[0];
2678         if(n) dy -= 1<<(shift + a + 1);
2679         else  dx -= 1<<(shift + a + 1);
2680         mb_v= s->sprite_offset[0][n] + dx*s->mb_x*16 + dy*s->mb_y*16;
2681
2682         sum=0;
2683         for(y=0; y<16; y++){
2684             int v;
2685         
2686             v= mb_v + dy*y;
2687             //XXX FIXME optimize
2688             for(x=0; x<16; x++){
2689                 sum+= v>>shift;
2690                 v+= dx;
2691             }
2692         }
2693         sum= RSHIFT(sum, a+8-s->quarter_sample);
2694     }
2695
2696     if      (sum < -len) sum= -len;
2697     else if (sum >= len) sum= len-1;
2698
2699     return sum;
2700 }
2701
2702 /**
2703  * decodes first partition.
2704  * @return number of MBs decoded or <0 if an error occured
2705  */
2706 static int mpeg4_decode_partition_a(MpegEncContext *s){
2707     int mb_num;
2708     static const INT8 quant_tab[4] = { -1, -2, 1, 2 };
2709     
2710     /* decode first partition */
2711     mb_num=0;
2712     s->first_slice_line=1;
2713     for(; s->mb_y<s->mb_height; s->mb_y++){
2714         ff_init_block_index(s);
2715         for(; s->mb_x<s->mb_width; s->mb_x++){
2716             const int xy= s->mb_x + s->mb_y*s->mb_width;
2717             int cbpc;
2718             int dir=0;
2719             
2720             mb_num++;
2721             ff_update_block_index(s);
2722             if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
2723                 s->first_slice_line=0;
2724             
2725             if(s->mb_x==0) PRINT_MB_TYPE("\n");
2726
2727             if(s->pict_type==I_TYPE){
2728                 int i;
2729
2730                 if(show_bits(&s->gb, 19)==DC_MARKER){
2731                     return mb_num-1;
2732                 }
2733
2734                 PRINT_MB_TYPE("I");
2735                 cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 1);
2736                 if (cbpc < 0){
2737
2738                     fprintf(stderr, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
2739                     return -1;
2740                 }
2741                 s->cbp_table[xy]= cbpc & 3;
2742                 s->mb_type[xy]= MB_TYPE_INTRA;
2743                 s->mb_intra = 1;
2744
2745                 if(cbpc & 4) {
2746                     change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
2747                 }
2748                 s->current_picture.qscale_table[xy]= s->qscale;
2749
2750                 s->mbintra_table[xy]= 1;
2751                 for(i=0; i<6; i++){
2752                     int dc_pred_dir;
2753                     int dc= mpeg4_decode_dc(s, i, &dc_pred_dir); 
2754                     if(dc < 0){
2755                         fprintf(stderr, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
2756                         return -1;
2757                     }
2758                     dir<<=1;
2759                     if(dc_pred_dir) dir|=1;
2760                 }
2761                 s->pred_dir_table[xy]= dir;
2762                 
2763                 s->error_status_table[xy]= AC_ERROR;
2764             }else{ /* P/S_TYPE */
2765                 int mx, my, pred_x, pred_y, bits;
2766                 INT16 * const mot_val= s->motion_val[s->block_index[0]];
2767                 const int stride= s->block_wrap[0]*2;
2768
2769                 bits= show_bits(&s->gb, 17);
2770                 if(bits==MOTION_MARKER){
2771                     return mb_num-1;
2772                 }
2773                 skip_bits1(&s->gb);
2774                 if(bits&0x10000){
2775                     /* skip mb */
2776                     s->mb_type[xy]= MB_TYPE_SKIPED;
2777                     if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
2778                         PRINT_MB_TYPE("G");
2779                         mx= get_amv(s, 0);
2780                         my= get_amv(s, 1);
2781                     }else{
2782                         PRINT_MB_TYPE("S");
2783                         mx=my=0;
2784                     }
2785                     mot_val[0       ]= mot_val[2       ]=
2786                     mot_val[0+stride]= mot_val[2+stride]= mx;
2787                     mot_val[1       ]= mot_val[3       ]=
2788                     mot_val[1+stride]= mot_val[3+stride]= my;
2789
2790                     if(s->mbintra_table[xy])
2791                         ff_clean_intra_table_entries(s);
2792
2793                     s->error_status_table[xy]= AC_ERROR;
2794                     continue;
2795                 }
2796                 cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
2797                 if (cbpc < 0){
2798                     fprintf(stderr, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
2799                     return -1;
2800                 }
2801                 if (cbpc > 20)
2802                     cbpc+=3;
2803                 else if (cbpc == 20)
2804                     fprintf(stderr, "Stuffing !");
2805                 s->cbp_table[xy]= cbpc&(8+3); //8 is dquant
2806     
2807                 s->mb_intra = ((cbpc & 4) != 0);
2808         
2809                 if(s->mb_intra){
2810                     PRINT_MB_TYPE("I");
2811                     s->mbintra_table[xy]= 1;
2812                     s->mb_type[xy]= MB_TYPE_INTRA;
2813                     mot_val[0       ]= mot_val[2       ]= 
2814                     mot_val[0+stride]= mot_val[2+stride]= 0;
2815                     mot_val[1       ]= mot_val[3       ]=
2816                     mot_val[1+stride]= mot_val[3+stride]= 0;
2817                     s->error_status_table[xy]= DC_ERROR|AC_ERROR;
2818                 }else{
2819                     if(s->mbintra_table[xy])
2820                         ff_clean_intra_table_entries(s);
2821
2822                     if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
2823                         s->mcsel= get_bits1(&s->gb);
2824                     else s->mcsel= 0;
2825         
2826                     if ((cbpc & 16) == 0) {
2827                         PRINT_MB_TYPE("P");
2828                         /* 16x16 motion prediction */
2829                         s->mb_type[xy]= MB_TYPE_INTER;
2830
2831                         h263_pred_motion(s, 0, &pred_x, &pred_y);
2832                         if(!s->mcsel){
2833                             mx = h263_decode_motion(s, pred_x, s->f_code);
2834                             if (mx >= 0xffff)
2835                                 return -1;
2836
2837                             my = h263_decode_motion(s, pred_y, s->f_code);
2838                             if (my >= 0xffff)
2839                                 return -1;
2840                         } else {
2841                             mx = get_amv(s, 0);
2842                             my = get_amv(s, 1);
2843                         }
2844
2845                         mot_val[0       ]= mot_val[2       ] =
2846                         mot_val[0+stride]= mot_val[2+stride]= mx;
2847                         mot_val[1       ]= mot_val[3       ]=
2848                         mot_val[1+stride]= mot_val[3+stride]= my;
2849                     } else {
2850                         int i;
2851                         PRINT_MB_TYPE("4");
2852                         s->mb_type[xy]= MB_TYPE_INTER4V;
2853                         for(i=0;i<4;i++) {
2854                             INT16 *mot_val= h263_pred_motion(s, i, &pred_x, &pred_y);
2855                             mx = h263_decode_motion(s, pred_x, s->f_code);
2856                             if (mx >= 0xffff)
2857                                 return -1;
2858                 
2859                             my = h263_decode_motion(s, pred_y, s->f_code);
2860                             if (my >= 0xffff)
2861                                 return -1;
2862                             mot_val[0] = mx;
2863                             mot_val[1] = my;
2864                         }
2865                     }
2866                     s->error_status_table[xy]= AC_ERROR;
2867                 }
2868             }
2869         }
2870         s->mb_x= 0;
2871     }
2872
2873     return mb_num;
2874 }
2875
2876 /**
2877  * decode second partition.
2878  * @return <0 if an error occured
2879  */
2880 static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count){
2881     int mb_num=0;
2882     static const INT8 quant_tab[4] = { -1, -2, 1, 2 };
2883
2884     s->mb_x= s->resync_mb_x;
2885     s->first_slice_line=1;
2886     for(s->mb_y= s->resync_mb_y; mb_num < mb_count; s->mb_y++){
2887         ff_init_block_index(s);
2888         for(; mb_num < mb_count && s->mb_x<s->mb_width; s->mb_x++){
2889             const int xy= s->mb_x + s->mb_y*s->mb_width;
2890
2891             mb_num++;
2892             ff_update_block_index(s);
2893             if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
2894                 s->first_slice_line=0;
2895             
2896             if(s->pict_type==I_TYPE){
2897                 int ac_pred= get_bits1(&s->gb);
2898                 int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
2899                 if(cbpy<0){
2900                     fprintf(stderr, "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
2901                     return -1;
2902                 }
2903                 
2904                 s->cbp_table[xy]|= cbpy<<2;
2905                 s->pred_dir_table[xy]|= ac_pred<<7;
2906             }else{ /* P || S_TYPE */
2907                 if(s->mb_type[xy]&MB_TYPE_INTRA){          
2908                     int dir=0,i;
2909                     int ac_pred = get_bits1(&s->gb);
2910                     int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
2911
2912                     if(cbpy<0){
2913                         fprintf(stderr, "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
2914                         return -1;
2915                     }
2916                     
2917                     if(s->cbp_table[xy] & 8) {
2918                         change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
2919                     }
2920                     s->current_picture.qscale_table[xy]= s->qscale;
2921
2922                     for(i=0; i<6; i++){
2923                         int dc_pred_dir;
2924                         int dc= mpeg4_decode_dc(s, i, &dc_pred_dir); 
2925                         if(dc < 0){
2926                             fprintf(stderr, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
2927                             return -1;
2928                         }
2929                         dir<<=1;
2930                         if(dc_pred_dir) dir|=1;
2931                     }
2932                     s->cbp_table[xy]&= 3; //remove dquant
2933                     s->cbp_table[xy]|= cbpy<<2;
2934                     s->pred_dir_table[xy]= dir | (ac_pred<<7);
2935                     s->error_status_table[xy]&= ~DC_ERROR;
2936                 }else if(s->mb_type[xy]&MB_TYPE_SKIPED){
2937                     s->current_picture.qscale_table[xy]= s->qscale;
2938                     s->cbp_table[xy]= 0;
2939                 }else{
2940                     int cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
2941
2942                     if(cbpy<0){
2943                         fprintf(stderr, "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
2944                         return -1;
2945                     }
2946                     
2947                     if(s->cbp_table[xy] & 8) {
2948                         change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
2949                     }
2950                     s->current_picture.qscale_table[xy]= s->qscale;
2951
2952                     s->cbp_table[xy]&= 3; //remove dquant
2953                     s->cbp_table[xy]|= (cbpy^0xf)<<2;
2954                 }
2955             }
2956         }
2957         if(mb_num >= mb_count) return 0;
2958         s->mb_x= 0;
2959     }
2960     return 0;
2961 }
2962
2963 /**
2964  * decodes the first & second partition
2965  * @return <0 if error (and sets error type in the error_status_table)
2966  */
2967 int ff_mpeg4_decode_partitions(MpegEncContext *s)
2968 {
2969     int mb_num;
2970     
2971     mb_num= mpeg4_decode_partition_a(s);    
2972     if(mb_num<0)
2973         return -1;
2974     
2975     if(s->resync_mb_x + s->resync_mb_y*s->mb_width + mb_num > s->mb_num){
2976         fprintf(stderr, "slice below monitor ...\n");
2977         return -1;
2978     }
2979
2980     s->mb_num_left= mb_num;
2981         
2982     if(s->pict_type==I_TYPE){
2983         if(get_bits(&s->gb, 19)!=DC_MARKER){
2984             fprintf(stderr, "marker missing after first I partition at %d %d\n", s->mb_x, s->mb_y);
2985             return -1;
2986         }else
2987             s->error_status_table[s->mb_x + s->mb_y*s->mb_width-1]|= MV_END|DC_END;
2988     }else{
2989         if(get_bits(&s->gb, 17)!=MOTION_MARKER){
2990             fprintf(stderr, "marker missing after first P partition at %d %d\n", s->mb_x, s->mb_y);
2991             return -1;
2992         }else
2993             s->error_status_table[s->mb_x + s->mb_y*s->mb_width-1]|= MV_END;
2994     }
2995     
2996     if( mpeg4_decode_partition_b(s, mb_num) < 0){
2997         return -1;
2998     }
2999     
3000     s->error_status_table[s->mb_x + s->mb_y*s->mb_width-1]|= DC_END;
3001
3002     return 0;        
3003 }
3004
3005 /**
3006  * decode partition C of one MB.
3007  * @return <0 if an error occured
3008  */
3009 static int mpeg4_decode_partitioned_mb(MpegEncContext *s, DCTELEM block[6][64])
3010 {
3011     int cbp, mb_type;
3012     const int xy= s->mb_x + s->mb_y*s->mb_width;
3013
3014     mb_type= s->mb_type[xy];
3015     cbp = s->cbp_table[xy];
3016
3017     if(s->current_picture.qscale_table[xy] != s->qscale){
3018         s->qscale= s->current_picture.qscale_table[xy];
3019         s->y_dc_scale= s->y_dc_scale_table[ s->qscale ];
3020         s->c_dc_scale= s->c_dc_scale_table[ s->qscale ];
3021     }
3022     
3023     if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
3024         int i;
3025         for(i=0; i<4; i++){
3026             s->mv[0][i][0] = s->motion_val[ s->block_index[i] ][0];
3027             s->mv[0][i][1] = s->motion_val[ s->block_index[i] ][1];
3028         }
3029         s->mb_intra = mb_type&MB_TYPE_INTRA;
3030
3031         if (mb_type&MB_TYPE_SKIPED) {
3032             /* skip mb */
3033             for(i=0;i<6;i++)
3034                 s->block_last_index[i] = -1;
3035             s->mv_dir = MV_DIR_FORWARD;
3036             s->mv_type = MV_TYPE_16X16;
3037             if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3038                 s->mcsel=1;
3039                 s->mb_skiped = 0;
3040             }else{
3041                 s->mcsel=0;
3042                 s->mb_skiped = 1;
3043             }
3044         }else if(s->mb_intra){
3045             s->ac_pred = s->pred_dir_table[xy]>>7;
3046
3047             /* decode each block */
3048             for (i = 0; i < 6; i++) {
3049                 if(mpeg4_decode_block(s, block[i], i, cbp&32, 1) < 0){
3050                     fprintf(stderr, "texture corrupted at %d %d\n", s->mb_x, s->mb_y);
3051                     return -1;
3052                 }
3053                 cbp+=cbp;
3054             }
3055         }else if(!s->mb_intra){
3056 //            s->mcsel= 0; //FIXME do we need to init that
3057             
3058             s->mv_dir = MV_DIR_FORWARD;
3059             if (mb_type&MB_TYPE_INTER4V) {
3060                 s->mv_type = MV_TYPE_8X8;
3061             } else {
3062                 s->mv_type = MV_TYPE_16X16;
3063             }
3064             /* decode each block */
3065             for (i = 0; i < 6; i++) {
3066                 if(mpeg4_decode_block(s, block[i], i, cbp&32, 0) < 0){
3067                     fprintf(stderr, "texture corrupted at %d %d (trying to continue with mc/dc only)\n", s->mb_x, s->mb_y);
3068                     return -1;
3069                 }
3070                 cbp+=cbp;
3071             }
3072         }
3073     } else { /* I-Frame */
3074         int i;
3075         s->mb_intra = 1;
3076         s->ac_pred = s->pred_dir_table[xy]>>7;
3077         
3078         /* decode each block */
3079         for (i = 0; i < 6; i++) {
3080             if(mpeg4_decode_block(s, block[i], i, cbp&32, 1) < 0){
3081                 fprintf(stderr, "texture corrupted at %d %d (trying to continue with dc only)\n", s->mb_x, s->mb_y);
3082                 return -1;
3083             }
3084             cbp+=cbp;
3085         }
3086     }
3087
3088     s->error_status_table[xy]&= ~AC_ERROR;
3089
3090     /* per-MB end of slice check */
3091
3092     if(--s->mb_num_left <= 0){
3093 //printf("%06X %d\n", show_bits(&s->gb, 24), s->gb.size_in_bits - get_bits_count(&s->gb));
3094         if(mpeg4_is_resync(s))
3095             return SLICE_END;
3096         else
3097             return SLICE_NOEND;     
3098     }else{
3099         if(s->cbp_table[xy+1] && mpeg4_is_resync(s))
3100             return SLICE_END;
3101         else
3102             return SLICE_OK;
3103     }
3104 }
3105
3106 int ff_h263_decode_mb(MpegEncContext *s,
3107                       DCTELEM block[6][64])
3108 {
3109     int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
3110     INT16 *mot_val;
3111     static INT8 quant_tab[4] = { -1, -2, 1, 2 };
3112
3113     s->error_status_table[s->mb_x + s->mb_y*s->mb_width]= 0;
3114
3115     if(s->mb_x==0) PRINT_MB_TYPE("\n");
3116
3117     if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {
3118         if (get_bits1(&s->gb)) {
3119             /* skip mb */
3120             s->mb_intra = 0;
3121             for(i=0;i<6;i++)
3122                 s->block_last_index[i] = -1;
3123             s->mv_dir = MV_DIR_FORWARD;
3124             s->mv_type = MV_TYPE_16X16;
3125             if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
3126                 PRINT_MB_TYPE("G");
3127                 s->mcsel=1;
3128                 s->mv[0][0][0]= get_amv(s, 0);
3129                 s->mv[0][0][1]= get_amv(s, 1);
3130
3131                 s->mb_skiped = 0;
3132             }else{
3133                 PRINT_MB_TYPE("S");
3134                 s->mcsel=0;
3135                 s->mv[0][0][0] = 0;
3136                 s->mv[0][0][1] = 0;
3137                 s->mb_skiped = 1;
3138             }
3139             goto end;
3140         }
3141         cbpc = get_vlc2(&s->gb, inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
3142         //fprintf(stderr, "\tCBPC: %d", cbpc);
3143         if (cbpc < 0)
3144             return -1;
3145         if (cbpc > 20)
3146             cbpc+=3;
3147         else if (cbpc == 20)
3148             fprintf(stderr, "Stuffing !");
3149         
3150         dquant = cbpc & 8;
3151         s->mb_intra = ((cbpc & 4) != 0);
3152         if (s->mb_intra) goto intra;
3153         
3154         if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
3155             s->mcsel= get_bits1(&s->gb);
3156         else s->mcsel= 0;
3157         cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3158         cbp = (cbpc & 3) | ((cbpy ^ 0xf) << 2);
3159         if (dquant) {
3160             change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
3161         }
3162         if((!s->progressive_sequence) && (cbp || (s->workaround_bugs&FF_BUG_XVID_ILACE)))
3163             s->interlaced_dct= get_bits1(&s->gb);
3164         
3165         s->mv_dir = MV_DIR_FORWARD;
3166         if ((cbpc & 16) == 0) {
3167             if(s->mcsel){
3168                 PRINT_MB_TYPE("G");
3169                 /* 16x16 global motion prediction */
3170                 s->mv_type = MV_TYPE_16X16;
3171                 mx= get_amv(s, 0);
3172                 my= get_amv(s, 1);
3173                 s->mv[0][0][0] = mx;
3174                 s->mv[0][0][1] = my;
3175             }else if((!s->progressive_sequence) && get_bits1(&s->gb)){
3176                 PRINT_MB_TYPE("f");
3177                 /* 16x8 field motion prediction */
3178                 s->mv_type= MV_TYPE_FIELD;
3179
3180                 s->field_select[0][0]= get_bits1(&s->gb);
3181                 s->field_select[0][1]= get_bits1(&s->gb);
3182
3183                 h263_pred_motion(s, 0, &pred_x, &pred_y);
3184                 
3185                 for(i=0; i<2; i++){
3186                     mx = h263_decode_motion(s, pred_x, s->f_code);
3187                     if (mx >= 0xffff)
3188                         return -1;
3189             
3190                     my = h263_decode_motion(s, pred_y/2, s->f_code);
3191                     if (my >= 0xffff)
3192                         return -1;
3193
3194                     s->mv[0][i][0] = mx;
3195                     s->mv[0][i][1] = my;
3196                 }
3197             }else{
3198                 PRINT_MB_TYPE("P");
3199                 /* 16x16 motion prediction */
3200                 s->mv_type = MV_TYPE_16X16;
3201                 h263_pred_motion(s, 0, &pred_x, &pred_y);
3202                 if (s->umvplus_dec)
3203                    mx = h263p_decode_umotion(s, pred_x);
3204                 else
3205                    mx = h263_decode_motion(s, pred_x, s->f_code);
3206             
3207                 if (mx >= 0xffff)
3208                     return -1;
3209             
3210                 if (s->umvplus_dec)
3211                    my = h263p_decode_umotion(s, pred_y);
3212                 else
3213                    my = h263_decode_motion(s, pred_y, s->f_code);
3214             
3215                 if (my >= 0xffff)
3216                     return -1;
3217                 s->mv[0][0][0] = mx;
3218                 s->mv[0][0][1] = my;
3219
3220                 if (s->umvplus_dec && (mx - pred_x) == 1 && (my - pred_y) == 1)
3221                    skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */                   
3222             }
3223         } else {
3224             PRINT_MB_TYPE("4");
3225             s->mv_type = MV_TYPE_8X8;
3226             for(i=0;i<4;i++) {
3227                 mot_val = h263_pred_motion(s, i, &pred_x, &pred_y);
3228                 if (s->umvplus_dec)
3229                   mx = h263p_decode_umotion(s, pred_x);
3230                 else
3231                   mx = h263_decode_motion(s, pred_x, s->f_code);
3232                 if (mx >= 0xffff)
3233                     return -1;
3234                 
3235                 if (s->umvplus_dec)
3236                   my = h263p_decode_umotion(s, pred_y);
3237                 else    
3238                   my = h263_decode_motion(s, pred_y, s->f_code);
3239                 if (my >= 0xffff)
3240                     return -1;
3241                 s->mv[0][i][0] = mx;
3242                 s->mv[0][i][1] = my;
3243                 if (s->umvplus_dec && (mx - pred_x) == 1 && (my - pred_y) == 1)
3244                   skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
3245                 mot_val[0] = mx;
3246                 mot_val[1] = my;
3247             }
3248         }
3249     } else if(s->pict_type==B_TYPE) {
3250         int modb1; // first bit of modb
3251         int modb2; // second bit of modb
3252         int mb_type;
3253         int xy;
3254
3255         s->mb_intra = 0; //B-frames never contain intra blocks
3256         s->mcsel=0;      //     ...               true gmc blocks
3257
3258         if(s->mb_x==0){
3259             for(i=0; i<2; i++){
3260                 s->last_mv[i][0][0]= 
3261                 s->last_mv[i][0][1]= 
3262                 s->last_mv[i][1][0]= 
3263                 s->last_mv[i][1][1]= 0;
3264             }
3265         }
3266
3267         /* if we skipped it in the future P Frame than skip it now too */
3268         s->mb_skiped= s->next_picture.mbskip_table[s->mb_y * s->mb_width + s->mb_x]; // Note, skiptab=0 if last was GMC
3269
3270         if(s->mb_skiped){
3271                 /* skip mb */
3272             for(i=0;i<6;i++)
3273                 s->block_last_index[i] = -1;
3274
3275             s->mv_dir = MV_DIR_FORWARD;
3276             s->mv_type = MV_TYPE_16X16;
3277             s->mv[0][0][0] = 0;
3278             s->mv[0][0][1] = 0;
3279             s->mv[1][0][0] = 0;
3280             s->mv[1][0][1] = 0;
3281             PRINT_MB_TYPE("s");
3282             goto end;
3283         }
3284
3285         modb1= get_bits1(&s->gb); 
3286         if(modb1){
3287             mb_type=4; //like MB_TYPE_B_DIRECT but no vectors coded
3288             cbp=0;
3289         }else{
3290             int field_mv;
3291         
3292             modb2= get_bits1(&s->gb);
3293             mb_type= get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);
3294             if(modb2) cbp= 0;
3295             else      cbp= get_bits(&s->gb, 6);
3296
3297             if (mb_type!=MB_TYPE_B_DIRECT && cbp) {
3298                 if(get_bits1(&s->gb)){
3299                     change_qscale(s, get_bits1(&s->gb)*4 - 2);
3300                 }
3301             }
3302             field_mv=0;
3303
3304             if(!s->progressive_sequence){
3305                 if(cbp)
3306                     s->interlaced_dct= get_bits1(&s->gb);
3307
3308                 if(mb_type!=MB_TYPE_B_DIRECT && get_bits1(&s->gb)){
3309                     field_mv=1;
3310
3311                     if(mb_type!=MB_TYPE_B_BACKW){
3312                         s->field_select[0][0]= get_bits1(&s->gb);
3313                         s->field_select[0][1]= get_bits1(&s->gb);
3314                     }
3315                     if(mb_type!=MB_TYPE_B_FORW){
3316                         s->field_select[1][0]= get_bits1(&s->gb);
3317                         s->field_select[1][1]= get_bits1(&s->gb);
3318                     }
3319                 }
3320             }
3321
3322             s->mv_dir = 0;
3323             if(mb_type!=MB_TYPE_B_DIRECT && !field_mv){
3324                 s->mv_type= MV_TYPE_16X16;
3325                 if(mb_type!=MB_TYPE_B_BACKW){
3326                     s->mv_dir = MV_DIR_FORWARD;
3327
3328                     mx = h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
3329                     my = h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
3330                     s->last_mv[0][1][0]= s->last_mv[0][0][0]= s->mv[0][0][0] = mx;
3331                     s->last_mv[0][1][1]= s->last_mv[0][0][1]= s->mv[0][0][1] = my;
3332                 }
3333     
3334                 if(mb_type!=MB_TYPE_B_FORW){
3335                     s->mv_dir |= MV_DIR_BACKWARD;
3336
3337                     mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
3338                     my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
3339                     s->last_mv[1][1][0]= s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
3340                     s->last_mv[1][1][1]= s->last_mv[1][0][1]= s->mv[1][0][1] = my;
3341                 }
3342                 if(mb_type!=MB_TYPE_B_DIRECT)
3343                     PRINT_MB_TYPE(mb_type==MB_TYPE_B_FORW ? "F" : (mb_type==MB_TYPE_B_BACKW ? "B" : "T"));
3344             }else if(mb_type!=MB_TYPE_B_DIRECT){
3345                 s->mv_type= MV_TYPE_FIELD;
3346
3347                 if(mb_type!=MB_TYPE_B_BACKW){
3348                     s->mv_dir = MV_DIR_FORWARD;
3349                 
3350                     for(i=0; i<2; i++){
3351                         mx = h263_decode_motion(s, s->last_mv[0][i][0]  , s->f_code);
3352                         my = h263_decode_motion(s, s->last_mv[0][i][1]/2, s->f_code);
3353                         s->last_mv[0][i][0]=  s->mv[0][i][0] = mx;
3354                         s->last_mv[0][i][1]= (s->mv[0][i][1] = my)*2;
3355                     }
3356                 }
3357     
3358                 if(mb_type!=MB_TYPE_B_FORW){
3359                     s->mv_dir |= MV_DIR_BACKWARD;
3360
3361                     for(i=0; i<2; i++){
3362                         mx = h263_decode_motion(s, s->last_mv[1][i][0]  , s->b_code);
3363                         my = h263_decode_motion(s, s->last_mv[1][i][1]/2, s->b_code);
3364                         s->last_mv[1][i][0]=  s->mv[1][i][0] = mx;
3365                         s->last_mv[1][i][1]= (s->mv[1][i][1] = my)*2;
3366                     }
3367                 }
3368                 if(mb_type!=MB_TYPE_B_DIRECT)
3369                     PRINT_MB_TYPE(mb_type==MB_TYPE_B_FORW ? "f" : (mb_type==MB_TYPE_B_BACKW ? "b" : "t"));
3370             }
3371         }
3372           
3373         if(mb_type==4 || mb_type==MB_TYPE_B_DIRECT){
3374             if(mb_type==4)
3375                 mx=my=0;
3376             else{
3377                 mx = h263_decode_motion(s, 0, 1);
3378                 my = h263_decode_motion(s, 0, 1);
3379             }
3380  
3381             s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
3382             ff_mpeg4_set_direct_mv(s, mx, my);
3383         }
3384         
3385         if(mb_type<0 || mb_type>4){
3386             printf("illegal MB_type\n");
3387             return -1;
3388         }
3389     } else { /* I-Frame */
3390         cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 1);
3391         if (cbpc < 0)
3392             return -1;
3393         dquant = cbpc & 4;
3394         s->mb_intra = 1;
3395 intra:
3396         s->ac_pred = 0;
3397         if (s->h263_pred || s->h263_aic) {
3398             s->ac_pred = get_bits1(&s->gb);
3399             if (s->ac_pred && s->h263_aic)
3400                 s->h263_aic_dir = get_bits1(&s->gb);
3401         }
3402         PRINT_MB_TYPE(s->ac_pred ? "A" : "I");
3403         
3404         cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3405         if(cbpy<0) return -1;
3406         cbp = (cbpc & 3) | (cbpy << 2);
3407         if (dquant) {
3408             change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
3409         }
3410         
3411         if(!s->progressive_sequence)
3412             s->interlaced_dct= get_bits1(&s->gb);
3413
3414         /* decode each block */
3415         if (s->h263_pred) {
3416             for (i = 0; i < 6; i++) {
3417                 if (mpeg4_decode_block(s, block[i], i, cbp&32, 1) < 0)
3418                     return -1;
3419                 cbp+=cbp;
3420             }
3421         } else {
3422             for (i = 0; i < 6; i++) {
3423                 if (h263_decode_block(s, block[i], i, cbp&32) < 0)
3424                     return -1;
3425                 cbp+=cbp;
3426             }
3427         }
3428         goto end;
3429     }
3430
3431     /* decode each block */
3432     if (s->h263_pred) {
3433         for (i = 0; i < 6; i++) {
3434             if (mpeg4_decode_block(s, block[i], i, cbp&32, 0) < 0)
3435                 return -1;
3436             cbp+=cbp;
3437         }
3438     } else {
3439         for (i = 0; i < 6; i++) {
3440             if (h263_decode_block(s, block[i], i, cbp&32) < 0)
3441                 return -1;
3442             cbp+=cbp;
3443         }
3444     }
3445 end:
3446
3447         /* per-MB end of slice check */
3448     if(s->codec_id==CODEC_ID_MPEG4){
3449         if(mpeg4_is_resync(s)){
3450             if(s->pict_type==B_TYPE && s->next_picture.mbskip_table[s->mb_y * s->mb_width + s->mb_x+1])
3451                 return SLICE_OK;
3452             return SLICE_END;
3453         }
3454     }else{
3455         int v= show_bits(&s->gb, 16);
3456     
3457         if(get_bits_count(&s->gb) + 16 > s->gb.size_in_bits){
3458             v>>= get_bits_count(&s->gb) + 16 - s->gb.size_in_bits;
3459         }
3460
3461         if(v==0)
3462             return SLICE_END;
3463     }
3464
3465     return SLICE_OK;     
3466 }
3467
3468 static int h263_decode_motion(MpegEncContext * s, int pred, int f_code)
3469 {
3470     int code, val, sign, shift, l;
3471     code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
3472     if (code < 0)
3473         return 0xffff;
3474
3475     if (code == 0)
3476         return pred;
3477
3478     sign = get_bits1(&s->gb);
3479     shift = f_code - 1;
3480     val = (code - 1) << shift;
3481     if (shift > 0)
3482         val |= get_bits(&s->gb, shift);
3483     val++;
3484     if (sign)
3485         val = -val;
3486     val += pred;
3487
3488     /* modulo decoding */
3489     if (!s->h263_long_vectors) {
3490         l = 1 << (f_code + 4);
3491         if (val < -l) {
3492             val += l<<1;
3493         } else if (val >= l) {
3494             val -= l<<1;
3495         }
3496     } else {
3497         /* horrible h263 long vector mode */
3498         if (pred < -31 && val < -63)
3499             val += 64;
3500         if (pred > 32 && val > 63)
3501             val -= 64;
3502         
3503     }
3504     return val;
3505 }
3506
3507 /* Decodes RVLC of H.263+ UMV */
3508 static int h263p_decode_umotion(MpegEncContext * s, int pred)
3509 {
3510    int code = 0, sign;
3511    
3512    if (get_bits1(&s->gb)) /* Motion difference = 0 */
3513       return pred;
3514    
3515    code = 2 + get_bits1(&s->gb);
3516    
3517    while (get_bits1(&s->gb))
3518    {
3519       code <<= 1;
3520       code += get_bits1(&s->gb);
3521    }
3522    sign = code & 1;
3523    code >>= 1;
3524    
3525    code = (sign) ? (pred - code) : (pred + code);
3526 #ifdef DEBUG
3527    fprintf(stderr,"H.263+ UMV Motion = %d\n", code);
3528 #endif
3529    return code;   
3530
3531 }
3532
3533 static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
3534                              int n, int coded)
3535 {
3536     int code, level, i, j, last, run;
3537     RLTable *rl = &rl_inter;
3538     const UINT8 *scan_table;
3539
3540     scan_table = s->intra_scantable.permutated;
3541     if (s->h263_aic && s->mb_intra) {
3542         rl = &rl_intra_aic;
3543         i = 0;
3544         if (s->ac_pred) {
3545             if (s->h263_aic_dir) 
3546                 scan_table = s->intra_v_scantable.permutated; /* left */
3547             else
3548                 scan_table = s->intra_h_scantable.permutated; /* top */
3549         }
3550     } else if (s->mb_intra) {
3551         /* DC coef */
3552         if (s->h263_rv10 && s->rv10_version == 3 && s->pict_type == I_TYPE) {
3553             int component, diff;
3554             component = (n <= 3 ? 0 : n - 4 + 1);
3555             level = s->last_dc[component];
3556             if (s->rv10_first_dc_coded[component]) {
3557                 diff = rv_decode_dc(s, n);
3558                 if (diff == 0xffff)
3559                     return -1;
3560                 level += diff;
3561                 level = level & 0xff; /* handle wrap round */
3562                 s->last_dc[component] = level;
3563             } else {
3564                 s->rv10_first_dc_coded[component] = 1;
3565             }
3566         } else {
3567             level = get_bits(&s->gb, 8);
3568             if (level == 255)
3569                 level = 128;
3570         }
3571         block[0] = level;
3572         i = 1;
3573     } else {
3574         i = 0;
3575     }
3576     if (!coded) {
3577         if (s->mb_intra && s->h263_aic)
3578             goto not_coded;
3579         s->block_last_index[n] = i - 1;
3580         return 0;
3581     }
3582
3583     for(;;) {
3584         code = get_vlc2(&s->gb, rl->vlc.table, TEX_VLC_BITS, 2);
3585         if (code < 0){
3586             fprintf(stderr, "illegal ac vlc code at %dx%d\n", s->mb_x, s->mb_y);
3587             return -1;
3588         }
3589         if (code == rl->n) {
3590             /* escape */
3591             last = get_bits1(&s->gb);
3592             run = get_bits(&s->gb, 6);
3593             level = (INT8)get_bits(&s->gb, 8);
3594             if (s->h263_rv10 && level == -128) {
3595                 /* XXX: should patch encoder too */
3596                 level = get_bits(&s->gb, 12);
3597                 level= (level + ((-1)<<11)) ^ ((-1)<<11); //sign extension
3598             }
3599         } else {
3600             run = rl->table_run[code];
3601             level = rl->table_level[code];
3602             last = code >= rl->last;
3603             if (get_bits1(&s->gb))
3604                 level = -level;
3605         }
3606         i += run;
3607         if (i >= 64){
3608             fprintf(stderr, "run overflow at %dx%d\n", s->mb_x, s->mb_y);
3609             return -1;
3610         }
3611         j = scan_table[i];
3612         block[j] = level;
3613         if (last)
3614             break;
3615         i++;
3616     }
3617 not_coded:    
3618     if (s->mb_intra && s->h263_aic) {
3619         h263_pred_acdc(s, block, n);
3620         i = 63;
3621     }
3622     s->block_last_index[n] = i;
3623     return 0;
3624 }
3625
3626 /**
3627  * decodes the dc value.
3628  * @param n block index (0-3 are luma, 4-5 are chroma)
3629  * @param dir_ptr the prediction direction will be stored here
3630  * @return the quantized dc
3631  */
3632 static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr)
3633 {
3634     int level, pred, code;
3635     UINT16 *dc_val;
3636
3637     if (n < 4) 
3638         code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1);
3639     else 
3640         code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1);
3641     if (code < 0 || code > 9 /* && s->nbit<9 */){
3642         fprintf(stderr, "illegal dc vlc\n");
3643         return -1;
3644     }
3645     if (code == 0) {
3646         level = 0;
3647     } else {
3648         level = get_bits(&s->gb, code);
3649         if ((level >> (code - 1)) == 0) /* if MSB not set it is negative*/
3650             level = - (level ^ ((1 << code) - 1));
3651         if (code > 8){
3652             if(get_bits1(&s->gb)==0){ /* marker */
3653                 if(s->error_resilience>=2){
3654                     fprintf(stderr, "dc marker bit missing\n");
3655                     return -1;
3656                 }
3657             }
3658         }
3659     }
3660     pred = ff_mpeg4_pred_dc(s, n, &dc_val, dir_ptr);
3661     level += pred;
3662     if (level < 0){
3663         if(s->error_resilience>=3){
3664             fprintf(stderr, "dc<0 at %dx%d\n", s->mb_x, s->mb_y);
3665             return -1;
3666         }
3667         level = 0;
3668     }
3669     if (n < 4) {
3670         *dc_val = level * s->y_dc_scale;
3671     } else {
3672         *dc_val = level * s->c_dc_scale;
3673     }
3674     if(s->error_resilience>=3){
3675         if(*dc_val > 2048 + s->y_dc_scale + s->c_dc_scale){
3676             fprintf(stderr, "dc overflow at %dx%d\n", s->mb_x, s->mb_y);
3677             return -1;
3678         }
3679     }
3680     return level;
3681 }
3682
3683 /**
3684  * decodes a block.
3685  * @return <0 if an error occured
3686  */
3687 static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
3688                               int n, int coded, int intra)
3689 {
3690     int level, i, last, run;
3691     int dc_pred_dir;
3692     RLTable * rl;
3693     RL_VLC_ELEM * rl_vlc;
3694     const UINT8 * scan_table;
3695     int qmul, qadd;
3696
3697     if(intra) {
3698         /* DC coef */
3699         if(s->partitioned_frame){
3700             level = s->dc_val[0][ s->block_index[n] ];
3701             if(n<4) level= (level + (s->y_dc_scale>>1))/s->y_dc_scale; //FIXME optimizs
3702             else    level= (level + (s->c_dc_scale>>1))/s->c_dc_scale;
3703             dc_pred_dir= (s->pred_dir_table[s->mb_x + s->mb_y*s->mb_width]<<n)&32;
3704         }else{
3705             level = mpeg4_decode_dc(s, n, &dc_pred_dir);
3706             if (level < 0)
3707                 return -1;
3708         }
3709         block[0] = level;
3710         i = 0;
3711         if (!coded) 
3712             goto not_coded;
3713         rl = &rl_intra;
3714         rl_vlc = rl_intra.rl_vlc[0];
3715         if (s->ac_pred) {
3716             if (dc_pred_dir == 0) 
3717                 scan_table = s->intra_v_scantable.permutated; /* left */
3718             else
3719                 scan_table = s->intra_h_scantable.permutated; /* top */
3720         } else {
3721             scan_table = s->intra_scantable.permutated;
3722         }
3723         qmul=1;
3724         qadd=0;
3725     } else {
3726         i = -1;
3727         if (!coded) {
3728             s->block_last_index[n] = i;
3729             return 0;
3730         }
3731         rl = &rl_inter;
3732    
3733         scan_table = s->intra_scantable.permutated;
3734
3735         if(s->mpeg_quant){
3736             qmul=1;
3737             qadd=0;
3738             rl_vlc = rl_inter.rl_vlc[0];        
3739         }else{
3740             qmul = s->qscale << 1;
3741             qadd = (s->qscale - 1) | 1;
3742             rl_vlc = rl_inter.rl_vlc[s->qscale];
3743         }
3744     }
3745   {
3746     OPEN_READER(re, &s->gb);
3747     for(;;) {
3748         UPDATE_CACHE(re, &s->gb);
3749         GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
3750         if (level==0) {
3751             int cache;
3752             cache= GET_CACHE(re, &s->gb);
3753             /* escape */
3754             if (cache&0x80000000) {
3755                 if (cache&0x40000000) {
3756                     /* third escape */
3757                     SKIP_CACHE(re, &s->gb, 2);
3758                     last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);
3759                     run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);
3760                     SKIP_COUNTER(re, &s->gb, 2+1+6);
3761                     UPDATE_CACHE(re, &s->gb);
3762
3763                     if(SHOW_UBITS(re, &s->gb, 1)==0){
3764                         fprintf(stderr, "1. marker bit missing in 3. esc\n");
3765                         return -1;
3766                     }; SKIP_CACHE(re, &s->gb, 1);
3767                     
3768                     level= SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12);
3769  
3770                     if(SHOW_UBITS(re, &s->gb, 1)==0){
3771                         fprintf(stderr, "2. marker bit missing in 3. esc\n");
3772                         return -1;
3773                     }; LAST_SKIP_CACHE(re, &s->gb, 1);
3774                     
3775                     SKIP_COUNTER(re, &s->gb, 1+12+1);
3776                     
3777                     if(level*s->qscale>1024 || level*s->qscale<-1024){
3778                         fprintf(stderr, "|level| overflow in 3. esc, qp=%d\n", s->qscale);
3779                         return -1;
3780                     }
3781 #if 1 
3782                     {
3783                         const int abs_level= ABS(level);
3784                         if(abs_level<=MAX_LEVEL && run<=MAX_RUN && !(s->workaround_bugs&FF_BUG_AC_VLC)){
3785                             const int run1= run - rl->max_run[last][abs_level] - 1;
3786                             if(abs_level <= rl->max_level[last][run]){
3787                                 fprintf(stderr, "illegal 3. esc, vlc encoding possible\n");
3788                                 return -1;
3789                             }
3790                             if(s->error_resilience > FF_ER_COMPLIANT){
3791                                 if(abs_level <= rl->max_level[last][run]*2){
3792                                     fprintf(stderr, "illegal 3. esc, esc 1 encoding possible\n");
3793                                     return -1;
3794                                 }
3795                                 if(run1 >= 0 && abs_level <= rl->max_level[last][run1]){
3796                                     fprintf(stderr, "illegal 3. esc, esc 2 encoding possible\n");
3797                                     return -1;
3798                                 }
3799                             }
3800                         }
3801                     }
3802 #endif
3803                     if (level>0) level= level * qmul + qadd;
3804                     else         level= level * qmul - qadd;
3805
3806                     i+= run + 1;
3807                     if(last) i+=192;
3808                 } else {
3809                     /* second escape */
3810 #if MIN_CACHE_BITS < 20
3811                     LAST_SKIP_BITS(re, &s->gb, 2);
3812                     UPDATE_CACHE(re, &s->gb);
3813 #else
3814                     SKIP_BITS(re, &s->gb, 2);
3815 #endif
3816                     GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
3817                     i+= run + rl->max_run[run>>7][level/qmul] +1; //FIXME opt indexing
3818                     level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
3819                     LAST_SKIP_BITS(re, &s->gb, 1);
3820                 }
3821             } else {
3822                 /* first escape */
3823 #if MIN_CACHE_BITS < 19
3824                 LAST_SKIP_BITS(re, &s->gb, 1);
3825                 UPDATE_CACHE(re, &s->gb);
3826 #else
3827                 SKIP_BITS(re, &s->gb, 1);
3828 #endif
3829                 GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
3830                 i+= run;
3831                 level = level + rl->max_level[run>>7][(run-1)&63] * qmul;//FIXME opt indexing
3832                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
3833                 LAST_SKIP_BITS(re, &s->gb, 1);
3834             }
3835         } else {
3836             i+= run;
3837             level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
3838             LAST_SKIP_BITS(re, &s->gb, 1);
3839         }
3840         if (i > 62){
3841             i-= 192;
3842             if(i&(~63)){
3843                 fprintf(stderr, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
3844                 return -1;
3845             }
3846
3847             block[scan_table[i]] = level;
3848             break;
3849         }
3850
3851         block[scan_table[i]] = level;
3852     }
3853     CLOSE_READER(re, &s->gb);
3854   }
3855  not_coded:
3856     if (s->mb_intra) {
3857         mpeg4_pred_ac(s, block, n, dc_pred_dir);
3858         if (s->ac_pred) {
3859             i = 63; /* XXX: not optimal */
3860         }
3861     }
3862     s->block_last_index[n] = i;
3863     return 0;
3864 }
3865
3866 /* most is hardcoded. should extend to handle all h263 streams */
3867 int h263_decode_picture_header(MpegEncContext *s)
3868 {
3869     int format, width, height;
3870
3871     /* picture start code */
3872     if (get_bits(&s->gb, 22) != 0x20) {
3873         fprintf(stderr, "Bad picture start code\n");
3874         return -1;
3875     }
3876     /* temporal reference */
3877     s->picture_number = get_bits(&s->gb, 8); /* picture timestamp */
3878
3879     /* PTYPE starts here */    
3880     if (get_bits1(&s->gb) != 1) {
3881         /* marker */
3882         fprintf(stderr, "Bad marker\n");
3883         return -1;
3884     }
3885     if (get_bits1(&s->gb) != 0) {
3886         fprintf(stderr, "Bad H263 id\n");
3887         return -1;      /* h263 id */
3888     }
3889     skip_bits1(&s->gb); /* split screen off */
3890     skip_bits1(&s->gb); /* camera  off */
3891     skip_bits1(&s->gb); /* freeze picture release off */
3892
3893     /* Reset GOB number */
3894     s->gob_number = 0;
3895         
3896     format = get_bits(&s->gb, 3);
3897     /*
3898         0    forbidden
3899         1    sub-QCIF
3900         10   QCIF
3901         7       extended PTYPE (PLUSPTYPE)
3902     */
3903
3904     if (format != 7 && format != 6) {
3905         s->h263_plus = 0;
3906         /* H.263v1 */
3907         width = h263_format[format][0];
3908         height = h263_format[format][1];
3909         if (!width)
3910             return -1;
3911         
3912         s->width = width;
3913         s->height = height;
3914         s->pict_type = I_TYPE + get_bits1(&s->gb);
3915
3916         s->unrestricted_mv = get_bits1(&s->gb); 
3917         s->h263_long_vectors = s->unrestricted_mv;
3918
3919         if (get_bits1(&s->gb) != 0) {
3920             fprintf(stderr, "H263 SAC not supported\n");
3921             return -1;  /* SAC: off */
3922         }
3923         if (get_bits1(&s->gb) != 0) {
3924             s->mv_type = MV_TYPE_8X8; /* Advanced prediction mode */
3925         }   
3926         
3927         if (get_bits1(&s->gb) != 0) {
3928             fprintf(stderr, "H263 PB frame not supported\n");
3929             return -1;  /* not PB frame */
3930         }
3931         s->qscale = get_bits(&s->gb, 5);
3932         skip_bits1(&s->gb);     /* Continuous Presence Multipoint mode: off */
3933     } else {
3934         int ufep;
3935         
3936         /* H.263v2 */
3937         s->h263_plus = 1;
3938         ufep = get_bits(&s->gb, 3); /* Update Full Extended PTYPE */
3939
3940         /* ufep other than 0 and 1 are reserved */        
3941         if (ufep == 1) {
3942             /* OPPTYPE */       
3943             format = get_bits(&s->gb, 3);
3944             dprintf("ufep=1, format: %d\n", format);
3945             skip_bits(&s->gb,1); /* Custom PCF */
3946             s->umvplus_dec = get_bits(&s->gb, 1); /* Unrestricted Motion Vector */
3947             skip_bits1(&s->gb); /* Syntax-based Arithmetic Coding (SAC) */
3948             if (get_bits1(&s->gb) != 0) {
3949                 s->mv_type = MV_TYPE_8X8; /* Advanced prediction mode */
3950             }
3951             if (get_bits1(&s->gb) != 0) { /* Advanced Intra Coding (AIC) */
3952                 s->h263_aic = 1;
3953             }
3954             
3955             skip_bits(&s->gb, 7);
3956             /* these are the 7 bits: (in order of appearence  */
3957             /* Deblocking Filter */
3958             /* Slice Structured */
3959             /* Reference Picture Selection */
3960             /* Independent Segment Decoding */
3961             /* Alternative Inter VLC */
3962             /* Modified Quantization */
3963             /* Prevent start code emulation */
3964
3965             skip_bits(&s->gb, 3); /* Reserved */
3966         } else if (ufep != 0) {
3967             fprintf(stderr, "Bad UFEP type (%d)\n", ufep);
3968             return -1;
3969         }
3970             
3971         /* MPPTYPE */
3972         s->pict_type = get_bits(&s->gb, 3) + I_TYPE;
3973         dprintf("pict_type: %d\n", s->pict_type);
3974         if (s->pict_type != I_TYPE &&
3975             s->pict_type != P_TYPE)
3976             return -1;
3977         skip_bits(&s->gb, 2);
3978         s->no_rounding = get_bits1(&s->gb);
3979         dprintf("RTYPE: %d\n", s->no_rounding);
3980         skip_bits(&s->gb, 4);
3981         
3982         /* Get the picture dimensions */
3983         if (ufep) {
3984             if (format == 6) {
3985                 /* Custom Picture Format (CPFMT) */
3986                 s->aspect_ratio_info = get_bits(&s->gb, 4);
3987                 dprintf("aspect: %d\n", s->aspect_ratio_info);
3988                 /* aspect ratios:
3989                 0 - forbidden
3990                 1 - 1:1
3991                 2 - 12:11 (CIF 4:3)
3992                 3 - 10:11 (525-type 4:3)
3993                 4 - 16:11 (CIF 16:9)
3994                 5 - 40:33 (525-type 16:9)
3995                 6-14 - reserved
3996                 */
3997                 width = (get_bits(&s->gb, 9) + 1) * 4;
3998                 skip_bits1(&s->gb);
3999                 height = get_bits(&s->gb, 9) * 4;
4000                 dprintf("\nH.263+ Custom picture: %dx%d\n",width,height);
4001                 if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
4002                     /* aspected dimensions */
4003                     s->aspected_width = get_bits(&s->gb, 8);
4004                     s->aspected_height = get_bits(&s->gb, 8);
4005                 }else{
4006                     s->aspected_width = pixel_aspect[s->aspect_ratio_info][0];
4007                     s->aspected_height= pixel_aspect[s->aspect_ratio_info][1];
4008                 }
4009             } else {
4010                 width = h263_format[format][0];
4011                 height = h263_format[format][1];
4012             }
4013             if ((width == 0) || (height == 0))
4014                 return -1;
4015             s->width = width;
4016             s->height = height;
4017             if (s->umvplus_dec) {
4018                 skip_bits1(&s->gb); /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
4019             }
4020         }
4021             
4022         s->qscale = get_bits(&s->gb, 5);
4023     }
4024     /* PEI */
4025     while (get_bits1(&s->gb) != 0) {
4026         skip_bits(&s->gb, 8);
4027     }
4028     s->f_code = 1;
4029     
4030     if(s->h263_aic){
4031          s->y_dc_scale_table= 
4032          s->c_dc_scale_table= h263_aic_dc_scale_table;
4033     }else{
4034         s->y_dc_scale_table=
4035         s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
4036     }
4037
4038     return 0;
4039 }
4040
4041 static void mpeg4_decode_sprite_trajectory(MpegEncContext * s)
4042 {
4043     int i;
4044     int a= 2<<s->sprite_warping_accuracy;
4045     int rho= 3-s->sprite_warping_accuracy;
4046     int r=16/a;
4047     const int vop_ref[4][2]= {{0,0}, {s->width,0}, {0, s->height}, {s->width, s->height}}; // only true for rectangle shapes
4048     int d[4][2]={{0,0}, {0,0}, {0,0}, {0,0}};
4049     int sprite_ref[4][2];
4050     int virtual_ref[2][2];
4051     int w2, h2, w3, h3;
4052     int alpha=0, beta=0;
4053     int w= s->width;
4054     int h= s->height;
4055     int min_ab;
4056
4057     for(i=0; i<s->num_sprite_warping_points; i++){
4058         int length;
4059         int x=0, y=0;
4060
4061         length= get_vlc(&s->gb, &sprite_trajectory);
4062         if(length){
4063             x= get_bits(&s->gb, length);
4064
4065             if ((x >> (length - 1)) == 0) /* if MSB not set it is negative*/
4066                 x = - (x ^ ((1 << length) - 1));
4067         }
4068         if(!(s->divx_version==500 && s->divx_build==413)) skip_bits1(&s->gb); /* marker bit */
4069         
4070         length= get_vlc(&s->gb, &sprite_trajectory);
4071         if(length){
4072             y=get_bits(&s->gb, length);
4073
4074             if ((y >> (length - 1)) == 0) /* if MSB not set it is negative*/
4075                 y = - (y ^ ((1 << length) - 1));
4076         }
4077         skip_bits1(&s->gb); /* marker bit */
4078 //printf("%d %d %d %d\n", x, y, i, s->sprite_warping_accuracy);
4079         d[i][0]= x;
4080         d[i][1]= y;
4081     }
4082
4083     while((1<<alpha)<w) alpha++;
4084     while((1<<beta )<h) beta++; // there seems to be a typo in the mpeg4 std for the definition of w' and h'
4085     w2= 1<<alpha;
4086     h2= 1<<beta;
4087
4088 // Note, the 4th point isnt used for GMC
4089     if(s->divx_version==500 && s->divx_build==413){
4090         sprite_ref[0][0]= a*vop_ref[0][0] + d[0][0];
4091         sprite_ref[0][1]= a*vop_ref[0][1] + d[0][1];
4092         sprite_ref[1][0]= a*vop_ref[1][0] + d[0][0] + d[1][0];
4093         sprite_ref[1][1]= a*vop_ref[1][1] + d[0][1] + d[1][1];
4094         sprite_ref[2][0]= a*vop_ref[2][0] + d[0][0] + d[2][0];
4095         sprite_ref[2][1]= a*vop_ref[2][1] + d[0][1] + d[2][1];
4096     } else {
4097         sprite_ref[0][0]= (a>>1)*(2*vop_ref[0][0] + d[0][0]);
4098         sprite_ref[0][1]= (a>>1)*(2*vop_ref[0][1] + d[0][1]);
4099         sprite_ref[1][0]= (a>>1)*(2*vop_ref[1][0] + d[0][0] + d[1][0]);
4100         sprite_ref[1][1]= (a>>1)*(2*vop_ref[1][1] + d[0][1] + d[1][1]);
4101         sprite_ref[2][0]= (a>>1)*(2*vop_ref[2][0] + d[0][0] + d[2][0]);
4102         sprite_ref[2][1]= (a>>1)*(2*vop_ref[2][1] + d[0][1] + d[2][1]);
4103     }
4104 /*    sprite_ref[3][0]= (a>>1)*(2*vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);
4105     sprite_ref[3][1]= (a>>1)*(2*vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */
4106     
4107 // this is mostly identical to the mpeg4 std (and is totally unreadable because of that ...)
4108 // perhaps it should be reordered to be more readable ...
4109 // the idea behind this virtual_ref mess is to be able to use shifts later per pixel instead of divides
4110 // so the distance between points is converted from w&h based to w2&h2 based which are of the 2^x form
4111     virtual_ref[0][0]= 16*(vop_ref[0][0] + w2) 
4112         + ROUNDED_DIV(((w - w2)*(r*sprite_ref[0][0] - 16*vop_ref[0][0]) + w2*(r*sprite_ref[1][0] - 16*vop_ref[1][0])),w);
4113     virtual_ref[0][1]= 16*vop_ref[0][1] 
4114         + ROUNDED_DIV(((w - w2)*(r*sprite_ref[0][1] - 16*vop_ref[0][1]) + w2*(r*sprite_ref[1][1] - 16*vop_ref[1][1])),w);
4115     virtual_ref[1][0]= 16*vop_ref[0][0] 
4116         + ROUNDED_DIV(((h - h2)*(r*sprite_ref[0][0] - 16*vop_ref[0][0]) + h2*(r*sprite_ref[2][0] - 16*vop_ref[2][0])),h);
4117     virtual_ref[1][1]= 16*(vop_ref[0][1] + h2) 
4118         + ROUNDED_DIV(((h - h2)*(r*sprite_ref[0][1] - 16*vop_ref[0][1]) + h2*(r*sprite_ref[2][1] - 16*vop_ref[2][1])),h);
4119         
4120     switch(s->num_sprite_warping_points)
4121     {
4122         case 0:
4123             s->sprite_offset[0][0]= 0;
4124             s->sprite_offset[0][1]= 0;
4125             s->sprite_offset[1][0]= 0;
4126             s->sprite_offset[1][1]= 0;
4127             s->sprite_delta[0][0]= a;
4128             s->sprite_delta[0][1]= 0;
4129             s->sprite_delta[1][0]= 0;
4130             s->sprite_delta[1][1]= a;
4131             s->sprite_shift[0]= 0;
4132             s->sprite_shift[1]= 0;
4133             break;
4134         case 1: //GMC only
4135             s->sprite_offset[0][0]= sprite_ref[0][0] - a*vop_ref[0][0];
4136             s->sprite_offset[0][1]= sprite_ref[0][1] - a*vop_ref[0][1];
4137             s->sprite_offset[1][0]= ((sprite_ref[0][0]>>1)|(sprite_ref[0][0]&1)) - a*(vop_ref[0][0]/2);
4138             s->sprite_offset[1][1]= ((sprite_ref[0][1]>>1)|(sprite_ref[0][1]&1)) - a*(vop_ref[0][1]/2);
4139             s->sprite_delta[0][0]= a;
4140             s->sprite_delta[0][1]= 0;
4141             s->sprite_delta[1][0]= 0;
4142             s->sprite_delta[1][1]= a;
4143             s->sprite_shift[0]= 0;
4144             s->sprite_shift[1]= 0;
4145             break;
4146         case 2:
4147             s->sprite_offset[0][0]= (sprite_ref[0][0]<<(alpha+rho))
4148                                                   + (-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][0])
4149                                                   + ( r*sprite_ref[0][1] - virtual_ref[0][1])*(-vop_ref[0][1])
4150                                                   + (1<<(alpha+rho-1));
4151             s->sprite_offset[0][1]= (sprite_ref[0][1]<<(alpha+rho))
4152                                                   + (-r*sprite_ref[0][1] + virtual_ref[0][1])*(-vop_ref[0][0])
4153        &n