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