weirdnet-streaming 0.1.0

Streaming for Weirdnet: live and recorded audio streams over weirdnet-net with per-listener queues, clocks and remote routing, a follow-transport protocol (start, stop, locate, tempo, beacon), and loop-positioned streams with alignment for record-along.
Documentation
//! The stream input's aligner: where each collaborator's audio plays on your loop.
//!
//! * Recorded, exact: a whole take is fetched first and plays at the loop position its stamp names, every time round. No network delay
//!   is involved at play time.
//! * Live, bar-aligned: a frame stamped with the sender's loop position plays at the same position on your loop a whole number of
//!   bars later (the default for record-along: [`crate::along`]). The bar delay is the smallest that covers the arrival delay plus jitter, or fixed.
//! * Live, immediate: plays on arrival after a small jitter buffer, moved by a manual trim (listen-along).
//!
//! A live frame that misses its slot is dropped and counted; the aligner never plays a frame at the wrong position. Positions are
//! absolute frames on your side (`loop_index * loop_frames + frame`), from [`crate::stage::Grid::abs`].

use std::collections::VecDeque;

/// How a source is aligned.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Mode {
    /// A recorded take, laid out over the loop and played in place.
    Recorded,
    /// Whole bars of delay; 0 picks it from the measured delay ([`bars_for`]).
    LiveBars(u32),
    /// 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.
    Immediate {
        /// Frames to hold back before playing starts.
        prebuffer: u64,
        /// Frames to wait longer (positive) or to skip (negative).
        trim: i64,
    },
}

/// The smallest whole number of bars (1, 2, 4, …) that covers `delay_ms + jitter_ms` plus one block.
pub fn bars_for(delay_ms: f64, jitter_ms: f64, block_frames: u64, bar_frames: u64, sample_rate: u32) -> u32 {
    let need = ((delay_ms + 2.0 * jitter_ms) * f64::from(sample_rate) / 1000.0).ceil() as u64 + block_frames;
    let mut bars = 1u32;
    while u64::from(bars) * bar_frames < need {
        bars *= 2;
    }
    bars
}

struct Chunk {
    /// The sender's position in your frames (for live sources), or the arrival order (immediate).
    at: u64,
    samples: Vec<f32>,
}

/// One collaborator's input.
pub struct Source {
    /// How this source is aligned.
    pub mode: Mode,
    /// Linear gain.
    pub gain: f32,
    /// Silences the source without dropping it.
    pub mute: bool,
    channels: usize,
    chunks: VecDeque<Chunk>,
    /// Recorded: the take laid out over one loop.
    take: Vec<f32>,
    /// Immediate: playing, and the next sample's offset into the queue.
    flowing: bool,
    skip: u64,
    /// Frames that arrived too late to play in place.
    pub late: u64,
    /// Frames played.
    pub played: u64,
    bars: u32,
}

impl Source {
    /// A source with unit gain, unmuted, that has nothing queued.
    pub fn new(mode: Mode, channels: u16) -> Source {
        Source {
            mode,
            gain: 1.0,
            mute: false,
            channels: channels as usize,
            chunks: VecDeque::new(),
            take: Vec::new(),
            flowing: false,
            skip: 0,
            late: 0,
            played: 0,
            bars: if let Mode::LiveBars(b) = mode { b.max(1) } else { 1 },
        }
    }

    /// The bar delay in use (live bar-aligned).
    pub fn bars(&self) -> u32 {
        self.bars
    }

    /// Set the bar delay (from [`bars_for`] when the mode asks for automatic).
    pub fn set_bars(&mut self, bars: u32) {
        self.bars = bars.max(1);
    }

    /// Recorded: lay out a take whose first sample belongs at `start_frame` (within the loop) over a loop of `loop_frames`.
    pub fn set_take(&mut self, samples: &[f32], start_frame: u64, loop_frames: u64) {
        let ch = self.channels;
        self.take = vec![0.0; loop_frames as usize * ch];
        let frames = (samples.len() / ch).min(loop_frames as usize);
        for i in 0..frames {
            let at = ((start_frame + i as u64) % loop_frames) as usize;
            self.take[at * ch..at * ch + ch].copy_from_slice(&samples[i * ch..i * ch + ch]);
        }
    }

    /// Live: a frame whose first sample was played at `sender_abs` (in your frames).
    pub fn push(&mut self, sender_abs: u64, samples: Vec<f32>) {
        self.chunks.push_back(Chunk { at: sender_abs, samples });
    }

    /// Frames queued (live).
    pub fn queued_frames(&self) -> u64 {
        self.chunks.iter().map(|c| (c.samples.len() / self.channels) as u64).sum::<u64>().saturating_sub(self.skip)
    }

    /// Add this source to `out` (interleaved), a block that starts at your absolute position `local` (`None` while stopped).
    pub fn render(&mut self, out: &mut [f32], local: Option<u64>, loop_frames: u64, bar_frames: u64) {
        self.render_into(out, local, loop_frames, bar_frames, &mut drop);
    }

    /// As [`Source::render`], handing every finished chunk to `spent` (the audio thread passes them back to be freed elsewhere).
    pub fn render_into(&mut self, out: &mut [f32], local: Option<u64>, loop_frames: u64, bar_frames: u64, spent: &mut dyn FnMut(Vec<f32>)) {
        let ch = self.channels;
        let n = (out.len() / ch) as u64;
        let g = if self.mute { 0.0 } else { self.gain };
        match self.mode {
            Mode::Recorded => {
                let Some(l) = local else { return };
                if self.take.is_empty() || loop_frames == 0 {
                    return;
                }
                for i in 0..n {
                    let at = ((l + i) % loop_frames) as usize;
                    for c in 0..ch {
                        out[i as usize * ch + c] += self.take[at * ch + c] * g;
                    }
                }
                self.played += n;
            }
            Mode::LiveBars(_) => {
                let Some(l) = local else {
                    while let Some(c) = self.chunks.pop_front() {
                        spent(c.samples);
                    }
                    return;
                };
                let delay = u64::from(self.bars) * bar_frames;
                let end = l + n;
                while let Some(c) = self.chunks.front() {
                    let len = (c.samples.len() / ch) as u64;
                    let start = c.at + delay;
                    if start + len <= l {
                        // its slot has passed: drop it, never play it late
                        self.late += 1;
                        if let Some(c) = self.chunks.pop_front() {
                            spent(c.samples);
                        }
                        continue;
                    }
                    if start >= end {
                        break;
                    }
                    let from = l.max(start);
                    let to = end.min(start + len);
                    for p in from..to {
                        let (o, s) = ((p - l) as usize * ch, (p - start) as usize * ch);
                        for k in 0..ch {
                            out[o + k] += c.samples[s + k] * g;
                        }
                    }
                    self.played += to - from;
                    if start + len <= end {
                        if let Some(c) = self.chunks.pop_front() {
                            spent(c.samples);
                        }
                    } else {
                        break;
                    }
                }
            }
            Mode::Immediate { prebuffer, trim } => {
                if !self.flowing {
                    let need = prebuffer + trim.max(0) as u64;
                    if self.queued_frames() < need {
                        return;
                    }
                    self.flowing = true;
                    // a negative trim starts that much further into what is buffered
                    self.skip = trim.min(0).unsigned_abs();
                    self.drop_skipped(spent);
                }
                let mut i = 0u64;
                while i < n {
                    let Some(c) = self.chunks.front() else {
                        self.flowing = false;
                        break;
                    };
                    let len = (c.samples.len() / ch) as u64;
                    let take = (len - self.skip).min(n - i);
                    for j in 0..take {
                        let (o, s) = ((i + j) as usize * ch, (self.skip + j) as usize * ch);
                        for k in 0..ch {
                            out[o + k] += c.samples[s + k] * g;
                        }
                    }
                    i += take;
                    self.skip += take;
                    self.played += take;
                    if self.skip == len {
                        if let Some(c) = self.chunks.pop_front() {
                            spent(c.samples);
                        }
                        self.skip = 0;
                    }
                }
            }
        }
    }

    fn drop_skipped(&mut self, spent: &mut dyn FnMut(Vec<f32>)) {
        while let Some(c) = self.chunks.front() {
            let len = (c.samples.len() / self.channels) as u64;
            if self.skip < len {
                break;
            }
            self.skip -= len;
            if let Some(c) = self.chunks.pop_front() {
                spent(c.samples);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A source signal whose value names its absolute position, so a test sees exactly where each sample landed.
    fn ramp(from: u64, n: u64) -> Vec<f32> {
        (from..from + n).map(|p| p as f32).collect()
    }

    #[test]
    fn a_recorded_take_plays_at_its_stamped_position_every_loop() {
        let mut s = Source::new(Mode::Recorded, 1);
        // a 100-frame loop; the take's first sample belongs at frame 30
        s.set_take(&ramp(1, 100), 30, 100);
        let mut out = vec![0.0; 100];
        s.render(&mut out, Some(200), 100, 25);
        assert_eq!(out[30], 1.0);
        assert_eq!(out[29], 100.0, "it wraps round the loop");
        let mut out2 = vec![0.0; 10];
        s.render(&mut out2, Some(335), 100, 25);
        assert_eq!(out2[0], 6.0, "frame 35 of any loop is the take's sixth sample");
        let mut stopped = vec![0.0; 10];
        s.render(&mut stopped, None, 100, 25);
        assert!(stopped.iter().all(|v| *v == 0.0));
    }

    /// The sender plays a ramp in 10-frame frames; the network delivers each `delay` frames later with up to `jitter` more.
    fn live_run(bars: u32, delay: u64, jitter: u64) -> (Vec<(u64, f32)>, u64) {
        let (bar, block) = (40u64, 8u64);
        let mut s = Source::new(Mode::LiveBars(bars), 1);
        let mut arrivals: Vec<(u64, u64)> = (0..30u64).map(|k| (k * 10, k * 10 + 10 + delay + (k * 7919 % (jitter + 1)))).collect();
        arrivals.sort_by_key(|a| a.1);
        let mut heard = Vec::new();
        let mut t = 0u64;
        while t < 600 {
            for &(at, _) in arrivals.iter().filter(|a| a.1 >= t && a.1 < t + block) {
                s.push(at, ramp(at, 10));
            }
            let mut out = vec![0.0; block as usize];
            s.render(&mut out, Some(t), 160, bar);
            for (i, v) in out.iter().enumerate() {
                if *v != 0.0 {
                    heard.push((t + i as u64, *v));
                }
            }
            t += block;
        }
        (heard, s.late)
    }

    #[test]
    fn live_frames_play_whole_bars_later_at_their_own_position() {
        let (heard, late) = live_run(1, 5, 3);
        assert_eq!(late, 0);
        assert!(!heard.is_empty());
        for (at, v) in &heard {
            assert_eq!(*at, *v as u64 + 40, "played exactly one bar after it was played, never elsewhere");
        }
    }

    #[test]
    fn a_frame_that_misses_its_slot_is_dropped_not_played_late() {
        // 45 frames of delay cannot fit in one 40-frame bar
        let (heard, late) = live_run(1, 45, 0);
        assert!(late > 0);
        for (at, v) in &heard {
            assert_eq!(*at, *v as u64 + 40);
        }
        // two bars fit
        let (heard, late) = live_run(2, 45, 0);
        assert_eq!(late, 0);
        assert!(heard.iter().all(|(at, v)| *at == *v as u64 + 80));
    }

    #[test]
    fn the_bar_delay_covers_delay_and_jitter() {
        // 48 kHz, 120 BPM in 4/4: a bar is 2 s
        assert_eq!(bars_for(30.0, 5.0, 256, 96_000, 48_000), 1);
        assert_eq!(bars_for(2500.0, 0.0, 256, 96_000, 48_000), 2);
        assert_eq!(bars_for(5000.0, 0.0, 256, 96_000, 48_000), 4);
    }

    #[test]
    fn immediate_waits_for_the_prebuffer_and_honours_the_trim() {
        let mut s = Source::new(Mode::Immediate { prebuffer: 20, trim: 0 }, 1);
        s.push(0, ramp(1, 10));
        let mut out = vec![0.0; 5];
        s.render(&mut out, None, 0, 0);
        assert!(out.iter().all(|v| *v == 0.0), "10 frames is under the prebuffer");
        s.push(10, ramp(11, 10));
        s.render(&mut out, None, 0, 0);
        assert_eq!(out, vec![1.0, 2.0, 3.0, 4.0, 5.0]);
        let mut early = Source::new(Mode::Immediate { prebuffer: 10, trim: -3 }, 1);
        early.push(0, ramp(1, 5));
        let mut out = vec![0.0; 3];
        early.render(&mut out, None, 0, 0);
        assert!(out.iter().all(|v| *v == 0.0), "a negative trim still waits for the prebuffer");
        early.push(5, ramp(6, 10));
        early.render(&mut out, None, 0, 0);
        assert_eq!(out, vec![4.0, 5.0, 6.0], "and starts 3 frames in");
    }

    #[test]
    fn mute_and_gain() {
        let mut s = Source::new(Mode::Recorded, 1);
        s.set_take(&[1.0; 10], 0, 10);
        s.gain = 0.5;
        let mut out = vec![0.0; 10];
        s.render(&mut out, Some(0), 10, 10);
        assert!(out.iter().all(|v| *v == 0.5));
        s.mute = true;
        let mut out = vec![0.0; 10];
        s.render(&mut out, Some(0), 10, 10);
        assert!(out.iter().all(|v| *v == 0.0));
    }
}