Skip to main content

alpha2_host_core/
audio_stream.rs

1//! Audio decoding over a container reader and a decoder session, placed by timestamp at the
2//! project rate.
3//!
4//! [`AudioStream`] applies what `FFmpeg`'s demuxers and decoders do for the native host: each
5//! packet's skip-samples (priming, end padding) are dropped, decoded samples sit at their packet's
6//! timestamp with gaps left silent and overlaps dropped, and everything is resampled to the
7//! project rate. A seek decodes from a pre-roll before its target and hands out samples from the
8//! target on.
9
10use std::collections::{HashMap, VecDeque};
11
12use alpha2_container::{
13    AudioCodec, AudioTrack, ContainerReader, Packet, PcmFormat, TrackInfo, TrackKind,
14};
15use alpha2_media::{
16    AudioBlock, CancelToken, DecodeError, DecodeEvent, DecodeRequest, DecodeResult, Decoder,
17    Orientation, SampleAspectRatio, Speaker, SpeakerLayout, StreamInfo, StreamKind,
18};
19use alpha2_time::{AudioFrameGrid, MediaTime, TICKS_PER_SECOND, audio_frame_grid};
20
21use crate::audio_timeline::SourceTimeline;
22use crate::recovery::{DecodePolicy, Recovery, WorkBudget, audio_timestamp_in_range};
23use crate::video_stream::{BackendError, Submit};
24
25/// Decoded samples from one packet.
26#[derive(Clone, Debug, PartialEq)]
27pub struct PcmChunk {
28    /// The presentation time of the packet it came from, in the track's timescale.
29    pub pts: i64,
30    /// Samples per second of the decoded audio.
31    pub sample_rate: u32,
32    /// One plane per channel.
33    pub planes: Vec<Vec<f32>>,
34    /// The speakers of the planes, when not the stream's: the stream takes its own speakers from
35    /// them in its order, a back pair standing in for a side pair it lacks, and drops the rest
36    /// (a decoder's silent LFE). `None` means the stream's speakers, in `FFmpeg`'s native channel
37    /// order for compressed codecs.
38    pub speakers: Option<SpeakerLayout>,
39}
40
41/// What an audio session had on a receive.
42#[derive(Debug)]
43pub enum AudioPoll {
44    /// Decoded samples.
45    Chunk(PcmChunk),
46    /// Nothing yet; submit more input.
47    Pending,
48    /// Input ended and every sample was given.
49    Drained,
50}
51
52/// One decoder session for one audio track, used from one thread at a time.
53pub trait AudioDecodeBackend: Send {
54    /// Queues a packet for decoding.
55    ///
56    /// # Errors
57    /// A lost session, a damaged packet, or a failed decoder.
58    fn submit(&mut self, packet: &Packet) -> Result<Submit, BackendError>;
59
60    /// Takes decoded samples, in packet order. With `wait`, blocks briefly for them.
61    ///
62    /// # Errors
63    /// A lost session or a failed decoder.
64    fn receive(&mut self, wait: bool) -> Result<AudioPoll, BackendError>;
65
66    /// No more packets follow until a [`Self::flush`].
67    ///
68    /// # Errors
69    /// A lost session or a failed decoder.
70    fn finish_input(&mut self) -> Result<(), BackendError>;
71
72    /// Drops every queued packet and sample.
73    ///
74    /// # Errors
75    /// A lost session or a failed decoder.
76    fn flush(&mut self) -> Result<(), BackendError>;
77}
78
79/// Opens audio decoder sessions for tracks.
80pub trait AudioBackends: Send + Sync {
81    /// A session for `track`.
82    ///
83    /// # Errors
84    /// [`BackendError::Unsupported`] when no decoder reads the track.
85    fn open(&self, track: &TrackInfo) -> Result<Box<dyn AudioDecodeBackend>, BackendError>;
86}
87
88/// Decodes PCM tracks itself; other codecs go to `platform`.
89pub struct WithPcm<B>(pub B);
90
91impl<B: AudioBackends> AudioBackends for WithPcm<B> {
92    fn open(&self, track: &TrackInfo) -> Result<Box<dyn AudioDecodeBackend>, BackendError> {
93        match track.audio.as_ref().map(|audio| (audio.codec, audio)) {
94            Some((AudioCodec::Pcm(format), audio)) => Ok(Box::new(PcmSession::new(
95                format,
96                audio.sample_rate,
97                audio.channels,
98            )?)),
99            _ => self.0.open(track),
100        }
101    }
102}
103
104/// No platform decoder: only PCM decodes.
105#[derive(Clone, Copy, Debug, Default)]
106pub struct PcmOnly;
107
108impl AudioBackends for PcmOnly {
109    fn open(&self, track: &TrackInfo) -> Result<Box<dyn AudioDecodeBackend>, BackendError> {
110        let codec = track.audio.as_ref().map(|audio| audio.codec);
111        Err(BackendError::Unsupported(format!(
112            "no decoder here reads {codec:?} audio"
113        )))
114    }
115}
116
117/// Interleaved PCM to planar float.
118struct PcmSession {
119    format: PcmFormat,
120    sample_rate: u32,
121    channels: usize,
122    out: VecDeque<PcmChunk>,
123    ended: bool,
124}
125
126impl PcmSession {
127    fn new(format: PcmFormat, sample_rate: u32, channels: u32) -> Result<Self, BackendError> {
128        let supported = matches!(
129            (format.float, format.bits),
130            (false, 8 | 16 | 24 | 32) | (true, 32 | 64)
131        );
132        if !supported || channels == 0 || sample_rate == 0 {
133            return Err(BackendError::Unsupported(format!(
134                "PCM of {} bits ({}) in {channels} channels at {sample_rate} Hz",
135                format.bits,
136                if format.float { "float" } else { "integer" }
137            )));
138        }
139        Ok(Self {
140            format,
141            sample_rate,
142            channels: usize::try_from(channels).unwrap_or(usize::MAX),
143            out: VecDeque::new(),
144            ended: false,
145        })
146    }
147
148    #[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
149    fn sample(&self, bytes: &[u8]) -> f32 {
150        let PcmFormat {
151            bits,
152            float,
153            big_endian,
154            signed,
155        } = self.format;
156        let mut word = [0_u8; 8];
157        let width = usize::from(bits / 8);
158        for (at, byte) in bytes.iter().take(width).enumerate() {
159            let index = if big_endian { width - 1 - at } else { at };
160            word[index] = *byte;
161        }
162        let raw = u64::from_le_bytes(word);
163        match (float, bits) {
164            (true, 32) => f32::from_bits(u32::try_from(raw & 0xffff_ffff).unwrap_or(0)),
165            (true, _) => f64::from_bits(raw) as f32,
166            (false, 8) if !signed => (raw as f32 - 128.0) / 128.0,
167            (false, _) => {
168                let shift = 64 - u32::from(bits);
169                let value = (raw << shift).cast_signed() >> shift;
170                value as f32 / (1_u64 << (bits - 1)) as f32
171            }
172        }
173    }
174}
175
176impl AudioDecodeBackend for PcmSession {
177    fn submit(&mut self, packet: &Packet) -> Result<Submit, BackendError> {
178        let width = usize::from(self.format.bits / 8);
179        let frame = width * self.channels;
180        let frames = packet.data.len() / frame;
181        let mut planes = vec![Vec::with_capacity(frames); self.channels];
182        for index in 0..frames {
183            for (channel, plane) in planes.iter_mut().enumerate() {
184                let at = index * frame + channel * width;
185                plane.push(self.sample(&packet.data[at..at + width]));
186            }
187        }
188        self.out.push_back(PcmChunk {
189            pts: packet.pts,
190            sample_rate: self.sample_rate,
191            planes,
192            speakers: None,
193        });
194        Ok(Submit::Accepted)
195    }
196
197    fn receive(&mut self, _wait: bool) -> Result<AudioPoll, BackendError> {
198        Ok(match self.out.pop_front() {
199            Some(chunk) => AudioPoll::Chunk(chunk),
200            None if self.ended => AudioPoll::Drained,
201            None => AudioPoll::Pending,
202        })
203    }
204
205    fn finish_input(&mut self) -> Result<(), BackendError> {
206        self.ended = true;
207        Ok(())
208    }
209
210    fn flush(&mut self) -> Result<(), BackendError> {
211        self.out.clear();
212        self.ended = false;
213        Ok(())
214    }
215}
216
217/// Samples at 48 kHz an Opus decoder decodes before a seek target when the container declares no
218/// pre-roll: the 80 ms RFC 7845 section 4.6 asks for at least.
219const OPUS_SEEK_PREROLL: u32 = 3_840;
220
221/// The least Opus pre-roll, 400 ms at 48 kHz: the decoder keeps converging past the RFC's 80 ms,
222/// to under 1e-6 of a straight decode from 400 ms, the pre-roll of the desktop host.
223const OPUS_CONVERGED_PREROLL: u32 = 19_200;
224
225/// The least pre-roll for every codec, 100 ms: the desktop host's. A platform decoder resumed one
226/// frame before its target still differs from a straight decode by up to about 1e-4 for the next
227/// frames, so a codec's spec minimum alone would not give the samples the desktop host gives; the
228/// codec's own figure decides where it is longer (low sample rates).
229const SHARED_SEEK_PREROLL: MediaTime = MediaTime::from_ticks(TICKS_PER_SECOND / 10);
230
231/// Samples per block handed out.
232const BLOCK_FRAMES: usize = 1_024;
233
234/// Milliseconds each second of audio [`AudioStream::next_block`] hands out takes on top of its
235/// work, on every thread, for a test that needs a decode of known length. Test builds only.
236#[cfg(any(test, feature = "test-hooks"))]
237pub static INJECT_DECODE_DELAY_MS_PER_SECOND: std::sync::atomic::AtomicU64 =
238    std::sync::atomic::AtomicU64::new(0);
239
240#[derive(Clone, Copy, Debug, Eq, PartialEq)]
241enum Input {
242    Open,
243    Full,
244    Ended,
245    Drained,
246}
247
248/// An audio track decoded at the project rate.
249pub struct AudioStream {
250    reader: Box<dyn ContainerReader>,
251    track: TrackInfo,
252    backend: Box<dyn AudioDecodeBackend>,
253    project_rate: u32,
254    channels: usize,
255    speakers: SpeakerLayout,
256    timeline: SourceTimeline,
257    pending: Vec<VecDeque<f32>>,
258    next_sample: Option<i64>,
259    input: Input,
260    pending_packet: Option<Packet>,
261    /// Skip-samples of submitted packets, by presentation time.
262    discards: HashMap<i64, (u32, u32)>,
263    /// Skip-samples a packet left over for the decoded audio after it.
264    carried_skip: usize,
265    /// The frame grid of the first packet timestamps, which places the first chunk after an open
266    /// or seek where a straight decode puts it; `None` where timestamps are exact.
267    grid: Option<AudioFrameGrid>,
268    /// How far before its target a seek starts decoding ([`seek_preroll`]).
269    preroll: MediaTime,
270    recovery: Recovery,
271    info: Vec<StreamInfo>,
272}
273
274impl std::fmt::Debug for AudioStream {
275    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
276        formatter
277            .debug_struct("AudioStream")
278            .field("track", &self.track.id)
279            .finish_non_exhaustive()
280    }
281}
282
283/// The planes of `to`'s speakers, in its order, from `planes` of `from`'s; `planes` unchanged
284/// unless every speaker of `to` has its own plane. A back speaker stands in for the side speaker
285/// on its side that `from` lacks, and the other way round, since layouts name the surround pair
286/// of a 5.1 either way.
287fn select(mut planes: Vec<Vec<f32>>, from: SpeakerLayout, to: SpeakerLayout) -> Vec<Vec<f32>> {
288    let from = from.speakers();
289    if from.len() != planes.len() {
290        return planes;
291    }
292    let counterpart = |speaker: Speaker| match speaker {
293        Speaker::SideLeft => Some(Speaker::BackLeft),
294        Speaker::SideRight => Some(Speaker::BackRight),
295        Speaker::BackLeft => Some(Speaker::SideLeft),
296        Speaker::BackRight => Some(Speaker::SideRight),
297        _ => None,
298    };
299    let find = |speaker: Speaker| from.iter().position(|named| *named == speaker);
300    let positions = to
301        .speakers()
302        .iter()
303        .map(|&speaker| {
304            find(speaker).or_else(|| {
305                counterpart(speaker)
306                    .filter(|other| !to.speakers().contains(other))
307                    .and_then(find)
308            })
309        })
310        .collect::<Option<Vec<_>>>();
311    let Some(positions) = positions.filter(|positions| {
312        positions
313            .iter()
314            .enumerate()
315            .all(|(index, position)| !positions[..index].contains(position))
316    }) else {
317        return planes;
318    };
319    let mut taken = planes.iter_mut().map(std::mem::take).collect::<Vec<_>>();
320    positions
321        .into_iter()
322        .map(|position| std::mem::take(&mut taken[position]))
323        .collect()
324}
325
326/// The frame grid `track`'s first packet timestamps show ([`audio_frame_grid`]), read from
327/// `reader`, which the caller seeks back.
328fn frame_grid(
329    reader: &mut dyn ContainerReader,
330    track: &TrackInfo,
331    sample_rate: u32,
332) -> Result<Option<AudioFrameGrid>, DecodeError> {
333    let timestamps = crate::video_stream::first_timestamps(reader, track)?;
334    Ok(audio_frame_grid(
335        &timestamps,
336        1,
337        i64::from(track.timescale.max(1)),
338        sample_rate,
339    ))
340}
341
342/// How far before a seek target decoding starts, so samples from the target on come out as a
343/// straight decode gives them.
344///
345/// The codec's own need, at least [`SHARED_SEEK_PREROLL`], comes first, then one timestamp unit
346/// (the reader seeks by rounded timestamps) and the resampler's reach before its first output when
347/// the project rate differs.
348fn seek_preroll(audio: &AudioTrack, timescale: u32, project_rate: u32) -> MediaTime {
349    let rate = audio.sample_rate.max(1);
350    // Samples and the rate they are counted at.
351    let codec = match audio.codec {
352        // Each frame's IMDCT output is overlap-added with the previous frame's (ISO/IEC 14496-3
353        // 4.6.11), so the frame before the target's decodes first.
354        AudioCodec::Aac => {
355            Some(crate::aac::core_frame(&audio.codec_private).unwrap_or((1_024, rate)))
356        }
357        AudioCodec::Opus => {
358            let declared = audio.seek_preroll.unwrap_or(OPUS_SEEK_PREROLL);
359            Some((declared.max(OPUS_CONVERGED_PREROLL), 48_000))
360        }
361        // A packet's window overlaps the previous packet's, and blocks reach 8192 samples
362        // (Vorbis I specification 4.2.2).
363        AudioCodec::Vorbis => Some((8_192, rate)),
364        // Layer III `main_data_begin` reaches up to 511 bytes back (ISO/IEC 11172-3), six 96-byte
365        // frames at its lowest rate, plus one frame of filterbank overlap: 7 x 1152.
366        AudioCodec::Mp3 => Some((8_064, rate)),
367        // Each block's MDCT overlaps the previous block's; a frame is 1536 samples (ATSC A/52).
368        AudioCodec::Ac3 | AudioCodec::Eac3 => Some((1_536, rate)),
369        // The core's QMF history spans less than one frame of at most 4096 samples
370        // (ETSI TS 102 114).
371        AudioCodec::Dts => Some((4_096, rate)),
372        // Frames decode alone.
373        AudioCodec::Pcm(_) | AudioCodec::Flac | AudioCodec::Alac => Some((0, rate)),
374        AudioCodec::Other(_) => None,
375    };
376    let ticks = |samples: u64, rate: u32| {
377        let ticks = (u128::from(samples) * u128::from(TICKS_PER_SECOND.unsigned_abs()))
378            .div_ceil(u128::from(rate.max(1)));
379        i64::try_from(ticks).unwrap_or(i64::MAX)
380    };
381    let codec = codec
382        .map_or(0, |(samples, rate)| ticks(u64::from(samples), rate))
383        .max(SHARED_SEEK_PREROLL.ticks());
384    let unit = ticks(1, timescale);
385    let resampler = alpha2_audio::Resampler::new(rate, project_rate)
386        .ok()
387        .filter(|resampler| !resampler.is_identity())
388        .map_or(0, |resampler| {
389            ticks(resampler.half_taps().unsigned_abs(), rate)
390        });
391    MediaTime::from_ticks(codec.saturating_add(unit).saturating_add(resampler))
392}
393
394/// What [`Decoder::streams`] tells of audio track `index`.
395fn audio_stream_info(index: usize, track: &TrackInfo) -> Option<StreamInfo> {
396    let audio = track.audio.as_ref()?;
397    Some(StreamInfo {
398        index,
399        kind: StreamKind::Audio,
400        codec: format!("{:?}", audio.codec).to_lowercase(),
401        duration: track
402            .duration
403            .map(|duration| crate::video_stream::to_media_time(duration, track.timescale)),
404        dimensions: None,
405        frame_rate: None,
406        sample_rate: Some(audio.sample_rate),
407        channels: Some(audio.channels),
408        orientation: Orientation::default(),
409        sample_aspect_ratio: SampleAspectRatio { num: 1, den: 1 },
410        color: None,
411        frame_bytes: None,
412        alpha: None,
413        language: track.language.clone(),
414        title: track.title.clone(),
415    })
416}
417
418/// The speakers of a track's decoded planes.
419///
420/// PCM planes keep the container's order. Decoders of compressed audio deliver `FFmpeg`'s native
421/// channel order (the WAVE mask order), so a declared layout is put in that order, and a track
422/// that declares none takes its codec's layout for the channel count.
423fn decoded_speakers(audio: &AudioTrack, channels: usize) -> Option<SpeakerLayout> {
424    if matches!(audio.codec, AudioCodec::Pcm(_)) {
425        return audio
426            .speakers
427            .or_else(|| SpeakerLayout::default_for(channels));
428    }
429    if let Some(declared) = audio.speakers {
430        let mut speakers = declared.speakers().to_vec();
431        speakers.sort_by_key(|speaker| speaker.ffmpeg_channel());
432        return SpeakerLayout::new(&speakers);
433    }
434    let codec_layout = match audio.codec {
435        AudioCodec::Aac => crate::aac::layout(&audio.codec_private, channels),
436        AudioCodec::Opus | AudioCodec::Vorbis | AudioCodec::Flac => vorbis_family_layout(channels),
437        _ => None,
438    };
439    codec_layout.or_else(|| SpeakerLayout::default_for(channels))
440}
441
442/// The layouts Vorbis defines by channel count (Opus mapping family 1 and FLAC share them), in
443/// native order.
444fn vorbis_family_layout(channels: usize) -> Option<SpeakerLayout> {
445    use Speaker::{
446        BackCenter, BackLeft, BackRight, FrontCenter, FrontLeft, FrontRight, LowFrequency,
447        SideLeft, SideRight,
448    };
449    let speakers: &[Speaker] = match channels {
450        1 => &[FrontCenter],
451        2 => &[FrontLeft, FrontRight],
452        3 => &[FrontLeft, FrontRight, FrontCenter],
453        4 => &[FrontLeft, FrontRight, BackLeft, BackRight],
454        5 => &[FrontLeft, FrontRight, FrontCenter, BackLeft, BackRight],
455        6 => &[
456            FrontLeft,
457            FrontRight,
458            FrontCenter,
459            LowFrequency,
460            BackLeft,
461            BackRight,
462        ],
463        7 => &[
464            FrontLeft,
465            FrontRight,
466            FrontCenter,
467            LowFrequency,
468            BackCenter,
469            SideLeft,
470            SideRight,
471        ],
472        8 => &[
473            FrontLeft,
474            FrontRight,
475            FrontCenter,
476            LowFrequency,
477            BackLeft,
478            BackRight,
479            SideLeft,
480            SideRight,
481        ],
482        _ => return None,
483    };
484    SpeakerLayout::new(speakers)
485}
486
487impl AudioStream {
488    /// Opens audio track `stream` (an ordinal over the file's audio tracks in container order;
489    /// `None` is the default track) of the file at `path`, delivered at `project_rate`.
490    ///
491    /// # Errors
492    /// [`DecodeError::Unsupported`] for a container this layer does not read, a missing track,
493    /// or a track no session reads; read failures.
494    pub fn open_file(
495        path: &std::path::Path,
496        backends: &dyn AudioBackends,
497        project_rate: u32,
498        stream: Option<u32>,
499        policy: DecodePolicy,
500    ) -> Result<Self, DecodeError> {
501        let reader = alpha2_container::open(path)?;
502        let tracks = reader.tracks();
503        let index = match stream {
504            None => alpha2_container::default_track(tracks, TrackKind::Audio),
505            Some(ordinal) => tracks
506                .iter()
507                .enumerate()
508                .filter(|(_, track)| track.kind == TrackKind::Audio)
509                .nth(usize::try_from(ordinal).unwrap_or(usize::MAX))
510                .map(|(index, _)| index),
511        }
512        .ok_or_else(|| {
513            DecodeError::Unsupported(match stream {
514                Some(ordinal) => format!("the file has no audio stream {ordinal}"),
515                None => "the file has no audio stream".into(),
516            })
517        })?;
518        Self::open(reader, index, backends, project_rate, policy)
519    }
520
521    /// Opens track `index` of `reader`, delivered at `project_rate`.
522    ///
523    /// # Errors
524    /// [`DecodeError::Unsupported`] for a track that is not audio or that no session reads;
525    /// [`DecodeError::OutOfRange`] for a zero rate.
526    pub fn open(
527        mut reader: Box<dyn ContainerReader>,
528        index: usize,
529        backends: &dyn AudioBackends,
530        project_rate: u32,
531        policy: DecodePolicy,
532    ) -> Result<Self, DecodeError> {
533        if project_rate == 0 {
534            return Err(DecodeError::OutOfRange);
535        }
536        let track =
537            reader.tracks().get(index).cloned().ok_or_else(|| {
538                DecodeError::Unsupported(format!("the file has no track {index}"))
539            })?;
540        let Some(audio) = track.audio.clone() else {
541            return Err(DecodeError::Unsupported(format!(
542                "track {} is not audio",
543                track.id.0
544            )));
545        };
546        let backend = backends.open(&track)?;
547        let channels = usize::try_from(audio.channels).unwrap_or(0);
548        if channels == 0 || channels > alpha2_media::MAX_AUDIO_CHANNELS {
549            return Err(DecodeError::Unsupported(format!(
550                "audio with {channels} channels"
551            )));
552        }
553        let speakers = decoded_speakers(&audio, channels).ok_or_else(|| {
554            DecodeError::Unsupported(format!("no layout for {channels} channels"))
555        })?;
556        let grid = frame_grid(reader.as_mut(), &track, audio.sample_rate)?;
557        reader.seek(track.id, i64::MIN)?;
558        let mut recovery = Recovery::new((1, i32::try_from(track.timescale).unwrap_or(i32::MAX)));
559        recovery.policy = policy;
560        // Every audio stream of the file, as the desktop decoder lists them.
561        let info = reader
562            .tracks()
563            .iter()
564            .enumerate()
565            .filter_map(|(index, track)| audio_stream_info(index, track))
566            .collect();
567        Ok(Self {
568            reader,
569            backend,
570            project_rate,
571            channels,
572            speakers,
573            timeline: SourceTimeline::new(project_rate, channels, None),
574            pending: vec![VecDeque::new(); channels],
575            next_sample: None,
576            input: Input::Open,
577            pending_packet: None,
578            discards: HashMap::new(),
579            carried_skip: 0,
580            grid,
581            preroll: seek_preroll(&audio, track.timescale, project_rate),
582            recovery,
583            info,
584            track,
585        })
586    }
587
588    /// The track decoded.
589    #[must_use]
590    pub const fn track(&self) -> &TrackInfo {
591        &self.track
592    }
593
594    /// The speaker order of every block.
595    #[must_use]
596    pub const fn speakers(&self) -> SpeakerLayout {
597        self.speakers
598    }
599
600    /// Gaps and overlaps recorded so far.
601    #[must_use]
602    pub const fn recovery(&self) -> &Recovery {
603        &self.recovery
604    }
605
606    /// The next block of up to 1024 samples at the project rate; `None` at the end.
607    ///
608    /// # Errors
609    /// Cancellation, a spent work budget, or a decoder failure.
610    pub fn next_block(&mut self, cancel: &CancelToken) -> Result<Option<AudioBlock>, DecodeError> {
611        self.fill(BLOCK_FRAMES, cancel)?;
612        let frames = self.pending[0].len().min(BLOCK_FRAMES);
613        if frames == 0 {
614            return Ok(None);
615        }
616        #[cfg(any(test, feature = "test-hooks"))]
617        std::thread::sleep(std::time::Duration::from_nanos(
618            INJECT_DECODE_DELAY_MS_PER_SECOND
619                .load(std::sync::atomic::Ordering::Relaxed)
620                .saturating_mul(1_000_000)
621                .saturating_mul(u64::try_from(frames).unwrap_or(u64::MAX))
622                / u64::from(self.project_rate),
623        ));
624        let start_sample = self.next_sample.unwrap_or(0);
625        let channels = self
626            .pending
627            .iter_mut()
628            .map(|plane| plane.drain(..frames).collect())
629            .collect();
630        self.next_sample = Some(start_sample + i64::try_from(frames).unwrap_or(0));
631        Ok(Some(AudioBlock {
632            start_sample,
633            sample_rate: self.project_rate,
634            speakers: self.speakers,
635            channels,
636        }))
637    }
638
639    /// The block holding `time`'s sample, starting at that sample, or at the stream's first
640    /// sample for an earlier time.
641    ///
642    /// # Errors
643    /// [`DecodeError::OutOfRange`] past the end; otherwise as [`Self::next_block`].
644    pub fn seek(
645        &mut self,
646        time: MediaTime,
647        cancel: &CancelToken,
648    ) -> Result<AudioBlock, DecodeError> {
649        let target =
650            i128::from(time.ticks()) * i128::from(self.project_rate) / i128::from(TICKS_PER_SECOND);
651        let target = i64::try_from(target).unwrap_or(i64::MAX);
652        let from = MediaTime::from_ticks(time.ticks().saturating_sub(self.preroll.ticks()));
653        let units = i128::from(from.ticks()) * i128::from(self.track.timescale.max(1))
654            / i128::from(TICKS_PER_SECOND);
655        self.reader
656            .seek(self.track.id, i64::try_from(units).unwrap_or(i64::MIN))?;
657        self.restart(Some(target))?;
658        self.next_block(cancel)?.ok_or(DecodeError::OutOfRange)
659    }
660
661    fn restart(&mut self, first: Option<i64>) -> Result<(), DecodeError> {
662        self.backend.flush()?;
663        self.timeline = SourceTimeline::new(self.project_rate, self.channels, first);
664        self.pending.iter_mut().for_each(VecDeque::clear);
665        self.next_sample = None;
666        self.input = Input::Open;
667        self.pending_packet = None;
668        self.discards.clear();
669        self.carried_skip = 0;
670        self.recovery.reset_progress();
671        Ok(())
672    }
673
674    /// Decodes until `frames` samples are pending or the stream ends.
675    fn fill(&mut self, frames: usize, cancel: &CancelToken) -> Result<(), DecodeError> {
676        let mut budget = WorkBudget::new();
677        loop {
678            let held = self.pending[0].len();
679            if held >= frames {
680                return Ok(());
681            }
682            budget.step(cancel)?;
683            if let Some((start, _)) = self.timeline.produce(&mut self.pending, frames - held) {
684                if held == 0 {
685                    self.next_sample = Some(start);
686                }
687                budget.progressed();
688                continue;
689            }
690            if self.input == Input::Drained {
691                if self.timeline.finished() {
692                    return Ok(());
693                }
694                self.timeline.finish();
695                continue;
696            }
697            if self.step()? {
698                budget.advanced();
699            }
700        }
701    }
702
703    /// One receive, or one packet in; `true` when a packet was read or accepted.
704    fn step(&mut self) -> Result<bool, DecodeError> {
705        match self.backend.receive(self.input != Input::Open)? {
706            AudioPoll::Chunk(chunk) => {
707                if self.input == Input::Full {
708                    self.input = Input::Open;
709                }
710                return self.place(chunk).map(|()| false);
711            }
712            AudioPoll::Drained => {
713                self.input = Input::Drained;
714                return Ok(false);
715            }
716            AudioPoll::Pending => {}
717        }
718        if matches!(self.input, Input::Ended | Input::Drained) {
719            return Ok(false);
720        }
721        let mut advanced = false;
722        if self.pending_packet.is_none() {
723            if let Some(packet) = self.reader.next_packet(self.track.id)? {
724                self.pending_packet = Some(packet);
725                advanced = true;
726            } else {
727                self.backend.finish_input()?;
728                self.input = Input::Ended;
729                return Ok(false);
730            }
731        }
732        let Some(packet) = self.pending_packet.as_ref() else {
733            return Ok(advanced);
734        };
735        match self.backend.submit(packet)? {
736            Submit::Accepted => {
737                if packet.discard != (0, 0) {
738                    self.discards.insert(packet.pts, packet.discard);
739                }
740                self.pending_packet = None;
741                self.input = Input::Open;
742                advanced = true;
743            }
744            Submit::Busy => self.input = Input::Full,
745        }
746        Ok(advanced)
747    }
748
749    /// Drops a chunk's skip-samples and places it by its timestamp.
750    ///
751    /// A chunk whose packet carries no leading skip-samples has its samples before time 0
752    /// dropped instead: they are priming the container does not mark on that packet, as on a
753    /// packet a seek's pre-roll starts within the priming.
754    fn place(&mut self, mut chunk: PcmChunk) -> Result<(), DecodeError> {
755        if let Some(order) = chunk.speakers.filter(|order| *order != self.speakers) {
756            chunk.planes = select(chunk.planes, order, self.speakers);
757        }
758        if chunk.planes.len() != self.channels {
759            return Err(DecodeError::Adapter(format!(
760                "the decoder gave {} channels of a {}-channel track",
761                chunk.planes.len(),
762                self.channels
763            )));
764        }
765        let (front, back) = self.discards.remove(&chunk.pts).unwrap_or((0, 0));
766        let length = chunk.planes[0].len();
767        let rate = chunk.sample_rate;
768        let timescale = i64::from(self.track.timescale.max(1));
769        let scaled = i128::from(chunk.pts) * i128::from(rate) / i128::from(timescale);
770        let Some(scaled) = i64::try_from(scaled)
771            .ok()
772            .filter(|_| audio_timestamp_in_range(chunk.pts, 1, timescale))
773        else {
774            return self.recovery.corrupt("audio timestamp", Some(chunk.pts));
775        };
776        let before_zero = if front == 0 {
777            let start = self.source_start(scaled, length, rate);
778            usize::try_from(start.saturating_neg().max(0)).unwrap_or(usize::MAX)
779        } else {
780            0
781        };
782        // Skip-samples longer than their packet go on into the next ones, as `FFmpeg` skips them.
783        let front = usize::try_from(front)
784            .unwrap_or(usize::MAX)
785            .saturating_add(std::mem::take(&mut self.carried_skip))
786            .max(before_zero);
787        self.carried_skip = front.saturating_sub(length);
788        let front = front.min(length);
789        let back = usize::try_from(back)
790            .unwrap_or(usize::MAX)
791            .min(length - front);
792        for plane in &mut chunk.planes {
793            plane.truncate(length - back);
794            plane.drain(..front);
795        }
796        if chunk.planes[0].is_empty() {
797            return Ok(());
798        }
799        let mut at = scaled.saturating_add(i64::try_from(front).unwrap_or(i64::MAX));
800        let frames = i64::try_from(chunk.planes[0].len()).unwrap_or(i64::MAX);
801        match self.timeline.expected(rate) {
802            None => {
803                if let Some(grid) = self.grid_at(rate) {
804                    at = grid.place(at, frames);
805                }
806            }
807            Some(expected) if self.snaps(at, expected, rate) => at = expected,
808            Some(_) => {}
809        }
810        if let Some(expected) = self.timeline.expected(rate) {
811            if at < expected {
812                let overlap = usize::try_from(expected.saturating_sub(at)).unwrap_or(usize::MAX);
813                let dropped = overlap.min(chunk.planes[0].len());
814                let end = at.saturating_add(i64::try_from(dropped).unwrap_or(i64::MAX));
815                self.recovery.timestamp_overlap(at, end, rate);
816                for plane in &mut chunk.planes {
817                    plane.drain(..dropped);
818                }
819                at = end;
820                if chunk.planes[0].is_empty() {
821                    return Ok(());
822                }
823            } else if at > expected {
824                self.recovery.timestamp_gap(expected, at, rate);
825            }
826        }
827        self.timeline.place(rate, at, chunk.planes)
828    }
829
830    /// The frame grid, for chunks at the track's declared rate.
831    fn grid_at(&self, rate: u32) -> Option<AudioFrameGrid> {
832        let declared = self.track.audio.as_ref().map(|audio| audio.sample_rate);
833        self.grid.filter(|_| declared == Some(rate))
834    }
835
836    /// Whether a continuing chunk whose timestamp says `at` starts at `expected`, the end of the
837    /// samples before it.
838    ///
839    /// Both positions come from timestamps rounded to the container's unit (Matroska's
840    /// milliseconds): each is within half a unit of its exact position, and truncating to samples
841    /// adds under one sample to their difference. One unit rounded up to samples bounds it.
842    fn snaps(&self, at: i64, expected: i64, rate: u32) -> bool {
843        let unit = u64::from(rate).div_ceil(u64::from(self.track.timescale.max(1)));
844        unit > 1 && at.abs_diff(expected) <= unit
845    }
846
847    /// Where a `length`-sample chunk whose timestamp says `scaled` starts before any skip, as
848    /// [`Self::place`] would put it.
849    fn source_start(&self, scaled: i64, length: usize, rate: u32) -> i64 {
850        let frames = i64::try_from(length).unwrap_or(i64::MAX);
851        match self.timeline.expected(rate) {
852            None => self
853                .grid_at(rate)
854                .map_or(scaled, |grid| grid.place(scaled, frames)),
855            Some(expected) if self.snaps(scaled, expected, rate) => expected,
856            Some(_) => scaled,
857        }
858    }
859}
860
861impl Decoder for AudioStream {
862    fn streams(&self) -> &[StreamInfo] {
863        &self.info
864    }
865
866    fn flush(&mut self) -> Result<(), DecodeError> {
867        self.reader.seek(self.track.id, i64::MIN)?;
868        self.restart(None)
869    }
870
871    fn seek(
872        &mut self,
873        request: DecodeRequest,
874        cancel: &CancelToken,
875    ) -> Result<DecodeResult, DecodeError> {
876        let block = AudioStream::seek(self, request.time, cancel)?;
877        Ok(DecodeResult {
878            request,
879            event: DecodeEvent::Audio(block),
880        })
881    }
882
883    fn decode_next(&mut self, cancel: &CancelToken) -> Result<DecodeEvent, DecodeError> {
884        Ok(match self.next_block(cancel)? {
885            Some(block) => DecodeEvent::Audio(block),
886            None => DecodeEvent::EndOfStream,
887        })
888    }
889}
890
891#[cfg(test)]
892#[path = "audio_stream_tests.rs"]
893mod tests;
894
895/// A stream behind a mix's audio windows; its blocks hold at most `BLOCK_FRAMES` samples.
896#[cfg(feature = "engine")]
897impl crate::audio_windows::WindowedAudioDecoder for AudioStream {
898    fn channels(&self) -> usize {
899        self.channels
900    }
901
902    fn speakers(&self) -> SpeakerLayout {
903        self.speakers
904    }
905
906    fn audio_duration(&self) -> Option<MediaTime> {
907        self.info.first().and_then(|info| info.duration)
908    }
909}