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
//! A manual sink on its own clock: a thread that calls the render callback once per block at
//! the pace of a device whose clock runs `drift_ppm` fast (or slow, when negative) against the
//! monotonic clock. Used for instances whose output is `none`, and in tests to inject
//! drift.
use crate::bus::Render;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

/// What the clocked sink counted.
#[derive(Default, Debug)]
pub struct ClockedStats {
    /// Blocks rendered.
    pub blocks: AtomicU64,
    /// Times it fell more than four blocks behind and skipped ahead.
    pub skips: AtomicU64,
}

/// A running clocked sink; dropping it stops the thread.
pub struct Clocked {
    stop: Arc<AtomicBool>,
    thread: Option<JoinHandle<()>>,
    /// Its counters.
    pub stats: Arc<ClockedStats>,
}

impl Clocked {
    /// Starts rendering `channels`-channel blocks of `block` frames at `sample_rate` with the
    /// given drift.
    pub fn start(mut render: Render, sample_rate: u32, channels: u16, block: u32, drift_ppm: f64) -> Clocked {
        let stop = Arc::new(AtomicBool::new(false));
        let stats = Arc::new(ClockedStats::default());
        let (s, st) = (stop.clone(), stats.clone());
        let thread = std::thread::Builder::new()
            .name("clocked".into())
            .spawn(move || {
                let mut buf = vec![0.0f32; block as usize * channels as usize];
                let block_s = f64::from(block) / (f64::from(sample_rate) * (1.0 + drift_ppm * 1e-6));
                let mut base = Instant::now();
                let mut k = 0u64;
                while !s.load(Ordering::Relaxed) {
                    let due = base + Duration::from_secs_f64(block_s * k as f64);
                    let now = Instant::now();
                    if due > now {
                        std::thread::sleep(due - now);
                    } else if now - due > Duration::from_secs_f64(block_s * 4.0) {
                        st.skips.fetch_add(1, Ordering::Relaxed);
                        base = now;
                        k = 0;
                    }
                    buf.fill(0.0);
                    render(&mut buf);
                    st.blocks.fetch_add(1, Ordering::Relaxed);
                    k += 1;
                }
            })
            .expect("a clocked sink thread");
        Clocked { stop, thread: Some(thread), stats }
    }
}

impl Drop for Clocked {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::Relaxed);
        if let Some(t) = self.thread.take() {
            let _ = t.join();
        }
    }
}