Skip to main content

alpha2_host_core/
audio_timeline.rs

1//! Decoded source audio placed where its timestamps say, and resampled to the project rate on
2//! demand by `alpha2_audio::Resampler`.
3//!
4//! The source is its samples at their positions and silence elsewhere, so a seeking decoder and a
5//! straight-through one give the same output, gaps included.
6
7use std::collections::VecDeque;
8
9use alpha2_audio::Resampler;
10use alpha2_media::DecodeError;
11
12/// The most project-rate samples resampled in one step, bounding the scratch copy they read.
13const STEP_SAMPLES: usize = 4_096;
14
15struct Piece {
16    /// Source index, at the segment's rate, of `planes[*][0]`.
17    start: i64,
18    planes: Vec<VecDeque<f32>>,
19}
20
21impl Piece {
22    fn len(&self) -> i64 {
23        i64::try_from(self.planes.first().map_or(0, VecDeque::len)).unwrap_or(i64::MAX)
24    }
25
26    fn end(&self) -> i64 {
27        self.start.saturating_add(self.len())
28    }
29}
30
31/// Source audio at one rate: pieces in order, silence between them.
32struct Segment {
33    resampler: Resampler,
34    pieces: VecDeque<Piece>,
35    /// No sample follows the last piece: the source is silent after it.
36    ended: bool,
37}
38
39impl Segment {
40    fn start(&self) -> i64 {
41        self.pieces.front().map_or(0, |piece| piece.start)
42    }
43
44    fn end(&self) -> i64 {
45        self.pieces.back().map_or(0, Piece::end)
46    }
47
48    fn first_output(&self) -> i64 {
49        self.resampler.target_at_or_after(self.start())
50    }
51
52    /// The output sample after the last one this segment can give now.
53    fn output_limit(&self) -> i64 {
54        if self.ended {
55            self.resampler.target_at_or_after(self.end())
56        } else {
57            self.resampler.target_known_before(self.end())
58        }
59    }
60
61    fn resample(&self, channel: usize, first: i64, output: &mut [f32]) {
62        let last = first + i64::try_from(output.len()).unwrap_or(i64::MAX);
63        let span = self.resampler.source_span(first..last);
64        let overlapping = self
65            .pieces
66            .iter()
67            .filter(|piece| piece.start < span.end && piece.end() > span.start);
68        let mut scratch = None::<Vec<f32>>;
69        for piece in overlapping {
70            let scratch = scratch.get_or_insert_with(|| {
71                vec![0.0; usize::try_from(span.end - span.start).unwrap_or(0)]
72            });
73            let from = piece.start.max(span.start);
74            let to = piece.end().min(span.end);
75            let skip = usize::try_from(from - piece.start).unwrap_or(0);
76            let count = usize::try_from(to - from).unwrap_or(0);
77            let at = usize::try_from(from - span.start).unwrap_or(0);
78            for (slot, sample) in scratch[at..at + count]
79                .iter_mut()
80                .zip(piece.planes[channel].range(skip..skip + count))
81            {
82                *slot = *sample;
83            }
84        }
85        match scratch {
86            Some(scratch) => self.resampler.resample(&scratch, span.start, first, output),
87            // Nothing decoded covers these outputs, so the source is silent there.
88            None => output.fill(0.0),
89        }
90    }
91
92    /// Drops samples no output from `next` on reads.
93    fn discard_before(&mut self, next: i64) {
94        let keep = self.resampler.source_span(next..next + 1).start;
95        while self.pieces.len() > 1 && self.pieces[0].end() <= keep {
96            self.pieces.pop_front();
97        }
98        if let Some(piece) = self.pieces.front_mut() {
99            let drop = usize::try_from(keep.min(piece.end()) - piece.start).unwrap_or(0);
100            if drop > 0 {
101                for plane in &mut piece.planes {
102                    plane.drain(..drop);
103                }
104                piece.start += i64::try_from(drop).unwrap_or(0);
105            }
106        }
107    }
108}
109
110/// Places one source's decoded audio by timestamp, leaving gaps silent, and resamples it to the
111/// target rate.
112pub struct SourceTimeline {
113    target_rate: u32,
114    channels: usize,
115    segments: VecDeque<Segment>,
116    /// The next output sample [`produce`](Self::produce) gives; `None` until a sample is placed.
117    next: Option<i64>,
118    /// No output before this one is given: a seek's target.
119    first: Option<i64>,
120    peak_held: usize,
121}
122
123impl SourceTimeline {
124    /// A timeline producing `channels` planes at `target_rate`, giving no output before sample
125    /// `first` when set.
126    #[must_use]
127    pub fn new(target_rate: u32, channels: usize, first: Option<i64>) -> Self {
128        Self {
129            target_rate,
130            channels,
131            segments: VecDeque::new(),
132            next: None,
133            first,
134            peak_held: 0,
135        }
136    }
137
138    /// The most source samples per channel held at once so far.
139    #[must_use]
140    pub const fn peak_held(&self) -> usize {
141        self.peak_held
142    }
143
144    /// Where a sample at `rate` continuing the last placed one would sit;
145    /// `None` before any placement.
146    #[must_use]
147    pub fn expected(&self, rate: u32) -> Option<i64> {
148        let segment = self.segments.back()?;
149        let end = segment.end();
150        let from = segment.resampler.source_rate();
151        if from == rate {
152            return Some(end);
153        }
154        let scaled = i128::from(end) * i128::from(rate);
155        let rounded = (scaled * 2 + i128::from(from)).div_euclid(i128::from(from) * 2);
156        i64::try_from(rounded).ok()
157    }
158
159    /// The output sample at or after source sample `source` at `rate`.
160    #[must_use]
161    pub fn output_at(&self, rate: u32, source: i64) -> i64 {
162        let scaled = i128::from(source) * i128::from(self.target_rate);
163        let rate = i128::from(rate);
164        let quotient = scaled.div_euclid(rate) + i128::from(scaled.rem_euclid(rate) != 0);
165        i64::try_from(quotient).unwrap_or(i64::MAX)
166    }
167
168    /// Places `planes`, decoded at `rate`, from source sample `at`, which is never before
169    /// [`expected`](Self::expected) (the caller drops overlaps). `at` comes from a timestamp that
170    /// passed [`audio_timestamp_in_range`](crate::recovery::audio_timestamp_in_range).
171    ///
172    /// # Errors
173    /// A rate the resampler cannot take, or planes of the wrong shape.
174    ///
175    /// # Panics
176    /// Never: a segment exists once the placement starts one.
177    pub fn place(&mut self, rate: u32, at: i64, planes: Vec<Vec<f32>>) -> Result<(), DecodeError> {
178        if planes.len() != self.channels
179            || planes.iter().any(|plane| plane.len() != planes[0].len())
180        {
181            return Err(DecodeError::Adapter(
182                "decoded audio has the wrong channel shape".into(),
183            ));
184        }
185        if planes[0].is_empty() {
186            return Ok(());
187        }
188        let continues = self
189            .segments
190            .back()
191            .is_some_and(|segment| !segment.ended && segment.resampler.source_rate() == rate);
192        if !continues {
193            if let Some(segment) = self.segments.back_mut() {
194                segment.ended = true;
195            }
196            let resampler = Resampler::new(rate, self.target_rate)
197                .map_err(|error| DecodeError::Unsupported(error.to_string()))?;
198            self.segments.push_back(Segment {
199                resampler,
200                pieces: VecDeque::new(),
201                ended: false,
202            });
203        }
204        let segment = self
205            .segments
206            .back_mut()
207            .expect("a segment was just ensured");
208        let planes = planes.into_iter().map(VecDeque::from);
209        match segment.pieces.back_mut() {
210            Some(piece) if piece.end() == at => {
211                for (plane, more) in piece.planes.iter_mut().zip(planes) {
212                    plane.extend(more);
213                }
214            }
215            Some(piece) if piece.end() > at => {
216                return Err(DecodeError::Adapter(
217                    "decoded audio overlaps the samples before it".into(),
218                ));
219            }
220            _ => segment.pieces.push_back(Piece {
221                start: at,
222                planes: planes.collect(),
223            }),
224        }
225        if self.next.is_none() {
226            let start = self.segments[0].first_output();
227            self.next = Some(self.first.map_or(start, |first| first.max(start)));
228        }
229        {
230            let held = self
231                .segments
232                .iter()
233                .flat_map(|segment| &segment.pieces)
234                .map(|piece| piece.planes.first().map_or(0, VecDeque::len))
235                .sum::<usize>();
236            self.peak_held = self.peak_held.max(held);
237        }
238        Ok(())
239    }
240
241    /// No sample follows the ones placed.
242    pub fn finish(&mut self) {
243        if let Some(segment) = self.segments.back_mut() {
244            segment.ended = true;
245        }
246    }
247
248    /// Whether [`finish`](Self::finish) was called and every output given.
249    #[must_use]
250    pub fn finished(&self) -> bool {
251        self.segments.back().is_none_or(|segment| segment.ended)
252    }
253
254    /// Appends up to `wanted` output samples to `output` (one deque per channel), returning the
255    /// first index and count. Fewer, or none, until more source is placed.
256    pub fn produce(&mut self, output: &mut [VecDeque<f32>], wanted: usize) -> Option<(i64, usize)> {
257        let mut next = self.next?;
258        let start = next;
259        let mut given = 0;
260        let mut step = vec![0.0; STEP_SAMPLES.min(wanted)];
261        while given < wanted {
262            let Some(segment) = self.segments.front() else {
263                break;
264            };
265            // A later segment may start after a gap of silence.
266            let first = segment.first_output();
267            if next < first {
268                let count = usize::try_from(first - next)
269                    .unwrap_or(usize::MAX)
270                    .min(wanted - given);
271                for plane in output.iter_mut() {
272                    plane.extend(std::iter::repeat_n(0.0, count));
273                }
274                next += i64::try_from(count).unwrap_or(i64::MAX);
275                given += count;
276                continue;
277            }
278            let limit = segment.output_limit();
279            if next >= limit {
280                if segment.ended && self.segments.len() > 1 {
281                    self.segments.pop_front();
282                    continue;
283                }
284                // Nothing placed reaches `next` yet (a far seek target): drop what no output
285                // reads so memory stays bounded.
286                if let Some(segment) = self.segments.front_mut() {
287                    segment.discard_before(next);
288                }
289                break;
290            }
291            let count = usize::try_from(limit - next)
292                .unwrap_or(usize::MAX)
293                .min(wanted - given)
294                .min(STEP_SAMPLES);
295            let step = &mut step[..count];
296            for (channel, plane) in output.iter_mut().enumerate() {
297                segment.resample(channel, next, step);
298                plane.extend(step.iter().copied());
299            }
300            next += i64::try_from(count).unwrap_or(i64::MAX);
301            given += count;
302            if let Some(segment) = self.segments.front_mut() {
303                segment.discard_before(next);
304            }
305        }
306        self.next = Some(next);
307        (given > 0).then_some((start, given))
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use super::SourceTimeline;
314    use std::collections::VecDeque;
315
316    fn drain(timeline: &mut SourceTimeline) -> (i64, Vec<f32>) {
317        let mut output = vec![VecDeque::new()];
318        let mut start = None;
319        while let Some((first, _)) = timeline.produce(&mut output, 1_000) {
320            start.get_or_insert(first);
321        }
322        (start.unwrap_or(0), output.remove(0).into())
323    }
324
325    /// The output is the same however the source arrives or is read.
326    #[test]
327    fn output_does_not_depend_on_how_frames_or_reads_split() {
328        let source: Vec<f32> = (0..9_000_u16).map(|n| f32::from(n % 97) / 97.0).collect();
329        let mut whole = SourceTimeline::new(48_000, 1, None);
330        whole
331            .place(44_100, 100, vec![source.clone()])
332            .expect("place");
333        whole.finish();
334        let expected = drain(&mut whole);
335        let mut split = SourceTimeline::new(48_000, 1, None);
336        let mut output = vec![VecDeque::new()];
337        let mut start = None;
338        for (index, chunk) in source.chunks(1_024).enumerate() {
339            let at = 100 + i64::try_from(index * 1_024).expect("small");
340            split
341                .place(44_100, at, vec![chunk.to_vec()])
342                .expect("place");
343            while let Some((first, _)) = split.produce(&mut output, 37) {
344                start.get_or_insert(first);
345            }
346        }
347        split.finish();
348        while let Some((first, _)) = split.produce(&mut output, 37) {
349            start.get_or_insert(first);
350        }
351        assert_eq!(
352            (start.expect("output"), Vec::from(output.remove(0))),
353            expected
354        );
355        // 100 samples at 44.1 kHz end before output sample 109 at 48 kHz; 9,100 before 9,905.
356        assert_eq!(expected.0, 109);
357        assert_eq!(
358            expected.0 + i64::try_from(expected.1.len()).expect("small"),
359            9_905
360        );
361    }
362
363    /// A rate change continues at the new rate's first sample position, with silence between.
364    #[test]
365    #[allow(clippy::float_cmp)]
366    fn a_rate_change_starts_a_new_segment_after_silence() {
367        let mut timeline = SourceTimeline::new(48_000, 1, None);
368        timeline
369            .place(48_000, 0, vec![vec![0.5; 4_800]])
370            .expect("place");
371        assert_eq!(timeline.expected(24_000), Some(2_400));
372        timeline
373            .place(24_000, 2_500, vec![vec![0.25; 2_400]])
374            .expect("place");
375        timeline.finish();
376        let (start, samples) = drain(&mut timeline);
377        assert_eq!(start, 0);
378        assert_eq!(samples.len(), 9_800);
379        assert!(samples[..4_800].iter().all(|sample| *sample == 0.5));
380        assert!(samples[4_800..5_000].iter().all(|sample| *sample == 0.0));
381        assert!(
382            samples[5_100..9_700]
383                .iter()
384                .all(|sample| (sample - 0.25).abs() < 1e-6)
385        );
386    }
387
388    #[test]
389    fn a_seek_target_is_the_first_output() {
390        let mut timeline = SourceTimeline::new(48_000, 1, Some(1_000));
391        timeline
392            .place(48_000, 0, vec![vec![0.5; 2_000]])
393            .expect("place");
394        timeline.finish();
395        let (start, samples) = drain(&mut timeline);
396        assert_eq!((start, samples.len()), (1_000, 1_000));
397        let mut timeline = SourceTimeline::new(48_000, 1, Some(10));
398        timeline
399            .place(48_000, 500, vec![vec![0.5; 100]])
400            .expect("place");
401        timeline.finish();
402        assert_eq!(drain(&mut timeline).0, 500);
403    }
404}