Skip to main content

alpha2_host_core/
audio_frames.rs

1//! Project audio cut into an encoder's frames at the encoder's rate.
2
3use std::collections::VecDeque;
4
5use alpha2_media::{AudioBlock, EncodeError};
6
7use crate::audio_timeline::SourceTimeline;
8
9/// The rate an encoder that supports `rates` (`None`: any) encodes a `project_rate` project at:
10/// that rate if supported, else the lowest above it, else its highest.
11#[must_use]
12pub fn encoder_sample_rate(rates: Option<&[u32]>, project_rate: u32) -> u32 {
13    let Some(rates) = rates else {
14        return project_rate;
15    };
16    let rates = rates
17        .iter()
18        .copied()
19        .filter(|rate| *rate > 0)
20        .collect::<Vec<_>>();
21    if rates.contains(&project_rate) {
22        return project_rate;
23    }
24    rates
25        .iter()
26        .copied()
27        .filter(|rate| *rate > project_rate)
28        .min()
29        .or_else(|| rates.iter().copied().max())
30        .unwrap_or(project_rate)
31}
32
33/// Project-rate audio blocks cut into the encoder's frames at its own rate.
34pub struct EncoderAudioInput {
35    project_rate: u32,
36    channels: usize,
37    frame_size: usize,
38    /// Brings the project's audio to the encoder's rate, when they differ.
39    resampler: Option<SourceTimeline>,
40    /// Samples at the encoder's rate not yet handed over.
41    pending: Vec<VecDeque<f32>>,
42    /// Project-rate samples accepted.
43    received: u64,
44}
45
46impl EncoderAudioInput {
47    /// Cuts `channels` planes at `project_rate` into `frame_size`-sample frames at `encoder_rate`.
48    #[must_use]
49    pub fn new(project_rate: u32, encoder_rate: u32, channels: usize, frame_size: usize) -> Self {
50        Self {
51            project_rate,
52            channels,
53            frame_size,
54            resampler: (encoder_rate != project_rate)
55                .then(|| SourceTimeline::new(encoder_rate, channels, Some(0))),
56            pending: (0..channels).map(|_| VecDeque::new()).collect(),
57            received: 0,
58        }
59    }
60
61    /// Takes the next block, which must start where the last ended, and returns the
62    /// whole frames it completes.
63    ///
64    /// # Errors
65    /// A block of another rate or channel count, of unequal channels, or out of order.
66    pub fn push(&mut self, block: &AudioBlock) -> Result<Vec<Vec<Vec<f32>>>, EncodeError> {
67        if block.sample_rate != self.project_rate
68            || block.channels.len() != self.channels
69            || block.channels.is_empty()
70        {
71            return Err(EncodeError::Adapter("audio block format changed".into()));
72        }
73        let frames = block.channels[0].len();
74        if block.channels.iter().any(|channel| channel.len() != frames) {
75            return Err(EncodeError::Adapter("audio channel lengths differ".into()));
76        }
77        if u64::try_from(block.start_sample).ok() != Some(self.received) {
78            return Err(EncodeError::InvalidTimestamp);
79        }
80        match self.resampler.as_mut() {
81            Some(resampler) => {
82                resampler
83                    .place(
84                        self.project_rate,
85                        block.start_sample,
86                        block.channels.clone(),
87                    )
88                    .map_err(|error| EncodeError::Adapter(error.to_string()))?;
89                resampler.produce(&mut self.pending, usize::MAX);
90            }
91            None => {
92                for (pending, channel) in self.pending.iter_mut().zip(&block.channels) {
93                    pending.extend(channel.iter().copied());
94                }
95            }
96        }
97        self.received = self
98            .received
99            .saturating_add(u64::try_from(frames).unwrap_or(u64::MAX));
100        let mut ready = Vec::new();
101        while self.pending[0].len() >= self.frame_size {
102            ready.push(self.take(self.frame_size));
103        }
104        Ok(ready)
105    }
106
107    /// Ends the input and returns the remaining frames, the last as long as what is left.
108    pub fn finish(&mut self) -> Vec<Vec<Vec<f32>>> {
109        if let Some(resampler) = self.resampler.as_mut() {
110            resampler.finish();
111            resampler.produce(&mut self.pending, usize::MAX);
112        }
113        let mut frames = Vec::new();
114        while !self.pending[0].is_empty() {
115            frames.push(self.take(self.frame_size.min(self.pending[0].len())));
116        }
117        frames
118    }
119
120    /// The input time accepted so far in ticks, reported back as consumed
121    /// once its frames are encoded.
122    #[must_use]
123    pub fn received_ticks(&self) -> i64 {
124        i64::try_from(self.received)
125            .unwrap_or(i64::MAX)
126            .saturating_mul(alpha2_time::TICKS_PER_SECOND)
127            .div_euclid(i64::from(self.project_rate))
128    }
129
130    fn take(&mut self, samples: usize) -> Vec<Vec<f32>> {
131        self.pending
132            .iter_mut()
133            .map(|pending| pending.drain(..samples).collect())
134            .collect()
135    }
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    #[test]
143    fn the_project_rate_is_kept_else_the_next_higher_else_the_highest() {
144        assert_eq!(encoder_sample_rate(None, 44_100), 44_100);
145        let opus = [48_000, 24_000, 16_000, 12_000, 8_000];
146        assert_eq!(encoder_sample_rate(Some(&opus), 44_100), 48_000);
147        assert_eq!(encoder_sample_rate(Some(&opus), 16_000), 16_000);
148        assert_eq!(encoder_sample_rate(Some(&opus), 96_000), 48_000);
149        assert_eq!(encoder_sample_rate(Some(&[0]), 32_000), 32_000);
150    }
151
152    #[test]
153    fn blocks_are_cut_into_whole_frames_and_the_tail_is_kept_short() {
154        let mut input = EncoderAudioInput::new(48_000, 48_000, 2, 1_024);
155        let block = |start: i64, frames: usize| AudioBlock {
156            start_sample: start,
157            sample_rate: 48_000,
158            speakers: alpha2_media::SpeakerLayout::STEREO,
159            channels: vec![vec![0.25; frames]; 2],
160        };
161        assert_eq!(input.push(&block(0, 1_000)).expect("first").len(), 0);
162        let ready = input.push(&block(1_000, 2_000)).expect("second");
163        assert_eq!(ready.len(), 2);
164        assert!(ready.iter().all(|frame| frame[0].len() == 1_024));
165        assert_eq!(
166            input.push(&block(10, 4)),
167            Err(EncodeError::InvalidTimestamp)
168        );
169        let tail = input.finish();
170        assert_eq!(tail.len(), 1);
171        assert_eq!(tail[0][0].len(), 3_000 - 2_048);
172        assert_eq!(input.received_ticks(), alpha2_time::TICKS_PER_SECOND / 16);
173    }
174}