Coverage Report

Created: 2026-11-30 06:31

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/mpv/stream/stream_lavf.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 <libavformat/avformat.h>
19
#include <libavformat/avio.h>
20
#include <libavutil/opt.h>
21
22
#include "options/path.h"
23
#include "common/common.h"
24
#include "common/msg.h"
25
#include "common/av_common.h"
26
#include "misc/thread_tools.h"
27
#include "stream.h"
28
#include "network.h"
29
#include "options/m_config.h"
30
#include "options/m_option.h"
31
32
#include "cookies.h"
33
34
#include "misc/bstr.h"
35
#include "mpv_talloc.h"
36
37
#define OPT_BASE_STRUCT struct stream_lavf_opts
38
39
struct stream_lavf_opts {
40
    char **avopts;
41
};
42
43
const struct m_sub_options stream_lavf_conf = {
44
    .opts = (const m_option_t[]) {
45
        {"stream-lavf-o", OPT_KEYVALUELIST(avopts)},
46
        {0}
47
    },
48
    .size = sizeof(struct stream_lavf_opts),
49
};
50
51
static const char *const http_like[] =
52
    {"http", "https", "mmsh", "mmshttp", "httproxy", NULL};
53
54
static int open_f(stream_t *stream);
55
static struct mp_tags *read_icy(stream_t *stream);
56
57
static int fill_buffer(stream_t *s, void *buffer, int max_len)
58
506
{
59
506
    AVIOContext *avio = s->priv;
60
506
    int r = avio_read_partial(avio, buffer, max_len);
61
506
    return (r <= 0) ? -1 : r;
62
506
}
63
64
static int write_buffer(stream_t *s, void *buffer, int len)
65
0
{
66
0
    AVIOContext *avio = s->priv;
67
0
    avio_write(avio, buffer, len);
68
0
    avio_flush(avio);
69
0
    if (avio->error)
70
0
        return -1;
71
0
    return len;
72
0
}
73
74
static int seek(stream_t *s, int64_t newpos)
75
0
{
76
0
    AVIOContext *avio = s->priv;
77
0
    if (avio_seek(avio, newpos, SEEK_SET) < 0) {
78
0
        return 0;
79
0
    }
80
0
    return 1;
81
0
}
82
83
static int64_t get_size(stream_t *s)
84
526
{
85
526
    AVIOContext *avio = s->priv;
86
526
    return avio_size(avio);
87
526
}
88
89
static void close_f(stream_t *stream)
90
526
{
91
526
    AVIOContext *avio = stream->priv;
92
    /* NOTE: As of 2011 write streams must be manually flushed before close.
93
     * Currently write_buffer() always flushes them after writing.
94
     * avio_close() could return an error, but we have no way to return that
95
     * with the current stream API.
96
     */
97
526
    if (avio)
98
526
        avio_close(avio);
99
526
}
100
101
static int control(stream_t *s, int cmd, void *arg)
102
0
{
103
0
    AVIOContext *avio = s->priv;
104
0
    switch(cmd) {
105
0
    case STREAM_CTRL_AVSEEK: {
106
0
        struct stream_avseek *c = arg;
107
0
        int64_t r = avio_seek_time(avio, c->stream_index, c->timestamp, c->flags);
108
0
        if (r >= 0) {
109
0
            stream_drop_buffers(s);
110
0
            return 1;
111
0
        }
112
0
        break;
113
0
    }
114
0
    case STREAM_CTRL_HAS_AVSEEK: {
115
        // Starting at some point, read_seek is always available, and runtime
116
        // behavior decides whether it exists or not. FFmpeg's API doesn't
117
        // return anything helpful to determine seekability upfront, so here's
118
        // a hardcoded whitelist. Not our fault.
119
        // In addition we also have to jump through ridiculous hoops just to
120
        // get the fucking protocol name.
121
0
        const char *proto = NULL;
122
0
        if (avio->av_class && avio->av_class->child_next) {
123
            // This usually yields the URLContext (why does it even exist?),
124
            // which holds the name of the actual protocol implementation.
125
0
            void *child = avio->av_class->child_next(avio, NULL);
126
0
            AVClass *cl = child ? *(AVClass **)child : NULL;
127
0
            if (cl && cl->item_name)
128
0
                proto = cl->item_name(child);
129
0
        }
130
0
        static const char *const has_read_seek[] = {
131
0
            "rtmp", "rtmpt", "rtmpe", "rtmpte", "rtmps", "rtmpts", "mmsh", 0};
132
0
        for (int n = 0; has_read_seek[n]; n++) {
133
0
            if (avio->read_seek && proto && strcmp(proto, has_read_seek[n]) == 0)
134
0
                return 1;
135
0
        }
136
0
        break;
137
0
    }
138
0
    case STREAM_CTRL_GET_METADATA: {
139
0
        *(struct mp_tags **)arg = read_icy(s);
140
0
        if (!*(struct mp_tags **)arg)
141
0
            break;
142
0
        return 1;
143
0
    }
144
0
    }
145
0
    return STREAM_UNSUPPORTED;
146
0
}
147
148
static int interrupt_cb(void *ctx)
149
5.25k
{
150
5.25k
    struct stream *stream = ctx;
151
5.25k
    return mp_cancel_test(stream->cancel);
152
5.25k
}
153
154
static const char * const prefix[] = { "lavf://", "ffmpeg://" };
155
156
void mp_setup_av_network_options(AVDictionary **dict, const char *target_fmt,
157
                                 struct mpv_global *global, struct mp_log *log)
158
2.04k
{
159
2.04k
    void *temp = talloc_new(NULL);
160
2.04k
    struct mp_network_opts *opts =
161
2.04k
        mp_get_config_group(temp, global, &mp_network_conf);
162
163
    // HTTP specific options (other protocols ignore them)
164
2.04k
    if (opts->useragent)
165
2.04k
        av_dict_set(dict, "user_agent", opts->useragent, 0);
166
2.04k
    if (opts->cookies_enabled) {
167
1
        char *file = opts->cookies_file;
168
1
        if (file && file[0])
169
0
            file = mp_get_user_path(temp, global, file);
170
1
        char *cookies = cookies_lavf(temp, global, log, file);
171
1
        if (cookies && cookies[0])
172
0
            av_dict_set(dict, "cookies", cookies, 0);
173
1
    }
174
2.04k
    av_dict_set(dict, "tls_verify", opts->tls_verify ? "1" : "0", 0);
175
2.04k
    if (opts->tls_ca_file) {
176
1
        char *file = mp_get_user_path(temp, global, opts->tls_ca_file);
177
1
        av_dict_set(dict, "ca_file", file, 0);
178
1
    }
179
2.04k
    if (opts->tls_cert_file) {
180
0
        char *file = mp_get_user_path(temp, global, opts->tls_cert_file);
181
0
        av_dict_set(dict, "cert_file", file, 0);
182
0
    }
183
2.04k
    if (opts->tls_key_file) {
184
1
        char *file = mp_get_user_path(temp, global, opts->tls_key_file);
185
1
        av_dict_set(dict, "key_file", file, 0);
186
1
    }
187
2.04k
    char *cust_headers = talloc_strdup(temp, "");
188
2.04k
    if (opts->referrer) {
189
1
        cust_headers = talloc_asprintf_append(cust_headers, "Referer: %s\r\n",
190
1
                                              opts->referrer);
191
1
    }
192
2.04k
    if (opts->http_header_fields) {
193
220
        for (int n = 0; opts->http_header_fields[n]; n++) {
194
198
            cust_headers = talloc_asprintf_append(cust_headers, "%s\r\n",
195
198
                                                  opts->http_header_fields[n]);
196
198
        }
197
22
    }
198
2.04k
    if (strlen(cust_headers))
199
23
        av_dict_set(dict, "headers", cust_headers, 0);
200
2.04k
    av_dict_set(dict, "icy", "1", 0);
201
    // So far, every known protocol uses microseconds for this
202
    // Except rtsp.
203
2.04k
    if (opts->timeout > 0) {
204
2.04k
        if (target_fmt && strcmp(target_fmt, "rtsp") == 0) {
205
0
            mp_verbose(log, "Broken FFmpeg RTSP API => not setting timeout.\n");
206
2.04k
        } else {
207
2.04k
            char buf[80];
208
2.04k
            snprintf(buf, sizeof(buf), "%lld", (long long)(opts->timeout * 1e6));
209
2.04k
            av_dict_set(dict, "timeout", buf, 0);
210
2.04k
        }
211
2.04k
    }
212
2.04k
    if (opts->http_proxy && opts->http_proxy[0])
213
1
        av_dict_set(dict, "http_proxy", opts->http_proxy, 0);
214
215
2.04k
    struct stream_lavf_opts *lavf_opts =
216
2.04k
        mp_get_config_group(temp, global, &stream_lavf_conf);
217
2.04k
    mp_set_avdict(dict, lavf_opts->avopts);
218
219
2.04k
    talloc_free(temp);
220
2.04k
}
221
222
#define PROTO(...) (const char *[]){__VA_ARGS__, NULL}
223
224
// List of safe protocols and their aliases
225
static const char **safe_protos[] = {
226
    PROTO("data"),
227
    PROTO("gopher"),
228
    PROTO("gophers"),
229
    PROTO("http", "dav", "webdav"),
230
    PROTO("httpproxy"),
231
    PROTO("https", "davs", "webdavs"),
232
    PROTO("ipfs"),
233
    PROTO("ipns"),
234
    PROTO("mmsh", "mms", "mmshttp"),
235
    PROTO("mmst"),
236
    PROTO("rist"),
237
    PROTO("rtmp"),
238
    PROTO("rtmpe"),
239
    PROTO("rtmps"),
240
    PROTO("rtmpt"),
241
    PROTO("rtmpte"),
242
    PROTO("rtmpts"),
243
    PROTO("rtp"),
244
    PROTO("srt"),
245
    PROTO("srtp"),
246
    NULL,
247
};
248
249
static char **get_safe_protocols(void)
250
9.31k
{
251
9.31k
    int num = 0;
252
9.31k
    char **protocols = NULL;
253
9.31k
    char **ffmpeg_demuxers = mp_get_lavf_demuxers();
254
9.31k
    char **ffmpeg_protos = mp_get_lavf_protocols();
255
256
111k
    for (int i = 0; ffmpeg_protos[i]; i++) {
257
1.96M
        for (int j = 0; safe_protos[j]; j++) {
258
1.87M
            if (strcmp(ffmpeg_protos[i], safe_protos[j][0]) != 0)
259
1.86M
                continue;
260
18.6k
            for (int k = 0; safe_protos[j][k]; k++)
261
9.31k
                MP_TARRAY_APPEND(NULL, protocols, num, talloc_strdup(protocols, safe_protos[j][k]));
262
9.31k
            break;
263
1.87M
        }
264
102k
    }
265
266
    // rtsp is a demuxer not protocol in ffmpeg so it is handled separately
267
3.40M
    for (int i = 0; ffmpeg_demuxers[i]; i++) {
268
3.39M
        if (strcmp("rtsp", ffmpeg_demuxers[i]) == 0) {
269
0
            MP_TARRAY_APPEND(NULL, protocols, num, talloc_strdup(protocols, "rtsp"));
270
0
            MP_TARRAY_APPEND(NULL, protocols, num, talloc_strdup(protocols, "rtsps"));
271
0
            break;
272
0
        }
273
3.39M
    }
274
275
9.31k
    MP_TARRAY_APPEND(NULL, protocols, num, NULL);
276
277
9.31k
    talloc_free(ffmpeg_demuxers);
278
9.31k
    talloc_free(ffmpeg_protos);
279
280
9.31k
    return protocols;
281
9.31k
}
282
283
static char **get_unsafe_protocols(void)
284
4.59k
{
285
4.59k
    int num = 0;
286
4.59k
    char **protocols = NULL;
287
4.59k
    char **safe_protocols = get_safe_protocols();
288
4.59k
    char **ffmpeg_protos = mp_get_lavf_protocols();
289
290
55.1k
    for (int i = 0; ffmpeg_protos[i]; i++) {
291
50.5k
        bool safe_protocol = false;
292
96.4k
        for (int j = 0; safe_protocols[j]; j++) {
293
50.5k
            if (strcmp(ffmpeg_protos[i], safe_protocols[j]) == 0) {
294
4.59k
                safe_protocol = true;
295
4.59k
                break;
296
4.59k
            }
297
50.5k
        }
298
        // Skip to avoid name conflict with builtin mpv protocol.
299
50.5k
        if (strcmp(ffmpeg_protos[i], "bluray") == 0 || strcmp(ffmpeg_protos[i], "dvd") == 0)
300
0
            continue;
301
302
50.5k
        if (!safe_protocol)
303
45.9k
            MP_TARRAY_APPEND(NULL, protocols, num, talloc_strdup(protocols, ffmpeg_protos[i]));
304
50.5k
    }
305
306
4.59k
    MP_TARRAY_APPEND(NULL, protocols, num, talloc_strdup(protocols, "ffmpeg"));
307
4.59k
    MP_TARRAY_APPEND(NULL, protocols, num, talloc_strdup(protocols, "lavf"));
308
309
4.59k
    MP_TARRAY_APPEND(NULL, protocols, num, NULL);
310
311
4.59k
    talloc_free(ffmpeg_protos);
312
4.59k
    talloc_free(safe_protocols);
313
4.59k
    return protocols;
314
4.59k
}
315
316
// Escape http URLs with unescaped, invalid characters in them.
317
// libavformat's http protocol does not do this, and a patch to add this
318
// in a 100% safe case (spaces only) was rejected.
319
static char *normalize_url(void *ta_parent, const char *filename)
320
2.04k
{
321
2.04k
    bstr proto = mp_split_proto(bstr0(filename), NULL);
322
12.1k
    for (int n = 0; http_like[n]; n++) {
323
10.1k
        if (bstr_equals0(proto, http_like[n]))
324
            // Escape everything but reserved characters.
325
            // Also don't double-scape, so include '%'.
326
37
            return mp_url_escape(ta_parent, filename, ":/?#[]@!$&'()*+,;=%");
327
10.1k
    }
328
2.00k
    return (char *)filename;
329
2.04k
}
330
331
static int open_f(stream_t *stream)
332
2.04k
{
333
2.04k
    AVIOContext *avio = NULL;
334
2.04k
    int res = STREAM_ERROR;
335
2.04k
    AVDictionary *dict = NULL;
336
2.04k
    void *temp = talloc_new(NULL);
337
338
2.04k
    stream->seek = NULL;
339
2.04k
    stream->seekable = false;
340
341
2.04k
    int flags = stream->mode == STREAM_WRITE ? AVIO_FLAG_WRITE : AVIO_FLAG_READ;
342
2.04k
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
343
2.04k
    if (flags & AVIO_FLAG_WRITE)
344
0
        goto out;
345
2.04k
#endif
346
347
2.04k
    const char *filename = stream->url;
348
2.04k
    if (!filename) {
349
0
        MP_ERR(stream, "No URL\n");
350
0
        goto out;
351
0
    }
352
6.13k
    for (int i = 0; i < MP_ARRAY_SIZE(prefix); i++)
353
4.09k
        if (!strncmp(filename, prefix[i], strlen(prefix[i])))
354
222
            filename += strlen(prefix[i]);
355
    // URLs that libavformat handles in a demuxer rather than in a protocol.
356
    // The demuxer opens the URL itself, so there is no stream layer and
357
    // demux_lavf does all the real work.
358
2.04k
    char *lavf_demuxer = NULL;
359
2.04k
    if (!strncmp(filename, "rtsp:", 5) || !strncmp(filename, "rtsps:", 6)) {
360
2
        lavf_demuxer = "rtsp";
361
2.04k
    } else if (!strncmp(filename, "rtp:", 4)) {
362
1
        lavf_demuxer = "rtp";
363
1
    }
364
2.04k
    if (lavf_demuxer) {
365
3
        stream->demuxer = "lavf";
366
3
        stream->lavf_type = lavf_demuxer;
367
3
        stream->streaming = true;
368
3
        if (stream->info->stream_origin == STREAM_ORIGIN_NET)
369
0
            stream->is_network = true;
370
3
        talloc_free(temp);
371
3
        return STREAM_OK;
372
3
    }
373
374
    // Replace "mms://" with "mmsh://", so that most mms:// URLs just work.
375
    // Replace "dav://" or "webdav://" with "http://" and "davs://" or "webdavs://" with "https://"
376
2.04k
    bstr b_filename = bstr0(filename);
377
2.04k
    if (bstr_eatstart0(&b_filename, "mms://") ||
378
2.02k
        bstr_eatstart0(&b_filename, "mmshttp://"))
379
19
    {
380
19
        filename = talloc_asprintf(temp, "mmsh://%.*s", BSTR_P(b_filename));
381
2.02k
    } else if (bstr_eatstart0(&b_filename, "dav://") || bstr_eatstart0(&b_filename, "webdav://"))
382
15
    {
383
15
        filename = talloc_asprintf(temp, "http://%.*s", BSTR_P(b_filename));
384
2.00k
    } else if (bstr_eatstart0(&b_filename, "davs://") || bstr_eatstart0(&b_filename, "webdavs://"))
385
3
    {
386
3
        filename = talloc_asprintf(temp, "https://%.*s", BSTR_P(b_filename));
387
3
    }
388
389
2.04k
    av_dict_set(&dict, "reconnect", "1", 0);
390
2.04k
    av_dict_set(&dict, "reconnect_delay_max", "7", 0);
391
392
2.04k
    mp_setup_av_network_options(&dict, NULL, stream->global, stream->log);
393
394
2.04k
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
395
2.04k
    av_dict_set(&dict, "protocol_blacklist", "fd,pipe", 0);
396
2.04k
#endif
397
398
2.04k
    AVIOInterruptCB cb = {
399
2.04k
        .callback = interrupt_cb,
400
2.04k
        .opaque = stream,
401
2.04k
    };
402
403
2.04k
    filename = normalize_url(stream, filename);
404
405
2.04k
    if (strncmp(filename, "rtmp", 4) == 0) {
406
2
        stream->demuxer = "lavf";
407
2
        stream->lavf_type = "flv";
408
        // Setting timeout enables listen mode - force it to disabled.
409
2
        av_dict_set(&dict, "timeout", "0", 0);
410
2
    }
411
412
2.04k
    int err = avio_open2(&avio, filename, flags, &cb, &dict);
413
2.04k
    if (err < 0) {
414
1.51k
        if (err == AVERROR_PROTOCOL_NOT_FOUND)
415
1.51k
            MP_ERR(stream, "Protocol not found. Make sure"
416
1.51k
                   " FFmpeg is compiled with networking support.\n");
417
1.51k
        goto out;
418
1.51k
    }
419
420
526
    mp_avdict_print_unset(stream->log, MSGL_V, dict);
421
422
526
    if (avio->av_class) {
423
526
        uint8_t *mt = NULL;
424
526
        if (av_opt_get(avio, "mime_type", AV_OPT_SEARCH_CHILDREN, &mt) >= 0) {
425
0
            stream->mime_type = talloc_strdup(stream, mt);
426
0
            av_free(mt);
427
0
        }
428
526
        uint8_t *location = NULL;
429
526
        if (av_opt_get(avio, "location", AV_OPT_SEARCH_CHILDREN, &location) >= 0) {
430
0
            if (*location)
431
0
                stream->effective_url = talloc_strdup(stream, location);
432
0
            av_free(location);
433
0
        }
434
526
    }
435
436
526
    stream->priv = avio;
437
526
    stream->seekable = avio->seekable & AVIO_SEEKABLE_NORMAL;
438
526
    stream->seek = stream->seekable ? seek : NULL;
439
526
    stream->fill_buffer = fill_buffer;
440
526
    stream->write_buffer = write_buffer;
441
526
    stream->get_size = get_size;
442
526
    stream->control = control;
443
526
    stream->close = close_f;
444
    // enable cache (should be avoided for files, but no way to detect this)
445
526
    stream->streaming = true;
446
526
    if (stream->info->stream_origin == STREAM_ORIGIN_NET)
447
107
        stream->is_network = true;
448
526
    res = STREAM_OK;
449
450
2.04k
out:
451
2.04k
    av_dict_free(&dict);
452
2.04k
    talloc_free(temp);
453
2.04k
    return res;
454
526
}
455
456
static struct mp_tags *read_icy(stream_t *s)
457
0
{
458
0
    AVIOContext *avio = s->priv;
459
460
0
    if (!avio->av_class)
461
0
        return NULL;
462
463
0
    uint8_t *icy_header = NULL;
464
0
    if (av_opt_get(avio, "icy_metadata_headers", AV_OPT_SEARCH_CHILDREN,
465
0
                   &icy_header) < 0)
466
0
        icy_header = NULL;
467
468
0
    uint8_t *icy_packet;
469
0
    if (av_opt_get(avio, "icy_metadata_packet", AV_OPT_SEARCH_CHILDREN,
470
0
                   &icy_packet) < 0)
471
0
        icy_packet = NULL;
472
473
    // Send a metadata update only 1. on start, and 2. on a new metadata packet.
474
    // To detect new packages, set the icy_metadata_packet to "-" once we've
475
    // read it (a bit hacky, but works).
476
0
    struct mp_tags *res = NULL;
477
0
    bstr packet = bstr0(icy_packet);
478
0
    if (!bstr_equals0(packet, "-"))
479
0
        res = mp_parse_icy_metadata(s, bstr0(icy_header), packet);
480
481
0
    if (res)
482
0
        av_opt_set(avio, "icy_metadata_packet", "-", AV_OPT_SEARCH_CHILDREN);
483
484
0
    av_free(icy_header);
485
0
    av_free(icy_packet);
486
0
    return res;
487
0
}
488
489
const stream_info_t stream_info_ffmpeg = {
490
    .name = "ffmpeg",
491
    .open = open_f,
492
    .get_protocols = get_safe_protocols,
493
    .can_write = true,
494
    .stream_origin = STREAM_ORIGIN_NET,
495
};
496
497
// Unlike above, this is not marked as safe, and can contain protocols which
498
// may do insecure things. (Such as "ffmpeg", which can access the "lavfi"
499
// pseudo-demuxer, which in turn gives access to filters that can access the
500
// local filesystem.)
501
const stream_info_t stream_info_ffmpeg_unsafe = {
502
    .name = "ffmpeg",
503
    .open = open_f,
504
    .get_protocols = get_unsafe_protocols,
505
    .stream_origin = STREAM_ORIGIN_UNSAFE,
506
    .can_write = true,
507
};