Coverage Report

Created: 2024-09-06 07:53

/src/ffmpeg/libavcodec/mpeg4videodec.c
Line
Count
Source (jump to first uncovered line)
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 "config_components.h"
26
27
#include "libavutil/internal.h"
28
#include "libavutil/opt.h"
29
#include "libavutil/thread.h"
30
#include "codec_internal.h"
31
#include "error_resilience.h"
32
#include "hwconfig.h"
33
#include "idctdsp.h"
34
#include "mpegutils.h"
35
#include "mpegvideo.h"
36
#include "mpegvideodata.h"
37
#include "mpegvideodec.h"
38
#include "mpeg4video.h"
39
#include "mpeg4videodata.h"
40
#include "mpeg4videodec.h"
41
#include "mpeg4videodefs.h"
42
#include "h263.h"
43
#include "h263data.h"
44
#include "h263dec.h"
45
#include "internal.h"
46
#include "profiles.h"
47
#include "qpeldsp.h"
48
#include "threadprogress.h"
49
#include "xvididct.h"
50
#include "unary.h"
51
52
/* The defines below define the number of bits that are read at once for
53
 * reading vlc values. Changing these may improve speed and data cache needs
54
 * be aware though that decreasing them may need the number of stages that is
55
 * passed to get_vlc* to be increased. */
56
0
#define SPRITE_TRAJ_VLC_BITS 6
57
0
#define DC_VLC_BITS 9
58
0
#define MB_TYPE_B_VLC_BITS 4
59
0
#define STUDIO_INTRA_BITS 9
60
61
static VLCElem dc_lum[512], dc_chrom[512];
62
static VLCElem sprite_trajectory[128];
63
static VLCElem mb_type_b_vlc[16];
64
static const VLCElem *studio_intra_tab[12];
65
static VLCElem studio_luma_dc[528];
66
static VLCElem studio_chroma_dc[528];
67
68
static const uint8_t mpeg4_block_count[4] = { 0, 6, 8, 12 };
69
70
static const int16_t mb_type_b_map[4] = {
71
    MB_TYPE_DIRECT2     | MB_TYPE_BIDIR_MV,
72
    MB_TYPE_BIDIR_MV    | MB_TYPE_16x16,
73
    MB_TYPE_BACKWARD_MV | MB_TYPE_16x16,
74
    MB_TYPE_FORWARD_MV  | MB_TYPE_16x16,
75
};
76
77
static void gmc1_motion(MpegEncContext *s, const Mpeg4DecContext *ctx,
78
                        uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
79
                        uint8_t *const *ref_picture)
80
0
{
81
0
    const uint8_t *ptr;
82
0
    int src_x, src_y, motion_x, motion_y;
83
0
    ptrdiff_t offset, linesize, uvlinesize;
84
0
    int emu = 0;
85
86
0
    motion_x   = ctx->sprite_offset[0][0];
87
0
    motion_y   = ctx->sprite_offset[0][1];
88
0
    src_x      = s->mb_x * 16 + (motion_x >> (ctx->sprite_warping_accuracy + 1));
89
0
    src_y      = s->mb_y * 16 + (motion_y >> (ctx->sprite_warping_accuracy + 1));
90
0
    motion_x *= 1 << (3 - ctx->sprite_warping_accuracy);
91
0
    motion_y *= 1 << (3 - ctx->sprite_warping_accuracy);
92
0
    src_x      = av_clip(src_x, -16, s->width);
93
0
    if (src_x == s->width)
94
0
        motion_x = 0;
95
0
    src_y = av_clip(src_y, -16, s->height);
96
0
    if (src_y == s->height)
97
0
        motion_y = 0;
98
99
0
    linesize   = s->linesize;
100
0
    uvlinesize = s->uvlinesize;
101
102
0
    ptr = ref_picture[0] + src_y * linesize + src_x;
103
104
0
    if ((unsigned)src_x >= FFMAX(s->h_edge_pos - 17, 0) ||
105
0
        (unsigned)src_y >= FFMAX(s->v_edge_pos - 17, 0)) {
106
0
        s->vdsp.emulated_edge_mc(s->sc.edge_emu_buffer, ptr,
107
0
                                 linesize, linesize,
108
0
                                 17, 17,
109
0
                                 src_x, src_y,
110
0
                                 s->h_edge_pos, s->v_edge_pos);
111
0
        ptr = s->sc.edge_emu_buffer;
112
0
    }
113
114
0
    if ((motion_x | motion_y) & 7) {
115
0
        ctx->mdsp.gmc1(dest_y, ptr, linesize, 16,
116
0
                       motion_x & 15, motion_y & 15, 128 - s->no_rounding);
117
0
        ctx->mdsp.gmc1(dest_y + 8, ptr + 8, linesize, 16,
118
0
                       motion_x & 15, motion_y & 15, 128 - s->no_rounding);
119
0
    } else {
120
0
        int dxy;
121
122
0
        dxy = ((motion_x >> 3) & 1) | ((motion_y >> 2) & 2);
123
0
        if (s->no_rounding) {
124
0
            s->hdsp.put_no_rnd_pixels_tab[0][dxy](dest_y, ptr, linesize, 16);
125
0
        } else {
126
0
            s->hdsp.put_pixels_tab[0][dxy](dest_y, ptr, linesize, 16);
127
0
        }
128
0
    }
129
130
0
    if (CONFIG_GRAY && s->avctx->flags & AV_CODEC_FLAG_GRAY)
131
0
        return;
132
133
0
    motion_x   = ctx->sprite_offset[1][0];
134
0
    motion_y   = ctx->sprite_offset[1][1];
135
0
    src_x      = s->mb_x * 8 + (motion_x >> (ctx->sprite_warping_accuracy + 1));
136
0
    src_y      = s->mb_y * 8 + (motion_y >> (ctx->sprite_warping_accuracy + 1));
137
0
    motion_x  *= 1 << (3 - ctx->sprite_warping_accuracy);
138
0
    motion_y  *= 1 << (3 - ctx->sprite_warping_accuracy);
139
0
    src_x      = av_clip(src_x, -8, s->width >> 1);
140
0
    if (src_x == s->width >> 1)
141
0
        motion_x = 0;
142
0
    src_y = av_clip(src_y, -8, s->height >> 1);
143
0
    if (src_y == s->height >> 1)
144
0
        motion_y = 0;
145
146
0
    offset = (src_y * uvlinesize) + src_x;
147
0
    ptr    = ref_picture[1] + offset;
148
0
    if ((unsigned)src_x >= FFMAX((s->h_edge_pos >> 1) - 9, 0) ||
149
0
        (unsigned)src_y >= FFMAX((s->v_edge_pos >> 1) - 9, 0)) {
150
0
        s->vdsp.emulated_edge_mc(s->sc.edge_emu_buffer, ptr,
151
0
                                 uvlinesize, uvlinesize,
152
0
                                 9, 9,
153
0
                                 src_x, src_y,
154
0
                                 s->h_edge_pos >> 1, s->v_edge_pos >> 1);
155
0
        ptr = s->sc.edge_emu_buffer;
156
0
        emu = 1;
157
0
    }
158
0
    ctx->mdsp.gmc1(dest_cb, ptr, uvlinesize, 8,
159
0
                   motion_x & 15, motion_y & 15, 128 - s->no_rounding);
160
161
0
    ptr = ref_picture[2] + offset;
162
0
    if (emu) {
163
0
        s->vdsp.emulated_edge_mc(s->sc.edge_emu_buffer, ptr,
164
0
                                 uvlinesize, uvlinesize,
165
0
                                 9, 9,
166
0
                                 src_x, src_y,
167
0
                                 s->h_edge_pos >> 1, s->v_edge_pos >> 1);
168
0
        ptr = s->sc.edge_emu_buffer;
169
0
    }
170
0
    ctx->mdsp.gmc1(dest_cr, ptr, uvlinesize, 8,
171
0
                   motion_x & 15, motion_y & 15, 128 - s->no_rounding);
172
0
}
173
174
static void gmc_motion(MpegEncContext *s, const Mpeg4DecContext *ctx,
175
                       uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
176
                       uint8_t *const *ref_picture)
177
0
{
178
0
    const uint8_t *ptr;
179
0
    int linesize, uvlinesize;
180
0
    const int a = ctx->sprite_warping_accuracy;
181
0
    int ox, oy;
182
183
0
    linesize   = s->linesize;
184
0
    uvlinesize = s->uvlinesize;
185
186
0
    ptr = ref_picture[0];
187
188
0
    ox = ctx->sprite_offset[0][0] + ctx->sprite_delta[0][0] * s->mb_x * 16 +
189
0
         ctx->sprite_delta[0][1] * s->mb_y * 16;
190
0
    oy = ctx->sprite_offset[0][1] + ctx->sprite_delta[1][0] * s->mb_x * 16 +
191
0
         ctx->sprite_delta[1][1] * s->mb_y * 16;
192
193
0
    ctx->mdsp.gmc(dest_y, ptr, linesize, 16,
194
0
                  ox, oy,
195
0
                  ctx->sprite_delta[0][0], ctx->sprite_delta[0][1],
196
0
                  ctx->sprite_delta[1][0], ctx->sprite_delta[1][1],
197
0
                  a + 1, (1 << (2 * a + 1)) - s->no_rounding,
198
0
                  s->h_edge_pos, s->v_edge_pos);
199
0
    ctx->mdsp.gmc(dest_y + 8, ptr, linesize, 16,
200
0
                  ox + ctx->sprite_delta[0][0] * 8,
201
0
                  oy + ctx->sprite_delta[1][0] * 8,
202
0
                  ctx->sprite_delta[0][0], ctx->sprite_delta[0][1],
203
0
                  ctx->sprite_delta[1][0], ctx->sprite_delta[1][1],
204
0
                  a + 1, (1 << (2 * a + 1)) - s->no_rounding,
205
0
                  s->h_edge_pos, s->v_edge_pos);
206
207
0
    if (CONFIG_GRAY && s->avctx->flags & AV_CODEC_FLAG_GRAY)
208
0
        return;
209
210
0
    ox = ctx->sprite_offset[1][0] + ctx->sprite_delta[0][0] * s->mb_x * 8 +
211
0
         ctx->sprite_delta[0][1] * s->mb_y * 8;
212
0
    oy = ctx->sprite_offset[1][1] + ctx->sprite_delta[1][0] * s->mb_x * 8 +
213
0
         ctx->sprite_delta[1][1] * s->mb_y * 8;
214
215
0
    ptr = ref_picture[1];
216
0
    ctx->mdsp.gmc(dest_cb, ptr, uvlinesize, 8,
217
0
                  ox, oy,
218
0
                  ctx->sprite_delta[0][0], ctx->sprite_delta[0][1],
219
0
                  ctx->sprite_delta[1][0], ctx->sprite_delta[1][1],
220
0
                  a + 1, (1 << (2 * a + 1)) - s->no_rounding,
221
0
                  (s->h_edge_pos + 1) >> 1, (s->v_edge_pos + 1) >> 1);
222
223
0
    ptr = ref_picture[2];
224
0
    ctx->mdsp.gmc(dest_cr, ptr, uvlinesize, 8,
225
0
                  ox, oy,
226
0
                  ctx->sprite_delta[0][0], ctx->sprite_delta[0][1],
227
0
                  ctx->sprite_delta[1][0], ctx->sprite_delta[1][1],
228
0
                  a + 1, (1 << (2 * a + 1)) - s->no_rounding,
229
0
                  (s->h_edge_pos + 1) >> 1, (s->v_edge_pos + 1) >> 1);
230
0
}
231
232
void ff_mpeg4_mcsel_motion(MpegEncContext *s,
233
                           uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
234
                           uint8_t *const *ref_picture)
235
0
{
236
0
    const Mpeg4DecContext *const ctx = (Mpeg4DecContext*)s;
237
238
0
    if (ctx->real_sprite_warping_points == 1) {
239
0
        gmc1_motion(s, ctx, dest_y, dest_cb, dest_cr,
240
0
                    ref_picture);
241
0
    } else {
242
0
        gmc_motion(s, ctx, dest_y, dest_cb, dest_cr,
243
0
                    ref_picture);
244
0
    }
245
0
}
246
247
void ff_mpeg4_decode_studio(MpegEncContext *s, uint8_t *dest_y, uint8_t *dest_cb,
248
                            uint8_t *dest_cr, int block_size, int uvlinesize,
249
                            int dct_linesize, int dct_offset)
250
0
{
251
0
    Mpeg4DecContext *const ctx = (Mpeg4DecContext*)s;
252
0
    const int act_block_size = block_size * 2;
253
254
0
    if (ctx->dpcm_direction == 0) {
255
0
        s->idsp.idct_put(dest_y,                               dct_linesize, (int16_t*)ctx->block32[0]);
256
0
        s->idsp.idct_put(dest_y              + act_block_size, dct_linesize, (int16_t*)ctx->block32[1]);
257
0
        s->idsp.idct_put(dest_y + dct_offset,                  dct_linesize, (int16_t*)ctx->block32[2]);
258
0
        s->idsp.idct_put(dest_y + dct_offset + act_block_size, dct_linesize, (int16_t*)ctx->block32[3]);
259
260
0
        dct_linesize = uvlinesize << s->interlaced_dct;
261
0
        dct_offset   = s->interlaced_dct ? uvlinesize : uvlinesize*block_size;
262
263
0
        s->idsp.idct_put(dest_cb,              dct_linesize, (int16_t*)ctx->block32[4]);
264
0
        s->idsp.idct_put(dest_cr,              dct_linesize, (int16_t*)ctx->block32[5]);
265
0
        s->idsp.idct_put(dest_cb + dct_offset, dct_linesize, (int16_t*)ctx->block32[6]);
266
0
        s->idsp.idct_put(dest_cr + dct_offset, dct_linesize, (int16_t*)ctx->block32[7]);
267
0
        if (!s->chroma_x_shift){ //Chroma444
268
0
            s->idsp.idct_put(dest_cb + act_block_size,              dct_linesize, (int16_t*)ctx->block32[8]);
269
0
            s->idsp.idct_put(dest_cr + act_block_size,              dct_linesize, (int16_t*)ctx->block32[9]);
270
0
            s->idsp.idct_put(dest_cb + act_block_size + dct_offset, dct_linesize, (int16_t*)ctx->block32[10]);
271
0
            s->idsp.idct_put(dest_cr + act_block_size + dct_offset, dct_linesize, (int16_t*)ctx->block32[11]);
272
0
        }
273
0
    } else if (ctx->dpcm_direction == 1) {
274
0
        uint16_t *dest_pcm[3] = {(uint16_t*)dest_y, (uint16_t*)dest_cb, (uint16_t*)dest_cr};
275
0
        int linesize[3] = {dct_linesize, uvlinesize, uvlinesize};
276
0
        for (int i = 0; i < 3; i++) {
277
0
            const uint16_t *src = ctx->dpcm_macroblock[i];
278
0
            int vsub = i ? s->chroma_y_shift : 0;
279
0
            int hsub = i ? s->chroma_x_shift : 0;
280
0
            int lowres = s->avctx->lowres;
281
0
            int step = 1 << lowres;
282
0
            for (int h = 0; h < (16 >> (vsub + lowres)); h++){
283
0
                for (int w = 0, idx = 0; w < (16 >> (hsub + lowres)); w++, idx += step)
284
0
                    dest_pcm[i][w] = src[idx];
285
0
                dest_pcm[i] += linesize[i] / 2;
286
0
                src         += (16 >> hsub) * step;
287
0
            }
288
0
        }
289
0
    } else {
290
0
        uint16_t *dest_pcm[3] = {(uint16_t*)dest_y, (uint16_t*)dest_cb, (uint16_t*)dest_cr};
291
0
        int linesize[3] = {dct_linesize, uvlinesize, uvlinesize};
292
0
        av_assert2(ctx->dpcm_direction == -1);
293
0
        for (int i = 0; i < 3; i++) {
294
0
            const uint16_t *src = ctx->dpcm_macroblock[i];
295
0
            int vsub = i ? s->chroma_y_shift : 0;
296
0
            int hsub = i ? s->chroma_x_shift : 0;
297
0
            int lowres = s->avctx->lowres;
298
0
            int step = 1 << lowres;
299
0
            dest_pcm[i] += (linesize[i] / 2) * ((16 >> vsub + lowres) - 1);
300
0
            for (int h = (16 >> (vsub + lowres)) - 1; h >= 0; h--){
301
0
                for (int w = (16 >> (hsub + lowres)) - 1, idx = 0; w >= 0; w--, idx += step)
302
0
                    dest_pcm[i][w] = src[idx];
303
0
                src += step * (16 >> hsub);
304
0
                dest_pcm[i] -= linesize[i] / 2;
305
0
            }
306
0
        }
307
0
    }
308
0
}
309
310
/**
311
 * Predict the ac.
312
 * @param n block index (0-3 are luma, 4-5 are chroma)
313
 * @param dir the ac prediction direction
314
 */
315
void ff_mpeg4_pred_ac(MpegEncContext *s, int16_t *block, int n, int dir)
316
1.86M
{
317
1.86M
    int i;
318
1.86M
    int16_t *ac_val, *ac_val1;
319
1.86M
    int8_t *const qscale_table = s->cur_pic.qscale_table;
320
321
    /* find prediction */
322
1.86M
    ac_val  = &s->ac_val[0][0][0] + s->block_index[n] * 16;
323
1.86M
    ac_val1 = ac_val;
324
1.86M
    if (s->ac_pred) {
325
0
        if (dir == 0) {
326
0
            const int xy = s->mb_x - 1 + s->mb_y * s->mb_stride;
327
            /* left prediction */
328
0
            ac_val -= 16;
329
330
0
            if (s->mb_x == 0 || s->qscale == qscale_table[xy] ||
331
0
                n == 1 || n == 3) {
332
                /* same qscale */
333
0
                for (i = 1; i < 8; i++)
334
0
                    block[s->idsp.idct_permutation[i << 3]] += ac_val[i];
335
0
            } else {
336
                /* different qscale, we must rescale */
337
0
                for (i = 1; i < 8; i++)
338
0
                    block[s->idsp.idct_permutation[i << 3]] += ROUNDED_DIV(ac_val[i] * qscale_table[xy], s->qscale);
339
0
            }
340
0
        } else {
341
0
            const int xy = s->mb_x + s->mb_y * s->mb_stride - s->mb_stride;
342
            /* top prediction */
343
0
            ac_val -= 16 * s->block_wrap[n];
344
345
0
            if (s->mb_y == 0 || s->qscale == qscale_table[xy] ||
346
0
                n == 2 || n == 3) {
347
                /* same qscale */
348
0
                for (i = 1; i < 8; i++)
349
0
                    block[s->idsp.idct_permutation[i]] += ac_val[i + 8];
350
0
            } else {
351
                /* different qscale, we must rescale */
352
0
                for (i = 1; i < 8; i++)
353
0
                    block[s->idsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8] * qscale_table[xy], s->qscale);
354
0
            }
355
0
        }
356
0
    }
357
    /* left copy */
358
14.9M
    for (i = 1; i < 8; i++)
359
13.0M
        ac_val1[i] = block[s->idsp.idct_permutation[i << 3]];
360
361
    /* top copy */
362
14.9M
    for (i = 1; i < 8; i++)
363
13.0M
        ac_val1[8 + i] = block[s->idsp.idct_permutation[i]];
364
1.86M
}
365
366
/**
367
 * check if the next stuff is a resync marker or the end.
368
 * @return 0 if not
369
 */
370
static inline int mpeg4_is_resync(Mpeg4DecContext *ctx)
371
0
{
372
0
    MpegEncContext *s = &ctx->m;
373
0
    int bits_count = get_bits_count(&s->gb);
374
0
    int v          = show_bits(&s->gb, 16);
375
376
0
    if (s->workaround_bugs & FF_BUG_NO_PADDING && !ctx->resync_marker)
377
0
        return 0;
378
379
0
    while (v <= 0xFF) {
380
0
        if (s->pict_type == AV_PICTURE_TYPE_B ||
381
0
            (v >> (8 - s->pict_type) != 1) || s->partitioned_frame)
382
0
            break;
383
0
        skip_bits(&s->gb, 8 + s->pict_type);
384
0
        bits_count += 8 + s->pict_type;
385
0
        v = show_bits(&s->gb, 16);
386
0
    }
387
388
0
    if (bits_count + 8 >= s->gb.size_in_bits) {
389
0
        v >>= 8;
390
0
        v  |= 0x7F >> (7 - (bits_count & 7));
391
392
0
        if (v == 0x7F)
393
0
            return s->mb_num;
394
0
    } else {
395
0
        static const uint16_t mpeg4_resync_prefix[8] = {
396
0
            0x7F00, 0x7E00, 0x7C00, 0x7800, 0x7000, 0x6000, 0x4000, 0x0000
397
0
        };
398
399
0
        if (v == mpeg4_resync_prefix[bits_count & 7]) {
400
0
            int len, mb_num;
401
0
            int mb_num_bits = av_log2(s->mb_num - 1) + 1;
402
0
            GetBitContext gb = s->gb;
403
404
0
            skip_bits(&s->gb, 1);
405
0
            align_get_bits(&s->gb);
406
407
0
            for (len = 0; len < 32; len++)
408
0
                if (get_bits1(&s->gb))
409
0
                    break;
410
411
0
            mb_num = get_bits(&s->gb, mb_num_bits);
412
0
            if (!mb_num || mb_num > s->mb_num || get_bits_count(&s->gb)+6 > s->gb.size_in_bits)
413
0
                mb_num= -1;
414
415
0
            s->gb = gb;
416
417
0
            if (len >= ff_mpeg4_get_video_packet_prefix_length(s))
418
0
                return mb_num;
419
0
        }
420
0
    }
421
0
    return 0;
422
0
}
423
424
static int mpeg4_decode_sprite_trajectory(Mpeg4DecContext *ctx, GetBitContext *gb)
425
0
{
426
0
    MpegEncContext *s = &ctx->m;
427
0
    int a     = 2 << ctx->sprite_warping_accuracy;
428
0
    int rho   = 3  - ctx->sprite_warping_accuracy;
429
0
    int r     = 16 / a;
430
0
    int alpha = 1;
431
0
    int beta  = 0;
432
0
    int w     = s->width;
433
0
    int h     = s->height;
434
0
    int min_ab, i, w2, h2, w3, h3;
435
0
    int sprite_ref[4][2];
436
0
    int virtual_ref[2][2];
437
0
    int64_t sprite_offset[2][2];
438
0
    int64_t sprite_delta[2][2];
439
440
    // only true for rectangle shapes
441
0
    const int vop_ref[4][2] = { { 0, 0 },         { s->width, 0 },
442
0
                                { 0, s->height }, { s->width, s->height } };
443
0
    int d[4][2]             = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } };
444
445
0
    if (w <= 0 || h <= 0)
446
0
        return AVERROR_INVALIDDATA;
447
448
0
    for (i = 0; i < ctx->num_sprite_warping_points; i++) {
449
0
        int length;
450
0
        int x = 0, y = 0;
451
452
0
        length = get_vlc2(gb, sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 2);
453
0
        if (length > 0)
454
0
            x = get_xbits(gb, length);
455
456
0
        if (!(ctx->divx_version == 500 && ctx->divx_build == 413))
457
0
            check_marker(s->avctx, gb, "before sprite_trajectory");
458
459
0
        length = get_vlc2(gb, sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 2);
460
0
        if (length > 0)
461
0
            y = get_xbits(gb, length);
462
463
0
        check_marker(s->avctx, gb, "after sprite_trajectory");
464
0
        ctx->sprite_traj[i][0] = d[i][0] = x;
465
0
        ctx->sprite_traj[i][1] = d[i][1] = y;
466
0
    }
467
0
    for (; i < 4; i++)
468
0
        ctx->sprite_traj[i][0] = ctx->sprite_traj[i][1] = 0;
469
470
0
    while ((1 << alpha) < w)
471
0
        alpha++;
472
0
    while ((1 << beta) < h)
473
0
        beta++;  /* typo in the MPEG-4 std for the definition of w' and h' */
474
0
    w2 = 1 << alpha;
475
0
    h2 = 1 << beta;
476
477
    // Note, the 4th point isn't used for GMC
478
0
    if (ctx->divx_version == 500 && ctx->divx_build == 413) {
479
0
        sprite_ref[0][0] = a * vop_ref[0][0] + d[0][0];
480
0
        sprite_ref[0][1] = a * vop_ref[0][1] + d[0][1];
481
0
        sprite_ref[1][0] = a * vop_ref[1][0] + d[0][0] + d[1][0];
482
0
        sprite_ref[1][1] = a * vop_ref[1][1] + d[0][1] + d[1][1];
483
0
        sprite_ref[2][0] = a * vop_ref[2][0] + d[0][0] + d[2][0];
484
0
        sprite_ref[2][1] = a * vop_ref[2][1] + d[0][1] + d[2][1];
485
0
    } else {
486
0
        sprite_ref[0][0] = (a >> 1) * (2 * vop_ref[0][0] + d[0][0]);
487
0
        sprite_ref[0][1] = (a >> 1) * (2 * vop_ref[0][1] + d[0][1]);
488
0
        sprite_ref[1][0] = (a >> 1) * (2 * vop_ref[1][0] + d[0][0] + d[1][0]);
489
0
        sprite_ref[1][1] = (a >> 1) * (2 * vop_ref[1][1] + d[0][1] + d[1][1]);
490
0
        sprite_ref[2][0] = (a >> 1) * (2 * vop_ref[2][0] + d[0][0] + d[2][0]);
491
0
        sprite_ref[2][1] = (a >> 1) * (2 * vop_ref[2][1] + d[0][1] + d[2][1]);
492
0
    }
493
    /* sprite_ref[3][0] = (a >> 1) * (2 * vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);
494
     * sprite_ref[3][1] = (a >> 1) * (2 * vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */
495
496
    /* This is mostly identical to the MPEG-4 std (and is totally unreadable
497
     * because of that...). Perhaps it should be reordered to be more readable.
498
     * The idea behind this virtual_ref mess is to be able to use shifts later
499
     * per pixel instead of divides so the distance between points is converted
500
     * from w&h based to w2&h2 based which are of the 2^x form. */
501
0
    virtual_ref[0][0] = 16 * (vop_ref[0][0] + w2) +
502
0
                         ROUNDED_DIV(((w - w2) *
503
0
                                           (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) +
504
0
                                      w2 * (r * sprite_ref[1][0] - 16LL * vop_ref[1][0])), w);
505
0
    virtual_ref[0][1] = 16 * vop_ref[0][1] +
506
0
                        ROUNDED_DIV(((w - w2) *
507
0
                                          (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) +
508
0
                                     w2 * (r * sprite_ref[1][1] - 16LL * vop_ref[1][1])), w);
509
0
    virtual_ref[1][0] = 16 * vop_ref[0][0] +
510
0
                        ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) +
511
0
                                           h2 * (r * sprite_ref[2][0] - 16LL * vop_ref[2][0])), h);
512
0
    virtual_ref[1][1] = 16 * (vop_ref[0][1] + h2) +
513
0
                        ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) +
514
0
                                           h2 * (r * sprite_ref[2][1] - 16LL * vop_ref[2][1])), h);
515
516
0
    switch (ctx->num_sprite_warping_points) {
517
0
    case 0:
518
0
        sprite_offset[0][0]    =
519
0
        sprite_offset[0][1]    =
520
0
        sprite_offset[1][0]    =
521
0
        sprite_offset[1][1]    = 0;
522
0
        sprite_delta[0][0]     = a;
523
0
        sprite_delta[0][1]     =
524
0
        sprite_delta[1][0]     = 0;
525
0
        sprite_delta[1][1]     = a;
526
0
        ctx->sprite_shift[0]   =
527
0
        ctx->sprite_shift[1]   = 0;
528
0
        break;
529
0
    case 1:     // GMC only
530
0
        sprite_offset[0][0]    = sprite_ref[0][0] - a * vop_ref[0][0];
531
0
        sprite_offset[0][1]    = sprite_ref[0][1] - a * vop_ref[0][1];
532
0
        sprite_offset[1][0]    = ((sprite_ref[0][0] >> 1) | (sprite_ref[0][0] & 1)) -
533
0
                                 a * (vop_ref[0][0] / 2);
534
0
        sprite_offset[1][1]    = ((sprite_ref[0][1] >> 1) | (sprite_ref[0][1] & 1)) -
535
0
                                 a * (vop_ref[0][1] / 2);
536
0
        sprite_delta[0][0]     = a;
537
0
        sprite_delta[0][1]     =
538
0
        sprite_delta[1][0]     = 0;
539
0
        sprite_delta[1][1]     = a;
540
0
        ctx->sprite_shift[0]   =
541
0
        ctx->sprite_shift[1]   = 0;
542
0
        break;
543
0
    case 2:
544
0
        sprite_offset[0][0]    = ((int64_t)      sprite_ref[0][0] * (1 << alpha + rho)) +
545
0
                                 ((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) *
546
0
                                 ((int64_t)        -vop_ref[0][0]) +
547
0
                                 ((int64_t)  r * sprite_ref[0][1] - virtual_ref[0][1]) *
548
0
                                 ((int64_t)        -vop_ref[0][1]) + (1 << (alpha + rho - 1));
549
0
        sprite_offset[0][1]    = ((int64_t)      sprite_ref[0][1] * (1 << alpha + rho)) +
550
0
                                 ((int64_t) -r * sprite_ref[0][1] + virtual_ref[0][1]) *
551
0
                                 ((int64_t)        -vop_ref[0][0]) +
552
0
                                 ((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) *
553
0
                                 ((int64_t)        -vop_ref[0][1]) + (1 << (alpha + rho - 1));
554
0
        sprite_offset[1][0]    = (((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) *
555
0
                                  ((int64_t)-2 *    vop_ref[0][0] + 1) +
556
0
                                  ((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) *
557
0
                                  ((int64_t)-2 *    vop_ref[0][1] + 1) + 2 * w2 * r *
558
0
                                   (int64_t)     sprite_ref[0][0] - 16 * w2 + (1 << (alpha + rho + 1)));
559
0
        sprite_offset[1][1]    = (((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) *
560
0
                                  ((int64_t)-2 *    vop_ref[0][0] + 1) +
561
0
                                  ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) *
562
0
                                  ((int64_t)-2 *    vop_ref[0][1] + 1) + 2 * w2 * r *
563
0
                                  (int64_t)      sprite_ref[0][1] - 16 * w2 + (1 << (alpha + rho + 1)));
564
0
        sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]);
565
0
        sprite_delta[0][1] = (+r * sprite_ref[0][1] - virtual_ref[0][1]);
566
0
        sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]);
567
0
        sprite_delta[1][1] = (-r * sprite_ref[0][0] + virtual_ref[0][0]);
568
569
0
        ctx->sprite_shift[0]  = alpha + rho;
570
0
        ctx->sprite_shift[1]  = alpha + rho + 2;
571
0
        break;
572
0
    case 3:
573
0
        min_ab = FFMIN(alpha, beta);
574
0
        w3     = w2 >> min_ab;
575
0
        h3     = h2 >> min_ab;
576
0
        sprite_offset[0][0]    = ((int64_t)sprite_ref[0][0] * (1 << (alpha + beta + rho - min_ab))) +
577
0
                                 ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-vop_ref[0][0]) +
578
0
                                 ((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-vop_ref[0][1]) +
579
0
                                 ((int64_t)1 << (alpha + beta + rho - min_ab - 1));
580
0
        sprite_offset[0][1]    = ((int64_t)sprite_ref[0][1] * (1 << (alpha + beta + rho - min_ab))) +
581
0
                                 ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-vop_ref[0][0]) +
582
0
                                 ((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-vop_ref[0][1]) +
583
0
                                 ((int64_t)1 << (alpha + beta + rho - min_ab - 1));
584
0
        sprite_offset[1][0]    = ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-2 * vop_ref[0][0] + 1) +
585
0
                                 ((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-2 * vop_ref[0][1] + 1) +
586
0
                                  (int64_t)2 * w2 * h3 * r * sprite_ref[0][0] - 16 * w2 * h3 +
587
0
                                 ((int64_t)1 << (alpha + beta + rho - min_ab + 1));
588
0
        sprite_offset[1][1]    = ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-2 * vop_ref[0][0] + 1) +
589
0
                                 ((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-2 * vop_ref[0][1] + 1) +
590
0
                                  (int64_t)2 * w2 * h3 * r * sprite_ref[0][1] - 16 * w2 * h3 +
591
0
                                 ((int64_t)1 << (alpha + beta + rho - min_ab + 1));
592
0
        sprite_delta[0][0] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[0][0]) * h3;
593
0
        sprite_delta[0][1] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[1][0]) * w3;
594
0
        sprite_delta[1][0] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[0][1]) * h3;
595
0
        sprite_delta[1][1] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[1][1]) * w3;
596
597
0
        ctx->sprite_shift[0]  = alpha + beta + rho - min_ab;
598
0
        ctx->sprite_shift[1]  = alpha + beta + rho - min_ab + 2;
599
0
        break;
600
0
    default:
601
0
        av_assert0(0);
602
0
    }
603
    /* try to simplify the situation */
604
0
    if (sprite_delta[0][0] == a << ctx->sprite_shift[0] &&
605
0
        sprite_delta[0][1] == 0 &&
606
0
        sprite_delta[1][0] == 0 &&
607
0
        sprite_delta[1][1] == a << ctx->sprite_shift[0]) {
608
0
        sprite_offset[0][0] >>= ctx->sprite_shift[0];
609
0
        sprite_offset[0][1] >>= ctx->sprite_shift[0];
610
0
        sprite_offset[1][0] >>= ctx->sprite_shift[1];
611
0
        sprite_offset[1][1] >>= ctx->sprite_shift[1];
612
0
        sprite_delta[0][0] = a;
613
0
        sprite_delta[0][1] = 0;
614
0
        sprite_delta[1][0] = 0;
615
0
        sprite_delta[1][1] = a;
616
0
        ctx->sprite_shift[0] = 0;
617
0
        ctx->sprite_shift[1] = 0;
618
0
        ctx->real_sprite_warping_points = 1;
619
0
    } else {
620
0
        int shift_y = 16 - ctx->sprite_shift[0];
621
0
        int shift_c = 16 - ctx->sprite_shift[1];
622
623
0
        for (i = 0; i < 2; i++) {
624
0
            if (shift_c < 0 || shift_y < 0 ||
625
0
                FFABS(  sprite_offset[0][i]) >= INT_MAX >> shift_y  ||
626
0
                FFABS(  sprite_offset[1][i]) >= INT_MAX >> shift_c  ||
627
0
                FFABS(   sprite_delta[0][i]) >= INT_MAX >> shift_y  ||
628
0
                FFABS(   sprite_delta[1][i]) >= INT_MAX >> shift_y
629
0
            ) {
630
0
                avpriv_request_sample(s->avctx, "Too large sprite shift, delta or offset");
631
0
                goto overflow;
632
0
            }
633
0
        }
634
635
0
        for (i = 0; i < 2; i++) {
636
0
            sprite_offset[0][i]    *= 1 << shift_y;
637
0
            sprite_offset[1][i]    *= 1 << shift_c;
638
0
            sprite_delta[0][i]     *= 1 << shift_y;
639
0
            sprite_delta[1][i]     *= 1 << shift_y;
640
0
            ctx->sprite_shift[i]     = 16;
641
642
0
        }
643
0
        for (i = 0; i < 2; i++) {
644
0
            int64_t sd[2] = {
645
0
                sprite_delta[i][0] - a * (1LL<<16),
646
0
                sprite_delta[i][1] - a * (1LL<<16)
647
0
            };
648
649
0
            if (llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL)) >= INT_MAX ||
650
0
                llabs(sprite_offset[0][i] + sprite_delta[i][1] * (h+16LL)) >= INT_MAX ||
651
0
                llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL) + sprite_delta[i][1] * (h+16LL)) >= INT_MAX ||
652
0
                llabs(sprite_delta[i][0] * (w+16LL)) >= INT_MAX ||
653
0
                llabs(sprite_delta[i][1] * (h+16LL)) >= INT_MAX ||
654
0
                llabs(sd[0]) >= INT_MAX ||
655
0
                llabs(sd[1]) >= INT_MAX ||
656
0
                llabs(sprite_offset[0][i] + sd[0] * (w+16LL)) >= INT_MAX ||
657
0
                llabs(sprite_offset[0][i] + sd[1] * (h+16LL)) >= INT_MAX ||
658
0
                llabs(sprite_offset[0][i] + sd[0] * (w+16LL) + sd[1] * (h+16LL)) >= INT_MAX
659
0
            ) {
660
0
                avpriv_request_sample(s->avctx, "Overflow on sprite points");
661
0
                goto overflow;
662
0
            }
663
0
        }
664
0
        ctx->real_sprite_warping_points = ctx->num_sprite_warping_points;
665
0
    }
666
667
0
    for (i = 0; i < 4; i++) {
668
0
        ctx->sprite_offset[i&1][i>>1] = sprite_offset[i&1][i>>1];
669
0
        ctx->sprite_delta [i&1][i>>1] = sprite_delta [i&1][i>>1];
670
0
    }
671
672
0
    return 0;
673
0
overflow:
674
0
    memset(ctx->sprite_offset, 0, sizeof(ctx->sprite_offset));
675
0
    memset(ctx->sprite_delta,  0, sizeof(ctx->sprite_delta));
676
0
    return AVERROR_PATCHWELCOME;
677
0
}
678
679
2.44k
static int decode_new_pred(Mpeg4DecContext *ctx, GetBitContext *gb) {
680
2.44k
    MpegEncContext *s = &ctx->m;
681
2.44k
    int len = FFMIN(ctx->time_increment_bits + 3, 15);
682
683
2.44k
    get_bits(gb, len);
684
2.44k
    if (get_bits1(gb))
685
168
        get_bits(gb, len);
686
2.44k
    check_marker(s->avctx, gb, "after new_pred");
687
688
2.44k
    return 0;
689
2.44k
}
690
691
/**
692
 * Decode the next video packet.
693
 * @return <0 if something went wrong
694
 */
695
int ff_mpeg4_decode_video_packet_header(Mpeg4DecContext *ctx)
696
0
{
697
0
    MpegEncContext *s = &ctx->m;
698
699
0
    int mb_num_bits      = av_log2(s->mb_num - 1) + 1;
700
0
    int header_extension = 0, mb_num, len;
701
702
    /* is there enough space left for a video packet + header */
703
0
    if (get_bits_count(&s->gb) > s->gb.size_in_bits - 20)
704
0
        return AVERROR_INVALIDDATA;
705
706
0
    for (len = 0; len < 32; len++)
707
0
        if (get_bits1(&s->gb))
708
0
            break;
709
710
0
    if (len != ff_mpeg4_get_video_packet_prefix_length(s)) {
711
0
        av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n");
712
0
        return AVERROR_INVALIDDATA;
713
0
    }
714
715
0
    if (ctx->shape != RECT_SHAPE) {
716
0
        header_extension = get_bits1(&s->gb);
717
        // FIXME more stuff here
718
0
    }
719
720
0
    mb_num = get_bits(&s->gb, mb_num_bits);
721
0
    if (mb_num >= s->mb_num || !mb_num) {
722
0
        av_log(s->avctx, AV_LOG_ERROR,
723
0
               "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
724
0
        return AVERROR_INVALIDDATA;
725
0
    }
726
727
0
    s->mb_x = mb_num % s->mb_width;
728
0
    s->mb_y = mb_num / s->mb_width;
729
730
0
    if (ctx->shape != BIN_ONLY_SHAPE) {
731
0
        int qscale = get_bits(&s->gb, ctx->quant_precision);
732
0
        if (qscale)
733
0
            s->chroma_qscale = s->qscale = qscale;
734
0
    }
735
736
0
    if (ctx->shape == RECT_SHAPE)
737
0
        header_extension = get_bits1(&s->gb);
738
739
0
    if (header_extension) {
740
0
        while (get_bits1(&s->gb) != 0)
741
0
            ;
742
743
0
        check_marker(s->avctx, &s->gb, "before time_increment in video packed header");
744
0
        skip_bits(&s->gb, ctx->time_increment_bits);      /* time_increment */
745
0
        check_marker(s->avctx, &s->gb, "before vop_coding_type in video packed header");
746
747
0
        skip_bits(&s->gb, 2); /* vop coding type */
748
        // FIXME not rect stuff here
749
750
0
        if (ctx->shape != BIN_ONLY_SHAPE) {
751
0
            skip_bits(&s->gb, 3); /* intra dc vlc threshold */
752
            // FIXME don't just ignore everything
753
0
            if (s->pict_type == AV_PICTURE_TYPE_S &&
754
0
                ctx->vol_sprite_usage == GMC_SPRITE) {
755
0
                if (mpeg4_decode_sprite_trajectory(ctx, &s->gb) < 0)
756
0
                    return AVERROR_INVALIDDATA;
757
0
                av_log(s->avctx, AV_LOG_ERROR, "untested\n");
758
0
            }
759
760
            // FIXME reduced res stuff here
761
762
0
            if (s->pict_type != AV_PICTURE_TYPE_I) {
763
0
                int f_code = get_bits(&s->gb, 3);       /* fcode_for */
764
0
                if (f_code == 0)
765
0
                    av_log(s->avctx, AV_LOG_ERROR,
766
0
                           "Error, video packet header damaged (f_code=0)\n");
767
0
            }
768
0
            if (s->pict_type == AV_PICTURE_TYPE_B) {
769
0
                int b_code = get_bits(&s->gb, 3);
770
0
                if (b_code == 0)
771
0
                    av_log(s->avctx, AV_LOG_ERROR,
772
0
                           "Error, video packet header damaged (b_code=0)\n");
773
0
            }
774
0
        }
775
0
    }
776
0
    if (ctx->new_pred)
777
0
        decode_new_pred(ctx, &s->gb);
778
779
0
    return 0;
780
0
}
781
782
static void reset_studio_dc_predictors(MpegEncContext *s)
783
1.09k
{
784
    /* Reset DC Predictors */
785
1.09k
    s->last_dc[0] =
786
1.09k
    s->last_dc[1] =
787
1.09k
    s->last_dc[2] = 1 << (s->avctx->bits_per_raw_sample + s->dct_precision + s->intra_dc_precision - 1);
788
1.09k
}
789
790
/**
791
 * Decode the next video packet.
792
 * @return <0 if something went wrong
793
 */
794
int ff_mpeg4_decode_studio_slice_header(Mpeg4DecContext *ctx)
795
0
{
796
0
    MpegEncContext *s = &ctx->m;
797
0
    GetBitContext *gb = &s->gb;
798
0
    unsigned vlc_len;
799
0
    uint16_t mb_num;
800
801
0
    if (get_bits_left(gb) >= 32 && get_bits_long(gb, 32) == SLICE_STARTCODE) {
802
0
        vlc_len = av_log2(s->mb_width * s->mb_height) + 1;
803
0
        mb_num = get_bits(gb, vlc_len);
804
805
0
        if (mb_num >= s->mb_num)
806
0
            return AVERROR_INVALIDDATA;
807
808
0
        s->mb_x = mb_num % s->mb_width;
809
0
        s->mb_y = mb_num / s->mb_width;
810
811
0
        if (ctx->shape != BIN_ONLY_SHAPE)
812
0
            s->qscale = mpeg_get_qscale(s);
813
814
0
        if (get_bits1(gb)) {  /* slice_extension_flag */
815
0
            skip_bits1(gb);   /* intra_slice */
816
0
            skip_bits1(gb);   /* slice_VOP_id_enable */
817
0
            skip_bits(gb, 6); /* slice_VOP_id */
818
0
            while (get_bits1(gb)) /* extra_bit_slice */
819
0
                skip_bits(gb, 8); /* extra_information_slice */
820
0
        }
821
822
0
        reset_studio_dc_predictors(s);
823
0
    }
824
0
    else {
825
0
        return AVERROR_INVALIDDATA;
826
0
    }
827
828
0
    return 0;
829
0
}
830
831
/**
832
 * Get the average motion vector for a GMC MB.
833
 * @param n either 0 for the x component or 1 for y
834
 * @return the average MV for a GMC MB
835
 */
836
static inline int get_amv(Mpeg4DecContext *ctx, int n)
837
0
{
838
0
    MpegEncContext *s = &ctx->m;
839
0
    int x, y, mb_v, sum, dx, dy, shift;
840
0
    int len     = 1 << (s->f_code + 4);
841
0
    const int a = ctx->sprite_warping_accuracy;
842
843
0
    if (s->workaround_bugs & FF_BUG_AMV)
844
0
        len >>= s->quarter_sample;
845
846
0
    if (ctx->real_sprite_warping_points == 1) {
847
0
        if (ctx->divx_version == 500 && ctx->divx_build == 413 && a >= s->quarter_sample)
848
0
            sum = ctx->sprite_offset[0][n] / (1 << (a - s->quarter_sample));
849
0
        else
850
0
            sum = RSHIFT(ctx->sprite_offset[0][n] * (1 << s->quarter_sample), a);
851
0
    } else {
852
0
        dx    = ctx->sprite_delta[n][0];
853
0
        dy    = ctx->sprite_delta[n][1];
854
0
        shift = ctx->sprite_shift[0];
855
0
        if (n)
856
0
            dy -= 1 << (shift + a + 1);
857
0
        else
858
0
            dx -= 1 << (shift + a + 1);
859
0
        mb_v = ctx->sprite_offset[0][n] + dx * s->mb_x * 16U + dy * s->mb_y * 16U;
860
861
0
        sum = 0;
862
0
        for (y = 0; y < 16; y++) {
863
0
            int v;
864
865
0
            v = mb_v + (unsigned)dy * y;
866
            // FIXME optimize
867
0
            for (x = 0; x < 16; x++) {
868
0
                sum += v >> shift;
869
0
                v   += dx;
870
0
            }
871
0
        }
872
0
        sum = RSHIFT(sum, a + 8 - s->quarter_sample);
873
0
    }
874
875
0
    if (sum < -len)
876
0
        sum = -len;
877
0
    else if (sum >= len)
878
0
        sum = len - 1;
879
880
0
    return sum;
881
0
}
882
883
/**
884
 * Decode the dc value.
885
 * @param n block index (0-3 are luma, 4-5 are chroma)
886
 * @param dir_ptr the prediction direction will be stored here
887
 * @return the quantized dc
888
 */
889
static inline int mpeg4_decode_dc(MpegEncContext *s, int n, int *dir_ptr)
890
0
{
891
0
    int level, code;
892
893
0
    if (n < 4)
894
0
        code = get_vlc2(&s->gb, dc_lum, DC_VLC_BITS, 1);
895
0
    else
896
0
        code = get_vlc2(&s->gb, dc_chrom, DC_VLC_BITS, 1);
897
898
0
    if (code < 0) {
899
0
        av_log(s->avctx, AV_LOG_ERROR, "illegal dc vlc\n");
900
0
        return AVERROR_INVALIDDATA;
901
0
    }
902
903
0
    if (code == 0) {
904
0
        level = 0;
905
0
    } else {
906
0
        if (IS_3IV1) {
907
0
            if (code == 1)
908
0
                level = 2 * get_bits1(&s->gb) - 1;
909
0
            else {
910
0
                if (get_bits1(&s->gb))
911
0
                    level = get_bits(&s->gb, code - 1) + (1 << (code - 1));
912
0
                else
913
0
                    level = -get_bits(&s->gb, code - 1) - (1 << (code - 1));
914
0
            }
915
0
        } else {
916
0
            level = get_xbits(&s->gb, code);
917
0
        }
918
919
0
        if (code > 8) {
920
0
            if (get_bits1(&s->gb) == 0) { /* marker */
921
0
                if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT)) {
922
0
                    av_log(s->avctx, AV_LOG_ERROR, "dc marker bit missing\n");
923
0
                    return AVERROR_INVALIDDATA;
924
0
                }
925
0
            }
926
0
        }
927
0
    }
928
929
0
    return ff_mpeg4_pred_dc(s, n, level, dir_ptr, 0);
930
0
}
931
932
/**
933
 * Decode first partition.
934
 * @return number of MBs decoded or <0 if an error occurred
935
 */
936
static int mpeg4_decode_partition_a(Mpeg4DecContext *ctx)
937
0
{
938
0
    MpegEncContext *s = &ctx->m;
939
0
    int mb_num = 0;
940
0
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
941
942
    /* decode first partition */
943
0
    s->first_slice_line = 1;
944
0
    for (; s->mb_y < s->mb_height; s->mb_y++) {
945
0
        ff_init_block_index(s);
946
0
        for (; s->mb_x < s->mb_width; s->mb_x++) {
947
0
            const int xy = s->mb_x + s->mb_y * s->mb_stride;
948
0
            int cbpc;
949
0
            int dir = 0;
950
951
0
            mb_num++;
952
0
            ff_update_block_index(s, 8, s->avctx->lowres, 1);
953
0
            if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1)
954
0
                s->first_slice_line = 0;
955
956
0
            if (s->pict_type == AV_PICTURE_TYPE_I) {
957
0
                int i;
958
959
0
                do {
960
0
                    if (show_bits(&s->gb, 19) == DC_MARKER)
961
0
                        return mb_num - 1;
962
963
0
                    cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc, INTRA_MCBPC_VLC_BITS, 2);
964
0
                    if (cbpc < 0) {
965
0
                        av_log(s->avctx, AV_LOG_ERROR,
966
0
                               "mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
967
0
                        return AVERROR_INVALIDDATA;
968
0
                    }
969
0
                } while (cbpc == 8);
970
971
0
                s->cbp_table[xy]               = cbpc & 3;
972
0
                s->cur_pic.mb_type[xy] = MB_TYPE_INTRA;
973
0
                s->mb_intra                    = 1;
974
975
0
                if (cbpc & 4)
976
0
                    ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
977
978
0
                s->cur_pic.qscale_table[xy] = s->qscale;
979
980
0
                s->mbintra_table[xy] = 1;
981
0
                for (i = 0; i < 6; i++) {
982
0
                    int dc_pred_dir;
983
0
                    int dc = mpeg4_decode_dc(s, i, &dc_pred_dir);
984
0
                    if (dc < 0) {
985
0
                        av_log(s->avctx, AV_LOG_ERROR,
986
0
                               "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
987
0
                        return dc;
988
0
                    }
989
0
                    dir <<= 1;
990
0
                    if (dc_pred_dir)
991
0
                        dir |= 1;
992
0
                }
993
0
                s->pred_dir_table[xy] = dir;
994
0
            } else { /* P/S_TYPE */
995
0
                int mx, my, pred_x, pred_y, bits;
996
0
                int16_t *const mot_val = s->cur_pic.motion_val[0][s->block_index[0]];
997
0
                const int stride       = s->b8_stride * 2;
998
999
0
try_again:
1000
0
                bits = show_bits(&s->gb, 17);
1001
0
                if (bits == MOTION_MARKER)
1002
0
                    return mb_num - 1;
1003
1004
0
                skip_bits1(&s->gb);
1005
0
                if (bits & 0x10000) {
1006
                    /* skip mb */
1007
0
                    if (s->pict_type == AV_PICTURE_TYPE_S &&
1008
0
                        ctx->vol_sprite_usage == GMC_SPRITE) {
1009
0
                        s->cur_pic.mb_type[xy] = MB_TYPE_SKIP  |
1010
0
                                                         MB_TYPE_16x16 |
1011
0
                                                         MB_TYPE_GMC   |
1012
0
                                                         MB_TYPE_FORWARD_MV;
1013
0
                        mx = get_amv(ctx, 0);
1014
0
                        my = get_amv(ctx, 1);
1015
0
                    } else {
1016
0
                        s->cur_pic.mb_type[xy] = MB_TYPE_SKIP  |
1017
0
                                                         MB_TYPE_16x16 |
1018
0
                                                         MB_TYPE_FORWARD_MV;
1019
0
                        mx = my = 0;
1020
0
                    }
1021
0
                    mot_val[0]          =
1022
0
                    mot_val[2]          =
1023
0
                    mot_val[0 + stride] =
1024
0
                    mot_val[2 + stride] = mx;
1025
0
                    mot_val[1]          =
1026
0
                    mot_val[3]          =
1027
0
                    mot_val[1 + stride] =
1028
0
                    mot_val[3 + stride] = my;
1029
1030
0
                    if (s->mbintra_table[xy])
1031
0
                        ff_clean_intra_table_entries(s);
1032
0
                    continue;
1033
0
                }
1034
1035
0
                cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc, INTER_MCBPC_VLC_BITS, 2);
1036
0
                if (cbpc < 0) {
1037
0
                    av_log(s->avctx, AV_LOG_ERROR,
1038
0
                           "mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
1039
0
                    return AVERROR_INVALIDDATA;
1040
0
                }
1041
0
                if (cbpc == 20)
1042
0
                    goto try_again;
1043
1044
0
                s->cbp_table[xy] = cbpc & (8 + 3);  // 8 is dquant
1045
1046
0
                s->mb_intra = ((cbpc & 4) != 0);
1047
1048
0
                if (s->mb_intra) {
1049
0
                    s->cur_pic.mb_type[xy] = MB_TYPE_INTRA;
1050
0
                    s->mbintra_table[xy] = 1;
1051
0
                    mot_val[0]          =
1052
0
                    mot_val[2]          =
1053
0
                    mot_val[0 + stride] =
1054
0
                    mot_val[2 + stride] = 0;
1055
0
                    mot_val[1]          =
1056
0
                    mot_val[3]          =
1057
0
                    mot_val[1 + stride] =
1058
0
                    mot_val[3 + stride] = 0;
1059
0
                } else {
1060
0
                    if (s->mbintra_table[xy])
1061
0
                        ff_clean_intra_table_entries(s);
1062
1063
0
                    if (s->pict_type == AV_PICTURE_TYPE_S &&
1064
0
                        ctx->vol_sprite_usage == GMC_SPRITE &&
1065
0
                        (cbpc & 16) == 0)
1066
0
                        s->mcsel = get_bits1(&s->gb);
1067
0
                    else
1068
0
                        s->mcsel = 0;
1069
1070
0
                    if ((cbpc & 16) == 0) {
1071
                        /* 16x16 motion prediction */
1072
1073
0
                        ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1074
0
                        if (!s->mcsel) {
1075
0
                            mx = ff_h263_decode_motion(s, pred_x, s->f_code);
1076
0
                            if (mx >= 0xffff)
1077
0
                                return AVERROR_INVALIDDATA;
1078
1079
0
                            my = ff_h263_decode_motion(s, pred_y, s->f_code);
1080
0
                            if (my >= 0xffff)
1081
0
                                return AVERROR_INVALIDDATA;
1082
0
                            s->cur_pic.mb_type[xy] = MB_TYPE_16x16 |
1083
0
                                                             MB_TYPE_FORWARD_MV;
1084
0
                        } else {
1085
0
                            mx = get_amv(ctx, 0);
1086
0
                            my = get_amv(ctx, 1);
1087
0
                            s->cur_pic.mb_type[xy] = MB_TYPE_16x16 |
1088
0
                                                             MB_TYPE_GMC   |
1089
0
                                                             MB_TYPE_FORWARD_MV;
1090
0
                        }
1091
1092
0
                        mot_val[0]          =
1093
0
                        mot_val[2]          =
1094
0
                        mot_val[0 + stride] =
1095
0
                        mot_val[2 + stride] = mx;
1096
0
                        mot_val[1]          =
1097
0
                        mot_val[3]          =
1098
0
                        mot_val[1 + stride] =
1099
0
                        mot_val[3 + stride] = my;
1100
0
                    } else {
1101
0
                        int i;
1102
0
                        s->cur_pic.mb_type[xy] = MB_TYPE_8x8 |
1103
0
                                                         MB_TYPE_FORWARD_MV;
1104
0
                        for (i = 0; i < 4; i++) {
1105
0
                            int16_t *mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
1106
0
                            mx = ff_h263_decode_motion(s, pred_x, s->f_code);
1107
0
                            if (mx >= 0xffff)
1108
0
                                return AVERROR_INVALIDDATA;
1109
1110
0
                            my = ff_h263_decode_motion(s, pred_y, s->f_code);
1111
0
                            if (my >= 0xffff)
1112
0
                                return AVERROR_INVALIDDATA;
1113
0
                            mot_val[0] = mx;
1114
0
                            mot_val[1] = my;
1115
0
                        }
1116
0
                    }
1117
0
                }
1118
0
            }
1119
0
        }
1120
0
        s->mb_x = 0;
1121
0
    }
1122
1123
0
    return mb_num;
1124
0
}
1125
1126
/**
1127
 * decode second partition.
1128
 * @return <0 if an error occurred
1129
 */
1130
static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count)
1131
0
{
1132
0
    int mb_num = 0;
1133
0
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
1134
1135
0
    s->mb_x = s->resync_mb_x;
1136
0
    s->first_slice_line = 1;
1137
0
    for (s->mb_y = s->resync_mb_y; mb_num < mb_count; s->mb_y++) {
1138
0
        ff_init_block_index(s);
1139
0
        for (; mb_num < mb_count && s->mb_x < s->mb_width; s->mb_x++) {
1140
0
            const int xy = s->mb_x + s->mb_y * s->mb_stride;
1141
1142
0
            mb_num++;
1143
0
            ff_update_block_index(s, 8, s->avctx->lowres, 1);
1144
0
            if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1)
1145
0
                s->first_slice_line = 0;
1146
1147
0
            if (s->pict_type == AV_PICTURE_TYPE_I) {
1148
0
                int ac_pred = get_bits1(&s->gb);
1149
0
                int cbpy    = get_vlc2(&s->gb, ff_h263_cbpy_vlc, CBPY_VLC_BITS, 1);
1150
0
                if (cbpy < 0) {
1151
0
                    av_log(s->avctx, AV_LOG_ERROR,
1152
0
                           "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
1153
0
                    return AVERROR_INVALIDDATA;
1154
0
                }
1155
1156
0
                s->cbp_table[xy]               |= cbpy << 2;
1157
0
                s->cur_pic.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED;
1158
0
            } else { /* P || S_TYPE */
1159
0
                if (IS_INTRA(s->cur_pic.mb_type[xy])) {
1160
0
                    int i;
1161
0
                    int dir     = 0;
1162
0
                    int ac_pred = get_bits1(&s->gb);
1163
0
                    int cbpy    = get_vlc2(&s->gb, ff_h263_cbpy_vlc, CBPY_VLC_BITS, 1);
1164
1165
0
                    if (cbpy < 0) {
1166
0
                        av_log(s->avctx, AV_LOG_ERROR,
1167
0
                               "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
1168
0
                        return AVERROR_INVALIDDATA;
1169
0
                    }
1170
1171
0
                    if (s->cbp_table[xy] & 8)
1172
0
                        ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
1173
0
                    s->cur_pic.qscale_table[xy] = s->qscale;
1174
1175
0
                    for (i = 0; i < 6; i++) {
1176
0
                        int dc_pred_dir;
1177
0
                        int dc = mpeg4_decode_dc(s, i, &dc_pred_dir);
1178
0
                        if (dc < 0) {
1179
0
                            av_log(s->avctx, AV_LOG_ERROR,
1180
0
                                   "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
1181
0
                            return dc;
1182
0
                        }
1183
0
                        dir <<= 1;
1184
0
                        if (dc_pred_dir)
1185
0
                            dir |= 1;
1186
0
                    }
1187
0
                    s->cbp_table[xy]               &= 3;  // remove dquant
1188
0
                    s->cbp_table[xy]               |= cbpy << 2;
1189
0
                    s->cur_pic.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED;
1190
0
                    s->pred_dir_table[xy]           = dir;
1191
0
                } else if (IS_SKIP(s->cur_pic.mb_type[xy])) {
1192
0
                    s->cur_pic.qscale_table[xy] = s->qscale;
1193
0
                    s->cbp_table[xy]                    = 0;
1194
0
                } else {
1195
0
                    int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc, CBPY_VLC_BITS, 1);
1196
1197
0
                    if (cbpy < 0) {
1198
0
                        av_log(s->avctx, AV_LOG_ERROR,
1199
0
                               "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
1200
0
                        return AVERROR_INVALIDDATA;
1201
0
                    }
1202
1203
0
                    if (s->cbp_table[xy] & 8)
1204
0
                        ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
1205
0
                    s->cur_pic.qscale_table[xy] = s->qscale;
1206
1207
0
                    s->cbp_table[xy] &= 3;  // remove dquant
1208
0
                    s->cbp_table[xy] |= (cbpy ^ 0xf) << 2;
1209
0
                }
1210
0
            }
1211
0
        }
1212
0
        if (mb_num >= mb_count)
1213
0
            return 0;
1214
0
        s->mb_x = 0;
1215
0
    }
1216
0
    return 0;
1217
0
}
1218
1219
/**
1220
 * Decode the first and second partition.
1221
 * @return <0 if error (and sets error type in the error_status_table)
1222
 */
1223
int ff_mpeg4_decode_partitions(Mpeg4DecContext *ctx)
1224
0
{
1225
0
    MpegEncContext *s = &ctx->m;
1226
0
    int mb_num;
1227
0
    int ret;
1228
0
    const int part_a_error = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_ERROR | ER_MV_ERROR) : ER_MV_ERROR;
1229
0
    const int part_a_end   = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_END   | ER_MV_END)   : ER_MV_END;
1230
1231
0
    mb_num = mpeg4_decode_partition_a(ctx);
1232
0
    if (mb_num <= 0) {
1233
0
        ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
1234
0
                        s->mb_x, s->mb_y, part_a_error);
1235
0
        return mb_num ? mb_num : AVERROR_INVALIDDATA;
1236
0
    }
1237
1238
0
    if (s->resync_mb_x + s->resync_mb_y * s->mb_width + mb_num > s->mb_num) {
1239
0
        av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n");
1240
0
        ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
1241
0
                        s->mb_x, s->mb_y, part_a_error);
1242
0
        return AVERROR_INVALIDDATA;
1243
0
    }
1244
1245
0
    s->mb_num_left = mb_num;
1246
1247
0
    if (s->pict_type == AV_PICTURE_TYPE_I) {
1248
0
        while (show_bits(&s->gb, 9) == 1)
1249
0
            skip_bits(&s->gb, 9);
1250
0
        if (get_bits(&s->gb, 19) != DC_MARKER) {
1251
0
            av_log(s->avctx, AV_LOG_ERROR,
1252
0
                   "marker missing after first I partition at %d %d\n",
1253
0
                   s->mb_x, s->mb_y);
1254
0
            return AVERROR_INVALIDDATA;
1255
0
        }
1256
0
    } else {
1257
0
        while (show_bits(&s->gb, 10) == 1)
1258
0
            skip_bits(&s->gb, 10);
1259
0
        if (get_bits(&s->gb, 17) != MOTION_MARKER) {
1260
0
            av_log(s->avctx, AV_LOG_ERROR,
1261
0
                   "marker missing after first P partition at %d %d\n",
1262
0
                   s->mb_x, s->mb_y);
1263
0
            return AVERROR_INVALIDDATA;
1264
0
        }
1265
0
    }
1266
0
    ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
1267
0
                    s->mb_x - 1, s->mb_y, part_a_end);
1268
1269
0
    ret = mpeg4_decode_partition_b(s, mb_num);
1270
0
    if (ret < 0) {
1271
0
        if (s->pict_type == AV_PICTURE_TYPE_P)
1272
0
            ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
1273
0
                            s->mb_x, s->mb_y, ER_DC_ERROR);
1274
0
        return ret;
1275
0
    } else {
1276
0
        if (s->pict_type == AV_PICTURE_TYPE_P)
1277
0
            ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
1278
0
                            s->mb_x - 1, s->mb_y, ER_DC_END);
1279
0
    }
1280
1281
0
    return 0;
1282
0
}
1283
1284
/**
1285
 * Decode a block.
1286
 * @return <0 if an error occurred
1287
 */
1288
static inline int mpeg4_decode_block(Mpeg4DecContext *ctx, int16_t *block,
1289
                                     int n, int coded, int intra,
1290
                                     int use_intra_dc_vlc, int rvlc)
1291
0
{
1292
0
    MpegEncContext *s = &ctx->m;
1293
0
    int level, i, last, run, qmul, qadd;
1294
0
    int av_uninit(dc_pred_dir);
1295
0
    const RLTable *rl;
1296
0
    const RL_VLC_ELEM *rl_vlc;
1297
0
    const uint8_t *scan_table;
1298
1299
    // Note intra & rvlc should be optimized away if this is inlined
1300
1301
0
    if (intra) {
1302
0
        if (use_intra_dc_vlc) {
1303
            /* DC coef */
1304
0
            if (s->partitioned_frame) {
1305
0
                level = s->dc_val[0][s->block_index[n]];
1306
0
                if (n < 4)
1307
0
                    level = FASTDIV((level + (s->y_dc_scale >> 1)), s->y_dc_scale);
1308
0
                else
1309
0
                    level = FASTDIV((level + (s->c_dc_scale >> 1)), s->c_dc_scale);
1310
0
                dc_pred_dir = (s->pred_dir_table[s->mb_x + s->mb_y * s->mb_stride] << n) & 32;
1311
0
            } else {
1312
0
                level = mpeg4_decode_dc(s, n, &dc_pred_dir);
1313
0
                if (level < 0)
1314
0
                    return level;
1315
0
            }
1316
0
            block[0] = level;
1317
0
            i        = 0;
1318
0
        } else {
1319
0
            i = -1;
1320
0
            ff_mpeg4_pred_dc(s, n, 0, &dc_pred_dir, 0);
1321
0
        }
1322
0
        if (!coded)
1323
0
            goto not_coded;
1324
1325
0
        if (rvlc) {
1326
0
            rl     = &ff_rvlc_rl_intra;
1327
0
            rl_vlc = ff_rvlc_rl_intra.rl_vlc[0];
1328
0
        } else {
1329
0
            rl     = &ff_mpeg4_rl_intra;
1330
0
            rl_vlc = ff_mpeg4_rl_intra.rl_vlc[0];
1331
0
        }
1332
0
        if (s->ac_pred) {
1333
0
            if (dc_pred_dir == 0)
1334
0
                scan_table = s->permutated_intra_v_scantable;  /* left */
1335
0
            else
1336
0
                scan_table = s->permutated_intra_h_scantable;  /* top */
1337
0
        } else {
1338
0
            scan_table = s->intra_scantable.permutated;
1339
0
        }
1340
0
        qmul = 1;
1341
0
        qadd = 0;
1342
0
    } else {
1343
0
        i = -1;
1344
0
        if (!coded) {
1345
0
            s->block_last_index[n] = i;
1346
0
            return 0;
1347
0
        }
1348
0
        if (rvlc)
1349
0
            rl = &ff_rvlc_rl_inter;
1350
0
        else
1351
0
            rl = &ff_h263_rl_inter;
1352
1353
0
        scan_table = s->intra_scantable.permutated;
1354
1355
0
        if (s->mpeg_quant) {
1356
0
            qmul = 1;
1357
0
            qadd = 0;
1358
0
            if (rvlc)
1359
0
                rl_vlc = ff_rvlc_rl_inter.rl_vlc[0];
1360
0
            else
1361
0
                rl_vlc = ff_h263_rl_inter.rl_vlc[0];
1362
0
        } else {
1363
0
            qmul = s->qscale << 1;
1364
0
            qadd = (s->qscale - 1) | 1;
1365
0
            if (rvlc)
1366
0
                rl_vlc = ff_rvlc_rl_inter.rl_vlc[s->qscale];
1367
0
            else
1368
0
                rl_vlc = ff_h263_rl_inter.rl_vlc[s->qscale];
1369
0
        }
1370
0
    }
1371
0
    {
1372
0
        OPEN_READER(re, &s->gb);
1373
0
        for (;;) {
1374
0
            UPDATE_CACHE(re, &s->gb);
1375
0
            GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 0);
1376
0
            if (level == 0) {
1377
                /* escape */
1378
0
                if (rvlc) {
1379
0
                    if (SHOW_UBITS(re, &s->gb, 1) == 0) {
1380
0
                        av_log(s->avctx, AV_LOG_ERROR,
1381
0
                               "1. marker bit missing in rvlc esc\n");
1382
0
                        return AVERROR_INVALIDDATA;
1383
0
                    }
1384
0
                    SKIP_CACHE(re, &s->gb, 1);
1385
1386
0
                    last = SHOW_UBITS(re, &s->gb, 1);
1387
0
                    SKIP_CACHE(re, &s->gb, 1);
1388
0
                    run = SHOW_UBITS(re, &s->gb, 6);
1389
0
                    SKIP_COUNTER(re, &s->gb, 1 + 1 + 6);
1390
0
                    UPDATE_CACHE(re, &s->gb);
1391
1392
0
                    if (SHOW_UBITS(re, &s->gb, 1) == 0) {
1393
0
                        av_log(s->avctx, AV_LOG_ERROR,
1394
0
                               "2. marker bit missing in rvlc esc\n");
1395
0
                        return AVERROR_INVALIDDATA;
1396
0
                    }
1397
0
                    SKIP_CACHE(re, &s->gb, 1);
1398
1399
0
                    level = SHOW_UBITS(re, &s->gb, 11);
1400
0
                    SKIP_CACHE(re, &s->gb, 11);
1401
1402
0
                    if (SHOW_UBITS(re, &s->gb, 5) != 0x10) {
1403
0
                        av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n");
1404
0
                        return AVERROR_INVALIDDATA;
1405
0
                    }
1406
0
                    SKIP_CACHE(re, &s->gb, 5);
1407
1408
0
                    level = level * qmul + qadd;
1409
0
                    level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1410
0
                    SKIP_COUNTER(re, &s->gb, 1 + 11 + 5 + 1);
1411
1412
0
                    i += run + 1;
1413
0
                    if (last)
1414
0
                        i += 192;
1415
0
                } else {
1416
0
                    int cache;
1417
0
                    cache = GET_CACHE(re, &s->gb);
1418
1419
0
                    if (IS_3IV1)
1420
0
                        cache ^= 0xC0000000;
1421
1422
0
                    if (cache & 0x80000000) {
1423
0
                        if (cache & 0x40000000) {
1424
                            /* third escape */
1425
0
                            SKIP_CACHE(re, &s->gb, 2);
1426
0
                            last = SHOW_UBITS(re, &s->gb, 1);
1427
0
                            SKIP_CACHE(re, &s->gb, 1);
1428
0
                            run = SHOW_UBITS(re, &s->gb, 6);
1429
0
                            SKIP_COUNTER(re, &s->gb, 2 + 1 + 6);
1430
0
                            UPDATE_CACHE(re, &s->gb);
1431
1432
0
                            if (IS_3IV1) {
1433
0
                                level = SHOW_SBITS(re, &s->gb, 12);
1434
0
                                LAST_SKIP_BITS(re, &s->gb, 12);
1435
0
                            } else {
1436
0
                                if (SHOW_UBITS(re, &s->gb, 1) == 0) {
1437
0
                                    av_log(s->avctx, AV_LOG_ERROR,
1438
0
                                           "1. marker bit missing in 3. esc\n");
1439
0
                                    if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR) || get_bits_left(&s->gb) <= 0)
1440
0
                                        return AVERROR_INVALIDDATA;
1441
0
                                }
1442
0
                                SKIP_CACHE(re, &s->gb, 1);
1443
1444
0
                                level = SHOW_SBITS(re, &s->gb, 12);
1445
0
                                SKIP_CACHE(re, &s->gb, 12);
1446
1447
0
                                if (SHOW_UBITS(re, &s->gb, 1) == 0) {
1448
0
                                    av_log(s->avctx, AV_LOG_ERROR,
1449
0
                                           "2. marker bit missing in 3. esc\n");
1450
0
                                    if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR) || get_bits_left(&s->gb) <= 0)
1451
0
                                        return AVERROR_INVALIDDATA;
1452
0
                                }
1453
1454
0
                                SKIP_COUNTER(re, &s->gb, 1 + 12 + 1);
1455
0
                            }
1456
1457
#if 0
1458
                            if (s->error_recognition >= FF_ER_COMPLIANT) {
1459
                                const int abs_level= FFABS(level);
1460
                                if (abs_level<=MAX_LEVEL && run<=MAX_RUN) {
1461
                                    const int run1= run - rl->max_run[last][abs_level] - 1;
1462
                                    if (abs_level <= rl->max_level[last][run]) {
1463
                                        av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n");
1464
                                        return AVERROR_INVALIDDATA;
1465
                                    }
1466
                                    if (s->error_recognition > FF_ER_COMPLIANT) {
1467
                                        if (abs_level <= rl->max_level[last][run]*2) {
1468
                                            av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 1 encoding possible\n");
1469
                                            return AVERROR_INVALIDDATA;
1470
                                        }
1471
                                        if (run1 >= 0 && abs_level <= rl->max_level[last][run1]) {
1472
                                            av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 2 encoding possible\n");
1473
                                            return AVERROR_INVALIDDATA;
1474
                                        }
1475
                                    }
1476
                                }
1477
                            }
1478
#endif
1479
0
                            if (level > 0)
1480
0
                                level = level * qmul + qadd;
1481
0
                            else
1482
0
                                level = level * qmul - qadd;
1483
1484
0
                            if ((unsigned)(level + 2048) > 4095) {
1485
0
                                if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_AGGRESSIVE)) {
1486
0
                                    if (level > 2560 || level < -2560) {
1487
0
                                        av_log(s->avctx, AV_LOG_ERROR,
1488
0
                                               "|level| overflow in 3. esc, qp=%d\n",
1489
0
                                               s->qscale);
1490
0
                                        return AVERROR_INVALIDDATA;
1491
0
                                    }
1492
0
                                }
1493
0
                                level = level < 0 ? -2048 : 2047;
1494
0
                            }
1495
1496
0
                            i += run + 1;
1497
0
                            if (last)
1498
0
                                i += 192;
1499
0
                        } else {
1500
                            /* second escape */
1501
0
                            SKIP_BITS(re, &s->gb, 2);
1502
0
                            GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
1503
0
                            i    += run + rl->max_run[run >> 7][level / qmul] + 1;  // FIXME opt indexing
1504
0
                            level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1505
0
                            LAST_SKIP_BITS(re, &s->gb, 1);
1506
0
                        }
1507
0
                    } else {
1508
                        /* first escape */
1509
0
                        SKIP_BITS(re, &s->gb, 1);
1510
0
                        GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
1511
0
                        i    += run;
1512
0
                        level = level + rl->max_level[run >> 7][(run - 1) & 63] * qmul;  // FIXME opt indexing
1513
0
                        level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1514
0
                        LAST_SKIP_BITS(re, &s->gb, 1);
1515
0
                    }
1516
0
                }
1517
0
            } else {
1518
0
                i    += run;
1519
0
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
1520
0
                LAST_SKIP_BITS(re, &s->gb, 1);
1521
0
            }
1522
0
            ff_tlog(s->avctx, "dct[%d][%d] = %- 4d end?:%d\n", scan_table[i&63]&7, scan_table[i&63] >> 3, level, i>62);
1523
0
            if (i > 62) {
1524
0
                i -= 192;
1525
0
                if (i & (~63)) {
1526
0
                    av_log(s->avctx, AV_LOG_ERROR,
1527
0
                           "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
1528
0
                    return AVERROR_INVALIDDATA;
1529
0
                }
1530
1531
0
                block[scan_table[i]] = level;
1532
0
                break;
1533
0
            }
1534
1535
0
            block[scan_table[i]] = level;
1536
0
        }
1537
0
        CLOSE_READER(re, &s->gb);
1538
0
    }
1539
1540
0
not_coded:
1541
0
    if (intra) {
1542
0
        if (!use_intra_dc_vlc) {
1543
0
            block[0] = ff_mpeg4_pred_dc(s, n, block[0], &dc_pred_dir, 0);
1544
1545
0
            i -= i >> 31;  // if (i == -1) i = 0;
1546
0
        }
1547
1548
0
        ff_mpeg4_pred_ac(s, block, n, dc_pred_dir);
1549
0
        if (s->ac_pred)
1550
0
            i = 63;  // FIXME not optimal
1551
0
    }
1552
0
    s->block_last_index[n] = i;
1553
0
    return 0;
1554
0
}
1555
1556
/**
1557
 * decode partition C of one MB.
1558
 * @return <0 if an error occurred
1559
 */
1560
static int mpeg4_decode_partitioned_mb(MpegEncContext *s, int16_t block[6][64])
1561
0
{
1562
0
    Mpeg4DecContext *ctx = s->avctx->priv_data;
1563
0
    int cbp, mb_type, use_intra_dc_vlc;
1564
0
    const int xy = s->mb_x + s->mb_y * s->mb_stride;
1565
1566
0
    av_assert2(s == (void*)ctx);
1567
1568
0
    mb_type = s->cur_pic.mb_type[xy];
1569
0
    cbp     = s->cbp_table[xy];
1570
1571
0
    use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold;
1572
1573
0
    if (s->cur_pic.qscale_table[xy] != s->qscale)
1574
0
        ff_set_qscale(s, s->cur_pic.qscale_table[xy]);
1575
1576
0
    if (s->pict_type == AV_PICTURE_TYPE_P ||
1577
0
        s->pict_type == AV_PICTURE_TYPE_S) {
1578
0
        int i;
1579
0
        for (i = 0; i < 4; i++) {
1580
0
            s->mv[0][i][0] = s->cur_pic.motion_val[0][s->block_index[i]][0];
1581
0
            s->mv[0][i][1] = s->cur_pic.motion_val[0][s->block_index[i]][1];
1582
0
        }
1583
0
        s->mb_intra = IS_INTRA(mb_type);
1584
1585
0
        if (IS_SKIP(mb_type)) {
1586
            /* skip mb */
1587
0
            for (i = 0; i < 6; i++)
1588
0
                s->block_last_index[i] = -1;
1589
0
            s->mv_dir  = MV_DIR_FORWARD;
1590
0
            s->mv_type = MV_TYPE_16X16;
1591
0
            if (s->pict_type == AV_PICTURE_TYPE_S
1592
0
                && ctx->vol_sprite_usage == GMC_SPRITE) {
1593
0
                s->mcsel      = 1;
1594
0
                s->mb_skipped = 0;
1595
0
                s->cur_pic.mbskip_table[xy] = 0;
1596
0
            } else {
1597
0
                s->mcsel      = 0;
1598
0
                s->mb_skipped = 1;
1599
0
                s->cur_pic.mbskip_table[xy] = 1;
1600
0
            }
1601
0
        } else if (s->mb_intra) {
1602
0
            s->ac_pred = IS_ACPRED(s->cur_pic.mb_type[xy]);
1603
0
        } else if (!s->mb_intra) {
1604
            // s->mcsel = 0;  // FIXME do we need to init that?
1605
1606
0
            s->mv_dir = MV_DIR_FORWARD;
1607
0
            if (IS_8X8(mb_type)) {
1608
0
                s->mv_type = MV_TYPE_8X8;
1609
0
            } else {
1610
0
                s->mv_type = MV_TYPE_16X16;
1611
0
            }
1612
0
        }
1613
0
    } else { /* I-Frame */
1614
0
        s->mb_intra = 1;
1615
0
        s->ac_pred  = IS_ACPRED(s->cur_pic.mb_type[xy]);
1616
0
    }
1617
1618
0
    if (!IS_SKIP(mb_type)) {
1619
0
        int i;
1620
0
        s->bdsp.clear_blocks(s->block[0]);
1621
        /* decode each block */
1622
0
        for (i = 0; i < 6; i++) {
1623
0
            if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, s->mb_intra,
1624
0
                                   use_intra_dc_vlc, ctx->rvlc) < 0) {
1625
0
                av_log(s->avctx, AV_LOG_ERROR,
1626
0
                       "texture corrupted at %d %d %d\n",
1627
0
                       s->mb_x, s->mb_y, s->mb_intra);
1628
0
                return AVERROR_INVALIDDATA;
1629
0
            }
1630
0
            cbp += cbp;
1631
0
        }
1632
0
    }
1633
1634
    /* per-MB end of slice check */
1635
0
    if (--s->mb_num_left <= 0) {
1636
0
        if (mpeg4_is_resync(ctx))
1637
0
            return SLICE_END;
1638
0
        else
1639
0
            return SLICE_NOEND;
1640
0
    } else {
1641
0
        if (mpeg4_is_resync(ctx)) {
1642
0
            const int delta = s->mb_x + 1 == s->mb_width ? 2 : 1;
1643
0
            if (s->cbp_table[xy + delta])
1644
0
                return SLICE_END;
1645
0
        }
1646
0
        return SLICE_OK;
1647
0
    }
1648
0
}
1649
1650
static int mpeg4_decode_mb(MpegEncContext *s, int16_t block[6][64])
1651
0
{
1652
0
    Mpeg4DecContext *ctx = s->avctx->priv_data;
1653
0
    int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
1654
0
    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
1655
0
    const int xy = s->mb_x + s->mb_y * s->mb_stride;
1656
0
    int next;
1657
1658
0
    av_assert2(s ==  (void*)ctx);
1659
0
    av_assert2(s->h263_pred);
1660
1661
0
    if (s->pict_type == AV_PICTURE_TYPE_P ||
1662
0
        s->pict_type == AV_PICTURE_TYPE_S) {
1663
0
        do {
1664
0
            if (get_bits1(&s->gb)) {
1665
                /* skip mb */
1666
0
                s->mb_intra = 0;
1667
0
                for (i = 0; i < 6; i++)
1668
0
                    s->block_last_index[i] = -1;
1669
0
                s->mv_dir  = MV_DIR_FORWARD;
1670
0
                s->mv_type = MV_TYPE_16X16;
1671
0
                if (s->pict_type == AV_PICTURE_TYPE_S &&
1672
0
                    ctx->vol_sprite_usage == GMC_SPRITE) {
1673
0
                    s->cur_pic.mb_type[xy] = MB_TYPE_SKIP  |
1674
0
                                                     MB_TYPE_GMC   |
1675
0
                                                     MB_TYPE_16x16 |
1676
0
                                             MB_TYPE_FORWARD_MV;
1677
0
                    s->mcsel       = 1;
1678
0
                    s->mv[0][0][0] = get_amv(ctx, 0);
1679
0
                    s->mv[0][0][1] = get_amv(ctx, 1);
1680
0
                    s->cur_pic.mbskip_table[xy] = 0;
1681
0
                    s->mb_skipped  = 0;
1682
0
                } else {
1683
0
                    s->cur_pic.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 |
1684
0
                                             MB_TYPE_FORWARD_MV;
1685
0
                    s->mcsel       = 0;
1686
0
                    s->mv[0][0][0] = 0;
1687
0
                    s->mv[0][0][1] = 0;
1688
0
                    s->cur_pic.mbskip_table[xy] = 1;
1689
0
                    s->mb_skipped  = 1;
1690
0
                }
1691
0
                goto end;
1692
0
            }
1693
0
            cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc, INTER_MCBPC_VLC_BITS, 2);
1694
0
            if (cbpc < 0) {
1695
0
                av_log(s->avctx, AV_LOG_ERROR,
1696
0
                       "mcbpc damaged at %d %d\n", s->mb_x, s->mb_y);
1697
0
                return AVERROR_INVALIDDATA;
1698
0
            }
1699
0
        } while (cbpc == 20);
1700
1701
0
        s->bdsp.clear_blocks(s->block[0]);
1702
0
        dquant      = cbpc & 8;
1703
0
        s->mb_intra = ((cbpc & 4) != 0);
1704
0
        if (s->mb_intra)
1705
0
            goto intra;
1706
1707
0
        if (s->pict_type == AV_PICTURE_TYPE_S &&
1708
0
            ctx->vol_sprite_usage == GMC_SPRITE && (cbpc & 16) == 0)
1709
0
            s->mcsel = get_bits1(&s->gb);
1710
0
        else
1711
0
            s->mcsel = 0;
1712
0
        cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc, CBPY_VLC_BITS, 1) ^ 0x0F;
1713
0
        if (cbpy < 0) {
1714
0
            av_log(s->avctx, AV_LOG_ERROR,
1715
0
                   "P cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
1716
0
            return AVERROR_INVALIDDATA;
1717
0
        }
1718
1719
0
        cbp = (cbpc & 3) | (cbpy << 2);
1720
0
        if (dquant)
1721
0
            ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
1722
0
        if ((!s->progressive_sequence) &&
1723
0
            (cbp || (s->workaround_bugs & FF_BUG_XVID_ILACE)))
1724
0
            s->interlaced_dct = get_bits1(&s->gb);
1725
1726
0
        s->mv_dir = MV_DIR_FORWARD;
1727
0
        if ((cbpc & 16) == 0) {
1728
0
            if (s->mcsel) {
1729
0
                s->cur_pic.mb_type[xy] = MB_TYPE_GMC | MB_TYPE_16x16 |
1730
0
                                         MB_TYPE_FORWARD_MV;
1731
                /* 16x16 global motion prediction */
1732
0
                s->mv_type     = MV_TYPE_16X16;
1733
0
                mx             = get_amv(ctx, 0);
1734
0
                my             = get_amv(ctx, 1);
1735
0
                s->mv[0][0][0] = mx;
1736
0
                s->mv[0][0][1] = my;
1737
0
            } else if ((!s->progressive_sequence) && get_bits1(&s->gb)) {
1738
0
                s->cur_pic.mb_type[xy] = MB_TYPE_16x8 | MB_TYPE_FORWARD_MV |
1739
0
                                                 MB_TYPE_INTERLACED;
1740
                /* 16x8 field motion prediction */
1741
0
                s->mv_type = MV_TYPE_FIELD;
1742
1743
0
                s->field_select[0][0] = get_bits1(&s->gb);
1744
0
                s->field_select[0][1] = get_bits1(&s->gb);
1745
1746
0
                ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1747
1748
0
                for (i = 0; i < 2; i++) {
1749
0
                    mx = ff_h263_decode_motion(s, pred_x, s->f_code);
1750
0
                    if (mx >= 0xffff)
1751
0
                        return AVERROR_INVALIDDATA;
1752
1753
0
                    my = ff_h263_decode_motion(s, pred_y / 2, s->f_code);
1754
0
                    if (my >= 0xffff)
1755
0
                        return AVERROR_INVALIDDATA;
1756
1757
0
                    s->mv[0][i][0] = mx;
1758
0
                    s->mv[0][i][1] = my;
1759
0
                }
1760
0
            } else {
1761
0
                s->cur_pic.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_FORWARD_MV;
1762
                /* 16x16 motion prediction */
1763
0
                s->mv_type = MV_TYPE_16X16;
1764
0
                ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
1765
0
                mx = ff_h263_decode_motion(s, pred_x, s->f_code);
1766
1767
0
                if (mx >= 0xffff)
1768
0
                    return AVERROR_INVALIDDATA;
1769
1770
0
                my = ff_h263_decode_motion(s, pred_y, s->f_code);
1771
1772
0
                if (my >= 0xffff)
1773
0
                    return AVERROR_INVALIDDATA;
1774
0
                s->mv[0][0][0] = mx;
1775
0
                s->mv[0][0][1] = my;
1776
0
            }
1777
0
        } else {
1778
0
            s->cur_pic.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_FORWARD_MV;
1779
0
            s->mv_type                     = MV_TYPE_8X8;
1780
0
            for (i = 0; i < 4; i++) {
1781
0
                int16_t *mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
1782
0
                mx      = ff_h263_decode_motion(s, pred_x, s->f_code);
1783
0
                if (mx >= 0xffff)
1784
0
                    return AVERROR_INVALIDDATA;
1785
1786
0
                my = ff_h263_decode_motion(s, pred_y, s->f_code);
1787
0
                if (my >= 0xffff)
1788
0
                    return AVERROR_INVALIDDATA;
1789
0
                s->mv[0][i][0] = mx;
1790
0
                s->mv[0][i][1] = my;
1791
0
                mot_val[0]     = mx;
1792
0
                mot_val[1]     = my;
1793
0
            }
1794
0
        }
1795
0
    } else if (s->pict_type == AV_PICTURE_TYPE_B) {
1796
0
        int modb1;   // first bit of modb
1797
0
        int modb2;   // second bit of modb
1798
0
        int mb_type;
1799
1800
0
        s->mb_intra = 0;  // B-frames never contain intra blocks
1801
0
        s->mcsel    = 0;  //      ...               true gmc blocks
1802
1803
0
        if (s->mb_x == 0) {
1804
0
            for (i = 0; i < 2; i++) {
1805
0
                s->last_mv[i][0][0] =
1806
0
                s->last_mv[i][0][1] =
1807
0
                s->last_mv[i][1][0] =
1808
0
                s->last_mv[i][1][1] = 0;
1809
0
            }
1810
1811
0
            ff_thread_progress_await(&s->next_pic.ptr->progress, s->mb_y);
1812
0
        }
1813
1814
        /* if we skipped it in the future P-frame than skip it now too */
1815
0
        s->mb_skipped = s->next_pic.mbskip_table[s->mb_y * s->mb_stride + s->mb_x];  // Note, skiptab=0 if last was GMC
1816
1817
0
        if (s->mb_skipped) {
1818
            /* skip mb */
1819
0
            for (i = 0; i < 6; i++)
1820
0
                s->block_last_index[i] = -1;
1821
1822
0
            s->mv_dir      = MV_DIR_FORWARD;
1823
0
            s->mv_type     = MV_TYPE_16X16;
1824
0
            s->mv[0][0][0] =
1825
0
            s->mv[0][0][1] =
1826
0
            s->mv[1][0][0] =
1827
0
            s->mv[1][0][1] = 0;
1828
0
            s->cur_pic.mb_type[xy] = MB_TYPE_SKIP  |
1829
0
                                             MB_TYPE_16x16 |
1830
0
                                             MB_TYPE_FORWARD_MV;
1831
0
            goto end;
1832
0
        }
1833
1834
0
        modb1 = get_bits1(&s->gb);
1835
0
        if (modb1) {
1836
            // like MB_TYPE_B_DIRECT but no vectors coded
1837
0
            mb_type = MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_BIDIR_MV;
1838
0
            cbp     = 0;
1839
0
        } else {
1840
0
            modb2   = get_bits1(&s->gb);
1841
0
            mb_type = get_vlc2(&s->gb, mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 1);
1842
0
            if (mb_type < 0) {
1843
0
                av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n");
1844
0
                return AVERROR_INVALIDDATA;
1845
0
            }
1846
0
            if (modb2) {
1847
0
                cbp = 0;
1848
0
            } else {
1849
0
                s->bdsp.clear_blocks(s->block[0]);
1850
0
                cbp = get_bits(&s->gb, 6);
1851
0
            }
1852
1853
0
            if ((!IS_DIRECT(mb_type)) && cbp) {
1854
0
                if (get_bits1(&s->gb))
1855
0
                    ff_set_qscale(s, s->qscale + get_bits1(&s->gb) * 4 - 2);
1856
0
            }
1857
1858
0
            if (!s->progressive_sequence) {
1859
0
                if (cbp)
1860
0
                    s->interlaced_dct = get_bits1(&s->gb);
1861
1862
0
                if (!IS_DIRECT(mb_type) && get_bits1(&s->gb)) {
1863
0
                    mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
1864
0
                    mb_type &= ~MB_TYPE_16x16;
1865
1866
0
                    if (HAS_FORWARD_MV(mb_type)) {
1867
0
                        s->field_select[0][0] = get_bits1(&s->gb);
1868
0
                        s->field_select[0][1] = get_bits1(&s->gb);
1869
0
                    }
1870
0
                    if (HAS_BACKWARD_MV(mb_type)) {
1871
0
                        s->field_select[1][0] = get_bits1(&s->gb);
1872
0
                        s->field_select[1][1] = get_bits1(&s->gb);
1873
0
                    }
1874
0
                }
1875
0
            }
1876
1877
0
            s->mv_dir = 0;
1878
0
            if ((mb_type & (MB_TYPE_DIRECT2 | MB_TYPE_INTERLACED)) == 0) {
1879
0
                s->mv_type = MV_TYPE_16X16;
1880
1881
0
                if (HAS_FORWARD_MV(mb_type)) {
1882
0
                    s->mv_dir = MV_DIR_FORWARD;
1883
1884
0
                    mx = ff_h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
1885
0
                    my = ff_h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
1886
0
                    s->last_mv[0][1][0] =
1887
0
                    s->last_mv[0][0][0] =
1888
0
                    s->mv[0][0][0]      = mx;
1889
0
                    s->last_mv[0][1][1] =
1890
0
                    s->last_mv[0][0][1] =
1891
0
                    s->mv[0][0][1]      = my;
1892
0
                }
1893
1894
0
                if (HAS_BACKWARD_MV(mb_type)) {
1895
0
                    s->mv_dir |= MV_DIR_BACKWARD;
1896
1897
0
                    mx = ff_h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
1898
0
                    my = ff_h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
1899
0
                    s->last_mv[1][1][0] =
1900
0
                    s->last_mv[1][0][0] =
1901
0
                    s->mv[1][0][0]      = mx;
1902
0
                    s->last_mv[1][1][1] =
1903
0
                    s->last_mv[1][0][1] =
1904
0
                    s->mv[1][0][1]      = my;
1905
0
                }
1906
0
            } else if (!IS_DIRECT(mb_type)) {
1907
0
                s->mv_type = MV_TYPE_FIELD;
1908
1909
0
                if (HAS_FORWARD_MV(mb_type)) {
1910
0
                    s->mv_dir = MV_DIR_FORWARD;
1911
1912
0
                    for (i = 0; i < 2; i++) {
1913
0
                        mx = ff_h263_decode_motion(s, s->last_mv[0][i][0], s->f_code);
1914
0
                        my = ff_h263_decode_motion(s, s->last_mv[0][i][1] / 2, s->f_code);
1915
0
                        s->last_mv[0][i][0] =
1916
0
                        s->mv[0][i][0]      = mx;
1917
0
                        s->last_mv[0][i][1] = (s->mv[0][i][1] = my) * 2;
1918
0
                    }
1919
0
                }
1920
1921
0
                if (HAS_BACKWARD_MV(mb_type)) {
1922
0
                    s->mv_dir |= MV_DIR_BACKWARD;
1923
1924
0
                    for (i = 0; i < 2; i++) {
1925
0
                        mx = ff_h263_decode_motion(s, s->last_mv[1][i][0], s->b_code);
1926
0
                        my = ff_h263_decode_motion(s, s->last_mv[1][i][1] / 2, s->b_code);
1927
0
                        s->last_mv[1][i][0] =
1928
0
                        s->mv[1][i][0]      = mx;
1929
0
                        s->last_mv[1][i][1] = (s->mv[1][i][1] = my) * 2;
1930
0
                    }
1931
0
                }
1932
0
            }
1933
0
        }
1934
1935
0
        if (IS_DIRECT(mb_type)) {
1936
0
            if (IS_SKIP(mb_type)) {
1937
0
                mx =
1938
0
                my = 0;
1939
0
            } else {
1940
0
                mx = ff_h263_decode_motion(s, 0, 1);
1941
0
                my = ff_h263_decode_motion(s, 0, 1);
1942
0
            }
1943
1944
0
            s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
1945
0
            mb_type  |= ff_mpeg4_set_direct_mv(s, mx, my);
1946
0
        }
1947
0
        s->cur_pic.mb_type[xy] = mb_type;
1948
0
    } else { /* I-Frame */
1949
0
        int use_intra_dc_vlc;
1950
1951
0
        do {
1952
0
            cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc, INTRA_MCBPC_VLC_BITS, 2);
1953
0
            if (cbpc < 0) {
1954
0
                av_log(s->avctx, AV_LOG_ERROR,
1955
0
                       "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
1956
0
                return AVERROR_INVALIDDATA;
1957
0
            }
1958
0
        } while (cbpc == 8);
1959
1960
0
        dquant = cbpc & 4;
1961
0
        s->mb_intra = 1;
1962
1963
0
intra:
1964
0
        s->ac_pred = get_bits1(&s->gb);
1965
0
        if (s->ac_pred)
1966
0
            s->cur_pic.mb_type[xy] = MB_TYPE_INTRA | MB_TYPE_ACPRED;
1967
0
        else
1968
0
            s->cur_pic.mb_type[xy] = MB_TYPE_INTRA;
1969
1970
0
        cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc, CBPY_VLC_BITS, 1);
1971
0
        if (cbpy < 0) {
1972
0
            av_log(s->avctx, AV_LOG_ERROR,
1973
0
                   "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
1974
0
            return AVERROR_INVALIDDATA;
1975
0
        }
1976
0
        cbp = (cbpc & 3) | (cbpy << 2);
1977
1978
0
        use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold;
1979
1980
0
        if (dquant)
1981
0
            ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
1982
1983
0
        if (!s->progressive_sequence)
1984
0
            s->interlaced_dct = get_bits1(&s->gb);
1985
1986
0
        s->bdsp.clear_blocks(s->block[0]);
1987
        /* decode each block */
1988
0
        for (i = 0; i < 6; i++) {
1989
0
            if (mpeg4_decode_block(ctx, block[i], i, cbp & 32,
1990
0
                                   1, use_intra_dc_vlc, 0) < 0)
1991
0
                return AVERROR_INVALIDDATA;
1992
0
            cbp += cbp;
1993
0
        }
1994
0
        goto end;
1995
0
    }
1996
1997
    /* decode each block */
1998
0
    for (i = 0; i < 6; i++) {
1999
0
        if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 0, 0, 0) < 0)
2000
0
            return AVERROR_INVALIDDATA;
2001
0
        cbp += cbp;
2002
0
    }
2003
2004
0
end:
2005
    /* per-MB end of slice check */
2006
0
    next = mpeg4_is_resync(ctx);
2007
0
    if (next) {
2008
0
        if        (s->mb_x + s->mb_y*s->mb_width + 1 >  next && (s->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
2009
0
            return AVERROR_INVALIDDATA;
2010
0
        } else if (s->mb_x + s->mb_y*s->mb_width + 1 >= next)
2011
0
            return SLICE_END;
2012
2013
0
        if (s->pict_type == AV_PICTURE_TYPE_B) {
2014
0
            const int delta = s->mb_x + 1 == s->mb_width ? 2 : 1;
2015
0
            ff_thread_progress_await(&s->next_pic.ptr->progress,
2016
0
                                        (s->mb_x + delta >= s->mb_width)
2017
0
                                        ? FFMIN(s->mb_y + 1, s->mb_height - 1)
2018
0
                                        : s->mb_y);
2019
0
            if (s->next_pic.mbskip_table[xy + delta])
2020
0
                return SLICE_OK;
2021
0
        }
2022
2023
0
        return SLICE_END;
2024
0
    }
2025
2026
0
    return SLICE_OK;
2027
0
}
2028
2029
/* As per spec, studio start code search isn't the same as the old type of start code */
2030
static void next_start_code_studio(GetBitContext *gb)
2031
15.4k
{
2032
15.4k
    align_get_bits(gb);
2033
2034
412k
    while (get_bits_left(gb) >= 24 && show_bits(gb, 24) != 0x1) {
2035
397k
        get_bits(gb, 8);
2036
397k
    }
2037
15.4k
}
2038
2039
/* additional_code, vlc index */
2040
static const uint8_t ac_state_tab[22][2] =
2041
{
2042
    {0, 0},
2043
    {0, 1},
2044
    {1, 1},
2045
    {2, 1},
2046
    {3, 1},
2047
    {4, 1},
2048
    {5, 1},
2049
    {1, 2},
2050
    {2, 2},
2051
    {3, 2},
2052
    {4, 2},
2053
    {5, 2},
2054
    {6, 2},
2055
    {1, 3},
2056
    {2, 4},
2057
    {3, 5},
2058
    {4, 6},
2059
    {5, 7},
2060
    {6, 8},
2061
    {7, 9},
2062
    {8, 10},
2063
    {0, 11}
2064
};
2065
2066
static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n)
2067
0
{
2068
0
    Mpeg4DecContext *ctx = s->avctx->priv_data;
2069
2070
0
    int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0,
2071
0
        additional_code_len, sign, mismatch;
2072
0
    const VLCElem *cur_vlc = studio_intra_tab[0];
2073
0
    const uint8_t *const scantable = s->intra_scantable.permutated;
2074
0
    const uint16_t *quant_matrix;
2075
0
    uint32_t flc;
2076
0
    const int min = -1 *  (1 << (s->avctx->bits_per_raw_sample + 6));
2077
0
    const int max =      ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1);
2078
0
    int shift =  3 - s->dct_precision;
2079
2080
0
    mismatch = 1;
2081
2082
0
    memset(block, 0, 64 * sizeof(int32_t));
2083
2084
0
    if (n < 4) {
2085
0
        cc = 0;
2086
0
        dct_dc_size = get_vlc2(&s->gb, studio_luma_dc, STUDIO_INTRA_BITS, 2);
2087
0
        quant_matrix = s->intra_matrix;
2088
0
    } else {
2089
0
        cc = (n & 1) + 1;
2090
0
        if (ctx->rgb)
2091
0
            dct_dc_size = get_vlc2(&s->gb, studio_luma_dc, STUDIO_INTRA_BITS, 2);
2092
0
        else
2093
0
            dct_dc_size = get_vlc2(&s->gb, studio_chroma_dc, STUDIO_INTRA_BITS, 2);
2094
0
        quant_matrix = s->chroma_intra_matrix;
2095
0
    }
2096
2097
0
    if (dct_dc_size == 0) {
2098
0
        dct_diff = 0;
2099
0
    } else {
2100
0
        dct_diff = get_xbits(&s->gb, dct_dc_size);
2101
2102
0
        if (dct_dc_size > 8) {
2103
0
            if(!check_marker(s->avctx, &s->gb, "dct_dc_size > 8"))
2104
0
                return AVERROR_INVALIDDATA;
2105
0
        }
2106
2107
0
    }
2108
2109
0
    s->last_dc[cc] += dct_diff;
2110
2111
0
    if (s->mpeg_quant)
2112
0
        block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision);
2113
0
    else
2114
0
        block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision);
2115
    /* TODO: support mpeg_quant for AC coefficients */
2116
2117
0
    block[0] = av_clip(block[0], min, max);
2118
0
    mismatch ^= block[0];
2119
2120
    /* AC Coefficients */
2121
0
    while (1) {
2122
0
        group = get_vlc2(&s->gb, cur_vlc, STUDIO_INTRA_BITS, 2);
2123
2124
0
        if (group < 0) {
2125
0
            av_log(s->avctx, AV_LOG_ERROR, "illegal ac coefficient group vlc\n");
2126
0
            return AVERROR_INVALIDDATA;
2127
0
        }
2128
2129
0
        additional_code_len = ac_state_tab[group][0];
2130
0
        cur_vlc = studio_intra_tab[ac_state_tab[group][1]];
2131
2132
0
        if (group == 0) {
2133
            /* End of Block */
2134
0
            break;
2135
0
        } else if (group >= 1 && group <= 6) {
2136
            /* Zero run length (Table B.47) */
2137
0
            run = 1 << additional_code_len;
2138
0
            if (additional_code_len)
2139
0
                run += get_bits(&s->gb, additional_code_len);
2140
0
            idx += run;
2141
0
            continue;
2142
0
        } else if (group >= 7 && group <= 12) {
2143
            /* Zero run length and +/-1 level (Table B.48) */
2144
0
            code = get_bits(&s->gb, additional_code_len);
2145
0
            sign = code & 1;
2146
0
            code >>= 1;
2147
0
            run = (1 << (additional_code_len - 1)) + code;
2148
0
            idx += run;
2149
0
            if (idx > 63)
2150
0
                return AVERROR_INVALIDDATA;
2151
0
            j = scantable[idx++];
2152
0
            block[j] = sign ? 1 : -1;
2153
0
        } else if (group >= 13 && group <= 20) {
2154
            /* Level value (Table B.49) */
2155
0
            if (idx > 63)
2156
0
                return AVERROR_INVALIDDATA;
2157
0
            j = scantable[idx++];
2158
0
            block[j] = get_xbits(&s->gb, additional_code_len);
2159
0
        } else if (group == 21) {
2160
            /* Escape */
2161
0
            if (idx > 63)
2162
0
                return AVERROR_INVALIDDATA;
2163
0
            j = scantable[idx++];
2164
0
            additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4;
2165
0
            flc = get_bits(&s->gb, additional_code_len);
2166
0
            if (flc >> (additional_code_len-1))
2167
0
                block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1);
2168
0
            else
2169
0
                block[j] = flc;
2170
0
        }
2171
0
        block[j] = ((block[j] * quant_matrix[j] * s->qscale) * (1 << shift)) / 16;
2172
0
        block[j] = av_clip(block[j], min, max);
2173
0
        mismatch ^= block[j];
2174
0
    }
2175
2176
0
    block[63] ^= mismatch & 1;
2177
2178
0
    return 0;
2179
0
}
2180
2181
static int mpeg4_decode_dpcm_macroblock(MpegEncContext *s, int16_t macroblock[256], int n)
2182
0
{
2183
0
    int i, j, w, h, idx = 0;
2184
0
    int block_mean, rice_parameter, rice_prefix_code, rice_suffix_code,
2185
0
        dpcm_residual, left, top, topleft, min_left_top, max_left_top, p, p2, output;
2186
0
    h = 16 >> (n ? s->chroma_y_shift : 0);
2187
0
    w = 16 >> (n ? s->chroma_x_shift : 0);
2188
2189
0
    block_mean = get_bits(&s->gb, s->avctx->bits_per_raw_sample);
2190
0
    if (block_mean == 0){
2191
0
        av_log(s->avctx, AV_LOG_ERROR, "Forbidden block_mean\n");
2192
0
        return AVERROR_INVALIDDATA;
2193
0
    }
2194
0
    s->last_dc[n] = block_mean * (1 << (s->dct_precision + s->intra_dc_precision));
2195
2196
0
    rice_parameter = get_bits(&s->gb, 4);
2197
0
    if (rice_parameter == 0) {
2198
0
        av_log(s->avctx, AV_LOG_ERROR, "Forbidden rice_parameter\n");
2199
0
        return AVERROR_INVALIDDATA;
2200
0
    }
2201
2202
0
    if (rice_parameter == 15)
2203
0
        rice_parameter = 0;
2204
2205
0
    if (rice_parameter > 11) {
2206
0
        av_log(s->avctx, AV_LOG_ERROR, "Forbidden rice_parameter\n");
2207
0
        return AVERROR_INVALIDDATA;
2208
0
    }
2209
2210
0
    for (i = 0; i < h; i++) {
2211
0
        output = 1 << (s->avctx->bits_per_raw_sample - 1);
2212
0
        top = 1 << (s->avctx->bits_per_raw_sample - 1);
2213
2214
0
        for (j = 0; j < w; j++) {
2215
0
            left = output;
2216
0
            topleft = top;
2217
2218
0
            rice_prefix_code = get_unary(&s->gb, 1, 12);
2219
2220
            /* Escape */
2221
0
            if (rice_prefix_code == 11)
2222
0
                dpcm_residual = get_bits(&s->gb, s->avctx->bits_per_raw_sample);
2223
0
            else {
2224
0
                if (rice_prefix_code == 12) {
2225
0
                    av_log(s->avctx, AV_LOG_ERROR, "Forbidden rice_prefix_code\n");
2226
0
                    return AVERROR_INVALIDDATA;
2227
0
                }
2228
0
                rice_suffix_code = get_bitsz(&s->gb, rice_parameter);
2229
0
                dpcm_residual = (rice_prefix_code << rice_parameter) + rice_suffix_code;
2230
0
            }
2231
2232
            /* Map to a signed residual */
2233
0
            if (dpcm_residual & 1)
2234
0
                dpcm_residual = (-1 * dpcm_residual) >> 1;
2235
0
            else
2236
0
                dpcm_residual = (dpcm_residual >> 1);
2237
2238
0
            if (i != 0)
2239
0
                top = macroblock[idx-w];
2240
2241
0
            p = left + top - topleft;
2242
0
            min_left_top = FFMIN(left, top);
2243
0
            if (p < min_left_top)
2244
0
                p = min_left_top;
2245
2246
0
            max_left_top = FFMAX(left, top);
2247
0
            if (p > max_left_top)
2248
0
                p = max_left_top;
2249
2250
0
            p2 = (FFMIN(min_left_top, topleft) + FFMAX(max_left_top, topleft)) >> 1;
2251
0
            if (p2 == p)
2252
0
                p2 = block_mean;
2253
2254
0
            if (p2 > p)
2255
0
                dpcm_residual *= -1;
2256
2257
0
            macroblock[idx++] = output = (dpcm_residual + p) & ((1 << s->avctx->bits_per_raw_sample) - 1);
2258
0
        }
2259
0
    }
2260
2261
0
    return 0;
2262
0
}
2263
2264
static int mpeg4_decode_studio_mb(MpegEncContext *s, int16_t block_[12][64])
2265
0
{
2266
0
    Mpeg4DecContext *const ctx = (Mpeg4DecContext*)s;
2267
0
    int i;
2268
2269
0
    ctx->dpcm_direction = 0;
2270
2271
    /* StudioMacroblock */
2272
    /* Assumes I-VOP */
2273
0
    s->mb_intra = 1;
2274
0
    if (get_bits1(&s->gb)) { /* compression_mode */
2275
        /* DCT */
2276
        /* macroblock_type, 1 or 2-bit VLC */
2277
0
        if (!get_bits1(&s->gb)) {
2278
0
            skip_bits1(&s->gb);
2279
0
            s->qscale = mpeg_get_qscale(s);
2280
0
        }
2281
2282
0
        for (i = 0; i < mpeg4_block_count[s->chroma_format]; i++) {
2283
0
            if (mpeg4_decode_studio_block(s, ctx->block32[i], i) < 0)
2284
0
                return AVERROR_INVALIDDATA;
2285
0
        }
2286
0
    } else {
2287
        /* DPCM */
2288
0
        check_marker(s->avctx, &s->gb, "DPCM block start");
2289
0
        ctx->dpcm_direction = get_bits1(&s->gb) ? -1 : 1;
2290
0
        for (i = 0; i < 3; i++) {
2291
0
            if (mpeg4_decode_dpcm_macroblock(s, ctx->dpcm_macroblock[i], i) < 0)
2292
0
                return AVERROR_INVALIDDATA;
2293
0
        }
2294
0
    }
2295
2296
0
    if (get_bits_left(&s->gb) >= 24 && show_bits(&s->gb, 23) == 0) {
2297
0
        next_start_code_studio(&s->gb);
2298
0
        return SLICE_END;
2299
0
    }
2300
2301
    //vcon-stp9L1.bits (first frame)
2302
0
    if (get_bits_left(&s->gb) == 0)
2303
0
        return SLICE_END;
2304
2305
    //vcon-stp2L1.bits, vcon-stp3L1.bits, vcon-stp6L1.bits, vcon-stp7L1.bits, vcon-stp8L1.bits, vcon-stp10L1.bits (first frame)
2306
0
    if (get_bits_left(&s->gb) < 8U && show_bits(&s->gb, get_bits_left(&s->gb)) == 0)
2307
0
        return SLICE_END;
2308
2309
0
    return SLICE_OK;
2310
0
}
2311
2312
static int mpeg4_decode_gop_header(MpegEncContext *s, GetBitContext *gb)
2313
1.66k
{
2314
1.66k
    int hours, minutes, seconds;
2315
2316
1.66k
    if (!show_bits(gb, 23)) {
2317
734
        av_log(s->avctx, AV_LOG_WARNING, "GOP header invalid\n");
2318
734
        return AVERROR_INVALIDDATA;
2319
734
    }
2320
2321
929
    hours   = get_bits(gb, 5);
2322
929
    minutes = get_bits(gb, 6);
2323
929
    check_marker(s->avctx, gb, "in gop_header");
2324
929
    seconds = get_bits(gb, 6);
2325
2326
929
    s->time_base = seconds + 60*(minutes + 60*hours);
2327
2328
929
    skip_bits1(gb);
2329
929
    skip_bits1(gb);
2330
2331
929
    return 0;
2332
1.66k
}
2333
2334
static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb, int *profile, int *level)
2335
1.11k
{
2336
2337
1.11k
    *profile = get_bits(gb, 4);
2338
1.11k
    *level   = get_bits(gb, 4);
2339
2340
    // for Simple profile, level 0
2341
1.11k
    if (*profile == 0 && *level == 8) {
2342
0
        *level = 0;
2343
0
    }
2344
2345
1.11k
    return 0;
2346
1.11k
}
2347
2348
static int mpeg4_decode_visual_object(MpegEncContext *s, GetBitContext *gb)
2349
1.46k
{
2350
1.46k
    int visual_object_type;
2351
1.46k
    int is_visual_object_identifier = get_bits1(gb);
2352
2353
1.46k
    if (is_visual_object_identifier) {
2354
1.07k
        skip_bits(gb, 4+3);
2355
1.07k
    }
2356
1.46k
    visual_object_type = get_bits(gb, 4);
2357
2358
1.46k
    if (visual_object_type == VOT_VIDEO_ID ||
2359
1.46k
        visual_object_type == VOT_STILL_TEXTURE_ID) {
2360
684
        int video_signal_type = get_bits1(gb);
2361
684
        if (video_signal_type) {
2362
451
            int video_range, color_description;
2363
451
            skip_bits(gb, 3); // video_format
2364
451
            video_range = get_bits1(gb);
2365
451
            color_description = get_bits1(gb);
2366
2367
451
            s->avctx->color_range = video_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
2368
2369
451
            if (color_description) {
2370
387
                s->avctx->color_primaries = get_bits(gb, 8);
2371
387
                s->avctx->color_trc       = get_bits(gb, 8);
2372
387
                s->avctx->colorspace      = get_bits(gb, 8);
2373
387
            }
2374
451
        }
2375
684
    }
2376
2377
1.46k
    return 0;
2378
1.46k
}
2379
2380
static void mpeg4_load_default_matrices(MpegEncContext *s)
2381
15.3k
{
2382
15.3k
    int i, v;
2383
2384
    /* load default matrices */
2385
997k
    for (i = 0; i < 64; i++) {
2386
982k
        int j = s->idsp.idct_permutation[i];
2387
982k
        v = ff_mpeg4_default_intra_matrix[i];
2388
982k
        s->intra_matrix[j]        = v;
2389
982k
        s->chroma_intra_matrix[j] = v;
2390
2391
982k
        v = ff_mpeg4_default_non_intra_matrix[i];
2392
982k
        s->inter_matrix[j]        = v;
2393
982k
        s->chroma_inter_matrix[j] = v;
2394
982k
    }
2395
15.3k
}
2396
2397
static int read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)
2398
1.73k
{
2399
1.73k
    int i, j, v;
2400
2401
1.73k
    if (get_bits1(gb)) {
2402
1.69k
        if (get_bits_left(gb) < 64*8)
2403
621
            return AVERROR_INVALIDDATA;
2404
        /* intra_quantiser_matrix */
2405
69.7k
        for (i = 0; i < 64; i++) {
2406
68.6k
            v = get_bits(gb, 8);
2407
68.6k
            j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
2408
68.6k
            s->intra_matrix[j]        = v;
2409
68.6k
            s->chroma_intra_matrix[j] = v;
2410
68.6k
        }
2411
1.07k
    }
2412
2413
1.10k
    if (get_bits1(gb)) {
2414
591
        if (get_bits_left(gb) < 64*8)
2415
121
            return AVERROR_INVALIDDATA;
2416
        /* non_intra_quantiser_matrix */
2417
30.5k
        for (i = 0; i < 64; i++) {
2418
30.0k
            get_bits(gb, 8);
2419
30.0k
        }
2420
470
    }
2421
2422
988
    if (get_bits1(gb)) {
2423
688
        if (get_bits_left(gb) < 64*8)
2424
143
            return AVERROR_INVALIDDATA;
2425
        /* chroma_intra_quantiser_matrix */
2426
35.4k
        for (i = 0; i < 64; i++) {
2427
34.8k
            v = get_bits(gb, 8);
2428
34.8k
            j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
2429
34.8k
            s->chroma_intra_matrix[j] = v;
2430
34.8k
        }
2431
545
    }
2432
2433
845
    if (get_bits1(gb)) {
2434
436
        if (get_bits_left(gb) < 64*8)
2435
29
            return AVERROR_INVALIDDATA;
2436
        /* chroma_non_intra_quantiser_matrix */
2437
26.4k
        for (i = 0; i < 64; i++) {
2438
26.0k
            get_bits(gb, 8);
2439
26.0k
        }
2440
407
    }
2441
2442
816
    next_start_code_studio(gb);
2443
816
    return 0;
2444
845
}
2445
2446
static void extension_and_user_data(MpegEncContext *s, GetBitContext *gb, int id)
2447
14.6k
{
2448
14.6k
    uint32_t startcode;
2449
14.6k
    uint8_t extension_type;
2450
2451
14.6k
    startcode = show_bits_long(gb, 32);
2452
14.6k
    if (startcode == USER_DATA_STARTCODE || startcode == EXT_STARTCODE) {
2453
2454
1.89k
        if ((id == 2 || id == 4) && startcode == EXT_STARTCODE) {
2455
1.75k
            skip_bits_long(gb, 32);
2456
1.75k
            extension_type = get_bits(gb, 4);
2457
1.75k
            if (extension_type == QUANT_MATRIX_EXT_ID)
2458
1.73k
                read_quant_matrix_ext(s, gb);
2459
1.75k
        }
2460
1.89k
    }
2461
14.6k
}
2462
2463
static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb)
2464
3.17k
{
2465
3.17k
    MpegEncContext *s = &ctx->m;
2466
3.17k
    int width, height, aspect_ratio_info;
2467
3.17k
    int bits_per_raw_sample;
2468
3.17k
    int rgb, chroma_format;
2469
2470
    // random_accessible_vol and video_object_type_indication have already
2471
    // been read by the caller decode_vol_header()
2472
3.17k
    skip_bits(gb, 4); /* video_object_layer_verid */
2473
3.17k
    ctx->shape = get_bits(gb, 2); /* video_object_layer_shape */
2474
3.17k
    skip_bits(gb, 4); /* video_object_layer_shape_extension */
2475
3.17k
    skip_bits1(gb); /* progressive_sequence */
2476
3.17k
    if (ctx->shape != RECT_SHAPE) {
2477
257
        avpriv_request_sample(s->avctx, "MPEG-4 Studio profile non rectangular shape");
2478
257
        return AVERROR_PATCHWELCOME;
2479
257
    }
2480
2.92k
    if (ctx->shape != BIN_ONLY_SHAPE) {
2481
2.92k
        rgb = get_bits1(gb); /* rgb_components */
2482
2.92k
        chroma_format = get_bits(gb, 2); /* chroma_format */
2483
2.92k
        if (!chroma_format || chroma_format == CHROMA_420 || (rgb && chroma_format == CHROMA_422)) {
2484
131
            av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n");
2485
131
            return AVERROR_INVALIDDATA;
2486
131
        }
2487
2488
2.79k
        bits_per_raw_sample = get_bits(gb, 4); /* bit_depth */
2489
2.79k
        if (bits_per_raw_sample == 10) {
2490
2.48k
            if (rgb) {
2491
2.25k
                s->avctx->pix_fmt = AV_PIX_FMT_GBRP10;
2492
2.25k
            } else {
2493
233
                s->avctx->pix_fmt = chroma_format == CHROMA_422 ? AV_PIX_FMT_YUV422P10 : AV_PIX_FMT_YUV444P10;
2494
233
            }
2495
2.48k
        } else {
2496
307
            avpriv_request_sample(s->avctx, "MPEG-4 Studio profile bit-depth %u", bits_per_raw_sample);
2497
307
            return AVERROR_PATCHWELCOME;
2498
307
        }
2499
2.48k
        if (rgb != ctx->rgb || s->chroma_format != chroma_format)
2500
131
            s->context_reinit = 1;
2501
2.48k
        s->avctx->bits_per_raw_sample = bits_per_raw_sample;
2502
2.48k
        ctx->rgb = rgb;
2503
2.48k
        s->chroma_format = chroma_format;
2504
2.48k
    }
2505
2.48k
    if (ctx->shape == RECT_SHAPE) {
2506
2.48k
        check_marker(s->avctx, gb, "before video_object_layer_width");
2507
2.48k
        width  = get_bits(gb, 14); /* video_object_layer_width */
2508
2.48k
        check_marker(s->avctx, gb, "before video_object_layer_height");
2509
2.48k
        height = get_bits(gb, 14); /* video_object_layer_height */
2510
2.48k
        check_marker(s->avctx, gb, "after video_object_layer_height");
2511
2512
        /* Do the same check as non-studio profile */
2513
2.48k
        if (width && height) {
2514
2.34k
            if (s->width && s->height &&
2515
2.34k
                (s->width != width || s->height != height))
2516
448
                s->context_reinit = 1;
2517
2.34k
            s->width  = width;
2518
2.34k
            s->height = height;
2519
2.34k
        }
2520
2.48k
    }
2521
2.48k
    aspect_ratio_info = get_bits(gb, 4);
2522
2.48k
    if (aspect_ratio_info == FF_ASPECT_EXTENDED) {
2523
47
        s->avctx->sample_aspect_ratio.num = get_bits(gb, 8);  // par_width
2524
47
        s->avctx->sample_aspect_ratio.den = get_bits(gb, 8);  // par_height
2525
2.43k
    } else {
2526
2.43k
        s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[aspect_ratio_info];
2527
2.43k
    }
2528
2.48k
    skip_bits(gb, 4); /* frame_rate_code */
2529
2.48k
    skip_bits(gb, 15); /* first_half_bit_rate */
2530
2.48k
    check_marker(s->avctx, gb, "after first_half_bit_rate");
2531
2.48k
    skip_bits(gb, 15); /* latter_half_bit_rate */
2532
2.48k
    check_marker(s->avctx, gb, "after latter_half_bit_rate");
2533
2.48k
    skip_bits(gb, 15); /* first_half_vbv_buffer_size */
2534
2.48k
    check_marker(s->avctx, gb, "after first_half_vbv_buffer_size");
2535
2.48k
    skip_bits(gb, 3); /* latter_half_vbv_buffer_size */
2536
2.48k
    skip_bits(gb, 11); /* first_half_vbv_buffer_size */
2537
2.48k
    check_marker(s->avctx, gb, "after first_half_vbv_buffer_size");
2538
2.48k
    skip_bits(gb, 15); /* latter_half_vbv_occupancy */
2539
2.48k
    check_marker(s->avctx, gb, "after latter_half_vbv_occupancy");
2540
2.48k
    s->low_delay  = get_bits1(gb);
2541
2.48k
    s->mpeg_quant = get_bits1(gb); /* mpeg2_stream */
2542
2543
2.48k
    next_start_code_studio(gb);
2544
2.48k
    extension_and_user_data(s, gb, 2);
2545
2546
2.48k
    return 0;
2547
2.92k
}
2548
2549
static int decode_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb)
2550
18.9k
{
2551
18.9k
    MpegEncContext *s = &ctx->m;
2552
18.9k
    int width, height, vo_ver_id, aspect_ratio_info;
2553
2554
    /* vol header */
2555
18.9k
    skip_bits(gb, 1);                   /* random access */
2556
18.9k
    ctx->vo_type = get_bits(gb, 8);
2557
2558
    /* If we are in studio profile (per vo_type), check if its all consistent
2559
     * and if so continue pass control to decode_studio_vol_header().
2560
     * elIf something is inconsistent, error out
2561
     * else continue with (non studio) vol header decpoding.
2562
     */
2563
18.9k
    if (ctx->vo_type == CORE_STUDIO_VO_TYPE ||
2564
18.9k
        ctx->vo_type == SIMPLE_STUDIO_VO_TYPE) {
2565
4.19k
        if (s->avctx->profile != AV_PROFILE_UNKNOWN && s->avctx->profile != AV_PROFILE_MPEG4_SIMPLE_STUDIO)
2566
1.01k
            return AVERROR_INVALIDDATA;
2567
3.17k
        s->studio_profile = 1;
2568
3.17k
        s->avctx->profile = AV_PROFILE_MPEG4_SIMPLE_STUDIO;
2569
3.17k
        return decode_studio_vol_header(ctx, gb);
2570
14.7k
    } else if (s->studio_profile) {
2571
1.40k
        return AVERROR_PATCHWELCOME;
2572
1.40k
    }
2573
2574
13.3k
    if (get_bits1(gb) != 0) {           /* is_ol_id */
2575
5.91k
        vo_ver_id = get_bits(gb, 4);    /* vo_ver_id */
2576
5.91k
        skip_bits(gb, 3);               /* vo_priority */
2577
7.48k
    } else {
2578
7.48k
        vo_ver_id = 1;
2579
7.48k
    }
2580
13.3k
    aspect_ratio_info = get_bits(gb, 4);
2581
13.3k
    if (aspect_ratio_info == FF_ASPECT_EXTENDED) {
2582
511
        s->avctx->sample_aspect_ratio.num = get_bits(gb, 8);  // par_width
2583
511
        s->avctx->sample_aspect_ratio.den = get_bits(gb, 8);  // par_height
2584
12.8k
    } else {
2585
12.8k
        s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[aspect_ratio_info];
2586
12.8k
    }
2587
2588
13.3k
    if ((ctx->vol_control_parameters = get_bits1(gb))) { /* vol control parameter */
2589
4.47k
        int chroma_format = get_bits(gb, 2);
2590
4.47k
        if (chroma_format != CHROMA_420)
2591
3.43k
            av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n");
2592
2593
4.47k
        s->low_delay = get_bits1(gb);
2594
4.47k
        if (get_bits1(gb)) {    /* vbv parameters */
2595
2.69k
            get_bits(gb, 15);   /* first_half_bitrate */
2596
2.69k
            check_marker(s->avctx, gb, "after first_half_bitrate");
2597
2.69k
            get_bits(gb, 15);   /* latter_half_bitrate */
2598
2.69k
            check_marker(s->avctx, gb, "after latter_half_bitrate");
2599
2.69k
            get_bits(gb, 15);   /* first_half_vbv_buffer_size */
2600
2.69k
            check_marker(s->avctx, gb, "after first_half_vbv_buffer_size");
2601
2.69k
            get_bits(gb, 3);    /* latter_half_vbv_buffer_size */
2602
2.69k
            get_bits(gb, 11);   /* first_half_vbv_occupancy */
2603
2.69k
            check_marker(s->avctx, gb, "after first_half_vbv_occupancy");
2604
2.69k
            get_bits(gb, 15);   /* latter_half_vbv_occupancy */
2605
2.69k
            check_marker(s->avctx, gb, "after latter_half_vbv_occupancy");
2606
2.69k
        }
2607
8.92k
    } else {
2608
        /* is setting low delay flag only once the smartest thing to do?
2609
         * low delay detection will not be overridden. */
2610
8.92k
        if (s->picture_number == 0) {
2611
1.05k
            switch (ctx->vo_type) {
2612
171
            case SIMPLE_VO_TYPE:
2613
172
            case ADV_SIMPLE_VO_TYPE:
2614
172
                s->low_delay = 1;
2615
172
                break;
2616
885
            default:
2617
885
                s->low_delay = 0;
2618
1.05k
            }
2619
1.05k
        }
2620
8.92k
    }
2621
2622
13.3k
    ctx->shape = get_bits(gb, 2); /* vol shape */
2623
13.3k
    if (ctx->shape != RECT_SHAPE)
2624
3.77k
        av_log(s->avctx, AV_LOG_ERROR, "only rectangular vol supported\n");
2625
13.3k
    if (ctx->shape == GRAY_SHAPE && vo_ver_id != 1) {
2626
294
        av_log(s->avctx, AV_LOG_ERROR, "Gray shape not supported\n");
2627
294
        skip_bits(gb, 4);  /* video_object_layer_shape_extension */
2628
294
    }
2629
2630
13.3k
    check_marker(s->avctx, gb, "before time_increment_resolution");
2631
2632
13.3k
    s->avctx->framerate.num = get_bits(gb, 16);
2633
13.3k
    if (!s->avctx->framerate.num) {
2634
598
        av_log(s->avctx, AV_LOG_ERROR, "framerate==0\n");
2635
598
        return AVERROR_INVALIDDATA;
2636
598
    }
2637
2638
12.8k
    ctx->time_increment_bits = av_log2(s->avctx->framerate.num - 1) + 1;
2639
12.8k
    if (ctx->time_increment_bits < 1)
2640
0
        ctx->time_increment_bits = 1;
2641
2642
12.8k
    check_marker(s->avctx, gb, "before fixed_vop_rate");
2643
2644
12.8k
    if (get_bits1(gb) != 0)     /* fixed_vop_rate  */
2645
6.75k
        s->avctx->framerate.den = get_bits(gb, ctx->time_increment_bits);
2646
6.05k
    else
2647
6.05k
        s->avctx->framerate.den = 1;
2648
2649
12.8k
    ctx->t_frame = 0;
2650
2651
12.8k
    if (ctx->shape != BIN_ONLY_SHAPE) {
2652
11.9k
        if (ctx->shape == RECT_SHAPE) {
2653
9.26k
            check_marker(s->avctx, gb, "before width");
2654
9.26k
            width = get_bits(gb, 13);
2655
9.26k
            check_marker(s->avctx, gb, "before height");
2656
9.26k
            height = get_bits(gb, 13);
2657
9.26k
            check_marker(s->avctx, gb, "after height");
2658
9.26k
            if (width && height &&  /* they should be non zero but who knows */
2659
9.26k
                !(s->width && s->codec_tag == AV_RL32("MP4S"))) {
2660
4.78k
                if (s->width && s->height &&
2661
4.78k
                    (s->width != width || s->height != height))
2662
2.83k
                    s->context_reinit = 1;
2663
4.78k
                s->width  = width;
2664
4.78k
                s->height = height;
2665
4.78k
            }
2666
9.26k
        }
2667
2668
11.9k
        s->progressive_sequence  =
2669
11.9k
        s->progressive_frame     = get_bits1(gb) ^ 1;
2670
11.9k
        s->interlaced_dct        = 0;
2671
11.9k
        if (!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO))
2672
0
            av_log(s->avctx, AV_LOG_INFO,           /* OBMC Disable */
2673
0
                   "MPEG-4 OBMC not supported (very likely buggy encoder)\n");
2674
11.9k
        if (vo_ver_id == 1)
2675
6.84k
            ctx->vol_sprite_usage = get_bits1(gb);    /* vol_sprite_usage */
2676
5.09k
        else
2677
5.09k
            ctx->vol_sprite_usage = get_bits(gb, 2);  /* vol_sprite_usage */
2678
2679
11.9k
        if (ctx->vol_sprite_usage == STATIC_SPRITE)
2680
2.46k
            av_log(s->avctx, AV_LOG_ERROR, "Static Sprites not supported\n");
2681
11.9k
        if (ctx->vol_sprite_usage == STATIC_SPRITE ||
2682
11.9k
            ctx->vol_sprite_usage == GMC_SPRITE) {
2683
2.73k
            if (ctx->vol_sprite_usage == STATIC_SPRITE) {
2684
2.46k
                skip_bits(gb, 13); // sprite_width
2685
2.46k
                check_marker(s->avctx, gb, "after sprite_width");
2686
2.46k
                skip_bits(gb, 13); // sprite_height
2687
2.46k
                check_marker(s->avctx, gb, "after sprite_height");
2688
2.46k
                skip_bits(gb, 13); // sprite_left
2689
2.46k
                check_marker(s->avctx, gb, "after sprite_left");
2690
2.46k
                skip_bits(gb, 13); // sprite_top
2691
2.46k
                check_marker(s->avctx, gb, "after sprite_top");
2692
2.46k
            }
2693
2.73k
            ctx->num_sprite_warping_points = get_bits(gb, 6);
2694
2.73k
            if (ctx->num_sprite_warping_points > 3) {
2695
1.93k
                av_log(s->avctx, AV_LOG_ERROR,
2696
1.93k
                       "%d sprite_warping_points\n",
2697
1.93k
                       ctx->num_sprite_warping_points);
2698
1.93k
                ctx->num_sprite_warping_points = 0;
2699
1.93k
                return AVERROR_INVALIDDATA;
2700
1.93k
            }
2701
801
            ctx->sprite_warping_accuracy  = get_bits(gb, 2);
2702
801
            ctx->sprite_brightness_change = get_bits1(gb);
2703
801
            if (ctx->vol_sprite_usage == STATIC_SPRITE)
2704
654
                skip_bits1(gb); // low_latency_sprite
2705
801
        }
2706
        // FIXME sadct disable bit if verid!=1 && shape not rect
2707
2708
10.0k
        if (get_bits1(gb) == 1) {                   /* not_8_bit */
2709
2.28k
            ctx->quant_precision = get_bits(gb, 4); /* quant_precision */
2710
2.28k
            if (get_bits(gb, 4) != 8)               /* bits_per_pixel */
2711
2.27k
                av_log(s->avctx, AV_LOG_ERROR, "N-bit not supported\n");
2712
2.28k
            if (ctx->quant_precision != 5)
2713
2.15k
                av_log(s->avctx, AV_LOG_ERROR,
2714
2.15k
                       "quant precision %d\n", ctx->quant_precision);
2715
2.28k
            if (ctx->quant_precision < 3 || ctx->quant_precision > 9)
2716
1.99k
                ctx->quant_precision = 5;
2717
7.71k
        } else {
2718
7.71k
            ctx->quant_precision = 5;
2719
7.71k
        }
2720
2721
        // FIXME a bunch of grayscale shape things
2722
2723
10.0k
        if ((s->mpeg_quant = get_bits1(gb))) { /* vol_quant_type */
2724
3.35k
            int i, v;
2725
2726
3.35k
            mpeg4_load_default_matrices(s);
2727
2728
            /* load custom intra matrix */
2729
3.35k
            if (get_bits1(gb)) {
2730
1.85k
                int last = 0;
2731
16.2k
                for (i = 0; i < 64; i++) {
2732
16.1k
                    int j;
2733
16.1k
                    if (get_bits_left(gb) < 8) {
2734
752
                        av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n");
2735
752
                        return AVERROR_INVALIDDATA;
2736
752
                    }
2737
15.4k
                    v = get_bits(gb, 8);
2738
15.4k
                    if (v == 0)
2739
1.04k
                        break;
2740
2741
14.3k
                    last = v;
2742
14.3k
                    j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
2743
14.3k
                    s->intra_matrix[j]        = last;
2744
14.3k
                    s->chroma_intra_matrix[j] = last;
2745
14.3k
                }
2746
2747
                /* replicate last value */
2748
57.4k
                for (; i < 64; i++) {
2749
56.3k
                    int j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
2750
56.3k
                    s->intra_matrix[j]        = last;
2751
56.3k
                    s->chroma_intra_matrix[j] = last;
2752
56.3k
                }
2753
1.10k
            }
2754
2755
            /* load custom non intra matrix */
2756
2.60k
            if (get_bits1(gb)) {
2757
861
                int last = 0;
2758
7.12k
                for (i = 0; i < 64; i++) {
2759
7.12k
                    int j;
2760
7.12k
                    if (get_bits_left(gb) < 8) {
2761
20
                        av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n");
2762
20
                        return AVERROR_INVALIDDATA;
2763
20
                    }
2764
7.10k
                    v = get_bits(gb, 8);
2765
7.10k
                    if (v == 0)
2766
836
                        break;
2767
2768
6.26k
                    last = v;
2769
6.26k
                    j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
2770
6.26k
                    s->inter_matrix[j]        = v;
2771
6.26k
                    s->chroma_inter_matrix[j] = v;
2772
6.26k
                }
2773
2774
                /* replicate last value */
2775
48.4k
                for (; i < 64; i++) {
2776
47.6k
                    int j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
2777
47.6k
                    s->inter_matrix[j]        = last;
2778
47.6k
                    s->chroma_inter_matrix[j] = last;
2779
47.6k
                }
2780
841
            }
2781
2782
            // FIXME a bunch of grayscale shape things
2783
2.60k
        }
2784
2785
9.22k
        if (vo_ver_id != 1)
2786
3.83k
            s->quarter_sample = get_bits1(gb);
2787
5.39k
        else
2788
5.39k
            s->quarter_sample = 0;
2789
2790
9.22k
        if (get_bits_left(gb) < 4) {
2791
1.02k
            av_log(s->avctx, AV_LOG_ERROR, "VOL Header truncated\n");
2792
1.02k
            return AVERROR_INVALIDDATA;
2793
1.02k
        }
2794
2795
8.20k
        if (!get_bits1(gb)) {
2796
6.13k
            int pos               = get_bits_count(gb);
2797
6.13k
            int estimation_method = get_bits(gb, 2);
2798
6.13k
            if (estimation_method < 2) {
2799
4.70k
                if (!get_bits1(gb)) {
2800
4.03k
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* opaque */
2801
4.03k
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* transparent */
2802
4.03k
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* intra_cae */
2803
4.03k
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* inter_cae */
2804
4.03k
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* no_update */
2805
4.03k
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* upsampling */
2806
4.03k
                }
2807
4.70k
                if (!get_bits1(gb)) {
2808
3.85k
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* intra_blocks */
2809
3.85k
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* inter_blocks */
2810
3.85k
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* inter4v_blocks */
2811
3.85k
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* not coded blocks */
2812
3.85k
                }
2813
4.70k
                if (!check_marker(s->avctx, gb, "in complexity estimation part 1")) {
2814
3.13k
                    skip_bits_long(gb, pos - get_bits_count(gb));
2815
3.13k
                    goto no_cplx_est;
2816
3.13k
                }
2817
1.57k
                if (!get_bits1(gb)) {
2818
1.08k
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* dct_coeffs */
2819
1.08k
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* dct_lines */
2820
1.08k
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* vlc_syms */
2821
1.08k
                    ctx->cplx_estimation_trash_i += 4 * get_bits1(gb);  /* vlc_bits */
2822
1.08k
                }
2823
1.57k
                if (!get_bits1(gb)) {
2824
860
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* apm */
2825
860
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* npm */
2826
860
                    ctx->cplx_estimation_trash_b += 8 * get_bits1(gb);  /* interpolate_mc_q */
2827
860
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* forwback_mc_q */
2828
860
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* halfpel2 */
2829
860
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* halfpel4 */
2830
860
                }
2831
1.57k
                if (!check_marker(s->avctx, gb, "in complexity estimation part 2")) {
2832
1.12k
                    skip_bits_long(gb, pos - get_bits_count(gb));
2833
1.12k
                    goto no_cplx_est;
2834
1.12k
                }
2835
442
                if (estimation_method == 1) {
2836
61
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* sadct */
2837
61
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* qpel */
2838
61
                }
2839
442
            } else
2840
1.42k
                av_log(s->avctx, AV_LOG_ERROR,
2841
1.42k
                       "Invalid Complexity estimation method %d\n",
2842
1.42k
                       estimation_method);
2843
6.13k
        } else {
2844
2845
6.34k
no_cplx_est:
2846
6.34k
            ctx->cplx_estimation_trash_i =
2847
6.34k
            ctx->cplx_estimation_trash_p =
2848
6.34k
            ctx->cplx_estimation_trash_b = 0;
2849
6.34k
        }
2850
2851
8.20k
        ctx->resync_marker = !get_bits1(gb); /* resync_marker_disabled */
2852
2853
8.20k
        s->data_partitioning = get_bits1(gb);
2854
8.20k
        if (s->data_partitioning)
2855
2.67k
            ctx->rvlc = get_bits1(gb);
2856
2857
8.20k
        if (vo_ver_id != 1) {
2858
3.72k
            ctx->new_pred = get_bits1(gb);
2859
3.72k
            if (ctx->new_pred) {
2860
1.06k
                av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n");
2861
1.06k
                skip_bits(gb, 2); /* requested upstream message type */
2862
1.06k
                skip_bits1(gb);   /* newpred segment type */
2863
1.06k
            }
2864
3.72k
            if (get_bits1(gb)) // reduced_res_vop
2865
1.31k
                av_log(s->avctx, AV_LOG_ERROR,
2866
1.31k
                       "reduced resolution VOP not supported\n");
2867
4.48k
        } else {
2868
4.48k
            ctx->new_pred = 0;
2869
4.48k
        }
2870
2871
8.20k
        ctx->scalability = get_bits1(gb);
2872
2873
8.20k
        if (ctx->scalability) {
2874
2.45k
            GetBitContext bak = *gb;
2875
2.45k
            int h_sampling_factor_n;
2876
2.45k
            int h_sampling_factor_m;
2877
2.45k
            int v_sampling_factor_n;
2878
2.45k
            int v_sampling_factor_m;
2879
2880
2.45k
            skip_bits1(gb);    // hierarchy_type
2881
2.45k
            skip_bits(gb, 4);  /* ref_layer_id */
2882
2.45k
            skip_bits1(gb);    /* ref_layer_sampling_dir */
2883
2.45k
            h_sampling_factor_n = get_bits(gb, 5);
2884
2.45k
            h_sampling_factor_m = get_bits(gb, 5);
2885
2.45k
            v_sampling_factor_n = get_bits(gb, 5);
2886
2.45k
            v_sampling_factor_m = get_bits(gb, 5);
2887
2.45k
            ctx->enhancement_type = get_bits1(gb);
2888
2889
2.45k
            if (h_sampling_factor_n == 0 || h_sampling_factor_m == 0 ||
2890
2.45k
                v_sampling_factor_n == 0 || v_sampling_factor_m == 0) {
2891
                /* illegal scalability header (VERY broken encoder),
2892
                 * trying to workaround */
2893
2.07k
                ctx->scalability = 0;
2894
2.07k
                *gb            = bak;
2895
2.07k
            } else
2896
376
                av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n");
2897
2898
            // bin shape stuff FIXME
2899
2.45k
        }
2900
8.20k
    }
2901
2902
9.07k
    if (s->avctx->debug&FF_DEBUG_PICT_INFO) {
2903
0
        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",
2904
0
               s->avctx->framerate.den, s->avctx->framerate.num,
2905
0
               ctx->time_increment_bits,
2906
0
               ctx->quant_precision,
2907
0
               s->progressive_sequence,
2908
0
               s->low_delay,
2909
0
               ctx->scalability ? "scalability " :"" , s->quarter_sample ? "qpel " : "",
2910
0
               s->data_partitioning ? "partition " : "", ctx->rvlc ? "rvlc " : ""
2911
0
        );
2912
0
    }
2913
2914
9.07k
    return 0;
2915
12.8k
}
2916
2917
/**
2918
 * Decode the user data stuff in the header.
2919
 * Also initializes divx/xvid/lavc_version/build.
2920
 */
2921
static int decode_user_data(Mpeg4DecContext *ctx, GetBitContext *gb)
2922
1.10k
{
2923
1.10k
    MpegEncContext *s = &ctx->m;
2924
1.10k
    char buf[256];
2925
1.10k
    int i;
2926
1.10k
    int e;
2927
1.10k
    int ver = 0, build = 0, ver2 = 0, ver3 = 0;
2928
1.10k
    char last;
2929
2930
14.3k
    for (i = 0; i < 255 && get_bits_count(gb) < gb->size_in_bits; i++) {
2931
14.3k
        if (show_bits(gb, 23) == 0)
2932
1.09k
            break;
2933
13.2k
        buf[i] = get_bits(gb, 8);
2934
13.2k
    }
2935
1.10k
    buf[i] = 0;
2936
2937
    /* divx detection */
2938
1.10k
    e = sscanf(buf, "DivX%dBuild%d%c", &ver, &build, &last);
2939
1.10k
    if (e < 2)
2940
1.10k
        e = sscanf(buf, "DivX%db%d%c", &ver, &build, &last);
2941
1.10k
    if (e >= 2) {
2942
19
        ctx->divx_version = ver;
2943
19
        ctx->divx_build   = build;
2944
19
        s->divx_packed  = e == 3 && last == 'p';
2945
19
    }
2946
2947
    /* libavcodec detection */
2948
1.10k
    e = sscanf(buf, "FFmpe%*[^b]b%d", &build) + 3;
2949
1.10k
    if (e != 4)
2950
1.10k
        e = sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build);
2951
1.10k
    if (e != 4) {
2952
1.10k
        e = sscanf(buf, "Lavc%d.%d.%d", &ver, &ver2, &ver3) + 1;
2953
1.10k
        if (e > 1) {
2954
1
            if (ver > 0xFFU || ver2 > 0xFFU || ver3 > 0xFFU) {
2955
0
                av_log(s->avctx, AV_LOG_WARNING,
2956
0
                     "Unknown Lavc version string encountered, %d.%d.%d; "
2957
0
                     "clamping sub-version values to 8-bits.\n",
2958
0
                     ver, ver2, ver3);
2959
0
            }
2960
1
            build = ((ver & 0xFF) << 16) + ((ver2 & 0xFF) << 8) + (ver3 & 0xFF);
2961
1
        }
2962
1.10k
    }
2963
1.10k
    if (e != 4) {
2964
1.10k
        if (strcmp(buf, "ffmpeg") == 0)
2965
41
            ctx->lavc_build = 4600;
2966
1.10k
    }
2967
1.10k
    if (e == 4)
2968
1
        ctx->lavc_build = build;
2969
2970
    /* Xvid detection */
2971
1.10k
    e = sscanf(buf, "XviD%d", &build);
2972
1.10k
    if (e == 1)
2973
16
        ctx->xvid_build = build;
2974
2975
1.10k
    return 0;
2976
1.10k
}
2977
2978
int ff_mpeg4_workaround_bugs(AVCodecContext *avctx)
2979
0
{
2980
0
    Mpeg4DecContext *ctx = avctx->priv_data;
2981
0
    MpegEncContext *s = &ctx->m;
2982
2983
0
    if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) {
2984
0
        if (s->codec_tag        == AV_RL32("XVID") ||
2985
0
            s->codec_tag        == AV_RL32("XVIX") ||
2986
0
            s->codec_tag        == AV_RL32("RMP4") ||
2987
0
            s->codec_tag        == AV_RL32("ZMP4") ||
2988
0
            s->codec_tag        == AV_RL32("SIPP"))
2989
0
            ctx->xvid_build = 0;
2990
0
    }
2991
2992
0
    if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1)
2993
0
        if (s->codec_tag == AV_RL32("DIVX") && ctx->vo_type == 0 &&
2994
0
            ctx->vol_control_parameters == 0)
2995
0
            ctx->divx_version = 400;  // divx 4
2996
2997
0
    if (ctx->xvid_build >= 0 && ctx->divx_version >= 0) {
2998
0
        ctx->divx_version =
2999
0
        ctx->divx_build   = -1;
3000
0
    }
3001
3002
0
    if (s->workaround_bugs & FF_BUG_AUTODETECT) {
3003
0
        if (s->codec_tag == AV_RL32("XVIX"))
3004
0
            s->workaround_bugs |= FF_BUG_XVID_ILACE;
3005
3006
0
        if (s->codec_tag == AV_RL32("UMP4"))
3007
0
            s->workaround_bugs |= FF_BUG_UMP4;
3008
3009
0
        if (ctx->divx_version >= 500 && ctx->divx_build < 1814)
3010
0
            s->workaround_bugs |= FF_BUG_QPEL_CHROMA;
3011
3012
0
        if (ctx->divx_version > 502 && ctx->divx_build < 1814)
3013
0
            s->workaround_bugs |= FF_BUG_QPEL_CHROMA2;
3014
3015
0
        if (ctx->xvid_build <= 3U)
3016
0
            s->padding_bug_score = 256 * 256 * 256 * 64;
3017
3018
0
        if (ctx->xvid_build <= 1U)
3019
0
            s->workaround_bugs |= FF_BUG_QPEL_CHROMA;
3020
3021
0
        if (ctx->xvid_build <= 12U)
3022
0
            s->workaround_bugs |= FF_BUG_EDGE;
3023
3024
0
        if (ctx->xvid_build <= 32U)
3025
0
            s->workaround_bugs |= FF_BUG_DC_CLIP;
3026
3027
0
#define SET_QPEL_FUNC(postfix1, postfix2)                           \
3028
0
    s->qdsp.put_        ## postfix1 = ff_put_        ## postfix2;   \
3029
0
    s->qdsp.put_no_rnd_ ## postfix1 = ff_put_no_rnd_ ## postfix2;   \
3030
0
    s->qdsp.avg_        ## postfix1 = ff_avg_        ## postfix2;
3031
3032
0
        if (ctx->lavc_build < 4653U)
3033
0
            s->workaround_bugs |= FF_BUG_STD_QPEL;
3034
3035
0
        if (ctx->lavc_build < 4655U)
3036
0
            s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE;
3037
3038
0
        if (ctx->lavc_build < 4670U)
3039
0
            s->workaround_bugs |= FF_BUG_EDGE;
3040
3041
0
        if (ctx->lavc_build <= 4712U)
3042
0
            s->workaround_bugs |= FF_BUG_DC_CLIP;
3043
3044
0
        if ((ctx->lavc_build&0xFF) >= 100) {
3045
0
            if (ctx->lavc_build > 3621476 && ctx->lavc_build < 3752552 &&
3046
0
               (ctx->lavc_build < 3752037 || ctx->lavc_build > 3752191) // 3.2.1+
3047
0
            )
3048
0
                s->workaround_bugs |= FF_BUG_IEDGE;
3049
0
        }
3050
3051
0
        if (ctx->divx_version >= 0)
3052
0
            s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE;
3053
0
        if (ctx->divx_version == 501 && ctx->divx_build == 20020416)
3054
0
            s->padding_bug_score = 256 * 256 * 256 * 64;
3055
3056
0
        if (ctx->divx_version < 500U)
3057
0
            s->workaround_bugs |= FF_BUG_EDGE;
3058
3059
0
        if (ctx->divx_version >= 0)
3060
0
            s->workaround_bugs |= FF_BUG_HPEL_CHROMA;
3061
0
    }
3062
3063
0
    if (s->workaround_bugs & FF_BUG_STD_QPEL) {
3064
0
        SET_QPEL_FUNC(qpel_pixels_tab[0][5], qpel16_mc11_old_c)
3065
0
        SET_QPEL_FUNC(qpel_pixels_tab[0][7], qpel16_mc31_old_c)
3066
0
        SET_QPEL_FUNC(qpel_pixels_tab[0][9], qpel16_mc12_old_c)
3067
0
        SET_QPEL_FUNC(qpel_pixels_tab[0][11], qpel16_mc32_old_c)
3068
0
        SET_QPEL_FUNC(qpel_pixels_tab[0][13], qpel16_mc13_old_c)
3069
0
        SET_QPEL_FUNC(qpel_pixels_tab[0][15], qpel16_mc33_old_c)
3070
3071
0
        SET_QPEL_FUNC(qpel_pixels_tab[1][5], qpel8_mc11_old_c)
3072
0
        SET_QPEL_FUNC(qpel_pixels_tab[1][7], qpel8_mc31_old_c)
3073
0
        SET_QPEL_FUNC(qpel_pixels_tab[1][9], qpel8_mc12_old_c)
3074
0
        SET_QPEL_FUNC(qpel_pixels_tab[1][11], qpel8_mc32_old_c)
3075
0
        SET_QPEL_FUNC(qpel_pixels_tab[1][13], qpel8_mc13_old_c)
3076
0
        SET_QPEL_FUNC(qpel_pixels_tab[1][15], qpel8_mc33_old_c)
3077
0
    }
3078
3079
0
    if (avctx->debug & FF_DEBUG_BUGS)
3080
0
        av_log(s->avctx, AV_LOG_DEBUG,
3081
0
               "bugs: %X lavc_build:%d xvid_build:%d divx_version:%d divx_build:%d %s\n",
3082
0
               s->workaround_bugs, ctx->lavc_build, ctx->xvid_build,
3083
0
               ctx->divx_version, ctx->divx_build, s->divx_packed ? "p" : "");
3084
3085
0
    if (CONFIG_MPEG4_DECODER && ctx->xvid_build >= 0 &&
3086
0
        avctx->idct_algo == FF_IDCT_AUTO) {
3087
0
        avctx->idct_algo = FF_IDCT_XVID;
3088
0
        ff_mpv_idct_init(s);
3089
0
        return 1;
3090
0
    }
3091
3092
0
    return 0;
3093
0
}
3094
3095
static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb,
3096
                             int parse_only)
3097
39.8k
{
3098
39.8k
    MpegEncContext *s = &ctx->m;
3099
39.8k
    int time_incr, time_increment;
3100
39.8k
    int64_t pts;
3101
3102
39.8k
    s->mcsel       = 0;
3103
39.8k
    s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I;        /* pict type: I = 0 , P = 1 */
3104
39.8k
    if (s->pict_type == AV_PICTURE_TYPE_B && s->low_delay &&
3105
39.8k
        ctx->vol_control_parameters == 0 && !(s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)) {
3106
67
        av_log(s->avctx, AV_LOG_ERROR, "low_delay flag set incorrectly, clearing it\n");
3107
67
        s->low_delay = 0;
3108
67
    }
3109
3110
39.8k
    s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B;
3111
39.8k
    if (s->partitioned_frame)
3112
7.83k
        s->decode_mb = mpeg4_decode_partitioned_mb;
3113
32.0k
    else
3114
32.0k
        s->decode_mb = mpeg4_decode_mb;
3115
3116
39.8k
    time_incr = 0;
3117
128k
    while (get_bits1(gb) != 0)
3118
88.1k
        time_incr++;
3119
3120
39.8k
    check_marker(s->avctx, gb, "before time_increment");
3121
3122
39.8k
    if (ctx->time_increment_bits == 0 ||
3123
39.8k
        !(show_bits(gb, ctx->time_increment_bits + 1) & 1)) {
3124
23.0k
        av_log(s->avctx, AV_LOG_WARNING,
3125
23.0k
               "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);
3126
3127
23.0k
        for (ctx->time_increment_bits = 1;
3128
309k
             ctx->time_increment_bits < 16;
3129
292k
             ctx->time_increment_bits++) {
3130
292k
            if (s->pict_type == AV_PICTURE_TYPE_P ||
3131
292k
                (s->pict_type == AV_PICTURE_TYPE_S &&
3132
277k
                 ctx->vol_sprite_usage == GMC_SPRITE)) {
3133
17.7k
                if ((show_bits(gb, ctx->time_increment_bits + 6) & 0x37) == 0x30)
3134
700
                    break;
3135
275k
            } else if ((show_bits(gb, ctx->time_increment_bits + 5) & 0x1F) == 0x18)
3136
5.56k
                break;
3137
292k
        }
3138
3139
23.0k
        av_log(s->avctx, AV_LOG_WARNING,
3140
23.0k
               "time_increment_bits set to %d bits, based on bitstream analysis\n", ctx->time_increment_bits);
3141
23.0k
    }
3142
3143
39.8k
    if (IS_3IV1)
3144
0
        time_increment = get_bits1(gb);        // FIXME investigate further
3145
39.8k
    else
3146
39.8k
        time_increment = get_bits(gb, ctx->time_increment_bits);
3147
3148
39.8k
    if (s->pict_type != AV_PICTURE_TYPE_B) {
3149
30.1k
        s->last_time_base = s->time_base;
3150
30.1k
        s->time_base     += time_incr;
3151
30.1k
        s->time = s->time_base * (int64_t)s->avctx->framerate.num + time_increment;
3152
30.1k
        if (s->workaround_bugs & FF_BUG_UMP4) {
3153
0
            if (s->time < s->last_non_b_time) {
3154
                /* header is not mpeg-4-compatible, broken encoder,
3155
                 * trying to workaround */
3156
0
                s->time_base++;
3157
0
                s->time += s->avctx->framerate.num;
3158
0
            }
3159
0
        }
3160
30.1k
        s->pp_time         = s->time - s->last_non_b_time;
3161
30.1k
        s->last_non_b_time = s->time;
3162
30.1k
    } else {
3163
9.67k
        s->time    = (s->last_time_base + time_incr) * (int64_t)s->avctx->framerate.num + time_increment;
3164
9.67k
        s->pb_time = s->pp_time - (s->last_non_b_time - s->time);
3165
9.67k
        if (s->pp_time <= s->pb_time ||
3166
9.67k
            s->pp_time <= s->pp_time - s->pb_time ||
3167
9.67k
            s->pp_time <= 0) {
3168
            /* messed up order, maybe after seeking? skipping current B-frame */
3169
5.09k
            return FRAME_SKIPPED;
3170
5.09k
        }
3171
4.58k
        ff_mpeg4_init_direct_mv(s);
3172
3173
4.58k
        if (ctx->t_frame == 0)
3174
1.80k
            ctx->t_frame = s->pb_time;
3175
4.58k
        if (ctx->t_frame == 0)
3176
0
            ctx->t_frame = 1;  // 1/0 protection
3177
4.58k
        s->pp_field_time = (ROUNDED_DIV(s->last_non_b_time, ctx->t_frame) -
3178
4.58k
                            ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;
3179
4.58k
        s->pb_field_time = (ROUNDED_DIV(s->time, ctx->t_frame) -
3180
4.58k
                            ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;
3181
4.58k
        if (s->pp_field_time <= s->pb_field_time || s->pb_field_time <= 1) {
3182
3.59k
            s->pb_field_time = 2;
3183
3.59k
            s->pp_field_time = 4;
3184
3.59k
            if (!s->progressive_sequence)
3185
1.34k
                return FRAME_SKIPPED;
3186
3.59k
        }
3187
4.58k
    }
3188
3189
33.4k
    if (s->avctx->framerate.den)
3190
32.7k
        pts = ROUNDED_DIV(s->time, s->avctx->framerate.den);
3191
644
    else
3192
644
        pts = AV_NOPTS_VALUE;
3193
33.4k
    ff_dlog(s->avctx, "MPEG4 PTS: %"PRId64"\n", pts);
3194
3195
33.4k
    check_marker(s->avctx, gb, "before vop_coded");
3196
3197
    /* vop coded */
3198
33.4k
    if (get_bits1(gb) != 1) {
3199
15.8k
        if (s->avctx->debug & FF_DEBUG_PICT_INFO)
3200
0
            av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n");
3201
15.8k
        return FRAME_SKIPPED;
3202
15.8k
    }
3203
17.5k
    if (ctx->new_pred)
3204
2.44k
        decode_new_pred(ctx, gb);
3205
3206
17.5k
    if (ctx->shape != BIN_ONLY_SHAPE &&
3207
17.5k
                    (s->pict_type == AV_PICTURE_TYPE_P ||
3208
16.2k
                     (s->pict_type == AV_PICTURE_TYPE_S &&
3209
13.4k
                      ctx->vol_sprite_usage == GMC_SPRITE))) {
3210
        /* rounding type for motion estimation */
3211
4.35k
        s->no_rounding = get_bits1(gb);
3212
13.2k
    } else {
3213
13.2k
        s->no_rounding = 0;
3214
13.2k
    }
3215
    // FIXME reduced res stuff
3216
3217
17.5k
    if (ctx->shape != RECT_SHAPE) {
3218
4.99k
        if (ctx->vol_sprite_usage != 1 || s->pict_type != AV_PICTURE_TYPE_I) {
3219
4.21k
            skip_bits(gb, 13);  /* width */
3220
4.21k
            check_marker(s->avctx, gb, "after width");
3221
4.21k
            skip_bits(gb, 13);  /* height */
3222
4.21k
            check_marker(s->avctx, gb, "after height");
3223
4.21k
            skip_bits(gb, 13);  /* hor_spat_ref */
3224
4.21k
            check_marker(s->avctx, gb, "after hor_spat_ref");
3225
4.21k
            skip_bits(gb, 13);  /* ver_spat_ref */
3226
4.21k
        }
3227
4.99k
        skip_bits1(gb);         /* change_CR_disable */
3228
3229
4.99k
        if (get_bits1(gb) != 0)
3230
1.95k
            skip_bits(gb, 8);   /* constant_alpha_value */
3231
4.99k
    }
3232
3233
    // FIXME complexity estimation stuff
3234
3235
17.5k
    if (ctx->shape != BIN_ONLY_SHAPE) {
3236
16.2k
        skip_bits_long(gb, ctx->cplx_estimation_trash_i);
3237
16.2k
        if (s->pict_type != AV_PICTURE_TYPE_I)
3238
12.0k
            skip_bits_long(gb, ctx->cplx_estimation_trash_p);
3239
16.2k
        if (s->pict_type == AV_PICTURE_TYPE_B)
3240
2.27k
            skip_bits_long(gb, ctx->cplx_estimation_trash_b);
3241
3242
16.2k
        if (get_bits_left(gb) < 3) {
3243
3.10k
            av_log(s->avctx, AV_LOG_ERROR, "Header truncated\n");
3244
3.10k
            return AVERROR_INVALIDDATA;
3245
3.10k
        }
3246
13.1k
        ctx->intra_dc_threshold = ff_mpeg4_dc_threshold[get_bits(gb, 3)];
3247
13.1k
        if (!s->progressive_sequence) {
3248
3.61k
            s->top_field_first = get_bits1(gb);
3249
3.61k
            s->alternate_scan  = get_bits1(gb);
3250
3.61k
        } else
3251
9.49k
            s->alternate_scan = 0;
3252
13.1k
    }
3253
14.4k
    if (s->alternate_scan) {
3254
1.60k
        ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable,   ff_alternate_vertical_scan);
3255
1.60k
        ff_permute_scantable(s->permutated_intra_h_scantable, ff_alternate_vertical_scan,
3256
1.60k
                             s->idsp.idct_permutation);
3257
12.8k
    } else {
3258
12.8k
        ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable,   ff_zigzag_direct);
3259
12.8k
        ff_permute_scantable(s->permutated_intra_h_scantable, ff_alternate_horizontal_scan,
3260
12.8k
                             s->idsp.idct_permutation);
3261
12.8k
    }
3262
14.4k
    ff_permute_scantable(s->permutated_intra_v_scantable, ff_alternate_vertical_scan,
3263
14.4k
                         s->idsp.idct_permutation);
3264
3265
    /* Skip at this point when only parsing since the remaining
3266
     * data is not useful for a parser and requires the
3267
     * sprite_trajectory VLC to be initialized. */
3268
14.4k
    if (parse_only)
3269
14.4k
        goto end;
3270
3271
0
    if (s->pict_type == AV_PICTURE_TYPE_S) {
3272
0
        if((ctx->vol_sprite_usage == STATIC_SPRITE ||
3273
0
            ctx->vol_sprite_usage == GMC_SPRITE)) {
3274
0
            if (mpeg4_decode_sprite_trajectory(ctx, gb) < 0)
3275
0
                return AVERROR_INVALIDDATA;
3276
0
            if (ctx->sprite_brightness_change)
3277
0
                av_log(s->avctx, AV_LOG_ERROR,
3278
0
                    "sprite_brightness_change not supported\n");
3279
0
            if (ctx->vol_sprite_usage == STATIC_SPRITE)
3280
0
                av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n");
3281
0
        } else {
3282
0
            memset(ctx->sprite_offset, 0, sizeof(ctx->sprite_offset));
3283
0
            memset(ctx->sprite_delta,  0, sizeof(ctx->sprite_delta));
3284
0
        }
3285
0
    }
3286
3287
0
    if (ctx->shape != BIN_ONLY_SHAPE) {
3288
0
        s->chroma_qscale = s->qscale = get_bits(gb, ctx->quant_precision);
3289
0
        if (s->qscale == 0) {
3290
0
            av_log(s->avctx, AV_LOG_ERROR,
3291
0
                   "Error, header damaged or not MPEG-4 header (qscale=0)\n");
3292
0
            return AVERROR_INVALIDDATA;  // makes no sense to continue, as there is nothing left from the image then
3293
0
        }
3294
3295
0
        if (s->pict_type != AV_PICTURE_TYPE_I) {
3296
0
            s->f_code = get_bits(gb, 3);        /* fcode_for */
3297
0
            if (s->f_code == 0) {
3298
0
                av_log(s->avctx, AV_LOG_ERROR,
3299
0
                       "Error, header damaged or not MPEG-4 header (f_code=0)\n");
3300
0
                s->f_code = 1;
3301
0
                return AVERROR_INVALIDDATA;  // makes no sense to continue, as there is nothing left from the image then
3302
0
            }
3303
0
        } else
3304
0
            s->f_code = 1;
3305
3306
0
        if (s->pict_type == AV_PICTURE_TYPE_B) {
3307
0
            s->b_code = get_bits(gb, 3);
3308
0
            if (s->b_code == 0) {
3309
0
                av_log(s->avctx, AV_LOG_ERROR,
3310
0
                       "Error, header damaged or not MPEG4 header (b_code=0)\n");
3311
0
                s->b_code=1;
3312
0
                return AVERROR_INVALIDDATA; // makes no sense to continue, as the MV decoding will break very quickly
3313
0
            }
3314
0
        } else
3315
0
            s->b_code = 1;
3316
3317
0
        if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
3318
0
            av_log(s->avctx, AV_LOG_DEBUG,
3319
0
                   "qp:%d fc:%d,%d %c size:%d pro:%d alt:%d top:%d %cpel part:%d resync:%d w:%d a:%d rnd:%d vot:%d%s dc:%d ce:%d/%d/%d time:%"PRId64" tincr:%d\n",
3320
0
                   s->qscale, s->f_code, s->b_code,
3321
0
                   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')),
3322
0
                   gb->size_in_bits,s->progressive_sequence, s->alternate_scan,
3323
0
                   s->top_field_first, s->quarter_sample ? 'q' : 'h',
3324
0
                   s->data_partitioning, ctx->resync_marker,
3325
0
                   ctx->num_sprite_warping_points, ctx->sprite_warping_accuracy,
3326
0
                   1 - s->no_rounding, ctx->vo_type,
3327
0
                   ctx->vol_control_parameters ? " VOLC" : " ", ctx->intra_dc_threshold,
3328
0
                   ctx->cplx_estimation_trash_i, ctx->cplx_estimation_trash_p,
3329
0
                   ctx->cplx_estimation_trash_b,
3330
0
                   s->time,
3331
0
                   time_increment
3332
0
                  );
3333
0
        }
3334
3335
0
        if (!ctx->scalability) {
3336
0
            if (ctx->shape != RECT_SHAPE && s->pict_type != AV_PICTURE_TYPE_I)
3337
0
                skip_bits1(gb);  // vop shape coding type
3338
0
        } else {
3339
0
            if (ctx->enhancement_type) {
3340
0
                int load_backward_shape = get_bits1(gb);
3341
0
                if (load_backward_shape)
3342
0
                    av_log(s->avctx, AV_LOG_ERROR,
3343
0
                           "load backward shape isn't supported\n");
3344
0
            }
3345
0
            skip_bits(gb, 2);  // ref_select_code
3346
0
        }
3347
0
    }
3348
3349
14.4k
end:
3350
    /* detect buggy encoders which don't set the low_delay flag
3351
     * (divx4/xvid/opendivx). Note we cannot detect divx5 without B-frames
3352
     * easily (although it's buggy too) */
3353
14.4k
    if (ctx->vo_type == 0 && ctx->vol_control_parameters == 0 &&
3354
14.4k
        ctx->divx_version == -1 && s->picture_number == 0) {
3355
0
        av_log(s->avctx, AV_LOG_WARNING,
3356
0
               "looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n");
3357
0
        s->low_delay = 1;
3358
0
    }
3359
3360
14.4k
    s->picture_number++;  // better than pic number==0 always ;)
3361
3362
    // FIXME add short header support
3363
14.4k
    s->y_dc_scale_table = ff_mpeg4_y_dc_scale_table;
3364
14.4k
    s->c_dc_scale_table = ff_mpeg4_c_dc_scale_table;
3365
3366
14.4k
    if (s->workaround_bugs & FF_BUG_EDGE) {
3367
0
        s->h_edge_pos = s->width;
3368
0
        s->v_edge_pos = s->height;
3369
0
    }
3370
14.4k
    return 0;
3371
0
}
3372
3373
static void decode_smpte_tc(Mpeg4DecContext *ctx, GetBitContext *gb)
3374
11.9k
{
3375
11.9k
    MpegEncContext *s = &ctx->m;
3376
3377
11.9k
    skip_bits(gb, 16); /* Time_code[63..48] */
3378
11.9k
    check_marker(s->avctx, gb, "after Time_code[63..48]");
3379
11.9k
    skip_bits(gb, 16); /* Time_code[47..32] */
3380
11.9k
    check_marker(s->avctx, gb, "after Time_code[47..32]");
3381
11.9k
    skip_bits(gb, 16); /* Time_code[31..16] */
3382
11.9k
    check_marker(s->avctx, gb, "after Time_code[31..16]");
3383
11.9k
    skip_bits(gb, 16); /* Time_code[15..0] */
3384
11.9k
    check_marker(s->avctx, gb, "after Time_code[15..0]");
3385
11.9k
    skip_bits(gb, 4); /* reserved_bits */
3386
11.9k
}
3387
3388
/**
3389
 * Decode the next studio vop header.
3390
 * @return <0 if something went wrong
3391
 */
3392
static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
3393
18.5k
{
3394
18.5k
    MpegEncContext *s = &ctx->m;
3395
3396
18.5k
    if (get_bits_left(gb) <= 32)
3397
6.58k
        return 0;
3398
3399
11.9k
    s->partitioned_frame = 0;
3400
11.9k
    s->interlaced_dct = 0;
3401
11.9k
    s->decode_mb = mpeg4_decode_studio_mb;
3402
3403
11.9k
    decode_smpte_tc(ctx, gb);
3404
3405
11.9k
    skip_bits(gb, 10); /* temporal_reference */
3406
11.9k
    skip_bits(gb, 2); /* vop_structure */
3407
11.9k
    s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */
3408
11.9k
    if (get_bits1(gb)) { /* vop_coded */
3409
3.29k
        skip_bits1(gb); /* top_field_first */
3410
3.29k
        skip_bits1(gb); /* repeat_first_field */
3411
3.29k
        s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */
3412
3.29k
    }
3413
3414
11.9k
    if (s->pict_type == AV_PICTURE_TYPE_I) {
3415
7.34k
        if (get_bits1(gb))
3416
1.09k
            reset_studio_dc_predictors(s);
3417
7.34k
    }
3418
3419
11.9k
    if (ctx->shape != BIN_ONLY_SHAPE) {
3420
11.6k
        s->alternate_scan = get_bits1(gb);
3421
11.6k
        s->frame_pred_frame_dct = get_bits1(gb);
3422
11.6k
        s->dct_precision = get_bits(gb, 2);
3423
11.6k
        s->intra_dc_precision = get_bits(gb, 2);
3424
11.6k
        s->q_scale_type = get_bits1(gb);
3425
11.6k
    }
3426
3427
11.9k
    ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable,
3428
11.9k
                      s->alternate_scan ? ff_alternate_vertical_scan : ff_zigzag_direct);
3429
3430
11.9k
    mpeg4_load_default_matrices(s);
3431
3432
11.9k
    next_start_code_studio(gb);
3433
11.9k
    extension_and_user_data(s, gb, 4);
3434
3435
11.9k
    return 0;
3436
18.5k
}
3437
3438
static int decode_studiovisualobject(Mpeg4DecContext *ctx, GetBitContext *gb)
3439
386
{
3440
386
    MpegEncContext *s = &ctx->m;
3441
386
    int visual_object_type;
3442
3443
386
    skip_bits(gb, 4); /* visual_object_verid */
3444
386
    visual_object_type = get_bits(gb, 4);
3445
386
    if (visual_object_type != VOT_VIDEO_ID) {
3446
197
        avpriv_request_sample(s->avctx, "VO type %u", visual_object_type);
3447
197
        return AVERROR_PATCHWELCOME;
3448
197
    }
3449
3450
189
    next_start_code_studio(gb);
3451
189
    extension_and_user_data(s, gb, 1);
3452
3453
189
    return 0;
3454
386
}
3455
3456
/**
3457
 * Decode MPEG-4 headers.
3458
 *
3459
 * @param  header If set the absence of a VOP is not treated as error; otherwise, it is treated as such.
3460
 * @param  parse_only If set, things only relevant to a decoder may be skipped;
3461
 *                    furthermore, the VLC tables may be uninitialized.
3462
 * @return <0 if an error occurred
3463
 *         FRAME_SKIPPED if a not coded VOP is found
3464
 *         0 else
3465
 */
3466
int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb,
3467
                                   int header, int parse_only)
3468
75.4k
{
3469
75.4k
    MpegEncContext *s = &ctx->m;
3470
75.4k
    unsigned startcode, v;
3471
75.4k
    int ret;
3472
75.4k
    int vol = 0;
3473
3474
    /* search next start code */
3475
75.4k
    align_get_bits(gb);
3476
3477
    // If we have not switched to studio profile than we also did not switch bps
3478
    // that means something else (like a previous instance) outside set bps which
3479
    // would be inconsistant with the currect state, thus reset it
3480
75.4k
    if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8)
3481
51.5k
        s->avctx->bits_per_raw_sample = 0;
3482
3483
75.4k
    if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) {
3484
0
        skip_bits(gb, 24);
3485
0
        if (get_bits(gb, 8) == 0xF0)
3486
0
            goto end;
3487
0
    }
3488
3489
75.4k
    startcode = 0xff;
3490
10.5M
    for (;;) {
3491
10.5M
        if (get_bits_count(gb) >= gb->size_in_bits) {
3492
8.12k
            if (gb->size_in_bits == 8 &&
3493
8.12k
                (ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) {
3494
75
                av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits);
3495
75
                return FRAME_SKIPPED;  // divx bug
3496
8.04k
            } else if (header && get_bits_count(gb) == gb->size_in_bits) {
3497
644
                return 0; // ordinary return value for parsing of extradata
3498
644
            } else
3499
7.40k
                return AVERROR_INVALIDDATA;  // end of stream
3500
8.12k
        }
3501
3502
        /* use the bits after the test */
3503
10.5M
        v = get_bits(gb, 8);
3504
10.5M
        startcode = ((startcode << 8) | v) & 0xffffffff;
3505
3506
10.5M
        if ((startcode & 0xFFFFFF00) != 0x100)
3507
10.4M
            continue;  // no startcode
3508
3509
172k
        if (s->avctx->debug & FF_DEBUG_STARTCODE) {
3510
0
            const char *name;
3511
0
            if (startcode <= 0x11F)
3512
0
                name = "Video Object Start";
3513
0
            else if (startcode <= 0x12F)
3514
0
                name = "Video Object Layer Start";
3515
0
            else if (startcode <= 0x13F)
3516
0
                name = "Reserved";
3517
0
            else if (startcode <= 0x15F)
3518
0
                name = "FGS bp start";
3519
0
            else if (startcode <= 0x1AF)
3520
0
                name = "Reserved";
3521
0
            else if (startcode == 0x1B0)
3522
0
                name = "Visual Object Seq Start";
3523
0
            else if (startcode == 0x1B1)
3524
0
                name = "Visual Object Seq End";
3525
0
            else if (startcode == 0x1B2)
3526
0
                name = "User Data";
3527
0
            else if (startcode == 0x1B3)
3528
0
                name = "Group of VOP start";
3529
0
            else if (startcode == 0x1B4)
3530
0
                name = "Video Session Error";
3531
0
            else if (startcode == 0x1B5)
3532
0
                name = "Visual Object Start";
3533
0
            else if (startcode == 0x1B6)
3534
0
                name = "Video Object Plane start";
3535
0
            else if (startcode == 0x1B7)
3536
0
                name = "slice start";
3537
0
            else if (startcode == 0x1B8)
3538
0
                name = "extension start";
3539
0
            else if (startcode == 0x1B9)
3540
0
                name = "fgs start";
3541
0
            else if (startcode == 0x1BA)
3542
0
                name = "FBA Object start";
3543
0
            else if (startcode == 0x1BB)
3544
0
                name = "FBA Object Plane start";
3545
0
            else if (startcode == 0x1BC)
3546
0
                name = "Mesh Object start";
3547
0
            else if (startcode == 0x1BD)
3548
0
                name = "Mesh Object Plane start";
3549
0
            else if (startcode == 0x1BE)
3550
0
                name = "Still Texture Object start";
3551
0
            else if (startcode == 0x1BF)
3552
0
                name = "Texture Spatial Layer start";
3553
0
            else if (startcode == 0x1C0)
3554
0
                name = "Texture SNR Layer start";
3555
0
            else if (startcode == 0x1C1)
3556
0
                name = "Texture Tile start";
3557
0
            else if (startcode == 0x1C2)
3558
0
                name = "Texture Shape Layer start";
3559
0
            else if (startcode == 0x1C3)
3560
0
                name = "stuffing start";
3561
0
            else if (startcode <= 0x1C5)
3562
0
                name = "Reserved";
3563
0
            else if (startcode <= 0x1FF)
3564
0
                name = "System start";
3565
0
            av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X %s at %d\n",
3566
0
                   startcode, name, get_bits_count(gb));
3567
0
        }
3568
3569
172k
        if (startcode >= 0x120 && startcode <= 0x12F) {
3570
22.3k
            if (vol) {
3571
3.34k
                av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n");
3572
3.34k
                continue;
3573
3.34k
            }
3574
18.9k
            vol++;
3575
18.9k
            if ((ret = decode_vol_header(ctx, gb)) < 0)
3576
7.43k
                return ret;
3577
150k
        } else if (startcode == USER_DATA_STARTCODE) {
3578
1.10k
            decode_user_data(ctx, gb);
3579
149k
        } else if (startcode == GOP_STARTCODE) {
3580
1.66k
            mpeg4_decode_gop_header(s, gb);
3581
147k
        } else if (startcode == VOS_STARTCODE) {
3582
1.11k
            int profile, level;
3583
1.11k
            mpeg4_decode_profile_level(s, gb, &profile, &level);
3584
1.11k
            if (profile == AV_PROFILE_MPEG4_SIMPLE_STUDIO &&
3585
1.11k
                (level > 0 && level < 9)) {
3586
4
                s->studio_profile = 1;
3587
4
                next_start_code_studio(gb);
3588
4
                extension_and_user_data(s, gb, 0);
3589
1.11k
            } else if (s->studio_profile) {
3590
322
                avpriv_request_sample(s->avctx, "Mix of studio and non studio profile");
3591
322
                return AVERROR_PATCHWELCOME;
3592
322
            }
3593
793
            s->avctx->profile = profile;
3594
793
            s->avctx->level   = level;
3595
146k
        } else if (startcode == VISUAL_OBJ_STARTCODE) {
3596
1.84k
            if (s->studio_profile) {
3597
386
                if ((ret = decode_studiovisualobject(ctx, gb)) < 0)
3598
197
                    return ret;
3599
386
            } else
3600
1.46k
                mpeg4_decode_visual_object(s, gb);
3601
144k
        } else if (startcode == VOP_STARTCODE) {
3602
59.4k
            break;
3603
59.4k
        }
3604
3605
102k
        align_get_bits(gb);
3606
102k
        startcode = 0xff;
3607
102k
    }
3608
3609
59.4k
end:
3610
59.4k
    if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)
3611
0
        s->low_delay = 1;
3612
59.4k
    s->avctx->has_b_frames = !s->low_delay;
3613
3614
59.4k
    if (s->studio_profile) {
3615
19.5k
        if (!s->avctx->bits_per_raw_sample) {
3616
991
            av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n");
3617
991
            return AVERROR_INVALIDDATA;
3618
991
        }
3619
18.5k
        return decode_studio_vop_header(ctx, gb);
3620
19.5k
    } else
3621
39.8k
        return decode_vop_header(ctx, gb, parse_only);
3622
59.4k
}
3623
3624
int ff_mpeg4_frame_end(AVCodecContext *avctx, const uint8_t *buf, int buf_size)
3625
0
{
3626
0
    Mpeg4DecContext *ctx = avctx->priv_data;
3627
0
    MpegEncContext    *s = &ctx->m;
3628
3629
    /* divx 5.01+ bitstream reorder stuff */
3630
    /* Since this clobbers the input buffer and hwaccel codecs still need the
3631
     * data during hwaccel->end_frame we should not do this any earlier */
3632
0
    if (s->divx_packed) {
3633
0
        int current_pos     = s->gb.buffer == s->bitstream_buffer ? 0 : (get_bits_count(&s->gb) >> 3);
3634
0
        int startcode_found = 0;
3635
3636
0
        if (buf_size - current_pos > 7) {
3637
3638
0
            int i;
3639
0
            for (i = current_pos; i < buf_size - 4; i++)
3640
3641
0
                if (buf[i]     == 0 &&
3642
0
                    buf[i + 1] == 0 &&
3643
0
                    buf[i + 2] == 1 &&
3644
0
                    buf[i + 3] == 0xB6) {
3645
0
                    startcode_found = !(buf[i + 4] & 0x40);
3646
0
                    break;
3647
0
                }
3648
0
        }
3649
3650
0
        if (startcode_found) {
3651
0
            if (!ctx->showed_packed_warning) {
3652
0
                av_log(s->avctx, AV_LOG_INFO, "Video uses a non-standard and "
3653
0
                       "wasteful way to store B-frames ('packed B-frames'). "
3654
0
                       "Consider using the mpeg4_unpack_bframes bitstream filter without encoding but stream copy to fix it.\n");
3655
0
                ctx->showed_packed_warning = 1;
3656
0
            }
3657
0
            av_fast_padded_malloc(&s->bitstream_buffer,
3658
0
                           &s->allocated_bitstream_buffer_size,
3659
0
                           buf_size - current_pos);
3660
0
            if (!s->bitstream_buffer) {
3661
0
                s->bitstream_buffer_size = 0;
3662
0
                return AVERROR(ENOMEM);
3663
0
            }
3664
0
            memcpy(s->bitstream_buffer, buf + current_pos,
3665
0
                   buf_size - current_pos);
3666
0
            s->bitstream_buffer_size = buf_size - current_pos;
3667
0
        }
3668
0
    }
3669
3670
0
    return 0;
3671
0
}
3672
3673
#if CONFIG_MPEG4_DECODER
3674
#if HAVE_THREADS
3675
static int mpeg4_update_thread_context(AVCodecContext *dst,
3676
                                       const AVCodecContext *src)
3677
0
{
3678
0
    Mpeg4DecContext *s = dst->priv_data;
3679
0
    const Mpeg4DecContext *s1 = src->priv_data;
3680
0
    int init = s->m.context_initialized;
3681
3682
0
    int ret = ff_mpeg_update_thread_context(dst, src);
3683
3684
0
    if (ret < 0)
3685
0
        return ret;
3686
3687
    // copy all the necessary fields explicitly
3688
0
    s->time_increment_bits       = s1->time_increment_bits;
3689
0
    s->shape                     = s1->shape;
3690
0
    s->vol_sprite_usage          = s1->vol_sprite_usage;
3691
0
    s->sprite_brightness_change  = s1->sprite_brightness_change;
3692
0
    s->sprite_warping_accuracy   = s1->sprite_warping_accuracy;
3693
0
    s->num_sprite_warping_points = s1->num_sprite_warping_points;
3694
0
    s->m.data_partitioning       = s1->m.data_partitioning;
3695
0
    s->rvlc                      = s1->rvlc;
3696
0
    s->resync_marker             = s1->resync_marker;
3697
0
    s->t_frame                   = s1->t_frame;
3698
0
    s->new_pred                  = s1->new_pred;
3699
0
    s->enhancement_type          = s1->enhancement_type;
3700
0
    s->scalability               = s1->scalability;
3701
0
    s->intra_dc_threshold        = s1->intra_dc_threshold;
3702
0
    s->divx_version              = s1->divx_version;
3703
0
    s->divx_build                = s1->divx_build;
3704
0
    s->xvid_build                = s1->xvid_build;
3705
0
    s->lavc_build                = s1->lavc_build;
3706
0
    s->vo_type                   = s1->vo_type;
3707
0
    s->showed_packed_warning     = s1->showed_packed_warning;
3708
0
    s->vol_control_parameters    = s1->vol_control_parameters;
3709
0
    s->cplx_estimation_trash_i   = s1->cplx_estimation_trash_i;
3710
0
    s->cplx_estimation_trash_p   = s1->cplx_estimation_trash_p;
3711
0
    s->cplx_estimation_trash_b   = s1->cplx_estimation_trash_b;
3712
0
    s->rgb                       = s1->rgb;
3713
3714
0
    memcpy(s->sprite_shift, s1->sprite_shift, sizeof(s1->sprite_shift));
3715
0
    memcpy(s->sprite_traj,  s1->sprite_traj,  sizeof(s1->sprite_traj));
3716
3717
0
    if (!init && s1->xvid_build >= 0)
3718
0
        ff_xvid_idct_init(&s->m.idsp, dst);
3719
3720
0
    return 0;
3721
0
}
3722
3723
static int mpeg4_update_thread_context_for_user(AVCodecContext *dst,
3724
                                                const AVCodecContext *src)
3725
0
{
3726
0
    MpegEncContext *m = dst->priv_data;
3727
0
    const MpegEncContext *m1 = src->priv_data;
3728
3729
0
    m->quarter_sample = m1->quarter_sample;
3730
0
    m->divx_packed    = m1->divx_packed;
3731
3732
0
    return 0;
3733
0
}
3734
#endif
3735
3736
static av_cold void mpeg4_init_static(void)
3737
0
{
3738
0
    static uint8_t mpeg4_rvlc_rl_tables[2][2][2 * MAX_RUN + MAX_LEVEL + 3];
3739
0
    static VLCElem vlc_buf[6498];
3740
0
    VLCInitState state = VLC_INIT_STATE(vlc_buf);
3741
3742
0
    VLC_INIT_STATIC_TABLE_FROM_LENGTHS(studio_luma_dc, STUDIO_INTRA_BITS, 19,
3743
0
                                       &ff_mpeg4_studio_dc_luma[0][1], 2,
3744
0
                                       &ff_mpeg4_studio_dc_luma[0][0], 2, 1,
3745
0
                                       0, 0);
3746
3747
0
    VLC_INIT_STATIC_TABLE_FROM_LENGTHS(studio_chroma_dc, STUDIO_INTRA_BITS, 19,
3748
0
                                       &ff_mpeg4_studio_dc_chroma[0][1], 2,
3749
0
                                       &ff_mpeg4_studio_dc_chroma[0][0], 2, 1,
3750
0
                                       0, 0);
3751
3752
0
    for (unsigned i = 0; i < 12; i++) {
3753
0
        studio_intra_tab[i] =
3754
0
            ff_vlc_init_tables_from_lengths(&state, STUDIO_INTRA_BITS, 24,
3755
0
                                            &ff_mpeg4_studio_intra[i][0][1], 2,
3756
0
                                            &ff_mpeg4_studio_intra[i][0][0], 2, 1,
3757
0
                                            0, 0);
3758
0
    }
3759
3760
0
    ff_mpeg4_init_rl_intra();
3761
0
    ff_rl_init(&ff_rvlc_rl_inter, mpeg4_rvlc_rl_tables[0]);
3762
0
    ff_rl_init(&ff_rvlc_rl_intra, mpeg4_rvlc_rl_tables[1]);
3763
0
    INIT_FIRST_VLC_RL(ff_mpeg4_rl_intra, 554);
3764
0
    VLC_INIT_RL(ff_rvlc_rl_inter, 1072);
3765
0
    INIT_FIRST_VLC_RL(ff_rvlc_rl_intra, 1072);
3766
0
    VLC_INIT_STATIC_TABLE(dc_lum, DC_VLC_BITS, 10 /* 13 */,
3767
0
                          &ff_mpeg4_DCtab_lum[0][1], 2, 1,
3768
0
                          &ff_mpeg4_DCtab_lum[0][0], 2, 1, 0);
3769
0
    VLC_INIT_STATIC_TABLE(dc_chrom, DC_VLC_BITS, 10 /* 13 */,
3770
0
                          &ff_mpeg4_DCtab_chrom[0][1], 2, 1,
3771
0
                          &ff_mpeg4_DCtab_chrom[0][0], 2, 1, 0);
3772
0
    VLC_INIT_STATIC_TABLE_FROM_LENGTHS(sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
3773
0
                                       ff_sprite_trajectory_lens, 1,
3774
0
                                       NULL, 0, 0, 0, 0);
3775
0
    VLC_INIT_STATIC_SPARSE_TABLE(mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
3776
0
                                 &ff_mb_type_b_tab[0][1], 2, 1,
3777
0
                                 &ff_mb_type_b_tab[0][0], 2, 1,
3778
0
                                 mb_type_b_map, 2, 2, 0);
3779
0
}
3780
3781
static av_cold int decode_init(AVCodecContext *avctx)
3782
0
{
3783
0
    static AVOnce init_static_once = AV_ONCE_INIT;
3784
0
    Mpeg4DecContext *ctx = avctx->priv_data;
3785
0
    MpegEncContext *s = &ctx->m;
3786
0
    int ret;
3787
3788
0
    ctx->divx_version =
3789
0
    ctx->divx_build   =
3790
0
    ctx->xvid_build   =
3791
0
    ctx->lavc_build   = -1;
3792
3793
0
    if ((ret = ff_h263_decode_init(avctx)) < 0)
3794
0
        return ret;
3795
3796
0
    s->h263_pred = 1;
3797
0
    s->low_delay = 0; /* default, might be overridden in the vol header during header parsing */
3798
0
    s->decode_mb = mpeg4_decode_mb;
3799
0
    ctx->time_increment_bits = 4; /* default value for broken headers */
3800
0
    ctx->quant_precision     = 5;
3801
3802
0
    avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
3803
3804
0
    ff_qpeldsp_init(&s->qdsp);
3805
0
    ff_mpeg4videodsp_init(&ctx->mdsp);
3806
3807
0
    ff_thread_once(&init_static_once, mpeg4_init_static);
3808
3809
    /* Must be after initializing the MPEG-4 static tables */
3810
0
    if (avctx->extradata_size && !avctx->internal->is_copy) {
3811
0
        GetBitContext gb;
3812
3813
0
        if (init_get_bits8(&gb, avctx->extradata, avctx->extradata_size) >= 0)
3814
0
            ff_mpeg4_decode_picture_header(ctx, &gb, 1, 0);
3815
0
    }
3816
3817
0
    return 0;
3818
0
}
3819
3820
#define OFFSET(x) offsetof(MpegEncContext, x)
3821
#define FLAGS AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY
3822
static const AVOption mpeg4_options[] = {
3823
    {"quarter_sample", "1/4 subpel MC", OFFSET(quarter_sample), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, FLAGS},
3824
    {"divx_packed", "divx style packed b frames", OFFSET(divx_packed), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, FLAGS},
3825
    {NULL}
3826
};
3827
3828
static const AVClass mpeg4_class = {
3829
    .class_name = "MPEG4 Video Decoder",
3830
    .item_name  = av_default_item_name,
3831
    .option     = mpeg4_options,
3832
    .version    = LIBAVUTIL_VERSION_INT,
3833
};
3834
3835
const FFCodec ff_mpeg4_decoder = {
3836
    .p.name                = "mpeg4",
3837
    CODEC_LONG_NAME("MPEG-4 part 2"),
3838
    .p.type                = AVMEDIA_TYPE_VIDEO,
3839
    .p.id                  = AV_CODEC_ID_MPEG4,
3840
    .priv_data_size        = sizeof(Mpeg4DecContext),
3841
    .init                  = decode_init,
3842
    FF_CODEC_DECODE_CB(ff_h263_decode_frame),
3843
    .close                 = ff_mpv_decode_close,
3844
    .p.capabilities        = AV_CODEC_CAP_DRAW_HORIZ_BAND | AV_CODEC_CAP_DR1 |
3845
                             AV_CODEC_CAP_DELAY | AV_CODEC_CAP_FRAME_THREADS,
3846
    .caps_internal         = FF_CODEC_CAP_INIT_CLEANUP |
3847
                             FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM,
3848
    .flush                 = ff_mpeg_flush,
3849
    .p.max_lowres          = 3,
3850
    .p.profiles            = NULL_IF_CONFIG_SMALL(ff_mpeg4_video_profiles),
3851
    UPDATE_THREAD_CONTEXT(mpeg4_update_thread_context),
3852
    UPDATE_THREAD_CONTEXT_FOR_USER(mpeg4_update_thread_context_for_user),
3853
    .p.priv_class = &mpeg4_class,
3854
    .hw_configs            = (const AVCodecHWConfigInternal *const []) {
3855
#if CONFIG_MPEG4_NVDEC_HWACCEL
3856
                               HWACCEL_NVDEC(mpeg4),
3857
#endif
3858
#if CONFIG_MPEG4_VAAPI_HWACCEL
3859
                               HWACCEL_VAAPI(mpeg4),
3860
#endif
3861
#if CONFIG_MPEG4_VDPAU_HWACCEL
3862
                               HWACCEL_VDPAU(mpeg4),
3863
#endif
3864
#if CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL
3865
                               HWACCEL_VIDEOTOOLBOX(mpeg4),
3866
#endif
3867
                               NULL
3868
                           },
3869
};
3870
#endif /* CONFIG_MPEG4_DECODER */