GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/mpeg4videodec.c Lines: 1019 2151 47.4 %
Date: 2020-11-28 20:53:16 Branches: 619 1469 42.1 %

Line Branch Exec Source
1
/*
2
 * MPEG-4 decoder
3
 * Copyright (c) 2000,2001 Fabrice Bellard
4
 * Copyright (c) 2002-2010 Michael Niedermayer <michaelni@gmx.at>
5
 *
6
 * This file is part of FFmpeg.
7
 *
8
 * FFmpeg is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU Lesser General Public
10
 * License as published by the Free Software Foundation; either
11
 * version 2.1 of the License, or (at your option) any later version.
12
 *
13
 * FFmpeg is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16
 * Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Lesser General Public
19
 * License along with FFmpeg; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
 */
22
23
#define UNCHECKED_BITSTREAM_READER 1
24
25
#include "libavutil/internal.h"
26
#include "libavutil/opt.h"
27
#include "libavutil/pixdesc.h"
28
#include "error_resilience.h"
29
#include "hwconfig.h"
30
#include "idctdsp.h"
31
#include "internal.h"
32
#include "mpegutils.h"
33
#include "mpegvideo.h"
34
#include "mpegvideodata.h"
35
#include "mpeg4video.h"
36
#include "h263.h"
37
#include "profiles.h"
38
#include "thread.h"
39
#include "xvididct.h"
40
#include "unary.h"
41
42
/* The defines below define the number of bits that are read at once for
43
 * reading vlc values. Changing these may improve speed and data cache needs
44
 * be aware though that decreasing them may need the number of stages that is
45
 * passed to get_vlc* to be increased. */
46
#define SPRITE_TRAJ_VLC_BITS 6
47
#define DC_VLC_BITS 9
48
#define MB_TYPE_B_VLC_BITS 4
49
#define STUDIO_INTRA_BITS 9
50
51
static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb);
52
53
static VLC dc_lum, dc_chrom;
54
static VLC sprite_trajectory;
55
static VLC mb_type_b_vlc;
56
57
static const int mb_type_b_map[4] = {
58
    MB_TYPE_DIRECT2 | MB_TYPE_L0L1,
59
    MB_TYPE_L0L1    | MB_TYPE_16x16,
60
    MB_TYPE_L1      | MB_TYPE_16x16,
61
    MB_TYPE_L0      | MB_TYPE_16x16,
62
};
63
64
/**
65
 * Predict the ac.
66
 * @param n block index (0-3 are luma, 4-5 are chroma)
67
 * @param dir the ac prediction direction
68
 */
69
1299666
void ff_mpeg4_pred_ac(MpegEncContext *s, int16_t *block, int n, int dir)
70
{
71
    int i;
72
    int16_t *ac_val, *ac_val1;
73
1299666
    int8_t *const qscale_table = s->current_picture.qscale_table;
74
75
    /* find prediction */
76
1299666
    ac_val  = &s->ac_val[0][0][0] + s->block_index[n] * 16;
77
1299666
    ac_val1 = ac_val;
78
1299666
    if (s->ac_pred) {
79
30084
        if (dir == 0) {
80
20713
            const int xy = s->mb_x - 1 + s->mb_y * s->mb_stride;
81
            /* left prediction */
82
20713
            ac_val -= 16;
83
84

20713
            if (s->mb_x == 0 || s->qscale == qscale_table[xy] ||
85
                n == 1 || n == 3) {
86
                /* same qscale */
87
165704
                for (i = 1; i < 8; i++)
88
144991
                    block[s->idsp.idct_permutation[i << 3]] += ac_val[i];
89
            } else {
90
                /* different qscale, we must rescale */
91
                for (i = 1; i < 8; i++)
92
                    block[s->idsp.idct_permutation[i << 3]] += ROUNDED_DIV(ac_val[i] * qscale_table[xy], s->qscale);
93
            }
94
        } else {
95
9371
            const int xy = s->mb_x + s->mb_y * s->mb_stride - s->mb_stride;
96
            /* top prediction */
97
9371
            ac_val -= 16 * s->block_wrap[n];
98
99

9371
            if (s->mb_y == 0 || s->qscale == qscale_table[xy] ||
100
2
                n == 2 || n == 3) {
101
                /* same qscale */
102
74968
                for (i = 1; i < 8; i++)
103
65597
                    block[s->idsp.idct_permutation[i]] += ac_val[i + 8];
104
            } else {
105
                /* different qscale, we must rescale */
106
                for (i = 1; i < 8; i++)
107
                    block[s->idsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8] * qscale_table[xy], s->qscale);
108
            }
109
        }
110
    }
111
    /* left copy */
112
10397328
    for (i = 1; i < 8; i++)
113
9097662
        ac_val1[i] = block[s->idsp.idct_permutation[i << 3]];
114
115
    /* top copy */
116
10397328
    for (i = 1; i < 8; i++)
117
9097662
        ac_val1[8 + i] = block[s->idsp.idct_permutation[i]];
118
1299666
}
119
120
/**
121
 * check if the next stuff is a resync marker or the end.
122
 * @return 0 if not
123
 */
124
1427120
static inline int mpeg4_is_resync(Mpeg4DecContext *ctx)
125
{
126
1427120
    MpegEncContext *s = &ctx->m;
127
1427120
    int bits_count = get_bits_count(&s->gb);
128
1427120
    int v          = show_bits(&s->gb, 16);
129
130

1427120
    if (s->workaround_bugs & FF_BUG_NO_PADDING && !ctx->resync_marker)
131
        return 0;
132
133
1427120
    while (v <= 0xFF) {
134
3299
        if (s->pict_type == AV_PICTURE_TYPE_B ||
135

2300
            (v >> (8 - s->pict_type) != 1) || s->partitioned_frame)
136
            break;
137
        skip_bits(&s->gb, 8 + s->pict_type);
138
        bits_count += 8 + s->pict_type;
139
        v = show_bits(&s->gb, 16);
140
    }
141
142
1427120
    if (bits_count + 8 >= s->gb.size_in_bits) {
143
11669
        v >>= 8;
144
11669
        v  |= 0x7F >> (7 - (bits_count & 7));
145
146
11669
        if (v == 0x7F)
147
11352
            return s->mb_num;
148
    } else {
149
1415451
        if (v == ff_mpeg4_resync_prefix[bits_count & 7]) {
150
            int len, mb_num;
151
4098
            int mb_num_bits = av_log2(s->mb_num - 1) + 1;
152
4098
            GetBitContext gb = s->gb;
153
154
4098
            skip_bits(&s->gb, 1);
155
4098
            align_get_bits(&s->gb);
156
157
72133
            for (len = 0; len < 32; len++)
158
72133
                if (get_bits1(&s->gb))
159
4098
                    break;
160
161
4098
            mb_num = get_bits(&s->gb, mb_num_bits);
162

4098
            if (!mb_num || mb_num > s->mb_num || get_bits_count(&s->gb)+6 > s->gb.size_in_bits)
163
                mb_num= -1;
164
165
4098
            s->gb = gb;
166
167
4098
            if (len >= ff_mpeg4_get_video_packet_prefix_length(s))
168
4096
                return mb_num;
169
        }
170
    }
171
1411672
    return 0;
172
}
173
174
static int mpeg4_decode_sprite_trajectory(Mpeg4DecContext *ctx, GetBitContext *gb)
175
{
176
    MpegEncContext *s = &ctx->m;
177
    int a     = 2 << s->sprite_warping_accuracy;
178
    int rho   = 3  - s->sprite_warping_accuracy;
179
    int r     = 16 / a;
180
    int alpha = 1;
181
    int beta  = 0;
182
    int w     = s->width;
183
    int h     = s->height;
184
    int min_ab, i, w2, h2, w3, h3;
185
    int sprite_ref[4][2];
186
    int virtual_ref[2][2];
187
    int64_t sprite_offset[2][2];
188
    int64_t sprite_delta[2][2];
189
190
    // only true for rectangle shapes
191
    const int vop_ref[4][2] = { { 0, 0 },         { s->width, 0 },
192
                                { 0, s->height }, { s->width, s->height } };
193
    int d[4][2]             = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } };
194
195
    if (w <= 0 || h <= 0)
196
        return AVERROR_INVALIDDATA;
197
198
    /* the decoder was not properly initialized and we cannot continue */
199
    if (sprite_trajectory.table == NULL)
200
        return AVERROR_INVALIDDATA;
201
202
    for (i = 0; i < ctx->num_sprite_warping_points; i++) {
203
        int length;
204
        int x = 0, y = 0;
205
206
        length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 2);
207
        if (length > 0)
208
            x = get_xbits(gb, length);
209
210
        if (!(ctx->divx_version == 500 && ctx->divx_build == 413))
211
            check_marker(s->avctx, gb, "before sprite_trajectory");
212
213
        length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 2);
214
        if (length > 0)
215
            y = get_xbits(gb, length);
216
217
        check_marker(s->avctx, gb, "after sprite_trajectory");
218
        ctx->sprite_traj[i][0] = d[i][0] = x;
219
        ctx->sprite_traj[i][1] = d[i][1] = y;
220
    }
221
    for (; i < 4; i++)
222
        ctx->sprite_traj[i][0] = ctx->sprite_traj[i][1] = 0;
223
224
    while ((1 << alpha) < w)
225
        alpha++;
226
    while ((1 << beta) < h)
227
        beta++;  /* typo in the MPEG-4 std for the definition of w' and h' */
228
    w2 = 1 << alpha;
229
    h2 = 1 << beta;
230
231
    // Note, the 4th point isn't used for GMC
232
    if (ctx->divx_version == 500 && ctx->divx_build == 413) {
233
        sprite_ref[0][0] = a * vop_ref[0][0] + d[0][0];
234
        sprite_ref[0][1] = a * vop_ref[0][1] + d[0][1];
235
        sprite_ref[1][0] = a * vop_ref[1][0] + d[0][0] + d[1][0];
236
        sprite_ref[1][1] = a * vop_ref[1][1] + d[0][1] + d[1][1];
237
        sprite_ref[2][0] = a * vop_ref[2][0] + d[0][0] + d[2][0];
238
        sprite_ref[2][1] = a * vop_ref[2][1] + d[0][1] + d[2][1];
239
    } else {
240
        sprite_ref[0][0] = (a >> 1) * (2 * vop_ref[0][0] + d[0][0]);
241
        sprite_ref[0][1] = (a >> 1) * (2 * vop_ref[0][1] + d[0][1]);
242
        sprite_ref[1][0] = (a >> 1) * (2 * vop_ref[1][0] + d[0][0] + d[1][0]);
243
        sprite_ref[1][1] = (a >> 1) * (2 * vop_ref[1][1] + d[0][1] + d[1][1]);
244
        sprite_ref[2][0] = (a >> 1) * (2 * vop_ref[2][0] + d[0][0] + d[2][0]);
245
        sprite_ref[2][1] = (a >> 1) * (2 * vop_ref[2][1] + d[0][1] + d[2][1]);
246
    }
247
    /* sprite_ref[3][0] = (a >> 1) * (2 * vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);
248
     * sprite_ref[3][1] = (a >> 1) * (2 * vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */
249
250
    /* This is mostly identical to the MPEG-4 std (and is totally unreadable
251
     * because of that...). Perhaps it should be reordered to be more readable.
252
     * The idea behind this virtual_ref mess is to be able to use shifts later
253
     * per pixel instead of divides so the distance between points is converted
254
     * from w&h based to w2&h2 based which are of the 2^x form. */
255
    virtual_ref[0][0] = 16 * (vop_ref[0][0] + w2) +
256
                         ROUNDED_DIV(((w - w2) *
257
                                           (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) +
258
                                      w2 * (r * sprite_ref[1][0] - 16LL * vop_ref[1][0])), w);
259
    virtual_ref[0][1] = 16 * vop_ref[0][1] +
260
                        ROUNDED_DIV(((w - w2) *
261
                                          (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) +
262
                                     w2 * (r * sprite_ref[1][1] - 16LL * vop_ref[1][1])), w);
263
    virtual_ref[1][0] = 16 * vop_ref[0][0] +
264
                        ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) +
265
                                           h2 * (r * sprite_ref[2][0] - 16LL * vop_ref[2][0])), h);
266
    virtual_ref[1][1] = 16 * (vop_ref[0][1] + h2) +
267
                        ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) +
268
                                           h2 * (r * sprite_ref[2][1] - 16LL * vop_ref[2][1])), h);
269
270
    switch (ctx->num_sprite_warping_points) {
271
    case 0:
272
        sprite_offset[0][0]    =
273
        sprite_offset[0][1]    =
274
        sprite_offset[1][0]    =
275
        sprite_offset[1][1]    = 0;
276
        sprite_delta[0][0]     = a;
277
        sprite_delta[0][1]     =
278
        sprite_delta[1][0]     = 0;
279
        sprite_delta[1][1]     = a;
280
        ctx->sprite_shift[0]   =
281
        ctx->sprite_shift[1]   = 0;
282
        break;
283
    case 1:     // GMC only
284
        sprite_offset[0][0]    = sprite_ref[0][0] - a * vop_ref[0][0];
285
        sprite_offset[0][1]    = sprite_ref[0][1] - a * vop_ref[0][1];
286
        sprite_offset[1][0]    = ((sprite_ref[0][0] >> 1) | (sprite_ref[0][0] & 1)) -
287
                                 a * (vop_ref[0][0] / 2);
288
        sprite_offset[1][1]    = ((sprite_ref[0][1] >> 1) | (sprite_ref[0][1] & 1)) -
289
                                 a * (vop_ref[0][1] / 2);
290
        sprite_delta[0][0]     = a;
291
        sprite_delta[0][1]     =
292
        sprite_delta[1][0]     = 0;
293
        sprite_delta[1][1]     = a;
294
        ctx->sprite_shift[0]   =
295
        ctx->sprite_shift[1]   = 0;
296
        break;
297
    case 2:
298
        sprite_offset[0][0]    = ((int64_t)      sprite_ref[0][0] * (1 << alpha + rho)) +
299
                                 ((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) *
300
                                 ((int64_t)        -vop_ref[0][0]) +
301
                                 ((int64_t)  r * sprite_ref[0][1] - virtual_ref[0][1]) *
302
                                 ((int64_t)        -vop_ref[0][1]) + (1 << (alpha + rho - 1));
303
        sprite_offset[0][1]    = ((int64_t)      sprite_ref[0][1] * (1 << alpha + rho)) +
304
                                 ((int64_t) -r * sprite_ref[0][1] + virtual_ref[0][1]) *
305
                                 ((int64_t)        -vop_ref[0][0]) +
306
                                 ((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) *
307
                                 ((int64_t)        -vop_ref[0][1]) + (1 << (alpha + rho - 1));
308
        sprite_offset[1][0]    = (((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) *
309
                                  ((int64_t)-2 *    vop_ref[0][0] + 1) +
310
                                  ((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) *
311
                                  ((int64_t)-2 *    vop_ref[0][1] + 1) + 2 * w2 * r *
312
                                   (int64_t)     sprite_ref[0][0] - 16 * w2 + (1 << (alpha + rho + 1)));
313
        sprite_offset[1][1]    = (((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) *
314
                                  ((int64_t)-2 *    vop_ref[0][0] + 1) +
315
                                  ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) *
316
                                  ((int64_t)-2 *    vop_ref[0][1] + 1) + 2 * w2 * r *
317
                                  (int64_t)      sprite_ref[0][1] - 16 * w2 + (1 << (alpha + rho + 1)));
318
        sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]);
319
        sprite_delta[0][1] = (+r * sprite_ref[0][1] - virtual_ref[0][1]);
320
        sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]);
321
        sprite_delta[1][1] = (-r * sprite_ref[0][0] + virtual_ref[0][0]);
322
323
        ctx->sprite_shift[0]  = alpha + rho;
324
        ctx->sprite_shift[1]  = alpha + rho + 2;
325
        break;
326
    case 3:
327
        min_ab = FFMIN(alpha, beta);
328
        w3     = w2 >> min_ab;
329
        h3     = h2 >> min_ab;
330
        sprite_offset[0][0]    = ((int64_t)sprite_ref[0][0] * (1 << (alpha + beta + rho - min_ab))) +
331
                                 ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-vop_ref[0][0]) +
332
                                 ((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-vop_ref[0][1]) +
333
                                 ((int64_t)1 << (alpha + beta + rho - min_ab - 1));
334
        sprite_offset[0][1]    = ((int64_t)sprite_ref[0][1] * (1 << (alpha + beta + rho - min_ab))) +
335
                                 ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-vop_ref[0][0]) +
336
                                 ((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-vop_ref[0][1]) +
337
                                 ((int64_t)1 << (alpha + beta + rho - min_ab - 1));
338
        sprite_offset[1][0]    = ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-2 * vop_ref[0][0] + 1) +
339
                                 ((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-2 * vop_ref[0][1] + 1) +
340
                                  (int64_t)2 * w2 * h3 * r * sprite_ref[0][0] - 16 * w2 * h3 +
341
                                 ((int64_t)1 << (alpha + beta + rho - min_ab + 1));
342
        sprite_offset[1][1]    = ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-2 * vop_ref[0][0] + 1) +
343
                                 ((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-2 * vop_ref[0][1] + 1) +
344
                                  (int64_t)2 * w2 * h3 * r * sprite_ref[0][1] - 16 * w2 * h3 +
345
                                 ((int64_t)1 << (alpha + beta + rho - min_ab + 1));
346
        sprite_delta[0][0] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[0][0]) * h3;
347
        sprite_delta[0][1] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[1][0]) * w3;
348
        sprite_delta[1][0] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[0][1]) * h3;
349
        sprite_delta[1][1] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[1][1]) * w3;
350
351
        ctx->sprite_shift[0]  = alpha + beta + rho - min_ab;
352
        ctx->sprite_shift[1]  = alpha + beta + rho - min_ab + 2;
353
        break;
354
    }
355
    /* try to simplify the situation */
356
    if (sprite_delta[0][0] == a << ctx->sprite_shift[0] &&
357
        sprite_delta[0][1] == 0 &&
358
        sprite_delta[1][0] == 0 &&
359
        sprite_delta[1][1] == a << ctx->sprite_shift[0]) {
360
        sprite_offset[0][0] >>= ctx->sprite_shift[0];
361
        sprite_offset[0][1] >>= ctx->sprite_shift[0];
362
        sprite_offset[1][0] >>= ctx->sprite_shift[1];
363
        sprite_offset[1][1] >>= ctx->sprite_shift[1];
364
        sprite_delta[0][0] = a;
365
        sprite_delta[0][1] = 0;
366
        sprite_delta[1][0] = 0;
367
        sprite_delta[1][1] = a;
368
        ctx->sprite_shift[0] = 0;
369
        ctx->sprite_shift[1] = 0;
370
        s->real_sprite_warping_points = 1;
371
    } else {
372
        int shift_y = 16 - ctx->sprite_shift[0];
373
        int shift_c = 16 - ctx->sprite_shift[1];
374
375
        for (i = 0; i < 2; i++) {
376
            if (shift_c < 0 || shift_y < 0 ||
377
                FFABS(  sprite_offset[0][i]) >= INT_MAX >> shift_y  ||
378
                FFABS(  sprite_offset[1][i]) >= INT_MAX >> shift_c  ||
379
                FFABS(   sprite_delta[0][i]) >= INT_MAX >> shift_y  ||
380
                FFABS(   sprite_delta[1][i]) >= INT_MAX >> shift_y
381
            ) {
382
                avpriv_request_sample(s->avctx, "Too large sprite shift, delta or offset");
383
                goto overflow;
384
            }
385
        }
386
387
        for (i = 0; i < 2; i++) {
388
            sprite_offset[0][i]    *= 1 << shift_y;
389
            sprite_offset[1][i]    *= 1 << shift_c;
390
            sprite_delta[0][i]     *= 1 << shift_y;
391
            sprite_delta[1][i]     *= 1 << shift_y;
392
            ctx->sprite_shift[i]     = 16;
393
394
        }
395
        for (i = 0; i < 2; i++) {
396
            int64_t sd[2] = {
397
                sprite_delta[i][0] - a * (1LL<<16),
398
                sprite_delta[i][1] - a * (1LL<<16)
399
            };
400
401
            if (llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL)) >= INT_MAX ||
402
                llabs(sprite_offset[0][i] + sprite_delta[i][1] * (h+16LL)) >= INT_MAX ||
403
                llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL) + sprite_delta[i][1] * (h+16LL)) >= INT_MAX ||
404
                llabs(sprite_delta[i][0] * (w+16LL)) >= INT_MAX ||
405
                llabs(sprite_delta[i][1] * (h+16LL)) >= INT_MAX ||
406
                llabs(sd[0]) >= INT_MAX ||
407
                llabs(sd[1]) >= INT_MAX ||
408
                llabs(sprite_offset[0][i] + sd[0] * (w+16LL)) >= INT_MAX ||
409
                llabs(sprite_offset[0][i] + sd[1] * (h+16LL)) >= INT_MAX ||
410
                llabs(sprite_offset[0][i] + sd[0] * (w+16LL) + sd[1] * (h+16LL)) >= INT_MAX
411
            ) {
412
                avpriv_request_sample(s->avctx, "Overflow on sprite points");
413
                goto overflow;
414
            }
415
        }
416
        s->real_sprite_warping_points = ctx->num_sprite_warping_points;
417
    }
418
419
    for (i = 0; i < 4; i++) {
420
        s->sprite_offset[i&1][i>>1] = sprite_offset[i&1][i>>1];
421
        s->sprite_delta [i&1][i>>1] = sprite_delta [i&1][i>>1];
422
    }
423
424
    return 0;
425
overflow:
426
    memset(s->sprite_offset, 0, sizeof(s->sprite_offset));
427
    memset(s->sprite_delta, 0, sizeof(s->sprite_delta));
428
    return AVERROR_PATCHWELCOME;
429
}
430
431
static int decode_new_pred(Mpeg4DecContext *ctx, GetBitContext *gb) {
432
    MpegEncContext *s = &ctx->m;
433
    int len = FFMIN(ctx->time_increment_bits + 3, 15);
434
435
    get_bits(gb, len);
436
    if (get_bits1(gb))
437
        get_bits(gb, len);
438
    check_marker(s->avctx, gb, "after new_pred");
439
440
    return 0;
441
}
442
443
/**
444
 * Decode the next video packet.
445
 * @return <0 if something went wrong
446
 */
447
3867
int ff_mpeg4_decode_video_packet_header(Mpeg4DecContext *ctx)
448
{
449
3867
    MpegEncContext *s = &ctx->m;
450
451
3867
    int mb_num_bits      = av_log2(s->mb_num - 1) + 1;
452
3867
    int header_extension = 0, mb_num, len;
453
454
    /* is there enough space left for a video packet + header */
455
3867
    if (get_bits_count(&s->gb) > s->gb.size_in_bits - 20)
456
        return AVERROR_INVALIDDATA;
457
458
68178
    for (len = 0; len < 32; len++)
459
68178
        if (get_bits1(&s->gb))
460
3867
            break;
461
462
3867
    if (len != ff_mpeg4_get_video_packet_prefix_length(s)) {
463
        av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n");
464
        return AVERROR_INVALIDDATA;
465
    }
466
467
3867
    if (ctx->shape != RECT_SHAPE) {
468
        header_extension = get_bits1(&s->gb);
469
        // FIXME more stuff here
470
    }
471
472
3867
    mb_num = get_bits(&s->gb, mb_num_bits);
473

3867
    if (mb_num >= s->mb_num || !mb_num) {
474
        av_log(s->avctx, AV_LOG_ERROR,
475
               "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
476
        return AVERROR_INVALIDDATA;
477
    }
478
479
3867
    s->mb_x = mb_num % s->mb_width;
480
3867
    s->mb_y = mb_num / s->mb_width;
481
482
3867
    if (ctx->shape != BIN_ONLY_SHAPE) {
483
3867
        int qscale = get_bits(&s->gb, s->quant_precision);
484
3867
        if (qscale)
485
3867
            s->chroma_qscale = s->qscale = qscale;
486
    }
487
488
3867
    if (ctx->shape == RECT_SHAPE)
489
3867
        header_extension = get_bits1(&s->gb);
490
491
3867
    if (header_extension) {
492
        int time_incr = 0;
493
494
        while (get_bits1(&s->gb) != 0)
495
            time_incr++;
496
497
        check_marker(s->avctx, &s->gb, "before time_increment in video packed header");
498
        skip_bits(&s->gb, ctx->time_increment_bits);      /* time_increment */
499
        check_marker(s->avctx, &s->gb, "before vop_coding_type in video packed header");
500
501
        skip_bits(&s->gb, 2); /* vop coding type */
502
        // FIXME not rect stuff here
503
504
        if (ctx->shape != BIN_ONLY_SHAPE) {
505
            skip_bits(&s->gb, 3); /* intra dc vlc threshold */
506
            // FIXME don't just ignore everything
507
            if (s->pict_type == AV_PICTURE_TYPE_S &&
508
                ctx->vol_sprite_usage == GMC_SPRITE) {
509
                if (mpeg4_decode_sprite_trajectory(ctx, &s->gb) < 0)
510
                    return AVERROR_INVALIDDATA;
511
                av_log(s->avctx, AV_LOG_ERROR, "untested\n");
512
            }
513
514
            // FIXME reduced res stuff here
515
516
            if (s->pict_type != AV_PICTURE_TYPE_I) {
517
                int f_code = get_bits(&s->gb, 3);       /* fcode_for */
518
                if (f_code == 0)
519
                    av_log(s->avctx, AV_LOG_ERROR,
520
                           "Error, video packet header damaged (f_code=0)\n");
521
            }
522
            if (s->pict_type == AV_PICTURE_TYPE_B) {
523
                int b_code = get_bits(&s->gb, 3);
524
                if (b_code == 0)
525
                    av_log(s->avctx, AV_LOG_ERROR,
526
                           "Error, video packet header damaged (b_code=0)\n");
527
            }
528
        }
529
    }
530
3867
    if (ctx->new_pred)
531
        decode_new_pred(ctx, &s->gb);
532
533
3867
    return 0;
534
}
535
536
static void reset_studio_dc_predictors(MpegEncContext *s)
537
{
538
    /* Reset DC Predictors */
539
    s->last_dc[0] =
540
    s->last_dc[1] =
541
    s->last_dc[2] = 1 << (s->avctx->bits_per_raw_sample + s->dct_precision + s->intra_dc_precision - 1);
542
}
543
544
/**
545
 * Decode the next video packet.
546
 * @return <0 if something went wrong
547
 */
548
int ff_mpeg4_decode_studio_slice_header(Mpeg4DecContext *ctx)
549
{
550
    MpegEncContext *s = &ctx->m;
551
    GetBitContext *gb = &s->gb;
552
    unsigned vlc_len;
553
    uint16_t mb_num;
554
555
    if (get_bits_left(gb) >= 32 && get_bits_long(gb, 32) == SLICE_START_CODE) {
556
        vlc_len = av_log2(s->mb_width * s->mb_height) + 1;
557
        mb_num = get_bits(gb, vlc_len);
558
559
        if (mb_num >= s->mb_num)
560
            return AVERROR_INVALIDDATA;
561
562
        s->mb_x = mb_num % s->mb_width;
563
        s->mb_y = mb_num / s->mb_width;
564
565
        if (ctx->shape != BIN_ONLY_SHAPE)
566
            s->qscale = mpeg_get_qscale(s);
567
568
        if (get_bits1(gb)) {  /* slice_extension_flag */
569
            skip_bits1(gb);   /* intra_slice */
570
            skip_bits1(gb);   /* slice_VOP_id_enable */
571
            skip_bits(gb, 6); /* slice_VOP_id */
572
            while (get_bits1(gb)) /* extra_bit_slice */
573
                skip_bits(gb, 8); /* extra_information_slice */
574
        }
575
576
        reset_studio_dc_predictors(s);
577
    }
578
    else {
579
        return AVERROR_INVALIDDATA;
580
    }
581
582
    return 0;
583
}
584
585
/**
586
 * Get the average motion vector for a GMC MB.
587
 * @param n either 0 for the x component or 1 for y
588
 * @return the average MV for a GMC MB
589
 */
590
static inline int get_amv(Mpeg4DecContext *ctx, int n)
591
{
592
    MpegEncContext *s = &ctx->m;
593
    int x, y, mb_v, sum, dx, dy, shift;
594
    int len     = 1 << (s->f_code + 4);
595
    const int a = s->sprite_warping_accuracy;
596
597
    if (s->workaround_bugs & FF_BUG_AMV)
598
        len >>= s->quarter_sample;
599
600
    if (s->real_sprite_warping_points == 1) {
601
        if (ctx->divx_version == 500 && ctx->divx_build == 413 && a >= s->quarter_sample)
602
            sum = s->sprite_offset[0][n] / (1 << (a - s->quarter_sample));
603
        else
604
            sum = RSHIFT(s->sprite_offset[0][n] * (1 << s->quarter_sample), a);
605
    } else {
606
        dx    = s->sprite_delta[n][0];
607
        dy    = s->sprite_delta[n][1];
608
        shift = ctx->sprite_shift[0];
609
        if (n)
610
            dy -= 1 << (shift + a + 1);
611
        else
612
            dx -= 1 << (shift + a + 1);
613
        mb_v = s->sprite_offset[0][n] + dx * s->mb_x * 16U + dy * s->mb_y * 16U;
614
615
        sum = 0;
616
        for (y = 0; y < 16; y++) {
617
            int v;
618
619
            v = mb_v + dy * y;
620
            // FIXME optimize
621
            for (x = 0; x < 16; x++) {
622
                sum += v >> shift;
623
                v   += dx;
624
            }
625
        }
626
        sum = RSHIFT(sum, a + 8 - s->quarter_sample);
627
    }
628
629
    if (sum < -len)
630
        sum = -len;
631
    else if (sum >= len)
632
        sum = len - 1;
633
634
    return sum;
635
}
636
637
/**
638
 * Decode the dc value.
639
 * @param n block index (0-3 are luma, 4-5 are chroma)
640
 * @param dir_ptr the prediction direction will be stored here
641
 * @return the quantized dc
642
 */
643
1068954
static inline int mpeg4_decode_dc(MpegEncContext *s, int n, int *dir_ptr)
644
{
645
    int level, code;
646
647
1068954
    if (n < 4)
648
712636
        code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1);
649
    else
650
356318
        code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1);
651
652

1068954
    if (code < 0 || code > 9 /* && s->nbit < 9 */) {
653
        av_log(s->avctx, AV_LOG_ERROR, "illegal dc vlc\n");
654
        return AVERROR_INVALIDDATA;
655
    }
656
657
1068954
    if (code == 0) {
658
156549
        level = 0;
659
    } else {
660
        if (IS_3IV1) {
661
            if (code == 1)
662
                level = 2 * get_bits1(&s->gb) - 1;
663
            else {
664
                if (get_bits1(&s->gb))
665
                    level = get_bits(&s->gb, code - 1) + (1 << (code - 1));
666
                else
667
                    level = -get_bits(&s->gb, code - 1) - (1 << (code - 1));
668
            }
669
        } else {
670
912405
            level = get_xbits(&s->gb, code);
671
        }
672
673
912405
        if (code > 8) {
674
            if (get_bits1(&s->gb) == 0) { /* marker */
675
                if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT)) {
676
                    av_log(s->avctx, AV_LOG_ERROR, "dc marker bit missing\n");
677
                    return AVERROR_INVALIDDATA;
678
                }
679
            }
680
        }
681
    }
682
683
1068954
    return ff_mpeg4_pred_dc(s, n, level, dir_ptr, 0);
684
}
685
686
/**
687
 * Decode first partition.
688
 * @return number of MBs decoded or <0 if an error occurred
689
 */
690
1728
static int mpeg4_decode_partition_a(Mpeg4DecContext *ctx)
691
{
692
1728
    MpegEncContext *s = &ctx->m;
693
1728
    int mb_num = 0;
694
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
695
696
    /* decode first partition */
697
1728
    s->first_slice_line = 1;
698
8311
    for (; s->mb_y < s->mb_height; s->mb_y++) {
699
7839
        ff_init_block_index(s);
700
145903
        for (; s->mb_x < s->mb_width; s->mb_x++) {
701
139320
            const int xy = s->mb_x + s->mb_y * s->mb_stride;
702
            int cbpc;
703
139320
            int dir = 0;
704
705
139320
            mb_num++;
706
139320
            ff_update_block_index(s);
707

139320
            if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1)
708
1611
                s->first_slice_line = 0;
709
710
139320
            if (s->pict_type == AV_PICTURE_TYPE_I) {
711
                int i;
712
713
                do {
714
17762
                    if (show_bits(&s->gb, 19) == DC_MARKER)
715
439
                        return mb_num - 1;
716
717
17323
                    cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
718
17323
                    if (cbpc < 0) {
719
                        av_log(s->avctx, AV_LOG_ERROR,
720
                               "mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
721
                        return AVERROR_INVALIDDATA;
722
                    }
723
17323
                } while (cbpc == 8);
724
725
17323
                s->cbp_table[xy]               = cbpc & 3;
726
17323
                s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
727
17323
                s->mb_intra                    = 1;
728
729
17323
                if (cbpc & 4)
730
                    ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
731
732
17323
                s->current_picture.qscale_table[xy] = s->qscale;
733
734
17323
                s->mbintra_table[xy] = 1;
735
121261
                for (i = 0; i < 6; i++) {
736
                    int dc_pred_dir;
737
103938
                    int dc = mpeg4_decode_dc(s, i, &dc_pred_dir);
738
103938
                    if (dc < 0) {
739
                        av_log(s->avctx, AV_LOG_ERROR,
740
                               "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
741
                        return dc;
742
                    }
743
103938
                    dir <<= 1;
744
103938
                    if (dc_pred_dir)
745
30118
                        dir |= 1;
746
                }
747
17323
                s->pred_dir_table[xy] = dir;
748
            } else { /* P/S_TYPE */
749
                int mx, my, pred_x, pred_y, bits;
750
121558
                int16_t *const mot_val = s->current_picture.motion_val[0][s->block_index[0]];
751
121558
                const int stride       = s->b8_stride * 2;
752
753
121558
try_again:
754
121558
                bits = show_bits(&s->gb, 17);
755
121558
                if (bits == MOTION_MARKER)
756
817
                    return mb_num - 1;
757
758
120741
                skip_bits1(&s->gb);
759
120741
                if (bits & 0x10000) {
760
                    /* skip mb */
761
997
                    if (s->pict_type == AV_PICTURE_TYPE_S &&
762
                        ctx->vol_sprite_usage == GMC_SPRITE) {
763
                        s->current_picture.mb_type[xy] = MB_TYPE_SKIP  |
764
                                                         MB_TYPE_16x16 |
765
                                                         MB_TYPE_GMC   |
766
                                                         MB_TYPE_L0;
767
                        mx = get_amv(ctx, 0);
768
                        my = get_amv(ctx, 1);
769
                    } else {
770
997
                        s->current_picture.mb_type[xy] = MB_TYPE_SKIP  |
771
                                                         MB_TYPE_16x16 |
772
                                                         MB_TYPE_L0;
773
997
                        mx = my = 0;
774
                    }
775
997
                    mot_val[0]          =
776
997
                    mot_val[2]          =
777
997
                    mot_val[0 + stride] =
778
997
                    mot_val[2 + stride] = mx;
779
997
                    mot_val[1]          =
780
997
                    mot_val[3]          =
781
997
                    mot_val[1 + stride] =
782
997
                    mot_val[3 + stride] = my;
783
784
997
                    if (s->mbintra_table[xy])
785
224
                        ff_clean_intra_table_entries(s);
786
997
                    continue;
787
                }
788
789
119744
                cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
790
119744
                if (cbpc < 0) {
791
                    av_log(s->avctx, AV_LOG_ERROR,
792
                           "mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
793
                    return AVERROR_INVALIDDATA;
794
                }
795
119744
                if (cbpc == 20)
796
                    goto try_again;
797
798
119744
                s->cbp_table[xy] = cbpc & (8 + 3);  // 8 is dquant
799
800
119744
                s->mb_intra = ((cbpc & 4) != 0);
801
802
119744
                if (s->mb_intra) {
803
6287
                    s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
804
6287
                    s->mbintra_table[xy] = 1;
805
6287
                    mot_val[0]          =
806
6287
                    mot_val[2]          =
807
6287
                    mot_val[0 + stride] =
808
6287
                    mot_val[2 + stride] = 0;
809
6287
                    mot_val[1]          =
810
6287
                    mot_val[3]          =
811
6287
                    mot_val[1 + stride] =
812
6287
                    mot_val[3 + stride] = 0;
813
                } else {
814
113457
                    if (s->mbintra_table[xy])
815
19851
                        ff_clean_intra_table_entries(s);
816
817
113457
                    if (s->pict_type == AV_PICTURE_TYPE_S &&
818
                        ctx->vol_sprite_usage == GMC_SPRITE &&
819
                        (cbpc & 16) == 0)
820
                        s->mcsel = get_bits1(&s->gb);
821
                    else
822
113457
                        s->mcsel = 0;
823
824
113457
                    if ((cbpc & 16) == 0) {
825
                        /* 16x16 motion prediction */
826
827
81626
                        ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
828
81626
                        if (!s->mcsel) {
829
81626
                            mx = ff_h263_decode_motion(s, pred_x, s->f_code);
830
81626
                            if (mx >= 0xffff)
831
                                return AVERROR_INVALIDDATA;
832
833
81626
                            my = ff_h263_decode_motion(s, pred_y, s->f_code);
834
81626
                            if (my >= 0xffff)
835
                                return AVERROR_INVALIDDATA;
836
81626
                            s->current_picture.mb_type[xy] = MB_TYPE_16x16 |
837
                                                             MB_TYPE_L0;
838
                        } else {
839
                            mx = get_amv(ctx, 0);
840
                            my = get_amv(ctx, 1);
841
                            s->current_picture.mb_type[xy] = MB_TYPE_16x16 |
842
                                                             MB_TYPE_GMC   |
843
                                                             MB_TYPE_L0;
844
                        }
845
846
81626
                        mot_val[0]          =
847
81626
                        mot_val[2]          =
848
81626
                        mot_val[0 + stride] =
849
81626
                        mot_val[2 + stride] = mx;
850
81626
                        mot_val[1]          =
851
81626
                        mot_val[3]          =
852
81626
                        mot_val[1 + stride] =
853
81626
                        mot_val[3 + stride] = my;
854
                    } else {
855
                        int i;
856
31831
                        s->current_picture.mb_type[xy] = MB_TYPE_8x8 |
857
                                                         MB_TYPE_L0;
858
159155
                        for (i = 0; i < 4; i++) {
859
127324
                            int16_t *mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
860
127324
                            mx = ff_h263_decode_motion(s, pred_x, s->f_code);
861
127324
                            if (mx >= 0xffff)
862
                                return AVERROR_INVALIDDATA;
863
864
127324
                            my = ff_h263_decode_motion(s, pred_y, s->f_code);
865
127324
                            if (my >= 0xffff)
866
                                return AVERROR_INVALIDDATA;
867
127324
                            mot_val[0] = mx;
868
127324
                            mot_val[1] = my;
869
                        }
870
                    }
871
                }
872
            }
873
        }
874
6583
        s->mb_x = 0;
875
    }
876
877
472
    return mb_num;
878
}
879
880
/**
881
 * decode second partition.
882
 * @return <0 if an error occurred
883
 */
884
1728
static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count)
885
{
886
1728
    int mb_num = 0;
887
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
888
889
1728
    s->mb_x = s->resync_mb_x;
890
1728
    s->first_slice_line = 1;
891
7728
    for (s->mb_y = s->resync_mb_y; mb_num < mb_count; s->mb_y++) {
892
7728
        ff_init_block_index(s);
893

145792
        for (; mb_num < mb_count && s->mb_x < s->mb_width; s->mb_x++) {
894
138064
            const int xy = s->mb_x + s->mb_y * s->mb_stride;
895
896
138064
            mb_num++;
897
138064
            ff_update_block_index(s);
898

138064
            if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1)
899
1611
                s->first_slice_line = 0;
900
901
138064
            if (s->pict_type == AV_PICTURE_TYPE_I) {
902
17323
                int ac_pred = get_bits1(&s->gb);
903
17323
                int cbpy    = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
904
17323
                if (cbpy < 0) {
905
                    av_log(s->avctx, AV_LOG_ERROR,
906
                           "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
907
                    return AVERROR_INVALIDDATA;
908
                }
909
910
17323
                s->cbp_table[xy]               |= cbpy << 2;
911
17323
                s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED;
912
            } else { /* P || S_TYPE */
913
120741
                if (IS_INTRA(s->current_picture.mb_type[xy])) {
914
                    int i;
915
6287
                    int dir     = 0;
916
6287
                    int ac_pred = get_bits1(&s->gb);
917
6287
                    int cbpy    = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
918
919
6287
                    if (cbpy < 0) {
920
                        av_log(s->avctx, AV_LOG_ERROR,
921
                               "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
922
                        return AVERROR_INVALIDDATA;
923
                    }
924
925
6287
                    if (s->cbp_table[xy] & 8)
926
                        ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
927
6287
                    s->current_picture.qscale_table[xy] = s->qscale;
928
929
44009
                    for (i = 0; i < 6; i++) {
930
                        int dc_pred_dir;
931
37722
                        int dc = mpeg4_decode_dc(s, i, &dc_pred_dir);
932
37722
                        if (dc < 0) {
933
                            av_log(s->avctx, AV_LOG_ERROR,
934
                                   "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
935
                            return dc;
936
                        }
937
37722
                        dir <<= 1;
938
37722
                        if (dc_pred_dir)
939
11780
                            dir |= 1;
940
                    }
941
6287
                    s->cbp_table[xy]               &= 3;  // remove dquant
942
6287
                    s->cbp_table[xy]               |= cbpy << 2;
943
6287
                    s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED;
944
6287
                    s->pred_dir_table[xy]           = dir;
945
114454
                } else if (IS_SKIP(s->current_picture.mb_type[xy])) {
946
997
                    s->current_picture.qscale_table[xy] = s->qscale;
947
997
                    s->cbp_table[xy]                    = 0;
948
                } else {
949
113457
                    int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
950
951
113457
                    if (cbpy < 0) {
952
                        av_log(s->avctx, AV_LOG_ERROR,
953
                               "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
954
                        return AVERROR_INVALIDDATA;
955
                    }
956
957
113457
                    if (s->cbp_table[xy] & 8)
958
                        ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
959
113457
                    s->current_picture.qscale_table[xy] = s->qscale;
960
961
113457
                    s->cbp_table[xy] &= 3;  // remove dquant
962
113457
                    s->cbp_table[xy] |= (cbpy ^ 0xf) << 2;
963
                }
964
            }
965
        }
966
7728
        if (mb_num >= mb_count)
967
1728
            return 0;
968
6000
        s->mb_x = 0;
969
    }
970
    return 0;
971
}
972
973
/**
974
 * Decode the first and second partition.
975
 * @return <0 if error (and sets error type in the error_status_table)
976
 */
977
1728
int ff_mpeg4_decode_partitions(Mpeg4DecContext *ctx)
978
{
979
1728
    MpegEncContext *s = &ctx->m;
980
    int mb_num;
981
    int ret;
982
1728
    const int part_a_error = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_ERROR | ER_MV_ERROR) : ER_MV_ERROR;
983
1728
    const int part_a_end   = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_END   | ER_MV_END)   : ER_MV_END;
984
985
1728
    mb_num = mpeg4_decode_partition_a(ctx);
986
1728
    if (mb_num <= 0) {
987
        ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
988
                        s->mb_x, s->mb_y, part_a_error);
989
        return mb_num ? mb_num : AVERROR_INVALIDDATA;
990
    }
991
992
1728
    if (s->resync_mb_x + s->resync_mb_y * s->mb_width + mb_num > s->mb_num) {
993
        av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n");
994
        ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
995
                        s->mb_x, s->mb_y, part_a_error);
996
        return AVERROR_INVALIDDATA;
997
    }
998
999
1728
    s->mb_num_left = mb_num;
1000
1001
1728
    if (s->pict_type == AV_PICTURE_TYPE_I) {
1002
499
        while (show_bits(&s->gb, 9) == 1)
1003
            skip_bits(&s->gb, 9);
1004
499
        if (get_bits(&s->gb, 19) != DC_MARKER) {
1005
            av_log(s->avctx, AV_LOG_ERROR,
1006
                   "marker missing after first I partition at %d %d\n",
1007
                   s->mb_x, s->mb_y);
1008
            return AVERROR_INVALIDDATA;
1009
        }
1010
    } else {
1011
1229
        while (show_bits(&s->gb, 10) == 1)
1012
            skip_bits(&s->gb, 10);
1013
1229
        if (get_bits(&s->gb, 17) != MOTION_MARKER) {
1014
            av_log(s->avctx, AV_LOG_ERROR,
1015
                   "marker missing after first P partition at %d %d\n",
1016
                   s->mb_x, s->mb_y);
1017
            return AVERROR_INVALIDDATA;
1018
        }
1019
    }
1020
1728
    ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
1021
1728
                    s->mb_x - 1, s->mb_y, part_a_end);
1022
1023
1728
    ret = mpeg4_decode_partition_b(s, mb_num);
1024
1728
    if (ret < 0) {
1025
        if (s->pict_type == AV_PICTURE_TYPE_P)
1026
            ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
1027
                            s->mb_x, s->mb_y, ER_DC_ERROR);
1028
        return ret;
1029
    } else {
1030
1728
        if (s->pict_type == AV_PICTURE_TYPE_P)
1031
1229
            ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
1032
1229
                            s->mb_x - 1, s->mb_y, ER_DC_END);
1033
    }
1034
1035
1728
    return 0;
1036
}
1037
1038
/**
1039
 * Decode a block.
1040
 * @return <0 if an error occurred
1041
 */
1042
7873800
static inline int mpeg4_decode_block(Mpeg4DecContext *ctx, int16_t *block,
1043
                                     int n, int coded, int intra, int rvlc)
1044
{
1045
7873800
    MpegEncContext *s = &ctx->m;
1046
    int level, i, last, run, qmul, qadd;
1047
7873800
    int av_uninit(dc_pred_dir);
1048
    RLTable *rl;
1049
    RL_VLC_ELEM *rl_vlc;
1050
    const uint8_t *scan_table;
1051
1052
    // Note intra & rvlc should be optimized away if this is inlined
1053
1054
7873800
    if (intra) {
1055
1068954
        if (ctx->use_intra_dc_vlc) {
1056
            /* DC coef */
1057
1068954
            if (s->partitioned_frame) {
1058
141660
                level = s->dc_val[0][s->block_index[n]];
1059
141660
                if (n < 4)
1060
94440
                    level = FASTDIV((level + (s->y_dc_scale >> 1)), s->y_dc_scale);
1061
                else
1062
47220
                    level = FASTDIV((level + (s->c_dc_scale >> 1)), s->c_dc_scale);
1063
141660
                dc_pred_dir = (s->pred_dir_table[s->mb_x + s->mb_y * s->mb_stride] << n) & 32;
1064
            } else {
1065
927294
                level = mpeg4_decode_dc(s, n, &dc_pred_dir);
1066
927294
                if (level < 0)
1067
                    return level;
1068
            }
1069
1068954
            block[0] = level;
1070
1068954
            i        = 0;
1071
        } else {
1072
            i = -1;
1073
            ff_mpeg4_pred_dc(s, n, 0, &dc_pred_dir, 0);
1074
        }
1075
1068954
        if (!coded)
1076
215012
            goto not_coded;
1077
1078
853942
        if (rvlc) {
1079
            rl     = &ff_rvlc_rl_intra;
1080
            rl_vlc = ff_rvlc_rl_intra.rl_vlc[0];
1081
        } else {
1082
853942
            rl     = &ff_mpeg4_rl_intra;
1083
853942
            rl_vlc = ff_mpeg4_rl_intra.rl_vlc[0];
1084
        }
1085
853942
        if (s->ac_pred) {
1086
22081
            if (dc_pred_dir == 0)
1087
15515
                scan_table = s->intra_v_scantable.permutated;  /* left */
1088
            else
1089
6566
                scan_table = s->intra_h_scantable.permutated;  /* top */
1090
        } else {
1091
831861
            scan_table = s->intra_scantable.permutated;
1092
        }
1093
853942
        qmul = 1;
1094
853942
        qadd = 0;
1095
    } else {
1096
6804846
        i = -1;
1097
6804846
        if (!coded) {
1098
4621462
            s->block_last_index[n] = i;
1099
4621462
            return 0;
1100
        }
1101
2183384
        if (rvlc)
1102
            rl = &ff_rvlc_rl_inter;
1103
        else
1104
2183384
            rl = &ff_h263_rl_inter;
1105
1106
2183384
        scan_table = s->intra_scantable.permutated;
1107
1108
2183384
        if (s->mpeg_quant) {
1109
11882
            qmul = 1;
1110
11882
            qadd = 0;
1111
11882
            if (rvlc)
1112
                rl_vlc = ff_rvlc_rl_inter.rl_vlc[0];
1113
            else
1114
11882
                rl_vlc = ff_h263_rl_inter.rl_vlc[0];
1115
        } else {
1116
2171502
            qmul = s->qscale << 1;
1117
2171502
            qadd = (s->qscale - 1) | 1;
1118
2171502
            if (rvlc)
1119
                rl_vlc = ff_rvlc_rl_inter.rl_vlc[s->qscale];
1120
            else
1121
2171502
                rl_vlc = ff_h263_rl_inter.rl_vlc[s->qscale];
1122
        }
1123
    }
1124
    {
1125
3037326
        OPEN_READER(re, &s->gb);
1126
        for (;;) {
1127
26282206
            UPDATE_CACHE(re, &s->gb);
1128
26282206
            GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 0);
1129
26282206
            if (level == 0) {
1130
                /* escape */
1131
770420
                if (rvlc) {
1132
                    if (SHOW_UBITS(re, &s->gb, 1) == 0) {
1133
                        av_log(s->avctx, AV_LOG_ERROR,
1134
                               "1. marker bit missing in rvlc esc\n");
1135
                        return AVERROR_INVALIDDATA;
1136
                    }
1137
                    SKIP_CACHE(re, &s->gb, 1);
1138
1139
                    last = SHOW_UBITS(re, &s->gb, 1);
1140
                    SKIP_CACHE(re, &s->gb, 1);
1141
                    run = SHOW_UBITS(re, &s->gb, 6);
1142
                    SKIP_COUNTER(re, &s->gb, 1 + 1 + 6);
1143
                    UPDATE_CACHE(re, &s->gb);
1144
1145
                    if (SHOW_UBITS(re, &s->gb, 1) == 0) {
1146
                        av_log(s->avctx, AV_LOG_ERROR,
1147
                               "2. marker bit missing in rvlc esc\n");
1148
                        return AVERROR_INVALIDDATA;
1149
                    }
1150
                    SKIP_CACHE(re, &s->gb, 1);
1151
1152
                    level = SHOW_UBITS(re, &s->gb, 11);
1153
                    SKIP_CACHE(re, &s->gb, 11);
1154
1155
                    if (SHOW_UBITS(re, &s->gb, 5) != 0x10) {
1156
                        av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n");
1157
                        return AVERROR_INVALIDDATA;
1158
                    }
1159
                    SKIP_CACHE(re, &s->gb, 5);
1160
1161
                    level = level * qmul + qadd;
1162
                    level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1163
                    SKIP_COUNTER(re, &s->gb, 1 + 11 + 5 + 1);
1164
1165
                    i += run + 1;
1166
                    if (last)
1167
                        i += 192;
1168
                } else {
1169
                    int cache;
1170
770420
                    cache = GET_CACHE(re, &s->gb);
1171
1172
                    if (IS_3IV1)
1173
                        cache ^= 0xC0000000;
1174
1175
770420
                    if (cache & 0x80000000) {
1176
353524
                        if (cache & 0x40000000) {
1177
                            /* third escape */
1178
137781
                            SKIP_CACHE(re, &s->gb, 2);
1179
137781
                            last = SHOW_UBITS(re, &s->gb, 1);
1180
137781
                            SKIP_CACHE(re, &s->gb, 1);
1181
137781
                            run = SHOW_UBITS(re, &s->gb, 6);
1182
137781
                            SKIP_COUNTER(re, &s->gb, 2 + 1 + 6);
1183
137781
                            UPDATE_CACHE(re, &s->gb);
1184
1185
                            if (IS_3IV1) {
1186
                                level = SHOW_SBITS(re, &s->gb, 12);
1187
                                LAST_SKIP_BITS(re, &s->gb, 12);
1188
                            } else {
1189
137781
                                if (SHOW_UBITS(re, &s->gb, 1) == 0) {
1190
                                    av_log(s->avctx, AV_LOG_ERROR,
1191
                                           "1. marker bit missing in 3. esc\n");
1192
                                    if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR))
1193
                                        return AVERROR_INVALIDDATA;
1194
                                }
1195
137781
                                SKIP_CACHE(re, &s->gb, 1);
1196
1197
137781
                                level = SHOW_SBITS(re, &s->gb, 12);
1198
137781
                                SKIP_CACHE(re, &s->gb, 12);
1199
1200
137781
                                if (SHOW_UBITS(re, &s->gb, 1) == 0) {
1201
                                    av_log(s->avctx, AV_LOG_ERROR,
1202
                                           "2. marker bit missing in 3. esc\n");
1203
                                    if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR))
1204
                                        return AVERROR_INVALIDDATA;
1205
                                }
1206
1207
137781
                                SKIP_COUNTER(re, &s->gb, 1 + 12 + 1);
1208
                            }
1209
1210
#if 0
1211
                            if (s->error_recognition >= FF_ER_COMPLIANT) {
1212
                                const int abs_level= FFABS(level);
1213
                                if (abs_level<=MAX_LEVEL && run<=MAX_RUN) {
1214
                                    const int run1= run - rl->max_run[last][abs_level] - 1;
1215
                                    if (abs_level <= rl->max_level[last][run]) {
1216
                                        av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n");
1217
                                        return AVERROR_INVALIDDATA;
1218
                                    }
1219
                                    if (s->error_recognition > FF_ER_COMPLIANT) {
1220
                                        if (abs_level <= rl->max_level[last][run]*2) {
1221
                                            av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 1 encoding possible\n");
1222
                                            return AVERROR_INVALIDDATA;
1223
                                        }
1224
                                        if (run1 >= 0 && abs_level <= rl->max_level[last][run1]) {
1225
                                            av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 2 encoding possible\n");
1226
                                            return AVERROR_INVALIDDATA;
1227
                                        }
1228
                                    }
1229
                                }
1230
                            }
1231
#endif
1232
137781
                            if (level > 0)
1233
69038
                                level = level * qmul + qadd;
1234
                            else
1235
68743
                                level = level * qmul - qadd;
1236
1237
137781
                            if ((unsigned)(level + 2048) > 4095) {
1238
                                if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_AGGRESSIVE)) {
1239
                                    if (level > 2560 || level < -2560) {
1240
                                        av_log(s->avctx, AV_LOG_ERROR,
1241
                                               "|level| overflow in 3. esc, qp=%d\n",
1242
                                               s->qscale);
1243
                                        return AVERROR_INVALIDDATA;
1244
                                    }
1245
                                }
1246
                                level = level < 0 ? -2048 : 2047;
1247
                            }
1248
1249
137781
                            i += run + 1;
1250
137781
                            if (last)
1251
44545
                                i += 192;
1252
                        } else {
1253
                            /* second escape */
1254
215743
                            SKIP_BITS(re, &s->gb, 2);
1255
215743
                            GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
1256
215743
                            i    += run + rl->max_run[run >> 7][level / qmul] + 1;  // FIXME opt indexing
1257
215743
                            level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1258
215743
                            LAST_SKIP_BITS(re, &s->gb, 1);
1259
                        }
1260
                    } else {
1261
                        /* first escape */
1262
416896
                        SKIP_BITS(re, &s->gb, 1);
1263
416896
                        GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
1264
416896
                        i    += run;
1265
416896
                        level = level + rl->max_level[run >> 7][(run - 1) & 63] * qmul;  // FIXME opt indexing
1266
416896
                        level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1267
416896
                        LAST_SKIP_BITS(re, &s->gb, 1);
1268
                    }
1269
                }
1270
            } else {
1271
25511786
                i    += run;
1272
25511786
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1273
25511786
                LAST_SKIP_BITS(re, &s->gb, 1);
1274
            }
1275
            ff_tlog(s->avctx, "dct[%d][%d] = %- 4d end?:%d\n", scan_table[i&63]&7, scan_table[i&63] >> 3, level, i>62);
1276
26282206
            if (i > 62) {
1277
3037326
                i -= 192;
1278
3037326
                if (i & (~63)) {
1279
                    av_log(s->avctx, AV_LOG_ERROR,
1280
                           "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1281
                    return AVERROR_INVALIDDATA;
1282
                }
1283
1284
3037326
                block[scan_table[i]] = level;
1285
3037326
                break;
1286
            }
1287
1288
23244880
            block[scan_table[i]] = level;
1289
        }
1290
3037326
        CLOSE_READER(re, &s->gb);
1291
    }
1292
1293
3252338
not_coded:
1294
3252338
    if (intra) {
1295
1068954
        if (!ctx->use_intra_dc_vlc) {
1296
            block[0] = ff_mpeg4_pred_dc(s, n, block[0], &dc_pred_dir, 0);
1297
1298
            i -= i >> 31;  // if (i == -1) i = 0;
1299
        }
1300
1301
1068954
        ff_mpeg4_pred_ac(s, block, n, dc_pred_dir);
1302
1068954
        if (s->ac_pred)
1303
25890
            i = 63;  // FIXME not optimal
1304
    }
1305
3252338
    s->block_last_index[n] = i;
1306
3252338
    return 0;
1307
}
1308
1309
/**
1310
 * decode partition C of one MB.
1311
 * @return <0 if an error occurred
1312
 */
1313
138064
static int mpeg4_decode_partitioned_mb(MpegEncContext *s, int16_t block[6][64])
1314
{
1315
138064
    Mpeg4DecContext *ctx = s->avctx->priv_data;
1316
    int cbp, mb_type;
1317
138064
    const int xy = s->mb_x + s->mb_y * s->mb_stride;
1318
1319
    av_assert2(s == (void*)ctx);
1320
1321
138064
    mb_type = s->current_picture.mb_type[xy];
1322
138064
    cbp     = s->cbp_table[xy];
1323
1324
138064
    ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold;
1325
1326
138064
    if (s->current_picture.qscale_table[xy] != s->qscale)
1327
        ff_set_qscale(s, s->current_picture.qscale_table[xy]);
1328
1329
138064
    if (s->pict_type == AV_PICTURE_TYPE_P ||
1330
138064
        s->pict_type == AV_PICTURE_TYPE_S) {
1331
        int i;
1332
603705
        for (i = 0; i < 4; i++) {
1333
482964
            s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
1334
482964
            s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
1335
        }
1336
120741
        s->mb_intra = IS_INTRA(mb_type);
1337
1338
120741
        if (IS_SKIP(mb_type)) {
1339
            /* skip mb */
1340
6979
            for (i = 0; i < 6; i++)
1341
5982
                s->block_last_index[i] = -1;
1342
997
            s->mv_dir  = MV_DIR_FORWARD;
1343
997
            s->mv_type = MV_TYPE_16X16;
1344
997
            if (s->pict_type == AV_PICTURE_TYPE_S
1345
                && ctx->vol_sprite_usage == GMC_SPRITE) {
1346
                s->mcsel      = 1;
1347
                s->mb_skipped = 0;
1348
            } else {
1349
997
                s->mcsel      = 0;
1350
997
                s->mb_skipped = 1;
1351
            }
1352
119744
        } else if (s->mb_intra) {
1353
6287
            s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
1354
113457
        } else if (!s->mb_intra) {
1355
            // s->mcsel = 0;  // FIXME do we need to init that?
1356
1357
113457
            s->mv_dir = MV_DIR_FORWARD;
1358
113457
            if (IS_8X8(mb_type)) {
1359
31831
                s->mv_type = MV_TYPE_8X8;
1360
            } else {
1361
81626
                s->mv_type = MV_TYPE_16X16;
1362
            }
1363
        }
1364
    } else { /* I-Frame */
1365
17323
        s->mb_intra = 1;
1366
17323
        s->ac_pred  = IS_ACPRED(s->current_picture.mb_type[xy]);
1367
    }
1368
1369
138064
    if (!IS_SKIP(mb_type)) {
1370
        int i;
1371
137067
        s->bdsp.clear_blocks(s->block[0]);
1372
        /* decode each block */
1373
959469
        for (i = 0; i < 6; i++) {
1374
822402
            if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, s->mb_intra, ctx->rvlc) < 0) {
1375
                av_log(s->avctx, AV_LOG_ERROR,
1376
                       "texture corrupted at %d %d %d\n",
1377
                       s->mb_x, s->mb_y, s->mb_intra);
1378
                return AVERROR_INVALIDDATA;
1379
            }
1380
822402
            cbp += cbp;
1381
        }
1382
    }
1383
1384
    /* per-MB end of slice check */
1385
138064
    if (--s->mb_num_left <= 0) {
1386
1728
        if (mpeg4_is_resync(ctx))
1387
1728
            return SLICE_END;
1388
        else
1389
            return SLICE_NOEND;
1390
    } else {
1391
136336
        if (mpeg4_is_resync(ctx)) {
1392
308
            const int delta = s->mb_x + 1 == s->mb_width ? 2 : 1;
1393
308
            if (s->cbp_table[xy + delta])
1394
                return SLICE_END;
1395
        }
1396
136336
        return SLICE_OK;
1397
    }
1398
}
1399
1400
1289056
static int mpeg4_decode_mb(MpegEncContext *s, int16_t block[6][64])
1401
{
1402
1289056
    Mpeg4DecContext *ctx = s->avctx->priv_data;
1403
    int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
1404
    int16_t *mot_val;
1405
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
1406
1289056
    const int xy = s->mb_x + s->mb_y * s->mb_stride;
1407
1408
    av_assert2(s ==  (void*)ctx);
1409
    av_assert2(s->h263_pred);
1410
1411
1289056
    if (s->pict_type == AV_PICTURE_TYPE_P ||
1412
367659
        s->pict_type == AV_PICTURE_TYPE_S) {
1413
        do {
1414
921397
            if (get_bits1(&s->gb)) {
1415
                /* skip mb */
1416
80953
                s->mb_intra = 0;
1417
566671
                for (i = 0; i < 6; i++)
1418
485718
                    s->block_last_index[i] = -1;
1419
80953
                s->mv_dir  = MV_DIR_FORWARD;
1420
80953
                s->mv_type = MV_TYPE_16X16;
1421
80953
                if (s->pict_type == AV_PICTURE_TYPE_S &&
1422
                    ctx->vol_sprite_usage == GMC_SPRITE) {
1423
                    s->current_picture.mb_type[xy] = MB_TYPE_SKIP  |
1424
                                                     MB_TYPE_GMC   |
1425
                                                     MB_TYPE_16x16 |
1426
                                                     MB_TYPE_L0;
1427
                    s->mcsel       = 1;
1428
                    s->mv[0][0][0] = get_amv(ctx, 0);
1429
                    s->mv[0][0][1] = get_amv(ctx, 1);
1430
                    s->mb_skipped  = 0;
1431
                } else {
1432
80953
                    s->current_picture.mb_type[xy] = MB_TYPE_SKIP  |
1433
                                                     MB_TYPE_16x16 |
1434
                                                     MB_TYPE_L0;
1435
80953
                    s->mcsel       = 0;
1436
80953
                    s->mv[0][0][0] = 0;
1437
80953
                    s->mv[0][0][1] = 0;
1438
80953
                    s->mb_skipped  = 1;
1439
                }
1440
80953
                goto end;
1441
            }
1442
840444
            cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
1443
840444
            if (cbpc < 0) {
1444
                av_log(s->avctx, AV_LOG_ERROR,
1445
                       "mcbpc damaged at %d %d\n", s->mb_x, s->mb_y);
1446
                return AVERROR_INVALIDDATA;
1447
            }
1448
840444
        } while (cbpc == 20);
1449
1450
840444
        s->bdsp.clear_blocks(s->block[0]);
1451
840444
        dquant      = cbpc & 8;
1452
840444
        s->mb_intra = ((cbpc & 4) != 0);
1453
840444
        if (s->mb_intra)
1454
27278
            goto intra;
1455
1456
813166
        if (s->pict_type == AV_PICTURE_TYPE_S &&
1457
            ctx->vol_sprite_usage == GMC_SPRITE && (cbpc & 16) == 0)
1458
            s->mcsel = get_bits1(&s->gb);
1459
        else
1460
813166
            s->mcsel = 0;
1461
813166
        cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1) ^ 0x0F;
1462
813166
        if (cbpy < 0) {
1463
            av_log(s->avctx, AV_LOG_ERROR,
1464
                   "P cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
1465
            return AVERROR_INVALIDDATA;
1466
        }
1467
1468
813166
        cbp = (cbpc & 3) | (cbpy << 2);
1469
813166
        if (dquant)
1470
9237
            ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
1471

813166
        if ((!s->progressive_sequence) &&
1472
            (cbp || (s->workaround_bugs & FF_BUG_XVID_ILACE)))
1473
            s->interlaced_dct = get_bits1(&s->gb);
1474
1475
813166
        s->mv_dir = MV_DIR_FORWARD;
1476
813166
        if ((cbpc & 16) == 0) {
1477
721166
            if (s->mcsel) {
1478
                s->current_picture.mb_type[xy] = MB_TYPE_GMC   |
1479
                                                 MB_TYPE_16x16 |
1480
                                                 MB_TYPE_L0;
1481
                /* 16x16 global motion prediction */
1482
                s->mv_type     = MV_TYPE_16X16;
1483
                mx             = get_amv(ctx, 0);
1484
                my             = get_amv(ctx, 1);
1485
                s->mv[0][0][0] = mx;
1486
                s->mv[0][0][1] = my;
1487

721166
            } else if ((!s->progressive_sequence) && get_bits1(&s->gb)) {
1488
                s->current_picture.mb_type[xy] = MB_TYPE_16x8 |
1489
                                                 MB_TYPE_L0   |
1490
                                                 MB_TYPE_INTERLACED;
1491
                /* 16x8 field motion prediction */
1492
                s->mv_type = MV_TYPE_FIELD;
1493
1494
                s->field_select[0][0] = get_bits1(&s->gb);
1495
                s->field_select[0][1] = get_bits1(&s->gb);
1496
1497
                ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1498
1499
                for (i = 0; i < 2; i++) {
1500
                    mx = ff_h263_decode_motion(s, pred_x, s->f_code);
1501
                    if (mx >= 0xffff)
1502
                        return AVERROR_INVALIDDATA;
1503
1504
                    my = ff_h263_decode_motion(s, pred_y / 2, s->f_code);
1505
                    if (my >= 0xffff)
1506
                        return AVERROR_INVALIDDATA;
1507
1508
                    s->mv[0][i][0] = mx;
1509
                    s->mv[0][i][1] = my;
1510
                }
1511
            } else {
1512
721166
                s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0;
1513
                /* 16x16 motion prediction */
1514
721166
                s->mv_type = MV_TYPE_16X16;
1515
721166
                ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1516
721166
                mx = ff_h263_decode_motion(s, pred_x, s->f_code);
1517
1518
721166
                if (mx >= 0xffff)
1519
                    return AVERROR_INVALIDDATA;
1520
1521
721166
                my = ff_h263_decode_motion(s, pred_y, s->f_code);
1522
1523
721166
                if (my >= 0xffff)
1524
                    return AVERROR_INVALIDDATA;
1525
721166
                s->mv[0][0][0] = mx;
1526
721166
                s->mv[0][0][1] = my;
1527
            }
1528
        } else {
1529
92000
            s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0;
1530
92000
            s->mv_type                     = MV_TYPE_8X8;
1531
460000
            for (i = 0; i < 4; i++) {
1532
368000
                mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
1533
368000
                mx      = ff_h263_decode_motion(s, pred_x, s->f_code);
1534
368000
                if (mx >= 0xffff)
1535
                    return AVERROR_INVALIDDATA;
1536
1537
368000
                my = ff_h263_decode_motion(s, pred_y, s->f_code);
1538
368000
                if (my >= 0xffff)
1539
                    return AVERROR_INVALIDDATA;
1540
368000
                s->mv[0][i][0] = mx;
1541
368000
                s->mv[0][i][1] = my;
1542
368000
                mot_val[0]     = mx;
1543
368000
                mot_val[1]     = my;
1544
            }
1545
        }
1546
367659
    } else if (s->pict_type == AV_PICTURE_TYPE_B) {
1547
        int modb1;   // first bit of modb
1548
        int modb2;   // second bit of modb
1549
        int mb_type;
1550
1551
240388
        s->mb_intra = 0;  // B-frames never contain intra blocks
1552
240388
        s->mcsel    = 0;  //      ...               true gmc blocks
1553
1554
240388
        if (s->mb_x == 0) {
1555
31062
            for (i = 0; i < 2; i++) {
1556
20708
                s->last_mv[i][0][0] =
1557
20708
                s->last_mv[i][0][1] =
1558
20708
                s->last_mv[i][1][0] =
1559
20708
                s->last_mv[i][1][1] = 0;
1560
            }
1561
1562
10354
            ff_thread_await_progress(&s->next_picture_ptr->tf, s->mb_y, 0);
1563
        }
1564
1565
        /* if we skipped it in the future P-frame than skip it now too */
1566
240388
        s->mb_skipped = s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x];  // Note, skiptab=0 if last was GMC
1567
1568
240388
        if (s->mb_skipped) {
1569
            /* skip mb */
1570
230090
            for (i = 0; i < 6; i++)
1571
197220
                s->block_last_index[i] = -1;
1572
1573
32870
            s->mv_dir      = MV_DIR_FORWARD;
1574
32870
            s->mv_type     = MV_TYPE_16X16;
1575
32870
            s->mv[0][0][0] =
1576
32870
            s->mv[0][0][1] =
1577
32870
            s->mv[1][0][0] =
1578
32870
            s->mv[1][0][1] = 0;
1579
32870
            s->current_picture.mb_type[xy] = MB_TYPE_SKIP  |
1580
                                             MB_TYPE_16x16 |
1581
                                             MB_TYPE_L0;
1582
32870
            goto end;
1583
        }
1584
1585
207518
        modb1 = get_bits1(&s->gb);
1586
207518
        if (modb1) {
1587
            // like MB_TYPE_B_DIRECT but no vectors coded
1588
44804
            mb_type = MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1;
1589
44804
            cbp     = 0;
1590
        } else {
1591
162714
            modb2   = get_bits1(&s->gb);
1592
162714
            mb_type = get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);
1593
162714
            if (mb_type < 0) {
1594
                av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n");
1595
                return AVERROR_INVALIDDATA;
1596
            }
1597
162714
            mb_type = mb_type_b_map[mb_type];
1598
162714
            if (modb2) {
1599
67183
                cbp = 0;
1600
            } else {
1601
95531
                s->bdsp.clear_blocks(s->block[0]);
1602
95531
                cbp = get_bits(&s->gb, 6);
1603
            }
1604
1605

162714
            if ((!IS_DIRECT(mb_type)) && cbp) {
1606
69310
                if (get_bits1(&s->gb))
1607
6992
                    ff_set_qscale(s, s->qscale + get_bits1(&s->gb) * 4 - 2);
1608
            }
1609
1610
162714
            if (!s->progressive_sequence) {
1611
                if (cbp)
1612
                    s->interlaced_dct = get_bits1(&s->gb);
1613
1614
                if (!IS_DIRECT(mb_type) && get_bits1(&s->gb)) {
1615
                    mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
1616
                    mb_type &= ~MB_TYPE_16x16;
1617
1618
                    if (USES_LIST(mb_type, 0)) {
1619
                        s->field_select[0][0] = get_bits1(&s->gb);
1620
                        s->field_select[0][1] = get_bits1(&s->gb);
1621
                    }
1622
                    if (USES_LIST(mb_type, 1)) {
1623
                        s->field_select[1][0] = get_bits1(&s->gb);
1624
                        s->field_select[1][1] = get_bits1(&s->gb);
1625
                    }
1626
                }
1627
            }
1628
1629
162714
            s->mv_dir = 0;
1630
162714
            if ((mb_type & (MB_TYPE_DIRECT2 | MB_TYPE_INTERLACED)) == 0) {
1631
120541
                s->mv_type = MV_TYPE_16X16;
1632
1633
120541
                if (USES_LIST(mb_type, 0)) {
1634
82655
                    s->mv_dir = MV_DIR_FORWARD;
1635
1636
82655
                    mx = ff_h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
1637
82655
                    my = ff_h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
1638
82655
                    s->last_mv[0][1][0] =
1639
82655
                    s->last_mv[0][0][0] =
1640
82655
                    s->mv[0][0][0]      = mx;
1641
82655
                    s->last_mv[0][1][1] =
1642
82655
                    s->last_mv[0][0][1] =
1643
82655
                    s->mv[0][0][1]      = my;
1644
                }
1645
1646
120541
                if (USES_LIST(mb_type, 1)) {
1647
94596
                    s->mv_dir |= MV_DIR_BACKWARD;
1648
1649
94596
                    mx = ff_h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
1650
94596
                    my = ff_h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
1651
94596
                    s->last_mv[1][1][0] =
1652
94596
                    s->last_mv[1][0][0] =
1653
94596
                    s->mv[1][0][0]      = mx;
1654
94596
                    s->last_mv[1][1][1] =
1655
94596
                    s->last_mv[1][0][1] =
1656
94596
                    s->mv[1][0][1]      = my;
1657
                }
1658
42173
            } else if (!IS_DIRECT(mb_type)) {
1659
                s->mv_type = MV_TYPE_FIELD;
1660
1661
                if (USES_LIST(mb_type, 0)) {
1662
                    s->mv_dir = MV_DIR_FORWARD;
1663
1664
                    for (i = 0; i < 2; i++) {
1665
                        mx = ff_h263_decode_motion(s, s->last_mv[0][i][0], s->f_code);
1666
                        my = ff_h263_decode_motion(s, s->last_mv[0][i][1] / 2, s->f_code);
1667
                        s->last_mv[0][i][0] =
1668
                        s->mv[0][i][0]      = mx;
1669
                        s->last_mv[0][i][1] = (s->mv[0][i][1] = my) * 2;
1670
                    }
1671
                }
1672
1673
                if (USES_LIST(mb_type, 1)) {
1674
                    s->mv_dir |= MV_DIR_BACKWARD;
1675
1676
                    for (i = 0; i < 2; i++) {
1677
                        mx = ff_h263_decode_motion(s, s->last_mv[1][i][0], s->b_code);
1678
                        my = ff_h263_decode_motion(s, s->last_mv[1][i][1] / 2, s->b_code);
1679
                        s->last_mv[1][i][0] =
1680
                        s->mv[1][i][0]      = mx;
1681
                        s->last_mv[1][i][1] = (s->mv[1][i][1] = my) * 2;
1682
                    }
1683
                }
1684
            }
1685
        }
1686
1687
207518
        if (IS_DIRECT(mb_type)) {
1688
86977
            if (IS_SKIP(mb_type)) {
1689
44804
                mx =
1690
44804
                my = 0;
1691
            } else {
1692
42173
                mx = ff_h263_decode_motion(s, 0, 1);
1693
42173
                my = ff_h263_decode_motion(s, 0, 1);
1694
            }
1695
1696
86977
            s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
1697
86977
            mb_type  |= ff_mpeg4_set_direct_mv(s, mx, my);
1698
        }
1699
207518
        s->current_picture.mb_type[xy] = mb_type;
1700
    } else { /* I-Frame */
1701
        do {
1702
127271
            cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
1703
127271
            if (cbpc < 0) {
1704
                av_log(s->avctx, AV_LOG_ERROR,
1705
                       "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
1706
                return AVERROR_INVALIDDATA;
1707
            }
1708
127271
        } while (cbpc == 8);
1709
1710
127271
        dquant = cbpc & 4;
1711
127271
        s->mb_intra = 1;
1712
1713
154549
intra:
1714
154549
        s->ac_pred = get_bits1(&s->gb);
1715
154549
        if (s->ac_pred)
1716
552
            s->current_picture.mb_type[xy] = MB_TYPE_INTRA | MB_TYPE_ACPRED;
1717
        else
1718
153997
            s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
1719
1720
154549
        cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
1721
154549
        if (cbpy < 0) {
1722
            av_log(s->avctx, AV_LOG_ERROR,
1723
                   "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
1724
            return AVERROR_INVALIDDATA;
1725
        }
1726
154549
        cbp = (cbpc & 3) | (cbpy << 2);
1727
1728
154549
        ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold;
1729
1730
154549
        if (dquant)
1731
7107
            ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
1732
1733
154549
        if (!s->progressive_sequence)
1734
            s->interlaced_dct = get_bits1(&s->gb);
1735
1736
154549
        s->bdsp.clear_blocks(s->block[0]);
1737
        /* decode each block */
1738
1081843
        for (i = 0; i < 6; i++) {
1739
927294
            if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 1, 0) < 0)
1740
                return AVERROR_INVALIDDATA;
1741
927294
            cbp += cbp;
1742
        }
1743
154549
        goto end;
1744
    }
1745
1746
    /* decode each block */
1747
7144788
    for (i = 0; i < 6; i++) {
1748
6124104
        if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 0, 0) < 0)
1749
            return AVERROR_INVALIDDATA;
1750
6124104
        cbp += cbp;
1751
    }
1752
1753
1020684
end:
1754
    /* per-MB end of slice check */
1755
1289056
    if (s->codec_id == AV_CODEC_ID_MPEG4) {
1756
1289056
        int next = mpeg4_is_resync(ctx);
1757
1289056
        if (next) {
1758

13412
            if        (s->mb_x + s->mb_y*s->mb_width + 1 >  next && (s->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
1759
                return AVERROR_INVALIDDATA;
1760
13412
            } else if (s->mb_x + s->mb_y*s->mb_width + 1 >= next)
1761
5468
                return SLICE_END;
1762
1763
7944
            if (s->pict_type == AV_PICTURE_TYPE_B) {
1764
7944
                const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
1765
7944
                ff_thread_await_progress(&s->next_picture_ptr->tf,
1766
7944
                                         (s->mb_x + delta >= s->mb_width)
1767
168
                                         ? FFMIN(s->mb_y + 1, s->mb_height - 1)
1768
                                         : s->mb_y, 0);
1769
7944
                if (s->next_picture.mbskip_table[xy + delta])
1770
7944
                    return SLICE_OK;
1771
            }
1772
1773
            return SLICE_END;
1774
        }
1775
    }
1776
1777
1275644
    return SLICE_OK;
1778
}
1779
1780
/* As per spec, studio start code search isn't the same as the old type of start code */
1781
static void next_start_code_studio(GetBitContext *gb)
1782
{
1783
    align_get_bits(gb);
1784
1785
    while (get_bits_left(gb) >= 24 && show_bits(gb, 24) != 0x1) {
1786
        get_bits(gb, 8);
1787
    }
1788
}
1789
1790
/* additional_code, vlc index */
1791
static const uint8_t ac_state_tab[22][2] =
1792
{
1793
    {0, 0},
1794
    {0, 1},
1795
    {1, 1},
1796
    {2, 1},
1797
    {3, 1},
1798
    {4, 1},
1799
    {5, 1},
1800
    {1, 2},
1801
    {2, 2},
1802
    {3, 2},
1803
    {4, 2},
1804
    {5, 2},
1805
    {6, 2},
1806
    {1, 3},
1807
    {2, 4},
1808
    {3, 5},
1809
    {4, 6},
1810
    {5, 7},
1811
    {6, 8},
1812
    {7, 9},
1813
    {8, 10},
1814
    {0, 11}
1815
};
1816
1817
static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n)
1818
{
1819
    Mpeg4DecContext *ctx = s->avctx->priv_data;
1820
1821
    int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0,
1822
        additional_code_len, sign, mismatch;
1823
    VLC *cur_vlc = &ctx->studio_intra_tab[0];
1824
    uint8_t *const scantable = s->intra_scantable.permutated;
1825
    const uint16_t *quant_matrix;
1826
    uint32_t flc;
1827
    const int min = -1 *  (1 << (s->avctx->bits_per_raw_sample + 6));
1828
    const int max =      ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1);
1829
    int shift =  3 - s->dct_precision;
1830
1831
    mismatch = 1;
1832
1833
    memset(block, 0, 64 * sizeof(int32_t));
1834
1835
    if (n < 4) {
1836
        cc = 0;
1837
        dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);
1838
        quant_matrix = s->intra_matrix;
1839
    } else {
1840
        cc = (n & 1) + 1;
1841
        if (ctx->rgb)
1842
            dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);
1843
        else
1844
            dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2);
1845
        quant_matrix = s->chroma_intra_matrix;
1846
    }
1847
1848
    if (dct_dc_size == 0) {
1849
        dct_diff = 0;
1850
    } else {
1851
        dct_diff = get_xbits(&s->gb, dct_dc_size);
1852
1853
        if (dct_dc_size > 8) {
1854
            if(!check_marker(s->avctx, &s->gb, "dct_dc_size > 8"))
1855
                return AVERROR_INVALIDDATA;
1856
        }
1857
1858
    }
1859
1860
    s->last_dc[cc] += dct_diff;
1861
1862
    if (s->mpeg_quant)
1863
        block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision);
1864
    else
1865
        block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision);
1866
    /* TODO: support mpeg_quant for AC coefficients */
1867
1868
    block[0] = av_clip(block[0], min, max);
1869
    mismatch ^= block[0];
1870
1871
    /* AC Coefficients */
1872
    while (1) {
1873
        group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2);
1874
1875
        if (group < 0) {
1876
            av_log(s->avctx, AV_LOG_ERROR, "illegal ac coefficient group vlc\n");
1877
            return AVERROR_INVALIDDATA;
1878
        }
1879
1880
        additional_code_len = ac_state_tab[group][0];
1881
        cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]];
1882
1883
        if (group == 0) {
1884
            /* End of Block */
1885
            break;
1886
        } else if (group >= 1 && group <= 6) {
1887
            /* Zero run length (Table B.47) */
1888
            run = 1 << additional_code_len;
1889
            if (additional_code_len)
1890
                run += get_bits(&s->gb, additional_code_len);
1891
            idx += run;
1892
            continue;
1893
        } else if (group >= 7 && group <= 12) {
1894
            /* Zero run length and +/-1 level (Table B.48) */
1895
            code = get_bits(&s->gb, additional_code_len);
1896
            sign = code & 1;
1897
            code >>= 1;
1898
            run = (1 << (additional_code_len - 1)) + code;
1899
            idx += run;
1900
            if (idx > 63)
1901
                return AVERROR_INVALIDDATA;
1902
            j = scantable[idx++];
1903
            block[j] = sign ? 1 : -1;
1904
        } else if (group >= 13 && group <= 20) {
1905
            /* Level value (Table B.49) */
1906
            if (idx > 63)
1907
                return AVERROR_INVALIDDATA;
1908
            j = scantable[idx++];
1909
            block[j] = get_xbits(&s->gb, additional_code_len);
1910
        } else if (group == 21) {
1911
            /* Escape */
1912
            if (idx > 63)
1913
                return AVERROR_INVALIDDATA;
1914
            j = scantable[idx++];
1915
            additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4;
1916
            flc = get_bits(&s->gb, additional_code_len);
1917
            if (flc >> (additional_code_len-1))
1918
                block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1);
1919
            else
1920
                block[j] = flc;
1921
        }
1922
        block[j] = ((block[j] * quant_matrix[j] * s->qscale) * (1 << shift)) / 16;
1923
        block[j] = av_clip(block[j], min, max);
1924
        mismatch ^= block[j];
1925
    }
1926
1927
    block[63] ^= mismatch & 1;
1928
1929
    return 0;
1930
}
1931
1932
static int mpeg4_decode_dpcm_macroblock(MpegEncContext *s, int16_t macroblock[256], int n)
1933
{
1934
    int i, j, w, h, idx = 0;
1935
    int block_mean, rice_parameter, rice_prefix_code, rice_suffix_code,
1936
        dpcm_residual, left, top, topleft, min_left_top, max_left_top, p, p2, output;
1937
    h = 16 >> (n ? s->chroma_y_shift : 0);
1938
    w = 16 >> (n ? s->chroma_x_shift : 0);
1939
1940
    block_mean = get_bits(&s->gb, s->avctx->bits_per_raw_sample);
1941
    if (block_mean == 0){
1942
        av_log(s->avctx, AV_LOG_ERROR, "Forbidden block_mean\n");
1943
        return AVERROR_INVALIDDATA;
1944
    }
1945
    s->last_dc[n] = block_mean * (1 << (s->dct_precision + s->intra_dc_precision));
1946
1947
    rice_parameter = get_bits(&s->gb, 4);
1948
    if (rice_parameter == 0) {
1949
        av_log(s->avctx, AV_LOG_ERROR, "Forbidden rice_parameter\n");
1950
        return AVERROR_INVALIDDATA;
1951
    }
1952
1953
    if (rice_parameter == 15)
1954
        rice_parameter = 0;
1955
1956
    if (rice_parameter > 11) {
1957
        av_log(s->avctx, AV_LOG_ERROR, "Forbidden rice_parameter\n");
1958
        return AVERROR_INVALIDDATA;
1959
    }
1960
1961
    for (i = 0; i < h; i++) {
1962
        output = 1 << (s->avctx->bits_per_raw_sample - 1);
1963
        top = 1 << (s->avctx->bits_per_raw_sample - 1);
1964
1965
        for (j = 0; j < w; j++) {
1966
            left = output;
1967
            topleft = top;
1968
1969
            rice_prefix_code = get_unary(&s->gb, 1, 12);
1970
1971
            /* Escape */
1972
            if (rice_prefix_code == 11)
1973
                dpcm_residual = get_bits(&s->gb, s->avctx->bits_per_raw_sample);
1974
            else {
1975
                if (rice_prefix_code == 12) {
1976
                    av_log(s->avctx, AV_LOG_ERROR, "Forbidden rice_prefix_code\n");
1977
                    return AVERROR_INVALIDDATA;
1978
                }
1979
                rice_suffix_code = get_bitsz(&s->gb, rice_parameter);
1980
                dpcm_residual = (rice_prefix_code << rice_parameter) + rice_suffix_code;
1981
            }
1982
1983
            /* Map to a signed residual */
1984
            if (dpcm_residual & 1)
1985
                dpcm_residual = (-1 * dpcm_residual) >> 1;
1986
            else
1987
                dpcm_residual = (dpcm_residual >> 1);
1988
1989
            if (i != 0)
1990
                top = macroblock[idx-w];
1991
1992
            p = left + top - topleft;
1993
            min_left_top = FFMIN(left, top);
1994
            if (p < min_left_top)
1995
                p = min_left_top;
1996
1997
            max_left_top = FFMAX(left, top);
1998
            if (p > max_left_top)
1999
                p = max_left_top;
2000
2001
            p2 = (FFMIN(min_left_top, topleft) + FFMAX(max_left_top, topleft)) >> 1;
2002
            if (p2 == p)
2003
                p2 = block_mean;
2004
2005
            if (p2 > p)
2006
                dpcm_residual *= -1;
2007
2008
            macroblock[idx++] = output = (dpcm_residual + p) & ((1 << s->avctx->bits_per_raw_sample) - 1);
2009
        }
2010
    }
2011
2012
    return 0;
2013
}
2014
2015
static int mpeg4_decode_studio_mb(MpegEncContext *s, int16_t block_[12][64])
2016
{
2017
    int i;
2018
2019
    s->dpcm_direction = 0;
2020
2021
    /* StudioMacroblock */
2022
    /* Assumes I-VOP */
2023
    s->mb_intra = 1;
2024
    if (get_bits1(&s->gb)) { /* compression_mode */
2025
        /* DCT */
2026
        /* macroblock_type, 1 or 2-bit VLC */
2027
        if (!get_bits1(&s->gb)) {
2028
            skip_bits1(&s->gb);
2029
            s->qscale = mpeg_get_qscale(s);
2030
        }
2031
2032
        for (i = 0; i < mpeg4_block_count[s->chroma_format]; i++) {
2033
            if (mpeg4_decode_studio_block(s, (*s->block32)[i], i) < 0)
2034
                return AVERROR_INVALIDDATA;
2035
        }
2036
    } else {
2037
        /* DPCM */
2038
        check_marker(s->avctx, &s->gb, "DPCM block start");
2039
        s->dpcm_direction = get_bits1(&s->gb) ? -1 : 1;
2040
        for (i = 0; i < 3; i++) {
2041
            if (mpeg4_decode_dpcm_macroblock(s, (*s->dpcm_macroblock)[i], i) < 0)
2042
                return AVERROR_INVALIDDATA;
2043
        }
2044
    }
2045
2046
    if (get_bits_left(&s->gb) >= 24 && show_bits(&s->gb, 23) == 0) {
2047
        next_start_code_studio(&s->gb);
2048
        return SLICE_END;
2049
    }
2050
2051
    //vcon-stp9L1.bits (first frame)
2052
    if (get_bits_left(&s->gb) == 0)
2053
        return SLICE_END;
2054
2055
    //vcon-stp2L1.bits, vcon-stp3L1.bits, vcon-stp6L1.bits, vcon-stp7L1.bits, vcon-stp8L1.bits, vcon-stp10L1.bits (first frame)
2056
    if (get_bits_left(&s->gb) < 8U && show_bits(&s->gb, get_bits_left(&s->gb)) == 0)
2057
        return SLICE_END;
2058
2059
    return SLICE_OK;
2060
}
2061
2062
954
static int mpeg4_decode_gop_header(MpegEncContext *s, GetBitContext *gb)
2063
{
2064
    int hours, minutes, seconds;
2065
2066
954
    if (!show_bits(gb, 23)) {
2067
        av_log(s->avctx, AV_LOG_WARNING, "GOP header invalid\n");
2068
        return AVERROR_INVALIDDATA;
2069
    }
2070
2071
954
    hours   = get_bits(gb, 5);
2072
954
    minutes = get_bits(gb, 6);
2073
954
    check_marker(s->avctx, gb, "in gop_header");
2074
954
    seconds = get_bits(gb, 6);
2075
2076
954
    s->time_base = seconds + 60*(minutes + 60*hours);
2077
2078
954
    skip_bits1(gb);
2079
954
    skip_bits1(gb);
2080
2081
954
    return 0;
2082
}
2083
2084
1217
static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb, int *profile, int *level)
2085
{
2086
2087
1217
    *profile = get_bits(gb, 4);
2088
1217
    *level   = get_bits(gb, 4);
2089
2090
    // for Simple profile, level 0
2091

1217
    if (*profile == 0 && *level == 8) {
2092
        *level = 0;
2093
    }
2094
2095
1217
    return 0;
2096
}
2097
2098
1217
static int mpeg4_decode_visual_object(MpegEncContext *s, GetBitContext *gb)
2099
{
2100
    int visual_object_type;
2101
1217
    int is_visual_object_identifier = get_bits1(gb);
2102
2103
1217
    if (is_visual_object_identifier) {
2104
1183
        skip_bits(gb, 4+3);
2105
    }
2106
1217
    visual_object_type = get_bits(gb, 4);
2107
2108

1217
    if (visual_object_type == VOT_VIDEO_ID ||
2109
        visual_object_type == VOT_STILL_TEXTURE_ID) {
2110
1217
        int video_signal_type = get_bits1(gb);
2111
1217
        if (video_signal_type) {
2112
            int video_range, color_description;
2113
            skip_bits(gb, 3); // video_format
2114
            video_range = get_bits1(gb);
2115
            color_description = get_bits1(gb);
2116
2117
            s->avctx->color_range = video_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
2118
2119
            if (color_description) {
2120
                s->avctx->color_primaries = get_bits(gb, 8);
2121
                s->avctx->color_trc       = get_bits(gb, 8);
2122
                s->avctx->colorspace      = get_bits(gb, 8);
2123
            }
2124
        }
2125
    }
2126
2127
1217
    return 0;
2128
}
2129
2130
23
static void mpeg4_load_default_matrices(MpegEncContext *s)
2131
{
2132
    int i, v;
2133
2134
    /* load default matrices */
2135
1495
    for (i = 0; i < 64; i++) {
2136
1472
        int j = s->idsp.idct_permutation[i];
2137
1472
        v = ff_mpeg4_default_intra_matrix[i];
2138
1472
        s->intra_matrix[j]        = v;
2139
1472
        s->chroma_intra_matrix[j] = v;
2140
2141
1472
        v = ff_mpeg4_default_non_intra_matrix[i];
2142
1472
        s->inter_matrix[j]        = v;
2143
1472
        s->chroma_inter_matrix[j] = v;
2144
    }
2145
23
}
2146
2147
1249
static int decode_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb)
2148
{
2149
1249
    MpegEncContext *s = &ctx->m;
2150
    int width, height, vo_ver_id;
2151
2152
    /* vol header */
2153
1249
    skip_bits(gb, 1);                   /* random access */
2154
1249
    s->vo_type = get_bits(gb, 8);
2155
2156
    /* If we are in studio profile (per vo_type), check if its all consistent
2157
     * and if so continue pass control to decode_studio_vol_header().
2158
     * elIf something is inconsistent, error out
2159
     * else continue with (non studio) vol header decpoding.
2160
     */
2161
1249
    if (s->vo_type == CORE_STUDIO_VO_TYPE ||
2162
1249
        s->vo_type == SIMPLE_STUDIO_VO_TYPE) {
2163
        if (s->avctx->profile != FF_PROFILE_UNKNOWN && s->avctx->profile != FF_PROFILE_MPEG4_SIMPLE_STUDIO)
2164
            return AVERROR_INVALIDDATA;
2165
        s->studio_profile = 1;
2166
        s->avctx->profile = FF_PROFILE_MPEG4_SIMPLE_STUDIO;
2167
        return decode_studio_vol_header(ctx, gb);
2168
1249
    } else if (s->studio_profile) {
2169
        return AVERROR_PATCHWELCOME;
2170
    }
2171
2172
1249
    if (get_bits1(gb) != 0) {           /* is_ol_id */
2173
1213
        vo_ver_id = get_bits(gb, 4);    /* vo_ver_id */
2174
1213
        skip_bits(gb, 3);               /* vo_priority */
2175
    } else {
2176
36
        vo_ver_id = 1;
2177
    }
2178
1249
    s->aspect_ratio_info = get_bits(gb, 4);
2179
1249
    if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
2180
        s->avctx->sample_aspect_ratio.num = get_bits(gb, 8);  // par_width
2181
        s->avctx->sample_aspect_ratio.den = get_bits(gb, 8);  // par_height
2182
    } else {
2183
1249
        s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info];
2184
    }
2185
2186
1249
    if ((ctx->vol_control_parameters = get_bits1(gb))) { /* vol control parameter */
2187
1209
        int chroma_format = get_bits(gb, 2);
2188
1209
        if (chroma_format != CHROMA_420)
2189
            av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n");
2190
2191
1209
        s->low_delay = get_bits1(gb);
2192
1209
        if (get_bits1(gb)) {    /* vbv parameters */
2193
            get_bits(gb, 15);   /* first_half_bitrate */
2194
            check_marker(s->avctx, gb, "after first_half_bitrate");
2195
            get_bits(gb, 15);   /* latter_half_bitrate */
2196
            check_marker(s->avctx, gb, "after latter_half_bitrate");
2197
            get_bits(gb, 15);   /* first_half_vbv_buffer_size */
2198
            check_marker(s->avctx, gb, "after first_half_vbv_buffer_size");
2199
            get_bits(gb, 3);    /* latter_half_vbv_buffer_size */
2200
            get_bits(gb, 11);   /* first_half_vbv_occupancy */
2201
            check_marker(s->avctx, gb, "after first_half_vbv_occupancy");
2202
            get_bits(gb, 15);   /* latter_half_vbv_occupancy */
2203
            check_marker(s->avctx, gb, "after latter_half_vbv_occupancy");
2204
        }
2205
    } else {
2206
        /* is setting low delay flag only once the smartest thing to do?
2207
         * low delay detection will not be overridden. */
2208
40
        if (s->picture_number == 0) {
2209
11
            switch(s->vo_type) {
2210
6
            case SIMPLE_VO_TYPE:
2211
            case ADV_SIMPLE_VO_TYPE:
2212
6
                s->low_delay = 1;
2213
6
                break;
2214
5
            default:
2215
5
                s->low_delay = 0;
2216
            }
2217
29
        }
2218
    }
2219
2220
1249
    ctx->shape = get_bits(gb, 2); /* vol shape */
2221
1249
    if (ctx->shape != RECT_SHAPE)
2222
        av_log(s->avctx, AV_LOG_ERROR, "only rectangular vol supported\n");
2223

1249
    if (ctx->shape == GRAY_SHAPE && vo_ver_id != 1) {
2224
        av_log(s->avctx, AV_LOG_ERROR, "Gray shape not supported\n");
2225
        skip_bits(gb, 4);  /* video_object_layer_shape_extension */
2226
    }
2227
2228
1249
    check_marker(s->avctx, gb, "before time_increment_resolution");
2229
2230
1249
    s->avctx->framerate.num = get_bits(gb, 16);
2231
1249
    if (!s->avctx->framerate.num) {
2232
        av_log(s->avctx, AV_LOG_ERROR, "framerate==0\n");
2233
        return AVERROR_INVALIDDATA;
2234
    }
2235
2236
1249
    ctx->time_increment_bits = av_log2(s->avctx->framerate.num - 1) + 1;
2237
1249
    if (ctx->time_increment_bits < 1)
2238
        ctx->time_increment_bits = 1;
2239
2240
1249
    check_marker(s->avctx, gb, "before fixed_vop_rate");
2241
2242
1249
    if (get_bits1(gb) != 0)     /* fixed_vop_rate  */
2243
26
        s->avctx->framerate.den = get_bits(gb, ctx->time_increment_bits);
2244
    else
2245
1223
        s->avctx->framerate.den = 1;
2246
2247
1249
    s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1}));
2248
2249
1249
    ctx->t_frame = 0;
2250
2251
1249
    if (ctx->shape != BIN_ONLY_SHAPE) {
2252
1249
        if (ctx->shape == RECT_SHAPE) {
2253
1249
            check_marker(s->avctx, gb, "before width");
2254
1249
            width = get_bits(gb, 13);
2255
1249
            check_marker(s->avctx, gb, "before height");
2256
1249
            height = get_bits(gb, 13);
2257
1249
            check_marker(s->avctx, gb, "after height");
2258

1249
            if (width && height &&  /* they should be non zero but who knows */
2259

1249
                !(s->width && s->codec_tag == AV_RL32("MP4S"))) {
2260

1249
                if (s->width && s->height &&
2261

914
                    (s->width != width || s->height != height))
2262
20
                    s->context_reinit = 1;
2263
1249
                s->width  = width;
2264
1249
                s->height = height;
2265
            }
2266
        }
2267
2268
1249
        s->progressive_sequence  =
2269
1249
        s->progressive_frame     = get_bits1(gb) ^ 1;
2270
1249
        s->interlaced_dct        = 0;
2271

1249
        if (!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO))
2272
            av_log(s->avctx, AV_LOG_INFO,           /* OBMC Disable */
2273
                   "MPEG-4 OBMC not supported (very likely buggy encoder)\n");
2274
1249
        if (vo_ver_id == 1)
2275
744
            ctx->vol_sprite_usage = get_bits1(gb);    /* vol_sprite_usage */
2276
        else
2277
505
            ctx->vol_sprite_usage = get_bits(gb, 2);  /* vol_sprite_usage */
2278
2279
1249
        if (ctx->vol_sprite_usage == STATIC_SPRITE)
2280
            av_log(s->avctx, AV_LOG_ERROR, "Static Sprites not supported\n");
2281
1249
        if (ctx->vol_sprite_usage == STATIC_SPRITE ||
2282
1249
            ctx->vol_sprite_usage == GMC_SPRITE) {
2283
            if (ctx->vol_sprite_usage == STATIC_SPRITE) {
2284
                skip_bits(gb, 13); // sprite_width
2285
                check_marker(s->avctx, gb, "after sprite_width");
2286
                skip_bits(gb, 13); // sprite_height
2287
                check_marker(s->avctx, gb, "after sprite_height");
2288
                skip_bits(gb, 13); // sprite_left
2289
                check_marker(s->avctx, gb, "after sprite_left");
2290
                skip_bits(gb, 13); // sprite_top
2291
                check_marker(s->avctx, gb, "after sprite_top");
2292
            }
2293
            ctx->num_sprite_warping_points = get_bits(gb, 6);
2294
            if (ctx->num_sprite_warping_points > 3) {
2295
                av_log(s->avctx, AV_LOG_ERROR,
2296
                       "%d sprite_warping_points\n",
2297
                       ctx->num_sprite_warping_points);
2298
                ctx->num_sprite_warping_points = 0;
2299
                return AVERROR_INVALIDDATA;
2300
            }
2301
            s->sprite_warping_accuracy  = get_bits(gb, 2);
2302
            ctx->sprite_brightness_change = get_bits1(gb);
2303
            if (ctx->vol_sprite_usage == STATIC_SPRITE)
2304
                skip_bits1(gb); // low_latency_sprite
2305
        }
2306
        // FIXME sadct disable bit if verid!=1 && shape not rect
2307
2308
1249
        if (get_bits1(gb) == 1) {                   /* not_8_bit */
2309
            s->quant_precision = get_bits(gb, 4);   /* quant_precision */
2310
            if (get_bits(gb, 4) != 8)               /* bits_per_pixel */
2311
                av_log(s->avctx, AV_LOG_ERROR, "N-bit not supported\n");
2312
            if (s->quant_precision != 5)
2313
                av_log(s->avctx, AV_LOG_ERROR,
2314
                       "quant precision %d\n", s->quant_precision);
2315
            if (s->quant_precision<3 || s->quant_precision>9) {
2316
                s->quant_precision = 5;
2317
            }
2318
        } else {
2319
1249
            s->quant_precision = 5;
2320
        }
2321
2322
        // FIXME a bunch of grayscale shape things
2323
2324
1249
        if ((s->mpeg_quant = get_bits1(gb))) { /* vol_quant_type */
2325
            int i, v;
2326
2327
23
            mpeg4_load_default_matrices(s);
2328
2329
            /* load custom intra matrix */
2330
23
            if (get_bits1(gb)) {
2331
12
                int last = 0;
2332
360
                for (i = 0; i < 64; i++) {
2333
                    int j;
2334
360
                    if (get_bits_left(gb) < 8) {
2335
                        av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n");
2336
                        return AVERROR_INVALIDDATA;
2337
                    }
2338
360
                    v = get_bits(gb, 8);
2339
360
                    if (v == 0)
2340
12
                        break;
2341
2342
348
                    last = v;
2343
348
                    j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
2344
348
                    s->intra_matrix[j]        = last;
2345
348
                    s->chroma_intra_matrix[j] = last;
2346
                }
2347
2348
                /* replicate last value */
2349
432
                for (; i < 64; i++) {
2350
420
                    int j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
2351
420
                    s->intra_matrix[j]        = last;
2352
420
                    s->chroma_intra_matrix[j] = last;
2353
                }
2354
            }
2355
2356
            /* load custom non intra matrix */
2357
23
            if (get_bits1(gb)) {
2358
12
                int last = 0;
2359
360
                for (i = 0; i < 64; i++) {
2360
                    int j;
2361
360
                    if (get_bits_left(gb) < 8) {
2362
                        av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n");
2363
                        return AVERROR_INVALIDDATA;
2364
                    }
2365
360
                    v = get_bits(gb, 8);
2366
360
                    if (v == 0)
2367
12
                        break;
2368
2369
348
                    last = v;
2370
348
                    j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
2371
348
                    s->inter_matrix[j]        = v;
2372
348
                    s->chroma_inter_matrix[j] = v;
2373
                }
2374
2375
                /* replicate last value */
2376
432
                for (; i < 64; i++) {
2377
420
                    int j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
2378
420
                    s->inter_matrix[j]        = last;
2379
420
                    s->chroma_inter_matrix[j] = last;
2380
                }
2381
            }
2382
2383
            // FIXME a bunch of grayscale shape things
2384
        }
2385
2386
1249
        if (vo_ver_id != 1)
2387
505
            s->quarter_sample = get_bits1(gb);
2388
        else
2389
744
            s->quarter_sample = 0;
2390
2391
1249
        if (get_bits_left(gb) < 4) {
2392
            av_log(s->avctx, AV_LOG_ERROR, "VOL Header truncated\n");
2393
            return AVERROR_INVALIDDATA;
2394
        }
2395
2396
1249
        if (!get_bits1(gb)) {
2397
            int pos               = get_bits_count(gb);
2398
            int estimation_method = get_bits(gb, 2);
2399
            if (estimation_method < 2) {
2400
                if (!get_bits1(gb)) {
2401
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* opaque */
2402
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* transparent */
2403
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* intra_cae */
2404
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* inter_cae */
2405
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* no_update */
2406
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* upsampling */
2407
                }
2408
                if (!get_bits1(gb)) {
2409
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* intra_blocks */
2410
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* inter_blocks */
2411
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* inter4v_blocks */
2412
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* not coded blocks */
2413
                }
2414
                if (!check_marker(s->avctx, gb, "in complexity estimation part 1")) {
2415
                    skip_bits_long(gb, pos - get_bits_count(gb));
2416
                    goto no_cplx_est;
2417
                }
2418
                if (!get_bits1(gb)) {
2419
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* dct_coeffs */
2420
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* dct_lines */
2421
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* vlc_syms */
2422
                    ctx->cplx_estimation_trash_i += 4 * get_bits1(gb);  /* vlc_bits */
2423
                }
2424
                if (!get_bits1(gb)) {
2425
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* apm */
2426
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* npm */
2427
                    ctx->cplx_estimation_trash_b += 8 * get_bits1(gb);  /* interpolate_mc_q */
2428
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* forwback_mc_q */
2429
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* halfpel2 */
2430
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* halfpel4 */
2431
                }
2432
                if (!check_marker(s->avctx, gb, "in complexity estimation part 2")) {
2433
                    skip_bits_long(gb, pos - get_bits_count(gb));
2434
                    goto no_cplx_est;
2435
                }
2436
                if (estimation_method == 1) {
2437
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* sadct */
2438
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* qpel */
2439
                }
2440
            } else
2441
                av_log(s->avctx, AV_LOG_ERROR,
2442
                       "Invalid Complexity estimation method %d\n",
2443
                       estimation_method);
2444
        } else {
2445
2446
1249
no_cplx_est:
2447
1249
            ctx->cplx_estimation_trash_i =
2448
1249
            ctx->cplx_estimation_trash_p =
2449
1249
            ctx->cplx_estimation_trash_b = 0;
2450
        }
2451
2452
1249
        ctx->resync_marker = !get_bits1(gb); /* resync_marker_disabled */
2453
2454
1249
        s->data_partitioning = get_bits1(gb);
2455
1249
        if (s->data_partitioning)
2456
288
            ctx->rvlc = get_bits1(gb);
2457
2458
1249
        if (vo_ver_id != 1) {
2459
505
            ctx->new_pred = get_bits1(gb);
2460
505
            if (ctx->new_pred) {
2461
                av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n");
2462
                skip_bits(gb, 2); /* requested upstream message type */
2463
                skip_bits1(gb);   /* newpred segment type */
2464
            }
2465
505
            if (get_bits1(gb)) // reduced_res_vop
2466
                av_log(s->avctx, AV_LOG_ERROR,
2467
                       "reduced resolution VOP not supported\n");
2468
        } else {
2469
744
            ctx->new_pred = 0;
2470
        }
2471
2472
1249
        ctx->scalability = get_bits1(gb);
2473
2474
1249
        if (ctx->scalability) {
2475
            GetBitContext bak = *gb;
2476
            int h_sampling_factor_n;
2477
            int h_sampling_factor_m;
2478
            int v_sampling_factor_n;
2479
            int v_sampling_factor_m;
2480
2481
            skip_bits1(gb);    // hierarchy_type
2482
            skip_bits(gb, 4);  /* ref_layer_id */
2483
            skip_bits1(gb);    /* ref_layer_sampling_dir */
2484
            h_sampling_factor_n = get_bits(gb, 5);
2485
            h_sampling_factor_m = get_bits(gb, 5);
2486
            v_sampling_factor_n = get_bits(gb, 5);
2487
            v_sampling_factor_m = get_bits(gb, 5);
2488
            ctx->enhancement_type = get_bits1(gb);
2489
2490
            if (h_sampling_factor_n == 0 || h_sampling_factor_m == 0 ||
2491
                v_sampling_factor_n == 0 || v_sampling_factor_m == 0) {
2492
                /* illegal scalability header (VERY broken encoder),
2493
                 * trying to workaround */
2494
                ctx->scalability = 0;
2495
                *gb            = bak;
2496
            } else
2497
                av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n");
2498
2499
            // bin shape stuff FIXME
2500
        }
2501
    }
2502
2503
1249
    if (s->avctx->debug&FF_DEBUG_PICT_INFO) {
2504
        av_log(s->avctx, AV_LOG_DEBUG, "tb %d/%d, tincrbits:%d, qp_prec:%d, ps:%d, low_delay:%d  %s%s%s%s\n",
2505
               s->avctx->framerate.den, s->avctx->framerate.num,
2506
               ctx->time_increment_bits,
2507
               s->quant_precision,
2508
               s->progressive_sequence,
2509
               s->low_delay,
2510
               ctx->scalability ? "scalability " :"" , s->quarter_sample ? "qpel " : "",
2511
               s->data_partitioning ? "partition " : "", ctx->rvlc ? "rvlc " : ""
2512
        );
2513
    }
2514
2515
1249
    return 0;
2516
}
2517
2518
/**
2519
 * Decode the user data stuff in the header.
2520
 * Also initializes divx/xvid/lavc_version/build.
2521
 */
2522
75
static int decode_user_data(Mpeg4DecContext *ctx, GetBitContext *gb)
2523
{
2524
75
    MpegEncContext *s = &ctx->m;
2525
    char buf[256];
2526
    int i;
2527
    int e;
2528
75
    int ver = 0, build = 0, ver2 = 0, ver3 = 0;
2529
    char last;
2530
2531

732
    for (i = 0; i < 255 && get_bits_count(gb) < gb->size_in_bits; i++) {
2532
716
        if (show_bits(gb, 23) == 0)
2533
59
            break;
2534
657
        buf[i] = get_bits(gb, 8);
2535
    }
2536
75
    buf[i] = 0;
2537
2538
    /* divx detection */
2539
75
    e = sscanf(buf, "DivX%dBuild%d%c", &ver, &build, &last);
2540
75
    if (e < 2)
2541
75
        e = sscanf(buf, "DivX%db%d%c", &ver, &build, &last);
2542
75
    if (e >= 2) {
2543
11
        ctx->divx_version = ver;
2544
11
        ctx->divx_build   = build;
2545

11
        s->divx_packed  = e == 3 && last == 'p';
2546
    }
2547
2548
    /* libavcodec detection */
2549
75
    e = sscanf(buf, "FFmpe%*[^b]b%d", &build) + 3;
2550
75
    if (e != 4)
2551
75
        e = sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build);
2552
75
    if (e != 4) {
2553
75
        e = sscanf(buf, "Lavc%d.%d.%d", &ver, &ver2, &ver3) + 1;
2554
75
        if (e > 1) {
2555

10
            if (ver > 0xFFU || ver2 > 0xFFU || ver3 > 0xFFU) {
2556
                av_log(s->avctx, AV_LOG_WARNING,
2557
                     "Unknown Lavc version string encountered, %d.%d.%d; "
2558
                     "clamping sub-version values to 8-bits.\n",
2559
                     ver, ver2, ver3);
2560
            }
2561
10
            build = ((ver & 0xFF) << 16) + ((ver2 & 0xFF) << 8) + (ver3 & 0xFF);
2562
        }
2563
    }
2564
75
    if (e != 4) {
2565
65
        if (strcmp(buf, "ffmpeg") == 0)
2566
            ctx->lavc_build = 4600;
2567
    }
2568
75
    if (e == 4)
2569
10
        ctx->lavc_build = build;
2570
2571
    /* Xvid detection */
2572
75
    e = sscanf(buf, "XviD%d", &build);
2573
75
    if (e == 1)
2574
26
        ctx->xvid_build = build;
2575
2576
75
    return 0;
2577
}
2578
2579
3473
int ff_mpeg4_workaround_bugs(AVCodecContext *avctx)
2580
{
2581
3473
    Mpeg4DecContext *ctx = avctx->priv_data;
2582
3473
    MpegEncContext *s = &ctx->m;
2583
2584

3473
    if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) {
2585
3323
        if (s->codec_tag        == AV_RL32("XVID") ||
2586
3323
            s->codec_tag        == AV_RL32("XVIX") ||
2587
3323
            s->codec_tag        == AV_RL32("RMP4") ||
2588
3323
            s->codec_tag        == AV_RL32("ZMP4") ||
2589
3323
            s->codec_tag        == AV_RL32("SIPP"))
2590
            ctx->xvid_build = 0;
2591
    }
2592
2593

3473
    if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1)
2594

3323
        if (s->codec_tag == AV_RL32("DIVX") && s->vo_type == 0 &&
2595
            ctx->vol_control_parameters == 0)
2596
            ctx->divx_version = 400;  // divx 4
2597
2598

3473
    if (ctx->xvid_build >= 0 && ctx->divx_version >= 0) {
2599
4
        ctx->divx_version =
2600
4
        ctx->divx_build   = -1;
2601
    }
2602
2603
3473
    if (s->workaround_bugs & FF_BUG_AUTODETECT) {
2604
3473
        if (s->codec_tag == AV_RL32("XVIX"))
2605
            s->workaround_bugs |= FF_BUG_XVID_ILACE;
2606
2607
3473
        if (s->codec_tag == AV_RL32("UMP4"))
2608
            s->workaround_bugs |= FF_BUG_UMP4;
2609
2610

3473
        if (ctx->divx_version >= 500 && ctx->divx_build < 1814)
2611
            s->workaround_bugs |= FF_BUG_QPEL_CHROMA;
2612
2613

3473
        if (ctx->divx_version > 502 && ctx->divx_build < 1814)
2614
            s->workaround_bugs |= FF_BUG_QPEL_CHROMA2;
2615
2616
3473
        if (ctx->xvid_build <= 3U)
2617
            s->padding_bug_score = 256 * 256 * 256 * 64;
2618
2619
3473
        if (ctx->xvid_build <= 1U)
2620
            s->workaround_bugs |= FF_BUG_QPEL_CHROMA;
2621
2622
3473
        if (ctx->xvid_build <= 12U)
2623
            s->workaround_bugs |= FF_BUG_EDGE;
2624
2625
3473
        if (ctx->xvid_build <= 32U)
2626
            s->workaround_bugs |= FF_BUG_DC_CLIP;
2627
2628
#define SET_QPEL_FUNC(postfix1, postfix2)                           \
2629
    s->qdsp.put_        ## postfix1 = ff_put_        ## postfix2;   \
2630
    s->qdsp.put_no_rnd_ ## postfix1 = ff_put_no_rnd_ ## postfix2;   \
2631
    s->qdsp.avg_        ## postfix1 = ff_avg_        ## postfix2;
2632
2633
3473
        if (ctx->lavc_build < 4653U)
2634
            s->workaround_bugs |= FF_BUG_STD_QPEL;
2635
2636
3473
        if (ctx->lavc_build < 4655U)
2637
            s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE;
2638
2639
3473
        if (ctx->lavc_build < 4670U)
2640
            s->workaround_bugs |= FF_BUG_EDGE;
2641
2642
3473
        if (ctx->lavc_build <= 4712U)
2643
            s->workaround_bugs |= FF_BUG_DC_CLIP;
2644
2645
3473
        if ((ctx->lavc_build&0xFF) >= 100) {
2646

3473
            if (ctx->lavc_build > 3621476 && ctx->lavc_build < 3752552 &&
2647
               (ctx->lavc_build < 3752037 || ctx->lavc_build > 3752191) // 3.2.1+
2648
            )
2649
                s->workaround_bugs |= FF_BUG_IEDGE;
2650
        }
2651
2652
3473
        if (ctx->divx_version >= 0)
2653
            s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE;
2654

3473
        if (ctx->divx_version == 501 && ctx->divx_build == 20020416)
2655
            s->padding_bug_score = 256 * 256 * 256 * 64;
2656
2657
3473
        if (ctx->divx_version < 500U)
2658
            s->workaround_bugs |= FF_BUG_EDGE;
2659
2660
3473
        if (ctx->divx_version >= 0)
2661
            s->workaround_bugs |= FF_BUG_HPEL_CHROMA;
2662
    }
2663
2664
3473
    if (s->workaround_bugs & FF_BUG_STD_QPEL) {
2665
        SET_QPEL_FUNC(qpel_pixels_tab[0][5], qpel16_mc11_old_c)
2666
        SET_QPEL_FUNC(qpel_pixels_tab[0][7], qpel16_mc31_old_c)
2667
        SET_QPEL_FUNC(qpel_pixels_tab[0][9], qpel16_mc12_old_c)
2668
        SET_QPEL_FUNC(qpel_pixels_tab[0][11], qpel16_mc32_old_c)
2669
        SET_QPEL_FUNC(qpel_pixels_tab[0][13], qpel16_mc13_old_c)
2670
        SET_QPEL_FUNC(qpel_pixels_tab[0][15], qpel16_mc33_old_c)
2671
2672
        SET_QPEL_FUNC(qpel_pixels_tab[1][5], qpel8_mc11_old_c)
2673
        SET_QPEL_FUNC(qpel_pixels_tab[1][7], qpel8_mc31_old_c)
2674
        SET_QPEL_FUNC(qpel_pixels_tab[1][9], qpel8_mc12_old_c)
2675
        SET_QPEL_FUNC(qpel_pixels_tab[1][11], qpel8_mc32_old_c)
2676
        SET_QPEL_FUNC(qpel_pixels_tab[1][13], qpel8_mc13_old_c)
2677
        SET_QPEL_FUNC(qpel_pixels_tab[1][15], qpel8_mc33_old_c)
2678
    }
2679
2680
3473
    if (avctx->debug & FF_DEBUG_BUGS)
2681
        av_log(s->avctx, AV_LOG_DEBUG,
2682
               "bugs: %X lavc_build:%d xvid_build:%d divx_version:%d divx_build:%d %s\n",
2683
               s->workaround_bugs, ctx->lavc_build, ctx->xvid_build,
2684
               ctx->divx_version, ctx->divx_build, s->divx_packed ? "p" : "");
2685
2686
3473
    if (CONFIG_MPEG4_DECODER && ctx->xvid_build >= 0 &&
2687
64
        s->codec_id == AV_CODEC_ID_MPEG4 &&
2688
64
        avctx->idct_algo == FF_IDCT_AUTO) {
2689
4
        avctx->idct_algo = FF_IDCT_XVID;
2690
4
        ff_mpv_idct_init(s);
2691
4
        return 1;
2692
    }
2693
2694
3469
    return 0;
2695
}
2696
2697
6949
static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
2698
{
2699
6949
    MpegEncContext *s = &ctx->m;
2700
    int time_incr, time_increment;
2701
    int64_t pts;
2702
2703
6949
    s->mcsel       = 0;
2704
6949
    s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I;        /* pict type: I = 0 , P = 1 */
2705

6949
    if (s->pict_type == AV_PICTURE_TYPE_B && s->low_delay &&
2706
        ctx->vol_control_parameters == 0 && !(s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)) {
2707
        av_log(s->avctx, AV_LOG_ERROR, "low_delay flag set incorrectly, clearing it\n");
2708
        s->low_delay = 0;
2709
    }
2710
2711

6949
    s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B;
2712
6949
    if (s->partitioned_frame)
2713
1028
        s->decode_mb = mpeg4_decode_partitioned_mb;
2714
    else
2715
5921
        s->decode_mb = mpeg4_decode_mb;
2716
2717
6949
    time_incr = 0;
2718
7198
    while (get_bits1(gb) != 0)
2719
249
        time_incr++;
2720
2721
6949
    check_marker(s->avctx, gb, "before time_increment");
2722
2723
6949
    if (ctx->time_increment_bits == 0 ||
2724
6947
        !(show_bits(gb, ctx->time_increment_bits + 1) & 1)) {
2725
10
        av_log(s->avctx, AV_LOG_WARNING,
2726
               "time_increment_bits %d is invalid in relation to the current bitstream, this is likely caused by a missing VOL header\n", ctx->time_increment_bits);
2727
2728
10
        for (ctx->time_increment_bits = 1;
2729
110
             ctx->time_increment_bits < 16;
2730
100
             ctx->time_increment_bits++) {
2731
110
            if (s->pict_type == AV_PICTURE_TYPE_P ||
2732
110
                (s->pict_type == AV_PICTURE_TYPE_S &&
2733
                 ctx->vol_sprite_usage == GMC_SPRITE)) {
2734
                if ((show_bits(gb, ctx->time_increment_bits + 6) & 0x37) == 0x30)
2735
                    break;
2736
110
            } else if ((show_bits(gb, ctx->time_increment_bits + 5) & 0x1F) == 0x18)
2737
10
                break;
2738
        }
2739
2740
10
        av_log(s->avctx, AV_LOG_WARNING,
2741
               "time_increment_bits set to %d bits, based on bitstream analysis\n", ctx->time_increment_bits);
2742

10
        if (s->avctx->framerate.num && 4*s->avctx->framerate.num < 1<<ctx->time_increment_bits) {
2743
6
            s->avctx->framerate.num = 1<<ctx->time_increment_bits;
2744
6
            s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1}));
2745
        }
2746
    }
2747
2748
    if (IS_3IV1)
2749
        time_increment = get_bits1(gb);        // FIXME investigate further
2750
    else
2751
6949
        time_increment = get_bits(gb, ctx->time_increment_bits);
2752
2753
6949
    if (s->pict_type != AV_PICTURE_TYPE_B) {
2754
5584
        s->last_time_base = s->time_base;
2755
5584
        s->time_base     += time_incr;
2756
5584
        s->time = s->time_base * (int64_t)s->avctx->framerate.num + time_increment;
2757
5584
        if (s->workaround_bugs & FF_BUG_UMP4) {
2758
            if (s->time < s->last_non_b_time) {
2759
                /* header is not mpeg-4-compatible, broken encoder,
2760
                 * trying to workaround */
2761
                s->time_base++;
2762
                s->time += s->avctx->framerate.num;
2763
            }
2764
        }
2765
5584
        s->pp_time         = s->time - s->last_non_b_time;
2766
5584
        s->last_non_b_time = s->time;
2767
    } else {
2768
1365
        s->time    = (s->last_time_base + time_incr) * (int64_t)s->avctx->framerate.num + time_increment;
2769
1365
        s->pb_time = s->pp_time - (s->last_non_b_time - s->time);
2770
1365
        if (s->pp_time <= s->pb_time ||
2771
1365
            s->pp_time <= s->pp_time - s->pb_time ||
2772
1365
            s->pp_time <= 0) {
2773
            /* messed up order, maybe after seeking? skipping current B-frame */
2774
            return FRAME_SKIPPED;
2775
        }
2776
1365
        ff_mpeg4_init_direct_mv(s);
2777
2778
1365
        if (ctx->t_frame == 0)
2779
215
            ctx->t_frame = s->pb_time;
2780
1365
        if (ctx->t_frame == 0)
2781
            ctx->t_frame = 1;  // 1/0 protection
2782
1365
        s->pp_field_time = (ROUNDED_DIV(s->last_non_b_time, ctx->t_frame) -
2783
1365
                            ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;
2784
1365
        s->pb_field_time = (ROUNDED_DIV(s->time, ctx->t_frame) -
2785
1365
                            ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;
2786

1365
        if (s->pp_field_time <= s->pb_field_time || s->pb_field_time <= 1) {
2787
2
            s->pb_field_time = 2;
2788
2
            s->pp_field_time = 4;
2789
2
            if (!s->progressive_sequence)
2790
                return FRAME_SKIPPED;
2791
        }
2792
    }
2793
2794
6949
    if (s->avctx->framerate.den)
2795
6949
        pts = ROUNDED_DIV(s->time, s->avctx->framerate.den);
2796
    else
2797
        pts = AV_NOPTS_VALUE;
2798
    ff_dlog(s->avctx, "MPEG4 PTS: %"PRId64"\n", pts);
2799
2800
6949
    check_marker(s->avctx, gb, "before vop_coded");
2801
2802
    /* vop coded */
2803
6949
    if (get_bits1(gb) != 1) {
2804
8
        if (s->avctx->debug & FF_DEBUG_PICT_INFO)
2805
            av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n");
2806
8
        return FRAME_SKIPPED;
2807
    }
2808
6941
    if (ctx->new_pred)
2809
        decode_new_pred(ctx, gb);
2810
2811
6941
    if (ctx->shape != BIN_ONLY_SHAPE &&
2812
6941
                    (s->pict_type == AV_PICTURE_TYPE_P ||
2813
2378
                     (s->pict_type == AV_PICTURE_TYPE_S &&
2814
                      ctx->vol_sprite_usage == GMC_SPRITE))) {
2815
        /* rounding type for motion estimation */
2816
4563
        s->no_rounding = get_bits1(gb);
2817
    } else {
2818
2378
        s->no_rounding = 0;
2819
    }
2820
    // FIXME reduced res stuff
2821
2822
6941
    if (ctx->shape != RECT_SHAPE) {
2823
        if (ctx->vol_sprite_usage != 1 || s->pict_type != AV_PICTURE_TYPE_I) {
2824
            skip_bits(gb, 13);  /* width */
2825
            check_marker(s->avctx, gb, "after width");
2826
            skip_bits(gb, 13);  /* height */
2827
            check_marker(s->avctx, gb, "after height");
2828
            skip_bits(gb, 13);  /* hor_spat_ref */
2829
            check_marker(s->avctx, gb, "after hor_spat_ref");
2830
            skip_bits(gb, 13);  /* ver_spat_ref */
2831
        }
2832
        skip_bits1(gb);         /* change_CR_disable */
2833
2834
        if (get_bits1(gb) != 0)
2835
            skip_bits(gb, 8);   /* constant_alpha_value */
2836
    }
2837
2838
    // FIXME complexity estimation stuff
2839
2840
6941
    if (ctx->shape != BIN_ONLY_SHAPE) {
2841
6941
        skip_bits_long(gb, ctx->cplx_estimation_trash_i);
2842
6941
        if (s->pict_type != AV_PICTURE_TYPE_I)
2843
5928
            skip_bits_long(gb, ctx->cplx_estimation_trash_p);
2844
6941
        if (s->pict_type == AV_PICTURE_TYPE_B)
2845
1365
            skip_bits_long(gb, ctx->cplx_estimation_trash_b);
2846
2847
6941
        if (get_bits_left(gb) < 3) {
2848
            av_log(s->avctx, AV_LOG_ERROR, "Header truncated\n");
2849
            return AVERROR_INVALIDDATA;
2850
        }
2851
6941
        ctx->intra_dc_threshold = ff_mpeg4_dc_threshold[get_bits(gb, 3)];
2852
6941
        if (!s->progressive_sequence) {
2853
50
            s->top_field_first = get_bits1(gb);
2854
50
            s->alternate_scan  = get_bits1(gb);
2855
        } else
2856
6891
            s->alternate_scan = 0;
2857
    }
2858
2859
6941
    if (s->alternate_scan) {
2860
6
        ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable,   ff_alternate_vertical_scan);
2861
6
        ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable,   ff_alternate_vertical_scan);
2862
6
        ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
2863
6
        ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
2864
    } else {
2865
6935
        ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable,   ff_zigzag_direct);
2866
6935
        ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable,   ff_zigzag_direct);
2867
6935
        ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
2868
6935
        ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
2869
    }
2870
2871
6941
    if (s->pict_type == AV_PICTURE_TYPE_S) {
2872
        if((ctx->vol_sprite_usage == STATIC_SPRITE ||
2873
            ctx->vol_sprite_usage == GMC_SPRITE)) {
2874
            if (mpeg4_decode_sprite_trajectory(ctx, gb) < 0)
2875
                return AVERROR_INVALIDDATA;
2876
            if (ctx->sprite_brightness_change)
2877
                av_log(s->avctx, AV_LOG_ERROR,
2878
                    "sprite_brightness_change not supported\n");
2879
            if (ctx->vol_sprite_usage == STATIC_SPRITE)
2880
                av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n");
2881
        } else {
2882
            memset(s->sprite_offset, 0, sizeof(s->sprite_offset));
2883
            memset(s->sprite_delta, 0, sizeof(s->sprite_delta));
2884
        }
2885
    }
2886
2887
6941
    if (ctx->shape != BIN_ONLY_SHAPE) {
2888
6941
        s->chroma_qscale = s->qscale = get_bits(gb, s->quant_precision);
2889
6941
        if (s->qscale == 0) {
2890
            av_log(s->avctx, AV_LOG_ERROR,
2891
                   "Error, header damaged or not MPEG-4 header (qscale=0)\n");
2892
            return AVERROR_INVALIDDATA;  // makes no sense to continue, as there is nothing left from the image then
2893
        }
2894
2895
6941
        if (s->pict_type != AV_PICTURE_TYPE_I) {
2896
5928
            s->f_code = get_bits(gb, 3);        /* fcode_for */
2897
5928
            if (s->f_code == 0) {
2898
4
                av_log(s->avctx, AV_LOG_ERROR,
2899
                       "Error, header damaged or not MPEG-4 header (f_code=0)\n");
2900
4
                s->f_code = 1;
2901
4
                return AVERROR_INVALIDDATA;  // makes no sense to continue, as there is nothing left from the image then
2902
            }
2903
        } else
2904
1013
            s->f_code = 1;
2905
2906
6937
        if (s->pict_type == AV_PICTURE_TYPE_B) {
2907
1365
            s->b_code = get_bits(gb, 3);
2908
1365
            if (s->b_code == 0) {
2909
                av_log(s->avctx, AV_LOG_ERROR,
2910
                       "Error, header damaged or not MPEG4 header (b_code=0)\n");
2911
                s->b_code=1;
2912
                return AVERROR_INVALIDDATA; // makes no sense to continue, as the MV decoding will break very quickly
2913
            }
2914
        } else
2915
5572
            s->b_code = 1;
2916
2917
6937
        if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
2918
            av_log(s->avctx, AV_LOG_DEBUG,
2919
                   "qp:%d fc:%d,%d %s size:%d pro:%d alt:%d top:%d %spel part:%d resync:%d w:%d a:%d rnd:%d vot:%d%s dc:%d ce:%d/%d/%d time:%"PRId64" tincr:%d\n",
2920
                   s->qscale, s->f_code, s->b_code,
2921
                   s->pict_type == AV_PICTURE_TYPE_I ? "I" : (s->pict_type == AV_PICTURE_TYPE_P ? "P" : (s->pict_type == AV_PICTURE_TYPE_B ? "B" : "S")),
2922
                   gb->size_in_bits,s->progressive_sequence, s->alternate_scan,
2923
                   s->top_field_first, s->quarter_sample ? "q" : "h",
2924
                   s->data_partitioning, ctx->resync_marker,
2925
                   ctx->num_sprite_warping_points, s->sprite_warping_accuracy,
2926
                   1 - s->no_rounding, s->vo_type,
2927
                   ctx->vol_control_parameters ? " VOLC" : " ", ctx->intra_dc_threshold,
2928
                   ctx->cplx_estimation_trash_i, ctx->cplx_estimation_trash_p,
2929
                   ctx->cplx_estimation_trash_b,
2930
                   s->time,
2931
                   time_increment
2932
                  );
2933
        }
2934
2935
6937
        if (!ctx->scalability) {
2936

6937
            if (ctx->shape != RECT_SHAPE && s->pict_type != AV_PICTURE_TYPE_I)
2937
                skip_bits1(gb);  // vop shape coding type
2938
        } else {
2939
            if (ctx->enhancement_type) {
2940
                int load_backward_shape = get_bits1(gb);
2941
                if (load_backward_shape)
2942
                    av_log(s->avctx, AV_LOG_ERROR,
2943
                           "load backward shape isn't supported\n");
2944
            }
2945
            skip_bits(gb, 2);  // ref_select_code
2946
        }
2947
    }
2948
    /* detect buggy encoders which don't set the low_delay flag
2949
     * (divx4/xvid/opendivx). Note we cannot detect divx5 without B-frames
2950
     * easily (although it's buggy too) */
2951

6937
    if (s->vo_type == 0 && ctx->vol_control_parameters == 0 &&
2952

48
        ctx->divx_version == -1 && s->picture_number == 0) {
2953
2
        av_log(s->avctx, AV_LOG_WARNING,
2954
               "looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n");
2955
2
        s->low_delay = 1;
2956
    }
2957
2958
6937
    s->picture_number++;  // better than pic number==0 always ;)
2959
2960
    // FIXME add short header support
2961
6937
    s->y_dc_scale_table = ff_mpeg4_y_dc_scale_table;
2962
6937
    s->c_dc_scale_table = ff_mpeg4_c_dc_scale_table;
2963
2964
6937
    if (s->workaround_bugs & FF_BUG_EDGE) {
2965
        s->h_edge_pos = s->width;
2966
        s->v_edge_pos = s->height;
2967
    }
2968
6937
    return 0;
2969
}
2970
2971
static int read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)
2972
{
2973
    int i, j, v;
2974
2975
    if (get_bits1(gb)) {
2976
        if (get_bits_left(gb) < 64*8)
2977
            return AVERROR_INVALIDDATA;
2978
        /* intra_quantiser_matrix */
2979
        for (i = 0; i < 64; i++) {
2980
            v = get_bits(gb, 8);
2981
            j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
2982
            s->intra_matrix[j]        = v;
2983
            s->chroma_intra_matrix[j] = v;
2984
        }
2985
    }
2986
2987
    if (get_bits1(gb)) {
2988
        if (get_bits_left(gb) < 64*8)
2989
            return AVERROR_INVALIDDATA;
2990
        /* non_intra_quantiser_matrix */
2991
        for (i = 0; i < 64; i++) {
2992
            get_bits(gb, 8);
2993
        }
2994
    }
2995
2996
    if (get_bits1(gb)) {
2997
        if (get_bits_left(gb) < 64*8)
2998
            return AVERROR_INVALIDDATA;
2999
        /* chroma_intra_quantiser_matrix */
3000
        for (i = 0; i < 64; i++) {
3001
            v = get_bits(gb, 8);
3002
            j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
3003
            s->chroma_intra_matrix[j] = v;
3004
        }
3005
    }
3006
3007
    if (get_bits1(gb)) {
3008
        if (get_bits_left(gb) < 64*8)
3009
            return AVERROR_INVALIDDATA;
3010
        /* chroma_non_intra_quantiser_matrix */
3011
        for (i = 0; i < 64; i++) {
3012
            get_bits(gb, 8);
3013
        }
3014
    }
3015
3016
    next_start_code_studio(gb);
3017
    return 0;
3018
}
3019
3020
static void extension_and_user_data(MpegEncContext *s, GetBitContext *gb, int id)
3021
{
3022
    uint32_t startcode;
3023
    uint8_t extension_type;
3024
3025
    startcode = show_bits_long(gb, 32);
3026
    if (startcode == USER_DATA_STARTCODE || startcode == EXT_STARTCODE) {
3027
3028
        if ((id == 2 || id == 4) && startcode == EXT_STARTCODE) {
3029
            skip_bits_long(gb, 32);
3030
            extension_type = get_bits(gb, 4);
3031
            if (extension_type == QUANT_MATRIX_EXT_ID)
3032
                read_quant_matrix_ext(s, gb);
3033
        }
3034
    }
3035
}
3036
3037
static void decode_smpte_tc(Mpeg4DecContext *ctx, GetBitContext *gb)
3038
{
3039
    MpegEncContext *s = &ctx->m;
3040
3041
    skip_bits(gb, 16); /* Time_code[63..48] */
3042
    check_marker(s->avctx, gb, "after Time_code[63..48]");
3043
    skip_bits(gb, 16); /* Time_code[47..32] */
3044
    check_marker(s->avctx, gb, "after Time_code[47..32]");
3045
    skip_bits(gb, 16); /* Time_code[31..16] */
3046
    check_marker(s->avctx, gb, "after Time_code[31..16]");
3047
    skip_bits(gb, 16); /* Time_code[15..0] */
3048
    check_marker(s->avctx, gb, "after Time_code[15..0]");
3049
    skip_bits(gb, 4); /* reserved_bits */
3050
}
3051
3052
/**
3053
 * Decode the next studio vop header.
3054
 * @return <0 if something went wrong
3055
 */
3056
static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
3057
{
3058
    MpegEncContext *s = &ctx->m;
3059
3060
    if (get_bits_left(gb) <= 32)
3061
        return 0;
3062
3063
    s->partitioned_frame = 0;
3064
    s->interlaced_dct = 0;
3065
    s->decode_mb = mpeg4_decode_studio_mb;
3066
3067
    decode_smpte_tc(ctx, gb);
3068
3069
    skip_bits(gb, 10); /* temporal_reference */
3070
    skip_bits(gb, 2); /* vop_structure */
3071
    s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */
3072
    if (get_bits1(gb)) { /* vop_coded */
3073
        skip_bits1(gb); /* top_field_first */
3074
        skip_bits1(gb); /* repeat_first_field */
3075
        s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */
3076
    }
3077
3078
    if (s->pict_type == AV_PICTURE_TYPE_I) {
3079
        if (get_bits1(gb))
3080
            reset_studio_dc_predictors(s);
3081
    }
3082
3083
    if (ctx->shape != BIN_ONLY_SHAPE) {
3084
        s->alternate_scan = get_bits1(gb);
3085
        s->frame_pred_frame_dct = get_bits1(gb);
3086
        s->dct_precision = get_bits(gb, 2);
3087
        s->intra_dc_precision = get_bits(gb, 2);
3088
        s->q_scale_type = get_bits1(gb);
3089
    }
3090
3091
    if (s->alternate_scan) {
3092
        ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable,   ff_alternate_vertical_scan);
3093
        ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable,   ff_alternate_vertical_scan);
3094
        ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
3095
        ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
3096
    } else {
3097
        ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable,   ff_zigzag_direct);
3098
        ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable,   ff_zigzag_direct);
3099
        ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
3100
        ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
3101
    }
3102
3103
    mpeg4_load_default_matrices(s);
3104
3105
    next_start_code_studio(gb);
3106
    extension_and_user_data(s, gb, 4);
3107
3108
    return 0;
3109
}
3110
3111
static int decode_studiovisualobject(Mpeg4DecContext *ctx, GetBitContext *gb)
3112
{
3113
    MpegEncContext *s = &ctx->m;
3114
    int visual_object_type;
3115
3116
        skip_bits(gb, 4); /* visual_object_verid */
3117
        visual_object_type = get_bits(gb, 4);
3118
        if (visual_object_type != VOT_VIDEO_ID) {
3119
            avpriv_request_sample(s->avctx, "VO type %u", visual_object_type);
3120
            return AVERROR_PATCHWELCOME;
3121
        }
3122
3123
        next_start_code_studio(gb);
3124
        extension_and_user_data(s, gb, 1);
3125
3126
    return 0;
3127
}
3128
3129
static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb)
3130
{
3131
    MpegEncContext *s = &ctx->m;
3132
    int width, height;
3133
    int bits_per_raw_sample;
3134
    int rgb, chroma_format;
3135
3136
            // random_accessible_vol and video_object_type_indication have already
3137
            // been read by the caller decode_vol_header()
3138
            skip_bits(gb, 4); /* video_object_layer_verid */
3139
            ctx->shape = get_bits(gb, 2); /* video_object_layer_shape */
3140
            skip_bits(gb, 4); /* video_object_layer_shape_extension */
3141
            skip_bits1(gb); /* progressive_sequence */
3142
            if (ctx->shape != RECT_SHAPE) {
3143
                avpriv_request_sample(s->avctx, "MPEG-4 Studio profile non rectangular shape");
3144
                return AVERROR_PATCHWELCOME;
3145
            }
3146
            if (ctx->shape != BIN_ONLY_SHAPE) {
3147
                rgb = get_bits1(gb); /* rgb_components */
3148
                chroma_format = get_bits(gb, 2); /* chroma_format */
3149
                if (!chroma_format || chroma_format == CHROMA_420 || (rgb && chroma_format == CHROMA_422)) {
3150
                    av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n");
3151
                    return AVERROR_INVALIDDATA;
3152
                }
3153
3154
                bits_per_raw_sample = get_bits(gb, 4); /* bit_depth */
3155
                if (bits_per_raw_sample == 10) {
3156
                    if (rgb) {
3157
                        s->avctx->pix_fmt = AV_PIX_FMT_GBRP10;
3158
                    }
3159
                    else {
3160
                        s->avctx->pix_fmt = chroma_format == CHROMA_422 ? AV_PIX_FMT_YUV422P10 : AV_PIX_FMT_YUV444P10;
3161
                    }
3162
                }
3163
                else {
3164
                    avpriv_request_sample(s->avctx, "MPEG-4 Studio profile bit-depth %u", bits_per_raw_sample);
3165
                    return AVERROR_PATCHWELCOME;
3166
                }
3167
                if (rgb != ctx->rgb || s->chroma_format != chroma_format)
3168
                    s->context_reinit = 1;
3169
                s->avctx->bits_per_raw_sample = bits_per_raw_sample;
3170
                ctx->rgb = rgb;
3171
                s->chroma_format = chroma_format;
3172
            }
3173
            if (ctx->shape == RECT_SHAPE) {
3174
                check_marker(s->avctx, gb, "before video_object_layer_width");
3175
                width = get_bits(gb, 14); /* video_object_layer_width */
3176
                check_marker(s->avctx, gb, "before video_object_layer_height");
3177
                height = get_bits(gb, 14); /* video_object_layer_height */
3178
                check_marker(s->avctx, gb, "after video_object_layer_height");
3179
3180
                /* Do the same check as non-studio profile */
3181
                if (width && height) {
3182
                    if (s->width && s->height &&
3183
                        (s->width != width || s->height != height))
3184
                        s->context_reinit = 1;
3185
                    s->width  = width;
3186
                    s->height = height;
3187
                }
3188
            }
3189
            s->aspect_ratio_info = get_bits(gb, 4);
3190
            if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
3191
                s->avctx->sample_aspect_ratio.num = get_bits(gb, 8);  // par_width
3192
                s->avctx->sample_aspect_ratio.den = get_bits(gb, 8);  // par_height
3193
            } else {
3194
                s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info];
3195
            }
3196
            skip_bits(gb, 4); /* frame_rate_code */
3197
            skip_bits(gb, 15); /* first_half_bit_rate */
3198
            check_marker(s->avctx, gb, "after first_half_bit_rate");
3199
            skip_bits(gb, 15); /* latter_half_bit_rate */
3200
            check_marker(s->avctx, gb, "after latter_half_bit_rate");
3201
            skip_bits(gb, 15); /* first_half_vbv_buffer_size */
3202
            check_marker(s->avctx, gb, "after first_half_vbv_buffer_size");
3203
            skip_bits(gb, 3); /* latter_half_vbv_buffer_size */
3204
            skip_bits(gb, 11); /* first_half_vbv_buffer_size */
3205
            check_marker(s->avctx, gb, "after first_half_vbv_buffer_size");
3206
            skip_bits(gb, 15); /* latter_half_vbv_occupancy */
3207
            check_marker(s->avctx, gb, "after latter_half_vbv_occupancy");
3208
            s->low_delay = get_bits1(gb);
3209
            s->mpeg_quant = get_bits1(gb); /* mpeg2_stream */
3210
3211
            next_start_code_studio(gb);
3212
            extension_and_user_data(s, gb, 2);
3213
3214
    return 0;
3215
}
3216
3217
/**
3218
 * Decode MPEG-4 headers.
3219
 *
3220
 * @param  header If set the absence of a VOP is not treated as error; otherwise, it is treated as such.
3221
 * @return <0 if an error occurred
3222
 *         FRAME_SKIPPED if a not coded VOP is found
3223
 *         0 else
3224
 */
3225
7442
int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb, int header)
3226
{
3227
7442
    MpegEncContext *s = &ctx->m;
3228
    unsigned startcode, v;
3229
    int ret;
3230
7442
    int vol = 0;
3231
3232
    /* search next start code */
3233
7442
    align_get_bits(gb);
3234
3235
    // If we have not switched to studio profile than we also did not switch bps
3236
    // that means something else (like a previous instance) outside set bps which
3237
    // would be inconsistant with the currect state, thus reset it
3238

7442
    if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8)
3239
7442
        s->avctx->bits_per_raw_sample = 0;
3240
3241

7442
    if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) {
3242
        skip_bits(gb, 24);
3243
        if (get_bits(gb, 8) == 0xF0)
3244
            goto end;
3245
    }
3246
3247
7442
    startcode = 0xff;
3248
    for (;;) {
3249
52137
        if (get_bits_count(gb) >= gb->size_in_bits) {
3250
493
            if (gb->size_in_bits == 8 &&
3251

493
                (ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) {
3252
                av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits);
3253
                return FRAME_SKIPPED;  // divx bug
3254

493
            } else if (header && get_bits_count(gb) == gb->size_in_bits) {
3255
402
                return 0; // ordinary return value for parsing of extradata
3256
            } else
3257
91
                return AVERROR_INVALIDDATA;  // end of stream
3258
        }
3259
3260
        /* use the bits after the test */
3261
51644
        v = get_bits(gb, 8);
3262
51644
        startcode = ((startcode << 8) | v) & 0xffffffff;
3263
3264
51644
        if ((startcode & 0xFFFFFF00) != 0x100)
3265
38734
            continue;  // no startcode
3266
3267
12910
        if (s->avctx->debug & FF_DEBUG_STARTCODE) {
3268
            av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode);
3269
            if (startcode <= 0x11F)
3270
                av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start");
3271
            else if (startcode <= 0x12F)
3272
                av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start");
3273
            else if (startcode <= 0x13F)
3274
                av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
3275
            else if (startcode <= 0x15F)
3276
                av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start");
3277
            else if (startcode <= 0x1AF)
3278
                av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
3279
            else if (startcode == 0x1B0)
3280
                av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start");
3281
            else if (startcode == 0x1B1)
3282
                av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End");
3283
            else if (startcode == 0x1B2)
3284
                av_log(s->avctx, AV_LOG_DEBUG, "User Data");
3285
            else if (startcode == 0x1B3)
3286
                av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start");
3287
            else if (startcode == 0x1B4)
3288
                av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error");
3289
            else if (startcode == 0x1B5)
3290
                av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start");
3291
            else if (startcode == 0x1B6)
3292
                av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start");
3293
            else if (startcode == 0x1B7)
3294
                av_log(s->avctx, AV_LOG_DEBUG, "slice start");
3295
            else if (startcode == 0x1B8)
3296
                av_log(s->avctx, AV_LOG_DEBUG, "extension start");
3297
            else if (startcode == 0x1B9)
3298
                av_log(s->avctx, AV_LOG_DEBUG, "fgs start");
3299
            else if (startcode == 0x1BA)
3300
                av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start");
3301
            else if (startcode == 0x1BB)
3302
                av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start");
3303
            else if (startcode == 0x1BC)
3304
                av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start");
3305
            else if (startcode == 0x1BD)
3306
                av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start");
3307
            else if (startcode == 0x1BE)
3308
                av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start");
3309
            else if (startcode == 0x1BF)
3310
                av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start");
3311
            else if (startcode == 0x1C0)
3312
                av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start");
3313
            else if (startcode == 0x1C1)
3314
                av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start");
3315
            else if (startcode == 0x1C2)
3316
                av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start");
3317
            else if (startcode == 0x1C3)
3318
                av_log(s->avctx, AV_LOG_DEBUG, "stuffing start");
3319
            else if (startcode <= 0x1C5)
3320
                av_log(s->avctx, AV_LOG_DEBUG, "reserved");
3321
            else if (startcode <= 0x1FF)
3322
                av_log(s->avctx, AV_LOG_DEBUG, "System start");
3323
            av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb));
3324
        }
3325
3326

12910
        if (startcode >= 0x120 && startcode <= 0x12F) {
3327
1249
            if (vol) {
3328
                av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n");
3329
                continue;
3330
            }
3331
1249
            vol++;
3332
1249
            if ((ret = decode_vol_header(ctx, gb)) < 0)
3333
                return ret;
3334
11661
        } else if (startcode == USER_DATA_STARTCODE) {
3335
75
            decode_user_data(ctx, gb);
3336
11586
        } else if (startcode == GOP_STARTCODE) {
3337
954
            mpeg4_decode_gop_header(s, gb);
3338
10632
        } else if (startcode == VOS_STARTCODE) {
3339
            int profile, level;
3340
1217
            mpeg4_decode_profile_level(s, gb, &profile, &level);
3341
1217
            if (profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO &&
3342
                (level > 0 && level < 9)) {
3343
                s->studio_profile = 1;
3344
                next_start_code_studio(gb);
3345
                extension_and_user_data(s, gb, 0);
3346
1217
            } else if (s->studio_profile) {
3347
                avpriv_request_sample(s->avctx, "Mix of studio and non studio profile");
3348
                return AVERROR_PATCHWELCOME;
3349
            }
3350
1217
            s->avctx->profile = profile;
3351
1217
            s->avctx->level   = level;
3352
9415
        } else if (startcode == VISUAL_OBJ_STARTCODE) {
3353
1217
            if (s->studio_profile) {
3354
                if ((ret = decode_studiovisualobject(ctx, gb)) < 0)
3355
                    return ret;
3356
            } else
3357
1217
                mpeg4_decode_visual_object(s, gb);
3358
8198
        } else if (startcode == VOP_STARTCODE) {
3359
6949
            break;
3360
        }
3361
3362
5961
        align_get_bits(gb);
3363
5961
        startcode = 0xff;
3364
    }
3365
3366
6949
end:
3367
6949
    if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)
3368
        s->low_delay = 1;
3369
6949
    s->avctx->has_b_frames = !s->low_delay;
3370
3371
6949
    if (s->studio_profile) {
3372
        if (!s->avctx->bits_per_raw_sample) {
3373
            av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n");
3374
            return AVERROR_INVALIDDATA;
3375
        }
3376
        return decode_studio_vop_header(ctx, gb);
3377
    } else
3378
6949
        return decode_vop_header(ctx, gb);
3379
}
3380
3381
494
av_cold void ff_mpeg4videodec_static_init(void) {
3382
    static int done = 0;
3383
3384
494
    if (!done) {
3385
96
        ff_rl_init(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
3386
96
        ff_rl_init(&ff_rvlc_rl_inter, ff_mpeg4_static_rl_table_store[1]);
3387
96
        ff_rl_init(&ff_rvlc_rl_intra, ff_mpeg4_static_rl_table_store[2]);
3388

3168
        INIT_VLC_RL(ff_mpeg4_rl_intra, 554);
3389

3168
        INIT_VLC_RL(ff_rvlc_rl_inter, 1072);
3390

3168
        INIT_VLC_RL(ff_rvlc_rl_intra, 1072);
3391
96
        INIT_VLC_STATIC(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
3392
                        &ff_mpeg4_DCtab_lum[0][1], 2, 1,
3393
                        &ff_mpeg4_DCtab_lum[0][0], 2, 1, 512);
3394
96
        INIT_VLC_STATIC(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
3395
                        &ff_mpeg4_DCtab_chrom[0][1], 2, 1,
3396
                        &ff_mpeg4_DCtab_chrom[0][0], 2, 1, 512);
3397
96
        INIT_VLC_STATIC(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
3398
                        &ff_sprite_trajectory_tab[0][1], 4, 2,
3399
                        &ff_sprite_trajectory_tab[0][0], 4, 2, 128);
3400
96
        INIT_VLC_STATIC(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
3401
                        &ff_mb_type_b_tab[0][1], 2, 1,
3402
                        &ff_mb_type_b_tab[0][0], 2, 1, 16);
3403
96
        done = 1;
3404