feat(quench): add Quench sub-safe clipper

Quench splits the signal with a Linkwitz-Riley crossover and lets the sub
pass unclipped. The top is clipped symmetrically at the ceiling minus the
sub's held peak, so it does not pump at the sub's rate and the sum stays
under the ceiling. What the clip removes is high-passed at the split, so its
products stay out of the low band. Two correction passes and an oversampled
hard clip hold the ceiling; a safety clip catches the downsampler's ringing.

- Controls: Drive, Ceiling, Split, Hold, Soft, Bypass.
- Listen to Quench, a plain clipper at the same settings, or the delta.
- Editor meter compares how much the low band changed for Quench and for a
  plain clip, with a scope of the output, the sub and the top's room.
- Measured: sub level +0.04 dB against -2.2 dB for a plain clip, low-band
  products -35 dB against -16 dB, at 0.5-1.2 dB less RMS.
- Registered in the catalog, workflows, editor-check, README, chain and
  development docs, and the website copy.
This commit is contained in:
nvrl committed 2026-11-06 15:51:36 +01:00
1 parent 77ee4a9078
commit 3d316cbe49
28 files changed
+4397 -17

No files matched your search

+17
View File
@@ -165,5 +165,22 @@
"braze-core",
"braze-ui"
]
},
"quench": {
"name": "Quench",
"description": "Clips the top as hard as you like while the sub passes clean",
"manifest": "plugins/quench/plugin/Cargo.toml",
"library": "quench",
"documentation": "docs/quench",
"clap_id": "io.narl.bass-foundry.quench",
"licenses": {
"plugins/common/ui/assets/OFL.txt": "licenses/Roboto-OFL.txt"
},
"packages": [
"common-ui",
"common-dsp",
"quench-core",
"quench-ui"
]
}
}
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "quench-core"
version = "0.1.0"
edition.workspace = true
license.workspace = true
[dependencies]
common-dsp = { path = "../../common/dsp" }
serde = { workspace = true }
[dev-dependencies]
serde_json = { workspace = true }
+422
View File
@@ -0,0 +1,422 @@
//! A clipper that leaves the sub alone.
//!
//! A plain clipper clips the sum of sub and top. Near the sub's peaks only one side of the top
//! gets clipped, so the clipping takes energy out at the sub's rate: the sub loses level and
//! the low band fills with products that were not in the mix.
//!
//! Quench splits the signal with a Linkwitz–Riley crossover. The sub passes untouched. The
//! top is clipped symmetrically at the room the sub leaves under the ceiling: the ceiling
//! minus the sub's held peak. Holding the peak through the sub's cycle keeps the top's clip
//! level steady, so the top is not pumped at the sub's rate. What the clip removes is then
//! high-passed at the split, so its products below the split do not reach the low band.
//! High-passing lets a few peaks overshoot; two correction passes clip those and high-pass the
//! correction again. A hard clip at the ceiling, still oversampled, takes the small rest, and a
//! safety clip after the downsampler catches its ringing.
//!
//! Everything runs at 4× oversampling. Plain clipping of the same signal runs alongside, for
//! the Plain monitor and for the meter that compares how much each changes the low band.
mod settings;
use common_dsp::oversample::Oversampler;
use common_dsp::svf::{Svf, SvfCoef};
use common_dsp::{coefficient, db_to_gain, gain_to_db};
pub use settings::{Settings, CEILING_MIN, DRIVE_MAX, HOLD_MAX, HOLD_MIN, SPLIT_MAX, SPLIT_MIN};
const Q: f32 = std::f32::consts::FRAC_1_SQRT_2;
const FACTOR: usize = Oversampler::FACTOR;
/// Correction passes after the top's clip.
pub const PASSES: usize = 2;
/// Points in the scope, each the extremes of `SCOPE_STEP` samples.
pub const SCOPE: usize = 256;
const SCOPE_STEP: usize = 8;
const SCOPE_LEN: usize = SCOPE * SCOPE_STEP;
/// Averaging time of the low-band meter.
const METER_MS: f32 = 300.;
const SMOOTH_MS: f32 = 20.;
const BYPASS_MS: f32 = 10.;
pub const SILENT: f32 = -120.;
/// Below this sub energy (−50 dB RMS) the low-band meter has nothing to compare against.
const SUB_FLOOR: f32 = 1e-5;
/// What the output plays. Monitors are not saved.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Monitor {
#[default]
Quench,
/// A plain clipper at the same Drive, Ceiling and Soft, for comparison.
Plain,
/// What Quench takes away: its output minus the unclipped input.
Delta,
}
#[derive(Clone, Copy, Debug)]
pub struct AnalyzerFrame {
/// Peak after Drive, in dBFS, since the last frame.
pub input_peak: f32,
pub output_peak: f32,
/// Peak of the sub band after Drive.
pub sub_peak: f32,
/// How far the top's loudest peak went past its clip level, in dB. 0 when nothing clipped.
pub top_clip: f32,
/// How far the final safety clip reached, in dB. 0 when it did nothing.
pub safety: f32,
/// Change of the low band below the split, against the sub, in dB: Quench and a plain clip
/// of the same signal. NaN without a sub.
pub low_quench: f32,
pub low_plain: f32,
pub ceiling: f32,
pub latency: u32,
pub sample_rate: f32,
/// Latest output of the selected monitor (oldest first), as extremes per point.
pub scope_min: [f32; SCOPE],
pub scope_max: [f32; SCOPE],
/// The sub band and the room it leaves the top, at the same points.
pub scope_sub: [f32; SCOPE],
pub scope_room: [f32; SCOPE],
}
impl Default for AnalyzerFrame {
fn default() -> Self {
Self {
input_peak: SILENT,
output_peak: SILENT,
sub_peak: SILENT,
top_clip: 0.,
safety: 0.,
low_quench: f32::NAN,
low_plain: f32::NAN,
ceiling: Settings::default().ceiling,
latency: Oversampler::latency() as u32,
sample_rate: 48000.,
scope_min: [0.; SCOPE],
scope_max: [0.; SCOPE],
scope_sub: [0.; SCOPE],
scope_room: [0.; SCOPE],
}
}
}
/// Clips `h` to ±`limit`. `knee` (0–1) is the share of the range below `limit` that bends:
/// 0 is a hard clip. Never exceeds `limit`.
#[inline]
pub fn shape(h: f32, limit: f32, knee: f32) -> f32 {
let a = limit * (1. - knee);
let m = h.abs();
if m <= a {
return h;
}
let w = limit - a;
let y = if w <= 1e-9 {
limit
} else {
a + w * ((m - a) / w).tanh()
};
y.min(limit).copysign(h)
}
/// One band of a Linkwitz–Riley crossover: two Butterworth stages.
#[inline]
fn lr4(f: &mut [Svf; 2], c: &SvfCoef, v: f32) -> f32 {
let v = f[0].process(c, v);
f[1].process(c, v)
}
#[derive(Clone, Copy)]
struct Coefs {
low: SvfCoef,
high: SvfCoef,
/// Held-peak length in oversampled samples, and its release per sample after that.
hold: usize,
release: f32,
knee: f32,
}
impl Coefs {
fn new(rate: f32, s: &Settings) -> Self {
let fast = rate * FACTOR as f32;
Self {
low: SvfCoef::lowpass(fast, s.split, Q),
high: SvfCoef::highpass(fast, s.split, Q),
hold: (s.hold * 0.001 * fast) as usize,
release: 1. - coefficient(fast, s.hold),
knee: s.soft * 0.01,
}
}
}
struct Channel {
os: Oversampler,
low: [Svf; 2],
high: [Svf; 2],
/// High-passes what the top's clip removed.
error: Svf,
passes: [Svf; PASSES],
env: f32,
hold_left: usize,
meter_quench: [Svf; 2],
meter_plain: [Svf; 2],
/// The input delayed by the latency, for bypass.
dry: Vec<f32>,
}
impl Channel {
fn new(latency: usize) -> Self {
Self {
os: Oversampler::new(),
low: [Svf::default(); 2],
high: [Svf::default(); 2],
error: Svf::default(),
passes: [Svf::default(); PASSES],
env: 0.,
hold_left: 0,
meter_quench: [Svf::default(); 2],
meter_plain: [Svf::default(); 2],
dry: vec![0.; latency + 1],
}
}
fn reset(&mut self) {
self.os.reset();
for f in self
.low
.iter_mut()
.chain(self.high.iter_mut())
.chain(self.passes.iter_mut())
.chain(self.meter_quench.iter_mut())
.chain(self.meter_plain.iter_mut())
{
f.reset();
}
self.error.reset();
self.env = 0.;
self.hold_left = 0;
self.dry.fill(0.);
}
}
/// Peaks and energies gathered between two analyzer frames.
#[derive(Clone, Copy, Default)]
struct Gather {
input: f32,
output: f32,
sub: f32,
/// Largest ratio of the top to its room.
top: f32,
safety: f32,
}
pub struct Engine {
rate: f32,
channels: usize,
settings: Settings,
coefs: Coefs,
channel: [Channel; 2],
drive: f32,
ceiling: f32,
bypass: f32,
primed: bool,
smooth: f32,
fade: f32,
meter: f32,
dry_at: usize,
energy_quench: f32,
energy_plain: f32,
energy_sub: f32,
gather: Gather,
scope: [[f32; 4]; SCOPE_LEN],
scope_at: usize,
}
impl Engine {
pub fn new(rate: f32, channels: usize) -> Result<Self, &'static str> {
if !(8000.0..=384000.).contains(&rate) {
return Err("unsupported sample rate");
}
if !(1..=2).contains(&channels) {
return Err("unsupported channel count");
}
let settings = Settings::default();
let latency = Oversampler::latency();
Ok(Self {
rate,
channels,
settings,
coefs: Coefs::new(rate, &settings),
channel: [Channel::new(latency), Channel::new(latency)],
drive: 1.,
ceiling: db_to_gain(settings.ceiling),
bypass: 0.,
primed: false,
smooth: coefficient(rate, SMOOTH_MS),
fade: coefficient(rate, BYPASS_MS),
meter: coefficient(rate * FACTOR as f32, METER_MS),
dry_at: 0,
energy_quench: 0.,
energy_plain: 0.,
energy_sub: 0.,
gather: Gather::default(),
scope: [[0.; 4]; SCOPE_LEN],
scope_at: 0,
})
}
pub fn channels(&self) -> usize {
self.channels
}
pub fn latency_samples(&self) -> u32 {
Oversampler::latency() as u32
}
pub fn settings(&self) -> Settings {
self.settings
}
pub fn set_settings(&mut self, s: Settings) -> Result<(), &'static str> {
s.validate()?;
if s != self.settings || !self.primed {
self.coefs = Coefs::new(self.rate, &s);
}
self.settings = s;
if !self.primed {
// The first settings after a start take effect at once instead of ramping.
self.drive = db_to_gain(s.drive);
self.ceiling = db_to_gain(s.ceiling);
self.bypass = if s.bypass { 1. } else { 0. };
self.primed = true;
}
Ok(())
}
pub fn reset(&mut self) {
for c in &mut self.channel {
c.reset();
}
self.dry_at = 0;
self.energy_quench = 0.;
self.energy_plain = 0.;
self.energy_sub = 0.;
self.gather = Gather::default();
self.scope = [[0.; 4]; SCOPE_LEN];
self.scope_at = 0;
self.primed = false;
let s = self.settings;
let _ = self.set_settings(s);
}
pub fn process_sample(&mut self, x: [f32; 2], monitor: Monitor) -> [f32; 2] {
let s = self.settings;
self.drive += self.smooth * (db_to_gain(s.drive) - self.drive);
self.ceiling += self.smooth * (db_to_gain(s.ceiling) - self.ceiling);
self.bypass += self.fade * (if s.bypass { 1. } else { 0. } - self.bypass);
let (c, k, drive) = (self.ceiling, self.coefs, self.drive);
let mut out = [0.; 2];
let mut point = [f32::MAX, f32::MIN, 0., 0.];
let n = self.channel[0].dry.len();
for (ch, &input) in x.iter().enumerate().take(self.channels) {
let chan = &mut self.channel[ch];
let driven = input * drive;
self.gather.input = self.gather.input.max(driven.abs());
let up = chan.os.up(driven);
let mut picked = [0.; FACTOR];
for (j, &v) in up.iter().enumerate() {
let low = lr4(&mut chan.low, &k.low, v);
let high = lr4(&mut chan.high, &k.high, v);
// The sub's held peak decides the top's room.
let a = low.abs();
if a >= chan.env {
chan.env = a;
chan.hold_left = k.hold;
} else if chan.hold_left > 0 {
chan.hold_left -= 1;
} else {
chan.env = a.max(chan.env * k.release);
}
let room = (c - chan.env).max(0.);
let top = shape(high, room, k.knee);
let reference = low + high;
let mut y = reference + chan.error.process(&k.high, top - high);
for p in &mut chan.passes {
y += p.process(&k.high, y.clamp(-c, c) - y);
}
// What the passes leave over the ceiling is small; clipping it here, still
// oversampled, leaves the safety clip after the downsampler almost idle.
let y = y.clamp(-c, c);
let plain = shape(reference, c, k.knee);
let lq = lr4(&mut chan.meter_quench, &k.low, y - reference);
let lp = lr4(&mut chan.meter_plain, &k.low, plain - reference);
self.energy_quench += self.meter * (lq * lq - self.energy_quench);
self.energy_plain += self.meter * (lp * lp - self.energy_plain);
self.energy_sub += self.meter * (low * low - self.energy_sub);
self.gather.sub = self.gather.sub.max(a);
if high.abs() > room {
let ratio = high.abs() / room.max(c * 1e-3);
self.gather.top = self.gather.top.max(ratio);
}
picked[j] = match monitor {
Monitor::Quench => y,
Monitor::Plain => plain,
Monitor::Delta => y - reference,
};
if ch == 0 {
point[0] = point[0].min(picked[j]);
point[1] = point[1].max(picked[j]);
point[2] = low;
point[3] = room;
}
}
let mut o = chan.os.down(picked);
if monitor != Monitor::Delta && o.abs() > c {
self.gather.safety = self.gather.safety.max(o.abs() / c);
o = o.clamp(-c, c);
}
let dry = chan.dry[(self.dry_at + 1) % n];
chan.dry[self.dry_at] = input;
o = if self.bypass >= 1. - 1e-6 {
dry
} else {
o + self.bypass * (dry - o)
};
self.gather.output = self.gather.output.max(o.abs());
out[ch] = o;
}
self.dry_at = (self.dry_at + 1) % n;
self.scope[self.scope_at] = point;
self.scope_at = (self.scope_at + 1) % SCOPE_LEN;
out
}
/// Readings since the last call. Never allocates.
pub fn take_analyzer(&mut self) -> AnalyzerFrame {
let g = std::mem::take(&mut self.gather);
let db = |v: f32| if v > 0. { gain_to_db(v) } else { SILENT };
let relative = |e: f32| {
if self.energy_sub > SUB_FLOOR {
10. * (e.max(1e-20) / self.energy_sub).log10()
} else {
f32::NAN
}
};
let mut f = AnalyzerFrame {
input_peak: db(g.input),
output_peak: db(g.output),
sub_peak: db(g.sub),
top_clip: if g.top > 1. { gain_to_db(g.top) } else { 0. },
safety: if g.safety > 1. {
gain_to_db(g.safety)
} else {
0.
},
low_quench: relative(self.energy_quench),
low_plain: relative(self.energy_plain),
ceiling: self.settings.ceiling,
latency: self.latency_samples(),
sample_rate: self.rate,
..AnalyzerFrame::default()
};
for i in 0..SCOPE {
let (mut lo, mut hi) = (f32::MAX, f32::MIN);
let mut last = [0.; 4];
for j in 0..SCOPE_STEP {
let v = self.scope[(self.scope_at + i * SCOPE_STEP + j) % SCOPE_LEN];
lo = lo.min(v[0]);
hi = hi.max(v[1]);
last = v;
}
f.scope_min[i] = if lo <= hi { lo } else { 0. };
f.scope_max[i] = if lo <= hi { hi } else { 0. };
f.scope_sub[i] = last[2];
f.scope_room[i] = last[3];
}
f
}
}
+58
View File
@@ -0,0 +1,58 @@
//! Host-independent controls. Levels in dB, times in milliseconds, amounts in percent.
use serde::{Deserialize, Serialize};
pub const DRIVE_MAX: f32 = 24.;
pub const CEILING_MIN: f32 = -12.;
pub const SPLIT_MIN: f32 = 40.;
pub const SPLIT_MAX: f32 = 300.;
pub const HOLD_MIN: f32 = 10.;
pub const HOLD_MAX: f32 = 300.;
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Settings {
/// Gain into the clipper.
pub drive: f32,
/// Highest output peak, in dBFS.
pub ceiling: f32,
/// Everything below this frequency is the sub: it passes without clipping.
pub split: f32,
/// How long the sub's peak keeps its headroom reserved. Longer than half a period of the
/// lowest note keeps the top's clip level steady through the sub's cycle.
pub hold: f32,
/// Knee of the top's clipper: 0 % is a hard clip, 100 % a soft curve from the start.
pub soft: f32,
pub bypass: bool,
}
impl Default for Settings {
fn default() -> Self {
Self {
drive: 0.,
ceiling: -0.3,
split: 120.,
hold: 60.,
soft: 0.,
bypass: false,
}
}
}
impl Settings {
pub fn validate(&self) -> Result<(), &'static str> {
let finite = [self.drive, self.ceiling, self.split, self.hold, self.soft]
.iter()
.all(|v| v.is_finite());
if !finite {
return Err("non-finite setting");
}
let ok = (0.0..=DRIVE_MAX).contains(&self.drive)
&& (CEILING_MIN..=0.).contains(&self.ceiling)
&& (SPLIT_MIN..=SPLIT_MAX).contains(&self.split)
&& (HOLD_MIN..=HOLD_MAX).contains(&self.hold)
&& (0.0..=100.).contains(&self.soft);
if ok {
Ok(())
} else {
Err("setting out of range")
}
}
}
+300
View File
@@ -0,0 +1,300 @@
use quench_core::{shape, Engine, Monitor, Settings};
use std::f64::consts::TAU;
const RATE: f32 = 48000.;
/// Partials of the top: not harmonics of the sub, so their clipping products can be told
/// apart from the sub's own harmonics.
const TOPS: [f64; 5] = [437., 611., 1013., 1597., 2399.];
fn top(t: f64) -> f64 {
TOPS.iter()
.enumerate()
.map(|(i, f)| (TAU * f * t + i as f64).sin())
.sum::<f64>()
/ 4.2
}
/// Mono render of `seconds` of `signal`, returned as the left channel.
fn render(
engine: &mut Engine,
seconds: f32,
monitor: Monitor,
signal: impl Fn(f64) -> f64,
) -> Vec<f32> {
let n = (seconds * RATE) as usize;
(0..n)
.map(|i| {
let v = signal(i as f64 / RATE as f64) as f32;
engine.process_sample([v, v], monitor)[0]
})
.collect()
}
fn engine(s: Settings) -> Engine {
let mut e = Engine::new(RATE, 2).unwrap();
e.set_settings(s).unwrap();
e
}
/// Amplitude of `hz` over a whole number of its periods at the end of `x`.
fn amplitude(x: &[f32], hz: f64) -> f64 {
let n = (RATE as f64 / hz * (0.5 * hz).floor()) as usize;
let x = &x[x.len() - n..];
let (mut re, mut im) = (0., 0.);
for (i, &v) in x.iter().enumerate() {
let a = TAU * hz * i as f64 / RATE as f64;
re += v as f64 * a.cos();
im += v as f64 * a.sin();
}
2. * (re * re + im * im).sqrt() / n as f64
}
/// Hann-windowed spectrum magnitude of the last half second, 2 Hz bins up to `top_bin`.
fn spectrum(x: &[f32], top_bin: usize) -> Vec<f64> {
let n = RATE as usize / 2;
let x = &x[x.len() - n..];
let w: Vec<f64> = (0..n)
.map(|i| 0.5 - 0.5 * (TAU * i as f64 / n as f64).cos())
.collect();
let norm: f64 = w.iter().sum();
(0..=top_bin)
.map(|b| {
let (mut re, mut im) = (0., 0.);
for i in 0..n {
let a = TAU * b as f64 * i as f64 / n as f64;
re += x[i] as f64 * w[i] * a.cos();
im += x[i] as f64 * w[i] * a.sin();
}
2. * (re * re + im * im).sqrt() / norm
})
.collect()
}
/// Everything below 110 Hz except the 50 Hz sub, against the sub, in dB.
fn low_junk(x: &[f32]) -> f64 {
let s = spectrum(x, 55);
let junk: f64 = s
.iter()
.enumerate()
.filter(|(b, _)| !(22..=28).contains(b) && *b > 0)
.map(|(_, v)| v * v)
.sum();
let sub: f64 = s[22..=28].iter().map(|v| v * v).sum();
10. * (junk / sub).log10()
}
fn db(r: f64) -> f64 {
20. * r.log10()
}
#[test]
fn below_the_ceiling_the_signal_passes_unchanged() {
let mut e = engine(Settings::default());
let signal = |t: f64| 0.3 * (TAU * 50. * t).sin() + 0.2 * (TAU * 1000. * t).sin();
let out = render(&mut e, 1., Monitor::Quench, signal);
for (hz, a) in [(50., 0.3), (1000., 0.2)] {
let got = db(amplitude(&out, hz) / a);
assert!(got.abs() < 0.02, "{hz} Hz: {got:.3} dB");
}
let f = e.take_analyzer();
assert_eq!(f.top_clip, 0.);
assert_eq!(f.safety, 0.);
let mut e = engine(Settings::default());
let delta = render(&mut e, 0.2, Monitor::Delta, signal);
assert!(delta.iter().all(|v| v.abs() < 1e-4));
}
#[test]
fn the_output_never_passes_the_ceiling() {
let mut seed = 1u32;
let noise: Vec<f64> = (0..RATE as usize)
.map(|_| {
seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
(seed >> 8) as f64 / (1u32 << 24) as f64 * 2. - 1.
})
.collect();
for ceiling in [-6., -0.3, 0.] {
for soft in [0., 50., 100.] {
for monitor in [Monitor::Quench, Monitor::Plain] {
let mut e = engine(Settings {
drive: 24.,
ceiling,
soft,
..Settings::default()
});
let out = render(&mut e, 1., monitor, |t| {
let i = ((t * RATE as f64) as usize).min(noise.len() - 1);
0.4 * (TAU * 41. * t).sin() + 0.3 * top(t) + 0.2 * noise[i]
});
let limit = 10f32.powf(ceiling / 20.) * (1. + 1e-6);
let peak = out.iter().fold(0f32, |m, v| m.max(v.abs()));
assert!(
peak <= limit,
"{ceiling} dB, soft {soft}, {monitor:?}: {peak}"
);
}
}
}
}
#[test]
fn the_sub_keeps_its_level_and_the_low_band_stays_clean() {
// A quiet sub under a top that peaks far over the ceiling: the hard case for a clipper.
let signal = |t: f64| 0.3 * (TAU * 50. * t).sin() + 2. * top(t);
let mut results = Vec::new();
for monitor in [Monitor::Quench, Monitor::Plain] {
let mut e = engine(Settings::default());
let out = render(&mut e, 1.5, monitor, signal);
let sub = db(amplitude(&out, 50.) / 0.3);
results.push((sub, low_junk(&out)));
}
let [(q_sub, q_junk), (p_sub, p_junk)] = [results[0], results[1]];
assert!(q_sub.abs() < 0.2, "Quench changes the sub by {q_sub:.2} dB");
assert!(
p_sub < -0.8,
"a plain clip should squash the sub: {p_sub:.2} dB"
);
assert!(
q_junk < p_junk - 10.,
"low-band products: Quench {q_junk:.1} dB, plain {p_junk:.1} dB"
);
}
#[test]
fn the_meter_shows_how_much_less_the_low_band_changes() {
let mut e = engine(Settings::default());
render(&mut e, 1.5, Monitor::Quench, |t| {
0.3 * (TAU * 50. * t).sin() + 2. * top(t)
});
let f = e.take_analyzer();
assert!(
f.low_quench < f.low_plain - 10.,
"Quench {:.1} dB, plain {:.1} dB",
f.low_quench,
f.low_plain
);
assert!(f.top_clip > 6.);
// The oversampled clip leaves the safety clip after the downsampler almost idle.
assert!(f.safety < 0.2, "{}", f.safety);
let mut e = engine(Settings::default());
render(&mut e, 0.5, Monitor::Quench, |t| {
0.5 * (TAU * 1000. * t).sin()
});
assert!(
e.take_analyzer().low_quench.is_nan(),
"no sub, nothing to compare"
);
}
#[test]
fn a_sub_over_the_ceiling_leaves_no_room_and_is_still_limited() {
let mut e = engine(Settings {
ceiling: -6.,
..Settings::default()
});
let out = render(&mut e, 1., Monitor::Quench, |t| {
0.8 * (TAU * 50. * t).sin() + 0.3 * top(t)
});
let f = e.take_analyzer();
assert!(f.sub_peak > -6., "{}", f.sub_peak);
assert!(f.safety > 0.);
let peak = out.iter().fold(0f32, |m, v| m.max(v.abs()));
assert!(peak <= 0.5012 * (1. + 1e-6));
let room = f.scope_room.iter().fold(0f32, |m, v| m.max(*v));
assert_eq!(room, 0., "the held sub peak is over the ceiling");
}
#[test]
fn the_held_peak_keeps_the_tops_room_steady_through_the_cycle() {
let room_ripple = |hold: f32, hz: f64| {
let mut e = engine(Settings {
hold,
..Settings::default()
});
render(&mut e, 1., Monitor::Quench, |t| {
0.5 * (TAU * hz * t).sin() + 0.3 * top(t)
});
let f = e.take_analyzer();
let (lo, hi) = f
.scope_room
.iter()
.fold((f32::MAX, f32::MIN), |(a, b), v| (a.min(*v), b.max(*v)));
(hi - lo) / hi
};
// 30 Hz: the sub peaks every 16.7 ms.
let held = room_ripple(60., 30.);
let short = room_ripple(10., 30.);
assert!(held < 0.01, "{held}");
assert!(short > 0.1, "{short}");
}
#[test]
fn bypass_is_the_input_delayed_by_the_latency() {
let mut e = engine(Settings {
bypass: true,
drive: 12.,
..Settings::default()
});
let latency = e.latency_samples() as usize;
let x: Vec<f32> = (0..4800)
.map(|i| (0.9 * (TAU * 50. * i as f64 / RATE as f64).sin()) as f32 + 0.5)
.collect();
let out: Vec<f32> = x
.iter()
.map(|&v| e.process_sample([v, v], Monitor::Quench)[0])
.collect();
for i in latency..x.len() {
assert_eq!(out[i], x[i - latency]);
}
}
#[test]
fn mono_works_and_the_shape_never_passes_its_limit() {
let mut e = Engine::new(44100., 1).unwrap();
e.set_settings(Settings {
drive: 12.,
..Settings::default()
})
.unwrap();
for i in 0..44100 {
let v = (TAU * 55. * i as f64 / 44100.).sin() as f32;
let o = e.process_sample([v, 0.], Monitor::Quench);
assert!(o[0].abs() <= 0.9661 && o[1] == 0.);
}
for knee in [0., 0.3, 1.] {
for h in [-5., -1., -0.2, 0., 0.5, 0.99, 3.] {
let y = shape(h, 0.8, knee);
assert!(y.abs() <= 0.8 && y * h >= 0.);
}
}
assert_eq!(shape(0.5, 0.8, 0.), 0.5);
assert_eq!(shape(0.5, 0., 0.), 0.);
}
#[test]
fn settings_are_validated_and_serialise() {
assert!(Settings::default().validate().is_ok());
for bad in [
Settings {
drive: -1.,
..Settings::default()
},
Settings {
ceiling: 0.5,
..Settings::default()
},
Settings {
split: 20.,
..Settings::default()
},
Settings {
hold: f32::NAN,
..Settings::default()
},
] {
assert!(bad.validate().is_err());
assert!(Engine::new(RATE, 2).unwrap().set_settings(bad).is_err());
}
let s = Settings {
drive: 9.,
soft: 40.,
..Settings::default()
};
let json = serde_json::to_string(&s).unwrap();
assert_eq!(serde_json::from_str::<Settings>(&json).unwrap(), s);
assert!(serde_json::from_str::<Settings>(r#"{"drive":0,"oops":1}"#).is_err());
}
+65
View File
@@ -0,0 +1,65 @@
use quench_core::{Engine, Monitor, Settings};
use std::{
alloc::{GlobalAlloc, Layout, System},
cell::Cell,
};
struct CheckedAllocator;
thread_local! {
static CHECK:Cell<bool>=const {Cell::new(false)};
static OPERATIONS:Cell<usize>=const {Cell::new(0)};
}
fn record() {
if CHECK.try_with(Cell::get).unwrap_or(false) {
let _ = OPERATIONS.try_with(|n| n.set(n.get() + 1));
}
}
unsafe impl GlobalAlloc for CheckedAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
record();
unsafe { System.alloc(layout) }
}
unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {
record();
unsafe { System.dealloc(pointer, layout) }
}
unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, size: usize) -> *mut u8 {
record();
unsafe { System.realloc(pointer, layout, size) }
}
}
#[global_allocator]
static ALLOCATOR: CheckedAllocator = CheckedAllocator;
#[test]
fn processing_settings_monitors_and_analysis_do_not_allocate_or_free() {
let mut engine = Engine::new(48000., 2).unwrap();
let mut settings = Settings {
drive: 12.,
..Settings::default()
};
engine.set_settings(settings).unwrap();
let monitors = [Monitor::Quench, Monitor::Plain, Monitor::Delta];
CHECK.with(|v| v.set(true));
for i in 0..96000 {
if i % 4800 == 0 {
let step = i / 4800;
settings.split = 60. + 20. * (step % 6) as f32;
settings.hold = 20. + 40. * (step % 3) as f32;
settings.soft = 25. * (step % 5) as f32;
settings.ceiling = -3. * (step % 3) as f32;
settings.bypass = step % 7 == 6;
engine.set_settings(settings).unwrap();
}
let t = i as f32 / 48000.;
let x = (std::f32::consts::TAU * 45. * t).sin() * 0.5
+ (std::f32::consts::TAU * 733. * t).sin() * 0.5;
std::hint::black_box(engine.process_sample([x, -x], monitors[(i / 9600) % 3]));
if i % 1600 == 0 {
std::hint::black_box(engine.take_analyzer());
}
}
engine.reset();
CHECK.with(|v| v.set(false));
assert_eq!(OPERATIONS.with(Cell::get), 0);
}
+2381
View File
File diff suppressed because it is too large. Load diff
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "quench"
version = "0.1.0"
edition = "2021"
license = "ISC"
[workspace]
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
nih_plug = { git = "https://github.com/robbert-vdh/nih-plug.git", rev = "de421011f41a6d10fc8c7a6084e4f4dee0143683", default-features = false }
nih_plug_egui = { git = "https://github.com/robbert-vdh/nih-plug.git", rev = "de421011f41a6d10fc8c7a6084e4f4dee0143683" }
quench-core = { path = "../core" }
quench-ui = { path = "../ui" }
crossbeam-queue = "0.3"
[dev-dependencies]
clap-sys = { git = "https://github.com/micahrj/clap-sys.git", rev = "25d7f53fdb6363ad63fbd80049cb7a42a97ac156" }
serde_json = "1"
[profile.release]
lto = "thin"
strip = "symbols"
+204
View File
@@ -0,0 +1,204 @@
//! CLAP audio effect. All DSP state is owned by the processing thread.
mod params;
use crossbeam_queue::ArrayQueue;
use nih_plug::prelude::*;
use nih_plug_egui::{create_egui_editor, egui};
use params::{QuenchParams, FLOATS};
use quench_core::{AnalyzerFrame, Engine, Monitor};
use std::sync::{
atomic::{AtomicU8, Ordering},
Arc,
};
struct Shared {
analyzer: ArrayQueue<AnalyzerFrame>,
/// The editor's listen choice: 0 Quench, 1 Plain, 2 Delta.
monitor: AtomicU8,
}
fn encode(m: Monitor) -> u8 {
match m {
Monitor::Quench => 0,
Monitor::Plain => 1,
Monitor::Delta => 2,
}
}
fn decode(v: u8) -> Monitor {
match v {
1 => Monitor::Plain,
2 => Monitor::Delta,
_ => Monitor::Quench,
}
}
struct EditorData {
ui: quench_ui::State,
gestures: [bool; FLOATS],
}
pub struct Quench {
params: Arc<QuenchParams>,
shared: Arc<Shared>,
engine: Option<Engine>,
publish_count: usize,
publish_interval: usize,
}
impl Default for Quench {
fn default() -> Self {
Self {
params: Arc::new(QuenchParams::default()),
shared: Arc::new(Shared {
analyzer: ArrayQueue::new(2),
monitor: AtomicU8::new(0),
}),
engine: None,
publish_count: 0,
publish_interval: 1600,
}
}
}
impl Plugin for Quench {
const NAME: &'static str = "Quench";
const VENDOR: &'static str = "Bass Foundry";
const URL: &'static str = "";
const EMAIL: &'static str = "";
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
const AUDIO_IO_LAYOUTS: &'static [AudioIOLayout] = &[
AudioIOLayout {
main_input_channels: NonZeroU32::new(2),
main_output_channels: NonZeroU32::new(2),
..AudioIOLayout::const_default()
},
AudioIOLayout {
main_input_channels: NonZeroU32::new(1),
main_output_channels: NonZeroU32::new(1),
..AudioIOLayout::const_default()
},
];
const SAMPLE_ACCURATE_AUTOMATION: bool = false;
type SysExMessage = ();
type BackgroundTask = ();
fn params(&self) -> Arc<dyn Params> {
self.params.clone()
}
fn editor(&mut self, _: AsyncExecutor<Self>) -> Option<Box<dyn Editor>> {
let params = self.params.clone();
let shared = self.shared.clone();
create_egui_editor(
params.editor.clone(),
EditorData {
ui: quench_ui::State::default(),
gestures: [false; FLOATS],
},
|ctx, data| {
data.ui.monitor = Monitor::Quench;
quench_ui::style(ctx);
},
move |ctx, setter, data| {
while let Some(frame) = shared.analyzer.pop() {
data.ui.accept_frame(frame);
}
let before = params.settings();
let mut edited = before;
nih_plug_egui::resizable_window::ResizableWindow::new("quench-editor")
.min_size(egui::vec2(
quench_ui::WIDTH as f32 - 80.,
quench_ui::HEIGHT as f32 - 40.,
))
.show(ctx, &params.editor, |ui| {
quench_ui::show(ui, &mut edited, &mut data.ui)
});
params.apply(
setter,
&before,
&edited,
data.ui.gesture_active,
&mut data.gestures,
);
// The monitor is a listen choice only: never saved and never left on after
// the editor closes.
shared
.monitor
.store(encode(data.ui.monitor), Ordering::Release);
ctx.request_repaint_after(std::time::Duration::from_millis(40));
},
)
}
fn initialize(
&mut self,
layout: &AudioIOLayout,
config: &BufferConfig,
context: &mut impl InitContext<Self>,
) -> bool {
let Ok(mut engine) = Engine::new(
config.sample_rate,
layout.main_input_channels.map_or(0, |v| v.get() as usize),
) else {
return false;
};
if engine.set_settings(self.params.settings()).is_err() {
return false;
}
context.set_latency_samples(engine.latency_samples());
self.shared.monitor.store(0, Ordering::Release);
self.publish_interval = (config.sample_rate / 30.) as usize;
self.engine = Some(engine);
true
}
fn reset(&mut self) {
if let Some(e) = self.engine.as_mut() {
e.reset();
}
self.publish_count = 0;
}
fn process(
&mut self,
buffer: &mut Buffer,
_: &mut AuxiliaryBuffers,
_: &mut impl ProcessContext<Self>,
) -> ProcessStatus {
let Some(engine) = self.engine.as_mut() else {
return ProcessStatus::Normal;
};
let _ = engine.set_settings(self.params.settings());
let monitor = if self.params.editor.is_open() {
decode(self.shared.monitor.load(Ordering::Acquire))
} else {
Monitor::Quench
};
for mut sample in buffer.iter_samples() {
let x = [
*sample.get_mut(0).unwrap(),
if engine.channels() == 2 {
*sample.get_mut(1).unwrap()
} else {
0.
},
];
let out = engine.process_sample(x, monitor);
for (c, value) in sample.into_iter().enumerate() {
*value = out[c];
}
self.publish_count += 1;
if self.publish_count >= self.publish_interval {
let _ = self.shared.analyzer.force_push(engine.take_analyzer());
self.publish_count = 0;
}
}
// The oversampling filters must drain after input stops.
ProcessStatus::KeepAlive
}
}
impl ClapPlugin for Quench {
const CLAP_ID: &'static str = "io.narl.bass-foundry.quench";
const CLAP_DESCRIPTION: Option<&'static str> =
Some("Clips the top as hard as you like while the sub passes clean");
const CLAP_MANUAL_URL: Option<&'static str> = None;
const CLAP_SUPPORT_URL: Option<&'static str> = None;
const CLAP_FEATURES: &'static [ClapFeature] = &[
ClapFeature::AudioEffect,
ClapFeature::Distortion,
ClapFeature::Limiter,
ClapFeature::Mastering,
ClapFeature::Stereo,
ClapFeature::Mono,
];
}
nih_export_clap!(Quench);
+108
View File
@@ -0,0 +1,108 @@
use nih_plug::prelude::*;
use nih_plug_egui::EguiState;
use quench_core::{Settings, CEILING_MIN, DRIVE_MAX, HOLD_MAX, HOLD_MIN, SPLIT_MAX, SPLIT_MIN};
use std::sync::Arc;
fn linear(name: &str, v: f32, min: f32, max: f32, unit: &'static str) -> FloatParam {
FloatParam::new(name, v, FloatRange::Linear { min, max }).with_unit(unit)
}
fn skewed(name: &str, v: f32, min: f32, max: f32, unit: &'static str) -> FloatParam {
FloatParam::new(
name,
v,
FloatRange::Skewed {
min,
max,
factor: FloatRange::skew_factor(-1.),
},
)
.with_unit(unit)
}
/// Continuous controls, in the order of the gesture slots.
pub const FLOATS: usize = 5;
#[derive(Params)]
pub struct QuenchParams {
#[persist = "editor"]
pub editor: Arc<EguiState>,
#[id = "drive"]
pub drive: FloatParam,
#[id = "ceiling"]
pub ceiling: FloatParam,
#[id = "split"]
pub split: FloatParam,
#[id = "hold"]
pub hold: FloatParam,
#[id = "soft"]
pub soft: FloatParam,
#[id = "bypass"]
pub bypass: BoolParam,
}
impl Default for QuenchParams {
fn default() -> Self {
let d = Settings::default();
Self {
editor: EguiState::from_size(quench_ui::WIDTH, quench_ui::HEIGHT),
drive: linear("Drive", d.drive, 0., DRIVE_MAX, " dB"),
ceiling: linear("Ceiling", d.ceiling, CEILING_MIN, 0., " dB"),
split: skewed("Split", d.split, SPLIT_MIN, SPLIT_MAX, " Hz"),
hold: skewed("Hold", d.hold, HOLD_MIN, HOLD_MAX, " ms"),
soft: linear("Soft", d.soft, 0., 100., " %"),
bypass: BoolParam::new("Bypass", false).make_bypass(),
}
}
}
impl QuenchParams {
pub fn settings(&self) -> Settings {
Settings {
drive: self.drive.value(),
ceiling: self.ceiling.value(),
split: self.split.value(),
hold: self.hold.value(),
soft: self.soft.value(),
bypass: self.bypass.value(),
}
}
fn floats(&self) -> [&FloatParam; FLOATS] {
[
&self.drive,
&self.ceiling,
&self.split,
&self.hold,
&self.soft,
]
}
fn values(s: &Settings) -> [f32; FLOATS] {
[s.drive, s.ceiling, s.split, s.hold, s.soft]
}
/// Pushes every changed editor value to the host. Continuous controls hold one gesture
/// while the pointer is down; switches are set in a single gesture.
pub fn apply(
&self,
setter: &ParamSetter,
old: &Settings,
new: &Settings,
dragging: bool,
open: &mut [bool; FLOATS],
) {
let pairs = Self::values(old).into_iter().zip(Self::values(new));
for (i, (p, (a, b))) in self.floats().into_iter().zip(pairs).enumerate() {
if a != b {
if !open[i] {
open[i] = true;
setter.begin_set_parameter(p);
}
setter.set_parameter(p, b);
}
if !dragging && open[i] {
setter.end_set_parameter(p);
open[i] = false;
}
}
if new.bypass != old.bypass {
setter.begin_set_parameter(&self.bypass);
setter.set_parameter(&self.bypass, new.bypass);
setter.end_set_parameter(&self.bypass);
}
}
}
+205
View File
@@ -0,0 +1,205 @@
//! Exercise the actual exported CLAP ABI without requiring a GUI or installed DAW.
use clap_sys::{
audio_buffer::*,
events::*,
ext::{audio_ports::*, latency::*, state::*},
factory::plugin_factory::*,
host::*,
process::*,
stream::*,
version::*,
};
use std::{
ffi::{c_char, c_void, CStr},
io::{Cursor, Read},
ptr,
};
unsafe extern "C" fn extension(_: *const clap_host, _: *const c_char) -> *const c_void {
ptr::null()
}
unsafe extern "C" fn request(_: *const clap_host) {}
unsafe extern "C" fn count(_: *const clap_input_events) -> u32 {
0
}
unsafe extern "C" fn event(_: *const clap_input_events, _: u32) -> *const clap_event_header {
ptr::null()
}
unsafe extern "C" fn push(_: *const clap_output_events, _: *const clap_event_header) -> bool {
true
}
unsafe extern "C" fn write(stream: *const clap_ostream, buffer: *const c_void, size: u64) -> i64 {
// SAFETY: The test owns the Vec for the entire synchronous save call.
let bytes = unsafe { &mut *((*stream).ctx as *mut Vec<u8>) };
bytes.extend_from_slice(unsafe {
std::slice::from_raw_parts(buffer as *const u8, size as usize)
});
size as i64
}
unsafe extern "C" fn read(stream: *const clap_istream, buffer: *mut c_void, size: u64) -> i64 {
// SAFETY: The test owns the Cursor; the wrapper supplies writable stream storage.
let cursor = unsafe { &mut *((*stream).ctx as *mut Cursor<Vec<u8>>) };
cursor
.read(unsafe { std::slice::from_raw_parts_mut(buffer as *mut u8, size as usize) })
.unwrap() as i64
}
#[test]
fn effect_ports_state_latency_and_audio_lifecycle() {
// SAFETY: All callbacks, strings, streams, buffers, and the host outlive their
// synchronous ABI calls. Activation/processing/destruction follow CLAP order.
unsafe {
let entry = &quench::clap_entry;
assert!(entry.init.unwrap()(c"quench.clap".as_ptr()));
let factory = entry.get_factory.unwrap()(CLAP_PLUGIN_FACTORY_ID.as_ptr())
as *const clap_plugin_factory;
assert!(!factory.is_null());
let factory = &*factory;
assert_eq!(factory.get_plugin_count.unwrap()(factory), 1);
let descriptor = factory.get_plugin_descriptor.unwrap()(factory, 0);
assert!(!descriptor.is_null());
assert_eq!(CStr::from_ptr((*descriptor).name), c"Quench");
assert_eq!(
CStr::from_ptr((*descriptor).id),
c"io.narl.bass-foundry.quench"
);
assert!(factory.get_plugin_descriptor.unwrap()(factory, 1).is_null());
let host = clap_host {
clap_version: CLAP_VERSION,
host_data: ptr::null_mut(),
name: c"Storyboard test host".as_ptr(),
vendor: c"Tests".as_ptr(),
url: c"".as_ptr(),
version: c"1.0".as_ptr(),
get_extension: Some(extension),
request_restart: Some(request),
request_process: Some(request),
request_callback: Some(request),
};
let plugin = factory.create_plugin.unwrap()(factory, &host, (*descriptor).id);
assert!(!plugin.is_null());
let p = &*plugin;
assert!(p.init.unwrap()(plugin));
let ports = p.get_extension.unwrap()(plugin, CLAP_EXT_AUDIO_PORTS.as_ptr())
as *const clap_plugin_audio_ports;
assert!(!ports.is_null());
assert_eq!((*ports).count.unwrap()(plugin, false), 1);
assert_eq!((*ports).count.unwrap()(plugin, true), 1);
let latency = p.get_extension.unwrap()(plugin, CLAP_EXT_LATENCY.as_ptr())
as *const clap_plugin_latency;
assert!(!latency.is_null());
let state =
p.get_extension.unwrap()(plugin, CLAP_EXT_STATE.as_ptr()) as *const clap_plugin_state;
assert!(!state.is_null());
let state = &*state;
let save = || {
let mut bytes = Vec::new();
let stream = clap_ostream {
ctx: &mut bytes as *mut Vec<u8> as *mut c_void,
write: Some(write),
};
assert!(state.save.unwrap()(plugin, &stream));
bytes
};
let mut envelope: nih_plug::prelude::PluginState =
serde_json::from_slice(&save()[8..]).unwrap();
use nih_plug::wrapper::state::ParamValue;
envelope.params.insert("soft".into(), ParamValue::F32(40.));
envelope.params.insert("hold".into(), ParamValue::F32(100.));
envelope.params.insert("split".into(), ParamValue::F32(90.));
let encoded = serde_json::to_vec(&envelope).unwrap();
let mut framed = (encoded.len() as u64).to_le_bytes().to_vec();
framed.extend_from_slice(&encoded);
let mut bytes = Cursor::new(framed);
let stream = clap_istream {
ctx: &mut bytes as *mut Cursor<Vec<u8>> as *mut c_void,
read: Some(read),
};
assert!(state.load.unwrap()(plugin, &stream));
let restored: nih_plug::prelude::PluginState =
serde_json::from_slice(&save()[8..]).unwrap();
assert_eq!(
serde_json::to_value(&restored.params).unwrap(),
serde_json::to_value(&envelope.params).unwrap()
);
for rate in [44100., 48000., 96000.] {
assert!(p.activate.unwrap()(plugin, rate, 1, 512));
let delay = (*latency).get.unwrap()(plugin) as usize;
// Only the 4× oversampling filters: under a millisecond at every rate.
assert_eq!(delay, 37);
assert!(p.start_processing.unwrap()(plugin));
let total = delay + 9600;
let mut position = 0;
let (mut energy_in, mut energy_out) = (0f64, 0f64);
while position < total {
let frames = [1, 127, 512, 31][position % 4].min(total - position);
// A 1 kHz tone well under the ceiling passes unchanged.
let tone = |n: usize| {
0.25 * (std::f64::consts::TAU * 1000. * n as f64 / rate).sin() as f32
};
let mut input_left = [0f32; 512];
let mut input_right = [0f32; 512];
for i in 0..frames {
input_left[i] = tone(position + i);
input_right[i] = -tone(position + i);
}
let mut left = [0f32; 512];
let mut right = [0f32; 512];
let mut in_channels = [input_left.as_mut_ptr(), input_right.as_mut_ptr()];
let mut out_channels = [left.as_mut_ptr(), right.as_mut_ptr()];
let incoming = clap_audio_buffer {
data32: in_channels.as_mut_ptr(),
data64: ptr::null_mut(),
channel_count: 2,
latency: 0,
constant_mask: 0,
};
let mut outgoing_audio = clap_audio_buffer {
data32: out_channels.as_mut_ptr(),
data64: ptr::null_mut(),
channel_count: 2,
latency: 0,
constant_mask: 0,
};
let input = clap_input_events {
ctx: ptr::null_mut(),
size: Some(count),
get: Some(event),
};
let outgoing = clap_output_events {
ctx: ptr::null_mut(),
try_push: Some(push),
};
let process = clap_process {
steady_time: position as i64,
frames_count: frames as u32,
transport: ptr::null(),
audio_inputs: &incoming,
audio_outputs: &mut outgoing_audio,
audio_inputs_count: 1,
audio_outputs_count: 1,
in_events: &input,
out_events: &outgoing,
};
assert_ne!(p.process.unwrap()(plugin, &process), CLAP_PROCESS_ERROR);
for i in 0..frames {
let n = position + i;
if n < delay + 4800 {
// The tone's onset rings in the filters, but never past the ceiling.
assert!(left[i].abs() <= 0.9661, "{}", left[i]);
} else if n > delay + 4800 {
energy_in += (tone(n - delay) as f64).powi(2);
energy_out += (left[i] as f64).powi(2) + (right[i] as f64).powi(2);
}
}
position += frames;
}
let ratio_db = 10. * (energy_out / (2. * energy_in)).log10();
assert!(ratio_db.abs() < 0.2, "{ratio_db}");
p.stop_processing.unwrap()(plugin);
p.deactivate.unwrap()(plugin);
}
p.destroy.unwrap()(plugin);
entry.deinit.unwrap()();
}
}
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "quench-ui"
version = "0.1.0"
edition.workspace = true
license.workspace = true
[dependencies]
egui = "0.31.1"
quench-core = { path = "../core" }
common-ui = { path = "../../common/ui" }
common-dsp = { path = "../../common/dsp" }
+327
View File
@@ -0,0 +1,327 @@
//! Quench editor, shared by the CLAP wrapper and the headless renderer.
use common_ui::*;
use egui::{self, Color32, FontId, Pos2, Rect, RichText, Sense, Stroke, Vec2};
use quench_core::{
AnalyzerFrame, Monitor, Settings, CEILING_MIN, DRIVE_MAX, HOLD_MAX, HOLD_MIN, SCOPE, SPLIT_MAX,
SPLIT_MIN,
};
pub use common_ui::style;
pub const WIDTH: u32 = 980;
pub const HEIGHT: u32 = 640;
pub struct State {
pub analyzer: AnalyzerFrame,
/// What the output plays. Not saved: the wrapper resets it when the editor opens.
pub monitor: Monitor,
/// True while a pointer button is held, so knob drags become one host gesture.
pub gesture_active: bool,
pub help: String,
}
impl Default for State {
fn default() -> Self {
Self {
analyzer: AnalyzerFrame::default(),
monitor: Monitor::Quench,
gesture_active: false,
help: DEFAULT_HELP.into(),
}
}
}
const DEFAULT_HELP: &str =
"Put Quench last on the master or the bass bus. Raise Drive until the top clips as hard as you want.";
impl State {
pub fn accept_frame(&mut self, frame: AnalyzerFrame) {
self.analyzer = frame;
}
}
fn hint(r: &egui::Response, state: &mut State, text: &str) {
if r.hovered() || r.has_focus() {
state.help = text.into();
}
}
#[allow(clippy::too_many_arguments)]
fn knob(
ui: &mut egui::Ui,
state: &mut State,
name: &str,
value: &mut f32,
range: std::ops::RangeInclusive<f32>,
default: f32,
unit: &str,
help: &str,
) {
ui.vertical_centered(|ui| {
let r = rotary(ui, name, value, range, default, unit, 72., ACCENT);
hint(&r, state, help);
});
}
/// The selected output with the ceiling, the sub band, and the room the sub leaves the top.
fn scope(ui: &mut egui::Ui, settings: &Settings, frame: &AnalyzerFrame, height: f32) {
let (rect, _) = ui.allocate_exact_size(Vec2::new(ui.available_width(), height), Sense::hover());
let p = ui.painter_at(rect);
p.rect_filled(rect, 2., SCREEN);
p.text(
rect.left_top() + Vec2::new(10., 8.),
egui::Align2::LEFT_TOP,
"OUTPUT · SUB · ROOM FOR THE TOP",
FontId::proportional(11.),
MUTED,
);
p.text(
rect.right_top() + Vec2::new(-12., 8.),
egui::Align2::RIGHT_TOP,
format!(
"{:.0} ms",
SCOPE as f32 * 8. / frame.sample_rate.max(1.) * 1000.
),
FontId::proportional(11.),
MUTED,
);
let area = Rect::from_min_max(
rect.left_top() + Vec2::new(12., 28.),
rect.right_bottom() - Vec2::new(12., 10.),
);
let mid = area.center().y;
let scale = area.height() * 0.5 / 1.08;
let y = |v: f32| mid - v.clamp(-1.08, 1.08) * scale;
let x = |i: usize| area.left() + area.width() * i as f32 / (SCOPE - 1) as f32;
p.line_segment(
[Pos2::new(area.left(), mid), Pos2::new(area.right(), mid)],
Stroke::new(1.0_f32, Color32::from_rgb(32, 35, 40)),
);
let c = 10f32.powf(settings.ceiling / 20.);
for v in [c, -c] {
p.line_segment(
[Pos2::new(area.left(), y(v)), Pos2::new(area.right(), y(v))],
Stroke::new(1.0_f32, ACCENT.gamma_multiply(0.6)),
);
}
p.text(
Pos2::new(area.right() - 4., y(c) - 3.),
egui::Align2::RIGHT_BOTTOM,
format!("CEILING {:.1} dB", settings.ceiling),
FontId::proportional(10.),
ACCENT,
);
for i in 0..SCOPE {
let (lo, hi) = (frame.scope_min[i], frame.scope_max[i]);
let top = y(hi);
let bottom = y(lo).max(top + 1.);
p.line_segment(
[Pos2::new(x(i), top), Pos2::new(x(i), bottom)],
Stroke::new(2.0_f32, STEEL.gamma_multiply(0.55)),
);
}
// Where the output may go: the sub plus or minus the top's room.
for sign in [1., -1.] {
let line: Vec<Pos2> = (0..SCOPE)
.map(|i| Pos2::new(x(i), y(frame.scope_sub[i] + sign * frame.scope_room[i])))
.collect();
p.add(egui::Shape::line(line, Stroke::new(1.0_f32, MUTED)));
}
let sub: Vec<Pos2> = (0..SCOPE)
.map(|i| Pos2::new(x(i), y(frame.scope_sub[i])))
.collect();
p.add(egui::Shape::line(sub, Stroke::new(2.0_f32, FOCUS)));
p.rect_stroke(
rect,
2.,
Stroke::new(1.0_f32, EDGE),
egui::StrokeKind::Inside,
);
}
pub fn show(ui: &mut egui::Ui, settings: &mut Settings, state: &mut State) {
backdrop(ui);
state.help = DEFAULT_HELP.into();
state.gesture_active = ui.input(|i| i.pointer.any_down());
ui.add_space(2.);
header(ui, "QUENCH", "SUB-SAFE CLIPPER", |ui| {
let r = ui
.selectable_label(settings.bypass, RichText::new("BYPASS").size(13.))
.on_hover_text("Crossfade to the input, delayed by the latency.");
if r.clicked() {
settings.bypass = !settings.bypass;
}
ui.separator();
for (monitor, label, text) in [
(
Monitor::Delta,
"DELTA",
"Hear what Quench takes away. Not saved.",
),
(
Monitor::Plain,
"PLAIN",
"Hear a plain clipper at the same settings, to compare the low end. Not saved.",
),
(Monitor::Quench, "QUENCH", "Hear Quench."),
] {
let r = ui
.selectable_label(state.monitor == monitor, RichText::new(label).size(13.))
.on_hover_text(text);
if r.clicked() {
state.monitor = monitor;
}
}
caption(ui, "LISTEN");
});
ui.add_space(6.);
let frame = state.analyzer;
ui.horizontal_top(|ui| {
panel(ui, |ui| {
ui.set_width(250.);
ui.set_min_height(TOP);
ui.vertical(|ui| readings(ui, settings, &frame));
});
ui.add_space(4.);
panel(ui, |ui| {
ui.set_width(ui.available_width());
scope(ui, settings, &frame, TOP);
});
});
ui.add_space(6.);
panel(ui, |ui| {
ui.set_width(ui.available_width());
ui.vertical(|ui| controls(ui, settings, state));
});
ui.separator();
ui.label(RichText::new(&state.help).color(MUTED));
}
const TOP: f32 = 330.;
fn readings(ui: &mut egui::Ui, settings: &Settings, frame: &AnalyzerFrame) {
caption(ui, "LOW END CHANGED BY");
let has_sub = frame.low_quench.is_finite();
ui.label(
RichText::new(if has_sub {
format!("{:.0} dB", frame.low_quench)
} else {
"—".into()
})
.font(FontId::new(44., egui::FontFamily::Name("medium".into())))
.color(if has_sub { TEXT } else { DIM }),
);
ui.label(
RichText::new(if has_sub {
format!("plain clip: {:.0} dB", frame.low_plain)
} else {
"no sub playing".into()
})
.monospace()
.size(13.)
.color(MUTED),
);
ui.add_space(12.);
readout(
ui,
"TOP CLIPPED BY",
if frame.top_clip >= 40. {
"no room left".into()
} else if frame.top_clip > 0. {
format!("{:.1} dB", frame.top_clip)
} else {
"not clipping".into()
},
ACCENT,
);
let room = settings.ceiling - frame.sub_peak;
readout(
ui,
"SUB PEAK · ROOM LEFT",
if frame.sub_peak > -119. {
format!("{:.1} dBFS · {:.1} dB", frame.sub_peak, room.max(0.))
} else {
"—".into()
},
FOCUS,
);
if frame.sub_peak > settings.ceiling - 1. {
ui.label(
RichText::new(
"The sub alone reaches the ceiling: the top has no room and the safety clip \
cuts the sub. Lower Drive or the sub.",
)
.size(12.)
.color(ACCENT),
);
ui.add_space(6.);
}
ui.add_space(4.);
meter(ui, "IN", frame.input_peak, STEEL, 150.);
meter(ui, "OUT", frame.output_peak, ACCENT, 150.);
ui.add_space(6.);
ui.label(
RichText::new(format!(
"safety clip {} · {:.1} ms latency",
if frame.safety > 0. {
format!("{:.2} dB", frame.safety)
} else {
"idle".into()
},
frame.latency as f32 / frame.sample_rate.max(1.) * 1000.
))
.size(12.)
.color(MUTED),
);
}
fn controls(ui: &mut egui::Ui, settings: &mut Settings, state: &mut State) {
let d = Settings::default();
ui.columns(5, |c| {
knob(
&mut c[0],
state,
"Drive",
&mut settings.drive,
0. ..=DRIVE_MAX,
d.drive,
" dB",
"Gain into the clipper. The sub rises with it: watch the room it leaves.",
);
knob(
&mut c[1],
state,
"Ceiling",
&mut settings.ceiling,
CEILING_MIN..=0.,
d.ceiling,
" dB",
"Highest output peak. The sub keeps its level; the top gets what is left.",
);
knob(
&mut c[2],
state,
"Split",
&mut settings.split,
SPLIT_MIN..=SPLIT_MAX,
d.split,
" Hz",
"Below this the sub passes without clipping. Set it above the highest sub note, \
or at Anvil's Split.",
);
knob(
&mut c[3],
state,
"Hold",
&mut settings.hold,
HOLD_MIN..=HOLD_MAX,
d.hold,
" ms",
"How long the sub's peak keeps its room. Longer than half a period of the lowest \
note keeps the top from pumping with the sub.",
);
knob(
&mut c[4],
state,
"Soft",
&mut settings.soft,
0. ..=100.,
d.soft,
" %",
"Knee of the top's clip. 0 % is a hard clip, 100 % a soft curve.",
);
});
}