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