Repository Public
1//! ORIX Sonata2//! File: crates/sonata-dsp/src/analysis/meters.rs3//! Description: Level measurement: sample peak, RMS, true peak (4x oversampling) and programme4//! loudness (momentary, short-term, gated integrated) after ITU-R BS.1770-4 / EBU R 128.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89/// Largest absolute sample value.10pub fn sample_peak(x: &[f32]) -> f32 {11 x.iter().fold(0.0f32, |a, b| a.max(b.abs()))12}1314/// Root mean square (0 for an empty slice). Accumulated in f64.15pub fn rms(x: &[f32]) -> f32 {16 if x.is_empty() {17 return 0.0;18 }19 (x.iter().map(|v| (*v as f64) * (*v as f64)).sum::<f64>() / x.len() as f64).sqrt() as f3220}2122/// Mean of the samples (DC offset).23pub fn dc_offset(x: &[f32]) -> f32 {24 if x.is_empty() {25 return 0.0;26 }27 (x.iter().map(|v| *v as f64).sum::<f64>() / x.len() as f64) as f3228}2930pub fn to_db(lin: f32) -> f32 {31 if lin > 1e-10 {32 20.0 * lin.log10()33 } else {34 -200.035 }36}3738const TP_PHASES: usize = 4;39const TP_TAPS: usize = 12;4041/// True-peak meter: the signal is interpolated 4 times with a 48-tap polyphase FIR (12 taps per42/// phase, Kaiser-windowed sinc, pass band to 0.45 fs) and the largest interpolated magnitude is43/// kept, as specified by ITU-R BS.1770-4 Annex 2 (the Recommendation lists one acceptable44/// filter; this one is a different design of the same structure). For rates of 176.4 kHz and45/// above the Recommendation allows plain sample peak; `new` selects that automatically.46/// Expected accuracy: within +0.1/-0.3 dB of the continuous-time peak for content below 0.45 fs.47pub struct TruePeak {48 coef: [[f32; TP_TAPS]; TP_PHASES],49 hist: [f32; TP_TAPS],50 pos: usize,51 peak: f32,52 oversample: bool,53}5455impl TruePeak {56 pub fn new(sample_rate: f32) -> TruePeak {57 let mut coef = [[0.0f32; TP_TAPS]; TP_PHASES];58 let total = TP_PHASES * TP_TAPS;59 let centre = (total - 1) as f64 / 2.0;60 let beta = 8.0;61 let i0 = |x: f64| {62 let (mut s, mut t, mut k) = (1.0, 1.0, 1.0);63 while t > 1e-16 * s {64 t *= (x / (2.0 * k)) * (x / (2.0 * k));65 s += t;66 k += 1.0;67 }68 s69 };70 for (p, phase) in coef.iter_mut().enumerate() {71 for (t, c) in phase.iter_mut().enumerate() {72 // Prototype tap index in the 4x domain; phase p uses taps p, p+4, ...73 let n = (t * TP_PHASES + p) as f64 - centre;74 let x = n / TP_PHASES as f64 * 0.98;75 let sinc = if x.abs() < 1e-12 { 1.0 } else { (std::f64::consts::PI * x).sin() / (std::f64::consts::PI * x) };76 let w = i0(beta * (1.0 - (n / (centre + 0.5)).powi(2)).max(0.0).sqrt()) / i0(beta);77 *c = (0.98 * sinc * w) as f32;78 }79 // Unity DC gain per phase so a constant reads exactly its value.80 let sum: f32 = phase.iter().sum();81 for c in phase.iter_mut() {82 *c /= sum;83 }84 }85 TruePeak { coef, hist: [0.0; TP_TAPS], pos: 0, peak: 0.0, oversample: sample_rate < 176_000.0 }86 }8788 pub fn reset(&mut self) {89 self.hist = [0.0; TP_TAPS];90 self.peak = 0.0;91 }9293 pub fn process(&mut self, x: &[f32]) {94 for &s in x {95 self.peak = self.peak.max(s.abs());96 if !self.oversample {97 continue;98 }99 self.hist[self.pos] = s;100 self.pos = (self.pos + 1) % TP_TAPS;101 for phase in &self.coef {102 let mut acc = 0.0f32;103 for (t, c) in phase.iter().enumerate() {104 // hist[pos] is the oldest sample; the newest pairs with tap 0.105 acc += c * self.hist[(self.pos + TP_TAPS - 1 - t) % TP_TAPS];106 }107 self.peak = self.peak.max(acc.abs());108 }109 }110 }111112 /// Largest true-peak magnitude seen since the last reset (linear).113 pub fn peak(&self) -> f32 {114 self.peak115 }116 pub fn peak_dbtp(&self) -> f32 {117 to_db(self.peak)118 }119}120121/// True peak of a whole buffer, in dBTP.122pub fn true_peak_dbtp(x: &[f32], sample_rate: f32) -> f32 {123 let mut tp = TruePeak::new(sample_rate);124 tp.process(x);125 // Flush the filter so a peak in the last samples is seen.126 tp.process(&[0.0; TP_TAPS]);127 tp.peak_dbtp()128}129130#[derive(Clone, Copy, Default)]131struct Biquad {132 b0: f64,133 b1: f64,134 b2: f64,135 a1: f64,136 a2: f64,137 z1: f64,138 z2: f64,139}140141impl Biquad {142 #[inline]143 fn run(&mut self, x: f64) -> f64 {144 let y = self.b0 * x + self.z1;145 self.z1 = self.b1 * x - self.a1 * y + self.z2;146 self.z2 = self.b2 * x - self.a2 * y;147 y148 }149}150151/// K-weighting: the BS.1770 pre-filter (high shelf, +4 dB) and RLB high-pass, re-derived for152/// any sample rate from their analogue prototypes (at 48 kHz this reproduces the coefficients153/// printed in the Recommendation to better than 1e-9).154fn k_weighting(sample_rate: f64) -> [Biquad; 2] {155 let (f0, g, q) = (1681.974450955533, 3.999843853973347, 0.7071752369554196);156 let k = (std::f64::consts::PI * f0 / sample_rate).tan();157 let vh = 10f64.powf(g / 20.0);158 let vb = vh.powf(0.4996667741545416);159 let a0 = 1.0 + k / q + k * k;160 let shelf = Biquad {161 b0: (vh + vb * k / q + k * k) / a0,162 b1: 2.0 * (k * k - vh) / a0,163 b2: (vh - vb * k / q + k * k) / a0,164 a1: 2.0 * (k * k - 1.0) / a0,165 a2: (1.0 - k / q + k * k) / a0,166 z1: 0.0,167 z2: 0.0,168 };169 let (f0, q) = (38.13547087602444, 0.5003270373238773);170 let k = (std::f64::consts::PI * f0 / sample_rate).tan();171 let a0 = 1.0 + k / q + k * k;172 let hp = Biquad { b0: 1.0, b1: -2.0, b2: 1.0, a1: 2.0 * (k * k - 1.0) / a0, a2: (1.0 - k / q + k * k) / a0, z1: 0.0, z2: 0.0 };173 [shelf, hp]174}175176/// Loudness of silence / of a measurement without any block above the absolute gate.177pub const LUFS_FLOOR: f64 = -200.0;178179/// Stereo (or mono) programme loudness meter, BS.1770-4.180///181/// Channel weights are 1.0 (left, right; a mono signal is measured as a single channel).182/// Gating block: 400 ms, 75 % overlap; absolute gate -70 LUFS; relative gate -10 LU.183/// Momentary = last 400 ms, short-term = last 3 s, both ungated. Not for the audio thread184/// (the block history grows with programme length).185pub struct LoudnessMeter {186 filters: [[Biquad; 2]; 2],187 channels: usize,188 step: usize,189 fill: usize,190 acc: f64,191 /// Summed weighted mean-square of every 100 ms step.192 steps: Vec<f64>,193}194195impl LoudnessMeter {196 /// `channels` is 1 or 2.197 pub fn new(sample_rate: u32, channels: usize) -> LoudnessMeter {198 let k = k_weighting(sample_rate as f64);199 LoudnessMeter { filters: [k, k], channels: channels.clamp(1, 2), step: (sample_rate as usize / 10).max(1), fill: 0, acc: 0.0, steps: Vec::new() }200 }201202 pub fn reset(&mut self) {203 for ch in &mut self.filters {204 for f in ch.iter_mut() {205 f.z1 = 0.0;206 f.z2 = 0.0;207 }208 }209 self.fill = 0;210 self.acc = 0.0;211 self.steps.clear();212 }213214 /// Feeds frames. For a mono meter only `left` is read.215 pub fn process(&mut self, left: &[f32], right: &[f32]) {216 for i in 0..left.len() {217 let s1 = self.filters[0][0].run(left[i] as f64);218 let l = self.filters[0][1].run(s1);219 self.acc += l * l;220 if self.channels == 2 {221 let s1 = self.filters[1][0].run(right.get(i).copied().unwrap_or(0.0) as f64);222 let r = self.filters[1][1].run(s1);223 self.acc += r * r;224 }225 self.fill += 1;226 if self.fill == self.step {227 self.steps.push(self.acc / self.step as f64);228 self.fill = 0;229 self.acc = 0.0;230 }231 }232 }233234 fn loudness(mean_square: f64) -> f64 {235 if mean_square > 1e-20 {236 -0.691 + 10.0 * mean_square.log10()237 } else {238 LUFS_FLOOR239 }240 }241242 fn window(&self, steps: usize) -> f64 {243 if self.steps.len() < steps {244 return LUFS_FLOOR;245 }246 Self::loudness(self.steps[self.steps.len() - steps..].iter().sum::<f64>() / steps as f64)247 }248249 /// Loudness of the last 400 ms, LUFS ([`LUFS_FLOOR`] until 400 ms were fed).250 pub fn momentary(&self) -> f64 {251 self.window(4)252 }253 /// Loudness of the last 3 s, LUFS.254 pub fn short_term(&self) -> f64 {255 self.window(30)256 }257258 /// Gated programme loudness, LUFS.259 pub fn integrated(&self) -> f64 {260 if self.steps.len() < 4 {261 return LUFS_FLOOR;262 }263 let blocks: Vec<f64> = self.steps.windows(4).map(|w| w.iter().sum::<f64>() / 4.0).collect();264 let abs: Vec<f64> = blocks.iter().copied().filter(|b| Self::loudness(*b) > -70.0).collect();265 if abs.is_empty() {266 return LUFS_FLOOR;267 }268 let rel_gate = Self::loudness(abs.iter().sum::<f64>() / abs.len() as f64) - 10.0;269 let rel: Vec<f64> = abs.iter().copied().filter(|b| Self::loudness(*b) > rel_gate).collect();270 if rel.is_empty() {271 return LUFS_FLOOR;272 }273 Self::loudness(rel.iter().sum::<f64>() / rel.len() as f64)274 }275}276277/// Integrated loudness of a whole stereo buffer, LUFS.278pub fn integrated_lufs(left: &[f32], right: &[f32], sample_rate: u32) -> f64 {279 let mut m = LoudnessMeter::new(sample_rate, 2);280 m.process(left, right);281 m.integrated()282}283284#[cfg(test)]285mod tests {286 use super::*;287288 fn sine(freq: f64, db: f64, sr: u32, secs: f64, phase: f64) -> Vec<f32> {289 let a = 10f64.powf(db / 20.0);290 (0..(secs * sr as f64) as usize).map(|i| (a * (2.0 * std::f64::consts::PI * freq * i as f64 / sr as f64 + phase).sin()) as f32).collect()291 }292293 #[test]294 fn basic_levels() {295 let x = sine(1000.0, -6.0, 48_000, 1.0, 0.0);296 assert!((to_db(sample_peak(&x)) + 6.0).abs() < 0.01);297 assert!((to_db(rms(&x)) + 9.0103).abs() < 0.01);298 assert!(dc_offset(&x).abs() < 1e-6);299 assert_eq!(rms(&[]), 0.0);300 assert_eq!(to_db(0.0), -200.0);301 }302303 #[test]304 fn k_weighting_matches_the_published_48k_coefficients() {305 let [s, h] = k_weighting(48_000.0);306 for (got, want) in [307 (s.b0, 1.53512485958697),308 (s.b1, -2.69169618940638),309 (s.b2, 1.19839281085285),310 (s.a1, -1.69065929318241),311 (s.a2, 0.73248077421585),312 (h.a1, -1.99004745483398),313 (h.a2, 0.99007225036621),314 ] {315 assert!((got - want).abs() < 1e-9, "{got} vs {want}");316 }317 }318319 /// EBU Tech 3341 style checks, synthesised: tolerance +/-0.1 LU as in the EBU specification.320 #[test]321 fn loudness_of_reference_signals() {322 for sr in [44_100u32, 48_000, 96_000] {323 // Stereo 1 kHz sine, -23 dBFS per channel, 20 s -> -23.0 LUFS (M, S and I).324 let x = sine(1000.0, -23.0, sr, 20.0, 0.0);325 let mut m = LoudnessMeter::new(sr, 2);326 m.process(&x, &x);327 for (name, v) in [("I", m.integrated()), ("M", m.momentary()), ("S", m.short_term())] {328 assert!((v + 23.0).abs() < 0.1, "{sr} Hz {name}: {v}");329 }330 // -33 dBFS -> -33.0 LUFS; mono channel alone reads 3.01 LU lower.331 let y = sine(1000.0, -33.0, sr, 20.0, 0.0);332 assert!((integrated_lufs(&y, &y, sr) + 33.0).abs() < 0.1);333 let mut mono = LoudnessMeter::new(sr, 1);334 mono.process(&x, &[]);335 assert!((mono.integrated() + 26.01).abs() < 0.1, "{}", mono.integrated());336 }337 }338339 #[test]340 fn gating_ignores_silence_and_quiet_passages() {341 let sr = 48_000;342 // 10 s at -36, 60 s at -23, 10 s at -36: the relative gate (-10 LU) removes the -36 parts.343 let mut x = sine(1000.0, -36.0, sr, 10.0, 0.0);344 x.extend(sine(1000.0, -23.0, sr, 60.0, 0.0));345 x.extend(sine(1000.0, -36.0, sr, 10.0, 0.0));346 let v = integrated_lufs(&x, &x, sr);347 assert!((v + 23.0).abs() < 0.1, "{v}");348 // Silence around a tone is removed by the absolute gate.349 let mut y = vec![0.0f32; sr as usize * 5];350 y.extend(sine(1000.0, -23.0, sr, 10.0, 0.0));351 y.extend(vec![0.0f32; sr as usize * 5]);352 // The six gating blocks that straddle the edges are partly silent yet above the relative gate353 // (as the Recommendation prescribes), which lowers the result by about 0.13 LU here.354 let v = integrated_lufs(&y, &y, sr);355 assert!(v < -23.0 && v > -23.25, "{v}");356 assert_eq!(integrated_lufs(&[0.0; 48_000], &[0.0; 48_000], sr), LUFS_FLOOR);357 let mut m = LoudnessMeter::new(sr, 2);358 m.process(&y[..1000], &y[..1000]);359 assert_eq!(m.momentary(), LUFS_FLOOR);360 }361362 #[test]363 fn k_weighting_frequency_response_is_plausible() {364 // +4 dB shelf at high frequencies, strong attenuation at 20 Hz relative to 1 kHz.365 let sr = 48_000;366 let level = |f: f64| {367 let x = sine(f, -20.0, sr, 10.0, 0.0);368 integrated_lufs(&x, &x, sr)369 };370 let ref1k = level(1000.0);371 assert!((level(10_000.0) - ref1k - 3.3).abs() < 0.3, "{}", level(10_000.0) - ref1k);372 assert!((level(100.0) - ref1k + 1.8).abs() < 0.4, "{}", level(100.0) - ref1k);373 assert!(level(25.0) - ref1k < -8.0);374 }375376 #[test]377 fn true_peak_finds_inter_sample_peaks() {378 // fs/4 sine with a 45 degree phase offset: samples reach only 0.7071 of the true peak.379 let sr = 48_000;380 // Signals are faded in and out over 10 ms: an abrupt start is a real discontinuity whose381 // band-limited reconstruction overshoots, which a true-peak meter rightly reports.382 let fade = |mut x: Vec<f32>| {383 let n = x.len();384 for i in 0..480 {385 x[i] *= i as f32 / 480.0;386 x[n - 1 - i] *= i as f32 / 480.0;387 }388 x389 };390 let x = fade(sine(12_000.0, 0.0, sr, 0.1, std::f64::consts::FRAC_PI_4));391 assert!((to_db(sample_peak(&x)) + 3.01).abs() < 0.01);392 let tp = true_peak_dbtp(&x, sr as f32);393 assert!(tp > -0.3 && tp < 0.1, "true peak {tp} dBTP, expected 0");394 // A low-frequency sine: true peak equals sample peak within 0.05 dB.395 let y = fade(sine(997.0, -1.0, sr, 0.1, 0.3));396 assert!((true_peak_dbtp(&y, sr as f32) + 1.0).abs() < 0.05);397 // A rectangular burst overshoots when reconstructed (Gibbs, about +0.8 dB): reported, not hidden.398 let burst = true_peak_dbtp(&[0.5; 100], sr as f32);399 assert!(burst > -6.0 && burst < -4.8, "{burst}");400 // At 192 kHz the meter is a sample-peak meter.401 assert!((true_peak_dbtp(&sine(48_000.0, 0.0, 192_000, 0.01, std::f64::consts::FRAC_PI_4), 192_000.0) + 3.01).abs() < 0.01);402 }403}404