Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpeg4videodec.c @ d375c104

History | View | Annotate | Download (85.2 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
#include "thread.h"
27

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

    
36

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

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

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

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

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

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

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

    
106
}
107

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

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

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

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

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

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

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

    
146
            s->gb= gb;
147

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
371
    mb_num= get_bits(&s->gb, mb_num_bits);
372
    if(mb_num>=s->mb_num){
373
        av_log(s->avctx, AV_LOG_ERROR, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
374
        return -1;
375
    }
376
    if(s->pict_type == FF_B_TYPE){
377
        int mb_x = 0, mb_y = 0;
378

    
379
        while(s->next_picture.mbskip_table[ s->mb_index2xy[ mb_num ] ]) {
380
            if (!mb_x) ff_thread_await_progress((AVFrame*)s->next_picture_ptr, mb_y++, 0);
381
            mb_num++;
382
            if (++mb_x == s->mb_width) mb_x = 0;
383
        }
384
        if(mb_num >= s->mb_num) return -1; // slice contains just skipped MBs which where already decoded
385
    }
386

    
387
    s->mb_x= mb_num % s->mb_width;
388
    s->mb_y= mb_num / s->mb_width;
389

    
390
    if(s->shape != BIN_ONLY_SHAPE){
391
        int qscale= get_bits(&s->gb, s->quant_precision);
392
        if(qscale)
393
            s->chroma_qscale=s->qscale= qscale;
394
    }
395

    
396
    if(s->shape == RECT_SHAPE){
397
        header_extension= get_bits1(&s->gb);
398
    }
399
    if(header_extension){
400
        int time_increment;
401
        int time_incr=0;
402

    
403
        while (get_bits1(&s->gb) != 0)
404
            time_incr++;
405

    
406
        check_marker(&s->gb, "before time_increment in video packed header");
407
        time_increment= get_bits(&s->gb, s->time_increment_bits);
408
        check_marker(&s->gb, "before vop_coding_type in video packed header");
409

    
410
        skip_bits(&s->gb, 2); /* vop coding type */
411
        //FIXME not rect stuff here
412

    
413
        if(s->shape != BIN_ONLY_SHAPE){
414
            skip_bits(&s->gb, 3); /* intra dc vlc threshold */
415
//FIXME don't just ignore everything
416
            if(s->pict_type == FF_S_TYPE && s->vol_sprite_usage==GMC_SPRITE){
417
                mpeg4_decode_sprite_trajectory(s, &s->gb);
418
                av_log(s->avctx, AV_LOG_ERROR, "untested\n");
419
            }
420

    
421
            //FIXME reduced res stuff here
422

    
423
            if (s->pict_type != FF_I_TYPE) {
424
                int f_code = get_bits(&s->gb, 3);       /* fcode_for */
425
                if(f_code==0){
426
                    av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (f_code=0)\n");
427
                }
428
            }
429
            if (s->pict_type == FF_B_TYPE) {
430
                int b_code = get_bits(&s->gb, 3);
431
                if(b_code==0){
432
                    av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (b_code=0)\n");
433
                }
434
            }
435
        }
436
    }
437
    //FIXME new-pred stuff
438

    
439
    return 0;
440
}
441

    
442
/**
443
 * gets the average motion vector for a GMC MB.
444
 * @param n either 0 for the x component or 1 for y
445
 * @return the average MV for a GMC MB
446
 */
447
static inline int get_amv(MpegEncContext *s, int n){
448
    int x, y, mb_v, sum, dx, dy, shift;
449
    int len = 1 << (s->f_code + 4);
450
    const int a= s->sprite_warping_accuracy;
451

    
452
    if(s->workaround_bugs & FF_BUG_AMV)
453
        len >>= s->quarter_sample;
454

    
455
    if(s->real_sprite_warping_points==1){
456
        if(s->divx_version==500 && s->divx_build==413)
457
            sum= s->sprite_offset[0][n] / (1<<(a - s->quarter_sample));
458
        else
459
            sum= RSHIFT(s->sprite_offset[0][n]<<s->quarter_sample, a);
460
    }else{
461
        dx= s->sprite_delta[n][0];
462
        dy= s->sprite_delta[n][1];
463
        shift= s->sprite_shift[0];
464
        if(n) dy -= 1<<(shift + a + 1);
465
        else  dx -= 1<<(shift + a + 1);
466
        mb_v= s->sprite_offset[0][n] + dx*s->mb_x*16 + dy*s->mb_y*16;
467

    
468
        sum=0;
469
        for(y=0; y<16; y++){
470
            int v;
471

    
472
            v= mb_v + dy*y;
473
            //XXX FIXME optimize
474
            for(x=0; x<16; x++){
475
                sum+= v>>shift;
476
                v+= dx;
477
            }
478
        }
479
        sum= RSHIFT(sum, a+8-s->quarter_sample);
480
    }
481

    
482
    if      (sum < -len) sum= -len;
483
    else if (sum >= len) sum= len-1;
484

    
485
    return sum;
486
}
487

    
488
/**
489
 * decodes the dc value.
490
 * @param n block index (0-3 are luma, 4-5 are chroma)
491
 * @param dir_ptr the prediction direction will be stored here
492
 * @return the quantized dc
493
 */
494
static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr)
495
{
496
    int level, code;
497

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

    
522
        if (code > 8){
523
            if(get_bits1(&s->gb)==0){ /* marker */
524
                if(s->error_recognition>=2){
525
                    av_log(s->avctx, AV_LOG_ERROR, "dc marker bit missing\n");
526
                    return -1;
527
                }
528
            }
529
        }
530
    }
531

    
532
    return ff_mpeg4_pred_dc(s, n, level, dir_ptr, 0);
533
}
534

    
535
/**
536
 * decodes first partition.
537
 * @return number of MBs decoded or <0 if an error occurred
538
 */
539
static int mpeg4_decode_partition_a(MpegEncContext *s){
540
    int mb_num;
541
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
542

    
543
    /* decode first partition */
544
    mb_num=0;
545
    s->first_slice_line=1;
546
    for(; s->mb_y<s->mb_height; s->mb_y++){
547
        ff_init_block_index(s);
548
        for(; s->mb_x<s->mb_width; s->mb_x++){
549
            const int xy= s->mb_x + s->mb_y*s->mb_stride;
550
            int cbpc;
551
            int dir=0;
552

    
553
            mb_num++;
554
            ff_update_block_index(s);
555
            if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
556
                s->first_slice_line=0;
557

    
558
            if(s->pict_type==FF_I_TYPE){
559
                int i;
560

    
561
                do{
562
                    if(show_bits_long(&s->gb, 19)==DC_MARKER){
563
                        return mb_num-1;
564
                    }
565

    
566
                    cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
567
                    if (cbpc < 0){
568
                        av_log(s->avctx, AV_LOG_ERROR, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
569
                        return -1;
570
                    }
571
                }while(cbpc == 8);
572

    
573
                s->cbp_table[xy]= cbpc & 3;
574
                s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
575
                s->mb_intra = 1;
576

    
577
                if(cbpc & 4) {
578
                    ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
579
                }
580
                s->current_picture.qscale_table[xy]= s->qscale;
581

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

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

    
620
                    if(s->mbintra_table[xy])
621
                        ff_clean_intra_table_entries(s);
622
                    continue;
623
                }
624

    
625
                cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
626
                if (cbpc < 0){
627
                    av_log(s->avctx, AV_LOG_ERROR, "cbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
628
                    return -1;
629
                }
630
                if(cbpc == 20)
631
                    goto try_again;
632

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

    
635
                s->mb_intra = ((cbpc & 4) != 0);
636

    
637
                if(s->mb_intra){
638
                    s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
639
                    s->mbintra_table[xy]= 1;
640
                    mot_val[0       ]= mot_val[2       ]=
641
                    mot_val[0+stride]= mot_val[2+stride]= 0;
642
                    mot_val[1       ]= mot_val[3       ]=
643
                    mot_val[1+stride]= mot_val[3+stride]= 0;
644
                }else{
645
                    if(s->mbintra_table[xy])
646
                        ff_clean_intra_table_entries(s);
647

    
648
                    if(s->pict_type==FF_S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
649
                        s->mcsel= get_bits1(&s->gb);
650
                    else s->mcsel= 0;
651

    
652
                    if ((cbpc & 16) == 0) {
653
                        /* 16x16 motion prediction */
654

    
655
                        h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
656
                        if(!s->mcsel){
657
                            mx = h263_decode_motion(s, pred_x, s->f_code);
658
                            if (mx >= 0xffff)
659
                                return -1;
660

    
661
                            my = h263_decode_motion(s, pred_y, s->f_code);
662
                            if (my >= 0xffff)
663
                                return -1;
664
                            s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0;
665
                        } else {
666
                            mx = get_amv(s, 0);
667
                            my = get_amv(s, 1);
668
                            s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0;
669
                        }
670

    
671
                        mot_val[0       ]= mot_val[2       ] =
672
                        mot_val[0+stride]= mot_val[2+stride]= mx;
673
                        mot_val[1       ]= mot_val[3       ]=
674
                        mot_val[1+stride]= mot_val[3+stride]= my;
675
                    } else {
676
                        int i;
677
                        s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0;
678
                        for(i=0;i<4;i++) {
679
                            int16_t *mot_val= h263_pred_motion(s, i, 0, &pred_x, &pred_y);
680
                            mx = h263_decode_motion(s, pred_x, s->f_code);
681
                            if (mx >= 0xffff)
682
                                return -1;
683

    
684
                            my = h263_decode_motion(s, pred_y, s->f_code);
685
                            if (my >= 0xffff)
686
                                return -1;
687
                            mot_val[0] = mx;
688
                            mot_val[1] = my;
689
                        }
690
                    }
691
                }
692
            }
693
        }
694
        s->mb_x= 0;
695
    }
696

    
697
    return mb_num;
698
}
699

    
700
/**
701
 * decode second partition.
702
 * @return <0 if an error occurred
703
 */
704
static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count){
705
    int mb_num=0;
706
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
707

    
708
    s->mb_x= s->resync_mb_x;
709
    s->first_slice_line=1;
710
    for(s->mb_y= s->resync_mb_y; mb_num < mb_count; s->mb_y++){
711
        ff_init_block_index(s);
712
        for(; mb_num < mb_count && s->mb_x<s->mb_width; s->mb_x++){
713
            const int xy= s->mb_x + s->mb_y*s->mb_stride;
714

    
715
            mb_num++;
716
            ff_update_block_index(s);
717
            if(s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y+1)
718
                s->first_slice_line=0;
719

    
720
            if(s->pict_type==FF_I_TYPE){
721
                int ac_pred= get_bits1(&s->gb);
722
                int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
723
                if(cbpy<0){
724
                    av_log(s->avctx, AV_LOG_ERROR, "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
725
                    return -1;
726
                }
727

    
728
                s->cbp_table[xy]|= cbpy<<2;
729
                s->current_picture.mb_type[xy] |= ac_pred*MB_TYPE_ACPRED;
730
            }else{ /* P || S_TYPE */
731
                if(IS_INTRA(s->current_picture.mb_type[xy])){
732
                    int dir=0,i;
733
                    int ac_pred = get_bits1(&s->gb);
734
                    int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
735

    
736
                    if(cbpy<0){
737
                        av_log(s->avctx, AV_LOG_ERROR, "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
738
                        return -1;
739
                    }
740

    
741
                    if(s->cbp_table[xy] & 8) {
742
                        ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
743
                    }
744
                    s->current_picture.qscale_table[xy]= s->qscale;
745

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

    
766
                    if(cbpy<0){
767
                        av_log(s->avctx, AV_LOG_ERROR, "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
768
                        return -1;
769
                    }
770

    
771
                    if(s->cbp_table[xy] & 8) {
772
                        ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
773
                    }
774
                    s->current_picture.qscale_table[xy]= s->qscale;
775

    
776
                    s->cbp_table[xy]&= 3; //remove dquant
777
                    s->cbp_table[xy]|= (cbpy^0xf)<<2;
778
                }
779
            }
780
        }
781
        if(mb_num >= mb_count) return 0;
782
        s->mb_x= 0;
783
    }
784
    return 0;
785
}
786

    
787
/**
788
 * decodes the first & second partition
789
 * @return <0 if error (and sets error type in the error_status_table)
790
 */
791
int ff_mpeg4_decode_partitions(MpegEncContext *s)
792
{
793
    int mb_num;
794
    const int part_a_error= s->pict_type==FF_I_TYPE ? (DC_ERROR|MV_ERROR) : MV_ERROR;
795
    const int part_a_end  = s->pict_type==FF_I_TYPE ? (DC_END  |MV_END)   : MV_END;
796

    
797
    mb_num= mpeg4_decode_partition_a(s);
798
    if(mb_num<0){
799
        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error);
800
        return -1;
801
    }
802

    
803
    if(s->resync_mb_x + s->resync_mb_y*s->mb_width + mb_num > s->mb_num){
804
        av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n");
805
        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error);
806
        return -1;
807
    }
808

    
809
    s->mb_num_left= mb_num;
810

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

    
828
    if( mpeg4_decode_partition_b(s, mb_num) < 0){
829
        if(s->pict_type==FF_P_TYPE)
830
            ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, DC_ERROR);
831
        return -1;
832
    }else{
833
        if(s->pict_type==FF_P_TYPE)
834
            ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, DC_END);
835
    }
836

    
837
    return 0;
838
}
839

    
840
/**
841
 * decodes a block.
842
 * @return <0 if an error occurred
843
 */
844
static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,
845
                              int n, int coded, int intra, int rvlc)
846
{
847
    int level, i, last, run;
848
    int dc_pred_dir;
849
    RLTable * rl;
850
    RL_VLC_ELEM * rl_vlc;
851
    const uint8_t * scan_table;
852
    int qmul, qadd;
853

    
854
    //Note intra & rvlc should be optimized away if this is inlined
855

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

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

    
904
        scan_table = s->intra_scantable.permutated;
905

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

    
937
                last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);
938
                run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);
939
                SKIP_COUNTER(re, &s->gb, 1+1+6);
940
                UPDATE_CACHE(re, &s->gb);
941

    
942
                if(SHOW_UBITS(re, &s->gb, 1)==0){
943
                    av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in rvlc esc\n");
944
                    return -1;
945
                }; SKIP_CACHE(re, &s->gb, 1);
946

    
947
                level= SHOW_UBITS(re, &s->gb, 11); SKIP_CACHE(re, &s->gb, 11);
948

    
949
                if(SHOW_UBITS(re, &s->gb, 5)!=0x10){
950
                    av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n");
951
                    return -1;
952
                }; SKIP_CACHE(re, &s->gb, 5);
953

    
954
                level=  level * qmul + qadd;
955
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_CACHE(re, &s->gb, 1);
956
                SKIP_COUNTER(re, &s->gb, 1+11+5+1);
957

    
958
                i+= run + 1;
959
                if(last) i+=192;
960
          }else{
961
            int cache;
962
            cache= GET_CACHE(re, &s->gb);
963

    
964
            if(IS_3IV1)
965
                cache ^= 0xC0000000;
966

    
967
            if (cache&0x80000000) {
968
                if (cache&0x40000000) {
969
                    /* third escape */
970
                    SKIP_CACHE(re, &s->gb, 2);
971
                    last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);
972
                    run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);
973
                    SKIP_COUNTER(re, &s->gb, 2+1+6);
974
                    UPDATE_CACHE(re, &s->gb);
975

    
976
                    if(IS_3IV1){
977
                        level= SHOW_SBITS(re, &s->gb, 12); LAST_SKIP_BITS(re, &s->gb, 12);
978
                    }else{
979
                        if(SHOW_UBITS(re, &s->gb, 1)==0){
980
                            av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in 3. esc\n");
981
                            return -1;
982
                        }; SKIP_CACHE(re, &s->gb, 1);
983

    
984
                        level= SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12);
985

    
986
                        if(SHOW_UBITS(re, &s->gb, 1)==0){
987
                            av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in 3. esc\n");
988
                            return -1;
989
                        }; LAST_SKIP_CACHE(re, &s->gb, 1);
990

    
991
                        SKIP_COUNTER(re, &s->gb, 1+12+1);
992
                    }
993

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

    
1019
                    if((unsigned)(level + 2048) > 4095){
1020
                        if(s->error_recognition > FF_ER_COMPLIANT){
1021
                            if(level > 2560 || level<-2560){
1022
                                av_log(s->avctx, AV_LOG_ERROR, "|level| overflow in 3. esc, qp=%d\n", s->qscale);
1023
                                return -1;
1024
                            }
1025
                        }
1026
                        level= level<0 ? -2048 : 2047;
1027
                    }
1028

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

    
1061
            block[scan_table[i]] = level;
1062
            break;
1063
        }
1064

    
1065
        block[scan_table[i]] = level;
1066
    }
1067
    CLOSE_READER(re, &s->gb);
1068
  }
1069
 not_coded:
1070
    if (intra) {
1071
        if(!s->use_intra_dc_vlc){
1072
            block[0] = ff_mpeg4_pred_dc(s, n, block[0], &dc_pred_dir, 0);
1073

    
1074
            i -= i>>31; //if(i == -1) i=0;
1075
        }
1076

    
1077
        mpeg4_pred_ac(s, block, n, dc_pred_dir);
1078
        if (s->ac_pred) {
1079
            i = 63; /* XXX: not optimal */
1080
        }
1081
    }
1082
    s->block_last_index[n] = i;
1083
    return 0;
1084
}
1085

    
1086
/**
1087
 * decode partition C of one MB.
1088
 * @return <0 if an error occurred
1089
 */
1090
static int mpeg4_decode_partitioned_mb(MpegEncContext *s, DCTELEM block[6][64])
1091
{
1092
    int cbp, mb_type;
1093
    const int xy= s->mb_x + s->mb_y*s->mb_stride;
1094

    
1095
    mb_type= s->current_picture.mb_type[xy];
1096
    cbp = s->cbp_table[xy];
1097

    
1098
    s->use_intra_dc_vlc= s->qscale < s->intra_dc_threshold;
1099

    
1100
    if(s->current_picture.qscale_table[xy] != s->qscale){
1101
        ff_set_qscale(s, s->current_picture.qscale_table[xy] );
1102
    }
1103

    
1104
    if (s->pict_type == FF_P_TYPE || s->pict_type==FF_S_TYPE) {
1105
        int i;
1106
        for(i=0; i<4; i++){
1107
            s->mv[0][i][0] = s->current_picture.motion_val[0][ s->block_index[i] ][0];
1108
            s->mv[0][i][1] = s->current_picture.motion_val[0][ s->block_index[i] ][1];
1109
        }
1110
        s->mb_intra = IS_INTRA(mb_type);
1111

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

    
1130
            s->mv_dir = MV_DIR_FORWARD;
1131
            if (IS_8X8(mb_type)) {
1132
                s->mv_type = MV_TYPE_8X8;
1133
            } else {
1134
                s->mv_type = MV_TYPE_16X16;
1135
            }
1136
        }
1137
    } else { /* I-Frame */
1138
        s->mb_intra = 1;
1139
        s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
1140
    }
1141

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

    
1155
    /* per-MB end of slice check */
1156

    
1157
    if(--s->mb_num_left <= 0){
1158
        if(mpeg4_is_resync(s))
1159
            return SLICE_END;
1160
        else
1161
            return SLICE_NOEND;
1162
    }else{
1163
        if(mpeg4_is_resync(s)){
1164
            const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
1165
            if(s->cbp_table[xy+delta])
1166
                return SLICE_END;
1167
        }
1168
        return SLICE_OK;
1169
    }
1170
}
1171

    
1172
static int mpeg4_decode_mb(MpegEncContext *s,
1173
                      DCTELEM block[6][64])
1174
{
1175
    int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
1176
    int16_t *mot_val;
1177
    static int8_t quant_tab[4] = { -1, -2, 1, 2 };
1178
    const int xy= s->mb_x + s->mb_y * s->mb_stride;
1179

    
1180
    assert(s->h263_pred);
1181

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

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

    
1214
        s->dsp.clear_blocks(s->block[0]);
1215
        dquant = cbpc & 8;
1216
        s->mb_intra = ((cbpc & 4) != 0);
1217
        if (s->mb_intra) goto intra;
1218

    
1219
        if(s->pict_type==FF_S_TYPE && s->vol_sprite_usage==GMC_SPRITE && (cbpc & 16) == 0)
1220
            s->mcsel= get_bits1(&s->gb);
1221
        else s->mcsel= 0;
1222
        cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1) ^ 0x0F;
1223

    
1224
        cbp = (cbpc & 3) | (cbpy << 2);
1225
        if (dquant) {
1226
            ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
1227
        }
1228
        if((!s->progressive_sequence) && (cbp || (s->workaround_bugs&FF_BUG_XVID_ILACE)))
1229
            s->interlaced_dct= get_bits1(&s->gb);
1230

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

    
1246
                s->field_select[0][0]= get_bits1(&s->gb);
1247
                s->field_select[0][1]= get_bits1(&s->gb);
1248

    
1249
                h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1250

    
1251
                for(i=0; i<2; i++){
1252
                    mx = h263_decode_motion(s, pred_x, s->f_code);
1253
                    if (mx >= 0xffff)
1254
                        return -1;
1255

    
1256
                    my = h263_decode_motion(s, pred_y/2, s->f_code);
1257
                    if (my >= 0xffff)
1258
                        return -1;
1259

    
1260
                    s->mv[0][i][0] = mx;
1261
                    s->mv[0][i][1] = my;
1262
                }
1263
            }else{
1264
                s->current_picture.mb_type[xy]= MB_TYPE_16x16 | MB_TYPE_L0;
1265
                /* 16x16 motion prediction */
1266
                s->mv_type = MV_TYPE_16X16;
1267
                h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1268
                mx = h263_decode_motion(s, pred_x, s->f_code);
1269

    
1270
                if (mx >= 0xffff)
1271
                    return -1;
1272

    
1273
                my = h263_decode_motion(s, pred_y, s->f_code);
1274

    
1275
                if (my >= 0xffff)
1276
                    return -1;
1277
                s->mv[0][0][0] = mx;
1278
                s->mv[0][0][1] = my;
1279
            }
1280
        } else {
1281
            s->current_picture.mb_type[xy]= MB_TYPE_8x8 | MB_TYPE_L0;
1282
            s->mv_type = MV_TYPE_8X8;
1283
            for(i=0;i<4;i++) {
1284
                mot_val = h263_pred_motion(s, i, 0, &pred_x, &pred_y);
1285
                mx = h263_decode_motion(s, pred_x, s->f_code);
1286
                if (mx >= 0xffff)
1287
                    return -1;
1288

    
1289
                my = h263_decode_motion(s, pred_y, s->f_code);
1290
                if (my >= 0xffff)
1291
                    return -1;
1292
                s->mv[0][i][0] = mx;
1293
                s->mv[0][i][1] = my;
1294
                mot_val[0] = mx;
1295
                mot_val[1] = my;
1296
            }
1297
        }
1298
    } else if(s->pict_type==FF_B_TYPE) {
1299
        int modb1; // first bit of modb
1300
        int modb2; // second bit of modb
1301
        int mb_type;
1302

    
1303
        s->mb_intra = 0; //B-frames never contain intra blocks
1304
        s->mcsel=0;      //     ...               true gmc blocks
1305

    
1306
        if(s->mb_x==0){
1307
            for(i=0; i<2; i++){
1308
                s->last_mv[i][0][0]=
1309
                s->last_mv[i][0][1]=
1310
                s->last_mv[i][1][0]=
1311
                s->last_mv[i][1][1]= 0;
1312
            }
1313

    
1314
            ff_thread_await_progress((AVFrame*)s->next_picture_ptr, s->mb_y, 0);
1315
        }
1316

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

    
1320
        if(s->mb_skipped){
1321
                /* skip mb */
1322
            for(i=0;i<6;i++)
1323
                s->block_last_index[i] = -1;
1324

    
1325
            s->mv_dir = MV_DIR_FORWARD;
1326
            s->mv_type = MV_TYPE_16X16;
1327
            s->mv[0][0][0] = 0;
1328
            s->mv[0][0][1] = 0;
1329
            s->mv[1][0][0] = 0;
1330
            s->mv[1][0][1] = 0;
1331
            s->current_picture.mb_type[xy]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
1332
            goto end;
1333
        }
1334

    
1335
        modb1= get_bits1(&s->gb);
1336
        if(modb1){
1337
            mb_type= MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1; //like MB_TYPE_B_DIRECT but no vectors coded
1338
            cbp=0;
1339
        }else{
1340
            modb2= get_bits1(&s->gb);
1341
            mb_type= get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);
1342
            if(mb_type<0){
1343
                av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n");
1344
                return -1;
1345
            }
1346
            mb_type= mb_type_b_map[ mb_type ];
1347
            if(modb2) cbp= 0;
1348
            else{
1349
                s->dsp.clear_blocks(s->block[0]);
1350
                cbp= get_bits(&s->gb, 6);
1351
            }
1352

    
1353
            if ((!IS_DIRECT(mb_type)) && cbp) {
1354
                if(get_bits1(&s->gb)){
1355
                    ff_set_qscale(s, s->qscale + get_bits1(&s->gb)*4 - 2);
1356
                }
1357
            }
1358

    
1359
            if(!s->progressive_sequence){
1360
                if(cbp)
1361
                    s->interlaced_dct= get_bits1(&s->gb);
1362

    
1363
                if(!IS_DIRECT(mb_type) && get_bits1(&s->gb)){
1364
                    mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
1365
                    mb_type &= ~MB_TYPE_16x16;
1366

    
1367
                    if(USES_LIST(mb_type, 0)){
1368
                        s->field_select[0][0]= get_bits1(&s->gb);
1369
                        s->field_select[0][1]= get_bits1(&s->gb);
1370
                    }
1371
                    if(USES_LIST(mb_type, 1)){
1372
                        s->field_select[1][0]= get_bits1(&s->gb);
1373
                        s->field_select[1][1]= get_bits1(&s->gb);
1374
                    }
1375
                }
1376
            }
1377

    
1378
            s->mv_dir = 0;
1379
            if((mb_type & (MB_TYPE_DIRECT2|MB_TYPE_INTERLACED)) == 0){
1380
                s->mv_type= MV_TYPE_16X16;
1381

    
1382
                if(USES_LIST(mb_type, 0)){
1383
                    s->mv_dir = MV_DIR_FORWARD;
1384

    
1385
                    mx = h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
1386
                    my = h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
1387
                    s->last_mv[0][1][0]= s->last_mv[0][0][0]= s->mv[0][0][0] = mx;
1388
                    s->last_mv[0][1][1]= s->last_mv[0][0][1]= s->mv[0][0][1] = my;
1389
                }
1390

    
1391
                if(USES_LIST(mb_type, 1)){
1392
                    s->mv_dir |= MV_DIR_BACKWARD;
1393

    
1394
                    mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
1395
                    my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
1396
                    s->last_mv[1][1][0]= s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
1397
                    s->last_mv[1][1][1]= s->last_mv[1][0][1]= s->mv[1][0][1] = my;
1398
                }
1399
            }else if(!IS_DIRECT(mb_type)){
1400
                s->mv_type= MV_TYPE_FIELD;
1401

    
1402
                if(USES_LIST(mb_type, 0)){
1403
                    s->mv_dir = MV_DIR_FORWARD;
1404

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

    
1413
                if(USES_LIST(mb_type, 1)){
1414
                    s->mv_dir |= MV_DIR_BACKWARD;
1415

    
1416
                    for(i=0; i<2; i++){
1417
                        mx = h263_decode_motion(s, s->last_mv[1][i][0]  , s->b_code);
1418
                        my = h263_decode_motion(s, s->last_mv[1][i][1]/2, s->b_code);
1419
                        s->last_mv[1][i][0]=  s->mv[1][i][0] = mx;
1420
                        s->last_mv[1][i][1]= (s->mv[1][i][1] = my)*2;
1421
                    }
1422
                }
1423
            }
1424
        }
1425

    
1426
        if(IS_DIRECT(mb_type)){
1427
            if(IS_SKIP(mb_type))
1428
                mx=my=0;
1429
            else{
1430
                mx = h263_decode_motion(s, 0, 1);
1431
                my = h263_decode_motion(s, 0, 1);
1432
            }
1433

    
1434
            s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
1435
            mb_type |= ff_mpeg4_set_direct_mv(s, mx, my);
1436
        }
1437
        s->current_picture.mb_type[xy]= mb_type;
1438
    } else { /* I-Frame */
1439
        do{
1440
            cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
1441
            if (cbpc < 0){
1442
                av_log(s->avctx, AV_LOG_ERROR, "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
1443
                return -1;
1444
            }
1445
        }while(cbpc == 8);
1446

    
1447
        dquant = cbpc & 4;
1448
        s->mb_intra = 1;
1449
intra:
1450
        s->ac_pred = get_bits1(&s->gb);
1451
        if(s->ac_pred)
1452
            s->current_picture.mb_type[xy]= MB_TYPE_INTRA | MB_TYPE_ACPRED;
1453
        else
1454
            s->current_picture.mb_type[xy]= MB_TYPE_INTRA;
1455

    
1456
        cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
1457
        if(cbpy<0){
1458
            av_log(s->avctx, AV_LOG_ERROR, "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
1459
            return -1;
1460
        }
1461
        cbp = (cbpc & 3) | (cbpy << 2);
1462

    
1463
        s->use_intra_dc_vlc= s->qscale < s->intra_dc_threshold;
1464

    
1465
        if (dquant) {
1466
            ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
1467
        }
1468

    
1469
        if(!s->progressive_sequence)
1470
            s->interlaced_dct= get_bits1(&s->gb);
1471

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

    
1482
    /* decode each block */
1483
    for (i = 0; i < 6; i++) {
1484
        if (mpeg4_decode_block(s, block[i], i, cbp&32, 0, 0) < 0)
1485
            return -1;
1486
        cbp+=cbp;
1487
    }
1488
end:
1489

    
1490
        /* per-MB end of slice check */
1491
    if(s->codec_id==CODEC_ID_MPEG4){
1492
        if(mpeg4_is_resync(s)){
1493
            const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
1494

    
1495
            if(s->pict_type==FF_B_TYPE){
1496
                ff_thread_await_progress((AVFrame*)s->next_picture_ptr,
1497
                                        (s->mb_x + delta >= s->mb_width) ? FFMIN(s->mb_y+1, s->mb_height-1) : s->mb_y, 0);
1498
            }
1499

    
1500
            if(s->pict_type==FF_B_TYPE && s->next_picture.mbskip_table[xy + delta])
1501
                return SLICE_OK;
1502
            return SLICE_END;
1503
        }
1504
    }
1505

    
1506
    return SLICE_OK;
1507
}
1508

    
1509

    
1510
static int mpeg4_decode_gop_header(MpegEncContext * s, GetBitContext *gb){
1511
    int hours, minutes, seconds;
1512

    
1513
    if(!show_bits(gb, 23)){
1514
        av_log(s->avctx, AV_LOG_WARNING, "GOP header invalid\n");
1515
        return -1;
1516
    }
1517

    
1518
    hours= get_bits(gb, 5);
1519
    minutes= get_bits(gb, 6);
1520
    skip_bits1(gb);
1521
    seconds= get_bits(gb, 6);
1522

    
1523
    s->time_base= seconds + 60*(minutes + 60*hours);
1524

    
1525
    skip_bits1(gb);
1526
    skip_bits1(gb);
1527

    
1528
    return 0;
1529
}
1530

    
1531
static int decode_vol_header(MpegEncContext *s, GetBitContext *gb){
1532
    int width, height, vo_ver_id;
1533

    
1534
    /* vol header */
1535
    skip_bits(gb, 1); /* random access */
1536
    s->vo_type= get_bits(gb, 8);
1537
    if (get_bits1(gb) != 0) { /* is_ol_id */
1538
        vo_ver_id = get_bits(gb, 4); /* vo_ver_id */
1539
        skip_bits(gb, 3); /* vo_priority */
1540
    } else {
1541
        vo_ver_id = 1;
1542
    }
1543
    s->aspect_ratio_info= get_bits(gb, 4);
1544
    if(s->aspect_ratio_info == FF_ASPECT_EXTENDED){
1545
        s->avctx->sample_aspect_ratio.num= get_bits(gb, 8); // par_width
1546
        s->avctx->sample_aspect_ratio.den= get_bits(gb, 8); // par_height
1547
    }else{
1548
        s->avctx->sample_aspect_ratio= ff_h263_pixel_aspect[s->aspect_ratio_info];
1549
    }
1550

    
1551
    if ((s->vol_control_parameters=get_bits1(gb))) { /* vol control parameter */
1552
        int chroma_format= get_bits(gb, 2);
1553
        if(chroma_format!=CHROMA_420){
1554
            av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n");
1555
        }
1556
        s->low_delay= get_bits1(gb);
1557
        if(get_bits1(gb)){ /* vbv parameters */
1558
            get_bits(gb, 15);   /* first_half_bitrate */
1559
            skip_bits1(gb);     /* marker */
1560
            get_bits(gb, 15);   /* latter_half_bitrate */
1561
            skip_bits1(gb);     /* marker */
1562
            get_bits(gb, 15);   /* first_half_vbv_buffer_size */
1563
            skip_bits1(gb);     /* marker */
1564
            get_bits(gb, 3);    /* latter_half_vbv_buffer_size */
1565
            get_bits(gb, 11);   /* first_half_vbv_occupancy */
1566
            skip_bits1(gb);     /* marker */
1567
            get_bits(gb, 15);   /* latter_half_vbv_occupancy */
1568
            skip_bits1(gb);     /* marker */
1569
        }
1570
    }else{
1571
        // set low delay flag only once the smartest? low delay detection won't be overriden
1572
        if(s->picture_number==0)
1573
            s->low_delay=0;
1574
    }
1575

    
1576
    s->shape = get_bits(gb, 2); /* vol shape */
1577
    if(s->shape != RECT_SHAPE) av_log(s->avctx, AV_LOG_ERROR, "only rectangular vol supported\n");
1578
    if(s->shape == GRAY_SHAPE && vo_ver_id != 1){
1579
        av_log(s->avctx, AV_LOG_ERROR, "Gray shape not supported\n");
1580
        skip_bits(gb, 4);  //video_object_layer_shape_extension
1581
    }
1582

    
1583
    check_marker(gb, "before time_increment_resolution");
1584

    
1585
    s->avctx->time_base.den = get_bits(gb, 16);
1586
    if(!s->avctx->time_base.den){
1587
        av_log(s->avctx, AV_LOG_ERROR, "time_base.den==0\n");
1588
        s->avctx->time_base.num = 0;
1589
        return -1;
1590
    }
1591

    
1592
    s->time_increment_bits = av_log2(s->avctx->time_base.den - 1) + 1;
1593
    if (s->time_increment_bits < 1)
1594
        s->time_increment_bits = 1;
1595

    
1596
    check_marker(gb, "before fixed_vop_rate");
1597

    
1598
    if (get_bits1(gb) != 0) {   /* fixed_vop_rate  */
1599
        s->avctx->time_base.num = get_bits(gb, s->time_increment_bits);
1600
    }else
1601
        s->avctx->time_base.num = 1;
1602

    
1603
    s->t_frame=0;
1604

    
1605
    if (s->shape != BIN_ONLY_SHAPE) {
1606
        if (s->shape == RECT_SHAPE) {
1607
            skip_bits1(gb);   /* marker */
1608
            width = get_bits(gb, 13);
1609
            skip_bits1(gb);   /* marker */
1610
            height = get_bits(gb, 13);
1611
            skip_bits1(gb);   /* marker */
1612
            if(width && height && !(s->width && s->codec_tag == AV_RL32("MP4S"))){ /* they should be non zero but who knows ... */
1613
                s->width = width;
1614
                s->height = height;
1615
            }
1616
        }
1617

    
1618
        s->progressive_sequence=
1619
        s->progressive_frame= get_bits1(gb)^1;
1620
        s->interlaced_dct=0;
1621
        if(!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO))
1622
            av_log(s->avctx, AV_LOG_INFO, "MPEG4 OBMC not supported (very likely buggy encoder)\n");   /* OBMC Disable */
1623
        if (vo_ver_id == 1) {
1624
            s->vol_sprite_usage = get_bits1(gb); /* vol_sprite_usage */
1625
        } else {
1626
            s->vol_sprite_usage = get_bits(gb, 2); /* vol_sprite_usage */
1627
        }
1628
        if(s->vol_sprite_usage==STATIC_SPRITE) av_log(s->avctx, AV_LOG_ERROR, "Static Sprites not supported\n");
1629
        if(s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE){
1630
            if(s->vol_sprite_usage==STATIC_SPRITE){
1631
                s->sprite_width = get_bits(gb, 13);
1632
                skip_bits1(gb); /* marker */
1633
                s->sprite_height= get_bits(gb, 13);
1634
                skip_bits1(gb); /* marker */
1635
                s->sprite_left  = get_bits(gb, 13);
1636
                skip_bits1(gb); /* marker */
1637
                s->sprite_top   = get_bits(gb, 13);
1638
                skip_bits1(gb); /* marker */
1639
            }
1640
            s->num_sprite_warping_points= get_bits(gb, 6);
1641
            if(s->num_sprite_warping_points > 3){
1642
                av_log(s->avctx, AV_LOG_ERROR, "%d sprite_warping_points\n", s->num_sprite_warping_points);
1643
                s->num_sprite_warping_points= 0;
1644
                return -1;
1645
            }
1646
            s->sprite_warping_accuracy = get_bits(gb, 2);
1647
            s->sprite_brightness_change= get_bits1(gb);
1648
            if(s->vol_sprite_usage==STATIC_SPRITE)
1649
                s->low_latency_sprite= get_bits1(gb);
1650
        }
1651
        // FIXME sadct disable bit if verid!=1 && shape not rect
1652

    
1653
        if (get_bits1(gb) == 1) {   /* not_8_bit */
1654
            s->quant_precision = get_bits(gb, 4); /* quant_precision */
1655
            if(get_bits(gb, 4)!=8) av_log(s->avctx, AV_LOG_ERROR, "N-bit not supported\n"); /* bits_per_pixel */
1656
            if(s->quant_precision!=5) av_log(s->avctx, AV_LOG_ERROR, "quant precision %d\n", s->quant_precision);
1657
        } else {
1658
            s->quant_precision = 5;
1659
        }
1660

    
1661
        // FIXME a bunch of grayscale shape things
1662

    
1663
        if((s->mpeg_quant=get_bits1(gb))){ /* vol_quant_type */
1664
            int i, v;
1665

    
1666
            /* load default matrixes */
1667
            for(i=0; i<64; i++){
1668
                int j= s->dsp.idct_permutation[i];
1669
                v= ff_mpeg4_default_intra_matrix[i];
1670
                s->intra_matrix[j]= v;
1671
                s->chroma_intra_matrix[j]= v;
1672

    
1673
                v= ff_mpeg4_default_non_intra_matrix[i];
1674
                s->inter_matrix[j]= v;
1675
                s->chroma_inter_matrix[j]= v;
1676
            }
1677

    
1678
            /* load custom intra matrix */
1679
            if(get_bits1(gb)){
1680
                int last=0;
1681
                for(i=0; i<64; i++){
1682
                    int j;
1683
                    v= get_bits(gb, 8);
1684
                    if(v==0) break;
1685

    
1686
                    last= v;
1687
                    j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
1688
                    s->intra_matrix[j]= v;
1689
                    s->chroma_intra_matrix[j]= v;
1690
                }
1691

    
1692
                /* replicate last value */
1693
                for(; i<64; i++){
1694
                    int j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
1695
                    s->intra_matrix[j]= last;
1696
                    s->chroma_intra_matrix[j]= last;
1697
                }
1698
            }
1699

    
1700
            /* load custom non intra matrix */
1701
            if(get_bits1(gb)){
1702
                int last=0;
1703
                for(i=0; i<64; i++){
1704
                    int j;
1705
                    v= get_bits(gb, 8);
1706
                    if(v==0) break;
1707

    
1708
                    last= v;
1709
                    j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
1710
                    s->inter_matrix[j]= v;
1711
                    s->chroma_inter_matrix[j]= v;
1712
                }
1713

    
1714
                /* replicate last value */
1715
                for(; i<64; i++){
1716
                    int j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];
1717
                    s->inter_matrix[j]= last;
1718
                    s->chroma_inter_matrix[j]= last;
1719
                }
1720
            }
1721

    
1722
            // FIXME a bunch of grayscale shape things
1723
        }
1724

    
1725
        if(vo_ver_id != 1)
1726
             s->quarter_sample= get_bits1(gb);
1727
        else s->quarter_sample=0;
1728

    
1729
        if(!get_bits1(gb)){
1730
            int pos= get_bits_count(gb);
1731
            int estimation_method= get_bits(gb, 2);
1732
            if(estimation_method<2){
1733
                if(!get_bits1(gb)){
1734
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //opaque
1735
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //transparent
1736
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //intra_cae
1737
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //inter_cae
1738
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //no_update
1739
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //upampling
1740
                }
1741
                if(!get_bits1(gb)){
1742
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //intra_blocks
1743
                    s->cplx_estimation_trash_p += 8*get_bits1(gb); //inter_blocks
1744
                    s->cplx_estimation_trash_p += 8*get_bits1(gb); //inter4v_blocks
1745
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //not coded blocks
1746
                }
1747
                if(!check_marker(gb, "in complexity estimation part 1")){
1748
                    skip_bits_long(gb, pos - get_bits_count(gb));
1749
                    goto no_cplx_est;
1750
                }
1751
                if(!get_bits1(gb)){
1752
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //dct_coeffs
1753
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //dct_lines
1754
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //vlc_syms
1755
                    s->cplx_estimation_trash_i += 4*get_bits1(gb); //vlc_bits
1756
                }
1757
                if(!get_bits1(gb)){
1758
                    s->cplx_estimation_trash_p += 8*get_bits1(gb); //apm
1759
                    s->cplx_estimation_trash_p += 8*get_bits1(gb); //npm
1760
                    s->cplx_estimation_trash_b += 8*get_bits1(gb); //interpolate_mc_q
1761
                    s->cplx_estimation_trash_p += 8*get_bits1(gb); //forwback_mc_q
1762
                    s->cplx_estimation_trash_p += 8*get_bits1(gb); //halfpel2
1763
                    s->cplx_estimation_trash_p += 8*get_bits1(gb); //halfpel4
1764
                }
1765
                if(!check_marker(gb, "in complexity estimation part 2")){
1766
                    skip_bits_long(gb, pos - get_bits_count(gb));
1767
                    goto no_cplx_est;
1768
                }
1769
                if(estimation_method==1){
1770
                    s->cplx_estimation_trash_i += 8*get_bits1(gb); //sadct
1771
                    s->cplx_estimation_trash_p += 8*get_bits1(gb); //qpel
1772
                }
1773
            }else
1774
                av_log(s->avctx, AV_LOG_ERROR, "Invalid Complexity estimation method %d\n", estimation_method);
1775
        }else{
1776
no_cplx_est:
1777
            s->cplx_estimation_trash_i=
1778
            s->cplx_estimation_trash_p=
1779
            s->cplx_estimation_trash_b= 0;
1780
        }
1781

    
1782
        s->resync_marker= !get_bits1(gb); /* resync_marker_disabled */
1783

    
1784
        s->data_partitioning= get_bits1(gb);
1785
        if(s->data_partitioning){
1786
            s->rvlc= get_bits1(gb);
1787
        }
1788

    
1789
        if(vo_ver_id != 1) {
1790
            s->new_pred= get_bits1(gb);
1791
            if(s->new_pred){
1792
                av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n");
1793
                skip_bits(gb, 2); /* requested upstream message type */
1794
                skip_bits1(gb); /* newpred segment type */
1795
            }
1796
            s->reduced_res_vop= get_bits1(gb);
1797
            if(s->reduced_res_vop) av_log(s->avctx, AV_LOG_ERROR, "reduced resolution VOP not supported\n");
1798
        }
1799
        else{
1800
            s->new_pred=0;
1801
            s->reduced_res_vop= 0;
1802
        }
1803

    
1804
        s->scalability= get_bits1(gb);
1805

    
1806
        if (s->scalability) {
1807
            GetBitContext bak= *gb;
1808
            int ref_layer_id;
1809
            int ref_layer_sampling_dir;
1810
            int h_sampling_factor_n;
1811
            int h_sampling_factor_m;
1812
            int v_sampling_factor_n;
1813
            int v_sampling_factor_m;
1814

    
1815
            s->hierachy_type= get_bits1(gb);
1816
            ref_layer_id= get_bits(gb, 4);
1817
            ref_layer_sampling_dir= get_bits1(gb);
1818
            h_sampling_factor_n= get_bits(gb, 5);
1819
            h_sampling_factor_m= get_bits(gb, 5);
1820
            v_sampling_factor_n= get_bits(gb, 5);
1821
            v_sampling_factor_m= get_bits(gb, 5);
1822
            s->enhancement_type= get_bits1(gb);
1823

    
1824
            if(   h_sampling_factor_n==0 || h_sampling_factor_m==0
1825
               || v_sampling_factor_n==0 || v_sampling_factor_m==0){
1826
                /* illegal scalability header (VERY broken encoder),
1827
                 * trying to workaround */
1828
                s->scalability=0;
1829
                *gb= bak;
1830
            }else
1831
                av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n");
1832

    
1833
            // bin shape stuff FIXME
1834
        }
1835
    }
1836
    return 0;
1837
}
1838

    
1839
/**
1840
 * decodes the user data stuff in the header.
1841
 * Also initializes divx/xvid/lavc_version/build.
1842
 */
1843
static int decode_user_data(MpegEncContext *s, GetBitContext *gb){
1844
    char buf[256];
1845
    int i;
1846
    int e;
1847
    int ver = 0, build = 0, ver2 = 0, ver3 = 0;
1848
    char last;
1849

    
1850
    for(i=0; i<255 && get_bits_count(gb) < gb->size_in_bits; i++){
1851
        if(show_bits(gb, 23) == 0) break;
1852
        buf[i]= get_bits(gb, 8);
1853
    }
1854
    buf[i]=0;
1855

    
1856
    /* divx detection */
1857
    e=sscanf(buf, "DivX%dBuild%d%c", &ver, &build, &last);
1858
    if(e<2)
1859
        e=sscanf(buf, "DivX%db%d%c", &ver, &build, &last);
1860
    if(e>=2){
1861
        s->divx_version= ver;
1862
        s->divx_build= build;
1863
        s->divx_packed= e==3 && last=='p';
1864
        if(s->divx_packed && !s->showed_packed_warning) {
1865
            av_log(s->avctx, AV_LOG_WARNING, "Invalid and inefficient vfw-avi packed B frames detected\n");
1866
            s->showed_packed_warning=1;
1867
        }
1868
    }
1869

    
1870
    /* ffmpeg detection */
1871
    e=sscanf(buf, "FFmpe%*[^b]b%d", &build)+3;
1872
    if(e!=4)
1873
        e=sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build);
1874
    if(e!=4){
1875
        e=sscanf(buf, "Lavc%d.%d.%d", &ver, &ver2, &ver3)+1;
1876
        if (e>1)
1877
            build= (ver<<16) + (ver2<<8) + ver3;
1878
    }
1879
    if(e!=4){
1880
        if(strcmp(buf, "ffmpeg")==0){
1881
            s->lavc_build= 4600;
1882
        }
1883
    }
1884
    if(e==4){
1885
        s->lavc_build= build;
1886
    }
1887

    
1888
    /* Xvid detection */
1889
    e=sscanf(buf, "XviD%d", &build);
1890
    if(e==1){
1891
        s->xvid_build= build;
1892
    }
1893

    
1894
    return 0;
1895
}
1896

    
1897
static int decode_vop_header(MpegEncContext *s, GetBitContext *gb){
1898
    int time_incr, time_increment;
1899

    
1900
    s->pict_type = get_bits(gb, 2) + FF_I_TYPE;        /* pict type: I = 0 , P = 1 */
1901
    if(s->pict_type==FF_B_TYPE && s->low_delay && s->vol_control_parameters==0 && !(s->flags & CODEC_FLAG_LOW_DELAY)){
1902
        av_log(s->avctx, AV_LOG_ERROR, "low_delay flag incorrectly, clearing it\n");
1903
        s->low_delay=0;
1904
    }
1905

    
1906
    s->partitioned_frame= s->data_partitioning && s->pict_type!=FF_B_TYPE;
1907
    if(s->partitioned_frame)
1908
        s->decode_mb= mpeg4_decode_partitioned_mb;
1909
    else
1910
        s->decode_mb= mpeg4_decode_mb;
1911

    
1912
    time_incr=0;
1913
    while (get_bits1(gb) != 0)
1914
        time_incr++;
1915

    
1916
    check_marker(gb, "before time_increment");
1917

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

    
1921
        for(s->time_increment_bits=1 ;s->time_increment_bits<16; s->time_increment_bits++){
1922
            if (    s->pict_type == FF_P_TYPE
1923
                || (s->pict_type == FF_S_TYPE && s->vol_sprite_usage==GMC_SPRITE)) {
1924
                if((show_bits(gb, s->time_increment_bits+6)&0x37) == 0x30) break;
1925
            }else
1926
                if((show_bits(gb, s->time_increment_bits+5)&0x1F) == 0x18) break;
1927
        }
1928

    
1929
        av_log(s->avctx, AV_LOG_ERROR, "my guess is %d bits ;)\n",s->time_increment_bits);
1930
    }
1931

    
1932
    if(IS_3IV1) time_increment= get_bits1(gb); //FIXME investigate further
1933
    else time_increment= get_bits(gb, s->time_increment_bits);
1934

    
1935
    if(s->pict_type!=FF_B_TYPE){
1936
        s->last_time_base= s->time_base;
1937
        s->time_base+= time_incr;
1938
        s->time= s->time_base*s->avctx->time_base.den + time_increment;
1939
        if(s->workaround_bugs&FF_BUG_UMP4){
1940
            if(s->time < s->last_non_b_time){
1941
                /* header is not mpeg-4-compatible, broken encoder,
1942
                 * trying to workaround */
1943
                s->time_base++;
1944
                s->time+= s->avctx->time_base.den;
1945
            }
1946
        }
1947
        s->pp_time= s->time - s->last_non_b_time;
1948
        s->last_non_b_time= s->time;
1949
    }else{
1950
        s->time= (s->last_time_base + time_incr)*s->avctx->time_base.den + time_increment;
1951
        s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
1952
        if(s->pp_time <=s->pb_time || s->pp_time <= s->pp_time - s->pb_time || s->pp_time<=0){
1953
            /* messed up order, maybe after seeking? skipping current b-frame */
1954
            return FRAME_SKIPPED;
1955
        }
1956
        ff_mpeg4_init_direct_mv(s);
1957

    
1958
        if(s->t_frame==0) s->t_frame= s->pb_time;
1959
        if(s->t_frame==0) s->t_frame=1; // 1/0 protection
1960
        s->pp_field_time= (  ROUNDED_DIV(s->last_non_b_time, s->t_frame)
1961
                           - ROUNDED_DIV(s->last_non_b_time - s->pp_time, s->t_frame))*2;
1962
        s->pb_field_time= (  ROUNDED_DIV(s->time, s->t_frame)
1963
                           - ROUNDED_DIV(s->last_non_b_time - s->pp_time, s->t_frame))*2;
1964
        if(!s->progressive_sequence){
1965
            if(s->pp_field_time <= s->pb_field_time || s->pb_field_time <= 1)
1966
                return FRAME_SKIPPED;
1967
        }
1968
    }
1969

    
1970
    if(s->avctx->time_base.num)
1971
        s->current_picture_ptr->pts= (s->time + s->avctx->time_base.num/2) / s->avctx->time_base.num;
1972
    else
1973
        s->current_picture_ptr->pts= AV_NOPTS_VALUE;
1974
    if(s->avctx->debug&FF_DEBUG_PTS)
1975
        av_log(s->avctx, AV_LOG_DEBUG, "MPEG4 PTS: %"PRId64"\n", s->current_picture_ptr->pts);
1976

    
1977
    check_marker(gb, "before vop_coded");
1978

    
1979
    /* vop coded */
1980
    if (get_bits1(gb) != 1){
1981
        if(s->avctx->debug&FF_DEBUG_PICT_INFO)
1982
            av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n");
1983
        return FRAME_SKIPPED;
1984
    }
1985
    if (s->shape != BIN_ONLY_SHAPE && ( s->pict_type == FF_P_TYPE
1986
                          || (s->pict_type == FF_S_TYPE && s->vol_sprite_usage==GMC_SPRITE))) {
1987
        /* rounding type for motion estimation */
1988
        s->no_rounding = get_bits1(gb);
1989
    } else {
1990
        s->no_rounding = 0;
1991
    }
1992
//FIXME reduced res stuff
1993

    
1994
     if (s->shape != RECT_SHAPE) {
1995
         if (s->vol_sprite_usage != 1 || s->pict_type != FF_I_TYPE) {
1996
             int width, height, hor_spat_ref, ver_spat_ref;
1997

    
1998
             width = get_bits(gb, 13);
1999
             skip_bits1(gb);   /* marker */
2000
             height = get_bits(gb, 13);
2001
             skip_bits1(gb);   /* marker */
2002
             hor_spat_ref = get_bits(gb, 13); /* hor_spat_ref */
2003
             skip_bits1(gb);   /* marker */
2004
             ver_spat_ref = get_bits(gb, 13); /* ver_spat_ref */
2005
         }
2006
         skip_bits1(gb); /* change_CR_disable */
2007

    
2008
         if (get_bits1(gb) != 0) {
2009
             skip_bits(gb, 8); /* constant_alpha_value */
2010
         }
2011
     }
2012
//FIXME complexity estimation stuff
2013

    
2014
     if (s->shape != BIN_ONLY_SHAPE) {
2015
         skip_bits_long(gb, s->cplx_estimation_trash_i);
2016
         if(s->pict_type != FF_I_TYPE)
2017
            skip_bits_long(gb, s->cplx_estimation_trash_p);
2018
         if(s->pict_type == FF_B_TYPE)
2019
            skip_bits_long(gb, s->cplx_estimation_trash_b);
2020

    
2021
         s->intra_dc_threshold= mpeg4_dc_threshold[ get_bits(gb, 3) ];
2022
         if(!s->progressive_sequence){
2023
             s->top_field_first= get_bits1(gb);
2024
             s->alternate_scan= get_bits1(gb);
2025
         }else
2026
             s->alternate_scan= 0;
2027
     }
2028

    
2029
     if(s->alternate_scan){
2030
         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_alternate_vertical_scan);
2031
         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_alternate_vertical_scan);
2032
         ff_init_scantable(s->dsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
2033
         ff_init_scantable(s->dsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
2034
     } else{
2035
         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_zigzag_direct);
2036
         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_zigzag_direct);
2037
         ff_init_scantable(s->dsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
2038
         ff_init_scantable(s->dsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
2039
     }
2040

    
2041
     if(s->pict_type == FF_S_TYPE && (s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE)){
2042
         mpeg4_decode_sprite_trajectory(s, gb);
2043
         if(s->sprite_brightness_change) av_log(s->avctx, AV_LOG_ERROR, "sprite_brightness_change not supported\n");
2044
         if(s->vol_sprite_usage==STATIC_SPRITE) av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n");
2045
     }
2046

    
2047
     if (s->shape != BIN_ONLY_SHAPE) {
2048
         s->chroma_qscale= s->qscale = get_bits(gb, s->quant_precision);
2049
         if(s->qscale==0){
2050
             av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG4 header (qscale=0)\n");
2051
             return -1; // makes no sense to continue, as there is nothing left from the image then
2052
         }
2053

    
2054
         if (s->pict_type != FF_I_TYPE) {
2055
             s->f_code = get_bits(gb, 3);       /* fcode_for */
2056
             if(s->f_code==0){
2057
                 av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG4 header (f_code=0)\n");
2058
                 return -1; // makes no sense to continue, as the MV decoding will break very quickly
2059
             }
2060
         }else
2061
             s->f_code=1;
2062

    
2063
         if (s->pict_type == FF_B_TYPE) {
2064
             s->b_code = get_bits(gb, 3);
2065
         }else
2066
             s->b_code=1;
2067

    
2068
         if(s->avctx->debug&FF_DEBUG_PICT_INFO){
2069
             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",
2070
                 s->qscale, s->f_code, s->b_code,
2071
                 s->pict_type == FF_I_TYPE ? "I" : (s->pict_type == FF_P_TYPE ? "P" : (s->pict_type == FF_B_TYPE ? "B" : "S")),
2072
                 gb->size_in_bits,s->progressive_sequence, s->alternate_scan, s->top_field_first,
2073
                 s->quarter_sample ? "q" : "h", s->data_partitioning, s->resync_marker, s->num_sprite_warping_points,
2074
                 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);
2075
         }
2076

    
2077
         if(!s->scalability){
2078
             if (s->shape!=RECT_SHAPE && s->pict_type!=FF_I_TYPE) {
2079
                 skip_bits1(gb); // vop shape coding type
2080
             }
2081
         }else{
2082
             if(s->enhancement_type){
2083
                 int load_backward_shape= get_bits1(gb);
2084
                 if(load_backward_shape){
2085
                     av_log(s->avctx, AV_LOG_ERROR, "load backward shape isn't supported\n");
2086
                 }
2087
             }
2088
             skip_bits(gb, 2); //ref_select_code
2089
         }
2090
     }
2091
     /* detect buggy encoders which don't set the low_delay flag (divx4/xvid/opendivx)*/
2092
     // note we cannot detect divx5 without b-frames easily (although it's buggy too)
2093
     if(s->vo_type==0 && s->vol_control_parameters==0 && s->divx_version==-1 && s->picture_number==0){
2094
         av_log(s->avctx, AV_LOG_WARNING, "looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n");
2095
         s->low_delay=1;
2096
     }
2097

    
2098
     s->picture_number++; // better than pic number==0 always ;)
2099

    
2100
     s->y_dc_scale_table= ff_mpeg4_y_dc_scale_table; //FIXME add short header support
2101
     s->c_dc_scale_table= ff_mpeg4_c_dc_scale_table;
2102

    
2103
     if(s->workaround_bugs&FF_BUG_EDGE){
2104
         s->h_edge_pos= s->width;
2105
         s->v_edge_pos= s->height;
2106
     }
2107
     return 0;
2108
}
2109

    
2110
/**
2111
 * decode mpeg4 headers
2112
 * @return <0 if no VOP found (or a damaged one)
2113
 *         FRAME_SKIPPED if a not coded VOP is found
2114
 *         0 if a VOP is found
2115
 */
2116
int ff_mpeg4_decode_picture_header(MpegEncContext * s, GetBitContext *gb)
2117
{
2118
    int startcode, v;
2119

    
2120
    /* search next start code */
2121
    align_get_bits(gb);
2122

    
2123
    if(s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630){
2124
        skip_bits(gb, 24);
2125
        if(get_bits(gb, 8) == 0xF0)
2126
            goto end;
2127
    }
2128

    
2129
    startcode = 0xff;
2130
    for(;;) {
2131
        if(get_bits_count(gb) >= gb->size_in_bits){
2132
            if(gb->size_in_bits==8 && (s->divx_version>=0 || s->xvid_build>=0)){
2133
                av_log(s->avctx, AV_LOG_WARNING, "frame skip %d\n", gb->size_in_bits);
2134
                return FRAME_SKIPPED; //divx bug
2135
            }else
2136
                return -1; //end of stream
2137
        }
2138

    
2139
        /* use the bits after the test */
2140
        v = get_bits(gb, 8);
2141
        startcode = ((startcode << 8) | v) & 0xffffffff;
2142

    
2143
        if((startcode&0xFFFFFF00) != 0x100)
2144
            continue; //no startcode
2145

    
2146
        if(s->avctx->debug&FF_DEBUG_STARTCODE){
2147
            av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode);
2148
            if     (startcode<=0x11F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start");
2149
            else if(startcode<=0x12F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start");
2150
            else if(startcode<=0x13F) av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
2151
            else if(startcode<=0x15F) av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start");
2152
            else if(startcode<=0x1AF) av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
2153
            else if(startcode==0x1B0) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start");
2154
            else if(startcode==0x1B1) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End");
2155
            else if(startcode==0x1B2) av_log(s->avctx, AV_LOG_DEBUG, "User Data");
2156
            else if(startcode==0x1B3) av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start");
2157
            else if(startcode==0x1B4) av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error");
2158
            else if(startcode==0x1B5) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start");
2159
            else if(startcode==0x1B6) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start");
2160
            else if(startcode==0x1B7) av_log(s->avctx, AV_LOG_DEBUG, "slice start");
2161
            else if(startcode==0x1B8) av_log(s->avctx, AV_LOG_DEBUG, "extension start");
2162
            else if(startcode==0x1B9) av_log(s->avctx, AV_LOG_DEBUG, "fgs start");
2163
            else if(startcode==0x1BA) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start");
2164
            else if(startcode==0x1BB) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start");
2165
            else if(startcode==0x1BC) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start");
2166
            else if(startcode==0x1BD) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start");
2167
            else if(startcode==0x1BE) av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start");
2168
            else if(startcode==0x1BF) av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start");
2169
            else if(startcode==0x1C0) av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start");
2170
            else if(startcode==0x1C1) av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start");
2171
            else if(startcode==0x1C2) av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start");
2172
            else if(startcode==0x1C3) av_log(s->avctx, AV_LOG_DEBUG, "stuffing start");
2173
            else if(startcode<=0x1C5) av_log(s->avctx, AV_LOG_DEBUG, "reserved");
2174
            else if(startcode<=0x1FF) av_log(s->avctx, AV_LOG_DEBUG, "System start");
2175
            av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb));
2176
        }
2177

    
2178
        if(startcode >= 0x120 && startcode <= 0x12F){
2179
            if(decode_vol_header(s, gb) < 0)
2180
                return -1;
2181
        }
2182
        else if(startcode == USER_DATA_STARTCODE){
2183
            decode_user_data(s, gb);
2184
        }
2185
        else if(startcode == GOP_STARTCODE){
2186
            mpeg4_decode_gop_header(s, gb);
2187
        }
2188
        else if(startcode == VOP_STARTCODE){
2189
            break;
2190
        }
2191

    
2192
        align_get_bits(gb);
2193
        startcode = 0xff;
2194
    }
2195
end:
2196
    if(s->flags& CODEC_FLAG_LOW_DELAY)
2197
        s->low_delay=1;
2198
    s->avctx->has_b_frames= !s->low_delay;
2199
    return decode_vop_header(s, gb);
2200
}
2201

    
2202
static av_cold int decode_init(AVCodecContext *avctx)
2203
{
2204
    MpegEncContext *s = avctx->priv_data;
2205
    int ret;
2206
    static int done = 0;
2207

    
2208
    s->divx_version=
2209
    s->divx_build=
2210
    s->xvid_build=
2211
    s->lavc_build= -1;
2212

    
2213
    if((ret=ff_h263_decode_init(avctx)) < 0)
2214
        return ret;
2215

    
2216
    if (!done) {
2217
        done = 1;
2218

    
2219
        init_rl(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
2220
        init_rl(&rvlc_rl_inter, ff_mpeg4_static_rl_table_store[1]);
2221
        init_rl(&rvlc_rl_intra, ff_mpeg4_static_rl_table_store[2]);
2222
        INIT_VLC_RL(ff_mpeg4_rl_intra, 554);
2223
        INIT_VLC_RL(rvlc_rl_inter, 1072);
2224
        INIT_VLC_RL(rvlc_rl_intra, 1072);
2225
        INIT_VLC_STATIC(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
2226
                 &ff_mpeg4_DCtab_lum[0][1], 2, 1,
2227
                 &ff_mpeg4_DCtab_lum[0][0], 2, 1, 512);
2228
        INIT_VLC_STATIC(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
2229
                 &ff_mpeg4_DCtab_chrom[0][1], 2, 1,
2230
                 &ff_mpeg4_DCtab_chrom[0][0], 2, 1, 512);
2231
        INIT_VLC_STATIC(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
2232
                 &sprite_trajectory_tab[0][1], 4, 2,
2233
                 &sprite_trajectory_tab[0][0], 4, 2, 128);
2234
        INIT_VLC_STATIC(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
2235
                 &mb_type_b_tab[0][1], 2, 1,
2236
                 &mb_type_b_tab[0][0], 2, 1, 16);
2237
    }
2238

    
2239
    s->h263_pred = 1;
2240
    s->low_delay = 0; //default, might be overriden in the vol header during header parsing
2241
    s->decode_mb= mpeg4_decode_mb;
2242
    s->time_increment_bits = 4; /* default value for broken headers */
2243
    avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
2244

    
2245
    return 0;
2246
}
2247

    
2248
AVCodec ff_mpeg4_decoder = {
2249
    "mpeg4",
2250
    AVMEDIA_TYPE_VIDEO,
2251
    CODEC_ID_MPEG4,
2252
    sizeof(MpegEncContext),
2253
    decode_init,
2254
    NULL,
2255
    ff_h263_decode_end,
2256
    ff_h263_decode_frame,
2257
    CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY | CODEC_CAP_FRAME_THREADS,
2258
    .flush= ff_mpeg_flush,
2259
    .max_lowres= 3,
2260
    .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2"),
2261
    .pix_fmts= ff_hwaccel_pixfmt_list_420,
2262
    .update_thread_context= ONLY_IF_THREADS_ENABLED(ff_mpeg_update_thread_context)
2263
};
2264

    
2265

    
2266
#if CONFIG_MPEG4_VDPAU_DECODER
2267
AVCodec ff_mpeg4_vdpau_decoder = {
2268
    "mpeg4_vdpau",
2269
    AVMEDIA_TYPE_VIDEO,
2270
    CODEC_ID_MPEG4,
2271
    sizeof(MpegEncContext),
2272
    decode_init,
2273
    NULL,
2274
    ff_h263_decode_end,
2275
    ff_h263_decode_frame,
2276
    CODEC_CAP_DR1 | CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
2277
    .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 (VDPAU)"),
2278
    .pix_fmts= (const enum PixelFormat[]){PIX_FMT_VDPAU_MPEG4, PIX_FMT_NONE},
2279
};
2280
#endif