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