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
//! How far another node's clock is from this one's, and how fast the gap grows.
//!
//! [`serve_clock`] answers on [`CLOCK_PROTOCOL`] with the node's clock. [`measure`] sends a few requests, and from each reply
//! takes the offset as the remote reading minus the midpoint of the local send and receive times; the sample with the shortest
//! round trip wins, since its midpoint error is bounded by half that round trip. [`DriftFit`] fits offsets taken over time to a
//! line, which gives the offset at any moment and the drift between the two clocks in parts per million.
//!
//! Clocks are functions returning nanoseconds of a monotonic clock ([`ClockFn`]), so a node can use the clock its audio runs on.

use crate::types::StreamError;
use futures::{AsyncReadExt, AsyncWriteExt};
use std::collections::VecDeque;
use std::sync::Arc;
use weirdnet_net::{Limits, Message, Multiaddr, Node, PeerId};

/// The clock protocol id.
pub const CLOCK_PROTOCOL: &str = "/weirdnet/audio-clock/1";

/// A monotonic clock in nanoseconds.
pub type ClockFn = Arc<dyn Fn() -> u64 + Send + Sync>;

/// A clock counting from when it was made, on the process's monotonic clock.
pub fn monotonic() -> ClockFn {
    let start = std::time::Instant::now();
    Arc::new(move || start.elapsed().as_nanos() as u64)
}

/// Answering clock requests. Dropping it stops.
pub struct ClockServer {
    task: tokio::task::JoinHandle<()>,
}

impl Drop for ClockServer {
    fn drop(&mut self) {
        self.task.abort();
    }
}

/// Answer clock requests on `node` with `clock`. Needs a tokio runtime context.
pub fn serve_clock<Q: Message, R: Message>(node: &Arc<Node<Q, R>>, clock: ClockFn) -> Result<ClockServer, StreamError> {
    let mut incoming = node.accept_streams(CLOCK_PROTOCOL, Limits::default()).map_err(|e| StreamError::Net(e.to_string()))?;
    let task = tokio::spawn(async move {
        while let Some(mut s) = incoming.next().await {
            let clock = clock.clone();
            tokio::spawn(async move {
                let mut req = [0u8; 8];
                while s.read_exact(&mut req).await.is_ok() {
                    let mut reply = [0u8; 16];
                    reply[..8].copy_from_slice(&req);
                    reply[8..].copy_from_slice(&clock().to_be_bytes());
                    if s.write_all(&reply).await.is_err() || s.flush().await.is_err() {
                        break;
                    }
                }
            });
        }
    });
    Ok(ClockServer { task })
}

/// One measurement of another clock against this one.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ClockSample {
    /// This clock's reading at the middle of the exchange.
    pub local_ns: u64,
    /// The other clock minus this one.
    pub offset_ns: i64,
    /// The round trip of the exchange; the offset is within half of it.
    pub rtt_ns: u64,
}

/// Measure the clock of `peer` (reached through `addrs` if not connected) with `probes` exchanges and keep the one with the
/// shortest round trip.
pub async fn measure<Q: Message, R: Message>(
    node: &Node<Q, R>,
    peer: PeerId,
    addrs: &[Multiaddr],
    local: &ClockFn,
    probes: usize,
) -> Result<ClockSample, StreamError> {
    let net = |e: std::io::Error| StreamError::Net(e.to_string());
    let mut s = node.open_stream_async(peer, addrs, CLOCK_PROTOCOL, Limits::default()).await.map_err(|e| StreamError::Net(e.to_string()))?;
    let mut best: Option<ClockSample> = None;
    for seq in 0..probes.max(1) as u64 {
        let t0 = local();
        s.write_all(&seq.to_be_bytes()).await.map_err(net)?;
        s.flush().await.map_err(net)?;
        let mut reply = [0u8; 16];
        s.read_exact(&mut reply).await.map_err(net)?;
        let t3 = local();
        if reply[..8] != seq.to_be_bytes() {
            return Err(StreamError::Protocol("a clock reply out of order".into()));
        }
        let remote = u64::from_be_bytes(reply[8..].try_into().expect("8 bytes"));
        let mid = t0 + (t3 - t0) / 2;
        let sample = ClockSample { local_ns: mid, offset_ns: remote as i64 - mid as i64, rtt_ns: t3 - t0 };
        if best.is_none_or(|b| sample.rtt_ns < b.rtt_ns) {
            best = Some(sample);
        }
    }
    let _ = s.close().await;
    Ok(best.expect("at least one probe"))
}

/// Clock samples over time fitted to a line: the offset at any moment, and the drift.
#[derive(Clone, Debug)]
pub struct DriftFit {
    samples: VecDeque<ClockSample>,
    keep: usize,
}

impl DriftFit {
    /// A fit over the newest `keep` samples.
    pub fn new(keep: usize) -> DriftFit {
        DriftFit { samples: VecDeque::new(), keep: keep.max(2) }
    }

    /// Adds a sample.
    pub fn push(&mut self, s: ClockSample) {
        self.samples.push_back(s);
        while self.samples.len() > self.keep {
            self.samples.pop_front();
        }
    }

    /// Adds samples.
    pub fn extend(&mut self, samples: impl IntoIterator<Item = ClockSample>) {
        for s in samples {
            self.push(s);
        }
    }

    /// Samples held.
    pub fn len(&self) -> usize {
        self.samples.len()
    }

    /// Whether there are none.
    pub fn is_empty(&self) -> bool {
        self.samples.is_empty()
    }

    /// (offset at the first sample, slope) by least squares, in ns and ns per ns.
    fn line(&self) -> Option<(f64, f64)> {
        let first = self.samples.front()?;
        let n = self.samples.len() as f64;
        let xs = self.samples.iter().map(|s| (s.local_ns - first.local_ns) as f64);
        let ys = self.samples.iter().map(|s| s.offset_ns as f64);
        let (mx, my) = (xs.clone().sum::<f64>() / n, ys.clone().sum::<f64>() / n);
        let sxx: f64 = xs.clone().map(|x| (x - mx) * (x - mx)).sum();
        if sxx <= 0.0 {
            return Some((my, 0.0));
        }
        let sxy: f64 = xs.zip(ys).map(|(x, y)| (x - mx) * (y - my)).sum();
        let slope = sxy / sxx;
        Some((my - slope * mx, slope))
    }

    /// The offset (other minus this) at this clock's reading `local_ns`.
    pub fn offset_at(&self, local_ns: u64) -> Option<i64> {
        let first = self.samples.front()?.local_ns;
        let (a, b) = self.line()?;
        Some((a + b * (local_ns as f64 - first as f64)).round() as i64)
    }

    /// How much faster the other clock runs, in parts per million (needs two samples at different times).
    pub fn drift_ppm(&self) -> Option<f64> {
        if self.samples.len() < 2 {
            return None;
        }
        self.line().map(|(_, b)| b * 1e6)
    }
}

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

    #[test]
    fn the_fit_finds_the_offset_and_the_drift() {
        let mut f = DriftFit::new(16);
        assert_eq!(f.offset_at(0), None);
        f.push(ClockSample { local_ns: 1_000_000_000, offset_ns: 5_000_000_000, rtt_ns: 100_000 });
        assert_eq!(f.offset_at(9_000_000_000), Some(5_000_000_000));
        assert_eq!(f.drift_ppm(), None);
        // the other clock gains 200 µs a second (200 ppm), with ±20 µs of noise
        for i in 1..10u64 {
            let noise = if i % 2 == 0 { 20_000 } else { -20_000 };
            f.push(ClockSample {
                local_ns: 1_000_000_000 + i * 1_000_000_000,
                offset_ns: 5_000_000_000 + (i * 200_000) as i64 + noise,
                rtt_ns: 100_000,
            });
        }
        assert!((f.drift_ppm().unwrap() - 200.0).abs() < 10.0, "{}", f.drift_ppm().unwrap());
        assert!((f.offset_at(21_000_000_000).unwrap() - 5_004_000_000).abs() < 100_000);
    }
}