Merge branch 'worktree-agent-a43a31d0be0dd0170'
Browse files at this commit2 changed files +368 -0
- crates/engine/src/eq.rs +367 -0
- crates/engine/src/lib.rs +1 -0
crates/engine/src/eq.rsadded+367 -0
| @@ -0,0 +1,367 @@ | ||
| 1 | +//! Per-segment audio equalizer: a cascade of RBJ biquads applied engine-side by | |
| 2 | +//! sample math. The effect has to live in our own samples, never in a device | |
| 3 | +//! property — a daemon-side gain would be invisible to an export and to anyone | |
| 4 | +//! reading the graph, and the RT callback is allocation-free either way. | |
| 5 | +//! | |
| 6 | +//! Coefficients follow the Audio EQ Cookbook (Robert Bristow-Johnson, | |
| 7 | +//! <https://www.w3.org/TR/audio-eq-cookbook/>), peaking and shelving sections, | |
| 8 | +//! run as transposed direct form II: two state words per band per channel, one | |
| 9 | +//! multiply-add chain per sample, nothing to allocate. | |
| 10 | +//! | |
| 11 | +//! [`EqParams::default_layout`] is a five-band starting point — shelves at the | |
| 12 | +//! edges (80 Hz, 12 kHz), where a peak would leave the last octave untouched, | |
| 13 | +//! and peaks at 250 Hz / 1 kHz / 4 kHz for mud, presence and air. It is only a | |
| 14 | +//! default: band count, frequency and kind are data, so a segment can carry any | |
| 15 | +//! layout the .edith file cares to write. | |
| 16 | + | |
| 17 | +use std::f64::consts::PI; | |
| 18 | + | |
| 19 | +/// Shape of one band's response. Shelves tilt everything past their corner; | |
| 20 | +/// a peak is local. | |
| 21 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 22 | +pub enum BandKind { | |
| 23 | + LowShelf, | |
| 24 | + Peak, | |
| 25 | + HighShelf, | |
| 26 | +} | |
| 27 | + | |
| 28 | +/// One band. Plain data with no invariants of its own: out-of-range values are | |
| 29 | +/// clamped when coefficients are built, so a deserializer can hand this over | |
| 30 | +/// unchecked. | |
| 31 | +#[derive(Debug, Clone, Copy, PartialEq)] | |
| 32 | +pub struct Band { | |
| 33 | + pub freq_hz: f32, | |
| 34 | + pub gain_db: f32, | |
| 35 | + /// Bandwidth for a peak, slope for a shelf. 0.707 is the flat-shelf value. | |
| 36 | + pub q: f32, | |
| 37 | + pub kind: BandKind, | |
| 38 | +} | |
| 39 | + | |
| 40 | +/// A segment's equalizer setting: the bands, in cascade order. | |
| 41 | +#[derive(Debug, Clone, PartialEq, Default)] | |
| 42 | +pub struct EqParams { | |
| 43 | + pub bands: Vec<Band>, | |
| 44 | +} | |
| 45 | + | |
| 46 | +impl EqParams { | |
| 47 | + /// The five-band default described in the module docs, all gains flat. | |
| 48 | + pub fn default_layout() -> Self { | |
| 49 | + let band = |freq_hz, kind| Band { | |
| 50 | + freq_hz, | |
| 51 | + gain_db: 0.0, | |
| 52 | + q: 0.707, | |
| 53 | + kind, | |
| 54 | + }; | |
| 55 | + Self { | |
| 56 | + bands: vec![ | |
| 57 | + band(80.0, BandKind::LowShelf), | |
| 58 | + band(250.0, BandKind::Peak), | |
| 59 | + band(1000.0, BandKind::Peak), | |
| 60 | + band(4000.0, BandKind::Peak), | |
| 61 | + band(12000.0, BandKind::HighShelf), | |
| 62 | + ], | |
| 63 | + } | |
| 64 | + } | |
| 65 | + | |
| 66 | + /// True when no band moves anything, so processing can be skipped outright. | |
| 67 | + pub fn is_identity(&self) -> bool { | |
| 68 | + self.bands.iter().all(|b| b.gain_db.abs() < 1e-4) | |
| 69 | + } | |
| 70 | +} | |
| 71 | + | |
| 72 | +/// Normalized biquad coefficients (a0 divided out). | |
| 73 | +#[derive(Debug, Clone, Copy, Default)] | |
| 74 | +struct Coeffs { | |
| 75 | + b0: f32, | |
| 76 | + b1: f32, | |
| 77 | + b2: f32, | |
| 78 | + a1: f32, | |
| 79 | + a2: f32, | |
| 80 | +} | |
| 81 | + | |
| 82 | +impl Coeffs { | |
| 83 | + /// Cookbook peaking/shelving section for `band` at `sample_rate`. | |
| 84 | + fn new(band: &Band, sample_rate: u32) -> Self { | |
| 85 | + // A frequency at or past Nyquist has no cookbook answer (sin(w0) folds), | |
| 86 | + // and Q of zero divides by zero: clamp rather than reject, the caller's | |
| 87 | + // value came out of a text file. | |
| 88 | + let fs = f64::from(sample_rate.max(1)); | |
| 89 | + let f0 = f64::from(band.freq_hz).clamp(1.0, fs * 0.49); | |
| 90 | + let q = f64::from(band.q).clamp(0.05, 40.0); | |
| 91 | + let a = 10f64.powf(f64::from(band.gain_db) / 40.0); | |
| 92 | + let w0 = 2.0 * PI * f0 / fs; | |
| 93 | + let (sin_w0, cos_w0) = (w0.sin(), w0.cos()); | |
| 94 | + let alpha = sin_w0 / (2.0 * q); | |
| 95 | + let two_sqrt_a_alpha = 2.0 * a.sqrt() * alpha; | |
| 96 | + | |
| 97 | + let (b0, b1, b2, a0, a1, a2) = match band.kind { | |
| 98 | + BandKind::Peak => ( | |
| 99 | + 1.0 + alpha * a, | |
| 100 | + -2.0 * cos_w0, | |
| 101 | + 1.0 - alpha * a, | |
| 102 | + 1.0 + alpha / a, | |
| 103 | + -2.0 * cos_w0, | |
| 104 | + 1.0 - alpha / a, | |
| 105 | + ), | |
| 106 | + BandKind::LowShelf => ( | |
| 107 | + a * ((a + 1.0) - (a - 1.0) * cos_w0 + two_sqrt_a_alpha), | |
| 108 | + 2.0 * a * ((a - 1.0) - (a + 1.0) * cos_w0), | |
| 109 | + a * ((a + 1.0) - (a - 1.0) * cos_w0 - two_sqrt_a_alpha), | |
| 110 | + (a + 1.0) + (a - 1.0) * cos_w0 + two_sqrt_a_alpha, | |
| 111 | + -2.0 * ((a - 1.0) + (a + 1.0) * cos_w0), | |
| 112 | + (a + 1.0) + (a - 1.0) * cos_w0 - two_sqrt_a_alpha, | |
| 113 | + ), | |
| 114 | + BandKind::HighShelf => ( | |
| 115 | + a * ((a + 1.0) + (a - 1.0) * cos_w0 + two_sqrt_a_alpha), | |
| 116 | + -2.0 * a * ((a - 1.0) + (a + 1.0) * cos_w0), | |
| 117 | + a * ((a + 1.0) + (a - 1.0) * cos_w0 - two_sqrt_a_alpha), | |
| 118 | + (a + 1.0) - (a - 1.0) * cos_w0 + two_sqrt_a_alpha, | |
| 119 | + 2.0 * ((a - 1.0) - (a + 1.0) * cos_w0), | |
| 120 | + (a + 1.0) - (a - 1.0) * cos_w0 - two_sqrt_a_alpha, | |
| 121 | + ), | |
| 122 | + }; | |
| 123 | + Self { | |
| 124 | + b0: (b0 / a0) as f32, | |
| 125 | + b1: (b1 / a0) as f32, | |
| 126 | + b2: (b2 / a0) as f32, | |
| 127 | + a1: (a1 / a0) as f32, | |
| 128 | + a2: (a2 / a0) as f32, | |
| 129 | + } | |
| 130 | + } | |
| 131 | +} | |
| 132 | + | |
| 133 | +/// Anything smaller than this is inaudible at any gain we allow, and letting it | |
| 134 | +/// stay would drag the state into denormals — where a decaying tail costs tens | |
| 135 | +/// of times what a live signal does on x86. Flushed to a hard zero instead. | |
| 136 | +const DENORMAL_FLOOR: f32 = 1e-20; | |
| 137 | + | |
| 138 | +/// A running equalizer: the coefficients plus one filter memory per band per | |
| 139 | +/// channel. Built off the UI thread, driven from the audio path. | |
| 140 | +pub struct EqState { | |
| 141 | + sample_rate: u32, | |
| 142 | + channels: usize, | |
| 143 | + coeffs: Vec<Coeffs>, | |
| 144 | + /// `[s1, s2]` per (band, channel), band-major. | |
| 145 | + state: Vec<[f32; 2]>, | |
| 146 | + /// All-flat params: [`process`](EqState::process) is then a no-op and the | |
| 147 | + /// samples come out bit-identical. | |
| 148 | + identity: bool, | |
| 149 | +} | |
| 150 | + | |
| 151 | +impl EqState { | |
| 152 | + /// Allocates coefficients and filter memory for `params`. `channels` is the | |
| 153 | + /// interleave width of the buffers [`process`](EqState::process) will see. | |
| 154 | + pub fn new(params: &EqParams, sample_rate: u32, channels: u16) -> Self { | |
| 155 | + let mut eq = Self { | |
| 156 | + sample_rate, | |
| 157 | + channels: (channels as usize).max(1), | |
| 158 | + coeffs: Vec::new(), | |
| 159 | + state: Vec::new(), | |
| 160 | + identity: true, | |
| 161 | + }; | |
| 162 | + eq.set_params(params); | |
| 163 | + eq | |
| 164 | + } | |
| 165 | + | |
| 166 | + /// Recomputes coefficients for edited params, keeping the filter memory so a | |
| 167 | + /// live segment does not click. Allocates — a UI edit, never the RT path. | |
| 168 | + pub fn set_params(&mut self, params: &EqParams) { | |
| 169 | + self.identity = params.is_identity(); | |
| 170 | + self.coeffs.clear(); | |
| 171 | + self.coeffs.extend( | |
| 172 | + params | |
| 173 | + .bands | |
| 174 | + .iter() | |
| 175 | + .map(|b| Coeffs::new(b, self.sample_rate)), | |
| 176 | + ); | |
| 177 | + self.state | |
| 178 | + .resize(self.coeffs.len() * self.channels, [0.0; 2]); | |
| 179 | + } | |
| 180 | + | |
| 181 | + /// Drops the filter memory: for a seek, where the samples either side of the | |
| 182 | + /// cut are unrelated and a carried tail would ring. | |
| 183 | + pub fn reset(&mut self) { | |
| 184 | + self.state.fill([0.0; 2]); | |
| 185 | + } | |
| 186 | + | |
| 187 | + /// Filters `interleaved` in place, `channels` values per frame. Allocation- | |
| 188 | + /// free and branch-light: safe to call from the feeder. | |
| 189 | + /// | |
| 190 | + /// A trailing partial frame is left alone rather than filtered into the | |
| 191 | + /// wrong channel's state. | |
| 192 | + pub fn process(&mut self, interleaved: &mut [f32]) { | |
| 193 | + if self.identity || self.coeffs.is_empty() { | |
| 194 | + return; | |
| 195 | + } | |
| 196 | + let channels = self.channels; | |
| 197 | + for (band, c) in self.coeffs.iter().enumerate() { | |
| 198 | + let state = &mut self.state[band * channels..][..channels]; | |
| 199 | + for frame in interleaved.chunks_exact_mut(channels) { | |
| 200 | + for (ch, x) in frame.iter_mut().enumerate() { | |
| 201 | + let s = &mut state[ch]; | |
| 202 | + let y = c.b0 * *x + s[0]; | |
| 203 | + s[0] = c.b1 * *x - c.a1 * y + s[1]; | |
| 204 | + s[1] = c.b2 * *x - c.a2 * y; | |
| 205 | + if s[0].abs() < DENORMAL_FLOOR { | |
| 206 | + s[0] = 0.0; | |
| 207 | + } | |
| 208 | + if s[1].abs() < DENORMAL_FLOOR { | |
| 209 | + s[1] = 0.0; | |
| 210 | + } | |
| 211 | + *x = y; | |
| 212 | + } | |
| 213 | + } | |
| 214 | + } | |
| 215 | + } | |
| 216 | +} | |
| 217 | + | |
| 218 | +#[cfg(test)] | |
| 219 | +mod tests { | |
| 220 | + use std::f32::consts::TAU; | |
| 221 | + | |
| 222 | + use super::{Band, BandKind, EqParams, EqState}; | |
| 223 | + | |
| 224 | + const FS: u32 = 48_000; | |
| 225 | + | |
| 226 | + fn peak(freq_hz: f32, gain_db: f32, q: f32) -> EqParams { | |
| 227 | + EqParams { | |
| 228 | + bands: vec![Band { | |
| 229 | + freq_hz, | |
| 230 | + gain_db, | |
| 231 | + q, | |
| 232 | + kind: BandKind::Peak, | |
| 233 | + }], | |
| 234 | + } | |
| 235 | + } | |
| 236 | + | |
| 237 | + fn sine(freq_hz: f32, frames: usize, channels: usize) -> Vec<f32> { | |
| 238 | + (0..frames * channels) | |
| 239 | + .map(|i| (TAU * freq_hz * (i / channels) as f32 / FS as f32).sin()) | |
| 240 | + .collect() | |
| 241 | + } | |
| 242 | + | |
| 243 | + /// RMS of the second half only: the first half is the filter's transient. | |
| 244 | + fn rms(samples: &[f32]) -> f32 { | |
| 245 | + let tail = &samples[samples.len() / 2..]; | |
| 246 | + (tail.iter().map(|v| v * v).sum::<f32>() / tail.len() as f32).sqrt() | |
| 247 | + } | |
| 248 | + | |
| 249 | + fn db(measured: f32, reference: f32) -> f32 { | |
| 250 | + 20.0 * (measured / reference).log10() | |
| 251 | + } | |
| 252 | + | |
| 253 | + #[test] | |
| 254 | + fn flat_params_pass_samples_through_bit_identical() { | |
| 255 | + let input = sine(440.0, 4800, 2); | |
| 256 | + let mut out = input.clone(); | |
| 257 | + EqState::new(&EqParams::default_layout(), FS, 2).process(&mut out); | |
| 258 | + assert_eq!(out, input, "a flat EQ must not touch the samples at all"); | |
| 259 | + | |
| 260 | + // ...and an explicitly built cascade of 0 dB bands is flat too, which is | |
| 261 | + // the case a serialized "EQ enabled, nothing moved" segment hits. | |
| 262 | + let mut params = EqParams::default_layout(); | |
| 263 | + params.bands[2].q = 4.0; | |
| 264 | + assert!(params.is_identity()); | |
| 265 | + } | |
| 266 | + | |
| 267 | + #[test] | |
| 268 | + fn a_band_moves_its_own_center_and_leaves_two_octaves_away_alone() { | |
| 269 | + for gain in [6.0, -6.0] { | |
| 270 | + let center = sine(1000.0, 48_000, 1); | |
| 271 | + let mut out = center.clone(); | |
| 272 | + EqState::new(&peak(1000.0, gain, 1.0), FS, 1).process(&mut out); | |
| 273 | + let at_center = db(rms(&out), rms(¢er)); | |
| 274 | + assert!( | |
| 275 | + (at_center - gain).abs() < 0.5, | |
| 276 | + "1 kHz sine through a {gain:+} dB band at 1 kHz measured {at_center:+.2} dB" | |
| 277 | + ); | |
| 278 | + | |
| 279 | + for off in [250.0, 4000.0] { | |
| 280 | + let away = sine(off, 48_000, 1); | |
| 281 | + let mut out = away.clone(); | |
| 282 | + EqState::new(&peak(1000.0, gain, 1.0), FS, 1).process(&mut out); | |
| 283 | + let leak = db(rms(&out), rms(&away)); | |
| 284 | + assert!( | |
| 285 | + leak.abs() < 1.0, | |
| 286 | + "{off} Hz is two octaves off but moved {leak:+.2} dB" | |
| 287 | + ); | |
| 288 | + } | |
| 289 | + } | |
| 290 | + } | |
| 291 | + | |
| 292 | + #[test] | |
| 293 | + fn ten_seconds_of_noise_through_every_band_boosted_stays_bounded() { | |
| 294 | + let mut params = EqParams::default_layout(); | |
| 295 | + for band in &mut params.bands { | |
| 296 | + band.gain_db = 12.0; | |
| 297 | + } | |
| 298 | + let mut eq = EqState::new(¶ms, FS, 2); | |
| 299 | + | |
| 300 | + // xorshift: a fixed white-noise source, no dev-dependency. | |
| 301 | + let mut seed = 0x2545_f491_4f6c_dd1du64; | |
| 302 | + let mut noise = || { | |
| 303 | + seed ^= seed << 13; | |
| 304 | + seed ^= seed >> 7; | |
| 305 | + seed ^= seed << 17; | |
| 306 | + (seed >> 40) as f32 / 8_388_608.0 - 1.0 | |
| 307 | + }; | |
| 308 | + | |
| 309 | + let mut peak = 0.0f32; | |
| 310 | + // Fed in 1024-frame blocks, as the feeder would: state must survive the | |
| 311 | + // block boundary, so a per-call reset would show up as clicks here. | |
| 312 | + for _ in 0..(10 * FS as usize / 1024) { | |
| 313 | + let mut block: Vec<f32> = (0..1024 * 2).map(|_| noise()).collect(); | |
| 314 | + eq.process(&mut block); | |
| 315 | + for v in block { | |
| 316 | + assert!(v.is_finite(), "EQ output went to {v}"); | |
| 317 | + peak = peak.max(v.abs()); | |
| 318 | + } | |
| 319 | + } | |
| 320 | + // +12 dB on five overlapping bands is about 4x on the worst-case sum of | |
| 321 | + // a full-scale input; anything past that is instability, not gain. | |
| 322 | + assert!( | |
| 323 | + (1.0..20.0).contains(&peak), | |
| 324 | + "peak {peak} out of the plausible band for +12 dB x5" | |
| 325 | + ); | |
| 326 | + } | |
| 327 | + | |
| 328 | + #[test] | |
| 329 | + fn a_decaying_tail_leaves_the_state_at_a_hard_zero() { | |
| 330 | + let mut params = EqParams::default_layout(); | |
| 331 | + params.bands[1].gain_db = 9.0; | |
| 332 | + let mut eq = EqState::new(¶ms, FS, 2); | |
| 333 | + | |
| 334 | + let mut decay: Vec<f32> = (0..4800 * 2) | |
| 335 | + .map(|i| 0.9f32.powi(i / 2) * if i % 2 == 0 { 1.0 } else { -1.0 }) | |
| 336 | + .collect(); | |
| 337 | + eq.process(&mut decay); | |
| 338 | + let mut silence = vec![0.0f32; 4800 * 2]; | |
| 339 | + eq.process(&mut silence); | |
| 340 | + | |
| 341 | + for (i, s) in eq.state.iter().enumerate() { | |
| 342 | + assert!( | |
| 343 | + s[0] == 0.0 && s[1] == 0.0, | |
| 344 | + "state {i} still holds {s:?} after a decayed tail — denormal territory" | |
| 345 | + ); | |
| 346 | + } | |
| 347 | + } | |
| 348 | + | |
| 349 | + #[test] | |
| 350 | + fn an_impulse_in_the_left_channel_never_reaches_the_right() { | |
| 351 | + let mut params = EqParams::default_layout(); | |
| 352 | + params.bands[3].gain_db = -10.0; | |
| 353 | + let mut eq = EqState::new(¶ms, FS, 2); | |
| 354 | + | |
| 355 | + let mut buf = vec![0.0f32; 512 * 2]; | |
| 356 | + buf[0] = 1.0; | |
| 357 | + eq.process(&mut buf); | |
| 358 | + | |
| 359 | + assert!(buf[2] != 0.0, "the left channel should be ringing"); | |
| 360 | + for (frame, pair) in buf.chunks_exact(2).enumerate() { | |
| 361 | + assert_eq!( | |
| 362 | + pair[1], 0.0, | |
| 363 | + "frame {frame}: right channel picked up {pair:?}" | |
| 364 | + ); | |
| 365 | + } | |
| 366 | + } | |
| 367 | +} |
crates/engine/src/lib.rsmodified+1 -0
| @@ -7,6 +7,7 @@ pub mod convert; | ||
| 7 | 7 | pub mod decode; |
| 8 | 8 | pub mod demux; |
| 9 | 9 | pub mod edith; |
| 10 | +pub mod eq; | |
| 10 | 11 | pub mod export; |
| 11 | 12 | pub mod hw; |
| 12 | 13 | pub mod mux; |