GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/decode.c Lines: 687 1120 61.3 %
Date: 2020-11-28 20:53:16 Branches: 498 881 56.5 %

Line Branch Exec Source
1
/*
2
 * generic decoding-related code
3
 *
4
 * This file is part of FFmpeg.
5
 *
6
 * FFmpeg is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU Lesser General Public
8
 * License as published by the Free Software Foundation; either
9
 * version 2.1 of the License, or (at your option) any later version.
10
 *
11
 * FFmpeg is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
 * Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with FFmpeg; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
 */
20
21
#include <stdint.h>
22
#include <string.h>
23
24
#include "config.h"
25
26
#if CONFIG_ICONV
27
# include <iconv.h>
28
#endif
29
30
#include "libavutil/avassert.h"
31
#include "libavutil/avstring.h"
32
#include "libavutil/bprint.h"
33
#include "libavutil/common.h"
34
#include "libavutil/frame.h"
35
#include "libavutil/hwcontext.h"
36
#include "libavutil/imgutils.h"
37
#include "libavutil/internal.h"
38
#include "libavutil/intmath.h"
39
#include "libavutil/opt.h"
40
41
#include "avcodec.h"
42
#include "bytestream.h"
43
#include "decode.h"
44
#include "hwconfig.h"
45
#include "internal.h"
46
#include "packet_internal.h"
47
#include "thread.h"
48
49
typedef struct FramePool {
50
    /**
51
     * Pools for each data plane. For audio all the planes have the same size,
52
     * so only pools[0] is used.
53
     */
54
    AVBufferPool *pools[4];
55
56
    /*
57
     * Pool parameters
58
     */
59
    int format;
60
    int width, height;
61
    int stride_align[AV_NUM_DATA_POINTERS];
62
    int linesize[4];
63
    int planes;
64
    int channels;
65
    int samples;
66
} FramePool;
67
68
374314
static int apply_param_change(AVCodecContext *avctx, const AVPacket *avpkt)
69
{
70
    int size, ret;
71
    const uint8_t *data;
72
    uint32_t flags;
73
    int64_t val;
74
75
374314
    data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
76
374314
    if (!data)
77
374312
        return 0;
78
79
2
    if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) {
80
        av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
81
               "changes, but PARAM_CHANGE side data was sent to it.\n");
82
        ret = AVERROR(EINVAL);
83
        goto fail2;
84
    }
85
86
2
    if (size < 4)
87
        goto fail;
88
89
2
    flags = bytestream_get_le32(&data);
90
2
    size -= 4;
91
92
2
    if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
93
        if (size < 4)
94
            goto fail;
95
        val = bytestream_get_le32(&data);
96
        if (val <= 0 || val > INT_MAX) {
97
            av_log(avctx, AV_LOG_ERROR, "Invalid channel count");
98
            ret = AVERROR_INVALIDDATA;
99
            goto fail2;
100
        }
101
        avctx->channels = val;
102
        size -= 4;
103
    }
104
2
    if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
105
        if (size < 8)
106
            goto fail;
107
        avctx->channel_layout = bytestream_get_le64(&data);
108
        size -= 8;
109
    }
110
2
    if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
111
        if (size < 4)
112
            goto fail;
113
        val = bytestream_get_le32(&data);
114
        if (val <= 0 || val > INT_MAX) {
115
            av_log(avctx, AV_LOG_ERROR, "Invalid sample rate");
116
            ret = AVERROR_INVALIDDATA;
117
            goto fail2;
118
        }
119
        avctx->sample_rate = val;
120
        size -= 4;
121
    }
122
2
    if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
123
2
        if (size < 8)
124
            goto fail;
125
2
        avctx->width  = bytestream_get_le32(&data);
126
2
        avctx->height = bytestream_get_le32(&data);
127
2
        size -= 8;
128
2
        ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
129
2
        if (ret < 0)
130
            goto fail2;
131
    }
132
133
2
    return 0;
134
fail:
135
    av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
136
    ret = AVERROR_INVALIDDATA;
137
fail2:
138
    if (ret < 0) {
139
        av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
140
        if (avctx->err_recognition & AV_EF_EXPLODE)
141
            return ret;
142
    }
143
    return 0;
144
}
145
146
#define IS_EMPTY(pkt) (!(pkt)->data)
147
148
375557
static int extract_packet_props(AVCodecInternal *avci, AVPacket *pkt)
149
{
150
375557
    int ret = 0;
151
152
375557
    ret = avpriv_packet_list_put(&avci->pkt_props, &avci->pkt_props_tail, pkt,
153
                                 av_packet_copy_props, 0);
154
375557
    if (ret < 0)
155
        return ret;
156
375557
    avci->pkt_props_tail->pkt.size = pkt->size; // HACK: Needed for ff_decode_frame_props().
157
375557
    avci->pkt_props_tail->pkt.data = (void*)1;  // HACK: Needed for IS_EMPTY().
158
159
375557
    if (IS_EMPTY(avci->last_pkt_props)) {
160
374349
        ret = avpriv_packet_list_get(&avci->pkt_props,
161
                                     &avci->pkt_props_tail,
162
                                     avci->last_pkt_props);
163
374349
        av_assert0(ret != AVERROR(EAGAIN));
164
    }
165
375557
    return ret;
166
}
167
168
3522
static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
169
{
170
    int ret;
171
172
    /* move the original frame to our backup */
173
3522
    av_frame_unref(avci->to_free);
174
3522
    av_frame_move_ref(avci->to_free, frame);
175
176
    /* now copy everything except the AVBufferRefs back
177
     * note that we make a COPY of the side data, so calling av_frame_free() on
178
     * the caller's frame will work properly */
179
3522
    ret = av_frame_copy_props(frame, avci->to_free);
180
3522
    if (ret < 0)
181
        return ret;
182
183
3522
    memcpy(frame->data,     avci->to_free->data,     sizeof(frame->data));
184
3522
    memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
185
3522
    if (avci->to_free->extended_data != avci->to_free->data) {
186
        int planes = avci->to_free->channels;
187
        int size   = planes * sizeof(*frame->extended_data);
188
189
        if (!size) {
190
            av_frame_unref(frame);
191
            return AVERROR_BUG;
192
        }
193
194
        frame->extended_data = av_malloc(size);
195
        if (!frame->extended_data) {
196
            av_frame_unref(frame);
197
            return AVERROR(ENOMEM);
198
        }
199
        memcpy(frame->extended_data, avci->to_free->extended_data,
200
               size);
201
    } else
202
3522
        frame->extended_data = frame->data;
203
204
3522
    frame->format         = avci->to_free->format;
205
3522
    frame->width          = avci->to_free->width;
206
3522
    frame->height         = avci->to_free->height;
207
3522
    frame->channel_layout = avci->to_free->channel_layout;
208
3522
    frame->nb_samples     = avci->to_free->nb_samples;
209
3522
    frame->channels       = avci->to_free->channels;
210
211
3522
    return 0;
212
}
213
214
12666
int ff_decode_bsfs_init(AVCodecContext *avctx)
215
{
216
12666
    AVCodecInternal *avci = avctx->internal;
217
    int ret;
218
219
12666
    if (avci->bsf)
220
        return 0;
221
222
12666
    ret = av_bsf_list_parse_str(avctx->codec->bsfs, &avci->bsf);
223
12666
    if (ret < 0) {
224
        av_log(avctx, AV_LOG_ERROR, "Error parsing decoder bitstream filters '%s': %s\n", avctx->codec->bsfs, av_err2str(ret));
225
        if (ret != AVERROR(ENOMEM))
226
            ret = AVERROR_BUG;
227
        goto fail;
228
    }
229
230
    /* We do not currently have an API for passing the input timebase into decoders,
231
     * but no filters used here should actually need it.
232
     * So we make up some plausible-looking number (the MPEG 90kHz timebase) */
233
12666
    avci->bsf->time_base_in = (AVRational){ 1, 90000 };
234
12666
    ret = avcodec_parameters_from_context(avci->bsf->par_in, avctx);
235
12666
    if (ret < 0)
236
        goto fail;
237
238
12666
    ret = av_bsf_init(avci->bsf);
239
12666
    if (ret < 0)
240
        goto fail;
241
242
12666
    return 0;
243
fail:
244
    av_bsf_free(&avci->bsf);
245
    return ret;
246
}
247
248
754592
int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt)
249
{
250
754592
    AVCodecInternal *avci = avctx->internal;
251
    int ret;
252
253
754592
    if (avci->draining)
254
2
        return AVERROR_EOF;
255
256
754590
    ret = av_bsf_receive_packet(avci->bsf, pkt);
257
754590
    if (ret == AVERROR_EOF)
258
5870
        avci->draining = 1;
259
754590
    if (ret < 0)
260
380276
        return ret;
261
262
374314
    ret = extract_packet_props(avctx->internal, pkt);
263
374314
    if (ret < 0)
264
        goto finish;
265
266
374314
    ret = apply_param_change(avctx, pkt);
267
374314
    if (ret < 0)
268
        goto finish;
269
270
374314
    if (avctx->codec->receive_frame)
271
92
        avci->compat_decode_consumed += pkt->size;
272
273
374314
    return 0;
274
finish:
275
    av_packet_unref(pkt);
276
    return ret;
277
}
278
279
/**
280
 * Attempt to guess proper monotonic timestamps for decoded video frames
281
 * which might have incorrect times. Input timestamps may wrap around, in
282
 * which case the output will as well.
283
 *
284
 * @param pts the pts field of the decoded AVPacket, as passed through
285
 * AVFrame.pts
286
 * @param dts the dts field of the decoded AVPacket
287
 * @return one of the input values, may be AV_NOPTS_VALUE
288
 */
289
395100
static int64_t guess_correct_pts(AVCodecContext *ctx,
290
                                 int64_t reordered_pts, int64_t dts)
291
{
292
395100
    int64_t pts = AV_NOPTS_VALUE;
293
294
395100
    if (dts != AV_NOPTS_VALUE) {
295
360215
        ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
296
360215
        ctx->pts_correction_last_dts = dts;
297
34885
    } else if (reordered_pts != AV_NOPTS_VALUE)
298
181
        ctx->pts_correction_last_dts = reordered_pts;
299
300
395100
    if (reordered_pts != AV_NOPTS_VALUE) {
301
331501
        ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
302
331501
        ctx->pts_correction_last_pts = reordered_pts;
303
63599
    } else if(dts != AV_NOPTS_VALUE)
304
28895
        ctx->pts_correction_last_pts = dts;
305
306

395100
    if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
307
394285
       && reordered_pts != AV_NOPTS_VALUE)
308
330687
        pts = reordered_pts;
309
    else
310
64413
        pts = dts;
311
312
395100
    return pts;
313
}
314
315
/*
316
 * The core of the receive_frame_wrapper for the decoders implementing
317
 * the simple API. Certain decoders might consume partial packets without
318
 * returning any output, so this function needs to be called in a loop until it
319
 * returns EAGAIN.
320
 **/
321
789975
static inline int decode_simple_internal(AVCodecContext *avctx, AVFrame *frame, int64_t *discarded_samples)
322
{
323
789975
    AVCodecInternal   *avci = avctx->internal;
324
789975
    DecodeSimpleContext *ds = &avci->ds;
325
789975
    AVPacket           *pkt = ds->in_pkt;
326
    // copy to ensure we do not change pkt
327
    int got_frame, actual_got_frame;
328
    int ret;
329
330

789975
    if (!pkt->data && !avci->draining) {
331
754404
        av_packet_unref(pkt);
332
754404
        ret = ff_decode_get_packet(avctx, pkt);
333

754404
        if (ret < 0 && ret != AVERROR_EOF)
334
374314
            return ret;
335
    }
336
337
    // Some codecs (at least wma lossless) will crash when feeding drain packets
338
    // after EOF was signaled.
339
415661
    if (avci->draining_done)
340
6164
        return AVERROR_EOF;
341
342
409497
    if (!pkt->data &&
343
6591
        !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY ||
344
5241
          avctx->active_thread_type & FF_THREAD_FRAME))
345
5192
        return AVERROR_EOF;
346
347
404305
    got_frame = 0;
348
349
404305
    if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) {
350
582
        ret = ff_thread_decode_frame(avctx, frame, &got_frame, pkt);
351
    } else {
352
403723
        ret = avctx->codec->decode(avctx, frame, &got_frame, pkt);
353
354
403723
        if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
355
403393
            frame->pkt_dts = pkt->dts;
356
403723
        if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
357
116154
            if(!avctx->has_b_frames)
358
84143
                frame->pkt_pos = pkt->pos;
359
            //FIXME these should be under if(!avctx->has_b_frames)
360
            /* get_buffer is supposed to set frame parameters */
361
116154
            if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {
362
21609
                if (!frame->sample_aspect_ratio.num)  frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
363
21609
                if (!frame->width)                    frame->width               = avctx->width;
364
21609
                if (!frame->height)                   frame->height              = avctx->height;
365
21609
                if (frame->format == AV_PIX_FMT_NONE) frame->format              = avctx->pix_fmt;
366
            }
367
        }
368
    }
369
404305
    emms_c();
370
404305
    actual_got_frame = got_frame;
371
372
404305
    if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
373
116264
        if (frame->flags & AV_FRAME_FLAG_DISCARD)
374
179
            got_frame = 0;
375
116264
        if (got_frame)
376
108463
            frame->best_effort_timestamp = guess_correct_pts(avctx,
377
                                                             frame->pts,
378
                                                             frame->pkt_dts);
379
288041
    } else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
380
        uint8_t *side;
381
        int side_size;
382
288041
        uint32_t discard_padding = 0;
383
288041
        uint8_t skip_reason = 0;
384
288041
        uint8_t discard_reason = 0;
385
386

288041
        if (ret >= 0 && got_frame) {
387
286637
            frame->best_effort_timestamp = guess_correct_pts(avctx,
388
                                                             frame->pts,
389
                                                             frame->pkt_dts);
390
286637
            if (frame->format == AV_SAMPLE_FMT_NONE)
391
                frame->format = avctx->sample_fmt;
392
286637
            if (!frame->channel_layout)
393
1318
                frame->channel_layout = avctx->channel_layout;
394
286637
            if (!frame->channels)
395
                frame->channels = avctx->channels;
396
286637
            if (!frame->sample_rate)
397
2
                frame->sample_rate = avctx->sample_rate;
398
        }
399
400
288041
        side= av_packet_get_side_data(avci->last_pkt_props, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
401

288041
        if(side && side_size>=10) {
402
92
            avci->skip_samples = AV_RL32(side) * avci->skip_samples_multiplier;
403
92
            discard_padding = AV_RL32(side + 4);
404
92
            av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
405
                   avci->skip_samples, (int)discard_padding);
406
92
            skip_reason = AV_RL8(side + 8);
407
92
            discard_reason = AV_RL8(side + 9);
408
        }
409
410

288041
        if ((frame->flags & AV_FRAME_FLAG_DISCARD) && got_frame &&
411
15
            !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
412
15
            avci->skip_samples = FFMAX(0, avci->skip_samples - frame->nb_samples);
413
15
            got_frame = 0;
414
15
            *discarded_samples += frame->nb_samples;
415
        }
416
417

288041
        if (avci->skip_samples > 0 && got_frame &&
418
143
            !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
419
143
            if(frame->nb_samples <= avci->skip_samples){
420
101
                got_frame = 0;
421
101
                *discarded_samples += frame->nb_samples;
422
101
                avci->skip_samples -= frame->nb_samples;
423
101
                av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
424
                       avci->skip_samples);
425
            } else {
426
42
                av_samples_copy(frame->extended_data, frame->extended_data, 0, avci->skip_samples,
427
42
                                frame->nb_samples - avci->skip_samples, avctx->channels, frame->format);
428

84
                if(avctx->pkt_timebase.num && avctx->sample_rate) {
429
42
                    int64_t diff_ts = av_rescale_q(avci->skip_samples,
430
42
                                                   (AVRational){1, avctx->sample_rate},
431
                                                   avctx->pkt_timebase);
432
42
                    if(frame->pts!=AV_NOPTS_VALUE)
433
42
                        frame->pts += diff_ts;
434
#if FF_API_PKT_PTS
435
FF_DISABLE_DEPRECATION_WARNINGS
436
42
                    if(frame->pkt_pts!=AV_NOPTS_VALUE)
437
42
                        frame->pkt_pts += diff_ts;
438
FF_ENABLE_DEPRECATION_WARNINGS
439
#endif
440
42
                    if(frame->pkt_dts!=AV_NOPTS_VALUE)
441
42
                        frame->pkt_dts += diff_ts;
442
42
                    if (frame->pkt_duration >= diff_ts)
443
42
                        frame->pkt_duration -= diff_ts;
444
                } else {
445
                    av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
446
                }
447
42
                av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
448
                       avci->skip_samples, frame->nb_samples);
449
42
                *discarded_samples += avci->skip_samples;
450
42
                frame->nb_samples -= avci->skip_samples;
451
42
                avci->skip_samples = 0;
452
            }
453
        }
454
455

288041
        if (discard_padding > 0 && discard_padding <= frame->nb_samples && got_frame &&
456
5
            !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
457
5
            if (discard_padding == frame->nb_samples) {
458
2
                *discarded_samples += frame->nb_samples;
459
2
                got_frame = 0;
460
            } else {
461

3
                if(avctx->pkt_timebase.num && avctx->sample_rate) {
462
3
                    int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
463
3
                                                   (AVRational){1, avctx->sample_rate},
464
                                                   avctx->pkt_timebase);
465
3
                    frame->pkt_duration = diff_ts;
466
                } else {
467
                    av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
468
                }
469
3
                av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
470
                       (int)discard_padding, frame->nb_samples);
471
3
                frame->nb_samples -= discard_padding;
472
            }
473
        }
474
475

288041
        if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && got_frame) {
476
            AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
477
            if (fside) {
478
                AV_WL32(fside->data, avci->skip_samples);
479
                AV_WL32(fside->data + 4, discard_padding);
480
                AV_WL8(fside->data + 8, skip_reason);
481
                AV_WL8(fside->data + 9, discard_reason);
482
                avci->skip_samples = 0;
483
            }
484
        }
485
    }
486
487
404305
    if (avctx->codec->type == AVMEDIA_TYPE_AUDIO &&
488

288041
        !avci->showed_multi_packet_warning &&
489

262707
        ret >= 0 && ret != pkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
490
12
        av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
491
12
        avci->showed_multi_packet_warning = 1;
492
    }
493
494
404305
    if (!got_frame)
495
9323
        av_frame_unref(frame);
496
497

404305
    if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
498
115241
        ret = pkt->size;
499
500
#if FF_API_AVCTX_TIMEBASE
501

404305
    if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
502
85035
        avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
503
#endif
504
505
    /* do not stop draining when actual_got_frame != 0 or ret < 0 */
506
    /* got_frame == 0 but actual_got_frame != 0 when frame is discarded */
507

404305
    if (avci->draining && !actual_got_frame) {
508
662
        if (ret < 0) {
509
            /* prevent infinite loop if a decoder wrongly always return error on draining */
510
            /* reasonable nb_errors_max = maximum b frames + thread count */
511
1
            int nb_errors_max = 20 + (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME ?
512
                                avctx->thread_count : 1);
513
514
1
            if (avci->nb_draining_errors++ >= nb_errors_max) {
515
                av_log(avctx, AV_LOG_ERROR, "Too many errors when draining, this is a bug. "
516
                       "Stop draining and force EOF.\n");
517
                avci->draining_done = 1;
518
                ret = AVERROR_BUG;
519
            }
520
        } else {
521
661
            avci->draining_done = 1;
522
        }
523
    }
524
525
404305
    avci->compat_decode_consumed += ret;
526
527

404305
    if (ret >= pkt->size || ret < 0) {
528
375621
        av_packet_unref(pkt);
529
375621
        av_packet_unref(avci->last_pkt_props);
530
    } else {
531
28684
        int consumed = ret;
532
533
28684
        pkt->data                += consumed;
534
28684
        pkt->size                -= consumed;
535
28684
        avci->last_pkt_props->size -= consumed; // See extract_packet_props() comment.
536
28684
        pkt->pts                  = AV_NOPTS_VALUE;
537
28684
        pkt->dts                  = AV_NOPTS_VALUE;
538
28684
        avci->last_pkt_props->pts = AV_NOPTS_VALUE;
539
28684
        avci->last_pkt_props->dts = AV_NOPTS_VALUE;
540
    }
541
542
404305
    if (got_frame)
543
394982
        av_assert0(frame->buf[0]);
544
545
404305
    return ret < 0 ? ret : 0;
546
}
547
548
781639
static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
549
{
550
    int ret;
551
781639
    int64_t discarded_samples = 0;
552
553
1184957
    while (!frame->buf[0]) {
554
789975
        if (discarded_samples > avctx->max_samples)
555
            return AVERROR(EAGAIN);
556
789975
        ret = decode_simple_internal(avctx, frame, &discarded_samples);
557
789975
        if (ret < 0)
558
386657
            return ret;
559
    }
560
561
394982
    return 0;
562
}
563
564
781907
static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
565
{
566
781907
    AVCodecInternal *avci = avctx->internal;
567
    int ret;
568
569
781907
    av_assert0(!frame->buf[0]);
570
571
781907
    if (avctx->codec->receive_frame) {
572
268
        ret = avctx->codec->receive_frame(avctx, frame);
573
268
        if (ret != AVERROR(EAGAIN))
574
176
            av_packet_unref(avci->last_pkt_props);
575
    } else
576
781639
        ret = decode_simple_receive_frame(avctx, frame);
577
578
781907
    if (ret == AVERROR_EOF)
579
11360
        avci->draining_done = 1;
580
581
781907
    if (!ret) {
582
        /* the only case where decode data is not set should be decoders
583
         * that do not call ff_get_buffer() */
584

395154
        av_assert0((frame->private_ref && frame->private_ref->size == sizeof(FrameDecodeData)) ||
585
                   !(avctx->codec->capabilities & AV_CODEC_CAP_DR1));
586
587
395154
        if (frame->private_ref) {
588
373754
            FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
589
590
373754
            if (fdd->post_process) {
591
                ret = fdd->post_process(avctx, frame);
592
                if (ret < 0) {
593
                    av_frame_unref(frame);
594
                    return ret;
595
                }
596
            }
597
        }
598
    }
599
600
    /* free the per-frame decode data */
601
781907
    av_buffer_unref(&frame->private_ref);
602
603
781907
    return ret;
604
}
605
606
380793
int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
607
{
608
380793
    AVCodecInternal *avci = avctx->internal;
609
    int ret;
610
611

380793
    if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
612
        return AVERROR(EINVAL);
613
614
380793
    if (avctx->internal->draining)
615
672
        return AVERROR_EOF;
616
617

380121
    if (avpkt && !avpkt->size && avpkt->data)
618
        return AVERROR(EINVAL);
619
620
380121
    av_packet_unref(avci->buffer_pkt);
621

380121
    if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
622
374251
        ret = av_packet_ref(avci->buffer_pkt, avpkt);
623
374251
        if (ret < 0)
624
            return ret;
625
    }
626
627
380121
    ret = av_bsf_send_packet(avci->bsf, avci->buffer_pkt);
628
380121
    if (ret < 0) {
629
        av_packet_unref(avci->buffer_pkt);
630
        return ret;
631
    }
632
633
380121
    if (!avci->buffer_frame->buf[0]) {
634
380121
        ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
635

380121
        if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
636
982
            return ret;
637
    }
638
639
379139
    return 0;
640
}
641
642
108463
static int apply_cropping(AVCodecContext *avctx, AVFrame *frame)
643
{
644
    /* make sure we are noisy about decoders returning invalid cropping data */
645
108463
    if (frame->crop_left >= INT_MAX - frame->crop_right        ||
646
108463
        frame->crop_top  >= INT_MAX - frame->crop_bottom       ||
647
108463
        (frame->crop_left + frame->crop_right) >= frame->width ||
648
108463
        (frame->crop_top + frame->crop_bottom) >= frame->height) {
649
        av_log(avctx, AV_LOG_WARNING,
650
               "Invalid cropping information set by a decoder: "
651
               "%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER" "
652
               "(frame size %dx%d). This is a bug, please report it\n",
653
               frame->crop_left, frame->crop_right, frame->crop_top, frame->crop_bottom,
654
               frame->width, frame->height);
655
        frame->crop_left   = 0;
656
        frame->crop_right  = 0;
657
        frame->crop_top    = 0;
658
        frame->crop_bottom = 0;
659
        return 0;
660
    }
661
662
108463
    if (!avctx->apply_cropping)
663
        return 0;
664
665
108463
    return av_frame_apply_cropping(frame, avctx->flags & AV_CODEC_FLAG_UNALIGNED ?
666
                                          AV_FRAME_CROP_UNALIGNED : 0);
667
}
668
669
769070
int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
670
{
671
769070
    AVCodecInternal *avci = avctx->internal;
672
    int ret, changed;
673
674
769070
    av_frame_unref(frame);
675
676

769070
    if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
677
        return AVERROR(EINVAL);
678
679
769070
    if (avci->buffer_frame->buf[0]) {
680
367284
        av_frame_move_ref(frame, avci->buffer_frame);
681
    } else {
682
401786
        ret = decode_receive_frame_internal(avctx, frame);
683
401786
        if (ret < 0)
684
373916
            return ret;
685
    }
686
687
395154
    if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
688
108463
        ret = apply_cropping(avctx, frame);
689
108463
        if (ret < 0) {
690
            av_frame_unref(frame);
691
            return ret;
692
        }
693
    }
694
695
395154
    avctx->frame_number++;
696
697
395154
    if (avctx->flags & AV_CODEC_FLAG_DROPCHANGED) {
698
699
        if (avctx->frame_number == 1) {
700
            avci->initial_format = frame->format;
701
            switch(avctx->codec_type) {
702
            case AVMEDIA_TYPE_VIDEO:
703
                avci->initial_width  = frame->width;
704
                avci->initial_height = frame->height;
705
                break;
706
            case AVMEDIA_TYPE_AUDIO:
707
                avci->initial_sample_rate = frame->sample_rate ? frame->sample_rate :
708
                                                                 avctx->sample_rate;
709
                avci->initial_channels       = frame->channels;
710
                avci->initial_channel_layout = frame->channel_layout;
711
                break;
712
            }
713
        }
714
715
        if (avctx->frame_number > 1) {
716
            changed = avci->initial_format != frame->format;
717
718
            switch(avctx->codec_type) {
719
            case AVMEDIA_TYPE_VIDEO:
720
                changed |= avci->initial_width  != frame->width ||
721
                           avci->initial_height != frame->height;
722
                break;
723
            case AVMEDIA_TYPE_AUDIO:
724
                changed |= avci->initial_sample_rate    != frame->sample_rate ||
725
                           avci->initial_sample_rate    != avctx->sample_rate ||
726
                           avci->initial_channels       != frame->channels ||
727
                           avci->initial_channel_layout != frame->channel_layout;
728
                break;
729
            }
730
731
            if (changed) {
732
                avci->changed_frames_dropped++;
733
                av_log(avctx, AV_LOG_INFO, "dropped changed frame #%d pts %"PRId64
734
                                            " drop count: %d \n",
735
                                            avctx->frame_number, frame->pts,
736
                                            avci->changed_frames_dropped);
737
                av_frame_unref(frame);
738
                return AVERROR_INPUT_CHANGED;
739
            }
740
        }
741
    }
742
395154
    return 0;
743
}
744
745
3530
static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
746
                         int *got_frame, const AVPacket *pkt)
747
{
748
3530
    AVCodecInternal *avci = avctx->internal;
749
3530
    int ret = 0;
750
751
3530
    av_assert0(avci->compat_decode_consumed == 0);
752
753

3530
    if (avci->draining_done && pkt && pkt->size != 0) {
754
        av_log(avctx, AV_LOG_WARNING, "Got unexpected packet after EOF\n");
755
        avcodec_flush_buffers(avctx);
756
    }
757
758
3530
    *got_frame = 0;
759
760
3530
    if (avci->compat_decode_partial_size > 0 &&
761
        avci->compat_decode_partial_size != pkt->size) {
762
        av_log(avctx, AV_LOG_ERROR,
763
               "Got unexpected packet size after a partial decode\n");
764
        ret = AVERROR(EINVAL);
765
        goto finish;
766
    }
767
768
3530
    if (!avci->compat_decode_partial_size) {
769
3530
        ret = avcodec_send_packet(avctx, pkt);
770
3530
        if (ret == AVERROR_EOF)
771
            ret = 0;
772
3530
        else if (ret == AVERROR(EAGAIN)) {
773
            /* we fully drain all the output in each decode call, so this should not
774
             * ever happen */
775
            ret = AVERROR_BUG;
776
            goto finish;
777
3530
        } else if (ret < 0)
778
            goto finish;
779
    }
780
781
7055
    while (ret >= 0) {
782
7055
        ret = avcodec_receive_frame(avctx, frame);
783
7055
        if (ret < 0) {
784

3530
            if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
785
3530
                ret = 0;
786
3530
            goto finish;
787
        }
788
789
3525
        if (frame != avci->compat_decode_frame) {
790
3525
            if (!avctx->refcounted_frames) {
791
3522
                ret = unrefcount_frame(avci, frame);
792
3522
                if (ret < 0)
793
                    goto finish;
794
            }
795
796
3525
            *got_frame = 1;
797
3525
            frame = avci->compat_decode_frame;
798
        } else {
799
            if (!avci->compat_decode_warned) {
800
                av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "
801
                       "API cannot return all the frames for this decoder. "
802
                       "Some frames will be dropped. Update your code to the "
803
                       "new decoding API to fix this.\n");
804
                avci->compat_decode_warned = 1;
805
            }
806
        }
807
808

3525
        if (avci->draining || (!avctx->codec->bsfs && avci->compat_decode_consumed < pkt->size))
809
            break;
810
    }
811
812
finish:
813
3530
    if (ret == 0) {
814
        /* if there are any bsfs then assume full packet is always consumed */
815
3530
        if (avctx->codec->bsfs)
816
            ret = pkt->size;
817
        else
818
3530
            ret = FFMIN(avci->compat_decode_consumed, pkt->size);
819
    }
820
3530
    avci->compat_decode_consumed = 0;
821
3530
    avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;
822
823
3530
    return ret;
824
}
825
826
330
int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
827
                                              int *got_picture_ptr,
828
                                              const AVPacket *avpkt)
829
{
830
330
    return compat_decode(avctx, picture, got_picture_ptr, avpkt);
831
}
832
833
3200
int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
834
                                              AVFrame *frame,
835
                                              int *got_frame_ptr,
836
                                              const AVPacket *avpkt)
837
{
838
3200
    return compat_decode(avctx, frame, got_frame_ptr, avpkt);
839
}
840
841
1273
static void get_subtitle_defaults(AVSubtitle *sub)
842
{
843
1273
    memset(sub, 0, sizeof(*sub));
844
1273
    sub->pts = AV_NOPTS_VALUE;
845
1273
}
846
847
#define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
848
1243
static int recode_subtitle(AVCodecContext *avctx,
849
                           AVPacket *outpkt, const AVPacket *inpkt)
850
{
851
#if CONFIG_ICONV
852
1243
    iconv_t cd = (iconv_t)-1;
853
1243
    int ret = 0;
854
    char *inb, *outb;
855
    size_t inl, outl;
856
    AVPacket tmp;
857
#endif
858
859

1243
    if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
860
1150
        return 0;
861
862
#if CONFIG_ICONV
863
93
    cd = iconv_open("UTF-8", avctx->sub_charenc);
864
93
    av_assert0(cd != (iconv_t)-1);
865
866
93
    inb = inpkt->data;
867
93
    inl = inpkt->size;
868
869
93
    if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
870
        av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
871
        ret = AVERROR(ENOMEM);
872
        goto end;
873
    }
874
875
93
    ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
876
93
    if (ret < 0)
877
        goto end;
878
93
    outpkt->buf  = tmp.buf;
879
93
    outpkt->data = tmp.data;
880
93
    outpkt->size = tmp.size;
881
93
    outb = outpkt->data;
882
93
    outl = outpkt->size;
883
884

186
    if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
885
93
        iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
886

93
        outl >= outpkt->size || inl != 0) {
887
        ret = FFMIN(AVERROR(errno), -1);
888
        av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
889
               "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
890
        av_packet_unref(&tmp);
891
        goto end;
892
    }
893
93
    outpkt->size -= outl;
894
93
    memset(outpkt->data + outpkt->size, 0, outl);
895
896
93
end:
897
93
    if (cd != (iconv_t)-1)
898
93
        iconv_close(cd);
899
93
    return ret;
900
#else
901
    av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
902
    return AVERROR(EINVAL);
903
#endif
904
}
905
906
552
static int utf8_check(const uint8_t *str)
907
{
908
    const uint8_t *byte;
909
    uint32_t codepoint, min;
910
911
46245
    while (*str) {
912
45693
        byte = str;
913


48466
        GET_UTF8(codepoint, *(byte++), return 0;);
914

46389
        min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
915
696
              1 << (5 * (byte - str) - 4);
916

45693
        if (codepoint < min || codepoint >= 0x110000 ||
917
45693
            codepoint == 0xFFFE /* BOM */ ||
918
            codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
919
            return 0;
920
45693
        str = byte;
921
    }
922
552
    return 1;
923
}
924
925
#if FF_API_ASS_TIMING
926
static void insert_ts(AVBPrint *buf, int ts)
927
{
928
    if (ts == -1) {
929
        av_bprintf(buf, "9:59:59.99,");
930
    } else {
931
        int h, m, s;
932
933
        h = ts/360000;  ts -= 360000*h;
934
        m = ts/  6000;  ts -=   6000*m;
935
        s = ts/   100;  ts -=    100*s;
936
        av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
937
    }
938
}
939
940
static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
941
{
942
    int i;
943
    AVBPrint buf;
944
945
    av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
946
947
    for (i = 0; i < sub->num_rects; i++) {
948
        char *final_dialog;
949
        const char *dialog;
950
        AVSubtitleRect *rect = sub->rects[i];
951
        int ts_start, ts_duration = -1;
952
        long int layer;
953
954
        if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
955
            continue;
956
957
        av_bprint_clear(&buf);
958
959
        /* skip ReadOrder */
960
        dialog = strchr(rect->ass, ',');
961
        if (!dialog)
962
            continue;
963
        dialog++;
964
965
        /* extract Layer or Marked */
966
        layer = strtol(dialog, (char**)&dialog, 10);
967
        if (*dialog != ',')
968
            continue;
969
        dialog++;
970
971
        /* rescale timing to ASS time base (ms) */
972
        ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
973
        if (pkt->duration != -1)
974
            ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
975
        sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
976
977
        /* construct ASS (standalone file form with timestamps) string */
978
        av_bprintf(&buf, "Dialogue: %ld,", layer);
979
        insert_ts(&buf, ts_start);
980
        insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
981
        av_bprintf(&buf, "%s\r\n", dialog);
982
983
        final_dialog = av_strdup(buf.str);
984
        if (!av_bprint_is_complete(&buf) || !final_dialog) {
985
            av_freep(&final_dialog);
986
            av_bprint_finalize(&buf, NULL);
987
            return AVERROR(ENOMEM);
988
        }
989
        av_freep(&rect->ass);
990
        rect->ass = final_dialog;
991
    }
992
993
    av_bprint_finalize(&buf, NULL);
994
    return 0;
995
}
996
#endif
997
998
1273
int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
999
                             int *got_sub_ptr,
1000
                             AVPacket *avpkt)
1001
{
1002
1273
    int i, ret = 0;
1003
1004

1273
    if (!avpkt->data && avpkt->size) {
1005
        av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1006
        return AVERROR(EINVAL);
1007
    }
1008
1273
    if (!avctx->codec)
1009
        return AVERROR(EINVAL);
1010
1273
    if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
1011
        av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
1012
        return AVERROR(EINVAL);
1013
    }
1014
1015
1273
    *got_sub_ptr = 0;
1016
1273
    get_subtitle_defaults(sub);
1017
1018

1273
    if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
1019
1243
        AVPacket pkt_recoded = *avpkt;
1020
1021
1243
        ret = recode_subtitle(avctx, &pkt_recoded, avpkt);
1022
1243
        if (ret < 0) {
1023
            *got_sub_ptr = 0;
1024
        } else {
1025
1243
             ret = extract_packet_props(avctx->internal, &pkt_recoded);
1026
1243
             if (ret < 0)
1027
                return ret;
1028
1029

1243
            if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
1030
1237
                sub->pts = av_rescale_q(avpkt->pts,
1031
1237
                                        avctx->pkt_timebase, AV_TIME_BASE_Q);
1032
1243
            ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
1033
            av_assert1((ret >= 0) >= !!*got_sub_ptr &&
1034
                       !!*got_sub_ptr >= !!sub->num_rects);
1035
1036
#if FF_API_ASS_TIMING
1037
1243
            if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
1038

1
                && *got_sub_ptr && sub->num_rects) {
1039
                const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
1040
                                                              : avctx->time_base;
1041
                int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
1042
                if (err < 0)
1043
                    ret = err;
1044
            }
1045
#endif
1046
1047

1243
            if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
1048
380
                avctx->pkt_timebase.num) {
1049
380
                AVRational ms = { 1, 1000 };
1050
380
                sub->end_display_time = av_rescale_q(avpkt->duration,
1051
                                                     avctx->pkt_timebase, ms);
1052
            }
1053
1054
1243
            if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
1055
150
                sub->format = 0;
1056
1093
            else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
1057
1093
                sub->format = 1;
1058
1059
1950
            for (i = 0; i < sub->num_rects; i++) {
1060
707
                if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_IGNORE &&
1061

707
                    sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
1062
                    av_log(avctx, AV_LOG_ERROR,
1063
                           "Invalid UTF-8 in decoded subtitles text; "
1064
                           "maybe missing -sub_charenc option\n");
1065
                    avsubtitle_free(sub);
1066
                    ret = AVERROR_INVALIDDATA;
1067
                    break;
1068
                }
1069
            }
1070
1071
1243
            if (avpkt->data != pkt_recoded.data) { // did we recode?
1072
                /* prevent from destroying side data from original packet */
1073
93
                pkt_recoded.side_data = NULL;
1074
93
                pkt_recoded.side_data_elems = 0;
1075
1076
93
                av_packet_unref(&pkt_recoded);
1077
            }
1078
        }
1079
1080
1243
        if (*got_sub_ptr)
1081
685
            avctx->frame_number++;
1082
    }
1083
1084
1273
    return ret;
1085
}
1086
1087
1395
enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *avctx,
1088
                                              const enum AVPixelFormat *fmt)
1089
{
1090
    const AVPixFmtDescriptor *desc;
1091
    const AVCodecHWConfig *config;
1092
    int i, n;
1093
1094
    // If a device was supplied when the codec was opened, assume that the
1095
    // user wants to use it.
1096

1395
    if (avctx->hw_device_ctx && avctx->codec->hw_configs) {
1097
        AVHWDeviceContext *device_ctx =
1098
            (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1099
        for (i = 0;; i++) {
1100
            config = &avctx->codec->hw_configs[i]->public;
1101
            if (!config)
1102
                break;
1103
            if (!(config->methods &
1104
                  AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
1105
                continue;
1106
            if (device_ctx->type != config->device_type)
1107
                continue;
1108
            for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
1109
                if (config->pix_fmt == fmt[n])
1110
                    return fmt[n];
1111
            }
1112
        }
1113
    }
1114
    // No device or other setup, so we have to choose from things which
1115
    // don't any other external information.
1116
1117
    // If the last element of the list is a software format, choose it
1118
    // (this should be best software format if any exist).
1119
4972
    for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
1120
1395
    desc = av_pix_fmt_desc_get(fmt[n - 1]);
1121
1395
    if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
1122
1395
        return fmt[n - 1];
1123
1124
    // Finally, traverse the list in order and choose the first entry
1125
    // with no external dependencies (if there is no hardware configuration
1126
    // information available then this just picks the first entry).
1127
    for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
1128
        for (i = 0;; i++) {
1129
            config = avcodec_get_hw_config(avctx->codec, i);
1130
            if (!config)
1131
                break;
1132
            if (config->pix_fmt == fmt[n])
1133
                break;
1134
        }
1135
        if (!config) {
1136
            // No specific config available, so the decoder must be able
1137
            // to handle this format without any additional setup.
1138
            return fmt[n];
1139
        }
1140
        if (config->methods & AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1141
            // Usable with only internal setup.
1142
            return fmt[n];
1143
        }
1144
    }
1145
1146
    // Nothing is usable, give up.
1147
    return AV_PIX_FMT_NONE;
1148
}
1149
1150
int ff_decode_get_hw_frames_ctx(AVCodecContext *avctx,
1151
                                enum AVHWDeviceType dev_type)
1152
{
1153
    AVHWDeviceContext *device_ctx;
1154
    AVHWFramesContext *frames_ctx;
1155
    int ret;
1156
1157
    if (!avctx->hwaccel)
1158
        return AVERROR(ENOSYS);
1159
1160
    if (avctx->hw_frames_ctx)
1161
        return 0;
1162
    if (!avctx->hw_device_ctx) {
1163
        av_log(avctx, AV_LOG_ERROR, "A hardware frames or device context is "
1164
                "required for hardware accelerated decoding.\n");
1165
        return AVERROR(EINVAL);
1166
    }
1167
1168
    device_ctx = (AVHWDeviceContext *)avctx->hw_device_ctx->data;
1169
    if (device_ctx->type != dev_type) {
1170
        av_log(avctx, AV_LOG_ERROR, "Device type %s expected for hardware "
1171
               "decoding, but got %s.\n", av_hwdevice_get_type_name(dev_type),
1172
               av_hwdevice_get_type_name(device_ctx->type));
1173
        return AVERROR(EINVAL);
1174
    }
1175
1176
    ret = avcodec_get_hw_frames_parameters(avctx,
1177
                                           avctx->hw_device_ctx,
1178
                                           avctx->hwaccel->pix_fmt,
1179
                                           &avctx->hw_frames_ctx);
1180
    if (ret < 0)
1181
        return ret;
1182
1183
    frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1184
1185
1186
    if (frames_ctx->initial_pool_size) {
1187
        // We guarantee 4 base work surfaces. The function above guarantees 1
1188
        // (the absolute minimum), so add the missing count.
1189
        frames_ctx->initial_pool_size += 3;
1190
    }
1191
1192
    ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
1193
    if (ret < 0) {
1194
        av_buffer_unref(&avctx->hw_frames_ctx);
1195
        return ret;
1196
    }
1197
1198
    return 0;
1199
}
1200
1201
int avcodec_get_hw_frames_parameters(AVCodecContext *avctx,
1202
                                     AVBufferRef *device_ref,
1203
                                     enum AVPixelFormat hw_pix_fmt,
1204
                                     AVBufferRef **out_frames_ref)
1205
{
1206
    AVBufferRef *frames_ref = NULL;
1207
    const AVCodecHWConfigInternal *hw_config;
1208
    const AVHWAccel *hwa;
1209
    int i, ret;
1210
1211
    for (i = 0;; i++) {
1212
        hw_config = avctx->codec->hw_configs[i];
1213
        if (!hw_config)
1214
            return AVERROR(ENOENT);
1215
        if (hw_config->public.pix_fmt == hw_pix_fmt)
1216
            break;
1217
    }
1218
1219
    hwa = hw_config->hwaccel;
1220
    if (!hwa || !hwa->frame_params)
1221
        return AVERROR(ENOENT);
1222
1223
    frames_ref = av_hwframe_ctx_alloc(device_ref);
1224
    if (!frames_ref)
1225
        return AVERROR(ENOMEM);
1226
1227
    ret = hwa->frame_params(avctx, frames_ref);
1228
    if (ret >= 0) {
1229
        AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frames_ref->data;
1230
1231
        if (frames_ctx->initial_pool_size) {
1232
            // If the user has requested that extra output surfaces be
1233
            // available then add them here.
1234
            if (avctx->extra_hw_frames > 0)
1235
                frames_ctx->initial_pool_size += avctx->extra_hw_frames;
1236
1237
            // If frame threading is enabled then an extra surface per thread
1238
            // is also required.
1239
            if (avctx->active_thread_type & FF_THREAD_FRAME)
1240
                frames_ctx->initial_pool_size += avctx->thread_count;
1241
        }
1242
1243
        *out_frames_ref = frames_ref;
1244
    } else {
1245
        av_buffer_unref(&frames_ref);
1246
    }
1247
    return ret;
1248
}
1249
1250
static int hwaccel_init(AVCodecContext *avctx,
1251
                        const AVCodecHWConfigInternal *hw_config)
1252
{
1253
    const AVHWAccel *hwaccel;
1254
    int err;
1255
1256
    hwaccel = hw_config->hwaccel;
1257
    if (hwaccel->capabilities & AV_HWACCEL_CODEC_CAP_EXPERIMENTAL &&
1258
        avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1259
        av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
1260
               hwaccel->name);
1261
        return AVERROR_PATCHWELCOME;
1262
    }
1263
1264
    if (hwaccel->priv_data_size) {
1265
        avctx->internal->hwaccel_priv_data =
1266
            av_mallocz(hwaccel->priv_data_size);
1267
        if (!avctx->internal->hwaccel_priv_data)
1268
            return AVERROR(ENOMEM);
1269
    }
1270
1271
    avctx->hwaccel = hwaccel;
1272
    if (hwaccel->init) {
1273
        err = hwaccel->init(avctx);
1274
        if (err < 0) {
1275
            av_log(avctx, AV_LOG_ERROR, "Failed setup for format %s: "
1276
                   "hwaccel initialisation returned error.\n",
1277
                   av_get_pix_fmt_name(hw_config->public.pix_fmt));
1278
            av_freep(&avctx->internal->hwaccel_priv_data);
1279
            avctx->hwaccel = NULL;
1280
            return err;
1281
        }
1282
    }
1283
1284
    return 0;
1285
}
1286
1287
2316
static void hwaccel_uninit(AVCodecContext *avctx)
1288
{
1289

2316
    if (avctx->hwaccel && avctx->hwaccel->uninit)
1290
        avctx->hwaccel->uninit(avctx);
1291
1292
2316
    av_freep(&avctx->internal->hwaccel_priv_data);
1293
1294
2316
    avctx->hwaccel = NULL;
1295
1296
2316
    av_buffer_unref(&avctx->hw_frames_ctx);
1297
2316
}
1298
1299
2316
int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1300
{
1301
    const AVPixFmtDescriptor *desc;
1302
    enum AVPixelFormat *choices;
1303
    enum AVPixelFormat ret, user_choice;
1304
    const AVCodecHWConfigInternal *hw_config;
1305
    const AVCodecHWConfig *config;
1306
    int i, n, err;
1307
1308
    // Find end of list.
1309
8426
    for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
1310
    // Must contain at least one entry.
1311
2316
    av_assert0(n >= 1);
1312
    // If a software format is available, it must be the last entry.
1313
2316
    desc = av_pix_fmt_desc_get(fmt[n - 1]);
1314
2316
    if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
1315
        // No software format is available.
1316
    } else {
1317
2316
        avctx->sw_pix_fmt = fmt[n - 1];
1318
    }
1319
1320
2316
    choices = av_malloc_array(n + 1, sizeof(*choices));
1321
2316
    if (!choices)
1322
        return AV_PIX_FMT_NONE;
1323
1324
2316
    memcpy(choices, fmt, (n + 1) * sizeof(*choices));
1325
1326
    for (;;) {
1327
        // Remove the previous hwaccel, if there was one.
1328
2316
        hwaccel_uninit(avctx);
1329
1330
2316
        user_choice = avctx->get_format(avctx, choices);
1331
2316
        if (user_choice == AV_PIX_FMT_NONE) {
1332
            // Explicitly chose nothing, give up.
1333
            ret = AV_PIX_FMT_NONE;
1334
            break;
1335
        }
1336
1337
2316
        desc = av_pix_fmt_desc_get(user_choice);
1338
2316
        if (!desc) {
1339
            av_log(avctx, AV_LOG_ERROR, "Invalid format returned by "
1340
                   "get_format() callback.\n");
1341
            ret = AV_PIX_FMT_NONE;
1342
            break;
1343
        }
1344
2316
        av_log(avctx, AV_LOG_DEBUG, "Format %s chosen by get_format().\n",
1345
               desc->name);
1346
1347
6110
        for (i = 0; i < n; i++) {
1348
6110
            if (choices[i] == user_choice)
1349
2316
                break;
1350
        }
1351
2316
        if (i == n) {
1352
            av_log(avctx, AV_LOG_ERROR, "Invalid return from get_format(): "
1353
                   "%s not in possible list.\n", desc->name);
1354
            ret = AV_PIX_FMT_NONE;
1355
            break;
1356
        }
1357
1358
2316
        if (avctx->codec->hw_configs) {
1359
6233
            for (i = 0;; i++) {
1360
6233
                hw_config = avctx->codec->hw_configs[i];
1361
6233
                if (!hw_config)
1362
2213
                    break;
1363
4020
                if (hw_config->public.pix_fmt == user_choice)
1364
                    break;
1365
            }
1366
        } else {
1367
103
            hw_config = NULL;
1368
        }
1369
1370
2316
        if (!hw_config) {
1371
            // No config available, so no extra setup required.
1372
2316
            ret = user_choice;
1373
2316
            break;
1374
        }
1375
        config = &hw_config->public;
1376
1377
        if (config->methods &
1378
            AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX &&
1379
            avctx->hw_frames_ctx) {
1380
            const AVHWFramesContext *frames_ctx =
1381
                (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1382
            if (frames_ctx->format != user_choice) {
1383
                av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1384
                       "does not match the format of the provided frames "
1385
                       "context.\n", desc->name);
1386
                goto try_again;
1387
            }
1388
        } else if (config->methods &
1389
                   AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
1390
                   avctx->hw_device_ctx) {
1391
            const AVHWDeviceContext *device_ctx =
1392
                (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1393
            if (device_ctx->type != config->device_type) {
1394
                av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1395
                       "does not match the type of the provided device "
1396
                       "context.\n", desc->name);
1397
                goto try_again;
1398
            }
1399
        } else if (config->methods &
1400
                   AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1401
            // Internal-only setup, no additional configuration.
1402
        } else if (config->methods &
1403
                   AV_CODEC_HW_CONFIG_METHOD_AD_HOC) {
1404
            // Some ad-hoc configuration we can't see and can't check.
1405
        } else {
1406
            av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1407
                   "missing configuration.\n", desc->name);
1408
            goto try_again;
1409
        }
1410
        if (hw_config->hwaccel) {
1411
            av_log(avctx, AV_LOG_DEBUG, "Format %s requires hwaccel "
1412
                   "initialisation.\n", desc->name);
1413
            err = hwaccel_init(avctx, hw_config);
1414
            if (err < 0)
1415
                goto try_again;
1416
        }
1417
        ret = user_choice;
1418
        break;
1419
1420
    try_again:
1421
        av_log(avctx, AV_LOG_DEBUG, "Format %s not usable, retrying "
1422
               "get_format() without it.\n", desc->name);
1423
        for (i = 0; i < n; i++) {
1424
            if (choices[i] == user_choice)
1425
                break;
1426
        }
1427
        for (; i + 1 < n; i++)
1428
            choices[i] = choices[i + 1];
1429
        --n;
1430
    }
1431
1432
2316
    av_freep(&choices);
1433
2316
    return ret;
1434
}
1435
1436
16408
static void frame_pool_free(void *opaque, uint8_t *data)
1437
{
1438
16408
    FramePool *pool = (FramePool*)data;
1439
    int i;
1440
1441
82040
    for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
1442
65632
        av_buffer_pool_uninit(&pool->pools[i]);
1443
1444
16408
    av_freep(&data);
1445
16408
}
1446
1447
16408
static AVBufferRef *frame_pool_alloc(void)
1448
{
1449
16408
    FramePool *pool = av_mallocz(sizeof(*pool));
1450
    AVBufferRef *buf;
1451
1452
16408
    if (!pool)
1453
        return NULL;
1454
1455
16408
    buf = av_buffer_create((uint8_t*)pool, sizeof(*pool),
1456
                           frame_pool_free, NULL, 0);
1457
16408
    if (!buf) {
1458
        av_freep(&pool);
1459
        return NULL;
1460
    }
1461
1462
16408
    return buf;
1463
}
1464
1465
379319
static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
1466
{
1467
758638
    FramePool *pool = avctx->internal->pool ?
1468
379319
                      (FramePool*)avctx->internal->pool->data : NULL;
1469
    AVBufferRef *pool_buf;
1470
    int i, ret, ch, planes;
1471
1472
379319
    if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
1473
286873
        int planar = av_sample_fmt_is_planar(frame->format);
1474
286873
        ch     = frame->channels;
1475
286873
        planes = planar ? ch : 1;
1476
    }
1477
1478

379319
    if (pool && pool->format == frame->format) {
1479
369541
        if (avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
1480

84235
            pool->width == frame->width && pool->height == frame->height)
1481
83980
            return 0;
1482

285561
        if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && pool->planes == planes &&
1483

285293
            pool->channels == ch && frame->nb_samples == pool->samples)
1484
278931
            return 0;
1485
    }
1486
1487
16408
    pool_buf = frame_pool_alloc();
1488
16408
    if (!pool_buf)
1489
        return AVERROR(ENOMEM);
1490
16408
    pool = (FramePool*)pool_buf->data;
1491
1492
16408
    switch (avctx->codec_type) {
1493
8466
    case AVMEDIA_TYPE_VIDEO: {
1494
        int linesize[4];
1495
8466
        int w = frame->width;
1496
8466
        int h = frame->height;
1497
        int unaligned;
1498
        ptrdiff_t linesize1[4];
1499
        size_t size[4];
1500
1501
8466
        avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
1502
1503
        do {
1504
            // NOTE: do not align linesizes individually, this breaks e.g. assumptions
1505
            // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
1506
17005
            ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
1507
17005
            if (ret < 0)
1508
                goto fail;
1509
            // increase alignment of w for next try (rhs gives the lowest bit set in w)
1510
17005
            w += w & ~(w - 1);
1511
1512
17005
            unaligned = 0;
1513
85025
            for (i = 0; i < 4; i++)
1514
68020
                unaligned |= linesize[i] % pool->stride_align[i];
1515
17005
        } while (unaligned);
1516
1517
42330
        for (i = 0; i < 4; i++)
1518
33864
            linesize1[i] = linesize[i];
1519
8466
        ret = av_image_fill_plane_sizes(size, avctx->pix_fmt, h, linesize1);
1520
8466
        if (ret < 0)
1521
            goto fail;
1522
1523
42330
        for (i = 0; i < 4; i++) {
1524
33864
            pool->linesize[i] = linesize[i];
1525
33864
            if (size[i]) {
1526
24062
                if (size[i] > INT_MAX - (16 + STRIDE_ALIGN - 1)) {
1527
                    ret = AVERROR(EINVAL);
1528
                    goto fail;
1529
                }
1530
24062
                pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
1531
                                                     CONFIG_MEMORY_POISONING ?
1532
                                                        NULL :
1533
                                                        av_buffer_allocz);
1534
24062
                if (!pool->pools[i]) {
1535
                    ret = AVERROR(ENOMEM);
1536
                    goto fail;
1537
                }
1538
            }
1539
        }
1540
8466
        pool->format = frame->format;
1541
8466
        pool->width  = frame->width;
1542
8466
        pool->height = frame->height;
1543
1544
8466
        break;
1545
        }
1546
7942
    case AVMEDIA_TYPE_AUDIO: {
1547
7942
        ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
1548
7942
                                         frame->nb_samples, frame->format, 0);
1549
7942
        if (ret < 0)
1550
            goto fail;
1551
1552
7942
        pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
1553
7942
        if (!pool->pools[0]) {
1554
            ret = AVERROR(ENOMEM);
1555
            goto fail;
1556
        }
1557
1558
7942
        pool->format     = frame->format;
1559
7942
        pool->planes     = planes;
1560
7942
        pool->channels   = ch;
1561
7942
        pool->samples = frame->nb_samples;
1562
7942
        break;
1563
        }
1564
    default: av_assert0(0);
1565
    }
1566
1567
16408
    av_buffer_unref(&avctx->internal->pool);
1568
16408
    avctx->internal->pool = pool_buf;
1569
1570
16408
    return 0;
1571
fail:
1572
    av_buffer_unref(&pool_buf);
1573
    return ret;
1574
}
1575
1576
286873
static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
1577
{
1578
286873
    FramePool *pool = (FramePool*)avctx->internal->pool->data;
1579
286873
    int planes = pool->planes;
1580
    int i;
1581
1582
286873
    frame->linesize[0] = pool->linesize[0];
1583
1584
286873
    if (planes > AV_NUM_DATA_POINTERS) {
1585
        frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
1586
        frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
1587
        frame->extended_buf  = av_mallocz_array(frame->nb_extended_buf,
1588
                                          sizeof(*frame->extended_buf));
1589
        if (!frame->extended_data || !frame->extended_buf) {
1590
            av_freep(&frame->extended_data);
1591
            av_freep(&frame->extended_buf);
1592
            return AVERROR(ENOMEM);
1593
        }
1594
    } else {
1595
286873
        frame->extended_data = frame->data;
1596
286873
        av_assert0(frame->nb_extended_buf == 0);
1597
    }
1598
1599
715884
    for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
1600
429011
        frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
1601
429011
        if (!frame->buf[i])
1602
            goto fail;
1603
429011
        frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
1604
    }
1605
286873
    for (i = 0; i < frame->nb_extended_buf; i++) {
1606
        frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
1607
        if (!frame->extended_buf[i])
1608
            goto fail;
1609
        frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
1610
    }
1611
1612
286873
    if (avctx->debug & FF_DEBUG_BUFFERS)
1613
        av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
1614
1615
286873
    return 0;
1616
fail:
1617
    av_frame_unref(frame);
1618
    return AVERROR(ENOMEM);
1619
}
1620
1621
92446
static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
1622
{
1623
92446
    FramePool *pool = (FramePool*)s->internal->pool->data;
1624
92446
    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
1625
    int i;
1626
1627


92446
    if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
1628
        av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
1629
        return -1;
1630
    }
1631
1632
92446
    if (!desc) {
1633
        av_log(s, AV_LOG_ERROR,
1634
            "Unable to get pixel format descriptor for format %s\n",
1635
            av_get_pix_fmt_name(pic->format));
1636
        return AVERROR(EINVAL);
1637
    }
1638
1639
92446
    memset(pic->data, 0, sizeof(pic->data));
1640
92446
    pic->extended_data = pic->data;
1641
1642

357400
    for (i = 0; i < 4 && pool->pools[i]; i++) {
1643
264954
        pic->linesize[i] = pool->linesize[i];
1644
1645
264954
        pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
1646
264954
        if (!pic->buf[i])
1647
            goto fail;
1648
1649
264954
        pic->data[i] = pic->buf[i]->data;
1650
    }
1651
567060
    for (; i < AV_NUM_DATA_POINTERS; i++) {
1652
474614
        pic->data[i] = NULL;
1653
474614
        pic->linesize[i] = 0;
1654
    }
1655
92446
    if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
1656

90319
        ((desc->flags & FF_PSEUDOPAL) && pic->data[1]))
1657
2403
        avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
1658
1659
92446
    if (s->debug & FF_DEBUG_BUFFERS)
1660
        av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
1661
1662
92446
    return 0;
1663
fail:
1664
    av_frame_unref(pic);
1665
    return AVERROR(ENOMEM);
1666
}
1667
1668
379319
int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
1669
{
1670
    int ret;
1671
1672
379319
    if (avctx->hw_frames_ctx) {
1673
        ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
1674
        frame->width  = avctx->coded_width;
1675
        frame->height = avctx->coded_height;
1676
        return ret;
1677
    }
1678
1679
379319
    if ((ret = update_frame_pool(avctx, frame)) < 0)
1680
        return ret;
1681
1682
379319
    switch (avctx->codec_type) {
1683
92446
    case AVMEDIA_TYPE_VIDEO:
1684
92446
        return video_get_buffer(avctx, frame);
1685
286873
    case AVMEDIA_TYPE_AUDIO:
1686
286873
        return audio_get_buffer(avctx, frame);
1687
    default:
1688
        return -1;
1689
    }
1690
}
1691
1692
406037
static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
1693
{
1694
    int size;
1695
    const uint8_t *side_metadata;
1696
1697
406037
    AVDictionary **frame_md = &frame->metadata;
1698
1699
406037
    side_metadata = av_packet_get_side_data(avpkt,
1700
                                            AV_PKT_DATA_STRINGS_METADATA, &size);
1701
406037
    return av_packet_unpack_dictionary(side_metadata, size, frame_md);
1702
}
1703
1704
406037
int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
1705
{
1706
406037
    AVPacket *pkt = avctx->internal->last_pkt_props;
1707
    int i;
1708
    static const struct {
1709
        enum AVPacketSideDataType packet;
1710
        enum AVFrameSideDataType frame;
1711
    } sd[] = {
1712
        { AV_PKT_DATA_REPLAYGAIN ,                AV_FRAME_DATA_REPLAYGAIN },
1713
        { AV_PKT_DATA_DISPLAYMATRIX,              AV_FRAME_DATA_DISPLAYMATRIX },
1714
        { AV_PKT_DATA_SPHERICAL,                  AV_FRAME_DATA_SPHERICAL },
1715
        { AV_PKT_DATA_STEREO3D,                   AV_FRAME_DATA_STEREO3D },
1716
        { AV_PKT_DATA_AUDIO_SERVICE_TYPE,         AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
1717
        { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
1718
        { AV_PKT_DATA_CONTENT_LIGHT_LEVEL,        AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
1719
        { AV_PKT_DATA_A53_CC,                     AV_FRAME_DATA_A53_CC },
1720
        { AV_PKT_DATA_ICC_PROFILE,                AV_FRAME_DATA_ICC_PROFILE },
1721
        { AV_PKT_DATA_S12M_TIMECODE,              AV_FRAME_DATA_S12M_TIMECODE },
1722
    };
1723
1724
406037
    if (IS_EMPTY(pkt))
1725
9013
        avpriv_packet_list_get(&avctx->internal->pkt_props,
1726
9013
                               &avctx->internal->pkt_props_tail,
1727
                               pkt);
1728
1729
406037
    if (pkt) {
1730
406037
        frame->pts = pkt->pts;
1731
#if FF_API_PKT_PTS
1732
FF_DISABLE_DEPRECATION_WARNINGS
1733
406037
        frame->pkt_pts = pkt->pts;
1734
FF_ENABLE_DEPRECATION_WARNINGS
1735
#endif
1736
406037
        frame->pkt_pos      = pkt->pos;
1737
406037
        frame->pkt_duration = pkt->duration;
1738
406037
        frame->pkt_size     = pkt->size;
1739
1740
4466407
        for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
1741
            int size;
1742
4060370
            uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
1743
4060370
            if (packet_sd) {
1744
209
                AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
1745
                                                                   sd[i].frame,
1746
                                                                   size);
1747
209
                if (!frame_sd)
1748
                    return AVERROR(ENOMEM);
1749
1750
209
                memcpy(frame_sd->data, packet_sd, size);
1751
            }
1752
        }
1753
406037
        add_metadata_from_side_data(pkt, frame);
1754
1755
406037
        if (pkt->flags & AV_PKT_FLAG_DISCARD) {
1756
196
            frame->flags |= AV_FRAME_FLAG_DISCARD;
1757
        } else {
1758
405841
            frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
1759
        }
1760
    }
1761
406037
    frame->reordered_opaque = avctx->reordered_opaque;
1762
1763
406037
    if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
1764
406037
        frame->color_primaries = avctx->color_primaries;
1765
406037
    if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
1766
406037
        frame->color_trc = avctx->color_trc;
1767
406037
    if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
1768
405602
        frame->colorspace = avctx->colorspace;
1769
406037
    if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
1770
405819
        frame->color_range = avctx->color_range;
1771
406037
    if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
1772
406037
        frame->chroma_location = avctx->chroma_sample_location;
1773
1774
406037
    switch (avctx->codec->type) {
1775
119164
    case AVMEDIA_TYPE_VIDEO:
1776
119164
        frame->format              = avctx->pix_fmt;
1777
119164
        if (!frame->sample_aspect_ratio.num)
1778
119045
            frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
1779
1780

216941
        if (frame->width && frame->height &&
1781
97777
            av_image_check_sar(frame->width, frame->height,
1782
                               frame->sample_aspect_ratio) < 0) {
1783
            av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1784
                   frame->sample_aspect_ratio.num,
1785
                   frame->sample_aspect_ratio.den);
1786
            frame->sample_aspect_ratio = (AVRational){ 0, 1 };
1787
        }
1788
1789
119164
        break;
1790
286873
    case AVMEDIA_TYPE_AUDIO:
1791
286873
        if (!frame->sample_rate)
1792
286873
            frame->sample_rate    = avctx->sample_rate;
1793
286873
        if (frame->format < 0)
1794
286873
            frame->format         = avctx->sample_fmt;
1795
286873
        if (!frame->channel_layout) {
1796
286873
            if (avctx->channel_layout) {
1797
285555
                 if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
1798
285555
                     avctx->channels) {
1799
                     av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
1800
                            "configuration.\n");
1801
                     return AVERROR(EINVAL);
1802
                 }
1803
1804
285555
                frame->channel_layout = avctx->channel_layout;
1805
            } else {
1806
1318
                if (avctx->channels > FF_SANE_NB_CHANNELS) {
1807
                    av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
1808
                           avctx->channels);
1809
                    return AVERROR(ENOSYS);
1810
                }
1811
            }
1812
        }
1813
286873
        frame->channels = avctx->channels;
1814
286873
        break;
1815
    }
1816
406037
    return 0;
1817
}
1818
1819
379240
static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
1820
{
1821
379240
    if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1822
        int i;
1823
92367
        int num_planes = av_pix_fmt_count_planes(frame->format);
1824
92367
        const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
1825
92367
        int flags = desc ? desc->flags : 0;
1826

92367
        if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
1827
2127
            num_planes = 2;
1828

92367
        if ((flags & FF_PSEUDOPAL) && frame->data[1])
1829
276
            num_planes = 2;
1830
357084
        for (i = 0; i < num_planes; i++) {
1831
264717
            av_assert0(frame->data[i]);
1832
        }
1833
        // For formats without data like hwaccel allow unused pointers to be non-NULL.
1834

566586
        for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
1835
474219
            if (frame->data[i])
1836
                av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
1837
474219
            frame->data[i] = NULL;
1838
        }
1839
    }
1840
379240
}
1841
1842
379240
static void decode_data_free(void *opaque, uint8_t *data)
1843
{
1844
379240
    FrameDecodeData *fdd = (FrameDecodeData*)data;
1845
1846
379240
    if (fdd->post_process_opaque_free)
1847
        fdd->post_process_opaque_free(fdd->post_process_opaque);
1848
1849
379240
    if (fdd->hwaccel_priv_free)
1850
        fdd->hwaccel_priv_free(fdd->hwaccel_priv);
1851
1852
379240
    av_freep(&fdd);
1853
379240
}
1854
1855
379240
int ff_attach_decode_data(AVFrame *frame)
1856
{
1857
    AVBufferRef *fdd_buf;
1858
    FrameDecodeData *fdd;
1859
1860
    av_assert1(!frame->private_ref);
1861
379240
    av_buffer_unref(&frame->private_ref);
1862
1863
379240
    fdd = av_mallocz(sizeof(*fdd));
1864
379240
    if (!fdd)
1865
        return AVERROR(ENOMEM);
1866
1867
379240
    fdd_buf = av_buffer_create((uint8_t*)fdd, sizeof(*fdd), decode_data_free,
1868
                               NULL, AV_BUFFER_FLAG_READONLY);
1869
379240
    if (!fdd_buf) {
1870
        av_freep(&fdd);
1871
        return AVERROR(ENOMEM);
1872
    }
1873
1874
379240
    frame->private_ref = fdd_buf;
1875
1876
379240
    return 0;
1877
}
1878
1879
379333
int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1880
{
1881
379333
    const AVHWAccel *hwaccel = avctx->hwaccel;
1882
379333
    int override_dimensions = 1;
1883
    int ret;
1884
1885
379333
    if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1886

184920
        if ((unsigned)avctx->width > INT_MAX - STRIDE_ALIGN ||
1887
184920
            (ret = av_image_check_size2(FFALIGN(avctx->width, STRIDE_ALIGN), avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) < 0 || avctx->pix_fmt<0) {
1888
93
            av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
1889
93
            ret = AVERROR(EINVAL);
1890
93
            goto fail;
1891
        }
1892
1893

92367
        if (frame->width <= 0 || frame->height <= 0) {
1894
82759
            frame->width  = FFMAX(avctx->width,  AV_CEIL_RSHIFT(avctx->coded_width,  avctx->lowres));
1895
82759
            frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
1896
82759
            override_dimensions = 0;
1897
        }
1898
1899


92367
        if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
1900
            av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
1901
            ret = AVERROR(EINVAL);
1902
            goto fail;
1903
        }
1904
286873
    } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
1905
286873
        if (frame->nb_samples * (int64_t)avctx->channels > avctx->max_samples) {
1906
            av_log(avctx, AV_LOG_ERROR, "samples per frame %d, exceeds max_samples %"PRId64"\n", frame->nb_samples, avctx->max_samples);
1907
            ret = AVERROR(EINVAL);
1908
            goto fail;
1909
        }
1910
    }
1911
379240
    ret = ff_decode_frame_props(avctx, frame);
1912
379240
    if (ret < 0)
1913
        goto fail;
1914
1915
379240
    if (hwaccel) {
1916
        if (hwaccel->alloc_frame) {
1917
            ret = hwaccel->alloc_frame(avctx, frame);
1918
            goto end;
1919
        }
1920
    } else
1921
379240
        avctx->sw_pix_fmt = avctx->pix_fmt;
1922
1923
379240
    ret = avctx->get_buffer2(avctx, frame, flags);
1924
379240
    if (ret < 0)
1925
        goto fail;
1926
1927
379240
    validate_avframe_allocation(avctx, frame);
1928
1929
379240
    ret = ff_attach_decode_data(frame);
1930
379240
    if (ret < 0)
1931
        goto fail;
1932
1933
379240
end:
1934

379240
    if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
1935
82759
        !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
1936
49855
        frame->width  = avctx->width;
1937
49855
        frame->height = avctx->height;
1938
    }
1939
1940
329385
fail:
1941
379333
    if (ret < 0) {
1942
93
        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1943
93
        av_frame_unref(frame);
1944
    }
1945
1946
379333
    return ret;
1947
}
1948
1949
6957
static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
1950
{
1951
    AVFrame *tmp;
1952
    int ret;
1953
1954
6957
    av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
1955
1956


6957
    if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
1957
        av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
1958
               frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
1959
        av_frame_unref(frame);
1960
    }
1961
1962
6957
    if (!frame->data[0])
1963
120
        return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1964
1965

6837
    if ((flags & FF_REGET_BUFFER_FLAG_READONLY) || av_frame_is_writable(frame))
1966
5301
        return ff_decode_frame_props(avctx, frame);
1967
1968
1536
    tmp = av_frame_alloc();
1969
1536
    if (!tmp)
1970
        return AVERROR(ENOMEM);
1971
1972
1536
    av_frame_move_ref(tmp, frame);
1973
1974
1536
    ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1975
1536
    if (ret < 0) {
1976
        av_frame_free(&tmp);
1977
        return ret;
1978
    }
1979
1980
1536
    av_frame_copy(frame, tmp);
1981
1536
    av_frame_free(&tmp);
1982
1983
1536
    return 0;
1984
}
1985
1986
6957
int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1987
{
1988
6957
    int ret = reget_buffer_internal(avctx, frame, flags);
1989
6957
    if (ret < 0)
1990
        av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
1991
6957
    return ret;
1992
}