9781a1ba843b21e6dd52301ec295f66cd4bd204f
[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_t *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_t **dc_val_ptr);
76 #ifdef CONFIG_ENCODERS
77 static void mpeg4_inv_pred_ac(MpegEncContext * s, DCTELEM *block, int n,
78                               int dir);
79 #endif //CONFIG_ENCODERS
80 static void mpeg4_decode_sprite_trajectory(MpegEncContext * s);
81 static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr, int *dir_ptr);
82
83 extern uint32_t inverse[256];
84
85 #ifdef CONFIG_ENCODERS
86 static uint8_t uni_DCtab_lum_len[512];
87 static uint8_t uni_DCtab_chrom_len[512];
88 static uint16_t uni_DCtab_lum_bits[512];
89 static uint16_t uni_DCtab_chrom_bits[512];
90
91 static uint16_t (*mv_penalty)[MAX_MV*2+1]= NULL;
92 static uint8_t fcode_tab[MAX_MV*2+1];
93 static uint8_t umv_fcode_tab[MAX_MV*2+1];
94
95 static uint32_t uni_mpeg4_intra_rl_bits[64*64*2*2];
96 static uint8_t  uni_mpeg4_intra_rl_len [64*64*2*2];
97 static uint32_t uni_mpeg4_inter_rl_bits[64*64*2*2];
98 static uint8_t  uni_mpeg4_inter_rl_len [64*64*2*2];
99 //#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128 + (run)*256 + (level))
100 //#define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run) + (level)*64)
101 #define UNI_MPEG4_ENC_INDEX(last,run,level) ((last)*128*64 + (run)*128 + (level))
102
103 /* mpeg4
104 inter
105 max level: 24/6
106 max run: 53/63
107
108 intra
109 max level: 53/16
110 max run: 29/41
111 */
112 #endif
113
114
115 int h263_get_picture_format(int width, int height)
116 {
117     int format;
118
119     if (width == 128 && height == 96)
120         format = 1;
121     else if (width == 176 && height == 144)
122         format = 2;
123     else if (width == 352 && height == 288)
124         format = 3;
125     else if (width == 704 && height == 576)
126         format = 4;
127     else if (width == 1408 && height == 1152)
128         format = 5;
129     else
130         format = 7;
131     return format;
132 }
133
134 #ifdef CONFIG_ENCODERS
135
136 static void float_aspect_to_info(MpegEncContext * s, float aspect){
137     int i;
138
139     aspect*= s->height/(double)s->width;
140 //printf("%f\n", aspect);
141     
142     if(aspect==0) aspect= 1.0;
143
144     ff_float2fraction(&s->aspected_width, &s->aspected_height, aspect, 255);
145
146 //printf("%d %d\n", s->aspected_width, s->aspected_height);
147     for(i=1; i<6; i++){
148         if(s->aspected_width == pixel_aspect[i][0] && s->aspected_height== pixel_aspect[i][1]){
149             s->aspect_ratio_info=i;
150             return;
151         }
152     }
153     
154     s->aspect_ratio_info= FF_ASPECT_EXTENDED;
155 }
156
157 void h263_encode_picture_header(MpegEncContext * s, int picture_number)
158 {
159     int format;
160
161     align_put_bits(&s->pb);
162
163     /* Update the pointer to last GOB */
164     s->ptr_lastgob = pbBufPtr(&s->pb);
165     s->gob_number = 0;
166
167     put_bits(&s->pb, 22, 0x20); /* PSC */
168     put_bits(&s->pb, 8, (((int64_t)s->picture_number * 30 * FRAME_RATE_BASE) / 
169                          s->frame_rate) & 0xff);
170
171     put_bits(&s->pb, 1, 1);     /* marker */
172     put_bits(&s->pb, 1, 0);     /* h263 id */
173     put_bits(&s->pb, 1, 0);     /* split screen off */
174     put_bits(&s->pb, 1, 0);     /* camera  off */
175     put_bits(&s->pb, 1, 0);     /* freeze picture release off */
176     
177     format = h263_get_picture_format(s->width, s->height);
178     if (!s->h263_plus) {
179         /* H.263v1 */
180         put_bits(&s->pb, 3, format);
181         put_bits(&s->pb, 1, (s->pict_type == P_TYPE));
182         /* By now UMV IS DISABLED ON H.263v1, since the restrictions
183         of H.263v1 UMV implies to check the predicted MV after
184         calculation of the current MB to see if we're on the limits */
185         put_bits(&s->pb, 1, 0); /* unrestricted motion vector: off */
186         put_bits(&s->pb, 1, 0); /* SAC: off */
187         put_bits(&s->pb, 1, 0); /* advanced prediction mode: off */
188         put_bits(&s->pb, 1, 0); /* not PB frame */
189         put_bits(&s->pb, 5, s->qscale);
190         put_bits(&s->pb, 1, 0); /* Continuous Presence Multipoint mode: off */
191     } else {
192         /* H.263v2 */
193         /* H.263 Plus PTYPE */
194         put_bits(&s->pb, 3, 7);
195         put_bits(&s->pb,3,1); /* Update Full Extended PTYPE */
196         if (format == 7)
197             put_bits(&s->pb,3,6); /* Custom Source Format */
198         else
199             put_bits(&s->pb, 3, format);
200             
201         put_bits(&s->pb,1,0); /* Custom PCF: off */
202         s->umvplus = s->unrestricted_mv;
203         put_bits(&s->pb, 1, s->umvplus); /* Unrestricted Motion Vector */
204         put_bits(&s->pb,1,0); /* SAC: off */
205         put_bits(&s->pb,1,0); /* Advanced Prediction Mode: off */
206         put_bits(&s->pb,1,s->h263_aic); /* Advanced Intra Coding */
207         put_bits(&s->pb,1,0); /* Deblocking Filter: off */
208         put_bits(&s->pb,1,0); /* Slice Structured: off */
209         put_bits(&s->pb,1,0); /* Reference Picture Selection: off */
210         put_bits(&s->pb,1,0); /* Independent Segment Decoding: off */
211         put_bits(&s->pb,1,0); /* Alternative Inter VLC: off */
212         put_bits(&s->pb,1,0); /* Modified Quantization: off */
213         put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
214         put_bits(&s->pb,3,0); /* Reserved */
215                 
216         put_bits(&s->pb, 3, s->pict_type == P_TYPE);
217                 
218         put_bits(&s->pb,1,0); /* Reference Picture Resampling: off */
219         put_bits(&s->pb,1,0); /* Reduced-Resolution Update: off */
220         put_bits(&s->pb,1,s->no_rounding); /* Rounding Type */
221         put_bits(&s->pb,2,0); /* Reserved */
222         put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
223                 
224         /* This should be here if PLUSPTYPE */
225         put_bits(&s->pb, 1, 0); /* Continuous Presence Multipoint mode: off */
226                 
227                 if (format == 7) {
228             /* Custom Picture Format (CPFMT) */
229             float_aspect_to_info(s, s->avctx->aspect_ratio);
230
231             put_bits(&s->pb,4,s->aspect_ratio_info);
232             put_bits(&s->pb,9,(s->width >> 2) - 1);
233             put_bits(&s->pb,1,1); /* "1" to prevent start code emulation */
234             put_bits(&s->pb,9,(s->height >> 2));
235             if (s->aspect_ratio_info == FF_ASPECT_EXTENDED)
236             {
237                 put_bits(&s->pb, 8, s->aspected_width);
238                 put_bits(&s->pb, 8, s->aspected_height);
239             }
240         }
241         
242         /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
243         if (s->umvplus)
244 //            put_bits(&s->pb,1,1); /* Limited according tables of Annex D */
245             put_bits(&s->pb,2,1); /* unlimited */
246
247         put_bits(&s->pb, 5, s->qscale);
248     }
249
250     put_bits(&s->pb, 1, 0);     /* no PEI */
251
252     if(s->h263_aic){
253          s->y_dc_scale_table= 
254          s->c_dc_scale_table= h263_aic_dc_scale_table;
255     }else{
256         s->y_dc_scale_table=
257         s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
258     }
259 }
260
261 /**
262  * Encodes a group of blocks header.
263  */
264 int h263_encode_gob_header(MpegEncContext * s, int mb_line)
265 {
266            align_put_bits(&s->pb);
267            flush_put_bits(&s->pb);
268            /* Call the RTP callback to send the last GOB */
269            if (s->rtp_callback) {
270                int pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
271                s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
272            }
273            put_bits(&s->pb, 17, 1); /* GBSC */
274            s->gob_number = mb_line / s->gob_index;
275            put_bits(&s->pb, 5, s->gob_number); /* GN */
276            put_bits(&s->pb, 2, s->pict_type == I_TYPE); /* GFID */
277            put_bits(&s->pb, 5, s->qscale); /* GQUANT */
278            //fprintf(stderr,"\nGOB: %2d size: %d", s->gob_number - 1, pdif);
279     return 0;
280 }
281
282 static inline int decide_ac_pred(MpegEncContext * s, DCTELEM block[6][64], int dir[6])
283 {
284     int score0=0, score1=0;
285     int i, n;
286     int8_t * const qscale_table= s->current_picture.qscale_table;
287
288     for(n=0; n<6; n++){
289         int16_t *ac_val, *ac_val1;
290
291         ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
292         ac_val1= ac_val;
293         if(dir[n]){
294             const int xy= s->mb_x + s->mb_y*s->mb_width - s->mb_width;
295             /* top prediction */
296             ac_val-= s->block_wrap[n]*16;
297             if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
298                 /* same qscale */
299                 for(i=1; i<8; i++){
300                     const int level= block[n][s->dsp.idct_permutation[i   ]];
301                     score0+= ABS(level);
302                     score1+= ABS(level - ac_val[i+8]);
303                     ac_val1[i  ]=    block[n][s->dsp.idct_permutation[i<<3]];
304                     ac_val1[i+8]= level;
305                 }
306             }else{
307                 /* different qscale, we must rescale */
308                 for(i=1; i<8; i++){
309                     const int level= block[n][s->dsp.idct_permutation[i   ]];
310                     score0+= ABS(level);
311                     score1+= ABS(level - ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale));
312                     ac_val1[i  ]=    block[n][s->dsp.idct_permutation[i<<3]];
313                     ac_val1[i+8]= level;
314                 }
315             }
316         }else{
317             const int xy= s->mb_x-1 + s->mb_y*s->mb_width;
318             /* left prediction */
319             ac_val-= 16;
320             if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
321                 /* same qscale */
322                 for(i=1; i<8; i++){
323                     const int level= block[n][s->dsp.idct_permutation[i<<3]];
324                     score0+= ABS(level);
325                     score1+= ABS(level - ac_val[i]);
326                     ac_val1[i  ]= level;
327                     ac_val1[i+8]=    block[n][s->dsp.idct_permutation[i   ]];
328                 }
329             }else{
330                 /* different qscale, we must rescale */
331                 for(i=1; i<8; i++){
332                     const int level= block[n][s->dsp.idct_permutation[i<<3]];
333                     score0+= ABS(level);
334                     score1+= ABS(level - ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale));
335                     ac_val1[i  ]= level;
336                     ac_val1[i+8]=    block[n][s->dsp.idct_permutation[i   ]];
337                 }
338             }
339         }
340     }
341
342     return score0 > score1 ? 1 : 0;    
343 }
344
345 /**
346  * modify qscale so that encoding is acually possible in h263 (limit difference to -2..2)
347  */
348 void ff_clean_h263_qscales(MpegEncContext *s){
349     int i;
350     int8_t * const qscale_table= s->current_picture.qscale_table;
351     
352     for(i=1; i<s->mb_num; i++){
353         if(qscale_table[i] - qscale_table[i-1] >2)
354             qscale_table[i]= qscale_table[i-1]+2;
355     }
356     for(i=s->mb_num-2; i>=0; i--){
357         if(qscale_table[i] - qscale_table[i+1] >2)
358             qscale_table[i]= qscale_table[i+1]+2;
359     }
360 }
361
362 /**
363  * modify mb_type & qscale so that encoding is acually possible in mpeg4
364  */
365 void ff_clean_mpeg4_qscales(MpegEncContext *s){
366     int i;
367     int8_t * const qscale_table= s->current_picture.qscale_table;
368
369     ff_clean_h263_qscales(s);
370     
371     for(i=1; i<s->mb_num; i++){
372         if(qscale_table[i] != qscale_table[i-1] && (s->mb_type[i]&MB_TYPE_INTER4V)){
373             s->mb_type[i]&= ~MB_TYPE_INTER4V;
374             s->mb_type[i]|= MB_TYPE_INTER;
375         }
376     }
377
378     if(s->pict_type== B_TYPE){
379         int odd=0;
380         /* ok, come on, this isnt funny anymore, theres more code for handling this mpeg4 mess than
381            for the actual adaptive quantization */
382         
383         for(i=0; i<s->mb_num; i++){
384             odd += qscale_table[i]&1;
385         }
386         
387         if(2*odd > s->mb_num) odd=1;
388         else                  odd=0;
389         
390         for(i=0; i<s->mb_num; i++){
391             if((qscale_table[i]&1) != odd)
392                 qscale_table[i]++;
393             if(qscale_table[i] > 31)
394                 qscale_table[i]= 31;
395         }            
396     
397         for(i=1; i<s->mb_num; i++){
398             if(qscale_table[i] != qscale_table[i-1] && (s->mb_type[i]&MB_TYPE_DIRECT)){
399                 s->mb_type[i]&= ~MB_TYPE_DIRECT;
400                 s->mb_type[i]|= MB_TYPE_BIDIR;
401             }
402         }
403     }
404 }
405
406 #endif //CONFIG_ENCODERS
407
408 void ff_mpeg4_set_direct_mv(MpegEncContext *s, int mx, int my){
409     const int mb_index= s->mb_x + s->mb_y*s->mb_width;
410     int xy= s->block_index[0];
411     uint16_t time_pp= s->pp_time;
412     uint16_t time_pb= s->pb_time;
413     int i;
414     
415     //FIXME avoid divides
416     switch(s->co_located_type_table[mb_index]){
417     case 0:
418         s->mv[0][0][0] = s->mv[0][1][0] = s->mv[0][2][0] = s->mv[0][3][0] = s->motion_val[xy][0]*time_pb/time_pp + mx;
419         s->mv[0][0][1] = s->mv[0][1][1] = s->mv[0][2][1] = s->mv[0][3][1] = s->motion_val[xy][1]*time_pb/time_pp + my;
420         s->mv[1][0][0] = s->mv[1][1][0] = s->mv[1][2][0] = s->mv[1][3][0] = mx ? s->mv[0][0][0] - s->motion_val[xy][0]
421                             : s->motion_val[xy][0]*(time_pb - time_pp)/time_pp;
422         s->mv[1][0][1] = s->mv[1][1][1] = s->mv[1][2][1] = s->mv[1][3][1] = my ? s->mv[0][0][1] - s->motion_val[xy][1] 
423                             : s->motion_val[xy][1]*(time_pb - time_pp)/time_pp;
424         if((s->avctx->workaround_bugs & FF_BUG_DIRECT_BLOCKSIZE) || !s->quarter_sample)
425             s->mv_type= MV_TYPE_16X16;
426         else
427             s->mv_type= MV_TYPE_8X8;
428         break;
429     case CO_LOCATED_TYPE_4MV:
430         s->mv_type = MV_TYPE_8X8;
431         for(i=0; i<4; i++){
432             xy= s->block_index[i];
433             s->mv[0][i][0] = s->motion_val[xy][0]*time_pb/time_pp + mx;
434             s->mv[0][i][1] = s->motion_val[xy][1]*time_pb/time_pp + my;
435             s->mv[1][i][0] = mx ? s->mv[0][i][0] - s->motion_val[xy][0]
436                                 : s->motion_val[xy][0]*(time_pb - time_pp)/time_pp;
437             s->mv[1][i][1] = my ? s->mv[0][i][1] - s->motion_val[xy][1] 
438                                 : s->motion_val[xy][1]*(time_pb - time_pp)/time_pp;
439         }
440         break;
441     case CO_LOCATED_TYPE_FIELDMV:
442         s->mv_type = MV_TYPE_FIELD;
443         for(i=0; i<2; i++){
444             if(s->top_field_first){
445                 time_pp= s->pp_field_time - s->field_select_table[mb_index][i] + i;
446                 time_pb= s->pb_field_time - s->field_select_table[mb_index][i] + i;
447             }else{
448                 time_pp= s->pp_field_time + s->field_select_table[mb_index][i] - i;
449                 time_pb= s->pb_field_time + s->field_select_table[mb_index][i] - i;
450             }
451             s->mv[0][i][0] = s->field_mv_table[mb_index][i][0]*time_pb/time_pp + mx;
452             s->mv[0][i][1] = s->field_mv_table[mb_index][i][1]*time_pb/time_pp + my;
453             s->mv[1][i][0] = mx ? s->mv[0][i][0] - s->field_mv_table[mb_index][i][0]
454                                 : s->field_mv_table[mb_index][i][0]*(time_pb - time_pp)/time_pp;
455             s->mv[1][i][1] = my ? s->mv[0][i][1] - s->field_mv_table[mb_index][i][1] 
456                                 : s->field_mv_table[mb_index][i][1]*(time_pb - time_pp)/time_pp;
457         }
458         break;
459     }
460 }
461
462 #ifdef CONFIG_ENCODERS
463 void mpeg4_encode_mb(MpegEncContext * s,
464                     DCTELEM block[6][64],
465                     int motion_x, int motion_y)
466 {
467     int cbpc, cbpy, pred_x, pred_y;
468     int bits;
469     PutBitContext * const pb2    = s->data_partitioning                         ? &s->pb2    : &s->pb;
470     PutBitContext * const tex_pb = s->data_partitioning && s->pict_type!=B_TYPE ? &s->tex_pb : &s->pb;
471     PutBitContext * const dc_pb  = s->data_partitioning && s->pict_type!=I_TYPE ? &s->pb2    : &s->pb;
472     const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1) && !s->data_partitioning ? 1 : 0;
473     const int dquant_code[5]= {1,0,9,2,3};
474     
475     //    printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
476     if (!s->mb_intra) {
477         /* compute cbp */
478         int i, cbp = 0;
479         for (i = 0; i < 6; i++) {
480             if (s->block_last_index[i] >= 0)
481                 cbp |= 1 << (5 - i);
482         }
483
484         if(s->pict_type==B_TYPE){
485             static const int mb_type_table[8]= {-1, 2, 3, 1,-1,-1,-1, 0}; /* convert from mv_dir to type */
486             int mb_type=  mb_type_table[s->mv_dir];
487             
488             if(s->mb_x==0){
489                 s->last_mv[0][0][0]= 
490                 s->last_mv[0][0][1]= 
491                 s->last_mv[1][0][0]= 
492                 s->last_mv[1][0][1]= 0;
493             }
494             
495             assert(s->dquant>=-2 && s->dquant<=2);
496             assert((s->dquant&1)==0);
497             assert(mb_type>=0);
498
499             /* nothing to do if this MB was skiped in the next P Frame */
500             if(s->next_picture.mbskip_table[s->mb_y * s->mb_width + s->mb_x]){ //FIXME avoid DCT & ...
501                 s->skip_count++;
502                 s->mv[0][0][0]= 
503                 s->mv[0][0][1]= 
504                 s->mv[1][0][0]= 
505                 s->mv[1][0][1]= 0;
506                 s->mv_dir= MV_DIR_FORWARD; //doesnt matter
507                 s->qscale -= s->dquant;
508 //                s->mb_skiped=1;
509
510                 return;
511             }
512             
513             if ((cbp | motion_x | motion_y | mb_type) ==0) {
514                 /* direct MB with MV={0,0} */
515                 assert(s->dquant==0);
516                 
517                 put_bits(&s->pb, 1, 1); /* mb not coded modb1=1 */
518
519                 if(interleaved_stats){
520                     s->misc_bits++;
521                     s->last_bits++;
522                 }
523                 s->skip_count++;
524                 return;
525             }
526             
527             put_bits(&s->pb, 1, 0);     /* mb coded modb1=0 */
528             put_bits(&s->pb, 1, cbp ? 0 : 1); /* modb2 */ //FIXME merge
529             put_bits(&s->pb, mb_type+1, 1); // this table is so simple that we dont need it :)
530             if(cbp) put_bits(&s->pb, 6, cbp);
531             
532             if(cbp && mb_type){
533                 if(s->dquant)
534                     put_bits(&s->pb, 2, (s->dquant>>2)+3);
535                 else
536                     put_bits(&s->pb, 1, 0);
537             }else
538                 s->qscale -= s->dquant;
539             
540             if(!s->progressive_sequence){
541                 if(cbp)
542                     put_bits(&s->pb, 1, s->interlaced_dct);
543                 if(mb_type) // not diect mode
544                     put_bits(&s->pb, 1, 0); // no interlaced ME yet
545             }
546
547             if(interleaved_stats){
548                 bits= get_bit_count(&s->pb);
549                 s->misc_bits+= bits - s->last_bits;
550                 s->last_bits=bits;
551             }
552
553             switch(mb_type)
554             {
555             case 0: /* direct */
556                 h263_encode_motion(s, motion_x, 1);
557                 h263_encode_motion(s, motion_y, 1);                
558                 s->b_count++;
559                 s->f_count++;
560                 break;
561             case 1: /* bidir */
562                 h263_encode_motion(s, s->mv[0][0][0] - s->last_mv[0][0][0], s->f_code);
563                 h263_encode_motion(s, s->mv[0][0][1] - s->last_mv[0][0][1], s->f_code);
564                 h263_encode_motion(s, s->mv[1][0][0] - s->last_mv[1][0][0], s->b_code);
565                 h263_encode_motion(s, s->mv[1][0][1] - s->last_mv[1][0][1], s->b_code);
566                 s->last_mv[0][0][0]= s->mv[0][0][0];
567                 s->last_mv[0][0][1]= s->mv[0][0][1];
568                 s->last_mv[1][0][0]= s->mv[1][0][0];
569                 s->last_mv[1][0][1]= s->mv[1][0][1];
570                 s->b_count++;
571                 s->f_count++;
572                 break;
573             case 2: /* backward */
574                 h263_encode_motion(s, motion_x - s->last_mv[1][0][0], s->b_code);
575                 h263_encode_motion(s, motion_y - s->last_mv[1][0][1], s->b_code);
576                 s->last_mv[1][0][0]= motion_x;
577                 s->last_mv[1][0][1]= motion_y;
578                 s->b_count++;
579                 break;
580             case 3: /* forward */
581                 h263_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code);
582                 h263_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code);
583                 s->last_mv[0][0][0]= motion_x;
584                 s->last_mv[0][0][1]= motion_y;
585                 s->f_count++;
586                 break;
587             default:
588                 printf("unknown mb type\n");
589                 return;
590             }
591
592             if(interleaved_stats){
593                 bits= get_bit_count(&s->pb);
594                 s->mv_bits+= bits - s->last_bits;
595                 s->last_bits=bits;
596             }
597
598             /* encode each block */
599             for (i = 0; i < 6; i++) {
600                 mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, NULL, &s->pb);
601             }
602
603             if(interleaved_stats){
604                 bits= get_bit_count(&s->pb);
605                 s->p_tex_bits+= bits - s->last_bits;
606                 s->last_bits=bits;
607             }
608         }else{ /* s->pict_type==B_TYPE */
609             if ((cbp | motion_x | motion_y | s->dquant) == 0 && s->mv_type==MV_TYPE_16X16) {
610                 /* check if the B frames can skip it too, as we must skip it if we skip here 
611                    why didnt they just compress the skip-mb bits instead of reusing them ?! */
612                 if(s->max_b_frames>0){
613                     int i;
614                     int x,y, offset;
615                     uint8_t *p_pic;
616
617                     x= s->mb_x*16;
618                     y= s->mb_y*16;
619                     if(x+16 > s->width)  x= s->width-16;
620                     if(y+16 > s->height) y= s->height-16;
621
622                     offset= x + y*s->linesize;
623                     p_pic= s->new_picture.data[0] + offset;
624                     
625                     s->mb_skiped=1;
626                     for(i=0; i<s->max_b_frames; i++){
627                         uint8_t *b_pic;
628                         int diff;
629                         Picture *pic= s->reordered_input_picture[i+1];
630
631                         if(pic==NULL || pic->pict_type!=B_TYPE) break;
632
633                         b_pic= pic->data[0] + offset + 16; //FIXME +16
634                         diff= s->dsp.pix_abs16x16(p_pic, b_pic, s->linesize);
635                         if(diff>s->qscale*70){ //FIXME check that 70 is optimal
636                             s->mb_skiped=0;
637                             break;
638                         }
639                     }
640                 }else
641                     s->mb_skiped=1; 
642
643                 if(s->mb_skiped==1){
644                     /* skip macroblock */
645                     put_bits(&s->pb, 1, 1);
646
647                     if(interleaved_stats){
648                         s->misc_bits++;
649                         s->last_bits++;
650                     }
651                     s->skip_count++;
652                     return;
653                 }
654             }
655
656             put_bits(&s->pb, 1, 0);     /* mb coded */
657             if(s->mv_type==MV_TYPE_16X16){
658                 cbpc = cbp & 3;
659                 if(s->dquant) cbpc+= 8;
660                 put_bits(&s->pb,
661                         inter_MCBPC_bits[cbpc],
662                         inter_MCBPC_code[cbpc]);
663
664                 cbpy = cbp >> 2;
665                 cbpy ^= 0xf;
666                 put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
667                 if(s->dquant)
668                     put_bits(pb2, 2, dquant_code[s->dquant+2]);
669
670                 if(!s->progressive_sequence){
671                     if(cbp)
672                         put_bits(pb2, 1, s->interlaced_dct);
673                     put_bits(pb2, 1, 0); // no interlaced ME yet
674                 }
675                     
676                 if(interleaved_stats){
677                     bits= get_bit_count(&s->pb);
678                     s->misc_bits+= bits - s->last_bits;
679                     s->last_bits=bits;
680                 }
681
682                 /* motion vectors: 16x16 mode */
683                 h263_pred_motion(s, 0, &pred_x, &pred_y);
684             
685                 h263_encode_motion(s, motion_x - pred_x, s->f_code);
686                 h263_encode_motion(s, motion_y - pred_y, s->f_code);
687             }else{
688                 cbpc = (cbp & 3)+16;
689                 put_bits(&s->pb,
690                         inter_MCBPC_bits[cbpc],
691                         inter_MCBPC_code[cbpc]);
692                 cbpy = cbp >> 2;
693                 cbpy ^= 0xf;
694                 put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
695
696                 if(!s->progressive_sequence){
697                     if(cbp)
698                         put_bits(pb2, 1, s->interlaced_dct);
699                 }
700     
701                 if(interleaved_stats){
702                     bits= get_bit_count(&s->pb);
703                     s->misc_bits+= bits - s->last_bits;
704                     s->last_bits=bits;
705                 }
706
707                 for(i=0; i<4; i++){
708                     /* motion vectors: 8x8 mode*/
709                     h263_pred_motion(s, i, &pred_x, &pred_y);
710
711                     h263_encode_motion(s, s->motion_val[ s->block_index[i] ][0] - pred_x, s->f_code);
712                     h263_encode_motion(s, s->motion_val[ s->block_index[i] ][1] - pred_y, s->f_code);
713                 }
714             }
715
716             if(interleaved_stats){ 
717                 bits= get_bit_count(&s->pb);
718                 s->mv_bits+= bits - s->last_bits;
719                 s->last_bits=bits;
720             }
721
722             /* encode each block */
723             for (i = 0; i < 6; i++) {
724                 mpeg4_encode_block(s, block[i], i, 0, s->intra_scantable.permutated, NULL, tex_pb);
725             }
726
727             if(interleaved_stats){
728                 bits= get_bit_count(&s->pb);
729                 s->p_tex_bits+= bits - s->last_bits;
730                 s->last_bits=bits;
731             }
732             s->f_count++;
733         }
734     } else {
735         int cbp;
736         int dc_diff[6];   //dc values with the dc prediction subtracted 
737         int dir[6];  //prediction direction
738         int zigzag_last_index[6];
739         uint8_t *scan_table[6];
740         int i;
741
742         for(i=0; i<6; i++){
743             const int level= block[i][0];
744             uint16_t *dc_ptr;
745
746             dc_diff[i]= level - ff_mpeg4_pred_dc(s, i, &dc_ptr, &dir[i]);
747             if (i < 4) {
748                 *dc_ptr = level * s->y_dc_scale;
749             } else {
750                 *dc_ptr = level * s->c_dc_scale;
751             }
752         }
753
754         s->ac_pred= decide_ac_pred(s, block, dir);
755
756         if(s->ac_pred){
757             for(i=0; i<6; i++){
758                 uint8_t *st;
759                 int last_index;
760
761                 mpeg4_inv_pred_ac(s, block[i], i, dir[i]);
762                 if (dir[i]==0) st = s->intra_v_scantable.permutated; /* left */
763                 else           st = s->intra_h_scantable.permutated; /* top */
764
765                 for(last_index=63; last_index>=0; last_index--) //FIXME optimize
766                     if(block[i][st[last_index]]) break;
767                 zigzag_last_index[i]= s->block_last_index[i];
768                 s->block_last_index[i]= last_index;
769                 scan_table[i]= st;
770             }
771         }else{
772             for(i=0; i<6; i++)
773                 scan_table[i]= s->intra_scantable.permutated;
774         }
775
776         /* compute cbp */
777         cbp = 0;
778         for (i = 0; i < 6; i++) {
779             if (s->block_last_index[i] >= 1)
780                 cbp |= 1 << (5 - i);
781         }
782
783         cbpc = cbp & 3;
784         if (s->pict_type == I_TYPE) {
785             if(s->dquant) cbpc+=4;
786             put_bits(&s->pb,
787                 intra_MCBPC_bits[cbpc],
788                 intra_MCBPC_code[cbpc]);
789         } else {
790             if(s->dquant) cbpc+=8;
791             put_bits(&s->pb, 1, 0);     /* mb coded */
792             put_bits(&s->pb,
793                 inter_MCBPC_bits[cbpc + 4],
794                 inter_MCBPC_code[cbpc + 4]);
795         }
796         put_bits(pb2, 1, s->ac_pred);
797         cbpy = cbp >> 2;
798         put_bits(pb2, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
799         if(s->dquant)
800             put_bits(dc_pb, 2, dquant_code[s->dquant+2]);
801
802         if(!s->progressive_sequence){
803             put_bits(dc_pb, 1, s->interlaced_dct);
804         }
805
806         if(interleaved_stats){
807             bits= get_bit_count(&s->pb);
808             s->misc_bits+= bits - s->last_bits;
809             s->last_bits=bits;
810         }
811
812         /* encode each block */
813         for (i = 0; i < 6; i++) {
814             mpeg4_encode_block(s, block[i], i, dc_diff[i], scan_table[i], dc_pb, tex_pb);
815         }
816
817         if(interleaved_stats){
818             bits= get_bit_count(&s->pb);
819             s->i_tex_bits+= bits - s->last_bits;
820             s->last_bits=bits;
821         }
822         s->i_count++;
823
824         /* restore ac coeffs & last_index stuff if we messed them up with the prediction */
825         if(s->ac_pred){
826             for(i=0; i<6; i++){
827                 int j;    
828                 int16_t *ac_val;
829
830                 ac_val = s->ac_val[0][0] + s->block_index[i] * 16;
831
832                 if(dir[i]){
833                     for(j=1; j<8; j++) 
834                         block[i][s->dsp.idct_permutation[j   ]]= ac_val[j+8];
835                 }else{
836                     for(j=1; j<8; j++) 
837                         block[i][s->dsp.idct_permutation[j<<3]]= ac_val[j  ];
838                 }
839                 s->block_last_index[i]= zigzag_last_index[i];
840             }
841         }
842     }
843 }
844
845 void h263_encode_mb(MpegEncContext * s,
846                     DCTELEM block[6][64],
847                     int motion_x, int motion_y)
848 {
849     int cbpc, cbpy, i, cbp, pred_x, pred_y;
850     int16_t pred_dc;
851     int16_t rec_intradc[6];
852     uint16_t *dc_ptr[6];
853     const int dquant_code[5]= {1,0,9,2,3};
854            
855     //printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);
856     if (!s->mb_intra) {
857         /* compute cbp */
858         cbp = 0;
859         for (i = 0; i < 6; i++) {
860             if (s->block_last_index[i] >= 0)
861                 cbp |= 1 << (5 - i);
862         }
863         if ((cbp | motion_x | motion_y | s->dquant) == 0) {
864             /* skip macroblock */
865             put_bits(&s->pb, 1, 1);
866             return;
867         }
868         put_bits(&s->pb, 1, 0); /* mb coded */
869         cbpc = cbp & 3;
870         if(s->dquant) cbpc+= 8;
871         put_bits(&s->pb,
872                     inter_MCBPC_bits[cbpc],
873                     inter_MCBPC_code[cbpc]);
874         cbpy = cbp >> 2;
875         cbpy ^= 0xf;
876         put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
877         if(s->dquant)
878             put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
879
880         /* motion vectors: 16x16 mode only now */
881         h263_pred_motion(s, 0, &pred_x, &pred_y);
882       
883         if (!s->umvplus) {  
884             h263_encode_motion(s, motion_x - pred_x, s->f_code);
885             h263_encode_motion(s, motion_y - pred_y, s->f_code);
886         }
887         else {
888             h263p_encode_umotion(s, motion_x - pred_x);
889             h263p_encode_umotion(s, motion_y - pred_y);
890             if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))
891                 /* To prevent Start Code emulation */
892                 put_bits(&s->pb,1,1);
893         }
894     } else {
895         int li = s->h263_aic ? 0 : 1;
896         
897         cbp = 0;
898         for(i=0; i<6; i++) {
899             /* Predict DC */
900             if (s->h263_aic && s->mb_intra) {
901                 int16_t level = block[i][0];
902             
903                 pred_dc = h263_pred_dc(s, i, &dc_ptr[i]);
904                 level -= pred_dc;
905                 /* Quant */
906                 if (level < 0)
907                     level = (level + (s->qscale >> 1))/(s->y_dc_scale);
908                 else
909                     level = (level - (s->qscale >> 1))/(s->y_dc_scale);
910                     
911                 /* AIC can change CBP */
912                 if (level == 0 && s->block_last_index[i] == 0)
913                     s->block_last_index[i] = -1;
914                 else if (level < -127)
915                     level = -127;
916                 else if (level > 127)
917                     level = 127;
918                 
919                 block[i][0] = level;
920                 /* Reconstruction */ 
921                 rec_intradc[i] = (s->y_dc_scale*level) + pred_dc;
922                 /* Oddify */
923                 rec_intradc[i] |= 1;
924                 //if ((rec_intradc[i] % 2) == 0)
925                 //    rec_intradc[i]++;
926                 /* Clipping */
927                 if (rec_intradc[i] < 0)
928                     rec_intradc[i] = 0;
929                 else if (rec_intradc[i] > 2047)
930                     rec_intradc[i] = 2047;
931                                 
932                 /* Update AC/DC tables */
933                 *dc_ptr[i] = rec_intradc[i];
934             }
935             /* compute cbp */
936             if (s->block_last_index[i] >= li)
937                 cbp |= 1 << (5 - i);
938         }
939
940         cbpc = cbp & 3;
941         if (s->pict_type == I_TYPE) {
942             if(s->dquant) cbpc+=4;
943             put_bits(&s->pb,
944                 intra_MCBPC_bits[cbpc],
945                 intra_MCBPC_code[cbpc]);
946         } else {
947             if(s->dquant) cbpc+=8;
948             put_bits(&s->pb, 1, 0);     /* mb coded */
949             put_bits(&s->pb,
950                 inter_MCBPC_bits[cbpc + 4],
951                 inter_MCBPC_code[cbpc + 4]);
952         }
953         if (s->h263_aic) {
954             /* XXX: currently, we do not try to use ac prediction */
955             put_bits(&s->pb, 1, 0);     /* no AC prediction */
956         }
957         cbpy = cbp >> 2;
958         put_bits(&s->pb, cbpy_tab[cbpy][1], cbpy_tab[cbpy][0]);
959         if(s->dquant)
960             put_bits(&s->pb, 2, dquant_code[s->dquant+2]);
961     }
962
963     for(i=0; i<6; i++) {
964         /* encode each block */
965         h263_encode_block(s, block[i], i);
966     
967         /* Update INTRADC for decoding */
968         if (s->h263_aic && s->mb_intra) {
969             block[i][0] = rec_intradc[i];
970             
971         }
972     }
973 }
974 #endif
975
976 static int h263_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr)
977 {
978     int x, y, wrap, a, c, pred_dc, scale;
979     int16_t *dc_val, *ac_val;
980
981     /* find prediction */
982     if (n < 4) {
983         x = 2 * s->mb_x + 1 + (n & 1);
984         y = 2 * s->mb_y + 1 + ((n & 2) >> 1);
985         wrap = s->mb_width * 2 + 2;
986         dc_val = s->dc_val[0];
987         ac_val = s->ac_val[0][0];
988         scale = s->y_dc_scale;
989     } else {
990         x = s->mb_x + 1;
991         y = s->mb_y + 1;
992         wrap = s->mb_width + 2;
993         dc_val = s->dc_val[n - 4 + 1];
994         ac_val = s->ac_val[n - 4 + 1][0];
995         scale = s->c_dc_scale;
996     }
997     /* B C
998      * A X 
999      */
1000     a = dc_val[(x - 1) + (y) * wrap];
1001     c = dc_val[(x) + (y - 1) * wrap];
1002     
1003     /* No prediction outside GOB boundary */
1004     if (s->first_slice_line && ((n < 2) || (n > 3)))
1005         c = 1024;
1006     pred_dc = 1024;
1007     /* just DC prediction */
1008     if (a != 1024 && c != 1024)
1009         pred_dc = (a + c) >> 1;
1010     else if (a != 1024)
1011         pred_dc = a;
1012     else
1013         pred_dc = c;
1014     
1015     /* we assume pred is positive */
1016     //pred_dc = (pred_dc + (scale >> 1)) / scale;
1017     *dc_val_ptr = &dc_val[x + y * wrap];
1018     return pred_dc;
1019 }
1020
1021 static void h263_pred_acdc(MpegEncContext * s, DCTELEM *block, int n)
1022 {
1023     int x, y, wrap, a, c, pred_dc, scale, i;
1024     int16_t *dc_val, *ac_val, *ac_val1;
1025
1026     /* find prediction */
1027     if (n < 4) {
1028         x = 2 * s->mb_x + 1 + (n & 1);
1029         y = 2 * s->mb_y + 1 + ((n & 2) >> 1);
1030         wrap = s->mb_width * 2 + 2;
1031         dc_val = s->dc_val[0];
1032         ac_val = s->ac_val[0][0];
1033         scale = s->y_dc_scale;
1034     } else {
1035         x = s->mb_x + 1;
1036         y = s->mb_y + 1;
1037         wrap = s->mb_width + 2;
1038         dc_val = s->dc_val[n - 4 + 1];
1039         ac_val = s->ac_val[n - 4 + 1][0];
1040         scale = s->c_dc_scale;
1041     }
1042     
1043     ac_val += ((y) * wrap + (x)) * 16;
1044     ac_val1 = ac_val;
1045     
1046     /* B C
1047      * A X 
1048      */
1049     a = dc_val[(x - 1) + (y) * wrap];
1050     c = dc_val[(x) + (y - 1) * wrap];
1051     
1052     /* No prediction outside GOB boundary */
1053     if (s->first_slice_line && ((n < 2) || (n > 3)))
1054         c = 1024;
1055     pred_dc = 1024;
1056     if (s->ac_pred) {
1057         if (s->h263_aic_dir) {
1058             /* left prediction */
1059             if (a != 1024) {
1060                 ac_val -= 16;
1061                 for(i=1;i<8;i++) {
1062                     block[s->dsp.idct_permutation[i<<3]] += ac_val[i];
1063                 }
1064                 pred_dc = a;
1065             }
1066         } else {
1067             /* top prediction */
1068             if (c != 1024) {
1069                 ac_val -= 16 * wrap;
1070                 for(i=1;i<8;i++) {
1071                     block[s->dsp.idct_permutation[i   ]] += ac_val[i + 8];
1072                 }
1073                 pred_dc = c;
1074             }
1075         }
1076     } else {
1077         /* just DC prediction */
1078         if (a != 1024 && c != 1024)
1079             pred_dc = (a + c) >> 1;
1080         else if (a != 1024)
1081             pred_dc = a;
1082         else
1083             pred_dc = c;
1084     }
1085     
1086     /* we assume pred is positive */
1087     block[0]=block[0]*scale + pred_dc;
1088     
1089     if (block[0] < 0)
1090         block[0] = 0;
1091     else if (!(block[0] & 1))
1092         block[0]++;
1093     
1094     /* Update AC/DC tables */
1095     dc_val[(x) + (y) * wrap] = block[0];
1096     
1097     /* left copy */
1098     for(i=1;i<8;i++)
1099         ac_val1[i    ] = block[s->dsp.idct_permutation[i<<3]];
1100     /* top copy */
1101     for(i=1;i<8;i++)
1102         ac_val1[8 + i] = block[s->dsp.idct_permutation[i   ]];
1103 }
1104
1105 int16_t *h263_pred_motion(MpegEncContext * s, int block, 
1106                         int *px, int *py)
1107 {
1108     int xy, wrap;
1109     int16_t *A, *B, *C, *mot_val;
1110     static const int off[4]= {2, 1, 1, -1};
1111
1112     wrap = s->block_wrap[0];
1113     xy = s->block_index[block];
1114
1115     mot_val = s->motion_val[xy];
1116
1117     A = s->motion_val[xy - 1];
1118     /* special case for first (slice) line */
1119     if (s->first_slice_line && block<3) {
1120         // we cant just change some MVs to simulate that as we need them for the B frames (and ME)
1121         // and if we ever support non rectangular objects than we need to do a few ifs here anyway :(
1122         if(block==0){ //most common case
1123             if(s->mb_x  == s->resync_mb_x){ //rare
1124                 *px= *py = 0;
1125             }else if(s->mb_x + 1 == s->resync_mb_x){ //rare
1126                 C = s->motion_val[xy + off[block] - wrap];
1127                 if(s->mb_x==0){
1128                     *px = C[0];
1129                     *py = C[1];
1130                 }else{
1131                     *px = mid_pred(A[0], 0, C[0]);
1132                     *py = mid_pred(A[1], 0, C[1]);
1133                 }
1134             }else{
1135                 *px = A[0];
1136                 *py = A[1];
1137             }
1138         }else if(block==1){
1139             if(s->mb_x + 1 == s->resync_mb_x){ //rare
1140                 C = s->motion_val[xy + off[block] - wrap];
1141                 *px = mid_pred(A[0], 0, C[0]);
1142                 *py = mid_pred(A[1], 0, C[1]);
1143             }else{
1144                 *px = A[0];
1145                 *py = A[1];
1146             }
1147         }else{ /* block==2*/
1148             B = s->motion_val[xy - wrap];
1149             C = s->motion_val[xy + off[block] - wrap];
1150             if(s->mb_x == s->resync_mb_x) //rare
1151                 A[0]=A[1]=0;
1152     
1153             *px = mid_pred(A[0], B[0], C[0]);
1154             *py = mid_pred(A[1], B[1], C[1]);
1155         }
1156     } else {
1157         B = s->motion_val[xy - wrap];
1158         C = s->motion_val[xy + off[block] - wrap];
1159         *px = mid_pred(A[0], B[0], C[0]);
1160         *py = mid_pred(A[1], B[1], C[1]);
1161     }
1162     return mot_val;
1163 }
1164
1165 #ifdef CONFIG_ENCODERS
1166 static void h263_encode_motion(MpegEncContext * s, int val, int f_code)
1167 {
1168     int range, l, bit_size, sign, code, bits;
1169
1170     if (val == 0) {
1171         /* zero vector */
1172         code = 0;
1173         put_bits(&s->pb, mvtab[code][1], mvtab[code][0]);
1174     } else {
1175         bit_size = f_code - 1;
1176         range = 1 << bit_size;
1177         /* modulo encoding */
1178         l = range * 32;
1179 #if 1
1180         val+= l;
1181         val&= 2*l-1;
1182         val-= l;
1183         sign = val>>31;
1184         val= (val^sign)-sign;
1185         sign&=1;
1186 #else
1187         if (val < -l) {
1188             val += 2*l;
1189         } else if (val >= l) {
1190             val -= 2*l;
1191         }
1192
1193         assert(val>=-l && val<l);
1194
1195         if (val >= 0) {
1196             sign = 0;
1197         } else {
1198             val = -val;
1199             sign = 1;
1200         }
1201 #endif
1202         val--;
1203         code = (val >> bit_size) + 1;
1204         bits = val & (range - 1);
1205
1206         put_bits(&s->pb, mvtab[code][1] + 1, (mvtab[code][0] << 1) | sign); 
1207         if (bit_size > 0) {
1208             put_bits(&s->pb, bit_size, bits);
1209         }
1210     }
1211
1212 }
1213
1214 /* Encode MV differences on H.263+ with Unrestricted MV mode */
1215 static void h263p_encode_umotion(MpegEncContext * s, int val)
1216 {
1217     short sval = 0; 
1218     short i = 0;
1219     short n_bits = 0;
1220     short temp_val;
1221     int code = 0;
1222     int tcode;
1223     
1224     if ( val == 0)
1225         put_bits(&s->pb, 1, 1);
1226     else if (val == 1)
1227         put_bits(&s->pb, 3, 0);
1228     else if (val == -1)
1229         put_bits(&s->pb, 3, 2);
1230     else {
1231         
1232         sval = ((val < 0) ? (short)(-val):(short)val);
1233         temp_val = sval;
1234         
1235         while (temp_val != 0) {
1236             temp_val = temp_val >> 1;
1237             n_bits++;
1238         }
1239         
1240         i = n_bits - 1;
1241         while (i > 0) {
1242             tcode = (sval & (1 << (i-1))) >> (i-1);
1243             tcode = (tcode << 1) | 1;
1244             code = (code << 2) | tcode;
1245             i--;
1246         }
1247         code = ((code << 1) | (val < 0)) << 1;
1248         put_bits(&s->pb, (2*n_bits)+1, code);
1249         //printf("\nVal = %d\tCode = %d", sval, code);
1250     }
1251 }
1252
1253 static void init_mv_penalty_and_fcode(MpegEncContext *s)
1254 {
1255     int f_code;
1256     int mv;
1257     
1258     if(mv_penalty==NULL)
1259         mv_penalty= av_mallocz( sizeof(uint16_t)*(MAX_FCODE+1)*(2*MAX_MV+1) );
1260     
1261     for(f_code=1; f_code<=MAX_FCODE; f_code++){
1262         for(mv=-MAX_MV; mv<=MAX_MV; mv++){
1263             int len;
1264
1265             if(mv==0) len= mvtab[0][1];
1266             else{
1267                 int val, bit_size, range, code;
1268
1269                 bit_size = s->f_code - 1;
1270                 range = 1 << bit_size;
1271
1272                 val=mv;
1273                 if (val < 0) 
1274                     val = -val;
1275                 val--;
1276                 code = (val >> bit_size) + 1;
1277                 if(code<33){
1278                     len= mvtab[code][1] + 1 + bit_size;
1279                 }else{
1280                     len= mvtab[32][1] + 2 + bit_size;
1281                 }
1282             }
1283
1284             mv_penalty[f_code][mv+MAX_MV]= len;
1285         }
1286     }
1287
1288     for(f_code=MAX_FCODE; f_code>0; f_code--){
1289         for(mv=-(16<<f_code); mv<(16<<f_code); mv++){
1290             fcode_tab[mv+MAX_MV]= f_code;
1291         }
1292     }
1293
1294     for(mv=0; mv<MAX_MV*2+1; mv++){
1295         umv_fcode_tab[mv]= 1;
1296     }
1297 }
1298 #endif
1299
1300 #ifdef CONFIG_ENCODERS
1301
1302 static void init_uni_dc_tab(void)
1303 {
1304     int level, uni_code, uni_len;
1305
1306     for(level=-256; level<256; level++){
1307         int size, v, l;
1308         /* find number of bits */
1309         size = 0;
1310         v = abs(level);
1311         while (v) {
1312             v >>= 1;
1313             size++;
1314         }
1315
1316         if (level < 0)
1317             l= (-level) ^ ((1 << size) - 1);
1318         else
1319             l= level;
1320
1321         /* luminance */
1322         uni_code= DCtab_lum[size][0];
1323         uni_len = DCtab_lum[size][1];
1324
1325         if (size > 0) {
1326             uni_code<<=size; uni_code|=l;
1327             uni_len+=size;
1328             if (size > 8){
1329                 uni_code<<=1; uni_code|=1;
1330                 uni_len++;
1331             }
1332         }
1333         uni_DCtab_lum_bits[level+256]= uni_code;
1334         uni_DCtab_lum_len [level+256]= uni_len;
1335
1336         /* chrominance */
1337         uni_code= DCtab_chrom[size][0];
1338         uni_len = DCtab_chrom[size][1];
1339         
1340         if (size > 0) {
1341             uni_code<<=size; uni_code|=l;
1342             uni_len+=size;
1343             if (size > 8){
1344                 uni_code<<=1; uni_code|=1;
1345                 uni_len++;
1346             }
1347         }
1348         uni_DCtab_chrom_bits[level+256]= uni_code;
1349         uni_DCtab_chrom_len [level+256]= uni_len;
1350
1351     }
1352 }
1353
1354 #endif //CONFIG_ENCODERS
1355
1356 #ifdef CONFIG_ENCODERS
1357 static void init_uni_mpeg4_rl_tab(RLTable *rl, uint32_t *bits_tab, uint8_t *len_tab){
1358     int slevel, run, last;
1359     
1360     assert(MAX_LEVEL >= 64);
1361     assert(MAX_RUN   >= 63);
1362
1363     for(slevel=-64; slevel<64; slevel++){
1364         if(slevel==0) continue;
1365         for(run=0; run<64; run++){
1366             for(last=0; last<=1; last++){
1367                 const int index= UNI_MPEG4_ENC_INDEX(last, run, slevel+64);
1368                 int level= slevel < 0 ? -slevel : slevel;
1369                 int sign= slevel < 0 ? 1 : 0;
1370                 int bits, len, code;
1371                 int level1, run1;
1372                 
1373                 len_tab[index]= 100;
1374                      
1375                 /* ESC0 */
1376                 code= get_rl_index(rl, last, run, level);
1377                 bits= rl->table_vlc[code][0];
1378                 len=  rl->table_vlc[code][1];
1379                 bits=bits*2+sign; len++;
1380                 
1381                 if(code!=rl->n && len < len_tab[index]){
1382                     bits_tab[index]= bits;
1383                     len_tab [index]= len;
1384                 }
1385 #if 1
1386                 /* ESC1 */
1387                 bits= rl->table_vlc[rl->n][0];
1388                 len=  rl->table_vlc[rl->n][1];
1389                 bits=bits*2;    len++; //esc1
1390                 level1= level - rl->max_level[last][run];
1391                 if(level1>0){
1392                     code= get_rl_index(rl, last, run, level1);
1393                     bits<<= rl->table_vlc[code][1];
1394                     len  += rl->table_vlc[code][1];
1395                     bits += rl->table_vlc[code][0];
1396                     bits=bits*2+sign; len++;
1397                 
1398                     if(code!=rl->n && len < len_tab[index]){
1399                         bits_tab[index]= bits;
1400                         len_tab [index]= len;
1401                     }
1402                 }
1403 #endif 
1404 #if 1
1405                 /* ESC2 */
1406                 bits= rl->table_vlc[rl->n][0];
1407                 len=  rl->table_vlc[rl->n][1];
1408                 bits=bits*4+2;    len+=2; //esc2
1409                 run1 = run - rl->max_run[last][level] - 1;
1410                 if(run1>=0){
1411                     code= get_rl_index(rl, last, run1, level);
1412                     bits<<= rl->table_vlc[code][1];
1413                     len  += rl->table_vlc[code][1];
1414                     bits += rl->table_vlc[code][0];
1415                     bits=bits*2+sign; len++;
1416                 
1417                     if(code!=rl->n && len < len_tab[index]){
1418                         bits_tab[index]= bits;
1419                         len_tab [index]= len;
1420                     }
1421                 }
1422 #endif           
1423                 /* ESC3 */        
1424                 bits= rl->table_vlc[rl->n][0];
1425                 len = rl->table_vlc[rl->n][1];
1426                 bits=bits*4+3;    len+=2; //esc3
1427                 bits=bits*2+last; len++;
1428                 bits=bits*64+run; len+=6;
1429                 bits=bits*2+1;    len++;  //marker
1430                 bits=bits*4096+(slevel&0xfff); len+=12;
1431                 bits=bits*2+1;    len++;  //marker
1432                 
1433                 if(len < len_tab[index]){
1434                     bits_tab[index]= bits;
1435                     len_tab [index]= len;
1436                 }
1437             }
1438         }
1439     }
1440 }
1441
1442 void h263_encode_init(MpegEncContext *s)
1443 {
1444     static int done = 0;
1445
1446     if (!done) {
1447         done = 1;
1448
1449         init_uni_dc_tab();
1450
1451         init_rl(&rl_inter);
1452         init_rl(&rl_intra);
1453         init_rl(&rl_intra_aic);
1454         
1455         init_uni_mpeg4_rl_tab(&rl_intra, uni_mpeg4_intra_rl_bits, uni_mpeg4_intra_rl_len);
1456         init_uni_mpeg4_rl_tab(&rl_inter, uni_mpeg4_inter_rl_bits, uni_mpeg4_inter_rl_len);
1457
1458         init_mv_penalty_and_fcode(s);
1459     }
1460     s->me.mv_penalty= mv_penalty; //FIXME exact table for msmpeg4 & h263p
1461     
1462     // use fcodes >1 only for mpeg4 & h263 & h263p FIXME
1463     switch(s->codec_id){
1464     case CODEC_ID_MPEG4:
1465         s->fcode_tab= fcode_tab;
1466         s->min_qcoeff= -2048;
1467         s->max_qcoeff=  2047;
1468         s->intra_ac_vlc_length     = uni_mpeg4_intra_rl_len;
1469         s->intra_ac_vlc_last_length= uni_mpeg4_intra_rl_len + 128*64;
1470         s->inter_ac_vlc_length     = uni_mpeg4_inter_rl_len;
1471         s->inter_ac_vlc_last_length= uni_mpeg4_inter_rl_len + 128*64;
1472         s->luma_dc_vlc_length= uni_DCtab_lum_len;
1473         s->chroma_dc_vlc_length= uni_DCtab_chrom_len;
1474         s->ac_esc_length= 7+2+1+6+1+12+1;
1475         break;
1476     case CODEC_ID_H263P:
1477         s->fcode_tab= umv_fcode_tab;
1478         s->min_qcoeff= -127;
1479         s->max_qcoeff=  127;
1480         break;
1481         //Note for mpeg4 & h263 the dc-scale table will be set per frame as needed later 
1482     default: //nothing needed default table allready set in mpegvideo.c
1483         s->min_qcoeff= -127;
1484         s->max_qcoeff=  127;
1485         s->y_dc_scale_table=
1486         s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
1487     }
1488
1489     if(s->mpeg_quant){
1490         s->intra_quant_bias= 3<<(QUANT_BIAS_SHIFT-3); //(a + x*3/8)/x
1491         s->inter_quant_bias= 0;
1492     }else{
1493         s->intra_quant_bias=0;
1494         s->inter_quant_bias=-(1<<(QUANT_BIAS_SHIFT-2)); //(a - x/4)/x
1495     }
1496 }
1497
1498 /**
1499  * encodes a 8x8 block.
1500  * @param block the 8x8 block
1501  * @param n block index (0-3 are luma, 4-5 are chroma)
1502  */
1503 static void h263_encode_block(MpegEncContext * s, DCTELEM * block, int n)
1504 {
1505     int level, run, last, i, j, last_index, last_non_zero, sign, slevel, code;
1506     RLTable *rl;
1507
1508     rl = &rl_inter;
1509     if (s->mb_intra && !s->h263_aic) {
1510         /* DC coef */
1511         level = block[0];
1512         /* 255 cannot be represented, so we clamp */
1513         if (level > 254) {
1514             level = 254;
1515             block[0] = 254;
1516         }
1517         /* 0 cannot be represented also */
1518         else if (level < 1) {
1519             level = 1;
1520             block[0] = 1;
1521         }
1522         if (level == 128) //FIXME check rv10
1523             put_bits(&s->pb, 8, 0xff);
1524         else
1525             put_bits(&s->pb, 8, level & 0xff);
1526         i = 1;
1527     } else {
1528         i = 0;
1529         if (s->h263_aic && s->mb_intra)
1530             rl = &rl_intra_aic;
1531     }
1532    
1533     /* AC coefs */
1534     last_index = s->block_last_index[n];
1535     last_non_zero = i - 1;
1536     for (; i <= last_index; i++) {
1537         j = s->intra_scantable.permutated[i];
1538         level = block[j];
1539         if (level) {
1540             run = i - last_non_zero - 1;
1541             last = (i == last_index);
1542             sign = 0;
1543             slevel = level;
1544             if (level < 0) {
1545                 sign = 1;
1546                 level = -level;
1547             }
1548             code = get_rl_index(rl, last, run, level);
1549             put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
1550             if (code == rl->n) {
1551                 put_bits(&s->pb, 1, last);
1552                 put_bits(&s->pb, 6, run);
1553                 
1554                 assert(slevel != 0);
1555
1556                 if(slevel < 128 && slevel > -128) 
1557                     put_bits(&s->pb, 8, slevel & 0xff);
1558                 else{
1559                     put_bits(&s->pb, 8, 128);
1560                     put_bits(&s->pb, 5, slevel & 0x1f);
1561                     put_bits(&s->pb, 6, (slevel>>5)&0x3f);
1562                 }
1563             } else {
1564                 put_bits(&s->pb, 1, sign);
1565             }
1566                 last_non_zero = i;
1567             }
1568     }
1569 }
1570 #endif
1571
1572 #ifdef CONFIG_ENCODERS
1573
1574 /***************************************************/
1575 /**
1576  * add mpeg4 stuffing bits (01...1)
1577  */
1578 void ff_mpeg4_stuffing(PutBitContext * pbc)
1579 {
1580     int length;
1581     put_bits(pbc, 1, 0);
1582     length= (-get_bit_count(pbc))&7;
1583     if(length) put_bits(pbc, length, (1<<length)-1);
1584 }
1585
1586 /* must be called before writing the header */
1587 void ff_set_mpeg4_time(MpegEncContext * s, int picture_number){
1588     int time_div, time_mod;
1589
1590     if(s->pict_type==I_TYPE){ //we will encode a vol header
1591         s->time_increment_resolution= s->frame_rate/ff_gcd(s->frame_rate, FRAME_RATE_BASE);
1592         if(s->time_increment_resolution>=256*256) s->time_increment_resolution= 256*128;
1593
1594         s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;
1595     }
1596     
1597     if(s->current_picture.pts)
1598         s->time= (s->current_picture.pts*s->time_increment_resolution + 500*1000)/(1000*1000);
1599     else
1600         s->time= picture_number*(int64_t)FRAME_RATE_BASE*s->time_increment_resolution/s->frame_rate;
1601     time_div= s->time/s->time_increment_resolution;
1602     time_mod= s->time%s->time_increment_resolution;
1603
1604     if(s->pict_type==B_TYPE){
1605         s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
1606     }else{
1607         s->last_time_base= s->time_base;
1608         s->time_base= time_div;
1609         s->pp_time= s->time - s->last_non_b_time;
1610         s->last_non_b_time= s->time;
1611     }
1612 }
1613
1614 static void mpeg4_encode_gop_header(MpegEncContext * s){
1615     int hours, minutes, seconds;
1616     
1617     put_bits(&s->pb, 16, 0);
1618     put_bits(&s->pb, 16, GOP_STARTCODE);
1619     
1620     seconds= s->time/s->time_increment_resolution;
1621     minutes= seconds/60; seconds %= 60;
1622     hours= minutes/60; minutes %= 60;
1623     hours%=24;
1624
1625     put_bits(&s->pb, 5, hours);
1626     put_bits(&s->pb, 6, minutes);
1627     put_bits(&s->pb, 1, 1);
1628     put_bits(&s->pb, 6, seconds);
1629     
1630     put_bits(&s->pb, 1, 0); //closed gov == NO
1631     put_bits(&s->pb, 1, 0); //broken link == NO
1632
1633     ff_mpeg4_stuffing(&s->pb);
1634 }
1635
1636 static void mpeg4_encode_visual_object_header(MpegEncContext * s){
1637     int profile_and_level_indication;
1638     int vo_ver_id;
1639     
1640     if(s->max_b_frames || s->quarter_sample){
1641         profile_and_level_indication= 0xF1; // adv simple level 1
1642         vo_ver_id= 5;
1643     }else{
1644         profile_and_level_indication= 0x01; // simple level 1
1645         vo_ver_id= 1;
1646     }
1647     //FIXME levels
1648
1649     put_bits(&s->pb, 16, 0);
1650     put_bits(&s->pb, 16, VOS_STARTCODE);
1651     
1652     put_bits(&s->pb, 8, profile_and_level_indication);
1653     
1654     put_bits(&s->pb, 16, 0);
1655     put_bits(&s->pb, 16, VISUAL_OBJ_STARTCODE);
1656     
1657     put_bits(&s->pb, 1, 1);
1658         put_bits(&s->pb, 4, vo_ver_id);
1659         put_bits(&s->pb, 3, 1); //priority
1660  
1661     put_bits(&s->pb, 4, 1); //visual obj type== video obj
1662     
1663     put_bits(&s->pb, 1, 0); //video signal type == no clue //FIXME
1664
1665     ff_mpeg4_stuffing(&s->pb);
1666 }
1667
1668 static void mpeg4_encode_vol_header(MpegEncContext * s, int vo_number, int vol_number)
1669 {
1670     int vo_ver_id;
1671     char buf[255];
1672
1673     if(s->max_b_frames || s->quarter_sample){
1674         vo_ver_id= 5;
1675         s->vo_type= ADV_SIMPLE_VO_TYPE;
1676     }else{
1677         vo_ver_id= 1;
1678         s->vo_type= SIMPLE_VO_TYPE;
1679     }
1680
1681     put_bits(&s->pb, 16, 0);
1682     put_bits(&s->pb, 16, 0x100 + vo_number);        /* video obj */
1683     put_bits(&s->pb, 16, 0);
1684     put_bits(&s->pb, 16, 0x120 + vol_number);       /* video obj layer */
1685
1686     put_bits(&s->pb, 1, 0);             /* random access vol */
1687     put_bits(&s->pb, 8, s->vo_type);    /* video obj type indication */
1688     put_bits(&s->pb, 1, 1);             /* is obj layer id= yes */
1689       put_bits(&s->pb, 4, vo_ver_id);   /* is obj layer ver id */
1690       put_bits(&s->pb, 3, 1);           /* is obj layer priority */
1691     
1692     float_aspect_to_info(s, s->avctx->aspect_ratio);
1693
1694     put_bits(&s->pb, 4, s->aspect_ratio_info);/* aspect ratio info */
1695     if (s->aspect_ratio_info == FF_ASPECT_EXTENDED)
1696     {
1697         put_bits(&s->pb, 8, s->aspected_width);
1698         put_bits(&s->pb, 8, s->aspected_height);
1699     }
1700
1701     if(s->low_delay){
1702         put_bits(&s->pb, 1, 1);         /* vol control parameters= yes */
1703         put_bits(&s->pb, 2, 1);         /* chroma format YUV 420/YV12 */
1704         put_bits(&s->pb, 1, s->low_delay);
1705         put_bits(&s->pb, 1, 0);         /* vbv parameters= no */
1706     }else{
1707         put_bits(&s->pb, 1, 0);         /* vol control parameters= no */
1708     }
1709
1710     put_bits(&s->pb, 2, RECT_SHAPE);    /* vol shape= rectangle */
1711     put_bits(&s->pb, 1, 1);             /* marker bit */
1712     
1713     put_bits(&s->pb, 16, s->time_increment_resolution);
1714     if (s->time_increment_bits < 1)
1715         s->time_increment_bits = 1;
1716     put_bits(&s->pb, 1, 1);             /* marker bit */
1717     put_bits(&s->pb, 1, 0);             /* fixed vop rate=no */
1718     put_bits(&s->pb, 1, 1);             /* marker bit */
1719     put_bits(&s->pb, 13, s->width);     /* vol width */
1720     put_bits(&s->pb, 1, 1);             /* marker bit */
1721     put_bits(&s->pb, 13, s->height);    /* vol height */
1722     put_bits(&s->pb, 1, 1);             /* marker bit */
1723     put_bits(&s->pb, 1, s->progressive_sequence ? 0 : 1);
1724     put_bits(&s->pb, 1, 1);             /* obmc disable */
1725     if (vo_ver_id == 1) {
1726         put_bits(&s->pb, 1, s->vol_sprite_usage=0);             /* sprite enable */
1727     }else{
1728         put_bits(&s->pb, 2, s->vol_sprite_usage=0);             /* sprite enable */
1729     }
1730     
1731     s->quant_precision=5;
1732     put_bits(&s->pb, 1, 0);             /* not 8 bit == false */
1733     put_bits(&s->pb, 1, s->mpeg_quant); /* quant type= (0=h263 style)*/
1734     if(s->mpeg_quant) put_bits(&s->pb, 2, 0); /* no custom matrixes */
1735
1736     if (vo_ver_id != 1)
1737         put_bits(&s->pb, 1, s->quarter_sample);
1738     put_bits(&s->pb, 1, 1);             /* complexity estimation disable */
1739     s->resync_marker= s->rtp_mode;
1740     put_bits(&s->pb, 1, s->resync_marker ? 0 : 1);/* resync marker disable */
1741     put_bits(&s->pb, 1, s->data_partitioning ? 1 : 0);
1742     if(s->data_partitioning){
1743         put_bits(&s->pb, 1, 0);         /* no rvlc */
1744     }
1745
1746     if (vo_ver_id != 1){
1747         put_bits(&s->pb, 1, 0);         /* newpred */
1748         put_bits(&s->pb, 1, 0);         /* reduced res vop */
1749     }
1750     put_bits(&s->pb, 1, 0);             /* scalability */
1751     
1752     ff_mpeg4_stuffing(&s->pb);
1753
1754     /* user data */
1755     if(!(s->flags & CODEC_FLAG_BITEXACT)){
1756         put_bits(&s->pb, 16, 0);
1757         put_bits(&s->pb, 16, 0x1B2);    /* user_data */
1758         sprintf(buf, "FFmpeg%sb%s", FFMPEG_VERSION, LIBAVCODEC_BUILD_STR);
1759         put_string(&s->pb, buf);
1760         ff_mpeg4_stuffing(&s->pb);
1761     }
1762 }
1763
1764 /* write mpeg4 VOP header */
1765 void mpeg4_encode_picture_header(MpegEncContext * s, int picture_number)
1766 {
1767     int time_incr;
1768     int time_div, time_mod;
1769     
1770     if(s->pict_type==I_TYPE){
1771         if(!(s->flags&CODEC_FLAG_GLOBAL_HEADER)){
1772             mpeg4_encode_visual_object_header(s);
1773             mpeg4_encode_vol_header(s, 0, 0);
1774         }
1775         mpeg4_encode_gop_header(s);
1776     }
1777     
1778     s->partitioned_frame= s->data_partitioning && s->pict_type!=B_TYPE;
1779
1780 //printf("num:%d rate:%d base:%d\n", s->picture_number, s->frame_rate, FRAME_RATE_BASE);
1781     
1782     put_bits(&s->pb, 16, 0);            /* vop header */
1783     put_bits(&s->pb, 16, VOP_STARTCODE);        /* vop header */
1784     put_bits(&s->pb, 2, s->pict_type - 1);      /* pict type: I = 0 , P = 1 */
1785
1786     time_div= s->time/s->time_increment_resolution;
1787     time_mod= s->time%s->time_increment_resolution;
1788     time_incr= time_div - s->last_time_base;
1789     while(time_incr--)
1790         put_bits(&s->pb, 1, 1);
1791         
1792     put_bits(&s->pb, 1, 0);
1793
1794     put_bits(&s->pb, 1, 1);     /* marker */
1795     put_bits(&s->pb, s->time_increment_bits, time_mod); /* time increment */
1796     put_bits(&s->pb, 1, 1);     /* marker */
1797     put_bits(&s->pb, 1, 1);     /* vop coded */
1798     if (    s->pict_type == P_TYPE 
1799         || (s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE)) {
1800         put_bits(&s->pb, 1, s->no_rounding);    /* rounding type */
1801     }
1802     put_bits(&s->pb, 3, 0);     /* intra dc VLC threshold */
1803     if(!s->progressive_sequence){
1804          put_bits(&s->pb, 1, s->top_field_first);
1805          put_bits(&s->pb, 1, s->alternate_scan);
1806     }
1807     //FIXME sprite stuff
1808
1809     put_bits(&s->pb, 5, s->qscale);
1810
1811     if (s->pict_type != I_TYPE)
1812         put_bits(&s->pb, 3, s->f_code); /* fcode_for */
1813     if (s->pict_type == B_TYPE)
1814         put_bits(&s->pb, 3, s->b_code); /* fcode_back */
1815     //    printf("****frame %d\n", picture_number);
1816
1817      s->y_dc_scale_table= ff_mpeg4_y_dc_scale_table; //FIXME add short header support 
1818      s->c_dc_scale_table= ff_mpeg4_c_dc_scale_table;
1819      s->h_edge_pos= s->width;
1820      s->v_edge_pos= s->height;
1821 }
1822
1823 #endif //CONFIG_ENCODERS
1824
1825 /**
1826  * change qscale by given dquant and update qscale dependant variables.
1827  */
1828 static void change_qscale(MpegEncContext * s, int dquant)
1829 {
1830     s->qscale += dquant;
1831
1832     if (s->qscale < 1)
1833         s->qscale = 1;
1834     else if (s->qscale > 31)
1835         s->qscale = 31;
1836
1837     s->y_dc_scale= s->y_dc_scale_table[ s->qscale ];
1838     s->c_dc_scale= s->c_dc_scale_table[ s->qscale ];
1839 }
1840
1841 /**
1842  * predicts the dc.
1843  * @param n block index (0-3 are luma, 4-5 are chroma)
1844  * @param dc_val_ptr a pointer to the dc_val entry for the current MB will be stored here
1845  * @param dir_ptr pointer to an integer where the prediction direction will be stored
1846  * @return the quantized predicted dc
1847  */
1848 static inline int ff_mpeg4_pred_dc(MpegEncContext * s, int n, uint16_t **dc_val_ptr, int *dir_ptr)
1849 {
1850     int a, b, c, wrap, pred, scale;
1851     uint16_t *dc_val;
1852     int dummy;
1853
1854     /* find prediction */
1855     if (n < 4) {
1856         scale = s->y_dc_scale;
1857     } else {
1858         scale = s->c_dc_scale;
1859     }
1860     wrap= s->block_wrap[n];
1861     dc_val = s->dc_val[0] + s->block_index[n];
1862
1863     /* B C
1864      * A X 
1865      */
1866     a = dc_val[ - 1];
1867     b = dc_val[ - 1 - wrap];
1868     c = dc_val[ - wrap];
1869
1870     /* outside slice handling (we cant do that by memset as we need the dc for error resilience) */
1871     if(s->first_slice_line && n!=3){
1872         if(n!=2) b=c= 1024;
1873         if(n!=1 && s->mb_x == s->resync_mb_x) b=a= 1024;
1874     }
1875     if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1){
1876         if(n==0 || n==4 || n==5)
1877             b=1024;
1878     }
1879
1880     if (abs(a - b) < abs(b - c)) {
1881         pred = c;
1882         *dir_ptr = 1; /* top */
1883     } else {
1884         pred = a;
1885         *dir_ptr = 0; /* left */
1886     }
1887     /* we assume pred is positive */
1888 #ifdef ARCH_X86
1889         asm volatile (
1890                 "xorl %%edx, %%edx      \n\t"
1891                 "mul %%ecx              \n\t"
1892                 : "=d" (pred), "=a"(dummy)
1893                 : "a" (pred + (scale >> 1)), "c" (inverse[scale])
1894         );
1895 #else
1896     pred = (pred + (scale >> 1)) / scale;
1897 #endif
1898
1899     /* prepare address for prediction update */
1900     *dc_val_ptr = &dc_val[0];
1901
1902     return pred;
1903 }
1904
1905 /**
1906  * predicts the ac.
1907  * @param n block index (0-3 are luma, 4-5 are chroma)
1908  * @param dir the ac prediction direction
1909  */
1910 void mpeg4_pred_ac(MpegEncContext * s, DCTELEM *block, int n,
1911                    int dir)
1912 {
1913     int i;
1914     int16_t *ac_val, *ac_val1;
1915     int8_t * const qscale_table= s->current_picture.qscale_table;
1916
1917     /* find prediction */
1918     ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
1919     ac_val1 = ac_val;
1920     if (s->ac_pred) {
1921         if (dir == 0) {
1922             const int xy= s->mb_x-1 + s->mb_y*s->mb_width;
1923             /* left prediction */
1924             ac_val -= 16;
1925             
1926             if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
1927                 /* same qscale */
1928                 for(i=1;i<8;i++) {
1929                     block[s->dsp.idct_permutation[i<<3]] += ac_val[i];
1930                 }
1931             }else{
1932                 /* different qscale, we must rescale */
1933                 for(i=1;i<8;i++) {
1934                     block[s->dsp.idct_permutation[i<<3]] += ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale);
1935                 }
1936             }
1937         } else {
1938             const int xy= s->mb_x + s->mb_y*s->mb_width - s->mb_width;
1939             /* top prediction */
1940             ac_val -= 16 * s->block_wrap[n];
1941
1942             if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
1943                 /* same qscale */
1944                 for(i=1;i<8;i++) {
1945                     block[s->dsp.idct_permutation[i]] += ac_val[i + 8];
1946                 }
1947             }else{
1948                 /* different qscale, we must rescale */
1949                 for(i=1;i<8;i++) {
1950                     block[s->dsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale);
1951                 }
1952             }
1953         }
1954     }
1955     /* left copy */
1956     for(i=1;i<8;i++)
1957         ac_val1[i    ] = block[s->dsp.idct_permutation[i<<3]];
1958
1959     /* top copy */
1960     for(i=1;i<8;i++)
1961         ac_val1[8 + i] = block[s->dsp.idct_permutation[i   ]];
1962
1963 }
1964
1965 #ifdef CONFIG_ENCODERS
1966
1967 static void mpeg4_inv_pred_ac(MpegEncContext * s, DCTELEM *block, int n,
1968                               int dir)
1969 {
1970     int i;
1971     int16_t *ac_val;
1972     int8_t * const qscale_table= s->current_picture.qscale_table;
1973
1974     /* find prediction */
1975     ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
1976  
1977     if (dir == 0) {
1978         const int xy= s->mb_x-1 + s->mb_y*s->mb_width;
1979         /* left prediction */
1980         ac_val -= 16;
1981         if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
1982             /* same qscale */
1983             for(i=1;i<8;i++) {
1984                 block[s->dsp.idct_permutation[i<<3]] -= ac_val[i];
1985             }
1986         }else{
1987             /* different qscale, we must rescale */
1988             for(i=1;i<8;i++) {
1989                 block[s->dsp.idct_permutation[i<<3]] -= ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale);
1990             }
1991         }
1992     } else {
1993         const int xy= s->mb_x + s->mb_y*s->mb_width - s->mb_width;
1994         /* top prediction */
1995         ac_val -= 16 * s->block_wrap[n];
1996         if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
1997             /* same qscale */
1998             for(i=1;i<8;i++) {
1999                 block[s->dsp.idct_permutation[i]] -= ac_val[i + 8];
2000             }
2001         }else{
2002             /* different qscale, we must rescale */
2003             for(i=1;i<8;i++) {
2004                 block[s->dsp.idct_permutation[i]] -= ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale);
2005             }
2006         }
2007     }
2008 }
2009
2010 /**
2011  * encodes the dc value.
2012  * @param n block index (0-3 are luma, 4-5 are chroma)
2013  */
2014 static inline void mpeg4_encode_dc(PutBitContext * s, int level, int n)
2015 {
2016 #if 1
2017 //    if(level<-255 || level>255) printf("dc overflow\n");
2018     level+=256;
2019     if (n < 4) {
2020         /* luminance */
2021         put_bits(s, uni_DCtab_lum_len[level], uni_DCtab_lum_bits[level]);
2022     } else {
2023         /* chrominance */
2024         put_bits(s, uni_DCtab_chrom_len[level], uni_DCtab_chrom_bits[level]);
2025     }
2026 #else
2027     int size, v;
2028     /* find number of bits */
2029     size = 0;
2030     v = abs(level);
2031     while (v) {
2032         v >>= 1;
2033         size++;
2034     }
2035
2036     if (n < 4) {
2037         /* luminance */
2038         put_bits(&s->pb, DCtab_lum[size][1], DCtab_lum[size][0]);
2039     } else {
2040         /* chrominance */
2041         put_bits(&s->pb, DCtab_chrom[size][1], DCtab_chrom[size][0]);
2042     }
2043
2044     /* encode remaining bits */
2045     if (size > 0) {
2046         if (level < 0)
2047             level = (-level) ^ ((1 << size) - 1);
2048         put_bits(&s->pb, size, level);
2049         if (size > 8)
2050             put_bits(&s->pb, 1, 1);
2051     }
2052 #endif
2053 }
2054
2055 /**
2056  * encodes a 8x8 block
2057  * @param n block index (0-3 are luma, 4-5 are chroma)
2058  */
2059 static inline void mpeg4_encode_block(MpegEncContext * s, DCTELEM * block, int n, int intra_dc, 
2060                                uint8_t *scan_table, PutBitContext *dc_pb, PutBitContext *ac_pb)
2061 {
2062     int i, last_non_zero;
2063 #if 0 //variables for the outcommented version
2064     int code, sign, last;
2065 #endif
2066     const RLTable *rl;
2067     uint32_t *bits_tab;
2068     uint8_t *len_tab;
2069     const int last_index = s->block_last_index[n];
2070
2071     if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
2072         /* mpeg4 based DC predictor */
2073         mpeg4_encode_dc(dc_pb, intra_dc, n);
2074         if(last_index<1) return;
2075         i = 1;
2076         rl = &rl_intra;
2077         bits_tab= uni_mpeg4_intra_rl_bits;
2078         len_tab = uni_mpeg4_intra_rl_len;
2079     } else {
2080         if(last_index<0) return;
2081         i = 0;
2082         rl = &rl_inter;
2083         bits_tab= uni_mpeg4_inter_rl_bits;
2084         len_tab = uni_mpeg4_inter_rl_len;
2085     }
2086
2087     /* AC coefs */
2088     last_non_zero = i - 1;
2089 #if 1
2090     for (; i < last_index; i++) {
2091         int level = block[ scan_table[i] ];
2092         if (level) {
2093             int run = i - last_non_zero - 1;
2094             level+=64;
2095             if((level&(~127)) == 0){
2096                 const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
2097                 put_bits(ac_pb, len_tab[index], bits_tab[index]);
2098             }else{ //ESC3
2099                 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);
2100             }
2101             last_non_zero = i;
2102         }
2103     }
2104     /*if(i<=last_index)*/{
2105         int level = block[ scan_table[i] ];
2106         int run = i - last_non_zero - 1;
2107         level+=64;
2108         if((level&(~127)) == 0){
2109             const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
2110             put_bits(ac_pb, len_tab[index], bits_tab[index]);
2111         }else{ //ESC3
2112             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);
2113         }
2114     }
2115 #else
2116     for (; i <= last_index; i++) {
2117         const int slevel = block[ scan_table[i] ];
2118         if (slevel) {
2119             int level;
2120             int run = i - last_non_zero - 1;
2121             last = (i == last_index);
2122             sign = 0;
2123             level = slevel;
2124             if (level < 0) {
2125                 sign = 1;
2126                 level = -level;
2127             }
2128             code = get_rl_index(rl, last, run, level);
2129             put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2130             if (code == rl->n) {
2131                 int level1, run1;
2132                 level1 = level - rl->max_level[last][run];
2133                 if (level1 < 1) 
2134                     goto esc2;
2135                 code = get_rl_index(rl, last, run, level1);
2136                 if (code == rl->n) {
2137                 esc2:
2138                     put_bits(ac_pb, 1, 1);
2139                     if (level > MAX_LEVEL)
2140                         goto esc3;
2141                     run1 = run - rl->max_run[last][level] - 1;
2142                     if (run1 < 0)
2143                         goto esc3;
2144                     code = get_rl_index(rl, last, run1, level);
2145                     if (code == rl->n) {
2146                     esc3:
2147                         /* third escape */
2148                         put_bits(ac_pb, 1, 1);
2149                         put_bits(ac_pb, 1, last);
2150                         put_bits(ac_pb, 6, run);
2151                         put_bits(ac_pb, 1, 1);
2152                         put_bits(ac_pb, 12, slevel & 0xfff);
2153                         put_bits(ac_pb, 1, 1);
2154                     } else {
2155                         /* second escape */
2156                         put_bits(ac_pb, 1, 0);
2157                         put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2158                         put_bits(ac_pb, 1, sign);
2159                     }
2160                 } else {
2161                     /* first escape */
2162                     put_bits(ac_pb, 1, 0);
2163                     put_bits(ac_pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
2164                     put_bits(ac_pb, 1, sign);
2165                 }
2166             } else {
2167                 put_bits(ac_pb, 1, sign);
2168             }
2169             last_non_zero = i;
2170         }
2171     }
2172 #endif
2173 }
2174
2175 static inline int mpeg4_get_block_length(MpegEncContext * s, DCTELEM * block, int n, int intra_dc, 
2176                                uint8_t *scan_table)
2177 {
2178     int i, last_non_zero;
2179     const RLTable *rl;
2180     uint8_t *len_tab;
2181     const int last_index = s->block_last_index[n];
2182     int len=0;
2183
2184     if (s->mb_intra) { //Note gcc (3.2.1 at least) will optimize this away
2185         /* mpeg4 based DC predictor */
2186         //mpeg4_encode_dc(dc_pb, intra_dc, n); //FIXME
2187         if(last_index<1) return len;
2188         i = 1;
2189         rl = &rl_intra;
2190         len_tab = uni_mpeg4_intra_rl_len;
2191     } else {
2192         if(last_index<0) return 0;
2193         i = 0;
2194         rl = &rl_inter;
2195         len_tab = uni_mpeg4_inter_rl_len;
2196     }
2197
2198     /* AC coefs */
2199     last_non_zero = i - 1;
2200     for (; i < last_index; i++) {
2201         int level = block[ scan_table[i] ];
2202         if (level) {
2203             int run = i - last_non_zero - 1;
2204             level+=64;
2205             if((level&(~127)) == 0){
2206                 const int index= UNI_MPEG4_ENC_INDEX(0, run, level);
2207                 len += len_tab[index];
2208             }else{ //ESC3
2209                 len += 7+2+1+6+1+12+1;
2210             }
2211             last_non_zero = i;
2212         }
2213     }
2214     /*if(i<=last_index)*/{
2215         int level = block[ scan_table[i] ];
2216         int run = i - last_non_zero - 1;
2217         level+=64;
2218         if((level&(~127)) == 0){
2219             const int index= UNI_MPEG4_ENC_INDEX(1, run, level);
2220             len += len_tab[index];
2221         }else{ //ESC3
2222             len += 7+2+1+6+1+12+1;
2223         }
2224     }
2225     
2226     return len;
2227 }
2228
2229 #endif
2230
2231
2232 /***********************************************/
2233 /* decoding */
2234
2235 static VLC intra_MCBPC_vlc;
2236 static VLC inter_MCBPC_vlc;
2237 static VLC cbpy_vlc;
2238 static VLC mv_vlc;
2239 static VLC dc_lum, dc_chrom;
2240 static VLC sprite_trajectory;
2241 static VLC mb_type_b_vlc;
2242
2243 void init_vlc_rl(RLTable *rl)
2244 {
2245     int i, q;
2246     
2247     init_vlc(&rl->vlc, 9, rl->n + 1, 
2248              &rl->table_vlc[0][1], 4, 2,
2249              &rl->table_vlc[0][0], 4, 2);
2250
2251     
2252     for(q=0; q<32; q++){
2253         int qmul= q*2;
2254         int qadd= (q-1)|1;
2255         
2256         if(q==0){
2257             qmul=1;
2258             qadd=0;
2259         }
2260         
2261         rl->rl_vlc[q]= av_malloc(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
2262         for(i=0; i<rl->vlc.table_size; i++){
2263             int code= rl->vlc.table[i][0];
2264             int len = rl->vlc.table[i][1];
2265             int level, run;
2266         
2267             if(len==0){ // illegal code
2268                 run= 66;
2269                 level= MAX_LEVEL;
2270             }else if(len<0){ //more bits needed
2271                 run= 0;
2272                 level= code;
2273             }else{
2274                 if(code==rl->n){ //esc
2275                     run= 66;
2276                     level= 0;
2277                 }else{
2278                     run=   rl->table_run  [code] + 1;
2279                     level= rl->table_level[code] * qmul + qadd;
2280                     if(code >= rl->last) run+=192;
2281                 }
2282             }
2283             rl->rl_vlc[q][i].len= len;
2284             rl->rl_vlc[q][i].level= level;
2285             rl->rl_vlc[q][i].run= run;
2286         }
2287     }
2288 }
2289
2290 /* init vlcs */
2291
2292 /* XXX: find a better solution to handle static init */
2293 void h263_decode_init_vlc(MpegEncContext *s)
2294 {
2295     static int done = 0;
2296
2297     if (!done) {
2298         done = 1;
2299
2300         init_vlc(&intra_MCBPC_vlc, INTRA_MCBPC_VLC_BITS, 8, 
2301                  intra_MCBPC_bits, 1, 1,
2302                  intra_MCBPC_code, 1, 1);
2303         init_vlc(&inter_MCBPC_vlc, INTER_MCBPC_VLC_BITS, 25, 
2304                  inter_MCBPC_bits, 1, 1,
2305                  inter_MCBPC_code, 1, 1);
2306         init_vlc(&cbpy_vlc, CBPY_VLC_BITS, 16,
2307                  &cbpy_tab[0][1], 2, 1,
2308                  &cbpy_tab[0][0], 2, 1);
2309         init_vlc(&mv_vlc, MV_VLC_BITS, 33,
2310                  &mvtab[0][1], 2, 1,
2311                  &mvtab[0][0], 2, 1);
2312         init_rl(&rl_inter);
2313         init_rl(&rl_intra);
2314         init_rl(&rl_intra_aic);
2315         init_vlc_rl(&rl_inter);
2316         init_vlc_rl(&rl_intra);
2317         init_vlc_rl(&rl_intra_aic);
2318         init_vlc(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
2319                  &DCtab_lum[0][1], 2, 1,
2320                  &DCtab_lum[0][0], 2, 1);
2321         init_vlc(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
2322                  &DCtab_chrom[0][1], 2, 1,
2323                  &DCtab_chrom[0][0], 2, 1);
2324         init_vlc(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
2325                  &sprite_trajectory_tab[0][1], 4, 2,
2326                  &sprite_trajectory_tab[0][0], 4, 2);
2327         init_vlc(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
2328                  &mb_type_b_tab[0][1], 2, 1,
2329                  &mb_type_b_tab[0][0], 2, 1);
2330     }
2331 }
2332
2333 /**
2334  * Get the GOB height based on picture height.
2335  */
2336 int ff_h263_get_gob_height(MpegEncContext *s){
2337     if (s->height <= 400)
2338         return 1;
2339     else if (s->height <= 800)
2340         return  2;
2341     else
2342         return 4;
2343 }
2344
2345 /**
2346  * decodes the group of blocks header.
2347  * @return <0 if an error occured
2348  */
2349 static int h263_decode_gob_header(MpegEncContext *s)
2350 {
2351     unsigned int val, gfid;
2352     int left;
2353     
2354     /* Check for GOB Start Code */
2355     val = show_bits(&s->gb, 16);
2356     if(val)
2357         return -1;
2358
2359         /* We have a GBSC probably with GSTUFF */
2360     skip_bits(&s->gb, 16); /* Drop the zeros */
2361     left= s->gb.size_in_bits - get_bits_count(&s->gb);
2362     //MN: we must check the bits left or we might end in a infinite loop (or segfault)
2363     for(;left>13; left--){
2364         if(get_bits1(&s->gb)) break; /* Seek the '1' bit */
2365     }
2366     if(left<=13) 
2367         return -1;
2368
2369 #ifdef DEBUG
2370     fprintf(stderr,"\nGOB Start Code at MB %d\n", (s->mb_y * s->mb_width) + s->mb_x);
2371 #endif
2372     s->gob_number = get_bits(&s->gb, 5); /* GN */
2373     gfid = get_bits(&s->gb, 2); /* GFID */
2374     s->qscale = get_bits(&s->gb, 5); /* GQUANT */
2375     if(s->qscale==0) 
2376         return -1;
2377     s->mb_x= 0;
2378     s->mb_y= s->gob_index* s->gob_number;
2379 #ifdef DEBUG
2380     fprintf(stderr, "\nGN: %u GFID: %u Quant: %u\n", s->gob_number, gfid, s->qscale);
2381 #endif
2382     return 0;
2383 }
2384
2385 static inline void memsetw(short *tab, int val, int n)
2386 {
2387     int i;
2388     for(i=0;i<n;i++)
2389         tab[i] = val;
2390 }
2391
2392 #ifdef CONFIG_ENCODERS
2393
2394 void ff_mpeg4_init_partitions(MpegEncContext *s)
2395 {
2396     init_put_bits(&s->tex_pb, s->tex_pb_buffer, PB_BUFFER_SIZE, NULL, NULL);
2397     init_put_bits(&s->pb2   , s->pb2_buffer   , PB_BUFFER_SIZE, NULL, NULL);
2398 }
2399
2400 void ff_mpeg4_merge_partitions(MpegEncContext *s)
2401 {
2402     const int pb2_len   = get_bit_count(&s->pb2   );
2403     const int tex_pb_len= get_bit_count(&s->tex_pb);
2404     const int bits= get_bit_count(&s->pb);
2405
2406     if(s->pict_type==I_TYPE){
2407         put_bits(&s->pb, 19, DC_MARKER);
2408         s->misc_bits+=19 + pb2_len + bits - s->last_bits;
2409         s->i_tex_bits+= tex_pb_len;
2410     }else{
2411         put_bits(&s->pb, 17, MOTION_MARKER);
2412         s->misc_bits+=17 + pb2_len;
2413         s->mv_bits+= bits - s->last_bits;
2414         s->p_tex_bits+= tex_pb_len;
2415     }
2416
2417     flush_put_bits(&s->pb2);
2418     flush_put_bits(&s->tex_pb);
2419
2420     ff_copy_bits(&s->pb, s->pb2_buffer   , pb2_len);
2421     ff_copy_bits(&s->pb, s->tex_pb_buffer, tex_pb_len);
2422     s->last_bits= get_bit_count(&s->pb);
2423 }
2424
2425 #endif //CONFIG_ENCODERS
2426
2427 int ff_mpeg4_get_video_packet_prefix_length(MpegEncContext *s){
2428     switch(s->pict_type){
2429         case I_TYPE:
2430             return 16;
2431         case P_TYPE:
2432         case S_TYPE:
2433             return s->f_code+15;
2434         case B_TYPE:
2435             return FFMAX(FFMAX(s->f_code, s->b_code)+15, 17);
2436         default:
2437             return -1;
2438     }
2439 }
2440
2441 #ifdef CONFIG_ENCODERS
2442
2443 void ff_mpeg4_encode_video_packet_header(MpegEncContext *s)
2444 {
2445     int mb_num_bits= av_log2(s->mb_num - 1) + 1;
2446
2447     ff_mpeg4_stuffing(&s->pb);
2448     put_bits(&s->pb, ff_mpeg4_get_video_packet_prefix_length(s), 0);
2449     put_bits(&s->pb, 1, 1);
2450     
2451     put_bits(&s->pb, mb_num_bits, s->mb_x + s->mb_y*s->mb_width);
2452     put_bits(&s->pb, s->quant_precision, s->qscale);
2453     put_bits(&s->pb, 1, 0); /* no HEC */
2454 }
2455
2456 #endif //CONFIG_ENCODERS
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_t));
2602     memset(s->ac_val[1] + c_xy, 0, (c_wrap  +1)*16*sizeof(int16_t));
2603     memset(s->ac_val[2] + c_xy, 0, (c_wrap  +1)*16*sizeof(int16_t));
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_t));
2608 //    memset(s->motion_val, 0, 2*sizeof(int16_t)*(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_t 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_t * 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_t *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_t 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_t *mot_val;
3111     static int8_t 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)
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)
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 && (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)
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)
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 && (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
3254         s->mb_intra = 0; //B-frames never contain intra blocks
3255         s->mcsel=0;      //     ...               true gmc blocks
3256
3257         if(s->mb_x==0){
3258             for(i=0; i<2; i++){
3259                 s->last_mv[i][0][0]= 
3260                 s->last_mv[i][0][1]= 
3261                 s->last_mv[i][1][0]= 
3262                 s->last_mv[i][1][1]= 0;
3263             }
3264         }
3265
3266         /* if we skipped it in the future P Frame than skip it now too */
3267         s->mb_skiped= s->next_picture.mbskip_table[s->mb_y * s->mb_width + s->mb_x]; // Note, skiptab=0 if last was GMC
3268
3269         if(s->mb_skiped){
3270                 /* skip mb */
3271             for(i=0;i<6;i++)
3272                 s->block_last_index[i] = -1;
3273
3274             s->mv_dir = MV_DIR_FORWARD;
3275             s->mv_type = MV_TYPE_16X16;
3276             s->mv[0][0][0] = 0;
3277             s->mv[0][0][1] = 0;
3278             s->mv[1][0][0] = 0;
3279             s->mv[1][0][1] = 0;
3280             PRINT_MB_TYPE("s");
3281             goto end;
3282         }
3283
3284         modb1= get_bits1(&s->gb); 
3285         if(modb1){
3286             mb_type=4; //like MB_TYPE_B_DIRECT but no vectors coded
3287             cbp=0;
3288         }else{
3289             int field_mv;
3290         
3291             modb2= get_bits1(&s->gb);
3292             mb_type= get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);
3293             if(modb2) cbp= 0;
3294             else      cbp= get_bits(&s->gb, 6);
3295
3296             if (mb_type!=MB_TYPE_B_DIRECT && cbp) {
3297                 if(get_bits1(&s->gb)){
3298                     change_qscale(s, get_bits1(&s->gb)*4 - 2);
3299                 }
3300             }
3301             field_mv=0;
3302
3303             if(!s->progressive_sequence){
3304                 if(cbp)
3305                     s->interlaced_dct= get_bits1(&s->gb);
3306
3307                 if(mb_type!=MB_TYPE_B_DIRECT && get_bits1(&s->gb)){
3308                     field_mv=1;
3309
3310                     if(mb_type!=MB_TYPE_B_BACKW){
3311                         s->field_select[0][0]= get_bits1(&s->gb);
3312                         s->field_select[0][1]= get_bits1(&s->gb);
3313                     }
3314                     if(mb_type!=MB_TYPE_B_FORW){
3315                         s->field_select[1][0]= get_bits1(&s->gb);
3316                         s->field_select[1][1]= get_bits1(&s->gb);
3317                     }
3318                 }
3319             }
3320
3321             s->mv_dir = 0;
3322             if(mb_type!=MB_TYPE_B_DIRECT && !field_mv){
3323                 s->mv_type= MV_TYPE_16X16;
3324                 if(mb_type!=MB_TYPE_B_BACKW){
3325                     s->mv_dir = MV_DIR_FORWARD;
3326
3327                     mx = h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
3328                     my = h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
3329                     s->last_mv[0][1][0]= s->last_mv[0][0][0]= s->mv[0][0][0] = mx;
3330                     s->last_mv[0][1][1]= s->last_mv[0][0][1]= s->mv[0][0][1] = my;
3331                 }
3332     
3333                 if(mb_type!=MB_TYPE_B_FORW){
3334                     s->mv_dir |= MV_DIR_BACKWARD;
3335
3336                     mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
3337                     my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
3338                     s->last_mv[1][1][0]= s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
3339                     s->last_mv[1][1][1]= s->last_mv[1][0][1]= s->mv[1][0][1] = my;
3340                 }
3341                 if(mb_type!=MB_TYPE_B_DIRECT)
3342                     PRINT_MB_TYPE(mb_type==MB_TYPE_B_FORW ? "F" : (mb_type==MB_TYPE_B_BACKW ? "B" : "T"));
3343             }else if(mb_type!=MB_TYPE_B_DIRECT){
3344                 s->mv_type= MV_TYPE_FIELD;
3345
3346                 if(mb_type!=MB_TYPE_B_BACKW){
3347                     s->mv_dir = MV_DIR_FORWARD;
3348                 
3349                     for(i=0; i<2; i++){
3350                         mx = h263_decode_motion(s, s->last_mv[0][i][0]  , s->f_code);
3351                         my = h263_decode_motion(s, s->last_mv[0][i][1]/2, s->f_code);
3352                         s->last_mv[0][i][0]=  s->mv[0][i][0] = mx;
3353                         s->last_mv[0][i][1]= (s->mv[0][i][1] = my)*2;
3354                     }
3355                 }
3356     
3357                 if(mb_type!=MB_TYPE_B_FORW){
3358                     s->mv_dir |= MV_DIR_BACKWARD;
3359
3360                     for(i=0; i<2; i++){
3361                         mx = h263_decode_motion(s, s->last_mv[1][i][0]  , s->b_code);
3362                         my = h263_decode_motion(s, s->last_mv[1][i][1]/2, s->b_code);
3363                         s->last_mv[1][i][0]=  s->mv[1][i][0] = mx;
3364                         s->last_mv[1][i][1]= (s->mv[1][i][1] = my)*2;
3365                     }
3366                 }
3367                 if(mb_type!=MB_TYPE_B_DIRECT)
3368                     PRINT_MB_TYPE(mb_type==MB_TYPE_B_FORW ? "f" : (mb_type==MB_TYPE_B_BACKW ? "b" : "t"));
3369             }
3370         }
3371           
3372         if(mb_type==4 || mb_type==MB_TYPE_B_DIRECT){
3373             if(mb_type==4)
3374                 mx=my=0;
3375             else{
3376                 mx = h263_decode_motion(s, 0, 1);
3377                 my = h263_decode_motion(s, 0, 1);
3378             }
3379  
3380             s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
3381             ff_mpeg4_set_direct_mv(s, mx, my);
3382         }
3383         
3384         if(mb_type<0 || mb_type>4){
3385             printf("illegal MB_type\n");
3386             return -1;
3387         }
3388     } else { /* I-Frame */
3389         cbpc = get_vlc2(&s->gb, intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 1);
3390         if (cbpc < 0)
3391             return -1;
3392         dquant = cbpc & 4;
3393         s->mb_intra = 1;
3394 intra:
3395         s->ac_pred = 0;
3396         if (s->h263_pred || s->h263_aic) {
3397             s->ac_pred = get_bits1(&s->gb);
3398             if (s->ac_pred && s->h263_aic)
3399                 s->h263_aic_dir = get_bits1(&s->gb);
3400         }
3401         PRINT_MB_TYPE(s->ac_pred ? "A" : "I");
3402         
3403         cbpy = get_vlc2(&s->gb, cbpy_vlc.table, CBPY_VLC_BITS, 1);
3404         if(cbpy<0) return -1;
3405         cbp = (cbpc & 3) | (cbpy << 2);
3406         if (dquant) {
3407             change_qscale(s, quant_tab[get_bits(&s->gb, 2)]);
3408         }
3409         
3410         if(!s->progressive_sequence)
3411             s->interlaced_dct= get_bits1(&s->gb);
3412
3413         /* decode each block */
3414         if (s->h263_pred) {
3415             for (i = 0; i < 6; i++) {
3416                 if (mpeg4_decode_block(s, block[i], i, cbp&32, 1) < 0)
3417                     return -1;
3418                 cbp+=cbp;
3419             }
3420         } else {
3421             for (i = 0; i < 6; i++) {
3422                 if (h263_decode_block(s, block[i], i, cbp&32) < 0)
3423                     return -1;
3424                 cbp+=cbp;
3425             }
3426         }
3427         goto end;
3428     }
3429
3430     /* decode each block */
3431     if (s->h263_pred) {
3432         for (i = 0; i < 6; i++) {
3433             if (mpeg4_decode_block(s, block[i], i, cbp&32, 0) < 0)
3434                 return -1;
3435             cbp+=cbp;
3436         }
3437     } else {
3438         for (i = 0; i < 6; i++) {
3439             if (h263_decode_block(s, block[i], i, cbp&32) < 0)
3440                 return -1;
3441             cbp+=cbp;
3442         }
3443     }
3444 end:
3445
3446         /* per-MB end of slice check */
3447     if(s->codec_id==CODEC_ID_MPEG4){
3448         if(mpeg4_is_resync(s)){
3449             if(s->pict_type==B_TYPE && s->next_picture.mbskip_table[s->mb_y * s->mb_width + s->mb_x+1])
3450                 return SLICE_OK;
3451             return SLICE_END;
3452         }
3453     }else{
3454         int v= show_bits(&s->gb, 16);
3455     
3456         if(get_bits_count(&s->gb) + 16 > s->gb.size_in_bits){
3457             v>>= get_bits_count(&s->gb) + 16 - s->gb.size_in_bits;
3458         }
3459
3460         if(v==0)
3461             return SLICE_END;
3462     }
3463
3464     return SLICE_OK;     
3465 }
3466
3467 static int h263_decode_motion(MpegEncContext * s, int pred, int f_code)
3468 {
3469     int code, val, sign, shift, l;
3470     code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
3471     if (code < 0)
3472         return 0xffff;
3473
3474     if (code == 0)
3475         return pred;
3476
3477     sign = get_bits1(&s->gb);
3478     shift = f_code - 1;
3479     val = (code - 1) << shift;
3480     if (shift > 0)
3481         val |= get_bits(&s->gb, shift);
3482     val++;
3483     if (sign)
3484         val = -val;
3485     val += pred;
3486
3487     /* modulo decoding */
3488     if (!s->h263_long_vectors) {
3489         l = 1 << (f_code + 4);
3490         if (val < -l) {
3491             val += l<<1;
3492         } else if (val >= l) {
3493             val -= l<<1;
3494         }
3495     } else {
3496         /* horrible h263 long vector mode */
3497         if (pred < -31 && val < -63)
3498             val += 64;
3499         if (pred > 32 && val > 63)
3500             val -= 64;
3501         
3502     }
3503     return val;
3504 }
3505
3506 /* Decodes RVLC of H.263+ UMV */
3507 static int h263p_decode_umotion(MpegEncContext * s, int pred)
3508 {
3509    int code = 0, sign;
3510    
3511    if (get_bits1(&s->gb)) /* Motion difference = 0 */
3512       return pred;
3513    
3514    code = 2 + get_bits1(&s->gb);
3515    
3516    while (get_bits1(&s->gb))
3517    {
3518       code <<= 1;
3519       code += get_bits1(&s->gb);
3520    }
3521    sign = code & 1;
3522    code >>= 1;
3523    
3524    code = (sign) ? (pred - code) : (pred + code);
3525 #ifdef DEBUG
3526    fprintf(stderr,"H.263+ UMV Motion = %d\n", code);
3527 #endif
3528    return code;   
3529
3530 }
3531
3532 static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
3533                              int n, int coded)
3534 {
3535     int code, level, i, j, last, run;
3536     RLTable *rl = &rl_inter;
3537     const uint8_t *scan_table;
3538
3539     scan_table = s->intra_scantable.permutated;
3540     if (s->h263_aic && s->mb_intra) {
3541         rl = &rl_intra_aic;
3542         i = 0;
3543         if (s->ac_pred) {
3544             if (s->h263_aic_dir) 
3545                 scan_table = s->intra_v_scantable.permutated; /* left */
3546             else
3547                 scan_table = s->intra_h_scantable.permutated; /* top */
3548         }
3549     } else if (s->mb_intra) {
3550         /* DC coef */
3551         if(s->h263_rv10){
3552           if (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           }
3569         }else{
3570             level = get_bits(&s->gb, 8);
3571             if((level&0x7F) == 0){
3572                 fprintf(stderr, "illegal dc %d at %d %d\n", level, s->mb_x, s->mb_y);
3573                 return -1;
3574             }
3575             if (level == 255)
3576                 level = 128;
3577         }
3578         block[0] = level;
3579         i = 1;
3580     } else {
3581         i = 0;
3582     }
3583     if (!coded) {
3584         if (s->mb_intra && s->h263_aic)
3585             goto not_coded;
3586         s->block_last_index[n] = i - 1;
3587         return 0;
3588     }
3589
3590     for(;;) {
3591         code = get_vlc2(&s->gb, rl->vlc.table, TEX_VLC_BITS, 2);
3592         if (code < 0){
3593             fprintf(stderr, "illegal ac vlc code at %dx%d\n", s->mb_x, s->mb_y);
3594             return -1;
3595         }
3596         if (code == rl->n) {
3597             /* escape */
3598             last = get_bits1(&s->gb);
3599             run = get_bits(&s->gb, 6);
3600             level = (int8_t)get_bits(&s->gb, 8);
3601             if(level == -128){
3602                 if (s->h263_rv10) {
3603                     /* XXX: should patch encoder too */
3604                     level = get_bits(&s->gb, 12);
3605                     level= (level + ((-1)<<11)) ^ ((-1)<<11); //sign extension
3606                 }else{
3607                     level = get_bits(&s->gb, 5);
3608                     level += get_bits(&s->gb, 6)<<5;
3609                     level= (level + ((-1)<<10)) ^ ((-1)<<10); //sign extension
3610                 }
3611             }
3612         } else {
3613             run = rl->table_run[code];
3614             level = rl->table_level[code];
3615             last = code >= rl->last;
3616             if (get_bits1(&s->gb))
3617                 level = -level;
3618         }
3619         i += run;
3620         if (i >= 64){
3621             fprintf(stderr, "run overflow at %dx%d\n", s->mb_x, s->mb_y);
3622             return -1;
3623         }
3624         j = scan_table[i];
3625         block[j] = level;
3626         if (last)
3627             break;
3628         i++;
3629     }
3630 not_coded:    
3631     if (s->mb_intra && s->h263_aic) {
3632         h263_pred_acdc(s, block, n);
3633         i = 63;
3634     }
3635     s->block_last_index[n] = i;
3636     return 0;
3637 }
3638
3639 /**
3640  * decodes the dc value.
3641  * @param n block index (0-3 are luma, 4-5 are chroma)
3642  * @param dir_ptr the prediction direction will be stored here
3643  * @return the quantized dc
3644  */
3645 static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr)
3646 {
3647     int level, pred, code;
3648     uint16_t *dc_val;
3649
3650     if (n < 4) 
3651         code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1);
3652     else 
3653         code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1);
3654     if (code < 0 || code > 9 /* && s->nbit<9 */){
3655         fprintf(stderr, "illegal dc vlc\n");
3656         return -1;
3657     }
3658     if (code == 0) {
3659         level = 0;
3660     } else {
3661         level = get_bits(&s->gb, code);
3662         if ((level >> (code - 1)) == 0) /* if MSB not set it is negative*/
3663             level = - (level ^ ((1 << code) - 1));
3664         if (code > 8){
3665             if(get_bits1(&s->gb)==0){ /* marker */
3666                 if(s->error_resilience>=2){
3667                     fprintf(stderr, "dc marker bit missing\n");
3668                     return -1;
3669                 }
3670             }
3671         }
3672     }
3673     pred = ff_mpeg4_pred_dc(s, n, &dc_val, dir_ptr);
3674     level += pred;
3675     if (level < 0){
3676         if(s->error_resilience>=3){
3677             fprintf(stderr, "dc<0 at %dx%d\n", s->mb_x, s->mb_y);
3678             return -1;
3679         }
3680         level = 0;
3681     }
3682     if (n < 4) {
3683         *dc_val = level * s->y_dc_scale;
3684     } else {
3685         *dc_val = level * s->c_dc_scale;
3686     }
3687     if(s->error_resilience>=3){
3688         if(*dc_val > 2048 + s->y_dc_scale + s->c_dc_scale){
3689             fprintf(stderr, "dc overflow at %dx%d\n", s->mb_x, s->mb_y);
3690             return -1;
3691         }
3692     }
3693     return level;
3694 }
3695
3696 /**
3697  * decodes a block.
3698  * @return <0 if an error occured
3699  */
3700 static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
3701                               int n, int coded, int intra)
3702 {
3703     int level, i, last, run;
3704     int dc_pred_dir;
3705     RLTable * rl;
3706     RL_VLC_ELEM * rl_vlc;
3707     const uint8_t * scan_table;
3708     int qmul, qadd;
3709
3710     if(intra) {
3711         /* DC coef */
3712         if(s->partitioned_frame){
3713             level = s->dc_val[0][ s->block_index[n] ];
3714             if(n<4) level= (level + (s->y_dc_scale>>1))/s->y_dc_scale; //FIXME optimizs
3715             else    level= (level + (s->c_dc_scale>>1))/s->c_dc_scale;
3716             dc_pred_dir= (s->pred_dir_table[s->mb_x + s->mb_y*s->mb_width]<<n)&32;
3717         }else{
3718             level = mpeg4_decode_dc(s, n, &dc_pred_dir);
3719             if (level < 0)
3720                 return -1;
3721         }
3722         block[0] = level;
3723         i = 0;
3724         if (!coded) 
3725             goto not_coded;
3726         rl = &rl_intra;
3727         rl_vlc = rl_intra.rl_vlc[0];
3728         if (s->ac_pred) {
3729             if (dc_pred_dir == 0) 
3730                 scan_table = s->intra_v_scantable.permutated; /* left */
3731             else
3732                 scan_table = s->intra_h_scantable.permutated; /* top */
3733         } else {
3734             scan_table = s->intra_scantable.permutated;
3735         }
3736         qmul=1;
3737         qadd=0;
3738     } else {
3739         i = -1;
3740         if (!coded) {
3741             s->block_last_index[n] = i;
3742             return 0;
3743         }
3744         rl = &rl_inter;
3745    
3746         scan_table = s->intra_scantable.permutated;
3747
3748         if(s->mpeg_quant){
3749             qmul=1;
3750             qadd=0;
3751             rl_vlc = rl_inter.rl_vlc[0];        
3752         }else{
3753             qmul = s->qscale << 1;
3754             qadd = (s->qscale - 1) | 1;
3755             rl_vlc = rl_inter.rl_vlc[s->qscale];
3756         }
3757     }
3758   {
3759     OPEN_READER(re, &s->gb);
3760     for(;;) {
3761         UPDATE_CACHE(re, &s->gb);
3762         GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
3763         if (level==0) {
3764             int cache;
3765             cache= GET_CACHE(re, &s->gb);
3766             /* escape */
3767             if (cache&0x80000000) {
3768                 if (cache&0x40000000) {
3769                     /* third escape */
3770                     SKIP_CACHE(re, &s->gb, 2);
3771                     last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);
3772                     run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);
3773                     SKIP_COUNTER(re, &s->gb, 2+1+6);
3774                     UPDATE_CACHE(re, &s->gb);
3775
3776                     if(SHOW_UBITS(re, &s->gb, 1)==0){
3777                         fprintf(stderr, "1. marker bit missing in 3. esc\n");
3778                         return -1;
3779                     }; SKIP_CACHE(re, &s->gb, 1);
3780                     
3781                     level= SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12);
3782  
3783                     if(SHOW_UBITS(re, &s->gb, 1)==0){
3784                         fprintf(stderr, "2. marker bit missing in 3. esc\n");
3785                         return -1;
3786                     }; LAST_SKIP_CACHE(re, &s->gb, 1);
3787                     
3788                     SKIP_COUNTER(re, &s->gb, 1+12+1);
3789                     
3790                     if(level*s->qscale>1024 || level*s->qscale<-1024){
3791                         fprintf(stderr, "|level| overflow in 3. esc, qp=%d\n", s->qscale);
3792                         return -1;
3793                     }
3794 #if 1 
3795                     {
3796                         const int abs_level= ABS(level);
3797                         if(abs_level<=MAX_LEVEL && run<=MAX_RUN && !(s->workaround_bugs&FF_BUG_AC_VLC)){
3798                             const int run1= run - rl->max_run[last][abs_level] - 1;
3799                             if(abs_level <= rl->max_level[last][run]){
3800                                 fprintf(stderr, "illegal 3. esc, vlc encoding possible\n");
3801                                 return -1;
3802                             }
3803                             if(s->error_resilience > FF_ER_COMPLIANT){
3804                                 if(abs_level <= rl->max_level[last][run]*2){
3805                                     fprintf(stderr, "illegal 3. esc, esc 1 encoding possible\n");
3806                                     return -1;
3807                                 }
3808                                 if(run1 >= 0 && abs_level <= rl->max_level[last][run1]){
3809                                     fprintf(stderr, "illegal 3. esc, esc 2 encoding possible\n");
3810                                     return -1;
3811                                 }
3812                             }
3813                         }
3814                     }
3815 #endif
3816                     if (level>0) level= level * qmul + qadd;
3817                     else         level= level * qmul - qadd;
3818
3819                     i+= run + 1;
3820                     if(last) i+=192;
3821                 } else {
3822                     /* second escape */
3823 #if MIN_CACHE_BITS < 20
3824                     LAST_SKIP_BITS(re, &s->gb, 2);
3825                     UPDATE_CACHE(re, &s->gb);
3826 #else
3827                     SKIP_BITS(re, &s->gb, 2);
3828 #endif
3829                     GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
3830                     i+= run + rl->max_run[run>>7][level/qmul] +1; //FIXME opt indexing
3831                     level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
3832                     LAST_SKIP_BITS(re, &s->gb, 1);
3833                 }
3834             } else {
3835                 /* first escape */
3836 #if MIN_CACHE_BITS < 19
3837                 LAST_SKIP_BITS(re, &s->gb, 1);
3838                 UPDATE_CACHE(re, &s->gb);
3839 #else
3840                 SKIP_BITS(re, &s->gb, 1);
3841 #endif
3842                 GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);
3843                 i+= run;
3844                 level = level + rl->max_level[run>>7][(run-1)&63] * qmul;//FIXME opt indexing
3845                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
3846                 LAST_SKIP_BITS(re, &s->gb, 1);
3847             }
3848         } else {
3849             i+= run;
3850             level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
3851             LAST_SKIP_BITS(re, &s->gb, 1);
3852         }
3853         if (i > 62){
3854             i-= 192;
3855             if(i&(~63)){
3856                 fprintf(stderr, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
3857                 return -1;
3858             }
3859
3860             block[scan_table[i]] = level;
3861             break;
3862         }
3863
3864         block[scan_table[i]] = level;
3865     }
3866     CLOSE_READER(re, &s->gb);
3867   }
3868  not_coded:
3869     if (s->mb_intra) {
3870         mpeg4_pred_ac(s, block, n, dc_pred_dir);
3871         if (s->ac_pred) {
3872             i = 63; /* XXX: not optimal */
3873         }
3874     }
3875     s->block_last_index[n] = i;
3876     return 0;
3877 }
3878
3879 /* most is hardcoded. should extend to handle all h263 streams */
3880 int h263_decode_picture_header(MpegEncContext *s)
3881 {
3882     int format, width, height;
3883
3884     /* picture start code */
3885     if (get_bits(&s->gb, 22) != 0x20) {
3886         fprintf(stderr, "Bad picture start code\n");
3887         return -1;
3888     }
3889     /* temporal reference */
3890     s->picture_number = get_bits(&s->gb, 8); /* picture timestamp */
3891
3892     /* PTYPE starts here */    
3893     if (get_bits1(&s->gb) != 1) {
3894         /* marker */
3895         fprintf(stderr, "Bad marker\n");
3896         return -1;
3897     }
3898     if (get_bits1(&s->gb) != 0) {
3899         fprintf(stderr, "Bad H263 id\n");
3900         return -1;      /* h263 id */
3901     }
3902     skip_bits1(&s->gb); /* split screen off */
3903     skip_bits1(&s->gb); /* camera  off */
3904     skip_bits1(&s->gb); /* freeze picture release off */
3905
3906     /* Reset GOB number */
3907     s->gob_number = 0;
3908         
3909     format = get_bits(&s->gb, 3);
3910     /*
3911         0    forbidden
3912         1    sub-QCIF
3913         10   QCIF
3914         7       extended PTYPE (PLUSPTYPE)
3915     */
3916
3917     if (format != 7 && format != 6) {
3918         s->h263_plus = 0;
3919         /* H.263v1 */
3920         width = h263_format[format][0];
3921         height = h263_format[format][1];
3922         if (!width)
3923             return -1;
3924         
3925         s->width = width;
3926         s->height = height;
3927         s->pict_type = I_TYPE + get_bits1(&s->gb);
3928
3929         s->unrestricted_mv = get_bits1(&s->gb); 
3930         s->h263_long_vectors = s->unrestricted_mv;
3931
3932         if (get_bits1(&s->gb) != 0) {
3933             fprintf(stderr, "H263 SAC not supported\n");
3934             return -1;  /* SAC: off */
3935         }
3936         if (get_bits1(&s->gb) != 0) {
3937             s->mv_type = MV_TYPE_8X8; /* Advanced prediction mode */
3938         }   
3939         
3940         if (get_bits1(&s->gb) != 0) {
3941             fprintf(stderr, "H263 PB frame not supported\n");
3942             return -1;  /* not PB frame */
3943         }
3944         s->qscale = get_bits(&s->gb, 5);
3945         skip_bits1(&s->gb);     /* Continuous Presence Multipoint mode: off */
3946     } else {
3947         int ufep;
3948         
3949         /* H.263v2 */
3950         s->h263_plus = 1;
3951         ufep = get_bits(&s->gb, 3); /* Update Full Extended PTYPE */
3952
3953         /* ufep other than 0 and 1 are reserved */        
3954         if (ufep == 1) {
3955             /* OPPTYPE */       
3956             format = get_bits(&s->gb, 3);
3957             dprintf("ufep=1, format: %d\n", format);
3958             skip_bits(&s->gb,1); /* Custom PCF */
3959             s->umvplus = get_bits(&s->gb, 1); /* Unrestricted Motion Vector */
3960             skip_bits1(&s->gb); /* Syntax-based Arithmetic Coding (SAC) */
3961             if (get_bits1(&s->gb) != 0) {
3962                 s->mv_type = MV_TYPE_8X8; /* Advanced prediction mode */
3963             }
3964             if (get_bits1(&s->gb) != 0) { /* Advanced Intra Coding (AIC) */
3965                 s->h263_aic = 1;
3966             }
3967             
3968             skip_bits(&s->gb, 7);
3969             /* these are the 7 bits: (in order of appearence  */
3970             /* Deblocking Filter */
3971             /* Slice Structured */
3972             /* Reference Picture Selection */
3973             /* Independent Segment Decoding */
3974             /* Alternative Inter VLC */
3975             /* Modified Quantization */
3976             /* Prevent start code emulation */
3977
3978             skip_bits(&s->gb, 3); /* Reserved */
3979         } else if (ufep != 0) {
3980             fprintf(stderr, "Bad UFEP type (%d)\n", ufep);
3981             return -1;
3982         }
3983             
3984         /* MPPTYPE */
3985         s->pict_type = get_bits(&s->gb, 3) + I_TYPE;
3986         dprintf("pict_type: %d\n", s->pict_type);
3987         if (s->pict_type != I_TYPE &&
3988             s->pict_type != P_TYPE)
3989             return -1;
3990         skip_bits(&s->gb, 2);
3991         s->no_rounding = get_bits1(&s->gb);
3992         dprintf("RTYPE: %d\n", s->no_rounding);
3993         skip_bits(&s->gb, 4);
3994         
3995         /* Get the picture dimensions */
3996         if (ufep) {
3997             if (format == 6) {
3998                 /* Custom Picture Format (CPFMT) */
3999                 s->aspect_ratio_info = get_bits(&s->gb, 4);
4000                 dprintf("aspect: %d\n", s->aspect_ratio_info);
4001                 /* aspect ratios:
4002                 0 - forbidden
4003                 1 - 1:1
4004                 2 - 12:11 (CIF 4:3)
4005                 3 - 10:11 (525-type 4:3)
4006                 4 - 16:11 (CIF 16:9)
4007                 5 - 40:33 (525-type 16:9)
4008                 6-14 - reserved
4009                 */
4010                 width = (get_bits(&s->gb, 9) + 1) * 4;
4011                 skip_bits1(&s->gb);
4012                 height = get_bits(&s->gb, 9) * 4;
4013                 dprintf("\nH.263+ Custom picture: %dx%d\n",width,height);
4014                 if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
4015                     /* aspected dimensions */
4016                     s->aspected_width = get_bits(&s->gb, 8);
4017                     s->aspected_height = get_bits(&s->gb, 8);
4018                 }else{
4019                     s->aspected_width = pixel_aspect[s->aspect_ratio_info][0];
4020                     s->aspected_height= pixel_aspect[s->aspect_ratio_info][1];
4021                 }
4022             } else {
4023                 width = h263_format[format][0];
4024                 height = h263_format[format][1];
4025             }
4026             if ((width == 0) || (height == 0))
4027                 return -1;
4028             s->width = width;
4029             s->height = height;
4030             if (s->umvplus) {
4031                 if(get_bits1(&s->gb)==0) /* Unlimited Unrestricted Motion Vectors Indicator (UUI) */
4032                     skip_bits1(&s->gb); 
4033             }
4034         }
4035             
4036         s->qscale = get_bits(&s->gb, 5);
4037     }
4038     /* PEI */
4039     while (get_bits1(&s->gb) != 0) {
4040         skip_bits(&s->gb, 8);
4041     }
4042     s->f_code = 1;
4043     
4044     if(s->h263_aic){
4045          s->y_dc_scale_table= 
4046          s->c_dc_scale_table= h263_aic_dc_scale_table;
4047     }else{
4048         s->y_dc_scale_table=
4049         s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
4050     }
4051
4052     return 0;
4053 }
4054
4055 static void mpeg4_decode_sprite_trajectory(MpegEncContext * s)
4056 {
4057     int i;
4058     int a= 2<<s->sprite_warping_accuracy;
4059     int rho= 3-s->sprite_warping_accuracy;
4060     int r=16/a;
4061     const int vop_ref[4][2]= {{0,0}, {s->width,0}, {0, s->height}, {s->width, s->height}}; // only true for rectangle shapes
4062     int d[4][2]={{0,0}, {0,0}, {0,0}, {0,0}};
4063     int sprite_ref[4][2];
4064     int virtual_ref[2][2];
4065     int w2, h2, w3, h3;
4066     int alpha=0, beta=0;
4067     int w= s->width;
4068     int h= s->height;
4069     int min_ab;
4070
4071     for(i=0; i<s->num_sprite_warping_points; i++){
4072         int length;
4073         int x=0, y=0;
4074
4075         length= get_vlc(&s->gb, &sprite_trajectory);
4076         if(length){
4077             x= get_bits(&s->gb, length);
4078
4079             if ((x >> (length - 1)) == 0) /* if MSB not set it is negative*/
4080                 x = - (x ^ ((1 << length) - 1));
4081         }
4082         if(!(s->divx_version==500 && s->divx_build==413)) skip_bits1(&s->gb); /* marker bit */
4083         
4084         length= get_vlc(&s->gb, &sprite_trajectory);
4085         if(length){
4086             y=get_bits(&s->gb, length);
4087
4088             if ((y >> (length - 1)) == 0) /* if MSB not set it is negative*/
4089                 y = - (y ^ ((1 << length) - 1));
4090         }
4091         skip_bits1(&s->gb); /* marker bit */
4092 //printf("%d %d %d %d\n", x, y, i, s->sprite_warping_accuracy);
4093         d[i][0]= x;
4094         d[i][1]= y;
4095     }
4096
4097     while((1<<alpha)<w) alpha++;
4098     while((1<<beta )<h) beta++; // there seems to be a typo in the mpeg4 std for the definition of w' and h'
4099     w2= 1<<alpha;
4100     h2= 1<<beta;
4101
4102 // Note, the 4th point isnt used for GMC
4103     if(s->divx_version==500 && s->divx_build==413){
4104         sprite_ref[0][0]= a*vop_ref[0][0] + d[0][0];
4105         sprite_ref[0][1]= a*vop_ref[0][1] + d[0][1];
4106         sprite_ref[1][0]= a*vop_ref[1][0] + d[0][0] + d[1][0];
4107         sprite_ref[1][1]= a*vop_ref[1][1] + d[0][1] + d[1][1];
4108         sprite_ref[2][0]= a*vop_ref[2][0] + d[0][0] + d[2][0];
4109         sprite_ref[2][1]= a*vop_ref[2][1] + d[0][1] + d[2][1];
4110     } else {
4111         sprite_ref[0][0]= (a>>1)*(2*vop_ref[0][0] + d[0][0]);
4112         sprite_ref[0][1]= (a>>1)*(2*vop_ref[0][1] + d[0][1]);
4113         sprite_ref[1][0]= (a>>1)*(2*vop_ref[1][0] + d[0][0] + d[1][0]);
4114         sprite_ref[1][1]= (a>>1)*(2*vop_ref[1][1] + d[0][1] + d[1][1]);
4115         sprite_ref[2][0]= (a>>1)*(2*vop_ref[2][0] + d[0][0] + d[2][0]);
4116         sprite_ref[2][1]= (a>>1)*(2*vop_ref[2][1] + d[0][1] + d[2][1]);
4117     }
4118 /*    sprite_ref[3][0]= (a>>1)*(2*vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);
4119     sprite_ref[3][1]= (a>>1)*(2*vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */
4120     
4121 // this is mostly identical to the mpeg4 std (and is totally unreadable because of that ...)
4122 // perhaps it should be reordered to be more readable ...
4123 // the idea behind this virtual_ref mess is to be able to use shifts later per pixel instead of divides
4124 // so the distance between points is converted from w&h based to w2&h2 based which are of the 2^x form
4125     virtual_ref[0][0]= 16*(vop_ref[0][0] + w2) 
4126         + 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);
4127     virtual_ref[0][1]= 16*vop_ref[0][1] 
4128         + 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);
4129     virtual_ref[1][0]= 16*vop_ref[0][0] 
4130         + 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);
4131     virtual_ref[1][1]= 16*(vop_ref[0][1] + h2) 
4132         + 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);
4133         
4134     switch(s->num_sprite_warping_points)
4135     {
4136         case 0:
4137             s->sprite_offset[0][0]= 0;
4138             s->sprite_offset[0][1]= 0;
4139             s->sprite_offset[1][0]= 0;
4140             s->sprite_offset[1][1]= 0;
4141             s->sprite_delta[0][0]= a;
4142             s->sprite_delta[0][1]= 0;
4143             s->sprite_delta[1][0]= 0;
4144             s->sprite_delta[1][1]= a;
4145             s->sprite_shift[0]= 0;
4146             s->sprite_shift[1]= 0;
4147             break;
4148         case 1: //GMC only
4149             s->sprite_offset[0][0]= sprite_ref[0][0] - a*vop_ref[0][0];
4150             s->sprite_offset[0][1]= sprite_ref[0][1] - a*vop_ref[0][1];
4151             s->sprite_offset[1][0]= ((sprite_ref[0][0]>>1)|(sprite_ref[0][0]&1)) - a*(vop_ref[0][0]/2);
4152             s->sprite_offset[1][1]= ((sprite_ref[0][1]>>1)|(sprite_ref[0][1]&1)) - a*(vop_ref[0][1]/2);
4153             s->sprite_delta[0][0]= a;
4154             s->sprite_delta[0][1]= 0;
4155             s->sprite_delta[1][0]= 0;
4156             s->sprite_delta[1][1]= a;
4157             s->sprite_shift[0]= 0;
4158             s->sprite_shift[1]= 0;