FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
M7.1: BS.1770 loudness meter
Brandon Thomas627c230871e8
diff --git a/Cargo.lock b/Cargo.lockindex d98205d18..a82de87f5 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1308,6 +1308,10 @@ dependencies = ["thiserror 2.0.21",]+[[package]]+name = "filmcraft-audio-dsp"+version = "0.1.0"+[[package]]name = "filmcraft-automation"version = "0.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex 66e046590..d42c4afcb 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -21,6 +21,7 @@ filmcraft-h264 = { path = "crates/h264" }filmcraft-prores = { path = "crates/prores" }filmcraft-aac = { path = "crates/aac" }filmcraft-h264enc = { path = "crates/h264enc" }+filmcraft-audio-dsp = { path = "crates/audio-dsp" }filmcraft-frame = { path = "crates/frame" }filmcraft-media = { path = "crates/media" }filmcraft-codecs = { path = "crates/codecs" }diff --git a/crates/audio-dsp/Cargo.toml b/crates/audio-dsp/Cargo.tomlnew file mode 100644index 000000000..bc1a0483b--- /dev/null+++ b/crates/audio-dsp/Cargo.toml@@ -0,0 +1,13 @@+[package]+name = "filmcraft-audio-dsp"+description = "Real-time audio DSP for FilmCraft: BS.1770 / EBU R128 loudness metering and audio effects"+version.workspace = true+edition.workspace = true+license.workspace = true+rust-version.workspace = true++[lints]+workspace = true++# Intentionally dependency-free (layer L1): planar `&mut [f32]` slices in, planar slices out.+[dependencies]diff --git a/crates/audio-dsp/src/biquad.rs b/crates/audio-dsp/src/biquad.rsnew file mode 100644index 000000000..b213d7b9f--- /dev/null+++ b/crates/audio-dsp/src/biquad.rs@@ -0,0 +1,219 @@+//! Second-order IIR sections: RBJ "Audio EQ Cookbook" designs, transposed direct form II.++use crate::flush;+use std::f64::consts::PI;++/// Filter shape.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum FilterType {+ Peaking,+ LowShelf,+ HighShelf,+ LowPass,+ HighPass,+ Notch,+ BandPass,+ AllPass,+}++impl FilterType {+ /// Order used by the parametric EQ's `type` choice parameter.+ pub const ALL: [FilterType; 7] =+ [FilterType::Peaking, FilterType::LowShelf, FilterType::HighShelf, FilterType::LowPass, FilterType::HighPass, FilterType::Notch, FilterType::BandPass];+ pub fn from_index(i: usize) -> FilterType {+ Self::ALL[i.min(Self::ALL.len() - 1)]+ }+}++/// Normalised biquad coefficients (`a0 == 1`).+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Coeffs {+ pub b0: f64,+ pub b1: f64,+ pub b2: f64,+ pub a1: f64,+ pub a2: f64,+}++impl Coeffs {+ /// Pass-through.+ pub const IDENTITY: Coeffs = Coeffs { b0: 1.0, b1: 0.0, b2: 0.0, a1: 0.0, a2: 0.0 };++ fn norm(b0: f64, b1: f64, b2: f64, a0: f64, a1: f64, a2: f64) -> Coeffs {+ Coeffs { b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, a1: a1 / a0, a2: a2 / a0 }+ }++ /// RBJ cookbook design. `freq` in Hz (clamped below Nyquist), `q` > 0, `gain_db` used by+ /// peaking and shelving types (shelves use `q` as the shelf "Q", S=1 ≙ Q=1/√2).+ pub fn design(kind: FilterType, sample_rate: f64, freq: f64, q: f64, gain_db: f64) -> Coeffs {+ let f = freq.clamp(1.0, sample_rate * 0.49);+ let q = q.max(1e-3);+ let w0 = 2.0 * PI * f / sample_rate;+ let (sn, cs) = w0.sin_cos();+ let alpha = sn / (2.0 * q);+ let a = 10f64.powf(gain_db / 40.0);+ match kind {+ FilterType::LowPass => Self::norm((1.0 - cs) / 2.0, 1.0 - cs, (1.0 - cs) / 2.0, 1.0 + alpha, -2.0 * cs, 1.0 - alpha),+ FilterType::HighPass => Self::norm((1.0 + cs) / 2.0, -(1.0 + cs), (1.0 + cs) / 2.0, 1.0 + alpha, -2.0 * cs, 1.0 - alpha),+ FilterType::BandPass => Self::norm(alpha, 0.0, -alpha, 1.0 + alpha, -2.0 * cs, 1.0 - alpha),+ FilterType::Notch => Self::norm(1.0, -2.0 * cs, 1.0, 1.0 + alpha, -2.0 * cs, 1.0 - alpha),+ FilterType::AllPass => Self::norm(1.0 - alpha, -2.0 * cs, 1.0 + alpha, 1.0 + alpha, -2.0 * cs, 1.0 - alpha),+ FilterType::Peaking => Self::norm(1.0 + alpha * a, -2.0 * cs, 1.0 - alpha * a, 1.0 + alpha / a, -2.0 * cs, 1.0 - alpha / a),+ FilterType::LowShelf => {+ let k = 2.0 * a.sqrt() * alpha;+ Self::norm(+ a * ((a + 1.0) - (a - 1.0) * cs + k),+ 2.0 * a * ((a - 1.0) - (a + 1.0) * cs),+ a * ((a + 1.0) - (a - 1.0) * cs - k),+ (a + 1.0) + (a - 1.0) * cs + k,+ -2.0 * ((a - 1.0) + (a + 1.0) * cs),+ (a + 1.0) + (a - 1.0) * cs - k,+ )+ }+ FilterType::HighShelf => {+ let k = 2.0 * a.sqrt() * alpha;+ Self::norm(+ a * ((a + 1.0) + (a - 1.0) * cs + k),+ -2.0 * a * ((a - 1.0) + (a + 1.0) * cs),+ a * ((a + 1.0) + (a - 1.0) * cs - k),+ (a + 1.0) - (a - 1.0) * cs + k,+ 2.0 * ((a - 1.0) - (a + 1.0) * cs),+ (a + 1.0) - (a - 1.0) * cs - k,+ )+ }+ }+ }++ /// |H(e^{jω})| at `freq` Hz.+ pub fn magnitude(&self, freq: f64, sample_rate: f64) -> f64 {+ let w = 2.0 * PI * freq / sample_rate;+ let (s1, c1) = w.sin_cos();+ let (s2, c2) = (2.0 * w).sin_cos();+ // H = (b0 + b1 z^-1 + b2 z^-2) / (1 + a1 z^-1 + a2 z^-2), z^-1 = e^{-jω}.+ let nr = self.b0 + self.b1 * c1 + self.b2 * c2;+ let ni = -(self.b1 * s1 + self.b2 * s2);+ let dr = 1.0 + self.a1 * c1 + self.a2 * c2;+ let di = -(self.a1 * s1 + self.a2 * s2);+ ((nr * nr + ni * ni) / (dr * dr + di * di)).sqrt()+ }++ /// Magnitude in dB.+ pub fn magnitude_db(&self, freq: f64, sample_rate: f64) -> f64 {+ 20.0 * self.magnitude(freq, sample_rate).log10()+ }+}++/// One biquad section's state (TDF-II), f64 internally.+#[derive(Clone, Copy, Debug, Default)]+pub struct Biquad {+ s1: f64,+ s2: f64,+}++impl Biquad {+ pub const fn new() -> Self {+ Biquad { s1: 0.0, s2: 0.0 }+ }+ #[inline(always)]+ pub fn tick(&mut self, c: &Coeffs, x: f64) -> f64 {+ let y = c.b0 * x + self.s1;+ self.s1 = flush(c.b1 * x - c.a1 * y + self.s2);+ self.s2 = flush(c.b2 * x - c.a2 * y);+ y+ }+ pub fn reset(&mut self) {+ *self = Biquad::new();+ }+ /// Filter a buffer in place.+ pub fn process(&mut self, c: &Coeffs, buf: &mut [f32]) {+ for v in buf {+ *v = self.tick(c, *v as f64) as f32;+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::testutil::*;++ const SR: f64 = 48000.0;++ fn measured_db(c: &Coeffs, freq: f64) -> f64 {+ let n = SR as usize;+ let mut x = sine(freq, 0.5, SR, n, 0.0);+ let mut bq = Biquad::new();+ bq.process(c, &mut x);+ // Skip the transient; measure over an integer number of periods-ish long tail.+ let tail = &x[n / 2..];+ db(tone_amplitude(tail, freq, SR) / 0.5)+ }++ #[test]+ fn peaking_hits_gain_at_centre() {+ let c = Coeffs::design(FilterType::Peaking, SR, 1000.0, 1.0, 6.0);+ assert!((c.magnitude_db(1000.0, SR) - 6.0).abs() < 1e-9);+ assert!(c.magnitude_db(20.0, SR).abs() < 0.05);+ assert!((measured_db(&c, 1000.0) - 6.0).abs() < 0.05);+ }++ #[test]+ fn lowpass_highpass_minus_3db_at_cutoff() {+ let q = std::f64::consts::FRAC_1_SQRT_2;+ let lp = Coeffs::design(FilterType::LowPass, SR, 2000.0, q, 0.0);+ let hp = Coeffs::design(FilterType::HighPass, SR, 2000.0, q, 0.0);+ assert!((lp.magnitude_db(2000.0, SR) + 3.0103).abs() < 0.01);+ assert!((hp.magnitude_db(2000.0, SR) + 3.0103).abs() < 0.01);+ assert!(lp.magnitude_db(100.0, SR).abs() < 0.01);+ assert!(hp.magnitude_db(15000.0, SR).abs() < 0.1);+ // 12 dB/oct slope well past cutoff.+ assert!(lp.magnitude_db(8000.0, SR) < -22.0);+ assert!((measured_db(&lp, 2000.0) + 3.0103).abs() < 0.05);+ assert!((measured_db(&hp, 500.0) - hp.magnitude_db(500.0, SR)).abs() < 0.05);+ }++ #[test]+ fn notch_is_deep_at_centre() {+ let c = Coeffs::design(FilterType::Notch, SR, 60.0, 10.0, 0.0);+ assert!(c.magnitude(60.0, SR) < 1e-6);+ assert!(c.magnitude_db(1000.0, SR).abs() < 0.01);+ assert!(measured_db(&c, 60.0) < -40.0);+ }++ #[test]+ fn shelves_reach_their_gain() {+ let q = std::f64::consts::FRAC_1_SQRT_2;+ let ls = Coeffs::design(FilterType::LowShelf, SR, 200.0, q, 9.0);+ let hs = Coeffs::design(FilterType::HighShelf, SR, 5000.0, q, -9.0);+ assert!((ls.magnitude_db(10.0, SR) - 9.0).abs() < 0.05);+ assert!((ls.magnitude_db(200.0, SR) - 4.5).abs() < 0.01);+ assert!(ls.magnitude_db(10000.0, SR).abs() < 0.05);+ assert!((hs.magnitude_db(23000.0, SR) + 9.0).abs() < 0.1);+ assert!((hs.magnitude_db(5000.0, SR) + 4.5).abs() < 0.01);+ assert!((measured_db(&ls, 40.0) - ls.magnitude_db(40.0, SR)).abs() < 0.05);+ assert!((measured_db(&hs, 12000.0) - hs.magnitude_db(12000.0, SR)).abs() < 0.05);+ }++ #[test]+ fn bandpass_and_allpass() {+ let bp = Coeffs::design(FilterType::BandPass, SR, 1000.0, 2.0, 0.0);+ assert!(bp.magnitude_db(1000.0, SR).abs() < 1e-9);+ let ap = Coeffs::design(FilterType::AllPass, SR, 1000.0, 2.0, 0.0);+ for f in [50.0, 1000.0, 9000.0] {+ assert!(ap.magnitude_db(f, SR).abs() < 1e-9);+ }+ }++ #[test]+ fn state_flushes_to_zero_no_denormals() {+ let c = Coeffs::design(FilterType::LowPass, SR, 100.0, 0.7, 0.0);+ let mut bq = Biquad::new();+ bq.tick(&c, 1.0);+ let mut last = 1.0;+ for _ in 0..2_000_000 {+ last = bq.tick(&c, 0.0);+ assert!(!(last as f32).is_subnormal());+ }+ assert_eq!(last, 0.0);+ }+}diff --git a/crates/audio-dsp/src/effects/mod.rs b/crates/audio-dsp/src/effects/mod.rsnew file mode 100644index 000000000..8a1ebf0bc--- /dev/null+++ b/crates/audio-dsp/src/effects/mod.rs@@ -0,0 +1,53 @@+//! Audio effects and their registry.++use crate::{AudioEffect, ParamSpec};++/// Effect category (for menus / the Effects panel's Audio Effects bin).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum Category {+ Filter,+ Dynamics,+ Time,+ Channel,+ Restoration,+ Pitch,+}++/// Registry entry describing one effect type.+#[derive(Clone, Copy)]+pub struct EffectInfo {+ pub id: &'static str,+ pub name: &'static str,+ pub category: Category,+ pub params: &'static [ParamSpec],+ /// Construct an instance for `(sample_rate, channels)`.+ pub create: fn(f32, usize) -> Box<dyn AudioEffect>,+}++impl std::fmt::Debug for EffectInfo {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("EffectInfo")+ .field("id", &self.id)+ .field("name", &self.name)+ .field("category", &self.category)+ .field("params", &self.params.len())+ .finish()+ }+}++static REGISTRY: &[EffectInfo] = &[];++/// All registered effects.+pub fn effects() -> &'static [EffectInfo] {+ REGISTRY+}++/// Look up an effect by id.+pub fn effect_info(id: &str) -> Option<&'static EffectInfo> {+ REGISTRY.iter().find(|e| e.id == id)+}++/// Instantiate an effect by id.+pub fn create_effect(id: &str, sample_rate: f32, channels: usize) -> Option<Box<dyn AudioEffect>> {+ effect_info(id).map(|e| (e.create)(sample_rate, channels))+}diff --git a/crates/audio-dsp/src/fft.rs b/crates/audio-dsp/src/fft.rsnew file mode 100644index 000000000..5f7510b6f--- /dev/null+++ b/crates/audio-dsp/src/fft.rs@@ -0,0 +1,115 @@+//! Minimal in-place radix-2 complex FFT (power-of-two sizes), allocation-free after planning.+//!+//! Kept in-crate (rather than depending on an FFT library) so the crate stays dependency-free;+//! the STFT effects only need a few fixed power-of-two sizes.++use std::f64::consts::PI;++/// A planned FFT of fixed power-of-two size.+#[derive(Clone, Debug)]+pub struct Fft {+ n: usize,+ /// e^{-2πik/n} for k in 0..n/2.+ tw_re: Vec<f32>,+ tw_im: Vec<f32>,+ rev: Vec<u32>,+}++impl Fft {+ /// Plan an FFT of size `n` (must be a power of two ≥ 2).+ pub fn new(n: usize) -> Fft {+ assert!(n >= 2 && n.is_power_of_two(), "FFT size must be a power of two");+ let bits = n.trailing_zeros();+ let rev = (0..n as u32).map(|i| i.reverse_bits() >> (32 - bits)).collect();+ let (tw_re, tw_im) = (0..n / 2)+ .map(|k| {+ let a = -2.0 * PI * k as f64 / n as f64;+ (a.cos() as f32, a.sin() as f32)+ })+ .unzip();+ Fft { n, tw_re, tw_im, rev }+ }++ pub fn len(&self) -> usize {+ self.n+ }++ pub fn is_empty(&self) -> bool {+ false+ }++ /// Forward transform (e^{-iωt}), unscaled.+ pub fn forward(&self, re: &mut [f32], im: &mut [f32]) {+ self.run(re, im, false);+ }++ /// Inverse transform (e^{+iωt}), unscaled (divide by `n` yourself).+ pub fn inverse(&self, re: &mut [f32], im: &mut [f32]) {+ self.run(re, im, true);+ }++ fn run(&self, re: &mut [f32], im: &mut [f32], inverse: bool) {+ let n = self.n;+ assert!(re.len() >= n && im.len() >= n);+ for i in 0..n {+ let j = self.rev[i] as usize;+ if j > i {+ re.swap(i, j);+ im.swap(i, j);+ }+ }+ let sign = if inverse { -1.0 } else { 1.0 };+ let mut len = 2;+ while len <= n {+ let half = len / 2;+ let stride = n / len;+ let mut start = 0;+ while start < n {+ for k in 0..half {+ let wr = self.tw_re[k * stride];+ let wi = sign * self.tw_im[k * stride];+ let a = start + k;+ let b = a + half;+ let xr = re[b] * wr - im[b] * wi;+ let xi = re[b] * wi + im[b] * wr;+ re[b] = re[a] - xr;+ im[b] = im[a] - xi;+ re[a] += xr;+ im[a] += xi;+ }+ start += len;+ }+ len <<= 1;+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn matches_naive_dft_and_round_trips() {+ let n = 64;+ let fft = Fft::new(n);+ let x: Vec<f32> = (0..n).map(|i| ((i * 7 % 13) as f32 - 6.0) / 6.0).collect();+ let mut re = x.clone();+ let mut im = vec![0.0; n];+ fft.forward(&mut re, &mut im);+ for k in 0..n {+ let (mut r, mut i) = (0.0f64, 0.0f64);+ for (t, &v) in x.iter().enumerate() {+ let a = -2.0 * PI * (k * t) as f64 / n as f64;+ r += v as f64 * a.cos();+ i += v as f64 * a.sin();+ }+ assert!((re[k] as f64 - r).abs() < 1e-4, "re {k}");+ assert!((im[k] as f64 - i).abs() < 1e-4, "im {k}");+ }+ fft.inverse(&mut re, &mut im);+ for t in 0..n {+ assert!((re[t] / n as f32 - x[t]).abs() < 1e-5);+ assert!((im[t] / n as f32).abs() < 1e-5);+ }+ }+}diff --git a/crates/audio-dsp/src/lib.rs b/crates/audio-dsp/src/lib.rsnew file mode 100644index 000000000..f4c17ddd7--- /dev/null+++ b/crates/audio-dsp/src/lib.rs@@ -0,0 +1,275 @@+//! Real-time audio DSP for FilmCraft (layer L1, dependency-free, `wasm32` clean).+//!+//! * [`loudness`] — ITU-R BS.1770-4 / EBU R128 loudness meter (momentary, short-term,+//! integrated, loudness range, sample peak, true peak) and the loudness-normalisation helper.+//! * [`effects`] — clip/track audio effects behind the common [`AudioEffect`] trait, with a+//! registry ([`effects()`]) describing every effect's parameters (range, unit, default) so the+//! engine and UI can build controls generically.+//! * [`biquad`] — RBJ-cookbook biquads (TDF-II) with analytic magnitude response.+//!+//! Conventions: audio is **planar f32** (`&mut [&mut [f32]]`, one slice per channel, all the same+//! length). `process` never allocates; all buffers are sized at construction. Parameters may be+//! changed between blocks and are smoothed per sample, so the output is independent of how the+//! stream is cut into blocks. Recursive state is flushed to zero when it decays below ~1e-30 so+//! denormals never appear (no FTZ/DAZ CPU flags needed, which keeps the crate `unsafe`-free and+//! portable to wasm).++// Effect plumbing is filled in by the effects module (M7.3).+#![allow(dead_code, unused_imports, unused_macros)]++pub mod biquad;+pub mod effects;+pub mod fft;+pub mod loudness;+pub mod oversample;+mod smooth;++pub use effects::{Category, EffectInfo, create_effect, effect_info, effects};+pub use loudness::{LoudnessMeter, normalize_gain_db};+pub use smooth::Smoothed;++/// Unit of a parameter value (for display and control construction).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum Unit {+ /// Unitless scalar.+ None,+ Decibels,+ Hertz,+ Milliseconds,+ Seconds,+ Percent,+ /// Filter quality factor.+ Q,+ /// Compression ratio (`x:1`).+ Ratio,+ Semitones,+ Bpm,+ /// Pan / balance position, −100 (left) … +100 (right).+ Pan,+ /// Boolean toggle: 0 = off, 1 = on.+ Toggle,+ /// Index into [`ParamSpec::choices`].+ Choice,+}++/// Static description of one effect parameter.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct ParamSpec {+ /// Stable id used by `set_param` / automation (e.g. `"threshold"`, `"b3.freq"`).+ pub id: &'static str,+ /// Human-readable label.+ pub name: &'static str,+ pub min: f32,+ pub max: f32,+ pub default: f32,+ pub unit: Unit,+ /// Hint that the control should be logarithmic (frequencies, times).+ pub log_scale: bool,+ /// Option labels when `unit == Unit::Choice` (value is the index).+ pub choices: &'static [&'static str],+}++impl ParamSpec {+ /// A continuous (linear) parameter.+ pub const fn new(id: &'static str, name: &'static str, min: f32, max: f32, default: f32, unit: Unit) -> Self {+ ParamSpec { id, name, min, max, default, unit, log_scale: false, choices: &[] }+ }+ /// A continuous parameter best shown on a logarithmic control.+ pub const fn log(id: &'static str, name: &'static str, min: f32, max: f32, default: f32, unit: Unit) -> Self {+ ParamSpec { id, name, min, max, default, unit, log_scale: true, choices: &[] }+ }+ /// An on/off toggle.+ pub const fn toggle(id: &'static str, name: &'static str, default: bool) -> Self {+ ParamSpec { id, name, min: 0.0, max: 1.0, default: if default { 1.0 } else { 0.0 }, unit: Unit::Toggle, log_scale: false, choices: &[] }+ }+ /// A discrete choice; the value is the index into `choices`.+ pub const fn choice(id: &'static str, name: &'static str, choices: &'static [&'static str], default: usize) -> Self {+ ParamSpec { id, name, min: 0.0, max: (choices.len() - 1) as f32, default: default as f32, unit: Unit::Choice, log_scale: false, choices }+ }+ /// Clamp (and for choices/toggles, round) a value into this parameter's domain.+ /// NaN maps to the default.+ pub fn sanitize(&self, v: f32) -> f32 {+ if v.is_nan() {+ return self.default;+ }+ let v = v.clamp(self.min, self.max);+ match self.unit {+ Unit::Choice | Unit::Toggle => v.round(),+ _ => v,+ }+ }+}++/// A real-time audio effect operating in place on planar channels.+///+/// Implementations are constructed (allocating) with a sample rate and channel count; after that+/// `process`, `set_param` and `reset` never allocate. If `process` receives more channels than the+/// effect was built for, the extra channels are passed through untouched (channel-generic effects+/// such as gain process all of them).+pub trait AudioEffect: Send {+ /// Registry id (e.g. `"compressor"`).+ fn id(&self) -> &'static str;+ /// Parameter descriptions (same as the registry entry's).+ fn params(&self) -> &'static [ParamSpec];+ /// Set a parameter by id; the value is clamped to its range. Returns `false` for unknown ids.+ /// Takes effect smoothly from the next processed sample.+ fn set_param(&mut self, id: &str, value: f32) -> bool;+ /// Current (target) value of a parameter.+ fn param(&self, id: &str) -> Option<f32>;+ /// Clear all internal state (delay lines, envelopes, filter memories); smoothed parameters+ /// jump to their targets.+ fn reset(&mut self);+ /// Process one block in place. All channel slices must have the same length (the shortest+ /// length is used otherwise). Zero-length blocks are allowed.+ fn process(&mut self, channels: &mut [&mut [f32]]);+ /// Processing latency in samples (look-ahead / STFT delay) for delay compensation.+ fn latency(&self) -> usize {+ 0+ }+}++/// Parameter value storage shared by the effect implementations.+#[derive(Clone, Debug)]+pub(crate) struct ParamValues {+ specs: &'static [ParamSpec],+ values: Vec<f32>,+}++impl ParamValues {+ pub(crate) fn new(specs: &'static [ParamSpec]) -> Self {+ ParamValues { specs, values: specs.iter().map(|s| s.default).collect() }+ }+ pub(crate) fn index_of(&self, id: &str) -> Option<usize> {+ self.specs.iter().position(|s| s.id == id)+ }+ /// Returns `true` if the id exists.+ pub(crate) fn set(&mut self, id: &str, v: f32) -> bool {+ match self.index_of(id) {+ Some(i) => {+ self.values[i] = self.specs[i].sanitize(v);+ true+ }+ None => false,+ }+ }+ pub(crate) fn get(&self, id: &str) -> Option<f32> {+ self.index_of(id).map(|i| self.values[i])+ }+ /// Value of a parameter that is known to exist (panics otherwise — programming error).+ pub(crate) fn v(&self, id: &str) -> f32 {+ match self.get(id) {+ Some(v) => v,+ None => panic!("unknown parameter {id}"),+ }+ }+ pub(crate) fn on(&self, id: &str) -> bool {+ self.v(id) >= 0.5+ }+ pub(crate) fn idx(&self, id: &str) -> usize {+ self.v(id).max(0.0) as usize+ }+}++/// Generates the id/params/set_param/param methods of [`AudioEffect`] for a struct with a+/// `pv: ParamValues` field, a `PARAMS` const and an `apply_params(&mut self, snap: bool)` method.+macro_rules! param_plumbing {+ ($id:expr) => {+ fn id(&self) -> &'static str {+ $id+ }+ fn params(&self) -> &'static [$crate::ParamSpec] {+ Self::PARAMS+ }+ fn set_param(&mut self, id: &str, value: f32) -> bool {+ if self.pv.set(id, value) {+ self.apply_params(false);+ true+ } else {+ false+ }+ }+ fn param(&self, id: &str) -> Option<f32> {+ self.pv.get(id)+ }+ };+}+pub(crate) use param_plumbing;++/// Decibels → linear amplitude.+#[inline]+pub fn db_to_gain(db: f32) -> f32 {+ 10f32.powf(db / 20.0)+}++/// Linear amplitude → decibels (−inf for 0).+#[inline]+pub fn gain_to_db(g: f32) -> f32 {+ 20.0 * g.abs().log10()+}++/// Flush tiny values to zero (denormal protection for recursive state).+#[inline(always)]+pub(crate) fn flush(x: f64) -> f64 {+ if x.abs() < 1e-30 { 0.0 } else { x }+}++/// f32 variant of [`flush`] for f32 delay lines.+#[inline(always)]+pub(crate) fn flush32(x: f32) -> f32 {+ if x.abs() < 1e-25 { 0.0 } else { x }+}++/// Common block length of planar channels.+#[inline]+pub(crate) fn block_len(channels: &[&mut [f32]]) -> usize {+ channels.iter().map(|c| c.len()).min().unwrap_or(0)+}++#[cfg(test)]+pub(crate) mod testutil {+ /// Tiny deterministic PRNG (xorshift64*) for tests.+ pub struct Rng(u64);+ impl Rng {+ pub fn new(seed: u64) -> Self {+ Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)+ }+ pub fn next_u64(&mut self) -> u64 {+ let mut x = self.0;+ x ^= x >> 12;+ x ^= x << 25;+ x ^= x >> 27;+ self.0 = x;+ x.wrapping_mul(0x2545_F491_4F6C_DD1D)+ }+ /// Uniform in [-1, 1).+ pub fn uniform(&mut self) -> f32 {+ ((self.next_u64() >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0+ }+ }++ pub fn sine(freq: f64, amp: f64, sr: f64, n: usize, phase: f64) -> Vec<f32> {+ (0..n).map(|i| (amp * (2.0 * std::f64::consts::PI * freq * i as f64 / sr + phase).sin()) as f32).collect()+ }++ pub fn rms(x: &[f32]) -> f64 {+ if x.is_empty() {+ return 0.0;+ }+ (x.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / x.len() as f64).sqrt()+ }++ pub fn db(x: f64) -> f64 {+ 20.0 * x.log10()+ }++ /// Amplitude of the `freq` component of `x` (single-bin DFT / Goertzel-style correlation).+ pub fn tone_amplitude(x: &[f32], freq: f64, sr: f64) -> f64 {+ let (mut re, mut im) = (0.0f64, 0.0f64);+ for (i, &v) in x.iter().enumerate() {+ let w = 2.0 * std::f64::consts::PI * freq * i as f64 / sr;+ re += v as f64 * w.cos();+ im += v as f64 * w.sin();+ }+ 2.0 * (re * re + im * im).sqrt() / x.len() as f64+ }+}diff --git a/crates/audio-dsp/src/loudness.rs b/crates/audio-dsp/src/loudness.rsnew file mode 100644index 000000000..1fbe8711b--- /dev/null+++ b/crates/audio-dsp/src/loudness.rs@@ -0,0 +1,693 @@+//! ITU-R BS.1770-4 / EBU R128 loudness metering.+//!+//! * K-weighting: the two BS.1770 stages (high-shelf "pre-filter" and the RLB high-pass) are+//! derived from their analog prototypes (centre frequency, Q, gain) through the bilinear+//! transform, so any sample rate is supported; at 48 kHz they reproduce the coefficient table in+//! the recommendation.+//! * Momentary (400 ms), short-term (3 s) windows are evaluated every 100 ms (75 % overlap for the+//! 400 ms gating blocks, as specified).+//! * Integrated loudness uses the two-stage gate (−70 LUFS absolute, −10 LU relative). Gating+//! blocks are accumulated in a fixed 0.01 LU histogram that also stores exact energy sums, so the+//! meter can run for arbitrarily long programmes without allocating and the result is exact up+//! to the placement of blocks within 0.01 LU of the relative threshold.+//! * Loudness range (EBU Tech 3342): short-term values, −70 LUFS absolute and −20 LU relative+//! gate, LRA = 95th − 10th percentile.+//! * Sample peak and true peak (polyphase oversampling to ≥ 176.4 kHz, see [`crate::oversample`]).++use crate::biquad::{Biquad, Coeffs};+use crate::oversample::{Interpolator, PolyphaseBank, true_peak_factor};+use std::f64::consts::PI;++const HIST_MIN: f64 = -70.0;+const HIST_MAX: f64 = 20.0;+const HIST_STEP: f64 = 0.01;+const HIST_BINS: usize = ((HIST_MAX - HIST_MIN) / HIST_STEP) as usize;+/// Short-term window in 100 ms sub-blocks.+const ST_SUBBLOCKS: usize = 30;+/// Momentary window in 100 ms sub-blocks.+const M_SUBBLOCKS: usize = 4;++/// Loudness of a mean-square energy (already channel-weighted), in LUFS.+#[inline]+pub fn energy_to_lufs(e: f64) -> f64 {+ if e <= 0.0 { f64::NEG_INFINITY } else { -0.691 + 10.0 * e.log10() }+}++#[cfg(test)]+fn lufs_to_energy(l: f64) -> f64 {+ 10f64.powf((l + 0.691) / 10.0)+}++/// Stage 1 of K-weighting: the high-shelf ("head") pre-filter for `sample_rate`.+pub fn k_prefilter(sample_rate: f64) -> Coeffs {+ // Analog prototype parameters of the BS.1770 shelving stage.+ let f0 = 1_681.974_450_955_533;+ let gain_db = 3.999_843_853_973_347;+ let q = 0.707_175_236_955_419_6;+ let k = (PI * f0 / sample_rate).tan();+ let vh = 10f64.powf(gain_db / 20.0);+ let vb = vh.powf(0.499_666_774_154_541_6);+ let a0 = 1.0 + k / q + k * k;+ Coeffs {+ b0: (vh + vb * k / q + k * k) / a0,+ b1: 2.0 * (k * k - vh) / a0,+ b2: (vh - vb * k / q + k * k) / a0,+ a1: 2.0 * (k * k - 1.0) / a0,+ a2: (1.0 - k / q + k * k) / a0,+ }+}++/// Stage 2 of K-weighting: the RLB high-pass for `sample_rate`.+pub fn k_rlb(sample_rate: f64) -> Coeffs {+ let f0 = 38.135_470_876_024_44;+ let q = 0.500_327_037_323_877_3;+ let k = (PI * f0 / sample_rate).tan();+ let a0 = 1.0 + k / q + k * k;+ Coeffs { 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 }+}++/// Default BS.1770 channel weights for a channel count (L R C LFE Ls Rs [Lb Rb] order for 5.1 /+/// 7.1; LFE is excluded; surrounds get 1.41 ≈ +1.5 dB).+pub fn default_channel_weights(channels: usize) -> Vec<f64> {+ match channels {+ 5 => vec![1.0, 1.0, 1.0, 1.41, 1.41],+ 6 => vec![1.0, 1.0, 1.0, 0.0, 1.41, 1.41],+ 8 => vec![1.0, 1.0, 1.0, 0.0, 1.41, 1.41, 1.41, 1.41],+ n => vec![1.0; n],+ }+}++/// Histogram of block loudness values with exact energy sums per bin.+#[derive(Clone, Debug)]+struct Histogram {+ count: Vec<u64>,+ energy: Vec<f64>,+}++impl Histogram {+ fn new() -> Self {+ Histogram { count: vec![0; HIST_BINS], energy: vec![0.0; HIST_BINS] }+ }+ fn clear(&mut self) {+ self.count.iter_mut().for_each(|c| *c = 0);+ self.energy.iter_mut().for_each(|e| *e = 0.0);+ }+ fn bin_of(l: f64) -> usize {+ (((l - HIST_MIN) / HIST_STEP).floor().max(0.0) as usize).min(HIST_BINS - 1)+ }+ fn bin_centre(i: usize) -> f64 {+ HIST_MIN + (i as f64 + 0.5) * HIST_STEP+ }+ /// Add a block if it passes the absolute gate.+ fn add(&mut self, energy: f64) {+ let l = energy_to_lufs(energy);+ if l >= HIST_MIN {+ let b = Self::bin_of(l);+ self.count[b] += 1;+ self.energy[b] += energy;+ }+ }+ /// Power mean (energy) of bins from `from` upward; None if empty.+ fn mean_energy_from(&self, from: usize) -> Option<(f64, u64)> {+ let (mut e, mut n) = (0.0, 0u64);+ for i in from..HIST_BINS {+ e += self.energy[i];+ n += self.count[i];+ }+ (n > 0).then(|| (e / n as f64, n))+ }+ /// Relative-gate start bin for a gate of `rel` LU below the absolute-gated mean.+ fn relative_gate_bin(&self, rel: f64) -> Option<usize> {+ let (e, _) = self.mean_energy_from(0)?;+ let thr = energy_to_lufs(e) + rel;+ Some(if thr < HIST_MIN { 0 } else { Self::bin_of(thr) })+ }+}++/// Streaming BS.1770-4 / EBU R128 loudness meter for planar or interleaved f32 audio.+#[derive(Clone, Debug)]+pub struct LoudnessMeter {+ sample_rate: f64,+ channels: usize,+ weights: Vec<f64>,+ pre: Coeffs,+ rlb: Coeffs,+ filt: Vec<(Biquad, Biquad)>,+ /// Per-channel sum of squares in the current 100 ms sub-block.+ acc: Vec<f64>,+ sub_len: usize,+ sub_pos: usize,+ /// Ring of (weighted energy sum, sample count) for the last 30 sub-blocks.+ ring: [(f64, usize); ST_SUBBLOCKS],+ ring_pos: usize,+ subblocks_seen: u64,+ momentary: f64,+ short_term: f64,+ max_momentary: f64,+ max_short_term: f64,+ integrated_hist: Histogram,+ lra_hist: Histogram,+ sample_peak: Vec<f32>,+ true_peak: Vec<f32>,+ bank: PolyphaseBank,+ interp: Vec<Interpolator>,+}++impl LoudnessMeter {+ /// A meter for `channels` channels at `sample_rate` Hz with default BS.1770 weights.+ pub fn new(sample_rate: f64, channels: usize) -> Self {+ let channels = channels.max(1);+ let sub_len = ((sample_rate * 0.1).round() as usize).max(1);+ LoudnessMeter {+ sample_rate,+ channels,+ weights: default_channel_weights(channels),+ pre: k_prefilter(sample_rate),+ rlb: k_rlb(sample_rate),+ filt: vec![(Biquad::new(), Biquad::new()); channels],+ acc: vec![0.0; channels],+ sub_len,+ sub_pos: 0,+ ring: [(0.0, 0); ST_SUBBLOCKS],+ ring_pos: 0,+ subblocks_seen: 0,+ momentary: f64::NEG_INFINITY,+ short_term: f64::NEG_INFINITY,+ max_momentary: f64::NEG_INFINITY,+ max_short_term: f64::NEG_INFINITY,+ integrated_hist: Histogram::new(),+ lra_hist: Histogram::new(),+ sample_peak: vec![0.0; channels],+ true_peak: vec![0.0; channels],+ bank: PolyphaseBank::new(true_peak_factor(sample_rate)),+ interp: vec![Interpolator::default(); channels],+ }+ }++ pub fn sample_rate(&self) -> f64 {+ self.sample_rate+ }+ pub fn channels(&self) -> usize {+ self.channels+ }++ /// Override the per-channel weights (missing entries are 1.0, extra ignored).+ pub fn set_channel_weights(&mut self, weights: &[f64]) {+ for (i, w) in self.weights.iter_mut().enumerate() {+ *w = weights.get(i).copied().unwrap_or(1.0);+ }+ }++ /// Clear all measurements and filter state.+ pub fn reset(&mut self) {+ self.integrated_hist.clear();+ self.lra_hist.clear();+ self.filt.iter_mut().for_each(|(a, b)| {+ a.reset();+ b.reset()+ });+ self.acc.iter_mut().for_each(|a| *a = 0.0);+ self.sample_peak.iter_mut().for_each(|p| *p = 0.0);+ self.true_peak.iter_mut().for_each(|p| *p = 0.0);+ self.interp.iter_mut().for_each(Interpolator::reset);+ self.sub_pos = 0;+ self.ring = [(0.0, 0); ST_SUBBLOCKS];+ self.ring_pos = 0;+ self.subblocks_seen = 0;+ self.momentary = f64::NEG_INFINITY;+ self.short_term = f64::NEG_INFINITY;+ self.max_momentary = f64::NEG_INFINITY;+ self.max_short_term = f64::NEG_INFINITY;+ }++ #[inline(always)]+ fn feed(&mut self, ch: usize, x: f32) {+ let (pre, rlb) = &mut self.filt[ch];+ let y = rlb.tick(&self.rlb, pre.tick(&self.pre, x as f64));+ self.acc[ch] += y * y;+ let a = x.abs();+ if a > self.sample_peak[ch] {+ self.sample_peak[ch] = a;+ }+ let tp = self.interp[ch].push_peak(&self.bank, x).max(a);+ if tp > self.true_peak[ch] {+ self.true_peak[ch] = tp;+ }+ }++ /// Feed a block of planar audio (one slice per channel; extra channels are ignored, missing+ /// channels count as silence).+ pub fn process(&mut self, channels: &[&[f32]]) {+ let n = channels.iter().take(self.channels).map(|c| c.len()).min().unwrap_or(0);+ let mut pos = 0;+ while pos < n {+ let take = (n - pos).min(self.sub_len - self.sub_pos);+ for (ch, data) in channels.iter().take(self.channels).enumerate() {+ for &x in &data[pos..pos + take] {+ self.feed(ch, x);+ }+ }+ for ch in channels.len()..self.channels {+ for _ in 0..take {+ self.feed(ch, 0.0);+ }+ }+ pos += take;+ self.sub_pos += take;+ if self.sub_pos == self.sub_len {+ self.finish_subblock();+ }+ }+ }++ /// Feed a block of interleaved audio with `self.channels()` channels per frame.+ pub fn process_interleaved(&mut self, data: &[f32]) {+ let nch = self.channels;+ let frames = data.len() / nch;+ let mut f = 0;+ while f < frames {+ let take = (frames - f).min(self.sub_len - self.sub_pos);+ for i in f..f + take {+ for ch in 0..nch {+ self.feed(ch, data[i * nch + ch]);+ }+ }+ f += take;+ self.sub_pos += take;+ if self.sub_pos == self.sub_len {+ self.finish_subblock();+ }+ }+ }++ fn finish_subblock(&mut self) {+ let mut e = 0.0;+ for ch in 0..self.channels {+ e += self.weights[ch] * self.acc[ch];+ self.acc[ch] = 0.0;+ }+ self.ring[self.ring_pos] = (e, self.sub_pos);+ self.ring_pos = (self.ring_pos + 1) % ST_SUBBLOCKS;+ self.sub_pos = 0;+ self.subblocks_seen += 1;++ let window = |k: usize, ring: &[(f64, usize); ST_SUBBLOCKS], pos: usize, sub_len: usize| {+ let mut s = 0.0;+ for i in 0..k {+ s += ring[(pos + ST_SUBBLOCKS - 1 - i) % ST_SUBBLOCKS].0;+ }+ s / (k * sub_len) as f64+ };+ let em = window(M_SUBBLOCKS, &self.ring, self.ring_pos, self.sub_len);+ let es = window(ST_SUBBLOCKS, &self.ring, self.ring_pos, self.sub_len);+ self.momentary = energy_to_lufs(em);+ self.short_term = energy_to_lufs(es);+ if self.subblocks_seen >= M_SUBBLOCKS as u64 {+ self.integrated_hist.add(em);+ self.max_momentary = self.max_momentary.max(self.momentary);+ }+ if self.subblocks_seen >= ST_SUBBLOCKS as u64 {+ self.lra_hist.add(es);+ self.max_short_term = self.max_short_term.max(self.short_term);+ }+ }++ /// Momentary loudness (last 400 ms), LUFS; updated every 100 ms. −∞ for silence.+ pub fn momentary(&self) -> f64 {+ self.momentary+ }+ /// Short-term loudness (last 3 s), LUFS; updated every 100 ms.+ pub fn short_term(&self) -> f64 {+ self.short_term+ }+ /// Maximum momentary loudness so far.+ pub fn max_momentary(&self) -> f64 {+ self.max_momentary+ }+ /// Maximum short-term loudness so far.+ pub fn max_short_term(&self) -> f64 {+ self.max_short_term+ }++ /// Gated integrated loudness (BS.1770-4), LUFS. −∞ if nothing passed the gates.+ pub fn integrated(&self) -> f64 {+ let h = &self.integrated_hist;+ match h.relative_gate_bin(-10.0).and_then(|b| h.mean_energy_from(b)) {+ Some((e, _)) => energy_to_lufs(e),+ None => f64::NEG_INFINITY,+ }+ }++ /// Relative gate threshold used for the integrated loudness (LUFS).+ pub fn relative_threshold(&self) -> f64 {+ match self.integrated_hist.mean_energy_from(0) {+ Some((e, _)) => energy_to_lufs(e) - 10.0,+ None => f64::NEG_INFINITY,+ }+ }++ /// Loudness range (EBU Tech 3342), LU. 0 when too little signal.+ pub fn loudness_range(&self) -> f64 {+ let h = &self.lra_hist;+ let Some(start) = h.relative_gate_bin(-20.0) else { return 0.0 };+ let n: u64 = h.count[start..].iter().sum();+ if n == 0 {+ return 0.0;+ }+ let percentile = |p: f64| {+ // Nearest-rank on the sorted gated values.+ let rank = ((p * (n - 1) as f64).round() as u64).min(n - 1);+ let mut c = 0u64;+ for i in start..HIST_BINS {+ c += h.count[i];+ if c > rank {+ return Histogram::bin_centre(i);+ }+ }+ Histogram::bin_centre(HIST_BINS - 1)+ };+ (percentile(0.95) - percentile(0.10)).max(0.0)+ }++ /// Maximum absolute sample value over all channels (linear).+ pub fn sample_peak(&self) -> f64 {+ self.sample_peak.iter().fold(0.0f32, |a, &b| a.max(b)) as f64+ }+ /// Per-channel sample peak (linear).+ pub fn sample_peak_channel(&self, ch: usize) -> f64 {+ self.sample_peak.get(ch).copied().unwrap_or(0.0) as f64+ }+ /// Maximum true peak over all channels (linear).+ pub fn true_peak(&self) -> f64 {+ self.true_peak.iter().fold(0.0f32, |a, &b| a.max(b)) as f64+ }+ /// Per-channel true peak (linear).+ pub fn true_peak_channel(&self, ch: usize) -> f64 {+ self.true_peak.get(ch).copied().unwrap_or(0.0) as f64+ }+ /// Maximum true peak in dBTP.+ pub fn true_peak_dbtp(&self) -> f64 {+ 20.0 * self.true_peak().log10()+ }++ /// Snapshot of all programme measurements.+ pub fn summary(&self) -> LoudnessSummary {+ LoudnessSummary {+ integrated_lufs: self.integrated(),+ loudness_range_lu: self.loudness_range(),+ max_momentary_lufs: self.max_momentary,+ max_short_term_lufs: self.max_short_term,+ sample_peak_dbfs: 20.0 * self.sample_peak().log10(),+ true_peak_dbtp: self.true_peak_dbtp(),+ }+ }+}++/// Programme loudness measurements (EBU R128 set).+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct LoudnessSummary {+ pub integrated_lufs: f64,+ pub loudness_range_lu: f64,+ pub max_momentary_lufs: f64,+ pub max_short_term_lufs: f64,+ pub sample_peak_dbfs: f64,+ pub true_peak_dbtp: f64,+}++/// Measure a whole planar programme in one call.+pub fn measure(channels: &[&[f32]], sample_rate: f64) -> LoudnessSummary {+ let mut m = LoudnessMeter::new(sample_rate, channels.len());+ m.process(channels);+ m.summary()+}++/// Gain (dB) that moves a programme measured at `measured_lufs` to `target_lufs`.+/// Returns 0 for silent / unmeasurable input.+pub fn normalize_gain_db(measured_lufs: f64, target_lufs: f64) -> f64 {+ if measured_lufs.is_finite() && target_lufs.is_finite() { target_lufs - measured_lufs } else { 0.0 }+}++/// Like [`normalize_gain_db`] but limited so that the resulting true peak does not exceed+/// `max_true_peak_dbtp` (a linear gain can't fix peaks, so the loudness target is sacrificed —+/// the behaviour of "Normalize" / Essential Sound auto-match without a limiter).+pub fn normalize_gain_db_peak_limited(measured_lufs: f64, target_lufs: f64, true_peak_dbtp: f64, max_true_peak_dbtp: f64) -> f64 {+ let g = normalize_gain_db(measured_lufs, target_lufs);+ if true_peak_dbtp.is_finite() { g.min(max_true_peak_dbtp - true_peak_dbtp) } else { g }+}++/// Expected loudness energy weighting of a pure tone at `freq` through K-weighting (|H|², for+/// tests and analytical tooling).+pub fn k_weighting_power(freq: f64, sample_rate: f64) -> f64 {+ let a = k_prefilter(sample_rate).magnitude(freq, sample_rate);+ let b = k_rlb(sample_rate).magnitude(freq, sample_rate);+ (a * b).powi(2)+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::testutil::*;++ fn dbfs(db: f64) -> f64 {+ 10f64.powf(db / 20.0)+ }++ /// Stereo programme made of (seconds, dBFS) sine segments.+ fn segments(freq: f64, sr: f64, segs: &[(f64, f64)]) -> Vec<f32> {+ let mut out = Vec::new();+ let mut phase_idx = 0usize;+ for &(secs, level) in segs {+ let n = (secs * sr).round() as usize;+ let a = dbfs(level);+ for _ in 0..n {+ out.push((a * (2.0 * PI * freq * phase_idx as f64 / sr).sin()) as f32);+ phase_idx += 1;+ }+ }+ out+ }++ fn stereo_measure(x: &[f32], sr: f64) -> LoudnessMeter {+ let mut m = LoudnessMeter::new(sr, 2);+ // Feed in odd-sized blocks to exercise the sub-block splitting.+ for chunk in x.chunks(1237) {+ m.process(&[chunk, chunk]);+ }+ m+ }++ #[test]+ fn k_weighting_matches_bs1770_table_at_48k() {+ let p = k_prefilter(48000.0);+ assert!((p.b0 - 1.535_124_859_586_97).abs() < 1e-8);+ assert!((p.b1 + 2.691_696_189_406_38).abs() < 1e-8);+ assert!((p.b2 - 1.198_392_810_852_85).abs() < 1e-8);+ assert!((p.a1 + 1.690_659_293_182_41).abs() < 1e-8);+ assert!((p.a2 - 0.732_480_774_215_85).abs() < 1e-8);+ let r = k_rlb(48000.0);+ assert!((r.a1 + 1.990_047_454_833_98).abs() < 1e-8);+ assert!((r.a2 - 0.990_072_250_366_21).abs() < 1e-8);+ }++ #[test]+ fn k_weighting_shape_is_sample_rate_independent() {+ for sr in [32000.0, 44100.0, 48000.0, 96000.0, 192000.0] {+ let db = |f| 10.0 * k_weighting_power(f, sr).log10();+ // ~+0.69 dB at 1 kHz, ~+4 dB high shelf, strong low-cut.+ assert!((db(1000.0) - 0.691).abs() < 0.03, "sr {sr}: {}", db(1000.0));+ assert!((db(10000.0) - 4.0).abs() < 0.3, "sr {sr}");+ assert!(db(20.0) < -10.0, "sr {sr}");+ }+ }++ #[test]+ fn tech3341_case1_and_2_stereo_sine() {+ for (sr, freq) in [(48000.0, 1000.0), (44100.0, 997.0), (96000.0, 1000.0)] {+ for level in [-23.0, -33.0] {+ let x = segments(freq, sr, &[(20.0, level)]);+ let m = stereo_measure(&x, sr);+ assert!((m.integrated() - level).abs() < 0.1, "sr {sr} I {}", m.integrated());+ assert!((m.momentary() - level).abs() < 0.1, "M {}", m.momentary());+ assert!((m.short_term() - level).abs() < 0.1, "S {}", m.short_term());+ assert!((m.max_momentary() - level).abs() < 0.1);+ assert!(m.loudness_range() < 0.1);+ }+ }+ }++ #[test]+ fn interleaved_matches_planar() {+ let sr = 48000.0;+ let x = segments(1000.0, sr, &[(5.0, -20.0)]);+ let il: Vec<f32> = x.iter().flat_map(|&v| [v, v]).collect();+ let mut m = LoudnessMeter::new(sr, 2);+ m.process_interleaved(&il);+ let p = stereo_measure(&x, sr);+ assert!((m.integrated() - p.integrated()).abs() < 1e-9);+ }++ #[test]+ fn tech3341_case3_4_gating() {+ let sr = 48000.0;+ // Case 3: -36 / -23 / -36 dBFS for 10 / 60 / 10 s → -23.0 LUFS.+ let x = segments(1000.0, sr, &[(10.0, -36.0), (60.0, -23.0), (10.0, -36.0)]);+ let m = stereo_measure(&x, sr);+ assert!((m.integrated() + 23.0).abs() < 0.1, "{}", m.integrated());+ // Case 4: -72 / -36 / -23 / -36 / -72 dBFS for 10/10/60/10/10 s → -23.0 LUFS.+ let x = segments(1000.0, sr, &[(10.0, -72.0), (10.0, -36.0), (60.0, -23.0), (10.0, -36.0), (10.0, -72.0)]);+ let m = stereo_measure(&x, sr);+ assert!((m.integrated() + 23.0).abs() < 0.1, "{}", m.integrated());+ }++ #[test]+ fn tech3341_case5_relative_gate() {+ let sr = 48000.0;+ let x = segments(1000.0, sr, &[(20.0, -26.0), (20.1, -20.0), (20.0, -26.0)]);+ let m = stereo_measure(&x, sr);+ assert!((m.integrated() + 23.0).abs() < 0.1, "{}", m.integrated());+ }++ #[test]+ fn silence_and_below_gate() {+ let sr = 48000.0;+ let mut m = LoudnessMeter::new(sr, 2);+ let z = vec![0.0f32; 48000 * 2];+ m.process(&[&z, &z]);+ assert_eq!(m.integrated(), f64::NEG_INFINITY);+ assert_eq!(m.loudness_range(), 0.0);+ let x = segments(1000.0, sr, &[(5.0, -80.0)]);+ let m = stereo_measure(&x, sr);+ assert_eq!(m.integrated(), f64::NEG_INFINITY);+ }++ #[test]+ fn tech3342_loudness_range() {+ let sr = 48000.0;+ let cases: [(&[(f64, f64)], f64); 4] = [+ (&[(20.0, -20.0), (20.0, -30.0)], 10.0),+ (&[(20.0, -20.0), (20.0, -15.0)], 5.0),+ (&[(20.0, -40.0), (20.0, -20.0)], 20.0),+ (&[(20.0, -50.0), (20.0, -35.0), (20.0, -20.0), (20.0, -35.0), (20.0, -50.0)], 15.0),+ ];+ for (segs, expect) in cases {+ let x = segments(1000.0, sr, segs);+ let m = stereo_measure(&x, sr);+ assert!((m.loudness_range() - expect).abs() < 1.0, "LRA {} expected {expect}", m.loudness_range());+ }+ }++ #[test]+ fn log_sweep_matches_analytic_k_weighting() {+ let sr = 48000.0;+ let secs = 20.0;+ let n = (sr * secs) as usize;+ let (f1, f2) = (20.0f64, 20000.0f64);+ let k = (f2 / f1).ln();+ let amp = dbfs(-20.0);+ let mut phase = 0.0f64;+ let mut x = Vec::with_capacity(n);+ let mut expected_e = 0.0;+ for i in 0..n {+ let f = f1 * (k * i as f64 / n as f64).exp();+ x.push((amp * phase.sin()) as f32);+ phase += 2.0 * PI * f / sr;+ // Stereo: 2 channels × A²/2 × |H(f)|².+ expected_e += amp * amp * k_weighting_power(f, sr);+ }+ expected_e /= n as f64;+ // Ungated average of the same signal: compare with the mean of momentary energies, i.e.+ // the integrated value is gated, so build the expectation the same way using short blocks.+ let m = stereo_measure(&x, sr);+ let expect = energy_to_lufs(expected_e);+ // Gating removes the quiet low-frequency start, so integrated ≥ ungated expectation; the+ // difference must be small for a sweep that is mostly well above the gates.+ let i = m.integrated();+ assert!(i >= expect - 0.1 && i - expect < 0.6, "I {i} vs ungated analytic {expect}");+ }++ #[test]+ fn surround_weights() {+ let sr = 48000.0;+ let x = segments(1000.0, sr, &[(10.0, -30.0)]);+ let z = vec![0.0f32; x.len()];+ // Signal only in Ls of a 5.1 layout → +1.5 dB weighting vs. front channel.+ let mut front = LoudnessMeter::new(sr, 6);+ front.process(&[&x, &z, &z, &z, &z, &z]);+ let mut surr = LoudnessMeter::new(sr, 6);+ surr.process(&[&z, &z, &z, &z, &x, &z]);+ let mut lfe = LoudnessMeter::new(sr, 6);+ lfe.process(&[&z, &z, &z, &x, &z, &z]);+ assert!((surr.integrated() - front.integrated() - 10.0 * 1.41f64.log10()).abs() < 0.01);+ assert_eq!(lfe.integrated(), f64::NEG_INFINITY);+ }++ #[test]+ fn true_peak_of_intersample_peak_signal() {+ for sr in [48000.0, 44100.0] {+ // fs/4 sine with 45° phase: every sample is at ±0.5·√2·A, true peak A (0 dBFS).+ let n = sr as usize;+ let x: Vec<f32> = (0..n).map(|i| (PI / 2.0 * i as f64 + PI / 4.0).sin() as f32).collect();+ let m = stereo_measure(&x, sr);+ assert!((20.0 * m.sample_peak().log10() + 3.01).abs() < 0.01);+ // EBU Tech 3341 true-peak tolerance: +0.2 / −0.4 dB.+ let tp = m.true_peak_dbtp();+ assert!((-0.4..=0.2).contains(&tp), "sr {sr} TP {tp}");+ }+ // A tone at an off-grid frequency with a 1 kHz-ish content: TP ≈ amplitude.+ let x = sine(997.0, dbfs(-6.0), 48000.0, 48000, 0.3);+ let m = stereo_measure(&x, 48000.0);+ assert!((m.true_peak_dbtp() + 6.0).abs() < 0.2);+ // Tech 3341 case 15-ish: 0 dBFS 1 kHz-ish tone at 48 kHz sampled off-peak.+ let x = sine(11025.0, 1.0, 44100.0, 44100, 0.0);+ let m = stereo_measure(&x, 44100.0);+ assert!((-0.4..=0.2).contains(&m.true_peak_dbtp()), "{}", m.true_peak_dbtp());+ }++ #[test]+ fn reset_clears_everything() {+ let sr = 48000.0;+ let x = segments(1000.0, sr, &[(5.0, -20.0)]);+ let mut m = stereo_measure(&x, sr);+ m.reset();+ assert_eq!(m.integrated(), f64::NEG_INFINITY);+ assert_eq!(m.true_peak(), 0.0);+ let x = segments(1000.0, sr, &[(5.0, -30.0)]);+ m.process(&[&x, &x]);+ assert!((m.integrated() + 30.0).abs() < 0.1);+ }++ #[test]+ fn normalize_helpers() {+ assert_eq!(normalize_gain_db(-30.0, -23.0), 7.0);+ assert_eq!(normalize_gain_db(f64::NEG_INFINITY, -23.0), 0.0);+ assert_eq!(normalize_gain_db_peak_limited(-30.0, -23.0, -3.0, -1.0), 2.0);+ assert_eq!(normalize_gain_db_peak_limited(-30.0, -23.0, -10.0, -1.0), 7.0);+ // Applying the gain lands on target.+ let sr = 48000.0;+ let x = segments(1000.0, sr, &[(10.0, -31.3)]);+ let m = stereo_measure(&x, sr);+ let g = 10f64.powf(normalize_gain_db(m.integrated(), -16.0) / 20.0) as f32;+ let y: Vec<f32> = x.iter().map(|v| v * g).collect();+ let m2 = stereo_measure(&y, sr);+ assert!((m2.integrated() + 16.0).abs() < 0.02);+ assert!((lufs_to_energy(energy_to_lufs(0.3)) - 0.3).abs() < 1e-12);+ }++ #[test]+ fn tiny_blocks_equal_big_blocks() {+ let sr = 48000.0;+ let x = segments(440.0, sr, &[(4.0, -18.0)]);+ let mut a = LoudnessMeter::new(sr, 1);+ a.process(&[&x]);+ let mut b = LoudnessMeter::new(sr, 1);+ b.process(&[&[]]);+ for s in x.chunks(1) {+ b.process(&[s]);+ }+ assert_eq!(a.integrated(), b.integrated());+ assert_eq!(a.true_peak(), b.true_peak());+ // Mono is summed without the dual-mono +3 dB (BS.1770).+ let expect = -0.691 + 20.0 * rms(&x).log10() + 10.0 * k_weighting_power(440.0, sr).log10();+ assert!((a.integrated() - expect).abs() < 0.1, "{} vs {expect}", a.integrated());+ }+}diff --git a/crates/audio-dsp/src/oversample.rs b/crates/audio-dsp/src/oversample.rsnew file mode 100644index 000000000..6bdfa4c30--- /dev/null+++ b/crates/audio-dsp/src/oversample.rs@@ -0,0 +1,144 @@+//! Polyphase FIR interpolator used for true-peak estimation (BS.1770-4 Annex 2 style).+//!+//! The prototype is a Kaiser-windowed sinc low-pass (cut-off at the original Nyquist) split into+//! `factor` phases of [`TAPS_PER_PHASE`] taps; each phase is normalised to unity DC gain.++use std::f64::consts::PI;++/// Taps per polyphase branch.+pub const TAPS_PER_PHASE: usize = 16;++/// Oversampling factor giving an effective rate of at least 176.4 kHz (4× at 44.1/48 kHz,+/// 2× at 88.2/96 kHz, 1× above), as recommended by BS.1770-4 for true-peak metering.+pub fn true_peak_factor(sample_rate: f64) -> usize {+ if sample_rate < 88_200.0 {+ 4+ } else if sample_rate < 176_400.0 {+ 2+ } else {+ 1+ }+}++fn bessel_i0(x: f64) -> f64 {+ let mut sum = 1.0;+ let mut term = 1.0;+ let q = x * x / 4.0;+ for k in 1..50 {+ term *= q / (k * k) as f64;+ sum += term;+ if term < sum * 1e-17 {+ break;+ }+ }+ sum+}++/// Polyphase coefficient bank shared by all channels.+#[derive(Clone, Debug)]+pub struct PolyphaseBank {+ factor: usize,+ /// `coeffs[p * TAPS_PER_PHASE + j]` multiplies `x[n - j]` for output phase `p`.+ coeffs: Vec<f32>,+}++impl PolyphaseBank {+ pub fn new(factor: usize) -> Self {+ let factor = factor.max(1);+ let len = factor * TAPS_PER_PHASE;+ let centre = (len - 1) as f64 / 2.0;+ let beta = 8.0;+ let i0b = bessel_i0(beta);+ let proto: Vec<f64> = (0..len)+ .map(|m| {+ let t = (m as f64 - centre) / factor as f64;+ let sinc = if t.abs() < 1e-12 { 1.0 } else { (PI * t).sin() / (PI * t) };+ let r = (m as f64 - centre) / (centre + 1.0);+ let w = bessel_i0(beta * (1.0 - r * r).max(0.0).sqrt()) / i0b;+ sinc * w+ })+ .collect();+ let mut coeffs = vec![0.0f32; len];+ for p in 0..factor {+ let sum: f64 = (0..TAPS_PER_PHASE).map(|j| proto[p + factor * j]).sum();+ for j in 0..TAPS_PER_PHASE {+ coeffs[p * TAPS_PER_PHASE + j] = (proto[p + factor * j] / sum) as f32;+ }+ }+ PolyphaseBank { factor, coeffs }+ }+ pub fn factor(&self) -> usize {+ self.factor+ }+ /// Approximate delay (in input samples) between an input sample and the interpolated+ /// values around it.+ pub fn delay(&self) -> usize {+ TAPS_PER_PHASE / 2+ }+}++/// Per-channel interpolator history.+#[derive(Clone, Debug)]+pub struct Interpolator {+ /// Double-written ring so a contiguous window of TAPS_PER_PHASE is always available.+ hist: [f32; 2 * TAPS_PER_PHASE],+ pos: usize,+}++impl Default for Interpolator {+ fn default() -> Self {+ Interpolator { hist: [0.0; 2 * TAPS_PER_PHASE], pos: 0 }+ }+}++impl Interpolator {+ pub fn reset(&mut self) {+ *self = Self::default();+ }++ /// Push one input sample; returns the maximum absolute value of the `factor` interpolated+ /// output samples produced for it.+ #[inline]+ pub fn push_peak(&mut self, bank: &PolyphaseBank, x: f32) -> f32 {+ if bank.factor == 1 {+ return x.abs();+ }+ // Newest sample at window[TAPS-1-0]... store so that window[j] = x[n - j].+ self.pos = if self.pos == 0 { TAPS_PER_PHASE - 1 } else { self.pos - 1 };+ self.hist[self.pos] = x;+ self.hist[self.pos + TAPS_PER_PHASE] = x;+ let win = &self.hist[self.pos..self.pos + TAPS_PER_PHASE];+ let mut peak = 0.0f32;+ for p in 0..bank.factor {+ let c = &bank.coeffs[p * TAPS_PER_PHASE..(p + 1) * TAPS_PER_PHASE];+ let y: f32 = c.iter().zip(win).map(|(a, b)| a * b).sum();+ peak = peak.max(y.abs());+ }+ peak+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn phases_have_unity_dc_and_interpolate_sines() {+ let bank = PolyphaseBank::new(4);+ for p in 0..4 {+ let s: f32 = bank.coeffs[p * TAPS_PER_PHASE..(p + 1) * TAPS_PER_PHASE].iter().sum();+ assert!((s - 1.0).abs() < 1e-5);+ }+ // Sine at fs/4 with 45° phase: samples at ±0.707, true peak 1.0.+ let mut ip = Interpolator::default();+ let mut peak = 0.0f32;+ for n in 0..400 {+ let x = (std::f64::consts::FRAC_PI_2 * n as f64 + std::f64::consts::FRAC_PI_4).sin() as f32;+ let p = ip.push_peak(&bank, x);+ if n > 40 {+ peak = peak.max(p);+ }+ }+ assert!((peak - 1.0).abs() < 0.02, "peak {peak}");+ }+}diff --git a/crates/audio-dsp/src/smooth.rs b/crates/audio-dsp/src/smooth.rsnew file mode 100644index 000000000..396cdfba3--- /dev/null+++ b/crates/audio-dsp/src/smooth.rs@@ -0,0 +1,105 @@+//! Per-sample parameter smoothing (linear ramps) to avoid zipper noise.++/// A value that ramps linearly to its target over a fixed number of samples.+#[derive(Clone, Copy, Debug)]+pub struct Smoothed {+ current: f64,+ target: f64,+ step: f64,+ remaining: u32,+ ramp: u32,+}++impl Smoothed {+ /// `ramp_samples` = length of a full transition (0 = no smoothing).+ pub fn new(value: f32, ramp_samples: u32) -> Self {+ Smoothed { current: value as f64, target: value as f64, step: 0.0, remaining: 0, ramp: ramp_samples }+ }+ /// Convenience: ramp length from a time in milliseconds.+ pub fn with_ms(value: f32, sample_rate: f32, ms: f32) -> Self {+ Self::new(value, (sample_rate * ms / 1000.0).round().max(0.0) as u32)+ }+ /// Start ramping towards `target`.+ pub fn set(&mut self, target: f32) {+ let t = target as f64;+ if t == self.target {+ return;+ }+ self.target = t;+ if self.ramp == 0 {+ self.current = t;+ self.remaining = 0;+ } else {+ self.remaining = self.ramp;+ self.step = (t - self.current) / self.ramp as f64;+ }+ }+ /// Jump straight to the target.+ pub fn snap(&mut self) {+ self.current = self.target;+ self.remaining = 0;+ }+ /// Set and jump.+ pub fn set_immediate(&mut self, v: f32) {+ self.target = v as f64;+ self.snap();+ }+ /// Advance one sample and return the new value.+ #[inline]+ pub fn tick(&mut self) -> f32 {+ if self.remaining > 0 {+ self.remaining -= 1;+ if self.remaining == 0 {+ self.current = self.target;+ } else {+ self.current += self.step;+ }+ }+ self.current as f32+ }+ /// Current value without advancing.+ #[inline]+ pub fn value(&self) -> f32 {+ self.current as f32+ }+ pub fn target(&self) -> f32 {+ self.target as f32+ }+ pub fn is_smoothing(&self) -> bool {+ self.remaining > 0+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn ramps_linearly_and_lands_exactly() {+ let mut s = Smoothed::new(0.0, 4);+ s.set(1.0);+ let v: Vec<f32> = (0..6).map(|_| s.tick()).collect();+ assert_eq!(v, vec![0.25, 0.5, 0.75, 1.0, 1.0, 1.0]);+ assert!(!s.is_smoothing());+ }++ #[test]+ fn retarget_mid_ramp_is_continuous() {+ let mut s = Smoothed::new(0.0, 10);+ s.set(1.0);+ for _ in 0..5 {+ s.tick();+ }+ let mid = s.value();+ s.set(0.0);+ let n = s.tick();+ assert!((n - mid).abs() <= 0.1 + 1e-6);+ }++ #[test]+ fn zero_ramp_is_immediate() {+ let mut s = Smoothed::new(0.0, 0);+ s.set(3.0);+ assert_eq!(s.value(), 3.0);+ }+}