Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpeg4videodec.c @ 2034ba08

History | View | Annotate | Download (84.5 KB)

1
/*
2
 * MPEG4 decoder.
3
 * Copyright (c) 2000,2001 Fabrice Bellard
4
 * Copyright (c) 2002-2010 Michael Niedermayer <michaelni@gmx.at>
5
 *
6
 * This file is part of FFmpeg.
7
 *
8
 * FFmpeg is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU Lesser General Public
10
 * License as published by the Free Software Foundation; either
11
 * version 2.1 of the License, or (at your option) any later version.
12
 *
13
 * FFmpeg is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16
 * Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Lesser General Public
19
 * License along with FFmpeg; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
 */
22

    
23
#include "mpegvideo.h"
24
#include "mpeg4video.h"
25
#include "h263.h"
26

    
27
// The defines below define the number of bits that are read at once for
28
// reading vlc values. Changing these may improve speed and data cache needs
29
// be aware though that decreasing them may need the number of stages that is
30
// passed to get_vlc* to be increased.
31
#define SPRITE_TRAJ_VLC_BITS 6
32
#define DC_VLC_BITS 9
33
#define MB_TYPE_B_VLC_BITS 4
34

    
35

    
36
static VLC dc_lum, dc_chrom;
37
static VLC sprite_trajectory;
38
static VLC mb_type_b_vlc;
39

    
40
static const int mb_type_b_map[4]= {
41
    MB_TYPE_DIRECT2 | MB_TYPE_L0L1,
42
    MB_TYPE_L0L1 | MB_TYPE_16x16,
43
    MB_TYPE_L1 | MB_TYPE_16x16,
44
    MB_TYPE_L0 | MB_TYPE_16x16,
45
};
46

    
47
/**
48
 * predicts the ac.
49
 * @param n block index (0-3 are luma, 4-5 are chroma)
50
 * @param dir the ac prediction direction
51
 */
52
void mpeg4_pred_ac(MpegEncContext * s, DCTELEM *block, int n,
53
                   int dir)
54
{
55
    int i;
56
    int16_t *ac_val, *ac_val1;
57
    int8_t * const qscale_table= s->current_picture.qscale_table;
58

    
59
    /* find prediction */
60
    ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
61
    ac_val1 = ac_val;
62
    if (s->ac_pred) {
63
        if (dir == 0) {
64
            const int xy= s->mb_x-1 + s->mb_y*s->mb_stride;
65
            /* left prediction */
66
            ac_val -= 16;
67

    
68
            if(s->mb_x==0 || s->qscale == qscale_table[xy] || n==1 || n==3){
69
                /* same qscale */
70
                for(i=1;i<8;i++) {
71
                    block[s->dsp.idct_permutation[i<<3]] += ac_val[i];
72
                }
73
            }else{
74
                /* different qscale, we must rescale */
75
                for(i=1;i<8;i++) {
76
                    block[s->dsp.idct_permutation[i<<3]] += ROUNDED_DIV(ac_val[i]*qscale_table[xy], s->qscale);
77
                }
78
            }
79
        } else {
80
            const int xy= s->mb_x + s->mb_y*s->mb_stride - s->mb_stride;
81
            /* top prediction */
82
            ac_val -= 16 * s->block_wrap[n];
83

    
84
            if(s->mb_y==0 || s->qscale == qscale_table[xy] || n==2 || n==3){
85
                /* same qscale */
86
                for(i=1;i<8;i++) {
87
                    block[s->dsp.idct_permutation[i]] += ac_val[i + 8];
88
                }
89
            }else{
90
                /* different qscale, we must rescale */
91
                for(i=1;i<8;i++) {
92
                    block[s->dsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8]*qscale_table[xy], s->qscale);
93
                }
94
            }
95
        }
96
    }
97
    /* left copy */
98
    for(i=1;i<8;i++)
99
        ac_val1[i    ] = block[s->dsp.idct_permutation[i<<3]];
100

    
101
    /* top copy */
102
    for(i=1;i<8;i++)
103
        ac_val1[8 + i] = block[s->dsp.idct_permutation[i   ]];
104

    
105
}
106

    
107
/**
108
 * check if the next stuff is a resync marker or the end.
109
 * @return 0 if not
110
 */
111
static inline int mpeg4_is_resync(MpegEncContext *s){
112
    int bits_count= get_bits_count(&s->gb);
113
    int v= show_bits(&s->gb, 16);
114

    
115
    if(s->workaround_bugs&FF_BUG_NO_PADDING){
116
        return 0;
117
    }
118

    
119
    while(v<=0xFF){
120
        if(s->pict_type==FF_B_TYPE || (v>>(8-s->pict_type)!=1) || s->partitioned_frame)
121
            break;
122
        skip_bits(&s->gb, 8+s->pict_type);
123
        bits_count+= 8+s->pict_type;
124
        v= show_bits(&s->gb, 16);
125
    }
126

    
127
    if(bits_count + 8 >= s->gb.size_in_bits){
128
        v>>=8;
129
        v|= 0x7F >> (7-(bits_count&7));
130

    
131
        if(v==0x7F)
132
            return 1;
133
    }else{
134
        if(v == ff_mpeg4_resync_prefix[bits_count&7]){
135
            int len;
136
            GetBitContext gb= s->gb;
137

    
138
            skip_bits(&s->gb, 1);
139
            align_get_bits(&s->gb);
140

    
141
            for(len=0; len<32; len++){
142
                if(get_bits1(&s->gb)) break;
143
            }
144

    
145
            s->gb= gb;
146

    
147
            if(len>=ff_mpeg4_get_video_packet_prefix_length(s))
148
                return 1;
149
        }
150
    }
151
    return 0;
152
}
153

    
154
static void mpeg4_decode_sprite_trajectory(MpegEncContext * s, GetBitContext *gb)
155
{
156
    int i;
157
    int a= 2<<s->sprite_warping_accuracy;
158
    int rho= 3-s->sprite_warping_accuracy;
159
    int r=16/a;
160
    const int vop_ref[4][2]= {{0,0}, {s->width,0}, {0, s->height}, {s->width, s->height}}; // only true for rectangle shapes
161
    int d[4][2]={{0,0}, {0,0}, {0,0}, {0,0}};
162
    int sprite_ref[4][2];
163
    int virtual_ref[2][2];
164
    int w2, h2, w3, h3;
165
    int alpha=0, beta=0;
166
    int w= s->width;
167
    int h= s->height;
168
    int min_ab;
169

    
170
    for(i=0; i<s->num_sprite_warping_points; i++){
171
        int length;
172
        int x=0, y=0;
173

    
174
        length= get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3);
175
        if(length){
176
            x= get_xbits(gb, length);
177
        }
178
        if(!(s->divx_version==500 && s->divx_build==413)) skip_bits1(gb); /* marker bit */
179

    
180
        length= get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3);
181
        if(length){
182
            y=get_xbits(gb, length);
183
        }
184
        skip_bits1(gb); /* marker bit */
185
        s->sprite_traj[i][0]= d[i][0]= x;
186
        s->sprite_traj[i][1]= d[i][1]= y;
187
    }
188
    for(; i<4; i++)
189
        s->sprite_traj[i][0]= s->sprite_traj[i][1]= 0;
190

    
191
    while((1<<alpha)<w) alpha++;
192
    while((1<<beta )<h) beta++; // there seems to be a typo in the mpeg4 std for the definition of w' and h'
193
    w2= 1<<alpha;
194
    h2= 1<<beta;
195

    
196
// Note, the 4th point isn't used for GMC
197
    if(s->divx_version==500 && s->divx_build==413){
198
        sprite_ref[0][0]= a*vop_ref[0][0] + d[0][0];
199
        sprite_ref[0][1]= a*vop_ref[0][1] + d[0][1];
200
        sprite_ref[1][0]= a*vop_ref[1][0] + d[0][0] + d[1][0];
201
        sprite_ref[1][1]= a*vop_ref[1][1] + d[0][1] + d[1][1];
202
        sprite_ref[2][0]= a*vop_ref[2][0] + d[0][0] + d[2][0];
203
        sprite_ref[2][1]= a*vop_ref[2][1] + d[0][1] + d[2][1];
204
    } else {
205
        sprite_ref[0][0]= (a>>1)*(2*vop_ref[0][0] + d[0][0]);
206
        sprite_ref[0][1]= (a>>1)*(2*vop_ref[0][1] + d[0][1]);
207
        sprite_ref[1][0]= (a>>1)*(2*vop_ref[1][0] + d[0][0] + d[1][0]);
208
        sprite_ref[1][1]= (a>>1)*(2*vop_ref[1][1] + d[0][1] + d[1][1]);
209
        sprite_ref[2][0]= (a>>1)*(2*vop_ref[2][0] + d[0][0] + d[2][0]);
210
        sprite_ref[2][1]= (a>>1)*(2*vop_ref[2][1] + d[0][1] + d[2][1]);
211
    }
212
/*    sprite_ref[3][0]= (a>>1)*(2*vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);
213
    sprite_ref[3][1]= (a>>1)*(2*vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */
214

    
215
// this is mostly identical to the mpeg4 std (and is totally unreadable because of that ...)
216
// perhaps it should be reordered to be more readable ...
217
// the idea behind this virtual_ref mess is to be able to use shifts later per pixel instead of divides
218
// so the distance between points is converted from w&h based to w2&h2 based which are of the 2^x form
219
    virtual_ref[0][0]= 16*(vop_ref[0][0] + w2)
220
        + ROUNDED_DIV(((w - w2)*(r*sprite_ref[0][0] - 16*vop_ref[0][0]) + w2*(r*sprite_ref[1][0] - 16*vop_ref[1][0])),w);
221
    virtual_ref[0][1]= 16*vop_ref[0][1]
222
        + ROUNDED_DIV(((w - w2)*(r*sprite_ref[0][1] - 16*vop_ref[0][1]) + w2*(r*sprite_ref[1][1] - 16*vop_ref[1][1])),w);
223
    virtual_ref[1][0]= 16*vop_ref[0][0]
224
        + ROUNDED_DIV(((h - h2)*(r*sprite_ref[0][0] - 16*vop_ref[0][0]) + h2*(r*sprite_ref[2][0] - 16*vop_ref[2][0])),h);
225
    virtual_ref[1][1]= 16*(vop_ref[0][1] + h2)
226
        + ROUNDED_DIV(((h - h2)*(r*sprite_ref[0][1] - 16*vop_ref[0][1]) + h2*(r*sprite_ref[2][1] - 16*vop_ref[2][1])),h);
227

    
228
    switch(s->num_sprite_warping_points)
229
    {
230
        case 0:
231
            s->sprite_offset[0][0]= 0;
232
            s->sprite_offset[0][1]= 0;
233
            s->sprite_offset[1][0]= 0;
234
            s->sprite_offset[1][1]= 0;
235
            s->sprite_delta[0][0]= a;
236
            s->sprite_delta[0][1]= 0;
237
            s->sprite_delta[1][0]= 0;
238
            s->sprite_delta[1][1]= a;
239
            s->sprite_shift[0]= 0;
240
            s->sprite_shift[1]= 0;
241
            break;
242
        case 1: //GMC only
243
            s->sprite_offset[0][0]= sprite_ref[0][0] - a*vop_ref[0][0];
244
            s->sprite_offset[0][1]= sprite_ref[0][1] - a*vop_ref[0][1];
245
            s->sprite_offset[1][0]= ((sprite_ref[0][0]>>1)|(sprite_ref[0][0]&1)) - a*(vop_ref[0][0]/2);
246
            s->sprite_offset[1][1]= ((sprite_ref[0][1]>>1)|(sprite_ref[0][1]&1)) - a*(vop_ref[0][1]/2);
247
            s->sprite_delta[0][0]= a;
248
            s->sprite_delta[0][1]= 0;
249
            s->sprite_delta[1][0]= 0;
250
            s->sprite_delta[1][1]= a;
251
            s->sprite_shift[0]= 0;
252
            s->sprite_shift[1]= 0;
253
            break;
254
        case 2:
255
            s->sprite_offset[0][0]= (sprite_ref[0][0]<<(alpha+rho))
256
                                                  + (-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][0])
257
                                                  + ( r*sprite_ref[0][1] - virtual_ref[0][1])*(-vop_ref[0][1])
258
                                                  + (1<<(alpha+rho-1));
259
            s->sprite_offset[0][1]= (sprite_ref[0][1]<<(alpha+rho))
260
                                                  + (-r*sprite_ref[0][1] + virtual_ref[0][1])*(-vop_ref[0][0])
261
                                                  + (-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][1])
262
                                                  + (1<<(alpha+rho-1));
263
            s->sprite_offset[1][0]= ( (-r*sprite_ref[0][0] + virtual_ref[0][0])*(-2*vop_ref[0][0] + 1)
264
                                     +( r*sprite_ref[0][1] - virtual_ref[0][1])*(-2*vop_ref[0][1] + 1)
265
                                     +2*w2*r*sprite_ref[0][0]
266
                                     - 16*w2
267
                                     + (1<<(alpha+rho+1)));
268
            s->sprite_offset[1][1]= ( (-r*sprite_ref[0][1] + virtual_ref[0][1])*(-2*vop_ref[0][0] + 1)
269
                                     +(-r*sprite_ref[0][0] + virtual_ref[0][0])*(-2*vop_ref[0][1] + 1)
270
                                     +2*w2*r*sprite_ref[0][1]
271
                                     - 16*w2
272
                                     + (1<<(alpha+rho+1)));
273
            s->sprite_delta[0][0]=   (-r*sprite_ref[0][0] + virtual_ref[0][0]);
274
            s->sprite_delta[0][1]=   (+r*sprite_ref[0][1] - virtual_ref[0][1]);
275
            s->sprite_delta[1][0]=   (-r*sprite_ref[0][1] + virtual_ref[0][1]);
276
            s->sprite_delta[1][1]=   (-r*sprite_ref[0][0] + virtual_ref[0][0]);
277

    
278
            s->sprite_shift[0]= alpha+rho;
279
            s->sprite_shift[1]= alpha+rho+2;
280
            break;
281
        case 3:
282
            min_ab= FFMIN(alpha, beta);
283
            w3= w2>>min_ab;
284
            h3= h2>>min_ab;
285
            s->sprite_offset[0][0]=  (sprite_ref[0][0]<<(alpha+beta+rho-min_ab))
286
                                   + (-r*sprite_ref[0][0] + virtual_ref[0][0])*h3*(-vop_ref[0][0])
287
                                   + (-r*sprite_ref[0][0] + virtual_ref[1][0])*w3*(-vop_ref[0][1])
288
                                   + (1<<(alpha+beta+rho-min_ab-1));
289
            s->sprite_offset[0][1]=  (sprite_ref[0][1]<<(alpha+beta+rho-min_ab))
290
                                   + (-r*sprite_ref[0][1] + virtual_ref[0][1])*h3*(-vop_ref[0][0])
291
                                   + (-r*sprite_ref[0][1] + virtual_ref[1][1])*w3*(-vop_ref[0][1])
292
                                   + (1<<(alpha+beta+rho-min_ab-1));
293
            s->sprite_offset[1][0]=  (-r*sprite_ref[0][0] + virtual_ref[0][0])*h3*(-2*vop_ref[0][0] + 1)
294
                                   + (-r*sprite_ref[0][0] + virtual_ref[1][0])*w3*(-2*vop_ref[0][1] + 1)
295
                                   + 2*w2*h3*r*sprite_ref[0][0]
296
                                   - 16*w2*h3
297
                                   + (1<<(alpha+beta+rho-min_ab+1));
298
            s->sprite_offset[1][1]=  (-r*sprite_ref[0][1] + virtual_ref[0][1])*h3*(-2*vop_ref[0][0] + 1)
299
                                   + (-r*sprite_ref[0][1] + virtual_ref[1][1])*w3*(-2*vop_ref[0][1] + 1)
300
                                   + 2*w2*h3*r*sprite_ref[0][1]
301
                                   - 16*w2*h3
302
                                   + (1<<(alpha+beta+rho-min_ab+1));
303
            s->sprite_delta[0][0]=   (-r*sprite_ref[0][0] + virtual_ref[0][0])*h3;
304
            s->sprite_delta[0][1]=   (-r*sprite_ref[0][0] + virtual_ref[1][0])*w3;
305
            s->sprite_delta[1][0]=   (-r*sprite_ref[0][1] + virtual_ref[0][1])*h3;
306
            s->sprite_delta[1][1]=   (-r*sprite_ref[0][1] + virtual_ref[1][1])*w3;
307

    
308
            s->sprite_shift[0]= alpha + beta + rho - min_ab;
309
            s->sprite_shift[1]= alpha + beta + rho - min_ab + 2;
310
            break;
311
    }
312
    /* try to simplify the situation */
313
    if(   s->sprite_delta[0][0] == a<<s->sprite_shift[0]
314
       && s->sprite_delta[0][1] == 0
315
       && s->sprite_delta[1][0] == 0
316
       && s->sprite_delta[1][1] == a<<s->sprite_shift[0])
317
    {
318
        s->sprite_offset[0][0]>>=s->sprite_shift[0];
319
        s->sprite_offset[0][1]>>=s->sprite_shift[0];
320
        s->sprite_offset[1][0]>>=s->sprite_shift[1];
321
        s->sprite_offset[1][1]>>=s->sprite_shift[1];
322
        s->sprite_delta[0][0]= a;
323
        s->sprite_delta[0][1]= 0;
324
        s->sprite_delta[1][0]= 0;
325
        s->sprite_delta[1][1]= a;
326
        s->sprite_shift[0]= 0;
327
        s->sprite_shift[1]= 0;
328
        s->real_sprite_warping_points=1;
329
    }
330
    else{
331
        int shift_y= 16 - s->sprite_shift[0];
332
        int shift_c= 16 - s->sprite_shift[1];
333
        for(i=0; i<2; i++){
334
            s->sprite_offset[0][i]<<= shift_y;
335
            s->sprite_offset[1][i]<<= shift_c;
336
            s->sprite_delta[0][i]<<= shift_y;
337
            s->sprite_delta[1][i]<<= shift_y;
338
            s->sprite_shift[i]= 16;
339
        }
340
        s->real_sprite_warping_points= s->num_sprite_warping_points;
341
    }
342
}
343

    
344
/**
345
 * decodes the next video packet.
346
 * @return <0 if something went wrong
347
 */
348
int mpeg4_decode_video_packet_header(MpegEncContext *s)
349
{
350
    int mb_num_bits= av_log2(s->mb_num - 1) + 1;
351
    int header_extension=0, mb_num, len;
352

    
353
    /* is there enough space left for a video packet + header */
354
    if( get_bits_count(&s->gb) > s->gb.size_in_bits-20) return -1;
355

    
356
    for(len=0; len<32; len++){
357
        if(get_bits1(&s->gb)) break;
358
    }
359

    
360
    if(len!=ff_mpeg4_get_video_packet_prefix_length(s)){
361
        av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n");
362
        return -1;
363
    }
364

    
365
    if(s->shape != RECT_SHAPE){
366
        header_extension= get_bits1(&s->gb);
367
        //FIXME more stuff here
368
    }
369

    
370
    mb_num= get_bits(&s->gb, mb_num_bits);
371
    if(mb_num>=s->mb_num){
372
        av_log(s->avctx, AV_LOG_ERROR, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
373
        return -1;
374
    }
375
    if(s->pict_type == FF_B_TYPE){
376
        while(s->next_picture.mbskip_table[ s->mb_index2xy[ mb_num ] ]) mb_num++;
377
        if(mb_num >= s->mb_num) return -1; // slice contains just skipped MBs which where already decoded
378
    }
379

    
380
    s->mb_x= mb_num % s->mb_width;
381
    s->mb_y= mb_num / s->mb_width;
382

    
383
    if(s->shape != BIN_ONLY_SHAPE){
384
        int qscale= get_bits(&s->gb, s->quant_precision);
385
        if(qscale)
386
            s->chroma_qscale=s->qscale= qscale;
387
    }
388

    
389
    if(s->shape == RECT_SHAPE){
390
        header_extension= get_bits1(&s->gb);
391
    }
392
    if(header_extension){
393
        int time_increment;
394
        int time_incr=0;
395

    
396
        while (get_bits1(&s->gb) != 0)
397
            time_incr++;
398

    
399
        check_marker(&s->gb, "before time_increment in video packed header");
400
        time_increment= get_bits(&s->gb, s->time_increment_bits);
401
        check_marker(&s->gb, "before vop_coding_type in video packed header");
402

    
403
        skip_bits(&s->gb, 2); /* vop coding type */
404
        //FIXME not rect stuff here
405

    
406
        if(s->shape != BIN_ONLY_SHAPE){
407
            skip_bits(&s->gb, 3); /* intra dc vlc threshold */
408
//FIXME don't just ignore everything
409
            if(s->pict_type == FF_S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
410
                mpeg4_decode_sprite_trajectory(s, &s->gb);
411
                av_log(s->avctx, AV_LOG_ERROR, "untested\n");
412
            }
413

    
414
            //FIXME reduced res stuff here
415

    
416
            if (s->pict_type != FF_I_TYPE) {
417
                int f_code = get_bits(&s->gb, 3);       /* fcode_for */
418
                if(f_code==0){
419
                    av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (f_code=0)\n");
420
                }
421
            }
422
            if (s->pict_type == FF_B_TYPE) {
423
                int b_code = get_bits(&s->gb, 3);
424
                if(b_code==0){
425
                    av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (b_code=0)\n");
426
                }
427
            }
428
        }
429
    }
430
    //FIXME new-pred stuff
431

    
432
    return 0;
433
}
434

    
435
/**
436
 * gets the average motion vector for a GMC MB.
437
 * @param n either 0 for the x component or 1 for y
438
 * @return the average MV for a GMC MB
439
 */
440
static inline int get_amv(MpegEncContext *s, int n){
441
    int x, y, mb_v, sum, dx, dy, shift;
442
    int len = 1 << (s->f_code + 4);
443
    const int a= s->sprite_warping_accuracy;
444

    
445
    if(s->workaround_bugs & FF_BUG_AMV)
446
        len >>= s->quarter_sample;
447

    
448
    if(s->real_sprite_warping_points==1){
449
        if(s->divx_version==500 && s->divx_build==413)
450
            sum= s->sprite_offset[0][n] / (1<<(a - s->quarter_sample));
451
        else
452
            sum= RSHIFT(s->sprite_offset[0][n]<<s->quarter_sample, a);
453
    }else{
454
        dx= s->sprite_delta[n][0];
455
        dy= s->sprite_delta[n][1];
456
        shift= s->sprite_shift[0];
457
        if(n) dy -= 1<<(shift + a + 1);
458
        else  dx -= 1<<(shift + a + 1);
459
        mb_v= s->sprite_offset[0][n] + dx*s->mb_x*16 + dy*s->mb_y*16;
460

    
461
        sum=0;
462
        for(y=0; y<16; y++){
463
            int v;
464

    
465
            v= mb_v + dy*y;
466
            //XXX FIXME optimize
467
            for(x=0; x<16; x++){
468
                sum+= v>>shift;
469
                v+= dx;
470
            }
471
        }
472
        sum= RSHIFT(sum, a+8-s->quarter_sample);
473
    }
474

    
475
    if      (sum < -len) sum= -len;
476
    else if (sum >= len) sum= len-1;
477

    
478
    return sum;
479
}
480

    
481
/**
482
 * decodes the dc value.
483
 * @param n block index (0-3 are luma, 4-5 are chroma)
484
 * @param dir_ptr the prediction direction will be stored here
485
 * @return the quantized dc
486
 */
487
static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr)
488
{
489
    int level, code;
490

    
491
    if (n < 4)
492
        code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1);
493
    else
494
        code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1);
495
    if (code < 0 || code > 9 /* && s->nbit<9 */){
496
        av_log(s->avctx, AV_LOG_ERROR, "illegal dc vlc\n");
497
        return -1;
498
    }
499
    if (code == 0) {
500
        level = 0;
501
    } else {
502
        if(IS_3IV1){
503
            if(code==1)
504
                level= 2*get_bits1(&s->gb)-1;
505
            else{
506
                if(get_bits1(&s->gb))
507
                    level = get_bits(&s->gb, code-1) + (1<<(code-1));
508
                else
509
                    level = -get_bits(&s->gb, code-1) - (1<<(code-1));
510
            }
511
        }else{
512
            level = get_xbits(&s->gb, code);
513
        }
514

    
515
        if (code > 8){
516
            if(get_bits1(&s->gb)==0){ /* marker */
517
                if(s->error_recognition>=2){
518
                    av_log(s->avctx, AV_LOG_ERROR, "dc marker bit missing\n");
519
                    return -1;
520
                }
521
            }
522
        }
523
    }
524

    
525
    return ff_mpeg4_pred_dc(s, n, level, dir_ptr, 0);
526
}
527

    
528
/**
529
 * decodes first partition.
530
 * @return number of MBs decoded or <0 if an error occurred
531
 */
532
static int mpeg4_decode_partition_a(MpegEncContext *s){
533
    int mb_num;
534
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
535

    
536
    /* decode first partition */
537
    mb_num=0;
538
    s->first_slice_line=1;
539
    for(; s->mb_y<s->mb_height; s->mb_y++){
540
        ff_init_block_index(s);
541
        for(; s->mb_x<s->mb_width; s->mb_x++){
542
            const int xy= s->mb_x + s->mb_y*s->mb_stride;
543
            int cbpc;
544
            int dir=0;
545

    
546
            mb_num++;
547
            ff_update_block_index(s);
548
            if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
549
                s->first_slice_line=0;
550

    
551
            if(s->pict_type==FF_I_TYPE){
552
                int i;
553

    
554
                do{
555
                    if(show_bits_long(&s->gb, 19)==DC_MARKER){
556
                        return mb_num-1;
557
                    }
558

    
559
                    cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
560
                    if (cbpc < 0){
561
                        av_log(s->avctx, AV_LOG_ERROR, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
562
                        return -1;
563
                    }
564
                }while(cbpc == 8);
565

    
566
                s->cbp_table[xy]= cbpc & 3;
567
                s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
568
                s->mb_intra = 1;
569

    
570
                if(cbpc & 4) {
571
                    ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
572
                }
573
                s->current_picture.qscale_table[xy]= s->qscale;
574

    
575
                s->mbintra_table[xy]= 1;
576
                for(i=0; i<6; i++){
577
                    int dc_pred_dir;
578
                    int dc= mpeg4_decode_dc(s, i, &dc_pred_dir);
579
                    if(dc < 0){
580
                        av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
581
                        return -1;
582
                    }
583
                    dir<<=1;
584
                    if(dc_pred_dir) dir|=1;
585
                }
586
                s->pred_dir_table[xy]= dir;
587
            }else{ /* P/S_TYPE */
588
                int mx, my, pred_x, pred_y, bits;
589
                int16_t * const mot_val= s->current_picture.motion_val[0][s->block_index[0]];
590
                const int stride= s->b8_stride*2;
591

    
592
try_again:
593
                bits= show_bits(&s->gb, 17);
594
                if(bits==MOTION_MARKER){
595
                    return mb_num-1;
596
                }
597
                skip_bits1(&s->gb);
598
                if(bits&0x10000){
599
                    /* skip mb */
600
                    if(s->pict_type==FF_S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
601
                        s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0;
602
                        mx= get_amv(s, 0);
603
                        my= get_amv(s, 1);
604
                    }else{
605
                        s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
606
                        mx=my=0;
607
                    }
608
                    mot_val[0       ]= mot_val[2       ]=
609
                    mot_val[0+stride]= mot_val[2+stride]= mx;
610
                    mot_val[1       ]= mot_val[3       ]=
611
                    mot_val[1+stride]= mot_val[3+stride]= my;
612

    
613
                    if(s->mbintra_table[xy])
614
                        ff_clean_intra_table_entries(s);
615
                    continue;
616
                }
617

    
618
                cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
619
                if (cbpc < 0){
620
                    av_log(s->avctx, AV_LOG_ERROR, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
621
                    return -1;
622
                }
623
                if(cbpc == 20)
624
                    goto try_again;
625

    
626
                s->cbp_table[xy]= cbpc&(8+3); //8 is dquant
627

    
628
                s->mb_intra = ((cbpc & 4) != 0);
629

    
630
                if(s->mb_intra){
631
                    s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
632
                    s->mbintra_table[xy]= 1;
633
                    mot_val[0       ]= mot_val[2       ]=
634
                    mot_val[0+stride]= mot_val[2+stride]= 0;
635
                    mot_val[1       ]= mot_val[3       ]=
636
                    mot_val[1+stride]= mot_val[3+stride]= 0;
637
                }else{
638
                    if(s->mbintra_table[xy])
639
                        ff_clean_intra_table_entries(s);
640

    
641
                    if(s->pict_type==FF_S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
642
                        s->mcsel= get_bits1(&s->gb);
643
                    else s->mcsel= 0;
644

    
645
                    if ((cbpc & 16) == 0) {
646
                        /* 16x16 motion prediction */
647

    
648
                        h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
649
                        if(!s->mcsel){
650
                            mx = h263_decode_motion(s, pred_x, s->f_code);
651
                            if (mx >= 0xffff)
652
                                return -1;
653

    
654
                            my = h263_decode_motion(s, pred_y, s->f_code);
655
                            if (my >= 0xffff)
656
                                return -1;
657
                            s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0;
658
                        } else {
659
                            mx = get_amv(s, 0);
660
                            my = get_amv(s, 1);
661
                            s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0;
662
                        }
663

    
664
                        mot_val[0       ]= mot_val[2       ] =
665
                        mot_val[0+stride]= mot_val[2+stride]= mx;
666
                        mot_val[1       ]= mot_val[3       ]=
667
                        mot_val[1+stride]= mot_val[3+stride]= my;
668
                    } else {
669
                        int i;
670
                        s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0;
671
                        for(i=0;i<4;i++) {
672
                            int16_t *mot_val= h263_pred_motion(s, i, 0, &pred_x, &pred_y);
673
                            mx = h263_decode_motion(s, pred_x, s->f_code);
674
                            if (mx >= 0xffff)
675
                                return -1;
676

    
677
                            my = h263_decode_motion(s, pred_y, s->f_code);
678
                            if (my >= 0xffff)
679
                                return -1;
680
                            mot_val[0] = mx;
681
                            mot_val[1] = my;
682
                        }
683
                    }
684
                }
685
            }
686
        }
687
        s->mb_x= 0;
688
    }
689

    
690
    return mb_num;
691
}
692

    
693
/**
694
 * decode second partition.
695
 * @return <0 if an error occurred
696
 */
697
static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count){
698
    int mb_num=0;
699
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
700

    
701
    s->mb_x= s->resync_mb_x;
702
    s->first_slice_line=1;
703
    for(s->mb_y= s->resync_mb_y; mb_num < mb_count; s->mb_y++){
704
        ff_init_block_index(s);
705
        for(; mb_num < mb_count && s->mb_x<s->mb_width; s->mb_x++){
706
            const int xy= s->mb_x + s->mb_y*s->mb_stride;
707

    
708
            mb_num++;
709
            ff_update_block_index(s);
710
            if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
711
                s->first_slice_line=0;
712

    
713
            if(s->pict_type==FF_I_TYPE){
714
                int ac_pred= get_bits1(&s->gb);
715
                int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
716
                if(cbpy<0){
717
                    av_log(s->avctx, AV_LOG_ERROR, "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
718
                    return -1;
719
                }
720

    
721
                s->cbp_table[xy]|= cbpy<<2;
722
                s->current_picture.mb_type[xy] |= ac_pred*MB_TYPE_ACPRED;
723
            }else{ /* P || S_TYPE */
724
                if(IS_INTRA(s->current_picture.mb_type[xy])){
725
                    int dir=0,i;
726
                    int ac_pred = get_bits1(&s->gb);
727
                    int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
728

    
729
                    if(cbpy<0){
730
                        av_log(s->avctx, AV_LOG_ERROR, "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
731
                        return -1;
732
                    }
733

    
734
                    if(s->cbp_table[xy] & 8) {
735
                        ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
736
                    }
737
                    s->current_picture.qscale_table[xy]= s->qscale;
738

    
739
                    for(i=0; i<6; i++){
740
                        int dc_pred_dir;
741
                        int dc= mpeg4_decode_dc(s, i, &dc_pred_dir);
742
                        if(dc < 0){
743
                            av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
744
                            return -1;
745
                        }
746
                        dir<<=1;
747
                        if(dc_pred_dir) dir|=1;
748
                    }
749
                    s->cbp_table[xy]&= 3; //remove dquant
750
                    s->cbp_table[xy]|= cbpy<<2;
751
                    s->current_picture.mb_type[xy] |= ac_pred*MB_TYPE_ACPRED;
752
                    s->pred_dir_table[xy]= dir;
753
                }else if(IS_SKIP(s->current_picture.mb_type[xy])){
754
                    s->current_picture.qscale_table[xy]= s->qscale;
755
                    s->cbp_table[xy]= 0;
756
                }else{
757
                    int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
758

    
759
                    if(cbpy<0){
760
                        av_log(s->avctx, AV_LOG_ERROR, "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
761
                        return -1;
762
                    }
763

    
764
                    if(s->cbp_table[xy] & 8) {
765
                        ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
766
                    }
767
                    s->current_picture.qscale_table[xy]= s->qscale;
768

    
769
                    s->cbp_table[xy]&= 3; //remove dquant
770
                    s->cbp_table[xy]|= (cbpy^0xf)<<2;
771
                }
772
            }
773
        }
774
        if(mb_num >= mb_count) return 0;
775
        s->mb_x= 0;
776
    }
777
    return 0;
778
}
779

    
780
/**
781
 * decodes the first & second partition
782
 * @return <0 if error (and sets error type in the error_status_table)
783
 */
784
int ff_mpeg4_decode_partitions(MpegEncContext *s)
785
{
786
    int mb_num;
787
    const int part_a_error= s->pict_type==FF_I_TYPE ? (DC_ERROR|MV_ERROR) : MV_ERROR;
788
    const int part_a_end  = s->pict_type==FF_I_TYPE ? (DC_END  |MV_END)   : MV_END;
789

    
790
    mb_num= mpeg4_decode_partition_a(s);
791
    if(mb_num<0){
792
        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error);
793
        return -1;
794
    }
795

    
796
    if(s->resync_mb_x + s->resync_mb_y*s->mb_width + mb_num > s->mb_num){
797
        av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n");
798
        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error);
799
        return -1;
800
    }
801

    
802
    s->mb_num_left= mb_num;
803

    
804
    if(s->pict_type==FF_I_TYPE){
805
        while(show_bits(&s->gb, 9) == 1)
806
            skip_bits(&s->gb, 9);
807
        if(get_bits_long(&s->gb, 19)!=DC_MARKER){
808
            av_log(s->avctx, AV_LOG_ERROR, "marker missing after first I partition at %d %d\n", s->mb_x, s->mb_y);
809
            return -1;
810
        }
811
    }else{
812
        while(show_bits(&s->gb, 10) == 1)
813
            skip_bits(&s->gb, 10);
814
        if(get_bits(&s->gb, 17)!=MOTION_MARKER){
815
            av_log(s->avctx, AV_LOG_ERROR, "marker missing after first P partition at %d %d\n", s->mb_x, s->mb_y);
816
            return -1;
817
        }
818
    }
819
    ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, part_a_end);
820

    
821
    if( mpeg4_decode_partition_b(s, mb_num) < 0){
822
        if(s->pict_type==FF_P_TYPE)
823
            ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, DC_ERROR);
824
        return -1;
825
    }else{
826
        if(s->pict_type==FF_P_TYPE)
827
            ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, DC_END);
828
    }
829

    
830
    return 0;
831
}
832

    
833
/**
834
 * decodes a block.
835
 * @return <0 if an error occurred
836
 */
837
static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
838
                              int n, int coded, int intra, int rvlc)
839
{
840
    int level, i, last, run;
841
    int dc_pred_dir;
842
    RLTable * rl;
843
    RL_VLC_ELEM * rl_vlc;
844
    const uint8_t * scan_table;
845
    int qmul, qadd;
846

    
847
    //Note intra & rvlc should be optimized away if this is inlined
848

    
849
    if(intra) {
850
      if(s->use_intra_dc_vlc){
851
        /* DC coef */
852
        if(s->partitioned_frame){
853
            level = s->dc_val[0][ s->block_index[n] ];
854
            if(n<4) level= FASTDIV((level + (s->y_dc_scale>>1)), s->y_dc_scale);
855
            else    level= FASTDIV((level + (s->c_dc_scale>>1)), s->c_dc_scale);
856
            dc_pred_dir= (s->pred_dir_table[s->mb_x + s->mb_y*s->mb_stride]<<n)&32;
857
        }else{
858
            level = mpeg4_decode_dc(s, n, &dc_pred_dir);
859
            if (level < 0)
860
                return -1;
861
        }
862
        block[0] = level;
863
        i = 0;
864
      }else{
865
            i = -1;
866
            ff_mpeg4_pred_dc(s, n, 0, &dc_pred_dir, 0);
867
      }
868
      if (!coded)
869
          goto not_coded;
870

    
871
      if(rvlc){
872
          rl = &rvlc_rl_intra;
873
          rl_vlc = rvlc_rl_intra.rl_vlc[0];
874
      }else{
875
          rl = &ff_mpeg4_rl_intra;
876
          rl_vlc = ff_mpeg4_rl_intra.rl_vlc[0];
877
      }
878
      if (s->ac_pred) {
879
          if (dc_pred_dir == 0)
880
              scan_table = s->intra_v_scantable.permutated; /* left */
881
          else
882
              scan_table = s->intra_h_scantable.permutated; /* top */
883
      } else {
884
            scan_table = s->intra_scantable.permutated;
885
      }
886
      qmul=1;
887
      qadd=0;
888
    } else {
889
        i = -1;
890
        if (!coded) {
891
            s->block_last_index[n] = i;
892
            return 0;
893
        }
894
        if(rvlc) rl = &rvlc_rl_inter;
895
        else     rl = &ff_h263_rl_inter;
896

    
897
        scan_table = s->intra_scantable.permutated;
898

    
899
        if(s->mpeg_quant){
900
            qmul=1;
901
            qadd=0;
902
            if(rvlc){
903
                rl_vlc = rvlc_rl_inter.rl_vlc[0];
904
            }else{
905
                rl_vlc = ff_h263_rl_inter.rl_vlc[0];
906
            }
907
        }else{
908
            qmul = s->qscale << 1;
909
            qadd = (s->qscale - 1) | 1;
910
            if(rvlc){
911
                rl_vlc = rvlc_rl_inter.rl_vlc[s->qscale];
912
            }else{
913
                rl_vlc = ff_h263_rl_inter.rl_vlc[s->qscale];
914
            }
915
        }
916
    }
917
  {
918
    OPEN_READER(re, &s->gb);
919
    for(;;) {
920
        UPDATE_CACHE(re, &s->gb);
921
        GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 0);
922
        if (level==0) {
923
          /* escape */
924
          if(rvlc){
925
                if(SHOW_UBITS(re, &s->gb, 1)==0){
926
                    av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in rvlc esc\n");
927
                    return -1;
928
                }; SKIP_CACHE(re, &s->gb, 1);
929

    
930
                last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);
931
                run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);
932
                SKIP_COUNTER(re, &s->gb, 1+1+6);
933
                UPDATE_CACHE(re, &s->gb);
934

    
935
                if(SHOW_UBITS(re, &s->gb, 1)==0){
936
                    av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in rvlc esc\n");
937
                    return -1;
938
                }; SKIP_CACHE(re, &s->gb, 1);
939

    
940
                level= SHOW_UBITS(re, &s->gb, 11); SKIP_CACHE(re, &s->gb, 11);
941

    
942
                if(SHOW_UBITS(re, &s->gb, 5)!=0x10){
943
                    av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n");
944
                    return -1;
945
                }; SKIP_CACHE(re, &s->gb, 5);
946

    
947
                level=  level * qmul + qadd;
948
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_CACHE(re, &s->gb, 1);
949
                SKIP_COUNTER(re, &s->gb, 1+11+5+1);
950

    
951
                i+= run + 1;
952
                if(last) i+=192;
953
          }else{
954
            int cache;
955
            cache= GET_CACHE(re, &s->gb);
956

    
957
            if(IS_3IV1)
958
                cache ^= 0xC0000000;
959

    
960
            if (cache&0x80000000) {
961
                if (cache&0x40000000) {
962
                    /* third escape */
963
                    SKIP_CACHE(re, &s->gb, 2);
964
                    last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);
965
                    run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);
966
                    SKIP_COUNTER(re, &s->gb, 2+1+6);
967
                    UPDATE_CACHE(re, &s->gb);
968

    
969
                    if(IS_3IV1){
970
                        level= SHOW_SBITS(re, &s->gb, 12); LAST_SKIP_BITS(re, &s->gb, 12);
971
                    }else{
972
                        if(SHOW_UBITS(re, &s->gb, 1)==0){
973
                            av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in 3. esc\n");
974
                            return -1;
975
                        }; SKIP_CACHE(re, &s->gb, 1);
976

    
977
                        level= SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12);
978

    
979
                        if(SHOW_UBITS(re, &s->gb, 1)==0){
980
                            av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in 3. esc\n");
981
                            return -1;
982
                        }; LAST_SKIP_CACHE(re, &s->gb, 1);
983

    
984
                        SKIP_COUNTER(re, &s->gb, 1+12+1);
985
                    }
986

    
987
#if 0
988
                    if(s->error_recognition >= FF_ER_COMPLIANT){
989
                        const int abs_level= FFABS(level);
990
                        if(abs_level<=MAX_LEVEL && run<=MAX_RUN){
991
                            const int run1= run - rl->max_run[last][abs_level] - 1;
992
                            if(abs_level <= rl->max_level[last][run]){
993
                                av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n");
994
                                return -1;
995
                            }
996
                            if(s->error_recognition > FF_ER_COMPLIANT){
997
                                if(abs_level <= rl->max_level[last][run]*2){
998
                                    av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 1 encoding possible\n");
999
                                    return -1;
1000
                                }
1001
                                if(run1 >= 0 && abs_level <= rl->max_level[last][run1]){
1002
                                    av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 2 encoding possible\n");
1003
                                    return -1;
1004
                                }
1005
                            }
1006
                        }
1007
                    }
1008
#endif
1009
                    if (level>0) level= level * qmul + qadd;
1010
                    else         level= level * qmul - qadd;
1011

    
1012
                    if((unsigned)(level + 2048) > 4095){
1013
                        if(s->error_recognition > FF_ER_COMPLIANT){
1014
                            if(level > 2560 || level<-2560){
1015
                                av_log(s->avctx, AV_LOG_ERROR, "|level| overflow in 3. esc, qp=%d\n", s->qscale);
1016
                                return -1;
1017
                            }
1018
                        }
1019
                        level= level<0 ? -2048 : 2047;
1020
                    }
1021

    
1022
                    i+= run + 1;
1023
                    if(last) i+=192;
1024
                } else {
1025
                    /* second escape */
1026
                    SKIP_BITS(re, &s->gb, 2);
1027
                    GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
1028
                    i+= run + rl->max_run[run>>7][level/qmul] +1; //FIXME opt indexing
1029
                    level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1030
                    LAST_SKIP_BITS(re, &s->gb, 1);
1031
                }
1032
            } else {
1033
                /* first escape */
1034
                SKIP_BITS(re, &s->gb, 1);
1035
                GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
1036
                i+= run;
1037
                level = level + rl->max_level[run>>7][(run-1)&63] * qmul;//FIXME opt indexing
1038
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1039
                LAST_SKIP_BITS(re, &s->gb, 1);
1040
            }
1041
          }
1042
        } else {
1043
            i+= run;
1044
            level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1045
            LAST_SKIP_BITS(re, &s->gb, 1);
1046
        }
1047
        if (i > 62){
1048
            i-= 192;
1049
            if(i&(~63)){
1050
                av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1051
                return -1;
1052
            }
1053

    
1054
            block[scan_table[i]] = level;
1055
            break;
1056
        }
1057

    
1058
        block[scan_table[i]] = level;
1059
    }
1060
    CLOSE_READER(re, &s->gb);
1061
  }
1062
 not_coded:
1063
    if (intra) {
1064
        if(!s->use_intra_dc_vlc){
1065
            block[0] = ff_mpeg4_pred_dc(s, n, block[0], &dc_pred_dir, 0);
1066

    
1067
            i -= i>>31; //if(i == -1) i=0;
1068
        }
1069

    
1070
        mpeg4_pred_ac(s, block, n, dc_pred_dir);
1071
        if (s->ac_pred) {
1072
            i = 63; /* XXX: not optimal */
1073
        }
1074
    }
1075
    s->block_last_index[n] = i;
1076
    return 0;
1077
}
1078

    
1079
/**
1080
 * decode partition C of one MB.
1081
 * @return <0 if an error occurred
1082
 */
1083
static int mpeg4_decode_partitioned_mb(MpegEncContext *s, DCTELEM block[6][64])
1084
{
1085
    int cbp, mb_type;
1086
    const int xy= s->mb_x + s->mb_y*s->mb_stride;
1087

    
1088
    mb_type= s->current_picture.mb_type[xy];
1089
    cbp = s->cbp_table[xy];
1090

    
1091
    s->use_intra_dc_vlc= s->qscale < s->intra_dc_threshold;
1092

    
1093
    if(s->current_picture.qscale_table[xy] != s->qscale){
1094
        ff_set_qscale(s, s->current_picture.qscale_table[xy] );
1095
    }
1096

    
1097
    if (s->pict_type == FF_P_TYPE || s->pict_type==FF_S_TYPE) {
1098
        int i;
1099
        for(i=0; i<4; i++){
1100
            s->mv[0][i][0] = s->current_picture.motion_val[0][ s->block_index[i] ][0];
1101
            s->mv[0][i][1] = s->current_picture.motion_val[0][ s->block_index[i] ][1];
1102
        }
1103
        s->mb_intra = IS_INTRA(mb_type);
1104

    
1105
        if (IS_SKIP(mb_type)) {
1106
            /* skip mb */
1107
            for(i=0;i<6;i++)
1108
                s->block_last_index[i] = -1;
1109
            s->mv_dir = MV_DIR_FORWARD;
1110
            s->mv_type = MV_TYPE_16X16;
1111
            if(s->pict_type==FF_S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
1112
                s->mcsel=1;
1113
                s->mb_skipped = 0;
1114
            }else{
1115
                s->mcsel=0;
1116
                s->mb_skipped = 1;
1117
            }
1118
        }else if(s->mb_intra){
1119
            s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
1120
        }else if(!s->mb_intra){
1121
//            s->mcsel= 0; //FIXME do we need to init that
1122

    
1123
            s->mv_dir = MV_DIR_FORWARD;
1124
            if (IS_8X8(mb_type)) {
1125
                s->mv_type = MV_TYPE_8X8;
1126
            } else {
1127
                s->mv_type = MV_TYPE_16X16;
1128
            }
1129
        }
1130
    } else { /* I-Frame */
1131
        s->mb_intra = 1;
1132
        s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
1133
    }
1134

    
1135
    if (!IS_SKIP(mb_type)) {
1136
        int i;
1137
        s->dsp.clear_blocks(s->block[0]);
1138
        /* decode each block */
1139
        for (i = 0; i < 6; i++) {
1140
            if(mpeg4_decode_block(s, block[i], i, cbp&32, s->mb_intra, s->rvlc) < 0){
1141
                av_log(s->avctx, AV_LOG_ERROR, "texture corrupted at %d %d %d\n", s->mb_x, s->mb_y, s->mb_intra);
1142
                return -1;
1143
            }
1144
            cbp+=cbp;
1145
        }
1146
    }
1147

    
1148
    /* per-MB end of slice check */
1149

    
1150
    if(--s->mb_num_left <= 0){
1151
        if(mpeg4_is_resync(s))
1152
            return SLICE_END;
1153
        else
1154
            return SLICE_NOEND;
1155
    }else{
1156
        if(mpeg4_is_resync(s)){
1157
            const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
1158
            if(s->cbp_table[xy+delta])
1159
                return SLICE_END;
1160
        }
1161
        return SLICE_OK;
1162
    }
1163
}
1164

    
1165
static int mpeg4_decode_mb(MpegEncContext *s,
1166
                      DCTELEM block[6][64])
1167
{
1168
    int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
1169
    int16_t *mot_val;
1170
    static int8_t quant_tab[4] = { -1, -2, 1, 2 };
1171
    const int xy= s->mb_x + s->mb_y * s->mb_stride;
1172

    
1173
    assert(s->h263_pred);
1174

    
1175
    if (s->pict_type == FF_P_TYPE || s->pict_type==FF_S_TYPE) {
1176
        do{
1177
            if (get_bits1(&s->gb)) {
1178
                /* skip mb */
1179
                s->mb_intra = 0;
1180
                for(i=0;i<6;i++)
1181
                    s->block_last_index[i] = -1;
1182
                s->mv_dir = MV_DIR_FORWARD;
1183
                s->mv_type = MV_TYPE_16X16;
1184
                if(s->pict_type==FF_S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
1185
                    s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0;
1186
                    s->mcsel=1;
1187
                    s->mv[0][0][0]= get_amv(s, 0);
1188
                    s->mv[0][0][1]= get_amv(s, 1);
1189

    
1190
                    s->mb_skipped = 0;
1191
                }else{
1192
                    s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
1193
                    s->mcsel=0;
1194
                    s->mv[0][0][0] = 0;
1195
                    s->mv[0][0][1] = 0;
1196
                    s->mb_skipped = 1;
1197
                }
1198
                goto end;
1199
            }
1200
            cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
1201
            if (cbpc < 0){
1202
                av_log(s->avctx, AV_LOG_ERROR, "cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
1203
                return -1;
1204
            }
1205
        }while(cbpc == 20);
1206

    
1207
        s->dsp.clear_blocks(s->block[0]);
1208
        dquant = cbpc & 8;
1209
        s->mb_intra = ((cbpc & 4) != 0);
1210
        if (s->mb_intra) goto intra;
1211

    
1212
        if(s->pict_type==FF_S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
1213
            s->mcsel= get_bits1(&s->gb);
1214
        else s->mcsel= 0;
1215
        cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1) ^ 0x0F;
1216

    
1217
        cbp = (cbpc & 3) | (cbpy << 2);
1218
        if (dquant) {
1219
            ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
1220
        }
1221
        if((!s->progressive_sequence) && (cbp || (s->workaround_bugs&FF_BUG_XVID_ILACE)))
1222
            s->interlaced_dct= get_bits1(&s->gb);
1223

    
1224
        s->mv_dir = MV_DIR_FORWARD;
1225
        if ((cbpc & 16) == 0) {
1226
            if(s->mcsel){
1227
                s->current_picture.mb_type[xy]= MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0;
1228
                /* 16x16 global motion prediction */
1229
                s->mv_type = MV_TYPE_16X16;
1230
                mx= get_amv(s, 0);
1231
                my= get_amv(s, 1);
1232
                s->mv[0][0][0] = mx;
1233
                s->mv[0][0][1] = my;
1234
            }else if((!s->progressive_sequence) && get_bits1(&s->gb)){
1235
                s->current_picture.mb_type[xy]= MB_TYPE_16x8 | MB_TYPE_L0 | MB_TYPE_INTERLACED;
1236
                /* 16x8 field motion prediction */
1237
                s->mv_type= MV_TYPE_FIELD;
1238

    
1239
                s->field_select[0][0]= get_bits1(&s->gb);
1240
                s->field_select[0][1]= get_bits1(&s->gb);
1241

    
1242
                h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1243

    
1244
                for(i=0; i<2; i++){
1245
                    mx = h263_decode_motion(s, pred_x, s->f_code);
1246
                    if (mx >= 0xffff)
1247
                        return -1;
1248

    
1249
                    my = h263_decode_motion(s, pred_y/2, s->f_code);
1250
                    if (my >= 0xffff)
1251
                        return -1;
1252

    
1253
                    s->mv[0][i][0] = mx;
1254
                    s->mv[0][i][1] = my;
1255
                }
1256
            }else{
1257
                s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0;
1258
                /* 16x16 motion prediction */
1259
                s->mv_type = MV_TYPE_16X16;
1260
                h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1261
                mx = h263_decode_motion(s, pred_x, s->f_code);
1262

    
1263
                if (mx >= 0xffff)
1264
                    return -1;
1265

    
1266
                my = h263_decode_motion(s, pred_y, s->f_code);
1267

    
1268
                if (my >= 0xffff)
1269
                    return -1;
1270
                s->mv[0][0][0] = mx;
1271
                s->mv[0][0][1] = my;
1272
            }
1273
        } else {
1274
            s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0;
1275
            s->mv_type = MV_TYPE_8X8;
1276
            for(i=0;i<4;i++) {
1277
                mot_val = h263_pred_motion(s, i, 0, &pred_x, &pred_y);
1278
                mx = h263_decode_motion(s, pred_x, s->f_code);
1279
                if (mx >= 0xffff)
1280
                    return -1;
1281

    
1282
                my = h263_decode_motion(s, pred_y, s->f_code);
1283
                if (my >= 0xffff)
1284
                    return -1;
1285
                s->mv[0][i][0] = mx;
1286
                s->mv[0][i][1] = my;
1287
                mot_val[0] = mx;
1288
                mot_val[1] = my;
1289
            }
1290
        }
1291
    } else if(s->pict_type==FF_B_TYPE) {
1292
        int modb1; // first bit of modb
1293
        int modb2; // second bit of modb
1294
        int mb_type;
1295

    
1296
        s->mb_intra = 0; //B-frames never contain intra blocks
1297
        s->mcsel=0;      //     ...               true gmc blocks
1298

    
1299
        if(s->mb_x==0){
1300
            for(i=0; i<2; i++){
1301
                s->last_mv[i][0][0]=
1302
                s->last_mv[i][0][1]=
1303
                s->last_mv[i][1][0]=
1304
                s->last_mv[i][1][1]= 0;
1305
            }
1306
        }
1307

    
1308
        /* if we skipped it in the future P Frame than skip it now too */
1309
        s->mb_skipped= s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]; // Note, skiptab=0 if last was GMC
1310

    
1311
        if(s->mb_skipped){
1312
                /* skip mb */
1313
            for(i=0;i<6;i++)
1314
                s->block_last_index[i] = -1;
1315

    
1316
            s->mv_dir = MV_DIR_FORWARD;
1317
            s->mv_type = MV_TYPE_16X16;
1318
            s->mv[0][0][0] = 0;
1319
            s->mv[0][0][1] = 0;
1320
            s->mv[1][0][0] = 0;
1321
            s->mv[1][0][1] = 0;
1322
            s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
1323
            goto end;
1324
        }
1325

    
1326
        modb1= get_bits1(&s->gb);
1327
        if(modb1){
1328
            mb_type= MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1; //like MB_TYPE_B_DIRECT but no vectors coded
1329
            cbp=0;
1330
        }else{
1331
            modb2= get_bits1(&s->gb);
1332
            mb_type= get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);
1333
            if(mb_type<0){
1334
                av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n");
1335
                return -1;
1336
            }
1337
            mb_type= mb_type_b_map[ mb_type ];
1338
            if(modb2) cbp= 0;
1339
            else{
1340
                s->dsp.clear_blocks(s->block[0]);
1341
                cbp= get_bits(&s->gb, 6);
1342
            }
1343

    
1344
            if ((!IS_DIRECT(mb_type)) && cbp) {
1345
                if(get_bits1(&s->gb)){
1346
                    ff_set_qscale(s, s->qscale + get_bits1(&s->gb)*4 - 2);
1347
                }
1348
            }
1349

    
1350
            if(!s->progressive_sequence){
1351
                if(cbp)
1352
                    s->interlaced_dct= get_bits1(&s->gb);
1353

    
1354
                if(!IS_DIRECT(mb_type) && get_bits1(&s->gb)){
1355
                    mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
1356
                    mb_type &= ~MB_TYPE_16x16;
1357

    
1358
                    if(USES_LIST(mb_type, 0)){
1359
                        s->field_select[0][0]= get_bits1(&s->gb);
1360
                        s->field_select[0][1]= get_bits1(&s->gb);
1361
                    }
1362
                    if(USES_LIST(mb_type, 1)){
1363
                        s->field_select[1][0]= get_bits1(&s->gb);
1364
                        s->field_select[1][1]= get_bits1(&s->gb);
1365
                    }
1366
                }
1367
            }
1368

    
1369
            s->mv_dir = 0;
1370
            if((mb_type & (MB_TYPE_DIRECT2|MB_TYPE_INTERLACED)) == 0){
1371
                s->mv_type= MV_TYPE_16X16;
1372

    
1373
                if(USES_LIST(mb_type, 0)){
1374
                    s->mv_dir = MV_DIR_FORWARD;
1375

    
1376
                    mx = h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
1377
                    my = h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
1378
                    s->last_mv[0][1][0]= s->last_mv[0][0][0]= s->mv[0][0][0] = mx;
1379
                    s->last_mv[0][1][1]= s->last_mv[0][0][1]= s->mv[0][0][1] = my;
1380
                }
1381

    
1382
                if(USES_LIST(mb_type, 1)){
1383
                    s->mv_dir |= MV_DIR_BACKWARD;
1384

    
1385
                    mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
1386
                    my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
1387
                    s->last_mv[1][1][0]= s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
1388
                    s->last_mv[1][1][1]= s->last_mv[1][0][1]= s->mv[1][0][1] = my;
1389
                }
1390
            }else if(!IS_DIRECT(mb_type)){
1391
                s->mv_type= MV_TYPE_FIELD;
1392

    
1393
                if(USES_LIST(mb_type, 0)){
1394
                    s->mv_dir = MV_DIR_FORWARD;
1395

    
1396
                    for(i=0; i<2; i++){
1397
                        mx = h263_decode_motion(s, s->last_mv[0][i][0]  , s->f_code);
1398
                        my = h263_decode_motion(s, s->last_mv[0][i][1]/2, s->f_code);
1399
                        s->last_mv[0][i][0]=  s->mv[0][i][0] = mx;
1400
                        s->last_mv[0][i][1]= (s->mv[0][i][1] = my)*2;
1401
                    }
1402
                }
1403

    
1404
                if(USES_LIST(mb_type, 1)){
1405
                    s->mv_dir |= MV_DIR_BACKWARD;
1406

    
1407
                    for(i=0; i<2; i++){
1408
                        mx = h263_decode_motion(s, s->last_mv[1][i][0]  , s->b_code);
1409
                        my = h263_decode_motion(s, s->last_mv[1][i][1]/2, s->b_code);
1410
                        s->last_mv[1][i][0]=  s->mv[1][i][0] = mx;
1411
                        s->last_mv[1][i][1]= (s->mv[1][i][1] = my)*2;
1412
                    }
1413
                }
1414
            }
1415
        }
1416

    
1417
        if(IS_DIRECT(mb_type)){
1418
            if(IS_SKIP(mb_type))
1419
                mx=my=0;
1420
            else{
1421
                mx = h263_decode_motion(s, 0, 1);
1422
                my = h263_decode_motion(s, 0, 1);
1423
            }
1424

    
1425
            s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
1426
            mb_type |= ff_mpeg4_set_direct_mv(s, mx, my);
1427
        }
1428
        s->current_picture.mb_type[xy]= mb_type;
1429
    } else { /* I-Frame */
1430
        do{
1431
            cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
1432
            if (cbpc < 0){
1433
                av_log(s->avctx, AV_LOG_ERROR, "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
1434
                return -1;
1435
            }
1436
        }while(cbpc == 8);
1437

    
1438
        dquant = cbpc & 4;
1439
        s->mb_intra = 1;
1440
intra:
1441
        s->ac_pred = get_bits1(&s->gb);
1442
        if(s->ac_pred)
1443
            s->current_picture.mb_type[xy]= MB_TYPE_INTRA | MB_TYPE_ACPRED;
1444
        else
1445
            s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
1446

    
1447
        cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
1448
        if(cbpy<0){
1449
            av_log(s->avctx, AV_LOG_ERROR, "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
1450
            return -1;
1451
        }
1452
        cbp = (cbpc & 3) | (cbpy << 2);
1453

    
1454
        s->use_intra_dc_vlc= s->qscale < s->intra_dc_threshold;
1455

    
1456
        if (dquant) {
1457
            ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
1458
        }
1459

    
1460
        if(!s->progressive_sequence)
1461
            s->interlaced_dct= get_bits1(&s->gb);
1462

    
1463
        s->dsp.clear_blocks(s->block[0]);
1464
        /* decode each block */
1465
        for (i = 0; i < 6; i++) {
1466
            if (mpeg4_decode_block(s, block[i], i, cbp&32, 1, 0) < 0)
1467
                return -1;
1468
            cbp+=cbp;
1469
        }
1470
        goto end;
1471
    }
1472

    
1473
    /* decode each block */
1474
    for (i = 0; i < 6; i++) {
1475
        if (mpeg4_decode_block(s, block[i], i, cbp&32, 0, 0) < 0)
1476
            return -1;
1477
        cbp+=cbp;
1478
    }
1479
end:
1480

    
1481
        /* per-MB end of slice check */
1482
    if(s->codec_id==CODEC_ID_MPEG4){
1483
        if(mpeg4_is_resync(s)){
1484
            const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
1485
            if(s->pict_type==FF_B_TYPE && s->next_picture.mbskip_table[xy + delta])
1486
                return SLICE_OK;
1487
            return SLICE_END;
1488
        }
1489
    }
1490

    
1491
    return SLICE_OK;
1492
}
1493

    
1494

    
1495
static int mpeg4_decode_gop_header(MpegEncContext * s, GetBitContext *gb){
1496
    int hours, minutes, seconds;
1497

    
1498
    if(!show_bits(gb, 18)){
1499
        av_log(s->avctx, AV_LOG_WARNING, "GOP header invalid\n");
1500
        return -1;
1501
    }
1502

    
1503
    hours= get_bits(gb, 5);
1504
    minutes= get_bits(gb, 6);
1505
    skip_bits1(gb);
1506
    seconds= get_bits(gb, 6);
1507

    
1508
    s->time_base= seconds + 60*(minutes + 60*hours);
1509

    
1510
    skip_bits1(gb);
1511
    skip_bits1(gb);
1512

    
1513
    return 0;
1514
}
1515

    
1516
static int decode_vol_header(MpegEncContext *s, GetBitContext *gb){
1517
    int width, height, vo_ver_id;
1518

    
1519
    /* vol header */
1520
    skip_bits(gb, 1); /* random access */
1521
    s->vo_type= get_bits(gb, 8);
1522
    if (get_bits1(gb) != 0) { /* is_ol_id */
1523
        vo_ver_id = get_bits(gb, 4); /* vo_ver_id */
1524
        skip_bits(gb, 3); /* vo_priority */
1525
    } else {
1526
        vo_ver_id = 1;
1527
    }
1528
    s->aspect_ratio_info= get_bits(gb, 4);
1529
    if(s->aspect_ratio_info == FF_ASPECT_EXTENDED){
1530
        s->avctx->sample_aspect_ratio.num= get_bits(gb, 8); // par_width
1531
        s->avctx->sample_aspect_ratio.den= get_bits(gb, 8); // par_height
1532
    }else{
1533
        s->avctx->sample_aspect_ratio= ff_h263_pixel_aspect[s->aspect_ratio_info];
1534
    }
1535

    
1536
    if ((s->vol_control_parameters=get_bits1(gb))) { /* vol control parameter */
1537
        int chroma_format= get_bits(gb, 2);
1538
        if(chroma_format!=CHROMA_420){
1539
            av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n");
1540
        }
1541
        s->low_delay= get_bits1(gb);
1542
        if(get_bits1(gb)){ /* vbv parameters */
1543
            get_bits(gb, 15);   /* first_half_bitrate */
1544
            skip_bits1(gb);     /* marker */
1545
            get_bits(gb, 15);   /* latter_half_bitrate */
1546
            skip_bits1(gb);     /* marker */
1547
            get_bits(gb, 15);   /* first_half_vbv_buffer_size */
1548
            skip_bits1(gb);     /* marker */
1549
            get_bits(gb, 3);    /* latter_half_vbv_buffer_size */
1550
            get_bits(gb, 11);   /* first_half_vbv_occupancy */
1551
            skip_bits1(gb);     /* marker */
1552
            get_bits(gb, 15);   /* latter_half_vbv_occupancy */
1553
            skip_bits1(gb);     /* marker */
1554
        }
1555
    }else{
1556
        // set low delay flag only once the smartest? low delay detection won't be overriden
1557
        if(s->picture_number==0)
1558
            s->low_delay=0;
1559
    }
1560

    
1561
    s->shape = get_bits(gb, 2); /* vol shape */
1562
    if(s->shape != RECT_SHAPE) av_log(s->avctx, AV_LOG_ERROR, "only rectangular vol supported\n");
1563
    if(s->shape == GRAY_SHAPE && vo_ver_id != 1){
1564
        av_log(s->avctx, AV_LOG_ERROR, "Gray shape not supported\n");
1565
        skip_bits(gb, 4);  //video_object_layer_shape_extension
1566
    }
1567

    
1568
    check_marker(gb, "before time_increment_resolution");
1569

    
1570
    s->avctx->time_base.den = get_bits(gb, 16);
1571
    if(!s->avctx->time_base.den){
1572
        av_log(s->avctx, AV_LOG_ERROR, "time_base.den==0\n");
1573
        s->avctx->time_base.num = 0;
1574
        return -1;
1575
    }
1576

    
1577
    s->time_increment_bits = av_log2(s->avctx->time_base.den - 1) + 1;
1578
    if (s->time_increment_bits < 1)
1579
        s->time_increment_bits = 1;
1580

    
1581
    check_marker(gb, "before fixed_vop_rate");
1582

    
1583
    if (get_bits1(gb) != 0) {   /* fixed_vop_rate  */
1584
        s->avctx->time_base.num = get_bits(gb, s->time_increment_bits);
1585
    }else
1586
        s->avctx->time_base.num = 1;
1587

    
1588
    s->t_frame=0;
1589

    
1590
    if (s->shape != BIN_ONLY_SHAPE) {
1591
        if (s->shape == RECT_SHAPE) {
1592
            skip_bits1(gb);   /* marker */
1593
            width = get_bits(gb, 13);
1594
            skip_bits1(gb);   /* marker */
1595
            height = get_bits(gb, 13);
1596
            skip_bits1(gb);   /* marker */
1597
            if(width && height && !(s->width && s->codec_tag == AV_RL32("MP4S"))){ /* they should be non zero but who knows ... */
1598
                s->width = width;
1599
                s->height = height;
1600
            }
1601
        }
1602

    
1603
        s->progressive_sequence=
1604
        s->progressive_frame= get_bits1(gb)^1;
1605
        s->interlaced_dct=0;
1606
        if(!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO))
1607
            av_log(s->avctx, AV_LOG_INFO, "MPEG4 OBMC not supported (very likely buggy encoder)\n");   /* OBMC Disable */
1608
        if (vo_ver_id == 1) {
1609
            s->vol_sprite_usage = get_bits1(gb); /* vol_sprite_usage */
1610
        } else {
1611
            s->vol_sprite_usage = get_bits(gb, 2); /* vol_sprite_usage */
1612
        }
1613
        if(s->vol_sprite_usage==STATIC_SPRITE) av_log(s->avctx, AV_LOG_ERROR, "Static Sprites not supported\n");
1614
        if(s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE){
1615
            if(s->vol_sprite_usage==STATIC_SPRITE){
1616
                s->sprite_width = get_bits(gb, 13);
1617
                skip_bits1(gb); /* marker */
1618
                s->sprite_height= get_bits(gb, 13);
1619
                skip_bits1(gb); /* marker */
1620
                s->sprite_left  = get_bits(gb, 13);
1621
                skip_bits1(gb); /* marker */
1622
                s->sprite_top   = get_bits(gb, 13);
1623
                skip_bits1(gb); /* marker */
1624
            }
1625
            s->num_sprite_warping_points= get_bits(gb, 6);
1626
            if(s->num_sprite_warping_points > 3){
1627
                av_log(s->avctx, AV_LOG_ERROR, "%d sprite_warping_points\n", s->num_sprite_warping_points);
1628
                s->num_sprite_warping_points= 0;
1629
                return -1;
1630
            }
1631
            s->sprite_warping_accuracy = get_bits(gb, 2);
1632
            s->sprite_brightness_change= get_bits1(gb);
1633
            if(s->vol_sprite_usage==STATIC_SPRITE)
1634
                s->low_latency_sprite= get_bits1(gb);
1635
        }
1636
        // FIXME sadct disable bit if verid!=1 && shape not rect
1637

    
1638
        if (get_bits1(gb) == 1) {   /* not_8_bit */
1639
            s->quant_precision = get_bits(gb, 4); /* quant_precision */
1640
            if(get_bits(gb, 4)!=8) av_log(s->avctx, AV_LOG_ERROR, "N-bit not supported\n"); /* bits_per_pixel */
1641
            if(s->quant_precision!=5) av_log(s->avctx, AV_LOG_ERROR, "quant precision %d\n", s->quant_precision);
1642
        } else {
1643
            s->quant_precision = 5;
1644
        }
1645

    
1646
        // FIXME a bunch of grayscale shape things
1647

    
1648
        if((s->mpeg_quant=get_bits1(gb))){ /* vol_quant_type */
1649
            int i, v;
1650

    
1651
            /* load default matrixes */
1652
            for(i=0; i<64; i++){
1653
                int j= s->dsp.idct_permutation[i];
1654
                v= ff_mpeg4_default_intra_matrix[i];
1655
                s->intra_matrix[j]= v;
1656
                s->chroma_intra_matrix[j]= v;
1657

    
1658
                v= ff_mpeg4_default_non_intra_matrix[i];
1659
                s->inter_matrix[j]= v;
1660
                s->chroma_inter_matrix[j]= v;
1661
            }
1662

    
1663
            /* load custom intra matrix */
1664
            if(get_bits1(gb)){
1665
                int last=0;
1666
                for(i=0; i<64; i++){
1667
                    int j;
1668
                    v= get_bits(gb, 8);
1669
                    if(v==0) break;
1670

    
1671
                    last= v;
1672
                    j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
1673
                    s->intra_matrix[j]= v;
1674
                    s->chroma_intra_matrix[j]= v;
1675
                }
1676

    
1677
                /* replicate last value */
1678
                for(; i<64; i++){
1679
                    int j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
1680
                    s->intra_matrix[j]= last;
1681
                    s->chroma_intra_matrix[j]= last;
1682
                }
1683
            }
1684

    
1685
            /* load custom non intra matrix */
1686
            if(get_bits1(gb)){
1687
                int last=0;
1688
                for(i=0; i<64; i++){
1689
                    int j;
1690
                    v= get_bits(gb, 8);
1691
                    if(v==0) break;
1692

    
1693
                    last= v;
1694
                    j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
1695
                    s->inter_matrix[j]= v;
1696
                    s->chroma_inter_matrix[j]= v;
1697
                }
1698

    
1699
                /* replicate last value */
1700
                for(; i<64; i++){
1701
                    int j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
1702
                    s->inter_matrix[j]= last;
1703
                    s->chroma_inter_matrix[j]= last;
1704
                }
1705
            }
1706

    
1707
            // FIXME a bunch of grayscale shape things
1708
        }
1709

    
1710
        if(vo_ver_id != 1)
1711
             s->quarter_sample= get_bits1(gb);
1712
        else s->quarter_sample=0;
1713

    
1714
        if(!get_bits1(gb)){
1715
            int pos= get_bits_count(gb);
1716
            int estimation_method= get_bits(gb, 2);
1717
            if(estimation_method<2){
1718
                if(!get_bits1(gb)){
1719
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //opaque
1720
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //transparent
1721
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //intra_cae
1722
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //inter_cae
1723
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //no_update
1724
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //upampling
1725
                }
1726
                if(!get_bits1(gb)){
1727
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //intra_blocks
1728
                    s->cplx_estimation_trash_p += 8*get_bits1(gb); //inter_blocks
1729
                    s->cplx_estimation_trash_p += 8*get_bits1(gb); //inter4v_blocks
1730
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //not coded blocks
1731
                }
1732
                if(!check_marker(gb, "in complexity estimation part 1")){
1733
                    skip_bits_long(gb, pos - get_bits_count(gb));
1734
                    goto no_cplx_est;
1735
                }
1736
                if(!get_bits1(gb)){
1737
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //dct_coeffs
1738
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //dct_lines
1739
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //vlc_syms
1740
                    s->cplx_estimation_trash_i += 4*get_bits1(gb); //vlc_bits
1741
                }
1742
                if(!get_bits1(gb)){
1743
                    s->cplx_estimation_trash_p += 8*get_bits1(gb); //apm
1744
                    s->cplx_estimation_trash_p += 8*get_bits1(gb); //npm
1745
                    s->cplx_estimation_trash_b += 8*get_bits1(gb); //interpolate_mc_q
1746
                    s->cplx_estimation_trash_p += 8*get_bits1(gb); //forwback_mc_q
1747
                    s->cplx_estimation_trash_p += 8*get_bits1(gb); //halfpel2
1748
                    s->cplx_estimation_trash_p += 8*get_bits1(gb); //halfpel4
1749
                }
1750
                if(!check_marker(gb, "in complexity estimation part 2")){
1751
                    skip_bits_long(gb, pos - get_bits_count(gb));
1752
                    goto no_cplx_est;
1753
                }
1754
                if(estimation_method==1){
1755
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //sadct
1756
                    s->cplx_estimation_trash_p += 8*get_bits1(gb); //qpel
1757
                }
1758
            }else
1759
                av_log(s->avctx, AV_LOG_ERROR, "Invalid Complexity estimation method %d\n", estimation_method);
1760
        }else{
1761
no_cplx_est:
1762
            s->cplx_estimation_trash_i=
1763
            s->cplx_estimation_trash_p=
1764
            s->cplx_estimation_trash_b= 0;
1765
        }
1766

    
1767
        s->resync_marker= !get_bits1(gb); /* resync_marker_disabled */
1768

    
1769
        s->data_partitioning= get_bits1(gb);
1770
        if(s->data_partitioning){
1771
            s->rvlc= get_bits1(gb);
1772
        }
1773

    
1774
        if(vo_ver_id != 1) {
1775
            s->new_pred= get_bits1(gb);
1776
            if(s->new_pred){
1777
                av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n");
1778
                skip_bits(gb, 2); /* requested upstream message type */
1779
                skip_bits1(gb); /* newpred segment type */
1780
            }
1781
            s->reduced_res_vop= get_bits1(gb);
1782
            if(s->reduced_res_vop) av_log(s->avctx, AV_LOG_ERROR, "reduced resolution VOP not supported\n");
1783
        }
1784
        else{
1785
            s->new_pred=0;
1786
            s->reduced_res_vop= 0;
1787
        }
1788

    
1789
        s->scalability= get_bits1(gb);
1790

    
1791
        if (s->scalability) {
1792
            GetBitContext bak= *gb;
1793
            int ref_layer_id;
1794
            int ref_layer_sampling_dir;
1795
            int h_sampling_factor_n;
1796
            int h_sampling_factor_m;
1797
            int v_sampling_factor_n;
1798
            int v_sampling_factor_m;
1799

    
1800
            s->hierachy_type= get_bits1(gb);
1801
            ref_layer_id= get_bits(gb, 4);
1802
            ref_layer_sampling_dir= get_bits1(gb);
1803
            h_sampling_factor_n= get_bits(gb, 5);
1804
            h_sampling_factor_m= get_bits(gb, 5);
1805
            v_sampling_factor_n= get_bits(gb, 5);
1806
            v_sampling_factor_m= get_bits(gb, 5);
1807
            s->enhancement_type= get_bits1(gb);
1808

    
1809
            if(   h_sampling_factor_n==0 || h_sampling_factor_m==0
1810
               || v_sampling_factor_n==0 || v_sampling_factor_m==0){
1811
                /* illegal scalability header (VERY broken encoder),
1812
                 * trying to workaround */
1813
                s->scalability=0;
1814
                *gb= bak;
1815
            }else
1816
                av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n");
1817

    
1818
            // bin shape stuff FIXME
1819
        }
1820
    }
1821
    return 0;
1822
}
1823

    
1824
/**
1825
 * decodes the user data stuff in the header.
1826
 * Also initializes divx/xvid/lavc_version/build.
1827
 */
1828
static int decode_user_data(MpegEncContext *s, GetBitContext *gb){
1829
    char buf[256];
1830
    int i;
1831
    int e;
1832
    int ver = 0, build = 0, ver2 = 0, ver3 = 0;
1833
    char last;
1834

    
1835
    for(i=0; i<255 && get_bits_count(gb) < gb->size_in_bits; i++){
1836
        if(show_bits(gb, 23) == 0) break;
1837
        buf[i]= get_bits(gb, 8);
1838
    }
1839
    buf[i]=0;
1840

    
1841
    /* divx detection */
1842
    e=sscanf(buf, "DivX%dBuild%d%c", &ver, &build, &last);
1843
    if(e<2)
1844
        e=sscanf(buf, "DivX%db%d%c", &ver, &build, &last);
1845
    if(e>=2){
1846
        s->divx_version= ver;
1847
        s->divx_build= build;
1848
        s->divx_packed= e==3 && last=='p';
1849
        if(s->divx_packed && !s->showed_packed_warning) {
1850
            av_log(s->avctx, AV_LOG_WARNING, "Invalid and inefficient vfw-avi packed B frames detected\n");
1851
            s->showed_packed_warning=1;
1852
        }
1853
    }
1854

    
1855
    /* ffmpeg detection */
1856
    e=sscanf(buf, "FFmpe%*[^b]b%d", &build)+3;
1857
    if(e!=4)
1858
        e=sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build);
1859
    if(e!=4){
1860
        e=sscanf(buf, "Lavc%d.%d.%d", &ver, &ver2, &ver3)+1;
1861
        if (e>1)
1862
            build= (ver<<16) + (ver2<<8) + ver3;
1863
    }
1864
    if(e!=4){
1865
        if(strcmp(buf, "ffmpeg")==0){
1866
            s->lavc_build= 4600;
1867
        }
1868
    }
1869
    if(e==4){
1870
        s->lavc_build= build;
1871
    }
1872

    
1873
    /* Xvid detection */
1874
    e=sscanf(buf, "XviD%d", &build);
1875
    if(e==1){
1876
        s->xvid_build= build;
1877
    }
1878

    
1879
    return 0;
1880
}
1881

    
1882
static int decode_vop_header(MpegEncContext *s, GetBitContext *gb){
1883
    int time_incr, time_increment;
1884

    
1885
    s->pict_type = get_bits(gb, 2) + FF_I_TYPE;        /* pict type: I = 0 , P = 1 */
1886
    if(s->pict_type==FF_B_TYPE && s->low_delay && s->vol_control_parameters==0 && !(s->flags & CODEC_FLAG_LOW_DELAY)){
1887
        av_log(s->avctx, AV_LOG_ERROR, "low_delay flag incorrectly, clearing it\n");
1888
        s->low_delay=0;
1889
    }
1890

    
1891
    s->partitioned_frame= s->data_partitioning && s->pict_type!=FF_B_TYPE;
1892
    if(s->partitioned_frame)
1893
        s->decode_mb= mpeg4_decode_partitioned_mb;
1894
    else
1895
        s->decode_mb= mpeg4_decode_mb;
1896

    
1897
    time_incr=0;
1898
    while (get_bits1(gb) != 0)
1899
        time_incr++;
1900

    
1901
    check_marker(gb, "before time_increment");
1902

    
1903
    if(s->time_increment_bits==0 || !(show_bits(gb, s->time_increment_bits+1)&1)){
1904
        av_log(s->avctx, AV_LOG_ERROR, "hmm, seems the headers are not complete, trying to guess time_increment_bits\n");
1905

    
1906
        for(s->time_increment_bits=1 ;s->time_increment_bits<16; s->time_increment_bits++){
1907
            if (    s->pict_type == FF_P_TYPE
1908
                || (s->pict_type == FF_S_TYPE && s->vol_sprite_usage==GMC_SPRITE)) {
1909
                if((show_bits(gb, s->time_increment_bits+6)&0x37) == 0x30) break;
1910
            }else
1911
                if((show_bits(gb, s->time_increment_bits+5)&0x1F) == 0x18) break;
1912
        }
1913

    
1914
        av_log(s->avctx, AV_LOG_ERROR, "my guess is %d bits ;)\n",s->time_increment_bits);
1915
    }
1916

    
1917
    if(IS_3IV1) time_increment= get_bits1(gb); //FIXME investigate further
1918
    else time_increment= get_bits(gb, s->time_increment_bits);
1919

    
1920
    if(s->pict_type!=FF_B_TYPE){
1921
        s->last_time_base= s->time_base;
1922
        s->time_base+= time_incr;
1923
        s->time= s->time_base*s->avctx->time_base.den + time_increment;
1924
        if(s->workaround_bugs&FF_BUG_UMP4){
1925
            if(s->time < s->last_non_b_time){
1926
                /* header is not mpeg-4-compatible, broken encoder,
1927
                 * trying to workaround */
1928
                s->time_base++;
1929
                s->time+= s->avctx->time_base.den;
1930
            }
1931
        }
1932
        s->pp_time= s->time - s->last_non_b_time;
1933
        s->last_non_b_time= s->time;
1934
    }else{
1935
        s->time= (s->last_time_base + time_incr)*s->avctx->time_base.den + time_increment;
1936
        s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
1937
        if(s->pp_time <=s->pb_time || s->pp_time <= s->pp_time - s->pb_time || s->pp_time<=0){
1938
            /* messed up order, maybe after seeking? skipping current b-frame */
1939
            return FRAME_SKIPPED;
1940
        }
1941
        ff_mpeg4_init_direct_mv(s);
1942

    
1943
        if(s->t_frame==0) s->t_frame= s->pb_time;
1944
        if(s->t_frame==0) s->t_frame=1; // 1/0 protection
1945
        s->pp_field_time= (  ROUNDED_DIV(s->last_non_b_time, s->t_frame)
1946
                           - ROUNDED_DIV(s->last_non_b_time - s->pp_time, s->t_frame))*2;
1947
        s->pb_field_time= (  ROUNDED_DIV(s->time, s->t_frame)
1948
                           - ROUNDED_DIV(s->last_non_b_time - s->pp_time, s->t_frame))*2;
1949
        if(!s->progressive_sequence){
1950
            if(s->pp_field_time <= s->pb_field_time || s->pb_field_time <= 1)
1951
                return FRAME_SKIPPED;
1952
        }
1953
    }
1954

    
1955
    if(s->avctx->time_base.num)
1956
        s->current_picture_ptr->pts= (s->time + s->avctx->time_base.num/2) / s->avctx->time_base.num;
1957
    else
1958
        s->current_picture_ptr->pts= AV_NOPTS_VALUE;
1959
    if(s->avctx->debug&FF_DEBUG_PTS)
1960
        av_log(s->avctx, AV_LOG_DEBUG, "MPEG4 PTS: %"PRId64"\n", s->current_picture_ptr->pts);
1961

    
1962
    check_marker(gb, "before vop_coded");
1963

    
1964
    /* vop coded */
1965
    if (get_bits1(gb) != 1){
1966
        if(s->avctx->debug&FF_DEBUG_PICT_INFO)
1967
            av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n");
1968
        return FRAME_SKIPPED;
1969
    }
1970
    if (s->shape != BIN_ONLY_SHAPE && ( s->pict_type == FF_P_TYPE
1971
                          || (s->pict_type == FF_S_TYPE && s->vol_sprite_usage==GMC_SPRITE))) {
1972
        /* rounding type for motion estimation */
1973
        s->no_rounding = get_bits1(gb);
1974
    } else {
1975
        s->no_rounding = 0;
1976
    }
1977
//FIXME reduced res stuff
1978

    
1979
     if (s->shape != RECT_SHAPE) {
1980
         if (s->vol_sprite_usage != 1 || s->pict_type != FF_I_TYPE) {
1981
             int width, height, hor_spat_ref, ver_spat_ref;
1982

    
1983
             width = get_bits(gb, 13);
1984
             skip_bits1(gb);   /* marker */
1985
             height = get_bits(gb, 13);
1986
             skip_bits1(gb);   /* marker */
1987
             hor_spat_ref = get_bits(gb, 13); /* hor_spat_ref */
1988
             skip_bits1(gb);   /* marker */
1989
             ver_spat_ref = get_bits(gb, 13); /* ver_spat_ref */
1990
         }
1991
         skip_bits1(gb); /* change_CR_disable */
1992

    
1993
         if (get_bits1(gb) != 0) {
1994
             skip_bits(gb, 8); /* constant_alpha_value */
1995
         }
1996
     }
1997
//FIXME complexity estimation stuff
1998

    
1999
     if (s->shape != BIN_ONLY_SHAPE) {
2000
         skip_bits_long(gb, s->cplx_estimation_trash_i);
2001
         if(s->pict_type != FF_I_TYPE)
2002
            skip_bits_long(gb, s->cplx_estimation_trash_p);
2003
         if(s->pict_type == FF_B_TYPE)
2004
            skip_bits_long(gb, s->cplx_estimation_trash_b);
2005

    
2006
         s->intra_dc_threshold= mpeg4_dc_threshold[ get_bits(gb, 3) ];
2007
         if(!s->progressive_sequence){
2008
             s->top_field_first= get_bits1(gb);
2009
             s->alternate_scan= get_bits1(gb);
2010
         }else
2011
             s->alternate_scan= 0;
2012
     }
2013

    
2014
     if(s->alternate_scan){
2015
         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_alternate_vertical_scan);
2016
         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_alternate_vertical_scan);
2017
         ff_init_scantable(s->dsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
2018
         ff_init_scantable(s->dsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
2019
     } else{
2020
         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_zigzag_direct);
2021
         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_zigzag_direct);
2022
         ff_init_scantable(s->dsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
2023
         ff_init_scantable(s->dsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
2024
     }
2025

    
2026
     if(s->pict_type == FF_S_TYPE && (s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE)){
2027
         mpeg4_decode_sprite_trajectory(s, gb);
2028
         if(s->sprite_brightness_change) av_log(s->avctx, AV_LOG_ERROR, "sprite_brightness_change not supported\n");
2029
         if(s->vol_sprite_usage==STATIC_SPRITE) av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n");
2030
     }
2031

    
2032
     if (s->shape != BIN_ONLY_SHAPE) {
2033
         s->chroma_qscale= s->qscale = get_bits(gb, s->quant_precision);
2034
         if(s->qscale==0){
2035
             av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG4 header (qscale=0)\n");
2036
             return -1; // makes no sense to continue, as there is nothing left from the image then
2037
         }
2038

    
2039
         if (s->pict_type != FF_I_TYPE) {
2040
             s->f_code = get_bits(gb, 3);       /* fcode_for */
2041
             if(s->f_code==0){
2042
                 av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG4 header (f_code=0)\n");
2043
                 return -1; // makes no sense to continue, as the MV decoding will break very quickly
2044
             }
2045
         }else
2046
             s->f_code=1;
2047

    
2048
         if (s->pict_type == FF_B_TYPE) {
2049
             s->b_code = get_bits(gb, 3);
2050
         }else
2051
             s->b_code=1;
2052

    
2053
         if(s->avctx->debug&FF_DEBUG_PICT_INFO){
2054
             av_log(s->avctx, AV_LOG_DEBUG, "qp:%d fc:%d,%d %s size:%d pro:%d alt:%d top:%d %spel part:%d resync:%d w:%d a:%d rnd:%d vot:%d%s dc:%d ce:%d/%d/%d\n",
2055
                 s->qscale, s->f_code, s->b_code,
2056
                 s->pict_type == FF_I_TYPE ? "I" : (s->pict_type == FF_P_TYPE ? "P" : (s->pict_type == FF_B_TYPE ? "B" : "S")),
2057
                 gb->size_in_bits,s->progressive_sequence, s->alternate_scan, s->top_field_first,
2058
                 s->quarter_sample ? "q" : "h", s->data_partitioning, s->resync_marker, s->num_sprite_warping_points,
2059
                 s->sprite_warping_accuracy, 1-s->no_rounding, s->vo_type, s->vol_control_parameters ? " VOLC" : " ", s->intra_dc_threshold, s->cplx_estimation_trash_i, s->cplx_estimation_trash_p, s->cplx_estimation_trash_b);
2060
         }
2061

    
2062
         if(!s->scalability){
2063
             if (s->shape!=RECT_SHAPE && s->pict_type!=FF_I_TYPE) {
2064
                 skip_bits1(gb); // vop shape coding type
2065
             }
2066
         }else{
2067
             if(s->enhancement_type){
2068
                 int load_backward_shape= get_bits1(gb);
2069
                 if(load_backward_shape){
2070
                     av_log(s->avctx, AV_LOG_ERROR, "load backward shape isn't supported\n");
2071
                 }
2072
             }
2073
             skip_bits(gb, 2); //ref_select_code
2074
         }
2075
     }
2076
     /* detect buggy encoders which don't set the low_delay flag (divx4/xvid/opendivx)*/
2077
     // note we cannot detect divx5 without b-frames easily (although it's buggy too)
2078
     if(s->vo_type==0 && s->vol_control_parameters==0 && s->divx_version==-1 && s->picture_number==0){
2079
         av_log(s->avctx, AV_LOG_WARNING, "looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n");
2080
         s->low_delay=1;
2081
     }
2082

    
2083
     s->picture_number++; // better than pic number==0 always ;)
2084

    
2085
     s->y_dc_scale_table= ff_mpeg4_y_dc_scale_table; //FIXME add short header support
2086
     s->c_dc_scale_table= ff_mpeg4_c_dc_scale_table;
2087

    
2088
     if(s->workaround_bugs&FF_BUG_EDGE){
2089
         s->h_edge_pos= s->width;
2090
         s->v_edge_pos= s->height;
2091
     }
2092
     return 0;
2093
}
2094

    
2095
/**
2096
 * decode mpeg4 headers
2097
 * @return <0 if no VOP found (or a damaged one)
2098
 *         FRAME_SKIPPED if a not coded VOP is found
2099
 *         0 if a VOP is found
2100
 */
2101
int ff_mpeg4_decode_picture_header(MpegEncContext * s, GetBitContext *gb)
2102
{
2103
    int startcode, v;
2104

    
2105
    /* search next start code */
2106
    align_get_bits(gb);
2107

    
2108
    if(s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630){
2109
        skip_bits(gb, 24);
2110
        if(get_bits(gb, 8) == 0xF0)
2111
            goto end;
2112
    }
2113

    
2114
    startcode = 0xff;
2115
    for(;;) {
2116
        if(get_bits_count(gb) >= gb->size_in_bits){
2117
            if(gb->size_in_bits==8 && (s->divx_version>=0 || s->xvid_build>=0)){
2118
                av_log(s->avctx, AV_LOG_WARNING, "frame skip %d\n", gb->size_in_bits);
2119
                return FRAME_SKIPPED; //divx bug
2120
            }else
2121
                return -1; //end of stream
2122
        }
2123

    
2124
        /* use the bits after the test */
2125
        v = get_bits(gb, 8);
2126
        startcode = ((startcode << 8) | v) & 0xffffffff;
2127

    
2128
        if((startcode&0xFFFFFF00) != 0x100)
2129
            continue; //no startcode
2130

    
2131
        if(s->avctx->debug&FF_DEBUG_STARTCODE){
2132
            av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode);
2133
            if     (startcode<=0x11F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start");
2134
            else if(startcode<=0x12F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start");
2135
            else if(startcode<=0x13F) av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
2136
            else if(startcode<=0x15F) av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start");
2137
            else if(startcode<=0x1AF) av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
2138
            else if(startcode==0x1B0) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start");
2139
            else if(startcode==0x1B1) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End");
2140
            else if(startcode==0x1B2) av_log(s->avctx, AV_LOG_DEBUG, "User Data");
2141
            else if(startcode==0x1B3) av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start");
2142
            else if(startcode==0x1B4) av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error");
2143
            else if(startcode==0x1B5) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start");
2144
            else if(startcode==0x1B6) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start");
2145
            else if(startcode==0x1B7) av_log(s->avctx, AV_LOG_DEBUG, "slice start");
2146
            else if(startcode==0x1B8) av_log(s->avctx, AV_LOG_DEBUG, "extension start");
2147
            else if(startcode==0x1B9) av_log(s->avctx, AV_LOG_DEBUG, "fgs start");
2148
            else if(startcode==0x1BA) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start");
2149
            else if(startcode==0x1BB) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start");
2150
            else if(startcode==0x1BC) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start");
2151
            else if(startcode==0x1BD) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start");
2152
            else if(startcode==0x1BE) av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start");
2153
            else if(startcode==0x1BF) av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start");
2154
            else if(startcode==0x1C0) av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start");
2155
            else if(startcode==0x1C1) av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start");
2156
            else if(startcode==0x1C2) av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start");
2157
            else if(startcode==0x1C3) av_log(s->avctx, AV_LOG_DEBUG, "stuffing start");
2158
            else if(startcode<=0x1C5) av_log(s->avctx, AV_LOG_DEBUG, "reserved");
2159
            else if(startcode<=0x1FF) av_log(s->avctx, AV_LOG_DEBUG, "System start");
2160
            av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb));
2161
        }
2162

    
2163
        if(startcode >= 0x120 && startcode <= 0x12F){
2164
            if(decode_vol_header(s, gb) < 0)
2165
                return -1;
2166
        }
2167
        else if(startcode == USER_DATA_STARTCODE){
2168
            decode_user_data(s, gb);
2169
        }
2170
        else if(startcode == GOP_STARTCODE){
2171
            mpeg4_decode_gop_header(s, gb);
2172
        }
2173
        else if(startcode == VOP_STARTCODE){
2174
            break;
2175
        }
2176

    
2177
        align_get_bits(gb);
2178
        startcode = 0xff;
2179
    }
2180
end:
2181
    if(s->flags& CODEC_FLAG_LOW_DELAY)
2182
        s->low_delay=1;
2183
    s->avctx->has_b_frames= !s->low_delay;
2184
    return decode_vop_header(s, gb);
2185
}
2186

    
2187
static av_cold int decode_init(AVCodecContext *avctx)
2188
{
2189
    MpegEncContext *s = avctx->priv_data;
2190
    int ret;
2191
    static int done = 0;
2192

    
2193
    s->divx_version=
2194
    s->divx_build=
2195
    s->xvid_build=
2196
    s->lavc_build= -1;
2197

    
2198
    if((ret=ff_h263_decode_init(avctx)) < 0)
2199
        return ret;
2200

    
2201
    if (!done) {
2202
        done = 1;
2203

    
2204
        init_rl(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
2205
        init_rl(&rvlc_rl_inter, ff_mpeg4_static_rl_table_store[1]);
2206
        init_rl(&rvlc_rl_intra, ff_mpeg4_static_rl_table_store[2]);
2207
        INIT_VLC_RL(ff_mpeg4_rl_intra, 554);
2208
        INIT_VLC_RL(rvlc_rl_inter, 1072);
2209
        INIT_VLC_RL(rvlc_rl_intra, 1072);
2210
        INIT_VLC_STATIC(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
2211
                 &ff_mpeg4_DCtab_lum[0][1], 2, 1,
2212
                 &ff_mpeg4_DCtab_lum[0][0], 2, 1, 512);
2213
        INIT_VLC_STATIC(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
2214
                 &ff_mpeg4_DCtab_chrom[0][1], 2, 1,
2215
                 &ff_mpeg4_DCtab_chrom[0][0], 2, 1, 512);
2216
        INIT_VLC_STATIC(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
2217
                 &sprite_trajectory_tab[0][1], 4, 2,
2218
                 &sprite_trajectory_tab[0][0], 4, 2, 128);
2219
        INIT_VLC_STATIC(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
2220
                 &mb_type_b_tab[0][1], 2, 1,
2221
                 &mb_type_b_tab[0][0], 2, 1, 16);
2222
    }
2223

    
2224
    s->h263_pred = 1;
2225
    s->low_delay = 0; //default, might be overriden in the vol header during header parsing
2226
    s->decode_mb= mpeg4_decode_mb;
2227
    s->time_increment_bits = 4; /* default value for broken headers */
2228
    avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
2229

    
2230
    return 0;
2231
}
2232

    
2233
AVCodec ff_mpeg4_decoder = {
2234
    "mpeg4",
2235
    AVMEDIA_TYPE_VIDEO,
2236
    CODEC_ID_MPEG4,
2237
    sizeof(MpegEncContext),
2238
    decode_init,
2239
    NULL,
2240
    ff_h263_decode_end,
2241
    ff_h263_decode_frame,
2242
    CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY,
2243
    .flush= ff_mpeg_flush,
2244
    .max_lowres= 3,
2245
    .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2"),
2246
    .pix_fmts= ff_hwaccel_pixfmt_list_420,
2247
};
2248

    
2249

    
2250
#if CONFIG_MPEG4_VDPAU_DECODER
2251
AVCodec ff_mpeg4_vdpau_decoder = {
2252
    "mpeg4_vdpau",
2253
    AVMEDIA_TYPE_VIDEO,
2254
    CODEC_ID_MPEG4,
2255
    sizeof(MpegEncContext),
2256
    decode_init,
2257
    NULL,
2258
    ff_h263_decode_end,
2259
    ff_h263_decode_frame,
2260
    CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
2261
    .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 (VDPAU)"),
2262
    .pix_fmts= (const enum PixelFormat[]){PIX_FMT_VDPAU_MPEG4, PIX_FMT_NONE},
2263
};
2264
#endif