Skip to main content

zvidlib_container/
prefetch.rs

1//! Non-blocking access to a track's compressed samples over a [`ByteSource`]
2//! whose reads genuinely suspend, such as a browser `fetch` or HTTP range
3//! request (issue #672).
4//!
5//! [`TrackSampleProvider`] reads through its source from inside
6//! [`ExactFrameReader::get`], which is synchronous, so it can only drive a
7//! source that resolves on the first poll. This module splits the read in two
8//! instead. A [`TrackSampleLoader`] owns the track's index and the source, and
9//! loads samples asynchronously into a byte-budgeted cache. The providers it
10//! hands out answer a reader's synchronous reads from that cache alone and
11//! report [`ErrorKind::WouldBlock`] for a sample that is not loaded yet rather
12//! than blocking. A provider remembers every sample it was asked for and did
13//! not have, so the caller awaits [`TrackSampleLoader::load_missing`] and asks
14//! again:
15//!
16//! ```ignore
17//! let frame = loop {
18//!     match reader.get(frame_index, &cancellation) {
19//!         Err(error) if error.kind() == ErrorKind::WouldBlock => {
20//!             loader.load_missing().await?;
21//!         }
22//!         result => break result?,
23//!     }
24//! };
25//! ```
26//!
27//! Both readers leave their state resumable when a provider read fails, so the
28//! retry carries on from the sample that was missing rather than decoding the
29//! run again from its random-access point. Loading the run a request needs
30//! before making it turns those per-sample round trips into one batch:
31//! [`ExactFrameReader::decode_positions_for`] and
32//! [`AudioSampleReader::packets_for_range`] name it, and
33//! [`TrackSampleLoader::load`] loads it together with a playback readahead.
34//!
35//! [`TrackSampleProvider`]: crate::track::TrackSampleProvider
36//! [`ExactFrameReader::get`]: crate::codec::ExactFrameReader::get
37//! [`ExactFrameReader::decode_positions_for`]: crate::codec::ExactFrameReader::decode_positions_for
38//! [`AudioSampleReader::packets_for_range`]: crate::audio::AudioSampleReader::packets_for_range
39
40use crate::audio::AudioPacketProvider;
41use crate::codec::{SampleProvider, TrackKind};
42use crate::io::ByteSource;
43use crate::media::Codec;
44use crate::timeline::{FrameIndex, SampleRange};
45use crate::track::{Track, TrackSample, read_exact};
46use crate::{Error, ErrorKind, Result};
47use std::borrow::Cow;
48use std::collections::{BTreeMap, BTreeSet, HashMap};
49use std::ops::Range;
50use std::sync::{Arc, Mutex, MutexGuard};
51
52/// The most bytes one coalesced read of adjacent samples asks the source for.
53///
54/// Adjacent samples are fetched together so a run costs one range request
55/// rather than one per sample, but a single unbounded request would delay the
56/// first sample of the run behind the whole of it.
57const MAX_COALESCED_READ_BYTES: u64 = 4 * 1024 * 1024;
58
59/// The most bytes between two samples that a coalesced read reads through and
60/// discards rather than splitting into two requests.
61///
62/// A WebM stores each sample in a block of its own, so a few header bytes
63/// separate every sample from the next, and the blocks of other tracks lie
64/// between a track's samples wherever the file interleaves them. Reading
65/// through a gap this small costs less than another round trip to the source
66/// (issue #685).
67const MAX_COALESCED_GAP_BYTES: u64 = 16 * 1024;
68
69/// Loads a track's compressed samples from a [`ByteSource`] asynchronously,
70/// ahead of the synchronous readers that decode them.
71///
72/// The loader holds the track's index, the source and a cache of loaded
73/// samples bounded by `budget_bytes`, evicting the least recently used
74/// samples once it is full. [`Self::sample_provider`] and
75/// [`Self::audio_packet_provider`] build providers that share the cache, for
76/// [`ExactFrameReader::from_provider`] and
77/// [`AudioSampleReader::from_provider`]. Those providers never touch the
78/// source themselves, so `S` need not be `Send` and its reads may suspend for
79/// as long as they like: a browser `fetch` is the case this exists for.
80///
81/// [`ExactFrameReader::from_provider`]: crate::codec::ExactFrameReader::from_provider
82/// [`AudioSampleReader::from_provider`]: crate::audio::AudioSampleReader::from_provider
83pub struct TrackSampleLoader<S> {
84    track: Track,
85    source: S,
86    cache: SharedCache,
87    /// The cache key of the track's first sample: loaders sharing a cache key
88    /// their samples from different bases, so their keys never meet.
89    base: usize,
90}
91
92/// A byte-budgeted cache of compressed samples that several
93/// [`TrackSampleLoader`]s can share, so loaders over different parts of one
94/// track - a lazily indexed WebM's cue spans (issue #692) - hold no more
95/// between them than one budget allows.
96#[derive(Clone)]
97pub struct SampleCache(SharedCache);
98
99impl SampleCache {
100    pub fn new(budget_bytes: u64) -> Self {
101        Self(SharedCache::new(budget_bytes))
102    }
103
104    pub fn budget_bytes(&self) -> u64 {
105        self.0.budget_bytes
106    }
107
108    /// The compressed bytes every loader sharing the cache holds now, which
109    /// never exceeds [`Self::budget_bytes`].
110    pub fn resident_bytes(&self) -> u64 {
111        self.0.lock().resident_bytes
112    }
113}
114
115impl<S: ByteSource> TrackSampleLoader<S> {
116    /// Fails if `budget_bytes` cannot hold the track's largest sample, which
117    /// could then never be loaded. Reads no sample data.
118    pub fn new(track: Track, source: S, budget_bytes: u64) -> Result<Self> {
119        Self::with_cache(track, source, &SampleCache::new(budget_bytes), 0)
120    }
121
122    /// A loader for `track` that loads into `cache`, keying its samples from
123    /// `base`. Loaders sharing a cache key their samples from bases far enough
124    /// apart that their keys never meet: one loader's `base` plus its sample
125    /// count at most the next one's `base`.
126    ///
127    /// Fails if the cache's budget cannot hold the track's largest sample.
128    /// Reads no sample data.
129    pub fn with_cache(track: Track, source: S, cache: &SampleCache, base: usize) -> Result<Self> {
130        let largest = track
131            .samples
132            .iter()
133            .map(|sample| u64::from(sample.size))
134            .max()
135            .ok_or_else(|| invalid("an on-demand sample loader requires a nonempty track"))?;
136        if cache.budget_bytes() < largest {
137            return Err(limit(
138                "the sample cache budget cannot hold the track's largest sample",
139            ));
140        }
141        Ok(Self {
142            track,
143            source,
144            cache: cache.0.clone(),
145            base,
146        })
147    }
148
149    /// The cache this loader loads into, to share with another.
150    pub fn cache(&self) -> SampleCache {
151        SampleCache(self.cache.clone())
152    }
153
154    /// Adds samples to the end of the track, as indexing more of it finds
155    /// them (issue #692). A provider built before keeps the samples it had;
156    /// one built after has these too. Fails, adding none, if the budget cannot
157    /// hold the largest of them.
158    pub fn append(&mut self, samples: &[TrackSample]) -> Result<()> {
159        if samples
160            .iter()
161            .any(|sample| u64::from(sample.size) > self.cache.budget_bytes)
162        {
163            return Err(limit(
164                "the sample cache budget cannot hold the track's largest sample",
165            ));
166        }
167        self.track.samples.extend_from_slice(samples);
168        Ok(())
169    }
170
171    pub fn track(&self) -> &Track {
172        &self.track
173    }
174
175    pub fn source(&self) -> &S {
176        &self.source
177    }
178
179    /// A [`SampleProvider`] for a video track, answering from this loader's
180    /// cache. Fails if the track is not a video track.
181    pub fn sample_provider(&self) -> Result<PrefetchedSampleProvider> {
182        if self.track.kind != TrackKind::Video {
183            return Err(unsupported("a sample provider requires a video track"));
184        }
185        Ok(PrefetchedSampleProvider {
186            presentation_index_by_decode: self.track.presentation_index_by_decode()?,
187            random_access: self
188                .track
189                .samples
190                .iter()
191                .map(|sample| sample.is_sync)
192                .collect(),
193            cache: self.cache.clone(),
194            base: self.base,
195        })
196    }
197
198    /// An [`AudioPacketProvider`] for an audio track, answering from this
199    /// loader's cache, with `decoded_ranges` giving each packet's decoded
200    /// interval in decode order.
201    ///
202    /// The intervals are the caller's because how they are known without
203    /// reading every packet depends on the codec, as [`AudioPacketProvider`]
204    /// explains. An AAC track should use [`Self::aac_packet_provider`], an
205    /// Opus track [`Self::opus_packet_provider`] and a Vorbis track
206    /// [`Self::vorbis_packet_provider`], which derive them for the codec.
207    /// Fails if the track is not an audio track or `decoded_ranges` does not
208    /// have one interval per sample.
209    pub fn audio_packet_provider(
210        &self,
211        decoded_ranges: Vec<SampleRange>,
212    ) -> Result<PrefetchedAudioPacketProvider> {
213        if self.track.kind != TrackKind::Audio {
214            return Err(unsupported(
215                "an audio packet provider requires an audio track",
216            ));
217        }
218        if decoded_ranges.len() != self.track.samples.len() {
219            return Err(invalid(
220                "an audio packet provider needs one decoded interval per sample",
221            ));
222        }
223        Ok(PrefetchedAudioPacketProvider {
224            decoded_ranges,
225            check_opus_durations: false,
226            cache: self.cache.clone(),
227            base: self.base,
228        })
229    }
230
231    /// An [`AudioPacketProvider`] for an Opus track whose packets' decoded
232    /// intervals the caller gives, one per sample in decode order, as
233    /// [`Self::opus_packet_provider`] would derive them from the whole
234    /// track's sample table: for a track only part of whose table is known
235    /// yet (issue #692). Each packet is checked against its interval as
236    /// playback reaches it, exactly as there. Reads no packet data. Fails if
237    /// the track is not an Opus audio track or `decoded_ranges` does not have
238    /// one interval per sample.
239    pub fn opus_packet_provider_with_ranges(
240        &self,
241        decoded_ranges: Vec<SampleRange>,
242    ) -> Result<PrefetchedAudioPacketProvider> {
243        if self.track.kind != TrackKind::Audio || self.track.codec != Codec::Opus {
244            return Err(unsupported(
245                "an Opus audio packet provider requires an Opus audio track",
246            ));
247        }
248        let mut provider = self.audio_packet_provider(decoded_ranges)?;
249        provider.check_opus_durations = true;
250        Ok(provider)
251    }
252
253    /// An [`AudioPacketProvider`] for an Opus track, answering from this
254    /// loader's cache, without reading every packet to learn its interval.
255    ///
256    /// Each packet's decoded interval is its sample-table duration, except
257    /// the last packet's, which comes from its own table of contents: a muxer
258    /// trims the stream's end by shortening that duration. Only that packet's
259    /// first two bytes are read here. The table is then checked a packet at a
260    /// time, as playback reaches each one: a packet whose table of contents
261    /// disagrees with its duration is read as [`ErrorKind::MalformedMedia`],
262    /// so a track whose intervals would differ from the ones
263    /// [`Track::to_encoded_audio_samples`] gives is refused rather than
264    /// played out of time. Fails if the track is not an Opus audio track.
265    pub async fn opus_packet_provider(&self) -> Result<PrefetchedAudioPacketProvider> {
266        if self.track.kind != TrackKind::Audio || self.track.codec != Codec::Opus {
267            return Err(unsupported(
268                "an Opus audio packet provider requires an Opus audio track",
269            ));
270        }
271        // `new` refuses an empty track.
272        let last = &self.track.samples[self.track.samples.len() - 1];
273        let mut head = [0_u8; 2];
274        let head = &mut head[..(last.size as usize).min(2)];
275        read_exact(&self.source, last.offset, head).await?;
276        let decoded_ranges = self
277            .track
278            .opus_decoded_ranges(crate::opus::opus_packet_samples(head)?)?;
279        self.opus_packet_provider_with_ranges(decoded_ranges)
280    }
281
282    /// An [`AudioPacketProvider`] for an AAC track, answering from this
283    /// loader's cache, with each packet's decoded interval taken from the
284    /// track's sample durations.
285    ///
286    /// The intervals are the ones [`TrackAudioPacketProvider`] and
287    /// [`Track::to_encoded_audio_samples`] give the same track, and
288    /// building them reads no packet data. Fails if the track is not an AAC
289    /// audio track: Opus tracks use [`Self::opus_packet_provider`], and Vorbis
290    /// tracks [`Self::vorbis_packet_provider`].
291    ///
292    /// [`TrackAudioPacketProvider`]: crate::track::TrackAudioPacketProvider
293    pub fn aac_packet_provider(&self) -> Result<PrefetchedAudioPacketProvider> {
294        if self.track.kind != TrackKind::Audio || self.track.codec != Codec::Aac {
295            return Err(unsupported(
296                "an AAC audio packet provider requires an AAC audio track",
297            ));
298        }
299        let decoded_ranges = self
300            .track
301            .aac_decoded_ranges(self.track.audio_sample_rate()?)?;
302        self.audio_packet_provider(decoded_ranges)
303    }
304
305    /// An [`AudioPacketProvider`] for a Vorbis track, answering from this
306    /// loader's cache, without reading any packet to learn its interval.
307    ///
308    /// A Vorbis packet decodes to a quarter of its block size plus a quarter
309    /// of the previous packet's, and its block size is named by the mode
310    /// number in its first byte. [`crate::WebmDemuxer`] reads that byte while
311    /// scanning each block's header and records it as
312    /// [`Track::vorbis_packet_heads`], so the intervals - the ones
313    /// [`Track::to_encoded_audio_samples`] gives - come from the index
314    /// alone, and a seek needs no earlier packet. Fails if the track is not a
315    /// Vorbis audio track, or does not record its packets' first bytes.
316    pub fn vorbis_packet_provider(&self) -> Result<PrefetchedAudioPacketProvider> {
317        if self.track.kind != TrackKind::Audio || self.track.codec != Codec::Vorbis {
318            return Err(unsupported(
319                "a Vorbis audio packet provider requires a Vorbis audio track",
320            ));
321        }
322        let decoded_ranges = self.track.vorbis_decoded_ranges()?;
323        self.audio_packet_provider(decoded_ranges)
324    }
325
326    /// The smallest budget an [`AudioSampleReader`] over `packets`, decoding
327    /// `preroll_packets` packets ahead of the first one a request needs, can
328    /// make progress through: the largest run of a packet that decodes
329    /// samples together with its preroll packets.
330    ///
331    /// The reader keeps nothing it decodes as preroll, nor a packet that
332    /// decodes no samples, so a request that resets the decoder must find its
333    /// first packet and every preroll packet before it loaded at once. With
334    /// less than this, the loader loads the same prefix of such a run on
335    /// every [`Self::load`] and the reader reports
336    /// [`ErrorKind::WouldBlock`] for the rest of it each time (issue #694).
337    ///
338    /// [`AudioSampleReader`]: crate::audio::AudioSampleReader
339    pub fn audio_budget_floor(
340        &self,
341        packets: &PrefetchedAudioPacketProvider,
342        preroll_packets: usize,
343    ) -> u64 {
344        let mut prefix = Vec::with_capacity(self.track.samples.len() + 1);
345        prefix.push(0_u64);
346        for sample in &self.track.samples {
347            prefix.push(prefix[prefix.len() - 1] + u64::from(sample.size));
348        }
349        (0..packets.len())
350            .filter(|&index| !packets.decoded_range(index).is_empty())
351            .map(|index| prefix[index + 1] - prefix[index.saturating_sub(preroll_packets)])
352            .max()
353            .unwrap_or(0)
354    }
355
356    /// Fails with [`ErrorKind::ResourceLimit`] if the budget is below
357    /// [`Self::audio_budget_floor`], so a reader over `packets` could never
358    /// load the packets one of its requests decodes. Reads no packet data.
359    pub fn check_audio_budget(
360        &self,
361        packets: &PrefetchedAudioPacketProvider,
362        preroll_packets: usize,
363    ) -> Result<()> {
364        if self.cache.budget_bytes < self.audio_budget_floor(packets, preroll_packets) {
365            return Err(limit(
366                "the sample cache budget cannot hold an audio packet together with its preroll \
367                 packets",
368            ));
369        }
370        Ok(())
371    }
372
373    /// Loads every sample in `required` that is not already loaded, then up
374    /// to `readahead` samples after it, as far as the budget allows.
375    ///
376    /// `required` is clamped to the track. Adjacent samples stored together,
377    /// or separated only by a few kilobytes such as a WebM's block headers,
378    /// are read together. The samples loaded here are the most recently used,
379    /// so making room for them evicts other samples first.
380    ///
381    /// A `required` run larger than the whole budget - the walk to a frame
382    /// deep inside a long group of pictures - is loaded from its start for as
383    /// far as it fits, with no readahead. The reader decodes that much, reports
384    /// [`ErrorKind::WouldBlock`] for the next sample, and resumes from there,
385    /// so the run streams through the budget over several loads rather than
386    /// having to fit in it at once.
387    pub async fn load(&self, required: Range<usize>, readahead: usize) -> Result<()> {
388        let len = self.track.samples.len();
389        let required_end = required.end.min(len);
390        let start = required.start.min(required_end);
391        let mut batch_bytes = 0_u64;
392        let mut end = start;
393        while end < len && (end < required_end || end - required_end < readahead) {
394            let size = u64::from(self.track.samples[end].size);
395            if batch_bytes + size > self.cache.budget_bytes {
396                break;
397            }
398            batch_bytes += size;
399            end += 1;
400        }
401        self.fetch(start..end).await
402    }
403
404    /// Loads every sample a provider was asked for and did not have since the
405    /// last call, returning how many that was.
406    ///
407    /// This is what a caller awaits after a reader reports
408    /// [`ErrorKind::WouldBlock`], before asking the reader again.
409    pub async fn load_missing(&self) -> Result<usize> {
410        let missing = self.take_missing();
411        let count = missing.len();
412        let mut indexes = missing.into_iter().peekable();
413        while let Some(start) = indexes.next() {
414            let mut end = start + 1;
415            while indexes.next_if_eq(&end).is_some() {
416                end += 1;
417            }
418            self.load(start..end, 0).await?;
419        }
420        Ok(count)
421    }
422
423    /// Forgets the samples providers have reported missing, as a seek does:
424    /// what the old position needed is no longer worth loading.
425    pub fn clear_missing(&self) {
426        self.take_missing();
427    }
428
429    /// Takes the decode indexes of this loader's samples that providers have
430    /// reported missing, leaving those of any other loader sharing the cache.
431    fn take_missing(&self) -> Vec<usize> {
432        let mut cache = self.cache.lock();
433        let own: Vec<usize> = cache
434            .missing
435            .range(self.base..self.base + self.track.samples.len())
436            .copied()
437            .collect();
438        for key in &own {
439            cache.missing.remove(key);
440        }
441        own.into_iter().map(|key| key - self.base).collect()
442    }
443
444    pub fn is_loaded(&self, decode_index: usize) -> bool {
445        self.cache
446            .lock()
447            .samples
448            .contains_key(&(self.base + decode_index))
449    }
450
451    /// The compressed bytes currently held, which never exceeds
452    /// [`Self::budget_bytes`]: by every loader sharing the cache.
453    pub fn resident_bytes(&self) -> u64 {
454        self.cache.lock().resident_bytes
455    }
456
457    pub fn budget_bytes(&self) -> u64 {
458        self.cache.budget_bytes
459    }
460
461    /// Loads the samples of `range` that are not resident and marks the rest
462    /// as just used, in order, so the whole range ends up the most recent.
463    ///
464    /// The cache is never locked across a read, so a provider can still
465    /// answer a reader while a load is waiting on the source.
466    async fn fetch(&self, range: Range<usize>) -> Result<()> {
467        let samples = &self.track.samples;
468        let mut index = range.start;
469        while index < range.end {
470            if self.cache.lock().touch(self.base + index) {
471                index += 1;
472                continue;
473            }
474            let offset = samples[index].offset;
475            let mut run_end = index + 1;
476            // The bytes from the run's first sample to the end of its last.
477            let mut run_bytes = u64::from(samples[index].size);
478            while run_end < range.end && !self.is_loaded(run_end) {
479                let next = &samples[run_end];
480                let Some(gap) = next.offset.checked_sub(offset + run_bytes) else {
481                    break;
482                };
483                let next_bytes = run_bytes + gap + u64::from(next.size);
484                if gap > MAX_COALESCED_GAP_BYTES || next_bytes > MAX_COALESCED_READ_BYTES {
485                    break;
486                }
487                run_bytes = next_bytes;
488                run_end += 1;
489            }
490            let mut bytes = vec![
491                0_u8;
492                usize::try_from(run_bytes).map_err(|_| limit(
493                    "coalesced sample read cannot be represented"
494                ))?
495            ];
496            read_exact(&self.source, offset, &mut bytes).await?;
497            let mut cache = self.cache.lock();
498            for (decode_index, sample) in samples.iter().enumerate().take(run_end).skip(index) {
499                let start = (sample.offset - offset) as usize;
500                cache.insert(
501                    self.base + decode_index,
502                    Arc::from(&bytes[start..start + sample.size as usize]),
503                );
504            }
505            index = run_end;
506        }
507        Ok(())
508    }
509}
510
511/// A [`SampleProvider`] that answers from a [`TrackSampleLoader`]'s cache and
512/// reports [`ErrorKind::WouldBlock`] for a sample that is not loaded yet.
513pub struct PrefetchedSampleProvider {
514    presentation_index_by_decode: Vec<u64>,
515    random_access: Vec<bool>,
516    cache: SharedCache,
517    /// The cache key of the first sample; see [`TrackSampleLoader::with_cache`].
518    base: usize,
519}
520
521impl SampleProvider for PrefetchedSampleProvider {
522    fn len(&self) -> usize {
523        self.random_access.len()
524    }
525
526    fn is_random_access(&self, decode_index: usize) -> bool {
527        self.random_access[decode_index]
528    }
529
530    fn presentation_index(&self, decode_index: usize) -> FrameIndex {
531        FrameIndex(self.presentation_index_by_decode[decode_index])
532    }
533
534    fn read(&self, decode_index: usize) -> Result<Cow<'_, [u8]>> {
535        if decode_index >= self.len() {
536            return Err(invalid("sample index is out of range"));
537        }
538        self.cache.read(self.base + decode_index)
539    }
540}
541
542/// An [`AudioPacketProvider`] that answers from a [`TrackSampleLoader`]'s
543/// cache and reports [`ErrorKind::WouldBlock`] for a packet that is not
544/// loaded yet.
545pub struct PrefetchedAudioPacketProvider {
546    decoded_ranges: Vec<SampleRange>,
547    /// Whether each packet is an Opus packet whose interval came from the
548    /// sample table, so its own table of contents must agree with it.
549    check_opus_durations: bool,
550    cache: SharedCache,
551    /// The cache key of the first packet; see [`TrackSampleLoader::with_cache`].
552    base: usize,
553}
554
555impl AudioPacketProvider for PrefetchedAudioPacketProvider {
556    fn len(&self) -> usize {
557        self.decoded_ranges.len()
558    }
559
560    fn decoded_range(&self, index: usize) -> SampleRange {
561        self.decoded_ranges[index]
562    }
563
564    fn read(&self, index: usize) -> Result<Cow<'_, [u8]>> {
565        if index >= self.len() {
566            return Err(invalid("sample index is out of range"));
567        }
568        let packet = self.cache.read(self.base + index)?;
569        if self.check_opus_durations
570            && u64::from(crate::opus::opus_packet_samples(&packet)?)
571                != self.decoded_ranges[index].len()
572        {
573            return Err(Error::new(
574                ErrorKind::MalformedMedia,
575                "an Opus packet's duration disagrees with the track's sample table",
576            ));
577        }
578        Ok(packet)
579    }
580}
581
582/// The cache a [`TrackSampleLoader`] fills and its providers read, shared
583/// between them.
584#[derive(Clone)]
585struct SharedCache {
586    state: Arc<Mutex<CacheState>>,
587    budget_bytes: u64,
588}
589
590struct CacheState {
591    /// Loaded samples by decode index, with the use they were last touched at.
592    samples: HashMap<usize, (Arc<[u8]>, u64)>,
593    /// The same samples by the use they were last touched at, oldest first.
594    by_use: BTreeMap<u64, usize>,
595    next_use: u64,
596    resident_bytes: u64,
597    budget_bytes: u64,
598    /// Samples a provider was asked for and did not have.
599    missing: BTreeSet<usize>,
600}
601
602impl SharedCache {
603    fn new(budget_bytes: u64) -> Self {
604        Self {
605            state: Arc::new(Mutex::new(CacheState {
606                samples: HashMap::new(),
607                by_use: BTreeMap::new(),
608                next_use: 0,
609                resident_bytes: 0,
610                budget_bytes,
611                missing: BTreeSet::new(),
612            })),
613            budget_bytes,
614        }
615    }
616
617    fn lock(&self) -> MutexGuard<'_, CacheState> {
618        // Nothing holding the lock can leave the cache inconsistent partway,
619        // so a panic elsewhere while it was held does not invalidate it.
620        self.state
621            .lock()
622            .unwrap_or_else(|poison| poison.into_inner())
623    }
624
625    fn read(&self, index: usize) -> Result<Cow<'static, [u8]>> {
626        let mut state = self.lock();
627        if state.touch(index) {
628            return Ok(Cow::Owned(state.samples[&index].0.to_vec()));
629        }
630        state.missing.insert(index);
631        Err(Error::new(
632            ErrorKind::WouldBlock,
633            "the compressed sample is not loaded yet",
634        ))
635    }
636}
637
638impl CacheState {
639    /// Marks a resident sample as the most recently used; `false` if it is
640    /// not resident.
641    fn touch(&mut self, index: usize) -> bool {
642        let next_use = self.next_use;
643        let Some((_, last_use)) = self.samples.get_mut(&index) else {
644            return false;
645        };
646        self.by_use.remove(last_use);
647        *last_use = next_use;
648        self.by_use.insert(next_use, index);
649        self.next_use += 1;
650        true
651    }
652
653    fn insert(&mut self, index: usize, bytes: Arc<[u8]>) {
654        if self.touch(index) {
655            // A concurrent load got here first.
656            return;
657        }
658        self.resident_bytes += bytes.len() as u64;
659        self.samples.insert(index, (bytes, self.next_use));
660        self.by_use.insert(self.next_use, index);
661        self.next_use += 1;
662        self.missing.remove(&index);
663        while self.resident_bytes > self.budget_bytes {
664            let Some((_, oldest)) = self.by_use.pop_first() else {
665                break;
666            };
667            if let Some((evicted, _)) = self.samples.remove(&oldest) {
668                self.resident_bytes -= evicted.len() as u64;
669            }
670        }
671    }
672}
673
674fn invalid(message: &str) -> Error {
675    Error::new(ErrorKind::InvalidInput, message)
676}
677
678fn limit(message: &str) -> Error {
679    Error::new(ErrorKind::ResourceLimit, message)
680}
681
682fn unsupported(message: &str) -> Error {
683    Error::new(ErrorKind::Unsupported, message)
684}
685
686#[cfg(test)]
687mod tests {
688    use super::*;
689    use crate::codec::SampleDependency;
690    use crate::io::{IoFuture, MemorySource};
691    use crate::track::TrackSample;
692    use std::cell::Cell;
693    use std::future::Future;
694    use std::pin::Pin;
695    use std::task::{Context, Poll, Waker};
696
697    /// A source whose every read suspends once before completing, the way a
698    /// network fetch does, and counts the reads it was asked for.
699    struct SuspendingSource {
700        inner: MemorySource,
701        reads: Cell<usize>,
702    }
703
704    impl ByteSource for SuspendingSource {
705        fn len(&self) -> Option<u64> {
706            self.inner.len()
707        }
708
709        fn read_at<'a>(&'a self, offset: u64, destination: &'a mut [u8]) -> IoFuture<'a, usize> {
710            self.reads.set(self.reads.get() + 1);
711            Box::pin(async move {
712                YieldOnce(false).await;
713                self.inner.read_at(offset, destination).await
714            })
715        }
716    }
717
718    struct YieldOnce(bool);
719
720    impl Future for YieldOnce {
721        type Output = ();
722
723        fn poll(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<()> {
724            if self.0 {
725                Poll::Ready(())
726            } else {
727                self.0 = true;
728                context.waker().wake_by_ref();
729                Poll::Pending
730            }
731        }
732    }
733
734    fn block_on<T>(future: impl Future<Output = T>) -> T {
735        let mut future = std::pin::pin!(future);
736        let mut context = Context::from_waker(Waker::noop());
737        loop {
738            if let Poll::Ready(value) = future.as_mut().poll(&mut context) {
739                return value;
740            }
741        }
742    }
743
744    /// A video track of `sizes.len()` samples stored back to back from
745    /// offset 0, every fourth a random-access point, each filled with its own
746    /// decode index.
747    fn track_and_source(sizes: &[u32]) -> (Track, SuspendingSource) {
748        let gaps = vec![0; sizes.len()];
749        gapped_track_and_source(sizes, &gaps)
750    }
751
752    /// [`track_and_source`] with `gaps[index]` bytes of something else, such
753    /// as a WebM block header, stored before each sample.
754    fn gapped_track_and_source(sizes: &[u32], gaps: &[usize]) -> (Track, SuspendingSource) {
755        let mut bytes = Vec::new();
756        let mut samples = Vec::new();
757        for (index, &size) in sizes.iter().enumerate() {
758            bytes.extend(std::iter::repeat_n(0xff, gaps[index]));
759            samples.push(TrackSample {
760                offset: bytes.len() as u64,
761                size,
762                dts: index as u64,
763                pts: index as i64,
764                duration: 1,
765                dependency: SampleDependency::INDEPENDENT,
766                is_sync: index % 4 == 0,
767            });
768            bytes.extend(std::iter::repeat_n(index as u8, size as usize));
769        }
770        let track = Track {
771            id: 1,
772            kind: TrackKind::Video,
773            codec: Codec::Hevc,
774            timescale: 30,
775            duration: sizes.len() as u64,
776            dimensions: None,
777            channels: None,
778            sample_rate: None,
779            language: None,
780            decoder_config: Vec::new(),
781            edits: Vec::new(),
782            presentation_order: (0..sizes.len()).collect(),
783            samples,
784            vorbis_packet_heads: Vec::new(),
785        };
786        let source = SuspendingSource {
787            inner: MemorySource::new(bytes),
788            reads: Cell::new(0),
789        };
790        (track, source)
791    }
792
793    #[test]
794    fn a_provider_reports_an_unloaded_sample_instead_of_blocking() {
795        let (track, source) = track_and_source(&[10; 8]);
796        let loader = TrackSampleLoader::new(track, source, 1_000).unwrap();
797        let provider = loader.sample_provider().unwrap();
798
799        let error = provider.read(3).unwrap_err();
800        assert_eq!(error.kind(), ErrorKind::WouldBlock);
801        assert_eq!(
802            loader.source().reads.get(),
803            0,
804            "the provider touched the source"
805        );
806
807        assert_eq!(block_on(loader.load_missing()).unwrap(), 1);
808        assert_eq!(provider.read(3).unwrap().as_ref(), &[3; 10]);
809        // Nothing is missing any more, so nothing more is loaded.
810        assert_eq!(block_on(loader.load_missing()).unwrap(), 0);
811    }
812
813    #[test]
814    fn loading_a_run_coalesces_contiguous_samples_and_adds_readahead() {
815        let (track, source) = track_and_source(&[10; 16]);
816        let loader = TrackSampleLoader::new(track, source, 1_000).unwrap();
817        let provider = loader.sample_provider().unwrap();
818
819        block_on(loader.load(4..7, 3)).unwrap();
820        assert_eq!(loader.source().reads.get(), 1, "the run was not coalesced");
821        for index in 4..10 {
822            assert_eq!(provider.read(index).unwrap().as_ref(), &[index as u8; 10]);
823        }
824        assert!(!loader.is_loaded(3));
825        assert!(!loader.is_loaded(10));
826
827        // Loading what is already resident reads nothing.
828        block_on(loader.load(4..10, 0)).unwrap();
829        assert_eq!(loader.source().reads.get(), 1);
830    }
831
832    /// Issue #685: samples a few bytes apart, as a WebM's blocks are, are
833    /// still read together, while a gap too large to be worth reading through
834    /// splits the run.
835    #[test]
836    fn loading_a_run_reads_through_small_gaps_between_samples() {
837        let mut gaps = vec![12; 8];
838        gaps[6] = MAX_COALESCED_GAP_BYTES as usize + 1;
839        let (track, source) = gapped_track_and_source(&[10; 8], &gaps);
840        let loader = TrackSampleLoader::new(track, source, 1_000).unwrap();
841        let provider = loader.sample_provider().unwrap();
842
843        block_on(loader.load(0..6, 0)).unwrap();
844        assert_eq!(loader.source().reads.get(), 1, "the run was not coalesced");
845        block_on(loader.load(0..8, 0)).unwrap();
846        assert_eq!(
847            loader.source().reads.get(),
848            2,
849            "the large gap was read through"
850        );
851        for index in 0..8 {
852            assert_eq!(provider.read(index).unwrap().as_ref(), &[index as u8; 10]);
853        }
854    }
855
856    #[test]
857    fn the_cache_stays_within_its_budget_and_evicts_the_least_recently_used() {
858        let (track, source) = track_and_source(&[10; 16]);
859        let loader = TrackSampleLoader::new(track, source, 40).unwrap();
860
861        block_on(loader.load(0..4, 0)).unwrap();
862        assert_eq!(loader.resident_bytes(), 40);
863        block_on(loader.load(8..10, 0)).unwrap();
864        assert_eq!(loader.resident_bytes(), 40);
865        assert!(!loader.is_loaded(0) && !loader.is_loaded(1));
866        assert!(loader.is_loaded(2) && loader.is_loaded(3));
867        assert!(loader.is_loaded(8) && loader.is_loaded(9));
868
869        // Readahead stops where it would no longer fit beside the request.
870        block_on(loader.load(12..14, 10)).unwrap();
871        assert!((12..16).all(|index| loader.is_loaded(index)));
872        assert_eq!(loader.resident_bytes(), 40);
873
874        // A run larger than the budget loads from its start as far as it fits.
875        block_on(loader.load(0..6, 10)).unwrap();
876        assert!((0..4).all(|index| loader.is_loaded(index)));
877        assert!(!loader.is_loaded(4) && !loader.is_loaded(5));
878        assert_eq!(loader.resident_bytes(), 40);
879    }
880
881    /// Issue #692: loaders over different parts of a track share one cache,
882    /// so together they hold no more than its budget, and each loads only the
883    /// samples its own providers missed.
884    #[test]
885    fn loaders_sharing_a_cache_share_its_budget_and_keep_their_own_samples() {
886        let (track, first_source) = track_and_source(&[10; 8]);
887        let (_, second_source) = track_and_source(&[10; 8]);
888        let part = |range: std::ops::Range<usize>| Track {
889            samples: track.samples[range.clone()].to_vec(),
890            presentation_order: (0..range.len()).collect(),
891            ..track.clone()
892        };
893        let cache = SampleCache::new(40);
894        let first = TrackSampleLoader::with_cache(part(0..4), first_source, &cache, 0).unwrap();
895        let second = TrackSampleLoader::with_cache(part(4..8), second_source, &cache, 4).unwrap();
896        let first_provider = first.sample_provider().unwrap();
897        let second_provider = second.sample_provider().unwrap();
898
899        first_provider.read(1).unwrap_err();
900        second_provider.read(1).unwrap_err();
901        // Each loader loads only what its own provider missed.
902        assert_eq!(block_on(first.load_missing()).unwrap(), 1);
903        assert_eq!(first_provider.read(1).unwrap().as_ref(), &[1; 10]);
904        assert_eq!(
905            second_provider.read(1).unwrap_err().kind(),
906            ErrorKind::WouldBlock
907        );
908        assert_eq!(block_on(second.load_missing()).unwrap(), 1);
909        assert_eq!(second_provider.read(1).unwrap().as_ref(), &[5; 10]);
910
911        block_on(first.load(0..4, 0)).unwrap();
912        block_on(second.load(0..4, 0)).unwrap();
913        assert_eq!(cache.resident_bytes(), 40);
914        assert_eq!(first.resident_bytes(), 40);
915        assert!((0..4).all(|index| second.is_loaded(index)));
916        assert!((0..4).all(|index| !first.is_loaded(index)));
917    }
918
919    #[test]
920    fn appended_samples_load_like_the_ones_before_them() {
921        let (track, source) = track_and_source(&[10; 8]);
922        let mut loader = TrackSampleLoader::new(
923            Track {
924                samples: track.samples[..3].to_vec(),
925                presentation_order: (0..3).collect(),
926                ..track.clone()
927            },
928            source,
929            1_000,
930        )
931        .unwrap();
932        let before = loader.sample_provider().unwrap();
933        loader.append(&track.samples[3..]).unwrap();
934        let after = loader.sample_provider().unwrap();
935        assert_eq!((before.len(), after.len()), (3, 8));
936        block_on(loader.load(2..6, 0)).unwrap();
937        assert_eq!(loader.source().reads.get(), 1, "the run was not coalesced");
938        assert_eq!(after.read(5).unwrap().as_ref(), &[5; 10]);
939        assert_eq!(before.read(2).unwrap().as_ref(), &[2; 10]);
940
941        let mut huge = track.samples[0].clone();
942        huge.size = 2_000;
943        assert_eq!(
944            loader.append(&[huge]).unwrap_err().kind(),
945            ErrorKind::ResourceLimit
946        );
947        assert_eq!(loader.track().samples.len(), 8);
948    }
949
950    #[test]
951    fn a_budget_smaller_than_the_largest_sample_is_refused() {
952        let (track, source) = track_and_source(&[10, 50, 10]);
953        let error = TrackSampleLoader::new(track, source, 49)
954            .err()
955            .expect("the budget cannot hold sample 1");
956        assert_eq!(error.kind(), ErrorKind::ResourceLimit);
957    }
958
959    #[test]
960    fn clearing_missing_samples_forgets_what_an_old_position_needed() {
961        let (track, source) = track_and_source(&[10; 8]);
962        let loader = TrackSampleLoader::new(track, source, 1_000).unwrap();
963        let provider = loader.sample_provider().unwrap();
964        provider.read(1).unwrap_err();
965        loader.clear_missing();
966        assert_eq!(block_on(loader.load_missing()).unwrap(), 0);
967        assert_eq!(loader.source().reads.get(), 0);
968    }
969
970    #[test]
971    fn an_audio_provider_answers_from_the_same_cache() {
972        let (mut track, source) = track_and_source(&[4; 4]);
973        track.kind = TrackKind::Audio;
974        let loader = TrackSampleLoader::new(track, source, 1_000).unwrap();
975        assert_eq!(
976            loader.sample_provider().err().unwrap().kind(),
977            ErrorKind::Unsupported
978        );
979        let ranges: Vec<_> = (0..4)
980            .map(|index| SampleRange::new(index * 1024, (index + 1) * 1024).unwrap())
981            .collect();
982        assert_eq!(
983            loader
984                .audio_packet_provider(ranges[..3].to_vec())
985                .err()
986                .unwrap()
987                .kind(),
988            ErrorKind::InvalidInput
989        );
990        let provider = loader.audio_packet_provider(ranges.clone()).unwrap();
991        assert_eq!(provider.decoded_range(2), ranges[2]);
992        assert_eq!(provider.read(2).unwrap_err().kind(), ErrorKind::WouldBlock);
993        block_on(loader.load_missing()).unwrap();
994        assert_eq!(provider.read(2).unwrap().as_ref(), &[2; 4]);
995    }
996
997    /// Issue #694: the floor is the largest run of a packet that decodes
998    /// samples and its preroll packets, so a first packet that decodes nothing,
999    /// as a Vorbis stream's does, only counts as another packet's preroll.
1000    #[test]
1001    fn an_audio_budget_must_hold_a_packet_with_its_preroll() {
1002        let (mut track, source) = track_and_source(&[40, 10, 20, 30, 5]);
1003        track.kind = TrackKind::Audio;
1004        let loader = TrackSampleLoader::new(track, source, 40).unwrap();
1005        let mut start = 0;
1006        let ranges: Vec<_> = [0, 64, 128, 128, 64]
1007            .into_iter()
1008            .map(|length| {
1009                start += length;
1010                SampleRange::new(start - length, start).unwrap()
1011            })
1012            .collect();
1013        let provider = loader.audio_packet_provider(ranges).unwrap();
1014        // With no preroll, packet 0's 40 bytes never need to be loaded.
1015        assert_eq!(loader.audio_budget_floor(&provider, 0), 30);
1016        // Packets 0 and 1.
1017        assert_eq!(loader.audio_budget_floor(&provider, 1), 50);
1018        // Packets 1, 2 and 3 rather than 0, 1 and 2.
1019        assert_eq!(loader.audio_budget_floor(&provider, 2), 70);
1020        assert_eq!(loader.audio_budget_floor(&provider, usize::MAX), 105);
1021        loader.check_audio_budget(&provider, 0).unwrap();
1022        assert_eq!(
1023            loader.check_audio_budget(&provider, 1).unwrap_err().kind(),
1024            ErrorKind::ResourceLimit
1025        );
1026    }
1027}