Skip to main content

weirdnet_streaming/
clocked.rs

1//! A manual sink on its own clock: a thread that calls the render callback once per block at
2//! the pace of a device whose clock runs `drift_ppm` fast (or slow, when negative) against the
3//! monotonic clock. Used for instances whose output is `none`, and in tests to inject
4//! drift.
5use crate::bus::Render;
6use std::sync::Arc;
7use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
8use std::thread::JoinHandle;
9use std::time::{Duration, Instant};
10
11/// What the clocked sink counted.
12#[derive(Default, Debug)]
13pub struct ClockedStats {
14    /// Blocks rendered.
15    pub blocks: AtomicU64,
16    /// Times it fell more than four blocks behind and skipped ahead.
17    pub skips: AtomicU64,
18}
19
20/// A running clocked sink; dropping it stops the thread.
21pub struct Clocked {
22    stop: Arc<AtomicBool>,
23    thread: Option<JoinHandle<()>>,
24    /// Its counters.
25    pub stats: Arc<ClockedStats>,
26}
27
28impl Clocked {
29    /// Starts rendering `channels`-channel blocks of `block` frames at `sample_rate` with the
30    /// given drift.
31    pub fn start(mut render: Render, sample_rate: u32, channels: u16, block: u32, drift_ppm: f64) -> Clocked {
32        let stop = Arc::new(AtomicBool::new(false));
33        let stats = Arc::new(ClockedStats::default());
34        let (s, st) = (stop.clone(), stats.clone());
35        let thread = std::thread::Builder::new()
36            .name("clocked".into())
37            .spawn(move || {
38                let mut buf = vec![0.0f32; block as usize * channels as usize];
39                let block_s = f64::from(block) / (f64::from(sample_rate) * (1.0 + drift_ppm * 1e-6));
40                let mut base = Instant::now();
41                let mut k = 0u64;
42                while !s.load(Ordering::Relaxed) {
43                    let due = base + Duration::from_secs_f64(block_s * k as f64);
44                    let now = Instant::now();
45                    if due > now {
46                        std::thread::sleep(due - now);
47                    } else if now - due > Duration::from_secs_f64(block_s * 4.0) {
48                        st.skips.fetch_add(1, Ordering::Relaxed);
49                        base = now;
50                        k = 0;
51                    }
52                    buf.fill(0.0);
53                    render(&mut buf);
54                    st.blocks.fetch_add(1, Ordering::Relaxed);
55                    k += 1;
56                }
57            })
58            .expect("a clocked sink thread");
59        Clocked { stop, thread: Some(thread), stats }
60    }
61}
62
63impl Drop for Clocked {
64    fn drop(&mut self) {
65        self.stop.store(true, Ordering::Relaxed);
66        if let Some(t) = self.thread.take() {
67            let _ = t.join();
68        }
69    }
70}