Coverage Report

Created: 2026-02-14 06:59

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ffmpeg/libavcodec/mpeg12dec.c
Line
Count
Source
1
/*
2
 * MPEG-1/2 decoder
3
 * Copyright (c) 2000, 2001 Fabrice Bellard
4
 * Copyright (c) 2002-2013 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
/**
24
 * @file
25
 * MPEG-1/2 decoder
26
 */
27
28
#include "config_components.h"
29
30
#define UNCHECKED_BITSTREAM_READER 1
31
#include <inttypes.h>
32
#include <stdatomic.h>
33
34
#include "libavutil/attributes.h"
35
#include "libavutil/emms.h"
36
#include "libavutil/imgutils.h"
37
#include "libavutil/internal.h"
38
#include "libavutil/mem_internal.h"
39
#include "libavutil/reverse.h"
40
#include "libavutil/stereo3d.h"
41
#include "libavutil/timecode.h"
42
43
#include "avcodec.h"
44
#include "codec_internal.h"
45
#include "decode.h"
46
#include "error_resilience.h"
47
#include "get_bits.h"
48
#include "hwaccel_internal.h"
49
#include "hwconfig.h"
50
#include "idctdsp.h"
51
#include "mpeg_er.h"
52
#include "mpeg12.h"
53
#include "mpeg12data.h"
54
#include "mpeg12dec.h"
55
#include "mpegutils.h"
56
#include "mpegvideo.h"
57
#include "mpegvideodata.h"
58
#include "mpegvideodec.h"
59
#include "profiles.h"
60
#include "startcode.h"
61
62
351k
#define A53_MAX_CC_COUNT 2000
63
64
enum Mpeg2ClosedCaptionsFormat {
65
    CC_FORMAT_AUTO,
66
    CC_FORMAT_A53_PART4,
67
    CC_FORMAT_SCTE20,
68
    CC_FORMAT_DVD,
69
    CC_FORMAT_DISH
70
};
71
72
typedef struct Mpeg12SliceContext {
73
    MPVContext c;
74
    GetBitContext gb;
75
76
    int last_dc[3];                ///< last DC values
77
78
    DECLARE_ALIGNED_32(int16_t, block)[12][64];
79
} Mpeg12SliceContext;
80
81
typedef struct Mpeg1Context {
82
    Mpeg12SliceContext slice;
83
    AVPanScan pan_scan;         /* some temporary storage for the panscan */
84
    enum AVStereo3DType stereo3d_type;
85
    int has_stereo3d;
86
    AVBufferRef *a53_buf_ref;
87
    enum Mpeg2ClosedCaptionsFormat cc_format;
88
    uint8_t afd;
89
    int has_afd;
90
    int slice_count;
91
    unsigned aspect_ratio_info;
92
    int save_progressive_seq, save_chroma_format;
93
    AVRational frame_rate_ext;  /* MPEG-2 specific framerate modificator */
94
    unsigned frame_rate_index;
95
    int sync;                   /* Did we reach a sync point like a GOP/SEQ/KEYFrame? */
96
    int closed_gop;
97
    int tmpgexs;
98
    int first_slice;
99
    int extradata_decoded;
100
    int vbv_delay;
101
    int64_t bit_rate;
102
    int64_t timecode_frame_start;  /*< GOP timecode frame start number, in non drop frame format */
103
} Mpeg1Context;
104
105
/* as H.263, but only 17 codes */
106
static int mpeg_decode_motion(Mpeg12SliceContext *const s, int fcode, int pred)
107
3.07M
{
108
3.07M
    int code, sign, val, shift;
109
110
3.07M
    code = get_vlc2(&s->gb, ff_mv_vlc, MV_VLC_BITS, 2);
111
3.07M
    if (code == 0)
112
1.65M
        return pred;
113
1.42M
    if (code < 0)
114
137k
        return 0xffff;
115
116
1.28M
    sign  = get_bits1(&s->gb);
117
1.28M
    shift = fcode - 1;
118
1.28M
    val   = code;
119
1.28M
    if (shift) {
120
531k
        val  = (val - 1) << shift;
121
531k
        val |= get_bits(&s->gb, shift);
122
531k
        val++;
123
531k
    }
124
1.28M
    if (sign)
125
648k
        val = -val;
126
1.28M
    val += pred;
127
128
    /* modulo decoding */
129
1.28M
    return sign_extend(val, 5 + shift);
130
1.42M
}
131
132
12.4M
#define MAX_INDEX (64 - 1)
133
#define check_scantable_index(ctx, x)                                         \
134
2.74M
    do {                                                                      \
135
2.74M
        if ((x) > MAX_INDEX) {                                                \
136
210k
            av_log(ctx->c.avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n",   \
137
210k
                   ctx->c.mb_x, ctx->c.mb_y);                                 \
138
210k
            return AVERROR_INVALIDDATA;                                       \
139
210k
        }                                                                     \
140
2.74M
    } while (0)
141
142
static inline int mpeg1_decode_block_inter(Mpeg12SliceContext *const s,
143
                                           int16_t *block, int n)
144
1.22M
{
145
1.22M
    int level, i, j, run;
146
1.22M
    const uint8_t *const scantable = s->c.intra_scantable.permutated;
147
1.22M
    const uint16_t *quant_matrix = s->c.inter_matrix;
148
1.22M
    const int qscale             = s->c.qscale;
149
150
1.22M
    {
151
1.22M
        OPEN_READER(re, &s->gb);
152
1.22M
        i = -1;
153
        // special case for first coefficient, no need to add second VLC table
154
1.22M
        UPDATE_CACHE(re, &s->gb);
155
1.22M
        if (((int32_t) GET_CACHE(re, &s->gb)) < 0) {
156
774k
            level = (3 * qscale * quant_matrix[0]) >> 5;
157
774k
            level = (level - 1) | 1;
158
774k
            if (GET_CACHE(re, &s->gb) & 0x40000000)
159
413k
                level = -level;
160
774k
            block[0] = level;
161
774k
            i++;
162
774k
            SKIP_BITS(re, &s->gb, 2);
163
774k
            if (((int32_t) GET_CACHE(re, &s->gb)) <= (int32_t) 0xBFFFFFFF)
164
275k
                goto end;
165
774k
        }
166
        /* now quantify & encode AC coefficients */
167
5.21M
        for (;;) {
168
5.21M
            GET_RL_VLC(level, run, re, &s->gb, ff_mpeg1_rl_vlc,
169
5.21M
                       TEX_VLC_BITS, 2, 0);
170
171
5.21M
            if (level != 0) {
172
5.05M
                i += run;
173
5.05M
                if (i > MAX_INDEX)
174
94.8k
                    break;
175
4.95M
                j = scantable[i];
176
4.95M
                level = ((level * 2 + 1) * qscale * quant_matrix[j]) >> 5;
177
4.95M
                level = (level - 1) | 1;
178
4.95M
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) -
179
4.95M
                        SHOW_SBITS(re, &s->gb, 1);
180
4.95M
                SKIP_BITS(re, &s->gb, 1);
181
4.95M
            } else {
182
                /* escape */
183
160k
                run = SHOW_UBITS(re, &s->gb, 6) + 1;
184
160k
                LAST_SKIP_BITS(re, &s->gb, 6);
185
160k
                UPDATE_CACHE(re, &s->gb);
186
160k
                level = SHOW_SBITS(re, &s->gb, 8);
187
160k
                SKIP_BITS(re, &s->gb, 8);
188
160k
                if (level == -128) {
189
13.0k
                    level = SHOW_UBITS(re, &s->gb, 8) - 256;
190
13.0k
                    SKIP_BITS(re, &s->gb, 8);
191
147k
                } else if (level == 0) {
192
64.6k
                    level = SHOW_UBITS(re, &s->gb, 8);
193
64.6k
                    SKIP_BITS(re, &s->gb, 8);
194
64.6k
                }
195
160k
                i += run;
196
160k
                if (i > MAX_INDEX)
197
2.79k
                    break;
198
158k
                j = scantable[i];
199
158k
                if (level < 0) {
200
49.4k
                    level = -level;
201
49.4k
                    level = ((level * 2 + 1) * qscale * quant_matrix[j]) >> 5;
202
49.4k
                    level = (level - 1) | 1;
203
49.4k
                    level = -level;
204
108k
                } else {
205
108k
                    level = ((level * 2 + 1) * qscale * quant_matrix[j]) >> 5;
206
108k
                    level = (level - 1) | 1;
207
108k
                }
208
158k
            }
209
210
5.11M
            block[j] = level;
211
5.11M
            if (((int32_t) GET_CACHE(re, &s->gb)) <= (int32_t) 0xBFFFFFFF)
212
853k
                break;
213
4.26M
            UPDATE_CACHE(re, &s->gb);
214
4.26M
        }
215
1.22M
end:
216
1.22M
        LAST_SKIP_BITS(re, &s->gb, 2);
217
1.22M
        CLOSE_READER(re, &s->gb);
218
1.22M
    }
219
220
1.22M
    check_scantable_index(s, i);
221
222
1.12M
    s->c.block_last_index[n] = i;
223
1.12M
    return 0;
224
1.22M
}
225
226
static inline int mpeg2_decode_block_non_intra(Mpeg12SliceContext *const s,
227
                                               int16_t *block, int n)
228
920k
{
229
920k
    int level, i, j, run;
230
920k
    const uint8_t *const scantable = s->c.intra_scantable.permutated;
231
920k
    const uint16_t *quant_matrix;
232
920k
    const int qscale = s->c.qscale;
233
920k
    int mismatch;
234
235
920k
    mismatch = 1;
236
237
920k
    {
238
920k
        OPEN_READER(re, &s->gb);
239
920k
        i = -1;
240
920k
        if (n < 4)
241
627k
            quant_matrix = s->c.inter_matrix;
242
292k
        else
243
292k
            quant_matrix = s->c.chroma_inter_matrix;
244
245
        // Special case for first coefficient, no need to add second VLC table.
246
920k
        UPDATE_CACHE(re, &s->gb);
247
920k
        if (((int32_t) GET_CACHE(re, &s->gb)) < 0) {
248
498k
            level = (3 * qscale * quant_matrix[0]) >> 5;
249
498k
            if (GET_CACHE(re, &s->gb) & 0x40000000)
250
313k
                level = -level;
251
498k
            block[0]  = level;
252
498k
            mismatch ^= level;
253
498k
            i++;
254
498k
            SKIP_BITS(re, &s->gb, 2);
255
498k
            if (((int32_t) GET_CACHE(re, &s->gb)) <= (int32_t) 0xBFFFFFFF)
256
123k
                goto end;
257
498k
        }
258
259
        /* now quantify & encode AC coefficients */
260
2.68M
        for (;;) {
261
2.68M
            GET_RL_VLC(level, run, re, &s->gb, ff_mpeg1_rl_vlc,
262
2.68M
                       TEX_VLC_BITS, 2, 0);
263
264
2.68M
            if (level != 0) {
265
2.54M
                i += run;
266
2.54M
                if (i > MAX_INDEX)
267
72.4k
                    break;
268
2.46M
                j = scantable[i];
269
2.46M
                level = ((level * 2 + 1) * qscale * quant_matrix[j]) >> 5;
270
2.46M
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) -
271
2.46M
                        SHOW_SBITS(re, &s->gb, 1);
272
2.46M
                SKIP_BITS(re, &s->gb, 1);
273
2.46M
            } else {
274
                /* escape */
275
143k
                run = SHOW_UBITS(re, &s->gb, 6) + 1;
276
143k
                LAST_SKIP_BITS(re, &s->gb, 6);
277
143k
                UPDATE_CACHE(re, &s->gb);
278
143k
                level = SHOW_SBITS(re, &s->gb, 12);
279
143k
                SKIP_BITS(re, &s->gb, 12);
280
281
143k
                i += run;
282
143k
                if (i > MAX_INDEX)
283
1.70k
                    break;
284
141k
                j = scantable[i];
285
141k
                if (level < 0) {
286
38.3k
                    level = ((-level * 2 + 1) * qscale * quant_matrix[j]) >> 5;
287
38.3k
                    level = -level;
288
103k
                } else {
289
103k
                    level = ((level * 2 + 1) * qscale * quant_matrix[j]) >> 5;
290
103k
                }
291
141k
            }
292
293
2.61M
            mismatch ^= level;
294
2.61M
            block[j]  = level;
295
2.61M
            if (((int32_t) GET_CACHE(re, &s->gb)) <= (int32_t) 0xBFFFFFFF)
296
722k
                break;
297
1.88M
            UPDATE_CACHE(re, &s->gb);
298
1.88M
        }
299
920k
end:
300
920k
        LAST_SKIP_BITS(re, &s->gb, 2);
301
920k
        CLOSE_READER(re, &s->gb);
302
920k
    }
303
0
    block[63] ^= (mismatch & 1);
304
305
920k
    check_scantable_index(s, i);
306
307
846k
    s->c.block_last_index[n] = i;
308
846k
    return 0;
309
920k
}
310
311
static inline int mpeg2_decode_block_intra(Mpeg12SliceContext *const s,
312
                                           int16_t *block, int n)
313
594k
{
314
594k
    int level, dc, diff, i, j, run;
315
594k
    int component;
316
594k
    const RL_VLC_ELEM *rl_vlc;
317
594k
    const uint8_t *const scantable = s->c.intra_scantable.permutated;
318
594k
    const uint16_t *quant_matrix;
319
594k
    const int qscale = s->c.qscale;
320
594k
    int mismatch;
321
322
    /* DC coefficient */
323
594k
    if (n < 4) {
324
370k
        quant_matrix = s->c.intra_matrix;
325
370k
        component    = 0;
326
370k
    } else {
327
224k
        quant_matrix = s->c.chroma_intra_matrix;
328
224k
        component    = (n & 1) + 1;
329
224k
    }
330
594k
    diff = decode_dc(&s->gb, component);
331
594k
    dc  = s->last_dc[component];
332
594k
    dc += diff;
333
594k
    s->last_dc[component] = dc;
334
594k
    block[0] = dc * (1 << (3 - s->c.intra_dc_precision));
335
594k
    ff_tlog(s->c.avctx, "dc=%d\n", block[0]);
336
594k
    mismatch = block[0] ^ 1;
337
594k
    i = 0;
338
594k
    if (s->c.intra_vlc_format)
339
57.7k
        rl_vlc = ff_mpeg2_rl_vlc;
340
536k
    else
341
536k
        rl_vlc = ff_mpeg1_rl_vlc;
342
343
594k
    {
344
594k
        OPEN_READER(re, &s->gb);
345
        /* now quantify & encode AC coefficients */
346
2.32M
        for (;;) {
347
2.32M
            UPDATE_CACHE(re, &s->gb);
348
2.32M
            GET_RL_VLC(level, run, re, &s->gb, rl_vlc,
349
2.32M
                       TEX_VLC_BITS, 2, 0);
350
351
2.32M
            if (level == 127) {
352
555k
                break;
353
1.77M
            } else if (level != 0) {
354
1.63M
                i += run;
355
1.63M
                if (i > MAX_INDEX)
356
35.6k
                    break;
357
1.59M
                j = scantable[i];
358
1.59M
                level = (level * qscale * quant_matrix[j]) >> 4;
359
1.59M
                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) -
360
1.59M
                        SHOW_SBITS(re, &s->gb, 1);
361
1.59M
                LAST_SKIP_BITS(re, &s->gb, 1);
362
1.59M
            } else {
363
                /* escape */
364
139k
                run = SHOW_UBITS(re, &s->gb, 6) + 1;
365
139k
                SKIP_BITS(re, &s->gb, 6);
366
139k
                level = SHOW_SBITS(re, &s->gb, 12);
367
139k
                LAST_SKIP_BITS(re, &s->gb, 12);
368
139k
                i += run;
369
139k
                if (i > MAX_INDEX)
370
3.09k
                    break;
371
135k
                j = scantable[i];
372
135k
                if (level < 0) {
373
9.54k
                    level = (-level * qscale * quant_matrix[j]) >> 4;
374
9.54k
                    level = -level;
375
126k
                } else {
376
126k
                    level = (level * qscale * quant_matrix[j]) >> 4;
377
126k
                }
378
135k
            }
379
380
1.73M
            mismatch ^= level;
381
1.73M
            block[j]  = level;
382
1.73M
        }
383
594k
        CLOSE_READER(re, &s->gb);
384
594k
    }
385
594k
    block[63] ^= mismatch & 1;
386
387
594k
    check_scantable_index(s, i);
388
389
555k
    return 0;
390
594k
}
391
392
static inline int get_dmv(Mpeg12SliceContext *const s)
393
241k
{
394
241k
    if (get_bits1(&s->gb))
395
151k
        return 1 - (get_bits1(&s->gb) << 1);
396
90.1k
    else
397
90.1k
        return 0;
398
241k
}
399
400
/* motion type (for MPEG-2) */
401
75.0k
#define MT_FIELD 1
402
2.03M
#define MT_FRAME 2
403
#define MT_16X8  2
404
74.8k
#define MT_DMV   3
405
406
static int mpeg_decode_mb(Mpeg12SliceContext *const s, int *mb_skip_run)
407
3.46M
{
408
3.46M
    int i, j, k, cbp, val, mb_type, motion_type;
409
3.46M
    const int mb_block_count = 4 + (1 << s->c.chroma_format);
410
3.46M
    int ret;
411
412
3.46M
    ff_tlog(s->c.avctx, "decode_mb: x=%d y=%d\n", s->c.mb_x, s->c.mb_y);
413
414
3.46M
    av_assert2(s->c.mb_skipped == 0);
415
416
3.46M
    if ((*mb_skip_run)-- != 0) {
417
1.79M
        if (s->c.pict_type == AV_PICTURE_TYPE_P) {
418
1.34M
            s->c.mb_skipped = 1;
419
1.34M
            s->c.cur_pic.mb_type[s->c.mb_x + s->c.mb_y * s->c.mb_stride] =
420
1.34M
                MB_TYPE_SKIP | MB_TYPE_FORWARD_MV | MB_TYPE_16x16;
421
1.34M
        } else {
422
458k
            int mb_type;
423
424
458k
            if (s->c.mb_x)
425
283k
                mb_type = s->c.cur_pic.mb_type[s->c.mb_x + s->c.mb_y * s->c.mb_stride - 1];
426
174k
            else
427
                // FIXME not sure if this is allowed in MPEG at all
428
174k
                mb_type = s->c.cur_pic.mb_type[s->c.mb_width + (s->c.mb_y - 1) * s->c.mb_stride - 1];
429
458k
            if (IS_INTRA(mb_type)) {
430
803
                av_log(s->c.avctx, AV_LOG_ERROR, "skip with previntra\n");
431
803
                return AVERROR_INVALIDDATA;
432
803
            }
433
457k
            s->c.cur_pic.mb_type[s->c.mb_x + s->c.mb_y * s->c.mb_stride] =
434
457k
                mb_type | MB_TYPE_SKIP;
435
436
457k
            if ((s->c.mv[0][0][0] | s->c.mv[0][0][1] | s->c.mv[1][0][0] | s->c.mv[1][0][1]) == 0)
437
64.0k
                s->c.mb_skipped = 1;
438
457k
        }
439
440
1.79M
        return 0;
441
1.79M
    }
442
443
1.66M
    switch (s->c.pict_type) {
444
0
    default:
445
176k
    case AV_PICTURE_TYPE_I:
446
176k
        if (get_bits1(&s->gb) == 0) {
447
51.1k
            if (get_bits1(&s->gb) == 0) {
448
21.9k
                av_log(s->c.avctx, AV_LOG_ERROR,
449
21.9k
                       "Invalid mb type in I-frame at %d %d\n",
450
21.9k
                       s->c.mb_x, s->c.mb_y);
451
21.9k
                return AVERROR_INVALIDDATA;
452
21.9k
            }
453
29.1k
            mb_type = MB_TYPE_QUANT | MB_TYPE_INTRA;
454
125k
        } else {
455
125k
            mb_type = MB_TYPE_INTRA;
456
125k
        }
457
154k
        break;
458
1.07M
    case AV_PICTURE_TYPE_P:
459
1.07M
        mb_type = get_vlc2(&s->gb, ff_mb_ptype_vlc, MB_PTYPE_VLC_BITS, 1);
460
1.07M
        if (mb_type < 0) {
461
28.2k
            av_log(s->c.avctx, AV_LOG_ERROR,
462
28.2k
                   "Invalid mb type in P-frame at %d %d\n", s->c.mb_x, s->c.mb_y);
463
28.2k
            return AVERROR_INVALIDDATA;
464
28.2k
        }
465
1.04M
        break;
466
1.04M
    case AV_PICTURE_TYPE_B:
467
419k
        mb_type = get_vlc2(&s->gb, ff_mb_btype_vlc, MB_BTYPE_VLC_BITS, 1);
468
419k
        if (mb_type < 0) {
469
16.8k
            av_log(s->c.avctx, AV_LOG_ERROR,
470
16.8k
                   "Invalid mb type in B-frame at %d %d\n", s->c.mb_x, s->c.mb_y);
471
16.8k
            return AVERROR_INVALIDDATA;
472
16.8k
        }
473
402k
        break;
474
1.66M
    }
475
1.59M
    ff_tlog(s->c.avctx, "mb_type=%x\n", mb_type);
476
//    motion_type = 0; /* avoid warning */
477
1.59M
    if (IS_INTRA(mb_type)) {
478
198k
        s->c.bdsp.clear_blocks(s->block[0]);
479
480
198k
        if (!s->c.chroma_y_shift)
481
43.0k
            s->c.bdsp.clear_blocks(s->block[6]);
482
483
        /* compute DCT type */
484
        // FIXME: add an interlaced_dct coded var?
485
198k
        if (s->c.picture_structure == PICT_FRAME &&
486
180k
            !s->c.frame_pred_frame_dct)
487
20.2k
            s->c.interlaced_dct = get_bits1(&s->gb);
488
489
198k
        if (IS_QUANT(mb_type))
490
35.4k
            s->c.qscale = mpeg_get_qscale(&s->gb, s->c.q_scale_type);
491
492
198k
        if (s->c.concealment_motion_vectors) {
493
            /* just parse them */
494
37.9k
            if (s->c.picture_structure != PICT_FRAME)
495
6.11k
                skip_bits1(&s->gb);  /* field select */
496
497
37.9k
            s->c.mv[0][0][0]      =
498
37.9k
            s->c.last_mv[0][0][0] =
499
37.9k
            s->c.last_mv[0][1][0] = mpeg_decode_motion(s, s->c.mpeg_f_code[0][0],
500
37.9k
                                                       s->c.last_mv[0][0][0]);
501
37.9k
            s->c.mv[0][0][1]      =
502
37.9k
            s->c.last_mv[0][0][1] =
503
37.9k
            s->c.last_mv[0][1][1] = mpeg_decode_motion(s, s->c.mpeg_f_code[0][1],
504
37.9k
                                                       s->c.last_mv[0][0][1]);
505
506
37.9k
            check_marker(s->c.avctx, &s->gb, "after concealment_motion_vectors");
507
160k
        } else {
508
            /* reset mv prediction */
509
160k
            memset(s->c.last_mv, 0, sizeof(s->c.last_mv));
510
160k
        }
511
198k
        s->c.mb_intra = 1;
512
513
198k
        if (s->c.codec_id == AV_CODEC_ID_MPEG2VIDEO) {
514
575k
            for (i = 0; i < mb_block_count; i++)
515
516k
                if ((ret = mpeg2_decode_block_intra(s, s->block[i], i)) < 0)
516
36.9k
                    return ret;
517
103k
        } else {
518
528k
            for (i = 0; i < 6; i++) {
519
479k
                ret = ff_mpeg1_decode_block_intra(&s->gb,
520
479k
                                                  s->c.intra_matrix,
521
479k
                                                  s->c.intra_scantable.permutated,
522
479k
                                                  s->last_dc, s->block[i],
523
479k
                                                  i, s->c.qscale);
524
479k
                if (ret < 0) {
525
55.4k
                    av_log(s->c.avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n",
526
55.4k
                           s->c.mb_x, s->c.mb_y);
527
55.4k
                    return ret;
528
55.4k
                }
529
479k
            }
530
103k
        }
531
1.40M
    } else {
532
1.40M
        if (mb_type & MB_TYPE_ZERO_MV) {
533
194k
            av_assert2(mb_type & MB_TYPE_CBP);
534
535
194k
            s->c.mv_dir = MV_DIR_FORWARD;
536
194k
            if (s->c.picture_structure == PICT_FRAME) {
537
182k
                if (s->c.picture_structure == PICT_FRAME
538
182k
                    && !s->c.frame_pred_frame_dct)
539
13.0k
                    s->c.interlaced_dct = get_bits1(&s->gb);
540
182k
                s->c.mv_type = MV_TYPE_16X16;
541
182k
            } else {
542
12.4k
                s->c.mv_type            = MV_TYPE_FIELD;
543
12.4k
                mb_type              |= MB_TYPE_INTERLACED;
544
12.4k
                s->c.field_select[0][0] = s->c.picture_structure - 1;
545
12.4k
            }
546
547
194k
            if (IS_QUANT(mb_type))
548
11.3k
                s->c.qscale = mpeg_get_qscale(&s->gb, s->c.q_scale_type);
549
550
194k
            s->c.last_mv[0][0][0] = 0;
551
194k
            s->c.last_mv[0][0][1] = 0;
552
194k
            s->c.last_mv[0][1][0] = 0;
553
194k
            s->c.last_mv[0][1][1] = 0;
554
194k
            s->c.mv[0][0][0]      = 0;
555
194k
            s->c.mv[0][0][1]      = 0;
556
1.20M
        } else {
557
1.20M
            av_assert2(mb_type & MB_TYPE_BIDIR_MV);
558
            // FIXME decide if MBs in field pictures are MB_TYPE_INTERLACED
559
            /* get additional motion vector type */
560
1.20M
            if (s->c.picture_structure == PICT_FRAME && s->c.frame_pred_frame_dct) {
561
991k
                motion_type = MT_FRAME;
562
991k
            } else {
563
215k
                motion_type = get_bits(&s->gb, 2);
564
215k
                if (s->c.picture_structure == PICT_FRAME && HAS_CBP(mb_type))
565
82.3k
                    s->c.interlaced_dct = get_bits1(&s->gb);
566
215k
            }
567
568
1.20M
            if (IS_QUANT(mb_type))
569
31.1k
                s->c.qscale = mpeg_get_qscale(&s->gb, s->c.q_scale_type);
570
571
            /* motion vectors */
572
1.20M
            s->c.mv_dir = MB_TYPE_MV_2_MV_DIR(mb_type);
573
1.20M
            ff_tlog(s->c.avctx, "motion_type=%d\n", motion_type);
574
1.20M
            switch (motion_type) {
575
1.04M
            case MT_FRAME: /* or MT_16X8 */
576
1.04M
                if (s->c.picture_structure == PICT_FRAME) {
577
1.01M
                    mb_type   |= MB_TYPE_16x16;
578
1.01M
                    s->c.mv_type = MV_TYPE_16X16;
579
3.05M
                    for (i = 0; i < 2; i++) {
580
2.03M
                        if (HAS_MV(mb_type, i)) {
581
                            /* MT_FRAME */
582
1.16M
                            s->c.mv[i][0][0]      =
583
1.16M
                            s->c.last_mv[i][0][0] =
584
1.16M
                            s->c.last_mv[i][1][0] =
585
1.16M
                                mpeg_decode_motion(s, s->c.mpeg_f_code[i][0],
586
1.16M
                                                   s->c.last_mv[i][0][0]);
587
1.16M
                            s->c.mv[i][0][1]      =
588
1.16M
                            s->c.last_mv[i][0][1] =
589
1.16M
                            s->c.last_mv[i][1][1] =
590
1.16M
                                mpeg_decode_motion(s, s->c.mpeg_f_code[i][1],
591
1.16M
                                                   s->c.last_mv[i][0][1]);
592
                            /* full_pel: only for MPEG-1 */
593
1.16M
                            if (s->c.full_pel[i]) {
594
217k
                                s->c.mv[i][0][0] *= 2;
595
217k
                                s->c.mv[i][0][1] *= 2;
596
217k
                            }
597
1.16M
                        }
598
2.03M
                    }
599
1.01M
                } else {
600
21.8k
                    mb_type   |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
601
21.8k
                    s->c.mv_type = MV_TYPE_16X8;
602
65.6k
                    for (i = 0; i < 2; i++) {
603
43.7k
                        if (HAS_MV(mb_type, i)) {
604
                            /* MT_16X8 */
605
85.2k
                            for (j = 0; j < 2; j++) {
606
56.8k
                                s->c.field_select[i][j] = get_bits1(&s->gb);
607
170k
                                for (k = 0; k < 2; k++) {
608
113k
                                    val = mpeg_decode_motion(s, s->c.mpeg_f_code[i][k],
609
113k
                                                             s->c.last_mv[i][j][k]);
610
113k
                                    s->c.last_mv[i][j][k] = val;
611
113k
                                    s->c.mv[i][j][k]      = val;
612
113k
                                }
613
56.8k
                            }
614
28.4k
                        }
615
43.7k
                    }
616
21.8k
                }
617
1.04M
                break;
618
75.0k
            case MT_FIELD:
619
75.0k
                s->c.mv_type = MV_TYPE_FIELD;
620
75.0k
                if (s->c.picture_structure == PICT_FRAME) {
621
57.7k
                    mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
622
173k
                    for (i = 0; i < 2; i++) {
623
115k
                        if (HAS_MV(mb_type, i)) {
624
207k
                            for (j = 0; j < 2; j++) {
625
138k
                                s->c.field_select[i][j] = get_bits1(&s->gb);
626
138k
                                val = mpeg_decode_motion(s, s->c.mpeg_f_code[i][0],
627
138k
                                                         s->c.last_mv[i][j][0]);
628
138k
                                s->c.last_mv[i][j][0] = val;
629
138k
                                s->c.mv[i][j][0]      = val;
630
138k
                                ff_tlog(s->c.avctx, "fmx=%d\n", val);
631
138k
                                val = mpeg_decode_motion(s, s->c.mpeg_f_code[i][1],
632
138k
                                                         s->c.last_mv[i][j][1] >> 1);
633
138k
                                s->c.last_mv[i][j][1] = 2 * val;
634
138k
                                s->c.mv[i][j][1]      = val;
635
138k
                                ff_tlog(s->c.avctx, "fmy=%d\n", val);
636
138k
                            }
637
69.3k
                        }
638
115k
                    }
639
57.7k
                } else {
640
17.2k
                    av_assert0(!s->c.progressive_sequence);
641
17.2k
                    mb_type |= MB_TYPE_16x16 | MB_TYPE_INTERLACED;
642
51.7k
                    for (i = 0; i < 2; i++) {
643
34.5k
                        if (HAS_MV(mb_type, i)) {
644
21.6k
                            s->c.field_select[i][0] = get_bits1(&s->gb);
645
65.0k
                            for (k = 0; k < 2; k++) {
646
43.3k
                                val = mpeg_decode_motion(s, s->c.mpeg_f_code[i][k],
647
43.3k
                                                         s->c.last_mv[i][0][k]);
648
43.3k
                                s->c.last_mv[i][0][k] = val;
649
43.3k
                                s->c.last_mv[i][1][k] = val;
650
43.3k
                                s->c.mv[i][0][k]      = val;
651
43.3k
                            }
652
21.6k
                        }
653
34.5k
                    }
654
17.2k
                }
655
75.0k
                break;
656
75.0k
            case MT_DMV:
657
74.8k
                if (s->c.progressive_sequence){
658
4.48k
                    av_log(s->c.avctx, AV_LOG_ERROR, "MT_DMV in progressive_sequence\n");
659
4.48k
                    return AVERROR_INVALIDDATA;
660
4.48k
                }
661
70.3k
                s->c.mv_type = MV_TYPE_DMV;
662
211k
                for (i = 0; i < 2; i++) {
663
140k
                    if (HAS_MV(mb_type, i)) {
664
120k
                        int dmx, dmy, mx, my, m;
665
120k
                        const int my_shift = s->c.picture_structure == PICT_FRAME;
666
667
120k
                        mx = mpeg_decode_motion(s, s->c.mpeg_f_code[i][0],
668
120k
                                                s->c.last_mv[i][0][0]);
669
120k
                        s->c.last_mv[i][0][0] = mx;
670
120k
                        s->c.last_mv[i][1][0] = mx;
671
120k
                        dmx = get_dmv(s);
672
120k
                        my  = mpeg_decode_motion(s, s->c.mpeg_f_code[i][1],
673
120k
                                                 s->c.last_mv[i][0][1] >> my_shift);
674
120k
                        dmy = get_dmv(s);
675
676
677
120k
                        s->c.last_mv[i][0][1] = my * (1 << my_shift);
678
120k
                        s->c.last_mv[i][1][1] = my * (1 << my_shift);
679
680
120k
                        s->c.mv[i][0][0] = mx;
681
120k
                        s->c.mv[i][0][1] = my;
682
120k
                        s->c.mv[i][1][0] = mx; // not used
683
120k
                        s->c.mv[i][1][1] = my; // not used
684
685
120k
                        if (s->c.picture_structure == PICT_FRAME) {
686
78.8k
                            mb_type |= MB_TYPE_16x16 | MB_TYPE_INTERLACED;
687
688
                            // m = 1 + 2 * s->c.top_field_first;
689
78.8k
                            m = s->c.top_field_first ? 1 : 3;
690
691
                            /* top -> top pred */
692
78.8k
                            s->c.mv[i][2][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
693
78.8k
                            s->c.mv[i][2][1] = ((my * m + (my > 0)) >> 1) + dmy - 1;
694
78.8k
                            m = 4 - m;
695
78.8k
                            s->c.mv[i][3][0] = ((mx * m + (mx > 0)) >> 1) + dmx;
696
78.8k
                            s->c.mv[i][3][1] = ((my * m + (my > 0)) >> 1) + dmy + 1;
697
78.8k
                        } else {
698
41.9k
                            mb_type |= MB_TYPE_16x16;
699
700
41.9k
                            s->c.mv[i][2][0] = ((mx + (mx > 0)) >> 1) + dmx;
701
41.9k
                            s->c.mv[i][2][1] = ((my + (my > 0)) >> 1) + dmy;
702
41.9k
                            if (s->c.picture_structure == PICT_TOP_FIELD)
703
14.4k
                                s->c.mv[i][2][1]--;
704
27.4k
                            else
705
27.4k
                                s->c.mv[i][2][1]++;
706
41.9k
                        }
707
120k
                    }
708
140k
                }
709
70.3k
                break;
710
15.8k
            default:
711
15.8k
                av_log(s->c.avctx, AV_LOG_ERROR,
712
15.8k
                       "00 motion_type at %d %d\n", s->c.mb_x, s->c.mb_y);
713
15.8k
                return AVERROR_INVALIDDATA;
714
1.20M
            }
715
1.20M
        }
716
717
1.38M
        s->c.mb_intra = 0;
718
1.38M
        s->last_dc[0] = s->last_dc[1] = s->last_dc[2] = 128 << s->c.intra_dc_precision;
719
1.38M
        if (HAS_CBP(mb_type)) {
720
924k
            s->c.bdsp.clear_blocks(s->block[0]);
721
722
924k
            cbp = get_vlc2(&s->gb, ff_mb_pat_vlc, MB_PAT_VLC_BITS, 1);
723
924k
            if (mb_block_count > 6) {
724
140k
                cbp *= 1 << mb_block_count - 6;
725
140k
                cbp |= get_bits(&s->gb, mb_block_count - 6);
726
140k
                s->c.bdsp.clear_blocks(s->block[6]);
727
140k
            }
728
924k
            if (cbp <= 0) {
729
29.7k
                av_log(s->c.avctx, AV_LOG_ERROR,
730
29.7k
                       "invalid cbp %d at %d %d\n", cbp, s->c.mb_x, s->c.mb_y);
731
29.7k
                return AVERROR_INVALIDDATA;
732
29.7k
            }
733
734
895k
            if (s->c.codec_id == AV_CODEC_ID_MPEG2VIDEO) {
735
374k
                cbp <<= 12 - mb_block_count;
736
737
2.60M
                for (i = 0; i < mb_block_count; i++) {
738
2.30M
                    if (cbp & (1 << 11)) {
739
920k
                        if ((ret = mpeg2_decode_block_non_intra(s, s->block[i], i)) < 0)
740
74.1k
                            return ret;
741
1.38M
                    } else {
742
1.38M
                        s->c.block_last_index[i] = -1;
743
1.38M
                    }
744
2.23M
                    cbp += cbp;
745
2.23M
                }
746
520k
            } else {
747
3.20M
                for (i = 0; i < 6; i++) {
748
2.77M
                    if (cbp & 32) {
749
1.22M
                        if ((ret = mpeg1_decode_block_inter(s, s->block[i], i)) < 0)
750
97.6k
                            return ret;
751
1.55M
                    } else {
752
1.55M
                        s->c.block_last_index[i] = -1;
753
1.55M
                    }
754
2.67M
                    cbp += cbp;
755
2.67M
                }
756
520k
            }
757
895k
        } else {
758
5.92M
            for (i = 0; i < 12; i++)
759
5.47M
                s->c.block_last_index[i] = -1;
760
455k
        }
761
1.38M
    }
762
763
1.28M
    s->c.cur_pic.mb_type[s->c.mb_x + s->c.mb_y * s->c.mb_stride] = mb_type;
764
765
1.28M
    return 0;
766
1.59M
}
767
768
static av_cold int mpeg_decode_init(AVCodecContext *avctx)
769
24.3k
{
770
24.3k
    Mpeg1Context *s    = avctx->priv_data;
771
24.3k
    MPVContext *const s2 = &s->slice.c;
772
24.3k
    int ret;
773
774
24.3k
    s2->slice_ctx_size = sizeof(s->slice);
775
24.3k
    s2->out_format = FMT_MPEG1;
776
777
24.3k
    if (   avctx->codec_tag != AV_RL32("VCR2")
778
24.0k
        && avctx->codec_tag != AV_RL32("BW10"))
779
24.0k
        avctx->coded_width = avctx->coded_height = 0; // do not trust dimensions from input
780
24.3k
    ret = ff_mpv_decode_init(s2, avctx);
781
24.3k
    if (ret < 0)
782
0
        return ret;
783
784
24.3k
    ff_mpeg12_init_vlcs();
785
786
24.3k
    s2->chroma_format  = CHROMA_420;
787
24.3k
    avctx->color_range             = AVCOL_RANGE_MPEG;
788
24.3k
    return 0;
789
24.3k
}
790
791
static const enum AVPixelFormat mpeg1_hwaccel_pixfmt_list_420[] = {
792
#if CONFIG_MPEG1_NVDEC_HWACCEL
793
    AV_PIX_FMT_CUDA,
794
#endif
795
#if CONFIG_MPEG1_VDPAU_HWACCEL
796
    AV_PIX_FMT_VDPAU,
797
#endif
798
    AV_PIX_FMT_YUV420P,
799
    AV_PIX_FMT_NONE
800
};
801
802
static const enum AVPixelFormat mpeg2_hwaccel_pixfmt_list_420[] = {
803
#if CONFIG_MPEG2_NVDEC_HWACCEL
804
    AV_PIX_FMT_CUDA,
805
#endif
806
#if CONFIG_MPEG2_VDPAU_HWACCEL
807
    AV_PIX_FMT_VDPAU,
808
#endif
809
#if CONFIG_MPEG2_DXVA2_HWACCEL
810
    AV_PIX_FMT_DXVA2_VLD,
811
#endif
812
#if CONFIG_MPEG2_D3D11VA_HWACCEL
813
    AV_PIX_FMT_D3D11VA_VLD,
814
    AV_PIX_FMT_D3D11,
815
#endif
816
#if CONFIG_MPEG2_D3D12VA_HWACCEL
817
    AV_PIX_FMT_D3D12,
818
#endif
819
#if CONFIG_MPEG2_VAAPI_HWACCEL
820
    AV_PIX_FMT_VAAPI,
821
#endif
822
#if CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL
823
    AV_PIX_FMT_VIDEOTOOLBOX,
824
#endif
825
    AV_PIX_FMT_YUV420P,
826
    AV_PIX_FMT_NONE
827
};
828
829
static const enum AVPixelFormat mpeg12_pixfmt_list_422[] = {
830
    AV_PIX_FMT_YUV422P,
831
    AV_PIX_FMT_NONE
832
};
833
834
static const enum AVPixelFormat mpeg12_pixfmt_list_444[] = {
835
    AV_PIX_FMT_YUV444P,
836
    AV_PIX_FMT_NONE
837
};
838
839
static enum AVPixelFormat mpeg_get_pixelformat(AVCodecContext *avctx)
840
89.0k
{
841
89.0k
    Mpeg1Context *s1  = avctx->priv_data;
842
89.0k
    MPVContext *const s = &s1->slice.c;
843
89.0k
    const enum AVPixelFormat *pix_fmts;
844
845
89.0k
    if (CONFIG_GRAY && (avctx->flags & AV_CODEC_FLAG_GRAY))
846
0
        return AV_PIX_FMT_GRAY8;
847
848
89.0k
    if (s->chroma_format < CHROMA_422)
849
47.0k
        pix_fmts = avctx->codec_id == AV_CODEC_ID_MPEG1VIDEO ?
850
26.8k
                                mpeg1_hwaccel_pixfmt_list_420 :
851
47.0k
                                mpeg2_hwaccel_pixfmt_list_420;
852
41.9k
    else if (s->chroma_format == CHROMA_422)
853
22.6k
        pix_fmts = mpeg12_pixfmt_list_422;
854
19.3k
    else
855
19.3k
        pix_fmts = mpeg12_pixfmt_list_444;
856
857
89.0k
    return ff_get_format(avctx, pix_fmts);
858
89.0k
}
859
860
/* Call this function when we know all parameters.
861
 * It may be called in different places for MPEG-1 and MPEG-2. */
862
static int mpeg_decode_postinit(AVCodecContext *avctx)
863
476k
{
864
476k
    Mpeg1Context *s1  = avctx->priv_data;
865
476k
    MPVContext *const s = &s1->slice.c;
866
476k
    int ret;
867
868
476k
    if (avctx->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
869
        // MPEG-1 aspect
870
170k
        AVRational aspect_inv = av_d2q(ff_mpeg1_aspect[s1->aspect_ratio_info], 255);
871
170k
        avctx->sample_aspect_ratio = (AVRational) { aspect_inv.den, aspect_inv.num };
872
305k
    } else { // MPEG-2
873
        // MPEG-2 aspect
874
305k
        if (s1->aspect_ratio_info > 1) {
875
134k
            AVRational dar =
876
134k
                av_mul_q(av_div_q(ff_mpeg2_aspect[s1->aspect_ratio_info],
877
134k
                                  (AVRational) { s1->pan_scan.width,
878
134k
                                                 s1->pan_scan.height }),
879
134k
                         (AVRational) { s->width, s->height });
880
881
            /* We ignore the spec here and guess a bit as reality does not
882
             * match the spec, see for example res_change_ffmpeg_aspect.ts
883
             * and sequence-display-aspect.mpg.
884
             * issue1613, 621, 562 */
885
134k
            if ((s1->pan_scan.width == 0) || (s1->pan_scan.height == 0) ||
886
31.7k
                (av_cmp_q(dar, (AVRational) { 4, 3 }) &&
887
132k
                 av_cmp_q(dar, (AVRational) { 16, 9 }))) {
888
132k
                s->avctx->sample_aspect_ratio =
889
132k
                    av_div_q(ff_mpeg2_aspect[s1->aspect_ratio_info],
890
132k
                             (AVRational) { s->width, s->height });
891
132k
            } else {
892
1.37k
                s->avctx->sample_aspect_ratio =
893
1.37k
                    av_div_q(ff_mpeg2_aspect[s1->aspect_ratio_info],
894
1.37k
                             (AVRational) { s1->pan_scan.width, s1->pan_scan.height });
895
// issue1613 4/3 16/9 -> 16/9
896
// res_change_ffmpeg_aspect.ts 4/3 225/44 ->4/3
897
// widescreen-issue562.mpg 4/3 16/9 -> 16/9
898
//                s->avctx->sample_aspect_ratio = av_mul_q(s->avctx->sample_aspect_ratio, (AVRational) {s->width, s->height});
899
1.37k
                ff_dlog(avctx, "aspect A %d/%d\n",
900
1.37k
                        ff_mpeg2_aspect[s1->aspect_ratio_info].num,
901
1.37k
                        ff_mpeg2_aspect[s1->aspect_ratio_info].den);
902
1.37k
                ff_dlog(avctx, "aspect B %d/%d\n", s->avctx->sample_aspect_ratio.num,
903
1.37k
                        s->avctx->sample_aspect_ratio.den);
904
1.37k
            }
905
171k
        } else {
906
171k
            s->avctx->sample_aspect_ratio =
907
171k
                ff_mpeg2_aspect[s1->aspect_ratio_info];
908
171k
        }
909
305k
    } // MPEG-2
910
911
476k
    if (av_image_check_sar(s->width, s->height,
912
476k
                           avctx->sample_aspect_ratio) < 0) {
913
108k
        av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
914
108k
                avctx->sample_aspect_ratio.num,
915
108k
                avctx->sample_aspect_ratio.den);
916
108k
        avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
917
108k
    }
918
919
476k
    if (!s->context_initialized                             ||
920
440k
        avctx->coded_width       != s->width                ||
921
414k
        avctx->coded_height      != s->height               ||
922
410k
        s1->save_chroma_format   != s->chroma_format        ||
923
376k
        (s1->save_progressive_seq != s->progressive_sequence && FFALIGN(s->height, 16) != FFALIGN(s->height, 32)) ||
924
108k
        0) {
925
108k
        if (s->context_initialized)
926
71.9k
            ff_mpv_common_end(s);
927
928
108k
        ret = ff_set_dimensions(avctx, s->width, s->height);
929
108k
        if (ret < 0)
930
24.7k
            return ret;
931
932
83.5k
        if (avctx->codec_id == AV_CODEC_ID_MPEG2VIDEO && s1->bit_rate &&
933
55.3k
            (s1->bit_rate != 0x3FFFF*400)) {
934
53.2k
            avctx->rc_max_rate = s1->bit_rate;
935
53.2k
        } else if (avctx->codec_id == AV_CODEC_ID_MPEG1VIDEO && s1->bit_rate &&
936
25.0k
                   (s1->bit_rate != 0x3FFFF*400 || s1->vbv_delay != 0xFFFF)) {
937
24.0k
            avctx->bit_rate = s1->bit_rate;
938
24.0k
        }
939
83.5k
        s1->save_progressive_seq = s->progressive_sequence;
940
83.5k
        s1->save_chroma_format   = s->chroma_format;
941
942
        /* low_delay may be forced, in this case we will have B-frames
943
         * that behave like P-frames. */
944
83.5k
        avctx->has_b_frames = !s->low_delay;
945
946
83.5k
        if (avctx->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
947
            // MPEG-1 fps
948
26.7k
            avctx->framerate = ff_mpeg12_frame_rate_tab[s1->frame_rate_index];
949
26.7k
            avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
950
56.7k
        } else { // MPEG-2
951
            // MPEG-2 fps
952
56.7k
            av_reduce(&s->avctx->framerate.num,
953
56.7k
                      &s->avctx->framerate.den,
954
56.7k
                      ff_mpeg12_frame_rate_tab[s1->frame_rate_index].num * s1->frame_rate_ext.num,
955
56.7k
                      ff_mpeg12_frame_rate_tab[s1->frame_rate_index].den * s1->frame_rate_ext.den,
956
56.7k
                      1 << 30);
957
958
56.7k
            switch (s->chroma_format) {
959
18.3k
            case CHROMA_420: avctx->chroma_sample_location = AVCHROMA_LOC_LEFT; break;
960
20.3k
            case CHROMA_422:
961
38.4k
            case CHROMA_444: avctx->chroma_sample_location = AVCHROMA_LOC_TOPLEFT; break;
962
0
            default: av_assert0(0);
963
56.7k
            }
964
56.7k
        } // MPEG-2
965
966
83.5k
        avctx->pix_fmt = mpeg_get_pixelformat(avctx);
967
968
83.5k
        if ((ret = ff_mpv_common_init(s)) < 0)
969
0
            return ret;
970
83.5k
        if (!s->avctx->lowres)
971
106k
            for (int i = 0; i < s->slice_context_count; i++)
972
53.3k
                ff_mpv_framesize_disable(&s->thread_context[i]->sc);
973
83.5k
    }
974
451k
    return 0;
975
476k
}
976
977
static int mpeg1_decode_picture(AVCodecContext *avctx, const uint8_t *buf,
978
                                int buf_size)
979
451k
{
980
451k
    Mpeg1Context *s1  = avctx->priv_data;
981
451k
    MPVContext *const s = &s1->slice.c;
982
451k
    GetBitContext gb0, *const gb = &gb0;
983
451k
    int ref, f_code, vbv_delay, ret;
984
985
451k
    ret = init_get_bits8(gb, buf, buf_size);
986
451k
    if (ret < 0)
987
0
        return ret;
988
989
451k
    ref = get_bits(gb, 10); /* temporal ref */
990
451k
    s->pict_type = get_bits(gb, 3);
991
451k
    if (s->pict_type == 0 || s->pict_type > 3)
992
128k
        return AVERROR_INVALIDDATA;
993
994
323k
    vbv_delay = get_bits(gb, 16);
995
323k
    s1->vbv_delay = vbv_delay;
996
323k
    if (s->pict_type == AV_PICTURE_TYPE_P ||
997
247k
        s->pict_type == AV_PICTURE_TYPE_B) {
998
247k
        s->full_pel[0] = get_bits1(gb);
999
247k
        f_code = get_bits(gb, 3);
1000
247k
        if (f_code == 0 && (avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT)))
1001
35.9k
            return AVERROR_INVALIDDATA;
1002
211k
        f_code += !f_code;
1003
211k
        s->mpeg_f_code[0][0] = f_code;
1004
211k
        s->mpeg_f_code[0][1] = f_code;
1005
211k
    }
1006
287k
    if (s->pict_type == AV_PICTURE_TYPE_B) {
1007
66.8k
        s->full_pel[1] = get_bits1(gb);
1008
66.8k
        f_code = get_bits(gb, 3);
1009
66.8k
        if (f_code == 0 && (avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT)))
1010
3.62k
            return AVERROR_INVALIDDATA;
1011
63.1k
        f_code += !f_code;
1012
63.1k
        s->mpeg_f_code[1][0] = f_code;
1013
63.1k
        s->mpeg_f_code[1][1] = f_code;
1014
63.1k
    }
1015
1016
284k
    if (avctx->debug & FF_DEBUG_PICT_INFO)
1017
0
        av_log(avctx, AV_LOG_DEBUG,
1018
0
               "vbv_delay %d, ref %d type:%d\n", vbv_delay, ref, s->pict_type);
1019
1020
284k
    return 0;
1021
287k
}
1022
1023
static void mpeg_decode_sequence_extension(Mpeg1Context *const s1,
1024
                                           GetBitContext *const gb)
1025
163k
{
1026
163k
    MPVContext *const s = &s1->slice.c;
1027
163k
    int horiz_size_ext, vert_size_ext;
1028
163k
    int bit_rate_ext;
1029
1030
163k
    skip_bits(gb, 1); /* profile and level esc*/
1031
163k
    s->avctx->profile       = get_bits(gb, 3);
1032
163k
    s->avctx->level         = get_bits(gb, 4);
1033
163k
    s->progressive_sequence = get_bits1(gb);   /* progressive_sequence */
1034
163k
    s->chroma_format        = get_bits(gb, 2); /* chroma_format 1=420, 2=422, 3=444 */
1035
1036
163k
    if (!s->chroma_format) {
1037
43.8k
        s->chroma_format = CHROMA_420;
1038
43.8k
        av_log(s->avctx, AV_LOG_WARNING, "Chroma format invalid\n");
1039
43.8k
    }
1040
1041
163k
    horiz_size_ext          = get_bits(gb, 2);
1042
163k
    vert_size_ext           = get_bits(gb, 2);
1043
163k
    s->width  |= (horiz_size_ext << 12);
1044
163k
    s->height |= (vert_size_ext  << 12);
1045
163k
    bit_rate_ext = get_bits(gb, 12);  /* XXX: handle it */
1046
163k
    s1->bit_rate += (bit_rate_ext << 18) * 400LL;
1047
163k
    check_marker(s->avctx, gb, "after bit rate extension");
1048
163k
    s->avctx->rc_buffer_size += get_bits(gb, 8) * 1024 * 16 << 10;
1049
1050
163k
    s->low_delay = get_bits1(gb);
1051
163k
    if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)
1052
0
        s->low_delay = 1;
1053
1054
163k
    s1->frame_rate_ext.num = get_bits(gb, 2) + 1;
1055
163k
    s1->frame_rate_ext.den = get_bits(gb, 5) + 1;
1056
1057
163k
    ff_dlog(s->avctx, "sequence extension\n");
1058
163k
    s->codec_id = s->avctx->codec_id = AV_CODEC_ID_MPEG2VIDEO;
1059
1060
163k
    if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1061
0
        av_log(s->avctx, AV_LOG_DEBUG,
1062
0
               "profile: %d, level: %d ps: %d cf:%d vbv buffer: %d, bitrate:%"PRId64"\n",
1063
0
               s->avctx->profile, s->avctx->level, s->progressive_sequence, s->chroma_format,
1064
0
               s->avctx->rc_buffer_size, s1->bit_rate);
1065
163k
}
1066
1067
static void mpeg_decode_sequence_display_extension(Mpeg1Context *const s1,
1068
                                                   GetBitContext *const gb)
1069
26.7k
{
1070
26.7k
    MPVContext *const s = &s1->slice.c;
1071
26.7k
    int color_description, w, h;
1072
1073
26.7k
    skip_bits(gb, 3); /* video format */
1074
26.7k
    color_description = get_bits1(gb);
1075
26.7k
    if (color_description) {
1076
19.5k
        s->avctx->color_primaries = get_bits(gb, 8);
1077
19.5k
        s->avctx->color_trc       = get_bits(gb, 8);
1078
19.5k
        s->avctx->colorspace      = get_bits(gb, 8);
1079
19.5k
    }
1080
26.7k
    w = get_bits(gb, 14);
1081
26.7k
    skip_bits(gb, 1); // marker
1082
26.7k
    h = get_bits(gb, 14);
1083
    // remaining 3 bits are zero padding
1084
1085
26.7k
    s1->pan_scan.width  = 16 * w;
1086
26.7k
    s1->pan_scan.height = 16 * h;
1087
1088
26.7k
    if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1089
0
        av_log(s->avctx, AV_LOG_DEBUG, "sde w:%d, h:%d\n", w, h);
1090
26.7k
}
1091
1092
static void mpeg_decode_picture_display_extension(Mpeg1Context *const s1,
1093
                                                  GetBitContext *const gb)
1094
12.8k
{
1095
12.8k
    MPVContext *const s = &s1->slice.c;
1096
12.8k
    int i, nofco;
1097
1098
12.8k
    nofco = 1;
1099
12.8k
    if (s->progressive_sequence) {
1100
7.95k
        if (s->repeat_first_field) {
1101
2.20k
            nofco++;
1102
2.20k
            if (s->top_field_first)
1103
1.00k
                nofco++;
1104
2.20k
        }
1105
7.95k
    } else {
1106
4.89k
        if (s->picture_structure == PICT_FRAME) {
1107
3.46k
            nofco++;
1108
3.46k
            if (s->repeat_first_field)
1109
1.94k
                nofco++;
1110
3.46k
        }
1111
4.89k
    }
1112
34.3k
    for (i = 0; i < nofco; i++) {
1113
21.4k
        s1->pan_scan.position[i][0] = get_sbits(gb, 16);
1114
21.4k
        skip_bits(gb, 1); // marker
1115
21.4k
        s1->pan_scan.position[i][1] = get_sbits(gb, 16);
1116
21.4k
        skip_bits(gb, 1); // marker
1117
21.4k
    }
1118
1119
12.8k
    if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1120
0
        av_log(s->avctx, AV_LOG_DEBUG,
1121
0
               "pde (%"PRId16",%"PRId16") (%"PRId16",%"PRId16") (%"PRId16",%"PRId16")\n",
1122
0
               s1->pan_scan.position[0][0], s1->pan_scan.position[0][1],
1123
0
               s1->pan_scan.position[1][0], s1->pan_scan.position[1][1],
1124
0
               s1->pan_scan.position[2][0], s1->pan_scan.position[2][1]);
1125
12.8k
}
1126
1127
static int load_matrix(MPVContext *const s, GetBitContext *const gb,
1128
                       uint16_t matrix0[64], uint16_t matrix1[64], int intra)
1129
83.4k
{
1130
83.4k
    int i;
1131
1132
901k
    for (i = 0; i < 64; i++) {
1133
894k
        int j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
1134
894k
        int v = get_bits(gb, 8);
1135
894k
        if (v == 0) {
1136
76.6k
            av_log(s->avctx, AV_LOG_ERROR, "matrix damaged\n");
1137
76.6k
            return AVERROR_INVALIDDATA;
1138
76.6k
        }
1139
817k
        if (intra && i == 0 && v != 8) {
1140
41.5k
            av_log(s->avctx, AV_LOG_DEBUG, "intra matrix specifies invalid DC quantizer %d, ignoring\n", v);
1141
41.5k
            v = 8; // needed by pink.mpg / issue1046
1142
41.5k
        }
1143
817k
        matrix0[j] = v;
1144
817k
        if (matrix1)
1145
532k
            matrix1[j] = v;
1146
817k
    }
1147
6.87k
    return 0;
1148
83.4k
}
1149
1150
static void mpeg_decode_quant_matrix_extension(MPVContext *const s,
1151
                                               GetBitContext *const gb)
1152
21.1k
{
1153
21.1k
    ff_dlog(s->avctx, "matrix extension\n");
1154
1155
21.1k
    if (get_bits1(gb))
1156
8.94k
        load_matrix(s, gb, s->chroma_intra_matrix, s->intra_matrix, 1);
1157
21.1k
    if (get_bits1(gb))
1158
3.35k
        load_matrix(s, gb, s->chroma_inter_matrix, s->inter_matrix, 0);
1159
21.1k
    if (get_bits1(gb))
1160
7.23k
        load_matrix(s, gb, s->chroma_intra_matrix, NULL, 1);
1161
21.1k
    if (get_bits1(gb))
1162
6.89k
        load_matrix(s, gb, s->chroma_inter_matrix, NULL, 0);
1163
21.1k
}
1164
1165
static int mpeg_decode_picture_coding_extension(Mpeg1Context *const s1,
1166
                                                GetBitContext *const gb)
1167
322k
{
1168
322k
    MPVContext *const s = &s1->slice.c;
1169
1170
322k
    s->full_pel[0]       = s->full_pel[1] = 0;
1171
322k
    s->mpeg_f_code[0][0] = get_bits(gb, 4);
1172
322k
    s->mpeg_f_code[0][1] = get_bits(gb, 4);
1173
322k
    s->mpeg_f_code[1][0] = get_bits(gb, 4);
1174
322k
    s->mpeg_f_code[1][1] = get_bits(gb, 4);
1175
322k
    s->mpeg_f_code[0][0] += !s->mpeg_f_code[0][0];
1176
322k
    s->mpeg_f_code[0][1] += !s->mpeg_f_code[0][1];
1177
322k
    s->mpeg_f_code[1][0] += !s->mpeg_f_code[1][0];
1178
322k
    s->mpeg_f_code[1][1] += !s->mpeg_f_code[1][1];
1179
322k
    if (!s->pict_type && s->context_initialized) {
1180
34.4k
        av_log(s->avctx, AV_LOG_ERROR, "Missing picture start code\n");
1181
34.4k
        if (s->avctx->err_recognition & AV_EF_EXPLODE)
1182
1.13k
            return AVERROR_INVALIDDATA;
1183
33.3k
        av_log(s->avctx, AV_LOG_WARNING, "Guessing pict_type from mpeg_f_code\n");
1184
33.3k
        if (s->mpeg_f_code[1][0] == 15 && s->mpeg_f_code[1][1] == 15) {
1185
4.33k
            if (s->mpeg_f_code[0][0] == 15 && s->mpeg_f_code[0][1] == 15)
1186
1.07k
                s->pict_type = AV_PICTURE_TYPE_I;
1187
3.26k
            else
1188
3.26k
                s->pict_type = AV_PICTURE_TYPE_P;
1189
4.33k
        } else
1190
29.0k
            s->pict_type = AV_PICTURE_TYPE_B;
1191
33.3k
    }
1192
1193
321k
    s->intra_dc_precision         = get_bits(gb, 2);
1194
321k
    s->picture_structure          = get_bits(gb, 2);
1195
321k
    s->top_field_first            = get_bits1(gb);
1196
321k
    s->frame_pred_frame_dct       = get_bits1(gb);
1197
321k
    s->concealment_motion_vectors = get_bits1(gb);
1198
321k
    s->q_scale_type               = get_bits1(gb);
1199
321k
    s->intra_vlc_format           = get_bits1(gb);
1200
321k
    s->alternate_scan             = get_bits1(gb);
1201
321k
    s->repeat_first_field         = get_bits1(gb);
1202
321k
    s->chroma_420_type            = get_bits1(gb);
1203
321k
    s->progressive_frame          = get_bits1(gb);
1204
1205
    // We only initialize intra_scantable.permutated, as this is all we use.
1206
321k
    ff_permute_scantable(s->intra_scantable.permutated,
1207
321k
                         s->alternate_scan ? ff_alternate_vertical_scan : ff_zigzag_direct,
1208
321k
                         s->idsp.idct_permutation);
1209
1210
    /* composite display not parsed */
1211
321k
    ff_dlog(s->avctx, "intra_dc_precision=%d\n", s->intra_dc_precision);
1212
321k
    ff_dlog(s->avctx, "picture_structure=%d\n", s->picture_structure);
1213
321k
    ff_dlog(s->avctx, "top field first=%d\n", s->top_field_first);
1214
321k
    ff_dlog(s->avctx, "repeat first field=%d\n", s->repeat_first_field);
1215
321k
    ff_dlog(s->avctx, "conceal=%d\n", s->concealment_motion_vectors);
1216
321k
    ff_dlog(s->avctx, "intra_vlc_format=%d\n", s->intra_vlc_format);
1217
321k
    ff_dlog(s->avctx, "alternate_scan=%d\n", s->alternate_scan);
1218
321k
    ff_dlog(s->avctx, "frame_pred_frame_dct=%d\n", s->frame_pred_frame_dct);
1219
321k
    ff_dlog(s->avctx, "progressive_frame=%d\n", s->progressive_frame);
1220
1221
321k
    return 0;
1222
322k
}
1223
1224
static int mpeg_field_start(Mpeg1Context *s1, const uint8_t *buf, int buf_size)
1225
176k
{
1226
176k
    MPVContext *const s = &s1->slice.c;
1227
176k
    AVCodecContext *avctx = s->avctx;
1228
176k
    int second_field = 0;
1229
176k
    int ret;
1230
1231
176k
    if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
1232
176k
        if (s->mb_width * s->mb_height * 11LL / (33 * 2 * 8) > buf_size)
1233
5.88k
            return AVERROR_INVALIDDATA;
1234
176k
    }
1235
1236
    /* start frame decoding */
1237
170k
    if (s->first_field || s->picture_structure == PICT_FRAME) {
1238
153k
        AVFrameSideData *pan_scan;
1239
1240
153k
        if ((ret = ff_mpv_frame_start(s, avctx)) < 0)
1241
538
            return ret;
1242
1243
152k
        if (s->picture_structure != PICT_FRAME) {
1244
21.7k
            s->cur_pic.ptr->f->flags |= AV_FRAME_FLAG_TOP_FIELD_FIRST *
1245
21.7k
                                        (s->picture_structure == PICT_TOP_FIELD);
1246
1247
87.1k
            for (int i = 0; i < 3; i++) {
1248
65.3k
                if (s->picture_structure == PICT_BOTTOM_FIELD) {
1249
36.6k
                    s->cur_pic.data[i] = FF_PTR_ADD(s->cur_pic.data[i],
1250
36.6k
                                                    s->cur_pic.linesize[i]);
1251
36.6k
                }
1252
65.3k
                s->cur_pic.linesize[i]  *= 2;
1253
65.3k
            }
1254
21.7k
        }
1255
1256
152k
        ff_mpeg_er_frame_start(s);
1257
1258
        /* first check if we must repeat the frame */
1259
152k
        s->cur_pic.ptr->f->repeat_pict = 0;
1260
152k
        if (s->repeat_first_field) {
1261
34.1k
            if (s->progressive_sequence) {
1262
15.7k
                if (s->top_field_first)
1263
8.03k
                    s->cur_pic.ptr->f->repeat_pict = 4;
1264
7.75k
                else
1265
7.75k
                    s->cur_pic.ptr->f->repeat_pict = 2;
1266
18.3k
            } else if (s->progressive_frame) {
1267
7.95k
                s->cur_pic.ptr->f->repeat_pict = 1;
1268
7.95k
            }
1269
34.1k
        }
1270
1271
152k
        ret = ff_frame_new_side_data(s->avctx, s->cur_pic.ptr->f,
1272
152k
                                     AV_FRAME_DATA_PANSCAN, sizeof(s1->pan_scan),
1273
152k
                                     &pan_scan);
1274
152k
        if (ret < 0)
1275
0
            return ret;
1276
152k
        if (pan_scan)
1277
152k
            memcpy(pan_scan->data, &s1->pan_scan, sizeof(s1->pan_scan));
1278
1279
152k
        if (s1->a53_buf_ref) {
1280
4.79k
            ret = ff_frame_new_side_data_from_buf(
1281
4.79k
                s->avctx, s->cur_pic.ptr->f, AV_FRAME_DATA_A53_CC,
1282
4.79k
                &s1->a53_buf_ref);
1283
4.79k
            if (ret < 0)
1284
0
                return ret;
1285
4.79k
        }
1286
1287
152k
        if (s1->has_stereo3d) {
1288
1.07k
            AVStereo3D *stereo = av_stereo3d_create_side_data(s->cur_pic.ptr->f);
1289
1.07k
            if (!stereo)
1290
0
                return AVERROR(ENOMEM);
1291
1292
1.07k
            stereo->type = s1->stereo3d_type;
1293
1.07k
            s1->has_stereo3d = 0;
1294
1.07k
        }
1295
1296
152k
        if (s1->has_afd) {
1297
2.26k
            AVFrameSideData *sd;
1298
2.26k
            ret = ff_frame_new_side_data(s->avctx, s->cur_pic.ptr->f,
1299
2.26k
                                         AV_FRAME_DATA_AFD, 1, &sd);
1300
2.26k
            if (ret < 0)
1301
0
                return ret;
1302
2.26k
            if (sd)
1303
2.26k
                *sd->data = s1->afd;
1304
2.26k
            s1->has_afd = 0;
1305
2.26k
        }
1306
152k
    } else { // second field
1307
17.4k
        second_field = 1;
1308
17.4k
        if (!s->cur_pic.ptr) {
1309
2.04k
            av_log(s->avctx, AV_LOG_ERROR, "first field missing\n");
1310
2.04k
            return AVERROR_INVALIDDATA;
1311
2.04k
        }
1312
1313
15.4k
        if (s->avctx->hwaccel) {
1314
0
            if ((ret = FF_HW_SIMPLE_CALL(s->avctx, end_frame)) < 0) {
1315
0
                av_log(avctx, AV_LOG_ERROR,
1316
0
                       "hardware accelerator failed to decode first field\n");
1317
0
                return ret;
1318
0
            }
1319
0
        }
1320
15.4k
        ret = ff_mpv_alloc_dummy_frames(s);
1321
15.4k
        if (ret < 0)
1322
0
            return ret;
1323
1324
61.6k
        for (int i = 0; i < 3; i++) {
1325
46.2k
            s->cur_pic.data[i] = s->cur_pic.ptr->f->data[i];
1326
46.2k
            if (s->picture_structure == PICT_BOTTOM_FIELD)
1327
25.3k
                s->cur_pic.data[i] +=
1328
25.3k
                    s->cur_pic.ptr->f->linesize[i];
1329
46.2k
        }
1330
15.4k
    }
1331
1332
167k
    if (avctx->hwaccel) {
1333
0
        if ((ret = FF_HW_CALL(avctx, start_frame, NULL, buf, buf_size)) < 0)
1334
0
            return ret;
1335
167k
    } else if (s->codec_tag == MKTAG('V', 'C', 'R', '2')) {
1336
        // Exchange UV
1337
2.98k
        FFSWAP(uint8_t*,  s->cur_pic.data[1],     s->cur_pic.data[2]);
1338
2.98k
        FFSWAP(ptrdiff_t, s->cur_pic.linesize[1], s->cur_pic.linesize[2]);
1339
2.98k
        if (!second_field) {
1340
2.26k
            FFSWAP(uint8_t*,  s->next_pic.data[1],     s->next_pic.data[2]);
1341
2.26k
            FFSWAP(ptrdiff_t, s->next_pic.linesize[1], s->next_pic.linesize[2]);
1342
2.26k
            FFSWAP(uint8_t*,  s->last_pic.data[1],     s->last_pic.data[2]);
1343
2.26k
            FFSWAP(ptrdiff_t, s->last_pic.linesize[1], s->last_pic.linesize[2]);
1344
2.26k
        }
1345
2.98k
    }
1346
1347
167k
    return 0;
1348
167k
}
1349
1350
0
#define DECODE_SLICE_ERROR -1
1351
0
#define DECODE_SLICE_OK     0
1352
1353
/**
1354
 * Decode a slice.
1355
 * Mpeg12SliceContext.c.mb_y must be set to the MB row from the startcode.
1356
 * @return DECODE_SLICE_ERROR if the slice is damaged,
1357
 *         DECODE_SLICE_OK if this slice is OK
1358
 */
1359
static int mpeg_decode_slice(Mpeg12SliceContext *const s, int mb_y,
1360
                             const uint8_t **buf, int buf_size)
1361
712k
{
1362
712k
    AVCodecContext *avctx = s->c.avctx;
1363
712k
    const int lowres      = s->c.avctx->lowres;
1364
712k
    const int field_pic   = s->c.picture_structure != PICT_FRAME;
1365
712k
    int ret;
1366
1367
712k
    s->c.resync_mb_x =
1368
712k
    s->c.resync_mb_y = -1;
1369
1370
712k
    av_assert0(mb_y < s->c.mb_height);
1371
1372
712k
    ret = init_get_bits8(&s->gb, *buf, buf_size);
1373
712k
    if (ret < 0)
1374
0
        return ret;
1375
1376
712k
    if (s->c.codec_id != AV_CODEC_ID_MPEG1VIDEO && s->c.mb_height > 2800/16)
1377
9.12k
        skip_bits(&s->gb, 3);
1378
1379
712k
    s->c.interlaced_dct = 0;
1380
1381
712k
    s->c.qscale = mpeg_get_qscale(&s->gb, s->c.q_scale_type);
1382
1383
712k
    if (s->c.qscale == 0) {
1384
64.6k
        av_log(s->c.avctx, AV_LOG_ERROR, "qscale == 0\n");
1385
64.6k
        return AVERROR_INVALIDDATA;
1386
64.6k
    }
1387
1388
    /* extra slice info */
1389
647k
    if (skip_1stop_8data_bits(&s->gb) < 0)
1390
1.25k
        return AVERROR_INVALIDDATA;
1391
1392
646k
    s->c.mb_x = 0;
1393
1394
646k
    if (mb_y == 0 && s->c.codec_tag == AV_RL32("SLIF")) {
1395
600
        skip_bits1(&s->gb);
1396
645k
    } else {
1397
848k
        while (get_bits_left(&s->gb) > 0) {
1398
842k
            int code = get_vlc2(&s->gb, ff_mbincr_vlc,
1399
842k
                                MBINCR_VLC_BITS, 2);
1400
842k
            if (code < 0) {
1401
4.27k
                av_log(s->c.avctx, AV_LOG_ERROR, "first mb_incr damaged\n");
1402
4.27k
                return AVERROR_INVALIDDATA;
1403
4.27k
            }
1404
837k
            if (code >= 33) {
1405
202k
                if (code == 33)
1406
10.6k
                    s->c.mb_x += 33;
1407
                /* otherwise, stuffing, nothing to do */
1408
635k
            } else {
1409
635k
                s->c.mb_x += code;
1410
635k
                break;
1411
635k
            }
1412
837k
        }
1413
645k
    }
1414
1415
642k
    if (s->c.mb_x >= (unsigned) s->c.mb_width) {
1416
65.1k
        av_log(s->c.avctx, AV_LOG_ERROR, "initial skip overflow\n");
1417
65.1k
        return AVERROR_INVALIDDATA;
1418
65.1k
    }
1419
1420
576k
    if (avctx->hwaccel) {
1421
0
        const uint8_t *buf_end, *buf_start = *buf - 4; /* include start_code */
1422
0
        int start_code = -1;
1423
0
        buf_end = avpriv_find_start_code(buf_start + 2, *buf + buf_size, &start_code);
1424
0
        if (buf_end < *buf + buf_size)
1425
0
            buf_end -= 4;
1426
0
        s->c.mb_y = mb_y;
1427
0
        if (FF_HW_CALL(avctx, decode_slice, buf_start, buf_end - buf_start) < 0)
1428
0
            return DECODE_SLICE_ERROR;
1429
0
        *buf = buf_end;
1430
0
        return DECODE_SLICE_OK;
1431
0
    }
1432
1433
576k
    s->c.resync_mb_x = s->c.mb_x;
1434
576k
    s->c.resync_mb_y = s->c.mb_y = mb_y;
1435
576k
    ff_init_block_index(&s->c);
1436
1437
576k
    if (s->c.mb_y == 0 && s->c.mb_x == 0 && (s->c.first_field || s->c.picture_structure == PICT_FRAME)) {
1438
310k
        if (s->c.avctx->debug & FF_DEBUG_PICT_INFO) {
1439
0
            av_log(s->c.avctx, AV_LOG_DEBUG,
1440
0
                   "qp:%d fc:%2d%2d%2d%2d %c %s %s %s %s dc:%d pstruct:%d fdct:%d cmv:%d qtype:%d ivlc:%d rff:%d %s\n",
1441
0
                   s->c.qscale,
1442
0
                   s->c.mpeg_f_code[0][0], s->c.mpeg_f_code[0][1],
1443
0
                   s->c.mpeg_f_code[1][0], s->c.mpeg_f_code[1][1],
1444
0
                   s->c.pict_type  == AV_PICTURE_TYPE_I ? 'I' :
1445
0
                   (s->c.pict_type == AV_PICTURE_TYPE_P ? 'P' :
1446
0
                   (s->c.pict_type == AV_PICTURE_TYPE_B ? 'B' : 'S')),
1447
0
                   s->c.progressive_sequence ? "ps"  : "",
1448
0
                   s->c.progressive_frame    ? "pf"  : "",
1449
0
                   s->c.alternate_scan       ? "alt" : "",
1450
0
                   s->c.top_field_first      ? "top" : "",
1451
0
                   s->c.intra_dc_precision, s->c.picture_structure,
1452
0
                   s->c.frame_pred_frame_dct, s->c.concealment_motion_vectors,
1453
0
                   s->c.q_scale_type, s->c.intra_vlc_format,
1454
0
                   s->c.repeat_first_field, s->c.chroma_420_type ? "420" : "");
1455
0
        }
1456
310k
    }
1457
1458
576k
    s->last_dc[0] = 128 << s->c.intra_dc_precision;
1459
576k
    s->last_dc[1] = s->last_dc[0];
1460
576k
    s->last_dc[2] = s->last_dc[0];
1461
576k
    memset(s->c.last_mv, 0, sizeof(s->c.last_mv));
1462
1463
3.46M
    for (int mb_skip_run = 0;;) {
1464
3.46M
        ret = mpeg_decode_mb(s, &mb_skip_run);
1465
3.46M
        if (ret < 0)
1466
382k
            return ret;
1467
1468
        // Note motion_val is normally NULL unless we want to extract the MVs.
1469
3.08M
        if (s->c.cur_pic.motion_val[0]) {
1470
350k
            const int wrap = s->c.b8_stride;
1471
350k
            int xy         = s->c.mb_x * 2 + s->c.mb_y * 2 * wrap;
1472
350k
            int b8_xy      = 4 * (s->c.mb_x + s->c.mb_y * s->c.mb_stride);
1473
350k
            int motion_x, motion_y, dir, i;
1474
1475
1.05M
            for (i = 0; i < 2; i++) {
1476
2.10M
                for (dir = 0; dir < 2; dir++) {
1477
1.40M
                    if (s->c.mb_intra ||
1478
1.32M
                        (dir == 1 && s->c.pict_type != AV_PICTURE_TYPE_B)) {
1479
609k
                        motion_x = motion_y = 0;
1480
792k
                    } else if (s->c.mv_type == MV_TYPE_16X16 ||
1481
735k
                               (s->c.mv_type == MV_TYPE_FIELD && field_pic)) {
1482
735k
                        motion_x = s->c.mv[dir][0][0];
1483
735k
                        motion_y = s->c.mv[dir][0][1];
1484
735k
                    } else { /* if ((s->c.mv_type == MV_TYPE_FIELD) || (s->c.mv_type == MV_TYPE_16X8)) */
1485
56.9k
                        motion_x = s->c.mv[dir][i][0];
1486
56.9k
                        motion_y = s->c.mv[dir][i][1];
1487
56.9k
                    }
1488
1489
1.40M
                    s->c.cur_pic.motion_val[dir][xy][0]     = motion_x;
1490
1.40M
                    s->c.cur_pic.motion_val[dir][xy][1]     = motion_y;
1491
1.40M
                    s->c.cur_pic.motion_val[dir][xy + 1][0] = motion_x;
1492
1.40M
                    s->c.cur_pic.motion_val[dir][xy + 1][1] = motion_y;
1493
1.40M
                    s->c.cur_pic.ref_index [dir][b8_xy]     =
1494
1.40M
                    s->c.cur_pic.ref_index [dir][b8_xy + 1] = s->c.field_select[dir][i];
1495
1.40M
                    av_assert2(s->c.field_select[dir][i] == 0 ||
1496
1.40M
                               s->c.field_select[dir][i] == 1);
1497
1.40M
                }
1498
700k
                xy    += wrap;
1499
700k
                b8_xy += 2;
1500
700k
            }
1501
350k
        }
1502
1503
3.08M
        s->c.dest[0] += 16 >> lowres;
1504
3.08M
        s->c.dest[1] +=(16 >> lowres) >> s->c.chroma_x_shift;
1505
3.08M
        s->c.dest[2] +=(16 >> lowres) >> s->c.chroma_x_shift;
1506
1507
3.08M
        ff_mpv_reconstruct_mb(&s->c, s->block);
1508
1509
3.08M
        if (++s->c.mb_x >= s->c.mb_width) {
1510
1.04M
            const int mb_size = 16 >> s->c.avctx->lowres;
1511
1.04M
            int left;
1512
1513
1.04M
            ff_mpeg_draw_horiz_band(&s->c, mb_size * (s->c.mb_y >> field_pic), mb_size);
1514
1515
1.04M
            s->c.mb_x  = 0;
1516
1.04M
            s->c.mb_y += 1 << field_pic;
1517
1518
1.04M
            if (s->c.mb_y >= s->c.mb_height) {
1519
127k
                int left   = get_bits_left(&s->gb);
1520
127k
                int is_d10 = s->c.chroma_format == CHROMA_422 &&
1521
21.1k
                             s->c.pict_type == AV_PICTURE_TYPE_I &&
1522
14.3k
                             avctx->profile == 0 && avctx->level == 5 &&
1523
4.04k
                             s->c.intra_dc_precision == 2 &&
1524
2.93k
                             s->c.q_scale_type == 1 && s->c.alternate_scan == 0 &&
1525
1.18k
                             s->c.progressive_frame == 0
1526
127k
                             /* vbv_delay == 0xBBB || 0xE10 */;
1527
1528
127k
                if (left >= 32 && !is_d10) {
1529
118k
                    GetBitContext gb = s->gb;
1530
118k
                    align_get_bits(&gb);
1531
118k
                    if (show_bits(&gb, 24) == 0x060E2B) {
1532
23.4k
                        av_log(avctx, AV_LOG_DEBUG, "Invalid MXF data found in video stream\n");
1533
23.4k
                        is_d10 = 1;
1534
23.4k
                    }
1535
118k
                    if (left > 32 && show_bits_long(&gb, 32) == 0x201) {
1536
8.71k
                        av_log(avctx, AV_LOG_DEBUG, "skipping m704 alpha (unsupported)\n");
1537
8.71k
                        goto eos;
1538
8.71k
                    }
1539
118k
                }
1540
1541
118k
                if (left < 0 ||
1542
115k
                    (left && show_bits(&s->gb, FFMIN(left, 23)) && !is_d10) ||
1543
104k
                    ((avctx->err_recognition & (AV_EF_BITSTREAM | AV_EF_AGGRESSIVE)) && left > 8)) {
1544
104k
                    av_log(avctx, AV_LOG_ERROR, "end mismatch left=%d %0X at %d %d\n",
1545
104k
                           left, left>0 ? show_bits(&s->gb, FFMIN(left, 23)) : 0, s->c.mb_x, s->c.mb_y);
1546
104k
                    return AVERROR_INVALIDDATA;
1547
104k
                } else
1548
13.7k
                    goto eos;
1549
118k
            }
1550
            // There are some files out there which are missing the last slice
1551
            // in cases where the slice is completely outside the visible
1552
            // area, we detect this here instead of running into the end expecting
1553
            // more data
1554
919k
            left = get_bits_left(&s->gb);
1555
919k
            if (s->c.mb_y >= ((s->c.height + 15) >> 4) &&
1556
61.9k
                !s->c.progressive_sequence &&
1557
61.9k
                left <= 25 &&
1558
6.19k
                left >= 0 &&
1559
5.03k
                mb_skip_run == -1 &&
1560
4.37k
                (!left || show_bits(&s->gb, left) == 0))
1561
1.80k
                goto eos;
1562
1563
918k
            ff_init_block_index(&s->c);
1564
918k
        }
1565
1566
        /* skip mb handling */
1567
2.95M
        if (mb_skip_run == -1) {
1568
            /* read increment again */
1569
1.24M
            mb_skip_run = 0;
1570
1.25M
            for (;;) {
1571
1.25M
                int code = get_vlc2(&s->gb, ff_mbincr_vlc,
1572
1.25M
                                    MBINCR_VLC_BITS, 2);
1573
1.25M
                if (code < 0) {
1574
9.86k
                    av_log(s->c.avctx, AV_LOG_ERROR, "mb incr damaged\n");
1575
9.86k
                    return AVERROR_INVALIDDATA;
1576
9.86k
                }
1577
1.24M
                if (code >= 33) {
1578
54.8k
                    if (code == 33) {
1579
4.54k
                        mb_skip_run += 33;
1580
50.3k
                    } else if (code == 35) {
1581
48.0k
                        if (mb_skip_run != 0 || show_bits(&s->gb, 15) != 0) {
1582
16.7k
                            av_log(s->c.avctx, AV_LOG_ERROR, "slice mismatch\n");
1583
16.7k
                            return AVERROR_INVALIDDATA;
1584
16.7k
                        }
1585
31.3k
                        goto eos; /* end of slice */
1586
48.0k
                    }
1587
                    /* otherwise, stuffing, nothing to do */
1588
1.18M
                } else {
1589
1.18M
                    mb_skip_run += code;
1590
1.18M
                    break;
1591
1.18M
                }
1592
1.24M
            }
1593
1.18M
            if (mb_skip_run) {
1594
539k
                int i;
1595
539k
                if (s->c.pict_type == AV_PICTURE_TYPE_I) {
1596
7.57k
                    av_log(s->c.avctx, AV_LOG_ERROR,
1597
7.57k
                           "skipped MB in I-frame at %d %d\n", s->c.mb_x, s->c.mb_y);
1598
7.57k
                    return AVERROR_INVALIDDATA;
1599
7.57k
                }
1600
1601
                /* skip mb */
1602
531k
                s->c.mb_intra = 0;
1603
6.90M
                for (i = 0; i < 12; i++)
1604
6.37M
                    s->c.block_last_index[i] = -1;
1605
531k
                s->last_dc[0] = s->last_dc[1] = s->last_dc[2] = 128 << s->c.intra_dc_precision;
1606
531k
                if (s->c.picture_structure == PICT_FRAME)
1607
511k
                    s->c.mv_type = MV_TYPE_16X16;
1608
19.8k
                else
1609
19.8k
                    s->c.mv_type = MV_TYPE_FIELD;
1610
531k
                if (s->c.pict_type == AV_PICTURE_TYPE_P) {
1611
                    /* if P type, zero motion vector is implied */
1612
390k
                    s->c.mv_dir             = MV_DIR_FORWARD;
1613
390k
                    s->c.mv[0][0][0]        = s->c.mv[0][0][1]      = 0;
1614
390k
                    s->c.last_mv[0][0][0]   = s->c.last_mv[0][0][1] = 0;
1615
390k
                    s->c.last_mv[0][1][0]   = s->c.last_mv[0][1][1] = 0;
1616
390k
                    s->c.field_select[0][0] = (s->c.picture_structure - 1) & 1;
1617
390k
                } else {
1618
                    /* if B type, reuse previous vectors and directions */
1619
141k
                    s->c.mv[0][0][0] = s->c.last_mv[0][0][0];
1620
141k
                    s->c.mv[0][0][1] = s->c.last_mv[0][0][1];
1621
141k
                    s->c.mv[1][0][0] = s->c.last_mv[1][0][0];
1622
141k
                    s->c.mv[1][0][1] = s->c.last_mv[1][0][1];
1623
141k
                    s->c.field_select[0][0] = (s->c.picture_structure - 1) & 1;
1624
141k
                    s->c.field_select[1][0] = (s->c.picture_structure - 1) & 1;
1625
141k
                }
1626
531k
            }
1627
1.18M
        }
1628
2.95M
    }
1629
55.6k
eos: // end of slice
1630
55.6k
    if (get_bits_left(&s->gb) < 0) {
1631
3.90k
        av_log(s->c.avctx, AV_LOG_ERROR, "overread %d\n", -get_bits_left(&s->gb));
1632
3.90k
        return AVERROR_INVALIDDATA;
1633
3.90k
    }
1634
51.7k
    *buf += (get_bits_count(&s->gb) - 1) / 8;
1635
51.7k
    ff_dlog(s->c.avctx, "Slice start:%d %d  end:%d %d\n", s->c.resync_mb_x, s->c.resync_mb_y, s->c.mb_x, s->c.mb_y);
1636
51.7k
    return 0;
1637
55.6k
}
1638
1639
static int slice_decode_thread(AVCodecContext *c, void *arg)
1640
0
{
1641
0
    Mpeg12SliceContext *const s = *(void **) arg;
1642
0
    const uint8_t *buf  = s->gb.buffer;
1643
0
    const uint8_t *end  = buf + get_bits_bytesize(&s->gb, 0);
1644
0
    int mb_y            = s->c.start_mb_y;
1645
0
    const int field_pic = s->c.picture_structure != PICT_FRAME;
1646
1647
0
    s->c.er.error_count = (3 * (s->c.end_mb_y - s->c.start_mb_y) * s->c.mb_width) >> field_pic;
1648
1649
0
    for (;;) {
1650
0
        uint32_t start_code;
1651
0
        int ret;
1652
1653
0
        ret = mpeg_decode_slice(s, mb_y, &buf, end - buf);
1654
0
        emms_c();
1655
0
        ff_dlog(c, "ret:%d resync:%d/%d mb:%d/%d ts:%d/%d ec:%d\n",
1656
0
                ret, s->c.resync_mb_x, s->c.resync_mb_y, s->c.mb_x, s->c.mb_y,
1657
0
                s->c.start_mb_y, s->c.end_mb_y, s->c.er.error_count);
1658
0
        if (ret < 0) {
1659
0
            if (c->err_recognition & AV_EF_EXPLODE)
1660
0
                return ret;
1661
0
            if (s->c.resync_mb_x >= 0 && s->c.resync_mb_y >= 0)
1662
0
                ff_er_add_slice(&s->c.er, s->c.resync_mb_x, s->c.resync_mb_y,
1663
0
                                s->c.mb_x, s->c.mb_y,
1664
0
                                ER_AC_ERROR | ER_DC_ERROR | ER_MV_ERROR);
1665
0
        } else {
1666
0
            ff_er_add_slice(&s->c.er, s->c.resync_mb_x, s->c.resync_mb_y,
1667
0
                            s->c.mb_x - 1, s->c.mb_y,
1668
0
                            ER_AC_END | ER_DC_END | ER_MV_END);
1669
0
        }
1670
1671
0
        if (s->c.mb_y == s->c.end_mb_y)
1672
0
            return 0;
1673
1674
0
        start_code = -1;
1675
0
        buf        = avpriv_find_start_code(buf, end, &start_code);
1676
0
        if (start_code < SLICE_MIN_START_CODE || start_code > SLICE_MAX_START_CODE)
1677
0
            return AVERROR_INVALIDDATA;
1678
0
        mb_y       = start_code - SLICE_MIN_START_CODE;
1679
0
        if (s->c.codec_id != AV_CODEC_ID_MPEG1VIDEO && s->c.mb_height > 2800/16)
1680
0
            mb_y += (*buf&0xE0)<<2;
1681
0
        mb_y <<= field_pic;
1682
0
        if (s->c.picture_structure == PICT_BOTTOM_FIELD)
1683
0
            mb_y++;
1684
0
        if (mb_y >= s->c.end_mb_y)
1685
0
            return AVERROR_INVALIDDATA;
1686
0
    }
1687
0
}
1688
1689
/**
1690
 * Handle slice ends.
1691
 * @return 1 if it seems to be the last slice
1692
 */
1693
static int slice_end(AVCodecContext *avctx, AVFrame *pict, int *got_output)
1694
564k
{
1695
564k
    Mpeg1Context *s1  = avctx->priv_data;
1696
564k
    MPVContext *const s = &s1->slice.c;
1697
1698
564k
    if (!s->context_initialized || !s->cur_pic.ptr)
1699
430k
        return 0;
1700
1701
133k
    if (s->avctx->hwaccel) {
1702
0
        int ret = FF_HW_SIMPLE_CALL(s->avctx, end_frame);
1703
0
        if (ret < 0) {
1704
0
            av_log(avctx, AV_LOG_ERROR,
1705
0
                   "hardware accelerator failed to decode picture\n");
1706
0
            return ret;
1707
0
        }
1708
0
    }
1709
1710
    /* end of slice reached */
1711
133k
    if (/* s->mb_y << field_pic == s->mb_height && */ !s->first_field && !s1->first_slice) {
1712
        /* end of image */
1713
1714
118k
        ff_er_frame_end(&s->er, NULL);
1715
1716
118k
        ff_mpv_frame_end(s);
1717
1718
118k
        if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay) {
1719
42.0k
            int ret = av_frame_ref(pict, s->cur_pic.ptr->f);
1720
42.0k
            if (ret < 0)
1721
0
                return ret;
1722
42.0k
            ff_print_debug_info(s, s->cur_pic.ptr, pict);
1723
42.0k
            ff_mpv_export_qp_table(s, pict, s->cur_pic.ptr, FF_MPV_QSCALE_TYPE_MPEG2);
1724
42.0k
            *got_output = 1;
1725
76.2k
        } else {
1726
            /* latency of 1 frame for I- and P-frames */
1727
76.2k
            if (s->last_pic.ptr && !s->last_pic.ptr->dummy) {
1728
31.0k
                int ret = av_frame_ref(pict, s->last_pic.ptr->f);
1729
31.0k
                if (ret < 0)
1730
0
                    return ret;
1731
31.0k
                ff_print_debug_info(s, s->last_pic.ptr, pict);
1732
31.0k
                ff_mpv_export_qp_table(s, pict, s->last_pic.ptr, FF_MPV_QSCALE_TYPE_MPEG2);
1733
31.0k
                *got_output = 1;
1734
31.0k
            }
1735
76.2k
        }
1736
1737
118k
        return 1;
1738
118k
    } else {
1739
14.9k
        return 0;
1740
14.9k
    }
1741
133k
}
1742
1743
static int mpeg1_decode_sequence(AVCodecContext *avctx,
1744
                                 const uint8_t *buf, int buf_size)
1745
210k
{
1746
210k
    Mpeg1Context *s1  = avctx->priv_data;
1747
210k
    MPVContext *const s = &s1->slice.c;
1748
210k
    GetBitContext gb0, *const gb = &gb0;
1749
210k
    int width, height;
1750
210k
    int i, v, j;
1751
1752
210k
    int ret = init_get_bits8(gb, buf, buf_size);
1753
210k
    if (ret < 0)
1754
0
        return ret;
1755
1756
210k
    width  = get_bits(gb, 12);
1757
210k
    height = get_bits(gb, 12);
1758
210k
    if (width == 0 || height == 0) {
1759
32.6k
        av_log(avctx, AV_LOG_WARNING,
1760
32.6k
               "Invalid horizontal or vertical size value.\n");
1761
32.6k
        if (avctx->err_recognition & (AV_EF_BITSTREAM | AV_EF_COMPLIANT))
1762
9.31k
            return AVERROR_INVALIDDATA;
1763
32.6k
    }
1764
201k
    s1->aspect_ratio_info = get_bits(gb, 4);
1765
201k
    if (s1->aspect_ratio_info == 0) {
1766
119k
        av_log(avctx, AV_LOG_ERROR, "aspect ratio has forbidden 0 value\n");
1767
119k
        if (avctx->err_recognition & (AV_EF_BITSTREAM | AV_EF_COMPLIANT))
1768
43.8k
            return AVERROR_INVALIDDATA;
1769
119k
    }
1770
157k
    s1->frame_rate_index = get_bits(gb, 4);
1771
157k
    if (s1->frame_rate_index == 0 || s1->frame_rate_index > 13) {
1772
102k
        av_log(avctx, AV_LOG_WARNING,
1773
102k
               "frame_rate_index %d is invalid\n", s1->frame_rate_index);
1774
102k
        s1->frame_rate_index = 1;
1775
102k
    }
1776
157k
    s1->bit_rate = get_bits(gb, 18) * 400;
1777
157k
    if (check_marker(s->avctx, gb, "in sequence header") == 0) {
1778
45.4k
        return AVERROR_INVALIDDATA;
1779
45.4k
    }
1780
1781
112k
    s->avctx->rc_buffer_size = get_bits(gb, 10) * 1024 * 16;
1782
112k
    skip_bits(gb, 1);
1783
1784
    /* get matrix */
1785
112k
    if (get_bits1(gb)) {
1786
33.4k
        load_matrix(s, gb, s->chroma_intra_matrix, s->intra_matrix, 1);
1787
78.7k
    } else {
1788
5.11M
        for (i = 0; i < 64; i++) {
1789
5.04M
            j = s->idsp.idct_permutation[i];
1790
5.04M
            v = ff_mpeg1_default_intra_matrix[i];
1791
5.04M
            s->intra_matrix[j]        = v;
1792
5.04M
            s->chroma_intra_matrix[j] = v;
1793
5.04M
        }
1794
78.7k
    }
1795
112k
    if (get_bits1(gb)) {
1796
23.5k
        load_matrix(s, gb, s->chroma_inter_matrix, s->inter_matrix, 0);
1797
88.6k
    } else {
1798
5.76M
        for (i = 0; i < 64; i++) {
1799
5.67M
            int j = s->idsp.idct_permutation[i];
1800
5.67M
            v = ff_mpeg1_default_non_intra_matrix[i];
1801
5.67M
            s->inter_matrix[j]        = v;
1802
5.67M
            s->chroma_inter_matrix[j] = v;
1803
5.67M
        }
1804
88.6k
    }
1805
1806
112k
    if (show_bits(gb, 23) != 0) {
1807
32.9k
        av_log(s->avctx, AV_LOG_ERROR, "sequence header damaged\n");
1808
32.9k
        return AVERROR_INVALIDDATA;
1809
32.9k
    }
1810
1811
79.2k
    s->width  = width;
1812
79.2k
    s->height = height;
1813
1814
    /* We set MPEG-2 parameters so that it emulates MPEG-1. */
1815
79.2k
    s->progressive_sequence = 1;
1816
79.2k
    s->progressive_frame    = 1;
1817
79.2k
    s->picture_structure    = PICT_FRAME;
1818
79.2k
    s->first_field          = 0;
1819
79.2k
    s->frame_pred_frame_dct = 1;
1820
79.2k
    s->chroma_format        = CHROMA_420;
1821
79.2k
    s->codec_id             =
1822
79.2k
    s->avctx->codec_id      = AV_CODEC_ID_MPEG1VIDEO;
1823
79.2k
    if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)
1824
0
        s->low_delay = 1;
1825
1826
79.2k
    if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1827
0
        av_log(s->avctx, AV_LOG_DEBUG, "vbv buffer: %d, bitrate:%"PRId64", aspect_ratio_info: %d \n",
1828
0
               s->avctx->rc_buffer_size, s1->bit_rate, s1->aspect_ratio_info);
1829
1830
79.2k
    return 0;
1831
112k
}
1832
1833
static int vcr2_init_sequence(AVCodecContext *avctx)
1834
5.55k
{
1835
5.55k
    Mpeg1Context *s1  = avctx->priv_data;
1836
5.55k
    MPVContext *const s = &s1->slice.c;
1837
5.55k
    int i, v, ret;
1838
1839
    /* start new MPEG-1 context decoding */
1840
5.55k
    if (s->context_initialized)
1841
0
        ff_mpv_common_end(s);
1842
1843
5.55k
    s->width            = avctx->coded_width;
1844
5.55k
    s->height           = avctx->coded_height;
1845
5.55k
    avctx->has_b_frames = 0; // true?
1846
5.55k
    s->low_delay        = 1;
1847
1848
5.55k
    avctx->pix_fmt = mpeg_get_pixelformat(avctx);
1849
1850
5.55k
    if ((ret = ff_mpv_common_init(s)) < 0)
1851
0
        return ret;
1852
5.55k
    if (!s->avctx->lowres)
1853
5.56k
        for (int i = 0; i < s->slice_context_count; i++)
1854
2.78k
            ff_mpv_framesize_disable(&s->thread_context[i]->sc);
1855
1856
361k
    for (i = 0; i < 64; i++) {
1857
355k
        int j = s->idsp.idct_permutation[i];
1858
355k
        v = ff_mpeg1_default_intra_matrix[i];
1859
355k
        s->intra_matrix[j]        = v;
1860
355k
        s->chroma_intra_matrix[j] = v;
1861
1862
355k
        v = ff_mpeg1_default_non_intra_matrix[i];
1863
355k
        s->inter_matrix[j]        = v;
1864
355k
        s->chroma_inter_matrix[j] = v;
1865
355k
    }
1866
1867
5.55k
    s->progressive_sequence  = 1;
1868
5.55k
    s->progressive_frame     = 1;
1869
5.55k
    s->picture_structure     = PICT_FRAME;
1870
5.55k
    s->first_field           = 0;
1871
5.55k
    s->frame_pred_frame_dct  = 1;
1872
5.55k
    s->chroma_format         = CHROMA_420;
1873
5.55k
    if (s->codec_tag == AV_RL32("BW10")) {
1874
768
        s->codec_id              = s->avctx->codec_id = AV_CODEC_ID_MPEG1VIDEO;
1875
4.78k
    } else {
1876
4.78k
        s->codec_id              = s->avctx->codec_id = AV_CODEC_ID_MPEG2VIDEO;
1877
4.78k
    }
1878
5.55k
    s1->save_progressive_seq = s->progressive_sequence;
1879
5.55k
    s1->save_chroma_format   = s->chroma_format;
1880
5.55k
    return 0;
1881
5.55k
}
1882
1883
static void mpeg_set_cc_format(AVCodecContext *avctx, enum Mpeg2ClosedCaptionsFormat format,
1884
                               const char *label)
1885
234k
{
1886
234k
    Mpeg1Context *s1 = avctx->priv_data;
1887
1888
234k
    av_assert2(format != CC_FORMAT_AUTO);
1889
1890
234k
    if (!s1->cc_format) {
1891
2.15k
        s1->cc_format = format;
1892
1893
2.15k
        av_log(avctx, AV_LOG_DEBUG, "CC: first seen substream is %s format\n", label);
1894
2.15k
    }
1895
1896
234k
#if FF_API_CODEC_PROPS
1897
234k
FF_DISABLE_DEPRECATION_WARNINGS
1898
234k
    avctx->properties |= FF_CODEC_PROPERTY_CLOSED_CAPTIONS;
1899
234k
FF_ENABLE_DEPRECATION_WARNINGS
1900
234k
#endif
1901
234k
}
1902
1903
static int mpeg_decode_a53_cc(AVCodecContext *avctx,
1904
                              const uint8_t *p, int buf_size)
1905
911k
{
1906
911k
    Mpeg1Context *s1 = avctx->priv_data;
1907
1908
911k
    if ((!s1->cc_format || s1->cc_format == CC_FORMAT_A53_PART4) &&
1909
434k
        buf_size >= 6 &&
1910
427k
        p[0] == 'G' && p[1] == 'A' && p[2] == '9' && p[3] == '4' &&
1911
26.8k
        p[4] == 3 && (p[5] & 0x40)) {
1912
        /* extract A53 Part 4 CC data */
1913
23.3k
        int cc_count = p[5] & 0x1f;
1914
23.3k
        if (cc_count > 0 && buf_size >= 7 + cc_count * 3) {
1915
21.0k
            int old_size = s1->a53_buf_ref ? s1->a53_buf_ref->size : 0;
1916
21.0k
            const uint64_t new_size = (old_size + cc_count
1917
21.0k
                                            * UINT64_C(3));
1918
21.0k
            int ret;
1919
1920
21.0k
            if (new_size > 3*A53_MAX_CC_COUNT)
1921
3.97k
                return AVERROR(EINVAL);
1922
1923
17.0k
            ret = av_buffer_realloc(&s1->a53_buf_ref, new_size);
1924
17.0k
            if (ret >= 0)
1925
17.0k
                memcpy(s1->a53_buf_ref->data + old_size, p + 7, cc_count * UINT64_C(3));
1926
1927
17.0k
            mpeg_set_cc_format(avctx, CC_FORMAT_A53_PART4, "A/53 Part 4");
1928
17.0k
        }
1929
19.3k
        return 1;
1930
888k
    } else if ((!s1->cc_format || s1->cc_format == CC_FORMAT_SCTE20) &&
1931
538k
               buf_size >= 2 &&
1932
536k
               p[0] == 0x03 && (p[1]&0x7f) == 0x01) {
1933
        /* extract SCTE-20 CC data */
1934
137k
        GetBitContext gb;
1935
137k
        int cc_count = 0;
1936
137k
        int i, ret;
1937
1938
137k
        ret = init_get_bits8(&gb, p + 2, buf_size - 2);
1939
137k
        if (ret < 0)
1940
0
            return ret;
1941
137k
        cc_count = get_bits(&gb, 5);
1942
137k
        if (cc_count > 0) {
1943
134k
            int old_size = s1->a53_buf_ref ? s1->a53_buf_ref->size : 0;
1944
134k
            const uint64_t new_size = (old_size + cc_count
1945
134k
                                            * UINT64_C(3));
1946
134k
            if (new_size > 3*A53_MAX_CC_COUNT)
1947
82.1k
                return AVERROR(EINVAL);
1948
1949
52.3k
            ret = av_buffer_realloc(&s1->a53_buf_ref, new_size);
1950
52.3k
            if (ret >= 0) {
1951
52.3k
                uint8_t field, cc1, cc2;
1952
52.3k
                uint8_t *cap = s1->a53_buf_ref->data + old_size;
1953
1954
52.3k
                memset(cap, 0, cc_count * 3);
1955
1.29M
                for (i = 0; i < cc_count && get_bits_left(&gb) >= 26; i++) {
1956
1.24M
                    skip_bits(&gb, 2); // priority
1957
1.24M
                    field = get_bits(&gb, 2);
1958
1.24M
                    skip_bits(&gb, 5); // line_offset
1959
1.24M
                    cc1 = get_bits(&gb, 8);
1960
1.24M
                    cc2 = get_bits(&gb, 8);
1961
1.24M
                    skip_bits(&gb, 1); // marker
1962
1963
1.24M
                    if (!field) { // forbidden
1964
658k
                        cap[0] = cap[1] = cap[2] = 0x00;
1965
658k
                    } else {
1966
588k
                        field = (field == 2 ? 1 : 0);
1967
588k
                        if (!s1->slice.c.top_field_first) field = !field;
1968
588k
                        cap[0] = 0x04 | field;
1969
588k
                        cap[1] = ff_reverse[cc1];
1970
588k
                        cap[2] = ff_reverse[cc2];
1971
588k
                    }
1972
1.24M
                    cap += 3;
1973
1.24M
                }
1974
52.3k
            }
1975
1976
52.3k
            mpeg_set_cc_format(avctx, CC_FORMAT_SCTE20, "SCTE-20");
1977
52.3k
        }
1978
55.0k
        return 1;
1979
750k
    } else if ((!s1->cc_format || s1->cc_format == CC_FORMAT_DVD) &&
1980
418k
               buf_size >= 11 &&
1981
406k
               p[0] == 'C' && p[1] == 'C' && p[2] == 0x01 && p[3] == 0xf8) {
1982
        /* extract DVD CC data
1983
         *
1984
         * uint32_t   user_data_start_code        0x000001B2    (big endian)
1985
         * uint16_t   user_identifier             0x4343 "CC"
1986
         * uint8_t    user_data_type_code         0x01
1987
         * uint8_t    caption_block_size          0xF8
1988
         * uint8_t
1989
         *   bit 7    caption_odd_field_first     1=odd field (CC1/CC2) first  0=even field (CC3/CC4) first
1990
         *   bit 6    caption_filler              0
1991
         *   bit 5:1  caption_block_count         number of caption blocks (pairs of caption words = frames). Most DVDs use 15 per start of GOP.
1992
         *   bit 0    caption_extra_field_added   1=one additional caption word
1993
         *
1994
         * struct caption_field_block {
1995
         *   uint8_t
1996
         *     bit 7:1 caption_filler             0x7F (all 1s)
1997
         *     bit 0   caption_field_odd          1=odd field (this is CC1/CC2)  0=even field (this is CC3/CC4)
1998
         *   uint8_t   caption_first_byte
1999
         *   uint8_t   caption_second_byte
2000
         * } caption_block[(caption_block_count * 2) + caption_extra_field_added];
2001
         *
2002
         * Some DVDs encode caption data for both fields with caption_field_odd=1. The only way to decode the fields
2003
         * correctly is to start on the field indicated by caption_odd_field_first and count between odd/even fields.
2004
         * Don't assume that the first caption word is the odd field. There do exist MPEG files in the wild that start
2005
         * on the even field. There also exist DVDs in the wild that encode an odd field count and the
2006
         * caption_extra_field_added/caption_odd_field_first bits change per packet to allow that. */
2007
33.3k
        int cc_count = 0;
2008
33.3k
        int i, ret;
2009
        // There is a caption count field in the data, but it is often
2010
        // incorrect.  So count the number of captions present.
2011
90.8k
        for (i = 5; i + 6 <= buf_size && ((p[i] & 0xfe) == 0xfe); i += 6)
2012
57.4k
            cc_count++;
2013
        // Transform the DVD format into A53 Part 4 format
2014
33.3k
        if (cc_count > 0) {
2015
31.8k
            int old_size = s1->a53_buf_ref ? s1->a53_buf_ref->size : 0;
2016
31.8k
            const uint64_t new_size = (old_size + cc_count
2017
31.8k
                                            * UINT64_C(6));
2018
31.8k
            if (new_size > 3*A53_MAX_CC_COUNT)
2019
9.46k
                return AVERROR(EINVAL);
2020
2021
22.3k
            ret = av_buffer_realloc(&s1->a53_buf_ref, new_size);
2022
22.3k
            if (ret >= 0) {
2023
22.3k
                uint8_t field1 = !!(p[4] & 0x80);
2024
22.3k
                uint8_t *cap = s1->a53_buf_ref->data + old_size;
2025
22.3k
                p += 5;
2026
67.8k
                for (i = 0; i < cc_count; i++) {
2027
45.4k
                    cap[0] = (p[0] == 0xff && field1) ? 0xfc : 0xfd;
2028
45.4k
                    cap[1] = p[1];
2029
45.4k
                    cap[2] = p[2];
2030
45.4k
                    cap[3] = (p[3] == 0xff && !field1) ? 0xfc : 0xfd;
2031
45.4k
                    cap[4] = p[4];
2032
45.4k
                    cap[5] = p[5];
2033
45.4k
                    cap += 6;
2034
45.4k
                    p += 6;
2035
45.4k
                }
2036
22.3k
            }
2037
2038
22.3k
            mpeg_set_cc_format(avctx, CC_FORMAT_DVD, "DVD");
2039
22.3k
        }
2040
23.9k
        return 1;
2041
717k
    } else if ((!s1->cc_format || s1->cc_format == CC_FORMAT_DISH) &&
2042
618k
               buf_size >= 12 &&
2043
603k
               p[0] == 0x05 && p[1] == 0x02) {
2044
        /* extract Dish Network CC data */
2045
199k
        const uint8_t cc_header = 0xf8 | 0x04 /* valid */ | 0x00 /* line 21 field 1 */;
2046
199k
        uint8_t cc_data[4] = {0};
2047
199k
        int cc_count = 0;
2048
199k
        uint8_t cc_type = p[7];
2049
199k
        p += 8;
2050
199k
        buf_size -= 8;
2051
2052
199k
        if (cc_type == 0x05 && buf_size >= 7) {
2053
51.9k
            cc_type = p[6];
2054
51.9k
            p += 7;
2055
51.9k
            buf_size -= 7;
2056
51.9k
        }
2057
2058
199k
        if (cc_type == 0x02 && buf_size >= 4) { /* 2-byte caption, can be repeated */
2059
128k
            cc_count = 1;
2060
128k
            cc_data[0] = p[1];
2061
128k
            cc_data[1] = p[2];
2062
128k
            cc_type = p[3];
2063
2064
            /* Only repeat characters when the next type flag
2065
             * is 0x04 and the characters are repeatable (i.e., less than
2066
             * 32 with the parity stripped).
2067
             */
2068
128k
            if (cc_type == 0x04 && (cc_data[0] & 0x7f) < 32) {
2069
26.3k
                cc_count = 2;
2070
26.3k
                cc_data[2] = cc_data[0];
2071
26.3k
                cc_data[3] = cc_data[1];
2072
26.3k
            }
2073
128k
        } else if (cc_type == 0x04 && buf_size >= 5) { /* 4-byte caption, not repeated */
2074
35.5k
            cc_count = 2;
2075
35.5k
            cc_data[0] = p[1];
2076
35.5k
            cc_data[1] = p[2];
2077
35.5k
            cc_data[2] = p[3];
2078
35.5k
            cc_data[3] = p[4];
2079
35.5k
        }
2080
2081
199k
        if (cc_count > 0) {
2082
164k
            int ret;
2083
164k
            int old_size = s1->a53_buf_ref ? s1->a53_buf_ref->size : 0;
2084
164k
            const uint64_t new_size = (old_size + cc_count * UINT64_C(3));
2085
164k
            if (new_size > 3 * A53_MAX_CC_COUNT)
2086
21.6k
                return AVERROR(EINVAL);
2087
2088
142k
            ret = av_buffer_realloc(&s1->a53_buf_ref, new_size);
2089
142k
            if (ret >= 0) {
2090
142k
                uint8_t *cap = s1->a53_buf_ref->data + old_size;
2091
142k
                cap[0] = cc_header;
2092
142k
                cap[1] = cc_data[0];
2093
142k
                cap[2] = cc_data[1];
2094
142k
                if (cc_count == 2) {
2095
45.4k
                    cap[3] = cc_header;
2096
45.4k
                    cap[4] = cc_data[2];
2097
45.4k
                    cap[5] = cc_data[3];
2098
45.4k
                }
2099
142k
            }
2100
2101
142k
            mpeg_set_cc_format(avctx, CC_FORMAT_DISH, "Dish Network");
2102
142k
        }
2103
177k
        return 1;
2104
199k
    }
2105
518k
    return 0;
2106
911k
}
2107
2108
static void mpeg_decode_user_data(AVCodecContext *avctx,
2109
                                  const uint8_t *p, int buf_size)
2110
929k
{
2111
929k
    const uint8_t *buf_end = p + buf_size;
2112
929k
    Mpeg1Context *s1 = avctx->priv_data;
2113
2114
#if 0
2115
    int i;
2116
    for(i=0; !(!p[i-2] && !p[i-1] && p[i]==1) && i<buf_size; i++){
2117
        av_log(avctx, AV_LOG_ERROR, "%c", p[i]);
2118
    }
2119
    av_log(avctx, AV_LOG_ERROR, "\n");
2120
#endif
2121
2122
929k
    if (buf_size > 29){
2123
891k
        int i;
2124
18.7M
        for(i=0; i<20; i++)
2125
17.8M
            if (!memcmp(p+i, "\0TMPGEXS\0", 9)){
2126
23.9k
                s1->tmpgexs = 1;
2127
23.9k
            }
2128
891k
    }
2129
    /* we parse the DTG active format information */
2130
929k
    if (buf_end - p >= 5 &&
2131
926k
        p[0] == 'D' && p[1] == 'T' && p[2] == 'G' && p[3] == '1') {
2132
10.3k
        int flags = p[4];
2133
10.3k
        p += 5;
2134
10.3k
        if (flags & 0x80) {
2135
            /* skip event id */
2136
6.09k
            p += 2;
2137
6.09k
        }
2138
10.3k
        if (flags & 0x40) {
2139
9.11k
            if (buf_end - p < 1)
2140
727
                return;
2141
8.38k
            s1->has_afd = 1;
2142
8.38k
            s1->afd     = p[0] & 0x0f;
2143
8.38k
        }
2144
919k
    } else if (buf_end - p >= 6 &&
2145
911k
               p[0] == 'J' && p[1] == 'P' && p[2] == '3' && p[3] == 'D' &&
2146
8.71k
               p[4] == 0x03) { // S3D_video_format_length
2147
        // the 0x7F mask ignores the reserved_bit value
2148
7.97k
        const uint8_t S3D_video_format_type = p[5] & 0x7F;
2149
2150
7.97k
        if (S3D_video_format_type == 0x03 ||
2151
6.55k
            S3D_video_format_type == 0x04 ||
2152
5.57k
            S3D_video_format_type == 0x08 ||
2153
6.88k
            S3D_video_format_type == 0x23) {
2154
2155
6.88k
            s1->has_stereo3d = 1;
2156
2157
6.88k
            switch (S3D_video_format_type) {
2158
1.41k
            case 0x03:
2159
1.41k
                s1->stereo3d_type = AV_STEREO3D_SIDEBYSIDE;
2160
1.41k
                break;
2161
980
            case 0x04:
2162
980
                s1->stereo3d_type = AV_STEREO3D_TOPBOTTOM;
2163
980
                break;
2164
2.03k
            case 0x08:
2165
2.03k
                s1->stereo3d_type = AV_STEREO3D_2D;
2166
2.03k
                break;
2167
2.44k
            case 0x23:
2168
2.44k
                s1->stereo3d_type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
2169
2.44k
                break;
2170
6.88k
            }
2171
6.88k
        }
2172
911k
    } else if (mpeg_decode_a53_cc(avctx, p, buf_size)) {
2173
393k
        return;
2174
393k
    }
2175
929k
}
2176
2177
static int mpeg_decode_gop(AVCodecContext *avctx,
2178
                            const uint8_t *buf, int buf_size)
2179
33.4k
{
2180
33.4k
    Mpeg1Context *s1  = avctx->priv_data;
2181
33.4k
    MPVContext *const s = &s1->slice.c;
2182
33.4k
    GetBitContext gb0, *const gb = &gb0;
2183
33.4k
    int broken_link;
2184
33.4k
    int64_t tc;
2185
2186
33.4k
    int ret = init_get_bits8(gb, buf, buf_size);
2187
33.4k
    if (ret < 0)
2188
0
        return ret;
2189
2190
33.4k
    tc = s1->timecode_frame_start = get_bits(gb, 25);
2191
2192
33.4k
    s1->closed_gop = get_bits1(gb);
2193
    /* broken_link indicates that after editing the
2194
     * reference frames of the first B-Frames after GOP I-Frame
2195
     * are missing (open gop) */
2196
33.4k
    broken_link = get_bits1(gb);
2197
2198
33.4k
    if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
2199
0
        char tcbuf[AV_TIMECODE_STR_SIZE];
2200
0
        av_timecode_make_mpeg_tc_string(tcbuf, tc);
2201
0
        av_log(s->avctx, AV_LOG_DEBUG,
2202
0
               "GOP (%s) closed_gop=%d broken_link=%d\n",
2203
0
               tcbuf, s1->closed_gop, broken_link);
2204
0
    }
2205
2206
33.4k
    return 0;
2207
33.4k
}
2208
2209
static void mpeg12_execute_slice_threads(AVCodecContext *avctx,
2210
                                         Mpeg1Context *const s)
2211
564k
{
2212
564k
    if (HAVE_THREADS && (avctx->active_thread_type & FF_THREAD_SLICE) &&
2213
0
        !avctx->hwaccel) {
2214
0
        MPVContext *const s2 = &s->slice.c;
2215
0
        int error_count = 0;
2216
2217
0
        avctx->execute(avctx, slice_decode_thread,
2218
0
                       s2->mpeg12_contexts, NULL,
2219
0
                       s->slice_count, sizeof(s2->mpeg12_contexts[0]));
2220
2221
0
        for (int i = 0; i < s->slice_count; i++) {
2222
0
            MpegEncContext *const slice = s2->thread_context[i];
2223
0
            int slice_err = atomic_load_explicit(&slice->er.error_count,
2224
0
                                                 memory_order_relaxed);
2225
            // error_count can get set to INT_MAX on serious errors.
2226
            // So use saturated addition.
2227
0
            if ((unsigned)slice_err > INT_MAX - error_count) {
2228
0
                error_count = INT_MAX;
2229
0
                break;
2230
0
            }
2231
0
            error_count += slice_err;
2232
0
        }
2233
0
        atomic_store_explicit(&s2->er.error_count, error_count,
2234
0
                              memory_order_relaxed);
2235
0
    }
2236
564k
}
2237
2238
static int decode_chunks(AVCodecContext *avctx, AVFrame *picture,
2239
                         int *got_output, const uint8_t *buf, int buf_size)
2240
848k
{
2241
848k
    Mpeg1Context *s = avctx->priv_data;
2242
848k
    MPVContext *const s2 = &s->slice.c;
2243
848k
    const uint8_t *buf_ptr = buf;
2244
848k
    const uint8_t *buf_end = buf + buf_size;
2245
848k
    int ret, input_size;
2246
848k
    int last_code = 0, skip_frame = 0;
2247
848k
    int picture_start_code_seen = 0;
2248
2249
5.44M
    for (;;) {
2250
        /* find next start code */
2251
5.44M
        uint32_t start_code = -1;
2252
5.44M
        buf_ptr = avpriv_find_start_code(buf_ptr, buf_end, &start_code);
2253
5.44M
        if (start_code > 0x1ff) {
2254
661k
            if (!skip_frame) {
2255
564k
                mpeg12_execute_slice_threads(avctx, s);
2256
2257
564k
                ret = slice_end(avctx, picture, got_output);
2258
564k
                if (ret < 0)
2259
0
                    return ret;
2260
564k
            }
2261
661k
            s2->pict_type = 0;
2262
2263
661k
            if (avctx->err_recognition & AV_EF_EXPLODE && s2->er.error_count)
2264
21.0k
                return AVERROR_INVALIDDATA;
2265
2266
640k
            return FFMAX(0, buf_ptr - buf);
2267
661k
        }
2268
2269
4.78M
        input_size = buf_end - buf_ptr;
2270
2271
4.78M
        if (avctx->debug & FF_DEBUG_STARTCODE)
2272
0
            av_log(avctx, AV_LOG_DEBUG, "%3"PRIX32" at %td left %d\n",
2273
0
                   start_code, buf_ptr - buf, input_size);
2274
2275
        /* prepare data for next start code */
2276
4.78M
        switch (start_code) {
2277
524k
        case SEQ_START_CODE:
2278
524k
            if (last_code == 0) {
2279
210k
                mpeg1_decode_sequence(avctx, buf_ptr, input_size);
2280
210k
                if (buf != avctx->extradata)
2281
208k
                    s->sync = 1;
2282
313k
            } else {
2283
313k
                av_log(avctx, AV_LOG_ERROR,
2284
313k
                       "ignoring SEQ_START_CODE after %X\n", last_code);
2285
313k
                if (avctx->err_recognition & AV_EF_EXPLODE)
2286
2.17k
                    return AVERROR_INVALIDDATA;
2287
313k
            }
2288
521k
            break;
2289
2290
995k
        case PICTURE_START_CODE:
2291
995k
            if (picture_start_code_seen && s2->picture_structure == PICT_FRAME) {
2292
               /* If it's a frame picture, there can't be more than one picture header.
2293
                  Yet, it does happen and we need to handle it. */
2294
276k
               av_log(avctx, AV_LOG_WARNING, "ignoring extra picture following a frame-picture\n");
2295
276k
               break;
2296
276k
            }
2297
719k
            picture_start_code_seen = 1;
2298
2299
719k
            if (buf == avctx->extradata && avctx->codec_tag == AV_RL32("AVmp")) {
2300
3
                av_log(avctx, AV_LOG_WARNING, "ignoring picture start code in AVmp extradata\n");
2301
3
                break;
2302
3
            }
2303
2304
719k
            if (s2->width <= 0 || s2->height <= 0) {
2305
27.5k
                av_log(avctx, AV_LOG_ERROR, "Invalid frame dimensions %dx%d.\n",
2306
27.5k
                       s2->width, s2->height);
2307
27.5k
                return AVERROR_INVALIDDATA;
2308
27.5k
            }
2309
2310
691k
            if (s->tmpgexs){
2311
45.1k
                s2->intra_dc_precision= 3;
2312
45.1k
                s2->intra_matrix[0]= 1;
2313
45.1k
            }
2314
691k
            if (s->slice_count) {
2315
0
                mpeg12_execute_slice_threads(avctx, s);
2316
0
                s->slice_count = 0;
2317
0
            }
2318
691k
            if (last_code == 0 || last_code == SLICE_MIN_START_CODE) {
2319
476k
                ret = mpeg_decode_postinit(avctx);
2320
476k
                if (ret < 0) {
2321
24.7k
                    av_log(avctx, AV_LOG_ERROR,
2322
24.7k
                           "mpeg_decode_postinit() failure\n");
2323
24.7k
                    return ret;
2324
24.7k
                }
2325
2326
                /* We have a complete image: we try to decompress it. */
2327
451k
                if (mpeg1_decode_picture(avctx, buf_ptr, input_size) < 0)
2328
167k
                    s2->pict_type = 0;
2329
451k
                s->first_slice = 1;
2330
451k
                last_code      = PICTURE_START_CODE;
2331
451k
            } else {
2332
215k
                av_log(avctx, AV_LOG_ERROR,
2333
215k
                       "ignoring pic after %X\n", last_code);
2334
215k
                if (avctx->err_recognition & AV_EF_EXPLODE)
2335
982
                    return AVERROR_INVALIDDATA;
2336
215k
            }
2337
665k
            break;
2338
751k
        case EXT_START_CODE: {
2339
751k
            GetBitContext gb0, *const gb = &gb0;
2340
2341
751k
            ret = init_get_bits8(gb, buf_ptr, input_size);
2342
751k
            if (ret < 0)
2343
0
                return ret;
2344
2345
751k
            switch (get_bits(gb, 4)) {
2346
233k
            case 0x1:
2347
233k
                if (last_code == 0) {
2348
163k
                    mpeg_decode_sequence_extension(s, gb);
2349
163k
                } else {
2350
69.6k
                    av_log(avctx, AV_LOG_ERROR,
2351
69.6k
                           "ignoring seq ext after %X\n", last_code);
2352
69.6k
                    if (avctx->err_recognition & AV_EF_EXPLODE)
2353
1.42k
                        return AVERROR_INVALIDDATA;
2354
69.6k
                }
2355
231k
                break;
2356
231k
            case 0x2:
2357
26.7k
                mpeg_decode_sequence_display_extension(s, gb);
2358
26.7k
                break;
2359
21.1k
            case 0x3:
2360
21.1k
                mpeg_decode_quant_matrix_extension(s2, gb);
2361
21.1k
                break;
2362
12.8k
            case 0x7:
2363
12.8k
                mpeg_decode_picture_display_extension(s, gb);
2364
12.8k
                break;
2365
428k
            case 0x8:
2366
428k
                if (last_code == PICTURE_START_CODE) {
2367
322k
                    int ret = mpeg_decode_picture_coding_extension(s, gb);
2368
322k
                    if (ret < 0)
2369
1.13k
                       return ret;
2370
322k
                } else {
2371
105k
                    av_log(avctx, AV_LOG_ERROR,
2372
105k
                           "ignoring pic cod ext after %X\n", last_code);
2373
105k
                    if (avctx->err_recognition & AV_EF_EXPLODE)
2374
2.15k
                        return AVERROR_INVALIDDATA;
2375
105k
                }
2376
424k
                break;
2377
751k
            }
2378
747k
            break;
2379
751k
        }
2380
929k
        case USER_START_CODE:
2381
929k
            mpeg_decode_user_data(avctx, buf_ptr, input_size);
2382
929k
            break;
2383
139k
        case GOP_START_CODE:
2384
139k
            if (last_code == 0) {
2385
33.4k
                s2->first_field = 0;
2386
33.4k
                ret = mpeg_decode_gop(avctx, buf_ptr, input_size);
2387
33.4k
                if (ret < 0)
2388
0
                    return ret;
2389
33.4k
                s->sync = 1;
2390
105k
            } else {
2391
105k
                av_log(avctx, AV_LOG_ERROR,
2392
105k
                       "ignoring GOP_START_CODE after %X\n", last_code);
2393
105k
                if (avctx->err_recognition & AV_EF_EXPLODE)
2394
906
                    return AVERROR_INVALIDDATA;
2395
105k
            }
2396
138k
            break;
2397
1.44M
        default:
2398
1.44M
            if (start_code >= SLICE_MIN_START_CODE &&
2399
1.41M
                start_code <= SLICE_MAX_START_CODE && last_code == PICTURE_START_CODE) {
2400
405k
                if (s2->progressive_sequence && !s2->progressive_frame) {
2401
25.3k
                    s2->progressive_frame = 1;
2402
25.3k
                    av_log(s2->avctx, AV_LOG_ERROR,
2403
25.3k
                           "interlaced frame in progressive sequence, ignoring\n");
2404
25.3k
                }
2405
2406
405k
                if (s2->picture_structure == 0 ||
2407
399k
                    (s2->progressive_frame && s2->picture_structure != PICT_FRAME)) {
2408
16.3k
                    av_log(s2->avctx, AV_LOG_ERROR,
2409
16.3k
                           "picture_structure %d invalid, ignoring\n",
2410
16.3k
                           s2->picture_structure);
2411
16.3k
                    s2->picture_structure = PICT_FRAME;
2412
16.3k
                }
2413
2414
405k
                if (s2->progressive_sequence && !s2->frame_pred_frame_dct)
2415
34.6k
                    av_log(s2->avctx, AV_LOG_WARNING, "invalid frame_pred_frame_dct\n");
2416
2417
405k
                if (s2->picture_structure == PICT_FRAME) {
2418
320k
                    s2->first_field = 0;
2419
320k
                    s2->v_edge_pos  = 16 * s2->mb_height;
2420
320k
                } else {
2421
84.6k
                    s2->first_field ^= 1;
2422
84.6k
                    s2->v_edge_pos   = 8 * s2->mb_height;
2423
84.6k
                    memset(s2->mbskip_table, 0, s2->mb_stride * s2->mb_height);
2424
84.6k
                }
2425
405k
            }
2426
1.44M
            if (start_code >= SLICE_MIN_START_CODE &&
2427
1.41M
                start_code <= SLICE_MAX_START_CODE && last_code != 0) {
2428
1.09M
                const int field_pic = s2->picture_structure != PICT_FRAME;
2429
1.09M
                int mb_y = start_code - SLICE_MIN_START_CODE;
2430
1.09M
                last_code = SLICE_MIN_START_CODE;
2431
1.09M
                if (s2->codec_id != AV_CODEC_ID_MPEG1VIDEO && s2->mb_height > 2800/16)
2432
29.9k
                    mb_y += (*buf_ptr&0xE0)<<2;
2433
2434
1.09M
                mb_y <<= field_pic;
2435
1.09M
                if (s2->picture_structure == PICT_BOTTOM_FIELD)
2436
52.8k
                    mb_y++;
2437
2438
1.09M
                if (buf_end - buf_ptr < 2) {
2439
29.9k
                    av_log(s2->avctx, AV_LOG_ERROR, "slice too small\n");
2440
29.9k
                    return AVERROR_INVALIDDATA;
2441
29.9k
                }
2442
2443
1.06M
                if (mb_y >= s2->mb_height) {
2444
35.0k
                    av_log(s2->avctx, AV_LOG_ERROR,
2445
35.0k
                           "slice below image (%d >= %d)\n", mb_y, s2->mb_height);
2446
35.0k
                    return AVERROR_INVALIDDATA;
2447
35.0k
                }
2448
2449
1.02M
                if (!s2->last_pic.ptr) {
2450
                    /* Skip B-frames if we do not have reference frames and
2451
                     * GOP is not closed. */
2452
438k
                    if (s2->pict_type == AV_PICTURE_TYPE_B) {
2453
105k
                        if (!s->closed_gop) {
2454
89.9k
                            skip_frame = 1;
2455
89.9k
                            av_log(s2->avctx, AV_LOG_DEBUG,
2456
89.9k
                                   "Skipping B slice due to open GOP\n");
2457
89.9k
                            break;
2458
89.9k
                        }
2459
105k
                    }
2460
438k
                }
2461
935k
                if (s2->pict_type == AV_PICTURE_TYPE_I || (s2->avctx->flags2 & AV_CODEC_FLAG2_SHOW_ALL))
2462
160k
                    s->sync = 1;
2463
935k
                if (!s2->next_pic.ptr) {
2464
                    /* Skip P-frames if we do not have a reference frame or
2465
                     * we have an invalid header. */
2466
279k
                    if (s2->pict_type == AV_PICTURE_TYPE_P && !s->sync) {
2467
71.9k
                        skip_frame = 1;
2468
71.9k
                        av_log(s2->avctx, AV_LOG_DEBUG,
2469
71.9k
                               "Skipping P slice due to !sync\n");
2470
71.9k
                        break;
2471
71.9k
                    }
2472
279k
                }
2473
863k
                if ((avctx->skip_frame >= AVDISCARD_NONREF &&
2474
44.4k
                     s2->pict_type == AV_PICTURE_TYPE_B) ||
2475
861k
                    (avctx->skip_frame >= AVDISCARD_NONKEY &&
2476
21.4k
                     s2->pict_type != AV_PICTURE_TYPE_I) ||
2477
846k
                    avctx->skip_frame >= AVDISCARD_ALL) {
2478
22.1k
                    skip_frame = 1;
2479
22.1k
                    break;
2480
22.1k
                }
2481
2482
841k
                if (!s2->context_initialized)
2483
0
                    break;
2484
2485
841k
                if (s2->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
2486
404k
                    if (mb_y < avctx->skip_top ||
2487
404k
                        mb_y >= s2->mb_height - avctx->skip_bottom)
2488
0
                        break;
2489
404k
                }
2490
2491
841k
                if (!s2->pict_type) {
2492
120k
                    av_log(avctx, AV_LOG_ERROR, "Missing picture start code\n");
2493
120k
                    if (avctx->err_recognition & AV_EF_EXPLODE)
2494
38.1k
                        return AVERROR_INVALIDDATA;
2495
82.5k
                    break;
2496
120k
                }
2497
2498
720k
                if (s->first_slice) {
2499
176k
                    skip_frame     = 0;
2500
176k
                    s->first_slice = 0;
2501
176k
                    if ((ret = mpeg_field_start(s, buf, buf_size)) < 0)
2502
8.47k
                        return ret;
2503
176k
                }
2504
712k
                if (!s2->cur_pic.ptr) {
2505
0
                    av_log(avctx, AV_LOG_ERROR,
2506
0
                           "current_picture not initialized\n");
2507
0
                    return AVERROR_INVALIDDATA;
2508
0
                }
2509
2510
712k
                if (HAVE_THREADS &&
2511
712k
                    (avctx->active_thread_type & FF_THREAD_SLICE) &&
2512
0
                    !avctx->hwaccel) {
2513
0
                    int threshold = (s2->mb_height * s->slice_count +
2514
0
                                     s2->slice_context_count / 2) /
2515
0
                                    s2->slice_context_count;
2516
0
                    if (threshold <= mb_y) {
2517
0
                        Mpeg12SliceContext *const thread_context = s2->mpeg12_contexts[s->slice_count];
2518
2519
0
                        thread_context->c.start_mb_y = mb_y;
2520
0
                        thread_context->c.end_mb_y   = s2->mb_height;
2521
0
                        if (s->slice_count) {
2522
0
                            s2->thread_context[s->slice_count - 1]->end_mb_y = mb_y;
2523
0
                            ret = ff_update_duplicate_context(&thread_context->c, s2);
2524
0
                            if (ret < 0)
2525
0
                                return ret;
2526
0
                        }
2527
0
                        ret = init_get_bits8(&thread_context->gb, buf_ptr, input_size);
2528
0
                        if (ret < 0)
2529
0
                            return ret;
2530
0
                        s->slice_count++;
2531
0
                    }
2532
0
                    buf_ptr += 2; // FIXME add minimum number of bytes per slice
2533
712k
                } else {
2534
712k
                    ret = mpeg_decode_slice(&s->slice, mb_y, &buf_ptr, input_size);
2535
712k
                    emms_c();
2536
2537
712k
                    if (ret < 0) {
2538
660k
                        if (avctx->err_recognition & AV_EF_EXPLODE)
2539
14.4k
                            return ret;
2540
646k
                        if (s2->resync_mb_x >= 0 && s2->resync_mb_y >= 0)
2541
511k
                            ff_er_add_slice(&s2->er, s2->resync_mb_x,
2542
511k
                                            s2->resync_mb_y, s2->mb_x, s2->mb_y,
2543
511k
                                            ER_AC_ERROR | ER_DC_ERROR | ER_MV_ERROR);
2544
646k
                    } else {
2545
51.7k
                        ff_er_add_slice(&s2->er, s2->resync_mb_x,
2546
51.7k
                                        s2->resync_mb_y, s2->mb_x - 1, s2->mb_y,
2547
51.7k
                                        ER_AC_END | ER_DC_END | ER_MV_END);
2548
51.7k
                    }
2549
712k
                }
2550
712k
            }
2551
1.04M
            break;
2552
4.78M
        }
2553
4.78M
    }
2554
848k
}
2555
2556
static int mpeg_decode_frame(AVCodecContext *avctx, AVFrame *picture,
2557
                             int *got_output, AVPacket *avpkt)
2558
990k
{
2559
990k
    const uint8_t *buf = avpkt->data;
2560
990k
    int ret;
2561
990k
    int buf_size = avpkt->size;
2562
990k
    Mpeg1Context *s = avctx->priv_data;
2563
990k
    MPVContext *const s2 = &s->slice.c;
2564
2565
990k
    if (buf_size == 0 || (buf_size == 4 && AV_RB32(buf) == SEQ_END_CODE)) {
2566
        /* special case for last picture */
2567
142k
        if (s2->low_delay == 0 && s2->next_pic.ptr) {
2568
15.1k
            int ret = av_frame_ref(picture, s2->next_pic.ptr->f);
2569
15.1k
            if (ret < 0)
2570
0
                return ret;
2571
2572
15.1k
            ff_mpv_unref_picture(&s2->next_pic);
2573
2574
15.1k
            *got_output = 1;
2575
15.1k
        }
2576
142k
        return buf_size;
2577
142k
    }
2578
2579
847k
    if (!s2->context_initialized &&
2580
294k
        (s2->codec_tag == AV_RL32("VCR2") || s2->codec_tag == AV_RL32("BW10")))
2581
5.55k
        vcr2_init_sequence(avctx);
2582
2583
847k
    s->slice_count = 0;
2584
2585
847k
    if (avctx->extradata && !s->extradata_decoded) {
2586
790
        ret = decode_chunks(avctx, picture, got_output,
2587
790
                            avctx->extradata, avctx->extradata_size);
2588
790
        if (*got_output) {
2589
8
            av_log(avctx, AV_LOG_ERROR, "picture in extradata\n");
2590
8
            av_frame_unref(picture);
2591
8
            *got_output = 0;
2592
8
        }
2593
790
        s->extradata_decoded = 1;
2594
790
        if (ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE)) {
2595
24
            ff_mpv_unref_picture(&s2->cur_pic);
2596
24
            return ret;
2597
24
        }
2598
790
    }
2599
2600
847k
    ret = decode_chunks(avctx, picture, got_output, buf, buf_size);
2601
847k
    if (ret<0 || *got_output) {
2602
271k
        ff_mpv_unref_picture(&s2->cur_pic);
2603
2604
271k
        if (s->timecode_frame_start != -1 && *got_output) {
2605
16.4k
            char tcbuf[AV_TIMECODE_STR_SIZE];
2606
16.4k
            AVFrameSideData *tcside = av_frame_new_side_data(picture,
2607
16.4k
                                                             AV_FRAME_DATA_GOP_TIMECODE,
2608
16.4k
                                                             sizeof(int64_t));
2609
16.4k
            if (!tcside)
2610
0
                return AVERROR(ENOMEM);
2611
16.4k
            memcpy(tcside->data, &s->timecode_frame_start, sizeof(int64_t));
2612
2613
16.4k
            av_timecode_make_mpeg_tc_string(tcbuf, s->timecode_frame_start);
2614
16.4k
            av_dict_set(&picture->metadata, "timecode", tcbuf, 0);
2615
2616
16.4k
            s->timecode_frame_start = -1;
2617
16.4k
        }
2618
271k
    }
2619
2620
847k
    return ret;
2621
847k
}
2622
2623
static av_cold void flush(AVCodecContext *avctx)
2624
466k
{
2625
466k
    Mpeg1Context *s = avctx->priv_data;
2626
2627
466k
    s->sync       = 0;
2628
466k
    s->closed_gop = 0;
2629
2630
466k
    av_buffer_unref(&s->a53_buf_ref);
2631
466k
    ff_mpeg_flush(avctx);
2632
466k
}
2633
2634
static av_cold int mpeg_decode_end(AVCodecContext *avctx)
2635
24.3k
{
2636
24.3k
    Mpeg1Context *s = avctx->priv_data;
2637
2638
24.3k
    av_buffer_unref(&s->a53_buf_ref);
2639
24.3k
    return ff_mpv_decode_close(avctx);
2640
24.3k
}
2641
2642
const FFCodec ff_mpeg1video_decoder = {
2643
    .p.name                = "mpeg1video",
2644
    CODEC_LONG_NAME("MPEG-1 video"),
2645
    .p.type                = AVMEDIA_TYPE_VIDEO,
2646
    .p.id                  = AV_CODEC_ID_MPEG1VIDEO,
2647
    .priv_data_size        = sizeof(Mpeg1Context),
2648
    .init                  = mpeg_decode_init,
2649
    .close                 = mpeg_decode_end,
2650
    FF_CODEC_DECODE_CB(mpeg_decode_frame),
2651
    .p.capabilities        = AV_CODEC_CAP_DRAW_HORIZ_BAND | AV_CODEC_CAP_DR1 |
2652
                             AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS,
2653
    .caps_internal         = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM,
2654
    .flush                 = flush,
2655
    .p.max_lowres          = 3,
2656
    .hw_configs            = (const AVCodecHWConfigInternal *const []) {
2657
#if CONFIG_MPEG1_NVDEC_HWACCEL
2658
                               HWACCEL_NVDEC(mpeg1),
2659
#endif
2660
#if CONFIG_MPEG1_VDPAU_HWACCEL
2661
                               HWACCEL_VDPAU(mpeg1),
2662
#endif
2663
#if CONFIG_MPEG1_VIDEOTOOLBOX_HWACCEL
2664
                               HWACCEL_VIDEOTOOLBOX(mpeg1),
2665
#endif
2666
                               NULL
2667
                           },
2668
};
2669
2670
#define M2V_OFFSET(x) offsetof(Mpeg1Context, x)
2671
#define M2V_PARAM     AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
2672
2673
static const AVOption mpeg2video_options[] = {
2674
    { "cc_format", "extract a specific Closed Captions format",
2675
       M2V_OFFSET(cc_format), AV_OPT_TYPE_INT, { .i64 = CC_FORMAT_AUTO },
2676
        CC_FORMAT_AUTO, CC_FORMAT_DISH, M2V_PARAM, .unit = "cc_format" },
2677
2678
       { "auto",   "pick first seen CC substream",  0, AV_OPT_TYPE_CONST,
2679
        { .i64 =   CC_FORMAT_AUTO },                .flags = M2V_PARAM, .unit = "cc_format" },
2680
       { "a53",    "pick A/53 Part 4 CC substream", 0, AV_OPT_TYPE_CONST,
2681
        { .i64 =   CC_FORMAT_A53_PART4 },           .flags = M2V_PARAM, .unit = "cc_format" },
2682
       { "scte20", "pick SCTE-20 CC substream",     0, AV_OPT_TYPE_CONST,
2683
        { .i64 =   CC_FORMAT_SCTE20 },              .flags = M2V_PARAM, .unit = "cc_format" },
2684
       { "dvd",    "pick DVD CC substream",         0, AV_OPT_TYPE_CONST,
2685
        { .i64 =   CC_FORMAT_DVD },                 .flags = M2V_PARAM, .unit = "cc_format" },
2686
       { "dish",   "pick Dish Network CC substream", 0, AV_OPT_TYPE_CONST,
2687
        { .i64 =   CC_FORMAT_DISH },                .flags = M2V_PARAM, .unit = "cc_format" },
2688
    { NULL }
2689
};
2690
2691
static const AVClass mpeg2video_class = {
2692
    .class_name = "MPEG-2 video",
2693
    .item_name  = av_default_item_name,
2694
    .option     = mpeg2video_options,
2695
    .version    = LIBAVUTIL_VERSION_INT,
2696
    .category   = AV_CLASS_CATEGORY_DECODER,
2697
};
2698
2699
const FFCodec ff_mpeg2video_decoder = {
2700
    .p.name         = "mpeg2video",
2701
    CODEC_LONG_NAME("MPEG-2 video"),
2702
    .p.type         = AVMEDIA_TYPE_VIDEO,
2703
    .p.id           = AV_CODEC_ID_MPEG2VIDEO,
2704
    .p.priv_class   = &mpeg2video_class,
2705
    .priv_data_size = sizeof(Mpeg1Context),
2706
    .init           = mpeg_decode_init,
2707
    .close          = mpeg_decode_end,
2708
    FF_CODEC_DECODE_CB(mpeg_decode_frame),
2709
    .p.capabilities = AV_CODEC_CAP_DRAW_HORIZ_BAND | AV_CODEC_CAP_DR1 |
2710
                      AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS,
2711
    .caps_internal  = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM,
2712
    .flush          = flush,
2713
    .p.max_lowres   = 3,
2714
    .p.profiles     = NULL_IF_CONFIG_SMALL(ff_mpeg2_video_profiles),
2715
    .hw_configs     = (const AVCodecHWConfigInternal *const []) {
2716
#if CONFIG_MPEG2_DXVA2_HWACCEL
2717
                        HWACCEL_DXVA2(mpeg2),
2718
#endif
2719
#if CONFIG_MPEG2_D3D11VA_HWACCEL
2720
                        HWACCEL_D3D11VA(mpeg2),
2721
#endif
2722
#if CONFIG_MPEG2_D3D11VA2_HWACCEL
2723
                        HWACCEL_D3D11VA2(mpeg2),
2724
#endif
2725
#if CONFIG_MPEG2_D3D12VA_HWACCEL
2726
                        HWACCEL_D3D12VA(mpeg2),
2727
#endif
2728
#if CONFIG_MPEG2_NVDEC_HWACCEL
2729
                        HWACCEL_NVDEC(mpeg2),
2730
#endif
2731
#if CONFIG_MPEG2_VAAPI_HWACCEL
2732
                        HWACCEL_VAAPI(mpeg2),
2733
#endif
2734
#if CONFIG_MPEG2_VDPAU_HWACCEL
2735
                        HWACCEL_VDPAU(mpeg2),
2736
#endif
2737
#if CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL
2738
                        HWACCEL_VIDEOTOOLBOX(mpeg2),
2739
#endif
2740
                        NULL
2741
                    },
2742
};
2743
2744
//legacy decoder
2745
const FFCodec ff_mpegvideo_decoder = {
2746
    .p.name         = "mpegvideo",
2747
    CODEC_LONG_NAME("MPEG-1 video"),
2748
    .p.type         = AVMEDIA_TYPE_VIDEO,
2749
    .p.id           = AV_CODEC_ID_MPEG2VIDEO,
2750
    .priv_data_size = sizeof(Mpeg1Context),
2751
    .init           = mpeg_decode_init,
2752
    .close          = mpeg_decode_end,
2753
    FF_CODEC_DECODE_CB(mpeg_decode_frame),
2754
    .p.capabilities = AV_CODEC_CAP_DRAW_HORIZ_BAND | AV_CODEC_CAP_DR1 |
2755
                      AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS,
2756
    .caps_internal  = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM,
2757
    .flush          = flush,
2758
    .p.max_lowres   = 3,
2759
};
2760
2761
typedef struct IPUContext {
2762
    Mpeg12SliceContext m;
2763
2764
    int flags;
2765
} IPUContext;
2766
2767
static int ipu_decode_frame(AVCodecContext *avctx, AVFrame *frame,
2768
                            int *got_frame, AVPacket *avpkt)
2769
924k
{
2770
924k
    IPUContext *s = avctx->priv_data;
2771
924k
    MPVContext *const m = &s->m.c;
2772
924k
    GetBitContext *const gb = &s->m.gb;
2773
924k
    int16_t (*const block)[64] = s->m.block;
2774
924k
    int ret;
2775
2776
    // Check for minimal intra MB size (considering mb header, luma & chroma dc VLC, ac EOB VLC)
2777
924k
    if (avpkt->size*8LL < (avctx->width+15)/16 * ((avctx->height+15)/16) * (2LL + 3*4 + 2*2 + 2*6))
2778
720k
        return AVERROR_INVALIDDATA;
2779
2780
204k
    ret = ff_get_buffer(avctx, frame, 0);
2781
204k
    if (ret < 0)
2782
50.8k
        return ret;
2783
2784
153k
    ret = init_get_bits8(gb, avpkt->data, avpkt->size);
2785
153k
    if (ret < 0)
2786
0
        return ret;
2787
2788
153k
    s->flags = get_bits(gb, 8);
2789
153k
    m->intra_dc_precision = s->flags & 3;
2790
153k
    m->q_scale_type = !!(s->flags & 0x40);
2791
153k
    m->intra_vlc_format = !!(s->flags & 0x20);
2792
153k
    m->alternate_scan = !!(s->flags & 0x10);
2793
2794
153k
    ff_permute_scantable(m->intra_scantable.permutated,
2795
153k
                         s->flags & 0x10 ? ff_alternate_vertical_scan : ff_zigzag_direct,
2796
153k
                         m->idsp.idct_permutation);
2797
2798
153k
    s->m.last_dc[0] = s->m.last_dc[1] = s->m.last_dc[2] = 128 << (s->flags & 3);
2799
153k
    m->qscale = 1;
2800
2801
303k
    for (int y = 0; y < avctx->height; y += 16) {
2802
160k
        int intraquant;
2803
2804
344k
        for (int x = 0; x < avctx->width; x += 16) {
2805
194k
            if (x || y) {
2806
40.5k
                if (!get_bits1(gb))
2807
774
                    return AVERROR_INVALIDDATA;
2808
40.5k
            }
2809
193k
            if (get_bits1(gb)) {
2810
42.2k
                intraquant = 0;
2811
151k
            } else {
2812
151k
                if (!get_bits1(gb))
2813
4.24k
                    return AVERROR_INVALIDDATA;
2814
146k
                intraquant = 1;
2815
146k
            }
2816
2817
189k
            if (s->flags & 4)
2818
16.7k
                skip_bits1(gb);
2819
2820
189k
            if (intraquant)
2821
146k
                m->qscale = mpeg_get_qscale(gb, m->q_scale_type);
2822
2823
189k
            memset(block, 0, 6 * sizeof(*block));
2824
2825
1.30M
            for (int n = 0; n < 6; n++) {
2826
1.11M
                if (s->flags & 0x80) {
2827
1.04M
                    ret = ff_mpeg1_decode_block_intra(gb,
2828
1.04M
                                                      m->intra_matrix,
2829
1.04M
                                                      m->intra_scantable.permutated,
2830
1.04M
                                                      s->m.last_dc, block[n],
2831
1.04M
                                                      n, m->qscale);
2832
1.04M
                } else {
2833
77.7k
                    ret = mpeg2_decode_block_intra(&s->m, block[n], n);
2834
77.7k
                }
2835
2836
1.11M
                if (ret < 0)
2837
5.60k
                    return ret;
2838
1.11M
            }
2839
2840
183k
            m->idsp.idct_put(frame->data[0] + y * frame->linesize[0] + x,
2841
183k
                             frame->linesize[0], block[0]);
2842
183k
            m->idsp.idct_put(frame->data[0] + y * frame->linesize[0] + x + 8,
2843
183k
                             frame->linesize[0], block[1]);
2844
183k
            m->idsp.idct_put(frame->data[0] + (y + 8) * frame->linesize[0] + x,
2845
183k
                             frame->linesize[0], block[2]);
2846
183k
            m->idsp.idct_put(frame->data[0] + (y + 8) * frame->linesize[0] + x + 8,
2847
183k
                             frame->linesize[0], block[3]);
2848
183k
            m->idsp.idct_put(frame->data[1] + (y >> 1) * frame->linesize[1] + (x >> 1),
2849
183k
                             frame->linesize[1], block[4]);
2850
183k
            m->idsp.idct_put(frame->data[2] + (y >> 1) * frame->linesize[2] + (x >> 1),
2851
183k
                             frame->linesize[2], block[5]);
2852
183k
        }
2853
160k
    }
2854
2855
143k
    align_get_bits(gb);
2856
143k
    if (get_bits_left(gb) != 32)
2857
3.67k
        return AVERROR_INVALIDDATA;
2858
2859
139k
    *got_frame = 1;
2860
2861
139k
    return avpkt->size;
2862
143k
}
2863
2864
static av_cold int ipu_decode_init(AVCodecContext *avctx)
2865
1.17k
{
2866
1.17k
    IPUContext *s = avctx->priv_data;
2867
1.17k
    MPVContext *const m = &s->m.c;
2868
2869
1.17k
    avctx->pix_fmt = AV_PIX_FMT_YUV420P;
2870
1.17k
    m->avctx       = avctx;
2871
2872
1.17k
    ff_idctdsp_init(&m->idsp, avctx);
2873
1.17k
    ff_mpeg12_init_vlcs();
2874
2875
76.3k
    for (int i = 0; i < 64; i++) {
2876
75.2k
        int j = m->idsp.idct_permutation[i];
2877
75.2k
        int v = ff_mpeg1_default_intra_matrix[i];
2878
75.2k
        m->intra_matrix[j]        = v;
2879
75.2k
        m->chroma_intra_matrix[j] = v;
2880
75.2k
    }
2881
2882
1.17k
    return 0;
2883
1.17k
}
2884
2885
const FFCodec ff_ipu_decoder = {
2886
    .p.name         = "ipu",
2887
    CODEC_LONG_NAME("IPU Video"),
2888
    .p.type         = AVMEDIA_TYPE_VIDEO,
2889
    .p.id           = AV_CODEC_ID_IPU,
2890
    .priv_data_size = sizeof(IPUContext),
2891
    .init           = ipu_decode_init,
2892
    FF_CODEC_DECODE_CB(ipu_decode_frame),
2893
    .p.capabilities = AV_CODEC_CAP_DR1,
2894
};