Skip to main content

qualia_audio/features/spectral/
hfc.rs

1//! High-frequency content (HFC) of a magnitude spectrum.
2
3use crate::types::AudioError;
4
5/// High-frequency content of a one-sided magnitude spectrum `mag`.
6///
7/// `HFC = Σ_k k · |X[k]|` — each bin is weighted by its index, so energy at
8/// higher bins contributes more. It is a percussive-onset / brightness measure:
9/// larger for spectra whose energy sits in the upper bins.
10///
11/// Zero-heap: single pass, scalar result.
12///
13/// # Errors
14/// - [`AudioError::InvalidParameter`] if `mag` is empty.
15pub fn high_frequency_content(mag: &[f32]) -> Result<f32, AudioError> {
16    if mag.is_empty() {
17        return Err(AudioError::InvalidParameter);
18    }
19    let mut acc = 0.0f64;
20    for (k, m) in mag.iter().enumerate() {
21        acc += (k as f64) * (*m as f64);
22    }
23    Ok(acc as f32)
24}
25
26#[cfg(test)]
27mod tests {
28    use super::*;
29
30    #[test]
31    fn high_bins_weigh_more() {
32        // Same total magnitude, placed low vs high in the spectrum.
33        let low = [0.0f32, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
34        let high = [0.0f32, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0];
35        let hl = high_frequency_content(&low).expect("hfc");
36        let hh = high_frequency_content(&high).expect("hfc");
37        assert!((hl - 1.0).abs() < 1e-6, "low hfc={hl}"); // 1 * 1.0
38        assert!((hh - 7.0).abs() < 1e-6, "high hfc={hh}"); // 7 * 1.0
39        assert!(hh > hl);
40    }
41
42    #[test]
43    fn dc_only_is_zero() {
44        // All energy at bin 0 -> weight 0 -> HFC 0.
45        let mag = [5.0f32, 0.0, 0.0, 0.0];
46        assert!(high_frequency_content(&mag).expect("hfc").abs() < 1e-6);
47    }
48
49    #[test]
50    fn known_sum() {
51        // 0*1 + 1*2 + 2*3 + 3*4 = 0 + 2 + 6 + 12 = 20
52        let mag = [1.0f32, 2.0, 3.0, 4.0];
53        assert!((high_frequency_content(&mag).expect("hfc") - 20.0).abs() < 1e-5);
54    }
55
56    #[test]
57    fn rejects_empty() {
58        assert_eq!(
59            high_frequency_content(&[]),
60            Err(AudioError::InvalidParameter)
61        );
62    }
63}