Coverage Report

Created: 2026-09-28 06:42

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/mpv/common/av_common.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 <assert.h>
19
#include <math.h>
20
#include <limits.h>
21
22
#include <libavutil/common.h>
23
#include <libavutil/log.h>
24
#include <libavutil/dict.h>
25
#include <libavutil/opt.h>
26
#include <libavutil/error.h>
27
#include <libavutil/cpu.h>
28
#include <libavcodec/avcodec.h>
29
#include <libavformat/avformat.h>
30
31
#include "config.h"
32
33
#include "audio/chmap_avchannel.h"
34
#include "common/common.h"
35
#include "common/msg.h"
36
#include "demux/packet.h"
37
#include "demux/stheader.h"
38
#include "misc/bstr.h"
39
#include "video/fmt-conversion.h"
40
#include "av_common.h"
41
#include "codecs.h"
42
43
enum AVMediaType mp_to_av_stream_type(int type)
44
27.2k
{
45
27.2k
    switch (type) {
46
15.4k
    case STREAM_VIDEO: return AVMEDIA_TYPE_VIDEO;
47
10.5k
    case STREAM_AUDIO: return AVMEDIA_TYPE_AUDIO;
48
1.31k
    case STREAM_SUB:   return AVMEDIA_TYPE_SUBTITLE;
49
0
    default:           return AVMEDIA_TYPE_UNKNOWN;
50
27.2k
    }
51
27.2k
}
52
53
AVCodecParameters *mp_codec_params_to_av(const struct mp_codec_params *c)
54
109k
{
55
109k
    AVCodecParameters *avp = avcodec_parameters_alloc();
56
109k
    if (!avp)
57
0
        return NULL;
58
59
    // If we have lavf demuxer params, they overwrite by definition any others.
60
109k
    if (c->lav_codecpar) {
61
82.4k
        if (avcodec_parameters_copy(avp, c->lav_codecpar) < 0)
62
0
            goto error;
63
82.4k
        return avp;
64
82.4k
    }
65
66
27.2k
    avp->codec_type = mp_to_av_stream_type(c->type);
67
27.2k
    avp->codec_id = mp_codec_to_av_codec_id(c->codec);
68
27.2k
    avp->codec_tag = c->codec_tag;
69
27.2k
    if (c->extradata_size) {
70
18.7k
        uint8_t *extradata = c->extradata;
71
18.7k
        int size = c->extradata_size;
72
73
18.7k
        if (avp->codec_id == AV_CODEC_ID_FLAC) {
74
            // ffmpeg expects FLAC extradata to be just the STREAMINFO,
75
            // so grab only that (and assume it'll be the first block)
76
81
            if (size >= 8 && !memcmp(c->extradata, "fLaC", 4)) {
77
76
                extradata += 8;
78
76
                size = MPMIN(34, size - 8); // FLAC_STREAMINFO_SIZE
79
76
            }
80
81
        }
81
82
18.7k
        avp->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
83
18.7k
        if (!avp->extradata)
84
0
            goto error;
85
18.7k
        avp->extradata_size = size;
86
18.7k
        memcpy(avp->extradata, extradata, size);
87
18.7k
    }
88
27.2k
    avp->bits_per_coded_sample = c->bits_per_coded_sample;
89
90
    // Video only
91
27.2k
    avp->width = c->disp_w;
92
27.2k
    avp->height = c->disp_h;
93
94
    // Audio only
95
27.2k
    avp->sample_rate = c->samplerate;
96
27.2k
    avp->bit_rate = c->bitrate;
97
27.2k
    avp->block_align = c->block_align;
98
99
27.2k
    mp_chmap_to_av_layout(&avp->ch_layout, &c->channels);
100
101
27.2k
    return avp;
102
0
error:
103
0
    avcodec_parameters_free(&avp);
104
0
    return NULL;
105
27.2k
}
106
107
// Set avctx codec headers for decoding. Returns <0 on failure.
108
int mp_set_avctx_codec_headers(AVCodecContext *avctx, const struct mp_codec_params *c)
109
96.3k
{
110
96.3k
    enum AVMediaType codec_type = avctx->codec_type;
111
96.3k
    enum AVCodecID codec_id = avctx->codec_id;
112
96.3k
    AVCodecParameters *avp = mp_codec_params_to_av(c);
113
96.3k
    if (!avp)
114
0
        return -1;
115
116
96.3k
    int r = avcodec_parameters_to_context(avctx, avp) < 0 ? -1 : 0;
117
96.3k
    avcodec_parameters_free(&avp);
118
119
96.3k
    if (avctx->codec_type != AVMEDIA_TYPE_UNKNOWN)
120
96.3k
        avctx->codec_type = codec_type;
121
96.3k
    if (avctx->codec_id != AV_CODEC_ID_NONE)
122
96.3k
        avctx->codec_id = codec_id;
123
96.3k
    return r;
124
96.3k
}
125
126
// Pick a "good" timebase, which will be used to convert double timestamps
127
// back to fractions for passing them through libavcodec.
128
AVRational mp_get_codec_timebase(const struct mp_codec_params *c)
129
95.3k
{
130
95.3k
    AVRational tb = {c->native_tb_num, c->native_tb_den};
131
95.3k
    if (tb.num < 1 || tb.den < 1) {
132
25.5k
        if (c->reliable_fps)
133
1.92k
            tb = av_inv_q(av_d2q(c->fps, 1000000));
134
25.5k
        if (tb.num < 1 || tb.den < 1)
135
23.6k
            tb = AV_TIME_BASE_Q;
136
25.5k
    }
137
138
    // If the timebase is too coarse, raise its precision, or small adjustments
139
    // to timestamps done between decoder and demuxer could be lost.
140
95.3k
    int64_t den = tb.den;
141
95.3k
    if (av_q2d(tb) > 0.001) {
142
23.0k
        int64_t scaling_num = tb.num * INT64_C(1000);
143
23.0k
        int64_t scaling_den = tb.den;
144
23.0k
        den *= (scaling_num + scaling_den - 1) / scaling_den;
145
23.0k
    }
146
147
95.3k
    av_reduce(&tb.num, &tb.den, tb.num, den, INT_MAX);
148
149
95.3k
    if (tb.num < 1 || tb.den < 1)
150
0
        tb = AV_TIME_BASE_Q;
151
152
95.3k
    return tb;
153
95.3k
}
154
155
static AVRational get_def_tb(AVRational *tb)
156
30.3M
{
157
30.3M
    return tb && tb->num > 0 && tb->den > 0 ? *tb : AV_TIME_BASE_Q;
158
30.3M
}
159
160
// Convert the mpv style timestamp (seconds as double) to a libavcodec style
161
// timestamp (integer units in a given timebase).
162
int64_t mp_pts_to_av(double mp_pts, AVRational *tb)
163
13.2M
{
164
13.2M
    AVRational b = get_def_tb(tb);
165
13.2M
    return mp_pts == MP_NOPTS_VALUE ? AV_NOPTS_VALUE : llrint(mp_pts / av_q2d(b));
166
13.2M
}
167
168
// Inverse of mp_pts_to_av(). (The timebases must be exactly the same.)
169
double mp_pts_from_av(int64_t av_pts, AVRational *tb)
170
17.1M
{
171
17.1M
    AVRational b = get_def_tb(tb);
172
17.1M
    return av_pts == AV_NOPTS_VALUE ? MP_NOPTS_VALUE : av_pts * av_q2d(b);
173
17.1M
}
174
175
// Set dst from mpkt. Note that dst is not refcountable.
176
// mpkt can be NULL to generate empty packets (used to flush delayed data).
177
// Sets pts/dts using mp_pts_to_av(ts, tb). (Be aware of the implications.)
178
// Set duration field only if tb is set.
179
void mp_set_av_packet(AVPacket *dst, struct demux_packet *mpkt, AVRational *tb)
180
6.62M
{
181
6.62M
    dst->side_data = NULL;
182
6.62M
    dst->side_data_elems = 0;
183
6.62M
    dst->buf = NULL;
184
6.62M
    av_packet_unref(dst);
185
186
6.62M
    dst->data = mpkt ? mpkt->buffer : NULL;
187
6.62M
    dst->size = mpkt ? mpkt->len : 0;
188
    /* Some codecs (ZeroCodec, some cases of PNG) may want keyframe info
189
     * from demuxer. */
190
6.62M
    if (mpkt && mpkt->keyframe)
191
5.56M
        dst->flags |= AV_PKT_FLAG_KEY;
192
6.62M
    if (mpkt && mpkt->avpacket) {
193
6.55M
        dst->side_data = mpkt->avpacket->side_data;
194
6.55M
        dst->side_data_elems = mpkt->avpacket->side_data_elems;
195
6.55M
        if (dst->data == mpkt->avpacket->data)
196
6.55M
            dst->buf = mpkt->avpacket->buf;
197
6.55M
        dst->flags |= mpkt->avpacket->flags;
198
6.55M
    }
199
6.62M
    if (mpkt && tb && tb->num > 0 && tb->den > 0)
200
6.55M
        dst->duration = mpkt->duration / av_q2d(*tb);
201
6.62M
    dst->pts = mp_pts_to_av(mpkt ? mpkt->pts : MP_NOPTS_VALUE, tb);
202
6.62M
    dst->dts = mp_pts_to_av(mpkt ? mpkt->dts : MP_NOPTS_VALUE, tb);
203
6.62M
}
204
205
void mp_set_avcodec_threads(struct mp_log *l, AVCodecContext *avctx, int threads)
206
95.0k
{
207
95.0k
    if (threads == 0) {
208
48.1k
        threads = av_cpu_count();
209
48.1k
        if (threads < 1) {
210
0
            mp_warn(l, "Could not determine thread count to use, defaulting to 1.\n");
211
0
            threads = 1;
212
48.1k
        } else {
213
48.1k
            mp_verbose(l, "Detected %d logical cores.\n", threads);
214
48.1k
            if (threads > 1)
215
48.1k
                threads += 1; // extra thread for better load balancing
216
48.1k
        }
217
        // Apparently some libavcodec versions have or had trouble with more
218
        // than 16 threads, and/or print a warning when using > 16.
219
48.1k
        threads = MPMIN(threads, 16);
220
48.1k
    }
221
95.0k
    mp_verbose(l, "Requesting %d threads for decoding.\n", threads);
222
95.0k
    avctx->thread_count = threads;
223
95.0k
}
224
225
static void add_codecs(struct mp_decoder_list *list, enum AVMediaType type,
226
                       bool decoders)
227
113k
{
228
113k
    void *iter = NULL;
229
56.7M
    for (;;) {
230
56.7M
        const AVCodec *cur = av_codec_iterate(&iter);
231
56.7M
        if (!cur)
232
113k
            break;
233
56.6M
        if (av_codec_is_decoder(cur) == decoders &&
234
56.5M
            (type == AVMEDIA_TYPE_UNKNOWN || cur->type == type))
235
27.0M
        {
236
27.0M
            mp_add_decoder(list, mp_codec_from_av_codec_id(cur->id),
237
27.0M
                           cur->name, cur->long_name);
238
27.0M
        }
239
56.6M
    }
240
113k
}
241
242
void mp_add_lavc_decoders(struct mp_decoder_list *list, enum AVMediaType type)
243
113k
{
244
113k
    add_codecs(list, type, true);
245
113k
}
246
247
// (Abuses the decoder list data structures.)
248
void mp_add_lavc_encoders(struct mp_decoder_list *list)
249
237
{
250
237
    add_codecs(list, AVMEDIA_TYPE_UNKNOWN, false);
251
237
}
252
253
char **mp_get_lavf_demuxers(void)
254
64.6k
{
255
64.6k
    char **list = NULL;
256
64.6k
    void *iter = NULL;
257
64.6k
    int num = 0;
258
23.4M
    for (;;) {
259
23.4M
        const AVInputFormat *cur = av_demuxer_iterate(&iter);
260
23.4M
        if (!cur)
261
64.6k
            break;
262
23.3M
        MP_TARRAY_APPEND(NULL, list, num, talloc_strdup(list, cur->name));
263
23.3M
    }
264
64.6k
    MP_TARRAY_APPEND(NULL, list, num, NULL);
265
64.6k
    return list;
266
64.6k
}
267
268
char **mp_get_lavf_protocols(void)
269
90.2k
{
270
90.2k
    char **list = NULL;
271
90.2k
    int num = 0;
272
90.2k
    void *opaque = NULL;
273
90.2k
    const char *name;
274
1.08M
    while ((name = avio_enum_protocols(&opaque, 0)))
275
992k
        MP_TARRAY_APPEND(NULL, list, num, talloc_strdup(list, name));
276
90.2k
    MP_TARRAY_APPEND(NULL, list, num, NULL);
277
90.2k
    return list;
278
90.2k
}
279
280
int mp_codec_to_av_codec_id(const char *codec)
281
95.4k
{
282
95.4k
    int id = AV_CODEC_ID_NONE;
283
95.4k
    if (codec) {
284
94.7k
        const AVCodecDescriptor *desc = avcodec_descriptor_get_by_name(codec);
285
94.7k
        if (desc)
286
90.1k
            id = desc->id;
287
94.7k
        if (id == AV_CODEC_ID_NONE) {
288
4.59k
            const AVCodec *avcodec = avcodec_find_decoder_by_name(codec);
289
4.59k
            if (avcodec)
290
0
                id = avcodec->id;
291
4.59k
        }
292
94.7k
    }
293
95.4k
    return id;
294
95.4k
}
295
296
const char *mp_codec_from_av_codec_id(int codec_id)
297
27.4M
{
298
27.4M
    const char *name = NULL;
299
27.4M
    const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
300
27.4M
    if (desc)
301
27.4M
        name = desc->name;
302
27.4M
    if (!name) {
303
4.52k
        const AVCodec *avcodec = avcodec_find_decoder(codec_id);
304
4.52k
        if (avcodec)
305
0
            name = avcodec->name;
306
4.52k
    }
307
27.4M
    return name;
308
27.4M
}
309
310
bool mp_codec_is_lossless(const char *codec)
311
59.8k
{
312
59.8k
    const AVCodecDescriptor *desc =
313
59.8k
        avcodec_descriptor_get(mp_codec_to_av_codec_id(codec));
314
59.8k
    return desc && (desc->props & AV_CODEC_PROP_LOSSLESS);
315
59.8k
}
316
317
// kv is in the format as by OPT_KEYVALUELIST(): kv[0]=key0, kv[1]=val0, ...
318
// Copy them to the dict.
319
void mp_set_avdict(AVDictionary **dict, char **kv)
320
132k
{
321
132k
    for (int n = 0; kv && kv[n * 2]; n++)
322
0
        av_dict_set(dict, kv[n * 2 + 0], kv[n * 2 + 1], 0);
323
132k
}
324
325
// For use with libav* APIs that take AVDictionaries of options.
326
// Print options remaining in the dict as unset.
327
void mp_avdict_print_unset(struct mp_log *log, int msgl, AVDictionary *dict)
328
101k
{
329
101k
    AVDictionaryEntry *t = NULL;
330
323k
    while ((t = av_dict_get(dict, "", t, AV_DICT_IGNORE_SUFFIX)))
331
222k
        mp_msg(log, msgl, "Could not set AVOption %s='%s'\n", t->key, t->value);
332
101k
}
333
334
// If the name starts with "@", try to interpret it as a number, and set *name
335
// to the name of the n-th parameter.
336
static void resolve_positional_arg(void *avobj, char **name)
337
1.51k
{
338
1.51k
    if (!*name || (*name)[0] != '@' || !avobj)
339
1.19k
        return;
340
341
317
    char *end = NULL;
342
317
    int pos = strtol(*name + 1, &end, 10);
343
317
    if (*end || pos < 0)
344
92
        return;
345
346
225
    const AVOption *opt = NULL;
347
225
    int offset = -1;
348
782
    while (1) {
349
782
        opt = av_opt_next(avobj, opt);
350
782
        if (!opt)
351
53
            return;
352
        // This is what libavfilter's parser does to skip aliases.
353
729
        if (opt->offset != offset && opt->type != AV_OPT_TYPE_CONST)
354
545
            pos--;
355
729
        if (pos < 0) {
356
172
            *name = (char *)opt->name;
357
172
            return;
358
172
        }
359
557
        offset = opt->offset;
360
557
    }
361
225
}
362
363
// kv is in the format as by OPT_KEYVALUELIST(): kv[0]=key0, kv[1]=val0, ...
364
// Set these options on given avobj (using av_opt_set..., meaning avobj must
365
// point to a struct that has AVClass as first member).
366
// Options which fail to set (error or not found) are printed to log.
367
// Returns: >=0 success, <0 failed to set an option
368
int mp_set_avopts(struct mp_log *log, void *avobj, char **kv)
369
104k
{
370
104k
    return mp_set_avopts_pos(log, avobj, avobj, kv);
371
104k
}
372
373
// Like mp_set_avopts(), but the posargs argument is used to resolve positional
374
// arguments. If posargs==NULL, positional args are disabled.
375
int mp_set_avopts_pos(struct mp_log *log, void *avobj, void *posargs, char **kv)
376
104k
{
377
104k
    int success = 0;
378
106k
    for (int n = 0; kv && kv[n * 2]; n++) {
379
1.51k
        char *k = kv[n * 2 + 0];
380
1.51k
        char *v = kv[n * 2 + 1];
381
1.51k
        resolve_positional_arg(posargs, &k);
382
1.51k
        int r = av_opt_set(avobj, k, v, AV_OPT_SEARCH_CHILDREN);
383
1.51k
        if (r == AVERROR_OPTION_NOT_FOUND) {
384
1.34k
            mp_err(log, "AVOption '%s' not found.\n", k);
385
1.34k
            success = -1;
386
1.34k
        } else if (r < 0) {
387
131
            char errstr[80];
388
131
            av_strerror(r, errstr, sizeof(errstr));
389
131
            mp_err(log, "Could not set AVOption %s='%s' (%s)\n", k, v, errstr);
390
131
            success = -1;
391
131
        }
392
1.51k
    }
393
104k
    return success;
394
104k
}
395
396
/**
397
 * Must be used to free an AVPacket that was used with mp_set_av_packet().
398
 *
399
 * We have a particular pattern where we "borrow" buffers and set them
400
 * into an AVPacket to pass data to ffmpeg without extra copies.
401
 * This applies to buf and side_data, so this function clears them before
402
 * freeing.
403
 */
404
void mp_free_av_packet(AVPacket **pkt)
405
147k
{
406
147k
    if (*pkt) {
407
97.4k
        (*pkt)->side_data = NULL;
408
97.4k
        (*pkt)->side_data_elems = 0;
409
97.4k
        (*pkt)->buf = NULL;
410
97.4k
    }
411
147k
    av_packet_free(pkt);
412
147k
}
413
414
void mp_codec_info_from_av(const AVCodecContext *avctx, struct mp_codec_params *c)
415
3.76M
{
416
3.76M
    c->codec_profile = av_get_profile_name(avctx->codec, avctx->profile);
417
3.76M
    if (!c->codec_profile)
418
3.66M
        c->codec_profile = avcodec_profile_name(avctx->codec_id, avctx->profile);
419
3.76M
    c->codec = avctx->codec_descriptor->name;
420
3.76M
    c->codec_desc = avctx->codec_descriptor->long_name;
421
3.76M
    c->decoder = avctx->codec->name;
422
3.76M
    c->decoder_desc = avctx->codec->long_name;
423
3.76M
}
424
425
void mp_codec_info_from_avcodecpar(const AVCodecParameters *avcodecpar, struct mp_codec_params *c)
426
90.2k
{
427
90.2k
    const AVCodec *codec = avcodec_find_decoder(avcodecpar->codec_id);
428
90.2k
    const AVCodecDescriptor *desc = avcodec_descriptor_get(avcodecpar->codec_id);
429
90.2k
    c->codec = mp_codec_from_av_codec_id(avcodecpar->codec_id);
430
90.2k
    if (desc)
431
85.7k
        c->codec_desc = desc->long_name;
432
90.2k
    if (codec) {
433
81.3k
        c->decoder = codec->name;
434
81.3k
        c->decoder_desc = codec->long_name;
435
81.3k
        c->codec_profile = av_get_profile_name(codec, avcodecpar->profile);
436
81.3k
    }
437
90.2k
    if (!c->codec_profile)
438
80.3k
        c->codec_profile = avcodec_profile_name(avcodecpar->codec_id, avcodecpar->profile);
439
90.2k
}