qualia_audio/features/spectral/
hfc.rs1use crate::types::AudioError;
4
5pub 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 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}"); assert!((hh - 7.0).abs() < 1e-6, "high hfc={hh}"); assert!(hh > hl);
40 }
41
42 #[test]
43 fn dc_only_is_zero() {
44 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 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}