Skip to main content

qualia_audio/features/loudness/
lra.rs

1//! Loudness Range (LRA) per EBU Tech 3342.
2//!
3//! LRA is the spread between the 10th and 95th percentiles of the *gated*
4//! short-term loudness distribution. The caller supplies the short-term
5//! loudness values (LUFS, e.g. from a 3 s sliding
6//! [`short_term_lufs`](crate::features::loudness::r128::short_term_lufs)) plus a
7//! scratch buffer; this function gates them (absolute −70 LUFS, then relative
8//! −20 LU below the power-mean) and reports `P95 − P10` in LU.
9//!
10//! **Zero-heap.** Gated values are copied into the caller-owned `scratch` slice
11//! and sorted in place there — no allocation, and the input is left untouched.
12
13use crate::types::AudioError;
14
15const OFFSET: f64 = -0.691;
16const ABS_GATE_LUFS: f64 = -70.0;
17/// EBU 3342 relative gate for LRA is −20 LU (distinct from R128's −10 LU).
18const REL_GATE_LU: f64 = 20.0;
19const LOW_PERCENTILE: f64 = 0.10;
20const HIGH_PERCENTILE: f64 = 0.95;
21
22#[inline]
23fn lufs_to_z(l: f64) -> f64 {
24    10f64.powf((l - OFFSET) / 10.0)
25}
26
27/// Loudness Range (LU) of a short-term loudness series.
28///
29/// `short_term_lufs` are LUFS values; `scratch` must be at least as long
30/// (holds the gated subset for percentile ranking; contents on return are
31/// unspecified). Returns:
32/// - `Err(OutputBufferTooSmall)` if `scratch` is shorter than the input,
33/// - `Ok(0.0)` if fewer than two values survive gating (range undefined/degenerate),
34/// - otherwise `P95 − P10` of the gated distribution.
35pub fn loudness_range(short_term_lufs: &[f32], scratch: &mut [f32]) -> Result<f32, AudioError> {
36    if scratch.len() < short_term_lufs.len() {
37        return Err(AudioError::OutputBufferTooSmall);
38    }
39
40    // Absolute gate (−70 LUFS): copy survivors into scratch, accumulate energy.
41    let abs_thresh = ABS_GATE_LUFS as f32;
42    let mut n = 0usize;
43    let mut sum_z = 0.0f64;
44    for &l in short_term_lufs {
45        if l.is_finite() && l >= abs_thresh {
46            scratch[n] = l;
47            n += 1;
48            sum_z += lufs_to_z(l as f64);
49        }
50    }
51    if n < 2 {
52        return Ok(0.0);
53    }
54
55    // Relative gate: −20 LU below the power-mean loudness of the abs-gated set.
56    let mean_loudness = OFFSET + 10.0 * (sum_z / n as f64).log10();
57    let rel_thresh = (mean_loudness - REL_GATE_LU) as f32;
58    let mut m = 0usize;
59    for i in 0..n {
60        if scratch[i] >= rel_thresh {
61            scratch[m] = scratch[i];
62            m += 1;
63        }
64    }
65    if m < 2 {
66        return Ok(0.0);
67    }
68
69    let gated = &mut scratch[..m];
70    gated.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap_or(core::cmp::Ordering::Equal));
71
72    let lo = percentile_sorted(gated, LOW_PERCENTILE);
73    let hi = percentile_sorted(gated, HIGH_PERCENTILE);
74    Ok(hi - lo)
75}
76
77/// Nearest-rank percentile of an ascending-sorted slice.
78///
79/// `index = round(p * (n - 1))`, clamped to bounds. `sorted` must be non-empty.
80fn percentile_sorted(sorted: &[f32], p: f64) -> f32 {
81    let n = sorted.len();
82    let idx = (p * (n - 1) as f64).round() as usize;
83    sorted[idx.min(n - 1)]
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89
90    #[test]
91    fn range_of_ungated_ramp() {
92        // 11 short-term values −10..0 LUFS, all within 20 LU of the mean so the
93        // relative gate keeps all. Sorted: [−10..0].
94        // P10: round(0.10*10)=1 → −9 ; P95: round(0.95*10)=10 → 0 ; LRA = 9.
95        let st: Vec<f32> = (0..=10).map(|i| -10.0 + i as f32).collect();
96        let mut scratch = vec![0.0f32; st.len()];
97        let lra = loudness_range(&st, &mut scratch).expect("lra");
98        assert!((lra - 9.0).abs() < 1e-4, "lra {lra}");
99    }
100
101    #[test]
102    fn flat_signal_has_zero_range() {
103        let st = [-18.0f32; 50];
104        let mut scratch = [0.0f32; 50];
105        let lra = loudness_range(&st, &mut scratch).expect("lra");
106        assert!(lra.abs() < 1e-4, "lra {lra}");
107    }
108
109    #[test]
110    fn silence_below_abs_gate_is_zero() {
111        let st = [-80.0f32; 20]; // all below −70 LUFS absolute gate
112        let mut scratch = [0.0f32; 20];
113        assert_eq!(loudness_range(&st, &mut scratch), Ok(0.0));
114    }
115
116    #[test]
117    fn small_scratch_errors() {
118        let st = [-10.0f32; 8];
119        let mut scratch = [0.0f32; 4];
120        assert_eq!(
121            loudness_range(&st, &mut scratch),
122            Err(AudioError::OutputBufferTooSmall)
123        );
124    }
125
126    #[test]
127    fn input_is_not_mutated() {
128        let st: Vec<f32> = (0..=10).map(|i| -10.0 + i as f32).collect();
129        let orig = st.clone();
130        let mut scratch = vec![0.0f32; st.len()];
131        let _ = loudness_range(&st, &mut scratch);
132        assert_eq!(st, orig);
133    }
134}