Skip to main content

sva_samples/measure/
loudness.rs

1// Concern: measures BS.1770 K-weighted loudness across a node's components | Non-concern: per-component level (envelope.rs), designing a biquad (biquad.rs) | IO: (planes, sample rate) -> Loudness
2
3use crate::biquad::{Coeffs, State};
4
5/// K-weighting as the analog prototypes BS.1770 bilinear-transforms, not the cookbook shapes:
6/// stating them as a design is what makes every rate but 48 kHz right too.
7const SHELF_HZ: f64 = 1681.97;
8const SHELF_Q: f64 = 0.70718;
9const SHELF_GAIN_DB: f64 = 3.99984;
10const SHELF_MID: f64 = 0.499_666_774_154_541_6;
11const HIGHPASS_HZ: f64 = 38.1355;
12const HIGHPASS_Q: f64 = 0.50033;
13
14/// At or under it the shelf stands at or past Nyquist.
15pub const LEAST_RATE_HZ: f64 = 2.0 * SHELF_HZ;
16
17fn shelf(sr: f64) -> Coeffs {
18    let k = (std::f64::consts::PI * SHELF_HZ / sr).tan();
19    let high = 10f64.powf(SHELF_GAIN_DB / 20.0);
20    let mid = high.powf(SHELF_MID);
21    let a0 = 1.0 + k / SHELF_Q + k * k;
22    Coeffs {
23        b0: (high + mid * k / SHELF_Q + k * k) / a0,
24        b1: 2.0 * (k * k - high) / a0,
25        b2: (high - mid * k / SHELF_Q + k * k) / a0,
26        a1: 2.0 * (k * k - 1.0) / a0,
27        a2: (1.0 - k / SHELF_Q + k * k) / a0,
28    }
29}
30
31fn highpass(sr: f64) -> Coeffs {
32    let k = (std::f64::consts::PI * HIGHPASS_HZ / sr).tan();
33    let a0 = 1.0 + k / HIGHPASS_Q + k * k;
34    Coeffs {
35        b0: 1.0,
36        b1: -2.0,
37        b2: 1.0,
38        a1: 2.0 * (k * k - 1.0) / a0,
39        a2: (1.0 - k / HIGHPASS_Q + k * k) / a0,
40    }
41}
42
43const OFFSET_DB: f64 = -0.691;
44const ABSOLUTE_GATE: f64 = -70.0;
45const INTEGRATED_GATE_LU: f64 = -10.0;
46
47const RANGE_GATE_LU: f64 = -20.0;
48
49const MOMENTARY_SECS: f64 = 0.4;
50const SHORT_TERM_SECS: f64 = 3.0;
51
52const STEP_SECS: f64 = 0.1;
53
54const PEAK_NOTE: &str = "sample peak, not true peak: no oversampling exists here, so an inter-sample peak above \
55     this figure is not measured";
56
57#[derive(Clone, Copy, Debug, PartialEq)]
58pub struct LoudnessFrame {
59    /// The block's START, the global seconds every other representation reports.
60    pub t: f64,
61    pub lufs: f64,
62}
63
64#[derive(Clone, Debug, PartialEq)]
65pub struct Loudness {
66    pub integrated_lufs: Option<f64>,
67    pub range_lu: Option<f64>,
68    pub momentary_max_lufs: Option<f64>,
69    pub short_term_max_lufs: Option<f64>,
70    pub sample_peak: f64,
71    pub sample_peak_dbfs: Option<f64>,
72    pub peak_note: &'static str,
73    pub momentary: Vec<LoudnessFrame>,
74    pub short_term: Vec<LoudnessFrame>,
75}
76
77/// A rate with no K-weighting.
78#[derive(Clone, Copy, Debug, PartialEq)]
79pub struct RateUnderWeighting {
80    pub rate_hz: f64,
81    pub least_hz: f64,
82}
83
84/// Every component weighs 1.0: BS.1770's 1.41 surround lift needs a channel identity an
85/// indexed component does not carry.
86pub fn analyze(
87    planes: &[&[f64]],
88    sr: f64,
89    start_secs: f64,
90) -> Result<Loudness, RateUnderWeighting> {
91    if sr <= LEAST_RATE_HZ {
92        return Err(RateUnderWeighting {
93            rate_hz: sr,
94            least_hz: LEAST_RATE_HZ,
95        });
96    }
97    let sample_peak = planes
98        .iter()
99        .flat_map(|p| p.iter())
100        .fold(0.0f64, |acc, v| acc.max(v.abs()));
101    let scale = headroom(sample_peak);
102    let squares = weighted_squares(planes, sr, scale);
103    let at = Blocks {
104        sr,
105        start_secs,
106        lift_db: 20.0 * scale.log10(),
107    };
108
109    let momentary = blocks(&squares, &at, MOMENTARY_SECS);
110    let short_term = blocks(&squares, &at, SHORT_TERM_SECS);
111
112    Ok(Loudness {
113        integrated_lufs: gated_mean(&momentary, INTEGRATED_GATE_LU),
114        range_lu: range(&short_term),
115        momentary_max_lufs: peak_of(&momentary),
116        short_term_max_lufs: peak_of(&short_term),
117        sample_peak,
118        sample_peak_dbfs: (sample_peak > 0.0).then(|| 20.0 * sample_peak.log10()),
119        peak_note: PEAK_NOTE,
120        momentary,
121        short_term,
122    })
123}
124
125/// A power of two at the peak: dividing is exact; only 3000 dB under it does a square underflow.
126fn headroom(peak: f64) -> f64 {
127    match peak > 0.0 && peak.is_finite() {
128        true => {
129            let exponent = peak
130                .log2()
131                .ceil()
132                .clamp(f64::from(f64::MIN_EXP - 1), f64::from(f64::MAX_EXP - 1));
133            2f64.powi(exponent as i32)
134        }
135        false => 1.0,
136    }
137}
138
139fn weighted_squares(planes: &[&[f64]], sr: f64, scale: f64) -> Vec<f64> {
140    let samples = planes.first().map_or(0, |p| p.len());
141    let mut out = vec![0.0; samples];
142    let (shelf, cut) = (shelf(sr), highpass(sr));
143    for plane in planes {
144        let (mut first, mut second) = (State::default(), State::default());
145        for (sum, x) in out.iter_mut().zip(plane.iter()) {
146            let k = second.step(&cut, first.step(&shelf, *x / scale));
147            *sum += k * k;
148        }
149    }
150    out
151}
152
153struct Blocks {
154    sr: f64,
155    start_secs: f64,
156    lift_db: f64,
157}
158
159/// A block sums its own samples, piece by piece between edges, whatever loud stretch precedes it.
160fn blocks(squares: &[f64], at: &Blocks, block_secs: f64) -> Vec<LoudnessFrame> {
161    let n = (block_secs * at.sr).round() as usize;
162    let step = ((STEP_SECS * at.sr).round() as usize).max(1);
163    if n == 0 || squares.len() < n {
164        return Vec::new();
165    }
166    let starts: Vec<usize> = (0..=(squares.len() - n)).step_by(step).collect();
167    let mut edges: Vec<usize> = starts.iter().flat_map(|k| [*k, k + n]).collect();
168    edges.sort_unstable();
169    edges.dedup();
170    let pieces: Vec<f64> = edges
171        .windows(2)
172        .map(|w| squares[w[0]..w[1]].iter().sum())
173        .collect();
174    let piece = |sample: usize| edges.binary_search(&sample).expect("a block edge");
175    starts
176        .iter()
177        .map(|&k| {
178            let power = pieces[piece(k)..piece(k + n)].iter().sum::<f64>() / n as f64;
179            LoudnessFrame {
180                t: at.start_secs + k as f64 / at.sr,
181                lufs: level(power) + at.lift_db,
182            }
183        })
184        .collect()
185}
186
187fn level(power: f64) -> f64 {
188    if power <= 0.0 {
189        return f64::NEG_INFINITY;
190    }
191    OFFSET_DB + 10.0 * power.log10()
192}
193
194/// The mean runs on POWER, not on the levels: averaging decibels is not averaging loudness.
195fn mean_above(frames: &[LoudnessFrame], threshold: f64) -> Option<f64> {
196    let kept: Vec<f64> = frames
197        .iter()
198        .map(|f| f.lufs)
199        .filter(|l| *l > threshold)
200        .collect();
201    if kept.is_empty() {
202        return None;
203    }
204    let from = kept.iter().copied().fold(OFFSET_DB, f64::max);
205    let power: f64 = kept.iter().map(|l| 10f64.powf((l - from) / 10.0)).sum();
206    Some(from + 10.0 * (power / kept.len() as f64).log10())
207}
208
209/// Both relative gates measure down from the ABSOLUTE-gated mean, never from each other.
210fn gated_mean(frames: &[LoudnessFrame], relative_lu: f64) -> Option<f64> {
211    mean_above(frames, mean_above(frames, ABSOLUTE_GATE)? + relative_lu)
212}
213
214/// EBU Tech 3342, whose gate is deliberately not the integrated measure's.
215fn range(short_term: &[LoudnessFrame]) -> Option<f64> {
216    let floor = mean_above(short_term, ABSOLUTE_GATE)? + RANGE_GATE_LU;
217    let mut kept: Vec<f64> = short_term
218        .iter()
219        .map(|f| f.lufs)
220        .filter(|l| *l > ABSOLUTE_GATE && *l > floor)
221        .collect();
222    if kept.is_empty() {
223        return None;
224    }
225    kept.sort_by(f64::total_cmp);
226    Some(percentile(&kept, 0.95) - percentile(&kept, 0.10))
227}
228
229fn percentile(sorted: &[f64], p: f64) -> f64 {
230    let at = ((sorted.len() as f64 - 1.0) * p).round() as usize;
231    sorted[at.min(sorted.len() - 1)]
232}
233
234fn peak_of(frames: &[LoudnessFrame]) -> Option<f64> {
235    frames
236        .iter()
237        .map(|f| f.lufs)
238        .filter(|l| l.is_finite())
239        .reduce(f64::max)
240}