mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 09:08:11 +00:00
audio-dsp: finite filter designs at the limits; fix tails, thresholds and searches
- Complex division scales by the divisor's larger component, so a 24-pole band-pass at 1.536 MHz keeps its gain instead of going silent. - The elliptic selectivity comes from the nomes when k1 is below 1e-6, so 0.01 dB ripple with 150 dB attenuation designs a finite filter. - Fft::new rounds a size up to a power of two between 2 and 16 M points, and a transform leaves slices shorter than the size unchanged. - A NaN delay reads the newest sample instead of NaN. - Ducking activity reads its hop and limits as their decimals: a region of exactly min_on_s is kept, a gap of exactly bridge_s is not bridged, and a one-sample hop no longer drifts over a long envelope. - WSOLA searches every offset when the coarse pass finds no match. - Sync confidence compares the peak with the RMS over every lag, so a narrow max_lag can still give a reliable result; the coarse and refinement sizes are bounded. - measure() reports the file loudness range, counting the windows of 1.5 s of silence after the program (EBU Tech 3342). - Scientific Filter clears the sections an order change drops. - The click remover repairs a click in digital silence. - Flanger Special Effects subtracts the opposite sweep. - Phaser reports the tail of its all-pass ring.
This commit is contained in:
@@ -95,9 +95,18 @@ impl Mul for C {
|
||||
|
||||
impl Div for C {
|
||||
type Output = C;
|
||||
/// Smith's algorithm: the divisor is scaled by its larger component, so no intermediate
|
||||
/// squares it and a divisor above about 1e154 does not overflow to infinity.
|
||||
fn div(self, o: C) -> C {
|
||||
let d = o.re * o.re + o.im * o.im;
|
||||
C::new((self.re * o.re + self.im * o.im) / d, (self.im * o.re - self.re * o.im) / d)
|
||||
if o.re.abs() >= o.im.abs() {
|
||||
let r = o.im / o.re;
|
||||
let d = o.re + o.im * r;
|
||||
C::new((self.re + self.im * r) / d, (self.im - self.re * r) / d)
|
||||
} else {
|
||||
let r = o.re / o.im;
|
||||
let d = o.re * r + o.im;
|
||||
C::new((self.re * r + self.im) / d, (self.im * r - self.re) / d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -335,19 +344,58 @@ fn asne(w: C, k: f64) -> C {
|
||||
C::real(1.0).sub(acde(w, k))
|
||||
}
|
||||
|
||||
/// Arithmetic-geometric mean of `a` and `b` (both ≥ 0).
|
||||
fn agm(a: f64, b: f64) -> f64 {
|
||||
let (mut a, mut b) = (a, b);
|
||||
for _ in 0..64 {
|
||||
if (a - b).abs() <= 1e-15 * a {
|
||||
break;
|
||||
}
|
||||
(a, b) = (0.5 * (a + b), (a * b).sqrt());
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
/// Selectivity modulus `k` that the degree equation gives for order `n` and discrimination
|
||||
/// modulus `k1` (Orfanidis, "Lecture Notes on Elliptic Filter Design", 2006, `ellipdeg`).
|
||||
/// Below `k1` = 1e-6, `1 − k1²` rounds toward 1 and the product form below gives `k = 0`, so
|
||||
/// `k` comes from the nomes instead: q = q1^(1/N), with q1 = exp(−π·K′(k1)/K(k1)).
|
||||
fn selectivity(n: usize, k1: f64) -> f64 {
|
||||
if k1 < 1e-6 { selectivity_from_nome(n, k1) } else { selectivity_from_product(n, k1) }
|
||||
}
|
||||
|
||||
fn selectivity_from_nome(n: usize, k1: f64) -> f64 {
|
||||
let kk = PI / (2.0 * agm(1.0, (1.0 - k1 * k1).sqrt()));
|
||||
let kkp = PI / (2.0 * agm(1.0, k1));
|
||||
let q = (-PI * kkp / (kk * n as f64)).exp();
|
||||
// k = 4·√q · (Σ_{m≥0} q^(m(m+1)))² / (1 + 2·Σ_{m≥1} q^(m²))²
|
||||
let (mut num, mut den) = (0.0f64, 1.0f64);
|
||||
for m in 0..16i32 {
|
||||
num += q.powi(m * (m + 1));
|
||||
if m > 0 {
|
||||
den += 2.0 * q.powi(m * m);
|
||||
}
|
||||
}
|
||||
(4.0 * q.sqrt() * num * num / (den * den)).min(1.0)
|
||||
}
|
||||
|
||||
fn selectivity_from_product(n: usize, k1: f64) -> f64 {
|
||||
let k1p = (1.0 - k1 * k1).sqrt();
|
||||
// Degree equation: k' = k1'^N · Π sn⁴(u_i K', k1').
|
||||
let mut kp = k1p.powi(n as i32);
|
||||
for i in 1..=n / 2 {
|
||||
let ui = (2 * i - 1) as f64 / n as f64;
|
||||
kp *= sne(C::real(ui), k1p).re.powi(4);
|
||||
}
|
||||
(1.0 - kp * kp).max(0.0).sqrt()
|
||||
}
|
||||
|
||||
fn elliptic(n: usize, rp: f64, rs: f64) -> Zpk {
|
||||
let ep = (10f64.powf(rp / 10.0) - 1.0).sqrt();
|
||||
let es = (10f64.powf(rs / 10.0) - 1.0).sqrt();
|
||||
let k1 = ep / es;
|
||||
let k1p = (1.0 - k1 * k1).sqrt();
|
||||
let l = n / 2;
|
||||
// Degree equation: k' = k1'^N · Π sn⁴(u_i K', k1').
|
||||
let mut kp = k1p.powi(n as i32);
|
||||
for i in 1..=l {
|
||||
let ui = (2 * i - 1) as f64 / n as f64;
|
||||
kp *= sne(C::real(ui), k1p).re.powi(4);
|
||||
}
|
||||
let k = (1.0 - kp * kp).max(0.0).sqrt();
|
||||
let k = selectivity(n, k1);
|
||||
// v0 = −j·asn(j/εp, k1) / N (normalized).
|
||||
let a = asne(C::new(0.0, 1.0 / ep), k1);
|
||||
let v0 = C::new(a.im, -a.re).scale(1.0 / n as f64); // −j·a/N
|
||||
@@ -759,10 +807,43 @@ mod tests {
|
||||
// sn(K, k) = 1; cd(0, k) = 1
|
||||
assert!((sne(C::real(1.0), 0.7).re - 1.0).abs() < 1e-9);
|
||||
assert!((cde(C::real(0.0), 0.7).re - 1.0).abs() < 1e-9);
|
||||
// A divisor whose squared components overflow still divides.
|
||||
let q = C::new(3e200, 4e200).div(C::new(6e200, -8e200));
|
||||
assert!((q.re + 0.14).abs() < 1e-12 && (q.im - 0.48).abs() < 1e-12, "{q:?}");
|
||||
let u = asne(C::real(0.5), 0.7);
|
||||
assert!((sne(u, 0.7).re - 0.5).abs() < 1e-9);
|
||||
}
|
||||
|
||||
/// At 1.536 MHz the 24-pole band-pass's bilinear denominator exceeds 1e155, whose square
|
||||
/// overflowed: the gain came out 0 and the filter silent.
|
||||
#[test]
|
||||
fn a_high_order_band_pass_at_a_high_rate_keeps_its_gain() {
|
||||
let sr = 1_536_000.0;
|
||||
let s = design(&spec(Family::Butterworth, Band::BandPass, MAX_ORDER, 1000.0, 2000.0), sr);
|
||||
let center = s.magnitude_db(1414.2, sr);
|
||||
assert!(center.is_finite() && center.abs() < 0.5, "center {center} dB");
|
||||
assert!(s.magnitude_db(100.0, sr) < -100.0, "{}", s.magnitude_db(100.0, sr));
|
||||
}
|
||||
|
||||
/// With 0.01 dB ripple and 150 dB attenuation, 1 − k1² rounds to 1; the degree equation then
|
||||
/// gave a selectivity of 0 and every coefficient came out non-finite.
|
||||
#[test]
|
||||
fn elliptic_at_the_attenuation_limits_is_finite() {
|
||||
for n in 1..=MAX_ORDER {
|
||||
let s = design(&Spec { ripple_db: 0.01, stop_db: 150.0, ..spec(Family::Elliptic, Band::LowPass, n, 1000.0, 0.0) }, SR);
|
||||
assert!(s.as_slice().iter().all(|c| [c.b0, c.b1, c.b2, c.a1, c.a2].iter().all(|v| v.is_finite())), "n={n}");
|
||||
let pass = s.magnitude_db(300.0, SR);
|
||||
assert!(pass.is_finite() && pass > -0.02 && pass < 1e-6, "n={n}: {pass}");
|
||||
}
|
||||
// The nome form agrees with the degree equation where both are accurate.
|
||||
for n in [2, 5, 8, 12] {
|
||||
for k1 in [1e-5, 1e-4, 1e-3] {
|
||||
let (a, b) = (selectivity_from_nome(n, k1), selectivity_from_product(n, k1));
|
||||
assert!(((a - b) / b).abs() < 1e-6, "n={n} k1={k1}: {a} vs {b}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_ripple_and_sample_rates_give_a_finite_filter() {
|
||||
for family in [Family::Chebyshev, Family::Elliptic] {
|
||||
|
||||
@@ -59,9 +59,13 @@ pub fn envelope_db(channels: &[&[f32]], sample_rate: f32, hop_s: f32, window_s:
|
||||
/// `bridge_s` are merged first, then regions shorter than `min_on_s` are dropped. A frame `k`
|
||||
/// covers `[k·hop, (k+1)·hop)`. For an envelope from [`envelope_db`], pass
|
||||
/// [`envelope_hop_s`] as `hop_s`.
|
||||
///
|
||||
/// `hop_s`, `min_on_s` and `bridge_s` are each read as the shortest decimal that gives the same
|
||||
/// `f32` (0.01 is exactly 0.01 s), and every time is a whole number of hops computed in `f64`, so
|
||||
/// a duration that equals a limit compares as equal and the times do not drift over a long
|
||||
/// envelope.
|
||||
pub fn activity(env_db: &[f32], hop_s: f32, threshold_db: f32, min_on_s: f32, bridge_s: f32) -> Vec<(f64, f64)> {
|
||||
// the f32 hop rounded to whole 10 ns, so 0.01 means exactly 0.01 s
|
||||
let hop = (hop_s as f64 * 1e8).round() / 1e8;
|
||||
let (hop, min_on_s, bridge_s) = (decimal(hop_s), decimal(min_on_s), decimal(bridge_s));
|
||||
let mut raw: Vec<(f64, f64)> = Vec::new();
|
||||
let mut start: Option<usize> = None;
|
||||
for (k, &v) in env_db.iter().enumerate() {
|
||||
@@ -80,14 +84,20 @@ pub fn activity(env_db: &[f32], hop_s: f32, threshold_db: f32, min_on_s: f32, br
|
||||
let mut merged: Vec<(f64, f64)> = Vec::new();
|
||||
for r in raw {
|
||||
match merged.last_mut() {
|
||||
Some(last) if r.0 - last.1 < bridge_s as f64 - 1e-9 => last.1 = r.1,
|
||||
Some(last) if r.0 - last.1 < bridge_s - 1e-9 => last.1 = r.1,
|
||||
_ => merged.push(r),
|
||||
}
|
||||
}
|
||||
merged.retain(|(a, b)| b - a >= min_on_s as f64 - 1e-9);
|
||||
merged.retain(|(a, b)| b - a >= min_on_s - 1e-9);
|
||||
merged
|
||||
}
|
||||
|
||||
/// `v` as the shortest decimal that rounds to it, in `f64` (`0.01f32` becomes `0.01`, not
|
||||
/// `0.009999999776`).
|
||||
fn decimal(v: f32) -> f64 {
|
||||
v.to_string().parse().unwrap_or(f64::from(v))
|
||||
}
|
||||
|
||||
/// Ducking sensitivity (0…10) → detection threshold in dBFS:
|
||||
/// `−20 − 4·s` (5 → −40 dBFS; higher sensitivity reacts to quieter triggers).
|
||||
pub fn sensitivity_threshold_db(sensitivity: f32) -> f32 {
|
||||
@@ -287,6 +297,29 @@ mod tests {
|
||||
assert!(e.iter().skip(2).all(|v| (v - 20.0 * 0.5f32.log10()).abs() < 0.1), "{e:?}");
|
||||
}
|
||||
|
||||
/// A region of exactly `min_on_s` is kept and a gap of exactly `bridge_s` is not bridged: both
|
||||
/// limits are strict, and the f32 limits used to compare a little above their decimals.
|
||||
#[test]
|
||||
fn durations_equal_to_the_limits_compare_as_equal() {
|
||||
let on = |frames: &[bool]| frames.iter().map(|&a| if a { 0.0 } else { FLOOR_DB }).collect::<Vec<f32>>();
|
||||
let ten = on(&[[false; 5].as_slice(), &[true; 10], &[false; 5]].concat());
|
||||
assert_eq!(activity(&ten, 0.01, -40.0, 0.1, 0.0), vec![(0.05, 0.15)]);
|
||||
let gap = on(&[[true; 10].as_slice(), &[false; 20], &[true; 10]].concat());
|
||||
assert_eq!(activity(&gap, 0.01, -40.0, 0.0, 0.2), vec![(0.0, 0.1), (0.3, 0.4)]);
|
||||
assert_eq!(activity(&gap, 0.01, -40.0, 0.0, 0.21), vec![(0.0, 0.4)]);
|
||||
}
|
||||
|
||||
/// At 44.1 kHz a one-sample hop rounded to 10 ns was 22.68 µs, so the end of a 60 s envelope
|
||||
/// landed at 60.011 s.
|
||||
#[test]
|
||||
fn a_one_sample_hop_does_not_drift() {
|
||||
let frames = 60 * 44_100;
|
||||
let hop = envelope_hop_s(44_100.0, 0.0, frames);
|
||||
let r = activity(&vec![0.0f32; frames], hop, -40.0, 0.0, 0.0);
|
||||
assert_eq!(r.len(), 1);
|
||||
assert!(r[0].0 == 0.0 && (r[0].1 - 60.0).abs() < 1e-5, "{r:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regions_stay_on_the_audio_when_the_hop_is_not_whole_samples() {
|
||||
// 15 ms at 44.1 kHz is 661.5 samples; the envelope steps 662.
|
||||
|
||||
@@ -144,8 +144,10 @@ fn every_effect_is_deterministic_and_latency_is_constant() {
|
||||
#[test]
|
||||
fn latency_is_where_the_impulse_lands() {
|
||||
// Effects with latency: an impulse comes out exactly `latency` samples later at neutral
|
||||
// settings (FFT filter / convolution / click remover / existing STFT effects).
|
||||
for (id, p) in [("fft_filter", vec![]), ("convolution_reverb", vec![("mix", 0.0)]), ("click_remover", vec![("threshold", 100.0)])] {
|
||||
// settings (FFT filter / convolution / existing STFT effects). The click remover repairs a
|
||||
// lone impulse in silence as a click, so its latency is checked on noise by
|
||||
// `neutral_settings_are_delayed_identity`.
|
||||
for (id, p) in [("fft_filter", vec![]), ("convolution_reverb", vec![("mix", 0.0)])] {
|
||||
let mut e = fx(id, &p);
|
||||
let lat = e.latency();
|
||||
assert!(lat > 0, "{id}");
|
||||
@@ -212,6 +214,22 @@ fn scientific_filter_matches_its_design() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Lowering the order left the dropped sections holding the earlier audio; raising it again
|
||||
/// played that audio back as a burst after a second of silence.
|
||||
#[test]
|
||||
fn scientific_filter_order_changes_start_new_sections_clean() {
|
||||
let mut e = fx("scientific_filter", &[("type", 1.0), ("order", 8.0)]);
|
||||
let x = noise(21, SR as usize / 2, 0.5);
|
||||
run(e.as_mut(), &x, &x);
|
||||
assert!(e.set_param("order", 2.0));
|
||||
let quiet = vec![0.0f32; SR as usize];
|
||||
run(e.as_mut(), &quiet, &quiet);
|
||||
assert!(e.set_param("order", 8.0));
|
||||
let (y, _) = run(e.as_mut(), &quiet, &quiet);
|
||||
let peak = y.iter().fold(0.0f32, |a, v| a.max(v.abs()));
|
||||
assert!(peak < 1e-6, "burst of {peak} after the order rose");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fft_filter_applies_its_curve() {
|
||||
let mut e = fx("fft_filter", &[("p5_gain", -30.0), ("interp", 0.0)]);
|
||||
@@ -307,6 +325,33 @@ fn flanger_static_comb_notch() {
|
||||
assert!(tone_db(e.as_mut(), 2.0 * notch, 0.3).abs() < 0.2);
|
||||
}
|
||||
|
||||
/// Special Effects subtracts the opposite sweep: with equal sweep ends both reads match and the
|
||||
/// wet signal cancels. It used to keep half of the normal sweep.
|
||||
#[test]
|
||||
fn flanger_special_mode_subtracts_the_opposite_sweep() {
|
||||
let mut e = fx("flanger", &[("initial_delay", 2.0), ("final_delay", 2.0), ("feedback", 0.0), ("mix", 100.0), ("special", 1.0)]);
|
||||
let x = noise(12, SR as usize / 4, 0.5);
|
||||
let (y, _) = run(e.as_mut(), &x, &x);
|
||||
let peak = y.iter().fold(0.0f32, |a, v| a.max(v.abs()));
|
||||
assert!(peak < 1e-6, "{peak}");
|
||||
}
|
||||
|
||||
/// The phaser reported no tail, so an offline render stopped while its all-pass chain still rang.
|
||||
#[test]
|
||||
fn phaser_tail_covers_its_ring() {
|
||||
for (fb, upper, depth) in [(0.0, 2500.0, 70.0), (60.0, 2500.0, 70.0), (-90.0, 2500.0, 70.0), (90.0, 12000.0, 0.0)] {
|
||||
let mut e = fx("phaser", &[("mix", 100.0), ("feedback", fb), ("stages", 12.0), ("upper_freq", upper), ("depth", depth)]);
|
||||
let tail = e.tail_samples();
|
||||
assert!(tail > 0, "feedback {fb}");
|
||||
let mut x = vec![0.0f32; tail + 4800];
|
||||
x[0] = 1.0;
|
||||
let (y, _) = run(e.as_mut(), &x, &x);
|
||||
let peak = y.iter().fold(0.0f32, |a, v| a.max(v.abs()));
|
||||
let after = y[tail..].iter().fold(0.0f32, |a, v| a.max(v.abs()));
|
||||
assert!(after < 1e-3 * peak, "feedback {fb}: {after} after a tail of {tail} (peak {peak})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chorus_flanger_and_phaser_modulate() {
|
||||
for id in ["chorus_flanger", "phaser"] {
|
||||
@@ -670,6 +715,23 @@ fn click_remover_keeps_a_non_finite_sample_as_silence() {
|
||||
assert!(click < 0.1, "the click next to the NaN was left at {click}");
|
||||
}
|
||||
|
||||
/// In digital silence the residual's median is 0, and a zero σ skipped the repair: the click
|
||||
/// came out unchanged. All-zero input still comes out as exact silence.
|
||||
#[test]
|
||||
fn click_remover_repairs_a_click_in_silence() {
|
||||
let n = SR as usize / 2;
|
||||
let mut x = vec![0.0f32; n];
|
||||
x[6000] = 0.8;
|
||||
let mut e = fx("click_remover", &[]);
|
||||
let lat = e.latency();
|
||||
let (y, _) = run(e.as_mut(), &x, &x);
|
||||
let peak = y.iter().fold(0.0f32, |a, v| a.max(v.abs()));
|
||||
assert!(peak < 0.1, "the click came out at {peak} (sample {})", 6000 + lat);
|
||||
let zero = vec![0.0f32; n];
|
||||
let (y, _) = run(e.as_mut(), &zero, &zero);
|
||||
assert!(y.iter().all(|v| v.to_bits() == 0), "silence did not stay exact");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_and_stereo_tools() {
|
||||
let n = 4800;
|
||||
|
||||
@@ -142,10 +142,10 @@ impl ClickRemover {
|
||||
let valid = &mut s.sorted[p..];
|
||||
let mid = valid.len() / 2;
|
||||
valid.select_nth_unstable_by(mid, |x, y| x.total_cmp(y));
|
||||
let sigma = valid[mid] / 0.6745;
|
||||
if sigma <= 1e-9 {
|
||||
return 0;
|
||||
}
|
||||
// A background the predictor matches exactly (digital silence) has a median residual of
|
||||
// 0; the floor of 1e-6 (−120 dBFS) still lets a click in it stand out. An all-zero span
|
||||
// never gets here: `lpc` turns it away, so it stays exact silence.
|
||||
let sigma = (valid[mid] / 0.6745).max(1e-6);
|
||||
let thr = k * sigma;
|
||||
s.marks.iter_mut().for_each(|m| *m = false);
|
||||
let mut n = CONTEXT;
|
||||
|
||||
@@ -495,6 +495,12 @@ impl ScientificFilter {
|
||||
fn redesign(&mut self) {
|
||||
let (f1, f2) = (2f64.powf(self.f1.value() as f64), 2f64.powf(self.f2.value() as f64));
|
||||
self.sections = design::realize(&self.proto, self.band, f1, f2, self.sr as f64);
|
||||
// Sections past the cascade stop running; clear them so a later, higher order starts
|
||||
// them from silence instead of from the audio they held before.
|
||||
let active = self.sections.as_slice().len();
|
||||
for st in &mut self.state {
|
||||
st.iter_mut().skip(active).for_each(Biquad::reset);
|
||||
}
|
||||
self.dirty = self.f1.is_smoothing() || self.f2.is_smoothing();
|
||||
}
|
||||
|
||||
|
||||
@@ -226,7 +226,7 @@ impl AudioEffect for Flanger {
|
||||
let y = line.read(d0 + (d1 - d0) * shape(p));
|
||||
let wet = if special {
|
||||
let y2 = line.read(d0 + (d1 - d0) * shape(wrap_phase(p + 0.5)));
|
||||
0.5 * (y - y2) + 0.5 * y
|
||||
0.5 * (y - y2)
|
||||
} else {
|
||||
y
|
||||
};
|
||||
@@ -306,6 +306,19 @@ impl Phaser {
|
||||
|
||||
impl AudioEffect for Phaser {
|
||||
param_plumbing!("phaser");
|
||||
/// The all-pass ring of the lowest frequency the sweep reaches: each stage's pole has a time
|
||||
/// constant τ, the cascade of `stages` poles falls 60 dB within (6.9 + 2·stages)·τ, and each
|
||||
/// pass around the feedback loop repeats that ring at the feedback gain.
|
||||
fn tail_samples(&self) -> usize {
|
||||
let stages = ((self.pv.v("stages").round() as usize / 2) * 2).clamp(2, MAX_STAGES) as f64;
|
||||
let lowest = self.pv.v("upper_freq") * 2f32.powf(-6.0 * self.pv.v("depth") / 100.0);
|
||||
let pole = AllPass1::coef(lowest, self.sr).abs().min(1.0 - 1e-12);
|
||||
// Each stage delays by at least one sample, also when its pole is at 0.
|
||||
let tau = (-1.0 / pole.ln()).max(1.0);
|
||||
let fb = (0.9 * self.pv.v("feedback").abs() / 100.0) as f64;
|
||||
let repeats = if fb > 0.0 { (0.001f64.ln() / fb.ln()).ceil() + 1.0 } else { 1.0 };
|
||||
super::util::tail_samples(((6.9 + 2.0 * stages) * tau * repeats / self.sr as f64) as f32, self.sr)
|
||||
}
|
||||
fn reset(&mut self) {
|
||||
self.ap.iter_mut().for_each(|a| a.iter_mut().for_each(AllPass1::reset));
|
||||
self.fbs.iter_mut().for_each(|v| *v = 0.0);
|
||||
|
||||
@@ -69,11 +69,12 @@ impl DelayLine {
|
||||
pub(crate) fn max_delay(&self) -> f32 {
|
||||
(self.buf.len() - 3) as f32
|
||||
}
|
||||
/// Sample written `d` samples ago (`d` ≥ 0; 0 = the sample written by the last `push`).
|
||||
/// Sample written `d` samples ago (`d` ≥ 0; 0 = the sample written by the last `push`). A NaN
|
||||
/// delay reads as 0.
|
||||
#[inline]
|
||||
pub(crate) fn read(&self, d: f32) -> f32 {
|
||||
let len = self.buf.len();
|
||||
let d = d.clamp(0.0, self.max_delay());
|
||||
let d = if d.is_nan() { 0.0 } else { d.clamp(0.0, self.max_delay()) };
|
||||
let di = d.floor();
|
||||
let frac = d - di;
|
||||
// `w < len` and `di <= len - 3`, so one conditional subtract wraps the index.
|
||||
@@ -279,7 +280,7 @@ mod tests {
|
||||
fn delay_read_matches_modulo_indexing() {
|
||||
let reference = |line: &DelayLine, d: f32| {
|
||||
let len = line.buf.len();
|
||||
let d = d.clamp(0.0, line.max_delay());
|
||||
let d = if d.is_nan() { 0.0 } else { d.clamp(0.0, line.max_delay()) };
|
||||
let di = d.floor();
|
||||
let frac = d - di;
|
||||
let i0 = (line.w + len - 1 - di as usize) % len;
|
||||
@@ -293,6 +294,8 @@ mod tests {
|
||||
for d in (-8..=4 * max as i32 + 12).map(|i| i as f32 * 0.25).chain([f32::NAN, f32::INFINITY, -f32::INFINITY, 1e30]) {
|
||||
assert_eq!(line.read(d).to_bits(), reference(&line, d).to_bits(), "max {max} w {} d {d}", line.w);
|
||||
}
|
||||
// A NaN delay reads the newest sample, not NaN.
|
||||
assert_eq!(line.read(f32::NAN).to_bits(), line.tap(0).to_bits(), "max {max} w {}", line.w);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,9 +19,10 @@ pub struct Fft {
|
||||
}
|
||||
|
||||
impl Fft {
|
||||
/// Plan an FFT of size `n` (must be a power of two ≥ 2).
|
||||
/// Plan an FFT of size `n`. A size that is not a power of two is rounded up to the next one,
|
||||
/// and the size is kept between 2 and [`Fft::MAX_SIZE`].
|
||||
pub fn new(n: usize) -> Fft {
|
||||
assert!(n >= 2 && n.is_power_of_two(), "FFT size must be a power of two");
|
||||
let n = n.clamp(2, Self::MAX_SIZE).next_power_of_two();
|
||||
let bits = n.trailing_zeros();
|
||||
let rev = (0..n as u32).map(|i| i.reverse_bits() >> (32 - bits)).collect();
|
||||
let (mut tw_re, mut tw_im) = (Vec::with_capacity(n - 1), Vec::with_capacity(n - 1));
|
||||
@@ -39,19 +40,32 @@ impl Fft {
|
||||
Fft { n, tw_re, tw_im, tw_im_inv, rev }
|
||||
}
|
||||
|
||||
/// Forward transform (e^{-iωt}), unscaled.
|
||||
/// Largest size [`Fft::new`] plans (16 M points; the plan then holds 256 MiB).
|
||||
pub const MAX_SIZE: usize = 1 << 24;
|
||||
|
||||
/// The transform size.
|
||||
#[cfg(test)]
|
||||
pub fn size(&self) -> usize {
|
||||
self.n
|
||||
}
|
||||
|
||||
/// Forward transform (e^{-iωt}), unscaled, of the first `size` values of `re` and `im`. When
|
||||
/// either slice is shorter than the size, both are left unchanged.
|
||||
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).
|
||||
/// Inverse transform (e^{+iωt}), unscaled (divide by the size yourself). When either slice
|
||||
/// is shorter than the size, both are left unchanged.
|
||||
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);
|
||||
if re.len() < n || im.len() < n {
|
||||
return;
|
||||
}
|
||||
let (re, im) = (&mut re[..n], &mut im[..n]);
|
||||
for i in 0..n {
|
||||
let j = self.rev[i] as usize;
|
||||
@@ -122,6 +136,21 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A size that is not a power of two, or below 2, is rounded up; short slices are left
|
||||
/// unchanged. Both used to panic.
|
||||
#[test]
|
||||
fn odd_sizes_and_short_slices_do_not_panic() {
|
||||
assert_eq!(Fft::new(0).size(), 2);
|
||||
assert_eq!(Fft::new(1).size(), 2);
|
||||
assert_eq!(Fft::new(48).size(), 64);
|
||||
assert_eq!(Fft::new(64).size(), 64);
|
||||
let fft = Fft::new(8);
|
||||
let (mut re, mut im) = (vec![1.0f32; 4], vec![0.0f32; 8]);
|
||||
fft.forward(&mut re, &mut im);
|
||||
fft.inverse(&mut re, &mut im);
|
||||
assert_eq!((re, im), (vec![1.0f32; 4], vec![0.0f32; 8]));
|
||||
}
|
||||
|
||||
/// The previous kernel (strided reads from one n/2-entry twiddle table), kept as reference.
|
||||
fn run_reference(n: usize, re: &mut [f32], im: &mut [f32], inverse: bool) {
|
||||
let rev: Vec<u32> = (0..n as u32).map(|i| i.reverse_bits() >> (32 - n.trailing_zeros())).collect();
|
||||
|
||||
@@ -492,6 +492,23 @@ impl LoudnessMeter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Loudness range of the program as a file measurement: the short-term windows of 1.5 s of
|
||||
/// silence after the audio fed so far are counted too, as EBU Tech 3342 asks for file-based
|
||||
/// measurement, so a program of only a few seconds gets more than one window. The meter
|
||||
/// itself is unchanged: [`LoudnessMeter::loudness_range`] and audio fed afterwards do not see
|
||||
/// the silence.
|
||||
pub fn file_loudness_range(&self) -> f64 {
|
||||
let mut tail = self.clone();
|
||||
let silence = vec![0.0f32; self.sub_len];
|
||||
let mut left = (self.sub_len - self.sub_pos) + 15 * self.sub_len;
|
||||
while left > 0 {
|
||||
let take = left.min(self.sub_len);
|
||||
tail.process(&[&silence[..take]]);
|
||||
left -= take;
|
||||
}
|
||||
tail.loudness_range()
|
||||
}
|
||||
|
||||
/// Snapshot of all program measurements.
|
||||
pub fn summary(&self) -> LoudnessSummary {
|
||||
LoudnessSummary {
|
||||
@@ -516,12 +533,13 @@ pub struct LoudnessSummary {
|
||||
pub true_peak_dbtp: f64,
|
||||
}
|
||||
|
||||
/// Measure a whole planar program in one call.
|
||||
/// Measure a whole planar program in one call. The loudness range is the file measurement of
|
||||
/// [`LoudnessMeter::file_loudness_range`].
|
||||
pub fn measure(channels: &[&[f32]], sample_rate: f64) -> LoudnessSummary {
|
||||
let mut m = LoudnessMeter::new(sample_rate, channels.len());
|
||||
m.process(channels);
|
||||
m.end_program();
|
||||
m.summary()
|
||||
LoudnessSummary { loudness_range_lu: m.file_loudness_range(), ..m.summary() }
|
||||
}
|
||||
|
||||
/// Gain (dB) that moves a program measured at `measured_lufs` to `target_lufs`.
|
||||
@@ -679,6 +697,26 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A 3 s program gives one short-term window, so its loudness range read 0 however much the
|
||||
/// level changed. The file measurement counts the windows of 1.5 s of silence after it.
|
||||
#[test]
|
||||
fn a_short_program_has_a_file_loudness_range() {
|
||||
let sr = 48000.0;
|
||||
let x = segments(1000.0, sr, &[(1.5, -20.0), (1.5, -30.0)]);
|
||||
let s = measure(&[&x, &x], sr);
|
||||
assert!(s.loudness_range_lu > 1.0, "LRA {}", s.loudness_range_lu);
|
||||
// The live reading and later audio do not see the silence.
|
||||
let mut m = LoudnessMeter::new(sr, 2);
|
||||
m.process(&[&x, &x]);
|
||||
let before = m.loudness_range();
|
||||
assert_eq!(before, 0.0);
|
||||
assert!((m.file_loudness_range() - s.loudness_range_lu).abs() < 1e-12);
|
||||
assert_eq!(m.loudness_range(), before);
|
||||
// A steady program keeps a file range near 0.
|
||||
let y = segments(1000.0, sr, &[(30.0, -20.0)]);
|
||||
assert!(measure(&[&y, &y], sr).loudness_range_lu < 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn log_sweep_matches_analytic_k_weighting() {
|
||||
let sr = 48000.0;
|
||||
|
||||
@@ -93,7 +93,19 @@ impl Wsola {
|
||||
}
|
||||
d += 2;
|
||||
}
|
||||
let Some((coarse, _)) = best else { return nominal };
|
||||
let Some((coarse, coarse_score)) = best else { return nominal };
|
||||
if coarse_score <= 0.0 {
|
||||
// The coarse pass found no match (for example, the template's energy sits on odd
|
||||
// samples only, which it skips): search every offset at full resolution instead.
|
||||
let mut full = None;
|
||||
for d in 0..=tol {
|
||||
consider(d, 1, &mut full);
|
||||
if d > 0 {
|
||||
consider(-d, 1, &mut full);
|
||||
}
|
||||
}
|
||||
return nominal.saturating_add(full.map_or(coarse, |(d, _)| d));
|
||||
}
|
||||
let mut fine = None;
|
||||
for d in [coarse, coarse - 1, coarse + 1] {
|
||||
if d.abs() <= tol {
|
||||
@@ -196,6 +208,17 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The template's only nonzero sample is at an odd index, so every coarse score was 0 and the
|
||||
/// search kept the nominal position next to an exact match 101 samples away.
|
||||
#[test]
|
||||
fn a_match_the_coarse_pass_skips_is_still_found() {
|
||||
let w = Wsola::new(48_000);
|
||||
let mut guide = vec![0.0f32; 4_000];
|
||||
guide[359] = 1.0;
|
||||
guide[2_460] = 1.0;
|
||||
assert_eq!(w.align(&guide, 0, 2_000), 2_101);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn silence_and_out_of_range_positions_keep_the_nominal_position() {
|
||||
let w = Wsola::new(48_000);
|
||||
|
||||
@@ -30,17 +30,24 @@ pub struct SyncOptions {
|
||||
pub max_lag: Option<i64>,
|
||||
/// Upper bound of the coarse search's sample rate (Hz).
|
||||
pub coarse_rate: u32,
|
||||
/// Most samples (both signals together) the coarse transform may hold, at least 4,096; longer
|
||||
/// recordings are decimated further, by at most [`MAX_DECIMATION`]. The coarse signals
|
||||
/// therefore hold the larger of this and 1/4,096 of the input, and the transform is the next
|
||||
/// power of two above that.
|
||||
/// Most samples (both signals together) the coarse transform may hold, from 4,096 to
|
||||
/// [`MAX_COARSE_SAMPLES`]; longer recordings are decimated further, by at most
|
||||
/// [`MAX_DECIMATION`]. The coarse signals therefore hold the larger of this and 1/4,096 of the
|
||||
/// input, and the transform is the next power of two above that. When that transform would
|
||||
/// exceed the FFT's largest size, [`find_offset`] returns `None`.
|
||||
pub max_coarse_samples: usize,
|
||||
/// PHAT weighting exponent (1 = full whitening, 0 = plain cross-correlation).
|
||||
pub phat_beta: f32,
|
||||
/// Length of the full-rate refinement window (samples).
|
||||
/// Length of the full-rate refinement window (samples), from 256 to [`MAX_REFINE_WINDOW`].
|
||||
pub refine_window: usize,
|
||||
}
|
||||
|
||||
/// Largest [`SyncOptions::max_coarse_samples`]; a larger value counts as this (8 M samples).
|
||||
pub const MAX_COARSE_SAMPLES: usize = 1 << 23;
|
||||
|
||||
/// Largest [`SyncOptions::refine_window`]; a larger value counts as this (4 M samples).
|
||||
pub const MAX_REFINE_WINDOW: usize = 1 << 22;
|
||||
|
||||
impl Default for SyncOptions {
|
||||
fn default() -> Self {
|
||||
Self { max_lag: None, coarse_rate: 8000, max_coarse_samples: 1 << 22, phat_beta: 0.75, refine_window: 1 << 17 }
|
||||
@@ -221,13 +228,16 @@ pub fn find_offset(a: &[f32], b: &[f32], sample_rate: u32, opts: &SyncOptions) -
|
||||
// ---- coarse
|
||||
// The factor `decimate` really applies to both signals, so the coarse lag scales back exactly.
|
||||
let d = (sr.div_ceil(opts.coarse_rate.max(500) as usize))
|
||||
.max((a.len() + b.len()).div_ceil(opts.max_coarse_samples.max(1 << 12)))
|
||||
.max((a.len() + b.len()).div_ceil(opts.max_coarse_samples.clamp(1 << 12, MAX_COARSE_SAMPLES)))
|
||||
.min(MAX_DECIMATION)
|
||||
.min(a.len().min(b.len()))
|
||||
.max(1);
|
||||
let (ca, cb) = (normalized_decimate(a, d), normalized_decimate(b, d));
|
||||
let (la, lb) = (ca.len() as i64, cb.len() as i64);
|
||||
let n = ((la + lb) as usize).next_power_of_two();
|
||||
if n > Fft::MAX_SIZE {
|
||||
return None;
|
||||
}
|
||||
let rate_c = sr as f32 / d as f32;
|
||||
let band = ((40.0 / rate_c).min(0.05), if d > 1 { 0.40 } else { 0.5 });
|
||||
let r = gcc(&ca, &cb, n, opts.phat_beta, band);
|
||||
@@ -239,24 +249,27 @@ pub fn find_offset(a: &[f32], b: &[f32], sample_rate: u32, opts: &SyncOptions) -
|
||||
if hi < lo {
|
||||
return None;
|
||||
}
|
||||
// The peak is taken within `max_lag`; the RMS it is compared with covers every lag with enough
|
||||
// overlap, so a narrow limit does not cap the confidence at √(lags in the limit).
|
||||
let mut best = (0i64, 0.0f32);
|
||||
let mut sum2 = 0.0f64;
|
||||
let mut count = 0usize;
|
||||
let mut inside = 0usize;
|
||||
for l in lo..=hi {
|
||||
let v = corr_at(&r, l);
|
||||
sum2 += (v as f64) * (v as f64);
|
||||
if max_lag_c.is_some_and(|m| l.abs() > m) {
|
||||
continue;
|
||||
}
|
||||
let v = corr_at(&r, l);
|
||||
sum2 += (v as f64) * (v as f64);
|
||||
count += 1;
|
||||
inside += 1;
|
||||
if v.abs() > best.1.abs() {
|
||||
best = (l, v);
|
||||
}
|
||||
}
|
||||
if count == 0 || best.1 == 0.0 {
|
||||
if inside == 0 || best.1 == 0.0 {
|
||||
return None;
|
||||
}
|
||||
let rms = (sum2 / count as f64).sqrt().max(1e-30) as f32;
|
||||
let count = (hi - lo + 1) as f64;
|
||||
let rms = (sum2 / count).sqrt().max(1e-30) as f32;
|
||||
let confidence = best.1.abs() / rms;
|
||||
let guard = ((rate_c * 0.05) as i64).max(2);
|
||||
let mut second = 0.0f32;
|
||||
@@ -277,7 +290,7 @@ pub fn find_offset(a: &[f32], b: &[f32], sample_rate: u32, opts: &SyncOptions) -
|
||||
if ov1 - ov0 < 16 {
|
||||
return Some(SyncResult { lag: coarse, lag_fine: coarse as f64, confidence, distinct, inverted });
|
||||
}
|
||||
let w = ((ov1 - ov0) as usize).min(opts.refine_window.max(256)) as i64;
|
||||
let w = ((ov1 - ov0) as usize).min(opts.refine_window.clamp(256, MAX_REFINE_WINDOW)) as i64;
|
||||
// the window of b with the most energy (both sides: a lag-shifted)
|
||||
let start = {
|
||||
let hop = (w / 4).max(1);
|
||||
@@ -561,6 +574,18 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// With a 100-sample limit at 48 kHz only 35 coarse lags lie inside it; the confidence was
|
||||
/// their peak over their own RMS, at most √35 ≈ 5.9, so even identical recordings were never
|
||||
/// `reliable()`.
|
||||
#[test]
|
||||
fn a_narrow_lag_limit_can_still_be_reliable() {
|
||||
let sr = 48_000;
|
||||
let s = speechy(sr as f64, 10.0, 5);
|
||||
let r = find_offset(&s, &s, sr, &SyncOptions { max_lag: Some(100), ..Default::default() }).unwrap();
|
||||
assert_eq!(r.lag, 0);
|
||||
assert!(r.reliable(), "{r:?}");
|
||||
}
|
||||
|
||||
/// A coarse budget that asks for more than [`MAX_DECIMATION`] still scales the coarse lag by
|
||||
/// the factor applied: 2 × 9 M samples at 8 kHz with a 4,096-sample budget asks for 4,395.
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user