Coverage Report

Created: 2026-11-30 06:48

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/mpv/demux/demux.c
Line
Count
Source
1
/*
2
 * This file is part of mpv.
3
 *
4
 * mpv is free software; you can redistribute it and/or
5
 * modify it under the terms of the GNU Lesser General Public
6
 * License as published by the Free Software Foundation; either
7
 * version 2.1 of the License, or (at your option) any later version.
8
 *
9
 * mpv is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 * GNU Lesser General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU Lesser General Public
15
 * License along with mpv.  If not, see <http://www.gnu.org/licenses/>.
16
 */
17
18
#include <assert.h>
19
#include <float.h>
20
#include <limits.h>
21
#include <math.h>
22
#include <stdatomic.h>
23
#include <stdint.h>
24
#include <stdio.h>
25
#include <stdlib.h>
26
#include <string.h>
27
#include <sys/stat.h>
28
#include <sys/types.h>
29
30
#include "cache.h"
31
#include "config.h"
32
#include "options/m_config.h"
33
#include "options/m_option.h"
34
#include "mpv_talloc.h"
35
#include "common/av_common.h"
36
#include "common/msg.h"
37
#include "common/global.h"
38
#include "common/recorder.h"
39
#include "common/stats.h"
40
#include "misc/charset_conv.h"
41
#include "misc/thread_tools.h"
42
#include "osdep/timer.h"
43
#include "osdep/threads.h"
44
45
#include "stream/stream.h"
46
#include "demux.h"
47
#include "packet_pool.h"
48
#include "timeline.h"
49
#include "stheader.h"
50
#include "cue.h"
51
52
// Demuxer list
53
extern const demuxer_desc_t demuxer_desc_mpv;
54
extern const demuxer_desc_t demuxer_desc_edl;
55
extern const demuxer_desc_t demuxer_desc_cue;
56
extern const demuxer_desc_t demuxer_desc_rawaudio;
57
extern const demuxer_desc_t demuxer_desc_rawvideo;
58
extern const demuxer_desc_t demuxer_desc_mf;
59
extern const demuxer_desc_t demuxer_desc_matroska;
60
extern const demuxer_desc_t demuxer_desc_lavf;
61
extern const demuxer_desc_t demuxer_desc_playlist;
62
extern const demuxer_desc_t demuxer_desc_directory;
63
extern const demuxer_desc_t demuxer_desc_disc;
64
extern const demuxer_desc_t demuxer_desc_rar;
65
extern const demuxer_desc_t demuxer_desc_libarchive;
66
#if HAVE_SUBRANDR
67
extern const demuxer_desc_t demuxer_desc_sbr;
68
#endif
69
extern const demuxer_desc_t demuxer_desc_null;
70
extern const demuxer_desc_t demuxer_desc_timeline;
71
72
static const demuxer_desc_t *const demuxer_list[] = {
73
    &demuxer_desc_directory,
74
    &demuxer_desc_disc,
75
    &demuxer_desc_edl,
76
    &demuxer_desc_cue,
77
    &demuxer_desc_rawaudio,
78
    &demuxer_desc_rawvideo,
79
    &demuxer_desc_matroska,
80
#if HAVE_LIBARCHIVE
81
    &demuxer_desc_libarchive,
82
#endif
83
#if HAVE_SUBRANDR
84
    &demuxer_desc_sbr,
85
#endif
86
    &demuxer_desc_lavf,
87
    &demuxer_desc_mf,
88
    &demuxer_desc_playlist,
89
    &demuxer_desc_null,
90
    &demuxer_desc_mpv,
91
    NULL
92
};
93
94
#define OPT_BASE_STRUCT struct demux_opts
95
96
static bool get_demux_sub_opts(int index, const struct m_sub_options **sub);
97
98
const struct m_sub_options demux_conf = {
99
    .opts = (const struct m_option[]){
100
        {"cache", OPT_CHOICE(enable_cache,
101
            {"no", 0}, {"auto", -1}, {"yes", 1})},
102
        {"cache-on-disk", OPT_BOOL(disk_cache)},
103
        {"demuxer-readahead-secs", OPT_DOUBLE(min_secs), M_RANGE(0, DBL_MAX)},
104
        {"demuxer-hysteresis-secs", OPT_DOUBLE(hyst_secs), M_RANGE(0, DBL_MAX)},
105
        {"demuxer-hysteresis-bytes", OPT_BYTE_SIZE(hyst_bytes),
106
            M_RANGE(0, M_MAX_MEM_BYTES)},
107
        {"demuxer-max-bytes", OPT_BYTE_SIZE(max_bytes),
108
            M_RANGE(0, M_MAX_MEM_BYTES)},
109
        {"demuxer-max-back-bytes", OPT_BYTE_SIZE(max_bytes_bw),
110
            M_RANGE(0, M_MAX_MEM_BYTES)},
111
        {"demuxer-donate-buffer", OPT_BOOL(donate_fw)},
112
        {"force-seekable", OPT_BOOL(force_seekable)},
113
        {"cache-secs", OPT_DOUBLE(min_secs_cache), M_RANGE(0, DBL_MAX)},
114
        {"access-references", OPT_BOOL(access_references)},
115
        {"demuxer-seekable-cache", OPT_CHOICE(seekable_cache,
116
            {"auto", -1}, {"no", 0}, {"yes", 1})},
117
        {"index", OPT_CHOICE(index_mode, {"default", 1}, {"recreate", 0})},
118
        {"mf-fps", OPT_DOUBLE(mf_fps)},
119
        {"mf-type", OPT_STRING(mf_type)},
120
        {"sub-create-cc-track", OPT_BOOL(create_ccs)},
121
        {"stream-record", OPT_STRING(record_file)},
122
        {"video-backward-overlap", OPT_CHOICE(video_back_preroll, {"auto", -1}),
123
            M_RANGE(0, 1024)},
124
        {"audio-backward-overlap", OPT_CHOICE(audio_back_preroll, {"auto", -1}),
125
            M_RANGE(0, 1024)},
126
        {"video-backward-batch", OPT_INT(back_batch[STREAM_VIDEO]),
127
            M_RANGE(0, 1024)},
128
        {"audio-backward-batch", OPT_INT(back_batch[STREAM_AUDIO]),
129
            M_RANGE(0, 1024)},
130
        {"demuxer-backward-playback-step", OPT_DOUBLE(back_seek_size),
131
            M_RANGE(0, DBL_MAX)},
132
        {"metadata-codepage", OPT_STRING(meta_cp)},
133
        {"directory-filter-types", OPT_STRINGLIST(directory_filter)},
134
        {"autocreate-playlist", OPT_CHOICE(autocreate_playlist,
135
            {"no", 0}, {"filter", 1}, {"same", 2})},
136
        {0}
137
    },
138
    .size = sizeof(struct demux_opts),
139
    .defaults = &(const struct demux_opts){
140
        .enable_cache = -1, // auto
141
        .max_bytes = 150 * 1024 * 1024,
142
        .max_bytes_bw = 50 * 1024 * 1024,
143
        .donate_fw = true,
144
        .min_secs = 1.0,
145
        .min_secs_cache = 1000.0 * 60 * 60,
146
        .seekable_cache = -1,
147
        .index_mode = 1,
148
        .mf_fps = 1.0,
149
        .access_references = true,
150
        .video_back_preroll = -1,
151
        .audio_back_preroll = -1,
152
        .back_seek_size = 60,
153
        .back_batch = {
154
            [STREAM_VIDEO] = 1,
155
            [STREAM_AUDIO] = 10,
156
        },
157
        .meta_cp = "auto",
158
        .directory_filter = (char *[]){
159
            "video", "audio", "image", "archive", "playlist", NULL
160
        },
161
    },
162
    .get_sub_options = get_demux_sub_opts,
163
};
164
165
struct demux_internal {
166
    struct mp_log *log;
167
    struct mpv_global *global;
168
    struct demux_packet_pool *packet_pool;
169
    struct stats_ctx *stats;
170
171
    bool can_cache;             // not a slave demuxer; caching makes sense
172
    bool can_record;            // stream recording is allowed
173
174
    // The demuxer runs potentially in another thread, so we keep two demuxer
175
    // structs; the real demuxer can access the shadow struct only.
176
    struct demuxer *d_thread;   // accessed by demuxer impl. (producer)
177
    struct demuxer *d_user;     // accessed by player (consumer)
178
179
    // The lock protects the packet queues (struct demux_stream),
180
    // and the fields below.
181
    mp_mutex lock;
182
    mp_cond wakeup;
183
    mp_thread thread;
184
185
    // -- All the following fields are protected by lock.
186
187
    atomic_bool thread_terminate;   // read unlocked by demux_read_interrupted()
188
    bool threading;
189
    bool shutdown_async;
190
    void (*wakeup_cb)(void *ctx);
191
    void *wakeup_cb_ctx;
192
193
    struct sh_stream **streams;
194
    int num_streams;
195
196
    char *meta_charset;
197
198
    // If non-NULL, a stream which is used for global (timed) metadata. It will
199
    // be an arbitrary stream, which hopefully will happen to work.
200
    struct sh_stream *metadata_stream;
201
202
    int events;
203
204
    struct demux_cache *cache;
205
206
    bool warned_queue_overflow;
207
    bool eof;                   // whether we're in EOF state
208
    double min_secs;
209
    double hyst_secs;           // stop reading till there's hyst_secs remaining
210
    size_t hyst_bytes;          // stop reading till there's hyst_bytes remaining
211
    bool hyst_active;
212
    bool nav_active;            // disc navigation (DVD/BD menus) is active
213
    bool nav_pump;              // one-shot request to force a single read
214
    size_t max_bytes;
215
    size_t max_bytes_bw;
216
    bool seekable_cache;
217
    bool using_network_cache_opts;
218
    char *record_filename;
219
220
    // Whether the demuxer thread should prefetch packets. This is set to false
221
    // if EOF was reached or the demuxer cache is full. This is also important
222
    // in the initial state: the decoder thread needs to select streams before
223
    // the first packet is read, so this is set to true by packet reading only.
224
    // Reset to false again on EOF or if prefetching is done.
225
    bool reading;
226
227
    // Set if we just performed a seek, without reading packets yet. Used to
228
    // avoid a redundant initial seek after enabling streams. We could just
229
    // allow it, but to avoid buggy seeking affecting normal playback, we don't.
230
    bool after_seek;
231
    // Set in addition to after_seek if we think we seeked to the start of the
232
    // file (or if the demuxer was just opened).
233
    bool after_seek_to_start;
234
235
    // Demuxing backwards. Since demuxer implementations don't support this
236
    // directly, it is emulated by seeking backwards for every packet run. Also,
237
    // packets between keyframes are demuxed forwards (you can't decode that
238
    // stuff otherwise), which adds complexity on top of it.
239
    bool back_demuxing;
240
241
    // For backward demuxing:
242
    bool need_back_seek;        // back-step seek needs to be triggered
243
    bool back_any_need_recheck; // at least 1 ds->back_need_recheck set
244
245
    bool tracks_switched;       // thread needs to inform demuxer of this
246
    bool nav_refresh;           // thread needs to call desc->nav_refresh
247
248
    atomic_bool seeking;        // there's a seek queued; read unlocked
249
                                // by demux_read_interrupted()
250
    int seek_flags;             // flags for next seek (if seeking==true)
251
    double seek_pts;
252
253
    // (fields for debugging)
254
    double seeking_in_progress; // low level seek state
255
    int low_level_seeks;        // number of started low level seeks
256
    double demux_ts;            // last demuxed DTS or PTS
257
258
    double ts_offset;           // timestamp offset to apply to everything
259
260
    // (sorted by least recent use: index 0 is least recently used)
261
    struct demux_cached_range **ranges;
262
    int num_ranges;
263
264
    size_t total_bytes;         // total sum of packet data buffered
265
    // Range from which decoder is reading, and to which demuxer is appending.
266
    // This is normally never NULL. This is always ranges[num_ranges - 1].
267
    // This is can be NULL during initialization or deinitialization.
268
    struct demux_cached_range *current_range;
269
270
    double highest_av_pts;      // highest non-subtitle PTS seen - for duration
271
272
    bool blocked;
273
274
    // Transient state.
275
    double duration;
276
    // Cached state.
277
    int64_t stream_size;
278
    int64_t last_speed_query;
279
    double speed_query_prev_sample;
280
    uint64_t bytes_per_second;
281
    int64_t next_cache_update;
282
283
    // demux user state (user thread, somewhat similar to reader/decoder state)
284
    double last_playback_pts;   // last playback_pts from demux_update()
285
    bool force_metadata_update;
286
287
    // Chapter/edition lists staged by the demux thread (demux_lists_changed),
288
    // published into d_user by demux_update() on the user thread.
289
    bool lists_changed;
290
    struct demux_chapter *staged_chapters;
291
    int num_staged_chapters;
292
    struct demux_edition *staged_editions;
293
    int num_staged_editions;
294
    int staged_edition;
295
    int cached_metadata_index;  // speed up repeated lookups
296
297
    struct mp_recorder *dumper;
298
    int dumper_status;
299
300
    bool owns_stream;
301
302
    // -- Access from demuxer thread only
303
    bool enable_recording;
304
    struct mp_recorder *recorder;
305
    int64_t slave_unbuffered_read_bytes; // value reported from demuxer impl.
306
    int64_t hack_unbuffered_read_bytes;  // for demux_get_bytes_read_hack()
307
    int64_t cache_unbuffered_read_bytes; // for demux_reader_state.bytes_per_second
308
    int64_t byte_level_seeks;            // for demux_reader_state.byte_level_seeks
309
};
310
311
struct timed_metadata {
312
    double pts;
313
    struct mp_tags *tags;
314
    bool from_stream;
315
};
316
317
// A continuous range of cached packets for all enabled streams.
318
// (One demux_queue for each known stream.)
319
struct demux_cached_range {
320
    // streams[] is indexed by demux_stream->index
321
    struct demux_queue **streams;
322
    int num_streams;
323
324
    // Computed from the stream queue's values. These fields (unlike as with
325
    // demux_queue) are always either NOPTS, or fully valid.
326
    double seek_start, seek_end;
327
328
    bool is_bof;            // set if the file begins with this range
329
    bool is_eof;            // set if the file ends with this range
330
331
    struct timed_metadata **metadata;
332
    int num_metadata;
333
};
334
335
2.13M
#define QUEUE_INDEX_SIZE_MASK(queue) ((queue)->index_size - 1)
336
337
// Access the idx-th entry in the given demux_queue.
338
// Requirement: idx >= 0 && idx < queue->num_index
339
#define QUEUE_INDEX_ENTRY(queue, idx) \
340
2.13M
    ((queue)->index[((queue)->index0 + (idx)) & QUEUE_INDEX_SIZE_MASK(queue)])
341
342
// Don't index packets whose timestamps that are within the last index entry by
343
// this amount of time (it's better to seek them manually).
344
2.04M
#define INDEX_STEP_SIZE 1.0
345
346
// Diff between the demuxer's reported start_time and a range's earliest cached
347
// timestamp, below which the range is still considered beginning-of-file.
348
15.6k
#define BOF_START_TOLERANCE 1.0
349
350
struct index_entry {
351
    double pts;
352
    struct demux_packet *pkt;
353
};
354
355
// A continuous list of cached packets for a single stream/range. There is one
356
// for each stream and range. Also contains some state for use during demuxing
357
// (keeping it across seeks makes it easier to resume demuxing).
358
struct demux_queue {
359
    struct demux_stream *ds;
360
    struct demux_cached_range *range;
361
362
    struct demux_packet *head;
363
    struct demux_packet *tail;
364
365
    uint64_t tail_cum_pos;  // cumulative size including tail packet
366
367
    bool correct_dts;       // packet DTS is strictly monotonically increasing
368
    bool correct_pos;       // packet pos is strictly monotonically increasing
369
    int64_t last_pos;       // for determining correct_pos
370
    int64_t last_pos_fixup; // for filling in unset dp->pos values
371
    double last_dts;        // for determining correct_dts
372
    double last_ts;         // timestamp of the last packet added to queue
373
374
    // for incrementally determining seek PTS range
375
    struct demux_packet *keyframe_latest;
376
    struct demux_packet *keyframe_first; // cached value of first KF packet
377
378
    // incrementally maintained seek range, possibly invalid
379
    double seek_start, seek_end;
380
    double last_pruned;     // timestamp of last pruned keyframe
381
382
    bool is_bof;            // started demuxing at beginning of file
383
    bool is_eof;            // received true EOF here
384
385
    // Complete index, though it may skip some entries to reduce density.
386
    struct index_entry *index;  // ring buffer
387
    size_t index_size;          // size of index[] (0 or a power of 2)
388
    size_t index0;              // first index entry
389
    size_t num_index;           // number of index entries (wraps on index_size)
390
};
391
392
struct demux_stream {
393
    struct demux_internal *in;
394
    struct sh_stream *sh;   // ds->sh->ds == ds
395
    enum stream_type type;  // equals to sh->type
396
    int index;              // equals to sh->index
397
    // --- all fields are protected by in->lock
398
399
    void (*wakeup_cb)(void *ctx);
400
    void *wakeup_cb_ctx;
401
402
    // demuxer state
403
    bool selected;          // user wants packets from this stream
404
    bool eager;             // try to keep at least 1 packet queued
405
                            // if false, this stream is disabled, or passively
406
                            // read (like subtitles)
407
    bool still_image;       // stream consists of multiple sparse still images
408
    bool refreshing;        // finding old position after track switches
409
    bool eof;               // end of demuxed stream? (true if no more packets)
410
    struct mp_codec_params *staged_codec; // next sh->codec, see demux_update()
411
412
    bool global_correct_dts;// all observed so far
413
    bool global_correct_pos;
414
415
    // current queue - used both for reading and demuxing (this is never NULL)
416
    struct demux_queue *queue;
417
418
    // reader (decoder) state (bitrate calculations are part of it because we
419
    // want to return the bitrate closest to the "current position")
420
    double base_ts;         // timestamp of the last packet returned to decoder
421
    double last_br_ts;      // timestamp of last packet bitrate was calculated
422
    size_t last_br_bytes;   // summed packet sizes since last bitrate calculation
423
    double bitrate;
424
    struct demux_packet *reader_head;   // points at current decoder position
425
    bool skip_to_keyframe;
426
    bool attached_picture_added;
427
    bool lazy_eof;          // last EOF returned to the reader was not the
428
                            // demuxer's EOF (non-eager stream or queue
429
                            // overflow), more packets may follow
430
    bool need_wakeup;       // call wakeup_cb on next reader_head state change
431
    double force_read_until;// eager=false streams (subs): force read-ahead
432
433
    // For demux_internal.dumper. Currently, this is used only temporarily
434
    // during blocking dumping.
435
    struct demux_packet *dump_pos;
436
437
    // for refresh seeks: pos/dts of last packet returned to reader
438
    int64_t last_ret_pos;
439
    double last_ret_dts;
440
441
    // Backwards demuxing.
442
    bool back_need_recheck; // flag for incremental find_backward_restart_pos work
443
    // pos/dts of the previous keyframe packet returned; always valid if back-
444
    // demuxing is enabled, and back_restart_eof/back_restart_next are false.
445
    int64_t back_restart_pos;
446
    double back_restart_dts;
447
    bool back_restart_eof; // restart position is at EOF; overrides pos/dts
448
    bool back_restart_next; // restart before next keyframe; overrides above
449
    bool back_restarting;   // searching keyframe before restart pos
450
    // Current PTS lower bound for back demuxing.
451
    double back_seek_pos;
452
    // pos/dts of the packet to resume demuxing from when another stream caused
453
    // a seek backward to get more packets. reader_head will be reset to this
454
    // packet as soon as it's encountered again.
455
    int64_t back_resume_pos;
456
    double back_resume_dts;
457
    bool back_resuming;     // resuming mode (above fields are valid/used)
458
    // Set to true if the first packet (keyframe) of a range was returned.
459
    bool back_range_started;
460
    // Number of KF packets at start of range yet to return. -1 is used for BOF.
461
    int back_range_count;
462
    // Number of KF packets yet to return that are marked as preroll.
463
    int back_range_preroll;
464
    // Static packet preroll count.
465
    int back_preroll;
466
467
    // for closed captions (demuxer_feed_caption)
468
    struct sh_stream *cc;
469
    bool ignore_eof;        // ignore stream in underrun detection
470
};
471
472
static void switch_to_fresh_cache_range(struct demux_internal *in);
473
static void demuxer_sort_chapters(demuxer_t *demuxer);
474
static MP_THREAD_VOID demux_thread(void *pctx);
475
static void update_cache(struct demux_internal *in);
476
static void add_packet_locked(struct sh_stream *stream, demux_packet_t *dp);
477
static struct demux_packet *advance_reader_head(struct demux_stream *ds);
478
static bool queue_seek(struct demux_internal *in, double seek_pts, int flags,
479
                       bool clear_back_state);
480
static struct demux_packet *compute_keyframe_times(struct demux_packet *pkt,
481
                                                   double *out_kf_min,
482
                                                   double *out_kf_max);
483
static void find_backward_restart_pos(struct demux_stream *ds);
484
static struct demux_packet *find_seek_target(struct demux_queue *queue,
485
                                             double pts, int flags);
486
static void prune_old_packets(struct demux_internal *in);
487
static void dumper_close(struct demux_internal *in);
488
static void demux_convert_tags_charset(struct demuxer *demuxer);
489
490
static uint64_t get_forward_buffered_bytes(struct demux_stream *ds)
491
123M
{
492
123M
    if (!ds->reader_head)
493
53.7M
        return 0;
494
70.1M
    return ds->queue->tail_cum_pos - ds->reader_head->cum_pos;
495
123M
}
496
497
#if 0
498
// very expensive check for redundant cached queue state
499
static void check_queue_consistency(struct demux_internal *in)
500
{
501
    uint64_t total_bytes = 0;
502
503
    mp_assert(in->current_range && in->num_ranges > 0);
504
    mp_assert(in->current_range == in->ranges[in->num_ranges - 1]);
505
506
    for (int n = 0; n < in->num_ranges; n++) {
507
        struct demux_cached_range *range = in->ranges[n];
508
        int range_num_packets = 0;
509
510
        mp_assert(range->num_streams == in->num_streams);
511
512
        for (int i = 0; i < range->num_streams; i++) {
513
            struct demux_queue *queue = range->streams[i];
514
515
            mp_assert(queue->range == range);
516
517
            size_t fw_bytes = 0;
518
            bool is_forward = false;
519
            bool kf_found = false;
520
            bool kf1_found = false;
521
            size_t next_index = 0;
522
            uint64_t queue_total_bytes = 0;
523
            for (struct demux_packet *dp = queue->head; dp; dp = dp->next) {
524
                is_forward |= dp == queue->ds->reader_head;
525
                kf_found |= dp == queue->keyframe_latest;
526
                kf1_found |= dp == queue->keyframe_first;
527
528
                size_t bytes = demux_packet_estimate_total_size(dp);
529
                total_bytes += bytes;
530
                queue_total_bytes += bytes;
531
                if (is_forward) {
532
                    fw_bytes += bytes;
533
                    mp_assert(range == in->current_range);
534
                    mp_assert(queue->ds->queue == queue);
535
                }
536
                range_num_packets += 1;
537
538
                if (!dp->next)
539
                    mp_assert(queue->tail == dp);
540
541
                if (next_index < queue->num_index &&
542
                    QUEUE_INDEX_ENTRY(queue, next_index).pkt == dp)
543
                    next_index += 1;
544
            }
545
            if (!queue->head)
546
                mp_assert(!queue->tail);
547
            mp_assert(next_index == queue->num_index);
548
549
            uint64_t queue_total_bytes2 = 0;
550
            if (queue->head)
551
                queue_total_bytes2 = queue->tail_cum_pos - queue->head->cum_pos;
552
553
            mp_assert(queue_total_bytes == queue_total_bytes2);
554
555
            // If the queue is currently used...
556
            if (queue->ds->queue == queue) {
557
                // ...reader_head and others must be in the queue.
558
                mp_assert(is_forward == !!queue->ds->reader_head);
559
                mp_assert(kf_found == !!queue->keyframe_latest);
560
                uint64_t fw_bytes2 = get_forward_buffered_bytes(queue->ds);
561
                mp_assert(fw_bytes == fw_bytes2);
562
            }
563
564
            mp_assert(kf1_found == !!queue->keyframe_first);
565
566
            if (range != in->current_range) {
567
                mp_assert(fw_bytes == 0);
568
            }
569
570
            if (queue->keyframe_latest)
571
                mp_assert(queue->keyframe_latest->keyframe);
572
573
            total_bytes += queue->index_size * sizeof(struct index_entry);
574
        }
575
576
        // Invariant needed by pruning; violation has worse effects than just
577
        // e.g. broken seeking due to incorrect seek ranges.
578
        if (range->seek_start != MP_NOPTS_VALUE)
579
            mp_assert(range_num_packets > 0);
580
    }
581
582
    mp_assert(in->total_bytes == total_bytes);
583
}
584
#endif
585
586
// (this doesn't do most required things for a switch, like updating ds->queue)
587
static void set_current_range(struct demux_internal *in,
588
                              struct demux_cached_range *range)
589
748k
{
590
748k
    in->current_range = range;
591
592
    // Move to in->ranges[in->num_ranges-1] (for LRU sorting/invariant)
593
1.12M
    for (int n = 0; n < in->num_ranges; n++) {
594
1.12M
        if (in->ranges[n] == range) {
595
748k
            MP_TARRAY_REMOVE_AT(in->ranges, in->num_ranges, n);
596
748k
            break;
597
748k
        }
598
1.12M
    }
599
748k
    MP_TARRAY_APPEND(in, in->ranges, in->num_ranges, range);
600
748k
}
601
602
static void prune_metadata(struct demux_cached_range *range)
603
10.8M
{
604
10.8M
    int first_needed = 0;
605
606
10.8M
    if (range->seek_start == MP_NOPTS_VALUE) {
607
8.94M
        first_needed = range->num_metadata;
608
8.94M
    } else {
609
1.89M
        for (int n = 0; n < range->num_metadata ; n++) {
610
0
            if (range->metadata[n]->pts > range->seek_start)
611
0
                break;
612
0
            first_needed = n;
613
0
        }
614
1.89M
    }
615
616
    // Always preserve the last entry.
617
10.8M
    first_needed = MPMIN(first_needed, range->num_metadata - 1);
618
619
    // (Could make this significantly more efficient for large first_needed,
620
    // however that might be very rare and even then it might not matter.)
621
10.8M
    for (int n = 0; n < first_needed; n++) {
622
101
        talloc_free(range->metadata[0]);
623
101
        MP_TARRAY_REMOVE_AT(range->metadata, range->num_metadata, 0);
624
101
    }
625
10.8M
}
626
627
// Refresh range->seek_start/end. Idempotent.
628
static void update_seek_ranges(struct demux_cached_range *range)
629
10.8M
{
630
10.8M
    range->seek_start = range->seek_end = MP_NOPTS_VALUE;
631
10.8M
    range->is_bof = true;
632
10.8M
    range->is_eof = true;
633
634
10.8M
    double min_start_pts = MP_NOPTS_VALUE;
635
10.8M
    double max_end_pts = MP_NOPTS_VALUE;
636
637
20.5M
    for (int n = 0; n < range->num_streams; n++) {
638
17.9M
        struct demux_queue *queue = range->streams[n];
639
640
17.9M
        if (queue->ds->selected && queue->ds->eager) {
641
10.8M
            if (queue->is_bof) {
642
2.42M
                min_start_pts = MP_PTS_MIN(min_start_pts, queue->seek_start);
643
8.43M
            } else {
644
8.43M
                range->seek_start =
645
8.43M
                    MP_PTS_MAX(range->seek_start, queue->seek_start);
646
8.43M
            }
647
648
10.8M
            if (queue->is_eof) {
649
688k
                max_end_pts = MP_PTS_MAX(max_end_pts, queue->seek_end);
650
10.1M
            } else {
651
10.1M
                range->seek_end = MP_PTS_MIN(range->seek_end, queue->seek_end);
652
10.1M
            }
653
654
10.8M
            range->is_eof &= queue->is_eof;
655
10.8M
            range->is_bof &= queue->is_bof;
656
657
10.8M
            bool empty = queue->is_eof && !queue->head;
658
10.8M
            if (queue->seek_start >= queue->seek_end && !empty &&
659
8.28M
                !(queue->seek_start == queue->seek_end &&
660
8.28M
                  queue->seek_start != MP_NOPTS_VALUE))
661
8.26M
                goto broken;
662
10.8M
        }
663
17.9M
    }
664
665
2.56M
    if (range->is_eof)
666
675k
        range->seek_end = max_end_pts;
667
2.56M
    if (range->is_bof)
668
2.38M
        range->seek_start = min_start_pts;
669
670
    // Sparse (subtitle) stream behavior is not very clearly defined, but
671
    // usually we don't want it to restrict the range of other streams. For
672
    // example, if there are subtitle packets at position 5 and 10 seconds, and
673
    // the demuxer demuxed the other streams until position 7 seconds, the seek
674
    // range end position is 7.
675
    // Assume that reading a non-sparse (audio/video) packet gets all sparse
676
    // packets that are needed before that non-sparse packet.
677
    // This is incorrect in any of these cases:
678
    //  - sparse streams only (it's unknown how to determine an accurate range)
679
    //  - if sparse streams have non-keyframe packets (we set queue->last_pruned
680
    //    to the start of the pruned keyframe range - we'd need the end or so)
681
    // We also assume that ds->eager equals to a stream not being sparse
682
    // (usually true, except if only sparse streams are selected).
683
    // We also rely on the fact that the demuxer position will always be ahead
684
    // of the seek_end for audio/video, because they need to prefetch at least
685
    // 1 packet to detect the end of a keyframe range. This means that there's
686
    // a relatively high guarantee to have all sparse (subtitle) packets within
687
    // the seekable range.
688
    // As a consequence, the code _never_ checks queue->seek_end for a sparse
689
    // queue, as the end of it is implied by the highest PTS of a non-sparse
690
    // stream (i.e. the latest demuxer position).
691
    // On the other hand, if a sparse packet was pruned, and that packet has
692
    // a higher PTS than seek_start for non-sparse queues, that packet is
693
    // missing. So the range's seek_start needs to be adjusted accordingly.
694
8.07M
    for (int n = 0; n < range->num_streams; n++) {
695
5.50M
        struct demux_queue *queue = range->streams[n];
696
5.50M
        if (queue->ds->selected && !queue->ds->eager &&
697
756
            queue->last_pruned != MP_NOPTS_VALUE &&
698
0
            range->seek_start != MP_NOPTS_VALUE)
699
0
        {
700
            // (last_pruned is _exclusive_ to the seekable range, so add a small
701
            // value to exclude it from the valid range.)
702
0
            range->seek_start =
703
0
                MP_PTS_MAX(range->seek_start, queue->last_pruned + 0.1);
704
0
        }
705
5.50M
    }
706
707
2.56M
    if (range->seek_start >= range->seek_end && !(range->is_bof && range->is_eof))
708
180k
        goto broken;
709
710
2.38M
    prune_metadata(range);
711
2.38M
    return;
712
713
8.44M
broken:
714
8.44M
    range->seek_start = range->seek_end = MP_NOPTS_VALUE;
715
8.44M
    prune_metadata(range);
716
8.44M
}
717
718
// Remove queue->head from the queue.
719
static void remove_head_packet(struct demux_queue *queue)
720
11.2M
{
721
11.2M
    struct demux_packet *dp = queue->head;
722
723
11.2M
    mp_assert(queue->ds->reader_head != dp);
724
11.2M
    if (queue->keyframe_first == dp)
725
7.13M
        queue->keyframe_first = NULL;
726
11.2M
    if (queue->keyframe_latest == dp)
727
0
        queue->keyframe_latest = NULL;
728
11.2M
    queue->is_bof = false;
729
730
11.2M
    uint64_t end_pos = dp->next ? dp->next->cum_pos : queue->tail_cum_pos;
731
11.2M
    queue->ds->in->total_bytes -= end_pos - dp->cum_pos;
732
733
11.2M
    if (queue->num_index && queue->index[queue->index0].pkt == dp) {
734
73
        queue->index0 = (queue->index0 + 1) & QUEUE_INDEX_SIZE_MASK(queue);
735
73
        queue->num_index -= 1;
736
73
    }
737
738
11.2M
    queue->head = dp->next;
739
11.2M
    if (!queue->head)
740
2.92M
        queue->tail = NULL;
741
742
11.2M
    demux_packet_pool_push(queue->ds->in->packet_pool, dp);
743
11.2M
}
744
745
static void free_index(struct demux_queue *queue)
746
11.3M
{
747
11.3M
    struct demux_stream *ds = queue->ds;
748
11.3M
    struct demux_internal *in = ds->in;
749
750
11.3M
    in->total_bytes -= queue->index_size * sizeof(queue->index[0]);
751
11.3M
    queue->index_size = 0;
752
11.3M
    queue->index0 = 0;
753
11.3M
    queue->num_index = 0;
754
11.3M
    TA_FREEP(&queue->index);
755
11.3M
}
756
757
static void clear_queue(struct demux_queue *queue)
758
11.3M
{
759
11.3M
    struct demux_stream *ds = queue->ds;
760
11.3M
    struct demux_internal *in = ds->in;
761
762
11.3M
    if (queue->head)
763
124k
        in->total_bytes -= queue->tail_cum_pos - queue->head->cum_pos;
764
765
11.3M
    free_index(queue);
766
767
11.3M
    demux_packet_pool_prepend(in->packet_pool, queue->head, queue->tail);
768
11.3M
    queue->head = queue->tail = NULL;
769
11.3M
    queue->keyframe_first = NULL;
770
11.3M
    queue->keyframe_latest = NULL;
771
11.3M
    queue->seek_start = queue->seek_end = queue->last_pruned = MP_NOPTS_VALUE;
772
773
11.3M
    queue->correct_dts = queue->correct_pos = true;
774
11.3M
    queue->last_pos = -1;
775
11.3M
    queue->last_ts = queue->last_dts = MP_NOPTS_VALUE;
776
11.3M
    queue->last_pos_fixup = -1;
777
778
11.3M
    queue->is_eof = false;
779
11.3M
    queue->is_bof = false;
780
11.3M
}
781
782
static void clear_cached_range(struct demux_internal *in,
783
                               struct demux_cached_range *range)
784
5.49M
{
785
15.5M
    for (int n = 0; n < range->num_streams; n++)
786
10.0M
        clear_queue(range->streams[n]);
787
788
5.49M
    for (int n = 0; n < range->num_metadata; n++)
789
90
        talloc_free(range->metadata[n]);
790
5.49M
    range->num_metadata = 0;
791
792
5.49M
    update_seek_ranges(range);
793
5.49M
}
794
795
// Remove ranges with no data (except in->current_range). Also remove excessive
796
// ranges.
797
static void free_empty_cached_ranges(struct demux_internal *in)
798
8.24M
{
799
8.24M
    while (1) {
800
8.24M
        struct demux_cached_range *worst = NULL;
801
802
8.24M
        int end = in->num_ranges - 1;
803
804
        // (Not set during early init or late destruction.)
805
8.24M
        if (in->current_range) {
806
1.90M
            mp_assert(in->current_range && in->num_ranges > 0);
807
1.90M
            mp_assert(in->current_range == in->ranges[in->num_ranges - 1]);
808
1.90M
            end -= 1;
809
1.90M
        }
810
811
8.99M
        for (int n = end; n >= 0; n--) {
812
749k
            struct demux_cached_range *range = in->ranges[n];
813
749k
            if (range->seek_start == MP_NOPTS_VALUE || !in->seekable_cache) {
814
748k
                clear_cached_range(in, range);
815
748k
                MP_TARRAY_REMOVE_AT(in->ranges, in->num_ranges, n);
816
1.89M
                for (int i = 0; i < range->num_streams; i++)
817
1.14M
                    talloc_free(range->streams[i]);
818
748k
                talloc_free(range);
819
748k
            } else {
820
77
                if (!worst || (range->seek_end - range->seek_start <
821
13
                               worst->seek_end - worst->seek_start))
822
69
                    worst = range;
823
77
            }
824
749k
        }
825
826
8.24M
        if (in->num_ranges <= MAX_SEEK_RANGES || !worst)
827
8.24M
            break;
828
829
18.4E
        clear_cached_range(in, worst);
830
18.4E
    }
831
8.24M
}
832
833
static void ds_clear_reader_queue_state(struct demux_stream *ds)
834
10.5M
{
835
10.5M
    ds->reader_head = NULL;
836
10.5M
    ds->eof = false;
837
10.5M
    ds->need_wakeup = true;
838
10.5M
}
839
840
static void ds_clear_reader_state(struct demux_stream *ds,
841
                                  bool clear_back_state)
842
10.4M
{
843
10.4M
    ds_clear_reader_queue_state(ds);
844
845
10.4M
    ds->base_ts = ds->last_br_ts = MP_NOPTS_VALUE;
846
10.4M
    ds->last_br_bytes = 0;
847
10.4M
    ds->bitrate = -1;
848
10.4M
    ds->skip_to_keyframe = false;
849
10.4M
    ds->attached_picture_added = false;
850
10.4M
    ds->lazy_eof = false;
851
10.4M
    ds->last_ret_pos = -1;
852
10.4M
    ds->last_ret_dts = MP_NOPTS_VALUE;
853
10.4M
    ds->force_read_until = MP_NOPTS_VALUE;
854
855
10.4M
    if (clear_back_state) {
856
6.81M
        ds->back_restart_pos = -1;
857
6.81M
        ds->back_restart_dts = MP_NOPTS_VALUE;
858
6.81M
        ds->back_restart_eof = false;
859
6.81M
        ds->back_restart_next = ds->in->back_demuxing;
860
6.81M
        ds->back_restarting = ds->in->back_demuxing && ds->eager;
861
6.81M
        ds->back_seek_pos = MP_NOPTS_VALUE;
862
6.81M
        ds->back_resume_pos = -1;
863
6.81M
        ds->back_resume_dts = MP_NOPTS_VALUE;
864
6.81M
        ds->back_resuming = false;
865
6.81M
        ds->back_range_started = false;
866
6.81M
        ds->back_range_count = 0;
867
6.81M
        ds->back_range_preroll = 0;
868
6.81M
    }
869
10.4M
}
870
871
// called locked, from user thread only
872
static void clear_reader_state(struct demux_internal *in,
873
                               bool clear_back_state)
874
7.91M
{
875
17.5M
    for (int n = 0; n < in->num_streams; n++)
876
9.67M
        ds_clear_reader_state(in->streams[n]->ds, clear_back_state);
877
7.91M
    in->warned_queue_overflow = false;
878
7.91M
    in->d_user->filepos = -1; // implicitly synchronized
879
7.91M
    in->blocked = false;
880
7.91M
    in->need_back_seek = false;
881
7.91M
}
882
883
// Call if the observed reader state on this stream somehow changes. The wakeup
884
// is skipped if the reader successfully read a packet, because that means we
885
// expect it to come back and ask for more.
886
static void wakeup_ds(struct demux_stream *ds)
887
48.9M
{
888
48.9M
    if (ds->need_wakeup) {
889
30.8M
        if (ds->wakeup_cb) {
890
24.8M
            ds->wakeup_cb(ds->wakeup_cb_ctx);
891
24.8M
        } else if (ds->in->wakeup_cb) {
892
2.80M
            ds->in->wakeup_cb(ds->in->wakeup_cb_ctx);
893
2.80M
        }
894
30.8M
        ds->need_wakeup = false;
895
30.8M
        mp_cond_signal(&ds->in->wakeup);
896
30.8M
    }
897
48.9M
}
898
899
static void update_stream_eager_state(struct demux_internal *in)
900
818k
{
901
818k
    bool any_av_streams = false;
902
818k
    bool any_streams = false;
903
904
10.5M
    for (int n = 0; n < in->num_streams; n++) {
905
9.70M
        struct demux_stream *s = in->streams[n]->ds;
906
907
9.70M
        s->still_image = s->sh->still_image;
908
9.70M
        s->eager = s->selected && !s->sh->absent && !s->sh->attached_picture;
909
9.70M
        if (s->eager && !s->still_image)
910
465k
            any_av_streams |= s->type != STREAM_SUB;
911
9.70M
        any_streams |= s->selected;
912
9.70M
    }
913
914
    // Subtitles and sparse still-image video are only eagerly read if there are
915
    // no other eagerly read streams.
916
818k
    if (any_av_streams) {
917
3.74M
        for (int n = 0; n < in->num_streams; n++) {
918
3.38M
            struct demux_stream *s = in->streams[n]->ds;
919
920
3.38M
            if (s->type == STREAM_SUB || s->still_image)
921
41.9k
                s->eager = false;
922
3.38M
        }
923
361k
    }
924
925
818k
    if (!any_streams)
926
445k
        in->blocked = false;
927
818k
}
928
929
// Set whether the media provides data for this stream at all.
930
void demux_set_stream_absent(demuxer_t *demuxer, struct sh_stream *sh,
931
                             bool absent)
932
0
{
933
0
    struct demux_internal *in = demuxer->in;
934
0
    mp_assert(demuxer == in->d_thread);
935
936
0
    mp_mutex_lock(&in->lock);
937
0
    if (sh->absent != absent) {
938
0
        MP_VERBOSE(in, "stream %d is %s\n", sh->index,
939
0
                   absent ? "absent" : "present");
940
0
        sh->absent = absent;
941
0
        update_stream_eager_state(in);
942
0
    }
943
0
    mp_mutex_unlock(&in->lock);
944
0
}
945
946
static void update_stream_selection_state(struct demux_internal *in,
947
                                          struct demux_stream *ds)
948
818k
{
949
818k
    ds->eof = false;
950
818k
    ds->refreshing = false;
951
952
818k
    update_stream_eager_state(in);
953
954
818k
    ds_clear_reader_state(ds, true);
955
956
    // Make sure any stream reselection or addition is reflected in the seek
957
    // ranges, and also get rid of data that is not needed anymore (or
958
    // rather, which can't be kept consistent). This has to happen after we've
959
    // updated all the subtle state (like s->eager).
960
1.23M
    for (int n = 0; n < in->num_ranges; n++) {
961
411k
        struct demux_cached_range *range = in->ranges[n];
962
963
411k
        if (!ds->selected)
964
61.6k
            clear_queue(range->streams[ds->index]);
965
966
411k
        update_seek_ranges(range);
967
411k
    }
968
969
818k
    free_empty_cached_ranges(in);
970
971
818k
    wakeup_ds(ds);
972
818k
}
973
974
void demux_set_ts_offset(struct demuxer *demuxer, double offset)
975
276k
{
976
276k
    struct demux_internal *in = demuxer->in;
977
276k
    mp_mutex_lock(&in->lock);
978
276k
    in->ts_offset = offset;
979
276k
    mp_mutex_unlock(&in->lock);
980
276k
}
981
982
static void add_missing_streams(struct demux_internal *in,
983
                                struct demux_cached_range *range)
984
749k
{
985
1.89M
    for (int n = range->num_streams; n < in->num_streams; n++) {
986
1.14M
        struct demux_stream *ds = in->streams[n]->ds;
987
988
1.14M
        struct demux_queue *queue = talloc_ptrtype(NULL, queue);
989
1.14M
        *queue = (struct demux_queue){
990
1.14M
            .ds = ds,
991
1.14M
            .range = range,
992
1.14M
        };
993
1.14M
        clear_queue(queue);
994
1.14M
        MP_TARRAY_APPEND(range, range->streams, range->num_streams, queue);
995
1.14M
        mp_assert(range->streams[ds->index] == queue);
996
1.14M
    }
997
749k
}
998
999
// Allocate a new sh_stream of the given type. It either has to be released
1000
// with talloc_free(), or added to a demuxer with demux_add_sh_stream(). You
1001
// cannot add or read packets from the stream before it has been added.
1002
// type may be changed later, but only before demux_add_sh_stream().
1003
struct sh_stream *demux_alloc_sh_stream(enum stream_type type)
1004
408k
{
1005
408k
    struct sh_stream *sh = talloc_ptrtype(NULL, sh);
1006
408k
    *sh = (struct sh_stream) {
1007
408k
        .type = type,
1008
408k
        .index = -1,
1009
408k
        .ff_index = -1,     // may be overwritten by demuxer
1010
408k
        .demuxer_id = -1,   // ... same
1011
408k
        .codec = talloc_zero(sh, struct mp_codec_params),
1012
408k
        .tags = talloc_zero(sh, struct mp_tags),
1013
408k
    };
1014
408k
    sh->codec->type = type;
1015
408k
    return sh;
1016
408k
}
1017
1018
// Add a new sh_stream to the demuxer. Note that as soon as the stream has been
1019
// added, it must be immutable, and must not be released (this will happen when
1020
// the demuxer is destroyed).
1021
static void demux_add_sh_stream_locked(struct demux_internal *in,
1022
                                       struct sh_stream *sh)
1023
407k
{
1024
407k
    mp_assert(!sh->ds); // must not be added yet
1025
1026
407k
    sh->index = in->num_streams;
1027
1028
407k
    sh->ds = talloc(sh, struct demux_stream);
1029
407k
    *sh->ds = (struct demux_stream) {
1030
407k
        .in = in,
1031
407k
        .sh = sh,
1032
407k
        .type = sh->type,
1033
407k
        .index = sh->index,
1034
407k
        .global_correct_dts = true,
1035
407k
        .global_correct_pos = true,
1036
407k
    };
1037
1038
407k
    struct demux_stream *ds = sh->ds;
1039
1040
407k
    if (!sh->codec->codec)
1041
35.5k
        sh->codec->codec = "";
1042
1043
407k
    MP_TARRAY_APPEND(in, in->streams, in->num_streams, sh);
1044
407k
    mp_assert(in->streams[sh->index] == sh);
1045
1046
407k
    if (in->current_range) {
1047
1.14k
        for (int n = 0; n < in->num_ranges; n++)
1048
574
            add_missing_streams(in, in->ranges[n]);
1049
1050
574
        sh->ds->queue = in->current_range->streams[sh->ds->index];
1051
574
    }
1052
1053
407k
    update_stream_selection_state(in, sh->ds);
1054
1055
407k
    switch (ds->type) {
1056
177k
    case STREAM_AUDIO:
1057
177k
        ds->back_preroll = in->d_user->opts->audio_back_preroll;
1058
177k
        if (ds->back_preroll < 0) { // auto
1059
177k
            ds->back_preroll = mp_codec_is_lossless(sh->codec->codec) ? 0 : 1;
1060
177k
            if (sh->codec->codec && (strcmp(sh->codec->codec, "opus") == 0 ||
1061
176k
                                     strcmp(sh->codec->codec, "vorbis") == 0 ||
1062
176k
                                     strcmp(sh->codec->codec, "mp3") == 0))
1063
6.45k
                ds->back_preroll = 2;
1064
177k
        }
1065
177k
        break;
1066
199k
    case STREAM_VIDEO:
1067
199k
        ds->back_preroll = in->d_user->opts->video_back_preroll;
1068
199k
        if (ds->back_preroll < 0)
1069
199k
            ds->back_preroll = 0; // auto
1070
199k
        break;
1071
407k
    }
1072
1073
407k
    if (!ds->sh->attached_picture) {
1074
        // Typically this is used for webradio, so any stream will do.
1075
407k
        if (!in->metadata_stream)
1076
303k
            in->metadata_stream = sh;
1077
407k
    }
1078
1079
407k
    in->events |= DEMUX_EVENT_STREAMS;
1080
407k
    if (in->wakeup_cb)
1081
561
        in->wakeup_cb(in->wakeup_cb_ctx);
1082
407k
}
1083
1084
// For demuxer implementations only.
1085
void demux_add_sh_stream(struct demuxer *demuxer, struct sh_stream *sh)
1086
407k
{
1087
407k
    struct demux_internal *in = demuxer->in;
1088
407k
    mp_assert(demuxer == in->d_thread);
1089
407k
    mp_mutex_lock(&in->lock);
1090
407k
    demux_add_sh_stream_locked(in, sh);
1091
407k
    mp_mutex_unlock(&in->lock);
1092
407k
}
1093
1094
// Return a stream with the given index. Since streams can only be added during
1095
// the lifetime of the demuxer, it is guaranteed that an index within the valid
1096
// range [0, demux_get_num_stream()) always returns a valid sh_stream pointer,
1097
// which will be valid until the demuxer is destroyed.
1098
struct sh_stream *demux_get_stream(struct demuxer *demuxer, int index)
1099
2.65M
{
1100
2.65M
    struct demux_internal *in = demuxer->in;
1101
2.65M
    mp_mutex_lock(&in->lock);
1102
2.65M
    mp_assert(index >= 0 && index < in->num_streams);
1103
2.65M
    struct sh_stream *r = in->streams[index];
1104
2.65M
    mp_mutex_unlock(&in->lock);
1105
2.65M
    return r;
1106
2.65M
}
1107
1108
// See demux_get_stream().
1109
int demux_get_num_stream(struct demuxer *demuxer)
1110
1.30M
{
1111
1.30M
    struct demux_internal *in = demuxer->in;
1112
1.30M
    mp_mutex_lock(&in->lock);
1113
1.30M
    int r = in->num_streams;
1114
1.30M
    mp_mutex_unlock(&in->lock);
1115
1.30M
    return r;
1116
1.30M
}
1117
1118
// It's UB to call anything but demux_dealloc() on the demuxer after this.
1119
static void demux_shutdown(struct demux_internal *in)
1120
3.15M
{
1121
3.15M
    struct demuxer *demuxer = in->d_user;
1122
1123
3.15M
    if (in->recorder) {
1124
0
        mp_recorder_destroy(in->recorder);
1125
0
        in->recorder = NULL;
1126
0
    }
1127
1128
3.15M
    dumper_close(in);
1129
1130
3.15M
    if (demuxer->desc->close)
1131
1.19M
        demuxer->desc->close(in->d_thread);
1132
3.15M
    demuxer->priv = NULL;
1133
3.15M
    in->d_thread->priv = NULL;
1134
1135
3.15M
    demux_flush(demuxer);
1136
3.15M
    mp_assert(in->total_bytes == 0);
1137
1138
3.15M
    in->current_range = NULL;
1139
3.15M
    free_empty_cached_ranges(in);
1140
1141
3.15M
    talloc_free(in->cache);
1142
3.15M
    in->cache = NULL;
1143
1144
3.15M
    if (in->owns_stream)
1145
3.15M
        free_stream(demuxer->stream);
1146
3.15M
    demuxer->stream = NULL;
1147
3.15M
}
1148
1149
static void demux_dealloc(struct demux_internal *in)
1150
3.15M
{
1151
3.55M
    for (int n = 0; n < in->num_streams; n++)
1152
407k
        talloc_free(in->streams[n]);
1153
3.15M
    mp_mutex_destroy(&in->lock);
1154
3.15M
    mp_cond_destroy(&in->wakeup);
1155
3.15M
    talloc_free(in->d_user);
1156
3.15M
}
1157
1158
void demux_free(struct demuxer *demuxer)
1159
3.21M
{
1160
3.21M
    if (!demuxer)
1161
304k
        return;
1162
2.91M
    struct demux_internal *in = demuxer->in;
1163
2.91M
    mp_assert(demuxer == in->d_user);
1164
1165
2.91M
    demux_stop_thread(demuxer);
1166
2.91M
    demux_shutdown(in);
1167
2.91M
    demux_dealloc(in);
1168
2.91M
}
1169
1170
// Start closing the demuxer and eventually freeing the demuxer asynchronously.
1171
// You must not access the demuxer once this has been started. Once the demuxer
1172
// is shutdown, the wakeup callback is invoked. Then you need to call
1173
// demux_free_async_finish() to end the operation (it must not be called from
1174
// the wakeup callback).
1175
// This can return NULL. Then the demuxer cannot be free'd asynchronously, and
1176
// you need to call demux_free() instead.
1177
struct demux_free_async_state *demux_free_async(struct demuxer *demuxer)
1178
267k
{
1179
267k
    struct demux_internal *in = demuxer->in;
1180
267k
    mp_assert(demuxer == in->d_user);
1181
1182
267k
    if (!in->threading)
1183
29.2k
        return NULL;
1184
1185
238k
    mp_mutex_lock(&in->lock);
1186
238k
    in->thread_terminate = true;
1187
238k
    in->shutdown_async = true;
1188
238k
    mp_cond_signal(&in->wakeup);
1189
238k
    mp_mutex_unlock(&in->lock);
1190
1191
238k
    return (struct demux_free_async_state *)demuxer->in; // lies
1192
267k
}
1193
1194
// As long as state is valid, you can call this to request immediate abort.
1195
// Roughly behaves as demux_cancel_and_free(), except you still need to wait
1196
// for the result.
1197
void demux_free_async_force(struct demux_free_async_state *state)
1198
34
{
1199
34
    struct demux_internal *in = (struct demux_internal *)state; // reverse lies
1200
1201
34
    mp_cancel_trigger(in->d_user->cancel);
1202
34
}
1203
1204
// Check whether the demuxer is shutdown yet. If not, return false, and you
1205
// need to call this again in the future (preferably after you were notified by
1206
// the wakeup callback). If yes, deallocate all state, and return true (in
1207
// particular, the state ptr becomes invalid, and the wakeup callback will never
1208
// be called again).
1209
bool demux_free_async_finish(struct demux_free_async_state *state)
1210
755k
{
1211
755k
    struct demux_internal *in = (struct demux_internal *)state; // reverse lies
1212
1213
755k
    mp_mutex_lock(&in->lock);
1214
755k
    bool busy = in->shutdown_async;
1215
755k
    mp_mutex_unlock(&in->lock);
1216
1217
755k
    if (busy)
1218
516k
        return false;
1219
1220
238k
    demux_stop_thread(in->d_user);
1221
238k
    demux_dealloc(in);
1222
238k
    return true;
1223
755k
}
1224
1225
// Like demux_free(), but trigger an abort, which will force the demuxer to
1226
// terminate immediately. If this wasn't opened with demux_open_url(), there is
1227
// some chance this will accidentally abort other things via demuxer->cancel.
1228
void demux_cancel_and_free(struct demuxer *demuxer)
1229
317k
{
1230
317k
    if (!demuxer)
1231
266k
        return;
1232
50.3k
    mp_cancel_trigger(demuxer->cancel);
1233
50.3k
    demux_free(demuxer);
1234
50.3k
}
1235
1236
// Start the demuxer thread, which reads ahead packets on its own.
1237
void demux_start_thread(struct demuxer *demuxer)
1238
257k
{
1239
257k
    struct demux_internal *in = demuxer->in;
1240
257k
    mp_assert(demuxer == in->d_user);
1241
1242
257k
    if (!in->threading) {
1243
257k
        in->threading = true;
1244
257k
        if (mp_thread_create(&in->thread, demux_thread, in))
1245
0
            in->threading = false;
1246
257k
    }
1247
257k
}
1248
1249
void demux_stop_thread(struct demuxer *demuxer)
1250
3.15M
{
1251
3.15M
    struct demux_internal *in = demuxer->in;
1252
3.15M
    mp_assert(demuxer == in->d_user);
1253
1254
3.15M
    if (in->threading) {
1255
257k
        mp_mutex_lock(&in->lock);
1256
257k
        in->thread_terminate = true;
1257
257k
        mp_cond_signal(&in->wakeup);
1258
257k
        mp_mutex_unlock(&in->lock);
1259
257k
        mp_thread_join(in->thread);
1260
257k
        in->threading = false;
1261
257k
        in->thread_terminate = false;
1262
257k
    }
1263
3.15M
}
1264
1265
// The demuxer thread will call cb(ctx) if there's a new packet, or EOF is reached.
1266
void demux_set_wakeup_cb(struct demuxer *demuxer, void (*cb)(void *ctx), void *ctx)
1267
524k
{
1268
524k
    struct demux_internal *in = demuxer->in;
1269
524k
    mp_mutex_lock(&in->lock);
1270
524k
    in->wakeup_cb = cb;
1271
524k
    in->wakeup_cb_ctx = ctx;
1272
524k
    mp_mutex_unlock(&in->lock);
1273
524k
}
1274
1275
void demux_start_prefetch(struct demuxer *demuxer)
1276
1
{
1277
1
    struct demux_internal *in = demuxer->in;
1278
1
    mp_assert(demuxer == in->d_user);
1279
1280
1
    mp_mutex_lock(&in->lock);
1281
1
    in->reading = true;
1282
1
    mp_cond_signal(&in->wakeup);
1283
1
    mp_mutex_unlock(&in->lock);
1284
1
}
1285
1286
void demux_drive_nav(struct demuxer *demuxer)
1287
0
{
1288
0
    struct demux_internal *in = demuxer->in;
1289
0
    mp_assert(demuxer == in->d_user);
1290
1291
0
    mp_mutex_lock(&in->lock);
1292
0
    in->nav_pump = true;
1293
0
    in->reading = true;
1294
0
    mp_cond_signal(&in->wakeup);
1295
0
    mp_mutex_unlock(&in->lock);
1296
0
}
1297
1298
// Re-queue sticky packets (e.g. the DVD menu subpicture) for re-delivery.
1299
void demux_nav_refresh(struct demuxer *demuxer)
1300
2.69M
{
1301
2.69M
    struct demux_internal *in = demuxer->in;
1302
2.69M
    mp_assert(demuxer == in->d_user);
1303
1304
2.69M
    mp_mutex_lock(&in->lock);
1305
2.69M
    if (in->d_thread->desc->nav_refresh) {
1306
0
        in->nav_refresh = true;
1307
0
        in->reading = true;
1308
0
        mp_cond_signal(&in->wakeup);
1309
0
    }
1310
2.69M
    mp_mutex_unlock(&in->lock);
1311
2.69M
}
1312
1313
const char *stream_type_name(enum stream_type type)
1314
14.3M
{
1315
14.3M
    switch (type) {
1316
3.25M
    case STREAM_VIDEO:  return "video";
1317
10.8M
    case STREAM_AUDIO:  return "audio";
1318
284k
    case STREAM_SUB:    return "sub";
1319
0
    default:            return "unknown";
1320
14.3M
    }
1321
14.3M
}
1322
1323
static void append_field(void *ta_ctx, bstr *dst, const char *skip_dup,
1324
                         const char *value)
1325
441k
{
1326
441k
    if (skip_dup && skip_dup[0] && strstr(skip_dup, value))
1327
0
        return;
1328
441k
    bstr_xappend_asprintf(ta_ctx, dst, " %s", value);
1329
441k
}
1330
1331
void demux_append_codec_desc(void *ta_ctx, bstr *dst, struct sh_stream *sh,
1332
                             const char *skip_dup)
1333
466k
{
1334
466k
    struct mp_codec_params *c = sh->codec;
1335
1336
466k
    bstr_xappend0(ta_ctx, dst, c->codec ? c->codec : "<unknown>");
1337
1338
466k
    if (c->codec_profile)
1339
92.9k
        bstr_xappend_asprintf(ta_ctx, dst, " [%s]", c->codec_profile);
1340
466k
    if (c->disp_w)
1341
176k
        append_field(ta_ctx, dst, skip_dup,
1342
176k
                     mp_tprintf(32, "%dx%d", c->disp_w, c->disp_h));
1343
466k
    if (c->fps && !sh->image) {
1344
141k
        char *fps = mp_format_double(ta_ctx, c->fps, 4, false, false, true);
1345
141k
        append_field(ta_ctx, dst, skip_dup, mp_tprintf(32, "%s fps", fps));
1346
141k
    }
1347
466k
    if (c->channels.num)
1348
146k
        bstr_xappend_asprintf(ta_ctx, dst, " %dch", c->channels.num);
1349
466k
    if (c->samplerate)
1350
144k
        bstr_xappend_asprintf(ta_ctx, dst, " %d Hz", c->samplerate);
1351
466k
    int bitrate = 0;
1352
466k
    if (c->bitrate > 0 && c->bitrate < INT_MAX - 500) {
1353
124k
        bitrate = (c->bitrate + 500) / 1000;
1354
341k
    } else if (sh->hls_bitrate > 0 && sh->hls_bitrate < INT_MAX - 500) {
1355
0
        bitrate = (sh->hls_bitrate + 500) / 1000;
1356
0
    }
1357
466k
    if (bitrate)
1358
123k
        append_field(ta_ctx, dst, skip_dup, mp_tprintf(32, "%d kbps", bitrate));
1359
466k
}
1360
1361
char *demux_compose_edition_title(void *ta_ctx, struct demuxer *demuxer,
1362
                                  int program_id, const char *prefix)
1363
0
{
1364
0
    struct sh_stream *vsh = NULL, *ash = NULL;
1365
0
    int video_count = 0, audio_count = 0;
1366
0
    int num = demux_get_num_stream(demuxer);
1367
0
    for (int i = 0; i < num; i++) {
1368
0
        struct sh_stream *s = demux_get_stream(demuxer, i);
1369
0
        if (!sh_stream_has_program(s, program_id))
1370
0
            continue;
1371
0
        if (s->type == STREAM_VIDEO) { video_count++; vsh = s; }
1372
0
        else if (s->type == STREAM_AUDIO) { audio_count++; ash = s; }
1373
0
    }
1374
1375
0
    bstr dst = {0};
1376
0
    if (prefix && prefix[0])
1377
0
        bstr_xappend0(ta_ctx, &dst, prefix);
1378
0
    if (video_count == 1) {
1379
0
        bstr_xappend0(ta_ctx, &dst, dst.len ? " (" : "(");
1380
0
        demux_append_codec_desc(ta_ctx, &dst, vsh, prefix);
1381
0
        bstr_xappend0(ta_ctx, &dst, ")");
1382
0
    }
1383
0
    if (audio_count == 1) {
1384
0
        bstr_xappend0(ta_ctx, &dst, dst.len ? " (" : "(");
1385
0
        demux_append_codec_desc(ta_ctx, &dst, ash, prefix);
1386
0
        bstr_xappend0(ta_ctx, &dst, ")");
1387
0
    }
1388
0
    if (!dst.len)
1389
0
        return NULL;
1390
0
    return bstrto0(ta_ctx, dst);
1391
0
}
1392
1393
static struct sh_stream *demuxer_get_cc_track_locked(struct sh_stream *stream)
1394
931
{
1395
931
    struct sh_stream *sh = stream->ds->cc;
1396
1397
931
    if (!sh) {
1398
429
        sh = demux_alloc_sh_stream(STREAM_SUB);
1399
429
        if (!sh)
1400
0
            return NULL;
1401
429
        sh->codec->codec = "eia_608";
1402
429
        sh->default_track = true;
1403
429
        sh->hls_bitrate = stream->hls_bitrate;
1404
429
        for (int i = 0; i < stream->num_program_ids; i++)
1405
0
            MP_TARRAY_APPEND(sh, sh->program_ids, sh->num_program_ids, stream->program_ids[i]);
1406
429
        stream->ds->cc = sh;
1407
429
        demux_add_sh_stream_locked(stream->ds->in, sh);
1408
429
        sh->ds->ignore_eof = true;
1409
429
    }
1410
1411
931
    return sh;
1412
931
}
1413
1414
void demuxer_feed_caption(struct sh_stream *stream, demux_packet_t *dp)
1415
875
{
1416
875
    struct demux_internal *in = stream->ds->in;
1417
1418
875
    mp_mutex_lock(&in->lock);
1419
875
    struct sh_stream *sh = demuxer_get_cc_track_locked(stream);
1420
875
    if (!sh) {
1421
0
        mp_mutex_unlock(&in->lock);
1422
0
        talloc_free(dp);
1423
0
        return;
1424
0
    }
1425
1426
875
    dp->keyframe = true;
1427
875
    dp->pts = MP_ADD_PTS(dp->pts, -in->ts_offset);
1428
875
    dp->dts = MP_ADD_PTS(dp->dts, -in->ts_offset);
1429
875
    dp->stream = sh->index;
1430
875
    add_packet_locked(sh, dp);
1431
875
    mp_mutex_unlock(&in->lock);
1432
875
}
1433
1434
static void error_on_backward_demuxing(struct demux_internal *in)
1435
0
{
1436
0
    if (!in->back_demuxing)
1437
0
        return;
1438
0
    MP_ERR(in, "Disabling backward demuxing.\n");
1439
0
    in->back_demuxing = false;
1440
0
    clear_reader_state(in, true);
1441
0
}
1442
1443
static void perform_backward_seek(struct demux_internal *in)
1444
1.87M
{
1445
1.87M
    double target = MP_NOPTS_VALUE;
1446
1447
5.55M
    for (int n = 0; n < in->num_streams; n++) {
1448
3.67M
        struct demux_stream *ds = in->streams[n]->ds;
1449
1450
3.67M
        if (ds->reader_head && !ds->back_restarting && !ds->back_resuming &&
1451
1.47k
            ds->eager)
1452
1.47k
        {
1453
1.47k
            ds->back_resuming = true;
1454
1.47k
            ds->back_resume_pos = ds->reader_head->pos;
1455
1.47k
            ds->back_resume_dts = ds->reader_head->dts;
1456
1.47k
        }
1457
1458
3.67M
        target = MP_PTS_MIN(target, ds->back_seek_pos);
1459
3.67M
    }
1460
1461
1.87M
    target = MP_PTS_OR_DEF(target, in->d_thread->start_time);
1462
1463
1.87M
    MP_VERBOSE(in, "triggering backward seek to get more packets\n");
1464
1.87M
    queue_seek(in, target, SEEK_SATAN | SEEK_HR, false);
1465
1.87M
    in->reading = true;
1466
1467
    // Don't starve other threads.
1468
1.87M
    mp_mutex_unlock(&in->lock);
1469
1.87M
    mp_mutex_lock(&in->lock);
1470
1.87M
}
1471
1472
// For incremental backward demuxing search work.
1473
static void check_backward_seek(struct demux_internal *in)
1474
61
{
1475
61
    in->back_any_need_recheck = false;
1476
1477
155
    for (int n = 0; n < in->num_streams; n++) {
1478
94
        struct demux_stream *ds = in->streams[n]->ds;
1479
1480
94
        if (ds->back_need_recheck)
1481
60
            find_backward_restart_pos(ds);
1482
94
    }
1483
61
}
1484
1485
// Search for a packet to resume demuxing from.
1486
// The implementation of this function is quite awkward, because the packet
1487
// queue is a singly linked list without back links, while it needs to search
1488
// backwards.
1489
// This is the core of backward demuxing.
1490
static void find_backward_restart_pos(struct demux_stream *ds)
1491
3.82M
{
1492
3.82M
    struct demux_internal *in = ds->in;
1493
1494
3.82M
    ds->back_need_recheck = false;
1495
3.82M
    if (!ds->back_restarting)
1496
0
        return;
1497
1498
3.82M
    struct demux_packet *first = ds->reader_head;
1499
3.82M
    struct demux_packet *last = ds->queue->tail;
1500
1501
3.82M
    if (first && !first->keyframe)
1502
3.82M
        MP_WARN(in, "Queue not starting on keyframe.\n");
1503
1504
    // Packet at back_restart_pos. (Note: we don't actually need it, only the
1505
    // packet immediately before it. But same effort.)
1506
    // If this is NULL, look for EOF (resume from very last keyframe).
1507
3.82M
    struct demux_packet *back_restart = NULL;
1508
1509
3.82M
    if (ds->back_restart_next) {
1510
        // Initial state. Switch to one of the other modi.
1511
1512
68.6k
        for (struct demux_packet *cur = first; cur; cur = cur->next) {
1513
            // Restart for next keyframe after reader_head.
1514
13.5k
            if (cur != first && cur->keyframe) {
1515
350
                ds->back_restart_dts = cur->dts;
1516
350
                ds->back_restart_pos = cur->pos;
1517
350
                ds->back_restart_eof = false;
1518
350
                ds->back_restart_next = false;
1519
350
                break;
1520
350
            }
1521
13.5k
        }
1522
1523
55.4k
        if (ds->back_restart_next && ds->eof) {
1524
            // Restart from end if nothing was found.
1525
24.1k
            ds->back_restart_eof = true;
1526
24.1k
            ds->back_restart_next = false;
1527
24.1k
        }
1528
1529
55.4k
        if (ds->back_restart_next)
1530
30.9k
            return;
1531
55.4k
    }
1532
1533
3.79M
    if (ds->back_restart_eof) {
1534
        // We're trying to find EOF (without discarding packets). Only continue
1535
        // if we really reach EOF.
1536
3.63M
        if (!ds->eof)
1537
1.80M
            return;
1538
3.63M
    } else if (!first && ds->eof) {
1539
        // Reached EOF during normal backward demuxing. We probably returned the
1540
        // last keyframe range to user. Need to resume at an earlier position.
1541
        // Fall through, hit the no-keyframe case (and possibly the BOF check
1542
        // if there are no packets at all), and then resume_earlier.
1543
152k
    } else if (!first) {
1544
75.2k
        return; // no packets yet
1545
77.0k
    } else {
1546
77.0k
        mp_assert(last);
1547
1548
77.0k
        if ((ds->global_correct_dts && last->dts < ds->back_restart_dts) ||
1549
77.0k
            (ds->global_correct_pos && last->pos < ds->back_restart_pos))
1550
0
            return; // restart pos not reached yet
1551
1552
        // The target we're searching for is apparently before the start of the
1553
        // queue.
1554
77.0k
        if ((ds->global_correct_dts && first->dts > ds->back_restart_dts) ||
1555
68.3k
            (ds->global_correct_pos && first->pos > ds->back_restart_pos))
1556
8.69k
            goto resume_earlier; // current position is too late; seek back
1557
1558
1559
69.0k
        for (struct demux_packet *cur = first; cur; cur = cur->next) {
1560
69.0k
            if ((ds->global_correct_dts && cur->dts == ds->back_restart_dts) ||
1561
645
                (ds->global_correct_pos && cur->pos == ds->back_restart_pos))
1562
68.3k
            {
1563
68.3k
                back_restart = cur;
1564
68.3k
                break;
1565
68.3k
            }
1566
69.0k
        }
1567
1568
68.3k
        if (!back_restart) {
1569
            // The packet should have been in the searched range; maybe dts/pos
1570
            // determinism assumptions were broken.
1571
0
            MP_ERR(in, "Demuxer not cooperating.\n");
1572
0
            error_on_backward_demuxing(in);
1573
0
            return;
1574
0
        }
1575
68.3k
    }
1576
1577
    // Find where to restart demuxing. It's usually the last keyframe packet
1578
    // before restart_pos, but might be up to back_preroll + batch keyframe
1579
    // packets earlier.
1580
1581
    // (Normally, we'd just iterate backwards, but no back links.)
1582
1.90M
    int num_kf = 0;
1583
1.90M
    struct demux_packet *pre_1 = NULL; // idiotic "optimization" for total=1
1584
1.91M
    for (struct demux_packet *dp = first; dp != back_restart; dp = dp->next) {
1585
6.91k
        if (dp->keyframe) {
1586
6.91k
            num_kf++;
1587
6.91k
            pre_1 = dp;
1588
6.91k
        }
1589
6.91k
    }
1590
1591
    // Number of renderable keyframes to return to user.
1592
    // (Excludes preroll, which is decoded by user, but then discarded.)
1593
1.90M
    int batch = MPMAX(in->d_user->opts->back_batch[ds->type], 1);
1594
    // Number of keyframes to return to the user in total.
1595
1.90M
    int total = batch + ds->back_preroll;
1596
1597
1.90M
    mp_assert(total >= 1);
1598
1599
1.90M
    bool is_bof = ds->queue->is_bof &&
1600
24.0k
        (first == ds->queue->head || ds->back_seek_pos < ds->queue->seek_start);
1601
1602
1.90M
    struct demux_packet *target = NULL; // resume pos
1603
    // nr. of keyframes, incl. target, excl. restart_pos
1604
1.90M
    int got_total = num_kf < total && is_bof ? num_kf : total;
1605
1.90M
    int got_preroll = MPMAX(got_total - batch, 0);
1606
1607
1.90M
    if (got_total == 1) {
1608
84.9k
        target = pre_1;
1609
1.82M
    } else if (got_total <= num_kf) {
1610
24.0k
        int cur_kf = 0;
1611
24.0k
        for (struct demux_packet *dp = first; dp != back_restart; dp = dp->next) {
1612
0
            if (dp->keyframe) {
1613
0
                if (num_kf - cur_kf == got_total) {
1614
0
                    target = dp;
1615
0
                    break;
1616
0
                }
1617
0
                cur_kf++;
1618
0
            }
1619
0
        }
1620
24.0k
    }
1621
1622
1.90M
    if (!target) {
1623
1.89M
        if (is_bof) {
1624
24.0k
            MP_VERBOSE(in, "BOF for stream %d\n", ds->index);
1625
24.0k
            ds->back_restarting = false;
1626
24.0k
            ds->back_range_started = false;
1627
24.0k
            ds->back_range_count = -1;
1628
24.0k
            ds->back_range_preroll = 0;
1629
24.0k
            ds->need_wakeup = true;
1630
24.0k
            wakeup_ds(ds);
1631
24.0k
            return;
1632
24.0k
        }
1633
1.87M
        goto resume_earlier;
1634
1.89M
    }
1635
1636
    // Skip reader_head from previous keyframe to current one.
1637
    // Or if preroll is involved, the first preroll packet.
1638
6.43k
    while (ds->reader_head != target) {
1639
0
        if (!advance_reader_head(ds))
1640
0
            MP_ASSERT_UNREACHABLE(); // target must be in list
1641
0
    }
1642
1643
6.43k
    double seek_pts;
1644
6.43k
    compute_keyframe_times(target, &seek_pts, NULL);
1645
6.43k
    if (seek_pts != MP_NOPTS_VALUE)
1646
6.43k
        ds->back_seek_pos = seek_pts;
1647
1648
    // For next backward adjust action.
1649
6.43k
    struct demux_packet *restart_pkt = NULL;
1650
6.43k
    int kf_pos = 0;
1651
6.43k
    for (struct demux_packet *dp = target; dp; dp = dp->next) {
1652
6.43k
        if (dp->keyframe) {
1653
6.43k
            if (kf_pos == got_preroll) {
1654
6.43k
                restart_pkt = dp;
1655
6.43k
                break;
1656
6.43k
            }
1657
0
            kf_pos++;
1658
0
        }
1659
6.43k
    }
1660
6.43k
    mp_assert(restart_pkt);
1661
6.43k
    ds->back_restart_dts = restart_pkt->dts;
1662
6.43k
    ds->back_restart_pos = restart_pkt->pos;
1663
1664
6.43k
    ds->back_restarting = false;
1665
6.43k
    ds->back_range_started = false;
1666
6.43k
    ds->back_range_count = got_total;
1667
6.43k
    ds->back_range_preroll = got_preroll;
1668
6.43k
    ds->need_wakeup = true;
1669
6.43k
    wakeup_ds(ds);
1670
6.43k
    return;
1671
1672
1.88M
resume_earlier:
1673
    // We want to seek back to get earlier packets. But before we do this, we
1674
    // must be sure that other streams have initialized their state. The only
1675
    // time when this state is not initialized is right after the seek that
1676
    // started backward demuxing (not any subsequent backstep seek). If this
1677
    // initialization is omitted, the stream would try to start demuxing from
1678
    // the "current" position. If another stream backstepped before that, the
1679
    // other stream will miss the original seek target, and start playback from
1680
    // a position that is too early.
1681
5.57M
    for (int n = 0; n < in->num_streams; n++) {
1682
3.70M
        struct demux_stream *ds2 = in->streams[n]->ds;
1683
3.70M
        if (ds2 == ds || !ds2->eager)
1684
2.58M
            continue;
1685
1686
1.12M
        if (ds2->back_restarting && ds2->back_restart_next) {
1687
8.82k
            MP_VERBOSE(in, "delaying stream %d for %d\n", ds->index, ds2->index);
1688
8.82k
            return;
1689
8.82k
        }
1690
1.12M
    }
1691
1692
1.87M
    if (ds->back_seek_pos != MP_NOPTS_VALUE) {
1693
1.87M
        struct demux_packet *t =
1694
1.87M
            find_seek_target(ds->queue, ds->back_seek_pos - 0.001, 0);
1695
1.87M
        if (t && t != ds->reader_head) {
1696
61
            double pts;
1697
61
            compute_keyframe_times(t, &pts, NULL);
1698
61
            ds->back_seek_pos = MP_PTS_MIN(ds->back_seek_pos, pts);
1699
61
            ds_clear_reader_state(ds, false);
1700
61
            ds->reader_head = t;
1701
61
            ds->back_need_recheck = true;
1702
61
            in->back_any_need_recheck = true;
1703
61
            mp_cond_signal(&in->wakeup);
1704
1.87M
        } else {
1705
1.87M
            ds->back_seek_pos -= in->d_user->opts->back_seek_size;
1706
1.87M
            in->need_back_seek = true;
1707
1.87M
        }
1708
1.87M
    }
1709
1.87M
}
1710
1711
// Process that one or multiple packets were added.
1712
static void back_demux_see_packets(struct demux_stream *ds)
1713
27.3M
{
1714
27.3M
    struct demux_internal *in = ds->in;
1715
1716
27.3M
    if (!ds->selected || !in->back_demuxing || !ds->eager)
1717
21.3M
        return;
1718
1719
6.01M
    mp_assert(!(ds->back_resuming && ds->back_restarting));
1720
1721
6.01M
    if (!ds->global_correct_dts && !ds->global_correct_pos) {
1722
0
        MP_ERR(in, "Can't demux backward due to demuxer problems.\n");
1723
0
        error_on_backward_demuxing(in);
1724
0
        return;
1725
0
    }
1726
1727
6.01M
    while (ds->back_resuming && ds->reader_head) {
1728
3.38k
        struct demux_packet *head = ds->reader_head;
1729
3.38k
        if ((ds->global_correct_dts && head->dts == ds->back_resume_dts) ||
1730
2.01k
            (ds->global_correct_pos && head->pos == ds->back_resume_pos))
1731
1.37k
        {
1732
1.37k
            ds->back_resuming = false;
1733
1.37k
            ds->need_wakeup = true;
1734
1.37k
            wakeup_ds(ds); // probably
1735
1.37k
            break;
1736
1.37k
        }
1737
2.01k
        advance_reader_head(ds);
1738
2.01k
    }
1739
1740
6.01M
    if (ds->back_restarting)
1741
3.82M
        find_backward_restart_pos(ds);
1742
6.01M
}
1743
1744
// Add the keyframe to the end of the index. Not all packets are actually added.
1745
static void add_index_entry(struct demux_queue *queue, struct demux_packet *dp,
1746
                            double pts)
1747
2.06M
{
1748
2.06M
    struct demux_internal *in = queue->ds->in;
1749
1750
2.06M
    mp_assert(dp->keyframe && pts != MP_NOPTS_VALUE);
1751
1752
2.06M
    if (queue->num_index > 0) {
1753
2.04M
        struct index_entry *last = &QUEUE_INDEX_ENTRY(queue, queue->num_index - 1);
1754
2.04M
        if (pts - last->pts < INDEX_STEP_SIZE)
1755
1.98M
            return;
1756
2.04M
    }
1757
1758
76.9k
    if (queue->num_index == queue->index_size) {
1759
        // Needs to honor power-of-2 requirement.
1760
15.9k
        size_t new_size = MPMAX(128, queue->index_size * 2);
1761
15.9k
        mp_assert(!(new_size & (new_size - 1)));
1762
15.9k
        MP_DBG(in, "stream %d: resize index to %zu\n", queue->ds->index,
1763
15.9k
               new_size);
1764
        // Note: we could tolerate allocation failure, and just discard the
1765
        // entire index (and prevent the index from being recreated).
1766
15.9k
        MP_RESIZE_ARRAY(NULL, queue->index, new_size);
1767
15.9k
        size_t highest_index = queue->index0 + queue->num_index;
1768
15.9k
        for (size_t n = queue->index_size; n < highest_index; n++)
1769
0
            queue->index[n] = queue->index[n - queue->index_size];
1770
15.9k
        in->total_bytes +=
1771
15.9k
            (new_size - queue->index_size) * sizeof(queue->index[0]);
1772
15.9k
        queue->index_size = new_size;
1773
15.9k
    }
1774
1775
76.9k
    mp_assert(queue->num_index < queue->index_size);
1776
1777
76.9k
    queue->num_index += 1;
1778
1779
76.9k
    QUEUE_INDEX_ENTRY(queue, queue->num_index - 1) = (struct index_entry){
1780
76.9k
        .pts = pts,
1781
76.9k
        .pkt = dp,
1782
76.9k
    };
1783
76.9k
}
1784
1785
// Check whether the next range in the list is, and if it appears to overlap,
1786
// try joining it into a single range.
1787
static void attempt_range_joining(struct demux_internal *in)
1788
2.42M
{
1789
2.42M
    struct demux_cached_range *current = in->current_range;
1790
2.42M
    struct demux_cached_range *next = NULL;
1791
2.42M
    double next_dist = INFINITY;
1792
1793
2.42M
    mp_assert(current && in->num_ranges > 0);
1794
2.42M
    mp_assert(current == in->ranges[in->num_ranges - 1]);
1795
1796
2.42M
    for (int n = 0; n < in->num_ranges - 1; n++) {
1797
137
        struct demux_cached_range *range = in->ranges[n];
1798
1799
137
        if (current->seek_start <= range->seek_start) {
1800
            // This uses ">" to get some non-0 overlap.
1801
55
            double dist = current->seek_end - range->seek_start;
1802
55
            if (dist > 0 && dist < next_dist) {
1803
0
                next = range;
1804
0
                next_dist = dist;
1805
0
            }
1806
55
        }
1807
137
    }
1808
1809
2.42M
    if (!next)
1810
2.42M
        return;
1811
1812
0
    MP_VERBOSE(in, "going to join ranges %f-%f + %f-%f\n",
1813
0
               current->seek_start, current->seek_end,
1814
0
               next->seek_start, next->seek_end);
1815
1816
    // Try to find a join point, where packets obviously overlap. (It would be
1817
    // better and faster to do this incrementally, but probably too complex.)
1818
    // The current range can overlap arbitrarily with the next one, not only by
1819
    // the seek overlap, but for arbitrary packet readahead as well.
1820
    // We also drop the overlapping packets (if joining fails, we discard the
1821
    // entire next range anyway, so this does no harm).
1822
0
    for (int n = 0; n < in->num_streams; n++) {
1823
0
        struct demux_stream *ds = in->streams[n]->ds;
1824
1825
0
        struct demux_queue *q1 = current->streams[n];
1826
0
        struct demux_queue *q2 = next->streams[n];
1827
1828
0
        if (!ds->global_correct_pos && !ds->global_correct_dts) {
1829
0
            MP_WARN(in, "stream %d: ranges unjoinable\n", n);
1830
0
            goto failed;
1831
0
        }
1832
1833
0
        struct demux_packet *end = q1->tail;
1834
0
        bool join_point_found = !end; // no packets yet -> joining will work
1835
0
        if (end) {
1836
0
            while (q2->head) {
1837
0
                struct demux_packet *dp = q2->head;
1838
1839
                // Some weird corner-case. We'd have to search the equivalent
1840
                // packet in q1 to update it correctly. Better just give up.
1841
0
                if (dp == q2->keyframe_latest) {
1842
0
                    MP_VERBOSE(in, "stream %d: not enough keyframes for join\n", n);
1843
0
                    goto failed;
1844
0
                }
1845
1846
0
                if ((ds->global_correct_dts && dp->dts == end->dts) ||
1847
0
                    (ds->global_correct_pos && dp->pos == end->pos))
1848
0
                {
1849
                    // Do some additional checks as a (imperfect) sanity check
1850
                    // in case pos/dts are not "correct" across the ranges (we
1851
                    // never actually check that).
1852
0
                    if (dp->dts != end->dts || dp->pos != end->pos ||
1853
0
                        dp->pts != end->pts)
1854
0
                    {
1855
0
                        MP_WARN(in,
1856
0
                            "stream %d: non-repeatable demuxer behavior\n", n);
1857
0
                        goto failed;
1858
0
                    }
1859
1860
0
                    remove_head_packet(q2);
1861
0
                    join_point_found = true;
1862
0
                    break;
1863
0
                }
1864
1865
                // This happens if the next range misses the end packet. For
1866
                // normal streams (ds->eager==true), this is a failure to find
1867
                // an overlap. For subtitles, this can mean the current_range
1868
                // has a subtitle somewhere before the end of its range, and
1869
                // next has another subtitle somewhere after the start of its
1870
                // range.
1871
0
                if ((ds->global_correct_dts && dp->dts > end->dts) ||
1872
0
                    (ds->global_correct_pos && dp->pos > end->pos))
1873
0
                    break;
1874
1875
0
                remove_head_packet(q2);
1876
0
            }
1877
0
        }
1878
1879
        // For enabled non-sparse streams, always require an overlap packet.
1880
0
        if (ds->eager && !join_point_found) {
1881
0
            MP_WARN(in, "stream %d: no join point found\n", n);
1882
0
            goto failed;
1883
0
        }
1884
0
    }
1885
1886
    // Actually join the ranges. Now that we think it will work, mutate the
1887
    // data associated with the current range.
1888
1889
0
    for (int n = 0; n < in->num_streams; n++) {
1890
0
        struct demux_queue *q1 = current->streams[n];
1891
0
        struct demux_queue *q2 = next->streams[n];
1892
1893
0
        struct demux_stream *ds = in->streams[n]->ds;
1894
0
        mp_assert(ds->queue == q1);
1895
1896
        // First new packet that is appended to the current range.
1897
0
        struct demux_packet *join_point = q2->head;
1898
1899
0
        if (q2->head) {
1900
0
            if (q1->head) {
1901
0
                q1->tail->next = q2->head;
1902
0
            } else {
1903
0
                q1->head = q2->head;
1904
0
            }
1905
0
            q1->tail = q2->tail;
1906
0
        }
1907
1908
0
        q1->seek_end = q2->seek_end;
1909
0
        q1->correct_dts &= q2->correct_dts;
1910
0
        q1->correct_pos &= q2->correct_pos;
1911
0
        q1->last_pos = q2->last_pos;
1912
0
        q1->last_dts = q2->last_dts;
1913
0
        q1->last_ts = q2->last_ts;
1914
0
        q1->keyframe_latest = q2->keyframe_latest;
1915
0
        q1->is_eof = q2->is_eof;
1916
1917
0
        q1->last_pos_fixup = -1;
1918
1919
0
        q2->head = q2->tail = NULL;
1920
0
        q2->keyframe_first = NULL;
1921
0
        q2->keyframe_latest = NULL;
1922
1923
0
        if (ds->selected && !ds->reader_head)
1924
0
            ds->reader_head = join_point;
1925
0
        ds->skip_to_keyframe = false;
1926
1927
        // Make the cum_pos values in all q2 packets continuous.
1928
0
        for (struct demux_packet *dp = join_point; dp; dp = dp->next) {
1929
0
            uint64_t next_pos = dp->next ? dp->next->cum_pos : q2->tail_cum_pos;
1930
0
            uint64_t size = next_pos - dp->cum_pos;
1931
0
            dp->cum_pos = q1->tail_cum_pos;
1932
0
            q1->tail_cum_pos += size;
1933
0
        }
1934
1935
        // And update the index with packets from q2.
1936
0
        for (size_t i = 0; i < q2->num_index; i++) {
1937
0
            struct index_entry *e = &QUEUE_INDEX_ENTRY(q2, i);
1938
0
            add_index_entry(q1, e->pkt, e->pts);
1939
0
        }
1940
0
        free_index(q2);
1941
1942
        // For moving demuxer position.
1943
0
        ds->refreshing = ds->selected;
1944
0
    }
1945
1946
0
    for (int n = 0; n < next->num_metadata; n++) {
1947
0
        MP_TARRAY_APPEND(current, current->metadata, current->num_metadata,
1948
0
                         next->metadata[n]);
1949
0
    }
1950
0
    next->num_metadata = 0;
1951
1952
0
    update_seek_ranges(current);
1953
1954
    // Move demuxing position to after the current range.
1955
0
    in->seeking = true;
1956
0
    in->seek_flags = SEEK_HR;
1957
0
    in->seek_pts = next->seek_end - 1.0;
1958
1959
0
    MP_VERBOSE(in, "ranges joined!\n");
1960
1961
0
    for (int n = 0; n < in->num_streams; n++)
1962
0
        back_demux_see_packets(in->streams[n]->ds);
1963
1964
0
failed:
1965
0
    clear_cached_range(in, next);
1966
0
    free_empty_cached_ranges(in);
1967
0
}
1968
1969
// Compute the assumed first and last frame timestamp for keyframe range
1970
// starting at pkt. To get valid results, pkt->keyframe must be true, otherwise
1971
// nonsense will be returned.
1972
// Always sets *out_kf_min and *out_kf_max without reading them. Both are set
1973
// to NOPTS if there are no timestamps at all in the stream. *kf_max will not
1974
// be set to the actual end time of the decoded output, just the last frame
1975
// (audio will typically end up with kf_min==kf_max).
1976
// Either of out_kf_min and out_kf_max can be NULL, which discards the result.
1977
// Return the next keyframe packet after pkt, or NULL if there's none.
1978
static struct demux_packet *compute_keyframe_times(struct demux_packet *pkt,
1979
                                                   double *out_kf_min,
1980
                                                   double *out_kf_max)
1981
11.8M
{
1982
11.8M
    struct demux_packet *start = pkt;
1983
11.8M
    double min = MP_NOPTS_VALUE;
1984
11.8M
    double max = MP_NOPTS_VALUE;
1985
1986
21.6M
    while (pkt) {
1987
18.7M
        if (pkt->keyframe && pkt != start)
1988
8.99M
            break;
1989
1990
9.74M
        double ts = MP_PTS_OR_DEF(pkt->pts, pkt->dts);
1991
9.74M
        if (pkt->segmented && ((pkt->start != MP_NOPTS_VALUE && ts < pkt->start) ||
1992
1.22M
                               (pkt->end != MP_NOPTS_VALUE && ts > pkt->end)))
1993
38.9k
            ts = MP_NOPTS_VALUE;
1994
1995
9.74M
        min = MP_PTS_MIN(min, ts);
1996
9.74M
        max = MP_PTS_MAX(max, ts);
1997
1998
9.74M
        pkt = pkt->next;
1999
9.74M
    }
2000
2001
11.8M
    if (out_kf_min)
2002
11.8M
        *out_kf_min = min;
2003
11.8M
    if (out_kf_max)
2004
2.06M
        *out_kf_max = max;
2005
11.8M
    return pkt;
2006
11.8M
}
2007
2008
// Determine seekable range when a packet is added. If dp==NULL, treat it as
2009
// EOF (i.e. closes the current block).
2010
// This has to deal with a number of corner cases, such as demuxers potentially
2011
// starting output at non-keyframes.
2012
// Can join seek ranges, which messes with in->current_range and all.
2013
static void adjust_seek_range_on_packet(struct demux_stream *ds,
2014
                                        struct demux_packet *dp)
2015
23.6M
{
2016
23.6M
    struct demux_queue *queue = ds->queue;
2017
2018
23.6M
    if (!ds->in->seekable_cache)
2019
20.7M
        return;
2020
2021
23.6M
    bool new_eof = !dp;
2022
2.94M
    bool update_ranges = queue->is_eof != new_eof;
2023
2.94M
    queue->is_eof = new_eof;
2024
2025
2.94M
    if (!dp || dp->keyframe) {
2026
2.85M
        if (queue->keyframe_latest) {
2027
2.06M
            double kf_min, kf_max;
2028
2.06M
            compute_keyframe_times(queue->keyframe_latest, &kf_min, &kf_max);
2029
2030
2.06M
            if (kf_min != MP_NOPTS_VALUE) {
2031
2.06M
                add_index_entry(queue, queue->keyframe_latest, kf_min);
2032
2033
                // Initialize the queue's start if it's unset.
2034
2.06M
                if (queue->seek_start == MP_NOPTS_VALUE) {
2035
15.9k
                    update_ranges = true;
2036
15.9k
                    queue->seek_start = kf_min + ds->sh->seek_preroll;
2037
2038
                    // queue->is_bof is set optimistically after a seek to start,
2039
                    // assuming demuxing began at the start of the file. That is
2040
                    // wrong for streams opened mid-content, which can happen in
2041
                    // unfinished event HLS playlists, which starts at live-edge,
2042
                    // but the seekable range in the past is still valid.
2043
15.9k
                    double start_time = ds->in->d_thread->start_time;
2044
15.9k
                    if (queue->is_bof && ds->in->d_thread->seekable &&
2045
15.6k
                        start_time != MP_NOPTS_VALUE &&
2046
15.6k
                        queue->seek_start > start_time + BOF_START_TOLERANCE)
2047
91
                    {
2048
91
                        queue->is_bof = false;
2049
91
                    }
2050
15.9k
                }
2051
2.06M
            }
2052
2053
2.06M
            if (kf_max != MP_NOPTS_VALUE &&
2054
2.06M
                (queue->seek_end == MP_NOPTS_VALUE || kf_max > queue->seek_end))
2055
1.92M
            {
2056
                // If the queue was past the current range's end even before
2057
                // this update, it means _other_ streams are not there yet,
2058
                // and the seek range doesn't need to be updated. This means
2059
                // if the _old_ queue->seek_end was already after the range end,
2060
                // then the new seek_end won't extend the range either.
2061
1.92M
                if (queue->range->seek_end == MP_NOPTS_VALUE ||
2062
1.89M
                    queue->seek_end <= queue->range->seek_end)
2063
1.90M
                {
2064
1.90M
                    update_ranges = true;
2065
1.90M
                }
2066
2067
1.92M
                queue->seek_end = kf_max;
2068
1.92M
            }
2069
2.06M
        }
2070
2071
2.85M
        queue->keyframe_latest = dp;
2072
2.85M
    }
2073
2074
    // Adding a sparse packet never changes the seek range.
2075
2.94M
    if (update_ranges && ds->eager) {
2076
2.42M
        update_seek_ranges(queue->range);
2077
2.42M
        attempt_range_joining(ds->in);
2078
2.42M
    }
2079
2.94M
}
2080
2081
static struct mp_recorder *recorder_create(struct demux_internal *in,
2082
                                           const char *dst)
2083
45
{
2084
45
    struct sh_stream **streams = NULL;
2085
45
    int num_streams = 0;
2086
134
    for (int n = 0; n < in->num_streams; n++) {
2087
89
        struct sh_stream *stream = in->streams[n];
2088
89
        if (stream->ds->selected)
2089
66
            MP_TARRAY_APPEND(NULL, streams, num_streams, stream);
2090
89
    }
2091
2092
45
    struct demuxer *demuxer = in->d_thread;
2093
45
    struct demux_attachment **attachments = talloc_array(NULL, struct demux_attachment*, demuxer->num_attachments);
2094
45
    for (int n = 0; n < demuxer->num_attachments; n++) {
2095
0
        attachments[n] = &demuxer->attachments[n];
2096
0
    }
2097
2098
45
    struct mp_recorder *res = mp_recorder_create(in->d_thread->global, dst,
2099
45
                                                 streams, num_streams,
2100
45
                                                 attachments, demuxer->num_attachments);
2101
45
    talloc_free(streams);
2102
45
    talloc_free(attachments);
2103
45
    return res;
2104
45
}
2105
2106
static void write_dump_packet(struct demux_internal *in, struct demux_packet *dp)
2107
0
{
2108
0
    mp_assert(in->dumper);
2109
0
    mp_assert(in->dumper_status == CONTROL_TRUE);
2110
2111
0
    struct mp_recorder_sink *sink =
2112
0
        mp_recorder_get_sink(in->dumper, in->streams[dp->stream]);
2113
0
    if (sink) {
2114
0
        mp_recorder_feed_packet(sink, dp);
2115
0
    } else {
2116
0
        MP_ERR(in, "New stream appeared; stopping recording.\n");
2117
0
        in->dumper_status = CONTROL_ERROR;
2118
0
    }
2119
0
}
2120
2121
static void record_packet(struct demux_internal *in, struct demux_packet *dp)
2122
14.1M
{
2123
    // (should preferably be outside of the lock)
2124
14.1M
    if (in->enable_recording && !in->recorder &&
2125
1
        in->d_user->opts->record_file && in->d_user->opts->record_file[0])
2126
1
    {
2127
        // Later failures shouldn't make it retry and overwrite the previously
2128
        // recorded file.
2129
1
        in->enable_recording = false;
2130
2131
1
        in->recorder = recorder_create(in, in->d_user->opts->record_file);
2132
1
        if (!in->recorder)
2133
1
            MP_ERR(in, "Disabling recording.\n");
2134
1
    }
2135
2136
14.1M
    if (in->recorder) {
2137
0
        struct mp_recorder_sink *sink =
2138
0
            mp_recorder_get_sink(in->recorder, in->streams[dp->stream]);
2139
0
        if (sink) {
2140
0
            mp_recorder_feed_packet(sink, dp);
2141
0
        } else {
2142
0
            MP_ERR(in, "New stream appeared; stopping recording.\n");
2143
0
            mp_recorder_destroy(in->recorder);
2144
0
            in->recorder = NULL;
2145
0
        }
2146
0
    }
2147
2148
14.1M
    if (in->dumper_status == CONTROL_OK)
2149
0
        write_dump_packet(in, dp);
2150
14.1M
}
2151
2152
static void add_packet_locked(struct sh_stream *stream, demux_packet_t *dp)
2153
14.3M
{
2154
14.3M
    struct demux_stream *ds = stream ? stream->ds : NULL;
2155
14.3M
    mp_assert(ds && ds->in);
2156
14.3M
    if (!dp->len || demux_cancel_test(ds->in->d_thread)) {
2157
173k
        talloc_free(dp);
2158
173k
        return;
2159
173k
    }
2160
2161
14.2M
    mp_assert(dp->stream == stream->index);
2162
14.2M
    mp_assert(!dp->next);
2163
2164
14.2M
    struct demux_internal *in = ds->in;
2165
2166
14.2M
    in->after_seek = false;
2167
14.2M
    in->after_seek_to_start = false;
2168
2169
14.2M
    double ts = dp->dts == MP_NOPTS_VALUE ? dp->pts : dp->dts;
2170
14.2M
    if (dp->segmented)
2171
1.81M
        ts = MP_PTS_MIN(ts, dp->end);
2172
2173
14.2M
    if (ts != MP_NOPTS_VALUE)
2174
13.6M
        in->demux_ts = ts;
2175
2176
14.2M
    struct demux_queue *queue = ds->queue;
2177
2178
14.2M
    bool drop = !ds->selected || in->seeking || ds->sh->attached_picture;
2179
2180
14.2M
    if (!drop) {
2181
        // If libavformat splits packets, some packets will have pos unset, so
2182
        // make up one based on the first packet => makes refresh seeks work.
2183
14.2M
        if ((dp->pos < 0 || dp->pos == queue->last_pos_fixup) &&
2184
4.09M
            !dp->keyframe && queue->last_pos_fixup >= 0)
2185
20.3k
            dp->pos = queue->last_pos_fixup + 1;
2186
14.2M
        queue->last_pos_fixup = dp->pos;
2187
14.2M
    }
2188
2189
14.2M
    if (!drop && ds->refreshing) {
2190
        // Resume reading once the old position was reached (i.e. we start
2191
        // returning packets where we left off before the refresh).
2192
        // If it's the same position, drop, but continue normally next time.
2193
5.16k
        if (queue->correct_dts) {
2194
2.83k
            ds->refreshing = dp->dts < queue->last_dts;
2195
2.83k
        } else if (queue->correct_pos) {
2196
2.32k
            ds->refreshing = dp->pos < queue->last_pos;
2197
2.32k
        } else {
2198
0
            ds->refreshing = false; // should not happen
2199
0
            MP_WARN(in, "stream %d: demux refreshing failed\n", ds->index);
2200
0
        }
2201
5.16k
        drop = true;
2202
5.16k
    }
2203
2204
14.2M
    if (drop) {
2205
5.64k
        demux_packet_pool_push(in->packet_pool, dp);
2206
5.64k
        return;
2207
5.64k
    }
2208
2209
14.1M
    record_packet(in, dp);
2210
2211
14.1M
    if (in->cache && in->d_user->opts->disk_cache && !dp->is_wrapped_avframe) {
2212
0
        int64_t pos = demux_cache_write(in->cache, dp);
2213
0
        if (pos >= 0) {
2214
0
            demux_packet_unref_contents(dp);
2215
0
            dp->is_cached = true;
2216
0
            dp->cached_data.pos = pos;
2217
0
        }
2218
0
    }
2219
2220
14.1M
    queue->correct_pos &= dp->pos >= 0 && dp->pos > queue->last_pos;
2221
14.1M
    queue->correct_dts &= dp->dts != MP_NOPTS_VALUE && dp->dts > queue->last_dts;
2222
14.1M
    queue->last_pos = dp->pos;
2223
14.1M
    queue->last_dts = dp->dts;
2224
14.1M
    ds->global_correct_pos &= queue->correct_pos;
2225
14.1M
    ds->global_correct_dts &= queue->correct_dts;
2226
2227
    // (keep in mind that even if the reader went out of data, the queue is not
2228
    // necessarily empty due to the backbuffer)
2229
14.1M
    if (!ds->reader_head && (!ds->skip_to_keyframe || dp->keyframe)) {
2230
3.06M
        ds->reader_head = dp;
2231
3.06M
        ds->skip_to_keyframe = false;
2232
3.06M
    }
2233
2234
14.1M
    size_t bytes = demux_packet_estimate_total_size(dp);
2235
14.1M
    in->total_bytes += bytes;
2236
14.1M
    dp->cum_pos = queue->tail_cum_pos;
2237
14.1M
    queue->tail_cum_pos += bytes;
2238
2239
14.1M
    if (queue->tail) {
2240
        // next packet in stream
2241
11.1M
        queue->tail->next = dp;
2242
11.1M
        queue->tail = dp;
2243
11.1M
    } else {
2244
        // first packet in stream
2245
3.05M
        queue->head = queue->tail = dp;
2246
3.05M
    }
2247
2248
14.1M
    if (!ds->ignore_eof) {
2249
        // obviously not true anymore
2250
14.1M
        ds->eof = false;
2251
14.1M
        in->eof = false;
2252
14.1M
    }
2253
2254
    // For video, PTS determination is not trivial, but for other media types
2255
    // distinguishing PTS and DTS is not useful.
2256
14.1M
    if (stream->type != STREAM_VIDEO && dp->pts == MP_NOPTS_VALUE)
2257
302k
        dp->pts = dp->dts;
2258
2259
14.1M
    if (ts != MP_NOPTS_VALUE && (ts > queue->last_ts || ts + 10 < queue->last_ts))
2260
11.5M
        queue->last_ts = ts;
2261
14.1M
    if (ds->base_ts == MP_NOPTS_VALUE)
2262
575k
        ds->base_ts = queue->last_ts;
2263
2264
14.1M
    const char *num_pkts = queue->head == queue->tail ? "1" : ">1";
2265
14.1M
    uint64_t fw_bytes = get_forward_buffered_bytes(ds);
2266
14.1M
    MP_TRACE(in, "append packet to %s: size=%zu pts=%f dts=%f pos=%"PRIi64" "
2267
14.1M
             "[num=%s size=%zd]\n", stream_type_name(stream->type),
2268
14.1M
             dp->len, dp->pts, dp->dts, dp->pos, num_pkts, (size_t)fw_bytes);
2269
2270
14.1M
    adjust_seek_range_on_packet(ds, dp);
2271
2272
    // May need to reduce backward cache.
2273
14.1M
    prune_old_packets(in);
2274
2275
    // Possibly update duration based on highest TS demuxed (but ignore subs).
2276
14.1M
    if (stream->type != STREAM_SUB) {
2277
13.9M
        if (dp->segmented)
2278
1.81M
            ts = MP_PTS_MIN(ts, dp->end);
2279
13.9M
        if (ts > in->highest_av_pts) {
2280
11.3M
            in->highest_av_pts = ts;
2281
11.3M
            double duration = in->highest_av_pts - in->d_thread->start_time;
2282
11.3M
            if (duration > in->d_thread->duration) {
2283
6.39M
                in->d_thread->duration = duration;
2284
                // (Don't wakeup user thread, would be too noisy.)
2285
6.39M
                in->events |= DEMUX_EVENT_DURATION;
2286
6.39M
                in->duration = duration;
2287
6.39M
            }
2288
11.3M
        }
2289
13.9M
    }
2290
2291
    // Don't process the packet further if it's skipped by the previous seek
2292
    // (see reader_head check/assignment above).
2293
14.1M
    if (!ds->reader_head)
2294
0
        return;
2295
2296
14.1M
    back_demux_see_packets(ds);
2297
2298
14.1M
    wakeup_ds(ds);
2299
14.1M
}
2300
2301
static void mark_stream_eof(struct demux_stream *ds)
2302
11.3M
{
2303
11.3M
    if (!ds->eof) {
2304
9.46M
        ds->eof = true;
2305
9.46M
        adjust_seek_range_on_packet(ds, NULL);
2306
9.46M
        back_demux_see_packets(ds);
2307
9.46M
        wakeup_ds(ds);
2308
9.46M
    }
2309
11.3M
}
2310
2311
static bool lazy_stream_needs_wait(struct demux_stream *ds)
2312
1.87M
{
2313
1.87M
    struct demux_internal *in = ds->in;
2314
    // Attempt to read until force_read_until was reached, or reading has
2315
    // stopped for some reason (true EOF, queue overflow).
2316
1.87M
    return !ds->eager && !in->back_demuxing &&
2317
1.17M
           !in->eof && ds->force_read_until != MP_NOPTS_VALUE &&
2318
576
           (in->demux_ts == MP_NOPTS_VALUE ||
2319
576
            in->demux_ts <= ds->force_read_until);
2320
1.87M
}
2321
2322
// Returns true if there was "progress" (lock was released temporarily).
2323
static bool read_packet(struct demux_internal *in)
2324
31.3M
{
2325
31.3M
    bool was_reading = in->reading;
2326
31.3M
    in->reading = false;
2327
2328
31.3M
    if (!was_reading || in->blocked || demux_cancel_test(in->d_thread))
2329
7.18M
        return false;
2330
2331
    // Check if we need to read a new packet. We do this if all queues are below
2332
    // the minimum, or if a stream explicitly needs new packets. Also includes
2333
    // safe-guards against packet queue overflow.
2334
31.3M
    bool read_more = false, prefetch_more = false, refresh_more = false;
2335
24.1M
    uint64_t total_fw_bytes = 0;
2336
55.0M
    for (int n = 0; n < in->num_streams; n++)
2337
30.9M
        total_fw_bytes += get_forward_buffered_bytes(in->streams[n]->ds);
2338
24.1M
    if (in->hyst_bytes > 0 && total_fw_bytes <= in->hyst_bytes)
2339
335
        in->hyst_active = false;
2340
55.0M
    for (int n = 0; n < in->num_streams; n++) {
2341
30.9M
        struct demux_stream *ds = in->streams[n]->ds;
2342
30.9M
        if (ds->eager) {
2343
29.1M
            read_more |= !ds->reader_head;
2344
29.1M
            if (in->back_demuxing)
2345
3.01M
                read_more |= ds->back_restarting || ds->back_resuming;
2346
29.1M
        } else {
2347
1.84M
            if (lazy_stream_needs_wait(ds)) {
2348
449
                read_more = true;
2349
1.84M
            } else {
2350
1.84M
                mark_stream_eof(ds); // let playback continue
2351
1.84M
            }
2352
1.84M
        }
2353
30.9M
        refresh_more |= ds->refreshing;
2354
30.9M
        if (ds->eager && ds->queue->last_ts != MP_NOPTS_VALUE &&
2355
19.7M
            in->min_secs > 0 && ds->base_ts != MP_NOPTS_VALUE &&
2356
17.6M
            ds->queue->last_ts >= ds->base_ts &&
2357
17.4M
            !in->back_demuxing)
2358
17.4M
        {
2359
17.4M
            if (ds->queue->last_ts - ds->base_ts <= in->hyst_secs)
2360
1.56M
                in->hyst_active = false;
2361
17.4M
            if (!in->hyst_active)
2362
17.4M
                prefetch_more |= ds->queue->last_ts - ds->base_ts < in->min_secs;
2363
17.4M
        }
2364
30.9M
    }
2365
2366
    // While interactive disc navigation is active, never read ahead. It would
2367
    // advance the disc VM past what the user is watching. Reads still happen
2368
    // whenever a selected stream demands data.
2369
24.1M
    if (in->nav_active)
2370
0
        prefetch_more = false;
2371
24.1M
    prefetch_more |= in->nav_pump;
2372
2373
24.1M
    MP_TRACE(in, "bytes=%zd, read_more=%d prefetch_more=%d, refresh_more=%d\n",
2374
24.1M
             (size_t)total_fw_bytes, read_more, prefetch_more, refresh_more);
2375
24.1M
    if (total_fw_bytes >= in->max_bytes) {
2376
        // if we hit the limit just by prefetching, simply stop prefetching
2377
104
        if (!read_more) {
2378
100
            in->hyst_active = in->hyst_secs > 0 || in->hyst_bytes > 0;
2379
100
            return false;
2380
100
        }
2381
4
        if (!in->warned_queue_overflow) {
2382
2
            in->warned_queue_overflow = true;
2383
2
            MP_WARN(in, "Too many packets in the demuxer packet queues:\n");
2384
4
            for (int n = 0; n < in->num_streams; n++) {
2385
2
                struct demux_stream *ds = in->streams[n]->ds;
2386
2
                if (ds->selected) {
2387
2
                    size_t num_pkts = 0;
2388
2
                    for (struct demux_packet *dp = ds->reader_head;
2389
2
                         dp; dp = dp->next)
2390
0
                        num_pkts++;
2391
2
                    uint64_t fw_bytes = get_forward_buffered_bytes(ds);
2392
2
                    MP_WARN(in, "  %s/%d: %zd packets, %zd bytes%s%s\n",
2393
2
                            stream_type_name(ds->type), n,
2394
2
                            num_pkts, (size_t)fw_bytes,
2395
2
                            ds->eager ? "" : " (lazy)",
2396
2
                            ds->refreshing ? " (refreshing)" : "");
2397
2
                }
2398
2
            }
2399
2
            if (in->back_demuxing)
2400
2
                MP_ERR(in, "Backward playback is likely stuck/broken now.\n");
2401
2
        }
2402
8
        for (int n = 0; n < in->num_streams; n++) {
2403
4
            struct demux_stream *ds = in->streams[n]->ds;
2404
4
            if (!ds->reader_head)
2405
4
                mark_stream_eof(ds);
2406
4
        }
2407
4
        return false;
2408
104
    }
2409
2410
24.1M
    if (!read_more && !prefetch_more && !refresh_more) {
2411
4.44M
        in->hyst_active = in->hyst_secs > 0 || in->hyst_bytes > 0;
2412
4.44M
        return false;
2413
4.44M
    }
2414
2415
19.6M
    if (in->after_seek_to_start) {
2416
12.2M
        for (int n = 0; n < in->num_streams; n++) {
2417
8.05M
            struct demux_stream *ds = in->streams[n]->ds;
2418
8.05M
            in->current_range->streams[n]->is_bof =
2419
8.05M
                ds->selected && !ds->refreshing;
2420
8.05M
        }
2421
4.18M
    }
2422
2423
    // Actually read a packet. Drop the lock while doing so, because waiting
2424
    // for disk or network I/O can take time.
2425
19.6M
    in->reading = true;
2426
19.6M
    in->nav_pump = false;
2427
19.6M
    in->after_seek = false;
2428
19.6M
    in->after_seek_to_start = false;
2429
19.6M
    mp_mutex_unlock(&in->lock);
2430
2431
19.6M
    struct demuxer *demux = in->d_thread;
2432
19.6M
    struct demux_packet *pkt = NULL;
2433
2434
19.6M
    bool eof = true;
2435
19.6M
    if (demux->desc->read_packet && !demux_read_interrupted(demux))
2436
19.6M
        eof = !demux->desc->read_packet(demux, &pkt);
2437
2438
19.6M
    mp_mutex_lock(&in->lock);
2439
19.6M
    update_cache(in);
2440
2441
19.6M
    if (pkt) {
2442
14.3M
        mp_assert(pkt->stream >= 0 && pkt->stream < in->num_streams);
2443
14.3M
        add_packet_locked(in->streams[pkt->stream], pkt);
2444
14.3M
    }
2445
2446
19.6M
    if (!in->seeking) {
2447
19.6M
        if (eof) {
2448
14.3M
            for (int n = 0; n < in->num_streams; n++)
2449
9.45M
                mark_stream_eof(in->streams[n]->ds);
2450
            // If we had EOF previously, then don't wakeup (avoids wakeup loop)
2451
4.90M
            if (!in->eof) {
2452
4.90M
                if (in->wakeup_cb)
2453
4.70M
                    in->wakeup_cb(in->wakeup_cb_ctx);
2454
4.90M
                mp_cond_signal(&in->wakeup);
2455
4.90M
                MP_VERBOSE(in, "EOF reached.\n");
2456
4.90M
            }
2457
4.90M
        }
2458
19.6M
        in->eof = eof;
2459
19.6M
        in->reading = !eof;
2460
19.6M
    }
2461
19.6M
    return true;
2462
19.6M
}
2463
2464
static void prune_old_packets(struct demux_internal *in)
2465
27.9M
{
2466
27.9M
    mp_assert(in->current_range == in->ranges[in->num_ranges - 1]);
2467
2468
    // It's not clear what the ideal way to prune old packets is. For now, we
2469
    // prune the oldest packet runs, as long as the total cache amount is too
2470
    // big.
2471
39.1M
    while (1) {
2472
39.1M
        uint64_t fw_bytes = 0;
2473
82.7M
        for (int n = 0; n < in->num_streams; n++) {
2474
43.5M
            struct demux_stream *ds = in->streams[n]->ds;
2475
43.5M
            fw_bytes += get_forward_buffered_bytes(ds);
2476
43.5M
        }
2477
39.1M
        uint64_t max_avail = in->max_bytes_bw;
2478
        // Backward cache (if enabled at all) can use unused forward cache.
2479
        // Still leave 1 byte free, so the read_packet logic doesn't get stuck.
2480
39.1M
        if (max_avail && in->max_bytes > (fw_bytes + 1) && in->d_user->opts->donate_fw)
2481
4.37M
            max_avail += in->max_bytes - (fw_bytes + 1);
2482
39.1M
        if (in->total_bytes - fw_bytes <= max_avail)
2483
27.9M
            break;
2484
2485
        // (Start from least recently used range.)
2486
11.2M
        struct demux_cached_range *range = in->ranges[0];
2487
11.2M
        double earliest_ts = MP_NOPTS_VALUE;
2488
11.2M
        struct demux_stream *earliest_stream = NULL;
2489
2490
11.8M
        for (int n = 0; n < range->num_streams; n++) {
2491
11.8M
            struct demux_queue *queue = range->streams[n];
2492
11.8M
            struct demux_stream *ds = queue->ds;
2493
2494
11.8M
            if (queue->head && queue->head != ds->reader_head) {
2495
11.2M
                struct demux_packet *dp = queue->head;
2496
11.2M
                double ts = queue->seek_start;
2497
                // If the ts is NOPTS, the queue has no retainable packets, so
2498
                // delete them all. This code is not run when there's enough
2499
                // free space, so normally the queue gets the chance to build up.
2500
11.2M
                bool prune_always =
2501
11.2M
                    !in->seekable_cache || ts == MP_NOPTS_VALUE || !dp->keyframe;
2502
11.2M
                if (prune_always || !earliest_stream || ts < earliest_ts) {
2503
11.2M
                    earliest_ts = ts;
2504
11.2M
                    earliest_stream = ds;
2505
11.2M
                    if (prune_always)
2506
11.2M
                        break;
2507
11.2M
                }
2508
11.2M
            }
2509
11.8M
        }
2510
2511
        // In some cases (like when the seek index became huge), there aren't
2512
        // any backwards packets, even if the total cache size is exceeded.
2513
11.2M
        if (!earliest_stream)
2514
787
            break;
2515
2516
11.2M
        struct demux_stream *ds = earliest_stream;
2517
11.2M
        struct demux_queue *queue = range->streams[ds->index];
2518
2519
11.2M
        bool non_kf_prune = queue->head && !queue->head->keyframe;
2520
11.2M
        bool kf_was_pruned = false;
2521
2522
22.4M
        while (queue->head && queue->head != ds->reader_head) {
2523
11.2M
            if (queue->head->keyframe) {
2524
                // If the cache is seekable, only delete until up the next
2525
                // keyframe. This is not always efficient, but ensures we
2526
                // prune all streams fairly.
2527
                // Also, if the first packet was _not_ a keyframe, we want it
2528
                // to remove all preceding non-keyframe packets first, before
2529
                // re-evaluating what to prune next.
2530
9.57M
                if ((kf_was_pruned || non_kf_prune) && in->seekable_cache)
2531
0
                    break;
2532
9.57M
                kf_was_pruned = true;
2533
9.57M
            }
2534
2535
11.2M
            remove_head_packet(queue);
2536
11.2M
        }
2537
2538
        // Need to update the seekable time range.
2539
11.2M
        if (kf_was_pruned) {
2540
9.57M
            mp_assert(!queue->keyframe_first); // it was just deleted, supposedly
2541
2542
9.57M
            queue->keyframe_first = queue->head;
2543
            // (May happen if reader_head stopped pruning the range, and there's
2544
            // no next range.)
2545
9.91M
            while (queue->keyframe_first && !queue->keyframe_first->keyframe)
2546
345k
                queue->keyframe_first = queue->keyframe_first->next;
2547
2548
9.57M
            if (queue->seek_start != MP_NOPTS_VALUE)
2549
7.09M
                queue->last_pruned = queue->seek_start;
2550
2551
9.57M
            double kf_min;
2552
9.57M
            compute_keyframe_times(queue->keyframe_first, &kf_min, NULL);
2553
2554
9.57M
            bool update_range = true;
2555
2556
9.57M
            queue->seek_start = kf_min;
2557
2558
9.57M
            if (queue->seek_start != MP_NOPTS_VALUE) {
2559
7.11M
                queue->seek_start += ds->sh->seek_preroll;
2560
2561
                // Don't need to update if the new start is still before the
2562
                // range's start (or if the range was undefined anyway).
2563
7.11M
                if (range->seek_start == MP_NOPTS_VALUE ||
2564
771
                    queue->seek_start <= range->seek_start)
2565
7.11M
                {
2566
7.11M
                    update_range = false;
2567
7.11M
                }
2568
7.11M
            }
2569
2570
9.57M
            if (update_range)
2571
2.46M
                update_seek_ranges(range);
2572
9.57M
        }
2573
2574
11.2M
        if (range != in->current_range && range->seek_start == MP_NOPTS_VALUE)
2575
1
            free_empty_cached_ranges(in);
2576
11.2M
    }
2577
27.9M
}
2578
2579
static void execute_trackswitch(struct demux_internal *in)
2580
336k
{
2581
336k
    in->tracks_switched = false;
2582
2583
336k
    mp_mutex_unlock(&in->lock);
2584
2585
336k
    if (in->d_thread->desc->switched_tracks)
2586
302k
        in->d_thread->desc->switched_tracks(in->d_thread);
2587
2588
336k
    mp_mutex_lock(&in->lock);
2589
336k
}
2590
2591
static void execute_nav_refresh(struct demux_internal *in)
2592
0
{
2593
0
    in->nav_refresh = false;
2594
2595
0
    mp_mutex_unlock(&in->lock);
2596
2597
0
    if (in->d_thread->desc->nav_refresh)
2598
0
        in->d_thread->desc->nav_refresh(in->d_thread);
2599
2600
0
    mp_mutex_lock(&in->lock);
2601
0
}
2602
2603
static void execute_seek(struct demux_internal *in)
2604
4.84M
{
2605
4.84M
    int flags = in->seek_flags;
2606
4.84M
    double pts = in->seek_pts;
2607
4.84M
    in->eof = false;
2608
4.84M
    in->seeking = false;
2609
4.84M
    in->seeking_in_progress = pts;
2610
4.84M
    in->demux_ts = MP_NOPTS_VALUE;
2611
4.84M
    in->low_level_seeks += 1;
2612
4.84M
    in->after_seek = true;
2613
4.84M
    in->after_seek_to_start =
2614
4.84M
        !(flags & (SEEK_FORWARD | SEEK_FACTOR)) &&
2615
4.83M
        pts <= in->d_thread->start_time;
2616
2617
16.7M
    for (int n = 0; n < in->num_streams; n++)
2618
11.9M
        in->streams[n]->ds->queue->last_pos_fixup = -1;
2619
2620
4.84M
    if (in->recorder)
2621
0
        mp_recorder_mark_discontinuity(in->recorder);
2622
2623
4.84M
    mp_mutex_unlock(&in->lock);
2624
2625
4.84M
    MP_VERBOSE(in, "execute seek (to %f flags %d)\n", pts, flags);
2626
2627
4.84M
    if (in->d_thread->desc->seek)
2628
4.84M
        in->d_thread->desc->seek(in->d_thread, pts, flags);
2629
2630
4.84M
    MP_VERBOSE(in, "seek done\n");
2631
2632
4.84M
    mp_mutex_lock(&in->lock);
2633
2634
4.84M
    in->seeking_in_progress = MP_NOPTS_VALUE;
2635
4.84M
}
2636
2637
static void update_opts(struct demuxer *demuxer)
2638
369k
{
2639
369k
    struct demux_opts *opts = demuxer->opts;
2640
369k
    struct demux_internal *in = demuxer->in;
2641
2642
369k
    in->min_secs = opts->min_secs;
2643
369k
    in->hyst_secs = opts->hyst_secs;
2644
369k
    in->hyst_bytes = opts->hyst_bytes;
2645
369k
    in->max_bytes = opts->max_bytes;
2646
369k
    in->max_bytes_bw = opts->max_bytes_bw;
2647
2648
369k
    int seekable = opts->seekable_cache;
2649
369k
    bool is_streaming = in->d_thread->is_streaming;
2650
369k
    bool use_cache = is_streaming;
2651
369k
    if (opts->enable_cache >= 0)
2652
1.99k
        use_cache = opts->enable_cache == 1;
2653
2654
369k
    if (use_cache) {
2655
41.2k
        in->min_secs = MPMAX(in->min_secs, opts->min_secs_cache);
2656
41.2k
        if (seekable < 0)
2657
41.2k
            seekable = 1;
2658
41.2k
    }
2659
369k
    in->seekable_cache = seekable == 1;
2660
369k
    if (in->d_thread->no_cache_seeking)
2661
0
        in->seekable_cache = false;
2662
369k
    in->using_network_cache_opts = is_streaming && use_cache;
2663
2664
369k
    if (!in->seekable_cache)
2665
328k
        in->max_bytes_bw = 0;
2666
2667
369k
    if (!in->can_cache) {
2668
80.3k
        in->seekable_cache = false;
2669
80.3k
        in->min_secs = 0;
2670
80.3k
        in->max_bytes = 1;
2671
80.3k
        in->max_bytes_bw = 0;
2672
80.3k
        in->using_network_cache_opts = false;
2673
80.3k
    }
2674
2675
369k
    if (in->seekable_cache && opts->disk_cache && !in->cache) {
2676
0
        in->cache = demux_cache_create(in->global, in->log);
2677
0
        if (!in->cache)
2678
0
            MP_ERR(in, "Failed to create file cache.\n");
2679
0
    }
2680
2681
    // The filename option really decides whether recording should be active.
2682
    // So if the filename changes, act upon it.
2683
369k
    char *old = in->record_filename ? in->record_filename : "";
2684
369k
    char *new = opts->record_file ? opts->record_file : "";
2685
369k
    if (strcmp(old, new) != 0) {
2686
2
        if (in->recorder) {
2687
0
            MP_WARN(in, "Stopping recording.\n");
2688
0
            mp_recorder_destroy(in->recorder);
2689
0
            in->recorder = NULL;
2690
0
        }
2691
2
        talloc_free(in->record_filename);
2692
2
        in->record_filename = talloc_strdup(in, opts->record_file);
2693
        // Note: actual recording only starts once packets are read. It may be
2694
        // important to delay creating in->recorder to that point, because the
2695
        // demuxer might detect more streams until finding the first packet.
2696
2
        in->enable_recording = in->can_record;
2697
2
    }
2698
2699
    // In case the cache was reduced in size.
2700
369k
    prune_old_packets(in);
2701
2702
    // In case the seekable cache was disabled.
2703
369k
    free_empty_cached_ranges(in);
2704
369k
}
2705
2706
// Make demuxing progress. Return whether progress was made.
2707
static bool thread_work(struct demux_internal *in)
2708
38.0M
{
2709
38.0M
    struct demux_opts *opts = in->d_user->opts;
2710
38.0M
    size_t old_max_bytes = opts->max_bytes;
2711
38.0M
    size_t old_max_bytes_bw = opts->max_bytes_bw;
2712
38.0M
    if (m_config_cache_update(in->d_user->opts_cache)) {
2713
824
        update_opts(in->d_user);
2714
824
        if (opts->max_bytes + opts->max_bytes_bw < old_max_bytes + old_max_bytes_bw)
2715
0
            demux_packet_pool_clear(in->packet_pool);
2716
824
    }
2717
38.0M
    if (in->tracks_switched) {
2718
285k
        execute_trackswitch(in);
2719
285k
        return true;
2720
285k
    }
2721
37.7M
    if (in->nav_refresh) {
2722
0
        execute_nav_refresh(in);
2723
0
        return true;
2724
0
    }
2725
37.7M
    if (in->need_back_seek) {
2726
1.87M
        perform_backward_seek(in);
2727
1.87M
        return true;
2728
1.87M
    }
2729
35.8M
    if (in->back_any_need_recheck) {
2730
61
        check_backward_seek(in);
2731
61
        return true;
2732
61
    }
2733
35.8M
    if (in->seeking) {
2734
4.58M
        execute_seek(in);
2735
4.58M
        return true;
2736
4.58M
    }
2737
31.3M
    if (read_packet(in))
2738
19.6M
        return true; // read_packet unlocked, so recheck conditions
2739
11.6M
    if (mp_time_ns() >= in->next_cache_update) {
2740
19
        update_cache(in);
2741
19
        return true;
2742
19
    }
2743
11.6M
    return false;
2744
11.6M
}
2745
2746
static MP_THREAD_VOID demux_thread(void *pctx)
2747
257k
{
2748
257k
    struct demux_internal *in = pctx;
2749
257k
    mp_thread_set_name("demux");
2750
257k
    mp_mutex_lock(&in->lock);
2751
2752
257k
    stats_register_thread_cputime(in->stats, "thread");
2753
2754
35.6M
    while (!in->thread_terminate) {
2755
35.4M
        if (thread_work(in))
2756
23.8M
            continue;
2757
11.6M
        mp_cond_signal(&in->wakeup);
2758
11.6M
        mp_cond_timedwait_until(&in->wakeup, &in->lock, in->next_cache_update);
2759
11.6M
    }
2760
2761
257k
    if (in->shutdown_async) {
2762
238k
        mp_mutex_unlock(&in->lock);
2763
238k
        demux_shutdown(in);
2764
238k
        mp_mutex_lock(&in->lock);
2765
238k
        in->shutdown_async = false;
2766
238k
        if (in->wakeup_cb)
2767
238k
            in->wakeup_cb(in->wakeup_cb_ctx);
2768
238k
    }
2769
2770
257k
    stats_unregister_thread(in->stats, "thread");
2771
2772
257k
    mp_mutex_unlock(&in->lock);
2773
257k
    MP_THREAD_RETURN();
2774
257k
}
2775
2776
// Low-level part of dequeueing a packet.
2777
static struct demux_packet *advance_reader_head(struct demux_stream *ds)
2778
13.3M
{
2779
13.3M
    struct demux_packet *pkt = ds->reader_head;
2780
13.3M
    if (!pkt)
2781
0
        return NULL;
2782
2783
13.3M
    ds->reader_head = pkt->next;
2784
2785
13.3M
    ds->last_ret_pos = pkt->pos;
2786
13.3M
    ds->last_ret_dts = pkt->dts;
2787
2788
13.3M
    return pkt;
2789
13.3M
}
2790
2791
// Return a newly allocated new packet. The pkt parameter may be either a
2792
// in-memory packet (then a new reference is made), or a reference to
2793
// packet in the disk cache (then the packet is read from disk).
2794
static struct demux_packet *read_packet_from_cache(struct demux_internal *in,
2795
                                                   struct demux_packet *pkt)
2796
13.3M
{
2797
13.3M
    if (!pkt)
2798
0
        return NULL;
2799
2800
13.3M
    if (pkt->is_cached) {
2801
0
        mp_assert(in->cache);
2802
0
        struct demux_packet *meta = pkt;
2803
0
        pkt = demux_cache_read(in->cache, pkt->cached_data.pos);
2804
0
        if (pkt) {
2805
0
            demux_packet_copy_attribs(pkt, meta);
2806
0
        } else {
2807
0
            MP_ERR(in, "Failed to retrieve packet from cache.\n");
2808
0
        }
2809
13.3M
    } else {
2810
        // The returned packet is mutated etc. and will be owned by the user.
2811
13.3M
        pkt = demux_copy_packet(in->packet_pool, pkt);
2812
13.3M
    }
2813
2814
13.3M
    return pkt;
2815
13.3M
}
2816
2817
// Returns:
2818
//   < 0: EOF was reached, *res is not set
2819
//  == 0: no new packet yet, wait, *res is not set
2820
//   > 0: new packet is moved to *res
2821
static int dequeue_packet(struct demux_stream *ds, double min_pts,
2822
                          struct demux_packet **res)
2823
26.0M
{
2824
26.0M
    struct demux_internal *in = ds->in;
2825
2826
26.0M
    if (!ds->selected)
2827
36.4k
        return -1;
2828
25.9M
    if (in->blocked)
2829
0
        return 0;
2830
2831
25.9M
    if (ds->sh->attached_picture) {
2832
482
        ds->eof = true;
2833
482
        if (ds->attached_picture_added)
2834
189
            return -1;
2835
293
        ds->attached_picture_added = true;
2836
293
        struct demux_packet *pkt = demux_copy_packet(in->packet_pool,
2837
293
                                                     ds->sh->attached_picture);
2838
293
        MP_HANDLE_OOM(pkt);
2839
293
        pkt->stream = ds->sh->index;
2840
293
        *res = pkt;
2841
293
        return 1;
2842
293
    }
2843
2844
25.9M
    if (!in->reading && !in->eof) {
2845
7.55M
        in->reading = true; // enable demuxer thread prefetching
2846
7.55M
        mp_cond_signal(&in->wakeup);
2847
7.55M
    }
2848
2849
25.9M
    ds->force_read_until = min_pts;
2850
2851
25.9M
    if (ds->back_resuming || ds->back_restarting) {
2852
544k
        mp_assert(in->back_demuxing);
2853
544k
        return 0;
2854
544k
    }
2855
2856
25.9M
    bool eof = !ds->reader_head && ds->eof;
2857
2858
25.4M
    if (in->back_demuxing) {
2859
        // Subtitles not supported => EOF.
2860
55.5k
        if (!ds->eager)
2861
0
            return -1;
2862
2863
        // Next keyframe (or EOF) was reached => step back.
2864
55.5k
        if (ds->back_range_started && !ds->back_range_count &&
2865
6.32k
            ((ds->reader_head && ds->reader_head->keyframe) || eof))
2866
6.32k
        {
2867
6.32k
            ds->back_restarting = true;
2868
6.32k
            ds->back_restart_eof = false;
2869
6.32k
            ds->back_restart_next = false;
2870
2871
6.32k
            find_backward_restart_pos(ds);
2872
2873
6.32k
            if (ds->back_restarting)
2874
6.32k
                return 0;
2875
6.32k
        }
2876
2877
49.2k
        eof = ds->back_range_count < 0;
2878
49.2k
    }
2879
2880
25.4M
    ds->need_wakeup = !ds->reader_head;
2881
25.4M
    if (!ds->reader_head || eof) {
2882
12.0M
        if (!ds->eager) {
2883
            // Non-eager streams temporarily return EOF. If they returned 0,
2884
            // the reader would have to wait for new packets, which does not
2885
            // make sense due to the sparseness and passiveness of non-eager
2886
            // streams.
2887
            // Unless the min_pts feature is used: then EOF is only signaled
2888
            // if read-ahead went above min_pts.
2889
37.7k
            if (!lazy_stream_needs_wait(ds))
2890
37.7k
                ds->eof = eof = true;
2891
37.7k
        }
2892
        // Non-eager streams and streams starved by a queue overflow get EOF
2893
        // while the demuxer can still read. Backward demuxing signals BOF
2894
        // this way, which is final.
2895
12.0M
        if (eof)
2896
6.27M
            ds->lazy_eof = !in->eof && !in->back_demuxing;
2897
12.0M
        return eof ? -1 : 0;
2898
12.0M
    }
2899
2900
13.3M
    struct demux_packet *pkt = advance_reader_head(ds);
2901
13.3M
    mp_assert(pkt);
2902
13.3M
    pkt = read_packet_from_cache(in, pkt);
2903
13.3M
    if (!pkt)
2904
0
        return 0;
2905
13.3M
    ds->lazy_eof = false;
2906
2907
13.3M
    if (in->back_demuxing) {
2908
6.32k
        if (pkt->keyframe) {
2909
6.32k
            mp_assert(ds->back_range_count > 0);
2910
6.32k
            ds->back_range_count -= 1;
2911
6.32k
            if (ds->back_range_preroll >= 0)
2912
6.32k
                ds->back_range_preroll -= 1;
2913
6.32k
        }
2914
2915
6.32k
        if (ds->back_range_preroll >= 0)
2916
0
            pkt->back_preroll = true;
2917
2918
6.32k
        if (!ds->back_range_started) {
2919
6.32k
            pkt->back_restart = true;
2920
6.32k
            ds->back_range_started = true;
2921
6.32k
        }
2922
6.32k
    }
2923
2924
13.3M
    double ts = MP_PTS_OR_DEF(pkt->dts, pkt->pts);
2925
13.3M
    if (ts != MP_NOPTS_VALUE)
2926
12.8M
        ds->base_ts = ts;
2927
2928
13.3M
    if (pkt->keyframe && ts != MP_NOPTS_VALUE) {
2929
        // Update bitrate - only at keyframe points, because we use the
2930
        // (possibly) reordered packet timestamps instead of realtime.
2931
11.5M
        double d = ts - ds->last_br_ts;
2932
11.5M
        if (ds->last_br_ts == MP_NOPTS_VALUE || d < 0) {
2933
343k
            ds->bitrate = -1;
2934
343k
            ds->last_br_ts = ts;
2935
343k
            ds->last_br_bytes = 0;
2936
11.2M
        } else if (d >= 0.5) { // a window of least 500ms for UI purposes
2937
1.01M
            ds->bitrate = ds->last_br_bytes / d;
2938
1.01M
            ds->last_br_ts = ts;
2939
1.01M
            ds->last_br_bytes = 0;
2940
1.01M
        }
2941
11.5M
    }
2942
13.3M
    ds->last_br_bytes += pkt->len;
2943
2944
    // This implies this function is actually called from "the" user thread.
2945
13.3M
    if (pkt->pos >= in->d_user->filepos)
2946
12.2M
        in->d_user->filepos = pkt->pos;
2947
13.3M
    in->d_user->filesize = in->stream_size;
2948
2949
13.3M
    pkt->pts = MP_ADD_PTS(pkt->pts, in->ts_offset);
2950
13.3M
    pkt->dts = MP_ADD_PTS(pkt->dts, in->ts_offset);
2951
2952
13.3M
    if (pkt->segmented) {
2953
1.81M
        pkt->start = MP_ADD_PTS(pkt->start, in->ts_offset);
2954
1.81M
        pkt->end = MP_ADD_PTS(pkt->end, in->ts_offset);
2955
1.81M
    }
2956
2957
13.3M
    prune_old_packets(in);
2958
13.3M
    *res = pkt;
2959
13.3M
    return 1;
2960
13.3M
}
2961
2962
// Poll the demuxer queue, and if there's a packet, return it. Otherwise, just
2963
// make the demuxer thread read packets for this stream, and if there's at
2964
// least one packet, call the wakeup callback.
2965
// This enables readahead if it wasn't yet (except for interleaved subtitles).
2966
// Returns:
2967
//   < 0: EOF was reached, *out_pkt=NULL
2968
//  == 0: no new packet yet, but maybe later, *out_pkt=NULL
2969
//   > 0: new packet read, *out_pkt is set
2970
// Note: when reading interleaved subtitles, the demuxer won't try to forcibly
2971
// read ahead to get the next subtitle packet (as the next packet could be
2972
// minutes away). In this situation, this function will just return -1.
2973
int demux_read_packet_async(struct sh_stream *sh, struct demux_packet **out_pkt)
2974
19.9M
{
2975
19.9M
    return demux_read_packet_async_until(sh, MP_NOPTS_VALUE, out_pkt);
2976
19.9M
}
2977
2978
// Like demux_read_packet_async(). They are the same for min_pts==MP_NOPTS_VALUE.
2979
// If min_pts is set, and the stream is lazily read (eager=false, interleaved
2980
// subtitles), then return 0 until demuxing has reached min_pts, or the queue
2981
// overflowed, or EOF was reached, or a packet was read for this stream.
2982
int demux_read_packet_async_until(struct sh_stream *sh, double min_pts,
2983
                                  struct demux_packet **out_pkt)
2984
21.2M
{
2985
21.2M
    struct demux_stream *ds = sh ? sh->ds : NULL;
2986
21.2M
    *out_pkt = NULL;
2987
21.2M
    if (!ds)
2988
0
        return -1;
2989
21.2M
    struct demux_internal *in = ds->in;
2990
2991
21.2M
    mp_mutex_lock(&in->lock);
2992
21.2M
    int r = -1;
2993
21.7M
    while (1) {
2994
21.7M
        r = dequeue_packet(ds, min_pts, out_pkt);
2995
21.7M
        if (in->threading || in->blocked || r != 0)
2996
21.2M
            break;
2997
        // Needs to actually read packets until we got a packet or EOF.
2998
479k
        thread_work(in);
2999
479k
    }
3000
21.2M
    mp_mutex_unlock(&in->lock);
3001
21.2M
    return r;
3002
21.2M
}
3003
3004
// Read and return any packet we find. NULL means EOF. With new_streams set,
3005
// return without a packet once the demuxer added streams, and set
3006
// *new_streams. Does not work with threading (don't call demux_start_thread()).
3007
struct demux_packet *demux_read_any_packet(struct demuxer *demuxer,
3008
                                           bool *new_streams)
3009
2.02M
{
3010
2.02M
    struct demux_internal *in = demuxer->in;
3011
2.02M
    mp_mutex_lock(&in->lock);
3012
2.02M
    mp_assert(!in->threading); // doesn't work with threading
3013
2.02M
    struct demux_packet *out_pkt = NULL;
3014
2.02M
    int num_streams = in->num_streams;
3015
2.02M
    bool read_more = true;
3016
4.16M
    while (read_more && !in->blocked) {
3017
4.13M
        bool all_eof = true;
3018
6.38M
        for (int n = 0; n < in->num_streams; n++) {
3019
4.24M
            int r = dequeue_packet(in->streams[n]->ds, MP_NOPTS_VALUE, &out_pkt);
3020
4.24M
            if (r > 0)
3021
1.99M
                goto done;
3022
2.25M
            if (r == 0)
3023
2.18M
                all_eof = false;
3024
2.25M
        }
3025
        // retry after calling this
3026
2.14M
        read_more = thread_work(in);
3027
2.14M
        read_more &= !all_eof;
3028
2.14M
        if (new_streams && in->num_streams > num_streams) {
3029
0
            *new_streams = true;
3030
0
            break;
3031
0
        }
3032
2.14M
    }
3033
2.02M
done:
3034
2.02M
    mp_mutex_unlock(&in->lock);
3035
2.02M
    return out_pkt;
3036
2.02M
}
3037
3038
int demuxer_help(struct mp_log *log, const m_option_t *opt, struct bstr name)
3039
1.22k
{
3040
1.22k
    int i;
3041
3042
1.22k
    mp_info(log, "Available demuxers:\n");
3043
1.22k
    mp_info(log, " demuxer:   info:\n");
3044
15.9k
    for (i = 0; demuxer_list[i]; i++) {
3045
14.7k
        mp_info(log, "%10s  %s\n",
3046
14.7k
                demuxer_list[i]->name, demuxer_list[i]->desc);
3047
14.7k
    }
3048
1.22k
    mp_info(log, "\n");
3049
3050
1.22k
    return M_OPT_EXIT;
3051
1.22k
}
3052
3053
static const char *d_level(enum demux_check level)
3054
3.61M
{
3055
3.61M
    switch (level) {
3056
33.0k
    case DEMUX_CHECK_FORCE:  return "force";
3057
879k
    case DEMUX_CHECK_UNSAFE: return "unsafe";
3058
321k
    case DEMUX_CHECK_REQUEST:return "request";
3059
2.38M
    case DEMUX_CHECK_NORMAL: return "normal";
3060
3.61M
    }
3061
0
    MP_ASSERT_UNREACHABLE();
3062
0
}
3063
3064
static int decode_float(char *str, float *out)
3065
0
{
3066
0
    char *rest;
3067
0
    float dec_val;
3068
3069
0
    dec_val = strtod(str, &rest);
3070
0
    if (rest == str || !isfinite(dec_val))
3071
0
        return -1;
3072
3073
0
    *out = dec_val;
3074
0
    return 0;
3075
0
}
3076
3077
static int decode_gain(struct mp_log *log, struct mp_tags *tags,
3078
                       const char *tag, float *out)
3079
3.88M
{
3080
3.88M
    char *tag_val = NULL;
3081
3.88M
    float dec_val;
3082
3083
3.88M
    tag_val = mp_tags_get_str(tags, tag);
3084
3.88M
    if (!tag_val)
3085
3.88M
        return -1;
3086
3087
0
    if (decode_float(tag_val, &dec_val) < 0) {
3088
0
        mp_msg(log, MSGL_ERR, "Invalid replaygain value\n");
3089
0
        return -1;
3090
0
    }
3091
3092
0
    *out = dec_val;
3093
0
    return 0;
3094
0
}
3095
3096
static int decode_peak(struct mp_log *log, struct mp_tags *tags,
3097
                       const char *tag, float *out)
3098
0
{
3099
0
    char *tag_val = NULL;
3100
0
    float dec_val;
3101
3102
0
    *out = 1.0;
3103
3104
0
    tag_val = mp_tags_get_str(tags, tag);
3105
0
    if (!tag_val)
3106
0
        return 0;
3107
3108
0
    if (decode_float(tag_val, &dec_val) < 0 || dec_val <= 0.0)
3109
0
        return -1;
3110
3111
0
    *out = dec_val;
3112
0
    return 0;
3113
0
}
3114
3115
static struct replaygain_data *decode_rgain(struct mp_log *log,
3116
                                            struct mp_tags *tags)
3117
1.29M
{
3118
1.29M
    struct replaygain_data rg = {0};
3119
3120
    // Set values in *rg, using track gain as a fallback for album gain if the
3121
    // latter is not present. This behavior matches that in demux/demux_lavf.c's
3122
    // export_replaygain; if you change this, please make equivalent changes
3123
    // there too.
3124
1.29M
    if (decode_gain(log, tags, "REPLAYGAIN_TRACK_GAIN", &rg.track_gain) >= 0 &&
3125
0
        decode_peak(log, tags, "REPLAYGAIN_TRACK_PEAK", &rg.track_peak) >= 0)
3126
0
    {
3127
0
        if (decode_gain(log, tags, "REPLAYGAIN_ALBUM_GAIN", &rg.album_gain) < 0 ||
3128
0
            decode_peak(log, tags, "REPLAYGAIN_ALBUM_PEAK", &rg.album_peak) < 0)
3129
0
        {
3130
            // Album gain is undefined; fall back to track gain.
3131
0
            rg.album_gain = rg.track_gain;
3132
0
            rg.album_peak = rg.track_peak;
3133
0
        }
3134
0
        return talloc_dup(NULL, &rg);
3135
0
    }
3136
3137
1.29M
    if (decode_gain(log, tags, "REPLAYGAIN_GAIN", &rg.track_gain) >= 0 &&
3138
0
        decode_peak(log, tags, "REPLAYGAIN_PEAK", &rg.track_peak) >= 0)
3139
0
    {
3140
0
        rg.album_gain = rg.track_gain;
3141
0
        rg.album_peak = rg.track_peak;
3142
0
        return talloc_dup(NULL, &rg);
3143
0
    }
3144
3145
    // The r128 replaygain tags declared in RFC 7845 for opus files. The tags
3146
    // are generated with EBU-R128, which does not use peak meters. And the
3147
    // values are stored as a Q7.8 fixed point number in dB.
3148
1.29M
    if (decode_gain(log, tags, "R128_TRACK_GAIN", &rg.track_gain) >= 0) {
3149
0
        if (decode_gain(log, tags, "R128_ALBUM_GAIN", &rg.album_gain) < 0) {
3150
            // Album gain is undefined; fall back to track gain.
3151
0
            rg.album_gain = rg.track_gain;
3152
0
        }
3153
0
        rg.track_gain /= 256.;
3154
0
        rg.album_gain /= 256.;
3155
3156
        // Add 5dB to compensate for the different reference levels between
3157
        // our reference of ReplayGain 2 (-18 LUFS) and EBU R128 (-23 LUFS).
3158
0
        rg.track_gain += 5.;
3159
0
        rg.album_gain += 5.;
3160
0
        return talloc_dup(NULL, &rg);
3161
0
    }
3162
3163
1.29M
    return NULL;
3164
1.29M
}
3165
3166
static void demux_update_replaygain(demuxer_t *demuxer)
3167
958k
{
3168
958k
    struct demux_internal *in = demuxer->in;
3169
2.37M
    for (int n = 0; n < in->num_streams; n++) {
3170
1.41M
        struct sh_stream *sh = in->streams[n];
3171
1.41M
        if (sh->type == STREAM_AUDIO && !sh->codec->replaygain_data) {
3172
648k
            struct replaygain_data *rg = decode_rgain(demuxer->log, sh->tags);
3173
648k
            if (!rg)
3174
648k
                rg = decode_rgain(demuxer->log, demuxer->metadata);
3175
648k
            if (rg)
3176
0
                sh->codec->replaygain_data = talloc_steal(sh->codec, rg);
3177
648k
        }
3178
1.41M
    }
3179
958k
}
3180
3181
// Copy some fields from src to dst (for initialization).
3182
static void demux_copy(struct demuxer *dst, struct demuxer *src)
3183
369k
{
3184
    // Note that we do as shallow copies as possible. We expect the data
3185
    // that is not-copied (only referenced) to be immutable.
3186
    // This implies e.g. that no chapters are added after initialization.
3187
369k
    dst->chapters = src->chapters;
3188
369k
    dst->num_chapters = src->num_chapters;
3189
369k
    dst->editions = src->editions;
3190
369k
    dst->num_editions = src->num_editions;
3191
369k
    dst->edition = src->edition;
3192
369k
    dst->edition_is_track_mapping = src->edition_is_track_mapping;
3193
369k
    dst->attachments = src->attachments;
3194
369k
    dst->num_attachments = src->num_attachments;
3195
369k
    dst->matroska_data = src->matroska_data;
3196
369k
    dst->playlist = src->playlist;
3197
369k
    dst->seekable = src->seekable;
3198
369k
    dst->partially_seekable = src->partially_seekable;
3199
369k
    dst->filetype = src->filetype;
3200
369k
    dst->ts_resets_possible = src->ts_resets_possible;
3201
369k
    dst->fully_read = src->fully_read;
3202
369k
    dst->start_time = src->start_time;
3203
369k
    dst->duration = src->duration;
3204
369k
    dst->is_network = src->is_network;
3205
369k
    dst->is_streaming = src->is_streaming;
3206
369k
    dst->stream_origin = src->stream_origin;
3207
369k
    dst->priv = src->priv;
3208
369k
    dst->metadata = mp_tags_dup(dst, src->metadata);
3209
369k
}
3210
3211
// Update metadata after initialization. If sh==NULL, it's global metadata,
3212
// otherwise it's bound to the stream. If pts==NOPTS, use the highest known pts
3213
// in the stream. Caller retains ownership of tags ptr. Called locked.
3214
static void add_timed_metadata(struct demux_internal *in, struct mp_tags *tags,
3215
                               struct sh_stream *sh, double pts)
3216
191
{
3217
191
    struct demux_cached_range *r = in->current_range;
3218
191
    if (!r)
3219
0
        return;
3220
3221
    // We don't expect this, nor do we find it useful.
3222
191
    if (sh && sh != in->metadata_stream)
3223
0
        return;
3224
3225
191
    if (pts == MP_NOPTS_VALUE) {
3226
838
        for (int n = 0; n < r->num_streams; n++)
3227
680
            pts = MP_PTS_MAX(pts, r->streams[n]->last_ts);
3228
3229
        // Tends to happen when doing the initial icy update.
3230
158
        if (pts == MP_NOPTS_VALUE)
3231
57
            pts = in->d_thread->start_time;
3232
158
    }
3233
3234
191
    struct timed_metadata *tm = talloc_zero(NULL, struct timed_metadata);
3235
191
    *tm = (struct timed_metadata){
3236
191
        .pts = pts,
3237
191
        .tags = mp_tags_dup(tm, tags),
3238
191
        .from_stream = !!sh,
3239
191
    };
3240
191
    MP_TARRAY_APPEND(r, r->metadata, r->num_metadata, tm);
3241
191
}
3242
3243
// This is called by demuxer implementations if sh->tags changed. Note that
3244
// sh->tags itself is never actually changed (it's immutable, because sh->tags
3245
// can be accessed by the playback thread, and there is no synchronization).
3246
// pts is the time at/after which the metadata becomes effective. You're
3247
// supposed to call this ordered by time, and only while a packet is being
3248
// read.
3249
// Ownership of tags goes to the function.
3250
void demux_stream_tags_changed(struct demuxer *demuxer, struct sh_stream *sh,
3251
                               struct mp_tags *tags, double pts)
3252
33
{
3253
33
    struct demux_internal *in = demuxer->in;
3254
33
    mp_assert(demuxer == in->d_thread);
3255
33
    struct demux_stream *ds = sh ? sh->ds : NULL;
3256
33
    mp_assert(!sh || ds); // stream must have been added
3257
3258
33
    mp_mutex_lock(&in->lock);
3259
3260
33
    if (pts == MP_NOPTS_VALUE) {
3261
0
        MP_WARN(in, "Discarding timed metadata without timestamp.\n");
3262
33
    } else {
3263
33
        add_timed_metadata(in, tags, sh, pts);
3264
33
    }
3265
33
    talloc_free(tags);
3266
3267
33
    mp_mutex_unlock(&in->lock);
3268
33
}
3269
3270
// This is called by demuxer implementations if demuxer->metadata changed.
3271
// (It will be propagated to the user as timed metadata.)
3272
void demux_metadata_changed(demuxer_t *demuxer)
3273
158
{
3274
158
    mp_assert(demuxer == demuxer->in->d_thread); // call from demuxer impl. only
3275
158
    struct demux_internal *in = demuxer->in;
3276
3277
158
    mp_mutex_lock(&in->lock);
3278
158
    add_timed_metadata(in, demuxer->metadata, NULL, MP_NOPTS_VALUE);
3279
158
    mp_mutex_unlock(&in->lock);
3280
158
}
3281
3282
// Updates the duration should it need to be changed. Used for demuxers that
3283
// changes titles/playlists at runtime.
3284
void demux_set_duration(demuxer_t *demuxer, double duration)
3285
0
{
3286
0
    mp_assert(demuxer == demuxer->in->d_thread);
3287
0
    struct demux_internal *in = demuxer->in;
3288
3289
0
    mp_mutex_lock(&in->lock);
3290
0
    in->duration = duration;
3291
0
    in->d_thread->duration = duration;
3292
0
    in->highest_av_pts = MP_NOPTS_VALUE;
3293
0
    in->events |= DEMUX_EVENT_DURATION;
3294
0
    mp_mutex_unlock(&in->lock);
3295
0
}
3296
3297
// Tell the cache whether interactive disc navigation is active.
3298
void demux_set_nav_active(demuxer_t *demuxer, bool active)
3299
0
{
3300
0
    struct demux_internal *in = demuxer->in;
3301
0
    mp_assert(demuxer == in->d_thread);
3302
3303
0
    mp_mutex_lock(&in->lock);
3304
0
    if (in->nav_active != active) {
3305
0
        in->nav_active = active;
3306
0
        mp_cond_signal(&in->wakeup);
3307
0
    }
3308
0
    mp_mutex_unlock(&in->lock);
3309
0
}
3310
3311
// Updates the chapters/editions should it need to be changed. Used for demuxers
3312
// that changes titles/playlists at runtime.
3313
void demux_lists_changed(demuxer_t *demuxer)
3314
0
{
3315
0
    mp_assert(demuxer == demuxer->in->d_thread);
3316
0
    struct demux_internal *in = demuxer->in;
3317
3318
0
    mp_mutex_lock(&in->lock);
3319
0
    in->lists_changed = true;
3320
0
    in->staged_chapters = in->d_thread->chapters;
3321
0
    in->num_staged_chapters = in->d_thread->num_chapters;
3322
0
    in->staged_editions = in->d_thread->editions;
3323
0
    in->num_staged_editions = in->d_thread->num_editions;
3324
0
    in->staged_edition = in->d_thread->edition;
3325
0
    in->events |= DEMUX_EVENT_LISTS;
3326
0
    mp_mutex_unlock(&in->lock);
3327
0
}
3328
3329
// Called locked, with user demuxer.
3330
static void update_final_metadata(demuxer_t *demuxer, struct timed_metadata *tm)
3331
728k
{
3332
728k
    mp_assert(demuxer == demuxer->in->d_user);
3333
728k
    struct demux_internal *in = demuxer->in;
3334
3335
728k
    struct mp_tags *dyn_tags = NULL;
3336
3337
    // Often useful for audio-only files, which have metadata in the audio track
3338
    // metadata instead of the main metadata, but can also have cover art
3339
    // metadata (which libavformat likes to treat as video streams).
3340
728k
    int astreams = 0;
3341
728k
    int astream_id = -1;
3342
728k
    int vstreams = 0;
3343
1.85M
    for (int n = 0; n < in->num_streams; n++) {
3344
1.12M
        struct sh_stream *sh = in->streams[n];
3345
1.12M
        if (sh->type == STREAM_VIDEO && !sh->attached_picture)
3346
558k
            vstreams += 1;
3347
1.12M
        if (sh->type == STREAM_AUDIO) {
3348
536k
            astreams += 1;
3349
536k
            astream_id = n;
3350
536k
        }
3351
1.12M
    }
3352
3353
    // Use the metadata_stream tags only if this really seems to be an audio-
3354
    // only stream. Otherwise it will happen too often that "uninteresting"
3355
    // stream metadata will trash the actual file tags.
3356
728k
    if (vstreams == 0 && astreams == 1 &&
3357
83.2k
        in->streams[astream_id] == in->metadata_stream)
3358
83.2k
    {
3359
83.2k
        dyn_tags = in->metadata_stream->tags;
3360
83.2k
        if (tm && tm->from_stream)
3361
0
            dyn_tags = tm->tags;
3362
83.2k
    }
3363
3364
    // Global metadata updates.
3365
728k
    if (tm && !tm->from_stream)
3366
0
        dyn_tags = tm->tags;
3367
3368
728k
    if (dyn_tags)
3369
83.2k
        mp_tags_merge(demuxer->metadata, dyn_tags);
3370
728k
}
3371
3372
static struct timed_metadata *lookup_timed_metadata(struct demux_internal *in,
3373
                                                    double pts)
3374
29.0M
{
3375
29.0M
    struct demux_cached_range *r = in->current_range;
3376
3377
29.0M
    if (!r || !r->num_metadata || pts == MP_NOPTS_VALUE)
3378
29.0M
        return NULL;
3379
3380
2.18k
    int start = 1;
3381
2.18k
    int i = in->cached_metadata_index;
3382
2.18k
    if (i >= 0 &&  i < r->num_metadata && r->metadata[i]->pts <= pts)
3383
2.01k
        start = i + 1;
3384
3385
2.18k
    in->cached_metadata_index = r->num_metadata - 1;
3386
2.26k
    for (int n = start; n < r->num_metadata; n++) {
3387
92
        if (r->metadata[n]->pts >= pts) {
3388
6
            in->cached_metadata_index = n - 1;
3389
6
            break;
3390
6
        }
3391
92
    }
3392
3393
2.18k
    return r->metadata[in->cached_metadata_index];
3394
29.0M
}
3395
3396
// Called by the user thread (i.e. player) to update metadata and other things
3397
// from the demuxer thread.
3398
// The pts parameter is the current playback position.
3399
void demux_update(demuxer_t *demuxer, double pts)
3400
14.5M
{
3401
14.5M
    mp_assert(demuxer == demuxer->in->d_user);
3402
14.5M
    struct demux_internal *in = demuxer->in;
3403
3404
14.5M
    mp_mutex_lock(&in->lock);
3405
3406
14.5M
    if (!in->threading)
3407
384k
        update_cache(in);
3408
3409
    // This implies this function is actually called from "the" user thread.
3410
14.5M
    in->d_user->filesize = in->stream_size;
3411
3412
14.5M
    pts = MP_ADD_PTS(pts, -in->ts_offset);
3413
3414
14.5M
    struct timed_metadata *prev = lookup_timed_metadata(in, in->last_playback_pts);
3415
14.5M
    struct timed_metadata *cur = lookup_timed_metadata(in, pts);
3416
14.5M
    if (prev != cur || in->force_metadata_update) {
3417
728k
        in->force_metadata_update = false;
3418
728k
        update_final_metadata(demuxer, cur);
3419
728k
        demuxer->events |= DEMUX_EVENT_METADATA;
3420
728k
    }
3421
3422
14.5M
    in->last_playback_pts = pts;
3423
3424
14.5M
    demuxer->events |= in->events;
3425
14.5M
    in->events = 0;
3426
14.5M
    if (in->lists_changed) {
3427
0
        in->lists_changed = false;
3428
0
        demuxer->chapters = in->staged_chapters;
3429
0
        demuxer->num_chapters = in->num_staged_chapters;
3430
0
        demuxer->editions = in->staged_editions;
3431
0
        demuxer->num_editions = in->num_staged_editions;
3432
0
        demuxer->edition = in->staged_edition;
3433
0
    }
3434
40.8M
    for (int n = 0; n < in->num_streams; n++) {
3435
26.3M
        struct demux_stream *ds = in->streams[n]->ds;
3436
26.3M
        if (ds->staged_codec) {
3437
0
            in->streams[n]->codec = ds->staged_codec;
3438
0
            ds->staged_codec = NULL;
3439
0
        }
3440
26.3M
    }
3441
14.5M
    if (demuxer->events & (DEMUX_EVENT_METADATA | DEMUX_EVENT_STREAMS | DEMUX_EVENT_CODEC))
3442
958k
        demux_update_replaygain(demuxer);
3443
14.5M
    if (demuxer->events & DEMUX_EVENT_DURATION)
3444
851k
        demuxer->duration = in->duration;
3445
3446
14.5M
    mp_mutex_unlock(&in->lock);
3447
14.5M
}
3448
3449
static void demux_init_cuesheet(struct demuxer *demuxer)
3450
369k
{
3451
369k
    if (demuxer->num_chapters)
3452
31.0k
        return;
3453
3454
338k
    struct sh_stream *sh = demuxer->in->metadata_stream;
3455
338k
    char *cue = mp_tags_get_str(demuxer->metadata, "cuesheet");
3456
338k
    if (!cue && sh)
3457
277k
        cue = mp_tags_get_str(sh->tags, "cuesheet");
3458
338k
    if (!cue)
3459
338k
        return;
3460
3461
2
    struct cue_file *f = mp_parse_cue(bstr0(cue));
3462
2
    if (f) {
3463
2
        if (mp_check_embedded_cue(f) < 0) {
3464
2
            MP_WARN(demuxer, "Embedded cue sheet references zero or multiple files. "
3465
2
                    "Ignoring it.\n");
3466
2
        } else {
3467
0
            for (int n = 0; n < f->num_tracks; n++) {
3468
0
                struct cue_track *t = &f->tracks[n];
3469
0
                int idx = demuxer_add_chapter(demuxer, "", t->start, -1);
3470
0
                mp_tags_merge(demuxer->chapters[idx].metadata, t->tags);
3471
0
            }
3472
0
        }
3473
2
        talloc_free(f);
3474
2
    }
3475
2
}
3476
3477
// A demuxer can use this during opening if all data was read from the stream.
3478
// Calling this after opening was completed is not allowed. Also, if opening
3479
// failed, this must not be called (or trying another demuxer would fail).
3480
// Useful so that e.g. subtitles don't keep the file or socket open.
3481
// If there's ever the situation where we can't allow the demuxer to close
3482
// the stream, this function could ignore the request.
3483
void demux_close_stream(struct demuxer *demuxer)
3484
29.8k
{
3485
29.8k
    struct demux_internal *in = demuxer->in;
3486
29.8k
    mp_assert(!in->threading && demuxer == in->d_thread);
3487
3488
29.8k
    if (!demuxer->stream || !in->owns_stream)
3489
0
        return;
3490
3491
29.8k
    MP_VERBOSE(demuxer, "demuxer read all data; closing stream\n");
3492
29.8k
    free_stream(demuxer->stream);
3493
29.8k
    demuxer->stream = NULL;
3494
29.8k
    in->d_user->stream = NULL;
3495
29.8k
}
3496
3497
static void demux_init_ccs(struct demuxer *demuxer, struct demux_opts *opts)
3498
369k
{
3499
369k
    struct demux_internal *in = demuxer->in;
3500
369k
    if (!opts->create_ccs)
3501
369k
        return;
3502
112
    mp_mutex_lock(&in->lock);
3503
280
    for (int n = 0; n < in->num_streams; n++) {
3504
168
        struct sh_stream *sh = in->streams[n];
3505
168
        if (sh->type == STREAM_VIDEO && !sh->attached_picture)
3506
56
            demuxer_get_cc_track_locked(sh);
3507
168
    }
3508
112
    mp_mutex_unlock(&in->lock);
3509
112
}
3510
3511
// Return whether "heavy" caching on this stream is enabled. By default, this
3512
// corresponds to whether the source stream is considered in the network. The
3513
// only effect should be adjusting display behavior (of cache stats etc.), and
3514
// possibly switching between which set of options influence cache settings.
3515
bool demux_is_network_cached(demuxer_t *demuxer)
3516
10.9k
{
3517
10.9k
    struct demux_internal *in = demuxer->in;
3518
10.9k
    mp_mutex_lock(&in->lock);
3519
10.9k
    bool r = in->using_network_cache_opts;
3520
10.9k
    mp_mutex_unlock(&in->lock);
3521
10.9k
    return r;
3522
10.9k
}
3523
3524
struct parent_stream_info {
3525
    bool seekable;
3526
    bool is_network;
3527
    bool is_streaming;
3528
    int stream_origin;
3529
    struct mp_cancel *cancel;
3530
    char *filename;
3531
    char *server_filename;
3532
};
3533
3534
static struct demuxer *open_given_type(struct mpv_global *global,
3535
                                       struct mp_log *log,
3536
                                       const struct demuxer_desc *desc,
3537
                                       struct stream *stream,
3538
                                       struct parent_stream_info *sinfo,
3539
                                       struct demuxer_params *params,
3540
                                       enum demux_check check)
3541
3.15M
{
3542
3.15M
    if (mp_cancel_test(sinfo->cancel))
3543
3.32k
        return NULL;
3544
3545
3.15M
    if (params->depth > 10) {
3546
106
        mp_err(log, "Demuxer recursion depth exceeded.\n");
3547
106
        return NULL;
3548
106
    }
3549
3550
3.15M
    mp_dbg(log, "Trying demuxer: %s (force-level: %s)\n",
3551
3.15M
           desc->name, d_level(check));
3552
3553
3.15M
    if (stream && !stream_seek(stream, 0)) {
3554
487
        mp_err(log, "Failed to rewind stream to the start.\n");
3555
487
        return NULL;
3556
487
    }
3557
3558
3.15M
    struct demuxer *demuxer = talloc_ptrtype(NULL, demuxer);
3559
3.15M
    struct m_config_cache *opts_cache =
3560
3.15M
        m_config_cache_alloc(demuxer, global, &demux_conf);
3561
3.15M
    struct demux_opts *opts = opts_cache->opts;
3562
3.15M
    *demuxer = (struct demuxer) {
3563
3.15M
        .desc = desc,
3564
3.15M
        .stream = stream,
3565
3.15M
        .cancel = sinfo->cancel,
3566
3.15M
        .seekable = sinfo->seekable,
3567
3.15M
        .filepos = -1,
3568
3.15M
        .global = global,
3569
3.15M
        .log = mp_log_new(demuxer, log, desc->name),
3570
3.15M
        .packet_pool = demux_packet_pool_get(global),
3571
3.15M
        .glog = log,
3572
3.15M
        .filename = talloc_strdup(demuxer, sinfo->filename),
3573
3.15M
        .server_filename = talloc_strdup(demuxer, sinfo->server_filename),
3574
3.15M
        .is_network = sinfo->is_network,
3575
3.15M
        .is_streaming = sinfo->is_streaming,
3576
3.15M
        .stream_origin = sinfo->stream_origin,
3577
3.15M
        .access_references = opts->access_references,
3578
3.15M
        .opts = opts,
3579
3.15M
        .opts_cache = opts_cache,
3580
3.15M
        .events = DEMUX_EVENT_INIT | DEMUX_EVENT_DURATION | DEMUX_EVENT_METADATA | DEMUX_EVENT_STREAMS,
3581
3.15M
        .duration = -1,
3582
3.15M
        .depth = params->depth,
3583
3.15M
    };
3584
3585
3.15M
    struct demux_internal *in = demuxer->in = talloc_ptrtype(demuxer, in);
3586
3.15M
    *in = (struct demux_internal){
3587
3.15M
        .global = global,
3588
3.15M
        .log = demuxer->log,
3589
3.15M
        .packet_pool = demux_packet_pool_get(global),
3590
3.15M
        .stats = stats_ctx_create(in, global, "demuxer"),
3591
3.15M
        .can_cache = params->is_top_level,
3592
3.15M
        .can_record = params->stream_record,
3593
3.15M
        .d_thread = talloc(demuxer, struct demuxer),
3594
3.15M
        .d_user = demuxer,
3595
3.15M
        .after_seek = true, // (assumed identical to initial demuxer state)
3596
3.15M
        .after_seek_to_start = true,
3597
3.15M
        .highest_av_pts = MP_NOPTS_VALUE,
3598
3.15M
        .seeking_in_progress = MP_NOPTS_VALUE,
3599
3.15M
        .demux_ts = MP_NOPTS_VALUE,
3600
3.15M
        .owns_stream = !params->external_stream,
3601
3.15M
    };
3602
3.15M
    mp_mutex_init(&in->lock);
3603
3.15M
    mp_cond_init(&in->wakeup);
3604
3605
3.15M
    *in->d_thread = *demuxer;
3606
3607
3.15M
    in->d_thread->metadata = talloc_zero(in->d_thread, struct mp_tags);
3608
3609
3.15M
    in->d_thread->params = params; // temporary during open()
3610
3.15M
    int ret = demuxer->desc->open(in->d_thread, check);
3611
3.15M
    if (ret >= 0) {
3612
369k
        in->d_thread->params = NULL;
3613
369k
        if (in->d_thread->filetype)
3614
291k
            mp_verbose(log, "Detected file format: %s (%s)\n",
3615
369k
                       in->d_thread->filetype, desc->desc);
3616
77.2k
        else
3617
77.2k
            mp_verbose(log, "Detected file format: %s\n", desc->desc);
3618
369k
        if (!in->d_thread->seekable)
3619
43.0k
            mp_verbose(log, "Stream is not seekable.\n");
3620
369k
        if (!in->d_thread->seekable && opts->force_seekable) {
3621
0
            mp_warn(log, "Not seekable, but enabling seeking on user request.\n");
3622
0
            in->d_thread->seekable = true;
3623
0
            in->d_thread->partially_seekable = true;
3624
0
        }
3625
369k
        demux_init_cuesheet(in->d_thread);
3626
369k
        demux_init_ccs(demuxer, opts);
3627
369k
        demux_convert_tags_charset(in->d_thread);
3628
369k
        demux_copy(in->d_user, in->d_thread);
3629
369k
        in->duration = in->d_thread->duration;
3630
369k
        demuxer_sort_chapters(demuxer);
3631
369k
        in->events = DEMUX_EVENT_INIT | DEMUX_EVENT_DURATION | DEMUX_EVENT_METADATA | DEMUX_EVENT_STREAMS;
3632
3633
369k
        struct demuxer *sub = NULL;
3634
369k
        if (!params->disable_timeline) {
3635
369k
            struct timeline *tl = timeline_load(global, log, demuxer);
3636
369k
            if (tl) {
3637
33.0k
                struct demuxer_params params2 = {0};
3638
33.0k
                params2.timeline = tl;
3639
33.0k
                params2.is_top_level = params->is_top_level;
3640
33.0k
                params2.stream_record = params->stream_record;
3641
33.0k
                params2.depth = params->depth + 1;
3642
33.0k
                sub =
3643
33.0k
                    open_given_type(global, log, &demuxer_desc_timeline,
3644
33.0k
                                    NULL, sinfo, &params2, DEMUX_CHECK_FORCE);
3645
33.0k
                if (sub) {
3646
33.0k
                    in->can_cache = false;
3647
33.0k
                    in->can_record = false;
3648
33.0k
                } else {
3649
0
                    timeline_destroy(tl);
3650
0
                }
3651
33.0k
            }
3652
369k
        }
3653
3654
369k
        switch_to_fresh_cache_range(in);
3655
3656
369k
        update_opts(demuxer);
3657
3658
369k
        demux_update(demuxer, MP_NOPTS_VALUE);
3659
3660
369k
        demuxer = sub ? sub : demuxer;
3661
369k
        return demuxer;
3662
369k
    }
3663
3664
2.78M
    demuxer->stream = NULL;
3665
2.78M
    demux_free(demuxer);
3666
2.78M
    return NULL;
3667
3.15M
}
3668
3669
static const int d_normal[]  = {DEMUX_CHECK_NORMAL, DEMUX_CHECK_UNSAFE, -1};
3670
static const int d_request[] = {DEMUX_CHECK_REQUEST, -1};
3671
static const int d_force[]   = {DEMUX_CHECK_FORCE, -1};
3672
3673
// This may free the stream parameter on success.
3674
static struct demuxer *demux_open(struct stream *stream,
3675
                                  struct mp_cancel *cancel,
3676
                                  struct demuxer_params *params,
3677
                                  struct mpv_global *global)
3678
394k
{
3679
394k
    const int *check_levels = d_normal;
3680
394k
    const struct demuxer_desc *check_desc = NULL;
3681
394k
    struct mp_log *log = mp_log_new(NULL, global->log, "!demux");
3682
394k
    struct demuxer *demuxer = NULL;
3683
394k
    char *force_format = params->force_format;
3684
3685
394k
    struct parent_stream_info sinfo = {
3686
394k
        .seekable = stream->seekable,
3687
394k
        .is_network = stream->is_network,
3688
394k
        .is_streaming = stream->streaming,
3689
394k
        .stream_origin = stream->stream_origin,
3690
394k
        .cancel = cancel,
3691
394k
        .filename = talloc_strdup(NULL, stream->url),
3692
394k
        .server_filename = stream->server_filename,
3693
394k
    };
3694
3695
394k
    if (!force_format)
3696
365k
        force_format = stream->demuxer;
3697
3698
394k
    if (force_format && force_format[0] && !stream->is_directory) {
3699
160k
        check_levels = d_request;
3700
160k
        if (force_format[0] == '+') {
3701
3
            force_format += 1;
3702
3
            check_levels = d_force;
3703
3
        }
3704
1.05M
        for (int n = 0; demuxer_list[n]; n++) {
3705
1.05M
            if (strcmp(demuxer_list[n]->name, force_format) == 0) {
3706
160k
                check_desc = demuxer_list[n];
3707
160k
                break;
3708
160k
            }
3709
1.05M
        }
3710
160k
        if (!check_desc) {
3711
12
            mp_err(log, "Demuxer %s does not exist.\n", force_format);
3712
12
            goto done;
3713
12
        }
3714
160k
    }
3715
3716
    // Test demuxers from first to last, one pass for each check_levels[] entry
3717
523k
    for (int pass = 0; check_levels[pass] != -1; pass++) {
3718
465k
        enum demux_check level = check_levels[pass];
3719
465k
        mp_verbose(log, "Trying demuxers for level=%s.\n", d_level(level));
3720
4.15M
        for (int n = 0; demuxer_list[n]; n++) {
3721
4.02M
            const struct demuxer_desc *desc = demuxer_list[n];
3722
4.02M
            if (!check_desc || desc == check_desc) {
3723
3.12M
                demuxer = open_given_type(global, log, desc, stream, &sinfo,
3724
3.12M
                                          params, level);
3725
3.12M
                if (demuxer) {
3726
336k
                    talloc_steal(demuxer, log);
3727
336k
                    log = NULL;
3728
336k
                    goto done;
3729
336k
                }
3730
3.12M
            }
3731
4.02M
        }
3732
465k
    }
3733
3734
394k
done:
3735
394k
    talloc_free(sinfo.filename);
3736
394k
    talloc_free(log);
3737
394k
    return demuxer;
3738
394k
}
3739
3740
static struct stream *create_webshit_concat_stream(struct mpv_global *global,
3741
                                                   struct mp_cancel *c,
3742
                                                   bstr init, struct stream *real)
3743
0
{
3744
0
    struct stream *mem = stream_memory_open(global, init.start, init.len);
3745
0
    mp_assert(mem);
3746
3747
0
    struct stream *streams[2] = {mem, real};
3748
0
    struct stream *concat = stream_concat_open(global, c, streams, 2);
3749
0
    if (!concat) {
3750
0
        free_stream(mem);
3751
0
        free_stream(real);
3752
0
    }
3753
0
    return concat;
3754
0
}
3755
3756
// Convenience function: open the stream, enable the cache (according to params
3757
// and global opts.), open the demuxer.
3758
// Also for some reason may close the opened stream if it's not needed.
3759
// demuxer->cancel is not the cancel parameter, but is its own object that will
3760
// be a slave (mp_cancel_set_parent()) to provided cancel object.
3761
// demuxer->cancel is automatically freed.
3762
struct demuxer *demux_open_url(const char *url,
3763
                               struct demuxer_params *params,
3764
                               struct mp_cancel *cancel,
3765
                               struct mpv_global *global)
3766
448k
{
3767
448k
    if (!params)
3768
0
        return NULL;
3769
448k
    struct mp_cancel *priv_cancel = mp_cancel_new(NULL);
3770
448k
    if (cancel)
3771
448k
        mp_cancel_set_parent(priv_cancel, cancel);
3772
448k
    struct stream *s = params->external_stream;
3773
448k
    if (!s) {
3774
448k
        s = stream_create(url, STREAM_READ | params->stream_flags,
3775
448k
                          priv_cancel, global);
3776
448k
        if (s && params->init_fragment.len) {
3777
0
            s = create_webshit_concat_stream(global, priv_cancel,
3778
0
                                             params->init_fragment, s);
3779
0
        }
3780
448k
    }
3781
448k
    if (!s) {
3782
53.9k
        talloc_free(priv_cancel);
3783
53.9k
        return NULL;
3784
53.9k
    }
3785
394k
    struct demuxer *d = demux_open(s, priv_cancel, params, global);
3786
394k
    if (d) {
3787
336k
        talloc_steal(d->in, priv_cancel);
3788
336k
        mp_assert(d->cancel);
3789
336k
    } else {
3790
58.1k
        params->demuxer_failed = true;
3791
58.1k
        if (!params->external_stream)
3792
58.1k
            free_stream(s);
3793
58.1k
        talloc_free(priv_cancel);
3794
58.1k
    }
3795
394k
    return d;
3796
394k
}
3797
3798
// clear the packet queues
3799
void demux_flush(demuxer_t *demuxer)
3800
3.15M
{
3801
3.15M
    struct demux_internal *in = demuxer->in;
3802
3.15M
    mp_assert(demuxer == in->d_user);
3803
3804
3.15M
    mp_mutex_lock(&in->lock);
3805
3.15M
    clear_reader_state(in, true);
3806
3.53M
    for (int n = 0; n < in->num_ranges; n++)
3807
375k
        clear_cached_range(in, in->ranges[n]);
3808
3.15M
    free_empty_cached_ranges(in);
3809
3.57M
    for (int n = 0; n < in->num_streams; n++) {
3810
420k
        struct demux_stream *ds = in->streams[n]->ds;
3811
420k
        ds->refreshing = false;
3812
420k
        ds->eof = false;
3813
420k
    }
3814
3.15M
    in->eof = false;
3815
3.15M
    in->seeking = false;
3816
3.15M
    mp_mutex_unlock(&in->lock);
3817
3.15M
}
3818
3819
// Does some (but not all) things for switching to another range.
3820
static void switch_current_range(struct demux_internal *in,
3821
                                 struct demux_cached_range *range)
3822
748k
{
3823
748k
    struct demux_cached_range *old = in->current_range;
3824
748k
    mp_assert(old != range);
3825
3826
748k
    set_current_range(in, range);
3827
3828
748k
    if (old) {
3829
        // Remove packets which can't be used when seeking back to the range.
3830
1.12M
        for (int n = 0; n < in->num_streams; n++) {
3831
741k
            struct demux_queue *queue = old->streams[n];
3832
3833
            // Remove all packets which cannot be involved in seeking.
3834
741k
            while (queue->head && !queue->head->keyframe)
3835
0
                remove_head_packet(queue);
3836
741k
        }
3837
3838
        // Exclude weird corner cases that break resuming.
3839
1.12M
        for (int n = 0; n < in->num_streams; n++) {
3840
741k
            struct demux_stream *ds = in->streams[n]->ds;
3841
            // This is needed to resume or join the range at all.
3842
741k
            if (ds->selected && !(ds->global_correct_dts ||
3843
0
                                  ds->global_correct_pos))
3844
0
            {
3845
0
                MP_VERBOSE(in, "discarding unseekable range due to stream %d\n", n);
3846
0
                clear_cached_range(in, old);
3847
0
                break;
3848
0
            }
3849
741k
        }
3850
379k
    }
3851
3852
    // Set up reading from new range (as well as writing to it).
3853
1.89M
    for (int n = 0; n < in->num_streams; n++) {
3854
1.14M
        struct demux_stream *ds = in->streams[n]->ds;
3855
3856
1.14M
        ds->queue = range->streams[n];
3857
1.14M
        ds->refreshing = false;
3858
1.14M
        ds->eof = false;
3859
1.14M
    }
3860
3861
    // No point in keeping any junk (especially if old current_range is empty).
3862
748k
    free_empty_cached_ranges(in);
3863
3864
    // The change detection doesn't work across ranges.
3865
748k
    in->force_metadata_update = true;
3866
748k
}
3867
3868
// Search for the entry with the highest index with entry.pts <= pts true.
3869
static struct demux_packet *search_index(struct demux_queue *queue, double pts)
3870
1.88M
{
3871
1.88M
    size_t a = 0;
3872
1.88M
    size_t b = queue->num_index;
3873
3874
1.88M
    while (a < b) {
3875
13.4k
        size_t m = a + (b - a) / 2;
3876
13.4k
        struct index_entry *e = &QUEUE_INDEX_ENTRY(queue, m);
3877
3878
13.4k
        bool m_ok = e->pts <= pts;
3879
3880
13.4k
        if (a + 1 == b)
3881
13.4k
            return m_ok ? e->pkt : NULL;
3882
3883
0
        if (m_ok) {
3884
0
            a = m;
3885
0
        } else {
3886
0
            b = m;
3887
0
        }
3888
0
    }
3889
3890
1.87M
    return NULL;
3891
1.88M
}
3892
3893
static struct demux_packet *find_seek_target(struct demux_queue *queue,
3894
                                             double pts, int flags)
3895
1.88M
{
3896
1.88M
    pts -= queue->ds->sh->seek_preroll;
3897
3898
1.88M
    struct demux_packet *start = search_index(queue, pts);
3899
1.88M
    if (!start)
3900
1.87M
        start = queue->head;
3901
3902
1.88M
    struct demux_packet *target = NULL;
3903
1.88M
    struct demux_packet *next = NULL;
3904
2.08M
    for (struct demux_packet *dp = start; dp; dp = next) {
3905
208k
        next = dp->next;
3906
208k
        if (!dp->keyframe)
3907
0
            continue;
3908
3909
208k
        double range_pts;
3910
208k
        next = compute_keyframe_times(dp, &range_pts, NULL);
3911
3912
208k
        if (range_pts == MP_NOPTS_VALUE)
3913
0
            continue;
3914
3915
208k
        if (flags & SEEK_FORWARD) {
3916
            // Stop on the first packet that is >= pts.
3917
57.3k
            if (target)
3918
0
                break;
3919
57.3k
            if (range_pts < pts)
3920
57.3k
                continue;
3921
151k
        } else {
3922
            // Stop before the first packet that is > pts.
3923
            // This still returns a packet with > pts if there's no better one.
3924
151k
            if (target && range_pts > pts)
3925
8.67k
                break;
3926
151k
        }
3927
3928
142k
        target = dp;
3929
142k
    }
3930
3931
1.88M
    return target;
3932
1.88M
}
3933
3934
// Return a cache range for the given pts/flags, or NULL if none available.
3935
// must be called locked
3936
static struct demux_cached_range *find_cache_seek_range(struct demux_internal *in,
3937
                                                        double pts, int flags)
3938
4.75M
{
3939
    // Note about queued low level seeks: in->seeking can be true here, and it
3940
    // might come from a previous resume seek to the current range. If we end
3941
    // up seeking into the current range (i.e. just changing time offset), the
3942
    // seek needs to continue. Otherwise, we override the queued seek anyway.
3943
4.75M
    if ((flags & SEEK_FACTOR) || !in->seekable_cache)
3944
4.37M
        return NULL;
3945
3946
385k
    struct demux_cached_range *res = NULL;
3947
3948
765k
    for (int n = 0; n < in->num_ranges; n++) {
3949
385k
        struct demux_cached_range *r = in->ranges[n];
3950
385k
        if (r->seek_start != MP_NOPTS_VALUE) {
3951
5.60k
            MP_VERBOSE(in, "cached range %d: %f <-> %f (bof=%d, eof=%d)\n",
3952
5.60k
                       n, r->seek_start, r->seek_end, r->is_bof, r->is_eof);
3953
3954
5.60k
            if ((pts >= r->seek_start || r->is_bof) &&
3955
5.53k
                (pts <= r->seek_end || r->is_eof))
3956
5.51k
            {
3957
5.51k
                MP_VERBOSE(in, "...using this range for in-cache seek.\n");
3958
5.51k
                res = r;
3959
5.51k
                break;
3960
5.51k
            }
3961
5.60k
        }
3962
385k
    }
3963
3964
385k
    return res;
3965
4.75M
}
3966
3967
// Adjust the seek target to the found video key frames. Otherwise the
3968
// video will undershoot the seek target, while audio will be closer to it.
3969
// The player frontend will play the additional video without audio, so
3970
// you get silent audio for the amount of "undershoot". Adjusting the seek
3971
// target will make the audio seek to the video target or before.
3972
// (If hr-seeks are used, it's better to skip this, as it would only mean
3973
// that more audio data than necessary would have to be decoded.)
3974
static void adjust_cache_seek_target(struct demux_internal *in,
3975
                                     struct demux_cached_range *range,
3976
                                     double *pts, int *flags)
3977
5.49k
{
3978
5.49k
    if (*flags & SEEK_HR)
3979
4.00k
        return;
3980
3981
1.61k
    for (int n = 0; n < in->num_streams; n++) {
3982
1.51k
        struct demux_stream *ds = in->streams[n]->ds;
3983
1.51k
        struct demux_queue *queue = range->streams[n];
3984
1.51k
        if (ds->selected && ds->type == STREAM_VIDEO) {
3985
1.38k
            struct demux_packet *target = find_seek_target(queue, *pts, *flags);
3986
1.38k
            if (target) {
3987
756
                double target_pts;
3988
756
                compute_keyframe_times(target, &target_pts, NULL);
3989
756
                if (target_pts != MP_NOPTS_VALUE) {
3990
756
                    MP_VERBOSE(in, "adjust seek target %f -> %f\n",
3991
756
                               *pts, target_pts);
3992
                    // (We assume the find_seek_target() call will return
3993
                    // the same target for the video stream.)
3994
756
                    *pts = target_pts;
3995
756
                    *flags &= ~SEEK_FORWARD;
3996
756
                }
3997
756
            }
3998
1.38k
            break;
3999
1.38k
        }
4000
1.51k
    }
4001
1.49k
}
4002
4003
// must be called locked
4004
// range must be non-NULL and from find_cache_seek_range() using the same pts
4005
// and flags, before any other changes to the cached state
4006
static void execute_cache_seek(struct demux_internal *in,
4007
                               struct demux_cached_range *range,
4008
                               double pts, int flags)
4009
5.38k
{
4010
5.38k
    adjust_cache_seek_target(in, range, &pts, &flags);
4011
4012
16.0k
    for (int n = 0; n < in->num_streams; n++) {
4013
10.6k
        struct demux_stream *ds = in->streams[n]->ds;
4014
10.6k
        struct demux_queue *queue = range->streams[n];
4015
4016
10.6k
        struct demux_packet *target = find_seek_target(queue, pts, flags);
4017
10.6k
        ds->reader_head = target;
4018
10.6k
        ds->skip_to_keyframe = !target;
4019
10.6k
        if (ds->reader_head)
4020
9.09k
            ds->base_ts = MP_PTS_OR_DEF(ds->reader_head->pts, ds->reader_head->dts);
4021
4022
10.6k
        MP_VERBOSE(in, "seeking stream %d (%s) to ",
4023
10.6k
                   n, stream_type_name(ds->type));
4024
4025
10.6k
        if (target) {
4026
9.09k
            MP_VERBOSE(in, "packet %f/%f\n", target->pts, target->dts);
4027
9.09k
        } else {
4028
1.59k
            MP_VERBOSE(in, "nothing\n");
4029
1.59k
        }
4030
10.6k
    }
4031
4032
    // If we seek to another range, we want to seek the low level demuxer to
4033
    // there as well, because reader and demuxer queue must be the same.
4034
5.38k
    if (in->current_range != range) {
4035
6
        switch_current_range(in, range);
4036
4037
6
        in->seeking = true;
4038
6
        in->seek_flags = SEEK_HR;
4039
6
        in->seek_pts = range->seek_end - 1.0;
4040
4041
        // When new packets are being appended, they could overlap with the old
4042
        // range due to demuxer seek imprecisions, or because the queue contains
4043
        // packets past the seek target but before the next seek target. Don't
4044
        // append them twice, instead skip them until new packets are found.
4045
18
        for (int n = 0; n < in->num_streams; n++) {
4046
12
            struct demux_stream *ds = in->streams[n]->ds;
4047
4048
12
            ds->refreshing = ds->selected;
4049
12
        }
4050
4051
6
        MP_VERBOSE(in, "resuming demuxer to end of cached range\n");
4052
6
    }
4053
5.38k
}
4054
4055
// Create a new blank cache range, and backup the old one. If the seekable
4056
// demuxer cache is disabled, merely reset the current range to a blank state.
4057
static void switch_to_fresh_cache_range(struct demux_internal *in)
4058
5.11M
{
4059
5.11M
    if (!in->seekable_cache && in->current_range) {
4060
4.36M
        clear_cached_range(in, in->current_range);
4061
4.36M
        return;
4062
4.36M
    }
4063
4064
748k
    struct demux_cached_range *range = talloc_ptrtype(NULL, range);
4065
748k
    *range = (struct demux_cached_range){
4066
748k
        .seek_start = MP_NOPTS_VALUE,
4067
748k
        .seek_end = MP_NOPTS_VALUE,
4068
748k
    };
4069
748k
    MP_TARRAY_APPEND(in, in->ranges, in->num_ranges, range);
4070
748k
    add_missing_streams(in, range);
4071
4072
748k
    switch_current_range(in, range);
4073
748k
}
4074
4075
int demux_seek(demuxer_t *demuxer, double seek_pts, int flags)
4076
2.88M
{
4077
2.88M
    struct demux_internal *in = demuxer->in;
4078
2.88M
    mp_assert(demuxer == in->d_user);
4079
4080
2.88M
    mp_mutex_lock(&in->lock);
4081
4082
2.88M
    if (!(flags & SEEK_FACTOR))
4083
2.88M
        seek_pts = MP_ADD_PTS(seek_pts, -in->ts_offset);
4084
4085
2.88M
    int res = queue_seek(in, seek_pts, flags, true);
4086
4087
2.88M
    mp_cond_signal(&in->wakeup);
4088
2.88M
    mp_mutex_unlock(&in->lock);
4089
4090
2.88M
    return res;
4091
2.88M
}
4092
4093
static bool queue_seek(struct demux_internal *in, double seek_pts, int flags,
4094
                       bool clear_back_state)
4095
4.75M
{
4096
4.75M
    if (seek_pts == MP_NOPTS_VALUE)
4097
2
        return false;
4098
4099
4.75M
    MP_VERBOSE(in, "queuing seek to %f%s\n", seek_pts,
4100
4.75M
               in->seeking ? " (cascade)" : "");
4101
4102
4.75M
    bool require_cache = flags & SEEK_CACHED;
4103
4.75M
    flags &= ~(unsigned)SEEK_CACHED;
4104
4105
4.75M
    bool set_backwards = flags & SEEK_SATAN;
4106
4.75M
    flags &= ~(unsigned)SEEK_SATAN;
4107
4108
4.75M
    bool block = flags & SEEK_BLOCK;
4109
4.75M
    flags &= ~(unsigned)SEEK_BLOCK;
4110
4111
4.75M
    struct demux_cached_range *cache_target =
4112
4.75M
        find_cache_seek_range(in, seek_pts, flags);
4113
4114
4.75M
    if (!cache_target) {
4115
4.74M
        if (require_cache) {
4116
0
            MP_VERBOSE(in, "Cached seek not possible.\n");
4117
0
            return false;
4118
0
        }
4119
4.74M
        if (!in->d_thread->seekable) {
4120
322
            MP_WARN(in, "Cannot seek in this file.\n");
4121
322
            return false;
4122
322
        }
4123
4.74M
    }
4124
4125
4.75M
    in->eof = false;
4126
4.75M
    in->reading = false;
4127
4.75M
    in->back_demuxing = set_backwards;
4128
4129
4.75M
    clear_reader_state(in, clear_back_state);
4130
4131
4.75M
    in->blocked = block;
4132
4133
4.75M
    if (cache_target) {
4134
5.38k
        execute_cache_seek(in, cache_target, seek_pts, flags);
4135
4.74M
    } else {
4136
4.74M
        switch_to_fresh_cache_range(in);
4137
4138
4.74M
        in->seeking = true;
4139
4.74M
        in->seek_flags = flags;
4140
4.74M
        in->seek_pts = seek_pts;
4141
4.74M
    }
4142
4143
14.0M
    for (int n = 0; n < in->num_streams; n++) {
4144
9.25M
        struct demux_stream *ds = in->streams[n]->ds;
4145
4146
9.25M
        if (in->back_demuxing) {
4147
3.70M
            if (ds->back_seek_pos == MP_NOPTS_VALUE)
4148
25.0k
                ds->back_seek_pos = seek_pts;
4149
            // Process possibly cached packets.
4150
3.70M
            back_demux_see_packets(in->streams[n]->ds);
4151
3.70M
        }
4152
4153
9.25M
        wakeup_ds(ds);
4154
9.25M
    }
4155
4156
4.75M
    if (!in->threading && in->seeking)
4157
262k
        execute_seek(in);
4158
4159
4.75M
    return true;
4160
4.75M
}
4161
4162
struct sh_stream *demuxer_stream_by_demuxer_id(struct demuxer *d,
4163
                                               enum stream_type t, int id)
4164
0
{
4165
0
    if (id < 0)
4166
0
        return NULL;
4167
0
    int num = demux_get_num_stream(d);
4168
0
    for (int n = 0; n < num; n++) {
4169
0
        struct sh_stream *s = demux_get_stream(d, n);
4170
0
        if (s->type == t && s->demuxer_id == id)
4171
0
            return s;
4172
0
    }
4173
0
    return NULL;
4174
0
}
4175
4176
// An obscure mechanism to get stream switching to be executed "faster" (as
4177
// perceived by the user), by making the stream return packets from the
4178
// current position
4179
// On a switch, it seeks back, and then grabs all packets that were
4180
// "missing" from the packet queue of the newly selected stream.
4181
static void initiate_refresh_seek(struct demux_internal *in,
4182
                                  struct demux_stream *stream,
4183
                                  double start_ts)
4184
115k
{
4185
115k
    struct demuxer *demux = in->d_thread;
4186
115k
    bool seekable = demux->desc->seek && demux->seekable &&
4187
115k
                    !demux->partially_seekable;
4188
4189
115k
    bool normal_seek = true;
4190
115k
    bool refresh_possible = true;
4191
2.85M
    for (int n = 0; n < in->num_streams; n++) {
4192
2.73M
        struct demux_stream *ds = in->streams[n]->ds;
4193
4194
2.73M
        if (!ds->selected)
4195
2.61M
            continue;
4196
4197
124k
        if (ds->type == STREAM_VIDEO || ds->type == STREAM_AUDIO)
4198
111k
            start_ts = MP_PTS_MIN(start_ts, ds->base_ts);
4199
4200
        // If there were no other streams selected, we can use a normal seek.
4201
124k
        normal_seek &= stream == ds;
4202
4203
124k
        refresh_possible &= ds->queue->correct_dts || ds->queue->correct_pos;
4204
124k
    }
4205
4206
115k
    if (start_ts == MP_NOPTS_VALUE || !seekable)
4207
13.9k
        return;
4208
4209
101k
    if (!normal_seek) {
4210
8.22k
        if (!refresh_possible) {
4211
1
            MP_VERBOSE(in, "can't issue refresh seek\n");
4212
1
            return;
4213
1
        }
4214
4215
47.5k
        for (int n = 0; n < in->num_streams; n++) {
4216
39.2k
            struct demux_stream *ds = in->streams[n]->ds;
4217
4218
39.2k
            bool correct_pos = ds->queue->correct_pos;
4219
39.2k
            bool correct_dts = ds->queue->correct_dts;
4220
4221
            // We need to re-read all packets anyway, so discard the buffered
4222
            // data. (In theory, we could keep the packets, and be able to use
4223
            // it for seeking if partially read streams are deselected again,
4224
            // but this causes other problems like queue overflows when
4225
            // selecting a new stream.)
4226
39.2k
            ds_clear_reader_queue_state(ds);
4227
39.2k
            clear_queue(ds->queue);
4228
4229
            // Streams which didn't have any packets yet will return all packets,
4230
            // other streams return packets only starting from the last position.
4231
39.2k
            if (ds->selected && (ds->last_ret_pos != -1 ||
4232
16.1k
                                 ds->last_ret_dts != MP_NOPTS_VALUE))
4233
7.66k
            {
4234
7.66k
                ds->refreshing = true;
4235
7.66k
                ds->queue->correct_dts = correct_dts;
4236
7.66k
                ds->queue->correct_pos = correct_pos;
4237
7.66k
                ds->queue->last_pos = ds->last_ret_pos;
4238
7.66k
                ds->queue->last_dts = ds->last_ret_dts;
4239
7.66k
            }
4240
4241
39.2k
            update_seek_ranges(in->current_range);
4242
39.2k
        }
4243
4244
8.22k
        start_ts -= 1.0; // small offset to get correct overlap
4245
8.22k
    }
4246
4247
101k
    MP_VERBOSE(in, "refresh seek to %f\n", start_ts);
4248
101k
    in->seeking = true;
4249
101k
    in->seek_flags = SEEK_HR;
4250
101k
    in->seek_pts = start_ts;
4251
101k
}
4252
4253
// Called locked.
4254
static void refresh_track(struct demux_internal *in, struct sh_stream *stream,
4255
                          double ref_pts)
4256
350k
{
4257
350k
    struct demux_stream *ds = stream->ds;
4258
350k
    ref_pts = MP_ADD_PTS(ref_pts, -in->ts_offset);
4259
4260
350k
    if (in->back_demuxing)
4261
299
        ds->back_seek_pos = ref_pts;
4262
    // Avoid refresh seek for video streams except when immediately after a seek
4263
    // to ensure a correct seek position.
4264
350k
    bool avoid_refresh = false;
4265
3.15M
    for (int n = 0; n < in->num_streams; n++) {
4266
3.04M
        struct demux_stream *ds_n = in->streams[n]->ds;
4267
3.04M
        if (ds_n->type == STREAM_VIDEO && ds_n->selected) {
4268
242k
            avoid_refresh = true;
4269
242k
            break;
4270
242k
        }
4271
3.04M
    }
4272
350k
    avoid_refresh = avoid_refresh && !(in->after_seek && !in->after_seek_to_start);
4273
    // Allow refresh seek for non-video streams, even if no packets have
4274
    // ever been read yet or after seeking. This is necessary because:
4275
    // - A-V sync targets may come from different demuxers, so enabling an external
4276
    //   audio track for the first time can cause desync since a seek is not performed.
4277
    // - If cache is enabled and a seek causes some new data to be cached, the demuxer
4278
    //   is sought to the end of cache after cache joining. Switching track immediately
4279
    //   after this also causes the same problem.
4280
350k
    if (!in->after_seek || (ds->type != STREAM_VIDEO && !avoid_refresh)) {
4281
115k
        MP_VERBOSE(in, "refresh track %d (%s)\n", stream->index,
4282
115k
                   stream_type_name(ds->type));
4283
115k
        initiate_refresh_seek(in, ds, ref_pts);
4284
115k
    }
4285
350k
}
4286
4287
static bool select_track(struct demux_internal *in,
4288
                         struct sh_stream *stream,
4289
                         double ref_pts, bool selected)
4290
526k
{
4291
526k
    struct demux_stream *ds = stream->ds;
4292
526k
    if (ds->selected == selected)
4293
115k
        return false;
4294
411k
    MP_VERBOSE(in, "%sselect track %d\n", selected ? "" : "de", stream->index);
4295
411k
    ds->selected = selected;
4296
411k
    update_stream_selection_state(in, ds);
4297
411k
    in->tracks_switched = true;
4298
411k
    if (ds->selected)
4299
350k
        refresh_track(in, stream, ref_pts);
4300
411k
    return true;
4301
526k
}
4302
4303
// Apply the selection of a base stream to the dependent members of its group.
4304
static bool select_dependent_tracks(struct demux_internal *in,
4305
                                    struct sh_stream *stream,
4306
                                    double ref_pts, bool selected)
4307
525k
{
4308
525k
    bool changed = false;
4309
525k
    if (stream->group && !stream->dependent_track) {
4310
902
        for (int i = 0; i < stream->group->num_members; i++) {
4311
880
            struct sh_stream *m = stream->group->members[i];
4312
880
            mp_assert(m);
4313
880
            if (m != stream && m->dependent_track)
4314
880
                changed |= select_track(in, m, ref_pts, selected);
4315
880
        }
4316
22
    }
4317
525k
    return changed;
4318
525k
}
4319
4320
// Set whether the given stream should return packets.
4321
// ref_pts is used only if the stream is enabled. Then it serves as approximate
4322
// start pts for this stream (in the worst case it is ignored).
4323
void demuxer_select_track(struct demuxer *demuxer, struct sh_stream *stream,
4324
                          double ref_pts, bool selected)
4325
525k
{
4326
525k
    struct demux_internal *in = demuxer->in;
4327
525k
    mp_mutex_lock(&in->lock);
4328
525k
    bool changed = select_track(in, stream, ref_pts, selected);
4329
525k
    changed |= select_dependent_tracks(in, stream, ref_pts, selected);
4330
525k
    if (changed) {
4331
410k
        if (in->threading) {
4332
359k
            mp_cond_signal(&in->wakeup);
4333
359k
        } else {
4334
50.9k
            execute_trackswitch(in);
4335
50.9k
        }
4336
410k
    }
4337
525k
    mp_mutex_unlock(&in->lock);
4338
525k
}
4339
4340
void demux_set_stream_group(struct demuxer *demuxer,
4341
                            struct sh_stream_group *group)
4342
0
{
4343
0
    struct demux_internal *in = demuxer->in;
4344
0
    mp_assert(demuxer == in->d_thread);
4345
4346
0
    mp_mutex_lock(&in->lock);
4347
0
    for (int i = 0; i < group->num_members; i++)
4348
0
        group->members[i]->group = group;
4349
0
    for (int i = 0; i < group->num_members; i++) {
4350
0
        struct sh_stream *m = group->members[i];
4351
0
        select_dependent_tracks(in, m, MP_NOPTS_VALUE, m->ds->selected);
4352
0
    }
4353
0
    mp_mutex_unlock(&in->lock);
4354
0
}
4355
4356
// Replace the codec params of a stream that was already added.
4357
void demux_set_stream_codec(struct demuxer *demuxer, struct sh_stream *sh,
4358
                            struct mp_codec_params *codec)
4359
0
{
4360
0
    struct demux_internal *in = demuxer->in;
4361
0
    mp_assert(demuxer == in->d_thread);
4362
0
    mp_assert(sh->ds); // stream must have been added
4363
4364
0
    mp_mutex_lock(&in->lock);
4365
0
    sh->ds->staged_codec = codec;
4366
0
    in->events |= DEMUX_EVENT_CODEC;
4367
0
    mp_mutex_unlock(&in->lock);
4368
0
}
4369
4370
// Execute a refresh seek on the given stream.
4371
// ref_pts has the same meaning as with demuxer_select_track()
4372
void demuxer_refresh_track(struct demuxer *demuxer, struct sh_stream *stream,
4373
                           double ref_pts)
4374
0
{
4375
0
    struct demux_internal *in = demuxer->in;
4376
0
    struct demux_stream *ds = stream->ds;
4377
0
    mp_mutex_lock(&in->lock);
4378
0
    if (ds->selected) {
4379
0
        update_stream_selection_state(in, ds);
4380
0
        refresh_track(in, stream, ref_pts);
4381
0
    }
4382
0
    mp_mutex_unlock(&in->lock);
4383
0
}
4384
4385
// This is for demuxer implementations only. demuxer_select_track() sets the
4386
// logical state, while this function returns the actual state (in case the
4387
// demuxer attempts to cache even unselected packets for track switching - this
4388
// will potentially be done in the future).
4389
bool demux_stream_is_selected(struct sh_stream *stream)
4390
15.5M
{
4391
15.5M
    if (!stream)
4392
7.80k
        return false;
4393
15.5M
    bool r = false;
4394
15.5M
    mp_mutex_lock(&stream->ds->in->lock);
4395
15.5M
    r = stream->ds->selected;
4396
15.5M
    mp_mutex_unlock(&stream->ds->in->lock);
4397
15.5M
    return r;
4398
15.5M
}
4399
4400
// Return true if the last EOF returned for the stream was a lazy one, i.e. the
4401
// demuxer could still read: the stream is not eager (sparse video, subtitles,
4402
// a stream absent from the current data), or it was starved by a queue
4403
// overflow. More packets may follow.
4404
bool demux_stream_eof_is_lazy(struct sh_stream *stream)
4405
23.9M
{
4406
23.9M
    if (!stream)
4407
0
        return false;
4408
23.9M
    mp_mutex_lock(&stream->ds->in->lock);
4409
23.9M
    bool r = stream->ds->lazy_eof;
4410
23.9M
    mp_mutex_unlock(&stream->ds->in->lock);
4411
23.9M
    return r;
4412
23.9M
}
4413
4414
// Return true if packets are queued for the reader.
4415
bool demux_stream_has_packets(struct sh_stream *stream)
4416
6
{
4417
6
    if (!stream)
4418
0
        return false;
4419
6
    mp_mutex_lock(&stream->ds->in->lock);
4420
6
    bool r = !!stream->ds->reader_head;
4421
6
    mp_mutex_unlock(&stream->ds->in->lock);
4422
6
    return r;
4423
6
}
4424
4425
void demux_set_stream_wakeup_cb(struct sh_stream *sh,
4426
                                void (*cb)(void *ctx), void *ctx)
4427
638k
{
4428
638k
    mp_mutex_lock(&sh->ds->in->lock);
4429
638k
    sh->ds->wakeup_cb = cb;
4430
638k
    sh->ds->wakeup_cb_ctx = ctx;
4431
638k
    sh->ds->need_wakeup = true;
4432
638k
    mp_mutex_unlock(&sh->ds->in->lock);
4433
638k
}
4434
4435
int demuxer_add_attachment(demuxer_t *demuxer, char *name, char *type,
4436
                           void *data, size_t data_size)
4437
1.33k
{
4438
1.33k
    if (!(demuxer->num_attachments % 32))
4439
757
        demuxer->attachments = talloc_realloc(demuxer, demuxer->attachments,
4440
1.33k
                                              struct demux_attachment,
4441
1.33k
                                              demuxer->num_attachments + 32);
4442
4443
1.33k
    struct demux_attachment *att = &demuxer->attachments[demuxer->num_attachments];
4444
1.33k
    att->name = talloc_strdup(demuxer->attachments, name);
4445
1.33k
    att->type = talloc_strdup(demuxer->attachments, type);
4446
1.33k
    att->data = talloc_memdup(demuxer->attachments, data, data_size);
4447
1.33k
    att->data_size = data_size;
4448
4449
1.33k
    return demuxer->num_attachments++;
4450
1.33k
}
4451
4452
static int chapter_compare(const void *p1, const void *p2)
4453
115k
{
4454
115k
    struct demux_chapter *c1 = (void *)p1;
4455
115k
    struct demux_chapter *c2 = (void *)p2;
4456
4457
115k
    if (c1->pts > c2->pts)
4458
6.69k
        return 1;
4459
108k
    else if (c1->pts < c2->pts)
4460
21.0k
        return -1;
4461
87.3k
    return c1->original_index > c2->original_index ? 1 :-1; // never equal
4462
115k
}
4463
4464
static void demuxer_sort_chapters(demuxer_t *demuxer)
4465
369k
{
4466
369k
    if (demuxer->num_chapters) {
4467
31.0k
        qsort(demuxer->chapters, demuxer->num_chapters,
4468
31.0k
            sizeof(struct demux_chapter), chapter_compare);
4469
31.0k
    }
4470
369k
}
4471
4472
int demuxer_add_chapter(demuxer_t *demuxer, char *name,
4473
                        double pts, uint64_t demuxer_id)
4474
27.4k
{
4475
27.4k
    struct demux_chapter new = {
4476
27.4k
        .original_index = demuxer->num_chapters,
4477
27.4k
        .pts = pts,
4478
27.4k
        .metadata = talloc_zero(demuxer, struct mp_tags),
4479
27.4k
        .demuxer_id = demuxer_id,
4480
27.4k
    };
4481
27.4k
    mp_tags_set_str(new.metadata, "TITLE", name);
4482
27.4k
    MP_TARRAY_APPEND(demuxer, demuxer->chapters, demuxer->num_chapters, new);
4483
27.4k
    talloc_steal(demuxer->chapters, new.metadata);
4484
27.4k
    return demuxer->num_chapters - 1;
4485
27.4k
}
4486
4487
// Disallow reading any packets and make readers think there is no new data
4488
// yet, until a seek is issued.
4489
void demux_block_reading(struct demuxer *demuxer, bool block)
4490
7.65M
{
4491
7.65M
    struct demux_internal *in = demuxer->in;
4492
7.65M
    mp_assert(demuxer == in->d_user);
4493
4494
7.65M
    mp_mutex_lock(&in->lock);
4495
7.65M
    in->blocked = block;
4496
22.7M
    for (int n = 0; n < in->num_streams; n++) {
4497
15.1M
        in->streams[n]->ds->need_wakeup = true;
4498
15.1M
        wakeup_ds(in->streams[n]->ds);
4499
15.1M
    }
4500
7.65M
    mp_cond_signal(&in->wakeup);
4501
7.65M
    mp_mutex_unlock(&in->lock);
4502
7.65M
}
4503
4504
static void update_bytes_read(struct demux_internal *in)
4505
22.2M
{
4506
22.2M
    struct demuxer *demuxer = in->d_thread;
4507
4508
22.2M
    int64_t new = in->slave_unbuffered_read_bytes;
4509
22.2M
    in->slave_unbuffered_read_bytes = 0;
4510
4511
22.2M
    int64_t new_seeks = 0;
4512
4513
22.2M
    struct stream *stream = demuxer->stream;
4514
22.2M
    if (stream) {
4515
19.5M
        new += stream->total_unbuffered_read_bytes;
4516
19.5M
        stream->total_unbuffered_read_bytes = 0;
4517
19.5M
        new_seeks += stream->total_stream_seeks;
4518
19.5M
        stream->total_stream_seeks = 0;
4519
19.5M
    }
4520
4521
22.2M
    in->cache_unbuffered_read_bytes += new;
4522
22.2M
    in->hack_unbuffered_read_bytes += new;
4523
22.2M
    in->byte_level_seeks += new_seeks;
4524
22.2M
}
4525
4526
// must be called locked, temporarily unlocks
4527
static void update_cache(struct demux_internal *in)
4528
20.0M
{
4529
20.0M
    struct demuxer *demuxer = in->d_thread;
4530
20.0M
    struct stream *stream = demuxer->stream;
4531
4532
20.0M
    int64_t now = mp_time_ns();
4533
20.0M
    int64_t diff = now - in->last_speed_query;
4534
20.0M
    bool do_update = diff >= MP_TIME_S_TO_NS(1) || !in->last_speed_query;
4535
4536
    // Don't lock while querying the stream.
4537
20.0M
    mp_mutex_unlock(&in->lock);
4538
4539
20.0M
    int64_t stream_size = -1;
4540
20.0M
    struct mp_tags *stream_metadata = NULL;
4541
20.0M
    if (stream) {
4542
17.5M
        if (do_update)
4543
306k
            stream_size = stream_get_size(stream);
4544
17.5M
        stream_control(stream, STREAM_CTRL_GET_METADATA, &stream_metadata);
4545
17.5M
    }
4546
4547
20.0M
    mp_mutex_lock(&in->lock);
4548
4549
20.0M
    update_bytes_read(in);
4550
4551
20.0M
    if (do_update)
4552
369k
        in->stream_size = stream_size;
4553
20.0M
    if (stream_metadata) {
4554
0
        add_timed_metadata(in, stream_metadata, NULL, MP_NOPTS_VALUE);
4555
0
        talloc_free(stream_metadata);
4556
0
    }
4557
4558
20.0M
    in->next_cache_update = INT64_MAX;
4559
4560
20.0M
    if (do_update) {
4561
369k
        uint64_t bytes = in->cache_unbuffered_read_bytes;
4562
369k
        in->cache_unbuffered_read_bytes = 0;
4563
369k
        in->last_speed_query = now;
4564
369k
        double speed = bytes / (diff / (double)MP_TIME_S_TO_NS(1));
4565
369k
        in->bytes_per_second = 0.5 * in->speed_query_prev_sample +
4566
369k
                               0.5 * speed;
4567
369k
        in->speed_query_prev_sample = speed;
4568
369k
    }
4569
    // The idea is to update as long as there is "activity".
4570
20.0M
    if (in->bytes_per_second)
4571
12.0M
        in->next_cache_update = now + MP_TIME_S_TO_NS(1) + MP_TIME_US_TO_NS(1);
4572
20.0M
}
4573
4574
static void dumper_close(struct demux_internal *in)
4575
3.15M
{
4576
3.15M
    if (in->dumper)
4577
0
        mp_recorder_destroy(in->dumper);
4578
3.15M
    in->dumper = NULL;
4579
3.15M
    if (in->dumper_status == CONTROL_TRUE)
4580
0
        in->dumper_status = CONTROL_FALSE; // make abort equal to success
4581
3.15M
}
4582
4583
static int range_time_compare(const void *p1, const void *p2)
4584
0
{
4585
0
    struct demux_cached_range *r1 = *((struct demux_cached_range **)p1);
4586
0
    struct demux_cached_range *r2 = *((struct demux_cached_range **)p2);
4587
4588
0
    if (r1->seek_start == r2->seek_start)
4589
0
        return 0;
4590
0
    return r1->seek_start < r2->seek_start ? -1 : 1;
4591
0
}
4592
4593
static void dump_cache(struct demux_internal *in, double start, double end)
4594
44
{
4595
44
    in->dumper_status = in->dumper ? CONTROL_TRUE : CONTROL_ERROR;
4596
44
    if (!in->dumper)
4597
44
        return;
4598
4599
    // (only in pathological cases there might be more ranges than allowed)
4600
0
    struct demux_cached_range *ranges[MAX_SEEK_RANGES];
4601
0
    int num_ranges = 0;
4602
0
    for (int n = 0; n < MPMIN(MP_ARRAY_SIZE(ranges), in->num_ranges); n++)
4603
0
        ranges[num_ranges++] = in->ranges[n];
4604
0
    qsort(ranges, num_ranges, sizeof(ranges[0]), range_time_compare);
4605
4606
0
    for (int n = 0; n < num_ranges; n++) {
4607
0
        struct demux_cached_range *r = ranges[n];
4608
0
        if (r->seek_start == MP_NOPTS_VALUE)
4609
0
            continue;
4610
0
        if (r->seek_end <= start)
4611
0
            continue;
4612
0
        if (end != MP_NOPTS_VALUE && r->seek_start >= end)
4613
0
            continue;
4614
4615
0
        mp_recorder_mark_discontinuity(in->dumper);
4616
4617
0
        double pts = start;
4618
0
        int flags = 0;
4619
0
        adjust_cache_seek_target(in, r, &pts, &flags);
4620
4621
0
        for (int i = 0; i < r->num_streams; i++) {
4622
0
            struct demux_queue *q = r->streams[i];
4623
0
            struct demux_stream *ds = q->ds;
4624
4625
0
            ds->dump_pos = find_seek_target(q, pts, flags);
4626
0
        }
4627
4628
        // We need to reinterleave the separate streams somehow, which makes
4629
        // everything more complex.
4630
0
        while (1) {
4631
0
            struct demux_packet *next = NULL;
4632
0
            double next_dts = MP_NOPTS_VALUE;
4633
4634
0
            for (int i = 0; i < r->num_streams; i++) {
4635
0
                struct demux_stream *ds = r->streams[i]->ds;
4636
0
                struct demux_packet *dp = ds->dump_pos;
4637
4638
0
                if (!dp)
4639
0
                    continue;
4640
0
                mp_assert(dp->stream == ds->index);
4641
4642
0
                double pdts = MP_PTS_OR_DEF(dp->dts, dp->pts);
4643
4644
                // Check for stream EOF. Note that we don't try to EOF
4645
                // streams at the same point (e.g. video can take longer
4646
                // to finish than audio, so the output file will have no
4647
                // audio for the last part of the video). Too much effort.
4648
0
                if (pdts != MP_NOPTS_VALUE && end != MP_NOPTS_VALUE &&
4649
0
                    pdts >= end && dp->keyframe)
4650
0
                {
4651
0
                    ds->dump_pos = NULL;
4652
0
                    continue;
4653
0
                }
4654
4655
0
                if (pdts == MP_NOPTS_VALUE || next_dts == MP_NOPTS_VALUE ||
4656
0
                    pdts < next_dts)
4657
0
                {
4658
0
                    next_dts = pdts;
4659
0
                    next = dp;
4660
0
                }
4661
0
            }
4662
4663
0
            if (!next)
4664
0
                break;
4665
4666
0
            struct demux_stream *ds = in->streams[next->stream]->ds;
4667
0
            ds->dump_pos = next->next;
4668
4669
0
            struct demux_packet *dp = read_packet_from_cache(in, next);
4670
0
            if (!dp) {
4671
0
                in->dumper_status = CONTROL_ERROR;
4672
0
                break;
4673
0
            }
4674
4675
0
            write_dump_packet(in, dp);
4676
4677
0
            talloc_free(dp);
4678
0
        }
4679
4680
0
        if (in->dumper_status != CONTROL_OK)
4681
0
            break;
4682
0
    }
4683
4684
    // (strictly speaking unnecessary; for clarity)
4685
0
    for (int n = 0; n < in->num_streams; n++)
4686
0
        in->streams[n]->ds->dump_pos = NULL;
4687
4688
    // If dumping (in end==NOPTS mode) doesn't continue at the range that
4689
    // was written last, we have a discontinuity.
4690
0
    if (num_ranges && ranges[num_ranges - 1] != in->current_range)
4691
0
        mp_recorder_mark_discontinuity(in->dumper);
4692
4693
    // end=NOPTS means the demuxer output continues to be written to the
4694
    // dump file.
4695
0
    if (end != MP_NOPTS_VALUE || in->dumper_status != CONTROL_OK)
4696
0
        dumper_close(in);
4697
0
}
4698
4699
// Set the current cache dumping mode. There is only at most 1 dump process
4700
// active, so calling this aborts the previous dumping. Passing file==NULL
4701
// stops dumping.
4702
// This is synchronous with demux_cache_dump_get_status() (i.e. starting or
4703
// aborting is not asynchronous). On status change, the demuxer wakeup callback
4704
// is invoked (except for this call).
4705
// Returns whether dumping was logically started.
4706
bool demux_cache_dump_set(struct demuxer *demuxer, double start, double end,
4707
                          char *file)
4708
118
{
4709
118
    struct demux_internal *in = demuxer->in;
4710
118
    mp_assert(demuxer == in->d_user);
4711
4712
118
    bool res = false;
4713
4714
118
    mp_mutex_lock(&in->lock);
4715
4716
118
    start = MP_ADD_PTS(start, -in->ts_offset);
4717
118
    end = MP_ADD_PTS(end, -in->ts_offset);
4718
4719
118
    dumper_close(in);
4720
4721
118
    if (file && file[0] && start != MP_NOPTS_VALUE) {
4722
44
        res = true;
4723
4724
44
        in->dumper = recorder_create(in, file);
4725
4726
        // This is not asynchronous and will freeze the shit for a while if the
4727
        // user is unlucky. It could be moved to a thread with some effort.
4728
        // General idea: iterate over all cache ranges, dump what intersects.
4729
        // After that, and if the user requested it, make it dump all newly
4730
        // received packets, even if it's awkward (consider the case if the
4731
        // current range is not the last range).
4732
44
        dump_cache(in, start, end);
4733
44
    }
4734
4735
118
    mp_mutex_unlock(&in->lock);
4736
4737
118
    return res;
4738
118
}
4739
4740
// Returns one of CONTROL_*. CONTROL_TRUE means dumping is in progress.
4741
int demux_cache_dump_get_status(struct demuxer *demuxer)
4742
44
{
4743
44
    struct demux_internal *in = demuxer->in;
4744
44
    mp_mutex_lock(&in->lock);
4745
44
    int status = in->dumper_status;
4746
44
    mp_mutex_unlock(&in->lock);
4747
44
    return status;
4748
44
}
4749
4750
// Return what range demux_cache_dump_set() would (probably) yield. This is a
4751
// conservative amount (in addition to internal consistency of this code, it
4752
// depends on what a player will do with the resulting file).
4753
// Use for_end==true to get the end of dumping, other the start.
4754
// Returns NOPTS if nothing was found.
4755
double demux_probe_cache_dump_target(struct demuxer *demuxer, double pts,
4756
                                     bool for_end)
4757
922
{
4758
922
    struct demux_internal *in = demuxer->in;
4759
922
    mp_assert(demuxer == in->d_user);
4760
4761
922
    double res = MP_NOPTS_VALUE;
4762
922
    if (pts == MP_NOPTS_VALUE)
4763
611
        return pts;
4764
4765
311
    mp_mutex_lock(&in->lock);
4766
4767
311
    pts = MP_ADD_PTS(pts, -in->ts_offset);
4768
4769
    // (When determining the end, look before the keyframe at pts, so subtract
4770
    // an arbitrary amount to round down.)
4771
311
    double seek_pts = for_end ? pts - 0.001 : pts;
4772
311
    int flags = 0;
4773
311
    struct demux_cached_range *r = find_cache_seek_range(in, seek_pts, flags);
4774
311
    if (r) {
4775
133
        if (!for_end)
4776
110
            adjust_cache_seek_target(in, r, &pts, &flags);
4777
4778
133
        double t[STREAM_TYPE_COUNT];
4779
532
        for (int n = 0; n < STREAM_TYPE_COUNT; n++)
4780
399
            t[n] = MP_NOPTS_VALUE;
4781
4782
399
        for (int n = 0; n < in->num_streams; n++) {
4783
266
            struct demux_stream *ds = in->streams[n]->ds;
4784
266
            struct demux_queue *q = r->streams[n];
4785
4786
266
            struct demux_packet *dp = find_seek_target(q, pts, flags);
4787
266
            if (dp) {
4788
238
                if (for_end) {
4789
45
                    while (dp) {
4790
45
                        double pdts = MP_PTS_OR_DEF(dp->dts, dp->pts);
4791
4792
45
                        if (pdts != MP_NOPTS_VALUE && pdts >= pts && dp->keyframe)
4793
41
                            break;
4794
4795
4
                        t[ds->type] = MP_PTS_MAX(t[ds->type], pdts);
4796
4797
4
                        dp = dp->next;
4798
4
                    }
4799
197
                } else {
4800
197
                    double start;
4801
197
                    compute_keyframe_times(dp, &start, NULL);
4802
197
                    start = MP_PTS_MAX(start, r->seek_start);
4803
197
                    t[ds->type] = MP_PTS_MAX(t[ds->type], start);
4804
197
                }
4805
238
            }
4806
266
        }
4807
4808
133
        res = t[STREAM_VIDEO];
4809
133
        if (res == MP_NOPTS_VALUE)
4810
46
            res = t[STREAM_AUDIO];
4811
133
        if (res == MP_NOPTS_VALUE) {
4812
76
            for (int n = 0; n < STREAM_TYPE_COUNT; n++) {
4813
57
                res = t[n];
4814
57
                if (res != MP_NOPTS_VALUE)
4815
0
                    break;
4816
57
            }
4817
19
        }
4818
133
    }
4819
4820
311
    res = MP_ADD_PTS(res, in->ts_offset);
4821
4822
311
    mp_mutex_unlock(&in->lock);
4823
4824
311
    return res;
4825
922
}
4826
4827
// Used by demuxers to report the amount of transferred bytes. This is for
4828
// streams which circumvent demuxer->stream (stream statistics are handled by
4829
// demux.c itself).
4830
void demux_report_unbuffered_read_bytes(struct demuxer *demuxer, int64_t new)
4831
2.15M
{
4832
2.15M
    struct demux_internal *in = demuxer->in;
4833
2.15M
    mp_assert(demuxer == in->d_thread);
4834
4835
2.15M
    in->slave_unbuffered_read_bytes += new;
4836
2.15M
}
4837
4838
// Return bytes read since last query. It's a hack because it works only if
4839
// the demuxer thread is disabled.
4840
int64_t demux_get_bytes_read_hack(struct demuxer *demuxer)
4841
2.15M
{
4842
2.15M
    struct demux_internal *in = demuxer->in;
4843
4844
    // Required because demuxer==in->d_user, and we access in->d_thread.
4845
    // Locking won't solve this, because we also need to access struct stream.
4846
2.15M
    mp_assert(!in->threading);
4847
4848
2.15M
    update_bytes_read(in);
4849
4850
2.15M
    int64_t res = in->hack_unbuffered_read_bytes;
4851
2.15M
    in->hack_unbuffered_read_bytes = 0;
4852
2.15M
    return res;
4853
2.15M
}
4854
4855
void demux_get_bitrate_stats(struct demuxer *demuxer, double *rates)
4856
208
{
4857
208
    struct demux_internal *in = demuxer->in;
4858
208
    mp_assert(demuxer == in->d_user);
4859
4860
208
    mp_mutex_lock(&in->lock);
4861
4862
832
    for (int n = 0; n < STREAM_TYPE_COUNT; n++)
4863
624
        rates[n] = -1;
4864
451
    for (int n = 0; n < in->num_streams; n++) {
4865
243
        struct demux_stream *ds = in->streams[n]->ds;
4866
243
        if (ds->selected && ds->bitrate >= 0)
4867
4
            rates[ds->type] = MPMAX(0, rates[ds->type]) + ds->bitrate;
4868
243
    }
4869
4870
208
    mp_mutex_unlock(&in->lock);
4871
208
}
4872
4873
void demux_get_reader_state(struct demuxer *demuxer, struct demux_reader_state *r)
4874
19.4M
{
4875
19.4M
    struct demux_internal *in = demuxer->in;
4876
19.4M
    mp_assert(demuxer == in->d_user);
4877
4878
19.4M
    mp_mutex_lock(&in->lock);
4879
4880
19.4M
    *r = (struct demux_reader_state){
4881
19.4M
        .eof = in->eof,
4882
19.4M
        .ts_info = {
4883
19.4M
            .reader = MP_NOPTS_VALUE,
4884
19.4M
            .end = MP_NOPTS_VALUE,
4885
19.4M
            .duration = -1,
4886
19.4M
        },
4887
19.4M
        .total_bytes = in->total_bytes,
4888
19.4M
        .seeking = in->seeking_in_progress,
4889
19.4M
        .low_level_seeks = in->low_level_seeks,
4890
19.4M
        .ts_last = in->demux_ts,
4891
19.4M
        .bytes_per_second = in->bytes_per_second,
4892
19.4M
        .byte_level_seeks = in->byte_level_seeks,
4893
19.4M
        .file_cache_bytes = in->cache ? demux_cache_get_size(in->cache) : -1,
4894
19.4M
    };
4895
19.4M
    bool any_packets = false;
4896
77.8M
    for (int n = 0; n < STREAM_TYPE_COUNT; n++) {
4897
58.3M
        r->ts_per_stream[n] = r->ts_info;
4898
58.3M
    }
4899
54.6M
    for (int n = 0; n < in->num_streams; n++) {
4900
35.2M
        struct demux_stream *ds = in->streams[n]->ds;
4901
35.2M
        if (ds->eager && !(!ds->queue->head && ds->eof) && !ds->ignore_eof) {
4902
9.66M
            r->underrun |= !ds->reader_head && !ds->eof && !ds->still_image;
4903
9.66M
            any_packets |= !!ds->reader_head;
4904
4905
9.66M
            double ts_reader = ds->base_ts;
4906
9.66M
            double ts_end = ds->queue->last_ts;
4907
9.66M
            double ts_duration = -1;
4908
9.66M
            if (ts_reader != MP_NOPTS_VALUE && ts_reader <= ts_end)
4909
3.83M
                ts_duration = ts_end - ts_reader;
4910
4911
9.66M
            struct demux_ctrl_ts_info *i = &r->ts_per_stream[ds->type];
4912
9.66M
            i->reader = MP_PTS_MIN(i->reader, ts_reader);
4913
9.66M
            i->end = MP_PTS_MIN(i->end, ts_end);
4914
9.66M
            i->duration = ts_duration;
4915
9.66M
        }
4916
35.2M
        r->fw_bytes += get_forward_buffered_bytes(ds);
4917
35.2M
    }
4918
19.4M
    struct demux_ctrl_ts_info *ots = &r->ts_info;
4919
    // find stream type with lowest duration and use its state
4920
77.8M
    for (int n = 0; n < STREAM_TYPE_COUNT; n++) {
4921
58.3M
        struct demux_ctrl_ts_info *ts = &r->ts_per_stream[n];
4922
58.3M
        if (r->ts_info.duration != -1) {
4923
            // skip if timestamps unknown
4924
6.48M
            if (ts->duration == -1)
4925
6.14M
                continue;
4926
            // skip if we already know of a smaller cached stream
4927
342k
            if (ts->duration > ots->duration)
4928
80.0k
                continue;
4929
            // skip empty subtitle streams when other streams exist
4930
262k
            if (n == STREAM_SUB && ts->duration == 0.0)
4931
0
                continue;
4932
262k
        }
4933
52.1M
        ots->duration = ts->duration;
4934
52.1M
        ots->reader = ts->reader;
4935
52.1M
        ots->end = ts->end;
4936
52.1M
    }
4937
19.4M
    r->idle = (!in->reading && !r->underrun) || r->eof;
4938
19.4M
    r->underrun &= !r->idle && in->threading;
4939
19.4M
    ots->reader = MP_ADD_PTS(ots->reader, in->ts_offset);
4940
19.4M
    ots->end = MP_ADD_PTS(ots->end, in->ts_offset);
4941
19.4M
    if (ots->reader != MP_NOPTS_VALUE && ots->reader <= ots->end)
4942
3.48M
        ots->duration = ots->end - ots->reader;
4943
19.4M
    if (in->seeking || !any_packets)
4944
15.9M
        ots->duration = 0;
4945
38.9M
    for (int n = 0; n < MPMIN(in->num_ranges, MAX_SEEK_RANGES); n++) {
4946
19.4M
        struct demux_cached_range *range = in->ranges[n];
4947
19.4M
        if (range->seek_start != MP_NOPTS_VALUE) {
4948
224k
            r->seek_ranges[r->num_seek_ranges++] =
4949
224k
                (struct demux_seek_range){
4950
224k
                    .start = MP_ADD_PTS(range->seek_start, in->ts_offset),
4951
224k
                    .end = MP_ADD_PTS(range->seek_end, in->ts_offset),
4952
224k
                };
4953
224k
            r->bof_cached |= range->is_bof;
4954
224k
            r->eof_cached |= range->is_eof;
4955
224k
        }
4956
19.4M
    }
4957
4958
19.4M
    mp_mutex_unlock(&in->lock);
4959
19.4M
}
4960
4961
bool demux_cancel_test(struct demuxer *demuxer)
4962
61.0M
{
4963
61.0M
    return mp_cancel_test(demuxer->cancel);
4964
61.0M
}
4965
4966
// Returns true if a blocking read should be aborted as soon as possible,
4967
// because its result will be discarded anyway.
4968
bool demux_read_interrupted(struct demuxer *demuxer)
4969
22.2M
{
4970
22.2M
    struct demux_internal *in = demuxer->in;
4971
22.2M
    return atomic_load_explicit(&in->seeking, memory_order_relaxed) ||
4972
22.2M
           atomic_load_explicit(&in->thread_terminate, memory_order_relaxed) ||
4973
22.2M
           demux_cancel_test(demuxer);
4974
22.2M
}
4975
4976
struct demux_chapter *demux_copy_chapter_data(struct demux_chapter *c, int num)
4977
229k
{
4978
229k
    struct demux_chapter *new = talloc_array(NULL, struct demux_chapter, num);
4979
289k
    for (int n = 0; n < num; n++) {
4980
60.1k
        new[n] = c[n];
4981
60.1k
        new[n].metadata = mp_tags_dup(new, new[n].metadata);
4982
60.1k
    }
4983
229k
    return new;
4984
229k
}
4985
4986
static void visit_tags(void *ctx, void (*visit)(void *ctx, void *ta, char **s),
4987
                       struct mp_tags *tags)
4988
966k
{
4989
1.23M
    for (int n = 0; n < (tags ? tags->num_keys : 0); n++)
4990
270k
        visit(ctx, tags, &tags->values[n]);
4991
966k
}
4992
4993
static void visit_meta(struct demuxer *demuxer, void *ctx,
4994
                       void (*visit)(void *ctx, void *ta, char **s))
4995
397k
{
4996
397k
    struct demux_internal *in = demuxer->in;
4997
4998
837k
    for (int n = 0; n < in->num_streams; n++) {
4999
440k
        struct sh_stream *sh = in->streams[n];
5000
5001
440k
        visit(ctx, sh, &sh->title);
5002
440k
        visit_tags(ctx, visit, sh->tags);
5003
440k
    }
5004
5005
526k
    for (int n = 0; n < demuxer->num_chapters; n++)
5006
128k
        visit_tags(ctx, visit, demuxer->chapters[n].metadata);
5007
5008
397k
    visit_tags(ctx, visit, demuxer->metadata);
5009
397k
}
5010
5011
5012
static void visit_detect(void *ctx, void *ta, char **s)
5013
581k
{
5014
581k
    char **all = ctx;
5015
5016
581k
    if (*s)
5017
188k
        *all = talloc_asprintf_append_buffer(*all, "%s\n", *s);
5018
581k
}
5019
5020
static void visit_convert(void *ctx, void *ta, char **s)
5021
129k
{
5022
129k
    struct demuxer *demuxer = ctx;
5023
129k
    struct demux_internal *in = demuxer->in;
5024
5025
129k
    if (!*s)
5026
28.9k
        return;
5027
5028
100k
    bstr data = bstr0(*s);
5029
100k
    bstr conv = mp_iconv_to_utf8(in->log, data, in->meta_charset,
5030
100k
                                 MP_ICONV_VERBOSE);
5031
100k
    if (conv.start && conv.start != data.start) {
5032
67.5k
        char *ns = conv.start; // 0-termination is guaranteed
5033
        // (The old string might not be an alloc, but if it is, it's a talloc
5034
        // child, and will not leak, even if it stays allocated uselessly.)
5035
67.5k
        *s = ns;
5036
67.5k
        talloc_steal(ta, *s);
5037
67.5k
    }
5038
100k
}
5039
5040
static void demux_convert_tags_charset(struct demuxer *demuxer)
5041
369k
{
5042
369k
    struct demux_internal *in = demuxer->in;
5043
5044
369k
    char *cp = demuxer->opts->meta_cp;
5045
369k
    if (!cp || mp_charset_is_utf8(cp))
5046
0
        return;
5047
5048
369k
    char *data = talloc_strdup(NULL, "");
5049
369k
    visit_meta(demuxer, &data, visit_detect);
5050
5051
369k
    in->meta_charset = (char *)mp_charset_guess(in, in->log, bstr0(data), cp, 0);
5052
369k
    if (in->meta_charset && !mp_charset_is_utf8(in->meta_charset)) {
5053
28.7k
        MP_INFO(demuxer, "Using tag charset: %s\n", in->meta_charset);
5054
28.7k
        visit_meta(demuxer, demuxer, visit_convert);
5055
28.7k
    }
5056
5057
369k
    talloc_free(data);
5058
369k
}
5059
5060
static bool get_demux_sub_opts(int index, const struct m_sub_options **sub)
5061
4.12M
{
5062
4.12M
    if (!demuxer_list[index])
5063
317k
        return false;
5064
3.80M
    *sub = demuxer_list[index]->options;
5065
    return true;
5066
4.12M
}