Merge remote-tracking branch 'qatar/master'
[ffmpeg.git] / libavcodec / mpeg4videodec.c
1 /*
2  * MPEG4 decoder.
3  * Copyright (c) 2000,2001 Fabrice Bellard
4  * Copyright (c) 2002-2010 Michael Niedermayer <michaelni@gmx.at>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include "mpegvideo.h"
24 #include "mpeg4video.h"
25 #include "h263.h"
26 #include "thread.h"
27
28 // The defines below define the number of bits that are read at once for
29 // reading vlc values. Changing these may improve speed and data cache needs
30 // be aware though that decreasing them may need the number of stages that is
31 // passed to get_vlc* to be increased.
32 #define SPRITE_TRAJ_VLC_BITS 6
33 #define DC_VLC_BITS 9
34 #define MB_TYPE_B_VLC_BITS 4
35
36
37 static VLC dc_lum, dc_chrom;
38 static VLC sprite_trajectory;
39 static VLC mb_type_b_vlc;
40
41 static const int mb_type_b_map[4]= {
42     MB_TYPE_DIRECT2 | MB_TYPE_L0L1,
43     MB_TYPE_L0L1 | MB_TYPE_16x16,
44     MB_TYPE_L1 | MB_TYPE_16x16,
45     MB_TYPE_L0 | MB_TYPE_16x16,
46 };
47
48 /**
49  * predicts the ac.
50  * @param n block index (0-3 are luma, 4-5 are chroma)
51  * @param dir the ac prediction direction
52  */
53 void mpeg4_pred_ac(MpegEncContext * s, DCTELEM *block, int n,
54                    int dir)
55 {
56     int i;
57     int16_t *ac_val, *ac_val1;
58     int8_t * const qscale_table = s->current_picture.f.qscale_table;
59
60     /* find prediction */
61     ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
62     ac_val1 = ac_val;
63     if (s->ac_pred) {
64         if (dir == 0) {
65             const int xy= s->mb_x-1 + s->mb_y*s->mb_stride;
66             /* left prediction */
67             ac_val -= 16;
68
69             if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
70                 /* same qscale */
71                 for(i=1;i<8;i++) {
72                     block[s->dsp.idct_permutation[i<<3]] += ac_val[i];
73                 }
74             }else{
75                 /* different qscale, we must rescale */
76                 for(i=1;i<8;i++) {
77                     block[s->dsp.idct_permutation[i<<3]] += ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale);
78                 }
79             }
80         } else {
81             const int xy= s->mb_x + s->mb_y*s->mb_stride - s->mb_stride;
82             /* top prediction */
83             ac_val -= 16 * s->block_wrap[n];
84
85             if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
86                 /* same qscale */
87                 for(i=1;i<8;i++) {
88                     block[s->dsp.idct_permutation[i]] += ac_val[i + 8];
89                 }
90             }else{
91                 /* different qscale, we must rescale */
92                 for(i=1;i<8;i++) {
93                     block[s->dsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale);
94                 }
95             }
96         }
97     }
98     /* left copy */
99     for(i=1;i<8;i++)
100         ac_val1[i    ] = block[s->dsp.idct_permutation[i<<3]];
101
102     /* top copy */
103     for(i=1;i<8;i++)
104         ac_val1[8 + i] = block[s->dsp.idct_permutation[i   ]];
105
106 }
107
108 /**
109  * check if the next stuff is a resync marker or the end.
110  * @return 0 if not
111  */
112 static inline int mpeg4_is_resync(MpegEncContext *s){
113     int bits_count= get_bits_count(&s->gb);
114     int v= show_bits(&s->gb, 16);
115
116     if(s->workaround_bugs&FF_BUG_NO_PADDING && !s->resync_marker){
117         return 0;
118     }
119
120     while(v<=0xFF){
121         if(s->pict_type==AV_PICTURE_TYPE_B || (v>>(8-s->pict_type)!=1) || s->partitioned_frame)
122             break;
123         skip_bits(&s->gb, 8+s->pict_type);
124         bits_count+= 8+s->pict_type;
125         v= show_bits(&s->gb, 16);
126     }
127
128     if(bits_count + 8 >= s->gb.size_in_bits){
129         v>>=8;
130         v|= 0x7F >> (7-(bits_count&7));
131
132         if(v==0x7F)
133             return s->mb_num;
134     }else{
135         if(v == ff_mpeg4_resync_prefix[bits_count&7]){
136             int len, mb_num;
137             int mb_num_bits= av_log2(s->mb_num - 1) + 1;
138             GetBitContext gb= s->gb;
139
140             skip_bits(&s->gb, 1);
141             align_get_bits(&s->gb);
142
143             for(len=0; len<32; len++){
144                 if(get_bits1(&s->gb)) break;
145             }
146
147             mb_num= get_bits(&s->gb, mb_num_bits);
148             if(!mb_num || mb_num > s->mb_num || get_bits_count(&s->gb)+6 > s->gb.size_in_bits)
149                 mb_num= -1;
150
151             s->gb= gb;
152
153             if(len>=ff_mpeg4_get_video_packet_prefix_length(s))
154                 return mb_num;
155         }
156     }
157     return 0;
158 }
159
160 static void mpeg4_decode_sprite_trajectory(MpegEncContext * s, GetBitContext *gb)
161 {
162     int i;
163     int a= 2<<s->sprite_warping_accuracy;
164     int rho= 3-s->sprite_warping_accuracy;
165     int r=16/a;
166     const int vop_ref[4][2]= {{0,0}, {s->width,0}, {0, s->height}, {s->width, s->height}}; // only true for rectangle shapes
167     int d[4][2]={{0,0}, {0,0}, {0,0}, {0,0}};
168     int sprite_ref[4][2];
169     int virtual_ref[2][2];
170     int w2, h2, w3, h3;
171     int alpha=0, beta=0;
172     int w= s->width;
173     int h= s->height;
174     int min_ab;
175
176     for(i=0; i<s->num_sprite_warping_points; i++){
177         int length;
178         int x=0, y=0;
179
180         length= get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3);
181         if(length){
182             x= get_xbits(gb, length);
183         }
184         if(!(s->divx_version==500 && s->divx_build==413)) skip_bits1(gb); /* marker bit */
185
186         length= get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3);
187         if(length){
188             y=get_xbits(gb, length);
189         }
190         skip_bits1(gb); /* marker bit */
191         s->sprite_traj[i][0]= d[i][0]= x;
192         s->sprite_traj[i][1]= d[i][1]= y;
193     }
194     for(; i<4; i++)
195         s->sprite_traj[i][0]= s->sprite_traj[i][1]= 0;
196
197     while((1<<alpha)<w) alpha++;
198     while((1<<beta )<h) beta++; // there seems to be a typo in the mpeg4 std for the definition of w' and h'
199     w2= 1<<alpha;
200     h2= 1<<beta;
201
202 // Note, the 4th point isn't used for GMC
203     if(s->divx_version==500 && s->divx_build==413){
204         sprite_ref[0][0]= a*vop_ref[0][0] + d[0][0];
205         sprite_ref[0][1]= a*vop_ref[0][1] + d[0][1];
206         sprite_ref[1][0]= a*vop_ref[1][0] + d[0][0] + d[1][0];
207         sprite_ref[1][1]= a*vop_ref[1][1] + d[0][1] + d[1][1];
208         sprite_ref[2][0]= a*vop_ref[2][0] + d[0][0] + d[2][0];
209         sprite_ref[2][1]= a*vop_ref[2][1] + d[0][1] + d[2][1];
210     } else {
211         sprite_ref[0][0]= (a>>1)*(2*vop_ref[0][0] + d[0][0]);
212         sprite_ref[0][1]= (a>>1)*(2*vop_ref[0][1] + d[0][1]);
213         sprite_ref[1][0]= (a>>1)*(2*vop_ref[1][0] + d[0][0] + d[1][0]);
214         sprite_ref[1][1]= (a>>1)*(2*vop_ref[1][1] + d[0][1] + d[1][1]);
215         sprite_ref[2][0]= (a>>1)*(2*vop_ref[2][0] + d[0][0] + d[2][0]);
216         sprite_ref[2][1]= (a>>1)*(2*vop_ref[2][1] + d[0][1] + d[2][1]);
217     }
218 /*    sprite_ref[3][0]= (a>>1)*(2*vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);
219     sprite_ref[3][1]= (a>>1)*(2*vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */
220
221 // this is mostly identical to the mpeg4 std (and is totally unreadable because of that ...)
222 // perhaps it should be reordered to be more readable ...
223 // the idea behind this virtual_ref mess is to be able to use shifts later per pixel instead of divides
224 // so the distance between points is converted from w&h based to w2&h2 based which are of the 2^x form
225     virtual_ref[0][0]= 16*(vop_ref[0][0] + w2)
226         + 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);
227     virtual_ref[0][1]= 16*vop_ref[0][1]
228         + 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);
229     virtual_ref[1][0]= 16*vop_ref[0][0]
230         + 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);
231     virtual_ref[1][1]= 16*(vop_ref[0][1] + h2)
232         + 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);
233
234     switch(s->num_sprite_warping_points)
235     {
236         case 0:
237             s->sprite_offset[0][0]= 0;
238             s->sprite_offset[0][1]= 0;
239             s->sprite_offset[1][0]= 0;
240             s->sprite_offset[1][1]= 0;
241             s->sprite_delta[0][0]= a;
242             s->sprite_delta[0][1]= 0;
243             s->sprite_delta[1][0]= 0;
244             s->sprite_delta[1][1]= a;
245             s->sprite_shift[0]= 0;
246             s->sprite_shift[1]= 0;
247             break;
248         case 1: //GMC only
249             s->sprite_offset[0][0]= sprite_ref[0][0] - a*vop_ref[0][0];
250             s->sprite_offset[0][1]= sprite_ref[0][1] - a*vop_ref[0][1];
251             s->sprite_offset[1][0]= ((sprite_ref[0][0]>>1)|(sprite_ref[0][0]&1)) - a*(vop_ref[0][0]/2);
252             s->sprite_offset[1][1]= ((sprite_ref[0][1]>>1)|(sprite_ref[0][1]&1)) - a*(vop_ref[0][1]/2);
253             s->sprite_delta[0][0]= a;
254             s->sprite_delta[0][1]= 0;
255             s->sprite_delta[1][0]= 0;
256             s->sprite_delta[1][1]= a;
257             s->sprite_shift[0]= 0;
258             s->sprite_shift[1]= 0;
259             break;
260         case 2:
261             s->sprite_offset[0][0]= (sprite_ref[0][0]<<(alpha+rho))
262                                                   + (-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][0])
263                                                   + ( r*sprite_ref[0][1] - virtual_ref[0][1])*(-vop_ref[0][1])
264                                                   + (1<<(alpha+rho-1));
265             s->sprite_offset[0][1]= (sprite_ref[0][1]<<(alpha+rho))
266                                                   + (-r*sprite_ref[0][1] + virtual_ref[0][1])*(-vop_ref[0][0])
267                                                   + (-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][1])
268                                                   + (1<<(alpha+rho-1));
269             s->sprite_offset[1][0]= ( (-r*sprite_ref[0][0] + virtual_ref[0][0])*(-2*vop_ref[0][0] + 1)
270                                      +( r*sprite_ref[0][1] - virtual_ref[0][1])*(-2*vop_ref[0][1] + 1)
271                                      +2*w2*r*sprite_ref[0][0]
272                                      - 16*w2
273                                      + (1<<(alpha+rho+1)));
274             s->sprite_offset[1][1]= ( (-r*sprite_ref[0][1] + virtual_ref[0][1])*(-2*vop_ref[0][0] + 1)
275                                      +(-r*sprite_ref[0][0] + virtual_ref[0][0])*(-2*vop_ref[0][1] + 1)
276                                      +2*w2*r*sprite_ref[0][1]
277                                      - 16*w2
278                                      + (1<<(alpha+rho+1)));
279             s->sprite_delta[0][0]=   (-r*sprite_ref[0][0] + virtual_ref[0][0]);
280             s->sprite_delta[0][1]=   (+r*sprite_ref[0][1] - virtual_ref[0][1]);
281             s->sprite_delta[1][0]=   (-r*sprite_ref[0][1] + virtual_ref[0][1]);
282             s->sprite_delta[1][1]=   (-r*sprite_ref[0][0] + virtual_ref[0][0]);
283
284             s->sprite_shift[0]= alpha+rho;
285             s->sprite_shift[1]= alpha+rho+2;
286             break;
287         case 3:
288             min_ab= FFMIN(alpha, beta);
289             w3= w2>>min_ab;
290             h3= h2>>min_ab;
291             s->sprite_offset[0][0]=  (sprite_ref[0][0]<<(alpha+beta+rho-min_ab))
292                                    + (-r*sprite_ref[0][0] + virtual_ref[0][0])*h3*(-vop_ref[0][0])
293                                    + (-r*sprite_ref[0][0] + virtual_ref[1][0])*w3*(-vop_ref[0][1])
294                                    + (1<<(alpha+beta+rho-min_ab-1));
295             s->sprite_offset[0][1]=  (sprite_ref[0][1]<<(alpha+beta+rho-min_ab))
296                                    + (-r*sprite_ref[0][1] + virtual_ref[0][1])*h3*(-vop_ref[0][0])
297                                    + (-r*sprite_ref[0][1] + virtual_ref[1][1])*w3*(-vop_ref[0][1])
298                                    + (1<<(alpha+beta+rho-min_ab-1));
299             s->sprite_offset[1][0]=  (-r*sprite_ref[0][0] + virtual_ref[0][0])*h3*(-2*vop_ref[0][0] + 1)
300                                    + (-r*sprite_ref[0][0] + virtual_ref[1][0])*w3*(-2*vop_ref[0][1] + 1)
301                                    + 2*w2*h3*r*sprite_ref[0][0]
302                                    - 16*w2*h3
303                                    + (1<<(alpha+beta+rho-min_ab+1));
304             s->sprite_offset[1][1]=  (-r*sprite_ref[0][1] + virtual_ref[0][1])*h3*(-2*vop_ref[0][0] + 1)
305                                    + (-r*sprite_ref[0][1] + virtual_ref[1][1])*w3*(-2*vop_ref[0][1] + 1)
306                                    + 2*w2*h3*r*sprite_ref[0][1]
307                                    - 16*w2*h3
308                                    + (1<<(alpha+beta+rho-min_ab+1));
309             s->sprite_delta[0][0]=   (-r*sprite_ref[0][0] + virtual_ref[0][0])*h3;
310             s->sprite_delta[0][1]=   (-r*sprite_ref[0][0] + virtual_ref[1][0])*w3;
311             s->sprite_delta[1][0]=   (-r*sprite_ref[0][1] + virtual_ref[0][1])*h3;
312             s->sprite_delta[1][1]=   (-r*sprite_ref[0][1] + virtual_ref[1][1])*w3;
313
314             s->sprite_shift[0]= alpha + beta + rho - min_ab;
315             s->sprite_shift[1]= alpha + beta + rho - min_ab + 2;
316             break;
317     }
318     /* try to simplify the situation */
319     if(   s->sprite_delta[0][0] == a<<s->sprite_shift[0]
320        && s->sprite_delta[0][1] == 0
321        && s->sprite_delta[1][0] == 0
322        && s->sprite_delta[1][1] == a<<s->sprite_shift[0])
323     {
324         s->sprite_offset[0][0]>>=s->sprite_shift[0];
325         s->sprite_offset[0][1]>>=s->sprite_shift[0];
326         s->sprite_offset[1][0]>>=s->sprite_shift[1];
327         s->sprite_offset[1][1]>>=s->sprite_shift[1];
328         s->sprite_delta[0][0]= a;
329         s->sprite_delta[0][1]= 0;
330         s->sprite_delta[1][0]= 0;
331         s->sprite_delta[1][1]= a;
332         s->sprite_shift[0]= 0;
333         s->sprite_shift[1]= 0;
334         s->real_sprite_warping_points=1;
335     }
336     else{
337         int shift_y= 16 - s->sprite_shift[0];
338         int shift_c= 16 - s->sprite_shift[1];
339         for(i=0; i<2; i++){
340             s->sprite_offset[0][i]<<= shift_y;
341             s->sprite_offset[1][i]<<= shift_c;
342             s->sprite_delta[0][i]<<= shift_y;
343             s->sprite_delta[1][i]<<= shift_y;
344             s->sprite_shift[i]= 16;
345         }
346         s->real_sprite_warping_points= s->num_sprite_warping_points;
347     }
348 }
349
350 /**
351  * decodes the next video packet.
352  * @return <0 if something went wrong
353  */
354 int mpeg4_decode_video_packet_header(MpegEncContext *s)
355 {
356     int mb_num_bits= av_log2(s->mb_num - 1) + 1;
357     int header_extension=0, mb_num, len;
358
359     /* is there enough space left for a video packet + header */
360     if( get_bits_count(&s->gb) > s->gb.size_in_bits-20) return -1;
361
362     for(len=0; len<32; len++){
363         if(get_bits1(&s->gb)) break;
364     }
365
366     if(len!=ff_mpeg4_get_video_packet_prefix_length(s)){
367         av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n");
368         return -1;
369     }
370
371     if(s->shape != RECT_SHAPE){
372         header_extension= get_bits1(&s->gb);
373         //FIXME more stuff here
374     }
375
376     mb_num= get_bits(&s->gb, mb_num_bits);
377     if(mb_num>=s->mb_num){
378         av_log(s->avctx, AV_LOG_ERROR, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
379         return -1;
380     }
381
382     s->mb_x= mb_num % s->mb_width;
383     s->mb_y= mb_num / s->mb_width;
384
385     if(s->shape != BIN_ONLY_SHAPE){
386         int qscale= get_bits(&s->gb, s->quant_precision);
387         if(qscale)
388             s->chroma_qscale=s->qscale= qscale;
389     }
390
391     if(s->shape == RECT_SHAPE){
392         header_extension= get_bits1(&s->gb);
393     }
394     if(header_extension){
395         int time_incr=0;
396
397         while (get_bits1(&s->gb) != 0)
398             time_incr++;
399
400         check_marker(&s->gb, "before time_increment in video packed header");
401         skip_bits(&s->gb, s->time_increment_bits); /* time_increment */
402         check_marker(&s->gb, "before vop_coding_type in video packed header");
403
404         skip_bits(&s->gb, 2); /* vop coding type */
405         //FIXME not rect stuff here
406
407         if(s->shape != BIN_ONLY_SHAPE){
408             skip_bits(&s->gb, 3); /* intra dc vlc threshold */
409 //FIXME don't just ignore everything
410             if(s->pict_type == AV_PICTURE_TYPE_S && s->vol_sprite_usage==GMC_SPRITE){
411                 mpeg4_decode_sprite_trajectory(s, &s->gb);
412                 av_log(s->avctx, AV_LOG_ERROR, "untested\n");
413             }
414
415             //FIXME reduced res stuff here
416
417             if (s->pict_type != AV_PICTURE_TYPE_I) {
418                 int f_code = get_bits(&s->gb, 3);       /* fcode_for */
419                 if(f_code==0){
420                     av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (f_code=0)\n");
421                 }
422             }
423             if (s->pict_type == AV_PICTURE_TYPE_B) {
424                 int b_code = get_bits(&s->gb, 3);
425                 if(b_code==0){
426                     av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (b_code=0)\n");
427                 }
428             }
429         }
430     }
431     //FIXME new-pred stuff
432
433     return 0;
434 }
435
436 /**
437  * gets the average motion vector for a GMC MB.
438  * @param n either 0 for the x component or 1 for y
439  * @return the average MV for a GMC MB
440  */
441 static inline int get_amv(MpegEncContext *s, int n){
442     int x, y, mb_v, sum, dx, dy, shift;
443     int len = 1 << (s->f_code + 4);
444     const int a= s->sprite_warping_accuracy;
445
446     if(s->workaround_bugs & FF_BUG_AMV)
447         len >>= s->quarter_sample;
448
449     if(s->real_sprite_warping_points==1){
450         if(s->divx_version==500 && s->divx_build==413)
451             sum= s->sprite_offset[0][n] / (1<<(a - s->quarter_sample));
452         else
453             sum= RSHIFT(s->sprite_offset[0][n]<<s->quarter_sample, a);
454     }else{
455         dx= s->sprite_delta[n][0];
456         dy= s->sprite_delta[n][1];
457         shift= s->sprite_shift[0];
458         if(n) dy -= 1<<(shift + a + 1);
459         else  dx -= 1<<(shift + a + 1);
460         mb_v= s->sprite_offset[0][n] + dx*s->mb_x*16 + dy*s->mb_y*16;
461
462         sum=0;
463         for(y=0; y<16; y++){
464             int v;
465
466             v= mb_v + dy*y;
467             //XXX FIXME optimize
468             for(x=0; x<16; x++){
469                 sum+= v>>shift;
470                 v+= dx;
471             }
472         }
473         sum= RSHIFT(sum, a+8-s->quarter_sample);
474     }
475
476     if      (sum < -len) sum= -len;
477     else if (sum >= len) sum= len-1;
478
479     return sum;
480 }
481
482 /**
483  * decodes the dc value.
484  * @param n block index (0-3 are luma, 4-5 are chroma)
485  * @param dir_ptr the prediction direction will be stored here
486  * @return the quantized dc
487  */
488 static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr)
489 {
490     int level, code;
491
492     if (n < 4)
493         code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1);
494     else
495         code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1);
496     if (code < 0 || code > 9 /* && s->nbit<9 */){
497         av_log(s->avctx, AV_LOG_ERROR, "illegal dc vlc\n");
498         return -1;
499     }
500     if (code == 0) {
501         level = 0;
502     } else {
503         if(IS_3IV1){
504             if(code==1)
505                 level= 2*get_bits1(&s->gb)-1;
506             else{
507                 if(get_bits1(&s->gb))
508                     level = get_bits(&s->gb, code-1) + (1<<(code-1));
509                 else
510                     level = -get_bits(&s->gb, code-1) - (1<<(code-1));
511             }
512         }else{
513             level = get_xbits(&s->gb, code);
514         }
515
516         if (code > 8){
517             if(get_bits1(&s->gb)==0){ /* marker */
518                 if(s->error_recognition>=2){
519                     av_log(s->avctx, AV_LOG_ERROR, "dc marker bit missing\n");
520                     return -1;
521                 }
522             }
523         }
524     }
525
526     return ff_mpeg4_pred_dc(s, n, level, dir_ptr, 0);
527 }
528
529 /**
530  * decodes first partition.
531  * @return number of MBs decoded or <0 if an error occurred
532  */
533 static int mpeg4_decode_partition_a(MpegEncContext *s){
534     int mb_num;
535     static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
536
537     /* decode first partition */
538     mb_num=0;
539     s->first_slice_line=1;
540     for(; s->mb_y<s->mb_height; s->mb_y++){
541         ff_init_block_index(s);
542         for(; s->mb_x<s->mb_width; s->mb_x++){
543             const int xy= s->mb_x + s->mb_y*s->mb_stride;
544             int cbpc;
545             int dir=0;
546
547             mb_num++;
548             ff_update_block_index(s);
549             if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
550                 s->first_slice_line=0;
551
552             if(s->pict_type==AV_PICTURE_TYPE_I){
553                 int i;
554
555                 do{
556                     if(show_bits_long(&s->gb, 19)==DC_MARKER){
557                         return mb_num-1;
558                     }
559
560                     cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
561                     if (cbpc < 0){
562                         av_log(s->avctx, AV_LOG_ERROR, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
563                         return -1;
564                     }
565                 }while(cbpc == 8);
566
567                 s->cbp_table[xy]= cbpc & 3;
568                 s->current_picture.f.mb_type[xy] = MB_TYPE_INTRA;
569                 s->mb_intra = 1;
570
571                 if(cbpc & 4) {
572                     ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
573                 }
574                 s->current_picture.f.qscale_table[xy]= s->qscale;
575
576                 s->mbintra_table[xy]= 1;
577                 for(i=0; i<6; i++){
578                     int dc_pred_dir;
579                     int dc= mpeg4_decode_dc(s, i, &dc_pred_dir);
580                     if(dc < 0){
581                         av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
582                         return -1;
583                     }
584                     dir<<=1;
585                     if(dc_pred_dir) dir|=1;
586                 }
587                 s->pred_dir_table[xy]= dir;
588             }else{ /* P/S_TYPE */
589                 int mx, my, pred_x, pred_y, bits;
590                 int16_t * const mot_val = s->current_picture.f.motion_val[0][s->block_index[0]];
591                 const int stride= s->b8_stride*2;
592
593 try_again:
594                 bits= show_bits(&s->gb, 17);
595                 if(bits==MOTION_MARKER){
596                     return mb_num-1;
597                 }
598                 skip_bits1(&s->gb);
599                 if(bits&0x10000){
600                     /* skip mb */
601                     if(s->pict_type==AV_PICTURE_TYPE_S && s->vol_sprite_usage==GMC_SPRITE){
602                         s->current_picture.f.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0;
603                         mx= get_amv(s, 0);
604                         my= get_amv(s, 1);
605                     }else{
606                         s->current_picture.f.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
607                         mx=my=0;
608                     }
609                     mot_val[0       ]= mot_val[2       ]=
610                     mot_val[0+stride]= mot_val[2+stride]= mx;
611                     mot_val[1       ]= mot_val[3       ]=
612                     mot_val[1+stride]= mot_val[3+stride]= my;
613
614                     if(s->mbintra_table[xy])
615                         ff_clean_intra_table_entries(s);
616                     continue;
617                 }
618
619                 cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
620                 if (cbpc < 0){
621                     av_log(s->avctx, AV_LOG_ERROR, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
622                     return -1;
623                 }
624                 if(cbpc == 20)
625                     goto try_again;
626
627                 s->cbp_table[xy]= cbpc&(8+3); //8 is dquant
628
629                 s->mb_intra = ((cbpc & 4) != 0);
630
631                 if(s->mb_intra){
632                     s->current_picture.f.mb_type[xy] = MB_TYPE_INTRA;
633                     s->mbintra_table[xy]= 1;
634                     mot_val[0       ]= mot_val[2       ]=
635                     mot_val[0+stride]= mot_val[2+stride]= 0;
636                     mot_val[1       ]= mot_val[3       ]=
637                     mot_val[1+stride]= mot_val[3+stride]= 0;
638                 }else{
639                     if(s->mbintra_table[xy])
640                         ff_clean_intra_table_entries(s);
641
642                     if(s->pict_type==AV_PICTURE_TYPE_S && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
643                         s->mcsel= get_bits1(&s->gb);
644                     else s->mcsel= 0;
645
646                     if ((cbpc & 16) == 0) {
647                         /* 16x16 motion prediction */
648
649                         h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
650                         if(!s->mcsel){
651                             mx = h263_decode_motion(s, pred_x, s->f_code);
652                             if (mx >= 0xffff)
653                                 return -1;
654
655                             my = h263_decode_motion(s, pred_y, s->f_code);
656                             if (my >= 0xffff)
657                                 return -1;
658                             s->current_picture.f.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0;
659                         } else {
660                             mx = get_amv(s, 0);
661                             my = get_amv(s, 1);
662                             s->current_picture.f.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0;
663                         }
664
665                         mot_val[0       ]= mot_val[2       ] =
666                         mot_val[0+stride]= mot_val[2+stride]= mx;
667                         mot_val[1       ]= mot_val[3       ]=
668                         mot_val[1+stride]= mot_val[3+stride]= my;
669                     } else {
670                         int i;
671                         s->current_picture.f.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0;
672                         for(i=0;i<4;i++) {
673                             int16_t *mot_val= h263_pred_motion(s, i, 0, &pred_x, &pred_y);
674                             mx = h263_decode_motion(s, pred_x, s->f_code);
675                             if (mx >= 0xffff)
676                                 return -1;
677
678                             my = h263_decode_motion(s, pred_y, s->f_code);
679                             if (my >= 0xffff)
680                                 return -1;
681                             mot_val[0] = mx;
682                             mot_val[1] = my;
683                         }
684                     }
685                 }
686             }
687         }
688         s->mb_x= 0;
689     }
690
691     return mb_num;
692 }
693
694 /**
695  * decode second partition.
696  * @return <0 if an error occurred
697  */
698 static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count){
699     int mb_num=0;
700     static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
701
702     s->mb_x= s->resync_mb_x;
703     s->first_slice_line=1;
704     for(s->mb_y= s->resync_mb_y; mb_num < mb_count; s->mb_y++){
705         ff_init_block_index(s);
706         for(; mb_num < mb_count && s->mb_x<s->mb_width; s->mb_x++){
707             const int xy= s->mb_x + s->mb_y*s->mb_stride;
708
709             mb_num++;
710             ff_update_block_index(s);
711             if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
712                 s->first_slice_line=0;
713
714             if(s->pict_type==AV_PICTURE_TYPE_I){
715                 int ac_pred= get_bits1(&s->gb);
716                 int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
717                 if(cbpy<0){
718                     av_log(s->avctx, AV_LOG_ERROR, "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
719                     return -1;
720                 }
721
722                 s->cbp_table[xy]|= cbpy<<2;
723                 s->current_picture.f.mb_type[xy] |= ac_pred*MB_TYPE_ACPRED;
724             }else{ /* P || S_TYPE */
725                 if (IS_INTRA(s->current_picture.f.mb_type[xy])) {
726                     int dir=0,i;
727                     int ac_pred = get_bits1(&s->gb);
728                     int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
729
730                     if(cbpy<0){
731                         av_log(s->avctx, AV_LOG_ERROR, "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
732                         return -1;
733                     }
734
735                     if(s->cbp_table[xy] & 8) {
736                         ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
737                     }
738                     s->current_picture.f.qscale_table[xy] = s->qscale;
739
740                     for(i=0; i<6; i++){
741                         int dc_pred_dir;
742                         int dc= mpeg4_decode_dc(s, i, &dc_pred_dir);
743                         if(dc < 0){
744                             av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
745                             return -1;
746                         }
747                         dir<<=1;
748                         if(dc_pred_dir) dir|=1;
749                     }
750                     s->cbp_table[xy]&= 3; //remove dquant
751                     s->cbp_table[xy]|= cbpy<<2;
752                     s->current_picture.f.mb_type[xy] |= ac_pred*MB_TYPE_ACPRED;
753                     s->pred_dir_table[xy]= dir;
754                 } else if (IS_SKIP(s->current_picture.f.mb_type[xy])) {
755                     s->current_picture.f.qscale_table[xy] = s->qscale;
756                     s->cbp_table[xy]= 0;
757                 }else{
758                     int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
759
760                     if(cbpy<0){
761                         av_log(s->avctx, AV_LOG_ERROR, "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
762                         return -1;
763                     }
764
765                     if(s->cbp_table[xy] & 8) {
766                         ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
767                     }
768                     s->current_picture.f.qscale_table[xy] = s->qscale;
769
770                     s->cbp_table[xy]&= 3; //remove dquant
771                     s->cbp_table[xy]|= (cbpy^0xf)<<2;
772                 }
773             }
774         }
775         if(mb_num >= mb_count) return 0;
776         s->mb_x= 0;
777     }
778     return 0;
779 }
780
781 /**
782  * decodes the first & second partition
783  * @return <0 if error (and sets error type in the error_status_table)
784  */
785 int ff_mpeg4_decode_partitions(MpegEncContext *s)
786 {
787     int mb_num;
788     const int part_a_error= s->pict_type==AV_PICTURE_TYPE_I ? (DC_ERROR|MV_ERROR) : MV_ERROR;
789     const int part_a_end  = s->pict_type==AV_PICTURE_TYPE_I ? (DC_END  |MV_END)   : MV_END;
790
791     mb_num= mpeg4_decode_partition_a(s);
792     if(mb_num<0){
793         ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error);
794         return -1;
795     }
796
797     if(s->resync_mb_x + s->resync_mb_y*s->mb_width + mb_num > s->mb_num){
798         av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n");
799         ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error);
800         return -1;
801     }
802
803     s->mb_num_left= mb_num;
804
805     if(s->pict_type==AV_PICTURE_TYPE_I){
806         while(show_bits(&s->gb, 9) == 1)
807             skip_bits(&s->gb, 9);
808         if(get_bits_long(&s->gb, 19)!=DC_MARKER){
809             av_log(s->avctx, AV_LOG_ERROR, "marker missing after first I partition at %d %d\n", s->mb_x, s->mb_y);
810             return -1;
811         }
812     }else{
813         while(show_bits(&s->gb, 10) == 1)
814             skip_bits(&s->gb, 10);
815         if(get_bits(&s->gb, 17)!=MOTION_MARKER){
816             av_log(s->avctx, AV_LOG_ERROR, "marker missing after first P partition at %d %d\n", s->mb_x, s->mb_y);
817             return -1;
818         }
819     }
820     ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, part_a_end);
821
822     if( mpeg4_decode_partition_b(s, mb_num) < 0){
823         if(s->pict_type==AV_PICTURE_TYPE_P)
824             ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, DC_ERROR);
825         return -1;
826     }else{
827         if(s->pict_type==AV_PICTURE_TYPE_P)
828             ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, DC_END);
829     }
830
831     return 0;
832 }
833
834 /**
835  * decodes a block.
836  * @return <0 if an error occurred
837  */
838 static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
839                               int n, int coded, int intra, int rvlc)
840 {
841     int level, i, last, run;
842     int dc_pred_dir;
843     RLTable * rl;
844     RL_VLC_ELEM * rl_vlc;
845     const uint8_t * scan_table;
846     int qmul, qadd;
847
848     //Note intra & rvlc should be optimized away if this is inlined
849
850     if(intra) {
851       if(s->use_intra_dc_vlc){
852         /* DC coef */
853         if(s->partitioned_frame){
854             level = s->dc_val[0][ s->block_index[n] ];
855             if(n<4) level= FASTDIV((level + (s->y_dc_scale>>1)), s->y_dc_scale);
856             else    level= FASTDIV((level + (s->c_dc_scale>>1)), s->c_dc_scale);
857             dc_pred_dir= (s->pred_dir_table[s->mb_x + s->mb_y*s->mb_stride]<<n)&32;
858         }else{
859             level = mpeg4_decode_dc(s, n, &dc_pred_dir);
860             if (level < 0)
861                 return -1;
862         }
863         block[0] = level;
864         i = 0;
865       }else{
866             i = -1;
867             ff_mpeg4_pred_dc(s, n, 0, &dc_pred_dir, 0);
868       }
869       if (!coded)
870           goto not_coded;
871
872       if(rvlc){
873           rl = &rvlc_rl_intra;
874           rl_vlc = rvlc_rl_intra.rl_vlc[0];
875       }else{
876           rl = &ff_mpeg4_rl_intra;
877           rl_vlc = ff_mpeg4_rl_intra.rl_vlc[0];
878       }
879       if (s->ac_pred) {
880           if (dc_pred_dir == 0)
881               scan_table = s->intra_v_scantable.permutated; /* left */
882           else
883               scan_table = s->intra_h_scantable.permutated; /* top */
884       } else {
885             scan_table = s->intra_scantable.permutated;
886       }
887       qmul=1;
888       qadd=0;
889     } else {
890         i = -1;
891         if (!coded) {
892             s->block_last_index[n] = i;
893             return 0;
894         }
895         if(rvlc) rl = &rvlc_rl_inter;
896         else     rl = &ff_h263_rl_inter;
897
898         scan_table = s->intra_scantable.permutated;
899
900         if(s->mpeg_quant){
901             qmul=1;
902             qadd=0;
903             if(rvlc){
904                 rl_vlc = rvlc_rl_inter.rl_vlc[0];
905             }else{
906                 rl_vlc = ff_h263_rl_inter.rl_vlc[0];
907             }
908         }else{
909             qmul = s->qscale << 1;
910             qadd = (s->qscale - 1) | 1;
911             if(rvlc){
912                 rl_vlc = rvlc_rl_inter.rl_vlc[s->qscale];
913             }else{
914                 rl_vlc = ff_h263_rl_inter.rl_vlc[s->qscale];
915             }
916         }
917     }
918   {
919     OPEN_READER(re, &s->gb);
920     for(;;) {
921         UPDATE_CACHE(re, &s->gb);
922         GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 0);
923         if (level==0) {
924           /* escape */
925           if(rvlc){
926                 if(SHOW_UBITS(re, &s->gb, 1)==0){
927                     av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in rvlc esc\n");
928                     return -1;
929                 }; SKIP_CACHE(re, &s->gb, 1);
930
931                 last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);
932                 run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);
933                 SKIP_COUNTER(re, &s->gb, 1+1+6);
934                 UPDATE_CACHE(re, &s->gb);
935
936                 if(SHOW_UBITS(re, &s->gb, 1)==0){
937                     av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in rvlc esc\n");
938                     return -1;
939                 }; SKIP_CACHE(re, &s->gb, 1);
940
941                 level= SHOW_UBITS(re, &s->gb, 11); SKIP_CACHE(re, &s->gb, 11);
942
943                 if(SHOW_UBITS(re, &s->gb, 5)!=0x10){
944                     av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n");
945                     return -1;
946                 }; SKIP_CACHE(re, &s->gb, 5);
947
948                 level=  level * qmul + qadd;
949                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_CACHE(re, &s->gb, 1);
950                 SKIP_COUNTER(re, &s->gb, 1+11+5+1);
951
952                 i+= run + 1;
953                 if(last) i+=192;
954           }else{
955             int cache;
956             cache= GET_CACHE(re, &s->gb);
957
958             if(IS_3IV1)
959                 cache ^= 0xC0000000;
960
961             if (cache&0x80000000) {
962                 if (cache&0x40000000) {
963                     /* third escape */
964                     SKIP_CACHE(re, &s->gb, 2);
965                     last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);
966                     run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);
967                     SKIP_COUNTER(re, &s->gb, 2+1+6);
968                     UPDATE_CACHE(re, &s->gb);
969
970                     if(IS_3IV1){
971                         level= SHOW_SBITS(re, &s->gb, 12); LAST_SKIP_BITS(re, &s->gb, 12);
972                     }else{
973                         if(SHOW_UBITS(re, &s->gb, 1)==0){
974                             av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in 3. esc\n");
975                             return -1;
976                         }; SKIP_CACHE(re, &s->gb, 1);
977
978                         level= SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12);
979
980                         if(SHOW_UBITS(re, &s->gb, 1)==0){
981                             av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in 3. esc\n");
982                             return -1;
983                         }; LAST_SKIP_CACHE(re, &s->gb, 1);
984
985                         SKIP_COUNTER(re, &s->gb, 1+12+1);
986                     }
987
988 #if 0
989                     if(s->error_recognition >= FF_ER_COMPLIANT){
990                         const int abs_level= FFABS(level);
991                         if(abs_level<=MAX_LEVEL && run<=MAX_RUN){
992                             const int run1= run - rl->max_run[last][abs_level] - 1;
993                             if(abs_level <= rl->max_level[last][run]){
994                                 av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n");
995                                 return -1;
996                             }
997                             if(s->error_recognition > FF_ER_COMPLIANT){
998                                 if(abs_level <= rl->max_level[last][run]*2){
999                                     av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 1 encoding possible\n");
1000                                     return -1;
1001                                 }
1002                                 if(run1 >= 0 && abs_level <= rl->max_level[last][run1]){
1003                                     av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 2 encoding possible\n");
1004                                     return -1;
1005                                 }
1006                             }
1007                         }
1008                     }
1009 #endif
1010                     if (level>0) level= level * qmul + qadd;
1011                     else         level= level * qmul - qadd;
1012
1013                     if((unsigned)(level + 2048) > 4095){
1014                         if(s->error_recognition > FF_ER_COMPLIANT){
1015                             if(level > 2560 || level<-2560){
1016                                 av_log(s->avctx, AV_LOG_ERROR, "|level| overflow in 3. esc, qp=%d\n", s->qscale);
1017                                 return -1;
1018                             }
1019                         }
1020                         level= level<0 ? -2048 : 2047;
1021                     }
1022
1023                     i+= run + 1;
1024                     if(last) i+=192;
1025                 } else {
1026                     /* second escape */
1027                     SKIP_BITS(re, &s->gb, 2);
1028                     GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
1029                     i+= run + rl->max_run[run>>7][level/qmul] +1; //FIXME opt indexing
1030                     level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1031                     LAST_SKIP_BITS(re, &s->gb, 1);
1032                 }
1033             } else {
1034                 /* first escape */
1035                 SKIP_BITS(re, &s->gb, 1);
1036                 GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
1037                 i+= run;
1038                 level = level + rl->max_level[run>>7][(run-1)&63] * qmul;//FIXME opt indexing
1039                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1040                 LAST_SKIP_BITS(re, &s->gb, 1);
1041             }
1042           }
1043         } else {
1044             i+= run;
1045             level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1046             LAST_SKIP_BITS(re, &s->gb, 1);
1047         }
1048         if (i > 62){
1049             i-= 192;
1050             if(i&(~63)){
1051                 av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1052                 return -1;
1053             }
1054
1055             block[scan_table[i]] = level;
1056             break;
1057         }
1058
1059         block[scan_table[i]] = level;
1060     }
1061     CLOSE_READER(re, &s->gb);
1062   }
1063  not_coded:
1064     if (intra) {
1065         if(!s->use_intra_dc_vlc){
1066             block[0] = ff_mpeg4_pred_dc(s, n, block[0], &dc_pred_dir, 0);
1067
1068             i -= i>>31; //if(i == -1) i=0;
1069         }
1070
1071         mpeg4_pred_ac(s, block, n, dc_pred_dir);
1072         if (s->ac_pred) {
1073             i = 63; /* XXX: not optimal */
1074         }
1075     }
1076     s->block_last_index[n] = i;
1077     return 0;
1078 }
1079
1080 /**
1081  * decode partition C of one MB.
1082  * @return <0 if an error occurred
1083  */
1084 static int mpeg4_decode_partitioned_mb(MpegEncContext *s, DCTELEM block[6][64])
1085 {
1086     int cbp, mb_type;
1087     const int xy= s->mb_x + s->mb_y*s->mb_stride;
1088
1089     mb_type = s->current_picture.f.mb_type[xy];
1090     cbp = s->cbp_table[xy];
1091
1092     s->use_intra_dc_vlc= s->qscale < s->intra_dc_threshold;
1093
1094     if (s->current_picture.f.qscale_table[xy] != s->qscale) {
1095         ff_set_qscale(s, s->current_picture.f.qscale_table[xy]);
1096     }
1097
1098     if (s->pict_type == AV_PICTURE_TYPE_P || s->pict_type==AV_PICTURE_TYPE_S) {
1099         int i;
1100         for(i=0; i<4; i++){
1101             s->mv[0][i][0] = s->current_picture.f.motion_val[0][s->block_index[i]][0];
1102             s->mv[0][i][1] = s->current_picture.f.motion_val[0][s->block_index[i]][1];
1103         }
1104         s->mb_intra = IS_INTRA(mb_type);
1105
1106         if (IS_SKIP(mb_type)) {
1107             /* skip mb */
1108             for(i=0;i<6;i++)
1109                 s->block_last_index[i] = -1;
1110             s->mv_dir = MV_DIR_FORWARD;
1111             s->mv_type = MV_TYPE_16X16;
1112             if(s->pict_type==AV_PICTURE_TYPE_S && s->vol_sprite_usage==GMC_SPRITE){
1113                 s->mcsel=1;
1114                 s->mb_skipped = 0;
1115             }else{
1116                 s->mcsel=0;
1117                 s->mb_skipped = 1;
1118             }
1119         }else if(s->mb_intra){
1120             s->ac_pred = IS_ACPRED(s->current_picture.f.mb_type[xy]);
1121         }else if(!s->mb_intra){
1122 //            s->mcsel= 0; //FIXME do we need to init that
1123
1124             s->mv_dir = MV_DIR_FORWARD;
1125             if (IS_8X8(mb_type)) {
1126                 s->mv_type = MV_TYPE_8X8;
1127             } else {
1128                 s->mv_type = MV_TYPE_16X16;
1129             }
1130         }
1131     } else { /* I-Frame */
1132         s->mb_intra = 1;
1133         s->ac_pred = IS_ACPRED(s->current_picture.f.mb_type[xy]);
1134     }
1135
1136     if (!IS_SKIP(mb_type)) {
1137         int i;
1138         s->dsp.clear_blocks(s->block[0]);
1139         /* decode each block */
1140         for (i = 0; i < 6; i++) {
1141             if(mpeg4_decode_block(s, block[i], i, cbp&32, s->mb_intra, s->rvlc) < 0){
1142                 av_log(s->avctx, AV_LOG_ERROR, "texture corrupted at %d %d %d\n", s->mb_x, s->mb_y, s->mb_intra);
1143                 return -1;
1144             }
1145             cbp+=cbp;
1146         }
1147     }
1148
1149     /* per-MB end of slice check */
1150
1151     if(--s->mb_num_left <= 0){
1152         if(mpeg4_is_resync(s))
1153             return SLICE_END;
1154         else
1155             return SLICE_NOEND;
1156     }else{
1157         if(mpeg4_is_resync(s)){
1158             const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
1159             if(s->cbp_table[xy+delta])
1160                 return SLICE_END;
1161         }
1162         return SLICE_OK;
1163     }
1164 }
1165
1166 static int mpeg4_decode_mb(MpegEncContext *s,
1167                       DCTELEM block[6][64])
1168 {
1169     int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
1170     int16_t *mot_val;
1171     static int8_t quant_tab[4] = { -1, -2, 1, 2 };
1172     const int xy= s->mb_x + s->mb_y * s->mb_stride;
1173
1174     assert(s->h263_pred);
1175
1176     if (s->pict_type == AV_PICTURE_TYPE_P || s->pict_type==AV_PICTURE_TYPE_S) {
1177         do{
1178             if (get_bits1(&s->gb)) {
1179                 /* skip mb */
1180                 s->mb_intra = 0;
1181                 for(i=0;i<6;i++)
1182                     s->block_last_index[i] = -1;
1183                 s->mv_dir = MV_DIR_FORWARD;
1184                 s->mv_type = MV_TYPE_16X16;
1185                 if(s->pict_type==AV_PICTURE_TYPE_S && s->vol_sprite_usage==GMC_SPRITE){
1186                     s->current_picture.f.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0;
1187                     s->mcsel=1;
1188                     s->mv[0][0][0]= get_amv(s, 0);
1189                     s->mv[0][0][1]= get_amv(s, 1);
1190
1191                     s->mb_skipped = 0;
1192                 }else{
1193                     s->current_picture.f.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
1194                     s->mcsel=0;
1195                     s->mv[0][0][0] = 0;
1196                     s->mv[0][0][1] = 0;
1197                     s->mb_skipped = 1;
1198                 }
1199                 goto end;
1200             }
1201             cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
1202             if (cbpc < 0){
1203                 av_log(s->avctx, AV_LOG_ERROR, "cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
1204                 return -1;
1205             }
1206         }while(cbpc == 20);
1207
1208         s->dsp.clear_blocks(s->block[0]);
1209         dquant = cbpc & 8;
1210         s->mb_intra = ((cbpc & 4) != 0);
1211         if (s->mb_intra) goto intra;
1212
1213         if(s->pict_type==AV_PICTURE_TYPE_S && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
1214             s->mcsel= get_bits1(&s->gb);
1215         else s->mcsel= 0;
1216         cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1) ^ 0x0F;
1217
1218         cbp = (cbpc & 3) | (cbpy << 2);
1219         if (dquant) {
1220             ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
1221         }
1222         if((!s->progressive_sequence) && (cbp || (s->workaround_bugs&FF_BUG_XVID_ILACE)))
1223             s->interlaced_dct= get_bits1(&s->gb);
1224
1225         s->mv_dir = MV_DIR_FORWARD;
1226         if ((cbpc & 16) == 0) {
1227             if(s->mcsel){
1228                 s->current_picture.f.mb_type[xy] = MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0;
1229                 /* 16x16 global motion prediction */
1230                 s->mv_type = MV_TYPE_16X16;
1231                 mx= get_amv(s, 0);
1232                 my= get_amv(s, 1);
1233                 s->mv[0][0][0] = mx;
1234                 s->mv[0][0][1] = my;
1235             }else if((!s->progressive_sequence) && get_bits1(&s->gb)){
1236                 s->current_picture.f.mb_type[xy] = MB_TYPE_16x8 | MB_TYPE_L0 | MB_TYPE_INTERLACED;
1237                 /* 16x8 field motion prediction */
1238                 s->mv_type= MV_TYPE_FIELD;
1239
1240                 s->field_select[0][0]= get_bits1(&s->gb);
1241                 s->field_select[0][1]= get_bits1(&s->gb);
1242
1243                 h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1244
1245                 for(i=0; i<2; i++){
1246                     mx = h263_decode_motion(s, pred_x, s->f_code);
1247                     if (mx >= 0xffff)
1248                         return -1;
1249
1250                     my = h263_decode_motion(s, pred_y/2, s->f_code);
1251                     if (my >= 0xffff)
1252                         return -1;
1253
1254                     s->mv[0][i][0] = mx;
1255                     s->mv[0][i][1] = my;
1256                 }
1257             }else{
1258                 s->current_picture.f.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0;
1259                 /* 16x16 motion prediction */
1260                 s->mv_type = MV_TYPE_16X16;
1261                 h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1262                 mx = h263_decode_motion(s, pred_x, s->f_code);
1263
1264                 if (mx >= 0xffff)
1265                     return -1;
1266
1267                 my = h263_decode_motion(s, pred_y, s->f_code);
1268
1269                 if (my >= 0xffff)
1270                     return -1;
1271                 s->mv[0][0][0] = mx;
1272                 s->mv[0][0][1] = my;
1273             }
1274         } else {
1275             s->current_picture.f.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0;
1276             s->mv_type = MV_TYPE_8X8;
1277             for(i=0;i<4;i++) {
1278                 mot_val = h263_pred_motion(s, i, 0, &pred_x, &pred_y);
1279                 mx = h263_decode_motion(s, pred_x, s->f_code);
1280                 if (mx >= 0xffff)
1281                     return -1;
1282
1283                 my = h263_decode_motion(s, pred_y, s->f_code);
1284                 if (my >= 0xffff)
1285                     return -1;
1286                 s->mv[0][i][0] = mx;
1287                 s->mv[0][i][1] = my;
1288                 mot_val[0] = mx;
1289                 mot_val[1] = my;
1290             }
1291         }
1292     } else if(s->pict_type==AV_PICTURE_TYPE_B) {
1293         int modb1; // first bit of modb
1294         int modb2; // second bit of modb
1295         int mb_type;
1296
1297         s->mb_intra = 0; //B-frames never contain intra blocks
1298         s->mcsel=0;      //     ...               true gmc blocks
1299
1300         if(s->mb_x==0){
1301             for(i=0; i<2; i++){
1302                 s->last_mv[i][0][0]=
1303                 s->last_mv[i][0][1]=
1304                 s->last_mv[i][1][0]=
1305                 s->last_mv[i][1][1]= 0;
1306             }
1307
1308             ff_thread_await_progress((AVFrame*)s->next_picture_ptr, s->mb_y, 0);
1309         }
1310
1311         /* if we skipped it in the future P Frame than skip it now too */
1312         s->mb_skipped = s->next_picture.f.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]; // Note, skiptab=0 if last was GMC
1313
1314         if(s->mb_skipped){
1315                 /* skip mb */
1316             for(i=0;i<6;i++)
1317                 s->block_last_index[i] = -1;
1318
1319             s->mv_dir = MV_DIR_FORWARD;
1320             s->mv_type = MV_TYPE_16X16;
1321             s->mv[0][0][0] = 0;
1322             s->mv[0][0][1] = 0;
1323             s->mv[1][0][0] = 0;
1324             s->mv[1][0][1] = 0;
1325             s->current_picture.f.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
1326             goto end;
1327         }
1328
1329         modb1= get_bits1(&s->gb);
1330         if(modb1){
1331             mb_type= MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1; //like MB_TYPE_B_DIRECT but no vectors coded
1332             cbp=0;
1333         }else{
1334             modb2= get_bits1(&s->gb);
1335             mb_type= get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);
1336             if(mb_type<0){
1337                 av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n");
1338                 return -1;
1339             }
1340             mb_type= mb_type_b_map[ mb_type ];
1341             if(modb2) cbp= 0;
1342             else{
1343                 s->dsp.clear_blocks(s->block[0]);
1344                 cbp= get_bits(&s->gb, 6);
1345             }
1346
1347             if ((!IS_DIRECT(mb_type)) && cbp) {
1348                 if(get_bits1(&s->gb)){
1349                     ff_set_qscale(s, s->qscale + get_bits1(&s->gb)*4 - 2);
1350                 }
1351             }
1352
1353             if(!s->progressive_sequence){
1354                 if(cbp)
1355                     s->interlaced_dct= get_bits1(&s->gb);
1356
1357                 if(!IS_DIRECT(mb_type) && get_bits1(&s->gb)){
1358                     mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
1359                     mb_type &= ~MB_TYPE_16x16;
1360
1361                     if(USES_LIST(mb_type, 0)){
1362                         s->field_select[0][0]= get_bits1(&s->gb);
1363                         s->field_select[0][1]= get_bits1(&s->gb);
1364                     }
1365                     if(USES_LIST(mb_type, 1)){
1366                         s->field_select[1][0]= get_bits1(&s->gb);
1367                         s->field_select[1][1]= get_bits1(&s->gb);
1368                     }
1369                 }
1370             }
1371
1372             s->mv_dir = 0;
1373             if((mb_type & (MB_TYPE_DIRECT2|MB_TYPE_INTERLACED)) == 0){
1374                 s->mv_type= MV_TYPE_16X16;
1375
1376                 if(USES_LIST(mb_type, 0)){
1377                     s->mv_dir = MV_DIR_FORWARD;
1378
1379                     mx = h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
1380                     my = h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
1381                     s->last_mv[0][1][0]= s->last_mv[0][0][0]= s->mv[0][0][0] = mx;
1382                     s->last_mv[0][1][1]= s->last_mv[0][0][1]= s->mv[0][0][1] = my;
1383                 }
1384
1385                 if(USES_LIST(mb_type, 1)){
1386                     s->mv_dir |= MV_DIR_BACKWARD;
1387
1388                     mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
1389                     my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
1390                     s->last_mv[1][1][0]= s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
1391                     s->last_mv[1][1][1]= s->last_mv[1][0][1]= s->mv[1][0][1] = my;
1392                 }
1393             }else if(!IS_DIRECT(mb_type)){
1394                 s->mv_type= MV_TYPE_FIELD;
1395
1396                 if(USES_LIST(mb_type, 0)){
1397                     s->mv_dir = MV_DIR_FORWARD;
1398
1399                     for(i=0; i<2; i++){
1400                         mx = h263_decode_motion(s, s->last_mv[0][i][0]  , s->f_code);
1401                         my = h263_decode_motion(s, s->last_mv[0][i][1]/2, s->f_code);
1402                         s->last_mv[0][i][0]=  s->mv[0][i][0] = mx;
1403                         s->last_mv[0][i][1]= (s->mv[0][i][1] = my)*2;
1404                     }
1405                 }
1406
1407                 if(USES_LIST(mb_type, 1)){
1408                     s->mv_dir |= MV_DIR_BACKWARD;
1409
1410                     for(i=0; i<2; i++){
1411                         mx = h263_decode_motion(s, s->last_mv[1][i][0]  , s->b_code);
1412                         my = h263_decode_motion(s, s->last_mv[1][i][1]/2, s->b_code);
1413                         s->last_mv[1][i][0]=  s->mv[1][i][0] = mx;
1414                         s->last_mv[1][i][1]= (s->mv[1][i][1] = my)*2;
1415                     }
1416                 }
1417             }
1418         }
1419
1420         if(IS_DIRECT(mb_type)){
1421             if(IS_SKIP(mb_type))
1422                 mx=my=0;
1423             else{
1424                 mx = h263_decode_motion(s, 0, 1);
1425                 my = h263_decode_motion(s, 0, 1);
1426             }
1427
1428             s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
1429             mb_type |= ff_mpeg4_set_direct_mv(s, mx, my);
1430         }
1431         s->current_picture.f.mb_type[xy] = mb_type;
1432     } else { /* I-Frame */
1433         do{
1434             cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
1435             if (cbpc < 0){
1436                 av_log(s->avctx, AV_LOG_ERROR, "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
1437                 return -1;
1438             }
1439         }while(cbpc == 8);
1440
1441         dquant = cbpc & 4;
1442         s->mb_intra = 1;
1443 intra:
1444         s->ac_pred = get_bits1(&s->gb);
1445         if(s->ac_pred)
1446             s->current_picture.f.mb_type[xy] = MB_TYPE_INTRA | MB_TYPE_ACPRED;
1447         else
1448             s->current_picture.f.mb_type[xy] = MB_TYPE_INTRA;
1449
1450         cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
1451         if(cbpy<0){
1452             av_log(s->avctx, AV_LOG_ERROR, "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
1453             return -1;
1454         }
1455         cbp = (cbpc & 3) | (cbpy << 2);
1456
1457         s->use_intra_dc_vlc= s->qscale < s->intra_dc_threshold;
1458
1459         if (dquant) {
1460             ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
1461         }
1462
1463         if(!s->progressive_sequence)
1464             s->interlaced_dct= get_bits1(&s->gb);
1465
1466         s->dsp.clear_blocks(s->block[0]);
1467         /* decode each block */
1468         for (i = 0; i < 6; i++) {
1469             if (mpeg4_decode_block(s, block[i], i, cbp&32, 1, 0) < 0)
1470                 return -1;
1471             cbp+=cbp;
1472         }
1473         goto end;
1474     }
1475
1476     /* decode each block */
1477     for (i = 0; i < 6; i++) {
1478         if (mpeg4_decode_block(s, block[i], i, cbp&32, 0, 0) < 0)
1479             return -1;
1480         cbp+=cbp;
1481     }
1482 end:
1483
1484         /* per-MB end of slice check */
1485     if(s->codec_id==CODEC_ID_MPEG4){
1486         int next= mpeg4_is_resync(s);
1487         if(next) {
1488             if        (s->mb_x + s->mb_y*s->mb_width + 1 >  next && s->avctx->error_recognition >= FF_ER_AGGRESSIVE) {
1489                 return -1;
1490             } else if (s->mb_x + s->mb_y*s->mb_width + 1 >= next)
1491                 return SLICE_END;
1492
1493             if(s->pict_type==AV_PICTURE_TYPE_B){
1494                 const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
1495                 ff_thread_await_progress((AVFrame*)s->next_picture_ptr,
1496                                         (s->mb_x + delta >= s->mb_width) ? FFMIN(s->mb_y+1, s->mb_height-1) : s->mb_y, 0);
1497                 if (s->next_picture.f.mbskip_table[xy + delta])
1498                     return SLICE_OK;
1499             }
1500
1501             return SLICE_END;
1502         }
1503     }
1504
1505     return SLICE_OK;
1506 }
1507
1508
1509 static int mpeg4_decode_gop_header(MpegEncContext * s, GetBitContext *gb){
1510     int hours, minutes, seconds;
1511
1512     if(!show_bits(gb, 23)){
1513         av_log(s->avctx, AV_LOG_WARNING, "GOP header invalid\n");
1514         return -1;
1515     }
1516
1517     hours= get_bits(gb, 5);
1518     minutes= get_bits(gb, 6);
1519     skip_bits1(gb);
1520     seconds= get_bits(gb, 6);
1521
1522     s->time_base= seconds + 60*(minutes + 60*hours);
1523
1524     skip_bits1(gb);
1525     skip_bits1(gb);
1526
1527     return 0;
1528 }
1529
1530 static int mpeg4_decode_profile_level(MpegEncContext * s, GetBitContext *gb){
1531
1532     s->avctx->profile = get_bits(gb, 4);
1533     s->avctx->level   = get_bits(gb, 4);
1534
1535     // for Simple profile, level 0
1536     if (s->avctx->profile == 0 && s->avctx->level == 8) {
1537         s->avctx->level = 0;
1538     }
1539
1540     return 0;
1541 }
1542
1543 static int decode_vol_header(MpegEncContext *s, GetBitContext *gb){
1544     int width, height, vo_ver_id;
1545
1546     /* vol header */
1547     skip_bits(gb, 1); /* random access */
1548     s->vo_type= get_bits(gb, 8);
1549     if (get_bits1(gb) != 0) { /* is_ol_id */
1550         vo_ver_id = get_bits(gb, 4); /* vo_ver_id */
1551         skip_bits(gb, 3); /* vo_priority */
1552     } else {
1553         vo_ver_id = 1;
1554     }
1555     s->aspect_ratio_info= get_bits(gb, 4);
1556     if(s->aspect_ratio_info == FF_ASPECT_EXTENDED){
1557         s->avctx->sample_aspect_ratio.num= get_bits(gb, 8); // par_width
1558         s->avctx->sample_aspect_ratio.den= get_bits(gb, 8); // par_height
1559     }else{
1560         s->avctx->sample_aspect_ratio= ff_h263_pixel_aspect[s->aspect_ratio_info];
1561     }
1562
1563     if ((s->vol_control_parameters=get_bits1(gb))) { /* vol control parameter */
1564         int chroma_format= get_bits(gb, 2);
1565         if(chroma_format!=CHROMA_420){
1566             av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n");
1567         }
1568         s->low_delay= get_bits1(gb);
1569         if(get_bits1(gb)){ /* vbv parameters */
1570             get_bits(gb, 15);   /* first_half_bitrate */
1571             skip_bits1(gb);     /* marker */
1572             get_bits(gb, 15);   /* latter_half_bitrate */
1573             skip_bits1(gb);     /* marker */
1574             get_bits(gb, 15);   /* first_half_vbv_buffer_size */
1575             skip_bits1(gb);     /* marker */
1576             get_bits(gb, 3);    /* latter_half_vbv_buffer_size */
1577             get_bits(gb, 11);   /* first_half_vbv_occupancy */
1578             skip_bits1(gb);     /* marker */
1579             get_bits(gb, 15);   /* latter_half_vbv_occupancy */
1580             skip_bits1(gb);     /* marker */
1581         }
1582     }else{
1583         // set low delay flag only once the smartest? low delay detection won't be overriden
1584         if(s->picture_number==0)
1585             s->low_delay=0;
1586     }
1587
1588     s->shape = get_bits(gb, 2); /* vol shape */
1589     if(s->shape != RECT_SHAPE) av_log(s->avctx, AV_LOG_ERROR, "only rectangular vol supported\n");
1590     if(s->shape == GRAY_SHAPE && vo_ver_id != 1){
1591         av_log(s->avctx, AV_LOG_ERROR, "Gray shape not supported\n");
1592         skip_bits(gb, 4);  //video_object_layer_shape_extension
1593     }
1594
1595     check_marker(gb, "before time_increment_resolution");
1596
1597     s->avctx->time_base.den = get_bits(gb, 16);
1598     if(!s->avctx->time_base.den){
1599         av_log(s->avctx, AV_LOG_ERROR, "time_base.den==0\n");
1600         s->avctx->time_base.num = 0;
1601         return -1;
1602     }
1603
1604     s->time_increment_bits = av_log2(s->avctx->time_base.den - 1) + 1;
1605     if (s->time_increment_bits < 1)
1606         s->time_increment_bits = 1;
1607
1608     check_marker(gb, "before fixed_vop_rate");
1609
1610     if (get_bits1(gb) != 0) {   /* fixed_vop_rate  */
1611         s->avctx->time_base.num = get_bits(gb, s->time_increment_bits);
1612     }else
1613         s->avctx->time_base.num = 1;
1614
1615     s->t_frame=0;
1616
1617     if (s->shape != BIN_ONLY_SHAPE) {
1618         if (s->shape == RECT_SHAPE) {
1619             skip_bits1(gb);   /* marker */
1620             width = get_bits(gb, 13);
1621             skip_bits1(gb);   /* marker */
1622             height = get_bits(gb, 13);
1623             skip_bits1(gb);   /* marker */
1624             if(width && height && !(s->width && s->codec_tag == AV_RL32("MP4S"))){ /* they should be non zero but who knows ... */
1625                 s->width = width;
1626                 s->height = height;
1627             }
1628         }
1629
1630         s->progressive_sequence=
1631         s->progressive_frame= get_bits1(gb)^1;
1632         s->interlaced_dct=0;
1633         if(!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO))
1634             av_log(s->avctx, AV_LOG_INFO, "MPEG4 OBMC not supported (very likely buggy encoder)\n");   /* OBMC Disable */
1635         if (vo_ver_id == 1) {
1636             s->vol_sprite_usage = get_bits1(gb); /* vol_sprite_usage */
1637         } else {
1638             s->vol_sprite_usage = get_bits(gb, 2); /* vol_sprite_usage */
1639         }
1640         if(s->vol_sprite_usage==STATIC_SPRITE) av_log(s->avctx, AV_LOG_ERROR, "Static Sprites not supported\n");
1641         if(s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE){
1642             if(s->vol_sprite_usage==STATIC_SPRITE){
1643                 s->sprite_width = get_bits(gb, 13);
1644                 skip_bits1(gb); /* marker */
1645                 s->sprite_height= get_bits(gb, 13);
1646                 skip_bits1(gb); /* marker */
1647                 s->sprite_left  = get_bits(gb, 13);
1648                 skip_bits1(gb); /* marker */
1649                 s->sprite_top   = get_bits(gb, 13);
1650                 skip_bits1(gb); /* marker */
1651             }
1652             s->num_sprite_warping_points= get_bits(gb, 6);
1653             if(s->num_sprite_warping_points > 3){
1654                 av_log(s->avctx, AV_LOG_ERROR, "%d sprite_warping_points\n", s->num_sprite_warping_points);
1655                 s->num_sprite_warping_points= 0;
1656                 return -1;
1657             }
1658             s->sprite_warping_accuracy = get_bits(gb, 2);
1659             s->sprite_brightness_change= get_bits1(gb);
1660             if(s->vol_sprite_usage==STATIC_SPRITE)
1661                 s->low_latency_sprite= get_bits1(gb);
1662         }
1663         // FIXME sadct disable bit if verid!=1 && shape not rect
1664
1665         if (get_bits1(gb) == 1) {   /* not_8_bit */
1666             s->quant_precision = get_bits(gb, 4); /* quant_precision */
1667             if(get_bits(gb, 4)!=8) av_log(s->avctx, AV_LOG_ERROR, "N-bit not supported\n"); /* bits_per_pixel */
1668             if(s->quant_precision!=5) av_log(s->avctx, AV_LOG_ERROR, "quant precision %d\n", s->quant_precision);
1669         } else {
1670             s->quant_precision = 5;
1671         }
1672
1673         // FIXME a bunch of grayscale shape things
1674
1675         if((s->mpeg_quant=get_bits1(gb))){ /* vol_quant_type */
1676             int i, v;
1677
1678             /* load default matrixes */
1679             for(i=0; i<64; i++){
1680                 int j= s->dsp.idct_permutation[i];
1681                 v= ff_mpeg4_default_intra_matrix[i];
1682                 s->intra_matrix[j]= v;
1683                 s->chroma_intra_matrix[j]= v;
1684
1685                 v= ff_mpeg4_default_non_intra_matrix[i];
1686                 s->inter_matrix[j]= v;
1687                 s->chroma_inter_matrix[j]= v;
1688             }
1689
1690             /* load custom intra matrix */
1691             if(get_bits1(gb)){
1692                 int last=0;
1693                 for(i=0; i<64; i++){
1694                     int j;
1695                     v= get_bits(gb, 8);
1696                     if(v==0) break;
1697
1698                     last= v;
1699                     j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
1700                     s->intra_matrix[j]= v;
1701                     s->chroma_intra_matrix[j]= v;
1702                 }
1703
1704                 /* replicate last value */
1705                 for(; i<64; i++){
1706                     int j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
1707                     s->intra_matrix[j]= last;
1708                     s->chroma_intra_matrix[j]= last;
1709                 }
1710             }
1711
1712             /* load custom non intra matrix */
1713             if(get_bits1(gb)){
1714                 int last=0;
1715                 for(i=0; i<64; i++){
1716                     int j;
1717                     v= get_bits(gb, 8);
1718                     if(v==0) break;
1719
1720                     last= v;
1721                     j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
1722                     s->inter_matrix[j]= v;
1723                     s->chroma_inter_matrix[j]= v;
1724                 }
1725
1726                 /* replicate last value */
1727                 for(; i<64; i++){
1728                     int j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
1729                     s->inter_matrix[j]= last;
1730                     s->chroma_inter_matrix[j]= last;
1731                 }
1732             }
1733
1734             // FIXME a bunch of grayscale shape things
1735         }
1736
1737         if(vo_ver_id != 1)
1738              s->quarter_sample= get_bits1(gb);
1739         else s->quarter_sample=0;
1740
1741         if(!get_bits1(gb)){
1742             int pos= get_bits_count(gb);
1743             int estimation_method= get_bits(gb, 2);
1744             if(estimation_method<2){
1745                 if(!get_bits1(gb)){
1746                     s->cplx_estimation_trash_i += 8*get_bits1(gb); //opaque
1747                     s->cplx_estimation_trash_i += 8*get_bits1(gb); //transparent
1748                     s->cplx_estimation_trash_i += 8*get_bits1(gb); //intra_cae
1749                     s->cplx_estimation_trash_i += 8*get_bits1(gb); //inter_cae
1750                     s->cplx_estimation_trash_i += 8*get_bits1(gb); //no_update
1751                     s->cplx_estimation_trash_i += 8*get_bits1(gb); //upampling
1752                 }
1753                 if(!get_bits1(gb)){
1754                     s->cplx_estimation_trash_i += 8*get_bits1(gb); //intra_blocks
1755                     s->cplx_estimation_trash_p += 8*get_bits1(gb); //inter_blocks
1756                     s->cplx_estimation_trash_p += 8*get_bits1(gb); //inter4v_blocks
1757                     s->cplx_estimation_trash_i += 8*get_bits1(gb); //not coded blocks
1758                 }
1759                 if(!check_marker(gb, "in complexity estimation part 1")){
1760                     skip_bits_long(gb, pos - get_bits_count(gb));
1761                     goto no_cplx_est;
1762                 }
1763                 if(!get_bits1(gb)){
1764                     s->cplx_estimation_trash_i += 8*get_bits1(gb); //dct_coeffs
1765                     s->cplx_estimation_trash_i += 8*get_bits1(gb); //dct_lines
1766                     s->cplx_estimation_trash_i += 8*get_bits1(gb); //vlc_syms
1767                     s->cplx_estimation_trash_i += 4*get_bits1(gb); //vlc_bits
1768                 }
1769                 if(!get_bits1(gb)){
1770                     s->cplx_estimation_trash_p += 8*get_bits1(gb); //apm
1771                     s->cplx_estimation_trash_p += 8*get_bits1(gb); //npm
1772                     s->cplx_estimation_trash_b += 8*get_bits1(gb); //interpolate_mc_q
1773                     s->cplx_estimation_trash_p += 8*get_bits1(gb); //forwback_mc_q
1774                     s->cplx_estimation_trash_p += 8*get_bits1(gb); //halfpel2
1775                     s->cplx_estimation_trash_p += 8*get_bits1(gb); //halfpel4
1776                 }
1777                 if(!check_marker(gb, "in complexity estimation part 2")){
1778                     skip_bits_long(gb, pos - get_bits_count(gb));
1779                     goto no_cplx_est;
1780                 }
1781                 if(estimation_method==1){
1782                     s->cplx_estimation_trash_i += 8*get_bits1(gb); //sadct
1783                     s->cplx_estimation_trash_p += 8*get_bits1(gb); //qpel
1784                 }
1785             }else
1786                 av_log(s->avctx, AV_LOG_ERROR, "Invalid Complexity estimation method %d\n", estimation_method);
1787         }else{
1788 no_cplx_est:
1789             s->cplx_estimation_trash_i=
1790             s->cplx_estimation_trash_p=
1791             s->cplx_estimation_trash_b= 0;
1792         }
1793
1794         s->resync_marker= !get_bits1(gb); /* resync_marker_disabled */
1795
1796         s->data_partitioning= get_bits1(gb);
1797         if(s->data_partitioning){
1798             s->rvlc= get_bits1(gb);
1799         }
1800
1801         if(vo_ver_id != 1) {
1802             s->new_pred= get_bits1(gb);
1803             if(s->new_pred){
1804                 av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n");
1805                 skip_bits(gb, 2); /* requested upstream message type */
1806                 skip_bits1(gb); /* newpred segment type */
1807             }
1808             s->reduced_res_vop= get_bits1(gb);
1809             if(s->reduced_res_vop) av_log(s->avctx, AV_LOG_ERROR, "reduced resolution VOP not supported\n");
1810         }
1811         else{
1812             s->new_pred=0;
1813             s->reduced_res_vop= 0;
1814         }
1815
1816         s->scalability= get_bits1(gb);
1817
1818         if (s->scalability) {
1819             GetBitContext bak= *gb;
1820             int h_sampling_factor_n;
1821             int h_sampling_factor_m;
1822             int v_sampling_factor_n;
1823             int v_sampling_factor_m;
1824
1825             s->hierachy_type= get_bits1(gb);
1826             skip_bits(gb, 4);  /* ref_layer_id */
1827             skip_bits1(gb);    /* ref_layer_sampling_dir */
1828             h_sampling_factor_n= get_bits(gb, 5);
1829             h_sampling_factor_m= get_bits(gb, 5);
1830             v_sampling_factor_n= get_bits(gb, 5);
1831             v_sampling_factor_m= get_bits(gb, 5);
1832             s->enhancement_type= get_bits1(gb);
1833
1834             if(   h_sampling_factor_n==0 || h_sampling_factor_m==0
1835                || v_sampling_factor_n==0 || v_sampling_factor_m==0){
1836                 /* illegal scalability header (VERY broken encoder),
1837                  * trying to workaround */
1838                 s->scalability=0;
1839                 *gb= bak;
1840             }else
1841                 av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n");
1842
1843             // bin shape stuff FIXME
1844         }
1845     }
1846     return 0;
1847 }
1848
1849 /**
1850  * decodes the user data stuff in the header.
1851  * Also initializes divx/xvid/lavc_version/build.
1852  */
1853 static int decode_user_data(MpegEncContext *s, GetBitContext *gb){
1854     char buf[256];
1855     int i;
1856     int e;
1857     int ver = 0, build = 0, ver2 = 0, ver3 = 0;
1858     char last;
1859
1860     for(i=0; i<255 && get_bits_count(gb) < gb->size_in_bits; i++){
1861         if(show_bits(gb, 23) == 0) break;
1862         buf[i]= get_bits(gb, 8);
1863     }
1864     buf[i]=0;
1865
1866     /* divx detection */
1867     e=sscanf(buf, "DivX%dBuild%d%c", &ver, &build, &last);
1868     if(e<2)
1869         e=sscanf(buf, "DivX%db%d%c", &ver, &build, &last);
1870     if(e>=2){
1871         s->divx_version= ver;
1872         s->divx_build= build;
1873         s->divx_packed= e==3 && last=='p';
1874         if(s->divx_packed && !s->showed_packed_warning) {
1875             av_log(s->avctx, AV_LOG_WARNING, "Invalid and inefficient vfw-avi packed B frames detected\n");
1876             s->showed_packed_warning=1;
1877         }
1878     }
1879
1880     /* ffmpeg detection */
1881     e=sscanf(buf, "FFmpe%*[^b]b%d", &build)+3;
1882     if(e!=4)
1883         e=sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build);
1884     if(e!=4){
1885         e=sscanf(buf, "Lavc%d.%d.%d", &ver, &ver2, &ver3)+1;
1886         if (e>1)
1887             build= (ver<<16) + (ver2<<8) + ver3;
1888     }
1889     if(e!=4){
1890         if(strcmp(buf, "ffmpeg")==0){
1891             s->lavc_build= 4600;
1892         }
1893     }
1894     if(e==4){
1895         s->lavc_build= build;
1896     }
1897
1898     /* Xvid detection */
1899     e=sscanf(buf, "XviD%d", &build);
1900     if(e==1){
1901         s->xvid_build= build;
1902     }
1903
1904     return 0;
1905 }
1906
1907 static int decode_vop_header(MpegEncContext *s, GetBitContext *gb){
1908     int time_incr, time_increment;
1909
1910     s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I;        /* pict type: I = 0 , P = 1 */
1911     if(s->pict_type==AV_PICTURE_TYPE_B && s->low_delay && s->vol_control_parameters==0 && !(s->flags & CODEC_FLAG_LOW_DELAY)){
1912         av_log(s->avctx, AV_LOG_ERROR, "low_delay flag incorrectly, clearing it\n");
1913         s->low_delay=0;
1914     }
1915
1916     s->partitioned_frame= s->data_partitioning && s->pict_type!=AV_PICTURE_TYPE_B;
1917     if(s->partitioned_frame)
1918         s->decode_mb= mpeg4_decode_partitioned_mb;
1919     else
1920         s->decode_mb= mpeg4_decode_mb;
1921
1922     time_incr=0;
1923     while (get_bits1(gb) != 0)
1924         time_incr++;
1925
1926     check_marker(gb, "before time_increment");
1927
1928     if(s->time_increment_bits==0 || !(show_bits(gb, s->time_increment_bits+1)&1)){
1929         av_log(s->avctx, AV_LOG_ERROR, "hmm, seems the headers are not complete, trying to guess time_increment_bits\n");
1930
1931         for(s->time_increment_bits=1 ;s->time_increment_bits<16; s->time_increment_bits++){
1932             if (    s->pict_type == AV_PICTURE_TYPE_P
1933                 || (s->pict_type == AV_PICTURE_TYPE_S && s->vol_sprite_usage==GMC_SPRITE)) {
1934                 if((show_bits(gb, s->time_increment_bits+6)&0x37) == 0x30) break;
1935             }else
1936                 if((show_bits(gb, s->time_increment_bits+5)&0x1F) == 0x18) break;
1937         }
1938
1939         av_log(s->avctx, AV_LOG_ERROR, "my guess is %d bits ;)\n",s->time_increment_bits);
1940     }
1941
1942     if(IS_3IV1) time_increment= get_bits1(gb); //FIXME investigate further
1943     else time_increment= get_bits(gb, s->time_increment_bits);
1944
1945     if(s->pict_type!=AV_PICTURE_TYPE_B){
1946         s->last_time_base= s->time_base;
1947         s->time_base+= time_incr;
1948         s->time= s->time_base*s->avctx->time_base.den + time_increment;
1949         if(s->workaround_bugs&FF_BUG_UMP4){
1950             if(s->time < s->last_non_b_time){
1951                 /* header is not mpeg-4-compatible, broken encoder,
1952                  * trying to workaround */
1953                 s->time_base++;
1954                 s->time+= s->avctx->time_base.den;
1955             }
1956         }
1957         s->pp_time= s->time - s->last_non_b_time;
1958         s->last_non_b_time= s->time;
1959     }else{
1960         s->time= (s->last_time_base + time_incr)*s->avctx->time_base.den + time_increment;
1961         s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
1962         if(s->pp_time <=s->pb_time || s->pp_time <= s->pp_time - s->pb_time || s->pp_time<=0){
1963             /* messed up order, maybe after seeking? skipping current b-frame */
1964             return FRAME_SKIPPED;
1965         }
1966         ff_mpeg4_init_direct_mv(s);
1967
1968         if(s->t_frame==0) s->t_frame= s->pb_time;
1969         if(s->t_frame==0) s->t_frame=1; // 1/0 protection
1970         s->pp_field_time= (  ROUNDED_DIV(s->last_non_b_time, s->t_frame)
1971                            - ROUNDED_DIV(s->last_non_b_time - s->pp_time, s->t_frame))*2;
1972         s->pb_field_time= (  ROUNDED_DIV(s->time, s->t_frame)
1973                            - ROUNDED_DIV(s->last_non_b_time - s->pp_time, s->t_frame))*2;
1974         if(!s->progressive_sequence){
1975             if(s->pp_field_time <= s->pb_field_time || s->pb_field_time <= 1)
1976                 return FRAME_SKIPPED;
1977         }
1978     }
1979
1980     if(s->avctx->time_base.num)
1981         s->current_picture_ptr->f.pts = (s->time + s->avctx->time_base.num / 2) / s->avctx->time_base.num;
1982     else
1983         s->current_picture_ptr->f.pts = AV_NOPTS_VALUE;
1984     if(s->avctx->debug&FF_DEBUG_PTS)
1985         av_log(s->avctx, AV_LOG_DEBUG, "MPEG4 PTS: %"PRId64"\n",
1986                s->current_picture_ptr->f.pts);
1987
1988     check_marker(gb, "before vop_coded");
1989
1990     /* vop coded */
1991     if (get_bits1(gb) != 1){
1992         if(s->avctx->debug&FF_DEBUG_PICT_INFO)
1993             av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n");
1994         return FRAME_SKIPPED;
1995     }
1996     if (s->shape != BIN_ONLY_SHAPE && ( s->pict_type == AV_PICTURE_TYPE_P
1997                           || (s->pict_type == AV_PICTURE_TYPE_S && s->vol_sprite_usage==GMC_SPRITE))) {
1998         /* rounding type for motion estimation */
1999         s->no_rounding = get_bits1(gb);
2000     } else {
2001         s->no_rounding = 0;
2002     }
2003 //FIXME reduced res stuff
2004
2005      if (s->shape != RECT_SHAPE) {
2006          if (s->vol_sprite_usage != 1 || s->pict_type != AV_PICTURE_TYPE_I) {
2007              skip_bits(gb, 13); /* width */
2008              skip_bits1(gb);   /* marker */
2009              skip_bits(gb, 13); /* height */
2010              skip_bits1(gb);   /* marker */
2011              skip_bits(gb, 13); /* hor_spat_ref */
2012              skip_bits1(gb);   /* marker */
2013              skip_bits(gb, 13); /* ver_spat_ref */
2014          }
2015          skip_bits1(gb); /* change_CR_disable */
2016
2017          if (get_bits1(gb) != 0) {
2018              skip_bits(gb, 8); /* constant_alpha_value */
2019          }
2020      }
2021 //FIXME complexity estimation stuff
2022
2023      if (s->shape != BIN_ONLY_SHAPE) {
2024          skip_bits_long(gb, s->cplx_estimation_trash_i);
2025          if(s->pict_type != AV_PICTURE_TYPE_I)
2026             skip_bits_long(gb, s->cplx_estimation_trash_p);
2027          if(s->pict_type == AV_PICTURE_TYPE_B)
2028             skip_bits_long(gb, s->cplx_estimation_trash_b);
2029
2030          s->intra_dc_threshold= mpeg4_dc_threshold[ get_bits(gb, 3) ];
2031          if(!s->progressive_sequence){
2032              s->top_field_first= get_bits1(gb);
2033              s->alternate_scan= get_bits1(gb);
2034          }else
2035              s->alternate_scan= 0;
2036      }
2037
2038      if(s->alternate_scan){
2039          ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_alternate_vertical_scan);
2040          ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_alternate_vertical_scan);
2041          ff_init_scantable(s->dsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
2042          ff_init_scantable(s->dsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
2043      } else{
2044          ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_zigzag_direct);
2045          ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_zigzag_direct);
2046          ff_init_scantable(s->dsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
2047          ff_init_scantable(s->dsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
2048      }
2049
2050      if(s->pict_type == AV_PICTURE_TYPE_S && (s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE)){
2051          mpeg4_decode_sprite_trajectory(s, gb);
2052          if(s->sprite_brightness_change) av_log(s->avctx, AV_LOG_ERROR, "sprite_brightness_change not supported\n");
2053          if(s->vol_sprite_usage==STATIC_SPRITE) av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n");
2054      }
2055
2056      if (s->shape != BIN_ONLY_SHAPE) {
2057          s->chroma_qscale= s->qscale = get_bits(gb, s->quant_precision);
2058          if(s->qscale==0){
2059              av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG4 header (qscale=0)\n");
2060              return -1; // makes no sense to continue, as there is nothing left from the image then
2061          }
2062
2063          if (s->pict_type != AV_PICTURE_TYPE_I) {
2064              s->f_code = get_bits(gb, 3);       /* fcode_for */
2065              if(s->f_code==0){
2066                  av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG4 header (f_code=0)\n");
2067                  return -1; // makes no sense to continue, as the MV decoding will break very quickly
2068              }
2069          }else
2070              s->f_code=1;
2071
2072          if (s->pict_type == AV_PICTURE_TYPE_B) {
2073              s->b_code = get_bits(gb, 3);
2074          }else
2075              s->b_code=1;
2076
2077          if(s->avctx->debug&FF_DEBUG_PICT_INFO){
2078              av_log(s->avctx, AV_LOG_DEBUG, "qp:%d fc:%d,%d %s size:%d pro:%d alt:%d top:%d %spel part:%d resync:%d w:%d a:%d rnd:%d vot:%d%s dc:%d ce:%d/%d/%d\n",
2079                  s->qscale, s->f_code, s->b_code,
2080                  s->pict_type == AV_PICTURE_TYPE_I ? "I" : (s->pict_type == AV_PICTURE_TYPE_P ? "P" : (s->pict_type == AV_PICTURE_TYPE_B ? "B" : "S")),
2081                  gb->size_in_bits,s->progressive_sequence, s->alternate_scan, s->top_field_first,
2082                  s->quarter_sample ? "q" : "h", s->data_partitioning, s->resync_marker, s->num_sprite_warping_points,
2083                  s->sprite_warping_accuracy, 1-s->no_rounding, s->vo_type, s->vol_control_parameters ? " VOLC" : " ", s->intra_dc_threshold, s->cplx_estimation_trash_i, s->cplx_estimation_trash_p, s->cplx_estimation_trash_b);
2084          }
2085
2086          if(!s->scalability){
2087              if (s->shape!=RECT_SHAPE && s->pict_type!=AV_PICTURE_TYPE_I) {
2088                  skip_bits1(gb); // vop shape coding type
2089              }
2090          }else{
2091              if(s->enhancement_type){
2092                  int load_backward_shape= get_bits1(gb);
2093                  if(load_backward_shape){
2094                      av_log(s->avctx, AV_LOG_ERROR, "load backward shape isn't supported\n");
2095                  }
2096              }
2097              skip_bits(gb, 2); //ref_select_code
2098          }
2099      }
2100      /* detect buggy encoders which don't set the low_delay flag (divx4/xvid/opendivx)*/
2101      // note we cannot detect divx5 without b-frames easily (although it's buggy too)
2102      if(s->vo_type==0 && s->vol_control_parameters==0 && s->divx_version==-1 && s->picture_number==0){
2103          av_log(s->avctx, AV_LOG_WARNING, "looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n");
2104          s->low_delay=1;
2105      }
2106
2107      s->picture_number++; // better than pic number==0 always ;)
2108
2109      s->y_dc_scale_table= ff_mpeg4_y_dc_scale_table; //FIXME add short header support
2110      s->c_dc_scale_table= ff_mpeg4_c_dc_scale_table;
2111
2112      if(s->workaround_bugs&FF_BUG_EDGE){
2113          s->h_edge_pos= s->width;
2114          s->v_edge_pos= s->height;
2115      }
2116      return 0;
2117 }
2118
2119 /**
2120  * decode mpeg4 headers
2121  * @return <0 if no VOP found (or a damaged one)
2122  *         FRAME_SKIPPED if a not coded VOP is found
2123  *         0 if a VOP is found
2124  */
2125 int ff_mpeg4_decode_picture_header(MpegEncContext * s, GetBitContext *gb)
2126 {
2127     unsigned startcode, v;
2128
2129     /* search next start code */
2130     align_get_bits(gb);
2131
2132     if(s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630){
2133         skip_bits(gb, 24);
2134         if(get_bits(gb, 8) == 0xF0)
2135             goto end;
2136     }
2137
2138     startcode = 0xff;
2139     for(;;) {
2140         if(get_bits_count(gb) >= gb->size_in_bits){
2141             if(gb->size_in_bits==8 && (s->divx_version>=0 || s->xvid_build>=0)){
2142                 av_log(s->avctx, AV_LOG_WARNING, "frame skip %d\n", gb->size_in_bits);
2143                 return FRAME_SKIPPED; //divx bug
2144             }else
2145                 return -1; //end of stream
2146         }
2147
2148         /* use the bits after the test */
2149         v = get_bits(gb, 8);
2150         startcode = ((startcode << 8) | v) & 0xffffffff;
2151
2152         if((startcode&0xFFFFFF00) != 0x100)
2153             continue; //no startcode
2154
2155         if(s->avctx->debug&FF_DEBUG_STARTCODE){
2156             av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode);
2157             if     (startcode<=0x11F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start");
2158             else if(startcode<=0x12F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start");
2159             else if(startcode<=0x13F) av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
2160             else if(startcode<=0x15F) av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start");
2161             else if(startcode<=0x1AF) av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
2162             else if(startcode==0x1B0) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start");
2163             else if(startcode==0x1B1) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End");
2164             else if(startcode==0x1B2) av_log(s->avctx, AV_LOG_DEBUG, "User Data");
2165             else if(startcode==0x1B3) av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start");
2166             else if(startcode==0x1B4) av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error");
2167             else if(startcode==0x1B5) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start");
2168             else if(startcode==0x1B6) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start");
2169             else if(startcode==0x1B7) av_log(s->avctx, AV_LOG_DEBUG, "slice start");
2170             else if(startcode==0x1B8) av_log(s->avctx, AV_LOG_DEBUG, "extension start");
2171             else if(startcode==0x1B9) av_log(s->avctx, AV_LOG_DEBUG, "fgs start");
2172             else if(startcode==0x1BA) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start");
2173             else if(startcode==0x1BB) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start");
2174             else if(startcode==0x1BC) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start");
2175             else if(startcode==0x1BD) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start");
2176             else if(startcode==0x1BE) av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start");
2177             else if(startcode==0x1BF) av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start");
2178             else if(startcode==0x1C0) av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start");
2179             else if(startcode==0x1C1) av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start");
2180             else if(startcode==0x1C2) av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start");
2181             else if(startcode==0x1C3) av_log(s->avctx, AV_LOG_DEBUG, "stuffing start");
2182             else if(startcode<=0x1C5) av_log(s->avctx, AV_LOG_DEBUG, "reserved");
2183             else if(startcode<=0x1FF) av_log(s->avctx, AV_LOG_DEBUG, "System start");
2184             av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb));
2185         }
2186
2187         if(startcode >= 0x120 && startcode <= 0x12F){
2188             if(decode_vol_header(s, gb) < 0)
2189                 return -1;
2190         }
2191         else if(startcode == USER_DATA_STARTCODE){
2192             decode_user_data(s, gb);
2193         }
2194         else if(startcode == GOP_STARTCODE){
2195             mpeg4_decode_gop_header(s, gb);
2196         }
2197         else if(startcode == VOS_STARTCODE){
2198             mpeg4_decode_profile_level(s, gb);
2199         }
2200         else if(startcode == VOP_STARTCODE){
2201             break;
2202         }
2203
2204         align_get_bits(gb);
2205         startcode = 0xff;
2206     }
2207 end:
2208     if(s->flags& CODEC_FLAG_LOW_DELAY)
2209         s->low_delay=1;
2210     s->avctx->has_b_frames= !s->low_delay;
2211     return decode_vop_header(s, gb);
2212 }
2213
2214 static av_cold int decode_init(AVCodecContext *avctx)
2215 {
2216     MpegEncContext *s = avctx->priv_data;
2217     int ret;
2218     static int done = 0;
2219
2220     s->divx_version=
2221     s->divx_build=
2222     s->xvid_build=
2223     s->lavc_build= -1;
2224
2225     if((ret=ff_h263_decode_init(avctx)) < 0)
2226         return ret;
2227
2228     if (!done) {
2229         done = 1;
2230
2231         init_rl(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
2232         init_rl(&rvlc_rl_inter, ff_mpeg4_static_rl_table_store[1]);
2233         init_rl(&rvlc_rl_intra, ff_mpeg4_static_rl_table_store[2]);
2234         INIT_VLC_RL(ff_mpeg4_rl_intra, 554);
2235         INIT_VLC_RL(rvlc_rl_inter, 1072);
2236         INIT_VLC_RL(rvlc_rl_intra, 1072);
2237         INIT_VLC_STATIC(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
2238                  &ff_mpeg4_DCtab_lum[0][1], 2, 1,
2239                  &ff_mpeg4_DCtab_lum[0][0], 2, 1, 512);
2240         INIT_VLC_STATIC(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
2241                  &ff_mpeg4_DCtab_chrom[0][1], 2, 1,
2242                  &ff_mpeg4_DCtab_chrom[0][0], 2, 1, 512);
2243         INIT_VLC_STATIC(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
2244                  &sprite_trajectory_tab[0][1], 4, 2,
2245                  &sprite_trajectory_tab[0][0], 4, 2, 128);
2246         INIT_VLC_STATIC(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
2247                  &mb_type_b_tab[0][1], 2, 1,
2248                  &mb_type_b_tab[0][0], 2, 1, 16);
2249     }
2250
2251     s->h263_pred = 1;
2252     s->low_delay = 0; //default, might be overriden in the vol header during header parsing
2253     s->decode_mb= mpeg4_decode_mb;
2254     s->time_increment_bits = 4; /* default value for broken headers */
2255     avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
2256
2257     return 0;
2258 }
2259
2260 static const AVProfile mpeg4_video_profiles[] = {
2261     { FF_PROFILE_MPEG4_SIMPLE,                    "Simple Profile" },
2262     { FF_PROFILE_MPEG4_SIMPLE_SCALABLE,           "Simple Scalable Profile" },
2263     { FF_PROFILE_MPEG4_CORE,                      "Core Profile" },
2264     { FF_PROFILE_MPEG4_MAIN,                      "Main Profile" },
2265     { FF_PROFILE_MPEG4_N_BIT,                     "N-bit Profile" },
2266     { FF_PROFILE_MPEG4_SCALABLE_TEXTURE,          "Scalable Texture Profile" },
2267     { FF_PROFILE_MPEG4_SIMPLE_FACE_ANIMATION,     "Simple Face Animation Profile" },
2268     { FF_PROFILE_MPEG4_BASIC_ANIMATED_TEXTURE,    "Basic Animated Texture Profile" },
2269     { FF_PROFILE_MPEG4_HYBRID,                    "Hybrid Profile" },
2270     { FF_PROFILE_MPEG4_ADVANCED_REAL_TIME,        "Advanced Real Time Simple Profile" },
2271     { FF_PROFILE_MPEG4_CORE_SCALABLE,             "Code Scalable Profile" },
2272     { FF_PROFILE_MPEG4_ADVANCED_CODING,           "Advanced Coding Profile" },
2273     { FF_PROFILE_MPEG4_ADVANCED_CORE,             "Advanced Core Profile" },
2274     { FF_PROFILE_MPEG4_ADVANCED_SCALABLE_TEXTURE, "Advanced Scalable Texture Profile" },
2275     { FF_PROFILE_MPEG4_SIMPLE_STUDIO,             "Simple Studio Profile" },
2276     { FF_PROFILE_MPEG4_ADVANCED_SIMPLE,           "Advanced Simple Profile" },
2277 };
2278
2279 AVCodec ff_mpeg4_decoder = {
2280     .name           = "mpeg4",
2281     .type           = AVMEDIA_TYPE_VIDEO,
2282     .id             = CODEC_ID_MPEG4,
2283     .priv_data_size = sizeof(MpegEncContext),
2284     .init           = decode_init,
2285     .close          = ff_h263_decode_end,
2286     .decode         = ff_h263_decode_frame,
2287     .capabilities   = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY | CODEC_CAP_FRAME_THREADS,
2288     .flush= ff_mpeg_flush,
2289     .max_lowres= 3,
2290     .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2"),
2291     .pix_fmts= ff_hwaccel_pixfmt_list_420,
2292     .profiles = NULL_IF_CONFIG_SMALL(mpeg4_video_profiles),
2293     .update_thread_context= ONLY_IF_THREADS_ENABLED(ff_mpeg_update_thread_context)
2294 };
2295
2296
2297 #if CONFIG_MPEG4_VDPAU_DECODER
2298 AVCodec ff_mpeg4_vdpau_decoder = {
2299     .name           = "mpeg4_vdpau",
2300     .type           = AVMEDIA_TYPE_VIDEO,
2301     .id             = CODEC_ID_MPEG4,
2302     .priv_data_size = sizeof(MpegEncContext),
2303     .init           = decode_init,
2304     .close          = ff_h263_decode_end,
2305     .decode         = ff_h263_decode_frame,
2306     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
2307     .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 (VDPAU)"),
2308     .pix_fmts= (const enum PixelFormat[]){PIX_FMT_VDPAU_MPEG4, PIX_FMT_NONE},
2309 };
2310 #endif