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
//! Listen-along: the host streams its master out as raw PCM (32-bit float) over weirdnet-streaming; members of the session subscribe
//! and hear it mixed into their own output. Each frame carries the sender's wall-clock time (frame metadata, 8 bytes, microseconds since
//! the Unix epoch) so a listener can measure the one-way delay when the clocks agree (same machine, or synced clocks). The take is kept
//! and offered as a recorded stream that can be played from any position.

use crate::bus::Ends;
use crate::{Frame, Hub, Publisher, Recording, StreamEvent, StreamId, StreamInfo};
use serde::{Deserialize, Serialize};
use std::sync::atomic::Ordering;
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

/// The live master out stream.
pub const MASTER: &str = "master";
/// The last take of the master out, recorded and seekable.
pub const TAKE: &str = "master-take";
/// Samples per channel in one frame: 10 ms at 48 kHz.
pub const FRAME_MS: u32 = 10;
/// The longest take kept, in seconds.
pub const TAKE_SECONDS: u32 = 120;

/// Stream metadata: what the stream is.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct StreamMeta {
    /// The app that made the stream.
    pub app: String,
    /// The kind of stream (for example [`MASTER`] or [`TAKE`]).
    pub class: String,
    /// The project the stream belongs to.
    pub project: String,
}

/// The wall-clock time now, microseconds since the Unix epoch.
pub fn wall_us() -> u64 {
    SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_micros() as u64).unwrap_or(0)
}

/// The send time carried in a frame's metadata.
pub fn sent_us(f: &Frame) -> Option<u64> {
    let m = f.meta.as_ref()?;
    Some(u64::from_le_bytes(m.get(..8)?.try_into().ok()?))
}

/// What a listener measured.
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct ListenStats {
    /// Frames received.
    pub frames: u64,
    /// Gaps seen in the sequence.
    pub gaps: u64,
    /// Frames missed in all.
    pub missed: u64,
    /// One-way delay from the sender's tap to arrival (needs agreeing clocks), milliseconds.
    pub delay_ms_mean: f64,
    /// Smallest one-way delay, milliseconds.
    pub delay_ms_min: f64,
    /// Largest one-way delay, milliseconds.
    pub delay_ms_max: f64,
    /// Interarrival jitter, milliseconds (weirdnet-streaming's estimate).
    pub jitter_ms: f64,
    /// Times playback ran dry.
    pub underruns: u64,
    /// Whether the connection is relayed.
    pub relayed: bool,
}

impl ListenStats {
    /// The statistics as one log line.
    pub fn line(&self) -> String {
        format!(
            "frames={} gaps={} missed={} delay_ms mean={:.2} min={:.2} max={:.2} jitter_ms={:.2} underruns={} path={}",
            self.frames,
            self.gaps,
            self.missed,
            self.delay_ms_mean,
            self.delay_ms_min,
            self.delay_ms_max,
            self.jitter_ms,
            self.underruns,
            if self.relayed { "relayed" } else { "direct" }
        )
    }
}

/// Moves the tap into frames on a publisher, and the take into a recording. Runs until `stop`.
pub async fn pump(ends: Arc<Mutex<Ends>>, publisher: Publisher, hub: Arc<Hub>, stop: Arc<std::sync::atomic::AtomicBool>) {
    let (rate, ch) = {
        let e = crate::lock(&ends);
        e.shared.tap_on.store(true, Ordering::Relaxed);
        (e.sample_rate, e.channels)
    };
    let per = (rate * FRAME_MS / 1000) as usize * ch as usize;
    let mut take = Recording::new(StreamInfo { id: StreamId::new(TAKE), ..publisher.info() });
    let max_take = (TAKE_SECONDS * 1000 / FRAME_MS) as usize;
    let (mut seq, mut pts) = (0u64, 0u64);
    let mut buf = Vec::with_capacity(per);
    while !stop.load(Ordering::Relaxed) {
        tokio::time::sleep(Duration::from_millis(2)).await;
        let mut e = crate::lock(&ends);
        loop {
            let n = (per - buf.len()).min(e.tap.slots());
            if n == 0 {
                break;
            }
            if let Ok(c) = e.tap.read_chunk(n) {
                let (a, b) = c.as_slices();
                buf.extend_from_slice(a);
                buf.extend_from_slice(b);
                c.commit_all();
            }
            if buf.len() == per {
                let mut f = Frame::pcm_f32(seq, pts, ch, &buf);
                f.meta = Some(wall_us().to_le_bytes().to_vec());
                pts += f.duration as u64;
                seq += 1;
                if take.len() < max_take {
                    take.push(f.clone());
                }
                let _ = publisher.send(f);
                buf.clear();
            }
        }
    }
    crate::lock(&ends).shared.tap_on.store(false, Ordering::Relaxed);
    publisher.finish();
    hub.remove(&StreamId::new(MASTER));
    if !take.is_empty() {
        hub.remove(&StreamId::new(TAKE));
        hub.add_recorded(take.finish());
    }
}

/// Plays a subscription into the mix until it ends or `stop`.
pub async fn play(mut sub: crate::net::Subscriber, ends: Arc<Mutex<Ends>>, stats: Arc<Mutex<ListenStats>>, stop: Arc<std::sync::atomic::AtomicBool>) {
    crate::lock(&ends).shared.listening.store(true, Ordering::Relaxed);
    let (mut sum, mut n) = (0.0f64, 0u64);
    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,
        };
        match ev {
            StreamEvent::Frame(f) => {
                let now = wall_us();
                {
                    let mut e = crate::lock(&ends);
                    let samples = f.f32_samples();
                    let k = samples.len().min(e.mix.slots());
                    if let Ok(c) = e.mix.write_chunk_uninit(k) {
                        c.fill_from_iter(samples);
                    }
                }
                let mut s = crate::lock(&stats);
                if let Some(t) = sent_us(&f) {
                    let d = now.saturating_sub(t) as f64 / 1000.0;
                    sum += d;
                    n += 1;
                    s.delay_ms_mean = sum / n as f64;
                    s.delay_ms_min = if n == 1 { d } else { s.delay_ms_min.min(d) };
                    s.delay_ms_max = s.delay_ms_max.max(d);
                }
                let st = sub.stats();
                s.frames = st.frames;
                s.gaps = st.gaps;
                s.missed = st.missed;
                s.jitter_ms = st.jitter_ms;
                s.underruns = crate::lock(&ends).shared.underruns.load(Ordering::Relaxed);
            }
            StreamEvent::Ended => break,
            _ => {}
        }
    }
    crate::lock(&ends).shared.listening.store(false, Ordering::Relaxed);
}