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