Skip to main content

weirdnet_streaming/
align.rs

1//! The stream input's aligner: where each collaborator's audio plays on your loop.
2//!
3//! * Recorded, exact: a whole take is fetched first and plays at the loop position its stamp names, every time round. No network delay
4//!   is involved at play time.
5//! * Live, bar-aligned: a frame stamped with the sender's loop position plays at the same position on your loop a whole number of
6//!   bars later (the default for record-along: [`crate::along`]). The bar delay is the smallest that covers the arrival delay plus jitter, or fixed.
7//! * Live, immediate: plays on arrival after a small jitter buffer, moved by a manual trim (listen-along).
8//!
9//! A live frame that misses its slot is dropped and counted; the aligner never plays a frame at the wrong position. Positions are
10//! absolute frames on your side (`loop_index * loop_frames + frame`), from [`crate::stage::Grid::abs`].
11
12use std::collections::VecDeque;
13
14/// How a source is aligned.
15#[derive(Debug, Clone, Copy, PartialEq)]
16pub enum Mode {
17    /// A recorded take, laid out over the loop and played in place.
18    Recorded,
19    /// Whole bars of delay; 0 picks it from the measured delay ([`bars_for`]).
20    LiveBars(u32),
21    /// Plays on arrival after `prebuffer` frames. A positive `trim` waits that many frames longer; a negative one skips that many of the buffered frames, so the sound comes earlier.
22    Immediate {
23        /// Frames to hold back before playing starts.
24        prebuffer: u64,
25        /// Frames to wait longer (positive) or to skip (negative).
26        trim: i64,
27    },
28}
29
30/// The smallest whole number of bars (1, 2, 4, …) that covers `delay_ms + jitter_ms` plus one block.
31pub fn bars_for(delay_ms: f64, jitter_ms: f64, block_frames: u64, bar_frames: u64, sample_rate: u32) -> u32 {
32    let need = ((delay_ms + 2.0 * jitter_ms) * f64::from(sample_rate) / 1000.0).ceil() as u64 + block_frames;
33    let mut bars = 1u32;
34    while u64::from(bars) * bar_frames < need {
35        bars *= 2;
36    }
37    bars
38}
39
40struct Chunk {
41    /// The sender's position in your frames (for live sources), or the arrival order (immediate).
42    at: u64,
43    samples: Vec<f32>,
44}
45
46/// One collaborator's input.
47pub struct Source {
48    /// How this source is aligned.
49    pub mode: Mode,
50    /// Linear gain.
51    pub gain: f32,
52    /// Silences the source without dropping it.
53    pub mute: bool,
54    channels: usize,
55    chunks: VecDeque<Chunk>,
56    /// Recorded: the take laid out over one loop.
57    take: Vec<f32>,
58    /// Immediate: playing, and the next sample's offset into the queue.
59    flowing: bool,
60    skip: u64,
61    /// Frames that arrived too late to play in place.
62    pub late: u64,
63    /// Frames played.
64    pub played: u64,
65    bars: u32,
66}
67
68impl Source {
69    /// A source with unit gain, unmuted, that has nothing queued.
70    pub fn new(mode: Mode, channels: u16) -> Source {
71        Source {
72            mode,
73            gain: 1.0,
74            mute: false,
75            channels: channels as usize,
76            chunks: VecDeque::new(),
77            take: Vec::new(),
78            flowing: false,
79            skip: 0,
80            late: 0,
81            played: 0,
82            bars: if let Mode::LiveBars(b) = mode { b.max(1) } else { 1 },
83        }
84    }
85
86    /// The bar delay in use (live bar-aligned).
87    pub fn bars(&self) -> u32 {
88        self.bars
89    }
90
91    /// Set the bar delay (from [`bars_for`] when the mode asks for automatic).
92    pub fn set_bars(&mut self, bars: u32) {
93        self.bars = bars.max(1);
94    }
95
96    /// Recorded: lay out a take whose first sample belongs at `start_frame` (within the loop) over a loop of `loop_frames`.
97    pub fn set_take(&mut self, samples: &[f32], start_frame: u64, loop_frames: u64) {
98        let ch = self.channels;
99        self.take = vec![0.0; loop_frames as usize * ch];
100        let frames = (samples.len() / ch).min(loop_frames as usize);
101        for i in 0..frames {
102            let at = ((start_frame + i as u64) % loop_frames) as usize;
103            self.take[at * ch..at * ch + ch].copy_from_slice(&samples[i * ch..i * ch + ch]);
104        }
105    }
106
107    /// Live: a frame whose first sample was played at `sender_abs` (in your frames).
108    pub fn push(&mut self, sender_abs: u64, samples: Vec<f32>) {
109        self.chunks.push_back(Chunk { at: sender_abs, samples });
110    }
111
112    /// Frames queued (live).
113    pub fn queued_frames(&self) -> u64 {
114        self.chunks.iter().map(|c| (c.samples.len() / self.channels) as u64).sum::<u64>().saturating_sub(self.skip)
115    }
116
117    /// Add this source to `out` (interleaved), a block that starts at your absolute position `local` (`None` while stopped).
118    pub fn render(&mut self, out: &mut [f32], local: Option<u64>, loop_frames: u64, bar_frames: u64) {
119        self.render_into(out, local, loop_frames, bar_frames, &mut drop);
120    }
121
122    /// As [`Source::render`], handing every finished chunk to `spent` (the audio thread passes them back to be freed elsewhere).
123    pub fn render_into(&mut self, out: &mut [f32], local: Option<u64>, loop_frames: u64, bar_frames: u64, spent: &mut dyn FnMut(Vec<f32>)) {
124        let ch = self.channels;
125        let n = (out.len() / ch) as u64;
126        let g = if self.mute { 0.0 } else { self.gain };
127        match self.mode {
128            Mode::Recorded => {
129                let Some(l) = local else { return };
130                if self.take.is_empty() || loop_frames == 0 {
131                    return;
132                }
133                for i in 0..n {
134                    let at = ((l + i) % loop_frames) as usize;
135                    for c in 0..ch {
136                        out[i as usize * ch + c] += self.take[at * ch + c] * g;
137                    }
138                }
139                self.played += n;
140            }
141            Mode::LiveBars(_) => {
142                let Some(l) = local else {
143                    while let Some(c) = self.chunks.pop_front() {
144                        spent(c.samples);
145                    }
146                    return;
147                };
148                let delay = u64::from(self.bars) * bar_frames;
149                let end = l + n;
150                while let Some(c) = self.chunks.front() {
151                    let len = (c.samples.len() / ch) as u64;
152                    let start = c.at + delay;
153                    if start + len <= l {
154                        // its slot has passed: drop it, never play it late
155                        self.late += 1;
156                        if let Some(c) = self.chunks.pop_front() {
157                            spent(c.samples);
158                        }
159                        continue;
160                    }
161                    if start >= end {
162                        break;
163                    }
164                    let from = l.max(start);
165                    let to = end.min(start + len);
166                    for p in from..to {
167                        let (o, s) = ((p - l) as usize * ch, (p - start) as usize * ch);
168                        for k in 0..ch {
169                            out[o + k] += c.samples[s + k] * g;
170                        }
171                    }
172                    self.played += to - from;
173                    if start + len <= end {
174                        if let Some(c) = self.chunks.pop_front() {
175                            spent(c.samples);
176                        }
177                    } else {
178                        break;
179                    }
180                }
181            }
182            Mode::Immediate { prebuffer, trim } => {
183                if !self.flowing {
184                    let need = prebuffer + trim.max(0) as u64;
185                    if self.queued_frames() < need {
186                        return;
187                    }
188                    self.flowing = true;
189                    // a negative trim starts that much further into what is buffered
190                    self.skip = trim.min(0).unsigned_abs();
191                    self.drop_skipped(spent);
192                }
193                let mut i = 0u64;
194                while i < n {
195                    let Some(c) = self.chunks.front() else {
196                        self.flowing = false;
197                        break;
198                    };
199                    let len = (c.samples.len() / ch) as u64;
200                    let take = (len - self.skip).min(n - i);
201                    for j in 0..take {
202                        let (o, s) = ((i + j) as usize * ch, (self.skip + j) as usize * ch);
203                        for k in 0..ch {
204                            out[o + k] += c.samples[s + k] * g;
205                        }
206                    }
207                    i += take;
208                    self.skip += take;
209                    self.played += take;
210                    if self.skip == len {
211                        if let Some(c) = self.chunks.pop_front() {
212                            spent(c.samples);
213                        }
214                        self.skip = 0;
215                    }
216                }
217            }
218        }
219    }
220
221    fn drop_skipped(&mut self, spent: &mut dyn FnMut(Vec<f32>)) {
222        while let Some(c) = self.chunks.front() {
223            let len = (c.samples.len() / self.channels) as u64;
224            if self.skip < len {
225                break;
226            }
227            self.skip -= len;
228            if let Some(c) = self.chunks.pop_front() {
229                spent(c.samples);
230            }
231        }
232    }
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238
239    /// A source signal whose value names its absolute position, so a test sees exactly where each sample landed.
240    fn ramp(from: u64, n: u64) -> Vec<f32> {
241        (from..from + n).map(|p| p as f32).collect()
242    }
243
244    #[test]
245    fn a_recorded_take_plays_at_its_stamped_position_every_loop() {
246        let mut s = Source::new(Mode::Recorded, 1);
247        // a 100-frame loop; the take's first sample belongs at frame 30
248        s.set_take(&ramp(1, 100), 30, 100);
249        let mut out = vec![0.0; 100];
250        s.render(&mut out, Some(200), 100, 25);
251        assert_eq!(out[30], 1.0);
252        assert_eq!(out[29], 100.0, "it wraps round the loop");
253        let mut out2 = vec![0.0; 10];
254        s.render(&mut out2, Some(335), 100, 25);
255        assert_eq!(out2[0], 6.0, "frame 35 of any loop is the take's sixth sample");
256        let mut stopped = vec![0.0; 10];
257        s.render(&mut stopped, None, 100, 25);
258        assert!(stopped.iter().all(|v| *v == 0.0));
259    }
260
261    /// The sender plays a ramp in 10-frame frames; the network delivers each `delay` frames later with up to `jitter` more.
262    fn live_run(bars: u32, delay: u64, jitter: u64) -> (Vec<(u64, f32)>, u64) {
263        let (bar, block) = (40u64, 8u64);
264        let mut s = Source::new(Mode::LiveBars(bars), 1);
265        let mut arrivals: Vec<(u64, u64)> = (0..30u64).map(|k| (k * 10, k * 10 + 10 + delay + (k * 7919 % (jitter + 1)))).collect();
266        arrivals.sort_by_key(|a| a.1);
267        let mut heard = Vec::new();
268        let mut t = 0u64;
269        while t < 600 {
270            for &(at, _) in arrivals.iter().filter(|a| a.1 >= t && a.1 < t + block) {
271                s.push(at, ramp(at, 10));
272            }
273            let mut out = vec![0.0; block as usize];
274            s.render(&mut out, Some(t), 160, bar);
275            for (i, v) in out.iter().enumerate() {
276                if *v != 0.0 {
277                    heard.push((t + i as u64, *v));
278                }
279            }
280            t += block;
281        }
282        (heard, s.late)
283    }
284
285    #[test]
286    fn live_frames_play_whole_bars_later_at_their_own_position() {
287        let (heard, late) = live_run(1, 5, 3);
288        assert_eq!(late, 0);
289        assert!(!heard.is_empty());
290        for (at, v) in &heard {
291            assert_eq!(*at, *v as u64 + 40, "played exactly one bar after it was played, never elsewhere");
292        }
293    }
294
295    #[test]
296    fn a_frame_that_misses_its_slot_is_dropped_not_played_late() {
297        // 45 frames of delay cannot fit in one 40-frame bar
298        let (heard, late) = live_run(1, 45, 0);
299        assert!(late > 0);
300        for (at, v) in &heard {
301            assert_eq!(*at, *v as u64 + 40);
302        }
303        // two bars fit
304        let (heard, late) = live_run(2, 45, 0);
305        assert_eq!(late, 0);
306        assert!(heard.iter().all(|(at, v)| *at == *v as u64 + 80));
307    }
308
309    #[test]
310    fn the_bar_delay_covers_delay_and_jitter() {
311        // 48 kHz, 120 BPM in 4/4: a bar is 2 s
312        assert_eq!(bars_for(30.0, 5.0, 256, 96_000, 48_000), 1);
313        assert_eq!(bars_for(2500.0, 0.0, 256, 96_000, 48_000), 2);
314        assert_eq!(bars_for(5000.0, 0.0, 256, 96_000, 48_000), 4);
315    }
316
317    #[test]
318    fn immediate_waits_for_the_prebuffer_and_honours_the_trim() {
319        let mut s = Source::new(Mode::Immediate { prebuffer: 20, trim: 0 }, 1);
320        s.push(0, ramp(1, 10));
321        let mut out = vec![0.0; 5];
322        s.render(&mut out, None, 0, 0);
323        assert!(out.iter().all(|v| *v == 0.0), "10 frames is under the prebuffer");
324        s.push(10, ramp(11, 10));
325        s.render(&mut out, None, 0, 0);
326        assert_eq!(out, vec![1.0, 2.0, 3.0, 4.0, 5.0]);
327        let mut early = Source::new(Mode::Immediate { prebuffer: 10, trim: -3 }, 1);
328        early.push(0, ramp(1, 5));
329        let mut out = vec![0.0; 3];
330        early.render(&mut out, None, 0, 0);
331        assert!(out.iter().all(|v| *v == 0.0), "a negative trim still waits for the prebuffer");
332        early.push(5, ramp(6, 10));
333        early.render(&mut out, None, 0, 0);
334        assert_eq!(out, vec![4.0, 5.0, 6.0], "and starts 3 frames in");
335    }
336
337    #[test]
338    fn mute_and_gain() {
339        let mut s = Source::new(Mode::Recorded, 1);
340        s.set_take(&[1.0; 10], 0, 10);
341        s.gain = 0.5;
342        let mut out = vec![0.0; 10];
343        s.render(&mut out, Some(0), 10, 10);
344        assert!(out.iter().all(|v| *v == 0.5));
345        s.mute = true;
346        let mut out = vec![0.0; 10];
347        s.render(&mut out, Some(0), 10, 10);
348        assert!(out.iter().all(|v| *v == 0.0));
349    }
350}