Skip to main content

zvidlib_container/
track.rs

1//! The container-neutral track index every demuxer produces.
2//!
3//! [`crate::Mp4Demuxer`] and [`crate::WebmDemuxer`] both index a track as a
4//! [`Track`]: its codec, timing and decode-order [`TrackSample`] table, with
5//! its codec configuration in the box form an MP4 sample entry carries. So
6//! everything built on an index - [`Track::to_encoded_video_samples`],
7//! [`Track::to_encoded_audio_samples`], the on-demand [`TrackSampleProvider`]
8//! and [`TrackAudioPacketProvider`], and [`crate::TrackSampleLoader`] - works
9//! the same over either container.
10
11use crate::audio::{AudioEdit, AudioPacketProvider, AudioTrackTiming, EncodedAudioSample};
12use crate::codec::{EncodedVideoSample, SampleDependency, SampleProvider, TrackKind};
13use crate::io::ByteSource;
14use crate::media::{Codec, VideoDimensions};
15use crate::mp4_demux::{AacTrackConfig, parse_aac_config};
16use crate::opus::{OPUS_SAMPLE_RATE, OpusHead};
17use crate::timeline::FrameIndex;
18use crate::vorbis::VorbisConfig;
19use crate::{Error, ErrorKind, Limits, Result};
20use std::borrow::Cow;
21use std::future::Future;
22
23/// A movie-to-media timeline edit. A media time of `-1` is an empty edit.
24#[derive(Clone, Copy, Debug, Eq, PartialEq)]
25pub struct EditMapping {
26    pub segment_duration: u64,
27    pub media_time: i64,
28    pub media_rate_integer: i16,
29    pub media_rate_fraction: i16,
30}
31
32/// One encoded sample in decode order.
33#[derive(Clone, Debug, Eq, PartialEq)]
34pub struct TrackSample {
35    pub offset: u64,
36    pub size: u32,
37    pub dts: u64,
38    pub pts: i64,
39    pub duration: u32,
40    pub dependency: SampleDependency,
41    pub is_sync: bool,
42}
43
44/// Read-only metadata and indexes for one demuxed track, from any container.
45#[derive(Clone, Debug, Eq, PartialEq)]
46pub struct Track {
47    pub id: u32,
48    pub kind: TrackKind,
49    pub codec: Codec,
50    pub timescale: u32,
51    pub duration: u64,
52    pub dimensions: Option<VideoDimensions>,
53    pub channels: Option<u16>,
54    pub sample_rate: Option<u32>,
55    /// The track's ISO 639-2/T language code, such as `"eng"` or `"fra"`,
56    /// from an MP4 track's `mdhd` box: `"und"` when the file marks the
57    /// language undetermined, and `None` when the box holds no valid code. A
58    /// WebM track's is always `None`.
59    pub language: Option<String>,
60    /// Complete codec configuration box, including its header, in the form an
61    /// MP4 sample entry carries it whichever container the track came from.
62    pub decoder_config: Vec<u8>,
63    pub edits: Vec<EditMapping>,
64    /// Samples in decode order.
65    pub samples: Vec<TrackSample>,
66    /// Decode-order indexes of the presentation frames, sorted by PTS, then
67    /// DTS, then decode index. A decode-only sample, such as a hidden VP8
68    /// frame stored as a WebM block of its own, is decoded on the way to the
69    /// frames after it but is never presented, so it is not listed.
70    pub presentation_order: Vec<usize>,
71    /// The first byte of every sample, in decode order, of a WebM Vorbis
72    /// track, which [`crate::WebmDemuxer`] reads anyway while scanning block
73    /// headers. A Vorbis packet's mode number is in it, so every packet's
74    /// decoded interval is known without reading the packets again; empty for
75    /// every other track.
76    pub vorbis_packet_heads: Vec<u8>,
77}
78
79impl Track {
80    /// Returns a sample by its zero-based presentation index.
81    pub fn presentation_sample(&self, index: usize) -> Option<&TrackSample> {
82        self.presentation_order
83            .get(index)
84            .and_then(|&decode_index| self.samples.get(decode_index))
85    }
86
87    /// Reads one decode-order sample without changing caller-visible source state.
88    pub async fn read_sample_into<S: ByteSource + ?Sized>(
89        &self,
90        source: &S,
91        decode_index: usize,
92        destination: &mut [u8],
93    ) -> Result<()> {
94        let sample = self
95            .samples
96            .get(decode_index)
97            .ok_or_else(|| invalid("sample index is out of range"))?;
98        if destination.len() != sample.size as usize {
99            return Err(invalid("sample destination size does not match the index"));
100        }
101        read_exact(source, sample.offset, destination).await
102    }
103
104    /// The presentation identity, in [`FrameIndex`] terms, of every
105    /// decode-order sample: [`Self::presentation_order`]'s inverse, with a
106    /// decode-only sample (one `presentation_order` does not list) given an
107    /// identity past the last presentation frame so it never collides with
108    /// a frame a caller asks for. Reads no sample data.
109    pub(crate) fn presentation_index_by_decode(&self) -> Result<Vec<u64>> {
110        let mut presentation_index_by_decode = vec![None; self.samples.len()];
111        for (presentation_index, &decode_index) in self.presentation_order.iter().enumerate() {
112            let presentation_index = u64::try_from(presentation_index)
113                .map_err(|_| limit("presentation index overflow"))?;
114            *presentation_index_by_decode
115                .get_mut(decode_index)
116                .ok_or_else(|| malformed("presentation order references a missing sample"))? =
117                Some(presentation_index);
118        }
119        let mut next_decode_only = self.presentation_order.len() as u64;
120        Ok(presentation_index_by_decode
121            .into_iter()
122            .map(|index| {
123                index.unwrap_or_else(|| {
124                    next_decode_only += 1;
125                    next_decode_only - 1
126                })
127            })
128            .collect())
129    }
130
131    /// Reads every decode-order sample and returns owned
132    /// [`EncodedVideoSample`] values keyed by presentation order, ready for
133    /// a [`crate::codec::VideoDecoderFactory`] backend.
134    ///
135    /// The zero-based position of each sample within
136    /// [`Self::presentation_order`] becomes its `presentation_index`, and
137    /// `is_sync` becomes `random_access`. A decode-only sample, which
138    /// `presentation_order` does not list, takes an identity past the last
139    /// presentation frame, in decode order, so it never collides with a frame
140    /// a caller asks for. Total decoded sample bytes are bounded by
141    /// `limits.max_allocation_bytes`.
142    pub async fn to_encoded_video_samples<S: ByteSource + ?Sized>(
143        &self,
144        source: &S,
145        limits: &Limits,
146    ) -> Result<Vec<EncodedVideoSample>> {
147        if self.kind != TrackKind::Video {
148            return Err(unsupported("encoded video samples require a video track"));
149        }
150        let presentation_index_by_decode = self.presentation_index_by_decode()?;
151
152        let mut total_bytes = 0_u64;
153        let mut samples = Vec::with_capacity(self.samples.len());
154        for (decode_index, sample) in self.samples.iter().enumerate() {
155            total_bytes = total_bytes
156                .checked_add(u64::from(sample.size))
157                .ok_or_else(|| limit("encoded sample allocation overflow"))?;
158            if total_bytes > limits.max_allocation_bytes {
159                return Err(limit(
160                    "encoded video samples exceed the configured allocation limit",
161                ));
162            }
163            let mut data = vec![0_u8; sample.size as usize];
164            self.read_sample_into(source, decode_index, &mut data)
165                .await?;
166            samples.push(EncodedVideoSample {
167                presentation_index: FrameIndex(presentation_index_by_decode[decode_index]),
168                random_access: sample.is_sync,
169                data,
170            });
171        }
172        Ok(samples)
173    }
174
175    /// Parses the AAC AudioSpecificConfig carried by this track's `esds` box.
176    pub fn aac_config(&self) -> Result<AacTrackConfig> {
177        if self.kind != TrackKind::Audio || self.codec != Codec::Aac {
178            return Err(unsupported("AAC configuration requires an AAC audio track"));
179        }
180        let sample_rate = self
181            .sample_rate
182            .ok_or_else(|| malformed("AAC sample rate is missing"))?;
183        let channels = self
184            .channels
185            .ok_or_else(|| malformed("AAC channel count is missing"))?;
186        parse_aac_config(&self.decoder_config, sample_rate, channels)
187    }
188
189    /// Parses the Opus identification header carried by this track's `dOps`
190    /// box.
191    pub fn opus_config(&self) -> Result<OpusHead> {
192        if self.kind != TrackKind::Audio || self.codec != Codec::Opus {
193            return Err(unsupported(
194                "Opus configuration requires an Opus audio track",
195            ));
196        }
197        let head = OpusHead::from_dops(&self.decoder_config)?;
198        if self.channels != Some(u16::from(head.channels)) {
199            return Err(malformed(
200                "Opus dOps channel count disagrees with the sample entry",
201            ));
202        }
203        Ok(head)
204    }
205
206    /// Parses the three Vorbis header packets a WebM Vorbis track carries as
207    /// its `decoder_config` (see [`crate::WebmDemuxer`]); Vorbis has no MP4
208    /// sample entry.
209    pub fn vorbis_config(&self) -> Result<VorbisConfig> {
210        if self.kind != TrackKind::Audio || self.codec != Codec::Vorbis {
211            return Err(unsupported(
212                "Vorbis configuration requires a Vorbis audio track",
213            ));
214        }
215        VorbisConfig::from_codec_private(&self.decoder_config)
216    }
217
218    /// The sample rate this audio track decodes at: the AAC
219    /// `AudioSpecificConfig`'s or the Vorbis identification header's, or 48
220    /// kHz for Opus, which always decodes at that rate whatever its input was.
221    pub fn audio_sample_rate(&self) -> Result<u32> {
222        match self.codec {
223            Codec::Aac => Ok(self.aac_config()?.sample_rate),
224            Codec::Opus => {
225                self.opus_config()?;
226                Ok(OPUS_SAMPLE_RATE)
227            }
228            Codec::Vorbis => Ok(self.vorbis_config()?.sample_rate),
229            _ => Err(unsupported(
230                "audio packets require an AAC, Opus or Vorbis track",
231            )),
232        }
233    }
234
235    /// Reads every indexed audio packet - AAC access units, Opus or Vorbis
236    /// packets - from its validated byte range.
237    ///
238    /// Packet intervals use the decoded PCM sample clock and remain contiguous
239    /// even when the track timescale differs from the decoded sample rate.
240    pub async fn to_encoded_audio_samples<S: ByteSource + ?Sized>(
241        &self,
242        source: &S,
243        limits: &Limits,
244    ) -> Result<Vec<EncodedAudioSample>> {
245        let sample_rate = self.audio_sample_rate()?;
246        // A Vorbis packet's length depends on the one before it, so the
247        // intervals are assigned once every packet has been read.
248        let vorbis = if self.codec == Codec::Vorbis {
249            Some(self.vorbis_config()?)
250        } else {
251            None
252        };
253        // An AAC packet's interval comes from the sample table alone.
254        let aac_ranges = if self.codec == Codec::Aac {
255            Some(self.aac_decoded_ranges(sample_rate)?)
256        } else {
257            None
258        };
259        let mut total_bytes = 0_u64;
260        let mut decoded_start = 0_u64;
261        let mut packets = Vec::with_capacity(self.samples.len());
262        for (decode_index, sample) in self.samples.iter().enumerate() {
263            total_bytes = total_bytes
264                .checked_add(u64::from(sample.size))
265                .ok_or_else(|| limit("encoded audio allocation overflow"))?;
266            if total_bytes > limits.max_allocation_bytes {
267                return Err(limit(
268                    "encoded audio samples exceed the configured allocation limit",
269                ));
270            }
271            let mut data = vec![0_u8; sample.size as usize];
272            self.read_sample_into(source, decode_index, &mut data)
273                .await?;
274            if vorbis.is_some() {
275                packets.push(EncodedAudioSample {
276                    decoded_range: crate::SampleRange::new(0, 0)?,
277                    data,
278                });
279                continue;
280            }
281            if let Some(ranges) = &aac_ranges {
282                packets.push(EncodedAudioSample {
283                    decoded_range: ranges[decode_index],
284                    data,
285                });
286                continue;
287            }
288            // An Opus packet's own table of contents says how long it
289            // decodes. Muxers shorten the last sample's duration to trim
290            // the stream's end - FFmpeg does - so the sample table cannot.
291            let decoded_end = decoded_start
292                .checked_add(u64::from(crate::opus::opus_packet_samples(&data)?))
293                .ok_or_else(|| limit("audio track timing overflow"))?;
294            if decoded_end <= decoded_start {
295                return Err(malformed("audio packet has an empty decoded interval"));
296            }
297            packets.push(EncodedAudioSample {
298                decoded_range: crate::SampleRange::new(decoded_start, decoded_end)?,
299                data,
300            });
301            decoded_start = decoded_end;
302        }
303        if packets.is_empty() {
304            return Err(malformed("audio track contains no samples"));
305        }
306        if let Some(vorbis) = vorbis {
307            return vorbis.encoded_samples(packets.into_iter().map(|packet| packet.data).collect());
308        }
309        Ok(packets)
310    }
311
312    /// The decoded PCM interval of every AAC packet, from the sample table's
313    /// durations alone. Reads no sample data.
314    pub(crate) fn aac_decoded_ranges(&self, sample_rate: u32) -> Result<Vec<crate::SampleRange>> {
315        self.table_decoded_ranges(&self.samples, sample_rate)
316    }
317
318    /// The decoded PCM interval of every Opus packet: the sample table's
319    /// durations for all but the last, and `last_packet_samples`, read from
320    /// the last packet's own table of contents, for that one. A muxer shortens
321    /// the last sample's duration to trim the stream's end, as
322    /// [`Self::to_encoded_audio_samples`] explains, so the table cannot give
323    /// it. Reads no sample data.
324    pub(crate) fn opus_decoded_ranges(
325        &self,
326        last_packet_samples: u32,
327    ) -> Result<Vec<crate::SampleRange>> {
328        let (_, leading) = self
329            .samples
330            .split_last()
331            .ok_or_else(|| malformed("audio track contains no samples"))?;
332        let mut ranges = self.table_decoded_ranges(leading, OPUS_SAMPLE_RATE)?;
333        let start = ranges.last().map_or(0, |range| range.end);
334        let end = start
335            .checked_add(u64::from(last_packet_samples))
336            .ok_or_else(|| limit("audio track timing overflow"))?;
337        if end <= start {
338            return Err(malformed("audio packet has an empty decoded interval"));
339        }
340        ranges.push(crate::SampleRange::new(start, end)?);
341        Ok(ranges)
342    }
343
344    /// The decoded PCM interval of every Vorbis packet, the ones
345    /// [`Self::to_encoded_audio_samples`] gives, from the block size each
346    /// packet's first byte names. Reads no sample data: the first bytes are
347    /// [`Self::vorbis_packet_heads`], which [`crate::WebmDemuxer`] records.
348    /// Fails with [`ErrorKind::Unsupported`] for a track that does not record
349    /// them.
350    pub(crate) fn vorbis_decoded_ranges(&self) -> Result<Vec<crate::SampleRange>> {
351        let config = self.vorbis_config()?;
352        if self.samples.is_empty() {
353            return Err(malformed("audio track contains no samples"));
354        }
355        if self.vorbis_packet_heads.len() != self.samples.len() {
356            return Err(unsupported(
357                "a Vorbis track's packet intervals need the first byte of every packet, which \
358                 the WebM demuxer records",
359            ));
360        }
361        let block_sizes = self
362            .vorbis_packet_heads
363            .iter()
364            .map(|&head| config.packet_block_size(&[head]))
365            .collect::<Result<Vec<_>>>()?;
366        VorbisConfig::decoded_ranges(block_sizes)
367    }
368
369    /// The decoded PCM interval of each of `samples`, the track's leading
370    /// samples, from their sample-table durations.
371    fn table_decoded_ranges(
372        &self,
373        samples: &[TrackSample],
374        sample_rate: u32,
375    ) -> Result<Vec<crate::SampleRange>> {
376        let mut decoded_start = 0_u64;
377        let mut track_ticks = 0_u64;
378        let mut ranges = Vec::with_capacity(samples.len());
379        for sample in samples {
380            track_ticks = track_ticks
381                .checked_add(u64::from(sample.duration))
382                .ok_or_else(|| limit("audio track timing overflow"))?;
383            let decoded_end = scale_time(track_ticks, self.timescale, sample_rate)?;
384            if decoded_end <= decoded_start {
385                return Err(malformed("audio packet has an empty decoded interval"));
386            }
387            ranges.push(crate::SampleRange::new(decoded_start, decoded_end)?);
388            decoded_start = decoded_end;
389        }
390        Ok(ranges)
391    }
392
393    /// Converts the track's MP4 edit-list timing to the presentation sample
394    /// clock used by [`crate::AudioSampleReader`], including decoder priming
395    /// and end padding.
396    ///
397    /// An Opus track without an edit list still has its `dOps` pre-skip
398    /// trimmed as priming, and ends where its sample table does: the packets
399    /// themselves can decode past that end, which is how a muxer that writes
400    /// no edit list trims the stream.
401    pub fn audio_timing(&self, movie_timescale: u32) -> Result<AudioTrackTiming> {
402        let sample_rate = self.audio_sample_rate()?;
403        let decoded_length = scale_time(self.duration, self.timescale, sample_rate)?;
404        if self.edits.is_empty() {
405            if self.codec != Codec::Opus {
406                return Ok(AudioTrackTiming::default());
407            }
408            let priming = self.opus_config()?.pre_skip;
409            let length = decoded_length
410                .checked_sub(u64::from(priming))
411                .filter(|&length| length > 0)
412                .ok_or_else(|| malformed("Opus pre-skip covers the whole track"))?;
413            return Ok(AudioTrackTiming {
414                priming: u32::from(priming),
415                padding: 0,
416                track_offset: 0,
417                edits: vec![AudioEdit {
418                    presentation: crate::SampleRange::new(0, length)?,
419                    media_start: Some(u64::from(priming)),
420                }],
421            });
422        }
423        let mut presentation_start = 0_u64;
424        let mut edits = Vec::with_capacity(self.edits.len());
425        let mut first_media = None;
426        let mut last_media_end = 0_u64;
427        for edit in &self.edits {
428            if edit.media_rate_integer != 1 || edit.media_rate_fraction != 0 {
429                return Err(unsupported(
430                    "audio edit rates other than 1.0 are unsupported",
431                ));
432            }
433            let length = scale_time(edit.segment_duration, movie_timescale, sample_rate)?;
434            if length == 0 {
435                return Err(malformed("audio edit has an empty presentation interval"));
436            }
437            let presentation_end = presentation_start
438                .checked_add(length)
439                .ok_or_else(|| limit("audio edit presentation overflow"))?;
440            let media_start = if edit.media_time == -1 {
441                None
442            } else {
443                if edit.media_time < 0 {
444                    return Err(malformed("audio edit has an invalid negative media time"));
445                }
446                let start = scale_time(edit.media_time as u64, self.timescale, sample_rate)?;
447                let end = start
448                    .checked_add(length)
449                    .ok_or_else(|| limit("audio edit media range overflow"))?;
450                first_media = Some(first_media.map_or(start, |value: u64| value.min(start)));
451                last_media_end = last_media_end.max(end);
452                Some(start)
453            };
454            edits.push(AudioEdit {
455                presentation: crate::SampleRange::new(presentation_start, presentation_end)?,
456                media_start,
457            });
458            presentation_start = presentation_end;
459        }
460        let priming = u32::try_from(first_media.unwrap_or(0))
461            .map_err(|_| limit("audio priming exceeds the supported range"))?;
462        let padding = u32::try_from(decoded_length.saturating_sub(last_media_end))
463            .map_err(|_| limit("audio padding exceeds the supported range"))?;
464        Ok(AudioTrackTiming {
465            priming,
466            padding,
467            track_offset: 0,
468            edits,
469        })
470    }
471}
472
473/// A [`SampleProvider`] that reads a video track's compressed bytes from a
474/// [`ByteSource`] on demand, holding only `track`'s index (and whatever `S`
475/// itself caches) rather than every sample's bytes.
476///
477/// Built from a container-neutral [`Track`] index, so it works over MP4 and
478/// WebM alike.
479///
480/// `S::read_at`'s future must resolve the first time it is polled: this
481/// provider is used from [`ExactFrameReader::get`][crate::codec::ExactFrameReader::get],
482/// which is synchronous, so [`Self::read`] polls the read once and reports
483/// [`ErrorKind::Unsupported`] rather than blocking if the source does not
484/// finish immediately. [`MemorySource`][crate::io::MemorySource] and a
485/// [`CachingByteSource`][crate::io::CachingByteSource] wrapping one both
486/// satisfy this; a source that genuinely waits on I/O (a network fetch, for
487/// example) needs its own asynchronous reader rather than this provider.
488///
489/// `S` must be `Send` so the provider - and a reader built over it - can be
490/// moved to a decode thread, matching [`SampleProvider`]'s own requirement.
491pub struct TrackSampleProvider<S> {
492    track: Track,
493    source: S,
494    presentation_index_by_decode: Vec<u64>,
495}
496
497impl<S: ByteSource + Send> TrackSampleProvider<S> {
498    /// Fails if `track` is not a video track; reads no sample data.
499    pub fn new(track: Track, source: S) -> Result<Self> {
500        if track.kind != TrackKind::Video {
501            return Err(unsupported("a sample provider requires a video track"));
502        }
503        let presentation_index_by_decode = track.presentation_index_by_decode()?;
504        Ok(Self {
505            track,
506            source,
507            presentation_index_by_decode,
508        })
509    }
510
511    pub fn track(&self) -> &Track {
512        &self.track
513    }
514
515    pub fn source(&self) -> &S {
516        &self.source
517    }
518
519    pub fn into_source(self) -> S {
520        self.source
521    }
522}
523
524impl<S: ByteSource + Send> SampleProvider for TrackSampleProvider<S> {
525    fn len(&self) -> usize {
526        self.track.samples.len()
527    }
528
529    fn is_random_access(&self, decode_index: usize) -> bool {
530        self.track.samples[decode_index].is_sync
531    }
532
533    fn presentation_index(&self, decode_index: usize) -> FrameIndex {
534        FrameIndex(self.presentation_index_by_decode[decode_index])
535    }
536
537    fn read(&self, decode_index: usize) -> Result<Cow<'_, [u8]>> {
538        let size = self
539            .track
540            .samples
541            .get(decode_index)
542            .ok_or_else(|| invalid("sample index is out of range"))?
543            .size as usize;
544        let mut data = vec![0_u8; size];
545        poll_once(
546            self.track
547                .read_sample_into(&self.source, decode_index, &mut data),
548        )
549        .ok_or_else(|| {
550            unsupported(
551                "TrackSampleProvider requires a byte source whose reads complete \
552                     synchronously; it cannot drive one that suspends",
553            )
554        })??;
555        Ok(Cow::Owned(data))
556    }
557}
558
559/// An [`AudioPacketProvider`] that reads an AAC or Vorbis track's compressed
560/// packets from a [`ByteSource`] on demand, holding only `track`'s index (and
561/// whatever `S` itself caches) rather than every packet's bytes.
562///
563/// The audio counterpart of [`TrackSampleProvider`], with the same requirement
564/// that `S::read_at`'s future resolve the first time it is polled: a source
565/// that suspends makes [`Self::read`] report [`ErrorKind::Unsupported`]
566/// rather than block.
567///
568/// [`Self::new`] builds the whole index without reading any packet. An AAC
569/// packet's decoded interval comes from the track's sample durations, and a
570/// Vorbis packet's from the block sizes of it and the packet before it, which
571/// [`Track::vorbis_packet_heads`] names. An Opus packet's interval is in its
572/// own table-of-contents byte, which only the packet has, so Opus tracks use
573/// [`crate::TrackSampleLoader::opus_packet_provider`] or
574/// [`Track::to_encoded_audio_samples`]; [`Self::new`] rejects them.
575pub struct TrackAudioPacketProvider<S> {
576    track: Track,
577    source: S,
578    decoded_ranges: Vec<crate::SampleRange>,
579}
580
581impl<S: ByteSource + Send> TrackAudioPacketProvider<S> {
582    /// Fails if `track` is not an AAC or Vorbis audio track; reads no packet
583    /// data.
584    pub fn new(track: Track, source: S) -> Result<Self> {
585        if track.kind != TrackKind::Audio || !matches!(track.codec, Codec::Aac | Codec::Vorbis) {
586            return Err(unsupported(
587                "an on-demand audio packet provider requires an AAC or Vorbis audio track",
588            ));
589        }
590        if track.samples.is_empty() {
591            return Err(malformed("audio track contains no samples"));
592        }
593        let decoded_ranges = if track.codec == Codec::Vorbis {
594            track.vorbis_decoded_ranges()?
595        } else {
596            track.aac_decoded_ranges(track.audio_sample_rate()?)?
597        };
598        Ok(Self {
599            track,
600            source,
601            decoded_ranges,
602        })
603    }
604
605    pub fn track(&self) -> &Track {
606        &self.track
607    }
608
609    pub fn source(&self) -> &S {
610        &self.source
611    }
612
613    pub fn into_source(self) -> S {
614        self.source
615    }
616}
617
618impl<S: ByteSource + Send> AudioPacketProvider for TrackAudioPacketProvider<S> {
619    fn len(&self) -> usize {
620        self.decoded_ranges.len()
621    }
622
623    fn decoded_range(&self, index: usize) -> crate::SampleRange {
624        self.decoded_ranges[index]
625    }
626
627    fn read(&self, index: usize) -> Result<Cow<'_, [u8]>> {
628        let size = self
629            .track
630            .samples
631            .get(index)
632            .ok_or_else(|| invalid("sample index is out of range"))?
633            .size as usize;
634        let mut data = vec![0_u8; size];
635        poll_once(self.track.read_sample_into(&self.source, index, &mut data)).ok_or_else(
636            || {
637                unsupported(
638                    "TrackAudioPacketProvider requires a byte source whose reads complete \
639                     synchronously; it cannot drive one that suspends",
640                )
641            },
642        )??;
643        Ok(Cow::Owned(data))
644    }
645}
646
647/// Polls a future once and returns its value if it was ready, without
648/// blocking or spinning. Every `ByteSource` this crate ships resolves on its
649/// first poll; this is how a synchronous caller, such as
650/// [`TrackSampleProvider::read`], drives one without an async runtime.
651fn poll_once<T>(future: impl Future<Output = T>) -> Option<T> {
652    let mut future = std::pin::pin!(future);
653    let mut context = std::task::Context::from_waker(std::task::Waker::noop());
654    match future.as_mut().poll(&mut context) {
655        std::task::Poll::Ready(value) => Some(value),
656        std::task::Poll::Pending => None,
657    }
658}
659
660pub(crate) async fn read_exact<S: ByteSource + ?Sized>(
661    source: &S,
662    mut offset: u64,
663    mut output: &mut [u8],
664) -> Result<()> {
665    while !output.is_empty() {
666        let read = source.read_at(offset, output).await?;
667        if read == 0 {
668            return Err(malformed("unexpected end of media source"));
669        }
670        offset = offset
671            .checked_add(read as u64)
672            .ok_or_else(|| malformed("read offset overflow"))?;
673        output = &mut output[read..];
674    }
675    Ok(())
676}
677
678pub(crate) fn scale_time(value: u64, source_timescale: u32, destination_rate: u32) -> Result<u64> {
679    if source_timescale == 0 || destination_rate == 0 {
680        return Err(malformed("media timescale and sample rate must be nonzero"));
681    }
682    let numerator = u128::from(value)
683        .checked_mul(u128::from(destination_rate))
684        .ok_or_else(|| limit("media time scaling overflow"))?;
685    let rounded = numerator
686        .checked_add(u128::from(source_timescale) / 2)
687        .ok_or_else(|| limit("media time rounding overflow"))?
688        / u128::from(source_timescale);
689    u64::try_from(rounded).map_err(|_| limit("scaled media time cannot be represented"))
690}
691
692fn invalid(m: impl Into<String>) -> Error {
693    Error::new(ErrorKind::InvalidInput, m)
694}
695fn malformed(m: impl Into<String>) -> Error {
696    Error::new(ErrorKind::MalformedMedia, m)
697}
698fn limit(m: impl Into<String>) -> Error {
699    Error::new(ErrorKind::ResourceLimit, m)
700}
701fn unsupported(m: impl Into<String>) -> Error {
702    Error::new(ErrorKind::Unsupported, m)
703}