forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

voice.rs1492 lines, 56.3 KiBHistoryRawDownload
1//! Voice cleanup: the per-lane processors a creator reaches for first -- a noise
2//! gate, spectral noise reduction, a compressor and a de-esser -- and the
3//! one-click preset that sets them together ([`VoiceFx::clean_voice`]).
4//!
5//! They run on one audio lane's samples, after the lane's clips have been
6//! decoded, cut, equalized and faded (the clip equalizer lives in the segment
7//! workers, so it comes *first*) and before the lane's volume, its duck and the
8//! master limiter: gate, then noise reduction, then compressor, then de-esser
9//! ([`VoiceChain`]). The whole chain is **streaming**: every stage carries its
10//! state from block to block, so the output does not depend on where the mix
11//! happens to cut the stream into blocks, and playback and export, which pour
12//! the same chunks through the same stage, cannot disagree.
13//!
14//! * **Gate** ([`Gate`]): a 10 ms RMS detector with 2 dB of hysteresis, hold,
15//! and attack/release time constants on the gain. It closes to `range_db`,
16//! not to silence, so a pause keeps a little of the room.
17//! * **Noise reduction** ([`Denoise`]): power spectral subtraction in the STFT
18//! domain -- 2048-point FFT, 75% overlap, Hann analysis and synthesis. The
19//! noise is a *profile* ([`learn_profile`]): the mean power spectrum of a
20//! stretch of the lane that holds only noise, kept in 256 bands of dB so it
21//! is small enough to live in the project file. `strength` scales how much of
22//! it is subtracted and `floor_db` is how far a bin may be pulled down, which
23//! is what keeps speech from going watery. The channels share one gain per
24//! bin, so the stereo image does not move. It has [`LATENCY`] samples of
25//! algorithmic delay, which the stage ([`spawn_stage`]) takes out again by
26//! reading ahead, so the lane stays in step with the picture and the other
27//! lanes.
28//! * **Compressor** ([`Compressor`]): feed-forward, a 10 ms RMS detector (dBFS),
29//! a soft-knee static curve and attack/release ballistics on the gain
30//! reduction in dB; manual or automatic makeup.
31//! * **De-esser** ([`DeEsser`]): a split-band compressor. A 4th-order band-pass
32//! between `lo_hz` and `hi_hz` measures the sibilance; whatever it is over the
33//! threshold, times `amount`, is taken out of that band by a peaking filter at
34//! its centre (a dynamic EQ), so everything outside the band passes untouched
35//! and with no reduction the filter is not even run.
36
37use std::collections::VecDeque;
38use std::f32::consts::PI;
39use std::sync::Arc;
40use std::sync::mpsc::{Receiver, sync_channel};
41use std::thread;
42
43use rustfft::num_complex::Complex;
44use rustfft::{Fft, FftPlanner};
45
46use crate::audio::AudioChunk;
47
48/// The FFT size of the noise reduction.
49pub const FFT_SIZE: usize = 2048;
50/// The hop between two frames: 75% overlap.
51pub const HOP: usize = FFT_SIZE / 4;
52/// The algorithmic delay of the noise reduction, in frames of audio.
53pub const LATENCY: usize = FFT_SIZE - HOP;
54/// The bands a noise profile is kept in.
55pub const PROFILE_BANDS: usize = 256;
56const BINS: usize = FFT_SIZE / 2 + 1;
57const BINS_PER_BAND: usize = (FFT_SIZE / 2) / PROFILE_BANDS;
58/// How long a stretch the automatic noise search looks for, in seconds.
59pub const AUTO_NOISE_SECS: f64 = 0.5;
60/// A level under this is digital silence -- a gap or a muted take -- and never noise.
61const DIGITAL_SILENCE_DB: f32 = -90.0;
62
63fn db_to_lin(db: f32) -> f32 {
64 10f32.powf(db / 20.0)
65}
66
67fn lin_to_db(x: f32) -> f32 {
68 20.0 * x.max(1e-12).log10()
69}
70
71/// One-pole smoothing coefficient for a time constant in ms: the share of the way
72/// to the target one sample covers.
73fn coef(ms: f32, rate: f32) -> f32 {
74 1.0 - (-1.0 / (ms.max(0.01) * 0.001 * rate)).exp()
75}
76
77/// A recursive state that has decayed to nothing is zero, so a long silence never
78/// leaves a denormal circulating (they cost 100x on some CPUs).
79fn flush(x: f32) -> f32 {
80 if x.abs() < 1e-20 { 0.0 } else { x }
81}
82
83fn all_finite(values: &[f32]) -> bool {
84 values.iter().all(|v| v.is_finite())
85}
86
87// ---- parameters -------------------------------------------------------------
88
89/// The noise gate of one lane.
90#[derive(Clone, Copy, Debug, PartialEq)]
91pub struct Gate {
92 pub on: bool,
93 /// Open at or above this RMS level, in dBFS (`-90..=0`).
94 pub threshold_db: f32,
95 /// How fast it opens, ms (`0.1..=100`).
96 pub attack_ms: f32,
97 /// How fast it closes, ms (`1..=3000`).
98 pub release_ms: f32,
99 /// How long it stays open after the level falls below the threshold, ms (`0..=2000`).
100 pub hold_ms: f32,
101 /// How far it attenuates when closed, dB (`-90..=0`).
102 pub range_db: f32,
103}
104
105impl Gate {
106 pub const DEFAULT: Gate =
107 Gate { on: false, threshold_db: -45.0, attack_ms: 2.0, release_ms: 150.0, hold_ms: 60.0, range_db: -18.0 };
108
109 pub fn clamped(self) -> Option<Self> {
110 all_finite(&[self.threshold_db, self.attack_ms, self.release_ms, self.hold_ms, self.range_db]).then(|| Self {
111 on: self.on,
112 threshold_db: self.threshold_db.clamp(-90.0, 0.0),
113 attack_ms: self.attack_ms.clamp(0.1, 100.0),
114 release_ms: self.release_ms.clamp(1.0, 3000.0),
115 hold_ms: self.hold_ms.clamp(0.0, 2000.0),
116 range_db: self.range_db.clamp(-90.0, 0.0),
117 })
118 }
119}
120
121impl Default for Gate {
122 fn default() -> Self {
123 Self::DEFAULT
124 }
125}
126
127/// The spectral noise reduction of one lane.
128#[derive(Clone, Debug, PartialEq)]
129pub struct NoiseReduction {
130 pub on: bool,
131 /// How much of the noise is taken out, `0..=1` (0 is nothing, 1 is four times the profile).
132 pub strength: f32,
133 /// How far a bin may be pulled down, dB (`-60..=0`). The spectral floor: a
134 /// shallower floor keeps speech natural at the cost of more left-over noise.
135 pub floor_db: f32,
136 /// The noise profile, [`PROFILE_BANDS`] bands of dB power, empty until one is learned.
137 pub profile: Vec<f32>,
138}
139
140impl NoiseReduction {
141 pub fn clamped(&self) -> Option<Self> {
142 if !all_finite(&[self.strength, self.floor_db]) || !all_finite(&self.profile) {
143 return None;
144 }
145 if !(self.profile.is_empty() || self.profile.len() == PROFILE_BANDS) {
146 return None;
147 }
148 Some(Self {
149 on: self.on,
150 strength: self.strength.clamp(0.0, 1.0),
151 floor_db: self.floor_db.clamp(-60.0, 0.0),
152 profile: self.profile.iter().map(|d| d.clamp(-200.0, 200.0)).collect(),
153 })
154 }
155}
156
157impl Default for NoiseReduction {
158 fn default() -> Self {
159 Self { on: false, strength: 0.6, floor_db: -18.0, profile: Vec::new() }
160 }
161}
162
163/// The compressor of one lane.
164#[derive(Clone, Copy, Debug, PartialEq)]
165pub struct Compressor {
166 pub on: bool,
167 /// Compression starts above this RMS level, dBFS (`-60..=0`).
168 pub threshold_db: f32,
169 /// Input dB per output dB above the threshold (`1..=20`).
170 pub ratio: f32,
171 /// ms (`0.1..=500`).
172 pub attack_ms: f32,
173 /// ms (`5..=5000`).
174 pub release_ms: f32,
175 /// Width of the soft knee, dB (`0..=30`).
176 pub knee_db: f32,
177 /// Makeup gain, dB (`-12..=24`); ignored while `auto_makeup` is on.
178 pub makeup_db: f32,
179 /// Makeup that brings full scale back to full scale.
180 pub auto_makeup: bool,
181}
182
183impl Compressor {
184 pub const DEFAULT: Compressor = Compressor {
185 on: false,
186 threshold_db: -24.0,
187 ratio: 3.0,
188 attack_ms: 10.0,
189 release_ms: 100.0,
190 knee_db: 6.0,
191 makeup_db: 0.0,
192 auto_makeup: true,
193 };
194
195 pub fn clamped(self) -> Option<Self> {
196 all_finite(&[self.threshold_db, self.ratio, self.attack_ms, self.release_ms, self.knee_db, self.makeup_db])
197 .then(|| Self {
198 on: self.on,
199 threshold_db: self.threshold_db.clamp(-60.0, 0.0),
200 ratio: self.ratio.clamp(1.0, 20.0),
201 attack_ms: self.attack_ms.clamp(0.1, 500.0),
202 release_ms: self.release_ms.clamp(5.0, 5000.0),
203 knee_db: self.knee_db.clamp(0.0, 30.0),
204 makeup_db: self.makeup_db.clamp(-12.0, 24.0),
205 auto_makeup: self.auto_makeup,
206 })
207 }
208
209 /// The makeup actually applied, dB.
210 pub fn makeup(&self) -> f32 {
211 if self.auto_makeup {
212 (-self.threshold_db * (1.0 - 1.0 / self.ratio)).clamp(0.0, 24.0)
213 } else {
214 self.makeup_db
215 }
216 }
217
218 /// The static curve: output level for an input level, both dB (makeup not included).
219 pub fn curve(&self, x: f32) -> f32 {
220 let (t, r, w) = (self.threshold_db, self.ratio, self.knee_db);
221 let over = x - t;
222 if 2.0 * over < -w {
223 x
224 } else if w > 0.0 && 2.0 * over.abs() <= w {
225 x + (1.0 / r - 1.0) * (over + w / 2.0).powi(2) / (2.0 * w)
226 } else {
227 t + over / r
228 }
229 }
230}
231
232impl Default for Compressor {
233 fn default() -> Self {
234 Self::DEFAULT
235 }
236}
237
238/// The de-esser of one lane.
239#[derive(Clone, Copy, Debug, PartialEq)]
240pub struct DeEsser {
241 pub on: bool,
242 /// The band's level above which it is turned down, dBFS of its peak envelope (`-60..=0`).
243 pub threshold_db: f32,
244 /// How much of the excess is taken out, `0..=1`.
245 pub amount: f32,
246 /// The band's edges, Hz (`1000..=12000` and `2000..=16000`, the top above the bottom).
247 pub lo_hz: f32,
248 pub hi_hz: f32,
249}
250
251impl DeEsser {
252 pub const DEFAULT: DeEsser = DeEsser { on: false, threshold_db: -30.0, amount: 0.55, lo_hz: 4500.0, hi_hz: 9000.0 };
253
254 pub fn clamped(self) -> Option<Self> {
255 if !all_finite(&[self.threshold_db, self.amount, self.lo_hz, self.hi_hz]) {
256 return None;
257 }
258 let lo_hz = self.lo_hz.clamp(1000.0, 12000.0);
259 let hi_hz = self.hi_hz.clamp(2000.0, 16000.0);
260 (hi_hz > lo_hz * 1.1).then_some(Self {
261 on: self.on,
262 threshold_db: self.threshold_db.clamp(-60.0, 0.0),
263 amount: self.amount.clamp(0.0, 1.0),
264 lo_hz,
265 hi_hz,
266 })
267 }
268}
269
270impl Default for DeEsser {
271 fn default() -> Self {
272 Self::DEFAULT
273 }
274}
275
276/// How hard a one-click cleanup works.
277#[derive(Clone, Copy, Debug, PartialEq, Eq)]
278pub enum Strength {
279 Light,
280 Medium,
281 Strong,
282}
283
284impl Strength {
285 pub fn from_name(s: &str) -> Option<Self> {
286 match s {
287 "light" => Some(Self::Light),
288 "medium" => Some(Self::Medium),
289 "strong" => Some(Self::Strong),
290 _ => None,
291 }
292 }
293
294 pub fn name(self) -> &'static str {
295 match self {
296 Self::Light => "light",
297 Self::Medium => "medium",
298 Self::Strong => "strong",
299 }
300 }
301}
302
303/// Every voice processor of one audio lane, in the order they run.
304#[derive(Clone, Debug, Default, PartialEq)]
305pub struct VoiceFx {
306 pub gate: Gate,
307 pub nr: NoiseReduction,
308 pub comp: Compressor,
309 pub deess: DeEsser,
310}
311
312impl VoiceFx {
313 /// Whether the noise reduction can run: it is on and has a profile to subtract.
314 pub fn nr_active(&self) -> bool {
315 self.nr.on && self.nr.profile.len() == PROFILE_BANDS && self.nr.strength > 0.0
316 }
317
318 /// Whether anything is switched on (and so whether the lane needs a stage at all).
319 pub fn is_active(&self) -> bool {
320 self.gate.on || self.nr_active() || self.comp.on || self.deess.on
321 }
322
323 /// Whether the lane carries no setting at all, which is what a save leaves out.
324 pub fn is_default(&self) -> bool {
325 *self == Self::default()
326 }
327
328 /// Every number clamped into its range; `None` for one that is not finite.
329 pub fn clamped(&self) -> Option<Self> {
330 Some(Self {
331 gate: self.gate.clamped()?,
332 nr: self.nr.clamped()?,
333 comp: self.comp.clamped()?,
334 deess: self.deess.clamped()?,
335 })
336 }
337
338 /// The processors that are on, for a one-line listing: `gate -45 dB, nr 60%, comp 3:1, de-ess`.
339 pub fn summary(&self) -> String {
340 let mut parts = Vec::new();
341 if self.gate.on {
342 parts.push(format!("gate {:.0} dB", self.gate.threshold_db));
343 }
344 if self.nr.on {
345 if self.nr.profile.is_empty() {
346 parts.push("nr (no profile)".to_string());
347 } else {
348 parts.push(format!("nr {:.0}%", self.nr.strength * 100.0));
349 }
350 }
351 if self.comp.on {
352 parts.push(format!("comp {:.0} dB {}:1", self.comp.threshold_db, trim_num(self.comp.ratio)));
353 }
354 if self.deess.on {
355 parts.push(format!("de-ess {:.0} dB", self.deess.threshold_db));
356 }
357 parts.join(", ")
358 }
359
360 /// The one-click voice preset: gate, noise reduction, compressor and de-esser at
361 /// settings that suit speech. `noise_db` is the learned noise's RMS level in dBFS
362 /// when known; it sets where the gate opens (a few dB over the noise).
363 pub fn clean_voice(strength: Strength, profile: Vec<f32>, noise_db: Option<f32>) -> Self {
364 let (gate_over, range, nr, floor, comp_t, ratio, comp_att, comp_rel, ess_t, ess) = match strength {
365 Strength::Light => (6.0, -10.0, 0.35, -12.0, -22.0, 2.0, 15.0, 120.0, -26.0, 0.4),
366 Strength::Medium => (9.0, -18.0, 0.6, -18.0, -24.0, 3.0, 10.0, 100.0, -30.0, 0.55),
367 Strength::Strong => (12.0, -30.0, 0.85, -24.0, -26.0, 4.0, 8.0, 100.0, -33.0, 0.7),
368 };
369 let threshold = noise_db.map_or(-45.0, |n| (n + gate_over).clamp(-70.0, -30.0));
370 Self {
371 gate: Gate { on: true, threshold_db: threshold, range_db: range, ..Gate::DEFAULT },
372 nr: NoiseReduction { on: !profile.is_empty(), strength: nr, floor_db: floor, profile },
373 comp: Compressor {
374 on: true,
375 threshold_db: comp_t,
376 ratio,
377 attack_ms: comp_att,
378 release_ms: comp_rel,
379 // Half the automatic makeup: the full amount lifts speech peaks past full scale.
380 makeup_db: -comp_t * (1.0 - 1.0 / ratio) * 0.5,
381 auto_makeup: false,
382 ..Compressor::DEFAULT
383 },
384 deess: DeEsser { on: true, threshold_db: ess_t, amount: ess, ..DeEsser::DEFAULT },
385 }
386 }
387}
388
389fn trim_num(x: f32) -> String {
390 let s = format!("{x:.2}");
391 s.trim_end_matches('0').trim_end_matches('.').to_string()
392}
393
394// ---- gate ---------------------------------------------------------------------
395
396/// The gate's running state.
397pub struct GateState {
398 channels: usize,
399 thr: f32,
400 range: f32,
401 power: f32,
402 det: f32,
403 gain: f32,
404 open: bool,
405 hold_left: u32,
406 hold_n: u32,
407 a_att: f32,
408 a_rel: f32,
409}
410
411const GATE_HYSTERESIS_DB: f32 = 2.0;
412
413impl GateState {
414 pub fn new(p: &Gate, rate: u32, channels: usize) -> Self {
415 let r = rate.max(1) as f32;
416 Self {
417 channels: channels.max(1),
418 thr: p.threshold_db,
419 range: db_to_lin(p.range_db),
420 power: 0.0,
421 det: coef(10.0, r),
422 gain: 1.0,
423 open: true,
424 hold_left: 0,
425 hold_n: (p.hold_ms * 0.001 * r) as u32,
426 a_att: coef(p.attack_ms, r),
427 a_rel: coef(p.release_ms, r),
428 }
429 }
430
431 pub fn process(&mut self, block: &mut [f32]) {
432 let ch = self.channels;
433 for frame in block.chunks_exact_mut(ch) {
434 let mut sq = 0.0f32;
435 for &s in frame.iter() {
436 sq = sq.max(s * s);
437 }
438 self.power = flush(self.power + (sq - self.power) * self.det);
439 let db = 10.0 * self.power.max(1e-20).log10();
440 if db >= self.thr {
441 self.open = true;
442 self.hold_left = self.hold_n;
443 } else if self.open {
444 if db >= self.thr - GATE_HYSTERESIS_DB {
445 self.hold_left = self.hold_n;
446 } else if self.hold_left == 0 {
447 self.open = false;
448 } else {
449 self.hold_left -= 1;
450 }
451 }
452 let target = if self.open { 1.0 } else { self.range };
453 let a = if target > self.gain { self.a_att } else { self.a_rel };
454 self.gain += (target - self.gain) * a;
455 if self.gain != 1.0 {
456 for s in frame.iter_mut() {
457 *s *= self.gain;
458 }
459 }
460 }
461 }
462
463 /// The gain now (1 open, the range closed).
464 pub fn gain(&self) -> f32 {
465 self.gain
466 }
467}
468
469// ---- compressor ----------------------------------------------------------------
470
471/// The compressor's running state.
472pub struct CompressorState {
473 channels: usize,
474 p: Compressor,
475 makeup_db: f32,
476 power: f32,
477 det: f32,
478 gr_db: f32,
479 a_att: f32,
480 a_rel: f32,
481}
482
483impl CompressorState {
484 pub fn new(p: &Compressor, rate: u32, channels: usize) -> Self {
485 let r = rate.max(1) as f32;
486 Self {
487 channels: channels.max(1),
488 p: *p,
489 makeup_db: p.makeup(),
490 power: 0.0,
491 det: coef(10.0, r),
492 gr_db: 0.0,
493 a_att: coef(p.attack_ms, r),
494 a_rel: coef(p.release_ms, r),
495 }
496 }
497
498 pub fn process(&mut self, block: &mut [f32]) {
499 let ch = self.channels;
500 for frame in block.chunks_exact_mut(ch) {
501 let mut sq = 0.0f32;
502 for &s in frame.iter() {
503 sq = sq.max(s * s);
504 }
505 self.power = flush(self.power + (sq - self.power) * self.det);
506 let level = 10.0 * self.power.max(1e-20).log10();
507 let target = self.p.curve(level) - level;
508 let a = if target < self.gr_db { self.a_att } else { self.a_rel };
509 self.gr_db = flush(self.gr_db + (target - self.gr_db) * a);
510 let g = db_to_lin(self.gr_db + self.makeup_db);
511 for s in frame.iter_mut() {
512 *s *= g;
513 }
514 }
515 }
516
517 /// The gain reduction now, dB (zero or negative).
518 pub fn gain_reduction_db(&self) -> f32 {
519 self.gr_db
520 }
521}
522
523// ---- de-esser ------------------------------------------------------------------
524
525#[derive(Clone, Copy, Default)]
526struct Biquad {
527 b0: f32,
528 b1: f32,
529 b2: f32,
530 a1: f32,
531 a2: f32,
532 z1: f32,
533 z2: f32,
534}
535
536impl Biquad {
537 /// RBJ Butterworth (Q = 1/sqrt 2) high- or low-pass.
538 fn new(high: bool, hz: f32, rate: f32) -> Self {
539 let w = 2.0 * PI * (hz / rate).clamp(1e-4, 0.49);
540 let (sin, cos) = w.sin_cos();
541 let alpha = sin / (2.0 * std::f32::consts::FRAC_1_SQRT_2);
542 let a0 = 1.0 + alpha;
543 let (b0, b1, b2) = if high {
544 ((1.0 + cos) / 2.0, -(1.0 + cos), (1.0 + cos) / 2.0)
545 } else {
546 ((1.0 - cos) / 2.0, 1.0 - cos, (1.0 - cos) / 2.0)
547 };
548 Self { b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, a1: -2.0 * cos / a0, a2: (1.0 - alpha) / a0, z1: 0.0, z2: 0.0 }
549 }
550
551 fn tick(&mut self, x: f32) -> f32 {
552 let y = self.b0 * x + self.z1;
553 self.z1 = flush(self.b1 * x - self.a1 * y + self.z2);
554 self.z2 = flush(self.b2 * x - self.a2 * y);
555 y
556 }
557}
558
559/// One channel's band split: a 4th-order high-pass into a 4th-order low-pass.
560#[derive(Clone, Copy)]
561struct BandSplit {
562 hp: [Biquad; 2],
563 lp: [Biquad; 2],
564}
565
566impl BandSplit {
567 fn new(lo: f32, hi: f32, rate: f32) -> Self {
568 Self { hp: [Biquad::new(true, lo, rate); 2], lp: [Biquad::new(false, hi, rate); 2] }
569 }
570
571 fn band(&mut self, x: f32) -> f32 {
572 let a = self.hp[0].tick(x);
573 let a = self.hp[1].tick(a);
574 let a = self.lp[0].tick(a);
575 self.lp[1].tick(a)
576 }
577}
578
579/// The de-esser's running state: a band-pass sidechain that measures the sibilance,
580/// and a peaking filter at the band's centre that is pulled down by as much as the
581/// sibilance is over the threshold -- a dynamic EQ, which (unlike subtracting a
582/// band-passed copy) cuts the band by exactly the reduction, phase shift or not.
583pub struct DeEsserState {
584 channels: usize,
585 p: DeEsser,
586 split: Vec<BandSplit>,
587 env: f32,
588 d_env: f32,
589 gr_db: f32,
590 a_att: f32,
591 a_rel: f32,
592 cos: f32,
593 alpha: f32,
594 /// b0 b1 b2 a1 a2, normalised by a0; refreshed every few samples.
595 k: [f32; 5],
596 /// Transposed direct form II state, per channel.
597 z: Vec<[f32; 2]>,
598 tick: u32,
599}
600
601/// The deepest cut a de-esser makes, dB: past it a voice starts to lisp.
602const DEESS_MAX_CUT_DB: f32 = 18.0;
603/// How often the peaking filter's coefficients follow the gain reduction, in samples.
604const DEESS_UPDATE: u32 = 4;
605
606impl DeEsserState {
607 pub fn new(p: &DeEsser, rate: u32, channels: usize) -> Self {
608 let r = rate.max(1) as f32;
609 let hi = p.hi_hz.min(r * 0.45);
610 let lo = p.lo_hz.min(hi * 0.8);
611 let octaves = (hi / lo).log2().max(0.1);
612 let q = 2f32.powf(octaves / 2.0) / (2f32.powf(octaves) - 1.0);
613 let w0 = 2.0 * PI * ((lo * hi).sqrt() / r).clamp(1e-4, 0.49);
614 let (sin, cos) = w0.sin_cos();
615 let channels = channels.max(1);
616 let mut state = Self {
617 channels,
618 p: *p,
619 split: vec![BandSplit::new(lo, hi, r); channels],
620 env: 0.0,
621 d_env: (-1.0 / (0.003 * r)).exp(),
622 gr_db: 0.0,
623 a_att: coef(0.5, r),
624 a_rel: coef(20.0, r),
625 cos,
626 alpha: sin / (2.0 * q),
627 k: [1.0, 0.0, 0.0, 0.0, 0.0],
628 z: vec![[0.0; 2]; channels],
629 tick: 0,
630 };
631 state.retune();
632 state
633 }
634
635 /// The peaking filter at the current gain reduction (RBJ cookbook).
636 fn retune(&mut self) {
637 let a = (self.gr_db * std::f32::consts::LN_10 / 40.0).exp();
638 let a0 = 1.0 + self.alpha / a;
639 self.k = [
640 (1.0 + self.alpha * a) / a0,
641 -2.0 * self.cos / a0,
642 (1.0 - self.alpha * a) / a0,
643 -2.0 * self.cos / a0,
644 (1.0 - self.alpha / a) / a0,
645 ];
646 }
647
648 pub fn process(&mut self, block: &mut [f32]) {
649 let ch = self.channels;
650 for frame in block.chunks_exact_mut(ch) {
651 let mut peak = 0.0f32;
652 for (c, &s) in frame.iter().enumerate() {
653 peak = peak.max(self.split[c].band(s).abs());
654 }
655 self.env = flush(if peak > self.env { peak } else { self.env * self.d_env });
656 let db = lin_to_db(self.env);
657 let over = (db - self.p.threshold_db).max(0.0);
658 let target = -(over * self.p.amount).min(DEESS_MAX_CUT_DB);
659 let a = if target < self.gr_db { self.a_att } else { self.a_rel };
660 self.gr_db = flush(self.gr_db + (target - self.gr_db) * a);
661 if self.gr_db == 0.0 && self.z.iter().all(|z| *z == [0.0, 0.0]) {
662 continue; // at rest and nothing circulating: the input to the last bit
663 }
664 if self.tick == 0 {
665 self.retune();
666 }
667 self.tick = (self.tick + 1) % DEESS_UPDATE;
668 let [b0, b1, b2, a1, a2] = self.k;
669 for (c, s) in frame.iter_mut().enumerate() {
670 let z = &mut self.z[c];
671 let x = *s;
672 let y = b0 * x + z[0];
673 z[0] = flush(b1 * x - a1 * y + z[1]);
674 z[1] = flush(b2 * x - a2 * y);
675 *s = y;
676 }
677 }
678 }
679
680 pub fn gain_reduction_db(&self) -> f32 {
681 self.gr_db
682 }
683}
684
685// ---- noise reduction -------------------------------------------------------------
686
687fn hann() -> Vec<f32> {
688 (0..FFT_SIZE).map(|i| 0.5 - 0.5 * (2.0 * PI * i as f32 / FFT_SIZE as f32).cos()).collect()
689}
690
691/// The per-bin noise power a stored profile stands for: linear in dB between band centres.
692fn noise_power(profile: &[f32]) -> Vec<f32> {
693 (0..BINS)
694 .map(|k| {
695 let pos = (k as f32 + 0.5) / BINS_PER_BAND as f32 - 0.5;
696 let lo = pos.floor().clamp(0.0, (PROFILE_BANDS - 1) as f32);
697 let hi = (lo + 1.0).min((PROFILE_BANDS - 1) as f32);
698 let t = (pos - lo).clamp(0.0, 1.0);
699 let db = profile[lo as usize] * (1.0 - t) + profile[hi as usize] * t;
700 10f32.powf(db / 10.0)
701 })
702 .collect()
703}
704
705/// Streaming spectral subtraction. See the module docs.
706pub struct Denoise {
707 channels: usize,
708 alpha: f32,
709 floor2: f32,
710 noise: Vec<f32>,
711 fft: Arc<dyn Fft<f32>>,
712 ifft: Arc<dyn Fft<f32>>,
713 win: Vec<f32>,
714 inbuf: Vec<Vec<f32>>,
715 filled: usize,
716 ola: Vec<Vec<f32>>,
717 spec: Vec<Vec<Complex<f32>>>,
718 scratch: Vec<Complex<f32>>,
719 smooth: Vec<f32>,
720 gain: Vec<f32>,
721 first: bool,
722 skip: usize,
723 fed: u64,
724 emitted: u64,
725}
726
727impl Denoise {
728 pub fn new(p: &NoiseReduction, channels: usize) -> Self {
729 let channels = channels.max(1);
730 let mut planner = FftPlanner::<f32>::new();
731 let fft = planner.plan_fft_forward(FFT_SIZE);
732 let ifft = planner.plan_fft_inverse(FFT_SIZE);
733 let scratch_len = fft.get_inplace_scratch_len().max(ifft.get_inplace_scratch_len());
734 Self {
735 channels,
736 alpha: 4.0 * p.strength,
737 floor2: db_to_lin(p.floor_db).powi(2),
738 noise: noise_power(&p.profile),
739 fft,
740 ifft,
741 win: hann(),
742 inbuf: vec![vec![0.0; FFT_SIZE]; channels],
743 filled: 0,
744 ola: vec![vec![0.0; FFT_SIZE]; channels],
745 spec: vec![vec![Complex::new(0.0, 0.0); FFT_SIZE]; channels],
746 scratch: vec![Complex::new(0.0, 0.0); scratch_len],
747 smooth: vec![0.0; BINS],
748 gain: vec![1.0; BINS],
749 first: true,
750 skip: LATENCY,
751 fed: 0,
752 emitted: 0,
753 }
754 }
755
756 /// Takes interleaved samples and returns the interleaved samples that are ready:
757 /// the same stream, in step with the input, [`LATENCY`] frames behind it. Over a
758 /// whole stream, `process` of every block then [`finish`](Self::finish) returns
759 /// exactly as many frames as went in.
760 pub fn process(&mut self, input: &[f32]) -> Vec<f32> {
761 self.fed += (input.len() / self.channels) as u64;
762 let mut out = Vec::with_capacity(input.len());
763 self.push(input, &mut out);
764 out
765 }
766
767 /// Flushes the frames still inside, so the stream ends where it began.
768 pub fn finish(&mut self) -> Vec<f32> {
769 let mut out = Vec::new();
770 let zeros = vec![0.0; HOP * self.channels];
771 while self.emitted < self.fed {
772 self.push(&zeros, &mut out);
773 }
774 let over = (self.emitted - self.fed) as usize * self.channels;
775 out.truncate(out.len() - over);
776 self.emitted = self.fed;
777 out
778 }
779
780 fn push(&mut self, input: &[f32], out: &mut Vec<f32>) {
781 let ch = self.channels;
782 for frame in input.chunks_exact(ch) {
783 for (c, &s) in frame.iter().enumerate() {
784 self.inbuf[c][LATENCY + self.filled] = s;
785 }
786 self.filled += 1;
787 if self.filled == HOP {
788 self.frame(out);
789 self.filled = 0;
790 }
791 }
792 }
793
794 fn frame(&mut self, out: &mut Vec<f32>) {
795 let ch = self.channels;
796 for c in 0..ch {
797 for (i, bin) in self.spec[c].iter_mut().enumerate() {
798 *bin = Complex::new(self.inbuf[c][i] * self.win[i], 0.0);
799 }
800 self.fft.process_with_scratch(&mut self.spec[c], &mut self.scratch);
801 }
802 let inv = 1.0 / ch as f32;
803 for k in 0..BINS {
804 let mut p = 0.0;
805 for spec in &self.spec {
806 p += spec[k].norm_sqr();
807 }
808 p *= inv;
809 self.smooth[k] = if self.first { p } else { 0.5 * self.smooth[k] + 0.5 * p };
810 let ps = self.smooth[k].max(1e-30);
811 let g2 = ((ps - self.alpha * self.noise[k]) / ps).clamp(self.floor2, 1.0);
812 self.gain[k] = g2.sqrt();
813 }
814 self.first = false;
815 // 1 / (N * sum of the squared window over a hop) -- 1.5 for a Hann at 75%.
816 let norm = 1.0 / (FFT_SIZE as f32 * 1.5);
817 for c in 0..ch {
818 let spec = &mut self.spec[c];
819 for k in 0..BINS {
820 spec[k] *= self.gain[k];
821 if k != 0 && k != FFT_SIZE / 2 {
822 spec[FFT_SIZE - k] *= self.gain[k];
823 }
824 }
825 self.ifft.process_with_scratch(spec, &mut self.scratch);
826 for (i, o) in self.ola[c].iter_mut().enumerate() {
827 *o += spec[i].re * self.win[i] * norm;
828 }
829 }
830 for j in 0..HOP {
831 if self.skip > 0 {
832 self.skip -= 1;
833 continue;
834 }
835 for c in 0..ch {
836 out.push(self.ola[c][j]);
837 }
838 self.emitted += 1;
839 }
840 for c in 0..ch {
841 self.ola[c].copy_within(HOP.., 0);
842 let n = self.ola[c].len();
843 self.ola[c][n - HOP..].fill(0.0);
844 self.inbuf[c].copy_within(HOP.., 0);
845 }
846 }
847}
848
849/// The noise profile of a mono stretch: the mean power spectrum of its Hann frames,
850/// in [`PROFILE_BANDS`] bands of dB (0.1 dB resolution), and the stretch's RMS level
851/// in dBFS. `None` when it is shorter than one frame or not finite.
852pub fn learn_profile(mono: &[f32]) -> Option<(Vec<f32>, f32)> {
853 if mono.len() < FFT_SIZE || !all_finite(mono) {
854 return None;
855 }
856 let mut planner = FftPlanner::<f32>::new();
857 let fft = planner.plan_fft_forward(FFT_SIZE);
858 let win = hann();
859 let mut buf = vec![Complex::new(0.0, 0.0); FFT_SIZE];
860 let mut mean = vec![0.0f64; BINS];
861 let mut frames = 0u32;
862 let mut at = 0;
863 while at + FFT_SIZE <= mono.len() {
864 for i in 0..FFT_SIZE {
865 buf[i] = Complex::new(mono[at + i] * win[i], 0.0);
866 }
867 fft.process(&mut buf);
868 for k in 0..BINS {
869 mean[k] += f64::from(buf[k].norm_sqr());
870 }
871 frames += 1;
872 at += HOP;
873 }
874 let profile = (0..PROFILE_BANDS)
875 .map(|b| {
876 let lo = b * BINS_PER_BAND;
877 let hi = if b == PROFILE_BANDS - 1 { BINS } else { lo + BINS_PER_BAND };
878 let m = mean[lo..hi].iter().sum::<f64>() / ((hi - lo) as f64 * f64::from(frames));
879 ((10.0 * m.max(1e-20).log10()) as f32 * 10.0).round() / 10.0
880 })
881 .collect();
882 let rms = (mono.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>() / mono.len() as f64).sqrt();
883 Some((profile, lin_to_db(rms as f32)))
884}
885
886/// The quietest [`AUTO_NOISE_SECS`] of a stream, found as it goes past (50 ms blocks,
887/// O(1) memory beyond the window itself). A window with any digital silence in it --
888/// a gap, a muted take -- is never the answer: there is no noise in nothing.
889pub struct QuietestFinder {
890 block: usize,
891 blocks_per_window: usize,
892 window: usize,
893 acc: f64,
894 acc_n: usize,
895 recent: VecDeque<f64>,
896 ring: VecDeque<f32>,
897 pos: u64,
898 best: Option<(f64, Vec<f32>, u64)>,
899}
900
901impl QuietestFinder {
902 pub fn new(rate: u32) -> Self {
903 let block = (rate.max(1) as usize / 20).max(1);
904 let blocks_per_window = ((AUTO_NOISE_SECS * 20.0) as usize).max(1);
905 Self {
906 block,
907 blocks_per_window,
908 window: block * blocks_per_window,
909 acc: 0.0,
910 acc_n: 0,
911 recent: VecDeque::new(),
912 ring: VecDeque::new(),
913 pos: 0,
914 best: None,
915 }
916 }
917
918 /// Feeds mono samples.
919 pub fn push(&mut self, mono: &[f32]) {
920 let silent = 10f64.powf(f64::from(DIGITAL_SILENCE_DB) / 10.0);
921 for &s in mono {
922 self.pos += 1;
923 self.ring.push_back(s);
924 if self.ring.len() > self.window {
925 self.ring.pop_front();
926 }
927 self.acc += f64::from(s) * f64::from(s);
928 self.acc_n += 1;
929 if self.acc_n == self.block {
930 self.recent.push_back(self.acc / self.block as f64);
931 if self.recent.len() > self.blocks_per_window {
932 self.recent.pop_front();
933 }
934 self.acc = 0.0;
935 self.acc_n = 0;
936 if self.recent.len() == self.blocks_per_window
937 && self.ring.len() == self.window
938 && self.recent.iter().all(|&p| p > silent)
939 {
940 let mean = self.recent.iter().sum::<f64>() / self.blocks_per_window as f64;
941 if self.best.as_ref().is_none_or(|(b, ..)| mean < *b) {
942 self.best = Some((mean, self.ring.iter().copied().collect(), self.pos));
943 }
944 }
945 }
946 }
947 }
948
949 /// The quietest window seen: its samples and the sample count where it ended.
950 pub fn best(self) -> Option<(Vec<f32>, u64)> {
951 self.best.map(|(_, samples, end)| (samples, end))
952 }
953}
954
955// ---- the chain ---------------------------------------------------------------------
956
957/// Gate, noise reduction, compressor, de-esser, in that order, with only the ones
958/// that are on built.
959pub struct VoiceChain {
960 gate: Option<GateState>,
961 nr: Option<Denoise>,
962 comp: Option<CompressorState>,
963 deess: Option<DeEsserState>,
964}
965
966impl VoiceChain {
967 pub fn new(fx: &VoiceFx, rate: u32, channels: usize) -> Self {
968 Self {
969 gate: fx.gate.on.then(|| GateState::new(&fx.gate, rate, channels)),
970 nr: fx.nr_active().then(|| Denoise::new(&fx.nr, channels)),
971 comp: fx.comp.on.then(|| CompressorState::new(&fx.comp, rate, channels)),
972 deess: fx.deess.on.then(|| DeEsserState::new(&fx.deess, rate, channels)),
973 }
974 }
975
976 fn tail(&mut self, block: &mut [f32]) {
977 if let Some(comp) = self.comp.as_mut() {
978 comp.process(block);
979 }
980 if let Some(deess) = self.deess.as_mut() {
981 deess.process(block);
982 }
983 }
984
985 /// Runs interleaved samples through the chain. With the noise reduction on the
986 /// result lags the input by [`LATENCY`] frames until [`finish`](Self::finish).
987 pub fn process(&mut self, mut block: Vec<f32>) -> Vec<f32> {
988 if let Some(gate) = self.gate.as_mut() {
989 gate.process(&mut block);
990 }
991 let mut block = match self.nr.as_mut() {
992 Some(nr) => nr.process(&block),
993 None => block,
994 };
995 self.tail(&mut block);
996 block
997 }
998
999 /// The frames still inside the noise reduction.
1000 pub fn finish(&mut self) -> Vec<f32> {
1001 let Some(nr) = self.nr.as_mut() else {
1002 return Vec::new();
1003 };
1004 let mut block = nr.finish();
1005 self.tail(&mut block);
1006 block
1007 }
1008}
1009
1010/// Puts a lane's chunk stream through its voice chain on a thread of its own and hands
1011/// back the processed stream. The result is the same length as the input and in
1012/// step with it: the noise reduction's delay is read ahead and flushed at the end.
1013pub fn spawn_stage(rx: Receiver<AudioChunk>, fx: &VoiceFx, rate: u32, channels: usize) -> Receiver<AudioChunk> {
1014 let (tx, out) = sync_channel(32);
1015 let mut chain = VoiceChain::new(fx, rate, channels);
1016 let ch = channels.max(1);
1017 let _ = thread::Builder::new().name("voice-fx".into()).spawn(move || {
1018 let mut next: Option<u64> = None;
1019 for chunk in rx {
1020 let start = *next.get_or_insert(chunk.start_sample);
1021 let samples = chain.process(chunk.samples);
1022 if samples.is_empty() {
1023 continue;
1024 }
1025 next = Some(start + (samples.len() / ch) as u64);
1026 if tx.send(AudioChunk { start_sample: start, samples }).is_err() {
1027 return;
1028 }
1029 }
1030 let tail = chain.finish();
1031 if !tail.is_empty() {
1032 let _ = tx.send(AudioChunk { start_sample: next.unwrap_or(0), samples: tail });
1033 }
1034 });
1035 out
1036}
1037
1038// ---- learning from a lane ------------------------------------------------------------
1039
1040/// What [`learn_noise`] found: the profile and the noise's own level.
1041#[derive(Clone, Debug, PartialEq)]
1042pub struct Learned {
1043 pub profile: Vec<f32>,
1044 /// The RMS level of the stretch the profile came from, dBFS.
1045 pub noise_db: f32,
1046 /// Where it came from, in seconds of lane (timeline) time.
1047 pub from: (f64, f64),
1048}
1049
1050/// Learns a noise profile from `lane`: the explicit `range` (lane seconds), or by
1051/// default the quietest half second of its sound. The lane is read exactly as it plays
1052/// (cuts, speeds and the clip equalizers applied), at `sample_rate`.
1053pub fn learn_noise(
1054 project: &crate::Project,
1055 lane: crate::project::Lane,
1056 fps: f64,
1057 sample_rate: Option<u32>,
1058 range: Option<(f64, f64)>,
1059) -> crate::Result<Learned> {
1060 let sources = project.audio_sources();
1061 let open = |start_frame: u32| {
1062 let segs = project.lane_segments_from(lane, start_frame, fps);
1063 let eqs = project.lane_eqs_from(lane, start_frame, fps);
1064 let speeds = project.lane_speeds_from(lane, start_frame, fps);
1065 crate::audio::AudioSession::open_multi_streams_speed_at(&sources, &segs, &eqs, &speeds, sample_rate)
1066 };
1067 let no_sound = || "the lane has no sound to learn noise from";
1068 let mono_of = |samples: &[f32], channels: usize, out: &mut Vec<f32>| {
1069 out.clear();
1070 out.extend(samples.chunks_exact(channels).map(|f| f.iter().sum::<f32>() / channels as f32));
1071 };
1072 let mut mono = Vec::new();
1073 let (samples, from) = match range {
1074 None => {
1075 let lane_frames = project.lane(lane).iter().map(|c| c.end()).max().unwrap_or(0);
1076 let mut best: Option<(f64, Vec<f32>, f64)> = None;
1077 for (start, take) in noise_scan_plan(lane_frames, fps) {
1078 let Some((meta, rx)) = open(start)? else {
1079 return Err(no_sound().into());
1080 };
1081 let channels = usize::from(meta.channels.max(1));
1082 let rate = f64::from(meta.sample_rate);
1083 let mut finder = QuietestFinder::new(meta.sample_rate);
1084 let mut left = (take * rate) as u64;
1085 for chunk in rx {
1086 mono_of(&chunk.samples, channels, &mut mono);
1087 let n = (mono.len() as u64).min(left) as usize;
1088 finder.push(&mono[..n]);
1089 left -= n as u64;
1090 // Dropping the receiver ends the decode: the cost stops at the slice.
1091 if left == 0 {
1092 break;
1093 }
1094 }
1095 let t0 = f64::from(start) / fps;
1096 if let Some((win, end)) = finder.best() {
1097 let power = win.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>() / win.len() as f64;
1098 if best.as_ref().is_none_or(|(b, ..)| power < *b) {
1099 best = Some((power, win, t0 + end as f64 / rate));
1100 }
1101 }
1102 }
1103 let (_, win, to) = best.ok_or(
1104 "no stretch of this lane is both quiet enough to be noise and long enough to learn from \
1105 (half a second with no gap in it)",
1106 )?;
1107 (win, (to - AUTO_NOISE_SECS, to))
1108 }
1109 Some((a, b)) => {
1110 let Some((meta, rx)) = open(0)? else {
1111 return Err(no_sound().into());
1112 };
1113 let channels = usize::from(meta.channels.max(1));
1114 let rate = f64::from(meta.sample_rate);
1115 let mut picked: Vec<f32> = Vec::new();
1116 for chunk in rx {
1117 if chunk.start_sample as f64 / rate >= b {
1118 break;
1119 }
1120 mono_of(&chunk.samples, channels, &mut mono);
1121 for (i, &s) in mono.iter().enumerate() {
1122 let t = (chunk.start_sample as f64 + i as f64) / rate;
1123 if t >= a && t < b {
1124 picked.push(s);
1125 }
1126 }
1127 }
1128 (picked, (a, b))
1129 }
1130 };
1131 let (profile, noise_db) = learn_profile(&samples)
1132 .ok_or("that stretch is too short to learn noise from (it needs at least 0.05 s of sound)")?;
1133 if noise_db < DIGITAL_SILENCE_DB {
1134 return Err("that stretch is digital silence: there is no noise in it to learn".into());
1135 }
1136 Ok(Learned { profile, noise_db, from })
1137}
1138
1139/// The most sound the automatic noise search reads, seconds.
1140pub const SCAN_BUDGET_SECS: f64 = 60.0;
1141/// How many slices that budget is spread over.
1142const SCAN_SLICES: u32 = 24;
1143
1144/// Where the automatic noise search looks: `(start frame, seconds to read)` slices. A lane
1145/// that fits the budget is read whole; a longer one is read in [`SCAN_SLICES`] slices spread
1146/// evenly from its start to its end, so the cost is the budget, not the lane's length.
1147pub fn noise_scan_plan(lane_frames: u32, fps: f64) -> Vec<(u32, f64)> {
1148 let total = f64::from(lane_frames) / fps;
1149 if !(fps.is_finite() && fps > 0.0) || total <= SCAN_BUDGET_SECS {
1150 return vec![(0, total.max(0.0) + 1.0)];
1151 }
1152 let take = SCAN_BUDGET_SECS / f64::from(SCAN_SLICES);
1153 let last = total - take;
1154 (0..SCAN_SLICES)
1155 .map(|k| ((last * f64::from(k) / f64::from(SCAN_SLICES - 1) * fps) as u32, take))
1156 .collect()
1157}
1158
1159#[cfg(test)]
1160mod tests {
1161 use super::*;
1162
1163 const RATE: u32 = 48_000;
1164
1165 /// Deterministic white noise at `rms` (a plain LCG; no rand dependency).
1166 fn noise(n: usize, rms: f32, seed: u64) -> Vec<f32> {
1167 let mut s = seed;
1168 (0..n)
1169 .map(|_| {
1170 let mut sum = 0.0;
1171 for _ in 0..4 {
1172 s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
1173 sum += ((s >> 33) as f32 / (1u64 << 31) as f32) - 0.5;
1174 }
1175 // Sum of four uniforms in -0.5..0.5 has variance 4/12.
1176 sum * rms / (4.0f32 / 12.0).sqrt()
1177 })
1178 .collect()
1179 }
1180
1181 fn sine(n: usize, hz: f32, amp: f32, start: usize) -> Vec<f32> {
1182 (0..n).map(|i| amp * (2.0 * PI * hz * (i + start) as f32 / RATE as f32).sin()).collect()
1183 }
1184
1185 fn rms_db(x: &[f32]) -> f32 {
1186 lin_to_db((x.iter().map(|s| s * s).sum::<f32>() / x.len() as f32).sqrt())
1187 }
1188
1189 fn run(fx: &VoiceFx, input: &[f32], chunk: usize, ch: usize) -> Vec<f32> {
1190 let mut chain = VoiceChain::new(fx, RATE, ch);
1191 let mut out = Vec::new();
1192 for c in input.chunks(chunk * ch) {
1193 out.extend(chain.process(c.to_vec()));
1194 }
1195 out.extend(chain.finish());
1196 out
1197 }
1198
1199 fn only_nr(strength: f32, profile: Vec<f32>) -> VoiceFx {
1200 VoiceFx { nr: NoiseReduction { on: true, strength, floor_db: -24.0, profile }, ..Default::default() }
1201 }
1202
1203 #[test]
1204 fn noise_reduction_drops_noise_and_keeps_the_tone() {
1205 let n = RATE as usize * 3;
1206 let hiss = noise(n, db_to_lin(-30.0), 7);
1207 // Learned from a separate stretch of the same noise, as a real profile is.
1208 let (profile, level) = learn_profile(&noise(RATE as usize, db_to_lin(-30.0), 99)).unwrap();
1209 assert!((level + 30.0).abs() < 0.5, "learned level {level}");
1210 // First 1.5 s noise only, then a -12 dBFS tone over it.
1211 let tone = sine(n, 1000.0, db_to_lin(-12.0), 0);
1212 let input: Vec<f32> = (0..n).map(|i| hiss[i] + if i >= n / 2 { tone[i] } else { 0.0 }).collect();
1213 let fx = only_nr(0.8, profile);
1214 let out = run(&fx, &input, 1000, 1);
1215 assert_eq!(out.len(), input.len(), "same length");
1216 let (a, b) = (RATE as usize / 2, n / 2 - RATE as usize / 4);
1217 let before = rms_db(&input[a..b]);
1218 let after = rms_db(&out[a..b]);
1219 assert!(before - after >= 15.0, "noise-only stretch fell {:.1} dB ({before:.1} -> {after:.1})", before - after);
1220 // The tone's level, by correlation with the reference sine.
1221 let (c0, c1) = (n / 2 + RATE as usize / 2, n - RATE as usize / 4);
1222 let level_of = |x: &[f32]| {
1223 let (mut s, mut c) = (0.0f64, 0.0f64);
1224 for (i, &v) in x.iter().enumerate().take(c1).skip(c0) {
1225 let ph = 2.0 * std::f64::consts::PI * 1000.0 * i as f64 / RATE as f64;
1226 s += f64::from(v) * ph.sin();
1227 c += f64::from(v) * ph.cos();
1228 }
1229 (20.0 * (2.0 * (s * s + c * c).sqrt() / (c1 - c0) as f64).log10()) as f32
1230 };
1231 assert!((level_of(&out) - level_of(&input)).abs() < 1.0, "tone {} -> {}", level_of(&input), level_of(&out));
1232 }
1233
1234 #[test]
1235 fn noise_reduction_is_aligned_with_its_input() {
1236 // An impulse comes out where it went in, not LATENCY frames later.
1237 let mut input = vec![0.0f32; 20_000];
1238 input[10_000] = 1.0;
1239 let out = run(&only_nr(0.5, vec![-100.0; PROFILE_BANDS]), &input, 777, 1);
1240 assert_eq!(out.len(), input.len());
1241 let peak = out.iter().enumerate().max_by(|a, b| a.1.abs().total_cmp(&b.1.abs())).unwrap().0;
1242 assert_eq!(peak, 10_000);
1243 assert!((out[10_000] - 1.0).abs() < 1e-3, "{}", out[10_000]);
1244 }
1245
1246 #[test]
1247 fn the_gate_closes_on_noise_below_its_threshold() {
1248 let gate = Gate { on: true, threshold_db: -35.0, range_db: -40.0, release_ms: 30.0, ..Gate::DEFAULT };
1249 let fx = VoiceFx { gate, ..Default::default() };
1250 let quiet = noise(RATE as usize, db_to_lin(-50.0), 3);
1251 let loud = sine(RATE as usize / 2, 440.0, 0.3, 0);
1252 let mut input = loud.clone();
1253 input.extend(&quiet);
1254 input.extend(&loud);
1255 let out = run(&fx, &input, 512, 1);
1256 let h = RATE as usize / 2;
1257 // Open on the tone, unchanged.
1258 assert!((rms_db(&out[h / 2..h]) - rms_db(&input[h / 2..h])).abs() < 0.2);
1259 // Closed on the noise once the release has run: 40 dB down.
1260 let (a, b) = (h + RATE as usize * 2 / 5, h + RATE as usize);
1261 let drop = rms_db(&input[a..b]) - rms_db(&out[a..b]);
1262 assert!(drop > 38.0, "closed by {drop:.1} dB");
1263 // Open again for the second tone.
1264 let t = 2 * h + RATE as usize;
1265 assert!((rms_db(&out[t - h / 2..t]) - rms_db(&input[t - h / 2..t])).abs() < 0.5);
1266 }
1267
1268 #[test]
1269 fn the_gate_holds_before_it_closes() {
1270 let gate = Gate { on: true, threshold_db: -30.0, hold_ms: 200.0, release_ms: 5.0, ..Gate::DEFAULT };
1271 let fx = VoiceFx { gate, ..Default::default() };
1272 let mut input = sine(RATE as usize / 4, 440.0, 0.3, 0);
1273 input.extend(vec![0.0; RATE as usize / 2]);
1274 let mut chain = VoiceChain::new(&fx, RATE, 1);
1275 let mut gains = Vec::new();
1276 for c in input.chunks(480) {
1277 chain.process(c.to_vec());
1278 gains.push(chain.gate.as_ref().unwrap().gain());
1279 }
1280 // 100 ms after the tone ended it is still open, 400 ms after it is shut.
1281 let at = |ms: usize| gains[(RATE as usize / 4 + RATE as usize * ms / 1000) / 480];
1282 assert!(at(100) > 0.99, "{}", at(100));
1283 assert!(at(400) < 0.2, "{}", at(400));
1284 }
1285
1286 #[test]
1287 fn the_compressor_follows_its_static_curve() {
1288 let comp = Compressor { on: true, threshold_db: -20.0, ratio: 4.0, knee_db: 0.0, auto_makeup: false, ..Compressor::DEFAULT };
1289 let fx = VoiceFx { comp, ..Default::default() };
1290 for in_db in [-40.0f32, -30.0, -20.0, -14.0, -8.0, -3.0] {
1291 // A sine whose RMS is in_db.
1292 let amp = db_to_lin(in_db) * std::f32::consts::SQRT_2;
1293 let input = sine(RATE as usize * 2, 997.0, amp, 0);
1294 let out = run(&fx, &input, 4096, 1);
1295 let t = RATE as usize..RATE as usize * 2;
1296 let got = rms_db(&out[t.clone()]) - rms_db(&input[t]);
1297 let want = comp.curve(in_db) - in_db;
1298 assert!((got - want).abs() < 0.5, "{in_db} dB in: reduced {got:.2}, curve says {want:.2}");
1299 }
1300 // With a knee, the curve is continuous through the threshold and below the hard one.
1301 let knee = Compressor { knee_db: 10.0, ..comp };
1302 assert!(knee.curve(-20.0) < -20.0 && knee.curve(-20.0) > comp.curve(-20.0) - 2.0);
1303 assert!((knee.curve(-26.0) - -26.0).abs() < 1e-5, "below the knee is untouched");
1304 assert!(comp.curve(-20.0).is_finite(), "a hard knee exactly at the threshold");
1305 }
1306
1307 /// The envelopes and the overlap state ride across chunks: the chain's output does not
1308 /// depend on how the stream was cut into blocks.
1309 #[test]
1310 fn chunk_size_does_not_change_the_output() {
1311 let n = RATE as usize * 3;
1312 let mut mono = noise(n, db_to_lin(-40.0), 5);
1313 for (i, s) in sine(n, 700.0, 0.2, RATE as usize).iter().enumerate() {
1314 mono[i] += s;
1315 }
1316 for (i, s) in sine(n, 6500.0, 0.1, RATE as usize * 2).iter().enumerate() {
1317 mono[i] += s;
1318 }
1319 let stereo: Vec<f32> = mono.iter().flat_map(|&s| [s, s * 0.7]).collect();
1320 let (profile, level) = learn_profile(&noise(RATE as usize, db_to_lin(-40.0), 11)).unwrap();
1321 let fx = VoiceFx::clean_voice(Strength::Strong, profile, Some(level));
1322 assert!(fx.gate.on && fx.nr.on && fx.comp.on && fx.deess.on);
1323 let whole = run(&fx, &stereo, n, 2);
1324 assert_eq!(whole.len(), stereo.len());
1325 for chunk in [1, 77, 480, 960, 1023, 4093, 20_001] {
1326 let odd = run(&fx, &stereo, chunk, 2);
1327 assert_eq!(odd.len(), whole.len(), "chunk {chunk}");
1328 let worst = whole.iter().zip(&odd).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
1329 assert!(worst < 1e-4, "chunk {chunk}: the output moved by {worst}");
1330 }
1331 }
1332
1333 #[test]
1334 fn the_noise_scan_reads_a_bounded_amount_however_long_the_lane() {
1335 for hours in [0.5f64, 1.0, 10.0] {
1336 let frames = (hours * 3600.0 * 30.0) as u32;
1337 let plan = noise_scan_plan(frames, 30.0);
1338 let read: f64 = plan.iter().map(|p| p.1).sum();
1339 assert!(read <= SCAN_BUDGET_SECS + 1e-9, "{hours} h reads {read} s");
1340 assert_eq!(plan.first().unwrap().0, 0);
1341 let (last, take) = *plan.last().unwrap();
1342 assert!(f64::from(last) / 30.0 + take <= hours * 3600.0 + 0.1, "the last slice ends inside the lane");
1343 assert!(plan.windows(2).all(|w| w[0].0 < w[1].0), "slices run in order");
1344 }
1345 let short = noise_scan_plan(300, 30.0);
1346 assert_eq!(short.len(), 1, "a short lane is read whole");
1347 }
1348
1349 #[test]
1350 fn auto_makeup_brings_full_scale_back() {
1351 let comp = Compressor { on: true, threshold_db: -20.0, ratio: 4.0, knee_db: 0.0, auto_makeup: true, ..Compressor::DEFAULT };
1352 assert!((comp.makeup() - 15.0).abs() < 1e-5);
1353 assert!((comp.curve(0.0) + comp.makeup()).abs() < 1e-5, "0 dB in is 0 dB out");
1354 }
1355
1356 #[test]
1357 fn the_de_esser_cuts_six_khz_and_leaves_one_khz() {
1358 let deess = DeEsser { on: true, threshold_db: -30.0, amount: 0.8, ..DeEsser::DEFAULT };
1359 let fx = VoiceFx { deess, ..Default::default() };
1360 let n = RATE as usize;
1361 for (hz, expect_cut) in [(6000.0f32, true), (1000.0, false)] {
1362 let input = sine(n, hz, 0.3, 0);
1363 let out = run(&fx, &input, 480, 1);
1364 let t = n / 2..n;
1365 let cut = rms_db(&input[t.clone()]) - rms_db(&out[t]);
1366 if expect_cut {
1367 assert!(cut > 8.0, "{hz} Hz cut {cut:.1} dB");
1368 } else {
1369 assert!(cut.abs() < 0.1, "{hz} Hz changed by {cut:.2} dB");
1370 }
1371 }
1372 // A 6 kHz burst inside a 1 kHz tone comes out quieter, the tone around it does not.
1373 let mut input = sine(n, 1000.0, 0.2, 0);
1374 for (i, b) in sine(4800, 6000.0, 0.3, 0).iter().enumerate() {
1375 input[n / 2 + i] += b;
1376 }
1377 let out = run(&fx, &input, 480, 1);
1378 let band_before = rms_db(&input[n / 2 + 2000..n / 2 + 4800]);
1379 let band_after = rms_db(&out[n / 2 + 2000..n / 2 + 4800]);
1380 assert!(band_before - band_after > 3.0, "burst {band_before:.1} -> {band_after:.1}");
1381 assert!((rms_db(&out[n / 4..n / 2 - 100]) - rms_db(&input[n / 4..n / 2 - 100])).abs() < 0.1);
1382 }
1383
1384 #[test]
1385 fn silence_stays_silent_and_finite() {
1386 let fx = VoiceFx::clean_voice(Strength::Strong, vec![-60.0; PROFILE_BANDS], Some(-50.0));
1387 // A burst, then ten seconds of nothing: no NaN, no denormal left circulating.
1388 let mut input = noise(RATE as usize / 4, 0.3, 5);
1389 input.extend(vec![0.0; RATE as usize * 10]);
1390 let out = run(&fx, &input, 1024, 1);
1391 assert_eq!(out.len(), input.len());
1392 assert!(out.iter().all(|s| s.is_finite()));
1393 let tail = &out[out.len() - RATE as usize..];
1394 assert!(tail.iter().all(|s| *s == 0.0 || s.abs() >= f32::MIN_POSITIVE), "no denormals");
1395 assert!(tail.iter().all(|s| s.abs() < 1e-9), "silence in, silence out");
1396 let mut chain = VoiceChain::new(&fx, RATE, 2);
1397 assert!(chain.process(vec![0.0; 9600]).iter().all(|s| *s == 0.0));
1398 }
1399
1400 #[test]
1401 fn the_output_does_not_depend_on_where_the_blocks_are_cut() {
1402 let profile = learn_profile(&noise(RATE as usize, 0.01, 1)).unwrap().0;
1403 let fx = VoiceFx::clean_voice(Strength::Medium, profile, Some(-40.0));
1404 // One continuous 300 Hz sine whose level steps every half second (each step lands on a zero crossing).
1405 let mut input = Vec::new();
1406 for i in 0..4 {
1407 let amp = if i % 2 == 0 { 0.4 } else { 0.01 };
1408 input.extend(sine(RATE as usize / 2, 300.0, amp, i * RATE as usize / 2));
1409 }
1410 let whole = run(&fx, &input, input.len(), 1);
1411 for chunk in [1usize, 37, 480, 513, 4410] {
1412 let cut = run(&fx, &input, chunk, 1);
1413 assert_eq!(cut.len(), whole.len());
1414 let worst = cut.iter().zip(&whole).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
1415 assert!(worst < 1e-5, "chunk {chunk}: differs by {worst}");
1416 }
1417 // And no step bigger than the signal's own anywhere (a 0.4 sine at 300 Hz steps ~0.016).
1418 let step = whole.windows(2).map(|w| (w[1] - w[0]).abs()).fold(0.0f32, f32::max);
1419 assert!(step < 0.1, "largest step {step}");
1420 }
1421
1422 #[test]
1423 fn stereo_channels_share_one_gain() {
1424 let (profile, _) = learn_profile(&noise(RATE as usize, 0.02, 4)).unwrap();
1425 let fx = only_nr(0.9, profile);
1426 let mono = noise(RATE as usize, 0.05, 11);
1427 let stereo: Vec<f32> = mono.iter().flat_map(|&s| [s, s * 0.5]).collect();
1428 let out = run(&fx, &stereo, 960, 2);
1429 assert_eq!(out.len(), stereo.len());
1430 for f in out.as_chunks::<2>().0.iter().skip(5000).take(20000) {
1431 assert!((f[1] - f[0] * 0.5).abs() < 1e-5, "the image moved: {} {}", f[0], f[1]);
1432 }
1433 }
1434
1435 #[test]
1436 fn the_quietest_finder_skips_gaps_and_finds_the_pause() {
1437 let mut finder = QuietestFinder::new(RATE);
1438 let r = RATE as usize;
1439 let mut sound = noise(r, 0.2, 1); // speech-ish
1440 sound.extend(vec![0.0; r]); // a gap
1441 sound.extend(noise(r, 0.01, 2)); // the pause
1442 sound.extend(noise(r, 0.2, 3));
1443 for c in sound.chunks(777) {
1444 finder.push(c);
1445 }
1446 let (best, end) = finder.best().unwrap();
1447 assert_eq!(best.len(), RATE as usize / 2);
1448 assert!(end > 2 * r as u64 && end <= 3 * r as u64, "ended at {end}");
1449 let level = rms_db(&best);
1450 assert!((level + 40.0).abs() < 1.5, "found {level:.1} dB");
1451 }
1452
1453 #[test]
1454 fn clean_voice_presets_are_in_range_and_grow_with_strength() {
1455 let profile = vec![-60.0; PROFILE_BANDS];
1456 let mut last = 0.0;
1457 for s in [Strength::Light, Strength::Medium, Strength::Strong] {
1458 let fx = VoiceFx::clean_voice(s, profile.clone(), Some(-55.0));
1459 assert_eq!(fx.clamped().as_ref(), Some(&fx), "{s:?} is inside every range");
1460 assert!(fx.is_active() && fx.nr_active());
1461 assert!(fx.nr.strength > last);
1462 last = fx.nr.strength;
1463 }
1464 let none = VoiceFx::clean_voice(Strength::Medium, Vec::new(), None);
1465 assert!(!none.nr.on, "no profile, no reduction");
1466 assert!(none.gate.on && none.comp.on && none.deess.on);
1467 assert_eq!(none.summary(), "gate -45 dB, comp -24 dB 3:1, de-ess -30 dB");
1468 }
1469
1470 /// `cargo test --release -p engine voice_speed -- --ignored --nocapture`
1471 #[test]
1472 #[ignore = "benchmark"]
1473 fn voice_speed() {
1474 let (profile, _) = learn_profile(&noise(RATE as usize, 0.01, 1)).unwrap();
1475 let fx = VoiceFx::clean_voice(Strength::Strong, profile, Some(-45.0));
1476 let secs = 20;
1477 let input: Vec<f32> = (0..RATE as usize * secs)
1478 .flat_map(|i| {
1479 let s = 0.2 * (i as f32 * 0.03).sin() + 0.01 * ((i * 7919 % 1000) as f32 / 500.0 - 1.0);
1480 [s, s]
1481 })
1482 .collect();
1483 let t = std::time::Instant::now();
1484 let out = run(&fx, &input, 1024, 2);
1485 let el = t.elapsed().as_secs_f64();
1486 println!(
1487 "voice chain, 1 lane 48 kHz stereo: {secs} s in {el:.3} s = {:.0}x realtime ({} frames)",
1488 secs as f64 / el,
1489 out.len() / 2
1490 );
1491 }
1492}