Skip to main content

qualia_audio/features/pitch/
yin.rs

1//! Full time-domain YIN fundamental-frequency estimator
2//! (de Cheveigné & Kawahara, 2002), delegated to [`etalon_signal::pitch`].
3
4use crate::features::pitch::confidence::pitch_confidence;
5use crate::features::pitch::estimate::{
6    absolute_threshold, cmnd_in_place, parabolic_min, PitchEstimate,
7};
8use crate::types::AudioError;
9
10/// Estimate the fundamental frequency of `frame` with the YIN algorithm.
11pub fn yin_pitch(
12    frame: &[f32],
13    sample_rate: f32,
14    min_hz: f32,
15    max_hz: f32,
16    threshold: f32,
17    scratch: &mut [f32],
18) -> Result<PitchEstimate, AudioError> {
19    let params_ok = sample_rate.is_finite()
20        && sample_rate > 0.0
21        && min_hz.is_finite()
22        && min_hz > 0.0
23        && max_hz.is_finite()
24        && max_hz > min_hz
25        && threshold.is_finite();
26    if !params_ok {
27        return Err(AudioError::InvalidParameter);
28    }
29    let n = frame.len();
30    if n < 8 {
31        return Err(AudioError::InvalidParameter);
32    }
33
34    let min_lag = ((sample_rate / max_hz).floor() as usize).max(2);
35    let max_lag = ((sample_rate / min_hz).floor() as usize).min(n / 2);
36    if max_lag < min_lag + 2 {
37        return Err(AudioError::InvalidParameter);
38    }
39    if scratch.len() < max_lag + 1 {
40        return Err(AudioError::OutputBufferTooSmall);
41    }
42
43    etalon_signal::pitch::yin_difference_into(frame, max_lag, &mut scratch[..=max_lag]);
44    cmnd_in_place(scratch, max_lag);
45
46    let tau = absolute_threshold(scratch, min_lag, max_lag, threshold);
47    let (better_tau, aperiodicity) = parabolic_min(scratch, tau, min_lag, max_lag);
48
49    if !(better_tau.is_finite() && better_tau > 0.0) {
50        return Ok(PitchEstimate::unvoiced());
51    }
52    let confidence = pitch_confidence(aperiodicity);
53    if aperiodicity > 1.0 || (scratch[tau] >= threshold && aperiodicity > 0.5) {
54        return Ok(PitchEstimate {
55            f0_hz: 0.0,
56            confidence,
57        });
58    }
59    Ok(PitchEstimate {
60        f0_hz: sample_rate / better_tau,
61        confidence,
62    })
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68    use core::f32::consts::TAU;
69
70    const SR: f32 = 44_100.0;
71
72    fn sine(freq: f32, n: usize, sr: f32) -> Vec<f32> {
73        (0..n).map(|i| (TAU * freq * i as f32 / sr).sin()).collect()
74    }
75
76    fn cents(a: f32, b: f32) -> f32 {
77        1200.0 * (a / b).log2().abs()
78    }
79
80    #[test]
81    fn recovers_440_within_one_percent() {
82        let frame = sine(440.0, 2048, SR);
83        let mut scratch = vec![0.0f32; 1200];
84        let est = yin_pitch(&frame, SR, 80.0, 1000.0, 0.1, &mut scratch).expect("yin");
85        let err = (est.f0_hz - 440.0).abs() / 440.0;
86        assert!(err < 0.01, "f0={} err={err}", est.f0_hz);
87        assert!(
88            cents(est.f0_hz, 440.0) < 10.0,
89            "cents={}",
90            cents(est.f0_hz, 440.0)
91        );
92        assert!(est.confidence > 0.9, "conf={}", est.confidence);
93    }
94
95    #[test]
96    fn recovers_220_within_one_percent() {
97        let frame = sine(220.0, 2048, SR);
98        let mut scratch = vec![0.0f32; 1200];
99        let est = yin_pitch(&frame, SR, 80.0, 1000.0, 0.1, &mut scratch).expect("yin");
100        let err = (est.f0_hz - 220.0).abs() / 220.0;
101        assert!(err < 0.01, "f0={} err={err}", est.f0_hz);
102        assert!(est.confidence > 0.9, "conf={}", est.confidence);
103    }
104
105    #[test]
106    fn parabolic_beats_integer_lag() {
107        let f0 = SR / 100.5;
108        let frame = sine(f0, 2048, SR);
109        let mut scratch = vec![0.0f32; 1200];
110        let est = yin_pitch(&frame, SR, 80.0, 1000.0, 0.1, &mut scratch).expect("yin");
111        let c = cents(est.f0_hz, f0);
112        assert!(c < 5.0, "recovered {} Hz vs {f0} Hz ({c} cents)", est.f0_hz);
113        assert!(cents(SR / 100.0, f0) > 8.0);
114    }
115
116    #[test]
117    fn white_noise_is_low_confidence() {
118        let mut s: u32 = 0x1234_5678;
119        let frame: Vec<f32> = (0..2048)
120            .map(|_| {
121                s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
122                (s >> 8) as f32 / (1u32 << 23) as f32 - 1.0
123            })
124            .collect();
125        let mut scratch = vec![0.0f32; 1200];
126        let est = yin_pitch(&frame, SR, 80.0, 1000.0, 0.1, &mut scratch).expect("yin");
127        assert!(est.confidence < 0.5, "noise conf={}", est.confidence);
128    }
129
130    #[test]
131    fn rejects_short_scratch() {
132        let frame = sine(440.0, 2048, SR);
133        let mut scratch = vec![0.0f32; 8];
134        assert_eq!(
135            yin_pitch(&frame, SR, 80.0, 1000.0, 0.1, &mut scratch),
136            Err(AudioError::OutputBufferTooSmall)
137        );
138    }
139
140    #[test]
141    fn rejects_bad_band() {
142        let frame = sine(440.0, 2048, SR);
143        let mut scratch = vec![0.0f32; 1200];
144        assert_eq!(
145            yin_pitch(&frame, SR, 1000.0, 80.0, 0.1, &mut scratch),
146            Err(AudioError::InvalidParameter)
147        );
148    }
149}