qualia_audio/features/tonal/tuning.rs
1//! Reference tuning estimation from spectral peaks — **does not assume 440 Hz**.
2//!
3//! Given peak frequencies, we measure how far each sits from an equal-tempered
4//! semitone grid anchored at a *nominal* reference, then take the magnitude-
5//! weighted **circular mean** of those deviations (deviations wrap at ±50 cents,
6//! so a plain average would be wrong). The resulting global deviation recovers the
7//! true tuning reference: `ref = nominal * 2^(deviation_cents / 1200)`.
8//!
9//! The nominal anchor is a parameter, so nothing here hardcodes 440 Hz as truth —
10//! it is only the grid we measure *against*, and the estimate is free to land
11//! anywhere (432, 415, 443, …).
12//!
13//! Zero-heap: a single streaming pass over the peaks; no allocation.
14
15use crate::types::AudioError;
16
17/// Estimated tuning: the recovered reference frequency and its deviation from the
18/// nominal anchor, plus a confidence in `[0, 1]` (resultant-vector concentration —
19/// high when peaks agree on one tuning, low for noise / inharmonic material).
20#[derive(Debug, Clone, Copy, PartialEq)]
21pub struct TuningEstimate {
22 /// Recovered reference frequency (Hz) for the equal-tempered grid.
23 pub ref_freq_hz: f32,
24 /// Deviation from the nominal anchor, in cents (range about ±50).
25 pub deviation_cents: f32,
26 /// Confidence `[0, 1]`: circular concentration of the peak deviations.
27 pub confidence: f32,
28}
29
30/// Estimate the reference tuning frequency from spectral peaks.
31///
32/// - `peak_freqs` / `peak_mags`: parallel peak arrays (Hz, magnitude).
33/// - `n_peaks`: leading entries to use (clamped to the shorter array).
34/// - `nominal_ref_hz`: the anchor grid frequency to measure against (e.g. 440);
35/// parameterised — the estimate is not forced to it.
36///
37/// Deviations are folded into one semitone (100 cents) and averaged on the circle,
38/// so octave / semitone offsets of a peak do not bias the result — only its
39/// fractional detuning does.
40///
41/// # Errors
42/// - [`AudioError::InvalidParameter`] if `nominal_ref_hz` is not positive-finite.
43pub fn estimate_tuning(
44 peak_freqs: &[f32],
45 peak_mags: &[f32],
46 n_peaks: usize,
47 nominal_ref_hz: f32,
48) -> Result<TuningEstimate, AudioError> {
49 if !(nominal_ref_hz > 0.0) || !nominal_ref_hz.is_finite() {
50 return Err(AudioError::InvalidParameter);
51 }
52
53 let np = n_peaks.min(peak_freqs.len()).min(peak_mags.len());
54 let two_pi = core::f32::consts::TAU;
55
56 // Weighted sum of unit vectors at angle = 2π * (deviation_cents / 100).
57 let mut sum_cos = 0.0f32;
58 let mut sum_sin = 0.0f32;
59 let mut sum_w = 0.0f32;
60
61 for k in 0..np {
62 let f = peak_freqs[k];
63 let m = peak_mags[k];
64 if !(f > 0.0) || !f.is_finite() || !(m > 0.0) || !m.is_finite() {
65 continue;
66 }
67 // Cents relative to the nominal grid, folded into one semitone [0,100).
68 let cents = 1200.0 * (f / nominal_ref_hz).log2();
69 let mut frac = cents % 100.0;
70 if frac < 0.0 {
71 frac += 100.0;
72 }
73 let ang = two_pi * (frac / 100.0);
74 sum_cos += m * ang.cos();
75 sum_sin += m * ang.sin();
76 sum_w += m;
77 }
78
79 if sum_w <= 0.0 {
80 // No usable peaks — abstain: report the nominal with zero confidence.
81 return Ok(TuningEstimate {
82 ref_freq_hz: nominal_ref_hz,
83 deviation_cents: 0.0,
84 confidence: 0.0,
85 });
86 }
87
88 // Mean angle → mean fractional cents in [0,100); map to signed ±50.
89 let mean_ang = sum_sin.atan2(sum_cos);
90 let mut dev = 100.0 * (mean_ang / two_pi); // (-50, 50]-ish
91 if dev > 50.0 {
92 dev -= 100.0;
93 } else if dev < -50.0 {
94 dev += 100.0;
95 }
96
97 // Resultant length ∈ [0,1] = agreement/concentration of the peaks.
98 let resultant = (sum_cos * sum_cos + sum_sin * sum_sin).sqrt() / sum_w;
99 let confidence = resultant.clamp(0.0, 1.0);
100
101 let ref_freq_hz = nominal_ref_hz * 2f32.powf(dev / 1200.0);
102 Ok(TuningEstimate {
103 ref_freq_hz,
104 deviation_cents: dev,
105 confidence,
106 })
107}
108
109#[cfg(test)]
110mod tests {
111 use super::*;
112
113 fn semis(a4: f32, n: i32) -> f32 {
114 a4 * 2f32.powf(n as f32 / 12.0)
115 }
116
117 /// GOLDEN: peaks synthesised on a **432 Hz** equal-tempered grid are recovered
118 /// as ref ≈ 432 (a deliberately-detuned reference), measured against a 440
119 /// nominal — within a couple of cents.
120 #[test]
121 fn recovers_432_from_440_nominal() {
122 let a4 = 432.0f32;
123 // A spread of notes on the 432 grid.
124 let freqs = [
125 semis(a4, -12),
126 semis(a4, -9),
127 semis(a4, -5),
128 semis(a4, 0),
129 semis(a4, 4),
130 semis(a4, 7),
131 ];
132 let mags = [1.0f32; 6];
133 let est = estimate_tuning(&freqs, &mags, 6, 440.0).expect("tuning");
134
135 // 1200*log2(432/440) ≈ -31.77 cents.
136 assert!(
137 (est.deviation_cents - (-31.77)).abs() < 2.0,
138 "deviation = {} cents",
139 est.deviation_cents
140 );
141 assert!(
142 (est.ref_freq_hz - 432.0).abs() < 1.0,
143 "recovered ref = {} Hz",
144 est.ref_freq_hz
145 );
146 // In-tune, consistent peaks → high confidence.
147 assert!(est.confidence > 0.95, "confidence = {}", est.confidence);
148 }
149
150 /// Standard 440 material measured against 440 → ~0 cents deviation.
151 #[test]
152 fn in_tune_440_reads_zero() {
153 let a4 = 440.0f32;
154 let freqs = [semis(a4, -9), semis(a4, -5), semis(a4, -2)];
155 let mags = [1.0f32; 3];
156 let est = estimate_tuning(&freqs, &mags, 3, 440.0).expect("tuning");
157 assert!(
158 est.deviation_cents.abs() < 1.0,
159 "dev = {}",
160 est.deviation_cents
161 );
162 assert!((est.ref_freq_hz - 440.0).abs() < 0.5);
163 }
164
165 #[test]
166 fn rejects_bad_nominal() {
167 assert_eq!(
168 estimate_tuning(&[440.0], &[1.0], 1, 0.0),
169 Err(AudioError::InvalidParameter)
170 );
171 }
172
173 /// No usable peaks → abstain with zero confidence (nominal returned).
174 #[test]
175 fn abstains_without_peaks() {
176 let est = estimate_tuning(&[], &[], 0, 440.0).expect("tuning");
177 assert_eq!(est.confidence, 0.0);
178 assert_eq!(est.ref_freq_hz, 440.0);
179 }
180}