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 audio side of listen-along, safe on the audio thread: a wrapper around the engine's render callback that copies the master out
//! into a ring (the tap, read by the network side to stream it) and adds samples from another ring (the mix, filled by a subscription
//! to someone else's master out). No locks and no allocation in the callback.

use crate::align::{Mode, Source};
use rtrb::{Consumer, Producer, RingBuffer};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};

/// The engine's render callback: fills an interleaved block.
pub type Render = Box<dyn FnMut(&mut [f32]) + Send>;

/// Counters and switches shared by the audio thread and the network side.
#[derive(Default)]
pub struct Shared {
    /// Copy the master out into the tap.
    pub tap_on: AtomicBool,
    /// Play what arrives in the mix.
    pub listening: AtomicBool,
    /// Samples the tap could not hold (the network side was late).
    pub tap_dropped: AtomicU64,
    /// Times the mix ran dry while listening.
    pub underruns: AtomicU64,
    /// Samples played from the mix.
    pub played: AtomicU64,
    /// Samples rendered in all (the audio clock).
    pub rendered: AtomicU64,
    /// The transport, posted by the window from the engine's timing: at output frame `xport_output` the transport was at
    /// `xport_transport` (absolute frames since play), while `playing`.
    pub xport_output: AtomicU64,
    /// The transport frame (absolute, since play) at `xport_output`.
    pub xport_transport: AtomicU64,
    /// Whether the transport is playing.
    pub playing: AtomicBool,
    /// Frames in one loop.
    pub loop_frames: AtomicU64,
    /// Frames in one bar.
    pub bar_frames: AtomicU64,
    /// Ticks in one loop.
    pub loop_ticks: AtomicU64,
    /// Copy your own voices, with their loop positions, into the dry tap.
    pub dry_on: AtomicBool,
    /// Live input frames dropped because their slot had passed.
    pub late: AtomicU64,
    /// Copy what goes to the device (your voices, collaborators and what you listen to: the
    /// last thing in the block), with positions, into the device-output tap.
    pub out_on: AtomicBool,
    /// The device's output latency in frames: the device-output stream is stamped where its
    /// audio is heard, this much after it leaves the block.
    pub out_latency: AtomicU64,
}

impl Shared {
    /// Post the transport (call often from the window; the engine timing is good to a block).
    pub fn set_transport(&self, output_frame: u64, transport_frame: u64, playing: bool, loop_frames: u64, bar_frames: u64, loop_ticks: u64) {
        self.loop_ticks.store(loop_ticks, Ordering::Relaxed);
        self.xport_output.store(output_frame, Ordering::Relaxed);
        self.xport_transport.store(transport_frame, Ordering::Relaxed);
        self.loop_frames.store(loop_frames, Ordering::Relaxed);
        self.bar_frames.store(bar_frames, Ordering::Relaxed);
        self.playing.store(playing, Ordering::Relaxed);
    }
}

/// What the network side tells the stream input.
pub enum Input {
    /// Add or replace the source in a slot.
    Source {
        /// Which collaborator slot (below [`SLOTS`]).
        slot: usize,
        /// How the source is aligned.
        mode: Mode,
    },
    /// A recorded take for a slot, its first sample at `start_frame` on your loop.
    Take {
        /// Which collaborator slot (below [`SLOTS`]).
        slot: usize,
        /// Interleaved samples.
        samples: Vec<f32>,
        /// Where on the loop the first sample belongs.
        start_frame: u64,
    },
    /// A live frame for a slot, played at `at` (your absolute frames) plus the bar delay.
    Frame {
        /// Which collaborator slot (below [`SLOTS`]).
        slot: usize,
        /// Absolute frame at which the first sample plays, before the bar delay.
        at: u64,
        /// Interleaved samples.
        samples: Vec<f32>,
    },
    /// Sets the bars of delay for a live slot.
    Bars {
        /// Which collaborator slot (below [`SLOTS`]).
        slot: usize,
        /// Whole bars of delay.
        bars: u32,
    },
    /// Sets a slot's gain and mute.
    Gain {
        /// Which collaborator slot (below [`SLOTS`]).
        slot: usize,
        /// Linear gain.
        gain: f32,
        /// Whether the slot is silenced.
        mute: bool,
    },
    /// Empties a slot.
    Remove {
        /// Which collaborator slot (below [`SLOTS`]).
        slot: usize,
    },
}

/// Slots for collaborators' inputs.
pub const SLOTS: usize = 4;

/// The network side's ends of the rings.
pub struct Ends {
    /// The master out, interleaved, while [`Shared::tap_on`].
    pub tap: Consumer<f32>,
    /// Samples to play, interleaved, while [`Shared::listening`].
    pub mix: Producer<f32>,
    /// Your voices while [`Shared::dry_on`] and playing: each block's absolute start position and length, then its samples in `dry`.
    pub dry_at: Consumer<(u64, u32)>,
    /// The samples of your voices, matching `dry_at`.
    pub dry: Consumer<f32>,
    /// What goes to the device while [`Shared::out_on`] and playing, laid out like `dry_at` and `dry`.
    pub out_at: Consumer<(u64, u32)>,
    /// The samples of the device output, matching `out_at`.
    pub out: Consumer<f32>,
    /// Commands for the stream input.
    pub input: Producer<Input>,
    /// Buffers the audio thread is done with, to free here.
    pub spent: Consumer<Vec<f32>>,
    /// The flags and counters shared with the audio thread.
    pub shared: Arc<Shared>,
    /// The sample rate of every ring, Hz.
    pub sample_rate: u32,
    /// Channels per frame in every ring.
    pub channels: u16,
}

/// How much arrives before the mix starts playing, and again after it ran dry.
pub const PREBUFFER_MS: u32 = 40;

/// Wrap `render` for `sample_rate` and `channels`. The rings hold two seconds each.
pub fn wrap(mut render: Render, sample_rate: u32, channels: u16) -> (Render, Ends) {
    let cap = sample_rate as usize * channels as usize * 2;
    let (mut tap_p, tap_c) = RingBuffer::<f32>::new(cap);
    let (mix_p, mut mix_c) = RingBuffer::<f32>::new(cap);
    let (mut dry_p, dry_c) = RingBuffer::<f32>::new(cap);
    let (mut dry_at_p, dry_at_c) = RingBuffer::<(u64, u32)>::new(1024);
    let (mut out_p, out_c) = RingBuffer::<f32>::new(cap);
    let (mut out_at_p, out_at_c) = RingBuffer::<(u64, u32)>::new(1024);
    let (input_p, mut input_c) = RingBuffer::<Input>::new(1024);
    let (mut spent_p, spent_c) = RingBuffer::<Vec<f32>>::new(4096);
    let mut sources: [Option<Source>; SLOTS] = Default::default();
    let ch = channels as usize;
    let shared = Arc::new(Shared::default());
    let s = shared.clone();
    let prebuffer = (sample_rate * PREBUFFER_MS / 1000) as usize * channels as usize;
    let mut started = false;
    let wrapped: Render = Box::new(move |out: &mut [f32]| {
        render(out);
        let block_start = s.rendered.fetch_add(out.len() as u64, Ordering::Relaxed) / ch as u64;
        let frames = (out.len() / ch) as u64;
        let local = s.playing.load(Ordering::Relaxed).then(|| {
            let (xo, xt) = (s.xport_output.load(Ordering::Relaxed), s.xport_transport.load(Ordering::Relaxed));
            (xt as i64 + block_start as i64 - xo as i64).max(0) as u64
        });
        // samples first, then the header: the reader takes a header only once its samples are there
        if let (true, Some(at)) = (s.dry_on.load(Ordering::Relaxed), local)
            && dry_at_p.slots() > 0
            && let Ok(chunk) = dry_p.write_chunk_uninit(out.len())
        {
            chunk.fill_from_iter(out.iter().copied());
            let _ = dry_at_p.push((at, frames as u32));
        }
        if s.tap_on.load(Ordering::Relaxed) {
            let n = out.len().min(tap_p.slots());
            if let Ok(chunk) = tap_p.write_chunk_uninit(n) {
                chunk.fill_from_iter(out[..n].iter().copied());
            }
            if n < out.len() {
                s.tap_dropped.fetch_add((out.len() - n) as u64, Ordering::Relaxed);
            }
        }
        // the stream input: collaborators aligned to your loop (after the taps, so your dry stream stays yours)
        while let Ok(cmd) = input_c.pop() {
            match cmd {
                Input::Source { slot, mode } if slot < SLOTS => sources[slot] = Some(Source::new(mode, channels)),
                Input::Take { slot, samples, start_frame } if slot < SLOTS => {
                    let lf = s.loop_frames.load(Ordering::Relaxed);
                    if let Some(src) = sources[slot].as_mut()
                        && lf > 0
                    {
                        src.set_take(&samples, start_frame, lf);
                    }
                    let _ = spent_p.push(samples);
                }
                Input::Frame { slot, at, samples } if slot < SLOTS => match sources[slot].as_mut() {
                    Some(src) => src.push(at, samples),
                    None => {
                        let _ = spent_p.push(samples);
                    }
                },
                Input::Bars { slot, bars } if slot < SLOTS => {
                    if let Some(src) = sources[slot].as_mut() {
                        src.set_bars(bars);
                    }
                }
                Input::Gain { slot, gain, mute } if slot < SLOTS => {
                    if let Some(src) = sources[slot].as_mut() {
                        src.gain = gain;
                        src.mute = mute;
                    }
                }
                Input::Remove { slot } if slot < SLOTS => sources[slot] = None,
                _ => {}
            }
        }
        let (lf, bf) = (s.loop_frames.load(Ordering::Relaxed), s.bar_frames.load(Ordering::Relaxed));
        let mut late = 0;
        for src in sources.iter_mut().flatten() {
            src.render_into(out, local, lf, bf, &mut |v| {
                let _ = spent_p.push(v);
            });
            late += src.late;
        }
        s.late.store(late, Ordering::Relaxed);
        'mix: {
            if !s.listening.load(Ordering::Relaxed) {
                started = false;
                let n = mix_c.slots();
                if let Ok(c) = mix_c.read_chunk(n) {
                    c.commit_all();
                }
                break 'mix;
            }
            if !started {
                if mix_c.slots() < prebuffer {
                    break 'mix;
                }
                started = true;
            }
            let n = out.len().min(mix_c.slots());
            if let Ok(c) = mix_c.read_chunk(n) {
                let (a, b) = c.as_slices();
                for (o, v) in out.iter_mut().zip(a.iter().chain(b.iter())) {
                    *o += *v;
                }
                c.commit_all();
            }
            s.played.fetch_add(n as u64, Ordering::Relaxed);
            if n < out.len() {
                s.underruns.fetch_add(1, Ordering::Relaxed);
                started = false;
            }
        }
        // the device-output tap: exactly what this block sends to the device
        if let (true, Some(at)) = (s.out_on.load(Ordering::Relaxed), local)
            && out_at_p.slots() > 0
            && let Ok(chunk) = out_p.write_chunk_uninit(out.len())
        {
            chunk.fill_from_iter(out.iter().copied());
            let _ = out_at_p.push((at, frames as u32));
        }
    });
    (
        wrapped,
        Ends {
            tap: tap_c,
            mix: mix_p,
            dry_at: dry_at_c,
            dry: dry_c,
            out_at: out_at_c,
            out: out_c,
            input: input_p,
            spent: spent_c,
            shared,
            sample_rate,
            channels,
        },
    )
}

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

    #[test]
    fn the_tap_copies_and_the_mix_adds_after_the_prebuffer() {
        let (mut r, mut e) = wrap(Box::new(|o: &mut [f32]| o.fill(0.25)), 1000, 1);
        let mut out = vec![0.0; 10];
        r(&mut out);
        assert_eq!(e.tap.slots(), 0, "the tap is off by default");
        e.shared.tap_on.store(true, Ordering::Relaxed);
        r(&mut out);
        assert_eq!(e.tap.slots(), 10);
        e.shared.listening.store(true, Ordering::Relaxed);
        for _ in 0..30 {
            e.mix.push(0.5).unwrap();
        }
        r(&mut out);
        assert!(out.iter().all(|v| (*v - 0.25).abs() < 1e-6), "30 samples is under the 40 ms prebuffer");
        for _ in 0..30 {
            e.mix.push(0.5).unwrap();
        }
        r(&mut out);
        assert!(out.iter().all(|v| (*v - 0.75).abs() < 1e-6), "mixed in once enough arrived");
        assert_eq!(e.shared.played.load(Ordering::Relaxed), 10);
    }
}