diff --git a/CLAUDE.md b/CLAUDE.md index f9ca98b..159617c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -50,8 +50,8 @@ The engine drives the chain per-block. Stages may override `Stage::process_block via nam-rs's batched `process_buffer`); the default impl loops per sample. RT thread = JACK process callback (standalone) or nih-plug `process()` (plugin). GUI → engine is -crossbeam channels; engine → GUI is `ArcSwap` (tuner, peak meter). Nothing allocates, locks, or -does I/O on the RT path — `rustortion-core/tests/no_alloc.rs` enforces this in CI. +crossbeam channels; engine → GUI is atomics (peak meter) and a lock-free sample queue (tuner — +pitch detection runs on the GUI thread). Nothing allocates, locks, or does I/O on the RT path — `rustortion-core/tests/no_alloc.rs` enforces this in CI. ## Adding a stage diff --git a/Cargo.lock b/Cargo.lock index 6eb3e02..291a59f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3802,7 +3802,6 @@ name = "rustortion-core" version = "0.3.0" dependencies = [ "anyhow", - "arc-swap", "assert_no_alloc", "chrono", "clap", diff --git a/rustortion-core/Cargo.toml b/rustortion-core/Cargo.toml index ce5fcb8..d4885e5 100644 --- a/rustortion-core/Cargo.toml +++ b/rustortion-core/Cargo.toml @@ -15,7 +15,6 @@ log = "0.4" anyhow = "1.0" rustfft = "6.4" realfft = "3.5" -arc-swap = "1.8" nam-rs = "0.4.0" [dev-dependencies] diff --git a/rustortion-core/src/tuner/mod.rs b/rustortion-core/src/tuner/mod.rs index d8fc0f0..4e929d5 100644 --- a/rustortion-core/src/tuner/mod.rs +++ b/rustortion-core/src/tuner/mod.rs @@ -1,19 +1,35 @@ -use arc_swap::ArcSwap; -use std::sync::Arc; +use crossbeam::queue::ArrayQueue; +use std::sync::{Arc, Mutex, PoisonError}; const BUFFER_SIZE: usize = 4096; -const A1_HZ: f32 = 50.1; -const E6_HZ: f32 = 1245.0; +/// Input above this rate is averaged down before analysis, keeping the window +/// long enough for [`MIN_HZ`] and the cost independent of the device rate. +const MAX_ANALYSIS_RATE: usize = 48_000; +/// Just below a 5-string bass's low B (30.87 Hz). +const MIN_HZ: f32 = 30.0; +const MAX_HZ: f32 = 1245.0; +const YIN_THRESHOLD: f32 = 0.15; +/// RT-side half: only copies input into a lock-free queue. Pitch detection +/// runs in [`TunerHandle::get_tuner_info`], off the audio thread. pub struct Tuner { - buffer: Vec, - sample_rate: usize, - info: Arc>, + queue: Arc>, enabled: bool, } pub struct TunerHandle { - info: Arc>, + queue: Arc>, + decimation: usize, + analysis_rate: f32, + state: Mutex, +} + +struct AnalysisState { + buffer: Vec, + /// Running sum and count for the sample being averaged down. + acc: f32, + acc_len: usize, + info: TunerInfo, } #[derive(Debug, Clone, Default)] @@ -26,16 +42,26 @@ pub struct TunerInfo { impl Tuner { pub fn new(sample_rate: usize) -> (Self, TunerHandle) { - let info = Arc::new(ArcSwap::from_pointee(TunerInfo::default())); + let decimation = sample_rate.div_ceil(MAX_ANALYSIS_RATE).max(1); + // Two analysis windows, so a late GUI poll doesn't lose samples. + let queue = Arc::new(ArrayQueue::new(BUFFER_SIZE * decimation * 2)); ( Self { - buffer: Vec::with_capacity(BUFFER_SIZE), - sample_rate, - info: Arc::clone(&info), + queue: Arc::clone(&queue), enabled: false, }, - TunerHandle { info }, + TunerHandle { + queue, + decimation, + analysis_rate: sample_rate as f32 / decimation as f32, + state: Mutex::new(AnalysisState { + buffer: Vec::with_capacity(BUFFER_SIZE), + acc: 0.0, + acc_len: 0, + info: TunerInfo::default(), + }), + }, ) } @@ -44,12 +70,9 @@ impl Tuner { return; } - self.buffer.extend_from_slice(samples); - if self.buffer.len() >= BUFFER_SIZE { - let detected_frequency = self.simple_amdf(); - self.info.store(Arc::new(detected_frequency.into())); - - self.buffer.clear(); + // Evicts the oldest sample when full, so the analysis sees fresh input. + for &sample in samples { + self.queue.force_push(sample); } } @@ -57,55 +80,111 @@ impl Tuner { self.enabled } - pub fn set_enabled(&mut self, enabled: bool) { + pub const fn set_enabled(&mut self, enabled: bool) { self.enabled = enabled; - if !enabled { - self.buffer.clear(); - self.info.store(Arc::new(TunerInfo::default())); - } } +} - fn simple_amdf(&self) -> Option { - if self.buffer.is_empty() { - return None; - } - let rms = - (self.buffer.iter().map(|x| x * x).sum::() / self.buffer.len() as f32).sqrt(); - - if rms < 0.01 { - return None; - } - - let min_period = (self.sample_rate as f32 / E6_HZ) as usize; - let max_period = (self.sample_rate as f32 / A1_HZ) as usize; - - let mut best_period = 0; - let mut min_diff = f32::MAX; +impl TunerHandle { + /// Drains queued input and, once a full window has arrived, re-runs pitch + /// detection. Call periodically from a non-RT thread. + pub fn get_tuner_info(&self) -> TunerInfo { + let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); - for lag in min_period..max_period.min(self.buffer.len() / 2) { - let mut diff = 0.0; - for i in 0..(self.buffer.len() - lag) { - diff += (self.buffer[i] - self.buffer[i + lag]).abs(); + while let Some(sample) = self.queue.pop() { + state.acc += sample; + state.acc_len += 1; + if state.acc_len < self.decimation { + continue; } + let averaged = state.acc / self.decimation as f32; + state.acc = 0.0; + state.acc_len = 0; - if diff < min_diff { - min_diff = diff; - best_period = lag; + state.buffer.push(averaged); + if state.buffer.len() == BUFFER_SIZE { + state.info = detect_pitch(&state.buffer, self.analysis_rate).into(); + state.buffer.clear(); } } - if best_period > 0 { - Some(self.sample_rate as f32 / best_period as f32) - } else { - None - } + state.info.clone() + } + + /// Discards queued input and the last readout, e.g. when the tuner is re-enabled. + pub fn reset(&self) { + let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + while self.queue.pop().is_some() {} + state.buffer.clear(); + state.acc = 0.0; + state.acc_len = 0; + state.info = TunerInfo::default(); } } -impl TunerHandle { - pub fn get_tuner_info(&self) -> TunerInfo { - self.info.load().as_ref().clone() +/// YIN pitch detection: squared difference over a fixed window, cumulative-mean +/// normalised, taking the first dip below threshold to avoid subharmonic picks. +fn detect_pitch(buffer: &[f32], sample_rate: f32) -> Option { + if buffer.is_empty() { + return None; + } + let rms = (buffer.iter().map(|x| x * x).sum::() / buffer.len() as f32).sqrt(); + + if rms < 0.01 { + return None; + } + + let min_period = (sample_rate / MAX_HZ) as usize; + let max_period = ((sample_rate / MIN_HZ) as usize).min(buffer.len() / 2); + if min_period < 2 || min_period >= max_period { + return None; + } + let window = buffer.len() - max_period - 1; + + // One extra lag so the interpolation below always has a right neighbour. + let mut diff = vec![0.0_f32; max_period + 2]; + let mut cmndf = vec![1.0_f32; max_period + 2]; + let mut running_sum = 0.0_f32; + for lag in 1..=max_period + 1 { + diff[lag] = buffer[..window] + .iter() + .zip(&buffer[lag..lag + window]) + .map(|(a, b)| (a - b) * (a - b)) + .sum(); + running_sum += diff[lag]; + if running_sum > 0.0 { + cmndf[lag] = diff[lag] * lag as f32 / running_sum; + } } + + let range = min_period..=max_period; + let best_period = cmndf[range.clone()] + .iter() + .position(|&d| d < YIN_THRESHOLD) + .map(|i| { + // Walk down to the bottom of this dip. + let mut lag = min_period + i; + while lag < max_period && cmndf[lag + 1] < cmndf[lag] { + lag += 1; + } + lag + }) + .or_else(|| range.min_by(|&a, &b| cmndf[a].total_cmp(&cmndf[b])))?; + + // Parabolic fit through the neighbouring lags for sub-sample resolution. + let (prev, here, next) = ( + diff[best_period - 1], + diff[best_period], + diff[best_period + 1], + ); + let curvature = 2.0f32.mul_add(-here, prev + next); + let offset = if curvature > 0.0 { + (0.5 * (prev - next) / curvature).clamp(-0.5, 0.5) + } else { + 0.0 + }; + + Some(sample_rate / (best_period as f32 + offset)) } impl From> for TunerInfo { @@ -136,7 +215,7 @@ fn freq_to_note(freq: f32) -> (&'static str, i32, f32) { "A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", ]; let note_index = note_number.rem_euclid(12) as usize; - let octave = 4 + (note_number + 9) / 12; // +9 because A is 9 semitones before C + let octave = 4 + (note_number + 9).div_euclid(12); // +9 because A is 9 semitones before C (NOTES[note_index], octave, cents) } @@ -152,4 +231,126 @@ mod tests { assert_eq!(octave, 4); assert!(cents.abs() < 0.1); } + + #[test] + fn octave_numbers_below_c4() { + for (freq, name, oct) in [ + (55.0, "A", 1), + (82.41, "E", 2), + (110.0, "A", 2), + (246.94, "B", 3), + (261.63, "C", 4), + ] { + let (note, octave, _) = freq_to_note(freq); + assert_eq!((note, octave), (name, oct), "{freq} Hz"); + } + } + + #[test] + fn detects_fundamental_of_open_strings() { + let sr = 48_000; + for freq in [82.41, 110.0, 146.83, 196.0, 246.94, 329.63] { + let buf = sine_block(freq, sr, 0, BUFFER_SIZE); + let detected = detect_pitch(&buf, sr as f32).unwrap(); + assert!( + (detected / freq - 1.0).abs() < 0.01, + "{freq} Hz read as {detected}" + ); + } + } + + #[test] + fn detects_fundamental_with_strong_harmonic() { + let sr = 48_000; + let buf: Vec = sine_block(110.0, sr, 0, BUFFER_SIZE) + .iter() + .zip(sine_block(220.0, sr, 0, BUFFER_SIZE)) + .map(|(a, b)| a * 0.6 + b) + .collect(); + let detected = detect_pitch(&buf, sr as f32).unwrap(); + assert!((detected / 110.0 - 1.0).abs() < 0.01, "read as {detected}"); + } + + /// Feeds a harmonic-rich tone through the RT side until the handle reads it. + fn read_tone(freq: f32, sample_rate: usize) -> TunerInfo { + let (mut tuner, handle) = Tuner::new(sample_rate); + tuner.set_enabled(true); + for b in 0..1024 { + let block: Vec = (b * 128..(b + 1) * 128) + .map(|n| { + let p = std::f32::consts::TAU * freq * n as f32 / sample_rate as f32; + [(1.0, 0.3), (2.0, 0.25), (3.0, 0.15)] + .iter() + .map(|(h, a)| a * (h * p).sin()) + .sum::() + }) + .collect(); + tuner.process(&block); + let info = handle.get_tuner_info(); + if info.frequency.is_some() { + return info; + } + } + panic!("no reading for {freq} Hz at {sample_rate} Hz"); + } + + #[test] + fn reads_bass_and_guitar_range_within_two_cents() { + for sr in [44_100, 48_000, 96_000] { + for freq in [ + 30.87, 41.2, 55.0, 82.41, 110.0, 196.0, 329.63, 659.26, 1046.5, + ] { + let info = read_tone(freq, sr); + let (note, octave, _) = freq_to_note(freq); + let cents = 1200.0 * (info.frequency.unwrap() / freq).log2(); + assert_eq!( + info.note, + Some(format!("{note}{octave}")), + "{freq} Hz at {sr}: {info:?}" + ); + assert!(cents.abs() < 2.0, "{freq} Hz at {sr}: {cents:.1} cents off"); + } + } + } + + fn sine_block(freq: f32, sample_rate: usize, offset: usize, len: usize) -> Vec { + (offset..offset + len) + .map(|n| (std::f32::consts::TAU * freq * n as f32 / sample_rate as f32).sin() * 0.5) + .collect() + } + + #[test] + fn handle_detects_pitch_from_rt_input() { + let sr = 48_000; + let (mut tuner, handle) = Tuner::new(sr); + tuner.set_enabled(true); + + for b in 0..(BUFFER_SIZE / 128) { + tuner.process(&sine_block(110.0, sr, b * 128, 128)); + } + + let info = handle.get_tuner_info(); + assert!( + info.note.as_deref().is_some_and(|n| n.starts_with('A')), + "{info:?}" + ); + assert!(info.in_tune, "{info:?}"); + } + + #[test] + fn disabled_tuner_queues_nothing() { + let (mut tuner, handle) = Tuner::new(48_000); + tuner.process(&sine_block(110.0, 48_000, 0, BUFFER_SIZE)); + assert!(handle.get_tuner_info().frequency.is_none()); + } + + #[test] + fn reset_discards_stale_input() { + let sr = 48_000; + let (mut tuner, handle) = Tuner::new(sr); + tuner.set_enabled(true); + tuner.process(&sine_block(110.0, sr, 0, BUFFER_SIZE)); + handle.reset(); + assert!(handle.get_tuner_info().frequency.is_none()); + } } diff --git a/rustortion-core/tests/no_alloc.rs b/rustortion-core/tests/no_alloc.rs index 07f5a5c..7833957 100644 --- a/rustortion-core/tests/no_alloc.rs +++ b/rustortion-core/tests/no_alloc.rs @@ -967,26 +967,23 @@ mod message_arms { } #[test] - fn set_tuner_enabled_drain_does_not_allocate() { - // SetTunerEnabled(true) flips a bool; the subsequent tuner.process - // appends into a pre-allocated 4096-sample buffer. Stay well under the - // detection threshold so no AMDF run (which allocates a readout) fires. - // This one drives process() (not just the drain) to also cover the - // tuner buffer-growth path. + fn tuner_does_not_allocate() { + // Drives the tuner well past its 4096-sample analysis window with a + // detectable signal — pitch detection must never run on the RT thread. let (mut engine, handle) = full_engine(1.0, None); - let (input, mut output) = buffers(); + let input: Vec = (0..BUFFER_SIZE) + .map(|i| (i as f32 * 0.05).sin() * 0.5) + .collect(); + let mut output = vec![0.0_f32; BUFFER_SIZE]; engine.process(&input, &mut output).unwrap(); let violations = check_no_alloc(|| { handle.set_tuner_enabled(true); - for _ in 0..8 { + for _ in 0..128 { engine.process(&input, &mut output).unwrap(); } }); - assert_eq!( - violations, 0, - "SetTunerEnabled drain allocated {violations} time(s)" - ); + assert_eq!(violations, 0, "tuner allocated {violations} time(s)"); } } diff --git a/rustortion-standalone/src/gui/handlers/tuner.rs b/rustortion-standalone/src/gui/handlers/tuner.rs index a52b49e..c39cc6c 100644 --- a/rustortion-standalone/src/gui/handlers/tuner.rs +++ b/rustortion-standalone/src/gui/handlers/tuner.rs @@ -30,6 +30,7 @@ impl TunerHandler { if self.enabled { self.dialog.show(); + audio_manager.tuner().reset(); audio_manager.engine().set_tuner_enabled(true); } else { self.dialog.hide();