Coverage Report

Created: 2026-11-30 06:48

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/mpv/player/loadfile.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 <stddef.h>
19
#include <stdbool.h>
20
#include <inttypes.h>
21
#include <assert.h>
22
#include <time.h>
23
24
#include <libavutil/avutil.h>
25
26
#include "mpv_talloc.h"
27
28
#include "misc/thread_pool.h"
29
#include "misc/thread_tools.h"
30
#include "osdep/io.h"
31
#include "osdep/terminal.h"
32
#include "osdep/threads.h"
33
#include "osdep/timer.h"
34
35
#include "client.h"
36
#include "common/msg.h"
37
#include "common/msg_control.h"
38
#include "options/path.h"
39
#include "options/m_config.h"
40
#include "options/parse_configfile.h"
41
#include "common/playlist.h"
42
#include "options/options.h"
43
#include "options/m_property.h"
44
#include "common/common.h"
45
#include "common/encode.h"
46
#include "common/stats.h"
47
#include "input/input.h"
48
#include "misc/json.h"
49
#include "misc/language.h"
50
51
#include "audio/out/ao.h"
52
#include "filters/f_decoder_wrapper.h"
53
#include "filters/f_lavfi.h"
54
#include "filters/filter_internal.h"
55
#include "demux/demux.h"
56
#include "stream/stream.h"
57
#include "sub/dec_sub.h"
58
#include "external_files.h"
59
#include "video/out/vo.h"
60
61
#include "core.h"
62
#include "command.h"
63
64
// Called from the demuxer thread if a new packet is available, or other changes.
65
static void wakeup_demux(void *pctx)
66
7.01M
{
67
7.01M
    struct MPContext *mpctx = pctx;
68
7.01M
    mp_wakeup_core(mpctx);
69
7.01M
}
70
71
// Called by foreign threads when playback should be stopped and such.
72
void mp_abort_playback_async(struct MPContext *mpctx)
73
19.2k
{
74
19.2k
    mp_cancel_trigger(mpctx->playback_abort);
75
76
19.2k
    mp_mutex_lock(&mpctx->abort_lock);
77
78
19.6k
    for (int n = 0; n < mpctx->num_abort_list; n++) {
79
412
        struct mp_abort_entry *abort = mpctx->abort_list[n];
80
412
        if (abort->coupled_to_playback)
81
312
            mp_abort_trigger_locked(mpctx, abort);
82
412
    }
83
84
19.2k
    mp_mutex_unlock(&mpctx->abort_lock);
85
19.2k
}
86
87
// Add it to the global list, and allocate required data structures.
88
void mp_abort_add(struct MPContext *mpctx, struct mp_abort_entry *abort)
89
93.3k
{
90
93.3k
    mp_mutex_lock(&mpctx->abort_lock);
91
93.3k
    mp_assert(!abort->cancel);
92
93.3k
    abort->cancel = mp_cancel_new(NULL);
93
93.3k
    MP_TARRAY_APPEND(NULL, mpctx->abort_list, mpctx->num_abort_list, abort);
94
93.3k
    mp_abort_recheck_locked(mpctx, abort);
95
93.3k
    mp_mutex_unlock(&mpctx->abort_lock);
96
93.3k
}
97
98
// Remove Add it to the global list, and free/clear required data structures.
99
// Does not deallocate the abort value itself.
100
void mp_abort_remove(struct MPContext *mpctx, struct mp_abort_entry *abort)
101
93.3k
{
102
93.3k
    mp_mutex_lock(&mpctx->abort_lock);
103
93.3k
    for (int n = 0; n < mpctx->num_abort_list; n++) {
104
93.3k
        if (mpctx->abort_list[n] == abort) {
105
93.3k
            MP_TARRAY_REMOVE_AT(mpctx->abort_list, mpctx->num_abort_list, n);
106
93.3k
            TA_FREEP(&abort->cancel);
107
93.3k
            abort = NULL; // it's not free'd, just clear for the assert below
108
93.3k
            break;
109
93.3k
        }
110
93.3k
    }
111
93.3k
    mp_assert(!abort); // should have been in the list
112
93.3k
    mp_mutex_unlock(&mpctx->abort_lock);
113
93.3k
}
114
115
// Verify whether the abort needs to be signaled after changing certain fields
116
// in abort.
117
void mp_abort_recheck_locked(struct MPContext *mpctx,
118
                             struct mp_abort_entry *abort)
119
94.2k
{
120
94.2k
    if ((abort->coupled_to_playback && mp_cancel_test(mpctx->playback_abort)) ||
121
82.2k
        mpctx->abort_all)
122
12.0k
    {
123
12.0k
        mp_abort_trigger_locked(mpctx, abort);
124
12.0k
    }
125
94.2k
}
126
127
void mp_abort_trigger_locked(struct MPContext *mpctx,
128
                             struct mp_abort_entry *abort)
129
12.3k
{
130
12.3k
    mp_cancel_trigger(abort->cancel);
131
12.3k
}
132
133
static void kill_demuxers_reentrant(struct MPContext *mpctx,
134
                                    struct demuxer **demuxers, int num_demuxers)
135
16.1k
{
136
16.1k
    struct demux_free_async_state **items = NULL;
137
16.1k
    int num_items = 0;
138
139
34.7k
    for (int n = 0; n < num_demuxers; n++) {
140
18.5k
        struct demuxer *d = demuxers[n];
141
142
18.5k
        if (!demux_cancel_test(d)) {
143
            // Make sure it is set if it wasn't yet.
144
18.1k
            demux_set_wakeup_cb(d, wakeup_demux, mpctx);
145
146
18.1k
            struct demux_free_async_state *item = demux_free_async(d);
147
18.1k
            if (item) {
148
14.2k
                MP_TARRAY_APPEND(NULL, items, num_items, item);
149
14.2k
                d = NULL;
150
14.2k
            }
151
18.1k
        }
152
153
18.5k
        demux_cancel_and_free(d);
154
18.5k
    }
155
156
16.1k
    if (!num_items)
157
1.96k
        return;
158
159
14.2k
    MP_DBG(mpctx, "Terminating demuxers...\n");
160
161
14.2k
    double end = mp_time_sec() + mpctx->opts->demux_termination_timeout;
162
14.2k
    bool force = false;
163
73.0k
    while (num_items) {
164
58.7k
        double wait = end - mp_time_sec();
165
166
103k
        for (int n = 0; n < num_items; n++) {
167
58.7k
            struct demux_free_async_state *item = items[n];
168
58.7k
            if (demux_free_async_finish(item)) {
169
14.2k
                items[n] = items[num_items - 1];
170
14.2k
                num_items -= 1;
171
14.2k
                n--;
172
14.2k
                goto repeat;
173
44.5k
            } else if (wait < 0) {
174
0
                demux_free_async_force(item);
175
0
                if (!force)
176
0
                    MP_VERBOSE(mpctx, "Forcefully terminating demuxers...\n");
177
0
                force = true;
178
0
            }
179
58.7k
        }
180
181
44.5k
        if (wait >= 0)
182
44.5k
            mp_set_timeout(mpctx, wait);
183
44.5k
        mp_idle(mpctx);
184
58.7k
    repeat:;
185
58.7k
    }
186
187
14.2k
    talloc_free(items);
188
189
14.2k
    MP_DBG(mpctx, "Done terminating demuxers.\n");
190
14.2k
}
191
192
static void uninit_demuxer(struct MPContext *mpctx)
193
16.1k
{
194
64.7k
    for (int t = 0; t < STREAM_TYPE_COUNT; t++) {
195
113k
        for (int r = 0; r < num_ptracks[t]; r++)
196
64.7k
            mpctx->current_track[r][t] = NULL;
197
48.5k
    }
198
199
16.1k
    talloc_free(mpctx->chapters);
200
16.1k
    mpctx->chapters = NULL;
201
16.1k
    mpctx->num_chapters = 0;
202
203
16.1k
    mp_abort_cache_dumping(mpctx);
204
205
16.1k
    struct demuxer **demuxers = NULL;
206
16.1k
    int num_demuxers = 0;
207
208
16.1k
    if (mpctx->demuxer)
209
14.6k
        MP_TARRAY_APPEND(NULL, demuxers, num_demuxers, mpctx->demuxer);
210
16.1k
    mpctx->demuxer = NULL;
211
212
48.5k
    for (int i = 0; i < mpctx->num_tracks; i++) {
213
32.4k
        struct track *track = mpctx->tracks[i];
214
215
32.4k
        mp_assert(!track->dec && !track->d_sub);
216
32.4k
        mp_assert(!track->vo_c && !track->ao_c);
217
32.4k
        mp_assert(!track->sink);
218
219
        // Demuxers can be added in any order (if they appear mid-stream), and
220
        // we can't know which tracks uses which, so here's some O(n^2) trash.
221
84.8k
        for (int n = 0; n < num_demuxers; n++) {
222
80.9k
            if (demuxers[n] == track->demuxer) {
223
28.4k
                track->demuxer = NULL;
224
28.4k
                break;
225
28.4k
            }
226
80.9k
        }
227
32.4k
        if (track->demuxer)
228
3.91k
            MP_TARRAY_APPEND(NULL, demuxers, num_demuxers, track->demuxer);
229
230
32.4k
        talloc_free(track);
231
32.4k
    }
232
16.1k
    mpctx->num_tracks = 0;
233
234
16.1k
    kill_demuxers_reentrant(mpctx, demuxers, num_demuxers);
235
16.1k
    talloc_free(demuxers);
236
237
16.1k
    disc_nav_reset(mpctx);
238
16.1k
}
239
240
466k
#define APPEND(s, ...) mp_snprintf_cat(s, sizeof(s), __VA_ARGS__)
241
2.68k
#define FILL(s, n) mp_snprintf_cat(s, sizeof(s), "%*s", n, "")
242
243
static void print_stream(struct MPContext *mpctx, struct track *t, bool indent)
244
164k
{
245
164k
    const char *tname = "?";
246
164k
    const char *selopt = "?";
247
164k
    const char *langopt = "?";
248
164k
    switch (t->type) {
249
49.0k
    case STREAM_VIDEO:
250
49.0k
        tname = t->image ? "Image" : "Video"; selopt = "vid"; langopt = "vlang";
251
49.0k
        break;
252
49.0k
    case STREAM_AUDIO:
253
49.0k
        tname = "Audio"; selopt = "aid"; langopt = "alang";
254
49.0k
        break;
255
66.3k
    case STREAM_SUB:
256
66.3k
        tname = "Subs"; selopt = "sid"; langopt = "slang";
257
66.3k
        break;
258
164k
    }
259
164k
    char b[2048] = {0};
260
261
164k
    int max_lang_length = 0;
262
2.55M
    for (int n = 0; n < mpctx->num_tracks; n++) {
263
2.38M
        if (mpctx->tracks[n]->lang)
264
6.05k
            max_lang_length = MPMAX(strlen(mpctx->tracks[n]->lang), max_lang_length);
265
2.38M
    }
266
267
164k
    if (indent)
268
136k
        APPEND(b, " ");
269
164k
    APPEND(b, "%s %-5s  --%s=%-2d", t->selected ? BLACK_CIRCLE : WHITE_CIRCLE,
270
164k
           tname, selopt, t->user_tid);
271
164k
    if (t->lang) {
272
957
        APPEND(b, " --%s=%-*s ", langopt, max_lang_length, t->lang);
273
163k
    } else if (max_lang_length) {
274
2.68k
        FILL(b, (int) strlen(" --alang= ") + max_lang_length);
275
2.68k
    }
276
277
164k
    void *ctx = talloc_new(NULL);
278
164k
    APPEND(b, " %s", mp_format_track_metadata(ctx, t, false));
279
164k
    talloc_free(ctx);
280
281
164k
    MP_INFO(mpctx, "%s\n", b);
282
164k
}
283
284
// Return true if any track of `type` has program_id matching the edition id.
285
static bool edition_has_track_of_type(struct MPContext *mpctx,
286
                                      enum stream_type type)
287
0
{
288
0
    struct demuxer *demuxer = mpctx->demuxer;
289
0
    if (!demuxer || !demuxer->edition_is_track_mapping || demuxer->num_editions <= 1)
290
0
        return false;
291
0
    int program = demuxer->editions[demuxer->edition].demuxer_id;
292
0
    for (int n = 0; n < mpctx->num_tracks; n++) {
293
0
        struct track *t = mpctx->tracks[n];
294
0
        if (t->type == type && track_has_program(t, program))
295
0
            return true;
296
0
    }
297
0
    return false;
298
0
}
299
300
static bool track_in_current_edition(struct MPContext *mpctx, struct track *track)
301
223k
{
302
223k
    struct demuxer *demuxer = mpctx->demuxer;
303
223k
    if (!demuxer || !demuxer->edition_is_track_mapping || demuxer->num_editions <= 1)
304
223k
        return true;
305
0
    if (track->is_external)
306
0
        return true;
307
0
    int program = demuxer->editions[demuxer->edition].demuxer_id;
308
0
    if (track_has_program(track, program))
309
0
        return true;
310
    // Program-agnostic tracks only show in editions that don't supply their own
311
    // track of this type.
312
0
    if (!track->stream || !track->stream->num_program_ids)
313
0
        return !edition_has_track_of_type(mpctx, track->type);
314
0
    return false;
315
0
}
316
317
bool track_is_visible(struct MPContext *mpctx, struct track *track)
318
223k
{
319
223k
    if (!track_in_current_edition(mpctx, track))
320
0
        return false;
321
223k
    if (track->dependent_track && !mpctx->opts->show_dependent_tracks)
322
0
        return false;
323
223k
    return true;
324
223k
}
325
326
void print_track_list(struct MPContext *mpctx, const char *msg)
327
49.0k
{
328
49.0k
    if (mpctx->opts->term_show_tracks == 2)
329
0
        return;
330
49.0k
    if (msg)
331
49.0k
        MP_INFO(mpctx, "%s\n", msg);
332
196k
    for (int t = 0; t < STREAM_TYPE_COUNT; t++) {
333
640k
        for (int n = 0; n < mpctx->num_tracks; n++) {
334
493k
            struct track *track = mpctx->tracks[n];
335
493k
            if (track->type != t || !track_is_visible(mpctx, track))
336
329k
                continue;
337
164k
            if (mpctx->opts->term_show_tracks == 1 && !track->selected)
338
0
                continue;
339
            // Indent tracks after messages like "Tracks switched" and
340
            // "Playing:".
341
164k
            print_stream(mpctx, track, msg ||
342
28.4k
                         mpctx->playlist->num_entries > 1 ||
343
28.4k
                         mpctx->playing->playlist_path);
344
164k
        }
345
147k
    }
346
49.0k
}
347
348
void update_demuxer_properties(struct MPContext *mpctx)
349
11.4M
{
350
11.4M
    struct demuxer *demuxer = mpctx->demuxer;
351
11.4M
    if (!demuxer)
352
0
        return;
353
11.4M
    demux_update(demuxer, get_current_time(mpctx));
354
11.4M
    int events = demuxer->events;
355
11.4M
    if ((events & DEMUX_EVENT_INIT) && demuxer->num_editions > 1 &&
356
0
        mpctx->opts->term_show_editions != 2)
357
0
    {
358
0
        for (int n = 0; n < demuxer->num_editions; n++) {
359
0
            if (mpctx->opts->term_show_editions == 1 && n != demuxer->edition)
360
0
                continue;
361
0
            struct demux_edition *edition = &demuxer->editions[n];
362
0
            char b[128] = {0};
363
0
            if (mpctx->playlist->num_entries > 1 || mpctx->playing->playlist_path)
364
0
                APPEND(b, " ");
365
0
            APPEND(b, "%s --edition=%d", n == demuxer->edition ?
366
0
                   BLACK_CIRCLE : WHITE_CIRCLE, n);
367
0
            char *name = mp_tags_get_str(edition->metadata, "title");
368
0
            if (name)
369
0
                APPEND(b, " '%s'", name);
370
0
            if (edition->default_edition)
371
0
                APPEND(b, " [default]");
372
0
            MP_INFO(mpctx, "%s\n", b);
373
0
        }
374
0
    }
375
11.4M
    struct demuxer *tracks = mpctx->demuxer;
376
11.4M
    if (tracks->events & DEMUX_EVENT_STREAMS) {
377
14.2k
        int num_old_tracks = mpctx->num_tracks;
378
14.2k
        add_demuxer_tracks(mpctx, tracks);
379
14.2k
        tracks->events &= ~DEMUX_EVENT_STREAMS;
380
381
        // Streams surfaced after play_current_file's selection phase (e.g.
382
        // disc-nav playlist hop, or lavf identifying a PES stream only once
383
        // its first packet arrives) wouldn't otherwise get auto-selected.
384
        // Only such a stream may claim a free slot, one that disc navigation
385
        // or a failed decoder emptied stays empty.
386
14.2k
        if (mpctx->playback_initialized && mpctx->opts->stream_auto_sel) {
387
0
            for (int t = 0; t < STREAM_TYPE_COUNT; t++) {
388
0
                for (int i = 0; i < num_ptracks[t]; i++) {
389
0
                    if (mpctx->current_track[i][t])
390
0
                        continue;
391
                    // The output belongs to a complex filter.
392
0
                    if ((t == STREAM_VIDEO && mpctx->vo_chain) ||
393
0
                        (t == STREAM_AUDIO && mpctx->ao_chain))
394
0
                        continue;
395
0
                    if (mpctx->opts->stream_id[i][t] == -2)
396
0
                        continue;
397
0
                    struct track *sel = select_default_track(mpctx, i, t);
398
0
                    bool is_new = false;
399
0
                    for (int n = num_old_tracks; n < mpctx->num_tracks; n++)
400
0
                        is_new |= mpctx->tracks[n] == sel;
401
0
                    if (is_new)
402
0
                        mp_switch_track_n(mpctx, i, t, sel, 0);
403
0
                }
404
0
            }
405
0
        }
406
14.2k
        print_track_list(mpctx, NULL);
407
14.2k
    }
408
11.4M
    if (events & DEMUX_EVENT_METADATA) {
409
373k
        struct mp_tags *info =
410
373k
            mp_tags_filtered(mpctx, demuxer->metadata, mpctx->opts->display_tags);
411
        // prev is used to attempt to print changed tags only (to some degree)
412
373k
        struct mp_tags *prev = mpctx->filtered_tags;
413
373k
        int n_prev = 0;
414
373k
        bool had_output = false;
415
373k
        for (int n = 0; n < info->num_keys; n++) {
416
0
            if (prev && n_prev < prev->num_keys) {
417
0
                if (strcmp(prev->keys[n_prev], info->keys[n]) == 0) {
418
0
                    n_prev++;
419
0
                    if (strcmp(prev->values[n_prev - 1], info->values[n]) == 0)
420
0
                        continue;
421
0
                }
422
0
            }
423
0
            struct mp_log *log = mp_log_new(NULL, mpctx->log, "!display-tags");
424
0
            if (!had_output)
425
0
                mp_info(log, "File tags:\n");
426
0
            mp_info(log, " %s: ", info->keys[n]);
427
0
            const char *p = info->values[n];
428
0
            while (*p) {
429
0
                int len = strcspn(p, "\x8\xa\xb\xc\xd");
430
0
                mp_info(log, "%.*s", len, p);
431
0
                p += len;
432
0
                if (*p == '\r')
433
0
                    mp_info(log, " ");
434
                // Align continued lines with header
435
0
                if (*p == '\n')
436
0
                    mp_info(log, "\n %-*s  ", (int)strlen(info->keys[n]), "");
437
0
                if (*p)
438
0
                    p++;
439
0
            }
440
0
            mp_info(log, "\n");
441
0
            had_output = true;
442
0
            talloc_free(log);
443
0
        }
444
373k
        talloc_free(mpctx->filtered_tags);
445
373k
        mpctx->filtered_tags = info;
446
373k
        mp_notify(mpctx, MP_EVENT_METADATA_UPDATE, NULL);
447
373k
    }
448
11.4M
    if (events & DEMUX_EVENT_DURATION)
449
62.1k
        mp_notify(mpctx, MP_EVENT_DURATION_UPDATE, NULL);
450
11.4M
    if (events & DEMUX_EVENT_CODEC)
451
0
        mp_notify(mpctx, MP_EVENT_TRACKS_CHANGED, NULL);
452
11.4M
    if (events & DEMUX_EVENT_LISTS) {
453
        // Demuxer just published a new chapter / edition list at runtime.
454
0
        char *chapter_file = mpctx->opts->chapter_file;
455
0
        if (!chapter_file || !chapter_file[0]) {
456
0
            TA_FREEP(&mpctx->chapters);
457
0
            mpctx->num_chapters = demuxer->num_chapters;
458
0
            if (demuxer->num_chapters > 0) {
459
0
                mpctx->chapters = demux_copy_chapter_data(demuxer->chapters,
460
0
                                                         demuxer->num_chapters);
461
0
                if (mpctx->opts->rebase_start_time) {
462
0
                    for (int n = 0; n < mpctx->num_chapters; n++)
463
0
                        mpctx->chapters[n].pts -= demuxer->start_time;
464
0
                }
465
0
            }
466
0
            mp_notify(mpctx, MP_EVENT_CHAPTER_CHANGE, NULL);
467
0
            mp_notify_property(mpctx, "chapter-list");
468
0
            mp_notify_property(mpctx, "chapters");
469
0
        }
470
0
        mp_notify_property(mpctx, "edition");
471
0
        mp_notify_property(mpctx, "edition-list");
472
0
        mp_notify_property(mpctx, "current-edition");
473
0
        mp_notify_property(mpctx, "editions");
474
0
    }
475
11.4M
    demuxer->events = 0;
476
11.4M
}
477
478
// Enables or disables the stream for the given track, according to
479
// track->selected.
480
// With refresh_only=true, refreshes the stream if it's enabled.
481
void reselect_demux_stream(struct MPContext *mpctx, struct track *track,
482
                           bool refresh_only)
483
66.9k
{
484
66.9k
    if (!track->stream)
485
0
        return;
486
66.9k
    double pts = get_current_time(mpctx);
487
66.9k
    if (pts != MP_NOPTS_VALUE) {
488
66.9k
        pts += get_track_seek_offset(mpctx, track);
489
66.9k
        if (track->type == STREAM_SUB)
490
8.52k
            pts -= 10.0;
491
66.9k
    }
492
66.9k
    if (refresh_only)
493
0
        demuxer_refresh_track(track->demuxer, track->stream, pts);
494
66.9k
    else
495
66.9k
        demuxer_select_track(track->demuxer, track->stream, pts, track->selected);
496
66.9k
}
497
498
static void enable_demux_thread(struct MPContext *mpctx, struct demuxer *demux)
499
20.5k
{
500
20.5k
    if (mpctx->opts->demuxer_thread && !demux->fully_read) {
501
14.7k
        demux_set_wakeup_cb(demux, wakeup_demux, mpctx);
502
14.7k
        demux_start_thread(demux);
503
14.7k
    }
504
20.5k
}
505
506
static int find_new_tid(struct MPContext *mpctx, enum stream_type t)
507
33.2k
{
508
33.2k
    int new_id = 0;
509
112k
    for (int i = 0; i < mpctx->num_tracks; i++) {
510
78.8k
        struct track *track = mpctx->tracks[i];
511
78.8k
        if (track->type == t)
512
55.1k
            new_id = MPMAX(new_id, track->user_tid);
513
78.8k
    }
514
33.2k
    return new_id + 1;
515
33.2k
}
516
517
static struct track *add_stream_track(struct MPContext *mpctx,
518
                                      struct demuxer *demuxer,
519
                                      struct sh_stream *stream)
520
61.6k
{
521
154k
    for (int i = 0; i < mpctx->num_tracks; i++) {
522
121k
        struct track *track = mpctx->tracks[i];
523
121k
        if (track->stream == stream)
524
28.4k
            return track;
525
121k
    }
526
527
33.2k
    struct track *track = talloc_ptrtype(NULL, track);
528
33.2k
    *track = (struct track) {
529
33.2k
        .type = stream->type,
530
33.2k
        .user_tid = find_new_tid(mpctx, stream->type),
531
33.2k
        .demuxer_id = stream->demuxer_id,
532
33.2k
        .ff_index = stream->ff_index,
533
33.2k
        .hls_bitrate = stream->hls_bitrate,
534
33.2k
        .title = stream->title,
535
33.2k
        .default_track = stream->default_track,
536
33.2k
        .forced_track = stream->forced_track,
537
33.2k
        .dependent_track = stream->dependent_track,
538
33.2k
        .visual_impaired_track = stream->visual_impaired_track,
539
33.2k
        .hearing_impaired_track = stream->hearing_impaired_track,
540
33.2k
        .original_track = stream->original_track,
541
33.2k
        .commentary_track = stream->commentary_track,
542
33.2k
        .image = stream->image,
543
33.2k
        .attached_picture = stream->attached_picture != NULL,
544
33.2k
        .lang = stream->lang,
545
33.2k
        .demuxer = demuxer,
546
33.2k
        .stream = stream,
547
33.2k
    };
548
33.2k
    MP_TARRAY_APPEND(mpctx, mpctx->tracks, mpctx->num_tracks, track);
549
550
33.2k
    mp_notify(mpctx, MP_EVENT_TRACKS_CHANGED, NULL);
551
552
33.2k
    return track;
553
61.6k
}
554
555
void add_demuxer_tracks(struct MPContext *mpctx, struct demuxer *demuxer)
556
28.4k
{
557
85.3k
    for (int n = 0; n < demux_get_num_stream(demuxer); n++)
558
56.9k
        add_stream_track(mpctx, demuxer, demux_get_stream(demuxer, n));
559
28.4k
}
560
561
/* Get the track wanted by the user.
562
 * tid is the track ID requested by the user (-2: deselect, -1: default)
563
 * lang is a string list, NULL is same as empty list
564
 * Sort tracks based on the following criteria, and pick the first:
565
  *0a) track matches tid (always wins)
566
 * 0b) track is not from --external-file
567
 * 1) track is external (no_default cancels this)
568
 * 1b) track was passed explicitly (is not an auto-loaded subtitle)
569
 * 1c) track matches the program ID of the video
570
 * 2) earlier match in lang list but not if we're using os_langs
571
 * 3a) track is marked forced and we're preferring forced tracks
572
 * 3b) track is marked non-forced and we're preferring non-forced tracks
573
 * 3c) track is marked default
574
 * 3d) match in lang list with os_langs
575
 * 4) attached picture, HLS bitrate
576
 * 5) lower track number
577
 * If select_fallback is not set, 5) is only used to determine whether a
578
 * matching track is preferred over another track. Otherwise, always pick a
579
 * track (if nothing else matches, return the track with lowest ID).
580
 * Forced tracks are preferred when the user prefers not to display subtitles
581
 */
582
// Return whether t1 is preferred over t2
583
static bool compare_track(struct track *t1, struct track *t2, char **langs, bool os_langs,
584
                          struct MPOpts *opts)
585
106
{
586
106
    bool sub = t2->type == STREAM_SUB;
587
106
    bool ext1 = t1->is_external && !t1->no_default;
588
106
    bool ext2 = t2->is_external && !t2->no_default;
589
106
    if (ext1 != ext2 && t1->image == t2->image) {
590
0
        if (t1->attached_picture && t2->attached_picture
591
0
            && opts->audio_display == 1)
592
0
            return !ext1;
593
0
        return ext1;
594
0
    }
595
106
    if (t1->auto_loaded != t2->auto_loaded)
596
0
        return !t1->auto_loaded;
597
106
    int l1 = mp_match_lang(langs, t1->lang), l2 = mp_match_lang(langs, t2->lang);
598
106
    if (!os_langs && l1 != l2)
599
0
        return l1 > l2;
600
106
    if (t1->forced_select != t2->forced_select)
601
0
        return t1->forced_select;
602
106
    if (t1->default_track != t2->default_track)
603
0
        return t1->default_track;
604
106
    if (sub && t1->forced_track != t2->forced_track)
605
0
        return !t1->forced_track;
606
106
    if (os_langs && l1 != l2)
607
0
        return l1 > l2;
608
106
    if (t1->attached_picture != t2->attached_picture)
609
0
        return !t1->attached_picture;
610
106
    if (t1->image != t2->image)
611
0
        return !t1->image;
612
106
    if (t1->dependent_track != t2->dependent_track)
613
0
        return !t1->dependent_track;
614
106
    if (t1->stream && t2->stream && opts->hls_bitrate >= 0 &&
615
106
        t1->stream->hls_bitrate != t2->stream->hls_bitrate)
616
0
    {
617
0
        bool t1_ok = t1->stream->hls_bitrate <= opts->hls_bitrate;
618
0
        bool t2_ok = t2->stream->hls_bitrate <= opts->hls_bitrate;
619
0
        if (t1_ok != t2_ok)
620
0
            return t1_ok;
621
0
        if (t1_ok && t2_ok)
622
0
            return t1->stream->hls_bitrate > t2->stream->hls_bitrate;
623
0
        return t1->stream->hls_bitrate < t2->stream->hls_bitrate;
624
0
    }
625
106
    return t1->user_tid <= t2->user_tid;
626
106
}
627
628
static bool duplicate_track(struct MPContext *mpctx, int order,
629
                            enum stream_type type, struct track *track)
630
28.1k
{
631
28.1k
    for (int i = 0; i < order; i++) {
632
0
        if (mpctx->current_track[i][type] == track)
633
0
            return true;
634
0
    }
635
28.1k
    return false;
636
28.1k
}
637
638
static bool append_lang(size_t *nb, char ***out, char *in)
639
0
{
640
0
    if (!in)
641
0
        return false;
642
0
    MP_TARRAY_GROW(NULL, *out, *nb + 1);
643
0
    (*out)[(*nb)++] = in;
644
0
    (*out)[*nb] = NULL;
645
0
    talloc_steal(*out, in);
646
0
    return true;
647
0
}
648
649
static char **add_os_langs(void)
650
14.3k
{
651
14.3k
    size_t nb = 0;
652
14.3k
    char **out = NULL;
653
14.3k
    char **autos = mp_get_user_langs();
654
14.3k
    for (int i = 0; autos && autos[i]; i++) {
655
0
        if (!append_lang(&nb, &out, autos[i]))
656
0
            goto cleanup;
657
0
    }
658
659
14.3k
cleanup:
660
14.3k
    talloc_free(autos);
661
14.3k
    return out;
662
14.3k
}
663
664
static char **process_langs(char **in)
665
42.4k
{
666
42.4k
    size_t nb = 0;
667
42.4k
    char **out = NULL;
668
42.4k
    for (int i = 0; in && in[i]; i++) {
669
0
        if (!append_lang(&nb, &out, talloc_strdup(NULL, in[i])))
670
0
            break;
671
0
    }
672
42.4k
    return out;
673
42.4k
}
674
675
struct track *select_default_track(struct MPContext *mpctx, int order,
676
                                   enum stream_type type)
677
57.2k
{
678
57.2k
    struct MPOpts *opts = mpctx->opts;
679
57.2k
    int tid = opts->stream_id[order][type];
680
57.2k
    const struct demuxer *demuxer = mpctx->demuxer;
681
57.2k
    if (tid == -2)
682
14.8k
        return NULL;
683
42.4k
    char **langs = process_langs(opts->stream_lang[type]);
684
42.4k
    bool os_langs = false;
685
    // Try to add OS languages if enabled by the user and we don't already have a lang from slang.
686
42.4k
    if (type == STREAM_SUB && (!langs || !strcmp(langs[0], "")) && opts->subs_match_os_language) {
687
14.3k
        talloc_free(langs);
688
14.3k
        langs = add_os_langs();
689
14.3k
        os_langs = true;
690
14.3k
    }
691
42.4k
    const char *audio_lang = mpctx->current_track[0][STREAM_AUDIO] ?
692
14.3k
                             mpctx->current_track[0][STREAM_AUDIO]->lang :
693
42.4k
                             NULL;
694
42.4k
    bool sub = type == STREAM_SUB;
695
42.4k
    int *preferred_programs = NULL;
696
42.4k
    int num_preferred_programs = 0;
697
42.4k
    struct track *cvt = mpctx->current_track[0][STREAM_VIDEO];
698
42.4k
    bool video_has_programs = cvt && cvt->stream && cvt->stream->num_program_ids;
699
42.4k
    bool no_edition_mapping = !demuxer || !demuxer->edition_is_track_mapping ||
700
0
                              demuxer->num_editions <= 1;
701
42.4k
    if (type != STREAM_VIDEO && video_has_programs && no_edition_mapping) {
702
0
        preferred_programs = cvt->stream->program_ids;
703
0
        num_preferred_programs = cvt->stream->num_program_ids;
704
0
    }
705
42.4k
    struct track *pick = NULL;
706
127k
    for (int n = 0; n < mpctx->num_tracks; n++) {
707
85.2k
        struct track *track = mpctx->tracks[n];
708
85.2k
        if (track->type != type)
709
56.9k
            continue;
710
28.2k
        if (!track_is_visible(mpctx, track))
711
0
            continue;
712
28.2k
        if (track->user_tid == tid) {
713
148
            pick = track;
714
148
            goto cleanup;
715
148
        }
716
28.1k
        if (track->no_auto_select || track->dec_failed)
717
0
            continue;
718
28.1k
        if (!opts->autoload_files && track->is_external)
719
0
            continue;
720
        // Prefer tracks from the same programs as the selected video.
721
28.1k
        bool in_program = !num_preferred_programs || track->is_external ||
722
0
                          !track->stream || !track->stream->num_program_ids;
723
28.1k
        for (int i = 0; i < num_preferred_programs && !in_program; i++)
724
0
            in_program = track_has_program(track, preferred_programs[i]);
725
28.1k
        if (!in_program)
726
0
            continue;
727
28.1k
        if (duplicate_track(mpctx, order, type, track))
728
0
            continue;
729
28.1k
        if (sub) {
730
            // Subtitle specific auto-selecting crap.
731
196
            bool audio_matches = mp_match_lang((char *[]){ (char *)audio_lang, NULL }, track->lang) > 0;
732
196
            bool forced = track->forced_track && (opts->subs_fallback_forced == 2 ||
733
0
                          (audio_matches && opts->subs_fallback_forced == 1));
734
196
            bool lang_match = !os_langs && mp_match_lang(langs, track->lang) > 0;
735
196
            bool subs_fallback = (track->is_external && !track->no_default) || opts->subs_fallback == 2 ||
736
0
                                 (opts->subs_fallback == 1 && track->default_track);
737
196
            bool subs_matching_audio = (!mp_match_lang(langs, audio_lang) || opts->subs_with_matching_audio == 2 ||
738
0
                                        (opts->subs_with_matching_audio == 1 && track->forced_track));
739
196
            if (!subs_matching_audio)
740
0
                continue;
741
196
            if (!forced && !lang_match && !subs_fallback)
742
0
                continue;
743
196
            track->forced_select = forced;
744
196
        }
745
28.1k
        if (!pick || compare_track(track, pick, langs, os_langs, mpctx->opts)) {
746
28.0k
            pick = track;
747
28.0k
        }
748
28.1k
    }
749
750
42.2k
    if (pick && pick->attached_picture && !mpctx->opts->audio_display)
751
0
        pick = NULL;
752
42.4k
cleanup:
753
42.4k
    talloc_free(langs);
754
42.4k
    return pick;
755
42.2k
}
756
757
static char *track_layout_hash(struct MPContext *mpctx)
758
35.9k
{
759
35.9k
    char *h = talloc_strdup(NULL, "");
760
143k
    for (int type = 0; type < STREAM_TYPE_COUNT; type++) {
761
544k
        for (int n = 0; n < mpctx->num_tracks; n++) {
762
436k
            struct track *track = mpctx->tracks[n];
763
436k
            if (track->type != type)
764
291k
                continue;
765
145k
            h = talloc_asprintf_append_buffer(h, "%d-%d-%d-%d-%s\n", type,
766
145k
                    track->user_tid, track->default_track, track->is_external,
767
145k
                    track->lang ? track->lang : "");
768
145k
        }
769
107k
    }
770
35.9k
    return h;
771
35.9k
}
772
773
// Normally, video/audio/sub track selection is persistent across files. This
774
// code resets track selection if the new file has a different track layout.
775
static void check_previous_track_selection(struct MPContext *mpctx)
776
14.2k
{
777
14.2k
    struct MPOpts *opts = mpctx->opts;
778
779
14.2k
    if (!mpctx->track_layout_hash)
780
13.7k
        return;
781
782
461
    char *h = track_layout_hash(mpctx);
783
461
    if (strcmp(h, mpctx->track_layout_hash) != 0) {
784
        // Reset selection, but only if they're not "auto" or "off". The
785
        // defaults are -1 (default selection), or -2 (off) for secondary tracks.
786
192
        for (int t = 0; t < STREAM_TYPE_COUNT; t++) {
787
336
            for (int i = 0; i < num_ptracks[t]; i++) {
788
192
                if (opts->stream_id[i][t] >= 0)
789
48
                    mark_track_selection(mpctx, i, t, i == 0 ? -1 : -2);
790
192
            }
791
144
        }
792
48
        talloc_free(mpctx->track_layout_hash);
793
48
        mpctx->track_layout_hash = NULL;
794
48
    }
795
461
    talloc_free(h);
796
461
}
797
798
// Update the matching track selection user option to the given value.
799
void mark_track_selection(struct MPContext *mpctx, int order,
800
                          enum stream_type type, int value)
801
46.9k
{
802
46.9k
    mp_assert(order >= 0 && order < num_ptracks[type]);
803
46.9k
    mpctx->opts->stream_id[order][type] = value;
804
46.9k
    m_config_notify_change_opt_ptr(mpctx->mconfig,
805
46.9k
                                   &mpctx->opts->stream_id[order][type]);
806
46.9k
}
807
808
void mp_switch_track_n(struct MPContext *mpctx, int order, enum stream_type type,
809
                       struct track *track, int flags)
810
35.5k
{
811
35.5k
    mp_assert(!track || track->type == type);
812
35.5k
    mp_assert(type >= 0 && type < STREAM_TYPE_COUNT);
813
35.5k
    mp_assert(order >= 0 && order < num_ptracks[type]);
814
815
    // Mark the current track selection as explicitly user-requested. (This is
816
    // different from auto-selection or disabling a track due to errors.)
817
35.5k
    if (flags & FLAG_MARK_SELECTION)
818
33.8k
        mark_track_selection(mpctx, order, type, track ? track->user_tid : -2);
819
820
    // No decoder should be initialized yet.
821
35.5k
    if (!mpctx->demuxer)
822
0
        return;
823
824
35.5k
    struct track *current = mpctx->current_track[order][type];
825
35.5k
    if (track == current)
826
68
        return;
827
828
35.5k
    if (current && current->sink) {
829
0
        MP_ERR(mpctx, "Can't disable input to complex filter.\n");
830
0
        goto error;
831
0
    }
832
35.5k
    if ((type == STREAM_VIDEO && mpctx->vo_chain && !mpctx->vo_chain->track) ||
833
35.5k
        (type == STREAM_AUDIO && mpctx->ao_chain && !mpctx->ao_chain->track))
834
0
    {
835
0
        MP_ERR(mpctx, "Can't switch away from complex filter output.\n");
836
0
        goto error;
837
0
    }
838
839
35.5k
    if (track && track->selected) {
840
        // Track has been selected in a different order parameter.
841
0
        MP_ERR(mpctx, "Track %d is already selected.\n", track->user_tid);
842
0
        goto error;
843
0
    }
844
845
35.5k
    if (order == 0) {
846
35.5k
        if (type == STREAM_VIDEO) {
847
24.4k
            uninit_video_chain(mpctx);
848
24.4k
            if (!track)
849
12.5k
                handle_force_window(mpctx, true);
850
24.4k
        } else if (type == STREAM_AUDIO) {
851
5.50k
            clear_audio_output_buffers(mpctx);
852
5.50k
            uninit_audio_chain(mpctx);
853
5.50k
            if (!track)
854
2.85k
                uninit_audio_out(mpctx);
855
5.50k
        }
856
35.5k
    }
857
35.5k
    if (type == STREAM_SUB)
858
5.56k
        uninit_sub(mpctx, current);
859
860
35.5k
    if (current) {
861
19.1k
        current->selected = false;
862
19.1k
        reselect_demux_stream(mpctx, current, false);
863
19.1k
    }
864
865
    // For the edge case of switching from no video to a still image, we need to
866
    // flush the ass events of any sub track for potential animations.
867
35.5k
    if (type == STREAM_VIDEO && order == 0 && !current && track->image) {
868
0
        for (int n = 0; n < num_ptracks[STREAM_SUB]; n++) {
869
0
            struct track *sub_track = mpctx->current_track[n][STREAM_SUB];
870
0
            if (sub_track && sub_track->d_sub) {
871
0
                sub_control(sub_track->d_sub, SD_CTRL_RESET_SOFT, NULL);
872
0
                sub_reset(sub_track->d_sub);
873
0
                if (sub_track->selected)
874
0
                    reselect_demux_stream(mpctx, sub_track, true);
875
0
            }
876
0
        }
877
0
    }
878
879
35.5k
    mpctx->current_track[order][type] = track;
880
881
35.5k
    if (track) {
882
19.2k
        track->selected = true;
883
19.2k
        reselect_demux_stream(mpctx, track, false);
884
19.2k
    }
885
886
35.5k
    if (type == STREAM_VIDEO && order == 0) {
887
24.4k
        reinit_video_chain(mpctx);
888
24.4k
    } else if (type == STREAM_AUDIO && order == 0) {
889
5.50k
        reinit_audio_chain(mpctx);
890
5.56k
    } else if (type == STREAM_SUB && order >= 0 && order <= 2) {
891
5.56k
        reinit_sub(mpctx, track);
892
5.56k
    }
893
894
35.5k
    mp_notify(mpctx, MP_EVENT_TRACK_SWITCHED, NULL);
895
35.5k
    mp_wakeup_core(mpctx);
896
897
35.5k
    talloc_free(mpctx->track_layout_hash);
898
35.5k
    mpctx->track_layout_hash = talloc_steal(mpctx, track_layout_hash(mpctx));
899
900
35.5k
    return;
901
0
error:
902
0
    mark_track_selection(mpctx, order, type, -1);
903
0
}
904
905
void mp_switch_track(struct MPContext *mpctx, enum stream_type type,
906
                     struct track *track, int flags)
907
4.79k
{
908
4.79k
    mp_switch_track_n(mpctx, 0, type, track, flags);
909
4.79k
}
910
911
void mp_deselect_track(struct MPContext *mpctx, struct track *track)
912
832
{
913
832
    if (track && track->selected) {
914
2.48k
        for (int t = 0; t < num_ptracks[track->type]; t++) {
915
1.64k
            if (mpctx->current_track[t][track->type] != track)
916
817
                continue;
917
832
            mp_switch_track_n(mpctx, t, track->type, NULL, 0);
918
832
            mark_track_selection(mpctx, t, track->type, -1); // default
919
832
        }
920
832
    }
921
832
}
922
923
struct track *mp_track_by_tid(struct MPContext *mpctx, enum stream_type type,
924
                              int tid)
925
11.3k
{
926
11.3k
    if (tid == -1)
927
11.0k
        return mpctx->current_track[0][type];
928
352
    for (int n = 0; n < mpctx->num_tracks; n++) {
929
126
        struct track *track = mpctx->tracks[n];
930
126
        if (track->type == type && track->user_tid == tid)
931
10
            return track;
932
126
    }
933
226
    return NULL;
934
236
}
935
936
bool mp_remove_track(struct MPContext *mpctx, struct track *track)
937
863
{
938
863
    if (!track->is_external)
939
46
        return false;
940
941
817
    mp_deselect_track(mpctx, track);
942
817
    if (track->selected)
943
0
        return false;
944
945
817
    struct demuxer *d = track->demuxer;
946
947
817
    int index = 0;
948
9.05k
    while (index < mpctx->num_tracks && mpctx->tracks[index] != track)
949
8.23k
        index++;
950
817
    MP_TARRAY_REMOVE_AT(mpctx->tracks, mpctx->num_tracks, index);
951
817
    talloc_free(track);
952
953
    // Close the demuxer, unless there is still a track using it. These are
954
    // all external tracks.
955
817
    bool in_use = false;
956
9.05k
    for (int n = mpctx->num_tracks - 1; n >= 0 && !in_use; n--)
957
8.24k
        in_use |= mpctx->tracks[n]->demuxer == d;
958
959
817
    if (!in_use)
960
817
        demux_cancel_and_free(d);
961
962
817
    mp_notify(mpctx, MP_EVENT_TRACKS_CHANGED, NULL);
963
964
817
    return true;
965
817
}
966
967
// Add the given file as additional track. The filter argument controls how or
968
// if tracks are auto-selected at any point.
969
// To be run on a worker thread, locked (temporarily unlocks core).
970
// cancel will generally be used to abort the loading process, but on success
971
// the demuxer is changed to be slaved to mpctx->playback_abort instead.
972
int mp_add_external_file(struct MPContext *mpctx, char *filename,
973
                         enum stream_type filter, struct mp_cancel *cancel,
974
                         enum track_flags flags)
975
27.3k
{
976
27.3k
    struct MPOpts *opts = mpctx->opts;
977
27.3k
    if (!filename || mp_cancel_test(cancel))
978
1
        return -1;
979
980
27.3k
    void *unescaped_url = NULL;
981
27.3k
    char *disp_filename = filename;
982
27.3k
    if (strncmp(disp_filename, "memory://", 9) == 0) {
983
16.5k
        disp_filename = "memory://"; // avoid noise
984
16.5k
    } else if (mp_is_url(bstr0(disp_filename))) {
985
3.46k
        disp_filename = unescaped_url = mp_url_unescape(NULL, disp_filename);
986
3.46k
    }
987
988
27.3k
    struct demuxer_params params = {
989
27.3k
        .is_top_level = true,
990
27.3k
        .stream_flags = STREAM_ORIGIN_DIRECT,
991
27.3k
        .allow_playlist_create = false,
992
27.3k
    };
993
994
27.3k
    switch (filter) {
995
26.3k
    case STREAM_SUB:
996
26.3k
        params.force_format = opts->sub_demuxer_name;
997
26.3k
        break;
998
50
    case STREAM_AUDIO:
999
50
        params.force_format = opts->audio_demuxer_name;
1000
50
        break;
1001
27.3k
    }
1002
1003
27.3k
    mp_core_unlock(mpctx);
1004
1005
27.3k
    char *path = mp_get_user_path(NULL, mpctx->global, filename);
1006
27.3k
    struct demuxer *demuxer =
1007
27.3k
        demux_open_url(path, &params, cancel, mpctx->global);
1008
27.3k
    talloc_free(path);
1009
1010
27.3k
    if (demuxer)
1011
6.34k
        enable_demux_thread(mpctx, demuxer);
1012
1013
27.3k
    mp_core_lock(mpctx);
1014
1015
    // The command could have overlapped with playback exiting. (We don't care
1016
    // if playback has started again meanwhile - weird, but not a problem.)
1017
27.3k
    if (mpctx->stop_play)
1018
295
        goto err_out;
1019
1020
27.0k
    if (!demuxer)
1021
20.7k
        goto err_out;
1022
1023
6.32k
    if (filter != STREAM_SUB && opts->rebase_start_time)
1024
288
        demux_set_ts_offset(demuxer, -demuxer->start_time);
1025
1026
6.32k
    bool has_any = false;
1027
6.80k
    for (int n = 0; n < demux_get_num_stream(demuxer); n++) {
1028
5.21k
        struct sh_stream *sh = demux_get_stream(demuxer, n);
1029
5.21k
        if (sh->type == filter || filter == STREAM_TYPE_COUNT) {
1030
4.73k
            has_any = true;
1031
4.73k
            break;
1032
4.73k
        }
1033
5.21k
    }
1034
1035
6.32k
    if (!has_any) {
1036
1.59k
        char *tname = mp_tprintf(20, "%s ", stream_type_name(filter));
1037
1.59k
        if (filter == STREAM_TYPE_COUNT)
1038
0
            tname = "";
1039
1.59k
        MP_ERR(mpctx, "No %sstreams in file %s.\n", tname, disp_filename);
1040
1.59k
        goto err_out;
1041
1.59k
    }
1042
1043
4.73k
    int first_num = -1;
1044
9.46k
    for (int n = 0; n < demux_get_num_stream(demuxer); n++) {
1045
4.73k
        struct sh_stream *sh = demux_get_stream(demuxer, n);
1046
4.73k
        struct track *t = add_stream_track(mpctx, demuxer, sh);
1047
4.73k
        t->is_external = true;
1048
4.73k
        if (sh->title && sh->title[0]) {
1049
0
            t->title = talloc_strdup(t, sh->title);
1050
4.73k
        } else {
1051
4.73k
            bstr parent = {0};
1052
4.73k
            if (mpctx->filename)
1053
4.73k
                parent = mp_strip_ext(bstr0(mp_basename(mpctx->filename)));
1054
4.73k
            bstr title = bstr0(mp_basename(disp_filename));
1055
4.73k
            bstr_eatstart(&title, parent);
1056
4.73k
            bstr_eatstart(&title, bstr0("."));
1057
4.73k
            if (title.len)
1058
0
                t->title = bstrdup0(t, title);
1059
4.73k
        }
1060
4.73k
        t->external_filename = mp_normalize_user_path(t, mpctx->global, filename);
1061
4.73k
        t->no_default = sh->type != filter;
1062
4.73k
        t->no_auto_select = t->no_default;
1063
4.73k
        t->hearing_impaired_track = flags & TRACK_HEARING_IMPAIRED;
1064
4.73k
        t->visual_impaired_track = flags & TRACK_VISUAL_IMPAIRED;
1065
4.73k
        t->forced_track = flags & TRACK_FORCED;
1066
4.73k
        t->default_track = flags & TRACK_DEFAULT;
1067
4.73k
        t->commentary_track = flags & TRACK_COMMENTARY;
1068
        // if we found video, and we are loading cover art, flag as such.
1069
4.73k
        t->attached_picture = t->type == STREAM_VIDEO && (flags & TRACK_ATTACHED_PICTURE);
1070
4.73k
        if (first_num < 0 && (filter == STREAM_TYPE_COUNT || sh->type == filter))
1071
4.73k
            first_num = mpctx->num_tracks - 1;
1072
4.73k
    }
1073
1074
4.73k
    mp_cancel_set_parent(demuxer->cancel, mpctx->playback_abort);
1075
1076
4.73k
    talloc_free(unescaped_url);
1077
4.73k
    return first_num;
1078
1079
22.6k
err_out:
1080
22.6k
    demux_cancel_and_free(demuxer);
1081
22.6k
    if (!mp_cancel_test(cancel))
1082
22.6k
        MP_ERR(mpctx, "Can not open external file %s.\n", disp_filename);
1083
22.6k
    talloc_free(unescaped_url);
1084
22.6k
    return -1;
1085
6.32k
}
1086
1087
// to be run on a worker thread, locked (temporarily unlocks core)
1088
static void open_external_files(struct MPContext *mpctx, char **files,
1089
                                enum stream_type filter)
1090
56.9k
{
1091
    // Need a copy, because the option value could be mutated during iteration.
1092
56.9k
    void *tmp = talloc_new(NULL);
1093
56.9k
    files = mp_dup_str_array(tmp, files);
1094
1095
56.9k
    for (int n = 0; files && files[n]; n++)
1096
        // when given filter is set to video, we are loading up cover art
1097
2
        mp_add_external_file(mpctx, files[n], filter, mpctx->playback_abort,
1098
2
                             filter == STREAM_VIDEO ? TRACK_ATTACHED_PICTURE : 0);
1099
1100
56.9k
    talloc_free(tmp);
1101
56.9k
}
1102
1103
// See mp_add_external_file() for meaning of cancel parameter.
1104
void autoload_external_files(struct MPContext *mpctx, struct mp_cancel *cancel)
1105
14.4k
{
1106
14.4k
    struct MPOpts *opts = mpctx->opts;
1107
1108
14.4k
    if (opts->sub_auto < 0 && opts->audiofile_auto < 0 && opts->coverart_auto < 0)
1109
0
        return;
1110
14.4k
    if (!opts->autoload_files || strcmp(mpctx->filename, "-") == 0)
1111
0
        return;
1112
1113
14.4k
    void *tmp = talloc_new(NULL);
1114
14.4k
    struct subfn *list = find_external_files(mpctx->global, mpctx->filename, opts);
1115
14.4k
    talloc_steal(tmp, list);
1116
1117
    // demux_edl allocates metadata track with type set to STREAM_TYPE_COUNT,
1118
    // count this too, even though it won't have any effect on the selection.
1119
14.4k
    int sc[STREAM_TYPE_COUNT + 1] = {0};
1120
43.5k
    for (int n = 0; n < mpctx->num_tracks; n++) {
1121
29.1k
        mp_assert(mpctx->tracks[n]->type >= 0);
1122
29.1k
        mp_assert(mpctx->tracks[n]->type <= STREAM_TYPE_COUNT);
1123
29.1k
        if (!mpctx->tracks[n]->attached_picture)
1124
29.1k
            sc[mpctx->tracks[n]->type]++;
1125
29.1k
    }
1126
1127
14.4k
    for (int i = 0; list && list[i].fname; i++) {
1128
0
        struct subfn *e = &list[i];
1129
1130
0
        for (int n = 0; n < mpctx->num_tracks; n++) {
1131
0
            struct track *t = mpctx->tracks[n];
1132
0
            if (t->demuxer && strcmp(t->demuxer->filename, e->fname) == 0)
1133
0
                goto skip;
1134
0
        }
1135
0
        if (e->type == STREAM_SUB && !sc[STREAM_VIDEO] && !sc[STREAM_AUDIO])
1136
0
            goto skip;
1137
0
        if (e->type == STREAM_AUDIO && !sc[STREAM_VIDEO])
1138
0
            goto skip;
1139
0
        if (e->type == STREAM_VIDEO && (sc[STREAM_VIDEO] || !sc[STREAM_AUDIO]))
1140
0
            goto skip;
1141
1142
0
        enum track_flags flags = e->flags;
1143
        // when given filter is set to video, we are loading up cover art
1144
0
        flags |= e->type == STREAM_VIDEO ? TRACK_ATTACHED_PICTURE : 0;
1145
0
        int first = mp_add_external_file(mpctx, e->fname, e->type, cancel, flags);
1146
0
        if (first < 0)
1147
0
            goto skip;
1148
1149
0
        for (int n = first; n < mpctx->num_tracks; n++) {
1150
0
            struct track *t = mpctx->tracks[n];
1151
0
            t->auto_loaded = true;
1152
0
            if (!t->lang)
1153
0
                t->lang = talloc_strdup(t, e->lang);
1154
0
        }
1155
0
    skip:;
1156
0
    }
1157
1158
14.4k
    talloc_free(tmp);
1159
14.4k
}
1160
1161
// Do stuff to a newly loaded playlist. This includes any processing that may
1162
// be required after loading a playlist.
1163
void prepare_playlist(struct MPContext *mpctx, struct playlist *pl, bool overwrite_current)
1164
16.0k
{
1165
16.0k
    struct MPOpts *opts = mpctx->opts;
1166
16.0k
    struct playlist_entry *entry = NULL;
1167
1168
16.0k
    if (overwrite_current)
1169
4.41k
        pl->current = NULL;
1170
1171
16.0k
    pl->playlist_completed = false;
1172
16.0k
    pl->playlist_started = false;
1173
1174
16.0k
    if (opts->playlist_pos >= 0) {
1175
0
        entry = playlist_entry_from_index(pl, opts->playlist_pos);
1176
0
        pl->current = overwrite_current || entry ? entry : pl->current;
1177
0
    }
1178
1179
16.0k
    if (pl->playlist_dir)
1180
0
        playlist_set_current(pl);
1181
1182
16.0k
    if (opts->shuffle)
1183
0
        playlist_shuffle(pl);
1184
1185
16.0k
    if (opts->merge_files)
1186
0
        merge_playlist_files(pl);
1187
1188
16.0k
    if (!pl->current || (!overwrite_current && !entry)) {
1189
16.0k
        entry = mp_check_playlist_resume(mpctx, pl);
1190
16.0k
        pl->current = overwrite_current || entry ? entry : pl->current;
1191
16.0k
    }
1192
1193
16.0k
    if (!pl->current)
1194
16.0k
        pl->current = playlist_get_first(pl);
1195
16.0k
}
1196
1197
// Replace the current playlist entry with playlist contents. Moves the entries
1198
// from the given playlist pl, so the entries don't actually need to be copied.
1199
// The new entries inherit the file-local options of the current entry.
1200
static void transfer_playlist(struct MPContext *mpctx, struct playlist *pl,
1201
                              int64_t *start_id, int *num_new_entries)
1202
0
{
1203
0
    if (pl->num_entries) {
1204
0
        prepare_playlist(mpctx, pl, true);
1205
0
        struct playlist_entry *new = pl->current;
1206
0
        struct playlist_entry *current = mpctx->playlist->current;
1207
0
        *num_new_entries = pl->num_entries;
1208
0
        if (current && mpctx->opts->playlist_inherit_options == 1)
1209
0
            playlist_set_params(pl, current->params, current->num_params);
1210
0
        else if (current && new && mpctx->opts->playlist_inherit_options == 2)
1211
0
            playlist_entry_add_params(new, current->params, current->num_params);
1212
0
        *start_id = playlist_transfer_entries(mpctx->playlist, pl);
1213
        // current entry is replaced
1214
0
        if (current)
1215
0
            playlist_remove(mpctx->playlist, current);
1216
0
        if (new)
1217
0
            mpctx->playlist->current = new;
1218
0
        mpctx->playlist->playlist_dir = talloc_steal(mpctx->playlist, pl->playlist_dir);
1219
0
    } else {
1220
0
        MP_WARN(mpctx, "Empty playlist!\n");
1221
0
    }
1222
0
}
1223
1224
static void process_hooks(struct MPContext *mpctx, char *name)
1225
93.7k
{
1226
93.7k
    mp_hook_start(mpctx, name);
1227
1228
93.7k
    while (!mp_hook_test_completion(mpctx, name)) {
1229
0
        mp_idle(mpctx);
1230
1231
        // We have no idea what blocks a hook, so just do a full abort. This
1232
        // does nothing for hooks that happen outside of playback.
1233
0
        if (mpctx->stop_play)
1234
0
            mp_abort_playback_async(mpctx);
1235
0
    }
1236
93.7k
}
1237
1238
// to be run on a worker thread, locked (temporarily unlocks core)
1239
static void load_chapters(struct MPContext *mpctx)
1240
14.2k
{
1241
14.2k
    struct demuxer *src = mpctx->demuxer;
1242
14.2k
    bool free_src = false;
1243
14.2k
    char *chapter_file = mpctx->opts->chapter_file;
1244
14.2k
    if (chapter_file && chapter_file[0]) {
1245
0
        chapter_file = mp_get_user_path(NULL, mpctx->global, chapter_file);
1246
0
        mp_core_unlock(mpctx);
1247
0
        struct demuxer_params p = {
1248
0
            .stream_flags = STREAM_ORIGIN_DIRECT,
1249
0
            .depth = src ? src->depth + 1 : 0,
1250
0
        };
1251
0
        struct demuxer *demux = demux_open_url(chapter_file, &p,
1252
0
                                               mpctx->playback_abort,
1253
0
                                               mpctx->global);
1254
0
        mp_core_lock(mpctx);
1255
0
        if (demux) {
1256
0
            src = demux;
1257
0
            free_src = true;
1258
0
        }
1259
0
        talloc_free(mpctx->chapters);
1260
0
        mpctx->chapters = NULL;
1261
0
        talloc_free(chapter_file);
1262
0
    }
1263
14.2k
    if (src && !mpctx->chapters) {
1264
14.2k
        talloc_free(mpctx->chapters);
1265
14.2k
        mpctx->num_chapters = src->num_chapters;
1266
14.2k
        mpctx->chapters = demux_copy_chapter_data(src->chapters, src->num_chapters);
1267
14.2k
        if (mpctx->opts->rebase_start_time) {
1268
14.2k
            for (int n = 0; n < mpctx->num_chapters; n++)
1269
0
                mpctx->chapters[n].pts -= src->start_time;
1270
14.2k
        }
1271
14.2k
    }
1272
14.2k
    if (free_src)
1273
0
        demux_cancel_and_free(src);
1274
14.2k
}
1275
1276
static void load_per_file_options(m_config_t *conf,
1277
                                  struct playlist_param *params,
1278
                                  int params_count)
1279
16.1k
{
1280
16.1k
    for (int n = 0; n < params_count; n++) {
1281
0
        m_config_set_option_cli(conf, params[n].name, params[n].value,
1282
0
                                M_SETOPT_BACKUP);
1283
0
    }
1284
16.1k
}
1285
1286
static MP_THREAD_VOID open_demux_thread(void *ctx)
1287
16.1k
{
1288
16.1k
    struct MPContext *mpctx = ctx;
1289
1290
16.1k
    mp_thread_set_name("opener");
1291
1292
16.1k
    struct demuxer_params p = {
1293
16.1k
        .force_format = mpctx->open_format,
1294
16.1k
        .stream_flags = mpctx->open_url_flags,
1295
16.1k
        .stream_record = true,
1296
16.1k
        .is_top_level = true,
1297
16.1k
        .allow_playlist_create = mpctx->playlist->num_entries <= 1 &&
1298
16.1k
                                 !mpctx->playlist->playlist_dir,
1299
16.1k
    };
1300
16.1k
    struct demuxer *demux =
1301
16.1k
        demux_open_url(mpctx->open_url, &p, mpctx->open_cancel, mpctx->global);
1302
16.1k
    mpctx->open_res_demuxer = demux;
1303
1304
16.1k
    if (demux) {
1305
14.6k
        MP_VERBOSE(mpctx, "Opening done: %s\n", mpctx->open_url);
1306
1307
14.6k
        if (mpctx->open_for_prefetch && !demux->fully_read) {
1308
0
            int num_streams = demux_get_num_stream(demux);
1309
0
            for (int n = 0; n < num_streams; n++) {
1310
0
                struct sh_stream *sh = demux_get_stream(demux, n);
1311
0
                demuxer_select_track(demux, sh, MP_NOPTS_VALUE, true);
1312
0
            }
1313
1314
0
            demux_set_wakeup_cb(demux, wakeup_demux, mpctx);
1315
0
            demux_start_thread(demux);
1316
0
            demux_start_prefetch(demux);
1317
0
        }
1318
14.6k
    } else {
1319
1.56k
        MP_VERBOSE(mpctx, "Opening failed or was aborted: %s\n", mpctx->open_url);
1320
1321
1.56k
        if (p.demuxer_failed) {
1322
75
            mpctx->open_res_error = MPV_ERROR_UNKNOWN_FORMAT;
1323
1.49k
        } else {
1324
1.49k
            mpctx->open_res_error = MPV_ERROR_LOADING_FAILED;
1325
1.49k
        }
1326
1.56k
    }
1327
1328
16.1k
    atomic_store(&mpctx->open_done, true);
1329
16.1k
    mp_wakeup_core(mpctx);
1330
16.1k
    MP_THREAD_RETURN();
1331
16.1k
}
1332
1333
static void cancel_open(struct MPContext *mpctx)
1334
44.0k
{
1335
44.0k
    if (mpctx->open_cancel)
1336
16.1k
        mp_cancel_trigger(mpctx->open_cancel);
1337
1338
44.0k
    if (mpctx->open_active)
1339
16.1k
        mp_thread_join(mpctx->open_thread);
1340
44.0k
    mpctx->open_active = false;
1341
1342
44.0k
    if (mpctx->open_res_demuxer)
1343
0
        demux_cancel_and_free(mpctx->open_res_demuxer);
1344
44.0k
    mpctx->open_res_demuxer = NULL;
1345
1346
44.0k
    TA_FREEP(&mpctx->open_cancel);
1347
44.0k
    TA_FREEP(&mpctx->open_url);
1348
44.0k
    TA_FREEP(&mpctx->open_format);
1349
1350
44.0k
    atomic_store(&mpctx->open_done, false);
1351
44.0k
}
1352
1353
// Setup all the field to open this url, and make sure a thread is running.
1354
static void start_open(struct MPContext *mpctx, char *url, int url_flags,
1355
                       bool for_prefetch)
1356
16.1k
{
1357
16.1k
    cancel_open(mpctx);
1358
1359
16.1k
    mp_assert(!mpctx->open_active);
1360
16.1k
    mp_assert(!mpctx->open_cancel);
1361
16.1k
    mp_assert(!mpctx->open_res_demuxer);
1362
16.1k
    mp_assert(!atomic_load(&mpctx->open_done));
1363
1364
16.1k
    mpctx->open_cancel = mp_cancel_new(NULL);
1365
16.1k
    mpctx->open_url = talloc_strdup(NULL, url);
1366
16.1k
    mpctx->open_format = talloc_strdup(NULL, mpctx->opts->demuxer_name);
1367
16.1k
    mpctx->open_url_flags = url_flags;
1368
16.1k
    mpctx->open_for_prefetch = for_prefetch && mpctx->opts->demuxer_thread;
1369
16.1k
    mpctx->demuxer_changed = false;
1370
1371
16.1k
    if (mp_thread_create(&mpctx->open_thread, open_demux_thread, mpctx)) {
1372
0
        cancel_open(mpctx);
1373
0
        return;
1374
0
    }
1375
1376
16.1k
    mpctx->open_active = true;
1377
16.1k
}
1378
1379
static void open_demux_reentrant(struct MPContext *mpctx)
1380
16.1k
{
1381
16.1k
    char *url = mpctx->stream_open_filename;
1382
1383
16.1k
    if (mpctx->open_active) {
1384
0
        bool done = atomic_load(&mpctx->open_done);
1385
0
        bool failed = done && !mpctx->open_res_demuxer;
1386
0
        bool correct_url = strcmp(mpctx->open_url, url) == 0;
1387
1388
0
        if (correct_url && !mpctx->demuxer_changed && !failed) {
1389
0
            MP_VERBOSE(mpctx, "Using prefetched/prefetching URL.\n");
1390
0
        } else {
1391
0
            if (correct_url && failed) {
1392
0
                MP_VERBOSE(mpctx, "Prefetched URL failed, retrying.\n");
1393
0
            } else if (mpctx->demuxer_changed) {
1394
0
                if (done) {
1395
0
                    MP_VERBOSE(mpctx, "Dropping finished prefetch because demuxer options changed.\n");
1396
0
                } else {
1397
0
                    MP_VERBOSE(mpctx, "Aborting ongoing prefetch because demuxer options changed.\n");
1398
0
                }
1399
0
            } else {
1400
0
                if (done) {
1401
0
                    MP_VERBOSE(mpctx, "Dropping finished prefetch of wrong URL.\n");
1402
0
                } else {
1403
0
                    MP_VERBOSE(mpctx, "Aborting ongoing prefetch of wrong URL.\n");
1404
0
                }
1405
0
            }
1406
0
            cancel_open(mpctx);
1407
0
        }
1408
0
    }
1409
1410
16.1k
    if (!mpctx->open_active)
1411
16.1k
        start_open(mpctx, url, mpctx->playing->stream_flags, false);
1412
1413
    // If thread failed to start, cancel the playback
1414
16.1k
    if (!mpctx->open_active)
1415
0
        goto cancel;
1416
1417
    // User abort should cancel the opener now.
1418
16.1k
    mp_cancel_set_parent(mpctx->open_cancel, mpctx->playback_abort);
1419
1420
84.4k
    while (!atomic_load(&mpctx->open_done)) {
1421
68.2k
        mp_idle(mpctx);
1422
1423
68.2k
        if (mpctx->stop_play)
1424
3.04k
            mp_abort_playback_async(mpctx);
1425
68.2k
    }
1426
1427
16.1k
    if (mpctx->open_res_demuxer) {
1428
14.6k
        mpctx->demuxer = mpctx->open_res_demuxer;
1429
14.6k
        mpctx->open_res_demuxer = NULL;
1430
14.6k
        mp_cancel_set_parent(mpctx->demuxer->cancel, mpctx->playback_abort);
1431
14.6k
    } else {
1432
1.56k
        mpctx->error_playing = mpctx->open_res_error;
1433
1.56k
    }
1434
1435
16.1k
cancel:
1436
16.1k
    cancel_open(mpctx); // cleanup
1437
16.1k
}
1438
1439
void prefetch_next(struct MPContext *mpctx)
1440
11.6M
{
1441
11.6M
    if (!mpctx->opts->prefetch_open || mpctx->open_active)
1442
11.6M
        return;
1443
1444
0
    struct playlist_entry *new_entry = mp_next_file(mpctx, +1, false, false);
1445
0
    if (new_entry && new_entry->filename) {
1446
0
        MP_VERBOSE(mpctx, "Prefetching: %s\n", new_entry->filename);
1447
0
        start_open(mpctx, new_entry->filename, new_entry->stream_flags, true);
1448
0
    }
1449
0
}
1450
1451
static void clear_playlist_paths(struct MPContext *mpctx)
1452
14.1k
{
1453
14.1k
    TA_FREEP(&mpctx->playlist_paths);
1454
14.1k
    mpctx->playlist_paths_len = 0;
1455
14.1k
}
1456
1457
static bool infinite_playlist_loading_loop(struct MPContext *mpctx, struct playlist *pl)
1458
0
{
1459
0
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1460
0
    if (mpctx->playlist_paths_len >= 10) {
1461
0
        clear_playlist_paths(mpctx);
1462
0
        return true;
1463
0
    }
1464
0
#endif
1465
0
    if (pl->num_entries) {
1466
0
        struct playlist_entry *e = pl->entries[0];
1467
0
        for (int n = 0; n < mpctx->playlist_paths_len; n++) {
1468
0
            if (strcmp(mpctx->playlist_paths[n], e->filename) == 0) {
1469
0
                clear_playlist_paths(mpctx);
1470
0
                return true;
1471
0
            }
1472
0
        }
1473
0
    }
1474
0
    MP_TARRAY_APPEND(mpctx, mpctx->playlist_paths, mpctx->playlist_paths_len,
1475
0
                     talloc_strdup(mpctx->playlist_paths, mpctx->filename));
1476
0
    return false;
1477
0
}
1478
1479
// Destroy the complex filter, and remove the references to the filter pads.
1480
// (Call cleanup_deassociated_complex_filters() to close decoders/VO/AO
1481
// that are not connected anymore due to this.)
1482
static void deassociate_complex_filters(struct MPContext *mpctx)
1483
0
{
1484
0
    for (int n = 0; n < mpctx->num_tracks; n++)
1485
0
        mpctx->tracks[n]->sink = NULL;
1486
0
    if (mpctx->vo_chain)
1487
0
        mpctx->vo_chain->filter_src = NULL;
1488
0
    if (mpctx->ao_chain)
1489
0
        mpctx->ao_chain->filter_src = NULL;
1490
0
    TA_FREEP(&mpctx->lavfi);
1491
0
    TA_FREEP(&mpctx->lavfi_graph);
1492
0
}
1493
1494
// Close all decoders and sinks (AO/VO) that are not connected to either
1495
// a track or a filter pad.
1496
static void cleanup_deassociated_complex_filters(struct MPContext *mpctx)
1497
0
{
1498
0
    for (int n = 0; n < mpctx->num_tracks; n++) {
1499
0
        struct track *track = mpctx->tracks[n];
1500
0
        if (!(track->sink || track->vo_c || track->ao_c)) {
1501
0
            if (track->dec && !track->vo_c && !track->ao_c) {
1502
0
                talloc_free(track->dec->f);
1503
0
                track->dec = NULL;
1504
0
            }
1505
0
            track->selected = false;
1506
0
        }
1507
0
    }
1508
1509
0
    if (mpctx->vo_chain && !mpctx->vo_chain->dec_src &&
1510
0
        !mpctx->vo_chain->filter_src)
1511
0
    {
1512
0
        uninit_video_chain(mpctx);
1513
0
    }
1514
0
    if (mpctx->ao_chain && !mpctx->ao_chain->dec_src &&
1515
0
        !mpctx->ao_chain->filter_src)
1516
0
    {
1517
0
        uninit_audio_chain(mpctx);
1518
0
    }
1519
0
}
1520
1521
static void kill_outputs(struct MPContext *mpctx, struct track *track)
1522
0
{
1523
0
    if (track->vo_c || track->ao_c) {
1524
0
        MP_VERBOSE(mpctx, "deselecting track %d for lavfi-complex option\n",
1525
0
                   track->user_tid);
1526
0
        mp_switch_track(mpctx, track->type, NULL, 0);
1527
0
    }
1528
0
    mp_assert(!(track->vo_c || track->ao_c));
1529
0
}
1530
1531
// >0: changed, 0: no change, -1: error
1532
static int reinit_complex_filters(struct MPContext *mpctx, bool force_uninit)
1533
30.3k
{
1534
30.3k
    char *graph = mpctx->opts->lavfi_complex;
1535
30.3k
    bool have_graph = graph && graph[0] && !force_uninit;
1536
30.3k
    if (have_graph && mpctx->lavfi &&
1537
0
        strcmp(graph, mpctx->lavfi_graph) == 0 &&
1538
0
        !mp_filter_has_failed(mpctx->lavfi))
1539
0
        return 0;
1540
30.3k
    if (!mpctx->lavfi && !have_graph)
1541
30.3k
        return 0;
1542
1543
    // Deassociate the old filter pads. We leave both sources (tracks) and
1544
    // sinks (AO/VO) "dangling", connected to neither track or filter pad.
1545
    // Later, we either reassociate them with new pads, or uninit them if
1546
    // they are still dangling. This avoids too interruptive actions like
1547
    // recreating the VO.
1548
0
    deassociate_complex_filters(mpctx);
1549
1550
0
    bool success = false;
1551
0
    if (!have_graph) {
1552
0
        success = true; // normal full removal of graph
1553
0
        goto done;
1554
0
    }
1555
1556
0
    struct mp_lavfi *l =
1557
0
        mp_lavfi_create_graph(mpctx->filter_root, 0, false, NULL, NULL, graph);
1558
0
    if (!l)
1559
0
        goto done;
1560
0
    mpctx->lavfi = l->f;
1561
0
    mpctx->lavfi_graph = talloc_strdup(NULL, graph);
1562
1563
0
    mp_filter_set_error_handler(mpctx->lavfi, mpctx->filter_root);
1564
1565
0
    for (int n = 0; n < mpctx->lavfi->num_pins; n++)
1566
0
        mp_pin_disconnect(mpctx->lavfi->pins[n]);
1567
1568
0
    struct mp_pin *pad = mp_filter_get_named_pin(mpctx->lavfi, "vo");
1569
0
    if (pad && mp_pin_get_dir(pad) == MP_PIN_OUT) {
1570
0
        if (mpctx->vo_chain && mpctx->vo_chain->track)
1571
0
            kill_outputs(mpctx, mpctx->vo_chain->track);
1572
0
        if (!mpctx->vo_chain) {
1573
0
            reinit_video_chain_src(mpctx, NULL);
1574
0
            if (!mpctx->vo_chain)
1575
0
                goto done;
1576
0
        }
1577
0
        struct vo_chain *vo_c = mpctx->vo_chain;
1578
0
        mp_assert(!vo_c->track);
1579
0
        vo_c->filter_src = pad;
1580
0
        mp_pin_connect(vo_c->filter->f->pins[0], vo_c->filter_src);
1581
0
    }
1582
1583
0
    pad = mp_filter_get_named_pin(mpctx->lavfi, "ao");
1584
0
    if (pad && mp_pin_get_dir(pad) == MP_PIN_OUT) {
1585
0
        if (mpctx->ao_chain && mpctx->ao_chain->track)
1586
0
            kill_outputs(mpctx, mpctx->ao_chain->track);
1587
0
        if (!mpctx->ao_chain) {
1588
0
            reinit_audio_chain_src(mpctx, NULL);
1589
0
            if (!mpctx->ao_chain)
1590
0
                goto done;
1591
0
        }
1592
0
        struct ao_chain *ao_c = mpctx->ao_chain;
1593
0
        mp_assert(!ao_c->track);
1594
0
        ao_c->filter_src = pad;
1595
0
        mp_pin_connect(ao_c->filter->f->pins[0], ao_c->filter_src);
1596
0
    }
1597
1598
0
    for (int n = 0; n < mpctx->num_tracks; n++) {
1599
0
        struct track *track = mpctx->tracks[n];
1600
1601
0
        char label[32];
1602
0
        char prefix;
1603
0
        switch (track->type) {
1604
0
        case STREAM_VIDEO: prefix = 'v'; break;
1605
0
        case STREAM_AUDIO: prefix = 'a'; break;
1606
0
        default: continue;
1607
0
        }
1608
0
        snprintf(label, sizeof(label), "%cid%d", prefix, track->user_tid);
1609
1610
0
        pad = mp_filter_get_named_pin(mpctx->lavfi, label);
1611
0
        if (!pad)
1612
0
            continue;
1613
0
        if (mp_pin_get_dir(pad) != MP_PIN_IN)
1614
0
            continue;
1615
0
        mp_assert(!mp_pin_is_connected(pad));
1616
1617
0
        mp_assert(!track->sink);
1618
1619
0
        kill_outputs(mpctx, track);
1620
1621
0
        track->sink = pad;
1622
0
        track->selected = true;
1623
1624
0
        if (!track->dec) {
1625
0
            bool ok = track->type == STREAM_VIDEO ? init_video_decoder(mpctx, track)
1626
0
                                                  : init_audio_decoder(mpctx, track);
1627
0
            if (!ok) {
1628
0
                error_on_track(mpctx, track);
1629
0
                goto done;
1630
0
            }
1631
0
        }
1632
1633
0
        mp_pin_connect(track->sink, track->dec->f->pins[0]);
1634
0
    }
1635
1636
    // Don't allow unconnected pins. Libavfilter would make the data flow a
1637
    // real pain anyway.
1638
0
    for (int n = 0; n < mpctx->lavfi->num_pins; n++) {
1639
0
        struct mp_pin *pin = mpctx->lavfi->pins[n];
1640
0
        if (!mp_pin_is_connected(pin)) {
1641
0
            MP_ERR(mpctx, "Pad %s is not connected to anything.\n",
1642
0
                   mp_pin_get_name(pin));
1643
0
            goto done;
1644
0
        }
1645
0
    }
1646
1647
0
    success = true;
1648
0
done:
1649
1650
0
    if (!success)
1651
0
        deassociate_complex_filters(mpctx);
1652
1653
0
    cleanup_deassociated_complex_filters(mpctx);
1654
1655
0
    if (mpctx->playback_initialized) {
1656
0
        for (int n = 0; n < mpctx->num_tracks; n++) {
1657
0
            struct track *t = mpctx->tracks[n];
1658
0
            if (t->stream && t->stream->dependent_track && !t->selected)
1659
0
                continue;
1660
0
            reselect_demux_stream(mpctx, t, false);
1661
0
        }
1662
0
    }
1663
1664
0
    mp_notify(mpctx, MP_EVENT_TRACKS_CHANGED, NULL);
1665
1666
0
    return success ? 1 : -1;
1667
0
}
1668
1669
// Match the enhancement-layer pairing on the vo_chain to the currently
1670
// selected video track. Idempotent. Decoupled from lavfi-complex internals.
1671
void update_vo_chain_el_pair(struct MPContext *mpctx)
1672
11.4M
{
1673
11.4M
    if (!mpctx->vo_chain || !mpctx->vo_chain->filter)
1674
961k
        return;
1675
10.4M
    struct track *track = mpctx->current_track[0][STREAM_VIDEO];
1676
10.4M
    mp_output_chain_set_el_stream(mpctx->vo_chain->filter,
1677
10.4M
        track ? sh_stream_dependent_sibling(track->stream) : NULL);
1678
10.4M
}
1679
1680
void update_lavfi_complex(struct MPContext *mpctx)
1681
11.6k
{
1682
11.6k
    if (mpctx->playback_initialized) {
1683
0
        int r = reinit_complex_filters(mpctx, false);
1684
0
        if (r != 0)
1685
0
            issue_refresh_seek(mpctx, MPSEEK_EXACT);
1686
0
        if (r > 0)
1687
0
            update_vo_chain_el_pair(mpctx);
1688
0
    }
1689
11.6k
}
1690
1691
1692
// Worker thread for loading external files and such. This is needed to avoid
1693
// freezing the core when waiting for network while loading these.
1694
static void load_external_opts_thread(void *p)
1695
14.2k
{
1696
14.2k
    void **a = p;
1697
14.2k
    struct MPContext *mpctx = a[0];
1698
14.2k
    struct mp_waiter *waiter = a[1];
1699
1700
14.2k
    mp_core_lock(mpctx);
1701
1702
14.2k
    load_chapters(mpctx);
1703
14.2k
    open_external_files(mpctx, mpctx->opts->audio_files, STREAM_AUDIO);
1704
14.2k
    open_external_files(mpctx, mpctx->opts->sub_name, STREAM_SUB);
1705
14.2k
    open_external_files(mpctx, mpctx->opts->coverart_files, STREAM_VIDEO);
1706
14.2k
    open_external_files(mpctx, mpctx->opts->external_files, STREAM_TYPE_COUNT);
1707
14.2k
    autoload_external_files(mpctx, mpctx->playback_abort);
1708
1709
14.2k
    mp_waiter_wakeup(waiter, 0);
1710
14.2k
    mp_wakeup_core(mpctx);
1711
14.2k
    mp_core_unlock(mpctx);
1712
14.2k
}
1713
1714
static void load_external_opts(struct MPContext *mpctx)
1715
14.2k
{
1716
14.2k
    struct mp_waiter wait = MP_WAITER_INITIALIZER;
1717
1718
14.2k
    void *a[] = {mpctx, &wait};
1719
14.2k
    if (!mp_thread_pool_queue(mpctx->thread_pool, load_external_opts_thread, a)) {
1720
0
        mpctx->stop_play = PT_ERROR;
1721
0
        return;
1722
0
    }
1723
1724
28.6k
    while (!mp_waiter_poll(&wait)) {
1725
14.4k
        mp_idle(mpctx);
1726
1727
14.4k
        if (mpctx->stop_play)
1728
35
            mp_abort_playback_async(mpctx);
1729
14.4k
    }
1730
1731
14.2k
    mp_waiter_wait(&wait);
1732
14.2k
}
1733
1734
static void append_to_watch_history(struct MPContext *mpctx)
1735
14.1k
{
1736
14.1k
    if (!mpctx->opts->save_watch_history)
1737
14.1k
        return;
1738
1739
2
    void *ctx = talloc_new(NULL);
1740
2
    char *history_path = mp_get_user_path(ctx, mpctx->global,
1741
2
                                          mpctx->opts->watch_history_path);
1742
2
    char *history_path_dir = bstrto0(ctx, mp_dirname(history_path));
1743
2
    mp_mkdirp(history_path_dir);
1744
1745
2
    FILE *history_file = fopen(history_path, "ab");
1746
2
    if (!history_file) {
1747
0
        MP_ERR(mpctx, "Failed to open history file: %s\n",
1748
0
               mp_strerror(errno));
1749
0
        goto done;
1750
0
    }
1751
1752
2
    char *title = (char *)mp_find_non_filename_media_title(mpctx);
1753
1754
2
    mpv_node_list *list = talloc_zero(ctx, mpv_node_list);
1755
2
    mpv_node node = {
1756
2
        .format = MPV_FORMAT_NODE_MAP,
1757
2
        .u.list = list,
1758
2
    };
1759
2
    list->num = title ? 3 : 2;
1760
2
    list->keys = talloc_array(ctx, char*, list->num);
1761
2
    list->values = talloc_array(ctx, mpv_node, list->num);
1762
2
    list->keys[0] = "time";
1763
2
    list->values[0] = (struct mpv_node) {
1764
2
        .format = MPV_FORMAT_INT64,
1765
2
        .u.int64 = time(NULL),
1766
2
    };
1767
2
    list->keys[1] = "path";
1768
2
    list->values[1] = (struct mpv_node) {
1769
2
        .format = MPV_FORMAT_STRING,
1770
2
        .u.string = mpctx->filename,
1771
2
    };
1772
2
    if (title) {
1773
0
        list->keys[2] = "title";
1774
0
        list->values[2] = (struct mpv_node) {
1775
0
            .format = MPV_FORMAT_STRING,
1776
0
            .u.string = title,
1777
0
        };
1778
0
    }
1779
1780
2
    bstr dst = {0};
1781
2
    json_append(&dst, &node, -1);
1782
2
    talloc_steal(ctx, dst.start);
1783
2
    if (!dst.len) {
1784
0
        MP_ERR(mpctx, "Failed to serialize history entry\n");
1785
0
        goto done;
1786
0
    }
1787
2
    bstr_xappend0(ctx, &dst, "\n");
1788
1789
2
    int seek = fseek(history_file, 0, SEEK_END);
1790
2
    off_t history_size = ftell(history_file);
1791
2
    if (seek != 0 || history_size == -1) {
1792
0
        MP_ERR(mpctx, "Failed to get history file size: %s\n",
1793
0
               mp_strerror(errno));
1794
0
        goto done;
1795
0
    }
1796
1797
2
    bool failed = fwrite(dst.start, dst.len, 1, history_file) != 1 ||
1798
2
                  fflush(history_file) != 0;
1799
1800
2
    if (failed) {
1801
0
        MP_ERR(mpctx, "Failed to write to history file: %s\n",
1802
0
               mp_strerror(errno));
1803
1804
0
        int fd = fileno(history_file);
1805
0
        if (fd == -1 || ftruncate(fd, history_size) == -1)
1806
0
            MP_ERR(mpctx, "Failed to roll-back history file: %s\n",
1807
0
                   mp_strerror(errno));
1808
0
    }
1809
1810
2
done:
1811
2
    if (history_file != NULL && fclose(history_file) != 0)
1812
2
        MP_ERR(mpctx, "Failed to close history file: %s\n", mp_strerror(errno));
1813
1814
2
    talloc_free(ctx);
1815
2
}
1816
1817
// Start playing the current playlist entry.
1818
// Handle initialization and deinitialization.
1819
static void play_current_file(struct MPContext *mpctx)
1820
16.1k
{
1821
16.1k
    struct MPOpts *opts = mpctx->opts;
1822
1823
16.1k
    mp_assert(mpctx->stop_play);
1824
16.1k
    mpctx->stop_play = 0;
1825
1826
16.1k
    process_hooks(mpctx, "on_before_start_file");
1827
16.1k
    if (mpctx->stop_play || !mpctx->playlist->current)
1828
0
        return;
1829
1830
16.1k
    mpv_event_start_file start_event = {
1831
16.1k
        .playlist_entry_id = mpctx->playlist->current->id,
1832
16.1k
    };
1833
16.1k
    mpv_event_end_file end_event = {
1834
16.1k
        .playlist_entry_id = start_event.playlist_entry_id,
1835
16.1k
    };
1836
1837
16.1k
    mp_notify(mpctx, MPV_EVENT_START_FILE, &start_event);
1838
1839
16.1k
    mp_cancel_reset(mpctx->playback_abort);
1840
1841
16.1k
    mpctx->error_playing = MPV_ERROR_LOADING_FAILED;
1842
16.1k
    mpctx->filename = NULL;
1843
16.1k
    mpctx->shown_aframes = 0;
1844
16.1k
    mpctx->shown_vframes = 0;
1845
16.1k
    mpctx->last_chapter_seek = -2;
1846
16.1k
    mpctx->last_chapter_flag = false;
1847
16.1k
    mpctx->last_chapter = -2;
1848
16.1k
    mpctx->paused = false;
1849
16.1k
    mpctx->playing_msg_shown = false;
1850
16.1k
    mpctx->max_frames = -1;
1851
16.1k
    mpctx->video_speed = mpctx->audio_speed = opts->playback_speed;
1852
16.1k
    mpctx->speed_factor_a = mpctx->speed_factor_v = 1.0;
1853
16.1k
    mpctx->display_sync_error = 0.0;
1854
16.1k
    mpctx->display_sync_active = false;
1855
    // let get_current_time() show 0 as start time (before playback_pts is set)
1856
16.1k
    mpctx->last_seek_pts = 0.0;
1857
16.1k
    mpctx->seek = (struct seek_params){ 0 };
1858
16.1k
    disc_nav_reset(mpctx);
1859
16.1k
    mpctx->filter_root = mp_filter_create_root(mpctx->global);
1860
16.1k
    mp_filter_graph_set_wakeup_cb(mpctx->filter_root, mp_wakeup_core_cb, mpctx);
1861
16.1k
    mp_filter_graph_set_max_run_time(mpctx->filter_root, 0.1);
1862
1863
16.1k
    reset_playback_state(mpctx);
1864
1865
16.1k
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1866
16.1k
    if (mpctx->playlist->num_entries > 3)
1867
0
        goto terminate_playback;
1868
16.1k
#endif
1869
1870
16.1k
    mpctx->playing = mpctx->playlist->current;
1871
16.1k
    mp_assert(mpctx->playing);
1872
16.1k
    mp_assert(mpctx->playing->filename);
1873
16.1k
    mpctx->playing->reserved += 1;
1874
1875
16.1k
    mpctx->filename = talloc_strdup(NULL, mpctx->playing->filename);
1876
16.1k
    mpctx->stream_open_filename = mpctx->filename;
1877
1878
16.1k
    mpctx->add_osd_seek_info &= OSD_SEEK_INFO_CURRENT_FILE;
1879
1880
16.1k
    if (opts->reset_options) {
1881
0
        for (int n = 0; opts->reset_options[n]; n++) {
1882
0
            const char *opt = opts->reset_options[n];
1883
0
            if (opt[0]) {
1884
0
                if (strcmp(opt, "all") == 0) {
1885
0
                    m_config_backup_all_opts(mpctx->mconfig);
1886
0
                } else {
1887
0
                    m_config_backup_opt(mpctx->mconfig, opt);
1888
0
                }
1889
0
            }
1890
0
        }
1891
0
    }
1892
1893
16.1k
    mp_load_auto_profiles(mpctx);
1894
1895
16.1k
    bool watch_later = mp_load_playback_resume(mpctx, mpctx->filename);
1896
1897
16.1k
    load_per_file_options(mpctx->mconfig, mpctx->playing->params,
1898
16.1k
                          mpctx->playing->num_params);
1899
1900
16.1k
    mpctx->remaining_file_loops = mpctx->opts->loop_file;
1901
16.1k
    mp_notify_property(mpctx, "remaining-file-loops");
1902
16.1k
    mpctx->remaining_ab_loops = mpctx->opts->ab_loop_count;
1903
16.1k
    mp_notify_property(mpctx, "remaining-ab-loops");
1904
1905
16.1k
    mpctx->max_frames = opts->play_frames;
1906
1907
16.1k
    handle_force_window(mpctx, false);
1908
1909
16.1k
    if (mpctx->playlist->num_entries > 1 ||
1910
16.1k
        mpctx->playing->playlist_path)
1911
16.1k
        MP_INFO(mpctx, "Playing: %s\n", mpctx->filename);
1912
1913
16.1k
    mp_assert(mpctx->demuxer == NULL);
1914
1915
16.1k
    process_hooks(mpctx, "on_load");
1916
16.1k
    if (mpctx->stop_play)
1917
0
        goto terminate_playback;
1918
1919
16.1k
    if (opts->stream_dump && opts->stream_dump[0]) {
1920
0
        if (stream_dump(mpctx, mpctx->stream_open_filename) >= 0)
1921
0
            mpctx->error_playing = 1;
1922
0
        goto terminate_playback;
1923
0
    }
1924
1925
16.1k
    open_demux_reentrant(mpctx);
1926
16.1k
    if (!mpctx->stop_play && !mpctx->demuxer) {
1927
628
        process_hooks(mpctx, "on_load_fail");
1928
628
        if (strcmp(mpctx->stream_open_filename, mpctx->filename) != 0 &&
1929
0
            !mpctx->stop_play)
1930
0
        {
1931
0
            mpctx->error_playing = MPV_ERROR_LOADING_FAILED;
1932
0
            open_demux_reentrant(mpctx);
1933
0
        }
1934
628
    }
1935
16.1k
    if (!mpctx->demuxer || mpctx->stop_play)
1936
1.93k
        goto terminate_playback;
1937
1938
14.2k
    struct playlist *pl = mpctx->demuxer->playlist;
1939
14.2k
    if (pl) {
1940
        // pl->playlist_dir indicates that the playlist was auto-created from
1941
        // the parent file. In this case, mpctx->filename points to real file.
1942
0
        if (watch_later && !pl->playlist_dir)
1943
0
            mp_delete_watch_later_conf(mpctx, mpctx->filename);
1944
0
        playlist_populate_playlist_path(pl, mpctx->filename);
1945
0
        if (infinite_playlist_loading_loop(mpctx, pl)) {
1946
0
            mpctx->stop_play = PT_STOP;
1947
0
            MP_ERR(mpctx, "Infinite playlist loading loop detected.\n");
1948
0
            goto terminate_playback;
1949
0
        }
1950
0
        transfer_playlist(mpctx, pl, &end_event.playlist_insert_id,
1951
0
                          &end_event.playlist_insert_num_entries);
1952
0
        mp_notify_property(mpctx, "playlist");
1953
0
        mpctx->error_playing = 2;
1954
0
        goto terminate_playback;
1955
0
    }
1956
1957
14.2k
    if (mpctx->opts->rebase_start_time)
1958
14.2k
        demux_set_ts_offset(mpctx->demuxer, -mpctx->demuxer->start_time);
1959
14.2k
    enable_demux_thread(mpctx, mpctx->demuxer);
1960
1961
14.2k
    add_demuxer_tracks(mpctx, mpctx->demuxer);
1962
1963
14.2k
    load_external_opts(mpctx);
1964
14.2k
    if (mpctx->stop_play)
1965
31
        goto terminate_playback;
1966
1967
14.2k
    check_previous_track_selection(mpctx);
1968
1969
14.2k
    process_hooks(mpctx, "on_preloaded");
1970
14.2k
    if (mpctx->stop_play)
1971
0
        goto terminate_playback;
1972
1973
14.2k
    if (reinit_complex_filters(mpctx, false) < 0)
1974
0
        goto terminate_playback;
1975
1976
56.8k
    for (int t = 0; t < STREAM_TYPE_COUNT; t++) {
1977
99.5k
        for (int i = 0; i < num_ptracks[t]; i++) {
1978
56.8k
            struct track *sel = NULL;
1979
56.8k
            bool taken = (t == STREAM_VIDEO && mpctx->vo_chain) ||
1980
56.8k
                         (t == STREAM_AUDIO && mpctx->ao_chain);
1981
56.8k
            if (!taken && opts->stream_auto_sel)
1982
56.8k
                sel = select_default_track(mpctx, i, t);
1983
56.8k
            mpctx->current_track[i][t] = sel;
1984
56.8k
        }
1985
42.6k
    }
1986
56.8k
    for (int t = 0; t < STREAM_TYPE_COUNT; t++) {
1987
99.5k
        for (int i = 0; i < num_ptracks[t]; i++) {
1988
            // One track can strictly feed at most 1 decoder
1989
56.8k
            struct track *track = mpctx->current_track[i][t];
1990
56.8k
            if (track) {
1991
27.8k
                if (track->type != STREAM_SUB &&
1992
27.8k
                    mpctx->encode_lavc_ctx &&
1993
0
                    !encode_lavc_stream_type_ok(mpctx->encode_lavc_ctx,
1994
0
                                                track->type))
1995
0
                {
1996
0
                    MP_WARN(mpctx, "Disabling %s (not supported by target "
1997
0
                            "format).\n", stream_type_name(track->type));
1998
0
                    mpctx->current_track[i][t] = NULL;
1999
0
                    mark_track_selection(mpctx, i, t, -2); // disable
2000
27.8k
                } else if (track->selected) {
2001
0
                    MP_ERR(mpctx, "Track %d can't be selected twice.\n",
2002
0
                           track->user_tid);
2003
0
                    mpctx->current_track[i][t] = NULL;
2004
0
                    mark_track_selection(mpctx, i, t, -2); // disable
2005
27.8k
                } else {
2006
27.8k
                    track->selected = true;
2007
27.8k
                }
2008
27.8k
            }
2009
2010
            // Revert selection of unselected tracks to default. This is needed
2011
            // because track properties have inconsistent behavior.
2012
56.8k
            if (!track && opts->stream_id[i][t] >= 0)
2013
9
                mark_track_selection(mpctx, i, t, -1); // default
2014
56.8k
        }
2015
42.6k
    }
2016
2017
14.2k
    process_hooks(mpctx, "on_loaded");
2018
56.8k
    for (int t = 0; t < STREAM_TYPE_COUNT; t++) {
2019
128k
        for (int n = 0; n < mpctx->num_tracks; n++) {
2020
85.3k
            struct track *track = mpctx->tracks[n];
2021
85.3k
            if (track->type != t)
2022
56.9k
                continue;
2023
            // Only reselect dependent tracks when explicitly selected by user
2024
28.4k
            if (track->stream && track->stream->dependent_track &&
2025
0
                !track->selected)
2026
0
                continue;
2027
28.4k
            reselect_demux_stream(mpctx, track, false);
2028
28.4k
        }
2029
42.6k
    }
2030
2031
14.2k
    update_demuxer_properties(mpctx);
2032
2033
14.2k
    update_playback_speed(mpctx);
2034
2035
14.2k
    reinit_video_chain(mpctx);
2036
14.2k
    reinit_audio_chain(mpctx);
2037
14.2k
    reinit_sub_all(mpctx);
2038
    // For lavfi-complex mode reinit_video_chain skips chain setup, so set up
2039
    // the enhancement-layer pairing here. No-op in non-lavfi-complex mode.
2040
14.2k
    update_vo_chain_el_pair(mpctx);
2041
2042
14.2k
    if (mpctx->encode_lavc_ctx) {
2043
0
        if (mpctx->vo_chain)
2044
0
            encode_lavc_expect_stream(mpctx->encode_lavc_ctx, STREAM_VIDEO);
2045
0
        if (mpctx->ao_chain)
2046
0
            encode_lavc_expect_stream(mpctx->encode_lavc_ctx, STREAM_AUDIO);
2047
0
        encode_lavc_set_metadata(mpctx->encode_lavc_ctx,
2048
0
                                 mpctx->demuxer->metadata);
2049
0
    }
2050
2051
14.2k
    if (!mpctx->vo_chain && !mpctx->ao_chain && opts->stream_auto_sel) {
2052
65
        MP_FATAL(mpctx, "No video or audio streams selected.\n");
2053
65
        mpctx->error_playing = MPV_ERROR_NOTHING_TO_PLAY;
2054
65
        goto terminate_playback;
2055
65
    }
2056
2057
14.1k
    if (mpctx->vo_chain && mpctx->vo_chain->is_coverart) {
2058
0
        MP_INFO(mpctx,
2059
0
            "Displaying cover art. Use --no-audio-display to prevent this.\n");
2060
0
    }
2061
2062
14.1k
    if (!mpctx->vo_chain)
2063
283
        handle_force_window(mpctx, true);
2064
2065
14.1k
    MP_VERBOSE(mpctx, "Starting playback...\n");
2066
2067
14.1k
    mpctx->playback_initialized = true;
2068
14.1k
    mpctx->playing->playlist_prev_attempt = false;
2069
14.1k
    mpctx->playlist->playlist_completed = false;
2070
14.1k
    mpctx->playlist->playlist_started = true;
2071
14.1k
    mp_notify(mpctx, MPV_EVENT_FILE_LOADED, NULL);
2072
14.1k
    update_screensaver_state(mpctx);
2073
14.1k
    clear_playlist_paths(mpctx);
2074
2075
    // Clear out subs from the previous file if the video track is a still image.
2076
14.1k
    redraw_subs(mpctx);
2077
2078
14.1k
    if (watch_later)
2079
0
        mp_delete_watch_later_conf(mpctx, mpctx->filename);
2080
2081
14.1k
    append_to_watch_history(mpctx);
2082
2083
14.1k
    if (mpctx->max_frames == 0) {
2084
0
        if (!mpctx->stop_play)
2085
0
            mpctx->stop_play = PT_NEXT_ENTRY;
2086
0
        mpctx->error_playing = 0;
2087
0
        goto terminate_playback;
2088
0
    }
2089
2090
14.1k
    if (opts->demuxer_cache_wait) {
2091
0
        demux_start_prefetch(mpctx->demuxer);
2092
2093
0
        while (!mpctx->stop_play) {
2094
0
            struct demux_reader_state s;
2095
0
            demux_get_reader_state(mpctx->demuxer, &s);
2096
0
            if (s.idle)
2097
0
                break;
2098
2099
0
            mp_idle(mpctx);
2100
0
        }
2101
0
    }
2102
2103
    // (Not get_play_start_pts(), which would always trigger a seek.)
2104
14.1k
    double play_start_pts = rel_time_to_abs(mpctx, opts->play_start);
2105
2106
    // Backward playback -> start from end by default.
2107
14.1k
    if (play_start_pts == MP_NOPTS_VALUE && opts->play_dir < 0)
2108
216
        play_start_pts = get_start_time(mpctx, -1);
2109
2110
14.1k
    if (play_start_pts != MP_NOPTS_VALUE) {
2111
216
        queue_seek(mpctx, MPSEEK_ABSOLUTE, play_start_pts, MPSEEK_DEFAULT, 0);
2112
216
        execute_queued_seek(mpctx);
2113
216
    }
2114
2115
14.1k
    update_internal_pause_state(mpctx);
2116
2117
14.1k
    mpctx->error_playing = 0;
2118
14.1k
    mpctx->in_playloop = true;
2119
11.4M
    while (!mpctx->stop_play)
2120
11.4M
        run_playloop(mpctx);
2121
14.1k
    mpctx->in_playloop = false;
2122
2123
14.1k
    MP_VERBOSE(mpctx, "EOF code: %d\n", mpctx->stop_play);
2124
2125
16.1k
terminate_playback:
2126
2127
16.1k
    if (!mpctx->stop_play)
2128
693
        mpctx->stop_play = PT_ERROR;
2129
2130
16.1k
    if (mpctx->stop_play != AT_END_OF_FILE)
2131
11.6k
        clear_audio_output_buffers(mpctx);
2132
2133
16.1k
    update_core_idle_state(mpctx);
2134
2135
16.1k
    if (mpctx->step_frames) {
2136
237
        opts->pause = true;
2137
237
        m_config_notify_change_opt_ptr(mpctx->mconfig, &opts->pause);
2138
237
    }
2139
2140
16.1k
    process_hooks(mpctx, "on_unload");
2141
2142
    // time to uninit all, except global stuff:
2143
16.1k
    reinit_complex_filters(mpctx, true);
2144
16.1k
    uninit_audio_chain(mpctx);
2145
16.1k
    uninit_video_chain(mpctx);
2146
16.1k
    uninit_sub_all(mpctx);
2147
16.1k
    if (!opts->gapless_audio && !mpctx->encode_lavc_ctx)
2148
1
        uninit_audio_out(mpctx);
2149
2150
16.1k
    mpctx->playback_initialized = false;
2151
2152
16.1k
    uninit_demuxer(mpctx);
2153
2154
    // Possibly stop ongoing async commands.
2155
16.1k
    mp_abort_playback_async(mpctx);
2156
2157
16.1k
    struct playlist_entry *current = mpctx->playlist->current;
2158
16.1k
    bool reloading = mpctx->stop_play == PT_CURRENT_ENTRY &&
2159
1.29k
                     current && current->reloading;
2160
16.1k
    if (current)
2161
15.6k
        current->reloading = false;
2162
16.1k
    if (!reloading)
2163
16.1k
        m_config_restore_backups(mpctx->mconfig);
2164
2165
16.1k
    TA_FREEP(&mpctx->filter_root);
2166
16.1k
    talloc_free(mpctx->filtered_tags);
2167
16.1k
    mpctx->filtered_tags = NULL;
2168
2169
16.1k
    mp_notify(mpctx, MP_EVENT_TRACKS_CHANGED, NULL);
2170
2171
16.1k
    if (encode_lavc_didfail(mpctx->encode_lavc_ctx))
2172
0
        mpctx->stop_play = PT_ERROR;
2173
2174
16.1k
    if (mpctx->stop_play == PT_ERROR && !mpctx->error_playing)
2175
0
        mpctx->error_playing = MPV_ERROR_GENERIC;
2176
2177
16.1k
    bool nothing_played = !mpctx->shown_aframes && !mpctx->shown_vframes &&
2178
2.24k
                          mpctx->error_playing <= 0;
2179
16.1k
    bool playlist_prev_continue = false;
2180
16.1k
    switch (mpctx->stop_play) {
2181
690
    case PT_ERROR:
2182
4.73k
    case AT_END_OF_FILE:
2183
4.73k
    {
2184
4.73k
        if (mpctx->error_playing == 0 && nothing_played)
2185
171
            mpctx->error_playing = MPV_ERROR_NOTHING_TO_PLAY;
2186
4.73k
        if (mpctx->error_playing < 0) {
2187
863
            end_event.error = mpctx->error_playing;
2188
863
            end_event.reason = MPV_END_FILE_REASON_ERROR;
2189
3.87k
        } else if (mpctx->error_playing == 2) {
2190
0
            end_event.reason = MPV_END_FILE_REASON_REDIRECT;
2191
3.87k
        } else {
2192
3.87k
            end_event.reason = MPV_END_FILE_REASON_EOF;
2193
3.87k
        }
2194
4.73k
        if (mpctx->playing) {
2195
4.73k
            mpctx->playing->init_failed = nothing_played;
2196
4.73k
            playlist_prev_continue = mpctx->playing->playlist_prev_attempt &&
2197
92
                                     nothing_played;
2198
4.73k
            mpctx->playing->playlist_prev_attempt = false;
2199
4.73k
        }
2200
4.73k
        break;
2201
690
    }
2202
    // Note that error_playing is meaningless in these cases.
2203
0
    case PT_NEXT_ENTRY:
2204
1.29k
    case PT_CURRENT_ENTRY:
2205
1.43k
    case PT_STOP:           end_event.reason = MPV_END_FILE_REASON_STOP; break;
2206
10.0k
    case PT_QUIT:           end_event.reason = MPV_END_FILE_REASON_QUIT; break;
2207
16.1k
    };
2208
16.1k
    mp_notify(mpctx, MPV_EVENT_END_FILE, &end_event);
2209
2210
16.1k
    MP_VERBOSE(mpctx, "finished playback, %s (reason %d)\n",
2211
16.1k
               mpv_error_string(end_event.error), end_event.reason);
2212
16.1k
    if (end_event.error == MPV_ERROR_UNKNOWN_FORMAT)
2213
16.1k
        MP_ERR(mpctx, "Failed to recognize file format.\n");
2214
2215
16.1k
    if (mpctx->playing)
2216
16.1k
        playlist_entry_unref(mpctx->playing);
2217
16.1k
    mpctx->playing = NULL;
2218
16.1k
    talloc_free(mpctx->filename);
2219
16.1k
    mpctx->filename = NULL;
2220
16.1k
    mpctx->stream_open_filename = NULL;
2221
2222
16.1k
    if (end_event.error < 0 && nothing_played) {
2223
860
        mpctx->files_broken++;
2224
15.3k
    } else if (end_event.error < 0) {
2225
3
        mpctx->files_errored++;
2226
15.3k
    } else {
2227
15.3k
        mpctx->files_played++;
2228
15.3k
    }
2229
2230
16.1k
    mp_assert(mpctx->stop_play);
2231
2232
16.1k
    process_hooks(mpctx, "on_after_end_file");
2233
2234
16.1k
    if (playlist_prev_continue) {
2235
92
        struct playlist_entry *e = mp_next_file(mpctx, -1, false, true);
2236
92
        if (e) {
2237
0
            mp_set_playlist_entry(mpctx, e);
2238
0
            play_current_file(mpctx);
2239
0
        }
2240
92
    }
2241
16.1k
}
2242
2243
// Determine the next file to play. Note that if this function returns non-NULL,
2244
// it can have side-effects and mutate mpctx.
2245
//  direction: -1 (previous) or +1 (next)
2246
//  force: if true, don't skip playlist entries marked as failed
2247
//  update_loop: whether to decrement --loop-playlist=N if it was specified
2248
struct playlist_entry *mp_next_file(struct MPContext *mpctx, int direction,
2249
                                    bool force, bool update_loop)
2250
9.76k
{
2251
9.76k
    struct playlist_entry *next = playlist_get_next(mpctx->playlist, direction);
2252
9.76k
    if (next && direction < 0 && !force)
2253
2.64k
        next->playlist_prev_attempt = true;
2254
9.76k
    if (!next && mpctx->opts->loop_times != 1) {
2255
0
        if (direction > 0) {
2256
0
            if (mpctx->opts->shuffle) {
2257
0
                if (!update_loop)
2258
0
                    return NULL;
2259
0
                playlist_shuffle(mpctx->playlist);
2260
0
            }
2261
0
            next = playlist_get_first(mpctx->playlist);
2262
0
            if (next && mpctx->opts->loop_times > 1 && update_loop) {
2263
0
                mpctx->opts->loop_times--;
2264
0
                m_config_notify_change_opt_ptr(mpctx->mconfig,
2265
0
                                               &mpctx->opts->loop_times);
2266
0
            }
2267
0
        } else {
2268
0
            next = playlist_get_last(mpctx->playlist);
2269
0
        }
2270
0
        bool ignore_failures = mpctx->opts->loop_times == -2;
2271
0
        if (!force && next && next->init_failed && !ignore_failures) {
2272
            // Don't endless loop if no file in playlist is playable
2273
0
            bool all_failed = true;
2274
0
            for (int n = 0; n < mpctx->playlist->num_entries; n++) {
2275
0
                all_failed &= mpctx->playlist->entries[n]->init_failed;
2276
0
                if (!all_failed)
2277
0
                    break;
2278
0
            }
2279
0
            if (all_failed)
2280
0
                next = NULL;
2281
0
        }
2282
0
    }
2283
9.76k
    return next;
2284
9.76k
}
2285
2286
// Play all entries on the playlist, starting from the current entry.
2287
// Return if all done.
2288
void mp_play_files(struct MPContext *mpctx)
2289
11.6k
{
2290
11.6k
    stats_register_thread_cputime(mpctx->stats, "thread");
2291
2292
    // Wait for all scripts to load before possibly starting playback.
2293
11.6k
    if (!mp_clients_all_initialized(mpctx)) {
2294
0
        MP_VERBOSE(mpctx, "Waiting for scripts...\n");
2295
0
        while (!mp_clients_all_initialized(mpctx))
2296
0
            mp_idle(mpctx);
2297
0
        mp_wakeup_core(mpctx); // avoid lost wakeups during waiting
2298
0
        MP_VERBOSE(mpctx, "Done loading scripts.\n");
2299
0
    }
2300
    // After above is finished; but even if it's skipped.
2301
11.6k
    mp_msg_set_early_logging(mpctx->global, false);
2302
2303
11.6k
    prepare_playlist(mpctx, mpctx->playlist, false);
2304
2305
17.8k
    for (;;) {
2306
17.8k
        idle_loop(mpctx);
2307
2308
17.8k
        if (mpctx->stop_play == PT_QUIT)
2309
1.66k
            break;
2310
2311
16.1k
        if (mpctx->playlist->current)
2312
16.1k
            play_current_file(mpctx);
2313
2314
16.1k
        if (mpctx->stop_play == PT_QUIT)
2315
10.0k
            break;
2316
2317
6.17k
        struct playlist_entry *new_entry = NULL;
2318
6.17k
        if (mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_ERROR ||
2319
5.48k
            mpctx->stop_play == AT_END_OF_FILE)
2320
4.73k
        {
2321
4.73k
            new_entry = mp_next_file(mpctx, +1, false, true);
2322
4.73k
        } else if (mpctx->stop_play == PT_CURRENT_ENTRY) {
2323
1.29k
            new_entry = mpctx->playlist->current;
2324
1.29k
        }
2325
2326
6.17k
        if (!new_entry)
2327
4.96k
            mpctx->playlist->playlist_completed = true;
2328
2329
6.17k
        mpctx->playlist->current = new_entry;
2330
6.17k
        mpctx->playlist->current_was_replaced = false;
2331
6.17k
        mpctx->stop_play = new_entry ? PT_NEXT_ENTRY : PT_STOP;
2332
2333
6.17k
        if (!mpctx->playlist->current && mpctx->opts->player_idle_mode < 2)
2334
0
            break;
2335
6.17k
    }
2336
2337
11.6k
    cancel_open(mpctx);
2338
2339
11.6k
    if (mpctx->encode_lavc_ctx) {
2340
        // Make sure all streams get finished.
2341
0
        uninit_audio_out(mpctx);
2342
0
        uninit_video_out(mpctx);
2343
2344
0
        if (!encode_lavc_free(mpctx->encode_lavc_ctx))
2345
0
            mpctx->files_errored += 1;
2346
2347
0
        mpctx->encode_lavc_ctx = NULL;
2348
0
    }
2349
11.6k
}
2350
2351
// Abort current playback and set the given entry to play next.
2352
// e must be on the mpctx->playlist.
2353
void mp_set_playlist_entry(struct MPContext *mpctx, struct playlist_entry *e)
2354
16.5k
{
2355
16.5k
    mp_assert(!e || playlist_entry_to_index(mpctx->playlist, e) >= 0);
2356
16.5k
    mpctx->playlist->current = e;
2357
16.5k
    mpctx->playlist->current_was_replaced = false;
2358
16.5k
    mp_notify(mpctx, MP_EVENT_CHANGE_PLAYLIST, NULL);
2359
    // Make it pick up the new entry.
2360
16.5k
    if (mpctx->stop_play != PT_QUIT)
2361
16.5k
        mpctx->stop_play = e ? PT_CURRENT_ENTRY : PT_STOP;
2362
16.5k
    mp_wakeup_core(mpctx);
2363
16.5k
}