zvidlib-container 0.5.30

MP4 and WebM muxing and demuxing for zvidlib
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
//! Non-blocking access to a track's compressed samples over a [`ByteSource`]
//! whose reads genuinely suspend, such as a browser `fetch` or HTTP range
//! request (issue #672).
//!
//! [`TrackSampleProvider`] reads through its source from inside
//! [`ExactFrameReader::get`], which is synchronous, so it can only drive a
//! source that resolves on the first poll. This module splits the read in two
//! instead. A [`TrackSampleLoader`] owns the track's index and the source, and
//! loads samples asynchronously into a byte-budgeted cache. The providers it
//! hands out answer a reader's synchronous reads from that cache alone and
//! report [`ErrorKind::WouldBlock`] for a sample that is not loaded yet rather
//! than blocking. A provider remembers every sample it was asked for and did
//! not have, so the caller awaits [`TrackSampleLoader::load_missing`] and asks
//! again:
//!
//! ```ignore
//! let frame = loop {
//!     match reader.get(frame_index, &cancellation) {
//!         Err(error) if error.kind() == ErrorKind::WouldBlock => {
//!             loader.load_missing().await?;
//!         }
//!         result => break result?,
//!     }
//! };
//! ```
//!
//! Both readers leave their state resumable when a provider read fails, so the
//! retry carries on from the sample that was missing rather than decoding the
//! run again from its random-access point. Loading the run a request needs
//! before making it turns those per-sample round trips into one batch:
//! [`ExactFrameReader::decode_positions_for`] and
//! [`AudioSampleReader::packets_for_range`] name it, and
//! [`TrackSampleLoader::load`] loads it together with a playback readahead.
//!
//! [`TrackSampleProvider`]: crate::track::TrackSampleProvider
//! [`ExactFrameReader::get`]: crate::codec::ExactFrameReader::get
//! [`ExactFrameReader::decode_positions_for`]: crate::codec::ExactFrameReader::decode_positions_for
//! [`AudioSampleReader::packets_for_range`]: crate::audio::AudioSampleReader::packets_for_range

use crate::audio::AudioPacketProvider;
use crate::codec::{SampleProvider, TrackKind};
use crate::io::ByteSource;
use crate::media::Codec;
use crate::timeline::{FrameIndex, SampleRange};
use crate::track::{Track, TrackSample, read_exact};
use crate::{Error, ErrorKind, Result};
use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::ops::Range;
use std::sync::{Arc, Mutex, MutexGuard};

/// The most bytes one coalesced read of adjacent samples asks the source for.
///
/// Adjacent samples are fetched together so a run costs one range request
/// rather than one per sample, but a single unbounded request would delay the
/// first sample of the run behind the whole of it.
const MAX_COALESCED_READ_BYTES: u64 = 4 * 1024 * 1024;

/// The most bytes between two samples that a coalesced read reads through and
/// discards rather than splitting into two requests.
///
/// A WebM stores each sample in a block of its own, so a few header bytes
/// separate every sample from the next, and the blocks of other tracks lie
/// between a track's samples wherever the file interleaves them. Reading
/// through a gap this small costs less than another round trip to the source
/// (issue #685).
const MAX_COALESCED_GAP_BYTES: u64 = 16 * 1024;

/// Loads a track's compressed samples from a [`ByteSource`] asynchronously,
/// ahead of the synchronous readers that decode them.
///
/// The loader holds the track's index, the source and a cache of loaded
/// samples bounded by `budget_bytes`, evicting the least recently used
/// samples once it is full. [`Self::sample_provider`] and
/// [`Self::audio_packet_provider`] build providers that share the cache, for
/// [`ExactFrameReader::from_provider`] and
/// [`AudioSampleReader::from_provider`]. Those providers never touch the
/// source themselves, so `S` need not be `Send` and its reads may suspend for
/// as long as they like: a browser `fetch` is the case this exists for.
///
/// [`ExactFrameReader::from_provider`]: crate::codec::ExactFrameReader::from_provider
/// [`AudioSampleReader::from_provider`]: crate::audio::AudioSampleReader::from_provider
pub struct TrackSampleLoader<S> {
    track: Track,
    source: S,
    cache: SharedCache,
    /// The cache key of the track's first sample: loaders sharing a cache key
    /// their samples from different bases, so their keys never meet.
    base: usize,
}

/// A byte-budgeted cache of compressed samples that several
/// [`TrackSampleLoader`]s can share, so loaders over different parts of one
/// track - a lazily indexed WebM's cue spans (issue #692) - hold no more
/// between them than one budget allows.
#[derive(Clone)]
pub struct SampleCache(SharedCache);

impl SampleCache {
    pub fn new(budget_bytes: u64) -> Self {
        Self(SharedCache::new(budget_bytes))
    }

    pub fn budget_bytes(&self) -> u64 {
        self.0.budget_bytes
    }

    /// The compressed bytes every loader sharing the cache holds now, which
    /// never exceeds [`Self::budget_bytes`].
    pub fn resident_bytes(&self) -> u64 {
        self.0.lock().resident_bytes
    }
}

impl<S: ByteSource> TrackSampleLoader<S> {
    /// Fails if `budget_bytes` cannot hold the track's largest sample, which
    /// could then never be loaded. Reads no sample data.
    pub fn new(track: Track, source: S, budget_bytes: u64) -> Result<Self> {
        Self::with_cache(track, source, &SampleCache::new(budget_bytes), 0)
    }

    /// A loader for `track` that loads into `cache`, keying its samples from
    /// `base`. Loaders sharing a cache key their samples from bases far enough
    /// apart that their keys never meet: one loader's `base` plus its sample
    /// count at most the next one's `base`.
    ///
    /// Fails if the cache's budget cannot hold the track's largest sample.
    /// Reads no sample data.
    pub fn with_cache(track: Track, source: S, cache: &SampleCache, base: usize) -> Result<Self> {
        let largest = track
            .samples
            .iter()
            .map(|sample| u64::from(sample.size))
            .max()
            .ok_or_else(|| invalid("an on-demand sample loader requires a nonempty track"))?;
        if cache.budget_bytes() < largest {
            return Err(limit(
                "the sample cache budget cannot hold the track's largest sample",
            ));
        }
        Ok(Self {
            track,
            source,
            cache: cache.0.clone(),
            base,
        })
    }

    /// The cache this loader loads into, to share with another.
    pub fn cache(&self) -> SampleCache {
        SampleCache(self.cache.clone())
    }

    /// Adds samples to the end of the track, as indexing more of it finds
    /// them (issue #692). A provider built before keeps the samples it had;
    /// one built after has these too. Fails, adding none, if the budget cannot
    /// hold the largest of them.
    pub fn append(&mut self, samples: &[TrackSample]) -> Result<()> {
        if samples
            .iter()
            .any(|sample| u64::from(sample.size) > self.cache.budget_bytes)
        {
            return Err(limit(
                "the sample cache budget cannot hold the track's largest sample",
            ));
        }
        self.track.samples.extend_from_slice(samples);
        Ok(())
    }

    pub fn track(&self) -> &Track {
        &self.track
    }

    pub fn source(&self) -> &S {
        &self.source
    }

    /// A [`SampleProvider`] for a video track, answering from this loader's
    /// cache. Fails if the track is not a video track.
    pub fn sample_provider(&self) -> Result<PrefetchedSampleProvider> {
        if self.track.kind != TrackKind::Video {
            return Err(unsupported("a sample provider requires a video track"));
        }
        Ok(PrefetchedSampleProvider {
            presentation_index_by_decode: self.track.presentation_index_by_decode()?,
            random_access: self
                .track
                .samples
                .iter()
                .map(|sample| sample.is_sync)
                .collect(),
            cache: self.cache.clone(),
            base: self.base,
        })
    }

    /// An [`AudioPacketProvider`] for an audio track, answering from this
    /// loader's cache, with `decoded_ranges` giving each packet's decoded
    /// interval in decode order.
    ///
    /// The intervals are the caller's because how they are known without
    /// reading every packet depends on the codec, as [`AudioPacketProvider`]
    /// explains. An AAC track should use [`Self::aac_packet_provider`], an
    /// Opus track [`Self::opus_packet_provider`] and a Vorbis track
    /// [`Self::vorbis_packet_provider`], which derive them for the codec.
    /// Fails if the track is not an audio track or `decoded_ranges` does not
    /// have one interval per sample.
    pub fn audio_packet_provider(
        &self,
        decoded_ranges: Vec<SampleRange>,
    ) -> Result<PrefetchedAudioPacketProvider> {
        if self.track.kind != TrackKind::Audio {
            return Err(unsupported(
                "an audio packet provider requires an audio track",
            ));
        }
        if decoded_ranges.len() != self.track.samples.len() {
            return Err(invalid(
                "an audio packet provider needs one decoded interval per sample",
            ));
        }
        Ok(PrefetchedAudioPacketProvider {
            decoded_ranges,
            check_opus_durations: false,
            cache: self.cache.clone(),
            base: self.base,
        })
    }

    /// An [`AudioPacketProvider`] for an Opus track whose packets' decoded
    /// intervals the caller gives, one per sample in decode order, as
    /// [`Self::opus_packet_provider`] would derive them from the whole
    /// track's sample table: for a track only part of whose table is known
    /// yet (issue #692). Each packet is checked against its interval as
    /// playback reaches it, exactly as there. Reads no packet data. Fails if
    /// the track is not an Opus audio track or `decoded_ranges` does not have
    /// one interval per sample.
    pub fn opus_packet_provider_with_ranges(
        &self,
        decoded_ranges: Vec<SampleRange>,
    ) -> Result<PrefetchedAudioPacketProvider> {
        if self.track.kind != TrackKind::Audio || self.track.codec != Codec::Opus {
            return Err(unsupported(
                "an Opus audio packet provider requires an Opus audio track",
            ));
        }
        let mut provider = self.audio_packet_provider(decoded_ranges)?;
        provider.check_opus_durations = true;
        Ok(provider)
    }

    /// An [`AudioPacketProvider`] for an Opus track, answering from this
    /// loader's cache, without reading every packet to learn its interval.
    ///
    /// Each packet's decoded interval is its sample-table duration, except
    /// the last packet's, which comes from its own table of contents: a muxer
    /// trims the stream's end by shortening that duration. Only that packet's
    /// first two bytes are read here. The table is then checked a packet at a
    /// time, as playback reaches each one: a packet whose table of contents
    /// disagrees with its duration is read as [`ErrorKind::MalformedMedia`],
    /// so a track whose intervals would differ from the ones
    /// [`Track::to_encoded_audio_samples`] gives is refused rather than
    /// played out of time. Fails if the track is not an Opus audio track.
    pub async fn opus_packet_provider(&self) -> Result<PrefetchedAudioPacketProvider> {
        if self.track.kind != TrackKind::Audio || self.track.codec != Codec::Opus {
            return Err(unsupported(
                "an Opus audio packet provider requires an Opus audio track",
            ));
        }
        // `new` refuses an empty track.
        let last = &self.track.samples[self.track.samples.len() - 1];
        let mut head = [0_u8; 2];
        let head = &mut head[..(last.size as usize).min(2)];
        read_exact(&self.source, last.offset, head).await?;
        let decoded_ranges = self
            .track
            .opus_decoded_ranges(crate::opus::opus_packet_samples(head)?)?;
        self.opus_packet_provider_with_ranges(decoded_ranges)
    }

    /// An [`AudioPacketProvider`] for an AAC track, answering from this
    /// loader's cache, with each packet's decoded interval taken from the
    /// track's sample durations.
    ///
    /// The intervals are the ones [`TrackAudioPacketProvider`] and
    /// [`Track::to_encoded_audio_samples`] give the same track, and
    /// building them reads no packet data. Fails if the track is not an AAC
    /// audio track: Opus tracks use [`Self::opus_packet_provider`], and Vorbis
    /// tracks [`Self::vorbis_packet_provider`].
    ///
    /// [`TrackAudioPacketProvider`]: crate::track::TrackAudioPacketProvider
    pub fn aac_packet_provider(&self) -> Result<PrefetchedAudioPacketProvider> {
        if self.track.kind != TrackKind::Audio || self.track.codec != Codec::Aac {
            return Err(unsupported(
                "an AAC audio packet provider requires an AAC audio track",
            ));
        }
        let decoded_ranges = self
            .track
            .aac_decoded_ranges(self.track.audio_sample_rate()?)?;
        self.audio_packet_provider(decoded_ranges)
    }

    /// An [`AudioPacketProvider`] for a Vorbis track, answering from this
    /// loader's cache, without reading any packet to learn its interval.
    ///
    /// A Vorbis packet decodes to a quarter of its block size plus a quarter
    /// of the previous packet's, and its block size is named by the mode
    /// number in its first byte. [`crate::WebmDemuxer`] reads that byte while
    /// scanning each block's header and records it as
    /// [`Track::vorbis_packet_heads`], so the intervals - the ones
    /// [`Track::to_encoded_audio_samples`] gives - come from the index
    /// alone, and a seek needs no earlier packet. Fails if the track is not a
    /// Vorbis audio track, or does not record its packets' first bytes.
    pub fn vorbis_packet_provider(&self) -> Result<PrefetchedAudioPacketProvider> {
        if self.track.kind != TrackKind::Audio || self.track.codec != Codec::Vorbis {
            return Err(unsupported(
                "a Vorbis audio packet provider requires a Vorbis audio track",
            ));
        }
        let decoded_ranges = self.track.vorbis_decoded_ranges()?;
        self.audio_packet_provider(decoded_ranges)
    }

    /// The smallest budget an [`AudioSampleReader`] over `packets`, decoding
    /// `preroll_packets` packets ahead of the first one a request needs, can
    /// make progress through: the largest run of a packet that decodes
    /// samples together with its preroll packets.
    ///
    /// The reader keeps nothing it decodes as preroll, nor a packet that
    /// decodes no samples, so a request that resets the decoder must find its
    /// first packet and every preroll packet before it loaded at once. With
    /// less than this, the loader loads the same prefix of such a run on
    /// every [`Self::load`] and the reader reports
    /// [`ErrorKind::WouldBlock`] for the rest of it each time (issue #694).
    ///
    /// [`AudioSampleReader`]: crate::audio::AudioSampleReader
    pub fn audio_budget_floor(
        &self,
        packets: &PrefetchedAudioPacketProvider,
        preroll_packets: usize,
    ) -> u64 {
        let mut prefix = Vec::with_capacity(self.track.samples.len() + 1);
        prefix.push(0_u64);
        for sample in &self.track.samples {
            prefix.push(prefix[prefix.len() - 1] + u64::from(sample.size));
        }
        (0..packets.len())
            .filter(|&index| !packets.decoded_range(index).is_empty())
            .map(|index| prefix[index + 1] - prefix[index.saturating_sub(preroll_packets)])
            .max()
            .unwrap_or(0)
    }

    /// Fails with [`ErrorKind::ResourceLimit`] if the budget is below
    /// [`Self::audio_budget_floor`], so a reader over `packets` could never
    /// load the packets one of its requests decodes. Reads no packet data.
    pub fn check_audio_budget(
        &self,
        packets: &PrefetchedAudioPacketProvider,
        preroll_packets: usize,
    ) -> Result<()> {
        if self.cache.budget_bytes < self.audio_budget_floor(packets, preroll_packets) {
            return Err(limit(
                "the sample cache budget cannot hold an audio packet together with its preroll \
                 packets",
            ));
        }
        Ok(())
    }

    /// Loads every sample in `required` that is not already loaded, then up
    /// to `readahead` samples after it, as far as the budget allows.
    ///
    /// `required` is clamped to the track. Adjacent samples stored together,
    /// or separated only by a few kilobytes such as a WebM's block headers,
    /// are read together. The samples loaded here are the most recently used,
    /// so making room for them evicts other samples first.
    ///
    /// A `required` run larger than the whole budget - the walk to a frame
    /// deep inside a long group of pictures - is loaded from its start for as
    /// far as it fits, with no readahead. The reader decodes that much, reports
    /// [`ErrorKind::WouldBlock`] for the next sample, and resumes from there,
    /// so the run streams through the budget over several loads rather than
    /// having to fit in it at once.
    pub async fn load(&self, required: Range<usize>, readahead: usize) -> Result<()> {
        let len = self.track.samples.len();
        let required_end = required.end.min(len);
        let start = required.start.min(required_end);
        let mut batch_bytes = 0_u64;
        let mut end = start;
        while end < len && (end < required_end || end - required_end < readahead) {
            let size = u64::from(self.track.samples[end].size);
            if batch_bytes + size > self.cache.budget_bytes {
                break;
            }
            batch_bytes += size;
            end += 1;
        }
        self.fetch(start..end).await
    }

    /// Loads every sample a provider was asked for and did not have since the
    /// last call, returning how many that was.
    ///
    /// This is what a caller awaits after a reader reports
    /// [`ErrorKind::WouldBlock`], before asking the reader again.
    pub async fn load_missing(&self) -> Result<usize> {
        let missing = self.take_missing();
        let count = missing.len();
        let mut indexes = missing.into_iter().peekable();
        while let Some(start) = indexes.next() {
            let mut end = start + 1;
            while indexes.next_if_eq(&end).is_some() {
                end += 1;
            }
            self.load(start..end, 0).await?;
        }
        Ok(count)
    }

    /// Forgets the samples providers have reported missing, as a seek does:
    /// what the old position needed is no longer worth loading.
    pub fn clear_missing(&self) {
        self.take_missing();
    }

    /// Takes the decode indexes of this loader's samples that providers have
    /// reported missing, leaving those of any other loader sharing the cache.
    fn take_missing(&self) -> Vec<usize> {
        let mut cache = self.cache.lock();
        let own: Vec<usize> = cache
            .missing
            .range(self.base..self.base + self.track.samples.len())
            .copied()
            .collect();
        for key in &own {
            cache.missing.remove(key);
        }
        own.into_iter().map(|key| key - self.base).collect()
    }

    pub fn is_loaded(&self, decode_index: usize) -> bool {
        self.cache
            .lock()
            .samples
            .contains_key(&(self.base + decode_index))
    }

    /// The compressed bytes currently held, which never exceeds
    /// [`Self::budget_bytes`]: by every loader sharing the cache.
    pub fn resident_bytes(&self) -> u64 {
        self.cache.lock().resident_bytes
    }

    pub fn budget_bytes(&self) -> u64 {
        self.cache.budget_bytes
    }

    /// Loads the samples of `range` that are not resident and marks the rest
    /// as just used, in order, so the whole range ends up the most recent.
    ///
    /// The cache is never locked across a read, so a provider can still
    /// answer a reader while a load is waiting on the source.
    async fn fetch(&self, range: Range<usize>) -> Result<()> {
        let samples = &self.track.samples;
        let mut index = range.start;
        while index < range.end {
            if self.cache.lock().touch(self.base + index) {
                index += 1;
                continue;
            }
            let offset = samples[index].offset;
            let mut run_end = index + 1;
            // The bytes from the run's first sample to the end of its last.
            let mut run_bytes = u64::from(samples[index].size);
            while run_end < range.end && !self.is_loaded(run_end) {
                let next = &samples[run_end];
                let Some(gap) = next.offset.checked_sub(offset + run_bytes) else {
                    break;
                };
                let next_bytes = run_bytes + gap + u64::from(next.size);
                if gap > MAX_COALESCED_GAP_BYTES || next_bytes > MAX_COALESCED_READ_BYTES {
                    break;
                }
                run_bytes = next_bytes;
                run_end += 1;
            }
            let mut bytes = vec![
                0_u8;
                usize::try_from(run_bytes).map_err(|_| limit(
                    "coalesced sample read cannot be represented"
                ))?
            ];
            read_exact(&self.source, offset, &mut bytes).await?;
            let mut cache = self.cache.lock();
            for (decode_index, sample) in samples.iter().enumerate().take(run_end).skip(index) {
                let start = (sample.offset - offset) as usize;
                cache.insert(
                    self.base + decode_index,
                    Arc::from(&bytes[start..start + sample.size as usize]),
                );
            }
            index = run_end;
        }
        Ok(())
    }
}

/// A [`SampleProvider`] that answers from a [`TrackSampleLoader`]'s cache and
/// reports [`ErrorKind::WouldBlock`] for a sample that is not loaded yet.
pub struct PrefetchedSampleProvider {
    presentation_index_by_decode: Vec<u64>,
    random_access: Vec<bool>,
    cache: SharedCache,
    /// The cache key of the first sample; see [`TrackSampleLoader::with_cache`].
    base: usize,
}

impl SampleProvider for PrefetchedSampleProvider {
    fn len(&self) -> usize {
        self.random_access.len()
    }

    fn is_random_access(&self, decode_index: usize) -> bool {
        self.random_access[decode_index]
    }

    fn presentation_index(&self, decode_index: usize) -> FrameIndex {
        FrameIndex(self.presentation_index_by_decode[decode_index])
    }

    fn read(&self, decode_index: usize) -> Result<Cow<'_, [u8]>> {
        if decode_index >= self.len() {
            return Err(invalid("sample index is out of range"));
        }
        self.cache.read(self.base + decode_index)
    }
}

/// An [`AudioPacketProvider`] that answers from a [`TrackSampleLoader`]'s
/// cache and reports [`ErrorKind::WouldBlock`] for a packet that is not
/// loaded yet.
pub struct PrefetchedAudioPacketProvider {
    decoded_ranges: Vec<SampleRange>,
    /// Whether each packet is an Opus packet whose interval came from the
    /// sample table, so its own table of contents must agree with it.
    check_opus_durations: bool,
    cache: SharedCache,
    /// The cache key of the first packet; see [`TrackSampleLoader::with_cache`].
    base: usize,
}

impl AudioPacketProvider for PrefetchedAudioPacketProvider {
    fn len(&self) -> usize {
        self.decoded_ranges.len()
    }

    fn decoded_range(&self, index: usize) -> SampleRange {
        self.decoded_ranges[index]
    }

    fn read(&self, index: usize) -> Result<Cow<'_, [u8]>> {
        if index >= self.len() {
            return Err(invalid("sample index is out of range"));
        }
        let packet = self.cache.read(self.base + index)?;
        if self.check_opus_durations
            && u64::from(crate::opus::opus_packet_samples(&packet)?)
                != self.decoded_ranges[index].len()
        {
            return Err(Error::new(
                ErrorKind::MalformedMedia,
                "an Opus packet's duration disagrees with the track's sample table",
            ));
        }
        Ok(packet)
    }
}

/// The cache a [`TrackSampleLoader`] fills and its providers read, shared
/// between them.
#[derive(Clone)]
struct SharedCache {
    state: Arc<Mutex<CacheState>>,
    budget_bytes: u64,
}

struct CacheState {
    /// Loaded samples by decode index, with the use they were last touched at.
    samples: HashMap<usize, (Arc<[u8]>, u64)>,
    /// The same samples by the use they were last touched at, oldest first.
    by_use: BTreeMap<u64, usize>,
    next_use: u64,
    resident_bytes: u64,
    budget_bytes: u64,
    /// Samples a provider was asked for and did not have.
    missing: BTreeSet<usize>,
}

impl SharedCache {
    fn new(budget_bytes: u64) -> Self {
        Self {
            state: Arc::new(Mutex::new(CacheState {
                samples: HashMap::new(),
                by_use: BTreeMap::new(),
                next_use: 0,
                resident_bytes: 0,
                budget_bytes,
                missing: BTreeSet::new(),
            })),
            budget_bytes,
        }
    }

    fn lock(&self) -> MutexGuard<'_, CacheState> {
        // Nothing holding the lock can leave the cache inconsistent partway,
        // so a panic elsewhere while it was held does not invalidate it.
        self.state
            .lock()
            .unwrap_or_else(|poison| poison.into_inner())
    }

    fn read(&self, index: usize) -> Result<Cow<'static, [u8]>> {
        let mut state = self.lock();
        if state.touch(index) {
            return Ok(Cow::Owned(state.samples[&index].0.to_vec()));
        }
        state.missing.insert(index);
        Err(Error::new(
            ErrorKind::WouldBlock,
            "the compressed sample is not loaded yet",
        ))
    }
}

impl CacheState {
    /// Marks a resident sample as the most recently used; `false` if it is
    /// not resident.
    fn touch(&mut self, index: usize) -> bool {
        let next_use = self.next_use;
        let Some((_, last_use)) = self.samples.get_mut(&index) else {
            return false;
        };
        self.by_use.remove(last_use);
        *last_use = next_use;
        self.by_use.insert(next_use, index);
        self.next_use += 1;
        true
    }

    fn insert(&mut self, index: usize, bytes: Arc<[u8]>) {
        if self.touch(index) {
            // A concurrent load got here first.
            return;
        }
        self.resident_bytes += bytes.len() as u64;
        self.samples.insert(index, (bytes, self.next_use));
        self.by_use.insert(self.next_use, index);
        self.next_use += 1;
        self.missing.remove(&index);
        while self.resident_bytes > self.budget_bytes {
            let Some((_, oldest)) = self.by_use.pop_first() else {
                break;
            };
            if let Some((evicted, _)) = self.samples.remove(&oldest) {
                self.resident_bytes -= evicted.len() as u64;
            }
        }
    }
}

fn invalid(message: &str) -> Error {
    Error::new(ErrorKind::InvalidInput, message)
}

fn limit(message: &str) -> Error {
    Error::new(ErrorKind::ResourceLimit, message)
}

fn unsupported(message: &str) -> Error {
    Error::new(ErrorKind::Unsupported, message)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::codec::SampleDependency;
    use crate::io::{IoFuture, MemorySource};
    use crate::track::TrackSample;
    use std::cell::Cell;
    use std::future::Future;
    use std::pin::Pin;
    use std::task::{Context, Poll, Waker};

    /// A source whose every read suspends once before completing, the way a
    /// network fetch does, and counts the reads it was asked for.
    struct SuspendingSource {
        inner: MemorySource,
        reads: Cell<usize>,
    }

    impl ByteSource for SuspendingSource {
        fn len(&self) -> Option<u64> {
            self.inner.len()
        }

        fn read_at<'a>(&'a self, offset: u64, destination: &'a mut [u8]) -> IoFuture<'a, usize> {
            self.reads.set(self.reads.get() + 1);
            Box::pin(async move {
                YieldOnce(false).await;
                self.inner.read_at(offset, destination).await
            })
        }
    }

    struct YieldOnce(bool);

    impl Future for YieldOnce {
        type Output = ();

        fn poll(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<()> {
            if self.0 {
                Poll::Ready(())
            } else {
                self.0 = true;
                context.waker().wake_by_ref();
                Poll::Pending
            }
        }
    }

    fn block_on<T>(future: impl Future<Output = T>) -> T {
        let mut future = std::pin::pin!(future);
        let mut context = Context::from_waker(Waker::noop());
        loop {
            if let Poll::Ready(value) = future.as_mut().poll(&mut context) {
                return value;
            }
        }
    }

    /// A video track of `sizes.len()` samples stored back to back from
    /// offset 0, every fourth a random-access point, each filled with its own
    /// decode index.
    fn track_and_source(sizes: &[u32]) -> (Track, SuspendingSource) {
        let gaps = vec![0; sizes.len()];
        gapped_track_and_source(sizes, &gaps)
    }

    /// [`track_and_source`] with `gaps[index]` bytes of something else, such
    /// as a WebM block header, stored before each sample.
    fn gapped_track_and_source(sizes: &[u32], gaps: &[usize]) -> (Track, SuspendingSource) {
        let mut bytes = Vec::new();
        let mut samples = Vec::new();
        for (index, &size) in sizes.iter().enumerate() {
            bytes.extend(std::iter::repeat_n(0xff, gaps[index]));
            samples.push(TrackSample {
                offset: bytes.len() as u64,
                size,
                dts: index as u64,
                pts: index as i64,
                duration: 1,
                dependency: SampleDependency::INDEPENDENT,
                is_sync: index % 4 == 0,
            });
            bytes.extend(std::iter::repeat_n(index as u8, size as usize));
        }
        let track = Track {
            id: 1,
            kind: TrackKind::Video,
            codec: Codec::Hevc,
            timescale: 30,
            duration: sizes.len() as u64,
            dimensions: None,
            channels: None,
            sample_rate: None,
            language: None,
            decoder_config: Vec::new(),
            edits: Vec::new(),
            presentation_order: (0..sizes.len()).collect(),
            samples,
            vorbis_packet_heads: Vec::new(),
        };
        let source = SuspendingSource {
            inner: MemorySource::new(bytes),
            reads: Cell::new(0),
        };
        (track, source)
    }

    #[test]
    fn a_provider_reports_an_unloaded_sample_instead_of_blocking() {
        let (track, source) = track_and_source(&[10; 8]);
        let loader = TrackSampleLoader::new(track, source, 1_000).unwrap();
        let provider = loader.sample_provider().unwrap();

        let error = provider.read(3).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::WouldBlock);
        assert_eq!(
            loader.source().reads.get(),
            0,
            "the provider touched the source"
        );

        assert_eq!(block_on(loader.load_missing()).unwrap(), 1);
        assert_eq!(provider.read(3).unwrap().as_ref(), &[3; 10]);
        // Nothing is missing any more, so nothing more is loaded.
        assert_eq!(block_on(loader.load_missing()).unwrap(), 0);
    }

    #[test]
    fn loading_a_run_coalesces_contiguous_samples_and_adds_readahead() {
        let (track, source) = track_and_source(&[10; 16]);
        let loader = TrackSampleLoader::new(track, source, 1_000).unwrap();
        let provider = loader.sample_provider().unwrap();

        block_on(loader.load(4..7, 3)).unwrap();
        assert_eq!(loader.source().reads.get(), 1, "the run was not coalesced");
        for index in 4..10 {
            assert_eq!(provider.read(index).unwrap().as_ref(), &[index as u8; 10]);
        }
        assert!(!loader.is_loaded(3));
        assert!(!loader.is_loaded(10));

        // Loading what is already resident reads nothing.
        block_on(loader.load(4..10, 0)).unwrap();
        assert_eq!(loader.source().reads.get(), 1);
    }

    /// Issue #685: samples a few bytes apart, as a WebM's blocks are, are
    /// still read together, while a gap too large to be worth reading through
    /// splits the run.
    #[test]
    fn loading_a_run_reads_through_small_gaps_between_samples() {
        let mut gaps = vec![12; 8];
        gaps[6] = MAX_COALESCED_GAP_BYTES as usize + 1;
        let (track, source) = gapped_track_and_source(&[10; 8], &gaps);
        let loader = TrackSampleLoader::new(track, source, 1_000).unwrap();
        let provider = loader.sample_provider().unwrap();

        block_on(loader.load(0..6, 0)).unwrap();
        assert_eq!(loader.source().reads.get(), 1, "the run was not coalesced");
        block_on(loader.load(0..8, 0)).unwrap();
        assert_eq!(
            loader.source().reads.get(),
            2,
            "the large gap was read through"
        );
        for index in 0..8 {
            assert_eq!(provider.read(index).unwrap().as_ref(), &[index as u8; 10]);
        }
    }

    #[test]
    fn the_cache_stays_within_its_budget_and_evicts_the_least_recently_used() {
        let (track, source) = track_and_source(&[10; 16]);
        let loader = TrackSampleLoader::new(track, source, 40).unwrap();

        block_on(loader.load(0..4, 0)).unwrap();
        assert_eq!(loader.resident_bytes(), 40);
        block_on(loader.load(8..10, 0)).unwrap();
        assert_eq!(loader.resident_bytes(), 40);
        assert!(!loader.is_loaded(0) && !loader.is_loaded(1));
        assert!(loader.is_loaded(2) && loader.is_loaded(3));
        assert!(loader.is_loaded(8) && loader.is_loaded(9));

        // Readahead stops where it would no longer fit beside the request.
        block_on(loader.load(12..14, 10)).unwrap();
        assert!((12..16).all(|index| loader.is_loaded(index)));
        assert_eq!(loader.resident_bytes(), 40);

        // A run larger than the budget loads from its start as far as it fits.
        block_on(loader.load(0..6, 10)).unwrap();
        assert!((0..4).all(|index| loader.is_loaded(index)));
        assert!(!loader.is_loaded(4) && !loader.is_loaded(5));
        assert_eq!(loader.resident_bytes(), 40);
    }

    /// Issue #692: loaders over different parts of a track share one cache,
    /// so together they hold no more than its budget, and each loads only the
    /// samples its own providers missed.
    #[test]
    fn loaders_sharing_a_cache_share_its_budget_and_keep_their_own_samples() {
        let (track, first_source) = track_and_source(&[10; 8]);
        let (_, second_source) = track_and_source(&[10; 8]);
        let part = |range: std::ops::Range<usize>| Track {
            samples: track.samples[range.clone()].to_vec(),
            presentation_order: (0..range.len()).collect(),
            ..track.clone()
        };
        let cache = SampleCache::new(40);
        let first = TrackSampleLoader::with_cache(part(0..4), first_source, &cache, 0).unwrap();
        let second = TrackSampleLoader::with_cache(part(4..8), second_source, &cache, 4).unwrap();
        let first_provider = first.sample_provider().unwrap();
        let second_provider = second.sample_provider().unwrap();

        first_provider.read(1).unwrap_err();
        second_provider.read(1).unwrap_err();
        // Each loader loads only what its own provider missed.
        assert_eq!(block_on(first.load_missing()).unwrap(), 1);
        assert_eq!(first_provider.read(1).unwrap().as_ref(), &[1; 10]);
        assert_eq!(
            second_provider.read(1).unwrap_err().kind(),
            ErrorKind::WouldBlock
        );
        assert_eq!(block_on(second.load_missing()).unwrap(), 1);
        assert_eq!(second_provider.read(1).unwrap().as_ref(), &[5; 10]);

        block_on(first.load(0..4, 0)).unwrap();
        block_on(second.load(0..4, 0)).unwrap();
        assert_eq!(cache.resident_bytes(), 40);
        assert_eq!(first.resident_bytes(), 40);
        assert!((0..4).all(|index| second.is_loaded(index)));
        assert!((0..4).all(|index| !first.is_loaded(index)));
    }

    #[test]
    fn appended_samples_load_like_the_ones_before_them() {
        let (track, source) = track_and_source(&[10; 8]);
        let mut loader = TrackSampleLoader::new(
            Track {
                samples: track.samples[..3].to_vec(),
                presentation_order: (0..3).collect(),
                ..track.clone()
            },
            source,
            1_000,
        )
        .unwrap();
        let before = loader.sample_provider().unwrap();
        loader.append(&track.samples[3..]).unwrap();
        let after = loader.sample_provider().unwrap();
        assert_eq!((before.len(), after.len()), (3, 8));
        block_on(loader.load(2..6, 0)).unwrap();
        assert_eq!(loader.source().reads.get(), 1, "the run was not coalesced");
        assert_eq!(after.read(5).unwrap().as_ref(), &[5; 10]);
        assert_eq!(before.read(2).unwrap().as_ref(), &[2; 10]);

        let mut huge = track.samples[0].clone();
        huge.size = 2_000;
        assert_eq!(
            loader.append(&[huge]).unwrap_err().kind(),
            ErrorKind::ResourceLimit
        );
        assert_eq!(loader.track().samples.len(), 8);
    }

    #[test]
    fn a_budget_smaller_than_the_largest_sample_is_refused() {
        let (track, source) = track_and_source(&[10, 50, 10]);
        let error = TrackSampleLoader::new(track, source, 49)
            .err()
            .expect("the budget cannot hold sample 1");
        assert_eq!(error.kind(), ErrorKind::ResourceLimit);
    }

    #[test]
    fn clearing_missing_samples_forgets_what_an_old_position_needed() {
        let (track, source) = track_and_source(&[10; 8]);
        let loader = TrackSampleLoader::new(track, source, 1_000).unwrap();
        let provider = loader.sample_provider().unwrap();
        provider.read(1).unwrap_err();
        loader.clear_missing();
        assert_eq!(block_on(loader.load_missing()).unwrap(), 0);
        assert_eq!(loader.source().reads.get(), 0);
    }

    #[test]
    fn an_audio_provider_answers_from_the_same_cache() {
        let (mut track, source) = track_and_source(&[4; 4]);
        track.kind = TrackKind::Audio;
        let loader = TrackSampleLoader::new(track, source, 1_000).unwrap();
        assert_eq!(
            loader.sample_provider().err().unwrap().kind(),
            ErrorKind::Unsupported
        );
        let ranges: Vec<_> = (0..4)
            .map(|index| SampleRange::new(index * 1024, (index + 1) * 1024).unwrap())
            .collect();
        assert_eq!(
            loader
                .audio_packet_provider(ranges[..3].to_vec())
                .err()
                .unwrap()
                .kind(),
            ErrorKind::InvalidInput
        );
        let provider = loader.audio_packet_provider(ranges.clone()).unwrap();
        assert_eq!(provider.decoded_range(2), ranges[2]);
        assert_eq!(provider.read(2).unwrap_err().kind(), ErrorKind::WouldBlock);
        block_on(loader.load_missing()).unwrap();
        assert_eq!(provider.read(2).unwrap().as_ref(), &[2; 4]);
    }

    /// Issue #694: the floor is the largest run of a packet that decodes
    /// samples and its preroll packets, so a first packet that decodes nothing,
    /// as a Vorbis stream's does, only counts as another packet's preroll.
    #[test]
    fn an_audio_budget_must_hold_a_packet_with_its_preroll() {
        let (mut track, source) = track_and_source(&[40, 10, 20, 30, 5]);
        track.kind = TrackKind::Audio;
        let loader = TrackSampleLoader::new(track, source, 40).unwrap();
        let mut start = 0;
        let ranges: Vec<_> = [0, 64, 128, 128, 64]
            .into_iter()
            .map(|length| {
                start += length;
                SampleRange::new(start - length, start).unwrap()
            })
            .collect();
        let provider = loader.audio_packet_provider(ranges).unwrap();
        // With no preroll, packet 0's 40 bytes never need to be loaded.
        assert_eq!(loader.audio_budget_floor(&provider, 0), 30);
        // Packets 0 and 1.
        assert_eq!(loader.audio_budget_floor(&provider, 1), 50);
        // Packets 1, 2 and 3 rather than 0, 1 and 2.
        assert_eq!(loader.audio_budget_floor(&provider, 2), 70);
        assert_eq!(loader.audio_budget_floor(&provider, usize::MAX), 105);
        loader.check_audio_budget(&provider, 0).unwrap();
        assert_eq!(
            loader.check_audio_budget(&provider, 1).unwrap_err().kind(),
            ErrorKind::ResourceLimit
        );
    }
}