qualia_audio/features/loudness/
r128.rs1use crate::features::filters::biquad::BiquadState;
6use crate::features::loudness::k_weighting::k_weighting_coeffs;
7use crate::types::AudioError;
8
9const OFFSET: f64 = -0.691;
11const ABS_GATE_LUFS: f64 = -70.0;
13const REL_GATE_LU: f64 = 10.0;
15
16#[inline]
18fn loudness_from_z(z: f64) -> f64 {
19 etalon_signal::loudness::energy_to_lufs(z)
20}
21
22fn for_each_gating_block<F>(
23 samples: &[f32],
24 sample_rate: u32,
25 mut on_block: F,
26) -> Result<usize, AudioError>
27where
28 F: FnMut(f64),
29{
30 if sample_rate == 0 {
31 return Err(AudioError::InvalidParameter);
32 }
33 let sub_len = (sample_rate as usize) / 10; if sub_len == 0 {
35 return Err(AudioError::InvalidParameter);
36 }
37 let block_len = (sub_len * 4) as f64; let (shelf, hp) = k_weighting_coeffs(sample_rate as f32);
40 let mut s1 = BiquadState::new();
41 let mut s2 = BiquadState::new();
42
43 let mut ring = [0.0f64; 4];
44 let mut ring_pos = 0usize;
45 let mut ring_filled = 0usize;
46 let mut sub_acc = 0.0f64;
47 let mut sub_count = 0usize;
48 let mut n_blocks = 0usize;
49
50 for &x in samples {
51 let y = s2.process_sample(&hp, s1.process_sample(&shelf, x)) as f64;
52 sub_acc += y * y;
53 sub_count += 1;
54 if sub_count == sub_len {
55 ring[ring_pos] = sub_acc;
56 ring_pos = (ring_pos + 1) & 3;
57 if ring_filled < 4 {
58 ring_filled += 1;
59 }
60 if ring_filled == 4 {
61 let block_ss = ring[0] + ring[1] + ring[2] + ring[3];
62 on_block(block_ss / block_len);
63 n_blocks += 1;
64 }
65 sub_acc = 0.0;
66 sub_count = 0;
67 }
68 }
69 Ok(n_blocks)
70}
71
72pub fn integrated_lufs(samples: &[f32], sample_rate: u32) -> Result<f32, AudioError> {
74 let abs_thresh_z = 10f64.powf((ABS_GATE_LUFS - OFFSET) / 10.0);
75
76 let mut sum_abs = 0.0f64;
77 let mut n_abs = 0usize;
78 let n_blocks = for_each_gating_block(samples, sample_rate, |z| {
79 if z >= abs_thresh_z {
80 sum_abs += z;
81 n_abs += 1;
82 }
83 })?;
84
85 if n_blocks == 0 {
86 return Err(AudioError::MalformedAudio);
87 }
88 if n_abs == 0 {
89 return Ok(f32::NEG_INFINITY);
90 }
91
92 let rel_thresh_z = (sum_abs / n_abs as f64) / 10f64.powf(REL_GATE_LU / 10.0);
93
94 let mut sum_rel = 0.0f64;
95 let mut n_rel = 0usize;
96 for_each_gating_block(samples, sample_rate, |z| {
97 if z >= abs_thresh_z && z >= rel_thresh_z {
98 sum_rel += z;
99 n_rel += 1;
100 }
101 })?;
102
103 if n_rel == 0 {
104 return Ok(f32::NEG_INFINITY);
105 }
106 Ok(loudness_from_z(sum_rel / n_rel as f64) as f32)
107}
108
109fn window_lufs(samples: &[f32], sample_rate: u32) -> Result<f32, AudioError> {
110 if samples.is_empty() {
111 return Err(AudioError::MalformedAudio);
112 }
113 if sample_rate == 0 {
114 return Err(AudioError::InvalidParameter);
115 }
116 let (shelf, hp) = k_weighting_coeffs(sample_rate as f32);
117 let mut s1 = BiquadState::new();
118 let mut s2 = BiquadState::new();
119 let mut acc = 0.0f64;
120 for &x in samples {
121 let y = s2.process_sample(&hp, s1.process_sample(&shelf, x)) as f64;
122 acc += y * y;
123 }
124 let z = acc / samples.len() as f64;
125 if z <= 0.0 {
126 return Ok(f32::NEG_INFINITY);
127 }
128 Ok(loudness_from_z(z) as f32)
129}
130
131pub fn momentary_lufs(samples: &[f32], sample_rate: u32) -> Result<f32, AudioError> {
133 window_lufs(samples, sample_rate)
134}
135
136pub fn short_term_lufs(samples: &[f32], sample_rate: u32) -> Result<f32, AudioError> {
138 window_lufs(samples, sample_rate)
139}
140
141#[cfg(test)]
142mod tests {
143 use super::*;
144 use core::f32::consts::PI;
145
146 fn sine_at_rms(rms: f32, n: usize) -> Vec<f32> {
147 let amp = rms * core::f32::consts::SQRT_2;
148 (0..n)
149 .map(|i| amp * (2.0 * PI * 1_000.0 * i as f32 / 48_000.0).sin())
150 .collect()
151 }
152
153 #[test]
154 fn integrated_minus_20_dbfs_sine_is_near_minus_20_lufs() {
155 let s = sine_at_rms(0.1, 48_000 * 3);
156 let l = integrated_lufs(&s, 48_000).expect("integrated");
157 assert!(
158 (l - (-20.0)).abs() < 1.0,
159 "integrated {l} LUFS, expected ~ -20"
160 );
161 }
162
163 #[test]
164 fn momentary_matches_calibration() {
165 let s = sine_at_rms(0.1, 48_000 / 2);
166 let m = momentary_lufs(&s, 48_000).expect("momentary");
167 assert!((m - (-20.0)).abs() < 1.0, "momentary {m}");
168 }
169
170 #[test]
171 fn level_change_moves_loudness_by_same_db() {
172 let a = integrated_lufs(&sine_at_rms(0.1, 48_000 * 2), 48_000).unwrap();
173 let b = integrated_lufs(&sine_at_rms(0.05, 48_000 * 2), 48_000).unwrap();
174 assert!(((a - b) - 6.02).abs() < 0.2, "delta {} LU", a - b);
175 }
176
177 #[test]
178 fn too_short_is_malformed() {
179 let s = sine_at_rms(0.1, 100);
180 assert_eq!(integrated_lufs(&s, 48_000), Err(AudioError::MalformedAudio));
181 }
182
183 #[test]
184 fn silence_is_neg_infinity() {
185 let s = vec![0.0f32; 48_000];
186 assert_eq!(integrated_lufs(&s, 48_000), Ok(f32::NEG_INFINITY));
187 }
188
189 #[test]
190 fn zero_sample_rate_rejected() {
191 let s = sine_at_rms(0.1, 48_000);
192 assert_eq!(integrated_lufs(&s, 0), Err(AudioError::InvalidParameter));
193 }
194}