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
//! Record-along on the network: your dry stream (your own voices, each frame stamped with its loop position), your last loop as a
//! stamped recorded take, and playing a collaborator's take or live dry stream aligned to your loop.

use crate::align::{Mode, bars_for};
use crate::bus::{Ends, Input};
use crate::lock;
use crate::stage::{Grid, StageKind, StageStreamMeta, frame_meta, marker_of, take_stream};
use crate::{Frame, Hub, Publisher, StreamEvent, StreamId};
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

/// Your live dry stream.
pub const DRY: &str = "dry";
/// Your last loop, recorded and stamped.
pub const DRY_TAKE: &str = "dry-take";
/// What your device plays (the device-output tap), stamped like the dry stream.
pub const OUT: &str = "out";

/// Which positioned tap to stream.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Tap {
    /// Your own voices.
    Dry,
    /// What goes to the device.
    Out,
}

/// The grid on your side now.
pub fn grid(ends: &Ends) -> Option<Grid> {
    let s = &ends.shared;
    let (lf, lt, bf) = (s.loop_frames.load(Ordering::Relaxed), s.loop_ticks.load(Ordering::Relaxed), s.bar_frames.load(Ordering::Relaxed));
    (lf > 0 && lt > 0 && bf > 0).then(|| Grid { loop_frames: lf, loop_ticks: lt, loop_bars: (lf / bf).max(1) as u16 })
}

/// Your transport position now, in absolute frames, while playing (estimated from the audio clock).
pub fn local_now(ends: &Ends) -> Option<u64> {
    let s = &ends.shared;
    if !s.playing.load(Ordering::Relaxed) {
        return None;
    }
    let rendered = s.rendered.load(Ordering::Relaxed) / u64::from(ends.channels.max(1));
    Some((s.xport_transport.load(Ordering::Relaxed) as i64 + rendered as i64 - s.xport_output.load(Ordering::Relaxed) as i64).max(0) as u64)
}

/// Whole loops to add to a sender's absolute position so that, `delay` frames (the bar delay) later, it still lies at least
/// `margin` frames ahead of `now`. The two transports run the same grid but started at different times, so this keeps the
/// position on the loop and picks the next time round that can still be played.
pub fn loop_offset(sender_abs: u64, now: u64, loop_frames: u64, delay: u64, margin: u64) -> i64 {
    let need = now as i64 + margin as i64 - delay as i64 - sender_abs as i64;
    need.div_euclid(loop_frames as i64) + i64::from(need.rem_euclid(loop_frames as i64) != 0)
}

/// How far ahead of now a live source is first placed: a jitter buffer of 2048 frames (about 43 ms at 48 kHz).
pub const MARGIN: u64 = 2048;

/// The last full loop of your dry audio: interleaved samples and the absolute position of the first.
#[derive(Default)]
pub struct LastLoop {
    samples: Vec<f32>,
    start: u64,
}

impl LastLoop {
    fn push(&mut self, at: u64, block: &[f32], ch: usize, loop_frames: u64) {
        if self.samples.is_empty() || at != self.start + (self.samples.len() / ch) as u64 {
            self.samples.clear();
            self.start = at;
        }
        self.samples.extend_from_slice(block);
        let max = loop_frames as usize * ch;
        if self.samples.len() > max {
            let cut = (self.samples.len() - max) / ch * ch;
            self.samples.drain(..cut);
            self.start += (cut / ch) as u64;
        }
    }
    /// A full loop and where it starts, if one has been played.
    pub fn full(&self, loop_frames: u64, ch: usize) -> Option<(&[f32], u64)> {
        (self.samples.len() == loop_frames as usize * ch).then_some((&self.samples[..], self.start))
    }
}

/// Moves the dry tap into stamped frames on `publisher`, keeping the last loop in `last`. Runs until `stop`.
pub async fn pump_dry(ends: Arc<Mutex<Ends>>, publisher: Publisher, last: Arc<Mutex<LastLoop>>, stop: Arc<AtomicBool>) {
    pump_tap(ends, Tap::Dry, publisher, Some(last), stop).await
}

/// Moves a positioned tap into stamped frames on `publisher` (keeping the last loop in `last`,
/// if given). Runs until `stop`.
pub async fn pump_tap(ends: Arc<Mutex<Ends>>, tap: Tap, publisher: Publisher, last: Option<Arc<Mutex<LastLoop>>>, stop: Arc<AtomicBool>) {
    let switch = |e: &Ends, on: bool| match tap {
        Tap::Dry => e.shared.dry_on.store(on, Ordering::Relaxed),
        Tap::Out => e.shared.out_on.store(on, Ordering::Relaxed),
    };
    switch(&lock(&ends), true);
    let ch = lock(&ends).channels as usize;
    let (mut seq, mut pts) = (0u64, 0u64);
    while !stop.load(Ordering::Relaxed) {
        tokio::time::sleep(Duration::from_millis(3)).await;
        let mut guard = lock(&ends);
        let e = &mut *guard;
        loop {
            let (at_ring, ring) = match tap {
                Tap::Dry => (&mut e.dry_at, &mut e.dry),
                Tap::Out => (&mut e.out_at, &mut e.out),
            };
            let Ok((at, n)) = at_ring.pop() else { break };
            // the device output is stamped where it is heard
            let at = if tap == Tap::Out { at + e.shared.out_latency.load(Ordering::Relaxed) } else { at };
            let len = n as usize * ch;
            let mut block = Vec::with_capacity(len);
            let avail = len.min(ring.slots());
            if let Ok(c) = ring.read_chunk(avail) {
                let (a, b) = c.as_slices();
                block.extend_from_slice(a);
                block.extend_from_slice(b);
                c.commit_all();
            }
            let Some(g) = grid(e) else { continue };
            if let Some(last) = &last {
                lock(last).push(at, &block, ch, g.loop_frames);
            }
            let mut f = Frame::pcm_f32(seq, pts, ch as u16, &block);
            f.meta = Some(frame_meta(Some(g.marker(at))));
            pts += u64::from(n);
            seq += 1;
            let _ = publisher.send(f);
        }
        if tap == Tap::Dry {
            while e.spent.pop().is_ok() {}
        }
    }
    switch(&lock(&ends), false);
    publisher.finish();
}

/// Publish your last loop as the recorded stream [`DRY_TAKE`], stamped with where it starts on the loop. Returns its frames.
pub fn publish_take(hub: &Hub, ends: &Ends, last: &LastLoop, mut meta: StageStreamMeta) -> Result<u64, String> {
    let g = grid(ends).ok_or("no loop yet")?;
    let ch = ends.channels as usize;
    let (samples, start) = last
        .full(g.loop_frames, ch)
        .ok_or_else(|| format!("play a whole loop with the dry stream on first ({} of {} frames so far)", last.samples.len() / ch, g.loop_frames))?;
    meta.kind = StageKind::Dry;
    let src = take_stream(DRY_TAKE, samples, ends.sample_rate, ends.channels, g, meta, start % g.loop_frames);
    hub.remove(&StreamId::new(DRY_TAKE));
    hub.add_recorded(src);
    Ok(g.loop_frames)
}

/// What a play-along source measured.
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct AlongStats {
    /// Frames received.
    pub frames: u64,
    /// Mean one-way delay, milliseconds.
    pub delay_ms_mean: f64,
    /// Interarrival jitter, milliseconds.
    pub jitter_ms: f64,
    /// Bars of delay the source plays with.
    pub bars: u32,
    /// Frames that arrived too late to play in place.
    pub late: u64,
    /// Frames in the received take.
    pub take_frames: u64,
}

/// Play a collaborator's recorded take (Mode::Recorded) or live dry stream (other modes) into `slot`.
pub async fn play_along(
    mut sub: crate::net::Subscriber,
    slot: usize,
    mode: Mode,
    ends: Arc<Mutex<Ends>>,
    stats: Arc<Mutex<AlongStats>>,
    stop: Arc<AtomicBool>,
) {
    let send = |cmd: Input| {
        let _ = lock(&ends).input.push(cmd);
    };
    send(Input::Source { slot, mode });
    let info = sub.info().clone();
    let meta: Option<StageStreamMeta> = info.meta.as_ref().and_then(|m| serde_json::from_slice(m).ok());
    if mode == Mode::Recorded {
        let mut samples = Vec::new();
        let mut first = None;
        while let Some(ev) = sub.next().await {
            match ev {
                StreamEvent::Frame(f) => {
                    first = first.or(marker_of(&f));
                    samples.extend(f.f32_samples());
                }
                StreamEvent::Ended => break,
                _ => {}
            }
        }
        let Some(g) = grid(&lock(&ends)) else { return };
        // the first frame's marker is exact; the stamp in ticks is the fallback
        let start = first.map(|m| g.within(m)).or(meta.and_then(|m| m.start_tick).map(|t| g.tick_to_frame(t))).unwrap_or(0) % g.loop_frames;
        lock(&stats).take_frames = (samples.len() / info.param("channels").and_then(|c| c.parse().ok()).unwrap_or(2)) as u64;
        send(Input::Take { slot, samples, start_frame: start });
        while !stop.load(Ordering::Relaxed) {
            tokio::time::sleep(Duration::from_millis(50)).await;
            while lock(&ends).spent.pop().is_ok() {}
        }
        send(Input::Remove { slot });
        return;
    }
    let (mut sum, mut n, mut bars) = (0.0f64, 0u64, 0u32);
    let mut offset: Option<i64> = None;
    while !stop.load(Ordering::Relaxed) {
        let ev = match tokio::time::timeout(Duration::from_millis(200), sub.next()).await {
            Ok(Some(ev)) => ev,
            Ok(None) => break,
            Err(_) => continue,
        };
        let StreamEvent::Frame(f) = ev else { continue };
        let now = crate::listen::wall_us();
        let (g, rate, now_frames) = {
            let mut e = lock(&ends);
            while e.spent.pop().is_ok() {}
            (grid(&e), e.sample_rate, local_now(&e))
        };
        let Some(g) = g else { continue };
        if let Some(t) = crate::listen::sent_us(&f) {
            sum += now.saturating_sub(t) as f64 / 1000.0;
            n += 1;
        }
        let mut s = lock(&stats);
        s.frames = sub.stats().frames;
        s.jitter_ms = sub.stats().jitter_ms;
        s.delay_ms_mean = if n > 0 { sum / n as f64 } else { 0.0 };
        if let Mode::LiveBars(0) = mode {
            // automatic: the smallest whole number of bars that covers the delay and jitter; it only grows
            let want = bars_for(s.delay_ms_mean, s.jitter_ms, 1024, g.bar_frames(), rate);
            if want > bars {
                bars = want;
                drop(s);
                send(Input::Bars { slot, bars });
                s = lock(&stats);
            }
        }
        s.bars = bars.max(if let Mode::LiveBars(b) = mode { b } else { 0 });
        s.late = lock(&ends).shared.late.load(Ordering::Relaxed);
        drop(s);
        let (Some(m), Some(now_frames)) = (marker_of(&f), now_frames) else {
            offset = None;
            continue;
        };
        let abs = g.abs(m);
        let delay = u64::from(bars.max(if let Mode::LiveBars(b) = mode { b } else { 0 }).max(1)) * g.bar_frames();
        let k = *offset.get_or_insert_with(|| loop_offset(abs, now_frames, g.loop_frames, delay, MARGIN));
        let at = (abs as i64 + k * g.loop_frames as i64).max(0) as u64;
        send(Input::Frame { slot, at, samples: f.f32_samples() });
    }
    send(Input::Remove { slot });
}

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

    #[test]
    fn the_offset_keeps_the_position_and_picks_the_next_playable_round() {
        // loop 100, one bar of 50 delay, margin 5
        let k = loop_offset(1030, 3020, 100, 50, 5);
        assert_eq!(k, 20);
        let at = |k: i64| 1030 + k * 100 + 50;
        assert_eq!(at(k) % 100, 80, "the same place on the loop, one bar (50) later");
        assert!(at(k) >= 3025 && at(k - 1) < 3025, "the earliest round that is still ahead");
        // a sender ahead of you in loops gets a negative offset
        assert_eq!(loop_offset(9030, 3020, 100, 50, 5), -60);
    }
}