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.74M
{
67
7.74M
    struct MPContext *mpctx = pctx;
68
7.74M
    mp_wakeup_core(mpctx);
69
7.74M
}
70
71
// Called by foreign threads when playback should be stopped and such.
72
void mp_abort_playback_async(struct MPContext *mpctx)
73
804k
{
74
804k
    mp_cancel_trigger(mpctx->playback_abort);
75
76
804k
    mp_mutex_lock(&mpctx->abort_lock);
77
78
805k
    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
804k
    mp_mutex_unlock(&mpctx->abort_lock);
85
804k
}
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
801k
{
136
801k
    struct demux_free_async_state **items = NULL;
137
801k
    int num_items = 0;
138
139
1.06M
    for (int n = 0; n < num_demuxers; n++) {
140
267k
        struct demuxer *d = demuxers[n];
141
142
267k
        if (!demux_cancel_test(d)) {
143
            // Make sure it is set if it wasn't yet.
144
267k
            demux_set_wakeup_cb(d, wakeup_demux, mpctx);
145
146
267k
            struct demux_free_async_state *item = demux_free_async(d);
147
267k
            if (item) {
148
238k
                MP_TARRAY_APPEND(NULL, items, num_items, item);
149
238k
                d = NULL;
150
238k
            }
151
267k
        }
152
153
267k
        demux_cancel_and_free(d);
154
267k
    }
155
156
801k
    if (!num_items)
157
587k
        return;
158
159
213k
    MP_DBG(mpctx, "Terminating demuxers...\n");
160
161
213k
    double end = mp_time_sec() + mpctx->opts->demux_termination_timeout;
162
213k
    bool force = false;
163
908k
    while (num_items) {
164
694k
        double wait = end - mp_time_sec();
165
166
1.21M
        for (int n = 0; n < num_items; n++) {
167
755k
            struct demux_free_async_state *item = items[n];
168
755k
            if (demux_free_async_finish(item)) {
169
238k
                items[n] = items[num_items - 1];
170
238k
                num_items -= 1;
171
238k
                n--;
172
238k
                goto repeat;
173
516k
            } else if (wait < 0) {
174
34
                demux_free_async_force(item);
175
34
                if (!force)
176
34
                    MP_VERBOSE(mpctx, "Forcefully terminating demuxers...\n");
177
34
                force = true;
178
34
            }
179
755k
        }
180
181
456k
        if (wait >= 0)
182
456k
            mp_set_timeout(mpctx, wait);
183
456k
        mp_idle(mpctx);
184
694k
    repeat:;
185
694k
    }
186
187
213k
    talloc_free(items);
188
189
213k
    MP_DBG(mpctx, "Done terminating demuxers.\n");
190
213k
}
191
192
static void uninit_demuxer(struct MPContext *mpctx)
193
801k
{
194
3.20M
    for (int t = 0; t < STREAM_TYPE_COUNT; t++) {
195
5.61M
        for (int r = 0; r < num_ptracks[t]; r++)
196
3.20M
            mpctx->current_track[r][t] = NULL;
197
2.40M
    }
198
199
801k
    talloc_free(mpctx->chapters);
200
801k
    mpctx->chapters = NULL;
201
801k
    mpctx->num_chapters = 0;
202
203
801k
    mp_abort_cache_dumping(mpctx);
204
205
801k
    struct demuxer **demuxers = NULL;
206
801k
    int num_demuxers = 0;
207
208
801k
    if (mpctx->demuxer)
209
237k
        MP_TARRAY_APPEND(NULL, demuxers, num_demuxers, mpctx->demuxer);
210
801k
    mpctx->demuxer = NULL;
211
212
1.12M
    for (int i = 0; i < mpctx->num_tracks; i++) {
213
318k
        struct track *track = mpctx->tracks[i];
214
215
318k
        mp_assert(!track->dec && !track->d_sub);
216
318k
        mp_assert(!track->vo_c && !track->ao_c);
217
318k
        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
397k
        for (int n = 0; n < num_demuxers; n++) {
222
367k
            if (demuxers[n] == track->demuxer) {
223
287k
                track->demuxer = NULL;
224
287k
                break;
225
287k
            }
226
367k
        }
227
318k
        if (track->demuxer)
228
30.6k
            MP_TARRAY_APPEND(NULL, demuxers, num_demuxers, track->demuxer);
229
230
318k
        talloc_free(track);
231
318k
    }
232
801k
    mpctx->num_tracks = 0;
233
234
801k
    kill_demuxers_reentrant(mpctx, demuxers, num_demuxers);
235
801k
    talloc_free(demuxers);
236
237
801k
    disc_nav_reset(mpctx);
238
801k
}
239
240
1.09M
#define APPEND(s, ...) mp_snprintf_cat(s, sizeof(s), __VA_ARGS__)
241
7.21k
#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
450k
{
245
450k
    const char *tname = "?";
246
450k
    const char *selopt = "?";
247
450k
    const char *langopt = "?";
248
450k
    switch (t->type) {
249
194k
    case STREAM_VIDEO:
250
194k
        tname = t->image ? "Image" : "Video"; selopt = "vid"; langopt = "vlang";
251
194k
        break;
252
166k
    case STREAM_AUDIO:
253
166k
        tname = "Audio"; selopt = "aid"; langopt = "alang";
254
166k
        break;
255
89.3k
    case STREAM_SUB:
256
89.3k
        tname = "Subs"; selopt = "sid"; langopt = "slang";
257
89.3k
        break;
258
450k
    }
259
450k
    char b[2048] = {0};
260
261
450k
    int max_lang_length = 0;
262
6.13M
    for (int n = 0; n < mpctx->num_tracks; n++) {
263
5.68M
        if (mpctx->tracks[n]->lang)
264
2.92M
            max_lang_length = MPMAX(strlen(mpctx->tracks[n]->lang), max_lang_length);
265
5.68M
    }
266
267
450k
    if (indent)
268
137k
        APPEND(b, " ");
269
450k
    APPEND(b, "%s %-5s  --%s=%-2d", t->selected ? BLACK_CIRCLE : WHITE_CIRCLE,
270
450k
           tname, selopt, t->user_tid);
271
450k
    if (t->lang) {
272
54.4k
        APPEND(b, " --%s=%-*s ", langopt, max_lang_length, t->lang);
273
396k
    } else if (max_lang_length) {
274
7.21k
        FILL(b, (int) strlen(" --alang= ") + max_lang_length);
275
7.21k
    }
276
277
450k
    void *ctx = talloc_new(NULL);
278
450k
    APPEND(b, " %s", mp_format_track_metadata(ctx, t, false));
279
450k
    talloc_free(ctx);
280
281
450k
    MP_INFO(mpctx, "%s\n", b);
282
450k
}
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
3.51M
{
302
3.51M
    struct demuxer *demuxer = mpctx->demuxer;
303
3.51M
    if (!demuxer || !demuxer->edition_is_track_mapping || demuxer->num_editions <= 1)
304
3.51M
        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
3.51M
{
319
3.51M
    if (!track_in_current_edition(mpctx, track))
320
0
        return false;
321
3.51M
    if (track->dependent_track && !mpctx->opts->show_dependent_tracks)
322
1.46k
        return false;
323
3.51M
    return true;
324
3.51M
}
325
326
void print_track_list(struct MPContext *mpctx, const char *msg)
327
265k
{
328
265k
    if (mpctx->opts->term_show_tracks == 2)
329
0
        return;
330
265k
    if (msg)
331
265k
        MP_INFO(mpctx, "%s\n", msg);
332
1.06M
    for (int t = 0; t < STREAM_TYPE_COUNT; t++) {
333
2.14M
        for (int n = 0; n < mpctx->num_tracks; n++) {
334
1.35M
            struct track *track = mpctx->tracks[n];
335
1.35M
            if (track->type != t || !track_is_visible(mpctx, track))
336
903k
                continue;
337
450k
            if (mpctx->opts->term_show_tracks == 1 && !track->selected)
338
0
                continue;
339
            // Indent tracks after messages like "Tracks switched" and
340
            // "Playing:".
341
450k
            print_stream(mpctx, track, msg ||
342
314k
                         mpctx->playlist->num_entries > 1 ||
343
313k
                         mpctx->playing->playlist_path);
344
450k
        }
345
795k
    }
346
265k
}
347
348
void update_demuxer_properties(struct MPContext *mpctx)
349
14.1M
{
350
14.1M
    struct demuxer *demuxer = mpctx->demuxer;
351
14.1M
    if (!demuxer)
352
0
        return;
353
14.1M
    demux_update(demuxer, get_current_time(mpctx));
354
14.1M
    int events = demuxer->events;
355
14.1M
    if ((events & DEMUX_EVENT_INIT) && demuxer->num_editions > 1 &&
356
275
        mpctx->opts->term_show_editions != 2)
357
275
    {
358
825
        for (int n = 0; n < demuxer->num_editions; n++) {
359
550
            if (mpctx->opts->term_show_editions == 1 && n != demuxer->edition)
360
0
                continue;
361
550
            struct demux_edition *edition = &demuxer->editions[n];
362
550
            char b[128] = {0};
363
550
            if (mpctx->playlist->num_entries > 1 || mpctx->playing->playlist_path)
364
0
                APPEND(b, " ");
365
550
            APPEND(b, "%s --edition=%d", n == demuxer->edition ?
366
550
                   BLACK_CIRCLE : WHITE_CIRCLE, n);
367
550
            char *name = mp_tags_get_str(edition->metadata, "title");
368
550
            if (name)
369
0
                APPEND(b, " '%s'", name);
370
550
            if (edition->default_edition)
371
1
                APPEND(b, " [default]");
372
550
            MP_INFO(mpctx, "%s\n", b);
373
550
        }
374
275
    }
375
14.1M
    struct demuxer *tracks = mpctx->demuxer;
376
14.1M
    if (tracks->events & DEMUX_EVENT_STREAMS) {
377
230k
        int num_old_tracks = mpctx->num_tracks;
378
230k
        add_demuxer_tracks(mpctx, tracks);
379
230k
        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
230k
        if (mpctx->playback_initialized && mpctx->opts->stream_auto_sel) {
387
1.95k
            for (int t = 0; t < STREAM_TYPE_COUNT; t++) {
388
3.41k
                for (int i = 0; i < num_ptracks[t]; i++) {
389
1.95k
                    if (mpctx->current_track[i][t])
390
748
                        continue;
391
                    // The output belongs to a complex filter.
392
1.20k
                    if ((t == STREAM_VIDEO && mpctx->vo_chain) ||
393
1.20k
                        (t == STREAM_AUDIO && mpctx->ao_chain))
394
0
                        continue;
395
1.20k
                    if (mpctx->opts->stream_id[i][t] == -2)
396
488
                        continue;
397
716
                    struct track *sel = select_default_track(mpctx, i, t);
398
716
                    bool is_new = false;
399
1.44k
                    for (int n = num_old_tracks; n < mpctx->num_tracks; n++)
400
732
                        is_new |= mpctx->tracks[n] == sel;
401
716
                    if (is_new)
402
379
                        mp_switch_track_n(mpctx, i, t, sel, 0);
403
716
                }
404
1.46k
            }
405
488
        }
406
230k
        print_track_list(mpctx, NULL);
407
230k
    }
408
14.1M
    if (events & DEMUX_EVENT_METADATA) {
409
588k
        struct mp_tags *info =
410
588k
            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
588k
        struct mp_tags *prev = mpctx->filtered_tags;
413
588k
        int n_prev = 0;
414
588k
        bool had_output = false;
415
600k
        for (int n = 0; n < info->num_keys; n++) {
416
12.0k
            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
12.0k
            struct mp_log *log = mp_log_new(NULL, mpctx->log, "!display-tags");
424
12.0k
            if (!had_output)
425
5.46k
                mp_info(log, "File tags:\n");
426
12.0k
            mp_info(log, " %s: ", info->keys[n]);
427
12.0k
            const char *p = info->values[n];
428
67.1k
            while (*p) {
429
55.0k
                int len = strcspn(p, "\x8\xa\xb\xc\xd");
430
55.0k
                mp_info(log, "%.*s", len, p);
431
55.0k
                p += len;
432
55.0k
                if (*p == '\r')
433
7.97k
                    mp_info(log, " ");
434
                // Align continued lines with header
435
55.0k
                if (*p == '\n')
436
15.8k
                    mp_info(log, "\n %-*s  ", (int)strlen(info->keys[n]), "");
437
55.0k
                if (*p)
438
43.3k
                    p++;
439
55.0k
            }
440
12.0k
            mp_info(log, "\n");
441
12.0k
            had_output = true;
442
12.0k
            talloc_free(log);
443
12.0k
        }
444
588k
        talloc_free(mpctx->filtered_tags);
445
588k
        mpctx->filtered_tags = info;
446
588k
        mp_notify(mpctx, MP_EVENT_METADATA_UPDATE, NULL);
447
588k
    }
448
14.1M
    if (events & DEMUX_EVENT_DURATION)
449
481k
        mp_notify(mpctx, MP_EVENT_DURATION_UPDATE, NULL);
450
14.1M
    if (events & DEMUX_EVENT_CODEC)
451
0
        mp_notify(mpctx, MP_EVENT_TRACKS_CHANGED, NULL);
452
14.1M
    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
14.1M
    demuxer->events = 0;
476
14.1M
}
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
402k
{
484
402k
    if (!track->stream)
485
0
        return;
486
402k
    double pts = get_current_time(mpctx);
487
402k
    if (pts != MP_NOPTS_VALUE) {
488
402k
        pts += get_track_seek_offset(mpctx, track);
489
402k
        if (track->type == STREAM_SUB)
490
31.8k
            pts -= 10.0;
491
402k
    }
492
402k
    if (refresh_only)
493
0
        demuxer_refresh_track(track->demuxer, track->stream, pts);
494
402k
    else
495
402k
        demuxer_select_track(track->demuxer, track->stream, pts, track->selected);
496
402k
}
497
498
static void enable_demux_thread(struct MPContext *mpctx, struct demuxer *demux)
499
281k
{
500
281k
    if (mpctx->opts->demuxer_thread && !demux->fully_read) {
501
257k
        demux_set_wakeup_cb(demux, wakeup_demux, mpctx);
502
257k
        demux_start_thread(demux);
503
257k
    }
504
281k
}
505
506
static int find_new_tid(struct MPContext *mpctx, enum stream_type t)
507
319k
{
508
319k
    int new_id = 0;
509
1.91M
    for (int i = 0; i < mpctx->num_tracks; i++) {
510
1.59M
        struct track *track = mpctx->tracks[i];
511
1.59M
        if (track->type == t)
512
1.46M
            new_id = MPMAX(new_id, track->user_tid);
513
1.59M
    }
514
319k
    return new_id + 1;
515
319k
}
516
517
static struct track *add_stream_track(struct MPContext *mpctx,
518
                                      struct demuxer *demuxer,
519
                                      struct sh_stream *stream)
520
606k
{
521
3.70M
    for (int i = 0; i < mpctx->num_tracks; i++) {
522
3.38M
        struct track *track = mpctx->tracks[i];
523
3.38M
        if (track->stream == stream)
524
287k
            return track;
525
3.38M
    }
526
527
319k
    struct track *track = talloc_ptrtype(NULL, track);
528
319k
    *track = (struct track) {
529
319k
        .type = stream->type,
530
319k
        .user_tid = find_new_tid(mpctx, stream->type),
531
319k
        .demuxer_id = stream->demuxer_id,
532
319k
        .ff_index = stream->ff_index,
533
319k
        .hls_bitrate = stream->hls_bitrate,
534
319k
        .title = stream->title,
535
319k
        .default_track = stream->default_track,
536
319k
        .forced_track = stream->forced_track,
537
319k
        .dependent_track = stream->dependent_track,
538
319k
        .visual_impaired_track = stream->visual_impaired_track,
539
319k
        .hearing_impaired_track = stream->hearing_impaired_track,
540
319k
        .original_track = stream->original_track,
541
319k
        .commentary_track = stream->commentary_track,
542
319k
        .image = stream->image,
543
319k
        .attached_picture = stream->attached_picture != NULL,
544
319k
        .lang = stream->lang,
545
319k
        .demuxer = demuxer,
546
319k
        .stream = stream,
547
319k
    };
548
319k
    MP_TARRAY_APPEND(mpctx, mpctx->tracks, mpctx->num_tracks, track);
549
550
319k
    mp_notify(mpctx, MP_EVENT_TRACKS_CHANGED, NULL);
551
552
319k
    return track;
553
606k
}
554
555
void add_demuxer_tracks(struct MPContext *mpctx, struct demuxer *demuxer)
556
459k
{
557
1.03M
    for (int n = 0; n < demux_get_num_stream(demuxer); n++)
558
574k
        add_stream_track(mpctx, demuxer, demux_get_stream(demuxer, n));
559
459k
}
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
1.34M
{
586
1.34M
    bool sub = t2->type == STREAM_SUB;
587
1.34M
    bool ext1 = t1->is_external && !t1->no_default;
588
1.34M
    bool ext2 = t2->is_external && !t2->no_default;
589
1.34M
    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
1.34M
    if (t1->auto_loaded != t2->auto_loaded)
596
0
        return !t1->auto_loaded;
597
1.34M
    int l1 = mp_match_lang(langs, t1->lang), l2 = mp_match_lang(langs, t2->lang);
598
1.34M
    if (!os_langs && l1 != l2)
599
0
        return l1 > l2;
600
1.34M
    if (t1->forced_select != t2->forced_select)
601
6
        return t1->forced_select;
602
1.34M
    if (t1->default_track != t2->default_track)
603
1.16k
        return t1->default_track;
604
1.34M
    if (sub && t1->forced_track != t2->forced_track)
605
3
        return !t1->forced_track;
606
1.34M
    if (os_langs && l1 != l2)
607
0
        return l1 > l2;
608
1.34M
    if (t1->attached_picture != t2->attached_picture)
609
1
        return !t1->attached_picture;
610
1.34M
    if (t1->image != t2->image)
611
15
        return !t1->image;
612
1.34M
    if (t1->dependent_track != t2->dependent_track)
613
0
        return !t1->dependent_track;
614
1.34M
    if (t1->stream && t2->stream && opts->hls_bitrate >= 0 &&
615
1.34M
        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
1.34M
    return t1->user_tid <= t2->user_tid;
626
1.34M
}
627
628
static bool duplicate_track(struct MPContext *mpctx, int order,
629
                            enum stream_type type, struct track *track)
630
1.65M
{
631
1.65M
    for (int i = 0; i < order; i++) {
632
0
        if (mpctx->current_track[i][type] == track)
633
0
            return true;
634
0
    }
635
1.65M
    return false;
636
1.65M
}
637
638
static bool append_lang(size_t *nb, char ***out, char *in)
639
550
{
640
550
    if (!in)
641
0
        return false;
642
550
    MP_TARRAY_GROW(NULL, *out, *nb + 1);
643
550
    (*out)[(*nb)++] = in;
644
550
    (*out)[*nb] = NULL;
645
550
    talloc_steal(*out, in);
646
550
    return true;
647
550
}
648
649
static char **add_os_langs(void)
650
230k
{
651
230k
    size_t nb = 0;
652
230k
    char **out = NULL;
653
230k
    char **autos = mp_get_user_langs();
654
230k
    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
230k
cleanup:
660
230k
    talloc_free(autos);
661
230k
    return out;
662
230k
}
663
664
static char **process_langs(char **in)
665
721k
{
666
721k
    size_t nb = 0;
667
721k
    char **out = NULL;
668
722k
    for (int i = 0; in && in[i]; i++) {
669
550
        if (!append_lang(&nb, &out, talloc_strdup(NULL, in[i])))
670
0
            break;
671
550
    }
672
721k
    return out;
673
721k
}
674
675
struct track *select_default_track(struct MPContext *mpctx, int order,
676
                                   enum stream_type type)
677
952k
{
678
952k
    struct MPOpts *opts = mpctx->opts;
679
952k
    int tid = opts->stream_id[order][type];
680
952k
    const struct demuxer *demuxer = mpctx->demuxer;
681
952k
    if (tid == -2)
682
230k
        return NULL;
683
721k
    char **langs = process_langs(opts->stream_lang[type]);
684
721k
    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
721k
    if (type == STREAM_SUB && (!langs || !strcmp(langs[0], "")) && opts->subs_match_os_language) {
687
230k
        talloc_free(langs);
688
230k
        langs = add_os_langs();
689
230k
        os_langs = true;
690
230k
    }
691
721k
    const char *audio_lang = mpctx->current_track[0][STREAM_AUDIO] ?
692
136k
                             mpctx->current_track[0][STREAM_AUDIO]->lang :
693
721k
                             NULL;
694
721k
    bool sub = type == STREAM_SUB;
695
721k
    int *preferred_programs = NULL;
696
721k
    int num_preferred_programs = 0;
697
721k
    struct track *cvt = mpctx->current_track[0][STREAM_VIDEO];
698
721k
    bool video_has_programs = cvt && cvt->stream && cvt->stream->num_program_ids;
699
721k
    bool no_edition_mapping = !demuxer || !demuxer->edition_is_track_mapping ||
700
0
                              demuxer->num_editions <= 1;
701
721k
    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
721k
    struct track *pick = NULL;
706
4.42M
    for (int n = 0; n < mpctx->num_tracks; n++) {
707
3.70M
        struct track *track = mpctx->tracks[n];
708
3.70M
        if (track->type != type)
709
679k
            continue;
710
3.02M
        if (!track_is_visible(mpctx, track))
711
927
            continue;
712
3.02M
        if (track->user_tid == tid) {
713
152
            pick = track;
714
152
            goto cleanup;
715
152
        }
716
3.02M
        if (track->no_auto_select || track->dec_failed)
717
1.36M
            continue;
718
1.65M
        if (!opts->autoload_files && track->is_external)
719
1
            continue;
720
        // Prefer tracks from the same programs as the selected video.
721
1.65M
        bool in_program = !num_preferred_programs || track->is_external ||
722
0
                          !track->stream || !track->stream->num_program_ids;
723
1.65M
        for (int i = 0; i < num_preferred_programs && !in_program; i++)
724
0
            in_program = track_has_program(track, preferred_programs[i]);
725
1.65M
        if (!in_program)
726
0
            continue;
727
1.65M
        if (duplicate_track(mpctx, order, type, track))
728
0
            continue;
729
1.65M
        if (sub) {
730
            // Subtitle specific auto-selecting crap.
731
24.0k
            bool audio_matches = mp_match_lang((char *[]){ (char *)audio_lang, NULL }, track->lang) > 0;
732
24.0k
            bool forced = track->forced_track && (opts->subs_fallback_forced == 2 ||
733
16
                          (audio_matches && opts->subs_fallback_forced == 1));
734
24.0k
            bool lang_match = !os_langs && mp_match_lang(langs, track->lang) > 0;
735
24.0k
            bool subs_fallback = (track->is_external && !track->no_default) || opts->subs_fallback == 2 ||
736
17.1k
                                 (opts->subs_fallback == 1 && track->default_track);
737
24.0k
            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
24.0k
            if (!subs_matching_audio)
740
0
                continue;
741
24.0k
            if (!forced && !lang_match && !subs_fallback)
742
12.7k
                continue;
743
11.3k
            track->forced_select = forced;
744
11.3k
        }
745
1.64M
        if (!pick || compare_track(track, pick, langs, os_langs, mpctx->opts)) {
746
296k
            pick = track;
747
296k
        }
748
1.64M
    }
749
750
721k
    if (pick && pick->attached_picture && !mpctx->opts->audio_display)
751
0
        pick = NULL;
752
721k
cleanup:
753
721k
    talloc_free(langs);
754
721k
    return pick;
755
721k
}
756
757
static char *track_layout_hash(struct MPContext *mpctx)
758
72.1k
{
759
72.1k
    char *h = talloc_strdup(NULL, "");
760
288k
    for (int type = 0; type < STREAM_TYPE_COUNT; type++) {
761
8.94M
        for (int n = 0; n < mpctx->num_tracks; n++) {
762
8.73M
            struct track *track = mpctx->tracks[n];
763
8.73M
            if (track->type != type)
764
5.82M
                continue;
765
2.91M
            h = talloc_asprintf_append_buffer(h, "%d-%d-%d-%d-%s\n", type,
766
2.91M
                    track->user_tid, track->default_track, track->is_external,
767
2.91M
                    track->lang ? track->lang : "");
768
2.91M
        }
769
216k
    }
770
72.1k
    return h;
771
72.1k
}
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
229k
{
777
229k
    struct MPOpts *opts = mpctx->opts;
778
779
229k
    if (!mpctx->track_layout_hash)
780
229k
        return;
781
782
494
    char *h = track_layout_hash(mpctx);
783
494
    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
240
        for (int t = 0; t < STREAM_TYPE_COUNT; t++) {
787
420
            for (int i = 0; i < num_ptracks[t]; i++) {
788
240
                if (opts->stream_id[i][t] >= 0)
789
48
                    mark_track_selection(mpctx, i, t, i == 0 ? -1 : -2);
790
240
            }
791
180
        }
792
60
        talloc_free(mpctx->track_layout_hash);
793
60
        mpctx->track_layout_hash = NULL;
794
60
    }
795
494
    talloc_free(h);
796
494
}
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
67.7k
{
802
67.7k
    mp_assert(order >= 0 && order < num_ptracks[type]);
803
67.7k
    mpctx->opts->stream_id[order][type] = value;
804
67.7k
    m_config_notify_change_opt_ptr(mpctx->mconfig,
805
67.7k
                                   &mpctx->opts->stream_id[order][type]);
806
67.7k
}
807
808
void mp_switch_track_n(struct MPContext *mpctx, int order, enum stream_type type,
809
                       struct track *track, int flags)
810
71.6k
{
811
71.6k
    mp_assert(!track || track->type == type);
812
71.6k
    mp_assert(type >= 0 && type < STREAM_TYPE_COUNT);
813
71.6k
    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
71.6k
    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
71.6k
    if (!mpctx->demuxer)
822
0
        return;
823
824
71.6k
    struct track *current = mpctx->current_track[order][type];
825
71.6k
    if (track == current)
826
68
        return;
827
828
71.6k
    if (current && current->sink) {
829
0
        MP_ERR(mpctx, "Can't disable input to complex filter.\n");
830
0
        goto error;
831
0
    }
832
71.6k
    if ((type == STREAM_VIDEO && mpctx->vo_chain && !mpctx->vo_chain->track) ||
833
71.6k
        (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
71.6k
    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
71.6k
    if (order == 0) {
846
71.6k
        if (type == STREAM_VIDEO) {
847
39.8k
            uninit_video_chain(mpctx);
848
39.8k
            if (!track)
849
26.7k
                handle_force_window(mpctx, true);
850
39.8k
        } else if (type == STREAM_AUDIO) {
851
25.6k
            clear_audio_output_buffers(mpctx);
852
25.6k
            uninit_audio_chain(mpctx);
853
25.6k
            if (!track)
854
9.20k
                uninit_audio_out(mpctx);
855
25.6k
        }
856
71.6k
    }
857
71.6k
    if (type == STREAM_SUB)
858
6.16k
        uninit_sub(mpctx, current);
859
860
71.6k
    if (current) {
861
54.8k
        current->selected = false;
862
54.8k
        reselect_demux_stream(mpctx, current, false);
863
54.8k
    }
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
71.6k
    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
71.6k
    mpctx->current_track[order][type] = track;
880
881
71.6k
    if (track) {
882
34.6k
        track->selected = true;
883
34.6k
        reselect_demux_stream(mpctx, track, false);
884
34.6k
    }
885
886
71.6k
    if (type == STREAM_VIDEO && order == 0) {
887
39.8k
        reinit_video_chain(mpctx);
888
39.8k
    } else if (type == STREAM_AUDIO && order == 0) {
889
25.6k
        reinit_audio_chain(mpctx);
890
25.6k
    } else if (type == STREAM_SUB && order >= 0 && order <= 2) {
891
6.16k
        reinit_sub(mpctx, track);
892
6.16k
    }
893
894
71.6k
    mp_notify(mpctx, MP_EVENT_TRACK_SWITCHED, NULL);
895
71.6k
    mp_wakeup_core(mpctx);
896
897
71.6k
    talloc_free(mpctx->track_layout_hash);
898
71.6k
    mpctx->track_layout_hash = talloc_steal(mpctx, track_layout_hash(mpctx));
899
900
71.6k
    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
21.5k
{
913
21.5k
    if (track && track->selected) {
914
44.0k
        for (int t = 0; t < num_ptracks[track->type]; t++) {
915
22.4k
            if (mpctx->current_track[t][track->type] != track)
916
937
                continue;
917
21.5k
            mp_switch_track_n(mpctx, t, track->type, NULL, 0);
918
21.5k
            mark_track_selection(mpctx, t, track->type, -1); // default
919
21.5k
        }
920
21.5k
    }
921
21.5k
}
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
79.9k
{
976
79.9k
    struct MPOpts *opts = mpctx->opts;
977
79.9k
    if (!filename || mp_cancel_test(cancel))
978
1
        return -1;
979
980
79.9k
    void *unescaped_url = NULL;
981
79.9k
    char *disp_filename = filename;
982
79.9k
    if (strncmp(disp_filename, "memory://", 9) == 0) {
983
16.5k
        disp_filename = "memory://"; // avoid noise
984
63.4k
    } else if (mp_is_url(bstr0(disp_filename))) {
985
56.0k
        disp_filename = unescaped_url = mp_url_unescape(NULL, disp_filename);
986
56.0k
    }
987
988
79.9k
    struct demuxer_params params = {
989
79.9k
        .is_top_level = true,
990
79.9k
        .stream_flags = STREAM_ORIGIN_DIRECT,
991
79.9k
        .allow_playlist_create = false,
992
79.9k
    };
993
994
79.9k
    switch (filter) {
995
58.8k
    case STREAM_SUB:
996
58.8k
        params.force_format = opts->sub_demuxer_name;
997
58.8k
        break;
998
20.1k
    case STREAM_AUDIO:
999
20.1k
        params.force_format = opts->audio_demuxer_name;
1000
20.1k
        break;
1001
79.9k
    }
1002
1003
79.9k
    mp_core_unlock(mpctx);
1004
1005
79.9k
    char *path = mp_get_user_path(NULL, mpctx->global, filename);
1006
79.9k
    struct demuxer *demuxer =
1007
79.9k
        demux_open_url(path, &params, cancel, mpctx->global);
1008
79.9k
    talloc_free(path);
1009
1010
79.9k
    if (demuxer)
1011
51.4k
        enable_demux_thread(mpctx, demuxer);
1012
1013
79.9k
    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
79.9k
    if (mpctx->stop_play)
1018
295
        goto err_out;
1019
1020
79.6k
    if (!demuxer)
1021
28.2k
        goto err_out;
1022
1023
51.4k
    if (filter != STREAM_SUB && opts->rebase_start_time)
1024
20.3k
        demux_set_ts_offset(demuxer, -demuxer->start_time);
1025
1026
51.4k
    bool has_any = false;
1027
93.1k
    for (int n = 0; n < demux_get_num_stream(demuxer); n++) {
1028
73.2k
        struct sh_stream *sh = demux_get_stream(demuxer, n);
1029
73.2k
        if (sh->type == filter || filter == STREAM_TYPE_COUNT) {
1030
31.5k
            has_any = true;
1031
31.5k
            break;
1032
31.5k
        }
1033
73.2k
    }
1034
1035
51.4k
    if (!has_any) {
1036
19.9k
        char *tname = mp_tprintf(20, "%s ", stream_type_name(filter));
1037
19.9k
        if (filter == STREAM_TYPE_COUNT)
1038
0
            tname = "";
1039
19.9k
        MP_ERR(mpctx, "No %sstreams in file %s.\n", tname, disp_filename);
1040
19.9k
        goto err_out;
1041
19.9k
    }
1042
1043
31.5k
    int first_num = -1;
1044
63.3k
    for (int n = 0; n < demux_get_num_stream(demuxer); n++) {
1045
31.8k
        struct sh_stream *sh = demux_get_stream(demuxer, n);
1046
31.8k
        struct track *t = add_stream_track(mpctx, demuxer, sh);
1047
31.8k
        t->is_external = true;
1048
31.8k
        if (sh->title && sh->title[0]) {
1049
0
            t->title = talloc_strdup(t, sh->title);
1050
31.8k
        } else {
1051
31.8k
            bstr parent = {0};
1052
31.8k
            if (mpctx->filename)
1053
31.8k
                parent = mp_strip_ext(bstr0(mp_basename(mpctx->filename)));
1054
31.8k
            bstr title = bstr0(mp_basename(disp_filename));
1055
31.8k
            bstr_eatstart(&title, parent);
1056
31.8k
            bstr_eatstart(&title, bstr0("."));
1057
31.8k
            if (title.len)
1058
27.1k
                t->title = bstrdup0(t, title);
1059
31.8k
        }
1060
31.8k
        t->external_filename = mp_normalize_user_path(t, mpctx->global, filename);
1061
31.8k
        t->no_default = sh->type != filter;
1062
31.8k
        t->no_auto_select = t->no_default;
1063
31.8k
        t->hearing_impaired_track = flags & TRACK_HEARING_IMPAIRED;
1064
31.8k
        t->visual_impaired_track = flags & TRACK_VISUAL_IMPAIRED;
1065
31.8k
        t->forced_track = flags & TRACK_FORCED;
1066
31.8k
        t->default_track = flags & TRACK_DEFAULT;
1067
31.8k
        t->commentary_track = flags & TRACK_COMMENTARY;
1068
        // if we found video, and we are loading cover art, flag as such.
1069
31.8k
        t->attached_picture = t->type == STREAM_VIDEO && (flags & TRACK_ATTACHED_PICTURE);
1070
31.8k
        if (first_num < 0 && (filter == STREAM_TYPE_COUNT || sh->type == filter))
1071
31.5k
            first_num = mpctx->num_tracks - 1;
1072
31.8k
    }
1073
1074
31.5k
    mp_cancel_set_parent(demuxer->cancel, mpctx->playback_abort);
1075
1076
31.5k
    talloc_free(unescaped_url);
1077
31.5k
    return first_num;
1078
1079
48.4k
err_out:
1080
48.4k
    demux_cancel_and_free(demuxer);
1081
48.4k
    if (!mp_cancel_test(cancel))
1082
48.4k
        MP_ERR(mpctx, "Can not open external file %s.\n", disp_filename);
1083
48.4k
    talloc_free(unescaped_url);
1084
48.4k
    return -1;
1085
51.4k
}
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
919k
{
1091
    // Need a copy, because the option value could be mutated during iteration.
1092
919k
    void *tmp = talloc_new(NULL);
1093
919k
    files = mp_dup_str_array(tmp, files);
1094
1095
971k
    for (int n = 0; files && files[n]; n++)
1096
        // when given filter is set to video, we are loading up cover art
1097
52.6k
        mp_add_external_file(mpctx, files[n], filter, mpctx->playback_abort,
1098
52.6k
                             filter == STREAM_VIDEO ? TRACK_ATTACHED_PICTURE : 0);
1099
1100
919k
    talloc_free(tmp);
1101
919k
}
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
229k
{
1106
229k
    struct MPOpts *opts = mpctx->opts;
1107
1108
229k
    if (opts->sub_auto < 0 && opts->audiofile_auto < 0 && opts->coverart_auto < 0)
1109
0
        return;
1110
229k
    if (!opts->autoload_files || strcmp(mpctx->filename, "-") == 0)
1111
1
        return;
1112
1113
229k
    void *tmp = talloc_new(NULL);
1114
229k
    struct subfn *list = find_external_files(mpctx->global, mpctx->filename, opts);
1115
229k
    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
229k
    int sc[STREAM_TYPE_COUNT + 1] = {0};
1120
544k
    for (int n = 0; n < mpctx->num_tracks; n++) {
1121
314k
        mp_assert(mpctx->tracks[n]->type >= 0);
1122
314k
        mp_assert(mpctx->tracks[n]->type <= STREAM_TYPE_COUNT);
1123
314k
        if (!mpctx->tracks[n]->attached_picture)
1124
313k
            sc[mpctx->tracks[n]->type]++;
1125
314k
    }
1126
1127
229k
    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
229k
    talloc_free(tmp);
1159
229k
}
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
312k
{
1165
312k
    struct MPOpts *opts = mpctx->opts;
1166
312k
    struct playlist_entry *entry = NULL;
1167
1168
312k
    if (overwrite_current)
1169
10.8k
        pl->current = NULL;
1170
1171
312k
    pl->playlist_completed = false;
1172
312k
    pl->playlist_started = false;
1173
1174
312k
    if (opts->playlist_pos >= 0) {
1175
31
        entry = playlist_entry_from_index(pl, opts->playlist_pos);
1176
31
        pl->current = overwrite_current || entry ? entry : pl->current;
1177
31
    }
1178
1179
312k
    if (pl->playlist_dir)
1180
0
        playlist_set_current(pl);
1181
1182
312k
    if (opts->shuffle)
1183
29
        playlist_shuffle(pl);
1184
1185
312k
    if (opts->merge_files)
1186
98
        merge_playlist_files(pl);
1187
1188
312k
    if (!pl->current || (!overwrite_current && !entry)) {
1189
312k
        entry = mp_check_playlist_resume(mpctx, pl);
1190
312k
        pl->current = overwrite_current || entry ? entry : pl->current;
1191
312k
    }
1192
1193
312k
    if (!pl->current)
1194
312k
        pl->current = playlist_get_first(pl);
1195
312k
}
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
6.91k
{
1203
6.91k
    if (pl->num_entries) {
1204
6.47k
        prepare_playlist(mpctx, pl, true);
1205
6.47k
        struct playlist_entry *new = pl->current;
1206
6.47k
        struct playlist_entry *current = mpctx->playlist->current;
1207
6.47k
        *num_new_entries = pl->num_entries;
1208
6.47k
        if (current && mpctx->opts->playlist_inherit_options == 1)
1209
0
            playlist_set_params(pl, current->params, current->num_params);
1210
6.47k
        else if (current && new && mpctx->opts->playlist_inherit_options == 2)
1211
0
            playlist_entry_add_params(new, current->params, current->num_params);
1212
6.47k
        *start_id = playlist_transfer_entries(mpctx->playlist, pl);
1213
        // current entry is replaced
1214
6.47k
        if (current)
1215
6.47k
            playlist_remove(mpctx->playlist, current);
1216
6.47k
        if (new)
1217
6.47k
            mpctx->playlist->current = new;
1218
6.47k
        mpctx->playlist->playlist_dir = talloc_steal(mpctx->playlist, pl->playlist_dir);
1219
6.47k
    } else {
1220
434
        MP_WARN(mpctx, "Empty playlist!\n");
1221
434
    }
1222
6.91k
}
1223
1224
static void process_hooks(struct MPContext *mpctx, char *name)
1225
3.17M
{
1226
3.17M
    mp_hook_start(mpctx, name);
1227
1228
3.17M
    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
3.17M
}
1237
1238
// to be run on a worker thread, locked (temporarily unlocks core)
1239
static void load_chapters(struct MPContext *mpctx)
1240
229k
{
1241
229k
    struct demuxer *src = mpctx->demuxer;
1242
229k
    bool free_src = false;
1243
229k
    char *chapter_file = mpctx->opts->chapter_file;
1244
229k
    if (chapter_file && chapter_file[0]) {
1245
4
        chapter_file = mp_get_user_path(NULL, mpctx->global, chapter_file);
1246
4
        mp_core_unlock(mpctx);
1247
4
        struct demuxer_params p = {
1248
4
            .stream_flags = STREAM_ORIGIN_DIRECT,
1249
4
            .depth = src ? src->depth + 1 : 0,
1250
4
        };
1251
4
        struct demuxer *demux = demux_open_url(chapter_file, &p,
1252
4
                                               mpctx->playback_abort,
1253
4
                                               mpctx->global);
1254
4
        mp_core_lock(mpctx);
1255
4
        if (demux) {
1256
0
            src = demux;
1257
0
            free_src = true;
1258
0
        }
1259
4
        talloc_free(mpctx->chapters);
1260
4
        mpctx->chapters = NULL;
1261
4
        talloc_free(chapter_file);
1262
4
    }
1263
229k
    if (src && !mpctx->chapters) {
1264
229k
        talloc_free(mpctx->chapters);
1265
229k
        mpctx->num_chapters = src->num_chapters;
1266
229k
        mpctx->chapters = demux_copy_chapter_data(src->chapters, src->num_chapters);
1267
229k
        if (mpctx->opts->rebase_start_time) {
1268
289k
            for (int n = 0; n < mpctx->num_chapters; n++)
1269
60.1k
                mpctx->chapters[n].pts -= src->start_time;
1270
229k
        }
1271
229k
    }
1272
229k
    if (free_src)
1273
0
        demux_cancel_and_free(src);
1274
229k
}
1275
1276
static void load_per_file_options(m_config_t *conf,
1277
                                  struct playlist_param *params,
1278
                                  int params_count)
1279
272k
{
1280
272k
    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
272k
}
1285
1286
static MP_THREAD_VOID open_demux_thread(void *ctx)
1287
272k
{
1288
272k
    struct MPContext *mpctx = ctx;
1289
1290
272k
    mp_thread_set_name("opener");
1291
1292
272k
    struct demuxer_params p = {
1293
272k
        .force_format = mpctx->open_format,
1294
272k
        .stream_flags = mpctx->open_url_flags,
1295
272k
        .stream_record = true,
1296
272k
        .is_top_level = true,
1297
272k
        .allow_playlist_create = mpctx->playlist->num_entries <= 1 &&
1298
268k
                                 !mpctx->playlist->playlist_dir,
1299
272k
    };
1300
272k
    struct demuxer *demux =
1301
272k
        demux_open_url(mpctx->open_url, &p, mpctx->open_cancel, mpctx->global);
1302
272k
    mpctx->open_res_demuxer = demux;
1303
1304
272k
    if (demux) {
1305
237k
        MP_VERBOSE(mpctx, "Opening done: %s\n", mpctx->open_url);
1306
1307
237k
        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
237k
    } else {
1319
35.3k
        MP_VERBOSE(mpctx, "Opening failed or was aborted: %s\n", mpctx->open_url);
1320
1321
35.3k
        if (p.demuxer_failed) {
1322
29.4k
            mpctx->open_res_error = MPV_ERROR_UNKNOWN_FORMAT;
1323
29.4k
        } else {
1324
5.86k
            mpctx->open_res_error = MPV_ERROR_LOADING_FAILED;
1325
5.86k
        }
1326
35.3k
    }
1327
1328
272k
    atomic_store(&mpctx->open_done, true);
1329
272k
    mp_wakeup_core(mpctx);
1330
272k
    MP_THREAD_RETURN();
1331
272k
}
1332
1333
static void cancel_open(struct MPContext *mpctx)
1334
846k
{
1335
846k
    if (mpctx->open_cancel)
1336
272k
        mp_cancel_trigger(mpctx->open_cancel);
1337
1338
846k
    if (mpctx->open_active)
1339
272k
        mp_thread_join(mpctx->open_thread);
1340
846k
    mpctx->open_active = false;
1341
1342
846k
    if (mpctx->open_res_demuxer)
1343
0
        demux_cancel_and_free(mpctx->open_res_demuxer);
1344
846k
    mpctx->open_res_demuxer = NULL;
1345
1346
846k
    TA_FREEP(&mpctx->open_cancel);
1347
846k
    TA_FREEP(&mpctx->open_url);
1348
846k
    TA_FREEP(&mpctx->open_format);
1349
1350
846k
    atomic_store(&mpctx->open_done, false);
1351
846k
}
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
272k
{
1357
272k
    cancel_open(mpctx);
1358
1359
272k
    mp_assert(!mpctx->open_active);
1360
272k
    mp_assert(!mpctx->open_cancel);
1361
272k
    mp_assert(!mpctx->open_res_demuxer);
1362
272k
    mp_assert(!atomic_load(&mpctx->open_done));
1363
1364
272k
    mpctx->open_cancel = mp_cancel_new(NULL);
1365
272k
    mpctx->open_url = talloc_strdup(NULL, url);
1366
272k
    mpctx->open_format = talloc_strdup(NULL, mpctx->opts->demuxer_name);
1367
272k
    mpctx->open_url_flags = url_flags;
1368
272k
    mpctx->open_for_prefetch = for_prefetch && mpctx->opts->demuxer_thread;
1369
272k
    mpctx->demuxer_changed = false;
1370
1371
272k
    if (mp_thread_create(&mpctx->open_thread, open_demux_thread, mpctx)) {
1372
0
        cancel_open(mpctx);
1373
0
        return;
1374
0
    }
1375
1376
272k
    mpctx->open_active = true;
1377
272k
}
1378
1379
static void open_demux_reentrant(struct MPContext *mpctx)
1380
272k
{
1381
272k
    char *url = mpctx->stream_open_filename;
1382
1383
272k
    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
272k
    if (!mpctx->open_active)
1411
272k
        start_open(mpctx, url, mpctx->playing->stream_flags, false);
1412
1413
    // If thread failed to start, cancel the playback
1414
272k
    if (!mpctx->open_active)
1415
0
        goto cancel;
1416
1417
    // User abort should cancel the opener now.
1418
272k
    mp_cancel_set_parent(mpctx->open_cancel, mpctx->playback_abort);
1419
1420
854k
    while (!atomic_load(&mpctx->open_done)) {
1421
581k
        mp_idle(mpctx);
1422
1423
581k
        if (mpctx->stop_play)
1424
3.04k
            mp_abort_playback_async(mpctx);
1425
581k
    }
1426
1427
272k
    if (mpctx->open_res_demuxer) {
1428
237k
        mpctx->demuxer = mpctx->open_res_demuxer;
1429
237k
        mpctx->open_res_demuxer = NULL;
1430
237k
        mp_cancel_set_parent(mpctx->demuxer->cancel, mpctx->playback_abort);
1431
237k
    } else {
1432
35.3k
        mpctx->error_playing = mpctx->open_res_error;
1433
35.3k
    }
1434
1435
272k
cancel:
1436
272k
    cancel_open(mpctx); // cleanup
1437
272k
}
1438
1439
void prefetch_next(struct MPContext *mpctx)
1440
12.1M
{
1441
12.1M
    if (!mpctx->opts->prefetch_open || mpctx->open_active)
1442
12.1M
        return;
1443
1444
6
    struct playlist_entry *new_entry = mp_next_file(mpctx, +1, false, false);
1445
6
    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
6
}
1450
1451
static void clear_playlist_paths(struct MPContext *mpctx)
1452
193k
{
1453
193k
    TA_FREEP(&mpctx->playlist_paths);
1454
193k
    mpctx->playlist_paths_len = 0;
1455
193k
}
1456
1457
static bool infinite_playlist_loading_loop(struct MPContext *mpctx, struct playlist *pl)
1458
7.15k
{
1459
7.15k
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1460
7.15k
    if (mpctx->playlist_paths_len >= 10) {
1461
119
        clear_playlist_paths(mpctx);
1462
119
        return true;
1463
119
    }
1464
7.04k
#endif
1465
7.04k
    if (pl->num_entries) {
1466
6.60k
        struct playlist_entry *e = pl->entries[0];
1467
16.2k
        for (int n = 0; n < mpctx->playlist_paths_len; n++) {
1468
9.73k
            if (strcmp(mpctx->playlist_paths[n], e->filename) == 0) {
1469
128
                clear_playlist_paths(mpctx);
1470
128
                return true;
1471
128
            }
1472
9.73k
        }
1473
6.60k
    }
1474
6.91k
    MP_TARRAY_APPEND(mpctx, mpctx->playlist_paths, mpctx->playlist_paths_len,
1475
6.91k
                     talloc_strdup(mpctx->playlist_paths, mpctx->filename));
1476
6.91k
    return false;
1477
7.04k
}
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
2
{
1484
6
    for (int n = 0; n < mpctx->num_tracks; n++)
1485
4
        mpctx->tracks[n]->sink = NULL;
1486
2
    if (mpctx->vo_chain)
1487
0
        mpctx->vo_chain->filter_src = NULL;
1488
2
    if (mpctx->ao_chain)
1489
0
        mpctx->ao_chain->filter_src = NULL;
1490
2
    TA_FREEP(&mpctx->lavfi);
1491
2
    TA_FREEP(&mpctx->lavfi_graph);
1492
2
}
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
1
{
1498
3
    for (int n = 0; n < mpctx->num_tracks; n++) {
1499
2
        struct track *track = mpctx->tracks[n];
1500
2
        if (!(track->sink || track->vo_c || track->ao_c)) {
1501
2
            if (track->dec && !track->vo_c && !track->ao_c) {
1502
0
                talloc_free(track->dec->f);
1503
0
                track->dec = NULL;
1504
0
            }
1505
2
            track->selected = false;
1506
2
        }
1507
2
    }
1508
1509
1
    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
1
    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
1
}
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
1.03M
{
1534
1.03M
    char *graph = mpctx->opts->lavfi_complex;
1535
1.03M
    bool have_graph = graph && graph[0] && !force_uninit;
1536
1.03M
    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
1.03M
    if (!mpctx->lavfi && !have_graph)
1541
1.03M
        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
1
    deassociate_complex_filters(mpctx);
1549
1550
1
    bool success = false;
1551
1
    if (!have_graph) {
1552
0
        success = true; // normal full removal of graph
1553
0
        goto done;
1554
0
    }
1555
1556
1
    struct mp_lavfi *l =
1557
1
        mp_lavfi_create_graph(mpctx->filter_root, 0, false, NULL, NULL, graph);
1558
1
    if (!l)
1559
1
        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
1
done:
1649
1650
1
    if (!success)
1651
1
        deassociate_complex_filters(mpctx);
1652
1653
1
    cleanup_deassociated_complex_filters(mpctx);
1654
1655
1
    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
1
    mp_notify(mpctx, MP_EVENT_TRACKS_CHANGED, NULL);
1665
1666
1
    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
14.3M
{
1673
14.3M
    if (!mpctx->vo_chain || !mpctx->vo_chain->filter)
1674
1.61M
        return;
1675
12.6M
    struct track *track = mpctx->current_track[0][STREAM_VIDEO];
1676
12.6M
    mp_output_chain_set_el_stream(mpctx->vo_chain->filter,
1677
12.6M
        track ? sh_stream_dependent_sibling(track->stream) : NULL);
1678
12.6M
}
1679
1680
void update_lavfi_complex(struct MPContext *mpctx)
1681
301k
{
1682
301k
    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
301k
}
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
229k
{
1696
229k
    void **a = p;
1697
229k
    struct MPContext *mpctx = a[0];
1698
229k
    struct mp_waiter *waiter = a[1];
1699
1700
229k
    mp_core_lock(mpctx);
1701
1702
229k
    load_chapters(mpctx);
1703
229k
    open_external_files(mpctx, mpctx->opts->audio_files, STREAM_AUDIO);
1704
229k
    open_external_files(mpctx, mpctx->opts->sub_name, STREAM_SUB);
1705
229k
    open_external_files(mpctx, mpctx->opts->coverart_files, STREAM_VIDEO);
1706
229k
    open_external_files(mpctx, mpctx->opts->external_files, STREAM_TYPE_COUNT);
1707
229k
    autoload_external_files(mpctx, mpctx->playback_abort);
1708
1709
229k
    mp_waiter_wakeup(waiter, 0);
1710
229k
    mp_wakeup_core(mpctx);
1711
229k
    mp_core_unlock(mpctx);
1712
229k
}
1713
1714
static void load_external_opts(struct MPContext *mpctx)
1715
229k
{
1716
229k
    struct mp_waiter wait = MP_WAITER_INITIALIZER;
1717
1718
229k
    void *a[] = {mpctx, &wait};
1719
229k
    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
459k
    while (!mp_waiter_poll(&wait)) {
1725
229k
        mp_idle(mpctx);
1726
1727
229k
        if (mpctx->stop_play)
1728
35
            mp_abort_playback_async(mpctx);
1729
229k
    }
1730
1731
229k
    mp_waiter_wait(&wait);
1732
229k
}
1733
1734
static void append_to_watch_history(struct MPContext *mpctx)
1735
192k
{
1736
192k
    if (!mpctx->opts->save_watch_history)
1737
192k
        return;
1738
1739
3
    void *ctx = talloc_new(NULL);
1740
3
    char *history_path = mp_get_user_path(ctx, mpctx->global,
1741
3
                                          mpctx->opts->watch_history_path);
1742
3
    char *history_path_dir = bstrto0(ctx, mp_dirname(history_path));
1743
3
    mp_mkdirp(history_path_dir);
1744
1745
3
    FILE *history_file = fopen(history_path, "ab");
1746
3
    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
3
    char *title = (char *)mp_find_non_filename_media_title(mpctx);
1753
1754
3
    mpv_node_list *list = talloc_zero(ctx, mpv_node_list);
1755
3
    mpv_node node = {
1756
3
        .format = MPV_FORMAT_NODE_MAP,
1757
3
        .u.list = list,
1758
3
    };
1759
3
    list->num = title ? 3 : 2;
1760
3
    list->keys = talloc_array(ctx, char*, list->num);
1761
3
    list->values = talloc_array(ctx, mpv_node, list->num);
1762
3
    list->keys[0] = "time";
1763
3
    list->values[0] = (struct mpv_node) {
1764
3
        .format = MPV_FORMAT_INT64,
1765
3
        .u.int64 = time(NULL),
1766
3
    };
1767
3
    list->keys[1] = "path";
1768
3
    list->values[1] = (struct mpv_node) {
1769
3
        .format = MPV_FORMAT_STRING,
1770
3
        .u.string = mpctx->filename,
1771
3
    };
1772
3
    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
3
    bstr dst = {0};
1781
3
    json_append(&dst, &node, -1);
1782
3
    talloc_steal(ctx, dst.start);
1783
3
    if (!dst.len) {
1784
0
        MP_ERR(mpctx, "Failed to serialize history entry\n");
1785
0
        goto done;
1786
0
    }
1787
3
    bstr_xappend0(ctx, &dst, "\n");
1788
1789
3
    int seek = fseek(history_file, 0, SEEK_END);
1790
3
    off_t history_size = ftell(history_file);
1791
3
    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
3
    bool failed = fwrite(dst.start, dst.len, 1, history_file) != 1 ||
1798
3
                  fflush(history_file) != 0;
1799
1800
3
    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
3
done:
1811
3
    if (history_file != NULL && fclose(history_file) != 0)
1812
3
        MP_ERR(mpctx, "Failed to close history file: %s\n", mp_strerror(errno));
1813
1814
3
    talloc_free(ctx);
1815
3
}
1816
1817
// Start playing the current playlist entry.
1818
// Handle initialization and deinitialization.
1819
static void play_current_file(struct MPContext *mpctx)
1820
801k
{
1821
801k
    struct MPOpts *opts = mpctx->opts;
1822
1823
801k
    mp_assert(mpctx->stop_play);
1824
801k
    mpctx->stop_play = 0;
1825
1826
801k
    process_hooks(mpctx, "on_before_start_file");
1827
801k
    if (mpctx->stop_play || !mpctx->playlist->current)
1828
0
        return;
1829
1830
801k
    mpv_event_start_file start_event = {
1831
801k
        .playlist_entry_id = mpctx->playlist->current->id,
1832
801k
    };
1833
801k
    mpv_event_end_file end_event = {
1834
801k
        .playlist_entry_id = start_event.playlist_entry_id,
1835
801k
    };
1836
1837
801k
    mp_notify(mpctx, MPV_EVENT_START_FILE, &start_event);
1838
1839
801k
    mp_cancel_reset(mpctx->playback_abort);
1840
1841
801k
    mpctx->error_playing = MPV_ERROR_LOADING_FAILED;
1842
801k
    mpctx->filename = NULL;
1843
801k
    mpctx->shown_aframes = 0;
1844
801k
    mpctx->shown_vframes = 0;
1845
801k
    mpctx->last_chapter_seek = -2;
1846
801k
    mpctx->last_chapter_flag = false;
1847
801k
    mpctx->last_chapter = -2;
1848
801k
    mpctx->paused = false;
1849
801k
    mpctx->playing_msg_shown = false;
1850
801k
    mpctx->max_frames = -1;
1851
801k
    mpctx->video_speed = mpctx->audio_speed = opts->playback_speed;
1852
801k
    mpctx->speed_factor_a = mpctx->speed_factor_v = 1.0;
1853
801k
    mpctx->display_sync_error = 0.0;
1854
801k
    mpctx->display_sync_active = false;
1855
    // let get_current_time() show 0 as start time (before playback_pts is set)
1856
801k
    mpctx->last_seek_pts = 0.0;
1857
801k
    mpctx->seek = (struct seek_params){ 0 };
1858
801k
    disc_nav_reset(mpctx);
1859
801k
    mpctx->filter_root = mp_filter_create_root(mpctx->global);
1860
801k
    mp_filter_graph_set_wakeup_cb(mpctx->filter_root, mp_wakeup_core_cb, mpctx);
1861
801k
    mp_filter_graph_set_max_run_time(mpctx->filter_root, 0.1);
1862
1863
801k
    reset_playback_state(mpctx);
1864
1865
801k
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1866
801k
    if (mpctx->playlist->num_entries > 3)
1867
529k
        goto terminate_playback;
1868
272k
#endif
1869
1870
272k
    mpctx->playing = mpctx->playlist->current;
1871
272k
    mp_assert(mpctx->playing);
1872
272k
    mp_assert(mpctx->playing->filename);
1873
272k
    mpctx->playing->reserved += 1;
1874
1875
272k
    mpctx->filename = talloc_strdup(NULL, mpctx->playing->filename);
1876
272k
    mpctx->stream_open_filename = mpctx->filename;
1877
1878
272k
    mpctx->add_osd_seek_info &= OSD_SEEK_INFO_CURRENT_FILE;
1879
1880
272k
    if (opts->reset_options) {
1881
3.62k
        for (int n = 0; opts->reset_options[n]; n++) {
1882
3.53k
            const char *opt = opts->reset_options[n];
1883
3.53k
            if (opt[0]) {
1884
1.75k
                if (strcmp(opt, "all") == 0) {
1885
49
                    m_config_backup_all_opts(mpctx->mconfig);
1886
1.70k
                } else {
1887
1.70k
                    m_config_backup_opt(mpctx->mconfig, opt);
1888
1.70k
                }
1889
1.75k
            }
1890
3.53k
        }
1891
87
    }
1892
1893
272k
    mp_load_auto_profiles(mpctx);
1894
1895
272k
    bool watch_later = mp_load_playback_resume(mpctx, mpctx->filename);
1896
1897
272k
    load_per_file_options(mpctx->mconfig, mpctx->playing->params,
1898
272k
                          mpctx->playing->num_params);
1899
1900
272k
    mpctx->remaining_file_loops = mpctx->opts->loop_file;
1901
272k
    mp_notify_property(mpctx, "remaining-file-loops");
1902
272k
    mpctx->remaining_ab_loops = mpctx->opts->ab_loop_count;
1903
272k
    mp_notify_property(mpctx, "remaining-ab-loops");
1904
1905
272k
    mpctx->max_frames = opts->play_frames;
1906
1907
272k
    handle_force_window(mpctx, false);
1908
1909
272k
    if (mpctx->playlist->num_entries > 1 ||
1910
268k
        mpctx->playing->playlist_path)
1911
272k
        MP_INFO(mpctx, "Playing: %s\n", mpctx->filename);
1912
1913
272k
    mp_assert(mpctx->demuxer == NULL);
1914
1915
272k
    process_hooks(mpctx, "on_load");
1916
272k
    if (mpctx->stop_play)
1917
0
        goto terminate_playback;
1918
1919
272k
    if (opts->stream_dump && opts->stream_dump[0]) {
1920
1
        if (stream_dump(mpctx, mpctx->stream_open_filename) >= 0)
1921
1
            mpctx->error_playing = 1;
1922
1
        goto terminate_playback;
1923
1
    }
1924
1925
272k
    open_demux_reentrant(mpctx);
1926
272k
    if (!mpctx->stop_play && !mpctx->demuxer) {
1927
34.3k
        process_hooks(mpctx, "on_load_fail");
1928
34.3k
        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
34.3k
    }
1935
272k
    if (!mpctx->demuxer || mpctx->stop_play)
1936
35.6k
        goto terminate_playback;
1937
1938
236k
    struct playlist *pl = mpctx->demuxer->playlist;
1939
236k
    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
7.15k
        if (watch_later && !pl->playlist_dir)
1943
0
            mp_delete_watch_later_conf(mpctx, mpctx->filename);
1944
7.15k
        playlist_populate_playlist_path(pl, mpctx->filename);
1945
7.15k
        if (infinite_playlist_loading_loop(mpctx, pl)) {
1946
247
            mpctx->stop_play = PT_STOP;
1947
247
            MP_ERR(mpctx, "Infinite playlist loading loop detected.\n");
1948
247
            goto terminate_playback;
1949
247
        }
1950
6.91k
        transfer_playlist(mpctx, pl, &end_event.playlist_insert_id,
1951
6.91k
                          &end_event.playlist_insert_num_entries);
1952
6.91k
        mp_notify_property(mpctx, "playlist");
1953
6.91k
        mpctx->error_playing = 2;
1954
6.91k
        goto terminate_playback;
1955
7.15k
    }
1956
1957
229k
    if (mpctx->opts->rebase_start_time)
1958
229k
        demux_set_ts_offset(mpctx->demuxer, -mpctx->demuxer->start_time);
1959
229k
    enable_demux_thread(mpctx, mpctx->demuxer);
1960
1961
229k
    add_demuxer_tracks(mpctx, mpctx->demuxer);
1962
1963
229k
    load_external_opts(mpctx);
1964
229k
    if (mpctx->stop_play)
1965
31
        goto terminate_playback;
1966
1967
229k
    check_previous_track_selection(mpctx);
1968
1969
229k
    process_hooks(mpctx, "on_preloaded");
1970
229k
    if (mpctx->stop_play)
1971
0
        goto terminate_playback;
1972
1973
229k
    if (reinit_complex_filters(mpctx, false) < 0)
1974
1
        goto terminate_playback;
1975
1976
918k
    for (int t = 0; t < STREAM_TYPE_COUNT; t++) {
1977
1.60M
        for (int i = 0; i < num_ptracks[t]; i++) {
1978
918k
            struct track *sel = NULL;
1979
918k
            bool taken = (t == STREAM_VIDEO && mpctx->vo_chain) ||
1980
918k
                         (t == STREAM_AUDIO && mpctx->ao_chain);
1981
918k
            if (!taken && opts->stream_auto_sel)
1982
918k
                sel = select_default_track(mpctx, i, t);
1983
918k
            mpctx->current_track[i][t] = sel;
1984
918k
        }
1985
689k
    }
1986
918k
    for (int t = 0; t < STREAM_TYPE_COUNT; t++) {
1987
1.60M
        for (int i = 0; i < num_ptracks[t]; i++) {
1988
            // One track can strictly feed at most 1 decoder
1989
918k
            struct track *track = mpctx->current_track[i][t];
1990
918k
            if (track) {
1991
280k
                if (track->type != STREAM_SUB &&
1992
271k
                    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
280k
                } 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
280k
                } else {
2006
280k
                    track->selected = true;
2007
280k
                }
2008
280k
            }
2009
2010
            // Revert selection of unselected tracks to default. This is needed
2011
            // because track properties have inconsistent behavior.
2012
918k
            if (!track && opts->stream_id[i][t] >= 0)
2013
44
                mark_track_selection(mpctx, i, t, -1); // default
2014
918k
        }
2015
689k
    }
2016
2017
229k
    process_hooks(mpctx, "on_loaded");
2018
918k
    for (int t = 0; t < STREAM_TYPE_COUNT; t++) {
2019
1.63M
        for (int n = 0; n < mpctx->num_tracks; n++) {
2020
941k
            struct track *track = mpctx->tracks[n];
2021
941k
            if (track->type != t)
2022
627k
                continue;
2023
            // Only reselect dependent tracks when explicitly selected by user
2024
313k
            if (track->stream && track->stream->dependent_track &&
2025
535
                !track->selected)
2026
535
                continue;
2027
313k
            reselect_demux_stream(mpctx, track, false);
2028
313k
        }
2029
689k
    }
2030
2031
229k
    update_demuxer_properties(mpctx);
2032
2033
229k
    update_playback_speed(mpctx);
2034
2035
229k
    reinit_video_chain(mpctx);
2036
229k
    reinit_audio_chain(mpctx);
2037
229k
    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
229k
    update_vo_chain_el_pair(mpctx);
2041
2042
229k
    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
229k
    if (!mpctx->vo_chain && !mpctx->ao_chain && opts->stream_auto_sel) {
2052
36.9k
        MP_FATAL(mpctx, "No video or audio streams selected.\n");
2053
36.9k
        mpctx->error_playing = MPV_ERROR_NOTHING_TO_PLAY;
2054
36.9k
        goto terminate_playback;
2055
36.9k
    }
2056
2057
192k
    if (mpctx->vo_chain && mpctx->vo_chain->is_coverart) {
2058
291
        MP_INFO(mpctx,
2059
291
            "Displaying cover art. Use --no-audio-display to prevent this.\n");
2060
291
    }
2061
2062
192k
    if (!mpctx->vo_chain)
2063
50.2k
        handle_force_window(mpctx, true);
2064
2065
192k
    MP_VERBOSE(mpctx, "Starting playback...\n");
2066
2067
192k
    mpctx->playback_initialized = true;
2068
192k
    mpctx->playing->playlist_prev_attempt = false;
2069
192k
    mpctx->playlist->playlist_completed = false;
2070
192k
    mpctx->playlist->playlist_started = true;
2071
192k
    mp_notify(mpctx, MPV_EVENT_FILE_LOADED, NULL);
2072
192k
    update_screensaver_state(mpctx);
2073
192k
    clear_playlist_paths(mpctx);
2074
2075
    // Clear out subs from the previous file if the video track is a still image.
2076
192k
    redraw_subs(mpctx);
2077
2078
192k
    if (watch_later)
2079
0
        mp_delete_watch_later_conf(mpctx, mpctx->filename);
2080
2081
192k
    append_to_watch_history(mpctx);
2082
2083
192k
    if (mpctx->max_frames == 0) {
2084
3
        if (!mpctx->stop_play)
2085
3
            mpctx->stop_play = PT_NEXT_ENTRY;
2086
3
        mpctx->error_playing = 0;
2087
3
        goto terminate_playback;
2088
3
    }
2089
2090
192k
    if (opts->demuxer_cache_wait) {
2091
1
        demux_start_prefetch(mpctx->demuxer);
2092
2093
3
        while (!mpctx->stop_play) {
2094
3
            struct demux_reader_state s;
2095
3
            demux_get_reader_state(mpctx->demuxer, &s);
2096
3
            if (s.idle)
2097
1
                break;
2098
2099
2
            mp_idle(mpctx);
2100
2
        }
2101
1
    }
2102
2103
    // (Not get_play_start_pts(), which would always trigger a seek.)
2104
192k
    double play_start_pts = rel_time_to_abs(mpctx, opts->play_start);
2105
2106
    // Backward playback -> start from end by default.
2107
192k
    if (play_start_pts == MP_NOPTS_VALUE && opts->play_dir < 0)
2108
217
        play_start_pts = get_start_time(mpctx, -1);
2109
2110
192k
    if (play_start_pts != MP_NOPTS_VALUE) {
2111
265
        queue_seek(mpctx, MPSEEK_ABSOLUTE, play_start_pts, MPSEEK_DEFAULT, 0);
2112
265
        execute_queued_seek(mpctx);
2113
265
    }
2114
2115
192k
    update_internal_pause_state(mpctx);
2116
2117
192k
    mpctx->error_playing = 0;
2118
192k
    mpctx->in_playloop = true;
2119
14.1M
    while (!mpctx->stop_play)
2120
13.9M
        run_playloop(mpctx);
2121
192k
    mpctx->in_playloop = false;
2122
2123
192k
    MP_VERBOSE(mpctx, "EOF code: %d\n", mpctx->stop_play);
2124
2125
801k
terminate_playback:
2126
2127
801k
    if (!mpctx->stop_play)
2128
594k
        mpctx->stop_play = PT_ERROR;
2129
2130
801k
    if (mpctx->stop_play != AT_END_OF_FILE)
2131
619k
        clear_audio_output_buffers(mpctx);
2132
2133
801k
    update_core_idle_state(mpctx);
2134
2135
801k
    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
801k
    process_hooks(mpctx, "on_unload");
2141
2142
    // time to uninit all, except global stuff:
2143
801k
    reinit_complex_filters(mpctx, true);
2144
801k
    uninit_audio_chain(mpctx);
2145
801k
    uninit_video_chain(mpctx);
2146
801k
    uninit_sub_all(mpctx);
2147
801k
    if (!opts->gapless_audio && !mpctx->encode_lavc_ctx)
2148
2
        uninit_audio_out(mpctx);
2149
2150
801k
    mpctx->playback_initialized = false;
2151
2152
801k
    uninit_demuxer(mpctx);
2153
2154
    // Possibly stop ongoing async commands.
2155
801k
    mp_abort_playback_async(mpctx);
2156
2157
801k
    struct playlist_entry *current = mpctx->playlist->current;
2158
801k
    bool reloading = mpctx->stop_play == PT_CURRENT_ENTRY &&
2159
1.29k
                     current && current->reloading;
2160
801k
    if (current)
2161
801k
        current->reloading = false;
2162
801k
    if (!reloading)
2163
801k
        m_config_restore_backups(mpctx->mconfig);
2164
2165
801k
    TA_FREEP(&mpctx->filter_root);
2166
801k
    talloc_free(mpctx->filtered_tags);
2167
801k
    mpctx->filtered_tags = NULL;
2168
2169
801k
    mp_notify(mpctx, MP_EVENT_TRACKS_CHANGED, NULL);
2170
2171
801k
    if (encode_lavc_didfail(mpctx->encode_lavc_ctx))
2172
0
        mpctx->stop_play = PT_ERROR;
2173
2174
801k
    if (mpctx->stop_play == PT_ERROR && !mpctx->error_playing)
2175
0
        mpctx->error_playing = MPV_ERROR_GENERIC;
2176
2177
801k
    bool nothing_played = !mpctx->shown_aframes && !mpctx->shown_vframes &&
2178
674k
                          mpctx->error_playing <= 0;
2179
801k
    bool playlist_prev_continue = false;
2180
801k
    switch (mpctx->stop_play) {
2181
607k
    case PT_ERROR:
2182
789k
    case AT_END_OF_FILE:
2183
789k
    {
2184
789k
        if (mpctx->error_playing == 0 && nothing_played)
2185
65.3k
            mpctx->error_playing = MPV_ERROR_NOTHING_TO_PLAY;
2186
789k
        if (mpctx->error_playing < 0) {
2187
666k
            end_event.error = mpctx->error_playing;
2188
666k
            end_event.reason = MPV_END_FILE_REASON_ERROR;
2189
666k
        } else if (mpctx->error_playing == 2) {
2190
6.91k
            end_event.reason = MPV_END_FILE_REASON_REDIRECT;
2191
115k
        } else {
2192
115k
            end_event.reason = MPV_END_FILE_REASON_EOF;
2193
115k
        }
2194
789k
        if (mpctx->playing) {
2195
259k
            mpctx->playing->init_failed = nothing_played;
2196
259k
            playlist_prev_continue = mpctx->playing->playlist_prev_attempt &&
2197
92
                                     nothing_played;
2198
259k
            mpctx->playing->playlist_prev_attempt = false;
2199
259k
        }
2200
789k
        break;
2201
607k
    }
2202
    // Note that error_playing is meaningless in these cases.
2203
3
    case PT_NEXT_ENTRY:
2204
1.29k
    case PT_CURRENT_ENTRY:
2205
1.68k
    case PT_STOP:           end_event.reason = MPV_END_FILE_REASON_STOP; break;
2206
10.9k
    case PT_QUIT:           end_event.reason = MPV_END_FILE_REASON_QUIT; break;
2207
801k
    };
2208
801k
    mp_notify(mpctx, MPV_EVENT_END_FILE, &end_event);
2209
2210
801k
    MP_VERBOSE(mpctx, "finished playback, %s (reason %d)\n",
2211
801k
               mpv_error_string(end_event.error), end_event.reason);
2212
801k
    if (end_event.error == MPV_ERROR_UNKNOWN_FORMAT)
2213
801k
        MP_ERR(mpctx, "Failed to recognize file format.\n");
2214
2215
801k
    if (mpctx->playing)
2216
272k
        playlist_entry_unref(mpctx->playing);
2217
801k
    mpctx->playing = NULL;
2218
801k
    talloc_free(mpctx->filename);
2219
801k
    mpctx->filename = NULL;
2220
801k
    mpctx->stream_open_filename = NULL;
2221
2222
801k
    if (end_event.error < 0 && nothing_played) {
2223
666k
        mpctx->files_broken++;
2224
666k
    } else if (end_event.error < 0) {
2225
208
        mpctx->files_errored++;
2226
135k
    } else {
2227
135k
        mpctx->files_played++;
2228
135k
    }
2229
2230
801k
    mp_assert(mpctx->stop_play);
2231
2232
801k
    process_hooks(mpctx, "on_after_end_file");
2233
2234
801k
    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
801k
}
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
794k
{
2251
794k
    struct playlist_entry *next = playlist_get_next(mpctx->playlist, direction);
2252
794k
    if (next && direction < 0 && !force)
2253
2.64k
        next->playlist_prev_attempt = true;
2254
794k
    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
794k
    return next;
2284
794k
}
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
301k
{
2290
301k
    stats_register_thread_cputime(mpctx->stats, "thread");
2291
2292
    // Wait for all scripts to load before possibly starting playback.
2293
301k
    if (!mp_clients_all_initialized(mpctx)) {
2294
212
        MP_VERBOSE(mpctx, "Waiting for scripts...\n");
2295
693
        while (!mp_clients_all_initialized(mpctx))
2296
481
            mp_idle(mpctx);
2297
212
        mp_wakeup_core(mpctx); // avoid lost wakeups during waiting
2298
212
        MP_VERBOSE(mpctx, "Done loading scripts.\n");
2299
212
    }
2300
    // After above is finished; but even if it's skipped.
2301
301k
    mp_msg_set_early_logging(mpctx->global, false);
2302
2303
301k
    prepare_playlist(mpctx, mpctx->playlist, false);
2304
2305
1.09M
    for (;;) {
2306
1.09M
        idle_loop(mpctx);
2307
2308
1.09M
        if (mpctx->stop_play == PT_QUIT)
2309
290k
            break;
2310
2311
801k
        if (mpctx->playlist->current)
2312
801k
            play_current_file(mpctx);
2313
2314
801k
        if (mpctx->stop_play == PT_QUIT)
2315
10.9k
            break;
2316
2317
790k
        struct playlist_entry *new_entry = NULL;
2318
790k
        if (mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_ERROR ||
2319
183k
            mpctx->stop_play == AT_END_OF_FILE)
2320
789k
        {
2321
789k
            new_entry = mp_next_file(mpctx, +1, false, true);
2322
789k
        } else if (mpctx->stop_play == PT_CURRENT_ENTRY) {
2323
1.29k
            new_entry = mpctx->playlist->current;
2324
1.29k
        }
2325
2326
790k
        if (!new_entry)
2327
253k
            mpctx->playlist->playlist_completed = true;
2328
2329
790k
        mpctx->playlist->current = new_entry;
2330
790k
        mpctx->playlist->current_was_replaced = false;
2331
790k
        mpctx->stop_play = new_entry ? PT_NEXT_ENTRY : PT_STOP;
2332
2333
790k
        if (!mpctx->playlist->current && mpctx->opts->player_idle_mode < 2)
2334
0
            break;
2335
790k
    }
2336
2337
301k
    cancel_open(mpctx);
2338
2339
301k
    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
301k
}
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
266k
{
2355
266k
    mp_assert(!e || playlist_entry_to_index(mpctx->playlist, e) >= 0);
2356
266k
    mpctx->playlist->current = e;
2357
266k
    mpctx->playlist->current_was_replaced = false;
2358
266k
    mp_notify(mpctx, MP_EVENT_CHANGE_PLAYLIST, NULL);
2359
    // Make it pick up the new entry.
2360
266k
    if (mpctx->stop_play != PT_QUIT)
2361
266k
        mpctx->stop_play = e ? PT_CURRENT_ENTRY : PT_STOP;
2362
266k
    mp_wakeup_core(mpctx);
2363
266k
}