use crate::bus::Render;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
#[derive(Default, Debug)]
pub struct ClockedStats {
pub blocks: AtomicU64,
pub skips: AtomicU64,
}
pub struct Clocked {
stop: Arc<AtomicBool>,
thread: Option<JoinHandle<()>>,
pub stats: Arc<ClockedStats>,
}
impl Clocked {
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();
}
}
}