weirdnet_streaming/
clocked.rs1use 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#[derive(Default, Debug)]
13pub struct ClockedStats {
14 pub blocks: AtomicU64,
16 pub skips: AtomicU64,
18}
19
20pub struct Clocked {
22 stop: Arc<AtomicBool>,
23 thread: Option<JoinHandle<()>>,
24 pub stats: Arc<ClockedStats>,
26}
27
28impl Clocked {
29 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}