Skip to main content

qualia_audio/features/loudness/
k_weighting.rs

1//! ITU-R BS.1770 / EBU R128 K-weighting pre-filter, as two biquads.
2//!
3//! K-weighting is a cascade of two second-order stages that run through the
4//! shared [`BiquadState`](crate::features::filters::biquad::BiquadState) engine:
5//!
6//! 1. **Stage 1 — high-frequency shelving** (a ~+4 dB high shelf) modelling the
7//!    acoustic effect of the head.
8//! 2. **Stage 2 — RLB high-pass** (a 2nd-order high-pass, ~38 Hz corner)
9//!    removing sub-audible / rumble energy.
10//!
11//! The coefficients are derived analytically via [`etalon_signal::filter`].
12
13use crate::features::filters::biquad::BiquadCoeffs;
14
15/// Build the two BS.1770 K-weighting biquads for `sample_rate` Hz.
16///
17/// Returns `(stage1_high_shelf, stage2_high_pass)`; run a sample through stage 1
18/// then stage 2. `sample_rate` is clamped to `>= 1.0` so coefficients stay
19/// finite for degenerate inputs.
20pub fn k_weighting_coeffs(sample_rate: f32) -> (BiquadCoeffs, BiquadCoeffs) {
21    let fs = if sample_rate > 1.0 {
22        f64::from(sample_rate)
23    } else {
24        1.0
25    };
26    let shelf = BiquadCoeffs::from_etalon(etalon_signal::filter::design_k_weighting_stage1(fs));
27    let hp = BiquadCoeffs::from_etalon(etalon_signal::filter::design_k_weighting_stage2(fs));
28    (shelf, hp)
29}
30
31#[cfg(test)]
32mod tests {
33    use super::*;
34    use crate::features::filters::biquad::BiquadState;
35    use core::f32::consts::PI as PI32;
36
37    #[test]
38    fn matches_bs1770_reference_at_48k() {
39        // Published ITU-R BS.1770 coefficient tables at 48 kHz.
40        let (shelf, hp) = k_weighting_coeffs(48_000.0);
41        assert!(
42            (shelf.b0 - 1.535_124_9).abs() < 1e-3,
43            "shelf.b0 {}",
44            shelf.b0
45        );
46        assert!(
47            (shelf.b1 - (-2.691_696_2)).abs() < 1e-3,
48            "shelf.b1 {}",
49            shelf.b1
50        );
51        assert!(
52            (shelf.b2 - 1.198_392_8).abs() < 1e-3,
53            "shelf.b2 {}",
54            shelf.b2
55        );
56        assert!(
57            (shelf.a1 - (-1.690_659_3)).abs() < 1e-3,
58            "shelf.a1 {}",
59            shelf.a1
60        );
61        assert!(
62            (shelf.a2 - 0.732_480_8).abs() < 1e-3,
63            "shelf.a2 {}",
64            shelf.a2
65        );
66        assert_eq!(hp.b0, 1.0);
67        assert_eq!(hp.b1, -2.0);
68        assert_eq!(hp.b2, 1.0);
69        assert!((hp.a1 - (-1.990_047_5)).abs() < 1e-3, "hp.a1 {}", hp.a1);
70        assert!((hp.a2 - 0.990_072_3).abs() < 1e-3, "hp.a2 {}", hp.a2);
71    }
72
73    /// Combined K-weighting amplitude gain at a frequency (steady-state RMS).
74    fn k_gain(sr: f32, freq: f32) -> f32 {
75        let (shelf, hp) = k_weighting_coeffs(sr);
76        let (n, skip) = (16_384usize, 4_096usize);
77        let mut s1 = BiquadState::new();
78        let mut s2 = BiquadState::new();
79        let (mut ein, mut eout, mut cnt) = (0.0f64, 0.0f64, 0.0f64);
80        for i in 0..n {
81            let x = (2.0 * PI32 * freq * i as f32 / sr).sin();
82            let y = s2.process_sample(&hp, s1.process_sample(&shelf, x));
83            if i >= skip {
84                ein += (x * x) as f64;
85                eout += (y * y) as f64;
86                cnt += 1.0;
87            }
88        }
89        ((eout / cnt).sqrt() / (ein / cnt).sqrt()) as f32
90    }
91
92    #[test]
93    fn one_khz_gain_is_slightly_positive_db() {
94        // The K-curve is ~0 to +1 dB around 1 kHz — the calibration region.
95        let g = k_gain(48_000.0, 1_000.0);
96        let db = 20.0 * g.log10();
97        assert!((-0.5..1.5).contains(&db), "1 kHz K-gain {db} dB");
98    }
99
100    #[test]
101    fn sub_bass_is_attenuated() {
102        // The RLB high-pass kills rumble: 20 Hz should be well below unity.
103        let g = k_gain(48_000.0, 20.0);
104        assert!(g < 0.6, "20 Hz gain {g}");
105    }
106}