Skip to main content

alpha2_host_core/
audio_windows.rs

1//! Decoded audio held in windows around what a mix reads, within a byte budget: each source's
2//! decoder moves forward with a clip playing through, and seeks for other reads.
3
4use std::collections::HashMap;
5
6use alpha2_media::{
7    AudioBlock, AudioBlockProvider, AudioSpan, CancelToken, DecodeError, DecodeEvent,
8    DecodeRequest, DecodeRequestKind, Decoder, SourceId, SpeakerLayout,
9};
10use alpha2_time::{MediaTime, TICKS_PER_SECOND};
11
12/// Samples each side of a read the mix's interpolation reaches.
13pub const AUDIO_INTERPOLATION_MARGIN: i64 = 2;
14
15/// A source's audio decoder as the windows drive it.
16pub trait WindowedAudioDecoder: Decoder {
17    /// Channels of every block it returns.
18    fn channels(&self) -> usize;
19    /// The speaker each channel feeds.
20    fn speakers(&self) -> SpeakerLayout;
21    /// Where the source's audio ends, as the project reads it; `None` when unknown.
22    fn audio_duration(&self) -> Option<MediaTime>;
23}
24
25/// Why the windows could not hold what a mix reads.
26#[derive(Clone, Debug, Eq, PartialEq)]
27pub enum AudioWindowError {
28    /// A source the mix reads has no file.
29    MissingInput(String),
30    /// The windows cannot fit the byte budget.
31    ResourceLimit(String),
32    /// A decoder failed.
33    Decode(DecodeError),
34    /// A decoder broke its contract.
35    Broken(String),
36}
37
38impl std::fmt::Display for AudioWindowError {
39    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        match self {
41            Self::MissingInput(message) | Self::ResourceLimit(message) | Self::Broken(message) => {
42                formatter.write_str(message)
43            }
44            Self::Decode(error) => write!(formatter, "{error}"),
45        }
46    }
47}
48
49impl std::error::Error for AudioWindowError {}
50
51/// A byte budget a scale may shrink, which still holds what one read needs up to the unscaled
52/// budget: only a budget too small before any scale refuses.
53#[derive(Copy, Clone, Debug, Eq, PartialEq)]
54pub struct ByteBudget {
55    /// The budget after the scale.
56    pub bytes: u64,
57    /// The unscaled budget.
58    pub ceiling: u64,
59}
60
61impl ByteBudget {
62    /// A budget no scale shrank.
63    #[must_use]
64    pub const fn exact(bytes: u64) -> Self {
65        Self {
66            bytes,
67            ceiling: bytes,
68        }
69    }
70
71    /// The budget, or `least` up to the unscaled budget where the scale shrank it below that.
72    #[must_use]
73    pub fn holding(self, least: u64) -> u64 {
74        self.bytes.max(least.min(self.ceiling))
75    }
76}
77
78impl From<u64> for ByteBudget {
79    fn from(bytes: u64) -> Self {
80        Self::exact(bytes)
81    }
82}
83
84/// Opens a source's audio stream (`None` is its default one) for the windows.
85pub type OpenAudio<D> =
86    Box<dyn FnMut(&SourceId, Option<u32>) -> Result<D, AudioWindowError> + Send>;
87
88/// One window of a source stream and the decoder that fills it.
89pub struct WindowedAudioSource<D> {
90    /// The decoder filling the window.
91    pub decoder: D,
92    /// The decoded samples held, from the read's start.
93    pub window: Option<AudioBlock>,
94    /// The request can start before the stream's first sample; that prefix is known silence and
95    /// is not allocated.
96    covered_start: i64,
97    /// Past the window the source is silent.
98    ended: bool,
99    /// A read before this moves backward, as a reversed clip reads.
100    last_start: Option<i64>,
101}
102
103/// Seeking this far before a backward read lets the following, slightly earlier reads continue the
104/// window.
105const BACKWARD_READAHEAD_SECONDS: i64 = 1;
106
107/// A window filled to a sample ends at most one block past it.
108const AUDIO_DECODE_BLOCK_FRAMES: usize = 4_096;
109
110impl<D: WindowedAudioDecoder> WindowedAudioSource<D> {
111    fn continues_at(&self, start: i64) -> bool {
112        self.window.as_ref().is_some_and(|window| {
113            let window_start = window.start_sample;
114            let window_end = window_start.saturating_add(audio_block_frames(window));
115            start >= self.covered_start && (start <= window_end || self.ended)
116        })
117    }
118
119    /// The full growth is reserved and checked against `limit` before anything past the first
120    /// block is decoded.
121    fn ensure_window(
122        &mut self,
123        source: &SourceId,
124        (start, end): (i64, i64),
125        sample_rate: u32,
126        limit: u64,
127        cancel: &CancelToken,
128    ) -> Result<(), AudioWindowError> {
129        let backward = self.last_start.is_some_and(|last| start < last);
130        self.last_start = Some(start);
131        if !self.continues_at(start) {
132            let seek_start = if backward {
133                start
134                    .saturating_sub(BACKWARD_READAHEAD_SECONDS * i64::from(sample_rate))
135                    .max(0)
136            } else {
137                start
138            };
139            let request_time =
140                MediaTime::from_ticks(samples_to_ticks_ceil(seek_start, sample_rate));
141            crate::request_watch::beat_request();
142            let result = self.decoder.seek(
143                DecodeRequest {
144                    source: source.clone(),
145                    time: request_time,
146                    kind: DecodeRequestKind::Seek,
147                    generation: 0,
148                },
149                cancel,
150            );
151            match result {
152                Ok(result) => {
153                    let DecodeEvent::Audio(block) = result.event else {
154                        return Err(AudioWindowError::Broken(format!(
155                            "audio source {} did not decode a block",
156                            source.as_str()
157                        )));
158                    };
159                    self.window = Some(block);
160                    self.ended = false;
161                }
162                // Past the stream's end (audio that stops early) the source is silent.
163                Err(DecodeError::OutOfRange) => {
164                    self.window = Some(AudioBlock {
165                        start_sample: seek_start,
166                        sample_rate,
167                        speakers: self.decoder.speakers(),
168                        channels: vec![Vec::new(); self.decoder.channels()],
169                    });
170                    self.ended = true;
171                }
172                Err(error) => return Err(AudioWindowError::Decode(error)),
173            }
174            self.covered_start = seek_start.min(start);
175        }
176        self.reserve_to(source, end, limit)?;
177        loop {
178            let window = self
179                .window
180                .as_ref()
181                .ok_or_else(|| AudioWindowError::Broken("audio window disappeared".to_owned()))?;
182            let window_start = window.start_sample;
183            let window_end = window_start.saturating_add(audio_block_frames(window));
184            if window_end >= end || self.ended {
185                break;
186            }
187            crate::request_watch::beat_request();
188            match self
189                .decoder
190                .decode_next(cancel)
191                .map_err(AudioWindowError::Decode)?
192            {
193                DecodeEvent::Audio(block) => append_audio_block(
194                    self.window.as_mut().ok_or_else(|| {
195                        AudioWindowError::Broken("audio window disappeared".to_owned())
196                    })?,
197                    block,
198                )?,
199                DecodeEvent::EndOfStream => {
200                    self.ended = true;
201                    break;
202                }
203                DecodeEvent::Retry | DecodeEvent::Video(_) => {}
204            }
205        }
206        let declared_duration = self.decoder.audio_duration();
207        let window = self
208            .window
209            .as_mut()
210            .ok_or_else(|| AudioWindowError::Broken("audio window disappeared".to_owned()))?;
211        if self.ended {
212            pad_audio_window_to_declared_end(window, end, declared_duration, sample_rate);
213        }
214        // Reading backward, what lies before this read is what the next reads want.
215        if !backward {
216            trim_audio_window(window, start);
217            self.covered_start = start;
218        }
219        Ok(())
220    }
221
222    /// Reserves every channel up to `end` plus the decoder block that may run past it, so the
223    /// window's growth never doubles past what was checked.
224    fn reserve_to(
225        &mut self,
226        source: &SourceId,
227        end: i64,
228        limit: u64,
229    ) -> Result<(), AudioWindowError> {
230        let ended = self.ended;
231        let Some(window) = self.window.as_mut() else {
232            return Ok(());
233        };
234        let held = audio_block_frames(window);
235        if ended || window.start_sample.saturating_add(held) >= end {
236            return Ok(());
237        }
238        let frames = usize::try_from(end.saturating_sub(window.start_sample))
239            .unwrap_or(usize::MAX)
240            .saturating_add(AUDIO_DECODE_BLOCK_FRAMES);
241        let bytes = u64::try_from(frames)
242            .unwrap_or(u64::MAX)
243            .saturating_mul(u64::try_from(window.channels.len()).unwrap_or(u64::MAX))
244            .saturating_mul(4);
245        if bytes > limit {
246            return Err(AudioWindowError::ResourceLimit(format!(
247                "the audio mix reads {frames} samples of {} channels of source {} at once, \
248                 {bytes} bytes, over the {limit} bytes the audio window budget has left",
249                window.channels.len(),
250                source.as_str(),
251            )));
252        }
253        for channel in &mut window.channels {
254            channel.reserve_exact(frames.saturating_sub(channel.len()));
255        }
256        Ok(())
257    }
258}
259
260/// A source's audio stream as the mix reads it (`AudioNeed::stream`); `None` is the default one.
261pub type AudioStreamKey = (SourceId, Option<u32>);
262
263/// Every source stream's windows, for one mix.
264pub struct WindowedAudioSources<D> {
265    /// The rate the mix reads at.
266    pub sample_rate: u32,
267    open: OpenAudio<D>,
268    /// One window per disjoint range of a source stream: two clips of one media may read
269    /// unrelated ranges, and one window over both would decode and retain everything between.
270    pub sources: HashMap<AudioStreamKey, Vec<WindowedAudioSource<D>>>,
271    /// A block that needs more than a scaled budget still gets up to the unscaled one
272    /// ([`ByteBudget::holding`]).
273    pub byte_budget: ByteBudget,
274    /// Bytes the windows hold after the last [`Self::prepare`].
275    pub retained_bytes: u64,
276    /// The most bytes the windows held after any [`Self::prepare`].
277    pub peak_bytes: u64,
278}
279
280impl<D: WindowedAudioDecoder> WindowedAudioSources<D> {
281    /// Windows at `sample_rate` within `byte_budget`, opening source streams with `open` as the
282    /// mix first reads them.
283    #[must_use]
284    pub fn new(sample_rate: u32, byte_budget: impl Into<ByteBudget>, open: OpenAudio<D>) -> Self {
285        Self {
286            sample_rate,
287            open,
288            sources: HashMap::new(),
289            byte_budget: byte_budget.into(),
290            retained_bytes: 0,
291            peak_bytes: 0,
292        }
293    }
294
295    /// Decodes what `needs` reads, plus the interpolation margin, and drops unneeded windows.
296    ///
297    /// # Errors
298    /// Fails with `RESOURCE_LIMIT` when the windows cannot fit the budget, and with the
299    /// decoder's error or a cancellation otherwise.
300    pub fn prepare(
301        &mut self,
302        needs: &[alpha2_engine::AudioNeed],
303        cancel: &CancelToken,
304    ) -> Result<(), AudioWindowError> {
305        let mut ranges = HashMap::<AudioStreamKey, Vec<(i64, i64)>>::new();
306        for need in needs {
307            let start = ticks_to_samples(need.source_range.start().ticks(), self.sample_rate)
308                .saturating_sub(AUDIO_INTERPOLATION_MARGIN)
309                .max(0);
310            let end = ticks_to_samples_ceil(need.source_range.end().ticks(), self.sample_rate)
311                .saturating_add(AUDIO_INTERPOLATION_MARGIN);
312            if end > start {
313                ranges
314                    .entry((need.source_id.clone(), need.stream))
315                    .or_default()
316                    .push((start, end));
317            }
318        }
319        // The least the windows will hold, in 32-bit samples per channel. A mix that cannot fit is
320        // refused before decoding.
321        let least = ranges.iter().fold(0_u64, |bytes, (source, spans)| {
322            let channels = self
323                .sources
324                .get(source)
325                .and_then(|states| states.first())
326                .map_or(1, |state| state.decoder.channels().max(1));
327            spans.iter().fold(bytes, |bytes, &(start, end)| {
328                bytes.saturating_add(
329                    u64::try_from(end.saturating_sub(start))
330                        .unwrap_or(u64::MAX)
331                        .saturating_mul(u64::try_from(channels).unwrap_or(u64::MAX))
332                        .saturating_mul(4),
333                )
334            })
335        });
336        let budget = self.byte_budget.holding(least);
337        if least > budget {
338            return Err(AudioWindowError::ResourceLimit(format!(
339                "the audio mix needs at least {least} bytes of decoded audio at once, over the {budget} byte audio window budget"
340            )));
341        }
342        self.sources.retain(|source, _| ranges.contains_key(source));
343        for (source, spans) in ranges {
344            self.ensure_windows(&source, &merge_sample_ranges(spans), budget, cancel)?;
345        }
346        self.retained_bytes = window_bytes(self.sources.values().flatten());
347        if self.retained_bytes > budget {
348            return Err(AudioWindowError::ResourceLimit(format!(
349                "decoded audio window exceeds {budget} byte budget"
350            )));
351        }
352        self.peak_bytes = self.peak_bytes.max(self.retained_bytes);
353        Ok(())
354    }
355
356    /// A span that continues a window keeps its decoder, so a clip playing through reads
357    /// sequentially. Other spans seek an unused window or open a decoder.
358    fn ensure_windows(
359        &mut self,
360        source: &AudioStreamKey,
361        spans: &[(i64, i64)],
362        budget: u64,
363        cancel: &CancelToken,
364    ) -> Result<(), AudioWindowError> {
365        let sample_rate = self.sample_rate;
366        let mut idle = self.sources.remove(source).unwrap_or_default();
367        let continued = spans
368            .iter()
369            .map(|&(start, _)| {
370                idle.iter()
371                    .position(|state| state.continues_at(start))
372                    .map(|index| idle.swap_remove(index))
373            })
374            .collect::<Vec<_>>();
375        let mut windows = Vec::with_capacity(spans.len());
376        let mut continued = continued.into_iter();
377        for &span in spans {
378            let mut state = match continued.next().flatten().or_else(|| idle.pop()) {
379                Some(state) => state,
380                None => self.open(&source.0, source.1)?,
381            };
382            let held = window_bytes(self.sources.values().flatten())
383                .saturating_add(window_bytes(&idle))
384                .saturating_add(window_bytes(&windows))
385                .saturating_add(window_bytes(continued.as_slice().iter().flatten()));
386            state.ensure_window(
387                &source.0,
388                span,
389                sample_rate,
390                budget.saturating_sub(held),
391                cancel,
392            )?;
393            windows.push(state);
394        }
395        self.sources.insert(source.clone(), windows);
396        Ok(())
397    }
398
399    fn open(
400        &mut self,
401        source: &SourceId,
402        stream: Option<u32>,
403    ) -> Result<WindowedAudioSource<D>, AudioWindowError> {
404        Ok(WindowedAudioSource {
405            decoder: (self.open)(source, stream)?,
406            window: None,
407            covered_start: 0,
408            ended: false,
409            last_start: None,
410        })
411    }
412
413    /// Opens source streams with `open` from now on and keeps the windows and decoders of the
414    /// sources `keep` names; the others are dropped and open again when the mix reads them.
415    pub fn rebind(&mut self, open: OpenAudio<D>, keep: impl Fn(&SourceId) -> bool) {
416        self.open = open;
417        self.sources.retain(|(source, _), _| keep(source));
418        self.retained_bytes = window_bytes(self.sources.values().flatten());
419    }
420
421    /// The most decoded audio the windows held at once.
422    #[must_use]
423    pub const fn peak_bytes(&self) -> u64 {
424        self.peak_bytes
425    }
426}
427
428impl<D: WindowedAudioDecoder> AudioBlockProvider for WindowedAudioSources<D> {
429    /// Windows are decoded in whole decoder blocks, so one can run past the start of another; the
430    /// first window holding the read's start is not always the one that holds the read.
431    fn block(
432        &self,
433        source: &SourceId,
434        stream: Option<u32>,
435        start_sample: i64,
436        frames: usize,
437    ) -> Option<AudioSpan<'_>> {
438        let request_end = start_sample.saturating_add(i64::try_from(frames).unwrap_or(i64::MAX));
439        let spans = self
440            .sources
441            .get(&(source.clone(), stream))?
442            .iter()
443            .filter_map(|state| {
444                let window = state.window.as_ref()?;
445                let window_start = window.start_sample;
446                let window_end = window_start.saturating_add(audio_block_frames(window));
447                (start_sample >= state.covered_start && (start_sample < window_end || state.ended))
448                    .then_some(AudioSpan {
449                        block: window,
450                        // A seek before the first sample decodes from it; what lies before is silence.
451                        starts_source: state.covered_start < window_start,
452                        // A clip ending exactly at the stream's end reads interpolation samples past
453                        // it.
454                        ends_source: state.ended,
455                    })
456            });
457        let mut first = None;
458        for span in spans {
459            if span.covers(start_sample, request_end) {
460                return Some(span);
461            }
462            first.get_or_insert(span);
463        }
464        first
465    }
466}
467
468/// `ranges` sorted, with overlapping and touching ones merged.
469#[must_use]
470pub fn merge_sample_ranges(mut ranges: Vec<(i64, i64)>) -> Vec<(i64, i64)> {
471    ranges.sort_unstable();
472    let mut merged: Vec<(i64, i64)> = Vec::with_capacity(ranges.len());
473    for (start, end) in ranges {
474        match merged.last_mut() {
475            Some(last) if start <= last.1 => last.1 = last.1.max(end),
476            _ => merged.push((start, end)),
477        }
478    }
479    merged
480}
481
482/// Samples per channel `block` holds.
483#[must_use]
484pub fn audio_block_frames(block: &AudioBlock) -> i64 {
485    block
486        .channels
487        .first()
488        .and_then(|channel| i64::try_from(channel.len()).ok())
489        .unwrap_or(0)
490}
491
492fn window_bytes<'a, D: 'a>(states: impl IntoIterator<Item = &'a WindowedAudioSource<D>>) -> u64 {
493    states.into_iter().fold(0_u64, |bytes, state| {
494        bytes.saturating_add(state.window.as_ref().map_or(0, audio_block_bytes))
495    })
496}
497
498/// Bytes `block`'s 32-bit samples take.
499#[must_use]
500pub fn audio_block_bytes(block: &AudioBlock) -> u64 {
501    block.channels.iter().fold(0_u64, |bytes, channel| {
502        bytes.saturating_add(
503            u64::try_from(channel.len())
504                .unwrap_or(u64::MAX)
505                .saturating_mul(4),
506        )
507    })
508}
509
510/// # Errors
511/// Fails when the format changes or `block` does not start exactly where `window` ends.
512pub fn append_audio_block(
513    window: &mut AudioBlock,
514    block: AudioBlock,
515) -> Result<(), AudioWindowError> {
516    if window.sample_rate != block.sample_rate || window.channels.len() != block.channels.len() {
517        return Err(AudioWindowError::Broken(
518            "decoded audio format changed inside a source".to_owned(),
519        ));
520    }
521    if block.start_sample
522        != window
523            .start_sample
524            .saturating_add(audio_block_frames(window))
525    {
526        return Err(AudioWindowError::Broken(
527            "decoded audio has an unreported gap or overlap inside AudioSpan".to_owned(),
528        ));
529    }
530    for (output, input) in window.channels.iter_mut().zip(block.channels) {
531        output.extend(input);
532    }
533    Ok(())
534}
535
536/// Pads no further than the declared duration plus the interpolation margin; does nothing without
537/// a declared duration.
538pub fn pad_audio_window_to_declared_end(
539    window: &mut AudioBlock,
540    requested_end: i64,
541    declared_duration: Option<MediaTime>,
542    sample_rate: u32,
543) {
544    let window_start = window.start_sample;
545    let window_end = window_start.saturating_add(audio_block_frames(window));
546    let Some(declared_end) =
547        declared_duration.map(|duration| ticks_to_samples_ceil(duration.ticks(), sample_rate))
548    else {
549        return;
550    };
551    let padded_end = requested_end.min(declared_end.saturating_add(AUDIO_INTERPOLATION_MARGIN));
552    let Ok(padding) = usize::try_from(padded_end.saturating_sub(window_end).max(0)) else {
553        return;
554    };
555    if padding == 0 {
556        return;
557    }
558    for channel in &mut window.channels {
559        channel.resize(channel.len().saturating_add(padding), 0.0);
560    }
561}
562
563/// Drops what `window` holds before `requested_start`.
564pub fn trim_audio_window(window: &mut AudioBlock, requested_start: i64) {
565    let window_start = window.start_sample;
566    let discard = usize::try_from(requested_start.saturating_sub(window_start).max(0))
567        .unwrap_or(usize::MAX)
568        .min(window.channels.first().map_or(0, Vec::len));
569    if discard == 0 {
570        return;
571    }
572    for channel in &mut window.channels {
573        channel.drain(..discard.min(channel.len()));
574    }
575    window.start_sample = window_start.saturating_add(i64::try_from(discard).unwrap_or(i64::MAX));
576}
577
578/// Rounds toward negative infinity.
579#[must_use]
580pub fn ticks_to_samples(ticks: i64, sample_rate: u32) -> i64 {
581    ticks
582        .saturating_mul(i64::from(sample_rate))
583        .div_euclid(TICKS_PER_SECOND)
584}
585
586/// Rounds up.
587#[must_use]
588pub fn ticks_to_samples_ceil(ticks: i64, sample_rate: u32) -> i64 {
589    let numerator = i128::from(ticks).saturating_mul(i128::from(sample_rate));
590    let denominator = i128::from(TICKS_PER_SECOND);
591    let samples =
592        numerator.div_euclid(denominator) + i128::from(numerator.rem_euclid(denominator) != 0);
593    i64::try_from(samples).unwrap_or(i64::MAX)
594}
595
596/// Rounds up; a zero rate is treated as 1.
597#[must_use]
598pub fn samples_to_ticks_ceil(samples: i64, sample_rate: u32) -> i64 {
599    let numerator = i128::from(samples).saturating_mul(i128::from(TICKS_PER_SECOND));
600    let denominator = i128::from(sample_rate.max(1));
601    let ticks =
602        numerator.div_euclid(denominator) + i128::from(numerator.rem_euclid(denominator) != 0);
603    i64::try_from(ticks).unwrap_or(i64::MAX)
604}
605
606impl<D: WindowedAudioDecoder> crate::audio_host::ProjectAudioSources for WindowedAudioSources<D> {
607    fn prepare(
608        &mut self,
609        needs: &[alpha2_engine::AudioNeed],
610        cancel: &CancelToken,
611    ) -> Result<(), AudioWindowError> {
612        Self::prepare(self, needs, cancel)
613    }
614}