diff --git a/crates/capri-voice/src/music.rs b/crates/capri-voice/src/music.rs new file mode 100644 index 0000000..f4a56ac --- /dev/null +++ b/crates/capri-voice/src/music.rs @@ -0,0 +1,654 @@ +//! Music listening: system playback from the PipeWire/Pulse default monitor, YAMNet music classification, +//! BPM and beat-phase tracking, and the music decision (Capri `music_runtime/{worker,features,tempo}.py`, +//! `music-listening-service.mjs`). Audio is never stored, logged or sent anywhere. +use std::collections::VecDeque; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::sync::LazyLock; + +use anyhow::{Context, Result, bail, ensure}; +use rustfft::FftPlanner; +use rustfft::num_complex::Complex; + +use crate::download::{Pinned, verified}; + +pub const RATE: usize = 16_000; +pub const PACKET: usize = 8_000; +const WINDOW: usize = 48_000; +const HOP: usize = 16_000; +const CLASSES: [(&str, usize); 3] = [("music", 132), ("speech", 0), ("singing", 24)]; +pub const TEMPO_MIN_CONFIDENCE: f64 = 0.45; + +// ---------------------------------------------------------------- detector files + +pub const DETECTOR_ID: &str = "yamnet-qualcomm-v0.61.0"; +const DETECTOR_FILES: [(&str, u64, &str); 4] = [ + ("yamnet.onnx", 166_437, "7ccdf9c6d5b81e7ad280dc04e1f481adc4fd596b632671beb46a42d47d8205a4"), + ("yamnet.data", 14_915_108, "0b4de0b14bf2b528d51e3cd84e2d3e2ae826b942fbec6001c654605f1f2ceb60"), + ("labels.txt", 6230, "8e1267a120c1932b7273c0d0e0c5529edbb9a35512b437b1c8982baa59047051"), + ("metadata.json", 950, "3db8f4779f7f701bf8b92bba971db0ad59721f5fced1161e3592311ea3f6536b"), +]; + +pub fn detector_dir(data: &Path) -> PathBuf { + data.join("models/music-detector").join(DETECTOR_ID) +} + +pub fn detector_ready(dir: &Path) -> bool { + DETECTOR_FILES.iter().all(|(name, bytes, sha)| verified(&dir.join(name), *bytes, sha)) +} + +/// Downloads the pinned Qualcomm YAMNet export (13.9 MB zip) and installs its four verified files. +pub async fn provision_detector(client: &reqwest::Client, data: &Path, progress: &(dyn Fn(u64, u64) + Send + Sync)) -> Result { + let dir = detector_dir(data); + if detector_ready(&dir) { + return Ok(dir); + } + let archive = data.join("models/music-detector/download/yamnet-onnx-float.zip"); + let pin = Pinned::new( + "https://qaihub-public-assets.s3.us-west-2.amazonaws.com/qai-hub-models/models/yamnet/releases/v0.61.0/yamnet-onnx-float.zip", + 13_893_328, + "0fbd3ed023fc6fdd63b3fcedf05c7d9730015187e0fa7ba38ea11ae2356364ec", + ); + crate::download::download_verified(client, &pin, &archive, progress).await?; + let names: Vec = DETECTOR_FILES.iter().map(|f| f.0.to_string()).collect(); + crate::download::extract_named(&archive, "yamnet-onnx-float", &names, &dir, 20 << 20)?; + ensure!(detector_ready(&dir), "Music model verification failed"); + let _ = std::fs::remove_file(&archive); + Ok(dir) +} + +// ---------------------------------------------------------------- YAMNet front end and classifier + +static MEL_BANK: LazyLock> = LazyLock::new(|| { + let mel = |f: f64| 2595.0 * (1.0 + f / 700.0).log10(); + let (lo, hi) = (mel(125.0), mel(7500.0)); + let edges: Vec = (0..66).map(|i| 700.0 * (10f64.powf((lo + (hi - lo) * i as f64 / 65.0) / 2595.0) - 1.0)).collect(); + (0..257) + .map(|k| { + let f = 8000.0 * k as f64 / 256.0; + let mut row = [0f32; 64]; + for (m, slot) in row.iter_mut().enumerate() { + let rising = (f - edges[m]) / (edges[m + 1] - edges[m]); + let falling = (edges[m + 2] - f) / (edges[m + 2] - edges[m + 1]); + *slot = rising.min(falling).max(0.0) as f32; + } + row + }) + .collect() +}); + +/// The classifier's `[1,1,96,64]` log-mel patch of the last second (periodic Hann 400 in a 512 FFT, hop 160). +pub fn log_mel_patch(samples: &[f32]) -> Vec { + let mut wave: Vec = samples[samples.len().saturating_sub(RATE)..].iter().map(|x| x.clamp(-1.0, 1.0)).collect(); + wave.resize(RATE, 0.0); + let mut padded: Vec = (1..=256).rev().map(|i| wave[i]).collect(); + padded.extend_from_slice(&wave); + padded.extend((1..=256).map(|i| wave[RATE - 1 - i])); + let window: Vec = (0..512) + .map(|i| if (56..456).contains(&i) { 0.5 - 0.5 * (2.0 * std::f32::consts::PI * (i - 56) as f32 / 400.0).cos() } else { 0.0 }) + .collect(); + let fft = FftPlanner::::new().plan_fft_forward(512); + let mut out = Vec::with_capacity(96 * 64); + for frame in 0..96 { + let mut buf: Vec> = (0..512).map(|i| Complex::new(padded[frame * 160 + i] * window[i], 0.0)).collect(); + fft.process(&mut buf); + for m in 0..64 { + let energy: f32 = (0..257).map(|k| buf[k].norm() * MEL_BANK[k][m]).sum(); + out.push((energy + 0.001).ln()); + } + } + out +} + +pub struct Yamnet { + session: ort::session::Session, +} + +impl Yamnet { + pub fn load(dir: &Path) -> Result { + ensure!(detector_ready(dir), "Music model verification failed"); + let labels: Vec = std::fs::read_to_string(dir.join("labels.txt"))?.lines().map(str::to_lowercase).collect(); + ensure!(labels.len() == 521 && CLASSES.iter().all(|(n, i)| labels[*i] == *n), "Music class map verification failed"); + let session = ort::session::Session::builder(crate::ort_env()?)? + .with_intra_threads(1) + .map_err(|e| anyhow::anyhow!("{e}"))? + .with_inter_threads(1) + .map_err(|e| anyhow::anyhow!("{e}"))? + .commit_from_file(dir.join("yamnet.onnx"))?; + Ok(Self { session }) + } + + /// Class probabilities (the export returns logits). + pub fn classify(&mut self, window: &[f32]) -> Result> { + let patch = log_mel_patch(window); + let outputs = self.session.run(ort::inputs!["audio" => ort::value::Tensor::from_array(([1usize, 1, 96, 64], patch))?])?; + Ok(outputs[0].try_extract_tensor::()?.1.iter().map(|x| 1.0 / (1.0 + (-x.clamp(-60.0, 60.0)).exp())).collect()) + } +} + +// ---------------------------------------------------------------- tempo (port of tempo.py; constants matter) + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Tempo { + pub tempo: f64, + pub confidence: f64, + pub phase: f64, +} + +pub struct TempoTracker { + window: Vec, + fft: std::sync::Arc>, + samples: Vec, + onsets: VecDeque, + times: VecDeque, + previous: Option>, + sample_count: u64, + nonmusic: u32, + locked: Option, + candidate: Option, + candidate_count: u32, +} + +fn round_to(x: f64, digits: i32) -> f64 { + let p = 10f64.powi(digits); + (x * p).round() / p +} + +fn correlation(envelope: &[f64], lag: f64) -> f64 { + let shift = lag.round_ties_even() as usize; + if shift < 1 || shift * 3 >= envelope.len() { + return 0.0; + } + let (left, right) = (&envelope[..envelope.len() - shift], &envelope[shift..]); + let norm = |v: &[f64]| v.iter().map(|x| x * x).sum::().sqrt(); + let denominator = norm(left) * norm(right); + if denominator > 1e-12 { left.iter().zip(right).map(|(a, b)| a * b).sum::() / denominator } else { 0.0 } +} + +/// Best-supported pulse grid: (offset in periods, support). +fn phase(times: &[f64], weights: &[f64], period: f64) -> (f64, f64) { + let phases: Vec = times.iter().map(|t| (t / period).rem_euclid(1.0)).collect(); + let total: f64 = weights.iter().sum(); + let kernel = |p: f64, g: f64| { + let d = (p - g + 0.5).rem_euclid(1.0) - 0.5; + (-0.5 * (d / 0.075).powi(2)).exp() + }; + let (mut best, mut best_support) = (0, f64::MIN); + for g in 0..64 { + let support = phases.iter().zip(weights).map(|(p, w)| kernel(*p, g as f64 / 64.0) * w).sum::() / total; + if support > best_support { + (best, best_support) = (g, support); + } + } + let (mut re, mut im) = (0.0, 0.0); + for (p, w) in phases.iter().zip(weights) { + let lw = kernel(*p, best as f64 / 64.0) * w; + re += (std::f64::consts::TAU * p).cos() * lw; + im += (std::f64::consts::TAU * p).sin() * lw; + } + (im.atan2(re) / std::f64::consts::TAU, best_support) +} + +impl Default for TempoTracker { + fn default() -> Self { + let window = (0..512).map(|n| (0.5 - 0.5 * (2.0 * std::f64::consts::PI * n as f64 / 511.0).cos()) as f32).collect(); + let mut t = Self { + window, + fft: FftPlanner::new().plan_fft_forward(512), + samples: Vec::new(), + onsets: VecDeque::new(), + times: VecDeque::new(), + previous: None, + sample_count: 0, + nonmusic: 0, + locked: None, + candidate: None, + candidate_count: 0, + }; + t.reset(); + t + } +} + +impl TempoTracker { + pub fn reset(&mut self) { + self.samples.clear(); + self.onsets.clear(); + self.times.clear(); + self.previous = None; + self.sample_count = 0; + self.nonmusic = 0; + self.locked = None; + self.candidate = None; + self.candidate_count = 0; + } + + /// One contiguous block; callers reset on sequence gaps. + pub fn accept(&mut self, block: &[f32]) -> Result<()> { + ensure!(!block.is_empty() && block.len() <= RATE && block.iter().all(|x| x.is_finite()), "Invalid tempo samples"); + let start = self.sample_count - self.samples.len() as u64; + self.sample_count += block.len() as u64; + self.samples.extend(block.iter().map(|x| x.clamp(-1.0, 1.0))); + if self.samples.len() < 512 { + return Ok(()); + } + let frames = (self.samples.len() - 512) / 160 + 1; + for f in 0..frames { + let mut buf: Vec> = (0..512).map(|i| Complex::new(self.samples[f * 160 + i] * self.window[i], 0.0)).collect(); + self.fft.process(&mut buf); + let spectrum: Vec = buf[1..241].iter().map(|c| c.norm()).collect(); + let previous = self.previous.as_deref().unwrap_or(&spectrum); + let diff: Vec = spectrum.iter().zip(previous).map(|(a, b)| (a - b).max(0.0) as f64).collect(); + let mean = |r: std::ops::Range| diff[r.clone()].iter().sum::() / r.len() as f64; + let novelty = 0.45 * mean(0..8) + 0.35 * mean(8..64) + 0.20 * mean(64..240); + self.previous = Some(spectrum); + self.onsets.push_back(novelty); + self.times.push_back((start + (f * 160) as u64 + 256) as f64 / RATE as f64); + if self.onsets.len() > 1200 { + self.onsets.pop_front(); + self.times.pop_front(); + } + } + self.samples.drain(..frames * 160); + Ok(()) + } + + /// BPM, confidence and beat phase at the latest block end; unknown is all zeros. + pub fn estimate(&mut self, music: bool) -> Tempo { + let unknown = Tempo::default(); + if !music { + self.nonmusic += 1; + if self.nonmusic >= 3 { + self.reset(); + self.nonmusic = 3; + } + return unknown; + } + self.nonmusic = 0; + if self.onsets.len() < 300 { + return unknown; + } + let skip = self.onsets.len().saturating_sub(800); + let raw: Vec = self.onsets.iter().skip(skip).copied().collect(); + let times: Vec = self.times.iter().skip(skip).copied().collect(); + let n = raw.len(); + let at = |i: isize| raw[i.clamp(0, n as isize - 1) as usize]; + let mut envelope: Vec = (0..n as isize).map(|i| (raw[i as usize] - (i - 10..=i + 10).map(at).sum::() / 21.0).max(0.0)).collect(); + let e = envelope.clone(); + for i in 0..n { + envelope[i] = 0.5 * e[i] + 0.25 * if i > 0 { e[i - 1] } else { 0.0 } + 0.25 * if i + 1 < n { e[i + 1] } else { 0.0 }; + } + let peak = envelope.iter().cloned().fold(0.0, f64::max); + if peak < 0.005 { + return unknown; + } + let peaks: Vec = (1..n - 1).filter(|&i| envelope[i] >= envelope[i - 1] && envelope[i] > envelope[i + 1] && envelope[i] >= peak * 0.18).collect(); + if peaks.len() < 5 { + return unknown; + } + let mean = envelope.iter().sum::() / n as f64; + let centred: Vec = envelope.iter().map(|x| x - mean).collect(); + let peak_times: Vec = peaks.iter().map(|&i| times[i]).collect(); + let weights: Vec = peaks.iter().map(|&i| envelope[i]).collect(); + let correlations: Vec = (25..151).map(|lag| correlation(¢red, lag as f64)).collect(); + let mut candidates: Vec<(f64, f64, f64)> = Vec::new(); + for (index, &direct) in correlations.iter().enumerate() { + if direct < 0.35 || (index > 0 && direct < correlations[index - 1]) || (index + 1 < correlations.len() && direct < correlations[index + 1]) { + continue; + } + let mut lag = (index + 25) as f64; + if index > 0 && index < correlations.len() - 1 { + let (a, b, c) = (correlations[index - 1], correlations[index], correlations[index + 1]); + let denominator = a - 2.0 * b + c; + if denominator < -1e-9 { + lag += (0.5 * (a - c) / denominator).clamp(-0.5, 0.5); + } + } + let (mut support, mut weight) = (0.0, 0.0); + for (multiplier, strength) in [(1.0, 0.6), (2.0, 0.25), (3.0, 0.15)] { + if lag * multiplier * 3.0 < n as f64 { + support += correlation(¢red, lag * multiplier).max(0.0) * strength; + weight += strength; + } + } + let (_, phase_support) = phase(&peak_times, &weights, lag / 100.0); + candidates.push((support / weight.max(1e-9) - 0.065 * lag / 150.0 + 0.4 * phase_support, lag, direct)); + } + if candidates.is_empty() { + return unknown; + } + candidates.sort_by(|a, b| b.partial_cmp(a).unwrap()); + let (mut score, mut lag, mut direct) = candidates[0]; + // Prefer the primitive period over a multiple with the same evidence. + for &(s, l, d) in &candidates[1..] { + let ratio = lag / l; + if (ratio - ratio.round()).abs() < 0.045 && ratio > 1.8 && ratio < 4.2 && s >= score - 0.08 && d >= direct * 0.86 { + (score, lag, direct) = (s, l, d); + } + } + let mut bpm = (6000.0 / lag).clamp(40.0, 240.0); + if let Some(locked) = self.locked { + let ratio = bpm / locked; + if (ratio - 2.0).abs() < 0.06 || (ratio - 0.5).abs() < 0.025 { + let old_lag = 6000.0 / locked; + let old = correlation(¢red, old_lag); + let (_, old_phase) = phase(&peak_times, &weights, old_lag / 100.0); + let (_, new_phase) = phase(&peak_times, &weights, lag / 100.0); + if old >= direct * 0.88 && old_phase >= 0.35f64.max(new_phase * 0.85) { + (bpm, lag, direct) = (locked, old_lag, old); + } + } + } + let period = lag / 100.0; + let (_, coherence) = phase(&peak_times, &weights, period); + let confidence = (0.65 * direct + 0.35 * coherence).clamp(0.0, 1.0); + if coherence < 0.35 || confidence < 0.53 { + return unknown; + } + let now = self.sample_count as f64 / RATE as f64; + if now - peak_times[peak_times.len() - 1] > period * 2.2 { + return unknown; + } + if self.candidate.is_some_and(|c| (bpm / c - 1.0).abs() < 0.035) { + self.candidate_count += 1; + } else { + self.candidate_count = 1; + } + self.candidate = Some(bpm); + if self.candidate_count < 2 { + return unknown; + } + if let Some(locked) = self.locked + && (bpm / locked - 1.0).abs() < 0.025 + { + bpm = locked * 0.6 + bpm * 0.4; + } + self.locked = Some(bpm); + let period = 60.0 / bpm; + let (offset, _) = phase(&peak_times, &weights, period); + let beat = (now / period - offset).rem_euclid(1.0); + Tempo { tempo: round_to(bpm, 3), confidence: round_to(confidence, 6), phase: round_to(beat, 6).min(0.999999) } + } +} + +// ---------------------------------------------------------------- streaming classifier + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Classification { + pub music: f64, + pub speech: f64, + pub singing: f64, + pub rms: f64, + pub tempo: Tempo, +} + +/// Windows the stream and classifies once per second; `classify` returns the 521 class probabilities. +pub struct Analyzer { + classify: C, + window: Vec, + scores: VecDeque>, + since: usize, + pub tempo: TempoTracker, +} + +impl Result>> Analyzer { + pub fn new(classify: C) -> Self { + Self { classify, window: Vec::new(), scores: VecDeque::new(), since: 0, tempo: TempoTracker::default() } + } + + /// Session or sequence change: forget audio, scores and tempo. + pub fn reset(&mut self) { + self.window.clear(); + self.scores.clear(); + self.since = 0; + self.tempo.reset(); + } + + pub fn accept(&mut self, packet: &[f32]) -> Result> { + ensure!(packet.len() == PACKET && packet.iter().all(|x| x.is_finite()), "Invalid music packet"); + self.tempo.accept(packet)?; + self.window.extend(packet.iter().map(|x| x.clamp(-1.0, 1.0))); + let excess = self.window.len().saturating_sub(WINDOW); + self.window.drain(..excess); + self.since += packet.len(); + if self.since < HOP { + return Ok(None); + } + self.since = 0; + let rms = (self.window.iter().map(|x| (*x as f64).powi(2)).sum::() / self.window.len() as f64).sqrt(); + let scores = if rms < 0.0003 { vec![0.0; 521] } else { (self.classify)(&self.window)? }; + ensure!(scores.len() == 521, "Unexpected music model output"); + self.scores.push_back(scores); + if self.scores.len() > 3 { + self.scores.pop_front(); + } + let mean = |i: usize| self.scores.iter().map(|s| s[i] as f64).sum::() / self.scores.len() as f64; + let music = mean(132); + let tempo = self.tempo.estimate(music >= 0.6 && rms >= 0.0003); + Ok(Some(Classification { music: round_to(music, 6), speech: round_to(mean(0), 6), singing: round_to(mean(24), 6), rms: round_to(rms, 6), tempo })) + } +} + +// ---------------------------------------------------------------- decision + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct MusicDecision { + pub hearing_music: bool, + enter: u32, + exit: u32, + pub energy: f64, + pub music: f64, + pub speech: f64, + pub tempo: f64, + pub tempo_confidence: f64, + /// Epoch milliseconds of a beat. + pub beat_at: f64, + pending: Option<(f64, f64, f64)>, +} + +impl MusicDecision { + pub fn reset(&mut self) { + *self = Self::default(); + } + + /// Three consecutive windows to enter or leave music; a reliable beat waits privately for the gate. + pub fn update(&mut self, c: &Classification, captured_at_ms: f64) -> bool { + self.music = c.music; + self.speech = c.speech; + self.energy = (c.rms * 6.0).min(1.0); + self.enter = if c.music >= 0.6 && c.rms >= 0.0003 { self.enter + 1 } else { 0 }; + self.exit = if c.music < 0.28 || c.rms < 0.0003 { self.exit + 1 } else { 0 }; + if !self.hearing_music && self.enter >= 3 { + self.hearing_music = true; + } else if self.hearing_music && self.exit >= 3 { + self.hearing_music = false; + } + let t = c.tempo; + let beat = (t.tempo > 0.0 && t.confidence >= TEMPO_MIN_CONFIDENCE).then(|| (t.tempo, t.confidence, (captured_at_ms - t.phase * 60000.0 / t.tempo).max(0.0))); + if !self.hearing_music { + let pending = if self.enter > 0 { beat.or(self.pending) } else { None }; + (self.tempo, self.tempo_confidence, self.beat_at) = (0.0, 0.0, 0.0); + self.pending = pending; + } else if let Some((tempo, confidence, at)) = beat.or(self.pending.take()) { + (self.tempo, self.tempo_confidence, self.beat_at) = (tempo, confidence, at); + } + self.hearing_music + } + + /// Music poses only once the BPM is known (no motionless dance while warming up). + pub fn animation_ready(&self) -> bool { + self.hearing_music && (40.0..=240.0).contains(&self.tempo) && self.tempo_confidence >= TEMPO_MIN_CONFIDENCE + } +} + +// ---------------------------------------------------------------- capture + +/// `parec` on the default sink monitor: stereo f32 at 16 kHz, resampled by the sound server. +pub fn monitor_command() -> std::process::Command { + let mut c = std::process::Command::new("parec"); + c.args(["--device=@DEFAULT_MONITOR@", "--format=float32le", "--rate=16000", "--channels=2", "--raw", "--latency-msec=100", "--client-name=Capri", "--stream-name=Capri music listening"]); + c +} + +/// Per 128-frame quantum, keeps the channel with the most energy (anti-phase or one-sided stereo survives). +pub fn louder_channel(stereo: &[f32]) -> Vec { + stereo + .chunks(256) + .flat_map(|q| { + let energy = |c: usize| q.iter().skip(c).step_by(2).map(|x| x * x).sum::(); + let c = usize::from(energy(1) > energy(0)); + q.iter().skip(c).step_by(2).copied().collect::>() + }) + .collect() +} + +/// Reads 0.5 s mono packets from a capture process (stdout: interleaved stereo f32le) until `stop` or EOF. +pub fn read_packets(mut command: std::process::Command, stop: &std::sync::atomic::AtomicBool, mut packet: impl FnMut(Vec) -> Result<()>) -> Result<()> { + use std::os::unix::process::CommandExt; + unsafe { + command.pre_exec(|| { + libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM); + Ok(()) + }); + } + let mut child = command.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::null()).spawn().context("System audio capture needs parec (pacman -S libpulse)")?; + let mut stdout = child.stdout.take().context("no capture output")?; + let mut bytes = vec![0u8; PACKET * 2 * 4]; + let result = loop { + if stop.load(std::sync::atomic::Ordering::Relaxed) { + break Ok(()); + } + match stdout.read_exact(&mut bytes) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => break Ok(()), + Err(e) => break Err(e.into()), + } + let stereo: Vec = bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect(); + if let Err(e) = packet(louder_channel(&stereo)) { + break Err(e); + } + }; + let _ = child.kill(); + let _ = child.wait(); + if result.is_ok() && !stop.load(std::sync::atomic::Ordering::Relaxed) { + bail!("System audio stopped. Enable it again to reconnect."); + } + result +} + +#[cfg(test)] +mod tests { + use super::*; + + /// 120 BPM: a decaying noise burst every 0.5 s. + fn clicks(seconds: usize, bpm: f64) -> Vec { + let mut seed: u32 = 1; + let period = (RATE as f64 * 60.0 / bpm) as usize; + (0..seconds * RATE) + .map(|i| { + seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); + let noise = seed as f32 / u32::MAX as f32 * 2.0 - 1.0; + let t = i % period; + if t < 800 { noise * 0.8 * (-(t as f32) / 150.0).exp() } else { noise * 0.002 } + }) + .collect() + } + + #[test] + fn tempo_tracks_a_click_track() { + let mut tracker = TempoTracker::default(); + let mut last = Tempo::default(); + for (i, packet) in clicks(12, 120.0).chunks(PACKET).enumerate() { + tracker.accept(packet).unwrap(); + if i % 2 == 1 { + last = tracker.estimate(true); + } + } + assert!((last.tempo - 120.0).abs() < 2.5, "{last:?}"); + assert!(last.confidence >= 0.53 && (0.0..1.0).contains(&last.phase)); + for _ in 0..3 { + tracker.estimate(false); + } + assert_eq!(tracker.estimate(true), Tempo::default(), "three non-music windows reset the tracker"); + } + + #[test] + fn chunking_does_not_change_onsets() { + let audio = clicks(2, 100.0); + let (mut a, mut b) = (TempoTracker::default(), TempoTracker::default()); + a.accept(&audio[..16000]).unwrap(); + a.accept(&audio[16000..]).unwrap(); + for chunk in audio.chunks(1234) { + b.accept(chunk).unwrap(); + } + assert_eq!(a.onsets.len(), b.onsets.len()); + assert!(a.onsets.iter().zip(&b.onsets).all(|(x, y)| (x - y).abs() < 1e-6)); + } + + #[test] + fn analyzer_classifies_each_second_and_decision_has_hysteresis() { + let mut analyzer = Analyzer::new(|_: &[f32]| { + let mut s = vec![0.0f32; 521]; + s[132] = 0.9; + Ok(s) + }); + let audio = clicks(4, 120.0); + let results: Vec<_> = audio.chunks(PACKET).filter_map(|p| analyzer.accept(p).unwrap()).collect(); + assert_eq!(results.len(), 4); + assert!((results[0].music - 0.9).abs() < 1e-6 && results[0].rms > 0.0); + let mut decision = MusicDecision::default(); + let beat = Classification { music: 0.9, rms: 0.05, tempo: Tempo { tempo: 120.0, confidence: 0.8, phase: 0.5 }, ..Default::default() }; + assert!(!decision.update(&beat, 10_000.0)); + assert_eq!(decision.tempo, 0.0, "beat stays private before the gate opens"); + assert!(!decision.update(&Classification { tempo: Tempo::default(), ..beat }, 11_000.0)); + assert!(decision.update(&Classification { tempo: Tempo::default(), ..beat }, 12_000.0)); + assert_eq!((decision.tempo, decision.beat_at), (120.0, 9_750.0), "prewarmed beat published on entry"); + assert!(decision.animation_ready()); + let quiet = Classification { music: 0.1, rms: 0.05, ..Default::default() }; + decision.update(&quiet, 13_000.0); + decision.update(&quiet, 14_000.0); + assert!(!decision.update(&quiet, 15_000.0)); + } + + #[test] + fn front_end_shape_and_channel_choice() { + let patch = log_mel_patch(&clicks(1, 120.0)); + assert_eq!(patch.len(), 96 * 64); + assert!(patch.iter().all(|x| x.is_finite())); + let silent = log_mel_patch(&[]); + assert!(silent.iter().all(|x| (x - 0.001f32.ln()).abs() < 1e-5)); + let stereo: Vec = (0..512).flat_map(|i| [0.0, (i as f32).sin()]).collect(); + assert_eq!(louder_channel(&stereo)[5], (5.0f32).sin()); + } + + /// Downloads and runs the pinned YAMNet (13.9 MB): `CAPRI_VOICE_DATA_DIR=/tmp/x cargo test -- --ignored`. + #[tokio::test] + #[ignore] + async fn yamnet_classifies_silence_and_noise() { + let data = PathBuf::from(std::env::var("CAPRI_VOICE_DATA_DIR").unwrap()); + let dir = provision_detector(&crate::download::http_client(), &data, &|_, _| {}).await.unwrap(); + let mut model = Yamnet::load(&dir).unwrap(); + let scores = model.classify(&clicks(3, 120.0)).unwrap(); + assert_eq!(scores.len(), 521); + assert!(scores.iter().all(|s| (0.0..=1.0).contains(s))); + } + + #[test] + fn capture_reads_packets_from_a_process() { + let dir = tempfile::tempdir().unwrap(); + let raw = dir.path().join("audio.raw"); + let bytes: Vec = (0..PACKET * 2 * 2).flat_map(|i| (if i % 2 == 0 { 0.25f32 } else { 0.0 }).to_le_bytes()).collect(); + std::fs::write(&raw, bytes).unwrap(); + let mut command = std::process::Command::new("cat"); + command.arg(&raw); + let stop = std::sync::atomic::AtomicBool::new(false); + let mut packets = Vec::new(); + let result = read_packets(command, &stop, |p| { + packets.push(p); + Ok(()) + }); + assert_eq!(packets.len(), 2); + assert!(packets[0].iter().all(|x| *x == 0.25)); + assert!(result.unwrap_err().to_string().contains("System audio stopped"), "an ended capture is reported"); + } +}