Skip to main content

qualia_audio/features/peaks/
max_mag_freq.rs

1//! Frequency of the maximum-magnitude bin (parabolic-refined).
2
3/// Frequency in Hz of the strongest bin in a one-sided magnitude spectrum
4/// `mag` (DC..Nyquist inclusive; bin spacing `sample_rate / (2*(N-1))`).
5///
6/// The peak bin is refined with a parabolic fit against its two neighbours when
7/// it is interior, giving a sub-bin frequency estimate. Returns `0.0` for an
8/// empty spectrum, a non-positive/non-finite `sample_rate`, or a peak that sits
9/// on the DC / Nyquist boundary (no interpolation possible — the bin-centre
10/// frequency is returned in that case).
11pub fn max_magnitude_frequency(mag: &[f32], sample_rate: f32) -> f32 {
12    if mag.is_empty() || sample_rate <= 0.0 || !sample_rate.is_finite() {
13        return 0.0;
14    }
15    if mag.len() == 1 {
16        return 0.0; // DC only
17    }
18    let bin_hz = sample_rate / (2.0 * (mag.len() - 1) as f32);
19
20    // Argmax.
21    let mut kmax = 0usize;
22    let mut vmax = mag[0];
23    for (k, &v) in mag.iter().enumerate() {
24        if v > vmax {
25            vmax = v;
26            kmax = k;
27        }
28    }
29
30    // Parabolic refinement when the peak is interior.
31    let mut refined = kmax as f32;
32    if kmax > 0 && kmax < mag.len() - 1 {
33        let ym1 = mag[kmax - 1];
34        let y0 = mag[kmax];
35        let yp1 = mag[kmax + 1];
36        let denom = ym1 - 2.0 * y0 + yp1;
37        if denom != 0.0 && denom.is_finite() {
38            refined += (0.5 * (ym1 - yp1) / denom).clamp(-0.5, 0.5);
39        }
40    }
41    refined * bin_hz
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47
48    /// Golden: a single-bin spike returns exactly that bin's frequency.
49    #[test]
50    fn single_bin_spike() {
51        let sr = 16000.0f32; // n = 9 bins (fft_size 16) -> bin_hz = 1000
52        let mut mag = [0.0f32; 9];
53        mag[3] = 1.0;
54        let f = max_magnitude_frequency(&mag, sr);
55        // Neighbours are zero -> symmetric -> no offset -> exactly 3 * 1000.
56        assert!((f - 3000.0).abs() < 1e-3, "f={f}");
57    }
58
59    /// Sub-bin: an asymmetric parabola vertex is recovered between bins.
60    #[test]
61    fn sub_bin_refinement() {
62        let sr = 2000.0f32; // n = 11 bins -> bin_hz = 100
63        let center = 5.4f32;
64        let mut mag = [0.0f32; 11];
65        for (k, m) in mag.iter_mut().enumerate() {
66            let v = 1.0 - 0.02 * (k as f32 - center) * (k as f32 - center);
67            *m = v.max(0.0);
68        }
69        let f = max_magnitude_frequency(&mag, sr);
70        assert!((f - center * 100.0).abs() < 1.0, "f={f}");
71    }
72
73    #[test]
74    fn empty_is_zero() {
75        assert_eq!(max_magnitude_frequency(&[], 44100.0), 0.0);
76    }
77
78    #[test]
79    fn bad_rate_is_zero() {
80        assert_eq!(max_magnitude_frequency(&[0.0, 1.0, 0.0], -1.0), 0.0);
81    }
82}