feat: add Lathe harmonic EQ and Temper tracked distortion
Check and Windows preview / check (anvil) (push) Successful in 2m8s
Check and Windows preview / check (crucible) (push) Successful in 1m32s
Check and Windows preview / check (lathe) (push) Successful in 2m13s
Check and Windows preview / check (patina) (push) Successful in 2m5s
Check and Windows preview / check (rivet) (push) Successful in 1m34s
Check and Windows preview / check (temper) (push) Successful in 2m12s
Check and Windows preview / previews (push) Successful in 1m19s
Check and Windows preview / windows (push) Successful in 2m13s
Independent plugin release / publish (push) Successful in 8s
Independent plugin release / plan (push) Successful in 6s
Independent plugin release / build (push) Successful in 2m57s
Check and Windows preview / check (anvil) (push) Successful in 2m8s
Check and Windows preview / check (crucible) (push) Successful in 1m32s
Check and Windows preview / check (lathe) (push) Successful in 2m13s
Check and Windows preview / check (patina) (push) Successful in 2m5s
Check and Windows preview / check (rivet) (push) Successful in 1m34s
Check and Windows preview / check (temper) (push) Successful in 2m12s
Check and Windows preview / previews (push) Successful in 1m19s
Check and Windows preview / windows (push) Successful in 2m13s
Independent plugin release / publish (push) Successful in 8s
Independent plugin release / plan (push) Successful in 6s
Independent plugin release / build (push) Successful in 2m57s
Lathe places EQ bands on harmonics 1-32 of the played note, so a cut on harmonic 3 stays on harmonic 3 on every note. Temper normalises each note's level before an oversampled shaper and tunes its floor, push and bright filters to the note, so every note distorts the same. The note tracker moves from Anvil into common-dsp, together with a state-variable filter, 4x oversampler and harmonic meter. Anvil's behaviour and editor render are unchanged. docs/ideas.md collects all plugin ideas and their status.
This commit is contained in:
1 parent
f36ff0780c
commit
b3ebe4d952
48 files changed
+9862
-339
No files matched your search
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "lathe-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 }
|
||||
@@ -0,0 +1,258 @@
|
||||
//! Harmonic EQ: bands sit on the harmonics of the played note instead of fixed frequencies,
|
||||
//! so a cut on harmonic 3 stays on harmonic 3 on every note.
|
||||
//!
|
||||
//! The audio path is delayed by the tracker's lookahead, so the filters are already tuned to
|
||||
//! a note when its attack leaves the plugin.
|
||||
mod settings;
|
||||
use common_dsp::meter::HarmonicMeter;
|
||||
use common_dsp::svf::{Svf, SvfCoef};
|
||||
use common_dsp::tracker::{PitchFollower, Tracker, TrackerConfig};
|
||||
use common_dsp::{coefficient, db_to_gain, hz_to_midi};
|
||||
pub use settings::{Settings, Source, GAIN_MAX, GAIN_MIN, HARMONICS};
|
||||
|
||||
pub const MIN_HZ: f32 = TrackerConfig::BASS.min_hz;
|
||||
pub const MAX_HZ: f32 = TrackerConfig::BASS.max_hz;
|
||||
/// Harmonic bands plus the bands halfway between them.
|
||||
const BANDS: usize = 2 * HARMONICS;
|
||||
/// Filter coefficients are recomputed this often, in samples.
|
||||
const RETUNE: usize = 16;
|
||||
const GAIN_MS: f32 = 20.;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct AnalyzerFrame {
|
||||
/// Fundamental the filters are tuned to, 0 before the first note.
|
||||
pub hz: f32,
|
||||
/// Sounding note, rounded; None between notes.
|
||||
pub note: Option<u8>,
|
||||
/// Harmonic levels in dBFS of the delayed input and of the output (index 0 = fundamental).
|
||||
pub input: [f32; HARMONICS],
|
||||
pub output: [f32; HARMONICS],
|
||||
pub latency: u32,
|
||||
pub sample_rate: f32,
|
||||
}
|
||||
impl Default for AnalyzerFrame {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
hz: 0.,
|
||||
note: None,
|
||||
input: [-120.; HARMONICS],
|
||||
output: [-120.; HARMONICS],
|
||||
latency: 0,
|
||||
sample_rate: 48000.,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Engine {
|
||||
rate: f32,
|
||||
channels: usize,
|
||||
settings: Settings,
|
||||
latency: usize,
|
||||
delay: Vec<[f32; 2]>,
|
||||
delay_at: usize,
|
||||
tracker: Tracker,
|
||||
pitch: PitchFollower,
|
||||
hz: f32,
|
||||
hz_coef: f32,
|
||||
countdown: usize,
|
||||
coefs: [SvfCoef; BANDS],
|
||||
active: [bool; BANDS],
|
||||
gains: [f32; BANDS],
|
||||
state: [[Svf; BANDS]; 2],
|
||||
gain_coef: f32,
|
||||
smooth: f32,
|
||||
mix: f32,
|
||||
output: f32,
|
||||
bypass: f32,
|
||||
meter_in: HarmonicMeter,
|
||||
meter_out: HarmonicMeter,
|
||||
/// Smoothed controls start at the next settings instead of gliding from defaults.
|
||||
fresh: bool,
|
||||
}
|
||||
|
||||
impl Engine {
|
||||
pub fn new(rate: f32, channels: usize) -> Result<Self, &'static str> {
|
||||
if !(8000.0..=768000.).contains(&rate) {
|
||||
return Err("unsupported sample rate");
|
||||
}
|
||||
if !(1..=2).contains(&channels) {
|
||||
return Err("unsupported channel count");
|
||||
}
|
||||
let tracker = Tracker::new(rate, TrackerConfig::BASS);
|
||||
let latency = tracker.latency();
|
||||
let settings = Settings::default();
|
||||
let mut e = Self {
|
||||
rate,
|
||||
channels,
|
||||
settings,
|
||||
latency,
|
||||
delay: vec![[0.; 2]; latency + 1],
|
||||
delay_at: 0,
|
||||
tracker,
|
||||
pitch: PitchFollower::default(),
|
||||
hz: 0.,
|
||||
hz_coef: 1.,
|
||||
countdown: 0,
|
||||
coefs: [SvfCoef::IDENTITY; BANDS],
|
||||
active: [false; BANDS],
|
||||
gains: [0.; BANDS],
|
||||
state: [[Svf::default(); BANDS]; 2],
|
||||
gain_coef: coefficient(rate / RETUNE as f32, GAIN_MS),
|
||||
smooth: coefficient(rate, 10.),
|
||||
mix: 1.,
|
||||
output: 1.,
|
||||
bypass: 0.,
|
||||
meter_in: HarmonicMeter::new(rate, 85.),
|
||||
meter_out: HarmonicMeter::new(rate, 85.),
|
||||
fresh: true,
|
||||
};
|
||||
e.set_settings(settings)?;
|
||||
e.fresh = true;
|
||||
Ok(e)
|
||||
}
|
||||
pub fn latency_samples(&self) -> u32 {
|
||||
self.latency as u32
|
||||
}
|
||||
pub fn channels(&self) -> usize {
|
||||
self.channels
|
||||
}
|
||||
pub fn settings(&self) -> Settings {
|
||||
self.settings
|
||||
}
|
||||
pub fn set_settings(&mut self, s: Settings) -> Result<(), &'static str> {
|
||||
s.validate()?;
|
||||
self.tracker
|
||||
.set(s.source == Source::Midi, s.gate, s.smooth > 0.);
|
||||
self.hz_coef = coefficient(self.rate, s.smooth / 3.);
|
||||
self.settings = s;
|
||||
if std::mem::take(&mut self.fresh) {
|
||||
self.mix = s.mix * 0.01;
|
||||
self.output = db_to_gain(s.output);
|
||||
self.bypass = f32::from(s.bypass);
|
||||
self.gains = self.targets();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn reset(&mut self) {
|
||||
self.delay.fill([0.; 2]);
|
||||
self.tracker.reset();
|
||||
for ch in &mut self.state {
|
||||
for f in ch.iter_mut() {
|
||||
f.reset();
|
||||
}
|
||||
}
|
||||
self.meter_in.reset();
|
||||
self.meter_out.reset();
|
||||
self.countdown = 0;
|
||||
self.fresh = true;
|
||||
}
|
||||
pub fn note_on(&mut self, note: u8) {
|
||||
self.tracker.note_on(note);
|
||||
}
|
||||
pub fn note_off(&mut self, note: u8) {
|
||||
self.tracker.note_off(note);
|
||||
}
|
||||
/// Gain targets in dB of every band for the current settings.
|
||||
fn targets(&self) -> [f32; BANDS] {
|
||||
let s = &self.settings;
|
||||
let mut t = [0.; BANDS];
|
||||
for k in 1..=s.harmonics as usize {
|
||||
t[k - 1] = s.effective(k);
|
||||
t[HARMONICS + k - 1] = s.between;
|
||||
}
|
||||
t
|
||||
}
|
||||
fn retune(&mut self, jump: bool) {
|
||||
let s = self.settings;
|
||||
let targets = self.targets();
|
||||
let width = s.width * 0.01;
|
||||
for b in 0..BANDS {
|
||||
self.gains[b] = if jump {
|
||||
targets[b]
|
||||
} else {
|
||||
self.gains[b] + (targets[b] - self.gains[b]) * self.gain_coef
|
||||
};
|
||||
if (self.gains[b] - targets[b]).abs() < 1e-4 {
|
||||
self.gains[b] = targets[b];
|
||||
}
|
||||
let order = if b < HARMONICS {
|
||||
(b + 1) as f32
|
||||
} else {
|
||||
(b - HARMONICS + 1) as f32 + 0.5
|
||||
};
|
||||
let centre = order * self.hz;
|
||||
let audible = self.hz > 0. && centre < 0.45 * self.rate;
|
||||
if audible && !self.active[b] {
|
||||
for ch in &mut self.state {
|
||||
ch[b].reset();
|
||||
}
|
||||
}
|
||||
self.active[b] = audible && self.gains[b] != 0.;
|
||||
if self.active[b] {
|
||||
self.coefs[b] = SvfCoef::bell(self.rate, centre, order / width, self.gains[b]);
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn process_sample(&mut self, x: [f32; 2]) -> [f32; 2] {
|
||||
let mono = if self.channels == 2 {
|
||||
0.5 * (x[0] + x[1])
|
||||
} else {
|
||||
x[0]
|
||||
};
|
||||
let (pitch, snap) = (&mut self.pitch, self.settings.snap);
|
||||
self.tracker.process(mono, |e| pitch.event(snap, e));
|
||||
let len = self.delay.len();
|
||||
self.delay[self.delay_at] = x;
|
||||
self.delay_at = (self.delay_at + 1) % len;
|
||||
let y = self.delay[self.delay_at];
|
||||
|
||||
let first = self.hz == 0.;
|
||||
let (hz, jump) = self.pitch.step(self.hz_coef);
|
||||
let first = first && jump;
|
||||
self.hz = hz;
|
||||
if jump || self.countdown == 0 {
|
||||
self.retune(first);
|
||||
self.countdown = RETUNE;
|
||||
}
|
||||
self.countdown -= 1;
|
||||
|
||||
let s = self.settings;
|
||||
self.mix += (s.mix * 0.01 - self.mix) * self.smooth;
|
||||
self.output += (db_to_gain(s.output) - self.output) * self.smooth;
|
||||
self.bypass += (f32::from(s.bypass) - self.bypass) * self.smooth;
|
||||
let mut out = [0.; 2];
|
||||
for c in 0..self.channels {
|
||||
let mut v = y[c];
|
||||
for b in 0..BANDS {
|
||||
if self.active[b] {
|
||||
v = self.state[c][b].process(&self.coefs[b], v);
|
||||
}
|
||||
}
|
||||
let wet = (self.mix * v + (1. - self.mix) * y[c]) * self.output;
|
||||
out[c] = wet * (1. - self.bypass) + y[c] * self.bypass;
|
||||
}
|
||||
let hz = if self.tracker.sounding() { self.hz } else { 0. };
|
||||
let (dry, wet) = if self.channels == 2 {
|
||||
(0.5 * (y[0] + y[1]), 0.5 * (out[0] + out[1]))
|
||||
} else {
|
||||
(y[0], out[0])
|
||||
};
|
||||
self.meter_in.push(dry, hz);
|
||||
self.meter_out.push(wet, hz);
|
||||
out
|
||||
}
|
||||
pub fn take_analyzer(&self) -> AnalyzerFrame {
|
||||
let mut f = AnalyzerFrame {
|
||||
hz: self.hz,
|
||||
latency: self.latency as u32,
|
||||
sample_rate: self.rate,
|
||||
input: *self.meter_in.levels(),
|
||||
output: *self.meter_out.levels(),
|
||||
..AnalyzerFrame::default()
|
||||
};
|
||||
if self.tracker.sounding() && self.hz > 0. {
|
||||
f.note = Some(hz_to_midi(self.hz).round().clamp(0., 127.) as u8);
|
||||
}
|
||||
f
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
//! Host-independent controls. Gains in dB, times in milliseconds.
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Editable harmonics: the fundamental is harmonic 1.
|
||||
pub const HARMONICS: usize = 32;
|
||||
pub const GAIN_MIN: f32 = -24.;
|
||||
pub const GAIN_MAX: f32 = 12.;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
pub enum Source {
|
||||
/// Pitch and note starts are detected from the incoming bass.
|
||||
#[default]
|
||||
Audio,
|
||||
/// Notes come from MIDI note input.
|
||||
Midi,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Settings {
|
||||
pub source: Source,
|
||||
/// Gain per harmonic, index 0 = fundamental.
|
||||
pub gains: [f32; HARMONICS],
|
||||
/// dB per octave of harmonic number, added on top of `gains`. Harmonic 1 is the pivot.
|
||||
pub tilt: f32,
|
||||
/// Positive lifts odd harmonics and lowers even ones by half this amount each.
|
||||
pub odd_even: f32,
|
||||
/// Gain of the regions halfway between harmonics: noise, beating, inharmonic grit.
|
||||
pub between: f32,
|
||||
/// Bandwidth of every band as a percentage of the fundamental.
|
||||
pub width: f32,
|
||||
/// Number of harmonics that are shaped; higher ones pass unchanged.
|
||||
pub harmonics: u32,
|
||||
/// Retune time when the pitch slides or bends.
|
||||
pub smooth: f32,
|
||||
/// Detection threshold in dBFS for note starts (Audio source).
|
||||
pub gate: f32,
|
||||
/// Round detected pitch to the nearest semitone.
|
||||
pub snap: bool,
|
||||
pub mix: f32,
|
||||
pub output: f32,
|
||||
pub bypass: bool,
|
||||
}
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
source: Source::Audio,
|
||||
gains: [0.; HARMONICS],
|
||||
tilt: 0.,
|
||||
odd_even: 0.,
|
||||
between: 0.,
|
||||
width: 20.,
|
||||
harmonics: 24,
|
||||
smooth: 10.,
|
||||
gate: -42.,
|
||||
snap: true,
|
||||
mix: 100.,
|
||||
output: 0.,
|
||||
bypass: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Settings {
|
||||
pub fn validate(&self) -> Result<(), &'static str> {
|
||||
let finite = [
|
||||
self.tilt,
|
||||
self.odd_even,
|
||||
self.between,
|
||||
self.width,
|
||||
self.smooth,
|
||||
self.gate,
|
||||
self.mix,
|
||||
self.output,
|
||||
]
|
||||
.iter()
|
||||
.chain(self.gains.iter())
|
||||
.all(|v| v.is_finite());
|
||||
if !finite {
|
||||
return Err("non-finite setting");
|
||||
}
|
||||
let ok = self.gains.iter().all(|g| (GAIN_MIN..=GAIN_MAX).contains(g))
|
||||
&& (-12.0..=12.).contains(&self.tilt)
|
||||
&& (-12.0..=12.).contains(&self.odd_even)
|
||||
&& (-24.0..=12.).contains(&self.between)
|
||||
&& (5.0..=50.).contains(&self.width)
|
||||
&& (8..=HARMONICS as u32).contains(&self.harmonics)
|
||||
&& (0.0..=100.).contains(&self.smooth)
|
||||
&& (-60.0..=-20.).contains(&self.gate)
|
||||
&& (0.0..=100.).contains(&self.mix)
|
||||
&& (-12.0..=12.).contains(&self.output);
|
||||
if ok {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("setting out of range")
|
||||
}
|
||||
}
|
||||
/// Gain applied to harmonic `k` (1-based), with tilt and odd/even included.
|
||||
pub fn effective(&self, k: usize) -> f32 {
|
||||
if k == 0 || k > self.harmonics as usize || k > HARMONICS {
|
||||
return 0.;
|
||||
}
|
||||
let parity = if k % 2 == 1 { 0.5 } else { -0.5 };
|
||||
(self.gains[k - 1] + self.tilt * (k as f32).log2() + self.odd_even * parity)
|
||||
.clamp(-30., 18.)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
use common_dsp::meter::HarmonicMeter;
|
||||
use common_dsp::Saw;
|
||||
use lathe_core::{Engine, Settings, Source};
|
||||
|
||||
const RATE: f32 = 48000.;
|
||||
|
||||
fn engine(s: Settings) -> (Engine, usize) {
|
||||
let mut e = Engine::new(RATE, 2).unwrap();
|
||||
e.set_settings(s).unwrap();
|
||||
let l = e.latency_samples() as usize;
|
||||
(e, l)
|
||||
}
|
||||
fn saw(hz: f32, seconds: f32, amp: f32) -> Vec<f32> {
|
||||
let mut s = Saw::new(RATE, hz);
|
||||
(0..(seconds * RATE) as usize)
|
||||
.map(|_| s.sample() * amp)
|
||||
.collect()
|
||||
}
|
||||
fn render(e: &mut Engine, x: &[f32]) -> Vec<f32> {
|
||||
x.iter().map(|&v| e.process_sample([v, v])[0]).collect()
|
||||
}
|
||||
/// Harmonic levels of the last complete window of `x`.
|
||||
fn harmonics(x: &[f32], hz: f32) -> [f32; 32] {
|
||||
let mut m = HarmonicMeter::new(RATE, 85.);
|
||||
for &v in x {
|
||||
m.push(v, hz);
|
||||
}
|
||||
*m.levels()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cut_on_harmonic_three_stays_on_harmonic_three_on_every_note() {
|
||||
let mut s = Settings::default();
|
||||
s.gains[2] = -12.;
|
||||
for hz in [43.65, 65.41, 130.81] {
|
||||
let x = saw(hz, 1., 0.5);
|
||||
let (mut e, l) = engine(s);
|
||||
let y = render(&mut e, &x);
|
||||
let a = harmonics(&x[..x.len() - l], hz);
|
||||
let b = harmonics(&y[l..], hz);
|
||||
let d: Vec<f32> = (0..6).map(|k| b[k] - a[k]).collect();
|
||||
assert!((d[2] + 12.).abs() < 0.7, "{hz}: {d:?}");
|
||||
for k in [0, 1, 3, 4] {
|
||||
assert!(d[k].abs() < 1., "{hz} harmonic {}: {d:?}", k + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flat_map_passes_the_delayed_input_exactly() {
|
||||
let x = saw(55., 0.5, 0.5);
|
||||
let (mut e, l) = engine(Settings::default());
|
||||
let y = render(&mut e, &x);
|
||||
for i in l..x.len() {
|
||||
assert_eq!(y[i], x[i - l]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odd_even_balances_the_harmonic_series() {
|
||||
let s = Settings {
|
||||
odd_even: 6.,
|
||||
..Settings::default()
|
||||
};
|
||||
let hz = 55.;
|
||||
let x = saw(hz, 1., 0.5);
|
||||
let (mut e, l) = engine(s);
|
||||
let y = render(&mut e, &x);
|
||||
let a = harmonics(&x[..x.len() - l], hz);
|
||||
let b = harmonics(&y[l..], hz);
|
||||
for k in 1..8 {
|
||||
let want = if k % 2 == 1 { 3. } else { -3. };
|
||||
let got = b[k - 1] - a[k - 1];
|
||||
assert!((got - want).abs() < 0.8, "harmonic {k}: {got}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn note_changes_do_not_click() {
|
||||
let mut s = Settings::default();
|
||||
s.gains[1] = 12.;
|
||||
s.gains[3] = -24.;
|
||||
s.tilt = -3.;
|
||||
let mut x = saw(43.65, 0.5, 0.5);
|
||||
x.extend(saw(58.27, 0.5, 0.5));
|
||||
x.extend(saw(87.31, 0.5, 0.5));
|
||||
let (mut e, _) = engine(s);
|
||||
let y = render(&mut e, &x);
|
||||
let step = y
|
||||
.windows(2)
|
||||
.map(|w| (w[1] - w[0]).abs())
|
||||
.fold(0f32, f32::max);
|
||||
let in_step = x
|
||||
.windows(2)
|
||||
.map(|w| (w[1] - w[0]).abs())
|
||||
.fold(0f32, f32::max);
|
||||
assert!(y.iter().all(|v| v.is_finite()));
|
||||
// A saw has its own jumps; the filtered output must not jump much further than that.
|
||||
assert!(step < 2. * in_step, "{step} vs {in_step}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn midi_source_tunes_the_bands_at_the_delayed_note_time() {
|
||||
let mut s = Settings {
|
||||
source: Source::Midi,
|
||||
..Settings::default()
|
||||
};
|
||||
s.gains[0] = -24.;
|
||||
let (mut e, l) = engine(s);
|
||||
// 43.65 Hz is MIDI 29. Notes arrive at sample 0; the bands must be tuned by sample l.
|
||||
e.note_on(29);
|
||||
let x = saw(43.65, 1., 0.5);
|
||||
let y = render(&mut e, &x);
|
||||
let a = harmonics(&x[..x.len() - l], 43.65);
|
||||
let b = harmonics(&y[l..], 43.65);
|
||||
assert!(b[0] - a[0] < -20., "{}", b[0] - a[0]);
|
||||
let f = e.take_analyzer();
|
||||
assert_eq!(f.note, Some(29));
|
||||
assert!((f.hz - 43.65).abs() < 0.05);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_are_validated_and_serialise() {
|
||||
let s = Settings::default();
|
||||
let json = serde_json::to_string(&s).unwrap();
|
||||
assert_eq!(serde_json::from_str::<Settings>(&json).unwrap(), s);
|
||||
let mut bad = s;
|
||||
bad.gains[5] = 40.;
|
||||
assert!(bad.validate().is_err());
|
||||
bad = s;
|
||||
bad.harmonics = 4;
|
||||
assert!(bad.validate().is_err());
|
||||
bad = s;
|
||||
bad.width = f32::NAN;
|
||||
assert!(bad.validate().is_err());
|
||||
let mut e = Engine::new(RATE, 2).unwrap();
|
||||
assert!(e.set_settings(bad).is_err());
|
||||
assert_eq!(e.settings(), s);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
use lathe_core::{Engine, Settings, Source};
|
||||
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_notes_settings_and_analysis_do_not_allocate_or_free() {
|
||||
let mut engine = Engine::new(48000., 2).unwrap();
|
||||
let mut settings = Settings::default();
|
||||
engine.set_settings(settings).unwrap();
|
||||
CHECK.with(|v| v.set(true));
|
||||
for i in 0..96000 {
|
||||
if i % 4800 == 0 {
|
||||
settings.gains[(i / 4800) % 32] = -6.;
|
||||
settings.tilt = ((i / 4800) % 5) as f32 - 2.;
|
||||
settings.source = if i > 48000 {
|
||||
Source::Midi
|
||||
} else {
|
||||
Source::Audio
|
||||
};
|
||||
engine.set_settings(settings).unwrap();
|
||||
engine.note_on(30 + (i / 4800 % 12) as u8);
|
||||
}
|
||||
if i % 4800 == 2400 {
|
||||
engine.note_off(30 + (i / 4800 % 12) as u8);
|
||||
}
|
||||
let t = i as f32 / 48000.;
|
||||
let x = if (i / 2400) % 2 == 0 {
|
||||
(std::f32::consts::TAU * 55. * t).sin() * 0.5
|
||||
} else {
|
||||
0.
|
||||
};
|
||||
std::hint::black_box(engine.process_sample([x, x]));
|
||||
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);
|
||||
}
|
||||
Generated
+2381
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,25 @@
|
||||
[package]
|
||||
name = "lathe"
|
||||
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" }
|
||||
lathe-core = { path = "../core" }
|
||||
lathe-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"
|
||||
@@ -0,0 +1,189 @@
|
||||
//! CLAP audio effect. All DSP state is owned by the processing thread.
|
||||
mod params;
|
||||
use crossbeam_queue::ArrayQueue;
|
||||
use lathe_core::{AnalyzerFrame, Engine, HARMONICS};
|
||||
use nih_plug::prelude::*;
|
||||
use nih_plug_egui::{create_egui_editor, egui};
|
||||
use params::LatheParams;
|
||||
use std::sync::Arc;
|
||||
|
||||
struct EditorData {
|
||||
ui: lathe_ui::State,
|
||||
gestures: [bool; 8],
|
||||
}
|
||||
pub struct Lathe {
|
||||
params: Arc<LatheParams>,
|
||||
analyzer: Arc<ArrayQueue<AnalyzerFrame>>,
|
||||
engine: Option<Engine>,
|
||||
gains: [f32; HARMONICS],
|
||||
publish_count: usize,
|
||||
publish_interval: usize,
|
||||
}
|
||||
impl Default for Lathe {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
params: Arc::new(LatheParams::default()),
|
||||
analyzer: Arc::new(ArrayQueue::new(2)),
|
||||
engine: None,
|
||||
gains: [0.; HARMONICS],
|
||||
publish_count: 0,
|
||||
publish_interval: 1600,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Plugin for Lathe {
|
||||
const NAME: &'static str = "Lathe";
|
||||
const VENDOR: &'static str = "Rivet & Patina";
|
||||
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 MIDI_INPUT: MidiConfig = MidiConfig::Basic;
|
||||
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 analyzer = self.analyzer.clone();
|
||||
create_egui_editor(
|
||||
params.editor.clone(),
|
||||
EditorData {
|
||||
ui: lathe_ui::State::default(),
|
||||
gestures: [false; 8],
|
||||
},
|
||||
|ctx, _| lathe_ui::style(ctx),
|
||||
move |ctx, setter, data| {
|
||||
while let Some(frame) = analyzer.pop() {
|
||||
data.ui.accept_frame(frame);
|
||||
}
|
||||
let current = params.gains.read().map(|g| *g).unwrap_or([0.; HARMONICS]);
|
||||
let before = params.settings(¤t);
|
||||
let mut edited = before;
|
||||
nih_plug_egui::resizable_window::ResizableWindow::new("lathe-editor")
|
||||
.min_size(egui::vec2(
|
||||
lathe_ui::WIDTH as f32 - 80.,
|
||||
lathe_ui::HEIGHT as f32 - 40.,
|
||||
))
|
||||
.show(ctx, ¶ms.editor, |ui| {
|
||||
lathe_ui::show(ui, &mut edited, &mut data.ui)
|
||||
});
|
||||
params.apply(
|
||||
setter,
|
||||
&before,
|
||||
&edited,
|
||||
data.ui.gesture_active,
|
||||
&mut data.gestures,
|
||||
);
|
||||
// Harmonic levels follow the audio.
|
||||
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;
|
||||
};
|
||||
let settings = self.params.settings(&self.gains);
|
||||
self.gains = settings.gains;
|
||||
if engine.set_settings(settings).is_err() {
|
||||
return false;
|
||||
}
|
||||
context.set_latency_samples(engine.latency_samples());
|
||||
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,
|
||||
context: &mut impl ProcessContext<Self>,
|
||||
) -> ProcessStatus {
|
||||
let Some(engine) = self.engine.as_mut() else {
|
||||
return ProcessStatus::Normal;
|
||||
};
|
||||
let settings = self.params.settings(&self.gains);
|
||||
self.gains = settings.gains;
|
||||
let _ = engine.set_settings(settings);
|
||||
let mut next = context.next_event();
|
||||
for (index, mut sample) in buffer.iter_samples().enumerate() {
|
||||
while let Some(event) = next {
|
||||
if event.timing() as usize > index {
|
||||
break;
|
||||
}
|
||||
match event {
|
||||
NoteEvent::NoteOn { note, velocity, .. } if velocity > 0. => {
|
||||
engine.note_on(note)
|
||||
}
|
||||
NoteEvent::NoteOn { note, .. } | NoteEvent::NoteOff { note, .. } => {
|
||||
engine.note_off(note)
|
||||
}
|
||||
NoteEvent::Choke { note, .. } => engine.note_off(note),
|
||||
_ => {}
|
||||
}
|
||||
next = context.next_event();
|
||||
}
|
||||
let x = [
|
||||
*sample.get_mut(0).unwrap(),
|
||||
if engine.channels() == 2 {
|
||||
*sample.get_mut(1).unwrap()
|
||||
} else {
|
||||
0.
|
||||
},
|
||||
];
|
||||
let out = engine.process_sample(x);
|
||||
for (c, value) in sample.into_iter().enumerate() {
|
||||
*value = out[c];
|
||||
}
|
||||
self.publish_count += 1;
|
||||
if self.publish_count >= self.publish_interval {
|
||||
self.analyzer.force_push(engine.take_analyzer());
|
||||
self.publish_count = 0;
|
||||
}
|
||||
}
|
||||
// The lookahead delay and filter tails must drain after input stops.
|
||||
ProcessStatus::KeepAlive
|
||||
}
|
||||
}
|
||||
impl ClapPlugin for Lathe {
|
||||
const CLAP_ID: &'static str = "io.storyboard.harmonic-eq";
|
||||
const CLAP_DESCRIPTION: Option<&'static str> =
|
||||
Some("EQ the harmonics of the played note: a cut on harmonic 3 stays on harmonic 3");
|
||||
const CLAP_MANUAL_URL: Option<&'static str> = None;
|
||||
const CLAP_SUPPORT_URL: Option<&'static str> = None;
|
||||
const CLAP_FEATURES: &'static [ClapFeature] = &[
|
||||
ClapFeature::AudioEffect,
|
||||
ClapFeature::Equalizer,
|
||||
ClapFeature::Stereo,
|
||||
ClapFeature::Mono,
|
||||
];
|
||||
}
|
||||
nih_export_clap!(Lathe);
|
||||
@@ -0,0 +1,186 @@
|
||||
use lathe_core::{Settings, Source, HARMONICS};
|
||||
use nih_plug::prelude::*;
|
||||
use nih_plug_egui::EguiState;
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
#[derive(Enum, Debug, PartialEq, Eq, Clone, Copy)]
|
||||
pub enum SourceParam {
|
||||
#[id = "audio"]
|
||||
Audio,
|
||||
#[id = "midi"]
|
||||
#[name = "MIDI"]
|
||||
Midi,
|
||||
}
|
||||
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)
|
||||
}
|
||||
/// Continuous controls, in the order of the gesture slots.
|
||||
const FLOATS: usize = 8;
|
||||
|
||||
#[derive(Params)]
|
||||
pub struct LatheParams {
|
||||
#[persist = "editor"]
|
||||
pub editor: Arc<EguiState>,
|
||||
/// Drawn per-harmonic gains. Saved with the project, not exposed as automation lanes.
|
||||
#[persist = "lathe-gains"]
|
||||
pub gains: RwLock<[f32; HARMONICS]>,
|
||||
#[id = "source"]
|
||||
pub source: EnumParam<SourceParam>,
|
||||
#[id = "tilt"]
|
||||
pub tilt: FloatParam,
|
||||
#[id = "odd-even"]
|
||||
pub odd_even: FloatParam,
|
||||
#[id = "between"]
|
||||
pub between: FloatParam,
|
||||
#[id = "width"]
|
||||
pub width: FloatParam,
|
||||
#[id = "smooth"]
|
||||
pub smooth: FloatParam,
|
||||
#[id = "gate"]
|
||||
pub gate: FloatParam,
|
||||
#[id = "mix"]
|
||||
pub mix: FloatParam,
|
||||
#[id = "output"]
|
||||
pub output: FloatParam,
|
||||
#[id = "harmonics"]
|
||||
pub harmonics: IntParam,
|
||||
#[id = "snap"]
|
||||
pub snap: BoolParam,
|
||||
#[id = "bypass"]
|
||||
pub bypass: BoolParam,
|
||||
}
|
||||
impl Default for LatheParams {
|
||||
fn default() -> Self {
|
||||
let d = Settings::default();
|
||||
Self {
|
||||
editor: EguiState::from_size(lathe_ui::WIDTH, lathe_ui::HEIGHT),
|
||||
gains: RwLock::new(d.gains),
|
||||
source: EnumParam::new("Pitch source", SourceParam::Audio),
|
||||
tilt: linear("Tilt", d.tilt, -12., 12., " dB/oct"),
|
||||
odd_even: linear("Odd/Even", d.odd_even, -12., 12., " dB"),
|
||||
between: linear("Between", d.between, -24., 12., " dB"),
|
||||
width: linear("Width", d.width, 5., 50., " %"),
|
||||
smooth: linear("Smooth", d.smooth, 0., 100., " ms"),
|
||||
gate: linear("Gate", d.gate, -60., -20., " dB"),
|
||||
mix: linear("Mix", d.mix, 0., 100., " %"),
|
||||
output: linear("Output", d.output, -12., 12., " dB"),
|
||||
harmonics: IntParam::new(
|
||||
"Harmonics",
|
||||
d.harmonics as i32,
|
||||
IntRange::Linear {
|
||||
min: 8,
|
||||
max: HARMONICS as i32,
|
||||
},
|
||||
),
|
||||
snap: BoolParam::new("Snap to semitone", d.snap),
|
||||
bypass: BoolParam::new("Bypass", false).make_bypass(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl LatheParams {
|
||||
/// Current settings. `gains` falls back to `last` when the editor holds the lock, so the
|
||||
/// audio thread never waits.
|
||||
pub fn settings(&self, last: &[f32; HARMONICS]) -> Settings {
|
||||
let gains = self.gains.try_read().map(|g| *g).unwrap_or(*last);
|
||||
Settings {
|
||||
source: match self.source.value() {
|
||||
SourceParam::Audio => Source::Audio,
|
||||
SourceParam::Midi => Source::Midi,
|
||||
},
|
||||
gains: gains.map(|g| {
|
||||
if g.is_finite() {
|
||||
g.clamp(lathe_core::GAIN_MIN, lathe_core::GAIN_MAX)
|
||||
} else {
|
||||
0.
|
||||
}
|
||||
}),
|
||||
tilt: self.tilt.value(),
|
||||
odd_even: self.odd_even.value(),
|
||||
between: self.between.value(),
|
||||
width: self.width.value(),
|
||||
harmonics: self.harmonics.value() as u32,
|
||||
smooth: self.smooth.value(),
|
||||
gate: self.gate.value(),
|
||||
snap: self.snap.value(),
|
||||
mix: self.mix.value(),
|
||||
output: self.output.value(),
|
||||
bypass: self.bypass.value(),
|
||||
}
|
||||
}
|
||||
fn floats(&self) -> [&FloatParam; FLOATS] {
|
||||
[
|
||||
&self.tilt,
|
||||
&self.odd_even,
|
||||
&self.between,
|
||||
&self.width,
|
||||
&self.smooth,
|
||||
&self.gate,
|
||||
&self.mix,
|
||||
&self.output,
|
||||
]
|
||||
}
|
||||
/// 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. Gains are stored
|
||||
/// directly.
|
||||
pub fn apply(
|
||||
&self,
|
||||
setter: &ParamSetter,
|
||||
old: &Settings,
|
||||
new: &Settings,
|
||||
dragging: bool,
|
||||
open: &mut [bool; FLOATS],
|
||||
) {
|
||||
if new.gains != old.gains {
|
||||
if let Ok(mut g) = self.gains.write() {
|
||||
*g = new.gains;
|
||||
}
|
||||
}
|
||||
let values = [
|
||||
(old.tilt, new.tilt),
|
||||
(old.odd_even, new.odd_even),
|
||||
(old.between, new.between),
|
||||
(old.width, new.width),
|
||||
(old.smooth, new.smooth),
|
||||
(old.gate, new.gate),
|
||||
(old.mix, new.mix),
|
||||
(old.output, new.output),
|
||||
];
|
||||
for (i, (p, (a, b))) in self.floats().into_iter().zip(values).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.harmonics != old.harmonics {
|
||||
setter.begin_set_parameter(&self.harmonics);
|
||||
setter.set_parameter(&self.harmonics, new.harmonics as i32);
|
||||
setter.end_set_parameter(&self.harmonics);
|
||||
}
|
||||
for (p, a, b) in [
|
||||
(&self.snap, old.snap, new.snap),
|
||||
(&self.bypass, old.bypass, new.bypass),
|
||||
] {
|
||||
if a != b {
|
||||
setter.begin_set_parameter(p);
|
||||
setter.set_parameter(p, b);
|
||||
setter.end_set_parameter(p);
|
||||
}
|
||||
}
|
||||
if new.source != old.source {
|
||||
let v = match new.source {
|
||||
Source::Audio => SourceParam::Audio,
|
||||
Source::Midi => SourceParam::Midi,
|
||||
};
|
||||
setter.begin_set_parameter(&self.source);
|
||||
setter.set_parameter(&self.source, v);
|
||||
setter.end_set_parameter(&self.source);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
//! 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 = &lathe::clap_entry;
|
||||
assert!(entry.init.unwrap()(c"lathe.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"Lathe");
|
||||
assert_eq!(
|
||||
CStr::from_ptr((*descriptor).id),
|
||||
c"io.storyboard.harmonic-eq"
|
||||
);
|
||||
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("tilt".into(), ParamValue::F32(-3.));
|
||||
envelope
|
||||
.params
|
||||
.insert("harmonics".into(), ParamValue::I32(16));
|
||||
let mut gains = [0f32; 32];
|
||||
gains[2] = -12.;
|
||||
gains[4] = 6.;
|
||||
envelope
|
||||
.fields
|
||||
.insert("lathe-gains".into(), serde_json::to_string(&gains).unwrap());
|
||||
envelope
|
||||
.params
|
||||
.insert("snap".into(), ParamValue::Bool(false));
|
||||
envelope
|
||||
.params
|
||||
.insert("source".into(), ParamValue::String("midi".into()));
|
||||
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()
|
||||
);
|
||||
let saved: [f32; 32] = serde_json::from_str(&restored.fields["lathe-gains"]).unwrap();
|
||||
assert_eq!(saved, gains);
|
||||
for rate in [44100., 48000., 96000.] {
|
||||
assert!(p.activate.unwrap()(plugin, rate, 1, 512));
|
||||
let delay = (*latency).get.unwrap()(plugin) as usize;
|
||||
// About 67 ms lookahead: two periods of the lowest detected note (30 Hz).
|
||||
assert!((delay as f64 / rate - 0.067).abs() < 0.01, "{delay}");
|
||||
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 sits above the split and passes through 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 {
|
||||
assert!(left[i].abs() < 1e-6, "output before the lookahead");
|
||||
} 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()();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "lathe-ui"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
egui = "0.31.1"
|
||||
lathe-core = { path = "../core" }
|
||||
common-ui = { path = "../../common/ui" }
|
||||
common-dsp = { path = "../../common/dsp" }
|
||||
@@ -0,0 +1,431 @@
|
||||
//! Lathe 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 lathe_core::{AnalyzerFrame, Settings, Source, GAIN_MAX, GAIN_MIN, HARMONICS};
|
||||
|
||||
pub use common_ui::style;
|
||||
pub const WIDTH: u32 = 1040;
|
||||
pub const HEIGHT: u32 = 650;
|
||||
|
||||
pub struct State {
|
||||
pub analyzer: AnalyzerFrame,
|
||||
/// True while a pointer button is held, so knob drags become one host gesture.
|
||||
pub gesture_active: bool,
|
||||
pub help: String,
|
||||
/// Last point of a draw stroke in the harmonic editor: (harmonic index, dB).
|
||||
stroke: Option<(usize, f32)>,
|
||||
}
|
||||
impl Default for State {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
analyzer: AnalyzerFrame::default(),
|
||||
gesture_active: false,
|
||||
help: DEFAULT_HELP.into(),
|
||||
stroke: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
const DEFAULT_HELP: &str =
|
||||
"Draw gains on the harmonics. They follow the note: harmonic 3 stays harmonic 3 on every pitch.";
|
||||
impl State {
|
||||
pub fn accept_frame(&mut self, frame: AnalyzerFrame) {
|
||||
let old = self.analyzer;
|
||||
self.analyzer = frame;
|
||||
// Levels fall smoothly so bars stay readable between windows.
|
||||
for k in 0..HARMONICS {
|
||||
self.analyzer.input[k] = frame.input[k].max(old.input[k] - 3.);
|
||||
self.analyzer.output[k] = frame.output[k].max(old.output[k] - 3.);
|
||||
}
|
||||
}
|
||||
}
|
||||
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,
|
||||
size: f32,
|
||||
help: &str,
|
||||
) {
|
||||
ui.vertical_centered(|ui| {
|
||||
let r = rotary(ui, name, value, range, default, unit, size, ACCENT);
|
||||
hint(&r, state, help);
|
||||
});
|
||||
}
|
||||
|
||||
const GRID: Color32 = Color32::from_rgb(24, 26, 30);
|
||||
const LEVEL_FLOOR: f32 = -72.;
|
||||
|
||||
fn gain_y(rect: Rect, db: f32) -> f32 {
|
||||
let t = (db - GAIN_MIN) / (GAIN_MAX - GAIN_MIN);
|
||||
rect.bottom() - rect.height() * t.clamp(0., 1.)
|
||||
}
|
||||
fn y_gain(rect: Rect, y: f32) -> f32 {
|
||||
let t = (rect.bottom() - y) / rect.height();
|
||||
// Snap near 0 dB so drawing a flat line is easy.
|
||||
let db = GAIN_MIN + t * (GAIN_MAX - GAIN_MIN);
|
||||
let db = if db.abs() < 0.4 { 0. } else { db };
|
||||
db.clamp(GAIN_MIN, GAIN_MAX)
|
||||
}
|
||||
|
||||
/// Bar editor of the per-harmonic gains, with the effective curve and measured levels.
|
||||
fn harmonic_editor(ui: &mut egui::Ui, settings: &mut Settings, state: &mut State, height: f32) {
|
||||
let size = Vec2::new(ui.available_width(), height);
|
||||
let (outer, response) = ui.allocate_exact_size(size, Sense::click_and_drag());
|
||||
let p = ui.painter_at(outer);
|
||||
p.rect_filled(outer, 2., SCREEN);
|
||||
let levels_h = 64.;
|
||||
let labels_h = 18.;
|
||||
let left = 34.;
|
||||
let gains = Rect::from_min_max(
|
||||
outer.left_top() + Vec2::new(left, 12.),
|
||||
Pos2::new(
|
||||
outer.right() - 10.,
|
||||
outer.bottom() - levels_h - labels_h - 8.,
|
||||
),
|
||||
);
|
||||
let levels = Rect::from_min_max(
|
||||
Pos2::new(gains.left(), gains.bottom() + labels_h + 4.),
|
||||
Pos2::new(gains.right(), outer.bottom() - 6.),
|
||||
);
|
||||
let col = gains.width() / HARMONICS as f32;
|
||||
let column = |x: f32| {
|
||||
(((x - gains.left()) / col).floor() as isize).clamp(0, HARMONICS as isize - 1) as usize
|
||||
};
|
||||
|
||||
// Interaction: drag draws, Shift-drag nudges, double-click resets a bar.
|
||||
if let Some(pos) = response.interact_pointer_pos() {
|
||||
let k = column(pos.x);
|
||||
if response.double_clicked() {
|
||||
settings.gains[k] = 0.;
|
||||
state.stroke = None;
|
||||
} else if response.dragged() || response.drag_started() || response.clicked() {
|
||||
if ui.input(|i| i.modifiers.shift) {
|
||||
let dy = ui.input(|i| i.pointer.delta().y);
|
||||
let step = dy * (GAIN_MAX - GAIN_MIN) / gains.height() * 0.15;
|
||||
settings.gains[k] = (settings.gains[k] - step).clamp(GAIN_MIN, GAIN_MAX);
|
||||
} else {
|
||||
let db = y_gain(gains, pos.y);
|
||||
// Fill every column the pointer skipped since the last frame.
|
||||
let (from, from_db) = state.stroke.unwrap_or((k, db));
|
||||
let (a, b) = (from.min(k), from.max(k));
|
||||
for i in a..=b {
|
||||
let t = if b == a {
|
||||
1.
|
||||
} else {
|
||||
(i as f32 - from as f32) / (k as f32 - from as f32)
|
||||
};
|
||||
settings.gains[i] = from_db + (db - from_db) * t.clamp(0., 1.);
|
||||
}
|
||||
state.stroke = Some((k, db));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !response.dragged() {
|
||||
state.stroke = None;
|
||||
}
|
||||
|
||||
// Grid: dB lines with labels.
|
||||
for db in [12., 6., 0., -6., -12., -18., -24.] {
|
||||
let y = gain_y(gains, db);
|
||||
let zero = db == 0.;
|
||||
p.line_segment(
|
||||
[Pos2::new(gains.left(), y), Pos2::new(gains.right(), y)],
|
||||
Stroke::new(1.0_f32, if zero { EDGE } else { GRID }),
|
||||
);
|
||||
p.text(
|
||||
Pos2::new(outer.left() + 6., y),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
if zero {
|
||||
"0".into()
|
||||
} else {
|
||||
format!("{db:+.0}")
|
||||
},
|
||||
FontId::proportional(10.),
|
||||
if zero { MUTED } else { DIM },
|
||||
);
|
||||
}
|
||||
let zero = gain_y(gains, 0.);
|
||||
let active = settings.harmonics as usize;
|
||||
let hover = response.hover_pos().map(|pos| column(pos.x));
|
||||
let mut curve = Vec::with_capacity(HARMONICS);
|
||||
for k in 0..HARMONICS {
|
||||
let x0 = gains.left() + col * k as f32;
|
||||
let bar = Rect::from_min_max(
|
||||
Pos2::new(x0 + col * 0.18, zero.min(gain_y(gains, settings.gains[k]))),
|
||||
Pos2::new(x0 + col * 0.82, zero.max(gain_y(gains, settings.gains[k]))),
|
||||
);
|
||||
let on = k < active;
|
||||
let fill = if !on {
|
||||
Color32::from_rgb(40, 42, 47)
|
||||
} else if hover == Some(k) {
|
||||
Color32::from_rgb(255, 60, 130)
|
||||
} else {
|
||||
ACCENT
|
||||
};
|
||||
if bar.height() >= 1. {
|
||||
p.rect_filled(bar, 1., fill);
|
||||
} else {
|
||||
p.line_segment(
|
||||
[Pos2::new(bar.left(), zero), Pos2::new(bar.right(), zero)],
|
||||
Stroke::new(2.0_f32, if on { DIM } else { GRID }),
|
||||
);
|
||||
}
|
||||
if on {
|
||||
curve.push(Pos2::new(
|
||||
x0 + col * 0.5,
|
||||
gain_y(gains, settings.effective(k + 1)),
|
||||
));
|
||||
}
|
||||
let label_color = if hover == Some(k) {
|
||||
TEXT
|
||||
} else if on {
|
||||
MUTED
|
||||
} else {
|
||||
DIM
|
||||
};
|
||||
p.text(
|
||||
Pos2::new(x0 + col * 0.5, gains.bottom() + 4.),
|
||||
egui::Align2::CENTER_TOP,
|
||||
format!("{}", k + 1),
|
||||
FontId::proportional(10.),
|
||||
label_color,
|
||||
);
|
||||
// Measured levels: input (steel) and output (accent), side by side.
|
||||
let f = &state.analyzer;
|
||||
for (i, (db, color)) in [(f.input[k], STEEL), (f.output[k], ACCENT)]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let t = ((db - LEVEL_FLOOR) / -LEVEL_FLOOR).clamp(0., 1.);
|
||||
if t <= 0. {
|
||||
continue;
|
||||
}
|
||||
let w = col * 0.3;
|
||||
let x = x0 + col * 0.18 + i as f32 * (w + col * 0.04);
|
||||
let r = Rect::from_min_max(
|
||||
Pos2::new(x, levels.bottom() - levels.height() * t),
|
||||
Pos2::new(x + w, levels.bottom()),
|
||||
);
|
||||
p.rect_filled(r, 0., color.gamma_multiply(if on { 0.9 } else { 0.4 }));
|
||||
}
|
||||
}
|
||||
if curve.len() > 1 {
|
||||
p.add(egui::Shape::line(curve, Stroke::new(1.5_f32, FOCUS)));
|
||||
}
|
||||
p.line_segment(
|
||||
[
|
||||
Pos2::new(levels.left(), levels.top() - 2.),
|
||||
Pos2::new(levels.right(), levels.top() - 2.),
|
||||
],
|
||||
Stroke::new(1.0_f32, GRID),
|
||||
);
|
||||
p.text(
|
||||
gains.right_top() + Vec2::new(-4., 2.),
|
||||
egui::Align2::RIGHT_TOP,
|
||||
"GAIN · EFFECTIVE",
|
||||
FontId::proportional(11.),
|
||||
MUTED,
|
||||
);
|
||||
p.text(
|
||||
Pos2::new(levels.right() - 4., levels.top() + 2.),
|
||||
egui::Align2::RIGHT_TOP,
|
||||
"LEVEL IN · OUT",
|
||||
FontId::proportional(11.),
|
||||
MUTED,
|
||||
);
|
||||
p.rect_stroke(
|
||||
outer,
|
||||
2.,
|
||||
Stroke::new(1.0_f32, EDGE),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
if let Some(k) = hover {
|
||||
let f = &state.analyzer;
|
||||
let at = if f.hz > 0. {
|
||||
format!(" at {:.0} Hz", f.hz * (k + 1) as f32)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
state.help = format!(
|
||||
"Harmonic {}{at}: drawn {:+.1} dB, effective {:+.1} dB. Drag to draw, Shift-drag fine, double-click resets.",
|
||||
k + 1,
|
||||
settings.gains[k],
|
||||
settings.effective(k + 1),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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, "LATHE", "HARMONIC EQ", |ui| {
|
||||
let r = ui
|
||||
.selectable_label(settings.bypass, RichText::new("BYPASS").size(13.))
|
||||
.on_hover_text("Crossfade to the delayed dry signal.");
|
||||
if r.clicked() {
|
||||
settings.bypass = !settings.bypass;
|
||||
}
|
||||
ui.separator();
|
||||
for (source, label) in [(Source::Midi, "MIDI"), (Source::Audio, "AUDIO")] {
|
||||
let r = ui.selectable_label(settings.source == source, RichText::new(label).size(13.));
|
||||
if r.clicked() {
|
||||
settings.source = source;
|
||||
}
|
||||
}
|
||||
caption(ui, "PITCH FROM");
|
||||
});
|
||||
ui.add_space(6.);
|
||||
let frame = state.analyzer;
|
||||
ui.horizontal_top(|ui| {
|
||||
panel(ui, |ui| {
|
||||
ui.set_width(210.);
|
||||
ui.set_min_height(TOP);
|
||||
ui.vertical(|ui| note_panel(ui, settings, state, &frame));
|
||||
});
|
||||
ui.add_space(4.);
|
||||
panel(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
harmonic_editor(ui, settings, state, 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.;
|
||||
|
||||
/// Label, help text, and gain in dB for 1-based harmonic `k`.
|
||||
type Preset = (&'static str, &'static str, fn(usize) -> f32);
|
||||
|
||||
fn note_panel(
|
||||
ui: &mut egui::Ui,
|
||||
settings: &mut Settings,
|
||||
state: &mut State,
|
||||
frame: &AnalyzerFrame,
|
||||
) {
|
||||
caption(ui, "NOTE");
|
||||
let (name, hz) = match frame.note {
|
||||
Some(n) if frame.hz > 0. => (common_dsp::note_name(n), format!("{:.1} Hz", frame.hz)),
|
||||
_ if frame.hz > 0. => ("—".into(), format!("holding {:.1} Hz", frame.hz)),
|
||||
_ => ("—".into(), "no note yet".into()),
|
||||
};
|
||||
ui.label(
|
||||
RichText::new(name)
|
||||
.font(FontId::new(54., egui::FontFamily::Name("medium".into())))
|
||||
.color(if frame.note.is_some() { TEXT } else { DIM }),
|
||||
);
|
||||
ui.label(RichText::new(hz).monospace().size(14.).color(MUTED));
|
||||
ui.add_space(6.);
|
||||
ui.label(
|
||||
RichText::new(format!(
|
||||
"{:.0} ms lookahead · {}",
|
||||
frame.latency as f32 / frame.sample_rate * 1000.,
|
||||
match settings.source {
|
||||
Source::Audio => "detecting pitch",
|
||||
Source::Midi => "following MIDI",
|
||||
}
|
||||
))
|
||||
.size(12.)
|
||||
.color(MUTED),
|
||||
);
|
||||
ui.add_space(14.);
|
||||
caption(ui, "SHAPES");
|
||||
let presets: [Preset; 4] = [
|
||||
("FLAT", "Reset every drawn gain to 0 dB.", |_| 0.),
|
||||
(
|
||||
"ODD ONLY",
|
||||
"Remove even harmonics: hollow, square-like.",
|
||||
|k| {
|
||||
if k % 2 == 0 {
|
||||
-24.
|
||||
} else {
|
||||
0.
|
||||
}
|
||||
},
|
||||
),
|
||||
(
|
||||
"EVEN ONLY",
|
||||
"Keep the fundamental and even harmonics: octave-like, smooth.",
|
||||
|k| {
|
||||
if k > 1 && k % 2 == 1 {
|
||||
-24.
|
||||
} else {
|
||||
0.
|
||||
}
|
||||
},
|
||||
),
|
||||
(
|
||||
"HOLLOW",
|
||||
"Cut harmonics 2–4: scooped, vocal growl body.",
|
||||
|k| {
|
||||
if (2..=4).contains(&k) {
|
||||
-12.
|
||||
} else {
|
||||
0.
|
||||
}
|
||||
},
|
||||
),
|
||||
];
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for (label, help, f) in presets {
|
||||
let r = ui.button(RichText::new(label).size(12.));
|
||||
if r.clicked() {
|
||||
for k in 0..HARMONICS {
|
||||
settings.gains[k] = f(k + 1);
|
||||
}
|
||||
}
|
||||
hint(&r, state, help);
|
||||
}
|
||||
});
|
||||
ui.add_space(10.);
|
||||
let r = ui.selectable_label(settings.snap, RichText::new("SNAP TO SEMITONE").size(13.));
|
||||
if r.clicked() {
|
||||
settings.snap = !settings.snap;
|
||||
}
|
||||
hint(
|
||||
&r,
|
||||
state,
|
||||
"Round the detected pitch. Turn off for slides and pitch bends.",
|
||||
);
|
||||
}
|
||||
|
||||
fn controls(ui: &mut egui::Ui, settings: &mut Settings, state: &mut State) {
|
||||
let d = Settings::default();
|
||||
ui.columns(9, |c| {
|
||||
knob(&mut c[0], state, "Tilt", &mut settings.tilt, -12. ..=12., d.tilt, " dB/oct", 80.,
|
||||
"Brighter or darker by harmonic number: dB per octave of harmonics, pivot on the fundamental.");
|
||||
knob(&mut c[1], state, "Odd/Even", &mut settings.odd_even, -12. ..=12., d.odd_even, " dB", 80.,
|
||||
"Positive: odd harmonics up, even down (square-like). Negative: the reverse.");
|
||||
knob(&mut c[2], state, "Between", &mut settings.between, -24. ..=12., d.between, " dB", 80.,
|
||||
"Gain between the harmonics. Cut to clean noise and beating, lift for grit.");
|
||||
knob(&mut c[3], state, "Width", &mut settings.width, 5. ..=50., d.width, " %", 80.,
|
||||
"Bandwidth of every band as a share of the harmonic spacing.");
|
||||
let mut harmonics = settings.harmonics as f32;
|
||||
knob(&mut c[4], state, "Harmonics", &mut harmonics, 8. ..=32., d.harmonics as f32, "", 54.,
|
||||
"How many harmonics are shaped. Higher harmonics pass unchanged.");
|
||||
settings.harmonics = harmonics.round() as u32;
|
||||
knob(&mut c[5], state, "Smooth", &mut settings.smooth, 0. ..=100., d.smooth, " ms", 54.,
|
||||
"Retune time for slides and bends. New notes always retune at once.");
|
||||
knob(&mut c[6], state, "Gate", &mut settings.gate, -60. ..=-20., d.gate, " dB", 54.,
|
||||
"Input level that counts as a note. Raise it if tails retrigger.");
|
||||
knob(&mut c[7], state, "Mix", &mut settings.mix, 0. ..=100., d.mix, " %", 54.,
|
||||
"Blend with the delayed dry signal.");
|
||||
knob(&mut c[8], state, "Output", &mut settings.output, -12. ..=12., d.output, " dB", 54.,
|
||||
"Output trim.");
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user