Coverage Report

Created: 2026-10-28 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ffmpeg/libavcodec/decode.c
Line
Count
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 <assert.h>
22
#include <stdint.h>
23
#include <stdbool.h>
24
#include <string.h>
25
26
#include "config.h"
27
28
#if CONFIG_ICONV
29
# include <iconv.h>
30
#endif
31
32
#include "libavutil/avassert.h"
33
#include "libavutil/channel_layout.h"
34
#include "libavutil/common.h"
35
#include "libavutil/emms.h"
36
#include "libavutil/frame.h"
37
#include "libavutil/hwcontext.h"
38
#include "libavutil/imgutils.h"
39
#include "libavutil/internal.h"
40
#include "libavutil/mastering_display_metadata.h"
41
#include "libavutil/mem.h"
42
#include "libavutil/stereo3d.h"
43
44
#include "avcodec.h"
45
#include "avcodec_internal.h"
46
#include "bytestream.h"
47
#include "bsf.h"
48
#include "codec_desc.h"
49
#include "codec_internal.h"
50
#include "decode.h"
51
#include "exif.h"
52
#include "exif_internal.h"
53
#include "hwaccel_internal.h"
54
#include "hwconfig.h"
55
#include "internal.h"
56
#include "lcevcdec.h"
57
#include "packet_internal.h"
58
#include "progressframe.h"
59
#include "libavutil/refstruct.h"
60
#include "thread.h"
61
#include "threadprogress.h"
62
63
typedef struct DecodeContext {
64
    AVCodecInternal avci;
65
66
    /**
67
     * This is set to AV_FRAME_FLAG_KEY for decoders of intra-only formats
68
     * (those whose codec descriptor has AV_CODEC_PROP_INTRA_ONLY set)
69
     * to set the flag generically.
70
     */
71
    int intra_only_flag;
72
73
    /**
74
     * This is set to AV_PICTURE_TYPE_I for intra only video decoders
75
     * and to AV_PICTURE_TYPE_NONE for other decoders. It is used to set
76
     * the AVFrame's pict_type before the decoder receives it.
77
     */
78
    enum AVPictureType initial_pict_type;
79
80
    /* to prevent infinite loop on errors when draining */
81
    int nb_draining_errors;
82
83
    /**
84
     * The caller has submitted a NULL packet on input.
85
     */
86
    int draining_started;
87
88
    int64_t pts_correction_num_faulty_pts; /// Number of incorrect PTS values so far
89
    int64_t pts_correction_num_faulty_dts; /// Number of incorrect DTS values so far
90
    int64_t pts_correction_last_pts;       /// PTS of the last frame
91
    int64_t pts_correction_last_dts;       /// DTS of the last frame
92
93
    /**
94
     * Bitmask indicating for which side data types we prefer user-supplied
95
     * (global or attached to packets) side data over bytestream.
96
     */
97
    uint64_t side_data_pref_mask;
98
99
#if CONFIG_LIBLCEVC_DEC
100
    struct {
101
        FFLCEVCContext *ctx;
102
        int frame;
103
        enum AVPixelFormat format;
104
        int base_width;
105
        int base_height;
106
        int width;
107
        int height;
108
    } lcevc;
109
#endif
110
} DecodeContext;
111
112
static DecodeContext *decode_ctx(AVCodecInternal *avci)
113
0
{
114
0
    return (DecodeContext *)avci;
115
0
}
116
117
static int apply_param_change(AVCodecContext *avctx, const AVPacket *avpkt)
118
0
{
119
0
    int ret;
120
0
    size_t size;
121
0
    const uint8_t *data;
122
0
    uint32_t flags;
123
0
    int64_t val;
124
125
0
    data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
126
0
    if (!data)
127
0
        return 0;
128
129
0
    if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) {
130
0
        av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
131
0
               "changes, but PARAM_CHANGE side data was sent to it.\n");
132
0
        ret = AVERROR(EINVAL);
133
0
        goto fail2;
134
0
    }
135
136
0
    if (size < 4)
137
0
        goto fail;
138
139
0
    flags = bytestream_get_le32(&data);
140
0
    size -= 4;
141
142
0
    if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
143
0
        if (size < 4)
144
0
            goto fail;
145
0
        val = bytestream_get_le32(&data);
146
0
        if (val <= 0 || val > INT_MAX) {
147
0
            av_log(avctx, AV_LOG_ERROR, "Invalid sample rate");
148
0
            ret = AVERROR_INVALIDDATA;
149
0
            goto fail2;
150
0
        }
151
0
        avctx->sample_rate = val;
152
0
        size -= 4;
153
0
    }
154
0
    if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
155
0
        if (size < 8)
156
0
            goto fail;
157
0
        avctx->width  = bytestream_get_le32(&data);
158
0
        avctx->height = bytestream_get_le32(&data);
159
0
        size -= 8;
160
0
        ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
161
0
        if (ret < 0)
162
0
            goto fail2;
163
0
    }
164
165
0
    return 0;
166
0
fail:
167
0
    av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
168
0
    ret = AVERROR_INVALIDDATA;
169
0
fail2:
170
0
    if (ret < 0) {
171
0
        av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
172
0
        if (avctx->err_recognition & AV_EF_EXPLODE)
173
0
            return ret;
174
0
    }
175
0
    return 0;
176
0
}
177
178
static int extract_packet_props(AVCodecInternal *avci, const AVPacket *pkt)
179
0
{
180
0
    int ret = 0;
181
182
0
    av_packet_unref(avci->last_pkt_props);
183
0
    if (pkt) {
184
0
        ret = av_packet_copy_props(avci->last_pkt_props, pkt);
185
0
    }
186
0
    return ret;
187
0
}
188
189
static int decode_bsfs_init(AVCodecContext *avctx)
190
0
{
191
0
    AVCodecInternal *avci = avctx->internal;
192
0
    const FFCodec *const codec = ffcodec(avctx->codec);
193
0
    int ret;
194
195
0
    if (avci->bsf)
196
0
        return 0;
197
198
0
    ret = av_bsf_list_parse_str(codec->bsfs, &avci->bsf);
199
0
    if (ret < 0) {
200
0
        av_log(avctx, AV_LOG_ERROR, "Error parsing decoder bitstream filters '%s': %s\n", codec->bsfs, av_err2str(ret));
201
0
        if (ret != AVERROR(ENOMEM))
202
0
            ret = AVERROR_BUG;
203
0
        goto fail;
204
0
    }
205
206
    /* We do not currently have an API for passing the input timebase into decoders,
207
     * but no filters used here should actually need it.
208
     * So we make up some plausible-looking number (the MPEG 90kHz timebase) */
209
0
    avci->bsf->time_base_in = (AVRational){ 1, 90000 };
210
0
    ret = avcodec_parameters_from_context(avci->bsf->par_in, avctx);
211
0
    if (ret < 0)
212
0
        goto fail;
213
214
0
    ret = av_bsf_init(avci->bsf);
215
0
    if (ret < 0)
216
0
        goto fail;
217
218
0
    return 0;
219
0
fail:
220
0
    av_bsf_free(&avci->bsf);
221
0
    return ret;
222
0
}
223
224
#if !HAVE_THREADS
225
#define ff_thread_get_packet(avctx, pkt) (AVERROR_BUG)
226
#define ff_thread_receive_frame(avctx, frame, flags) (AVERROR_BUG)
227
#endif
228
229
static int decode_get_packet(AVCodecContext *avctx, AVPacket *pkt)
230
0
{
231
0
    AVCodecInternal *avci = avctx->internal;
232
0
    int ret;
233
234
0
    ret = av_bsf_receive_packet(avci->bsf, pkt);
235
0
    if (ret < 0)
236
0
        return ret;
237
238
0
    if (!(ffcodec(avctx->codec)->caps_internal & FF_CODEC_CAP_SETS_FRAME_PROPS)) {
239
0
        ret = extract_packet_props(avctx->internal, pkt);
240
0
        if (ret < 0)
241
0
            goto finish;
242
0
    }
243
244
0
    ret = apply_param_change(avctx, pkt);
245
0
    if (ret < 0)
246
0
        goto finish;
247
248
0
    return 0;
249
0
finish:
250
0
    av_packet_unref(pkt);
251
0
    return ret;
252
0
}
253
254
int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt)
255
0
{
256
0
    AVCodecInternal *avci = avctx->internal;
257
0
    DecodeContext     *dc = decode_ctx(avci);
258
259
0
    if (avci->draining)
260
0
        return AVERROR_EOF;
261
262
    /* If we are a worker thread, get the next packet from the threading
263
     * context. Otherwise we are the main (user-facing) context, so we get the
264
     * next packet from the input filterchain.
265
     */
266
0
    if (avctx->internal->is_frame_mt)
267
0
        return ff_thread_get_packet(avctx, pkt);
268
269
0
    while (1) {
270
0
        int ret = decode_get_packet(avctx, pkt);
271
0
        if (ret == AVERROR(EAGAIN) &&
272
0
            (!AVPACKET_IS_EMPTY(avci->buffer_pkt) || dc->draining_started)) {
273
0
            ret = av_bsf_send_packet(avci->bsf, avci->buffer_pkt);
274
0
            if (ret >= 0)
275
0
                continue;
276
277
0
            av_packet_unref(avci->buffer_pkt);
278
0
        }
279
280
0
        if (ret == AVERROR_EOF)
281
0
            avci->draining = 1;
282
0
        return ret;
283
0
    }
284
0
}
285
286
/**
287
 * Attempt to guess proper monotonic timestamps for decoded video frames
288
 * which might have incorrect times. Input timestamps may wrap around, in
289
 * which case the output will as well.
290
 *
291
 * @param pts the pts field of the decoded AVPacket, as passed through
292
 * AVFrame.pts
293
 * @param dts the dts field of the decoded AVPacket
294
 * @return one of the input values, may be AV_NOPTS_VALUE
295
 */
296
static int64_t guess_correct_pts(DecodeContext *dc,
297
                                 int64_t reordered_pts, int64_t dts)
298
0
{
299
0
    int64_t pts = AV_NOPTS_VALUE;
300
301
0
    if (dts != AV_NOPTS_VALUE) {
302
0
        dc->pts_correction_num_faulty_dts += dts <= dc->pts_correction_last_dts;
303
0
        dc->pts_correction_last_dts = dts;
304
0
    } else if (reordered_pts != AV_NOPTS_VALUE)
305
0
        dc->pts_correction_last_dts = reordered_pts;
306
307
0
    if (reordered_pts != AV_NOPTS_VALUE) {
308
0
        dc->pts_correction_num_faulty_pts += reordered_pts <= dc->pts_correction_last_pts;
309
0
        dc->pts_correction_last_pts = reordered_pts;
310
0
    } else if(dts != AV_NOPTS_VALUE)
311
0
        dc->pts_correction_last_pts = dts;
312
313
0
    if ((dc->pts_correction_num_faulty_pts<=dc->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
314
0
       && reordered_pts != AV_NOPTS_VALUE)
315
0
        pts = reordered_pts;
316
0
    else
317
0
        pts = dts;
318
319
0
    return pts;
320
0
}
321
322
static int discard_samples(AVCodecContext *avctx, AVFrame *frame, int64_t *discarded_samples)
323
0
{
324
0
    AVCodecInternal *avci = avctx->internal;
325
0
    AVFrameSideData *side;
326
0
    uint32_t discard_padding = 0;
327
0
    int nb_samples = frame->nb_samples;
328
0
    uint8_t skip_reason = 0;
329
0
    uint8_t discard_reason = 0;
330
331
0
    side = av_frame_get_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES);
332
0
    if (side && side->size >= 10) {
333
0
        int skip_samples = AV_RL32(side->data);
334
0
        if (skip_samples)
335
0
            avci->skip_samples = skip_samples;
336
0
        avci->skip_samples = FFMAX(0, avci->skip_samples);
337
0
        discard_padding = AV_RL32(side->data + 4);
338
0
        av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
339
0
               avci->skip_samples, (int)discard_padding);
340
0
        skip_reason = AV_RL8(side->data + 8);
341
0
        discard_reason = AV_RL8(side->data + 9);
342
0
    }
343
344
0
    if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
345
0
        if (!side && (avci->skip_samples || discard_padding))
346
0
            side = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
347
0
        if (side && (avci->skip_samples || discard_padding)) {
348
0
            AV_WL32(side->data, avci->skip_samples);
349
0
            AV_WL32(side->data + 4, discard_padding);
350
0
            AV_WL8(side->data + 8, skip_reason);
351
0
            AV_WL8(side->data + 9, discard_reason);
352
0
            avci->skip_samples = 0;
353
0
        }
354
0
        return 0;
355
0
    }
356
0
    av_frame_remove_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES);
357
358
0
    if ((frame->flags & AV_FRAME_FLAG_DISCARD)) {
359
0
        avci->skip_samples = FFMAX(0, avci->skip_samples - frame->nb_samples);
360
0
        av_log(avctx, AV_LOG_DEBUG, "discard whole frame due to discard frame flag, skip left: %d\n",
361
0
               avci->skip_samples);
362
0
        *discarded_samples += frame->nb_samples;
363
0
        return AVERROR(EAGAIN);
364
0
    }
365
366
0
    if (avci->skip_samples > 0) {
367
0
        if (frame->nb_samples <= avci->skip_samples){
368
0
            *discarded_samples += frame->nb_samples;
369
0
            avci->skip_samples -= frame->nb_samples;
370
0
            av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
371
0
                   avci->skip_samples);
372
0
            return AVERROR(EAGAIN);
373
0
        } else {
374
0
            av_samples_copy(frame->extended_data, frame->extended_data, 0, avci->skip_samples,
375
0
                            frame->nb_samples - avci->skip_samples, avctx->ch_layout.nb_channels, frame->format);
376
0
            if (avctx->pkt_timebase.num && avctx->sample_rate) {
377
0
                int64_t diff_ts = av_rescale_q(avci->skip_samples,
378
0
                                               (AVRational){1, avctx->sample_rate},
379
0
                                               avctx->pkt_timebase);
380
0
                if (diff_ts != AV_NOPTS_VALUE) {
381
0
                    if (frame->pts != AV_NOPTS_VALUE)
382
0
                        frame->pts = av_sat_add64(frame->pts, diff_ts);
383
0
                    if (frame->pkt_dts != AV_NOPTS_VALUE)
384
0
                        frame->pkt_dts = av_sat_add64(frame->pkt_dts, diff_ts);
385
0
                    if (frame->duration >= diff_ts)
386
0
                        frame->duration = av_sat_sub64(frame->duration, diff_ts);
387
0
                } else {
388
0
                    frame->pts = AV_NOPTS_VALUE;
389
0
                    frame->pkt_dts = AV_NOPTS_VALUE;
390
0
                    frame->duration = 0;
391
0
                }
392
0
            } else
393
0
                av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
394
395
0
            av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
396
0
                   avci->skip_samples, frame->nb_samples);
397
0
            *discarded_samples += avci->skip_samples;
398
0
            frame->nb_samples -= avci->skip_samples;
399
0
            avci->skip_samples = 0;
400
0
        }
401
0
    }
402
403
0
    if (discard_padding > 0 && discard_padding <= nb_samples) {
404
        // The padding may overlap the samples skipped at the start.
405
0
        discard_padding = FFMIN(discard_padding, frame->nb_samples);
406
0
        if (discard_padding == frame->nb_samples) {
407
0
            av_log(avctx, AV_LOG_DEBUG, "discard whole frame\n");
408
0
            *discarded_samples += frame->nb_samples;
409
0
            return AVERROR(EAGAIN);
410
0
        } else {
411
0
            if (avctx->pkt_timebase.num && avctx->sample_rate) {
412
0
                int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
413
0
                                               (AVRational){1, avctx->sample_rate},
414
0
                                               avctx->pkt_timebase);
415
0
                frame->duration = diff_ts == AV_NOPTS_VALUE ? 0 : diff_ts;
416
0
            } else
417
0
                av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
418
419
0
            av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
420
0
                   (int)discard_padding, frame->nb_samples);
421
0
            frame->nb_samples -= discard_padding;
422
0
        }
423
0
    }
424
425
0
    return 0;
426
0
}
427
428
/*
429
 * The core of the receive_frame_wrapper for the decoders implementing
430
 * the simple API. Certain decoders might consume partial packets without
431
 * returning any output, so this function needs to be called in a loop until it
432
 * returns EAGAIN.
433
 **/
434
static inline int decode_simple_internal(AVCodecContext *avctx, AVFrame *frame, int64_t *discarded_samples)
435
0
{
436
0
    AVCodecInternal   *avci = avctx->internal;
437
0
    DecodeContext     *dc = decode_ctx(avci);
438
0
    AVPacket     *const pkt = avci->in_pkt;
439
0
    const FFCodec *const codec = ffcodec(avctx->codec);
440
0
    int got_frame, consumed;
441
0
    int ret;
442
443
0
    if (!pkt->data && !avci->draining) {
444
0
        av_packet_unref(pkt);
445
0
        ret = ff_decode_get_packet(avctx, pkt);
446
0
        if (ret < 0 && ret != AVERROR_EOF)
447
0
            return ret;
448
0
    }
449
450
    // Some codecs (at least wma lossless) will crash when feeding drain packets
451
    // after EOF was signaled.
452
0
    if (avci->draining_done)
453
0
        return AVERROR_EOF;
454
455
0
    if (!pkt->data &&
456
0
        !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY))
457
0
        return AVERROR_EOF;
458
459
0
    got_frame = 0;
460
461
0
    frame->pict_type = dc->initial_pict_type;
462
0
    frame->flags    |= dc->intra_only_flag;
463
0
    consumed = codec->cb.decode(avctx, frame, &got_frame, pkt);
464
465
0
    if (!(codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
466
0
        frame->pkt_dts = pkt->dts;
467
0
    emms_c();
468
469
0
    if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
470
0
        ret = (!got_frame || frame->flags & AV_FRAME_FLAG_DISCARD)
471
0
                          ? AVERROR(EAGAIN)
472
0
                          : 0;
473
0
    } else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
474
0
        ret =  !got_frame ? AVERROR(EAGAIN)
475
0
                          : discard_samples(avctx, frame, discarded_samples);
476
0
    } else
477
0
        av_assert0(0);
478
479
0
    if (ret == AVERROR(EAGAIN))
480
0
        av_frame_unref(frame);
481
482
    // FF_CODEC_CB_TYPE_DECODE decoders must not return AVERROR EAGAIN
483
    // or AVERROR_EOF.
484
    // code later will add AVERROR(EAGAIN) to a pointer
485
0
    av_assert0(consumed != AVERROR(EAGAIN) && consumed != AVERROR_EOF);
486
0
    if (consumed < 0)
487
0
        ret = consumed;
488
0
    if (consumed >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO)
489
0
        consumed = pkt->size;
490
491
0
    if (!ret)
492
0
        av_assert0(frame->buf[0]);
493
0
    if (ret == AVERROR(EAGAIN))
494
0
        ret = 0;
495
496
    /* do not stop draining when got_frame != 0 or ret < 0 */
497
0
    if (avci->draining && !got_frame) {
498
0
        if (ret < 0) {
499
            /* prevent infinite loop if a decoder wrongly always return error on draining */
500
            /* reasonable nb_errors_max = maximum b frames + thread count */
501
0
            int nb_errors_max = 20 + (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME ?
502
0
                                avctx->thread_count : 1);
503
504
0
            if (decode_ctx(avci)->nb_draining_errors++ >= nb_errors_max) {
505
0
                av_log(avctx, AV_LOG_ERROR, "Too many errors when draining, this is a bug. "
506
0
                       "Stop draining and force EOF.\n");
507
0
                avci->draining_done = 1;
508
0
                ret = AVERROR_BUG;
509
0
            }
510
0
        } else {
511
0
            avci->draining_done = 1;
512
0
        }
513
0
    }
514
515
0
    if (consumed >= pkt->size || ret < 0) {
516
0
        av_packet_unref(pkt);
517
0
    } else {
518
0
        pkt->data                += consumed;
519
0
        pkt->size                -= consumed;
520
0
        pkt->pts                  = AV_NOPTS_VALUE;
521
0
        pkt->dts                  = AV_NOPTS_VALUE;
522
0
        if (!(codec->caps_internal & FF_CODEC_CAP_SETS_FRAME_PROPS)) {
523
0
            avci->last_pkt_props->pts = AV_NOPTS_VALUE;
524
0
            avci->last_pkt_props->dts = AV_NOPTS_VALUE;
525
0
        }
526
0
    }
527
528
0
    return ret;
529
0
}
530
531
#if CONFIG_LCMS2
532
static int detect_colorspace(AVCodecContext *avctx, AVFrame *frame)
533
{
534
    AVCodecInternal *avci = avctx->internal;
535
    enum AVColorTransferCharacteristic trc;
536
    AVColorPrimariesDesc coeffs;
537
    enum AVColorPrimaries prim;
538
    cmsHPROFILE profile;
539
    AVFrameSideData *sd;
540
    int ret;
541
    if (!(avctx->flags2 & AV_CODEC_FLAG2_ICC_PROFILES))
542
        return 0;
543
544
    sd = av_frame_get_side_data(frame, AV_FRAME_DATA_ICC_PROFILE);
545
    if (!sd || !sd->size)
546
        return 0;
547
548
    if (!avci->icc.avctx) {
549
        ret = ff_icc_context_init(&avci->icc, avctx);
550
        if (ret < 0)
551
            return ret;
552
    }
553
554
    profile = cmsOpenProfileFromMemTHR(avci->icc.ctx, sd->data, sd->size);
555
    if (!profile)
556
        return AVERROR_INVALIDDATA;
557
558
    ret = ff_icc_profile_sanitize(&avci->icc, profile);
559
    if (!ret)
560
        ret = ff_icc_profile_read_primaries(&avci->icc, profile, &coeffs);
561
    if (!ret)
562
        ret = ff_icc_profile_detect_transfer(&avci->icc, profile, &trc);
563
    cmsCloseProfile(profile);
564
    if (ret < 0)
565
        return ret;
566
567
    prim = av_csp_primaries_id_from_desc(&coeffs);
568
    if (prim != AVCOL_PRI_UNSPECIFIED)
569
        frame->color_primaries = prim;
570
    if (trc != AVCOL_TRC_UNSPECIFIED)
571
        frame->color_trc = trc;
572
    return 0;
573
}
574
#else /* !CONFIG_LCMS2 */
575
static int detect_colorspace(av_unused AVCodecContext *c, av_unused AVFrame *f)
576
0
{
577
0
    return 0;
578
0
}
579
#endif
580
581
static int fill_frame_props(const AVCodecContext *avctx, AVFrame *frame)
582
0
{
583
0
    int ret;
584
585
0
    if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
586
0
        frame->color_primaries = avctx->color_primaries;
587
0
    if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
588
0
        frame->color_trc = avctx->color_trc;
589
0
    if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
590
0
        frame->colorspace = avctx->colorspace;
591
0
    if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
592
0
        frame->color_range = avctx->color_range;
593
0
    if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
594
0
        frame->chroma_location = avctx->chroma_sample_location;
595
0
    if (frame->alpha_mode == AVALPHA_MODE_UNSPECIFIED)
596
0
        frame->alpha_mode = avctx->alpha_mode;
597
598
0
    if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
599
0
            if (!frame->sample_aspect_ratio.num)  frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
600
0
            if (frame->format == AV_PIX_FMT_NONE) frame->format              = avctx->pix_fmt;
601
0
    } else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
602
0
        if (frame->format == AV_SAMPLE_FMT_NONE)
603
0
            frame->format = avctx->sample_fmt;
604
0
        if (!frame->ch_layout.nb_channels) {
605
0
            ret = av_channel_layout_copy(&frame->ch_layout, &avctx->ch_layout);
606
0
            if (ret < 0)
607
0
                return ret;
608
0
        }
609
0
        if (!frame->sample_rate)
610
0
            frame->sample_rate = avctx->sample_rate;
611
0
    }
612
613
0
    return 0;
614
0
}
615
616
static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
617
0
{
618
0
    int ret;
619
0
    int64_t discarded_samples = 0;
620
621
0
    while (!frame->buf[0]) {
622
0
        if (discarded_samples > avctx->max_samples)
623
0
            return AVERROR(EAGAIN);
624
0
        ret = decode_simple_internal(avctx, frame, &discarded_samples);
625
0
        if (ret < 0)
626
0
            return ret;
627
0
    }
628
629
0
    return 0;
630
0
}
631
632
int ff_decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
633
0
{
634
0
    AVCodecInternal *avci = avctx->internal;
635
0
    DecodeContext     *dc = decode_ctx(avci);
636
0
    const FFCodec *const codec = ffcodec(avctx->codec);
637
0
    int ret;
638
639
0
    av_assert0(!frame->buf[0]);
640
641
0
    if (codec->cb_type == FF_CODEC_CB_TYPE_RECEIVE_FRAME) {
642
0
        while (1) {
643
0
            frame->pict_type = dc->initial_pict_type;
644
0
            frame->flags    |= dc->intra_only_flag;
645
0
            ret = codec->cb.receive_frame(avctx, frame);
646
0
            emms_c();
647
0
            if (!ret) {
648
0
                if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
649
0
                    int64_t discarded_samples = 0;
650
0
                    ret = discard_samples(avctx, frame, &discarded_samples);
651
0
                }
652
0
                if (ret == AVERROR(EAGAIN) || (frame->flags & AV_FRAME_FLAG_DISCARD)) {
653
0
                    av_frame_unref(frame);
654
0
                    continue;
655
0
                }
656
0
            }
657
0
            break;
658
0
        }
659
0
    } else
660
0
        ret = decode_simple_receive_frame(avctx, frame);
661
662
0
    if (ret == AVERROR_EOF)
663
0
        avci->draining_done = 1;
664
665
0
    return ret;
666
0
}
667
668
static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame,
669
                                         unsigned flags)
670
0
{
671
0
    AVCodecInternal *avci = avctx->internal;
672
0
    DecodeContext     *dc = decode_ctx(avci);
673
0
    int ret, ok;
674
675
0
    if (avctx->active_thread_type & FF_THREAD_FRAME)
676
0
        ret = ff_thread_receive_frame(avctx, frame, flags);
677
0
    else
678
0
        ret = ff_decode_receive_frame_internal(avctx, frame);
679
680
    /* preserve ret */
681
0
    ok = detect_colorspace(avctx, frame);
682
0
    if (ok < 0) {
683
0
        av_frame_unref(frame);
684
0
        return ok;
685
0
    }
686
687
0
    if (!ret) {
688
0
        if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
689
0
            if (!frame->width)
690
0
                frame->width = avctx->width;
691
0
            if (!frame->height)
692
0
                frame->height = avctx->height;
693
0
        }
694
695
0
        ret = fill_frame_props(avctx, frame);
696
0
        if (ret < 0) {
697
0
            av_frame_unref(frame);
698
0
            return ret;
699
0
        }
700
701
0
        frame->best_effort_timestamp = guess_correct_pts(dc,
702
0
                                                         frame->pts,
703
0
                                                         frame->pkt_dts);
704
705
        /* the only case where decode data is not set should be decoders
706
         * that do not call ff_get_buffer() */
707
0
        av_assert0(frame->private_ref ||
708
0
                   !(avctx->codec->capabilities & AV_CODEC_CAP_DR1));
709
710
0
        if (frame->private_ref) {
711
0
            FrameDecodeData *fdd = frame->private_ref;
712
713
0
            if (fdd->hwaccel_priv_post_process) {
714
0
                ret = fdd->hwaccel_priv_post_process(avctx, frame);
715
0
                if (ret < 0) {
716
0
                    av_frame_unref(frame);
717
0
                    return ret;
718
0
                }
719
0
            }
720
721
0
            if (fdd->post_process) {
722
0
                ret = fdd->post_process(avctx, frame);
723
0
                if (ret < 0) {
724
0
                    av_frame_unref(frame);
725
0
                    return ret;
726
0
                }
727
0
            }
728
0
        }
729
0
    }
730
731
    /* free the per-frame decode data */
732
0
    av_refstruct_unref(&frame->private_ref);
733
734
0
    return ret;
735
0
}
736
737
int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
738
0
{
739
0
    AVCodecInternal *avci = avctx->internal;
740
0
    DecodeContext     *dc = decode_ctx(avci);
741
0
    int ret;
742
743
0
    if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
744
0
        return AVERROR(EINVAL);
745
746
0
    if (dc->draining_started)
747
0
        return AVERROR_EOF;
748
749
0
    if (avpkt && !avpkt->size && avpkt->data)
750
0
        return AVERROR(EINVAL);
751
752
0
    if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
753
0
        if (!AVPACKET_IS_EMPTY(avci->buffer_pkt))
754
0
            return AVERROR(EAGAIN);
755
0
        ret = av_packet_ref(avci->buffer_pkt, avpkt);
756
0
        if (ret < 0)
757
0
            return ret;
758
0
    } else
759
0
        dc->draining_started = 1;
760
761
0
    if (!avci->buffer_frame->buf[0] && !dc->draining_started) {
762
0
        ret = decode_receive_frame_internal(avctx, avci->buffer_frame, 0);
763
0
        if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
764
0
            return ret;
765
0
    }
766
767
0
    return 0;
768
0
}
769
770
static int apply_cropping(AVCodecContext *avctx, AVFrame *frame)
771
0
{
772
    /* make sure we are noisy about decoders returning invalid cropping data */
773
0
    if (frame->crop_left >= INT_MAX - frame->crop_right        ||
774
0
        frame->crop_top  >= INT_MAX - frame->crop_bottom       ||
775
0
        (frame->crop_left + frame->crop_right) >= frame->width ||
776
0
        (frame->crop_top + frame->crop_bottom) >= frame->height) {
777
0
        av_log(avctx, AV_LOG_WARNING,
778
0
               "Invalid cropping information set by a decoder: "
779
0
               "%zu/%zu/%zu/%zu (frame size %dx%d). "
780
0
               "This is a bug, please report it\n",
781
0
               frame->crop_left, frame->crop_right, frame->crop_top, frame->crop_bottom,
782
0
               frame->width, frame->height);
783
0
        frame->crop_left   = 0;
784
0
        frame->crop_right  = 0;
785
0
        frame->crop_top    = 0;
786
0
        frame->crop_bottom = 0;
787
0
        return 0;
788
0
    }
789
790
0
    if (!avctx->apply_cropping)
791
0
        return 0;
792
793
0
    return av_frame_apply_cropping(frame, avctx->flags & AV_CODEC_FLAG_UNALIGNED ?
794
0
                                          AV_FRAME_CROP_UNALIGNED : 0);
795
0
}
796
797
// make sure frames returned to the caller are valid
798
static int frame_validate(AVCodecContext *avctx, AVFrame *frame)
799
0
{
800
0
    if (!frame->buf[0] || frame->format < 0)
801
0
        goto fail;
802
803
0
    switch (avctx->codec_type) {
804
0
    case AVMEDIA_TYPE_VIDEO:
805
0
        if (frame->width <= 0 || frame->height <= 0)
806
0
            goto fail;
807
0
        break;
808
0
    case AVMEDIA_TYPE_AUDIO:
809
0
        if (!av_channel_layout_check(&frame->ch_layout) ||
810
0
            frame->sample_rate <= 0)
811
0
            goto fail;
812
813
0
        break;
814
0
    default: av_assert0(0);
815
0
    }
816
817
0
    return 0;
818
0
fail:
819
0
    av_log(avctx, AV_LOG_ERROR, "An invalid frame was output by a decoder. "
820
0
           "This is a bug, please report it.\n");
821
0
    return AVERROR_BUG;
822
0
}
823
824
int ff_decode_receive_frame(AVCodecContext *avctx, AVFrame *frame, unsigned flags)
825
0
{
826
0
    AVCodecInternal *avci = avctx->internal;
827
0
    int ret;
828
829
0
    if (avci->buffer_frame->buf[0]) {
830
0
        av_frame_move_ref(frame, avci->buffer_frame);
831
0
    } else {
832
0
        ret = decode_receive_frame_internal(avctx, frame, flags);
833
0
        if (ret < 0)
834
0
            return ret;
835
0
    }
836
837
0
    ret = frame_validate(avctx, frame);
838
0
    if (ret < 0)
839
0
        goto fail;
840
841
0
    if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
842
0
        ret = apply_cropping(avctx, frame);
843
0
        if (ret < 0)
844
0
            goto fail;
845
0
    }
846
847
0
    avctx->frame_num++;
848
849
0
    return 0;
850
0
fail:
851
0
    av_frame_unref(frame);
852
0
    return ret;
853
0
}
854
855
static void get_subtitle_defaults(AVSubtitle *sub)
856
0
{
857
0
    memset(sub, 0, sizeof(*sub));
858
0
    sub->pts = AV_NOPTS_VALUE;
859
0
}
860
861
0
#define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
862
static int recode_subtitle(AVCodecContext *avctx, const AVPacket **outpkt,
863
                           const AVPacket *inpkt, AVPacket *buf_pkt)
864
0
{
865
0
#if CONFIG_ICONV
866
0
    iconv_t cd = (iconv_t)-1;
867
0
    int ret = 0;
868
0
    char *inb, *outb;
869
0
    size_t inl, outl;
870
0
#endif
871
872
0
    if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0) {
873
0
        *outpkt = inpkt;
874
0
        return 0;
875
0
    }
876
877
0
#if CONFIG_ICONV
878
0
    inb = inpkt->data;
879
0
    inl = inpkt->size;
880
881
0
    if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
882
0
        av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
883
0
        return AVERROR(ERANGE);
884
0
    }
885
886
0
    cd = iconv_open("UTF-8", avctx->sub_charenc);
887
0
    av_assert0(cd != (iconv_t)-1);
888
889
0
    ret = av_new_packet(buf_pkt, inl * UTF8_MAX_BYTES);
890
0
    if (ret < 0)
891
0
        goto end;
892
0
    ret = av_packet_copy_props(buf_pkt, inpkt);
893
0
    if (ret < 0)
894
0
        goto end;
895
0
    outb = buf_pkt->data;
896
0
    outl = buf_pkt->size;
897
898
0
    if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
899
0
        iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
900
0
        outl >= buf_pkt->size || inl != 0) {
901
0
        ret = FFMIN(AVERROR(errno), -1);
902
0
        av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%.*s\" "
903
0
               "from %s to UTF-8\n", inpkt->size, inpkt->data, avctx->sub_charenc);
904
0
        goto end;
905
0
    }
906
0
    buf_pkt->size -= outl;
907
0
    memset(buf_pkt->data + buf_pkt->size, 0, outl);
908
0
    *outpkt = buf_pkt;
909
910
0
    ret = 0;
911
0
end:
912
0
    if (ret < 0)
913
0
        av_packet_unref(buf_pkt);
914
0
    if (cd != (iconv_t)-1)
915
0
        iconv_close(cd);
916
0
    return ret;
917
#else
918
    av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
919
    return AVERROR(EINVAL);
920
#endif
921
0
}
922
923
static int utf8_check(const uint8_t *str)
924
0
{
925
0
    const uint8_t *byte;
926
0
    uint32_t codepoint, min;
927
928
0
    while (*str) {
929
0
        byte = str;
930
0
        GET_UTF8(codepoint, *(byte++), return 0;);
931
0
        min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
932
0
              1 << (5 * (byte - str) - 4);
933
0
        if (codepoint < min || codepoint >= 0x110000 ||
934
0
            codepoint == 0xFFFE /* BOM */ ||
935
0
            codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
936
0
            return 0;
937
0
        str = byte;
938
0
    }
939
0
    return 1;
940
0
}
941
942
const char *ff_decode_subtitle_text(AVCodecContext *avctx, const AVPacket *avpkt)
943
0
{
944
0
    AVPacket *copy = avctx->internal->buffer_pkt;
945
946
0
    if (avpkt->size <= 0 || !avpkt->data[avpkt->size])
947
0
        return avpkt->data;
948
0
    if (av_new_packet(copy, avpkt->size) < 0)
949
0
        return NULL;
950
0
    memcpy(copy->data, avpkt->data, avpkt->size);
951
0
    return copy->data;
952
0
}
953
954
int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
955
                             int *got_sub_ptr, const AVPacket *avpkt)
956
0
{
957
0
    int ret = 0;
958
959
0
    if (!avpkt->data && avpkt->size) {
960
0
        av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
961
0
        return AVERROR(EINVAL);
962
0
    }
963
0
    if (!avctx->codec)
964
0
        return AVERROR(EINVAL);
965
0
    if (ffcodec(avctx->codec)->cb_type != FF_CODEC_CB_TYPE_DECODE_SUB) {
966
0
        av_log(avctx, AV_LOG_ERROR, "Codec not subtitle decoder\n");
967
0
        return AVERROR(EINVAL);
968
0
    }
969
970
0
    *got_sub_ptr = 0;
971
0
    get_subtitle_defaults(sub);
972
973
0
    if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
974
0
        AVCodecInternal *avci = avctx->internal;
975
0
        const AVPacket *pkt;
976
977
0
        ret = recode_subtitle(avctx, &pkt, avpkt, avci->buffer_pkt);
978
0
        if (ret < 0)
979
0
            return ret;
980
981
0
        if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
982
0
            sub->pts = av_rescale_q(avpkt->pts,
983
0
                                    avctx->pkt_timebase, AV_TIME_BASE_Q);
984
0
        ret = ffcodec(avctx->codec)->cb.decode_sub(avctx, sub, got_sub_ptr, pkt);
985
0
        av_packet_unref(avci->buffer_pkt);
986
0
        if (ret < 0) {
987
0
            *got_sub_ptr = 0;
988
0
            avsubtitle_free(sub);
989
0
            return ret;
990
0
        }
991
0
        av_assert1(!sub->num_rects || *got_sub_ptr);
992
993
0
        if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
994
0
            avctx->pkt_timebase.num) {
995
0
            AVRational ms = { 1, 1000 };
996
0
            sub->end_display_time = av_rescale_q(avpkt->duration,
997
0
                                                 avctx->pkt_timebase, ms);
998
0
        }
999
1000
0
        if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
1001
0
            sub->format = 0;
1002
0
        else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
1003
0
            sub->format = 1;
1004
1005
0
        for (unsigned i = 0; i < sub->num_rects; i++) {
1006
0
            if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_IGNORE &&
1007
0
                sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
1008
0
                av_log(avctx, AV_LOG_ERROR,
1009
0
                       "Invalid UTF-8 in decoded subtitles text; "
1010
0
                       "maybe missing -sub_charenc option\n");
1011
0
                avsubtitle_free(sub);
1012
0
                *got_sub_ptr = 0;
1013
0
                return AVERROR_INVALIDDATA;
1014
0
            }
1015
0
        }
1016
1017
0
        if (*got_sub_ptr)
1018
0
            avctx->frame_num++;
1019
0
    }
1020
1021
0
    return ret;
1022
0
}
1023
1024
enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *avctx,
1025
                                              const enum AVPixelFormat *fmt)
1026
0
{
1027
0
    const AVCodecHWConfig *config;
1028
0
    int i, n;
1029
1030
    // If a device was supplied when the codec was opened, assume that the
1031
    // user wants to use it.
1032
0
    if (avctx->hw_device_ctx && ffcodec(avctx->codec)->hw_configs) {
1033
0
        AVHWDeviceContext *device_ctx =
1034
0
            (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1035
0
        for (i = 0;; i++) {
1036
0
            config = avcodec_get_hw_config(avctx->codec, i);
1037
0
            if (!config)
1038
0
                break;
1039
0
            if (!(config->methods &
1040
0
                  AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
1041
0
                continue;
1042
0
            if (device_ctx->type != config->device_type)
1043
0
                continue;
1044
0
            for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
1045
0
                if (config->pix_fmt == fmt[n])
1046
0
                    return fmt[n];
1047
0
            }
1048
0
        }
1049
0
    }
1050
    // No device or other setup, so we have to choose from things which
1051
    // don't any other external information.
1052
1053
    // Choose the first software format
1054
    // (this should be best software format if any exist).
1055
0
    for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
1056
0
        const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(fmt[n]);
1057
0
        if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
1058
0
            return fmt[n];
1059
0
    }
1060
1061
    // Finally, traverse the list in order and choose the first entry
1062
    // with no external dependencies (if there is no hardware configuration
1063
    // information available then this just picks the first entry).
1064
0
    for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
1065
0
        for (i = 0;; i++) {
1066
0
            config = avcodec_get_hw_config(avctx->codec, i);
1067
0
            if (!config)
1068
0
                break;
1069
0
            if (config->pix_fmt == fmt[n])
1070
0
                break;
1071
0
        }
1072
0
        if (!config) {
1073
            // No specific config available, so the decoder must be able
1074
            // to handle this format without any additional setup.
1075
0
            return fmt[n];
1076
0
        }
1077
0
        if (config->methods & AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1078
            // Usable with only internal setup.
1079
0
            return fmt[n];
1080
0
        }
1081
0
    }
1082
1083
    // Nothing is usable, give up.
1084
0
    return AV_PIX_FMT_NONE;
1085
0
}
1086
1087
int ff_decode_get_hw_frames_ctx(AVCodecContext *avctx,
1088
                                enum AVHWDeviceType dev_type)
1089
0
{
1090
0
    AVHWDeviceContext *device_ctx;
1091
0
    AVHWFramesContext *frames_ctx;
1092
0
    int ret;
1093
1094
0
    if (!avctx->hwaccel)
1095
0
        return AVERROR(ENOSYS);
1096
1097
0
    if (avctx->hw_frames_ctx)
1098
0
        return 0;
1099
0
    if (!avctx->hw_device_ctx) {
1100
0
        av_log(avctx, AV_LOG_ERROR, "A hardware frames or device context is "
1101
0
                "required for hardware accelerated decoding.\n");
1102
0
        return AVERROR(EINVAL);
1103
0
    }
1104
1105
0
    device_ctx = (AVHWDeviceContext *)avctx->hw_device_ctx->data;
1106
0
    if (device_ctx->type != dev_type) {
1107
0
        av_log(avctx, AV_LOG_ERROR, "Device type %s expected for hardware "
1108
0
               "decoding, but got %s.\n", av_hwdevice_get_type_name(dev_type),
1109
0
               av_hwdevice_get_type_name(device_ctx->type));
1110
0
        return AVERROR(EINVAL);
1111
0
    }
1112
1113
0
    ret = avcodec_get_hw_frames_parameters(avctx,
1114
0
                                           avctx->hw_device_ctx,
1115
0
                                           avctx->hwaccel->pix_fmt,
1116
0
                                           &avctx->hw_frames_ctx);
1117
0
    if (ret < 0)
1118
0
        return ret;
1119
1120
0
    frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1121
1122
1123
0
    if (frames_ctx->initial_pool_size) {
1124
        // We guarantee 4 base work surfaces. The function above guarantees 1
1125
        // (the absolute minimum), so add the missing count.
1126
0
        frames_ctx->initial_pool_size += 3;
1127
0
    }
1128
1129
0
    ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
1130
0
    if (ret < 0) {
1131
0
        av_buffer_unref(&avctx->hw_frames_ctx);
1132
0
        return ret;
1133
0
    }
1134
1135
0
    return 0;
1136
0
}
1137
1138
int avcodec_get_hw_frames_parameters(AVCodecContext *avctx,
1139
                                     AVBufferRef *device_ref,
1140
                                     enum AVPixelFormat hw_pix_fmt,
1141
                                     AVBufferRef **out_frames_ref)
1142
0
{
1143
0
    AVBufferRef *frames_ref = NULL;
1144
0
    const AVCodecHWConfigInternal *hw_config;
1145
0
    const FFHWAccel *hwa;
1146
0
    int i, ret;
1147
0
    bool clean_priv_data = false;
1148
1149
0
    for (i = 0;; i++) {
1150
0
        hw_config = ffcodec(avctx->codec)->hw_configs[i];
1151
0
        if (!hw_config)
1152
0
            return AVERROR(ENOENT);
1153
0
        if (hw_config->public.pix_fmt == hw_pix_fmt)
1154
0
            break;
1155
0
    }
1156
1157
0
    hwa = hw_config->hwaccel;
1158
0
    if (!hwa || !hwa->frame_params)
1159
0
        return AVERROR(ENOENT);
1160
1161
0
    frames_ref = av_hwframe_ctx_alloc(device_ref);
1162
0
    if (!frames_ref)
1163
0
        return AVERROR(ENOMEM);
1164
1165
0
    if (!avctx->internal->hwaccel_priv_data) {
1166
0
        avctx->internal->hwaccel_priv_data =
1167
0
            av_mallocz(hwa->priv_data_size);
1168
0
        if (!avctx->internal->hwaccel_priv_data) {
1169
0
            av_buffer_unref(&frames_ref);
1170
0
            return AVERROR(ENOMEM);
1171
0
        }
1172
0
        clean_priv_data = true;
1173
0
    }
1174
1175
0
    ret = hwa->frame_params(avctx, frames_ref);
1176
0
    if (ret >= 0) {
1177
0
        AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frames_ref->data;
1178
1179
0
        if (frames_ctx->initial_pool_size) {
1180
            // If the user has requested that extra output surfaces be
1181
            // available then add them here.
1182
0
            if (avctx->extra_hw_frames > 0)
1183
0
                frames_ctx->initial_pool_size += avctx->extra_hw_frames;
1184
1185
            // If frame threading is enabled then an extra surface per thread
1186
            // is also required.
1187
0
            if (avctx->active_thread_type & FF_THREAD_FRAME)
1188
0
                frames_ctx->initial_pool_size += avctx->thread_count;
1189
0
        }
1190
1191
0
        *out_frames_ref = frames_ref;
1192
0
    } else {
1193
0
        if (clean_priv_data)
1194
0
            av_freep(&avctx->internal->hwaccel_priv_data);
1195
0
        av_buffer_unref(&frames_ref);
1196
0
    }
1197
0
    return ret;
1198
0
}
1199
1200
static int hwaccel_init(AVCodecContext *avctx,
1201
                        const FFHWAccel *hwaccel)
1202
0
{
1203
0
    int err;
1204
1205
0
    if (hwaccel->p.capabilities & AV_HWACCEL_CODEC_CAP_EXPERIMENTAL &&
1206
0
        avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1207
0
        av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
1208
0
               hwaccel->p.name);
1209
0
        return AVERROR_PATCHWELCOME;
1210
0
    }
1211
1212
0
    if (!avctx->internal->hwaccel_priv_data && hwaccel->priv_data_size) {
1213
0
        avctx->internal->hwaccel_priv_data =
1214
0
            av_mallocz(hwaccel->priv_data_size);
1215
0
        if (!avctx->internal->hwaccel_priv_data)
1216
0
            return AVERROR(ENOMEM);
1217
0
    }
1218
1219
0
    avctx->hwaccel = &hwaccel->p;
1220
0
    if (hwaccel->init) {
1221
0
        err = hwaccel->init(avctx);
1222
0
        if (err < 0) {
1223
0
            av_log(avctx, AV_LOG_ERROR, "Failed setup for format %s: "
1224
0
                   "hwaccel initialisation returned error.\n",
1225
0
                   av_get_pix_fmt_name(hwaccel->p.pix_fmt));
1226
0
            av_freep(&avctx->internal->hwaccel_priv_data);
1227
0
            avctx->hwaccel = NULL;
1228
0
            return err;
1229
0
        }
1230
0
    }
1231
1232
0
    return 0;
1233
0
}
1234
1235
void ff_hwaccel_uninit(AVCodecContext *avctx)
1236
0
{
1237
0
    if (FF_HW_HAS_CB(avctx, uninit))
1238
0
        FF_HW_SIMPLE_CALL(avctx, uninit);
1239
1240
0
    av_freep(&avctx->internal->hwaccel_priv_data);
1241
1242
0
    avctx->hwaccel = NULL;
1243
1244
0
    av_buffer_unref(&avctx->hw_frames_ctx);
1245
0
}
1246
1247
int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1248
0
{
1249
0
    const AVPixFmtDescriptor *desc;
1250
0
    enum AVPixelFormat *choices;
1251
0
    enum AVPixelFormat ret, user_choice;
1252
0
    const AVCodecHWConfigInternal *hw_config;
1253
0
    const AVCodecHWConfig *config;
1254
0
    int i, n, err;
1255
1256
    // Find end of list.
1257
0
    for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
1258
    // Must contain at least one entry.
1259
0
    av_assert0(n >= 1);
1260
    // If a software format is available, it must be the last entry.
1261
0
    desc = av_pix_fmt_desc_get(fmt[n - 1]);
1262
0
    if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
1263
        // No software format is available.
1264
0
    } else {
1265
0
        avctx->sw_pix_fmt = fmt[n - 1];
1266
0
    }
1267
1268
0
    choices = av_memdup(fmt, (n + 1) * sizeof(*choices));
1269
0
    if (!choices)
1270
0
        return AV_PIX_FMT_NONE;
1271
1272
0
    for (;;) {
1273
        // Remove the previous hwaccel, if there was one.
1274
0
        ff_hwaccel_uninit(avctx);
1275
1276
0
        user_choice = avctx->get_format(avctx, choices);
1277
0
        if (user_choice == AV_PIX_FMT_NONE) {
1278
            // Explicitly chose nothing, give up.
1279
0
            ret = AV_PIX_FMT_NONE;
1280
0
            break;
1281
0
        }
1282
1283
0
        desc = av_pix_fmt_desc_get(user_choice);
1284
0
        if (!desc) {
1285
0
            av_log(avctx, AV_LOG_ERROR, "Invalid format returned by "
1286
0
                   "get_format() callback.\n");
1287
0
            ret = AV_PIX_FMT_NONE;
1288
0
            break;
1289
0
        }
1290
0
        av_log(avctx, AV_LOG_DEBUG, "Format %s chosen by get_format().\n",
1291
0
               desc->name);
1292
1293
0
        for (i = 0; i < n; i++) {
1294
0
            if (choices[i] == user_choice)
1295
0
                break;
1296
0
        }
1297
0
        if (i == n) {
1298
0
            av_log(avctx, AV_LOG_ERROR, "Invalid return from get_format(): "
1299
0
                   "%s not in possible list.\n", desc->name);
1300
0
            ret = AV_PIX_FMT_NONE;
1301
0
            break;
1302
0
        }
1303
1304
0
        if (ffcodec(avctx->codec)->hw_configs) {
1305
0
            for (i = 0;; i++) {
1306
0
                hw_config = ffcodec(avctx->codec)->hw_configs[i];
1307
0
                if (!hw_config)
1308
0
                    break;
1309
0
                if (hw_config->public.pix_fmt == user_choice)
1310
0
                    break;
1311
0
            }
1312
0
        } else {
1313
0
            hw_config = NULL;
1314
0
        }
1315
1316
0
        if (!hw_config) {
1317
            // No config available, so no extra setup required.
1318
0
            ret = user_choice;
1319
0
            break;
1320
0
        }
1321
0
        config = &hw_config->public;
1322
1323
0
        if (config->methods &
1324
0
            AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX &&
1325
0
            avctx->hw_frames_ctx) {
1326
0
            const AVHWFramesContext *frames_ctx =
1327
0
                (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1328
0
            if (frames_ctx->format != user_choice) {
1329
0
                av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1330
0
                       "does not match the format of the provided frames "
1331
0
                       "context.\n", desc->name);
1332
0
                goto try_again;
1333
0
            }
1334
0
        } else if (config->methods &
1335
0
                   AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
1336
0
                   avctx->hw_device_ctx) {
1337
0
            const AVHWDeviceContext *device_ctx =
1338
0
                (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1339
0
            if (device_ctx->type != config->device_type) {
1340
0
                av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1341
0
                       "does not match the type of the provided device "
1342
0
                       "context.\n", desc->name);
1343
0
                goto try_again;
1344
0
            }
1345
0
        } else if (config->methods &
1346
0
                   AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1347
            // Internal-only setup, no additional configuration.
1348
0
        } else if (config->methods &
1349
0
                   AV_CODEC_HW_CONFIG_METHOD_AD_HOC) {
1350
            // Some ad-hoc configuration we can't see and can't check.
1351
0
        } else {
1352
0
            av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1353
0
                   "missing configuration.\n", desc->name);
1354
0
            goto try_again;
1355
0
        }
1356
0
        if (hw_config->hwaccel) {
1357
0
            av_log(avctx, AV_LOG_DEBUG, "Format %s requires hwaccel %s "
1358
0
                   "initialisation.\n", desc->name, hw_config->hwaccel->p.name);
1359
0
            err = hwaccel_init(avctx, hw_config->hwaccel);
1360
0
            if (err < 0)
1361
0
                goto try_again;
1362
0
        }
1363
0
        ret = user_choice;
1364
0
        break;
1365
1366
0
    try_again:
1367
0
        av_log(avctx, AV_LOG_DEBUG, "Format %s not usable, retrying "
1368
0
               "get_format() without it.\n", desc->name);
1369
0
        for (i = 0; i < n; i++) {
1370
0
            if (choices[i] == user_choice)
1371
0
                break;
1372
0
        }
1373
0
        for (; i + 1 < n; i++)
1374
0
            choices[i] = choices[i + 1];
1375
0
        --n;
1376
0
    }
1377
1378
0
    if (ret < 0)
1379
0
        ff_hwaccel_uninit(avctx);
1380
1381
0
    av_freep(&choices);
1382
0
    return ret;
1383
0
}
1384
1385
static const AVPacketSideData*
1386
packet_side_data_get(const AVPacketSideData *sd, int nb_sd,
1387
                     enum AVPacketSideDataType type)
1388
0
{
1389
0
    for (int i = 0; i < nb_sd; i++)
1390
0
        if (sd[i].type == type)
1391
0
            return &sd[i];
1392
1393
0
    return NULL;
1394
0
}
1395
1396
const AVPacketSideData *ff_get_coded_side_data(const AVCodecContext *avctx,
1397
                                               enum AVPacketSideDataType type)
1398
0
{
1399
0
    return packet_side_data_get(avctx->coded_side_data, avctx->nb_coded_side_data, type);
1400
0
}
1401
1402
static int side_data_stereo3d_merge(AVFrameSideData *sd_frame,
1403
                                    const AVPacketSideData *sd_pkt)
1404
0
{
1405
0
    const AVStereo3D *src;
1406
0
    AVStereo3D       *dst;
1407
0
    int ret;
1408
1409
0
    ret = av_buffer_make_writable(&sd_frame->buf);
1410
0
    if (ret < 0)
1411
0
        return ret;
1412
0
    sd_frame->data = sd_frame->buf->data;
1413
1414
0
    dst = (      AVStereo3D*)sd_frame->data;
1415
0
    src = (const AVStereo3D*)sd_pkt->data;
1416
1417
0
    if (dst->type == AV_STEREO3D_UNSPEC)
1418
0
        dst->type = src->type;
1419
1420
0
    if (dst->view == AV_STEREO3D_VIEW_UNSPEC)
1421
0
        dst->view = src->view;
1422
1423
0
    if (dst->primary_eye == AV_PRIMARY_EYE_NONE)
1424
0
        dst->primary_eye = src->primary_eye;
1425
1426
0
    if (!dst->baseline)
1427
0
        dst->baseline = src->baseline;
1428
1429
0
    if (!dst->horizontal_disparity_adjustment.num)
1430
0
        dst->horizontal_disparity_adjustment = src->horizontal_disparity_adjustment;
1431
1432
0
    if (!dst->horizontal_field_of_view.num)
1433
0
        dst->horizontal_field_of_view = src->horizontal_field_of_view;
1434
1435
0
    return 0;
1436
0
}
1437
1438
static int side_data_exif_parse(AVFrame *dst, const AVPacketSideData *sd_pkt)
1439
0
{
1440
0
    AVExifMetadata ifd = { 0 };
1441
0
    AVExifEntry *entry = NULL;
1442
0
    AVBufferRef *buf = NULL;
1443
0
    AVFrameSideData *sd_frame;
1444
0
    int ret;
1445
1446
0
    ret = av_exif_parse_buffer(NULL, sd_pkt->data, sd_pkt->size, &ifd,
1447
0
                               AV_EXIF_TIFF_HEADER);
1448
0
    if (ret < 0)
1449
0
        return ret;
1450
1451
0
    ret = av_exif_get_entry(NULL, &ifd, av_exif_get_tag_id("Orientation"), 0, &entry);
1452
0
    if (ret < 0)
1453
0
        goto end;
1454
1455
0
    if (!entry) {
1456
0
        ret = av_exif_ifd_to_dict(NULL, &ifd, &dst->metadata);
1457
0
        if (ret < 0)
1458
0
            goto end;
1459
1460
0
        sd_frame = av_frame_side_data_new(&dst->side_data, &dst->nb_side_data, AV_FRAME_DATA_EXIF,
1461
0
                                          sd_pkt->size, 0);
1462
0
        if (sd_frame)
1463
0
            memcpy(sd_frame->data, sd_pkt->data, sd_pkt->size);
1464
0
        ret = sd_frame ? 0 : AVERROR(ENOMEM);
1465
1466
0
        goto end;
1467
0
    } else if (entry->count <= 0 || entry->type != AV_TIFF_SHORT) {
1468
0
        ret = AVERROR_INVALIDDATA;
1469
0
        goto end;
1470
0
    }
1471
1472
    // If a display matrix already exists in the frame, give it priority
1473
0
    if (av_frame_side_data_get(dst->side_data, dst->nb_side_data, AV_FRAME_DATA_DISPLAYMATRIX))
1474
0
        goto finish;
1475
1476
0
    sd_frame = av_frame_side_data_new(&dst->side_data, &dst->nb_side_data, AV_FRAME_DATA_DISPLAYMATRIX,
1477
0
                                      sizeof(int32_t) * 9, 0);
1478
0
    if (!sd_frame) {
1479
0
        ret = AVERROR(ENOMEM);
1480
0
        goto end;
1481
0
    }
1482
1483
0
    ret = av_exif_orientation_to_matrix((int32_t *)sd_frame->data, entry->value.uint[0]);
1484
0
    if (ret < 0)
1485
0
        goto end;
1486
1487
0
finish:
1488
0
    av_exif_remove_entry(NULL, &ifd, entry->id, 0);
1489
1490
0
    ret = av_exif_ifd_to_dict(NULL, &ifd, &dst->metadata);
1491
0
    if (ret < 0)
1492
0
        goto end;
1493
1494
0
    ret = av_exif_write(NULL, &ifd, &buf, AV_EXIF_TIFF_HEADER);
1495
0
    if (ret < 0)
1496
0
        goto end;
1497
1498
0
    if (!av_frame_side_data_add(&dst->side_data, &dst->nb_side_data, AV_FRAME_DATA_EXIF, &buf, 0)) {
1499
0
        ret = AVERROR(ENOMEM);
1500
0
        goto end;
1501
0
    }
1502
1503
0
    ret = 0;
1504
0
end:
1505
0
    av_buffer_unref(&buf);
1506
0
    av_exif_free(&ifd);
1507
0
    return ret;
1508
0
}
1509
1510
static int side_data_map(AVFrame *dst,
1511
                         const AVPacketSideData *sd_src, int nb_sd_src,
1512
                         const SideDataMap *map)
1513
1514
0
{
1515
0
    for (int i = 0; map[i].packet < AV_PKT_DATA_NB; i++) {
1516
0
        const enum AVPacketSideDataType type_pkt   = map[i].packet;
1517
0
        const enum AVFrameSideDataType  type_frame = map[i].frame;
1518
0
        const AVPacketSideData *sd_pkt;
1519
0
        AVFrameSideData *sd_frame;
1520
1521
0
        sd_pkt = packet_side_data_get(sd_src, nb_sd_src, type_pkt);
1522
0
        if (!sd_pkt)
1523
0
            continue;
1524
1525
0
        sd_frame = av_frame_get_side_data(dst, type_frame);
1526
0
        if (sd_frame) {
1527
0
            if (type_frame == AV_FRAME_DATA_STEREO3D) {
1528
0
                int ret = side_data_stereo3d_merge(sd_frame, sd_pkt);
1529
0
                if (ret < 0)
1530
0
                    return ret;
1531
0
            }
1532
1533
0
            continue;
1534
0
        }
1535
1536
0
        switch (type_pkt) {
1537
0
        case AV_PKT_DATA_EXIF: {
1538
0
            int ret = side_data_exif_parse(dst, sd_pkt);
1539
0
            if (ret < 0)
1540
0
                return ret;
1541
0
            break;
1542
0
        }
1543
0
        default:
1544
0
            sd_frame = av_frame_new_side_data(dst, type_frame, sd_pkt->size);
1545
0
            if (!sd_frame)
1546
0
                return AVERROR(ENOMEM);
1547
1548
0
            memcpy(sd_frame->data, sd_pkt->data, sd_pkt->size);
1549
0
            break;
1550
0
        }
1551
0
    }
1552
1553
0
    return 0;
1554
0
}
1555
1556
static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
1557
0
{
1558
0
    size_t size;
1559
0
    const uint8_t *side_metadata;
1560
1561
0
    AVDictionary **frame_md = &frame->metadata;
1562
1563
0
    side_metadata = av_packet_get_side_data(avpkt,
1564
0
                                            AV_PKT_DATA_STRINGS_METADATA, &size);
1565
0
    return av_packet_unpack_dictionary(side_metadata, size, frame_md);
1566
0
}
1567
1568
int ff_decode_frame_props_from_pkt(const AVCodecContext *avctx,
1569
                                   AVFrame *frame, const AVPacket *pkt)
1570
0
{
1571
0
    static const SideDataMap sd[] = {
1572
0
        { AV_PKT_DATA_A53_CC,                      AV_FRAME_DATA_A53_CC },
1573
0
        { AV_PKT_DATA_AFD,                         AV_FRAME_DATA_AFD },
1574
0
        { AV_PKT_DATA_DYNAMIC_HDR10_PLUS,          AV_FRAME_DATA_DYNAMIC_HDR_PLUS },
1575
0
        { AV_PKT_DATA_DYNAMIC_HDR_SMPTE_2094_APP5, AV_FRAME_DATA_DYNAMIC_HDR_SMPTE_2094_APP5 },
1576
0
        { AV_PKT_DATA_S12M_TIMECODE,               AV_FRAME_DATA_S12M_TIMECODE },
1577
0
        { AV_PKT_DATA_SKIP_SAMPLES,                AV_FRAME_DATA_SKIP_SAMPLES },
1578
0
        { AV_PKT_DATA_LCEVC,                       AV_FRAME_DATA_LCEVC },
1579
0
        { AV_PKT_DATA_IAMF_MIX_GAIN_PARAM,         AV_FRAME_DATA_IAMF_MIX_GAIN_PARAM },
1580
0
        { AV_PKT_DATA_IAMF_DEMIXING_INFO_PARAM,    AV_FRAME_DATA_IAMF_DEMIXING_INFO_PARAM },
1581
0
        { AV_PKT_DATA_IAMF_RECON_GAIN_INFO_PARAM,  AV_FRAME_DATA_IAMF_RECON_GAIN_INFO_PARAM },
1582
0
        { AV_PKT_DATA_NB }
1583
0
    };
1584
1585
0
    int ret = 0;
1586
1587
0
    frame->pts          = pkt->pts;
1588
0
    frame->duration     = pkt->duration;
1589
1590
0
    if (pkt->side_data_elems) {
1591
0
        ret = side_data_map(frame, pkt->side_data, pkt->side_data_elems, ff_sd_global_map);
1592
0
        if (ret < 0)
1593
0
            return ret;
1594
1595
0
        ret = side_data_map(frame, pkt->side_data, pkt->side_data_elems, sd);
1596
0
        if (ret < 0)
1597
0
            return ret;
1598
1599
0
        add_metadata_from_side_data(pkt, frame);
1600
0
    }
1601
1602
0
    if (pkt->flags & AV_PKT_FLAG_DISCARD) {
1603
0
        frame->flags |= AV_FRAME_FLAG_DISCARD;
1604
0
    }
1605
1606
0
    if (avctx->flags & AV_CODEC_FLAG_COPY_OPAQUE) {
1607
0
        ret = av_buffer_replace(&frame->opaque_ref, pkt->opaque_ref);
1608
0
        if (ret < 0)
1609
0
            return ret;
1610
0
        frame->opaque = pkt->opaque;
1611
0
    }
1612
1613
0
    return 0;
1614
0
}
1615
1616
int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
1617
0
{
1618
0
    int ret;
1619
1620
0
    ret = side_data_map(frame, avctx->coded_side_data, avctx->nb_coded_side_data,
1621
0
                        ff_sd_global_map);
1622
0
    if (ret < 0)
1623
0
        return ret;
1624
1625
0
    for (int i = 0; i < avctx->nb_decoded_side_data; i++) {
1626
0
        const AVFrameSideData *src = avctx->decoded_side_data[i];
1627
0
        if (av_frame_get_side_data(frame, src->type))
1628
0
            continue;
1629
0
        ret = av_frame_side_data_clone(&frame->side_data, &frame->nb_side_data, src, 0);
1630
0
        if (ret < 0)
1631
0
            return ret;
1632
0
    }
1633
1634
0
    if (!(ffcodec(avctx->codec)->caps_internal & FF_CODEC_CAP_SETS_FRAME_PROPS)) {
1635
0
        const AVPacket *pkt = avctx->internal->last_pkt_props;
1636
1637
0
        ret = ff_decode_frame_props_from_pkt(avctx, frame, pkt);
1638
0
        if (ret < 0)
1639
0
            return ret;
1640
0
    }
1641
1642
0
    ret = fill_frame_props(avctx, frame);
1643
0
    if (ret < 0)
1644
0
        return ret;
1645
1646
0
    switch (avctx->codec->type) {
1647
0
    case AVMEDIA_TYPE_VIDEO:
1648
0
        if (frame->width && frame->height &&
1649
0
            av_image_check_sar(frame->width, frame->height,
1650
0
                               frame->sample_aspect_ratio) < 0) {
1651
0
            av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1652
0
                   frame->sample_aspect_ratio.num,
1653
0
                   frame->sample_aspect_ratio.den);
1654
0
            frame->sample_aspect_ratio = (AVRational){ 0, 1 };
1655
0
        }
1656
0
        break;
1657
0
    }
1658
1659
#if CONFIG_LIBLCEVC_DEC
1660
    AVCodecInternal    *avci = avctx->internal;
1661
    DecodeContext        *dc = decode_ctx(avci);
1662
1663
    dc->lcevc.frame = dc->lcevc.ctx &&
1664
                      av_frame_get_side_data(frame, AV_FRAME_DATA_LCEVC);
1665
1666
    if (dc->lcevc.frame) {
1667
        ret = ff_lcevc_parse_frame(dc->lcevc.ctx, frame, &dc->lcevc.format,
1668
                                   &dc->lcevc.width, &dc->lcevc.height);
1669
        if (ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE))
1670
            return ret;
1671
1672
        // force get_buffer2() to allocate the base frame using the same dimensions
1673
        // as the final enhanced frame, in order to prevent reinitializing the buffer
1674
        // pools unnecessarely
1675
        if (!ret && dc->lcevc.width && dc->lcevc.height) {
1676
            dc->lcevc.base_width  = frame->width;
1677
            dc->lcevc.base_height = frame->height;
1678
            frame->width  = dc->lcevc.width;
1679
            frame->height = dc->lcevc.height;
1680
        } else
1681
            dc->lcevc.frame = 0;
1682
    }
1683
#endif
1684
1685
0
    return 0;
1686
0
}
1687
1688
static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
1689
0
{
1690
0
    if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1691
0
        int i;
1692
0
        int num_planes = av_pix_fmt_count_planes(frame->format);
1693
0
        const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
1694
0
        int flags = desc ? desc->flags : 0;
1695
0
        if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
1696
0
            num_planes = 2;
1697
0
        for (i = 0; i < num_planes; i++) {
1698
0
            av_assert0(frame->data[i]);
1699
0
        }
1700
        // For formats without data like hwaccel allow unused pointers to be non-NULL.
1701
0
        for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
1702
0
            if (frame->data[i])
1703
0
                av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
1704
0
            frame->data[i] = NULL;
1705
0
        }
1706
0
    }
1707
0
}
1708
1709
static void decode_data_free(AVRefStructOpaque unused, void *obj)
1710
0
{
1711
0
    FrameDecodeData *fdd = obj;
1712
1713
0
    if (CONFIG_LIBLCEVC_DEC)
1714
0
        av_refstruct_unref(&fdd->post_process_opaque);
1715
0
    else
1716
0
        av_assert1(!fdd->post_process_opaque);
1717
1718
0
    if (fdd->hwaccel_priv_free)
1719
0
        fdd->hwaccel_priv_free(fdd->hwaccel_priv);
1720
0
}
1721
1722
int ff_attach_decode_data(AVCodecContext *avctx, AVFrame *frame)
1723
0
{
1724
0
    FrameDecodeData *fdd;
1725
1726
0
    av_assert1(!frame->private_ref);
1727
0
    av_refstruct_unref(&frame->private_ref);
1728
1729
0
    fdd = av_refstruct_alloc_ext(sizeof(*fdd), 0, NULL, decode_data_free);
1730
0
    if (!fdd)
1731
0
        return AVERROR(ENOMEM);
1732
1733
0
    frame->private_ref = fdd;
1734
1735
#if CONFIG_LIBLCEVC_DEC
1736
    AVCodecInternal    *avci = avctx->internal;
1737
    DecodeContext        *dc = decode_ctx(avci);
1738
1739
    if (!dc->lcevc.frame) {
1740
        dc->lcevc.frame = dc->lcevc.ctx &&
1741
                          av_frame_get_side_data(frame, AV_FRAME_DATA_LCEVC);
1742
1743
        if (dc->lcevc.frame) {
1744
            int ret = ff_lcevc_parse_frame(dc->lcevc.ctx, frame, &dc->lcevc.format,
1745
                                           &dc->lcevc.width, &dc->lcevc.height);
1746
            if (ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE))
1747
                return ret;
1748
1749
            if (!ret && dc->lcevc.width && dc->lcevc.height) {
1750
                dc->lcevc.base_width  = frame->width;
1751
                dc->lcevc.base_height = frame->height;
1752
            } else
1753
                dc->lcevc.frame = 0;
1754
        }
1755
    }
1756
    if (dc->lcevc.frame) {
1757
        FFLCEVCFrame *frame_ctx;
1758
        int ret;
1759
1760
        if (fdd->post_process || !dc->lcevc.width || !dc->lcevc.height) {
1761
            dc->lcevc.frame = 0;
1762
            return 0;
1763
        }
1764
1765
        frame_ctx = av_refstruct_pool_get(dc->lcevc.ctx->frame_pool);
1766
        if (!frame_ctx)
1767
            return AVERROR(ENOMEM);
1768
1769
        frame_ctx->lcevc = av_refstruct_ref(dc->lcevc.ctx);
1770
        frame_ctx->frame->width  = dc->lcevc.width;
1771
        frame_ctx->frame->height = dc->lcevc.height;
1772
        frame_ctx->frame->format = dc->lcevc.format;
1773
        avctx->bits_per_raw_sample = av_pix_fmt_desc_get(dc->lcevc.format)->comp[0].depth;
1774
1775
        frame->width  = dc->lcevc.base_width;
1776
        frame->height = dc->lcevc.base_height;
1777
1778
        ret = avctx->get_buffer2(avctx, frame_ctx->frame, 0);
1779
        if (ret < 0) {
1780
            av_refstruct_unref(&frame_ctx);
1781
            return ret;
1782
        }
1783
1784
        validate_avframe_allocation(avctx, frame_ctx->frame);
1785
1786
        fdd->post_process_opaque = frame_ctx;
1787
        fdd->post_process = ff_lcevc_process;
1788
    }
1789
    dc->lcevc.frame = 0;
1790
#endif
1791
1792
0
    return 0;
1793
0
}
1794
1795
int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1796
0
{
1797
0
    const FFHWAccel *hwaccel = ffhwaccel(avctx->hwaccel);
1798
0
    int override_dimensions = 1;
1799
0
    int ret;
1800
1801
0
    av_assert0(ff_codec_is_decoder(avctx->codec));
1802
1803
0
    if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1804
0
        if ((unsigned)avctx->width > INT_MAX - STRIDE_ALIGN ||
1805
0
            (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) {
1806
0
            av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
1807
0
            ret = AVERROR(EINVAL);
1808
0
            goto fail;
1809
0
        }
1810
1811
0
        if (frame->width <= 0 || frame->height <= 0) {
1812
0
            frame->width  = FFMAX(avctx->width,  AV_CEIL_RSHIFT(avctx->coded_width,  avctx->lowres));
1813
0
            frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
1814
0
            override_dimensions = 0;
1815
0
        }
1816
1817
0
        if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
1818
0
            av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
1819
0
            ret = AVERROR(EINVAL);
1820
0
            goto fail;
1821
0
        }
1822
0
    } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
1823
0
        if (frame->nb_samples * (int64_t)avctx->ch_layout.nb_channels > avctx->max_samples) {
1824
0
            av_log(avctx, AV_LOG_ERROR, "samples per frame %d, exceeds max_samples %"PRId64"\n", frame->nb_samples, avctx->max_samples);
1825
0
            ret = AVERROR(EINVAL);
1826
0
            goto fail;
1827
0
        }
1828
0
    }
1829
0
    ret = ff_decode_frame_props(avctx, frame);
1830
0
    if (ret < 0)
1831
0
        goto fail;
1832
1833
0
    if (hwaccel) {
1834
0
        if (hwaccel->alloc_frame) {
1835
0
            ret = hwaccel->alloc_frame(avctx, frame);
1836
0
            goto end;
1837
0
        }
1838
0
    } else {
1839
0
        avctx->sw_pix_fmt = avctx->pix_fmt;
1840
0
    }
1841
1842
0
    ret = avctx->get_buffer2(avctx, frame, flags);
1843
0
    if (ret < 0)
1844
0
        goto fail;
1845
1846
0
    validate_avframe_allocation(avctx, frame);
1847
1848
0
    ret = ff_attach_decode_data(avctx, frame);
1849
0
    if (ret < 0)
1850
0
        goto fail;
1851
1852
0
end:
1853
0
    if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
1854
0
        !(ffcodec(avctx->codec)->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
1855
0
        frame->width  = avctx->width;
1856
0
        frame->height = avctx->height;
1857
0
    }
1858
1859
0
fail:
1860
0
    if (ret < 0) {
1861
0
        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1862
0
        av_frame_unref(frame);
1863
0
    }
1864
1865
0
    return ret;
1866
0
}
1867
1868
static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
1869
0
{
1870
0
    int ret;
1871
1872
0
    av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
1873
1874
    // make sure the discard flag does not persist
1875
0
    frame->flags &= ~AV_FRAME_FLAG_DISCARD;
1876
1877
0
    if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
1878
0
        av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
1879
0
               frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
1880
0
        av_frame_unref(frame);
1881
0
    }
1882
1883
0
    if (!frame->data[0])
1884
0
        return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1885
1886
0
    av_frame_side_data_free(&frame->side_data, &frame->nb_side_data);
1887
1888
0
    if ((flags & FF_REGET_BUFFER_FLAG_READONLY) || av_frame_is_writable(frame))
1889
0
        return ff_decode_frame_props(avctx, frame);
1890
1891
0
    uint8_t *data[AV_VIDEO_MAX_PLANES];
1892
0
    AVBufferRef *buf[AV_VIDEO_MAX_PLANES];
1893
0
    int linesize[AV_VIDEO_MAX_PLANES];
1894
1895
0
    static_assert(AV_VIDEO_MAX_PLANES <= FF_ARRAY_ELEMS(frame->data) &&
1896
0
                  AV_VIDEO_MAX_PLANES <= FF_ARRAY_ELEMS(frame->buf)  &&
1897
0
                  AV_VIDEO_MAX_PLANES <= FF_ARRAY_ELEMS(frame->linesize),
1898
0
                  "Copying code needs to be adjusted");
1899
0
    static_assert(sizeof(frame->linesize[0]) == sizeof(linesize[0]),
1900
0
                  "linesize needs to be switched to ptrdiff_t");
1901
1902
0
    for (int i = 0; i < AV_VIDEO_MAX_PLANES; ++i) {
1903
0
        data[i]       = frame->data[i];
1904
0
        linesize[i]   = frame->linesize[i];
1905
0
        buf[i]        = frame->buf[i];
1906
0
        frame->buf[i] = NULL;
1907
0
    }
1908
0
    av_assert1(!frame->buf[AV_VIDEO_MAX_PLANES] && !frame->extended_buf);
1909
1910
0
    av_frame_unref(frame);
1911
1912
0
    ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1913
0
    if (ret >= 0) {
1914
0
        av_image_copy2(frame->data, frame->linesize,
1915
0
                       data, linesize,
1916
0
                       frame->format, frame->width, frame->height);
1917
0
    }
1918
0
    for (int i = 0; i < AV_VIDEO_MAX_PLANES; ++i)
1919
0
        av_buffer_unref(&buf[i]);
1920
1921
0
    return ret;
1922
0
}
1923
1924
int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1925
0
{
1926
0
    int ret = reget_buffer_internal(avctx, frame, flags);
1927
0
    if (ret < 0)
1928
0
        av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
1929
0
    return ret;
1930
0
}
1931
1932
typedef struct ProgressInternal {
1933
    ThreadProgress progress;
1934
    struct AVFrame *f;
1935
} ProgressInternal;
1936
1937
static void check_progress_consistency(const ProgressFrame *f)
1938
0
{
1939
0
    av_assert1(!!f->f == !!f->progress);
1940
0
    av_assert1(!f->progress || f->progress->f == f->f);
1941
0
}
1942
1943
int ff_progress_frame_alloc(AVCodecContext *avctx, ProgressFrame *f)
1944
0
{
1945
0
    AVRefStructPool *pool = avctx->internal->progress_frame_pool;
1946
1947
0
    av_assert1(!f->f && !f->progress);
1948
1949
0
    f->progress = av_refstruct_pool_get(pool);
1950
0
    if (!f->progress)
1951
0
        return AVERROR(ENOMEM);
1952
1953
0
    f->f = f->progress->f;
1954
0
    return 0;
1955
0
}
1956
1957
int ff_progress_frame_get_buffer(AVCodecContext *avctx, ProgressFrame *f, int flags)
1958
0
{
1959
0
    int ret = ff_progress_frame_alloc(avctx, f);
1960
0
    if (ret < 0)
1961
0
        return ret;
1962
1963
0
    ret = ff_thread_get_buffer(avctx, f->progress->f, flags);
1964
0
    if (ret < 0) {
1965
0
        f->f = NULL;
1966
0
        av_refstruct_unref(&f->progress);
1967
0
        return ret;
1968
0
    }
1969
0
    return 0;
1970
0
}
1971
1972
void ff_progress_frame_ref(ProgressFrame *dst, const ProgressFrame *src)
1973
0
{
1974
0
    av_assert1(src->progress && src->f && src->f == src->progress->f);
1975
0
    av_assert1(!dst->f && !dst->progress);
1976
0
    dst->f = src->f;
1977
0
    dst->progress = av_refstruct_ref(src->progress);
1978
0
}
1979
1980
void ff_progress_frame_unref(ProgressFrame *f)
1981
0
{
1982
0
    check_progress_consistency(f);
1983
0
    f->f = NULL;
1984
0
    av_refstruct_unref(&f->progress);
1985
0
}
1986
1987
void ff_progress_frame_replace(ProgressFrame *dst, const ProgressFrame *src)
1988
0
{
1989
0
    if (dst == src)
1990
0
        return;
1991
0
    ff_progress_frame_unref(dst);
1992
0
    check_progress_consistency(src);
1993
0
    if (src->f)
1994
0
        ff_progress_frame_ref(dst, src);
1995
0
}
1996
1997
void ff_progress_frame_report(ProgressFrame *f, int n)
1998
0
{
1999
0
    ff_thread_progress_report(&f->progress->progress, n);
2000
0
}
2001
2002
void ff_progress_frame_await(const ProgressFrame *f, int n)
2003
0
{
2004
0
    ff_thread_progress_await(&f->progress->progress, n);
2005
0
}
2006
2007
#if !HAVE_THREADS
2008
enum ThreadingStatus ff_thread_sync_ref(AVCodecContext *avctx, size_t offset)
2009
{
2010
    return FF_THREAD_NO_FRAME_THREADING;
2011
}
2012
#endif /* !HAVE_THREADS */
2013
2014
static av_cold int progress_frame_pool_init_cb(AVRefStructOpaque opaque, void *obj)
2015
0
{
2016
0
    const AVCodecContext *avctx = opaque.nc;
2017
0
    ProgressInternal *progress = obj;
2018
0
    int ret;
2019
2020
0
    ret = ff_thread_progress_init(&progress->progress, avctx->active_thread_type & FF_THREAD_FRAME);
2021
0
    if (ret < 0)
2022
0
        return ret;
2023
2024
0
    progress->f = av_frame_alloc();
2025
0
    if (!progress->f)
2026
0
        return AVERROR(ENOMEM);
2027
2028
0
    return 0;
2029
0
}
2030
2031
static void progress_frame_pool_reset_cb(AVRefStructOpaque unused, void *obj)
2032
0
{
2033
0
    ProgressInternal *progress = obj;
2034
2035
0
    ff_thread_progress_reset(&progress->progress);
2036
0
    av_frame_unref(progress->f);
2037
0
}
2038
2039
static av_cold void progress_frame_pool_free_entry_cb(AVRefStructOpaque opaque, void *obj)
2040
0
{
2041
0
    ProgressInternal *progress = obj;
2042
2043
0
    ff_thread_progress_destroy(&progress->progress);
2044
0
    av_frame_free(&progress->f);
2045
0
}
2046
2047
av_cold int ff_decode_preinit(AVCodecContext *avctx)
2048
0
{
2049
0
    AVCodecInternal *avci = avctx->internal;
2050
0
    DecodeContext     *dc = decode_ctx(avci);
2051
0
    int ret = 0;
2052
2053
0
    dc->initial_pict_type = AV_PICTURE_TYPE_NONE;
2054
0
    if (avctx->codec_descriptor->props & AV_CODEC_PROP_INTRA_ONLY) {
2055
0
        dc->intra_only_flag = AV_FRAME_FLAG_KEY;
2056
0
        if (avctx->codec_type == AVMEDIA_TYPE_VIDEO)
2057
0
            dc->initial_pict_type = AV_PICTURE_TYPE_I;
2058
0
    }
2059
2060
    /* if the decoder init function was already called previously,
2061
     * free the already allocated subtitle_header before overwriting it */
2062
0
    av_freep(&avctx->subtitle_header);
2063
2064
0
    if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) {
2065
0
        av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n",
2066
0
               avctx->codec->max_lowres);
2067
0
        avctx->lowres = avctx->codec->max_lowres;
2068
0
    }
2069
0
    if (avctx->sub_charenc) {
2070
0
        if (avctx->codec_type != AVMEDIA_TYPE_SUBTITLE) {
2071
0
            av_log(avctx, AV_LOG_ERROR, "Character encoding is only "
2072
0
                   "supported with subtitles codecs\n");
2073
0
            return AVERROR(EINVAL);
2074
0
        } else if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB) {
2075
0
            av_log(avctx, AV_LOG_WARNING, "Codec '%s' is bitmap-based, "
2076
0
                   "subtitles character encoding will be ignored\n",
2077
0
                   avctx->codec_descriptor->name);
2078
0
            avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_DO_NOTHING;
2079
0
        } else {
2080
            /* input character encoding is set for a text based subtitle
2081
             * codec at this point */
2082
0
            if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_AUTOMATIC)
2083
0
                avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_PRE_DECODER;
2084
2085
0
            if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_PRE_DECODER) {
2086
0
#if CONFIG_ICONV
2087
0
                iconv_t cd = iconv_open("UTF-8", avctx->sub_charenc);
2088
0
                if (cd == (iconv_t)-1) {
2089
0
                    ret = AVERROR(errno);
2090
0
                    av_log(avctx, AV_LOG_ERROR, "Unable to open iconv context "
2091
0
                           "with input character encoding \"%s\"\n", avctx->sub_charenc);
2092
0
                    return ret;
2093
0
                }
2094
0
                iconv_close(cd);
2095
#else
2096
                av_log(avctx, AV_LOG_ERROR, "Character encoding subtitles "
2097
                       "conversion needs a libavcodec built with iconv support "
2098
                       "for this codec\n");
2099
                return AVERROR(ENOSYS);
2100
#endif
2101
0
            }
2102
0
        }
2103
0
    }
2104
2105
0
    dc->pts_correction_num_faulty_pts =
2106
0
    dc->pts_correction_num_faulty_dts = 0;
2107
0
    dc->pts_correction_last_pts =
2108
0
    dc->pts_correction_last_dts = INT64_MIN;
2109
2110
0
    if (   !CONFIG_GRAY && avctx->flags & AV_CODEC_FLAG_GRAY
2111
0
        && avctx->codec_descriptor->type == AVMEDIA_TYPE_VIDEO)
2112
0
        av_log(avctx, AV_LOG_WARNING,
2113
0
               "gray decoding requested but not enabled at configuration time\n");
2114
0
    if (avctx->flags2 & AV_CODEC_FLAG2_EXPORT_MVS) {
2115
0
        avctx->export_side_data |= AV_CODEC_EXPORT_DATA_MVS;
2116
0
    }
2117
2118
0
    if (avctx->nb_side_data_prefer_packet == 1 &&
2119
0
        avctx->side_data_prefer_packet[0] == -1)
2120
0
        dc->side_data_pref_mask = ~0ULL;
2121
0
    else {
2122
0
        for (unsigned i = 0; i < avctx->nb_side_data_prefer_packet; i++) {
2123
0
            int val = avctx->side_data_prefer_packet[i];
2124
0
            int mapped = 0;
2125
2126
0
            if (val < 0 || val >= AV_PKT_DATA_NB) {
2127
0
                av_log(avctx, AV_LOG_ERROR, "Invalid side data type: %d\n", val);
2128
0
                return AVERROR(EINVAL);
2129
0
            }
2130
2131
0
            for (unsigned j = 0; ff_sd_global_map[j].packet < AV_PKT_DATA_NB; j++) {
2132
0
                if (ff_sd_global_map[j].packet == val) {
2133
0
                    mapped = 1;
2134
0
                    val = ff_sd_global_map[j].frame;
2135
2136
                    // this code will need to be changed when we have more than
2137
                    // 64 frame side data types
2138
0
                    if (val >= 64) {
2139
0
                        av_log(avctx, AV_LOG_ERROR, "Side data type too big\n");
2140
0
                        return AVERROR_BUG;
2141
0
                    }
2142
2143
0
                    dc->side_data_pref_mask |= 1ULL << val;
2144
0
                }
2145
0
            }
2146
2147
0
            if (!mapped)
2148
0
                av_log(avctx, AV_LOG_WARNING,
2149
0
                       "Side data type %s has no frame side data counterpart, "
2150
0
                       "ignoring it in side_data_prefer_packet\n",
2151
0
                       av_packet_side_data_name(val));
2152
0
        }
2153
0
    }
2154
2155
0
    avci->in_pkt         = av_packet_alloc();
2156
0
    avci->last_pkt_props = av_packet_alloc();
2157
0
    if (!avci->in_pkt || !avci->last_pkt_props)
2158
0
        return AVERROR(ENOMEM);
2159
2160
0
    if (ffcodec(avctx->codec)->caps_internal & FF_CODEC_CAP_USES_PROGRESSFRAMES) {
2161
0
        avci->progress_frame_pool =
2162
0
            av_refstruct_pool_alloc_ext(sizeof(ProgressInternal),
2163
0
                                        AV_REFSTRUCT_POOL_FLAG_FREE_ON_INIT_ERROR,
2164
0
                                        avctx, progress_frame_pool_init_cb,
2165
0
                                        progress_frame_pool_reset_cb,
2166
0
                                        progress_frame_pool_free_entry_cb, NULL);
2167
0
        if (!avci->progress_frame_pool)
2168
0
            return AVERROR(ENOMEM);
2169
0
    }
2170
0
    ret = decode_bsfs_init(avctx);
2171
0
    if (ret < 0)
2172
0
        return ret;
2173
2174
0
    if (!(avctx->export_side_data & AV_CODEC_EXPORT_DATA_ENHANCEMENTS)) {
2175
0
        if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
2176
#if CONFIG_LIBLCEVC_DEC
2177
            FFCodecContext *ffavc = ffcodeccontext(avctx);
2178
            ret = ff_lcevc_alloc(&dc->lcevc.ctx, &ffavc->lcevc_params,
2179
                                 av_log_get_level() + avctx->log_level_offset);
2180
            if (ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE))
2181
                return ret;
2182
#endif
2183
0
        }
2184
0
    }
2185
2186
0
    return 0;
2187
0
}
2188
2189
/**
2190
 * Check side data preference and clear existing side data from frame
2191
 * if needed.
2192
 *
2193
 * @retval 0 side data of this type can be added to frame
2194
 * @retval 1 side data of this type should not be added to frame
2195
 */
2196
static int side_data_pref(const AVCodecContext *avctx, AVFrameSideData ***sd,
2197
                          int *nb_sd, enum AVFrameSideDataType type)
2198
0
{
2199
0
    DecodeContext *dc = decode_ctx(avctx->internal);
2200
2201
    // Note: could be skipped for `type` without corresponding packet sd
2202
0
    if (av_frame_side_data_get(*sd, *nb_sd, type)) {
2203
0
        if (dc->side_data_pref_mask & (1ULL << type))
2204
0
            return 1;
2205
0
        av_frame_side_data_remove(sd, nb_sd, type);
2206
0
    }
2207
2208
0
    return 0;
2209
0
}
2210
2211
2212
int ff_frame_new_side_data(const AVCodecContext *avctx, AVFrame *frame,
2213
                           enum AVFrameSideDataType type, size_t size,
2214
                           AVFrameSideData **psd)
2215
0
{
2216
0
    AVFrameSideData *sd;
2217
2218
0
    if (side_data_pref(avctx, &frame->side_data, &frame->nb_side_data, type)) {
2219
0
        if (psd)
2220
0
            *psd = NULL;
2221
0
        return 0;
2222
0
    }
2223
2224
0
    sd = av_frame_new_side_data(frame, type, size);
2225
0
    if (psd)
2226
0
        *psd = sd;
2227
2228
0
    return sd ? 0 : AVERROR(ENOMEM);
2229
0
}
2230
2231
int ff_frame_new_side_data_from_buf_ext(const AVCodecContext *avctx,
2232
                                        AVFrameSideData ***sd, int *nb_sd,
2233
                                        enum AVFrameSideDataType type,
2234
                                        AVBufferRef **buf)
2235
0
{
2236
0
    int ret = 0;
2237
2238
0
    if (side_data_pref(avctx, sd, nb_sd, type))
2239
0
        goto finish;
2240
2241
0
    if (!av_frame_side_data_add(sd, nb_sd, type, buf, 0))
2242
0
        ret = AVERROR(ENOMEM);
2243
2244
0
finish:
2245
0
    av_buffer_unref(buf);
2246
2247
0
    return ret;
2248
0
}
2249
2250
int ff_frame_new_side_data_from_buf(const AVCodecContext *avctx,
2251
                                    AVFrame *frame, enum AVFrameSideDataType type,
2252
                                    AVBufferRef **buf)
2253
0
{
2254
0
    return ff_frame_new_side_data_from_buf_ext(avctx,
2255
0
                                               &frame->side_data, &frame->nb_side_data,
2256
0
                                               type, buf);
2257
0
}
2258
2259
int ff_decode_mastering_display_new_ext(const AVCodecContext *avctx,
2260
                                        AVFrameSideData ***sd, int *nb_sd,
2261
                                        struct AVMasteringDisplayMetadata **mdm)
2262
0
{
2263
0
    AVBufferRef *buf;
2264
0
    size_t size;
2265
2266
0
    if (side_data_pref(avctx, sd, nb_sd, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA)) {
2267
0
        *mdm = NULL;
2268
0
        return 0;
2269
0
    }
2270
2271
0
    *mdm = av_mastering_display_metadata_alloc_size(&size);
2272
0
    if (!*mdm)
2273
0
        return AVERROR(ENOMEM);
2274
2275
0
    buf = av_buffer_create((uint8_t *)*mdm, size, NULL, NULL, 0);
2276
0
    if (!buf) {
2277
0
        av_freep(mdm);
2278
0
        return AVERROR(ENOMEM);
2279
0
    }
2280
2281
0
    if (!av_frame_side_data_add(sd, nb_sd, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA,
2282
0
                                &buf, 0)) {
2283
0
        *mdm = NULL;
2284
0
        av_buffer_unref(&buf);
2285
0
        return AVERROR(ENOMEM);
2286
0
    }
2287
2288
0
    return 0;
2289
0
}
2290
2291
int ff_decode_mastering_display_new(const AVCodecContext *avctx, AVFrame *frame,
2292
                                    AVMasteringDisplayMetadata **mdm)
2293
0
{
2294
0
    if (side_data_pref(avctx, &frame->side_data, &frame->nb_side_data,
2295
0
                       AV_FRAME_DATA_MASTERING_DISPLAY_METADATA)) {
2296
0
        *mdm = NULL;
2297
0
        return 0;
2298
0
    }
2299
2300
0
    *mdm = av_mastering_display_metadata_create_side_data(frame);
2301
0
    return *mdm ? 0 : AVERROR(ENOMEM);
2302
0
}
2303
2304
int ff_decode_content_light_new_ext(const AVCodecContext *avctx,
2305
                                    AVFrameSideData ***sd, int *nb_sd,
2306
                                    AVContentLightMetadata **clm)
2307
0
{
2308
0
    AVBufferRef *buf;
2309
0
    size_t size;
2310
2311
0
    if (side_data_pref(avctx, sd, nb_sd, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL)) {
2312
0
        *clm = NULL;
2313
0
        return 0;
2314
0
    }
2315
2316
0
    *clm = av_content_light_metadata_alloc(&size);
2317
0
    if (!*clm)
2318
0
        return AVERROR(ENOMEM);
2319
2320
0
    buf = av_buffer_create((uint8_t *)*clm, size, NULL, NULL, 0);
2321
0
    if (!buf) {
2322
0
        av_freep(clm);
2323
0
        return AVERROR(ENOMEM);
2324
0
    }
2325
2326
0
    if (!av_frame_side_data_add(sd, nb_sd, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL,
2327
0
                                &buf, 0)) {
2328
0
        *clm = NULL;
2329
0
        av_buffer_unref(&buf);
2330
0
        return AVERROR(ENOMEM);
2331
0
    }
2332
2333
0
    return 0;
2334
0
}
2335
2336
int ff_decode_content_light_new(const AVCodecContext *avctx, AVFrame *frame,
2337
                                AVContentLightMetadata **clm)
2338
0
{
2339
0
    if (side_data_pref(avctx, &frame->side_data, &frame->nb_side_data,
2340
0
                       AV_FRAME_DATA_CONTENT_LIGHT_LEVEL)) {
2341
0
        *clm = NULL;
2342
0
        return 0;
2343
0
    }
2344
2345
0
    *clm = av_content_light_metadata_create_side_data(frame);
2346
0
    return *clm ? 0 : AVERROR(ENOMEM);
2347
0
}
2348
2349
int ff_copy_palette(void *dst, const AVPacket *src, void *logctx)
2350
0
{
2351
0
    size_t size;
2352
0
    const void *pal = av_packet_get_side_data(src, AV_PKT_DATA_PALETTE, &size);
2353
2354
0
    if (pal && size == AVPALETTE_SIZE) {
2355
0
        memcpy(dst, pal, AVPALETTE_SIZE);
2356
0
        return 1;
2357
0
    } else if (pal) {
2358
0
        av_log(logctx, AV_LOG_ERROR,
2359
0
               "Palette size %zu is wrong\n", size);
2360
0
    }
2361
0
    return 0;
2362
0
}
2363
2364
int ff_hwaccel_frame_priv_alloc(AVCodecContext *avctx, void **hwaccel_picture_private)
2365
0
{
2366
0
    const FFHWAccel *hwaccel = ffhwaccel(avctx->hwaccel);
2367
2368
0
    if (!hwaccel || !hwaccel->frame_priv_data_size)
2369
0
        return 0;
2370
2371
0
    av_assert0(!*hwaccel_picture_private);
2372
2373
0
    if (hwaccel->free_frame_priv) {
2374
0
        AVHWDeviceContext *device_ctx = NULL;
2375
2376
0
        if (avctx->hw_frames_ctx)
2377
0
            device_ctx = ((AVHWFramesContext *)avctx->hw_frames_ctx->data)->device_ctx;
2378
2379
0
        *hwaccel_picture_private = av_refstruct_alloc_ext(hwaccel->frame_priv_data_size, 0,
2380
0
                                                          device_ctx,
2381
0
                                                          hwaccel->free_frame_priv);
2382
0
    } else {
2383
0
        *hwaccel_picture_private = av_refstruct_allocz(hwaccel->frame_priv_data_size);
2384
0
    }
2385
2386
0
    if (!*hwaccel_picture_private)
2387
0
        return AVERROR(ENOMEM);
2388
2389
0
    return 0;
2390
0
}
2391
2392
av_cold void ff_decode_flush_buffers(AVCodecContext *avctx)
2393
0
{
2394
0
    AVCodecInternal *avci = avctx->internal;
2395
0
    DecodeContext     *dc = decode_ctx(avci);
2396
2397
0
    av_packet_unref(avci->last_pkt_props);
2398
0
    av_packet_unref(avci->in_pkt);
2399
2400
0
    dc->pts_correction_num_faulty_pts =
2401
0
    dc->pts_correction_num_faulty_dts = 0;
2402
0
    dc->pts_correction_last_pts =
2403
0
    dc->pts_correction_last_dts = INT64_MIN;
2404
2405
0
    if (avci->bsf)
2406
0
        av_bsf_flush(avci->bsf);
2407
2408
0
    dc->nb_draining_errors = 0;
2409
0
    dc->draining_started   = 0;
2410
0
}
2411
2412
av_cold AVCodecInternal *ff_decode_internal_alloc(void)
2413
0
{
2414
0
    return av_mallocz(sizeof(DecodeContext));
2415
0
}
2416
2417
av_cold void ff_decode_internal_sync(AVCodecContext *dst, const AVCodecContext *src)
2418
0
{
2419
0
    const DecodeContext *src_dc = decode_ctx(src->internal);
2420
0
    DecodeContext *dst_dc = decode_ctx(dst->internal);
2421
2422
0
    dst_dc->initial_pict_type = src_dc->initial_pict_type;
2423
0
    dst_dc->intra_only_flag   = src_dc->intra_only_flag;
2424
0
    dst_dc->side_data_pref_mask = src_dc->side_data_pref_mask;
2425
#if CONFIG_LIBLCEVC_DEC
2426
    av_refstruct_replace(&dst_dc->lcevc.ctx, src_dc->lcevc.ctx);
2427
    dst_dc->lcevc.width = src_dc->lcevc.width;
2428
    dst_dc->lcevc.height = src_dc->lcevc.height;
2429
    dst_dc->lcevc.format = src_dc->lcevc.format;
2430
#endif
2431
0
}
2432
2433
av_cold void ff_decode_internal_uninit(AVCodecContext *avctx)
2434
0
{
2435
#if CONFIG_LIBLCEVC_DEC
2436
    AVCodecInternal *avci = avctx->internal;
2437
    DecodeContext *dc = decode_ctx(avci);
2438
2439
    av_refstruct_unref(&dc->lcevc.ctx);
2440
#endif
2441
0
}
2442
2443
static int attach_displaymatrix(AVCodecContext *avctx, AVFrame *frame, int orientation)
2444
0
{
2445
0
    AVFrameSideData *sd = NULL;
2446
0
    int32_t *matrix;
2447
0
    int ret;
2448
    /* invalid orientation */
2449
0
    if (orientation < 1 || orientation > 8)
2450
0
        return AVERROR_INVALIDDATA;
2451
0
    ret = ff_frame_new_side_data(avctx, frame, AV_FRAME_DATA_DISPLAYMATRIX, sizeof(int32_t) * 9, &sd);
2452
0
    if (ret < 0) {
2453
0
        av_log(avctx, AV_LOG_ERROR, "Could not allocate frame side data: %s\n", av_err2str(ret));
2454
0
        return ret;
2455
0
    }
2456
0
    if (sd) {
2457
0
        matrix = (int32_t *) sd->data;
2458
0
        ret = av_exif_orientation_to_matrix(matrix, orientation);
2459
0
    }
2460
2461
0
    return ret;
2462
0
}
2463
2464
static int exif_attach_ifd(AVCodecContext *avctx, AVFrame *frame, const AVExifMetadata *ifd, AVBufferRef **pbuf)
2465
0
{
2466
0
    const AVExifEntry *orient = NULL;
2467
0
    AVExifMetadata *cloned = NULL;
2468
0
    int ret;
2469
2470
0
    for (size_t i = 0; i < ifd->count; i++) {
2471
0
        const AVExifEntry *entry = &ifd->entries[i];
2472
0
        if (entry->id == av_exif_get_tag_id("Orientation") &&
2473
0
            entry->count > 0 && entry->type == AV_TIFF_SHORT) {
2474
0
            orient = entry;
2475
0
            break;
2476
0
        }
2477
0
    }
2478
2479
0
    if (orient) {
2480
0
        av_log(avctx, AV_LOG_DEBUG, "found EXIF orientation: %" PRIu64 "\n", orient->value.uint[0]);
2481
0
        ret = attach_displaymatrix(avctx, frame, orient->value.uint[0]);
2482
0
        if (ret < 0) {
2483
0
            av_log(avctx, AV_LOG_WARNING, "unable to attach displaymatrix from EXIF\n");
2484
0
        } else {
2485
0
            cloned = av_exif_clone_ifd(ifd);
2486
0
            if (!cloned) {
2487
0
                ret = AVERROR(ENOMEM);
2488
0
                goto end;
2489
0
            }
2490
0
            av_exif_remove_entry(avctx, cloned, orient->id, 0);
2491
0
            ifd = cloned;
2492
0
        }
2493
0
    }
2494
2495
0
    ret = av_exif_ifd_to_dict(avctx, ifd, &frame->metadata);
2496
0
    if (ret < 0)
2497
0
        goto end;
2498
2499
0
    if (cloned || !*pbuf) {
2500
0
        av_buffer_unref(pbuf);
2501
0
        ret = av_exif_write(avctx, ifd, pbuf, AV_EXIF_TIFF_HEADER);
2502
0
        if (ret < 0)
2503
0
            goto end;
2504
0
    }
2505
2506
0
    ret = ff_frame_new_side_data_from_buf(avctx, frame, AV_FRAME_DATA_EXIF, pbuf);
2507
0
    if (ret < 0)
2508
0
        goto end;
2509
2510
0
    ret = 0;
2511
2512
0
end:
2513
0
    av_buffer_unref(pbuf);
2514
0
    av_exif_free(cloned);
2515
0
    av_free(cloned);
2516
0
    return ret;
2517
0
}
2518
2519
int ff_decode_exif_attach_ifd(AVCodecContext *avctx, AVFrame *frame, const AVExifMetadata *ifd)
2520
0
{
2521
0
    AVBufferRef *dummy = NULL;
2522
0
    return exif_attach_ifd(avctx, frame, ifd, &dummy);
2523
0
}
2524
2525
int ff_decode_exif_attach_buffer(AVCodecContext *avctx, AVFrame *frame, AVBufferRef **pbuf,
2526
                                 enum AVExifHeaderMode header_mode)
2527
0
{
2528
0
    int ret;
2529
0
    AVBufferRef *data = *pbuf;
2530
0
    AVExifMetadata ifd = { 0 };
2531
2532
0
    ret = av_exif_parse_buffer(avctx, data->data, data->size, &ifd, header_mode);
2533
0
    if (ret < 0)
2534
0
        goto end;
2535
2536
0
    ret = exif_attach_ifd(avctx, frame, &ifd, pbuf);
2537
2538
0
end:
2539
0
    av_buffer_unref(pbuf);
2540
0
    av_exif_free(&ifd);
2541
0
    return ret;
2542
0
}