Skip to main content

qualia_audio/features/loudness/
crest_factor.rs

1//! Crest factor — peak-to-RMS ratio, delegated to [`etalon_signal::loudness`].
2
3/// Linear crest factor `max|x| / rms(x)` of a mono block.
4#[inline]
5pub fn crest_factor(samples: &[f32]) -> f32 {
6    etalon_signal::loudness::crest_factor_f32(samples)
7}
8
9/// Crest factor in dB (`20*log10(peak/rms)`).
10#[inline]
11pub fn crest_factor_db(samples: &[f32]) -> f32 {
12    etalon_signal::loudness::crest_factor_db(samples)
13}
14
15#[cfg(test)]
16mod tests {
17    use super::*;
18    use core::f32::consts::PI;
19
20    fn sine(n: usize, amp: f32) -> Vec<f32> {
21        (0..n)
22            .map(|i| amp * (2.0 * PI * 1_000.0 * i as f32 / 48_000.0).sin())
23            .collect()
24    }
25
26    #[test]
27    fn sine_crest_is_root_two() {
28        let s = sine(48_000, 0.8);
29        let c = crest_factor(&s);
30        assert!((c - core::f32::consts::SQRT_2).abs() < 1e-2, "crest {c}");
31    }
32
33    #[test]
34    fn sine_crest_db_is_about_3() {
35        let s = sine(48_000, 0.8);
36        let db = crest_factor_db(&s);
37        assert!((db - 3.0103).abs() < 0.1, "crest dB {db}");
38    }
39
40    #[test]
41    fn square_wave_crest_is_one() {
42        let s: Vec<f32> = (0..1000)
43            .map(|i| if i % 2 == 0 { 0.5 } else { -0.5 })
44            .collect();
45        let c = crest_factor(&s);
46        assert!((c - 1.0).abs() < 1e-4, "crest {c}");
47    }
48
49    #[test]
50    fn empty_and_silent_are_zero() {
51        assert_eq!(crest_factor(&[]), 0.0);
52        assert_eq!(crest_factor(&[0.0; 32]), 0.0);
53        assert_eq!(crest_factor_db(&[0.0; 32]), f32::NEG_INFINITY);
54    }
55}