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