Skip to main content

alpha2_engine/extract/
timeline_audio.rs

1//! Turns blocks of the project mix into the blocks a timeline audio need asks for.
2
3use std::ops::Range;
4
5use alpha2_audio::{ResampleError, Resampler};
6
7use super::descriptor::AudioChannels;
8use super::session::SuppliedAudio;
9
10/// Most project-rate samples [`TimelineAudioRead::wanted`] asks for at once.
11pub const TIMELINE_MIX_BLOCK: usize = 4_096;
12
13const BACKWARD_WINDOW_SECONDS: i64 = 1;
14
15struct Asked {
16    at_delivered_rate: Range<i64>,
17    mix_span_from_timeline_zero: Range<i64>,
18    channels: AudioChannels,
19}
20
21/// Answers a session's [`super::Need::TimelineAudio`] from the project mix, on every surface.
22///
23/// Per need: [`Self::begin`], then every block [`Self::wanted`] names, mixed in stereo at exact
24/// continuity (the master output, or the need's tap) and handed to [`Self::push`], then
25/// [`Self::finish`]. A need that reads on continues the mix; one that reads earlier restarts it
26/// a second before, so a backward pass mixes each second once. Another rate is the mix through
27/// [`Resampler`], and a mono need the mean of its left and right.
28pub struct TimelineAudioRead {
29    resampler: Resampler,
30    held_start: i64,
31    left: Vec<f32>,
32    right: Vec<f32>,
33    last_span_start: Option<i64>,
34    asked: Option<Asked>,
35}
36
37impl TimelineAudioRead {
38    /// A read of a mix at `project_rate`, delivered at `rate`.
39    ///
40    /// # Errors
41    /// [`ResampleError`] for rates the resampler does not convert between.
42    pub fn new(project_rate: u32, rate: u32) -> Result<Self, ResampleError> {
43        Ok(Self {
44            resampler: Resampler::new(project_rate, rate)?,
45            held_start: 0,
46            left: Vec::new(),
47            right: Vec::new(),
48            last_span_start: None,
49            asked: None,
50        })
51    }
52
53    fn held_end(&self) -> i64 {
54        self.held_start
55            .saturating_add(i64::try_from(self.left.len()).unwrap_or(i64::MAX))
56    }
57
58    /// Begins the answer to a need of `frames` frames from `start_sample`, in `channels`.
59    pub fn begin(&mut self, start_sample: i64, frames: u32, channels: AudioChannels) {
60        let at_delivered_rate = start_sample..start_sample.saturating_add(i64::from(frames));
61        let weighed = self.resampler.source_span(at_delivered_rate.clone());
62        let span = weighed.start.max(0)..weighed.end.max(0);
63        let backward = self.last_span_start.is_some_and(|last| span.start < last);
64        self.last_span_start = Some(span.start);
65        if !(self.held_start..=self.held_end()).contains(&span.start) {
66            let window = BACKWARD_WINDOW_SECONDS * i64::from(self.resampler.source_rate());
67            self.held_start = if backward {
68                span.start.saturating_sub(window).max(0)
69            } else {
70                span.start
71            };
72            self.left.clear();
73            self.right.clear();
74        } else if !backward {
75            let passed = usize::try_from(span.start - self.held_start).unwrap_or(0);
76            self.left.drain(..passed);
77            self.right.drain(..passed);
78            self.held_start = span.start;
79        }
80        self.asked = Some(Asked {
81            at_delivered_rate,
82            mix_span_from_timeline_zero: span,
83            channels,
84        });
85    }
86
87    /// The next block of the mix [`Self::push`] takes, as its first project-rate sample and its
88    /// length (at most [`TIMELINE_MIX_BLOCK`]); `None` once the need begun can be answered.
89    #[must_use]
90    pub fn wanted(&self) -> Option<(i64, usize)> {
91        let asked = self.asked.as_ref()?;
92        let held_end = self.held_end();
93        let mix_end = asked.mix_span_from_timeline_zero.end;
94        let missing = usize::try_from(mix_end.saturating_sub(held_end)).unwrap_or(0);
95        (missing > 0).then(|| (held_end, missing.min(TIMELINE_MIX_BLOCK)))
96    }
97
98    /// Takes the block [`Self::wanted`] named: its left and right planes.
99    ///
100    /// # Errors
101    /// When no block is wanted, or the planes are not its length.
102    pub fn push(&mut self, left: &[f32], right: &[f32]) -> Result<(), String> {
103        let (_, frames) = self
104            .wanted()
105            .ok_or_else(|| "no block of the mix is wanted".to_owned())?;
106        if left.len() != frames || right.len() != frames {
107            return Err(format!(
108                "the mix block holds {} and {} samples, not the {frames} wanted",
109                left.len(),
110                right.len()
111            ));
112        }
113        self.left.extend_from_slice(left);
114        self.right.extend_from_slice(right);
115        Ok(())
116    }
117
118    /// The answer to the need begun.
119    ///
120    /// # Errors
121    /// When no need was begun, or [`Self::wanted`] still names a block.
122    pub fn finish(&mut self) -> Result<SuppliedAudio, String> {
123        if self.wanted().is_some() {
124            return Err("the mix does not reach the end of the block asked for".to_owned());
125        }
126        let asked = self
127            .asked
128            .take()
129            .ok_or_else(|| "no timeline audio is asked for".to_owned())?;
130        let block = asked.at_delivered_rate;
131        let frames = usize::try_from(block.end - block.start).unwrap_or(0);
132        let at_rate = |plane: &[f32]| {
133            let mut output = vec![0.0; frames];
134            self.resampler
135                .resample(plane, self.held_start, block.start, &mut output);
136            output
137        };
138        let mut samples = at_rate(&self.left);
139        let right = at_rate(&self.right);
140        Ok(match asked.channels {
141            AudioChannels::Mono => {
142                for (mean, right) in samples.iter_mut().zip(&right) {
143                    *mean = f32::midpoint(*mean, *right);
144                }
145                SuppliedAudio {
146                    channels: 1,
147                    samples,
148                }
149            }
150            AudioChannels::Source => {
151                samples.extend_from_slice(&right);
152                SuppliedAudio {
153                    channels: 2,
154                    samples,
155                }
156            }
157        })
158    }
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164
165    fn mix(sample: i64) -> (f32, f32) {
166        let step = |modulus: i64| {
167            f32::from(u16::try_from(sample.rem_euclid(modulus)).expect("small")) / 1_024.0
168        };
169        (step(1_000) - 0.25, 0.5 - step(617))
170    }
171
172    fn planes(span: Range<i64>) -> (Vec<f32>, Vec<f32>) {
173        span.map(mix).unzip()
174    }
175
176    fn read_and_blocks_mixed(
177        reader: &mut TimelineAudioRead,
178        start: i64,
179        frames: u32,
180        channels: AudioChannels,
181    ) -> (SuppliedAudio, Vec<(i64, usize)>) {
182        reader.begin(start, frames, channels);
183        let mut mixed = Vec::new();
184        while let Some((at, count)) = reader.wanted() {
185            let (left, right) = planes(at..at + i64::try_from(count).expect("count"));
186            reader.push(&left, &right).expect("push");
187            mixed.push((at, count));
188        }
189        (reader.finish().expect("finish"), mixed)
190    }
191
192    fn stereo(span: Range<i64>) -> Vec<f32> {
193        let (mut left, right) = planes(span);
194        left.extend(right);
195        left
196    }
197
198    #[test]
199    fn a_read_at_the_project_rate_is_the_mix_in_blocks_that_follow_on() {
200        let mut reader = TimelineAudioRead::new(48_000, 48_000).expect("reader");
201        let (first, mixed) = read_and_blocks_mixed(&mut reader, 0, 6_000, AudioChannels::Source);
202        assert_eq!(first.channels, 2);
203        assert_eq!(first.samples, stereo(0..6_000));
204        assert_eq!(mixed, [(0, TIMELINE_MIX_BLOCK), (4_096, 1_904)]);
205        let (second, mixed) =
206            read_and_blocks_mixed(&mut reader, 6_000, 1_000, AudioChannels::Source);
207        assert_eq!(second.samples, stereo(6_000..7_000));
208        assert_eq!(mixed, [(6_000, 1_000)]);
209    }
210
211    #[test]
212    fn a_block_asked_again_is_answered_from_what_is_held() {
213        let mut reader = TimelineAudioRead::new(48_000, 48_000).expect("reader");
214        let (first, _) = read_and_blocks_mixed(&mut reader, 9_000, 512, AudioChannels::Source);
215        let (again, mixed) = read_and_blocks_mixed(&mut reader, 9_000, 512, AudioChannels::Source);
216        assert_eq!(again, first);
217        assert_eq!(mixed, []);
218    }
219
220    #[test]
221    fn a_read_ahead_of_what_is_held_restarts_the_mix_at_its_start() {
222        let mut reader = TimelineAudioRead::new(48_000, 48_000).expect("reader");
223        read_and_blocks_mixed(&mut reader, 0, 512, AudioChannels::Source);
224        let (jumped, mixed) =
225            read_and_blocks_mixed(&mut reader, 96_000, 512, AudioChannels::Source);
226        assert_eq!(jumped.samples, stereo(96_000..96_512));
227        assert_eq!(mixed, [(96_000, 512)]);
228    }
229
230    #[test]
231    fn a_backward_pass_mixes_each_second_once() {
232        let mut reader = TimelineAudioRead::new(48_000, 48_000).expect("reader");
233        let mut mixed = Vec::new();
234        let mut end = 100_000;
235        while end > 0 {
236            let start = (end - 1_024).max(0);
237            let frames = u32::try_from(end - start).expect("frames");
238            let (block, blocks) =
239                read_and_blocks_mixed(&mut reader, start, frames, AudioChannels::Source);
240            assert_eq!(block.samples, stereo(start..end), "block at {start}");
241            mixed.extend(blocks);
242            end = start;
243        }
244        let restarts: Vec<i64> = mixed
245            .iter()
246            .zip(std::iter::once(&(i64::MAX, 0)).chain(&mixed))
247            .filter(|((at, _), (before, count))| {
248                *at != before.saturating_add(i64::try_from(*count).expect("count"))
249            })
250            .map(|((at, _), _)| *at)
251            .collect();
252        assert_eq!(restarts, [98_976, 49_952, 1_824, 0]);
253        let total: usize = mixed.iter().map(|(_, count)| count).sum();
254        assert!(total < 100_000 + 4 * 1_024, "mixed {total} samples");
255    }
256
257    #[test]
258    fn another_rate_is_the_resampler_of_the_mix() {
259        let resampler = Resampler::new(48_000, 16_000).expect("resampler");
260        let (left, right) = planes(0..48_000);
261        let mut expected = (vec![0.0; 16_000], vec![0.0; 16_000]);
262        resampler.resample(&left, 0, 0, &mut expected.0);
263        resampler.resample(&right, 0, 0, &mut expected.1);
264        let mut reader = TimelineAudioRead::new(48_000, 16_000).expect("reader");
265        for (start, frames) in [(0, 1_024), (1_024, 1_024), (2_048, 700), (9_000, 1_024)] {
266            let (block, _) =
267                read_and_blocks_mixed(&mut reader, start, frames, AudioChannels::Source);
268            let at = usize::try_from(start).expect("start");
269            let count = usize::try_from(frames).expect("frames");
270            assert_eq!(block.samples[..count], expected.0[at..at + count]);
271            assert_eq!(block.samples[count..], expected.1[at..at + count]);
272        }
273    }
274
275    #[test]
276    fn a_mono_need_is_the_mean_of_left_and_right() {
277        for rate in [48_000, 44_100] {
278            let mut reader = TimelineAudioRead::new(48_000, rate).expect("reader");
279            let (both, _) = read_and_blocks_mixed(&mut reader, 2_000, 300, AudioChannels::Source);
280            let (mono, _) = read_and_blocks_mixed(&mut reader, 2_000, 300, AudioChannels::Mono);
281            assert_eq!(mono.channels, 1);
282            let mean: Vec<f32> = (0..300)
283                .map(|at| f32::midpoint(both.samples[at], both.samples[300 + at]))
284                .collect();
285            assert_eq!(mono.samples, mean);
286        }
287    }
288
289    #[test]
290    fn nothing_is_mixed_before_timeline_zero() {
291        let mut reader = TimelineAudioRead::new(48_000, 16_000).expect("reader");
292        let (_, mixed) = read_and_blocks_mixed(&mut reader, 0, 64, AudioChannels::Mono);
293        assert_eq!(mixed.first().map(|(at, _)| *at), Some(0));
294    }
295
296    #[test]
297    fn a_block_of_another_length_than_wanted_is_refused() {
298        let mut reader = TimelineAudioRead::new(48_000, 48_000).expect("reader");
299        assert!(reader.push(&[0.0], &[0.0]).is_err());
300        assert!(reader.finish().is_err());
301        reader.begin(0, 64, AudioChannels::Mono);
302        assert!(reader.push(&[0.0; 63], &[0.0; 63]).is_err());
303        assert!(reader.finish().is_err());
304        reader.push(&[0.0; 64], &[0.0; 64]).expect("push");
305        assert_eq!(reader.finish().expect("finish").samples, [0.0; 64]);
306    }
307}