Coverage Report

Created: 2026-05-16 07:24

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/mpv/video/decode/vd_lavc.c
Line
Count
Source
1
/*
2
 * This file is part of mpv.
3
 *
4
 * mpv is free software; you can redistribute it and/or
5
 * modify it under the terms of the GNU Lesser General Public
6
 * License as published by the Free Software Foundation; either
7
 * version 2.1 of the License, or (at your option) any later version.
8
 *
9
 * mpv is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 * GNU Lesser General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU Lesser General Public
15
 * License along with mpv.  If not, see <http://www.gnu.org/licenses/>.
16
 */
17
18
#include <float.h>
19
#include <stdio.h>
20
#include <stdlib.h>
21
#include <assert.h>
22
#include <stdbool.h>
23
24
#include <libavcodec/avcodec.h>
25
#include <libavformat/version.h>
26
#include <libavutil/common.h>
27
#include <libavutil/hwcontext.h>
28
#include <libavutil/opt.h>
29
#include <libavutil/intreadwrite.h>
30
#include <libavutil/pixdesc.h>
31
32
#include "mpv_talloc.h"
33
#include "common/msg.h"
34
#include "options/m_config.h"
35
#include "options/options.h"
36
#include "osdep/threads.h"
37
#include "misc/bstr.h"
38
#include "common/av_common.h"
39
#include "common/codecs.h"
40
41
#include "video/fmt-conversion.h"
42
43
#include "filters/f_decoder_wrapper.h"
44
#include "filters/filter_internal.h"
45
#include "video/hwdec.h"
46
#include "video/img_format.h"
47
#include "video/mp_image.h"
48
#include "video/mp_image_pool.h"
49
#include "demux/demux.h"
50
#include "demux/stheader.h"
51
#include "demux/packet.h"
52
#include "demux/packet_pool.h"
53
#include "video/csputils.h"
54
#include "video/sws_utils.h"
55
#include "video/out/vo.h"
56
57
#include "options/m_option.h"
58
59
static void init_avctx(struct mp_filter *vd);
60
static void uninit_avctx(struct mp_filter *vd);
61
62
static int get_buffer2_direct(AVCodecContext *avctx, AVFrame *pic, int flags);
63
static enum AVPixelFormat get_format_hwdec(struct AVCodecContext *avctx,
64
                                           const enum AVPixelFormat *pix_fmt);
65
static int hwdec_opt_help(struct mp_log *log, const m_option_t *opt,
66
                          struct bstr name);
67
68
0
#define HWDEC_DELAY_QUEUE_COUNT 2
69
0
#define HWDEC_WAIT_KEYFRAME_COUNT 96
70
71
#define OPT_BASE_STRUCT struct vd_lavc_params
72
73
struct vd_lavc_params {
74
    bool fast;
75
    int film_grain;
76
    bool show_all;
77
    int skip_loop_filter;
78
    int skip_idct;
79
    int skip_frame;
80
    int framedrop;
81
    int threads;
82
    bool bitexact;
83
    bool old_x264;
84
    bool apply_cropping;
85
    bool check_hw_profile;
86
    char **avopts;
87
    int dr;
88
};
89
90
static const struct m_opt_choice_alternatives discard_names[] = {
91
    {"none",        AVDISCARD_NONE},
92
    {"default",     AVDISCARD_DEFAULT},
93
    {"nonref",      AVDISCARD_NONREF},
94
    {"bidir",       AVDISCARD_BIDIR},
95
    {"nonkey",      AVDISCARD_NONKEY},
96
    {"all",         AVDISCARD_ALL},
97
    {0}
98
};
99
#define OPT_DISCARD(field) OPT_CHOICE_C(field, discard_names)
100
101
const struct m_sub_options vd_lavc_conf = {
102
    .opts = (const m_option_t[]){
103
        {"vd-lavc-fast", OPT_BOOL(fast)},
104
        {"vd-lavc-film-grain", OPT_CHOICE(film_grain,
105
            {"auto", -1}, {"cpu", 0}, {"gpu", 1})},
106
        {"vd-lavc-show-all", OPT_BOOL(show_all)},
107
        {"vd-lavc-skiploopfilter", OPT_DISCARD(skip_loop_filter)},
108
        {"vd-lavc-skipidct", OPT_DISCARD(skip_idct)},
109
        {"vd-lavc-skipframe", OPT_DISCARD(skip_frame)},
110
        {"vd-lavc-framedrop", OPT_DISCARD(framedrop)},
111
        {"vd-lavc-threads", OPT_INT(threads), M_RANGE(0, DBL_MAX)},
112
        {"vd-lavc-bitexact", OPT_BOOL(bitexact)},
113
        {"vd-lavc-assume-old-x264", OPT_BOOL(old_x264)},
114
        {"vd-lavc-check-hw-profile", OPT_BOOL(check_hw_profile)},
115
        {"vd-lavc-o", OPT_KEYVALUELIST(avopts)},
116
        {"vd-lavc-dr", OPT_CHOICE(dr,
117
            {"auto", -1}, {"no", 0}, {"yes", 1})},
118
        {"vd-apply-cropping", OPT_BOOL(apply_cropping)},
119
        {0}
120
    },
121
    .change_flags = UPDATE_VD,
122
    .size = sizeof(struct vd_lavc_params),
123
    .defaults = &(const struct vd_lavc_params){
124
        .film_grain = -1 /*auto*/,
125
        .check_hw_profile = true,
126
        .skip_loop_filter = AVDISCARD_DEFAULT,
127
        .skip_idct = AVDISCARD_DEFAULT,
128
        .skip_frame = AVDISCARD_DEFAULT,
129
        .framedrop = AVDISCARD_NONREF,
130
        .dr = -1,
131
        .apply_cropping = true,
132
    },
133
};
134
135
#undef OPT_BASE_STRUCT
136
#define OPT_BASE_STRUCT struct hwdec_opts
137
138
struct hwdec_opts {
139
    int software_fallback;
140
    char **hwdec_api;
141
    char *hwdec_codecs;
142
    int hwdec_image_format;
143
    int hwdec_extra_frames;
144
    int hwdec_threads;
145
};
146
147
const struct m_sub_options hwdec_conf = {
148
    .opts = (const m_option_t[]){
149
        {"hwdec", OPT_STRINGLIST(hwdec_api),
150
            .help = hwdec_opt_help,
151
            .flags = M_OPT_OPTIONAL_PARAM | M_OPT_ALLOW_NO | UPDATE_HWDEC},
152
        {"hwdec-codecs", OPT_STRING(hwdec_codecs),
153
            .flags = UPDATE_HWDEC},
154
        {"hwdec-extra-frames", OPT_INT(hwdec_extra_frames), M_RANGE(0, 256),
155
            .flags = UPDATE_VD},
156
        {"hwdec-image-format", OPT_IMAGEFORMAT(hwdec_image_format),
157
            .flags = UPDATE_VO},
158
        {"hwdec-software-fallback", OPT_CHOICE(software_fallback,
159
            {"no", INT_MAX}, {"yes", 1}), M_RANGE(1, INT_MAX),
160
            .flags = UPDATE_HWDEC},
161
        {"hwdec-threads", OPT_INT(hwdec_threads), M_RANGE(0, DBL_MAX)},
162
        {"vd-lavc-software-fallback", OPT_REPLACED("hwdec-software-fallback")},
163
        {0}
164
    },
165
    .size = sizeof(struct hwdec_opts),
166
    .defaults = &(const struct hwdec_opts){
167
        .software_fallback = 3,
168
        .hwdec_api = (char *[]){"no", NULL,},
169
        .hwdec_codecs = "h264,vc1,hevc,vp8,vp9,av1,prores,prores_raw,ffv1,dpx",
170
        // Maximum number of surfaces the player wants to buffer. This number
171
        // might require adjustment depending on whatever the player does;
172
        // for example, if vo_gpu increases the number of reference surfaces for
173
        // interpolation, this value has to be increased too.
174
        .hwdec_extra_frames = 6,
175
        .hwdec_threads = 4,
176
    },
177
};
178
179
struct hwdec_info {
180
    char name[64];
181
    char method_name[24]; // non-unique name describing the hwdec method
182
    const AVCodec *codec; // implemented by this codec
183
    enum AVHWDeviceType lavc_device; // if not NONE, get a hwdevice
184
    bool copying; // if true, outputs sw frames, or copy to sw ourselves
185
    enum AVPixelFormat pix_fmt; // if not NONE, select in get_format
186
    bool use_hw_frames; // set AVCodecContext.hw_frames_ctx
187
    bool use_hw_device; // set AVCodecContext.hw_device_ctx
188
    unsigned int flags; // HWDEC_FLAG_*
189
190
    // for internal sorting
191
    int auto_pos;
192
    int rank;
193
};
194
195
typedef struct lavc_ctx {
196
    struct mp_log *log;
197
    struct m_config_cache *opts_cache;
198
    struct vd_lavc_params *opts;
199
    struct m_config_cache *hwdec_opts_cache;
200
    struct hwdec_opts *hwdec_opts;
201
    struct mp_codec_params *codec;
202
    AVCodecContext *avctx;
203
    AVFrame *pic;
204
    AVPacket *avpkt;
205
    bool use_hwdec;
206
    struct hwdec_info hwdec; // valid only if use_hwdec==true
207
    bstr *attempted_hwdecs;
208
    int num_attempted_hwdecs;
209
    AVRational codec_timebase;
210
    enum AVDiscard skip_frame;
211
    bool flushing;
212
    struct lavc_state state;
213
    const char *decoder;
214
    bool hwdec_failed;
215
    bool hwdec_notified;
216
    bool force_eof;
217
    int wait_for_keyframe; // max number of frames to wait for keyframe after reset
218
219
    bool intra_only;
220
    int framedrop_flags;
221
222
    bool hw_probing;
223
    struct demux_packet **sent_packets;
224
    int num_sent_packets;
225
226
    struct demux_packet **requeue_packets;
227
    int num_requeue_packets;
228
229
    struct mp_image **delay_queue;
230
    int num_delay_queue;
231
    int max_delay_queue;
232
233
    // From VO
234
    struct vo *vo;
235
    struct mp_hwdec_devices *hwdec_devs;
236
    bool force_swdec;
237
238
    // Wrapped AVHWDeviceContext* used for decoding.
239
    AVBufferRef *hwdec_dev;
240
241
    bool hwdec_request_reinit;
242
    int hwdec_fail_count;
243
244
    struct mp_image_pool *hwdec_swpool;
245
246
    AVBufferRef *cached_hw_frames_ctx;
247
248
    // --- The following fields are protected by dr_lock.
249
    mp_mutex dr_lock;
250
    bool dr_failed;
251
    struct mp_image_pool *dr_pool;
252
    int dr_imgfmt, dr_w, dr_h, dr_stride_align;
253
254
    struct mp_decoder public;
255
} vd_ffmpeg_ctx;
256
257
enum {
258
    HWDEC_FLAG_AUTO         = (1 << 0), // prioritize in autoprobe order
259
    HWDEC_FLAG_WHITELIST    = (1 << 1), // whitelist for auto
260
};
261
262
struct autoprobe_info {
263
    const char *method_name;
264
    unsigned int flags;         // HWDEC_FLAG_*
265
};
266
267
// Things not included in this list will be tried last, in random order.
268
const struct autoprobe_info hwdec_autoprobe_info[] = {
269
    {"d3d11va",         HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
270
    {"vulkan",          HWDEC_FLAG_AUTO},
271
    {"dxva2",           HWDEC_FLAG_AUTO},
272
    {"nvdec",           HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
273
    {"vaapi",           HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
274
    {"vdpau",           HWDEC_FLAG_AUTO},
275
    {"drm",             HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
276
    {"mediacodec",      HWDEC_FLAG_AUTO},
277
    {"videotoolbox",    HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
278
    {"d3d11va-copy",    HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
279
    {"vulkan-copy",     HWDEC_FLAG_AUTO},
280
    {"dxva2-copy",      HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
281
    {"nvdec-copy",      HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
282
    {"vaapi-copy",      HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
283
    {"vdpau-copy",      HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
284
    {"drm-copy",        HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
285
    {"mediacodec-copy", HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
286
    {"videotoolbox-copy", HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
287
    {0}
288
};
289
290
static int hwdec_compare(const void *p1, const void *p2)
291
650k
{
292
650k
    struct hwdec_info *h1 = (void *)p1;
293
650k
    struct hwdec_info *h2 = (void *)p2;
294
295
650k
    if (h1 == h2)
296
0
        return 0;
297
298
    // Strictly put non-preferred hwdecs to the end of the list.
299
650k
    if ((h1->auto_pos == INT_MAX) != (h2->auto_pos == INT_MAX))
300
0
        return h1->auto_pos == INT_MAX ? 1 : -1;
301
    // List non-copying entries first, so --hwdec=auto takes them.
302
650k
    if (h1->copying != h2->copying)
303
0
        return h1->copying ? 1 : -1;
304
    // Order by autoprobe preference order.
305
650k
    if (h1->auto_pos != h2->auto_pos)
306
0
        return h1->auto_pos > h2->auto_pos ? 1 : -1;
307
    // Put hwdecs without hw_device_ctx last
308
650k
    if ((!!h1->lavc_device) != (!!h2->lavc_device))
309
0
        return h1->lavc_device ? -1 : 1;
310
    // Fallback sort order to make sorting stable.
311
650k
    return h1->rank > h2->rank ? 1 :-1;
312
650k
}
313
314
// (This takes care of some bookkeeping too, like setting info.name)
315
static void add_hwdec_item(struct hwdec_info **infos, int *num_infos,
316
                           struct hwdec_info info)
317
450k
{
318
450k
    if (info.copying)
319
450k
        mp_snprintf_cat(info.method_name, sizeof(info.method_name), "-copy");
320
321
    // (Including the codec name in case this is a wrapper looks pretty dumb,
322
    // but better not have them clash with hwaccels and others.)
323
450k
    snprintf(info.name, sizeof(info.name), "%s-%s",
324
450k
             info.codec->name, info.method_name);
325
326
450k
    info.rank = *num_infos;
327
450k
    info.auto_pos = INT_MAX;
328
329
8.56M
    for (int x = 0; hwdec_autoprobe_info[x].method_name; x++) {
330
8.11M
        const struct autoprobe_info *entry = &hwdec_autoprobe_info[x];
331
8.11M
        if (strcmp(entry->method_name, info.method_name) == 0) {
332
0
            info.flags |= entry->flags;
333
0
            if (info.flags & HWDEC_FLAG_AUTO)
334
0
                info.auto_pos = x;
335
0
        }
336
8.11M
    }
337
338
450k
    MP_TARRAY_APPEND(NULL, *infos, *num_infos, info);
339
450k
}
340
341
static void add_all_hwdec_methods(struct hwdec_info **infos, int *num_infos)
342
50.0k
{
343
50.0k
    const AVCodec *codec = NULL;
344
50.0k
    void *iter = NULL;
345
24.9M
    while (1) {
346
24.9M
        codec = av_codec_iterate(&iter);
347
24.9M
        if (!codec)
348
50.0k
            break;
349
24.9M
        if (codec->type != AVMEDIA_TYPE_VIDEO || !av_codec_is_decoder(codec))
350
12.1M
            continue;
351
352
12.8M
        struct hwdec_info info_template = {
353
12.8M
            .pix_fmt = AV_PIX_FMT_NONE,
354
12.8M
            .codec = codec,
355
12.8M
        };
356
357
12.8M
        const char *wrapper = NULL;
358
12.8M
        if (codec->capabilities & (AV_CODEC_CAP_HARDWARE | AV_CODEC_CAP_HYBRID))
359
450k
            wrapper = codec->wrapper_name;
360
361
        // A decoder can provide multiple methods. In particular, hwaccels
362
        // provide various methods (e.g. native h264 with vaapi & d3d11), but
363
        // even wrapper decoders could provide multiple methods.
364
12.8M
        bool found_any = false;
365
12.8M
        for (int n = 0; ; n++) {
366
12.8M
            const AVCodecHWConfig *cfg = avcodec_get_hw_config(codec, n);
367
12.8M
            if (!cfg)
368
12.8M
                break;
369
370
0
            if ((cfg->methods & AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX) ||
371
0
                (cfg->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
372
0
            {
373
0
                struct hwdec_info info = info_template;
374
0
                info.lavc_device = cfg->device_type;
375
0
                info.pix_fmt = cfg->pix_fmt;
376
377
0
                const char *name = av_hwdevice_get_type_name(cfg->device_type);
378
0
                mp_assert(name); // API violation by libavcodec
379
380
                // nvdec hwaccels and the cuvid full decoder clash with their
381
                // naming, so fix it here; we also prefer nvdec for the hwaccel.
382
0
                if (strcmp(name, "cuda") == 0 && !wrapper)
383
0
                    name = "nvdec";
384
385
0
                snprintf(info.method_name, sizeof(info.method_name), "%s", name);
386
387
                // Usually we want to prefer using hw_frames_ctx for true
388
                // hwaccels only, but we actually don't have any way to detect
389
                // those, so always use hw_frames_ctx if offered.
390
0
                if (cfg->methods & AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX) {
391
0
                    info.use_hw_frames = true;
392
0
                } else {
393
0
                    info.use_hw_device = true;
394
0
                }
395
396
                // Direct variant.
397
0
                add_hwdec_item(infos, num_infos, info);
398
399
                // Copy variant.
400
0
                info.copying = true;
401
0
                if (cfg->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) {
402
0
                    info.use_hw_frames = false;
403
0
                    info.use_hw_device = true;
404
0
                }
405
0
                add_hwdec_item(infos, num_infos, info);
406
407
0
                found_any = true;
408
0
            } else if (cfg->methods & AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
409
0
                struct hwdec_info info = info_template;
410
0
                info.pix_fmt = cfg->pix_fmt;
411
412
0
                const char *name = wrapper;
413
0
                if (!name)
414
0
                    name = av_get_pix_fmt_name(info.pix_fmt);
415
0
                mp_assert(name); // API violation by libavcodec
416
417
0
                snprintf(info.method_name, sizeof(info.method_name), "%s", name);
418
419
                // Direct variant.
420
0
                add_hwdec_item(infos, num_infos, info);
421
422
                // Copy variant.
423
0
                info.copying = true;
424
0
                info.pix_fmt = AV_PIX_FMT_NONE; // trust it can do sw output
425
0
                add_hwdec_item(infos, num_infos, info);
426
427
0
                found_any = true;
428
0
            }
429
0
        }
430
431
12.8M
        if (!found_any && wrapper) {
432
            // We _know_ there's something supported here, usually outputting
433
            // sw surfaces. E.g. mediacodec (before hw_device_ctx support).
434
435
450k
            struct hwdec_info info = info_template;
436
450k
            info.copying = true; // probably
437
438
450k
            snprintf(info.method_name, sizeof(info.method_name), "%s", wrapper);
439
450k
            add_hwdec_item(infos, num_infos, info);
440
450k
        }
441
12.8M
    }
442
443
50.0k
    qsort(*infos, *num_infos, sizeof(struct hwdec_info), hwdec_compare);
444
50.0k
}
445
446
static bool hwdec_codec_allowed(struct mp_filter *vd, const char *codec)
447
43
{
448
43
    vd_ffmpeg_ctx *ctx = vd->priv;
449
43
    bstr s = bstr0(ctx->hwdec_opts->hwdec_codecs);
450
473
    while (s.len) {
451
430
        bstr item;
452
430
        bstr_split_tok(s, ",", &item, &s);
453
430
        if (bstr_equals0(item, "all") || bstr_equals0(item, codec))
454
0
            return true;
455
430
    }
456
43
    return false;
457
43
}
458
459
static AVBufferRef *hwdec_create_dev(struct mp_filter *vd,
460
                                     struct hwdec_info *hwdec,
461
                                     bool autoprobe)
462
0
{
463
0
    vd_ffmpeg_ctx *ctx = vd->priv;
464
0
    mp_assert(hwdec->lavc_device);
465
466
0
    if (hwdec->copying) {
467
0
        const struct hwcontext_fns *fns =
468
0
            hwdec_get_hwcontext_fns(hwdec->lavc_device);
469
0
        if (fns && fns->create_dev) {
470
0
            struct hwcontext_create_dev_params params = {
471
0
                .probing = autoprobe,
472
0
            };
473
0
            return fns->create_dev(vd->global, vd->log, &params);
474
0
        } else {
475
0
            AVBufferRef* ref = NULL;
476
0
            av_hwdevice_ctx_create(&ref, hwdec->lavc_device, NULL, NULL, 0);
477
0
            return ref;
478
0
        }
479
0
    } else if (ctx->hwdec_devs) {
480
0
        int imgfmt = pixfmt2imgfmt(hwdec->pix_fmt);
481
0
        struct hwdec_imgfmt_request params = {
482
0
            .imgfmt = imgfmt,
483
0
            .probing = autoprobe,
484
0
        };
485
0
        hwdec_devices_request_for_img_fmt(ctx->hwdec_devs, &params);
486
487
0
        const struct mp_hwdec_ctx *hw_ctx =
488
0
            hwdec_devices_get_by_imgfmt_and_type(ctx->hwdec_devs, imgfmt,
489
0
                                                 hwdec->lavc_device);
490
491
0
        if (hw_ctx && hw_ctx->av_device_ref)
492
0
            return av_buffer_ref(hw_ctx->av_device_ref);
493
0
    }
494
495
0
    return NULL;
496
0
}
497
498
// Select if and which hwdec to use. Also makes sure to get the decode device.
499
static void select_and_set_hwdec(struct mp_filter *vd)
500
45.5k
{
501
45.5k
    vd_ffmpeg_ctx *ctx = vd->priv;
502
45.5k
    const char *codec = ctx->codec->codec;
503
504
45.5k
    m_config_cache_update(ctx->hwdec_opts_cache);
505
506
45.5k
    struct hwdec_info *hwdecs = NULL;
507
45.5k
    int num_hwdecs = 0;
508
45.5k
    add_all_hwdec_methods(&hwdecs, &num_hwdecs);
509
510
45.5k
    char **hwdec_api = ctx->hwdec_opts->hwdec_api;
511
45.5k
    for (int i = 0; hwdec_api && hwdec_api[i]; i++) {
512
45.5k
        bstr opt = bstr0(hwdec_api[i]);
513
514
45.5k
        bool hwdec_requested = !bstr_equals0(opt, "no");
515
45.5k
        bool hwdec_auto_safe = bstr_equals0(opt, "auto") ||
516
45.5k
                            bstr_equals0(opt, "auto-safe") ||
517
45.5k
                            bstr_equals0(opt, "auto-copy") ||
518
45.5k
                            bstr_equals0(opt, "auto-copy-safe") ||
519
45.5k
                            bstr_equals0(opt, "yes") ||
520
45.5k
                            bstr_equals0(opt, "");
521
45.5k
        bool hwdec_auto_unsafe = bstr_equals0(opt, "auto-unsafe");
522
45.5k
        bool hwdec_auto_copy = bstr_equals0(opt, "auto-copy") ||
523
45.5k
                            bstr_equals0(opt, "auto-copy-safe") ||
524
45.5k
                            bstr_equals0(opt, "auto-copy-unsafe");
525
45.5k
        bool hwdec_auto = hwdec_auto_unsafe || hwdec_auto_copy || hwdec_auto_safe;
526
527
45.5k
        if (!hwdec_requested) {
528
45.4k
            MP_VERBOSE(vd, "No hardware decoding requested.\n");
529
45.4k
            break;
530
45.4k
        } else if (!hwdec_codec_allowed(vd, codec)) {
531
43
            MP_VERBOSE(vd, "Not trying to use hardware decoding: codec %s is not "
532
43
                    "on whitelist.\n", codec);
533
43
            break;
534
43
        } else if (ctx->force_swdec) {
535
0
            MP_VERBOSE(vd, "Not trying to use hardware decoding: disallowed\n");
536
0
            break;
537
0
        } else {
538
0
            bool hwdec_name_supported = false;  // relevant only if !hwdec_auto
539
0
            for (int n = 0; n < num_hwdecs; n++) {
540
0
                struct hwdec_info *hwdec = &hwdecs[n];
541
542
0
                if (!hwdec_auto && !(bstr_equals0(opt, hwdec->method_name) ||
543
0
                                    bstr_equals0(opt, hwdec->name)))
544
0
                    continue;
545
0
                hwdec_name_supported = true;
546
547
0
                bool already_attempted = false;
548
0
                for (int j = 0; j < ctx->num_attempted_hwdecs; j++) {
549
0
                    if (bstr_equals0(ctx->attempted_hwdecs[j], hwdec->name)) {
550
0
                        MP_DBG(vd, "Skipping previously attempted hwdec: %s\n",
551
0
                               hwdec->name);
552
0
                        already_attempted = true;
553
0
                        break;
554
0
                    }
555
0
                }
556
0
                if (already_attempted)
557
0
                    continue;
558
559
0
                const char *hw_codec = mp_codec_from_av_codec_id(hwdec->codec->id);
560
0
                if (!hw_codec || strcmp(hw_codec, codec) != 0)
561
0
                    continue;
562
563
0
                if (hwdec_auto_safe && !(hwdec->flags & HWDEC_FLAG_WHITELIST))
564
0
                    continue;
565
566
0
                MP_VERBOSE(vd, "Looking at hwdec %s...\n", hwdec->name);
567
568
                /*
569
                 * Past this point, any kind of failure that results in us
570
                 * looking for a new hwdec should not lead to use trying this
571
                 * hwdec again - so add it to the list, regardless of whether
572
                 * initialisation will succeed or not.
573
                 */
574
0
                MP_TARRAY_APPEND(ctx, ctx->attempted_hwdecs,
575
0
                                 ctx->num_attempted_hwdecs,
576
0
                                 bstrdup(ctx, bstr0(hwdec->name)));
577
578
0
                if (hwdec_auto_copy && !hwdec->copying) {
579
0
                    MP_VERBOSE(vd, "Not using this for auto-copy.\n");
580
0
                    continue;
581
0
                }
582
583
0
                if (hwdec->lavc_device) {
584
0
                    ctx->hwdec_dev = hwdec_create_dev(vd, hwdec, hwdec_auto);
585
0
                    if (!ctx->hwdec_dev) {
586
0
                        MP_VERBOSE(vd, "Could not create device.\n");
587
0
                        continue;
588
0
                    }
589
590
0
                    const struct hwcontext_fns *fns =
591
0
                                hwdec_get_hwcontext_fns(hwdec->lavc_device);
592
0
                    if (fns && fns->is_emulated && fns->is_emulated(ctx->hwdec_dev)) {
593
0
                        if (hwdec_auto) {
594
0
                            MP_VERBOSE(vd, "Not using emulated API.\n");
595
0
                            av_buffer_unref(&ctx->hwdec_dev);
596
0
                            continue;
597
0
                        }
598
0
                        MP_WARN(vd, "Using emulated hardware decoding API.\n");
599
0
                    }
600
0
                } else if (!hwdec->copying) {
601
                    // Most likely METHOD_INTERNAL, which often use delay-loaded
602
                    // VO support as well.
603
0
                    if (ctx->hwdec_devs) {
604
0
                        struct hwdec_imgfmt_request params = {
605
0
                            .imgfmt = pixfmt2imgfmt(hwdec->pix_fmt),
606
0
                            .probing = hwdec_auto,
607
0
                        };
608
0
                        hwdec_devices_request_for_img_fmt(
609
0
                            ctx->hwdec_devs, &params);
610
0
                    }
611
0
                }
612
613
0
                ctx->use_hwdec = true;
614
0
                ctx->hwdec = *hwdec;
615
0
                break;
616
0
            }
617
0
            if (ctx->use_hwdec)
618
0
                break;
619
0
            else if (!hwdec_auto && !hwdec_name_supported)
620
0
                MP_WARN(vd, "Unsupported hwdec: %.*s\n", BSTR_P(opt));
621
0
        }
622
45.5k
    }
623
45.5k
    talloc_free(hwdecs);
624
625
626
45.5k
    if (ctx->use_hwdec) {
627
0
        MP_VERBOSE(vd, "Trying hardware decoding via %s.\n", ctx->hwdec.name);
628
0
        if (strcmp(ctx->decoder, ctx->hwdec.codec->name) != 0)
629
0
            MP_VERBOSE(vd, "Using underlying hw-decoder '%s'\n",
630
0
                       ctx->hwdec.codec->name);
631
45.5k
    } else {
632
        // If software fallback is disabled and we get here, all hwdec must
633
        // have failed. Tell the ctx to always force an eof.
634
45.5k
        if (ctx->hwdec_opts->software_fallback == INT_MAX) {
635
1
            MP_WARN(ctx, "Software decoding fallback is disabled.\n");
636
1
            ctx->force_eof = true;
637
45.5k
        } else {
638
45.5k
            MP_VERBOSE(vd, "Using software decoding.\n");
639
45.5k
        }
640
45.5k
    }
641
45.5k
}
642
643
static int hwdec_opt_help(struct mp_log *log, const m_option_t *opt,
644
                          struct bstr name)
645
4.53k
{
646
4.53k
    struct hwdec_info *hwdecs = NULL;
647
4.53k
    int num_hwdecs = 0;
648
4.53k
    add_all_hwdec_methods(&hwdecs, &num_hwdecs);
649
650
4.53k
    mp_info(log, "Valid values (with alternative full names):\n");
651
652
45.3k
    for (int n = 0; n < num_hwdecs; n++) {
653
40.7k
        struct hwdec_info *hwdec = &hwdecs[n];
654
655
40.7k
        mp_info(log, "  %s (%s)\n", hwdec->method_name, hwdec->name);
656
40.7k
    }
657
658
4.53k
    talloc_free(hwdecs);
659
660
4.53k
    mp_info(log, "  auto (yes '')\n");
661
4.53k
    mp_info(log, "  no\n");
662
4.53k
    mp_info(log, "  auto-safe\n");
663
4.53k
    mp_info(log, "  auto-copy\n");
664
4.53k
    mp_info(log, "  auto-unsafe\n");
665
4.53k
    mp_info(log, "  auto-copy-safe\n");
666
4.53k
    mp_info(log, "  auto-copy-unsafe\n");
667
668
4.53k
    return M_OPT_EXIT;
669
4.53k
}
670
671
static void force_fallback(struct mp_filter *vd)
672
0
{
673
0
    vd_ffmpeg_ctx *ctx = vd->priv;
674
675
0
    uninit_avctx(vd);
676
0
    int lev = ctx->hwdec_notified ? MSGL_WARN : MSGL_V;
677
0
    mp_msg(vd->log, lev, "Attempting next decoding method after failure of %.*s.\n",
678
0
           BSTR_P(ctx->attempted_hwdecs[ctx->num_attempted_hwdecs - 1]));
679
0
    select_and_set_hwdec(vd);
680
0
    init_avctx(vd);
681
0
}
682
683
static void reinit(struct mp_filter *vd)
684
45.5k
{
685
45.5k
    vd_ffmpeg_ctx *ctx = vd->priv;
686
687
45.5k
    uninit_avctx(vd);
688
689
    /*
690
     * Reset attempted hwdecs so that if the hwdec list is reconfigured
691
     * we attempt all of them from the beginning. The most practical
692
     * reason for this is that ctrl+h toggles between `no` and
693
     * `auto`, and we want to reevaluate from a clean slate each time.
694
     */
695
45.5k
    TA_FREEP(&ctx->attempted_hwdecs);
696
45.5k
    ctx->num_attempted_hwdecs = 0;
697
45.5k
    ctx->hwdec_notified = false;
698
699
45.5k
    select_and_set_hwdec(vd);
700
701
45.5k
    bool use_hwdec = ctx->use_hwdec;
702
45.5k
    init_avctx(vd);
703
45.5k
    if (!ctx->avctx && use_hwdec) {
704
0
        do {
705
0
            force_fallback(vd);
706
0
        } while (!ctx->avctx);
707
0
    }
708
709
    // Wait for the first keyframe after reinit to ensure the decoder state is
710
    // valid and to avoid decoding errors that could cause hwdec to fail and
711
    // fall back immediately after a reinit.
712
45.5k
    ctx->wait_for_keyframe = ctx->use_hwdec ? HWDEC_WAIT_KEYFRAME_COUNT : 0;
713
45.5k
}
714
715
static void init_avctx(struct mp_filter *vd)
716
45.5k
{
717
45.5k
    vd_ffmpeg_ctx *ctx = vd->priv;
718
45.5k
    struct vd_lavc_params *lavc_param = ctx->opts;
719
45.5k
    struct mp_codec_params *c = ctx->codec;
720
721
45.5k
    m_config_cache_update(ctx->opts_cache);
722
723
45.5k
    mp_assert(!ctx->avctx);
724
725
45.5k
    const AVCodec *lavc_codec = NULL;
726
727
45.5k
    if (ctx->use_hwdec) {
728
0
        lavc_codec = ctx->hwdec.codec;
729
45.5k
    } else {
730
45.5k
        lavc_codec = avcodec_find_decoder_by_name(ctx->decoder);
731
45.5k
    }
732
45.5k
    if (!lavc_codec)
733
0
        return;
734
735
45.5k
    const AVCodecDescriptor *desc = avcodec_descriptor_get(lavc_codec->id);
736
45.5k
    ctx->intra_only = desc && (desc->props & AV_CODEC_PROP_INTRA_ONLY);
737
738
45.5k
    ctx->codec_timebase = mp_get_codec_timebase(ctx->codec);
739
740
45.5k
    ctx->hwdec_failed = false;
741
45.5k
    ctx->hwdec_request_reinit = false;
742
45.5k
    ctx->avctx = avcodec_alloc_context3(lavc_codec);
743
45.5k
    AVCodecContext *avctx = ctx->avctx;
744
45.5k
    if (!ctx->avctx)
745
0
        goto error;
746
45.5k
    avctx->codec_type = AVMEDIA_TYPE_VIDEO;
747
45.5k
    avctx->codec_id = lavc_codec->id;
748
45.5k
    avctx->pkt_timebase = ctx->codec_timebase;
749
750
45.5k
    ctx->pic = av_frame_alloc();
751
45.5k
    if (!ctx->pic)
752
0
        goto error;
753
754
45.5k
    ctx->avpkt = av_packet_alloc();
755
45.5k
    if (!ctx->avpkt)
756
0
        goto error;
757
758
45.5k
    int threads = lavc_param->threads;
759
45.5k
    if (ctx->use_hwdec) {
760
0
        avctx->opaque = vd;
761
0
        avctx->hwaccel_flags |= AV_HWACCEL_FLAG_IGNORE_LEVEL;
762
0
        if (!lavc_param->check_hw_profile)
763
0
            avctx->hwaccel_flags |= AV_HWACCEL_FLAG_ALLOW_PROFILE_MISMATCH;
764
765
0
#ifdef AV_HWACCEL_FLAG_UNSAFE_OUTPUT
766
        /*
767
         * This flag primarily exists for nvdec which has a very limited
768
         * output frame pool, which can get exhausted if consumers don't
769
         * release frames quickly. However, as an implementation
770
         * requirement, we have to copy the frames anyway, so we don't
771
         * need this extra implicit copy.
772
         */
773
0
        avctx->hwaccel_flags |= AV_HWACCEL_FLAG_UNSAFE_OUTPUT;
774
0
#endif
775
776
0
        if (ctx->hwdec.use_hw_device) {
777
0
            if (ctx->hwdec_dev)
778
0
                avctx->hw_device_ctx = av_buffer_ref(ctx->hwdec_dev);
779
0
            if (!avctx->hw_device_ctx)
780
0
                goto error;
781
0
        }
782
0
        if (ctx->hwdec.use_hw_frames) {
783
0
            if (!ctx->hwdec_dev)
784
0
                goto error;
785
0
        }
786
787
0
        if (ctx->hwdec.pix_fmt != AV_PIX_FMT_NONE)
788
0
            avctx->get_format = get_format_hwdec;
789
790
        // Some APIs benefit from this, for others it's additional bloat.
791
0
        if (ctx->hwdec.copying)
792
0
            ctx->max_delay_queue = HWDEC_DELAY_QUEUE_COUNT;
793
0
        ctx->hw_probing = true;
794
795
0
        threads = ctx->hwdec_opts->hwdec_threads;
796
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(62, 11, 100)
797
        // Vulkan threading was not safe before 62.11.100
798
        bstr hwdec_name = bstr0(ctx->hwdec.name);
799
        if (bstr_endswith0(hwdec_name, "vulkan") || bstr_endswith0(hwdec_name, "vulkan-copy"))
800
            threads = 1;
801
#endif
802
0
    }
803
804
45.5k
    mp_set_avcodec_threads(vd->log, avctx, threads);
805
806
45.5k
    if (!ctx->use_hwdec && ctx->vo && lavc_param->dr) {
807
45.5k
        avctx->opaque = vd;
808
45.5k
        avctx->get_buffer2 = get_buffer2_direct;
809
45.5k
    }
810
811
45.5k
    avctx->flags |= lavc_param->bitexact ? AV_CODEC_FLAG_BITEXACT : 0;
812
45.5k
    avctx->flags2 |= lavc_param->fast ? AV_CODEC_FLAG2_FAST : 0;
813
814
45.5k
    if (lavc_param->show_all)
815
0
        avctx->flags |= AV_CODEC_FLAG_OUTPUT_CORRUPT;
816
817
45.5k
    avctx->skip_loop_filter = lavc_param->skip_loop_filter;
818
45.5k
    avctx->skip_idct = lavc_param->skip_idct;
819
45.5k
    avctx->skip_frame = lavc_param->skip_frame;
820
45.5k
    avctx->apply_cropping = lavc_param->apply_cropping;
821
822
45.5k
    if (lavc_codec->id == AV_CODEC_ID_H264 && lavc_param->old_x264)
823
0
        av_opt_set(avctx, "x264_build", "150", AV_OPT_SEARCH_CHILDREN);
824
825
45.5k
    switch(ctx->opts->film_grain) {
826
0
    case 0: /*CPU*/
827
        // default lavc flags handle film grain within the decoder.
828
0
        break;
829
0
    case 1: /*GPU*/
830
0
        if (!ctx->vo ||
831
0
            (ctx->vo && !(ctx->vo->driver->caps & VO_CAP_FILM_GRAIN))) {
832
0
            MP_MSG(vd, ctx->vo ? MSGL_WARN : MSGL_V,
833
0
                   "GPU film grain requested, but VO %s, expect wrong output.\n",
834
0
                   ctx->vo ?
835
0
                   "does not support applying film grain" :
836
0
                   "is not available at decoder initialization to verify support");
837
0
        }
838
839
0
        avctx->export_side_data |= AV_CODEC_EXPORT_DATA_FILM_GRAIN;
840
0
        break;
841
45.5k
    default:
842
45.5k
        if (ctx->vo && (ctx->vo->driver->caps & VO_CAP_FILM_GRAIN))
843
0
            avctx->export_side_data |= AV_CODEC_EXPORT_DATA_FILM_GRAIN;
844
845
45.5k
        break;
846
45.5k
    }
847
848
45.5k
    mp_set_avopts(vd->log, avctx, lavc_param->avopts);
849
850
    // Do this after the above avopt handling in case it changes values
851
45.5k
    ctx->skip_frame = avctx->skip_frame;
852
853
45.5k
    if (mp_set_avctx_codec_headers(avctx, c) < 0) {
854
0
        MP_ERR(vd, "Could not set codec parameters.\n");
855
0
        goto error;
856
0
    }
857
858
45.5k
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
859
45.5k
    if (avctx->width > 8192 || avctx->height > 8192) {
860
679
        MP_ERR(vd, "Frame size too big %" PRIu32 "x%" PRIu32 ".\n", avctx->width, avctx->height);
861
679
        goto error;
862
679
    }
863
44.8k
#endif
864
865
    /* open it */
866
44.8k
    if (avcodec_open2(avctx, lavc_codec, NULL) < 0)
867
343
        goto error;
868
869
    // Sometimes, the first packet contains information required for correct
870
    // decoding of the rest of the stream. The only currently known case is the
871
    // x264 build number (encoded in a SEI element), needed to enable a
872
    // workaround for broken 4:4:4 streams produced by older x264 versions.
873
44.5k
    if (lavc_codec->id == AV_CODEC_ID_H264 && c->first_packet) {
874
4.34k
        mp_set_av_packet(ctx->avpkt, c->first_packet, &ctx->codec_timebase);
875
4.34k
        avcodec_send_packet(avctx, ctx->avpkt);
876
4.34k
        avcodec_receive_frame(avctx, ctx->pic);
877
4.34k
        av_frame_unref(ctx->pic);
878
4.34k
        avcodec_flush_buffers(ctx->avctx);
879
4.34k
    }
880
881
44.5k
    return;
882
883
1.02k
error:
884
1.02k
    MP_ERR(vd, "Could not open codec.\n");
885
1.02k
    uninit_avctx(vd);
886
1.02k
}
887
888
static void reset_avctx(struct mp_filter *vd)
889
131k
{
890
131k
    vd_ffmpeg_ctx *ctx = vd->priv;
891
892
131k
    if (ctx->avctx && avcodec_is_open(ctx->avctx))
893
84.3k
        avcodec_flush_buffers(ctx->avctx);
894
131k
    ctx->flushing = false;
895
131k
    ctx->hwdec_request_reinit = false;
896
    // Wait for the first keyframe after reset to ensure the decoder state is
897
    // valid. Seeking should already jump to a keyframe, so this is safe.
898
131k
    ctx->wait_for_keyframe = ctx->use_hwdec ? HWDEC_WAIT_KEYFRAME_COUNT : 0;
899
131k
}
900
901
static void flush_all(struct mp_filter *vd)
902
94.5k
{
903
94.5k
    vd_ffmpeg_ctx *ctx = vd->priv;
904
905
94.5k
    for (int n = 0; n < ctx->num_delay_queue; n++)
906
0
        talloc_free(ctx->delay_queue[n]);
907
94.5k
    ctx->num_delay_queue = 0;
908
909
94.5k
    for (int n = 0; n < ctx->num_sent_packets; n++)
910
0
        talloc_free(ctx->sent_packets[n]);
911
94.5k
    ctx->num_sent_packets = 0;
912
913
94.5k
    for (int n = 0; n < ctx->num_requeue_packets; n++)
914
0
        talloc_free(ctx->requeue_packets[n]);
915
94.5k
    ctx->num_requeue_packets = 0;
916
917
94.5k
    reset_avctx(vd);
918
94.5k
}
919
920
static void uninit_avctx(struct mp_filter *vd)
921
92.0k
{
922
92.0k
    vd_ffmpeg_ctx *ctx = vd->priv;
923
924
92.0k
    flush_all(vd);
925
92.0k
    av_frame_free(&ctx->pic);
926
92.0k
    mp_free_av_packet(&ctx->avpkt);
927
92.0k
    av_buffer_unref(&ctx->cached_hw_frames_ctx);
928
929
92.0k
    avcodec_free_context(&ctx->avctx);
930
931
92.0k
    av_buffer_unref(&ctx->hwdec_dev);
932
933
92.0k
    ctx->hwdec_failed = false;
934
92.0k
    ctx->hwdec_fail_count = 0;
935
92.0k
    ctx->max_delay_queue = 0;
936
92.0k
    ctx->hw_probing = false;
937
92.0k
    ctx->hwdec = (struct hwdec_info){0};
938
92.0k
    ctx->use_hwdec = false;
939
92.0k
}
940
941
static int init_generic_hwaccel(struct AVCodecContext *avctx, enum AVPixelFormat hw_fmt)
942
0
{
943
0
    struct mp_filter *vd = avctx->opaque;
944
0
    vd_ffmpeg_ctx *ctx = vd->priv;
945
0
    AVBufferRef *new_frames_ctx = NULL;
946
947
0
    if (!ctx->hwdec.use_hw_frames)
948
0
        return 0;
949
950
0
    if (!ctx->hwdec_dev) {
951
0
        MP_ERR(ctx, "Missing device context.\n");
952
0
        goto error;
953
0
    }
954
955
0
    if (avcodec_get_hw_frames_parameters(avctx,
956
0
                                ctx->hwdec_dev, hw_fmt, &new_frames_ctx) < 0)
957
0
    {
958
0
        MP_VERBOSE(ctx, "Hardware decoding of this stream is unsupported?\n");
959
0
        goto error;
960
0
    }
961
962
0
    AVHWFramesContext *new_fctx = (void *)new_frames_ctx->data;
963
964
0
    if (ctx->hwdec_opts->hwdec_image_format)
965
0
        new_fctx->sw_format = imgfmt2pixfmt(ctx->hwdec_opts->hwdec_image_format);
966
967
    // 1 surface is already included by libavcodec. The field is 0 if the
968
    // hwaccel supports dynamic surface allocation.
969
0
    if (new_fctx->initial_pool_size)
970
0
        new_fctx->initial_pool_size += ctx->hwdec_opts->hwdec_extra_frames - 1;
971
972
0
    const struct hwcontext_fns *fns =
973
0
        hwdec_get_hwcontext_fns(new_fctx->device_ctx->type);
974
975
0
    if (fns && fns->refine_hwframes)
976
0
        fns->refine_hwframes(new_frames_ctx);
977
978
    // We might be able to reuse a previously allocated frame pool.
979
0
    if (ctx->cached_hw_frames_ctx) {
980
0
        AVHWFramesContext *old_fctx = (void *)ctx->cached_hw_frames_ctx->data;
981
982
0
        if (new_fctx->format            != old_fctx->format ||
983
0
            new_fctx->sw_format         != old_fctx->sw_format ||
984
0
            new_fctx->width             != old_fctx->width ||
985
0
            new_fctx->height            != old_fctx->height ||
986
0
            new_fctx->initial_pool_size != old_fctx->initial_pool_size)
987
0
            av_buffer_unref(&ctx->cached_hw_frames_ctx);
988
0
    }
989
990
0
    if (!ctx->cached_hw_frames_ctx) {
991
0
        if (av_hwframe_ctx_init(new_frames_ctx) < 0) {
992
0
            MP_ERR(ctx, "Failed to allocate hw frames.\n");
993
0
            goto error;
994
0
        }
995
996
0
        ctx->cached_hw_frames_ctx = new_frames_ctx;
997
0
        new_frames_ctx = NULL;
998
0
    }
999
1000
0
    avctx->hw_frames_ctx = av_buffer_ref(ctx->cached_hw_frames_ctx);
1001
0
    if (!avctx->hw_frames_ctx)
1002
0
        goto error;
1003
1004
0
    av_buffer_unref(&new_frames_ctx);
1005
0
    return 0;
1006
1007
0
error:
1008
0
    av_buffer_unref(&new_frames_ctx);
1009
0
    av_buffer_unref(&ctx->cached_hw_frames_ctx);
1010
0
    return -1;
1011
0
}
1012
1013
static enum AVPixelFormat get_format_hwdec(struct AVCodecContext *avctx,
1014
                                           const enum AVPixelFormat *fmt)
1015
0
{
1016
0
    struct mp_filter *vd = avctx->opaque;
1017
0
    vd_ffmpeg_ctx *ctx = vd->priv;
1018
1019
0
    MP_VERBOSE(vd, "Pixel formats supported by decoder:");
1020
0
    for (int i = 0; fmt[i] != AV_PIX_FMT_NONE; i++)
1021
0
        MP_VERBOSE(vd, " %s", av_get_pix_fmt_name(fmt[i]));
1022
0
    MP_VERBOSE(vd, "\n");
1023
1024
0
    const char *profile = avcodec_profile_name(avctx->codec_id, avctx->profile);
1025
0
    MP_VERBOSE(vd, "Codec profile: %s (0x%x)\n", profile ? profile : "unknown",
1026
0
               avctx->profile);
1027
1028
0
    mp_assert(ctx->use_hwdec);
1029
1030
0
    ctx->hwdec_request_reinit |= ctx->hwdec_failed;
1031
0
    ctx->hwdec_failed = false;
1032
1033
0
    enum AVPixelFormat select = AV_PIX_FMT_NONE;
1034
0
    for (int i = 0; fmt[i] != AV_PIX_FMT_NONE; i++) {
1035
0
        if (ctx->hwdec.pix_fmt == fmt[i]) {
1036
0
            if (init_generic_hwaccel(avctx, fmt[i]) < 0)
1037
0
                break;
1038
0
            select = fmt[i];
1039
0
            break;
1040
0
        }
1041
0
    }
1042
1043
0
    if (select == AV_PIX_FMT_NONE)
1044
0
        ctx->hwdec_failed = true;
1045
1046
0
    const char *name = av_get_pix_fmt_name(select);
1047
0
    MP_VERBOSE(vd, "Requesting pixfmt '%s' from decoder.\n", name ? name : "-");
1048
0
    return select;
1049
0
}
1050
1051
static int get_buffer2_direct(AVCodecContext *avctx, AVFrame *pic, int flags)
1052
515k
{
1053
515k
    struct mp_filter *vd = avctx->opaque;
1054
515k
    vd_ffmpeg_ctx *p = vd->priv;
1055
1056
515k
    mp_mutex_lock(&p->dr_lock);
1057
1058
515k
    int w = pic->width;
1059
515k
    int h = pic->height;
1060
515k
    int linesize_align[AV_NUM_DATA_POINTERS] = {0};
1061
515k
    avcodec_align_dimensions2(avctx, &w, &h, linesize_align);
1062
1063
    // We assume that different alignments are just different power-of-2s.
1064
    // Thus, a higher alignment always satisfies a lower alignment.
1065
515k
    int stride_align = MP_IMAGE_BYTE_ALIGN;
1066
4.63M
    for (int n = 0; n < AV_NUM_DATA_POINTERS; n++)
1067
4.12M
        stride_align = MPMAX(stride_align, linesize_align[n]);
1068
1069
    // Note: texel sizes may be NPOT, so use full lcm instead of max
1070
515k
    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
1071
515k
    if (!(desc->flags & AV_PIX_FMT_FLAG_BITSTREAM)) {
1072
1.54M
        for (int n = 0; n < desc->nb_components; n++)
1073
1.04M
            stride_align = mp_lcm(stride_align, desc->comp[n].step);
1074
494k
    }
1075
1076
515k
    int imgfmt = pixfmt2imgfmt(pic->format);
1077
515k
    if (!imgfmt)
1078
0
        goto fallback;
1079
1080
515k
    if (p->dr_failed)
1081
494k
        goto fallback;
1082
1083
    // (For simplicity, we realloc on any parameter change, instead of trying
1084
    // to be clever.)
1085
21.3k
    if (stride_align != p->dr_stride_align || w != p->dr_w || h != p->dr_h ||
1086
0
        imgfmt != p->dr_imgfmt)
1087
21.3k
    {
1088
21.3k
        mp_image_pool_clear(p->dr_pool);
1089
21.3k
        p->dr_imgfmt = imgfmt;
1090
21.3k
        p->dr_w = w;
1091
21.3k
        p->dr_h = h;
1092
21.3k
        p->dr_stride_align = stride_align;
1093
21.3k
        MP_DBG(p, "DR parameter change to %dx%d %s align=%d\n", w, h,
1094
21.3k
               mp_imgfmt_to_name(imgfmt), stride_align);
1095
21.3k
    }
1096
1097
21.3k
    struct mp_image *img = mp_image_pool_get_no_alloc(p->dr_pool, imgfmt, w, h);
1098
21.3k
    if (!img) {
1099
21.3k
        bool host_cached = p->opts->dr == -1; // auto
1100
21.3k
        int dr_flags = host_cached ? VO_DR_FLAG_HOST_CACHED : 0;
1101
21.3k
        MP_DBG(p, "Allocating new%s DR image...\n", host_cached ? " (host-cached)" : "");
1102
21.3k
        img = vo_get_image(p->vo, imgfmt, w, h, stride_align, dr_flags);
1103
21.3k
        if (!img) {
1104
21.3k
            MP_DBG(p, "...failed..\n");
1105
21.3k
            goto fallback;
1106
21.3k
        }
1107
1108
        // Now make the mp_image part of the pool. This requires doing magic to
1109
        // the image, so just add it to the pool and get it back to avoid
1110
        // dealing with magic ourselves. (Normally this never fails.)
1111
0
        mp_image_pool_add(p->dr_pool, img);
1112
0
        img = mp_image_pool_get_no_alloc(p->dr_pool, imgfmt, w, h);
1113
0
        if (!img)
1114
0
            goto fallback;
1115
0
    }
1116
1117
    // get_buffer2 callers seem very unappreciative of overwriting pic with a
1118
    // new reference. The AVCodecContext.get_buffer2 comments tell us exactly
1119
    // what we should do, so follow that.
1120
0
    for (int n = 0; n < 4; n++) {
1121
0
        pic->data[n] = img->planes[n];
1122
0
        pic->linesize[n] = img->stride[n];
1123
0
        pic->buf[n] = img->bufs[n];
1124
0
        img->bufs[n] = NULL;
1125
0
    }
1126
0
    talloc_free(img);
1127
1128
0
    mp_mutex_unlock(&p->dr_lock);
1129
1130
0
    return 0;
1131
1132
515k
fallback:
1133
515k
    if (!p->dr_failed)
1134
515k
        MP_VERBOSE(p, "DR failed - disabling.\n");
1135
515k
    p->dr_failed = true;
1136
515k
    mp_mutex_unlock(&p->dr_lock);
1137
1138
515k
    return avcodec_default_get_buffer2(avctx, pic, flags);
1139
21.3k
}
1140
1141
static void prepare_decoding(struct mp_filter *vd)
1142
3.70M
{
1143
3.70M
    vd_ffmpeg_ctx *ctx = vd->priv;
1144
3.70M
    AVCodecContext *avctx = ctx->avctx;
1145
3.70M
    struct vd_lavc_params *opts = ctx->opts;
1146
1147
3.70M
    if (!avctx)
1148
0
        return;
1149
1150
3.70M
    int drop = ctx->framedrop_flags;
1151
3.70M
    if (drop == 1) {
1152
0
        avctx->skip_frame = opts->framedrop;    // normal framedrop
1153
3.70M
    } else if (drop == 2) {
1154
0
        avctx->skip_frame = AVDISCARD_NONREF;   // hr-seek framedrop
1155
        // Can be much more aggressive for true intra codecs.
1156
0
        if (ctx->intra_only)
1157
0
            avctx->skip_frame = AVDISCARD_ALL;
1158
3.70M
    } else {
1159
3.70M
        avctx->skip_frame = ctx->skip_frame;    // normal playback
1160
3.70M
    }
1161
1162
3.70M
    if (ctx->hwdec_request_reinit)
1163
0
        reset_avctx(vd);
1164
3.70M
}
1165
1166
static void handle_err(struct mp_filter *vd)
1167
293k
{
1168
293k
    vd_ffmpeg_ctx *ctx = vd->priv;
1169
293k
    struct hwdec_opts *hwdec_opts = ctx->hwdec_opts;
1170
1171
293k
    MP_WARN(vd, "Error while decoding frame%s!\n",
1172
293k
            ctx->use_hwdec ? " (hardware decoding)" : "");
1173
1174
293k
    if (ctx->use_hwdec) {
1175
0
        ctx->hwdec_fail_count += 1;
1176
0
        if (ctx->hwdec_fail_count >= hwdec_opts->software_fallback)
1177
0
            ctx->hwdec_failed = true;
1178
0
    }
1179
293k
}
1180
1181
static int send_packet(struct mp_filter *vd, struct demux_packet *pkt)
1182
1.07M
{
1183
1.07M
    vd_ffmpeg_ctx *ctx = vd->priv;
1184
1.07M
    AVCodecContext *avctx = ctx->avctx;
1185
1186
1.07M
    if (ctx->num_requeue_packets && ctx->requeue_packets[0] != pkt)
1187
0
        return AVERROR(EAGAIN); // cannot consume the packet
1188
1189
1.07M
    if (ctx->hwdec_failed)
1190
0
        return AVERROR(EAGAIN);
1191
1192
1.07M
    if (!ctx->avctx)
1193
0
        return AVERROR_EOF;
1194
1195
1.07M
    prepare_decoding(vd);
1196
1197
1.07M
    if (ctx->wait_for_keyframe > 0 && pkt) {
1198
0
        if (!pkt->keyframe && !ctx->intra_only) {
1199
0
            MP_DBG(vd, "Waiting for keyframe after reinit (dropping frame).\n");
1200
0
            ctx->wait_for_keyframe--;
1201
0
            return 0;
1202
0
        }
1203
0
        ctx->wait_for_keyframe = 0;
1204
0
    }
1205
1206
1.07M
    if (avctx->skip_frame == AVDISCARD_ALL)
1207
0
        return 0;
1208
1209
1.07M
    mp_set_av_packet(ctx->avpkt, pkt, &ctx->codec_timebase);
1210
1211
1.07M
    int ret = avcodec_send_packet(avctx, pkt ? ctx->avpkt : NULL);
1212
1.07M
    if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
1213
0
        return ret;
1214
1215
1.07M
    if (ctx->hw_probing && ctx->num_sent_packets < 32 &&
1216
0
        ctx->hwdec_opts->software_fallback <= 32)
1217
0
    {
1218
0
        pkt = pkt ? demux_copy_packet(vd->packet_pool, pkt) : NULL;
1219
0
        MP_TARRAY_APPEND(ctx, ctx->sent_packets, ctx->num_sent_packets, pkt);
1220
0
    }
1221
1222
1.07M
    if (ret < 0)
1223
264k
        handle_err(vd);
1224
1.07M
    return ret;
1225
1.07M
}
1226
1227
static void send_queued_packet(struct mp_filter *vd)
1228
0
{
1229
0
    vd_ffmpeg_ctx *ctx = vd->priv;
1230
1231
0
    mp_assert(ctx->num_requeue_packets);
1232
1233
0
    if (send_packet(vd, ctx->requeue_packets[0]) != AVERROR(EAGAIN)) {
1234
0
        talloc_free(ctx->requeue_packets[0]);
1235
0
        MP_TARRAY_REMOVE_AT(ctx->requeue_packets, ctx->num_requeue_packets, 0);
1236
0
    }
1237
0
}
1238
1239
// Returns whether decoder is still active (!EOF state).
1240
static int decode_frame(struct mp_filter *vd)
1241
2.63M
{
1242
2.63M
    vd_ffmpeg_ctx *ctx = vd->priv;
1243
2.63M
    AVCodecContext *avctx = ctx->avctx;
1244
1245
2.63M
    if (!avctx || ctx->force_eof)
1246
1
        return AVERROR_EOF;
1247
1248
2.63M
    prepare_decoding(vd);
1249
1250
    // Re-send old packets (typically after a hwdec fallback during init).
1251
2.63M
    if (ctx->num_requeue_packets)
1252
0
        send_queued_packet(vd);
1253
1254
2.63M
    int ret = avcodec_receive_frame(avctx, ctx->pic);
1255
2.63M
    if (ret < 0) {
1256
2.24M
        if (ret == AVERROR_EOF) {
1257
            // If flushing was initialized earlier and has ended now, make it
1258
            // start over in case we get new packets at some point in the future.
1259
            // This must take the delay queue into account, so avctx returns EOF
1260
            // until the delay queue has been drained.
1261
37.3k
            if (!ctx->num_delay_queue)
1262
37.3k
                reset_avctx(vd);
1263
2.21M
        } else if (ret == AVERROR(EAGAIN)) {
1264
            // just retry after caller writes a packet
1265
2.18M
        } else {
1266
28.8k
            handle_err(vd);
1267
28.8k
        }
1268
2.24M
        return ret;
1269
2.24M
    }
1270
1271
383k
    mp_codec_info_from_av(avctx, ctx->codec);
1272
1273
    // If something was decoded successfully, it must return a frame with valid
1274
    // data.
1275
383k
    mp_assert(ctx->pic->buf[0]);
1276
1277
383k
    struct mp_image *mpi = mp_image_from_av_frame(ctx->pic);
1278
383k
    if (!mpi) {
1279
0
        av_frame_unref(ctx->pic);
1280
0
        return ret;
1281
0
    }
1282
1283
383k
    if (mpi->imgfmt == IMGFMT_CUDA && !mpi->planes[0]) {
1284
0
        MP_ERR(vd, "CUDA frame without data. This is a FFmpeg bug.\n");
1285
0
        talloc_free(mpi);
1286
0
        handle_err(vd);
1287
0
        return AVERROR_BUG;
1288
0
    }
1289
1290
383k
    ctx->hwdec_fail_count = 0;
1291
1292
383k
    mpi->pts = mp_pts_from_av(ctx->pic->pts, &ctx->codec_timebase);
1293
383k
    mpi->dts = mp_pts_from_av(ctx->pic->pkt_dts, &ctx->codec_timebase);
1294
383k
    mpi->pkt_duration = mp_pts_from_av(ctx->pic->duration, &ctx->codec_timebase);
1295
1296
383k
    av_frame_unref(ctx->pic);
1297
1298
383k
    MP_TARRAY_APPEND(ctx, ctx->delay_queue, ctx->num_delay_queue, mpi);
1299
383k
    return ret;
1300
383k
}
1301
1302
static int receive_frame(struct mp_filter *vd, struct mp_frame *out_frame)
1303
2.63M
{
1304
2.63M
    vd_ffmpeg_ctx *ctx = vd->priv;
1305
1306
2.63M
    int ret = decode_frame(vd);
1307
1308
2.63M
    if (ctx->hwdec_failed) {
1309
        // Failed hardware decoding? Try the next one, and eventually software.
1310
0
        struct demux_packet **pkts = ctx->sent_packets;
1311
0
        int num_pkts = ctx->num_sent_packets;
1312
0
        ctx->sent_packets = NULL;
1313
0
        ctx->num_sent_packets = 0;
1314
1315
        /*
1316
         * We repeatedly force_fallback until we get an avctx, because there are
1317
         * certain hwdecs that are really full decoders, and so if these fail,
1318
         * they also fail to give us a valid avctx, and the early return path
1319
         * here will simply give up on decoding completely if there is no
1320
         * decoder. We should never hit an infinite loop as the hwdec list is
1321
         * finite and we will eventually exhaust it and fall back to software
1322
         * decoding (and in practice, most hwdecs are hwaccels and so the
1323
         * decoder will successfully init even if the hwaccel fails later.)
1324
         */
1325
0
        do {
1326
0
            force_fallback(vd);
1327
0
        } while (!ctx->avctx);
1328
1329
0
        ctx->requeue_packets = pkts;
1330
0
        ctx->num_requeue_packets = num_pkts;
1331
1332
0
        return 0; // force retry
1333
0
    }
1334
1335
2.63M
    if (ret == AVERROR(EAGAIN) && ctx->num_requeue_packets)
1336
0
        return 0; // force retry, so send_queued_packet() gets called
1337
1338
2.63M
    if (ctx->num_delay_queue <= ctx->max_delay_queue && ret != AVERROR_EOF)
1339
2.21M
        return ret;
1340
1341
420k
    if (!ctx->num_delay_queue)
1342
37.3k
        return ret;
1343
1344
383k
    struct mp_image *res = ctx->delay_queue[0];
1345
383k
    MP_TARRAY_REMOVE_AT(ctx->delay_queue, ctx->num_delay_queue, 0);
1346
1347
383k
    res = res ? mp_img_swap_to_native(res) : NULL;
1348
383k
    if (!res)
1349
0
        return AVERROR_UNKNOWN;
1350
1351
383k
    if (ctx->use_hwdec && ctx->hwdec.copying && res->hwctx) {
1352
0
        struct mp_image *sw = mp_image_hw_download(res, ctx->hwdec_swpool);
1353
0
        mp_image_unrefp(&res);
1354
0
        res = sw;
1355
0
        if (!res) {
1356
0
            MP_ERR(vd, "Could not copy back hardware decoded frame.\n");
1357
0
            ctx->hwdec_fail_count = INT_MAX - 1; // force fallback
1358
0
            handle_err(vd);
1359
0
            return AVERROR_UNKNOWN;
1360
0
        }
1361
0
    }
1362
1363
383k
    if (!ctx->hwdec_notified) {
1364
22.3k
        if (ctx->use_hwdec) {
1365
0
            MP_INFO(vd, "Using hardware decoding (%s).\n",
1366
0
                    ctx->hwdec.method_name);
1367
22.3k
        } else {
1368
22.3k
            MP_VERBOSE(vd, "Using software decoding.\n");
1369
22.3k
        }
1370
22.3k
        ctx->hwdec_notified = true;
1371
22.3k
    }
1372
1373
383k
    if (ctx->hw_probing) {
1374
0
        for (int n = 0; n < ctx->num_sent_packets; n++)
1375
0
            demux_packet_pool_push(vd->packet_pool, ctx->sent_packets[n]);
1376
0
        ctx->num_sent_packets = 0;
1377
0
        ctx->hw_probing = false;
1378
0
    }
1379
1380
383k
    *out_frame = MAKE_FRAME(MP_FRAME_VIDEO, res);
1381
383k
    return 0;
1382
383k
}
1383
1384
static int control(struct mp_filter *vd, enum dec_ctrl cmd, void *arg)
1385
1.93M
{
1386
1.93M
    vd_ffmpeg_ctx *ctx = vd->priv;
1387
1.93M
    switch (cmd) {
1388
1.07M
    case VDCTRL_SET_FRAMEDROP:
1389
1.07M
        ctx->framedrop_flags = *(int *)arg;
1390
1.07M
        return CONTROL_TRUE;
1391
405k
    case VDCTRL_CHECK_FORCED_EOF: {
1392
405k
        *(bool *)arg = ctx->force_eof;
1393
405k
        return CONTROL_TRUE;
1394
0
    }
1395
1.27k
    case VDCTRL_GET_BFRAMES: {
1396
1.27k
        AVCodecContext *avctx = ctx->avctx;
1397
1.27k
        if (!avctx)
1398
0
            break;
1399
1.27k
        *(int *)arg = avctx->has_b_frames;
1400
1.27k
        return CONTROL_TRUE;
1401
1.27k
    }
1402
449k
    case VDCTRL_GET_HWDEC: {
1403
449k
        if (!ctx->hwdec_notified)
1404
78.6k
            return CONTROL_FALSE;
1405
371k
        *(char **)arg = ctx->use_hwdec ? ctx->hwdec.method_name : NULL;
1406
371k
        return CONTROL_TRUE;
1407
449k
    }
1408
0
    case VDCTRL_FORCE_HWDEC_FALLBACK:
1409
0
        if (ctx->use_hwdec) {
1410
0
            force_fallback(vd);
1411
0
            return ctx->avctx ? CONTROL_OK : CONTROL_ERROR;
1412
0
        }
1413
0
        return CONTROL_FALSE;
1414
0
    case VDCTRL_REINIT:
1415
0
        reinit(vd);
1416
0
        return CONTROL_TRUE;
1417
1.93M
    }
1418
0
    return CONTROL_UNKNOWN;
1419
1.93M
}
1420
1421
static void vd_lavc_process(struct mp_filter *vd)
1422
2.67M
{
1423
2.67M
    vd_ffmpeg_ctx *ctx = vd->priv;
1424
1425
2.67M
    lavc_process(vd, &ctx->state, send_packet, receive_frame);
1426
2.67M
}
1427
1428
static void vd_lavc_reset(struct mp_filter *vd)
1429
2.47k
{
1430
2.47k
    vd_ffmpeg_ctx *ctx = vd->priv;
1431
1432
2.47k
    flush_all(vd);
1433
1434
2.47k
    ctx->state = (struct lavc_state){0};
1435
2.47k
    ctx->framedrop_flags = 0;
1436
2.47k
}
1437
1438
static void vd_lavc_destroy(struct mp_filter *vd)
1439
45.5k
{
1440
45.5k
    vd_ffmpeg_ctx *ctx = vd->priv;
1441
1442
45.5k
    uninit_avctx(vd);
1443
1444
45.5k
    mp_mutex_destroy(&ctx->dr_lock);
1445
45.5k
}
1446
1447
static const struct mp_filter_info vd_lavc_filter = {
1448
    .name = "vd_lavc",
1449
    .priv_size = sizeof(vd_ffmpeg_ctx),
1450
    .process = vd_lavc_process,
1451
    .reset = vd_lavc_reset,
1452
    .destroy = vd_lavc_destroy,
1453
};
1454
1455
static struct mp_decoder *create(struct mp_filter *parent,
1456
                                 struct mp_codec_params *codec,
1457
                                 const char *decoder)
1458
45.5k
{
1459
45.5k
    struct mp_filter *vd = mp_filter_create(parent, &vd_lavc_filter);
1460
45.5k
    if (!vd)
1461
0
        return NULL;
1462
1463
45.5k
    mp_filter_add_pin(vd, MP_PIN_IN, "in");
1464
45.5k
    mp_filter_add_pin(vd, MP_PIN_OUT, "out");
1465
1466
45.5k
    vd->log = mp_log_new(vd, parent->log, NULL);
1467
1468
45.5k
    vd_ffmpeg_ctx *ctx = vd->priv;
1469
45.5k
    ctx->log = vd->log;
1470
45.5k
    ctx->opts_cache = m_config_cache_alloc(ctx, vd->global, &vd_lavc_conf);
1471
45.5k
    ctx->opts = ctx->opts_cache->opts;
1472
45.5k
    ctx->hwdec_opts_cache = m_config_cache_alloc(ctx, vd->global, &hwdec_conf);
1473
45.5k
    ctx->hwdec_opts = ctx->hwdec_opts_cache->opts;
1474
45.5k
    ctx->codec = codec;
1475
45.5k
    ctx->decoder = talloc_strdup(ctx, decoder);
1476
45.5k
    ctx->hwdec_swpool = mp_image_pool_new(ctx);
1477
45.5k
    ctx->dr_pool = mp_image_pool_new(ctx);
1478
1479
45.5k
    ctx->public.f = vd;
1480
45.5k
    ctx->public.control = control;
1481
1482
45.5k
    mp_mutex_init(&ctx->dr_lock);
1483
1484
    // hwdec/DR
1485
45.5k
    struct mp_stream_info *info = mp_filter_find_stream_info(vd);
1486
45.5k
    if (info) {
1487
45.5k
        ctx->hwdec_devs = info->hwdec_devs;
1488
45.5k
        ctx->vo = info->dr_vo;
1489
45.5k
        ctx->force_swdec = info->force_swdec;
1490
45.5k
    }
1491
1492
45.5k
    reinit(vd);
1493
1494
45.5k
    if (!ctx->avctx) {
1495
1.02k
        talloc_free(vd);
1496
1.02k
        return NULL;
1497
1.02k
    }
1498
1499
44.5k
    codec->codec_desc = ctx->avctx->codec_descriptor->long_name;
1500
1501
44.5k
    return &ctx->public;
1502
45.5k
}
1503
1504
static void add_decoders(struct mp_decoder_list *list)
1505
58.8k
{
1506
58.8k
    mp_add_lavc_decoders(list, AVMEDIA_TYPE_VIDEO);
1507
58.8k
}
1508
1509
const struct mp_decoder_fns vd_lavc = {
1510
    .create = create,
1511
    .add_decoders = add_decoders,
1512
};