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