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 = "temper-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,405 @@
|
||||
//! Note-tracked distortion: the filters around the shaper follow the played note and the
|
||||
//! input level is normalised per note, so every note distorts with the same character.
|
||||
//!
|
||||
//! The audio path is delayed by the tracker's lookahead, so filters and drive are set for a
|
||||
//! note before its attack reaches the shaper. The shaper runs at 4× the sample rate.
|
||||
mod settings;
|
||||
use common_dsp::meter::{HarmonicMeter, HARMONICS};
|
||||
use common_dsp::oversample::Oversampler;
|
||||
use common_dsp::svf::{Svf, SvfCoef};
|
||||
use common_dsp::tracker::{NoteEvent, PitchFollower, Tracker, TrackerConfig};
|
||||
use common_dsp::{coefficient, db_to_gain, gain_to_db, hz_to_midi};
|
||||
pub use settings::{Curve, Settings, Source};
|
||||
|
||||
pub const MIN_HZ: f32 = TrackerConfig::BASS.min_hz;
|
||||
pub const MAX_HZ: f32 = TrackerConfig::BASS.max_hz;
|
||||
/// Harmonics shown by the editor.
|
||||
pub const SHOWN: usize = 16;
|
||||
/// RMS level that Normalize brings every note to before Drive.
|
||||
const TARGET_DB: f32 = -12.;
|
||||
const RETUNE: usize = 16;
|
||||
const DRY: usize = 64;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct AnalyzerFrame {
|
||||
pub hz: f32,
|
||||
pub note: Option<u8>,
|
||||
/// Harmonic levels in dBFS of the delayed input and of the output (index 0 = fundamental).
|
||||
pub input: [f32; SHOWN],
|
||||
pub output: [f32; SHOWN],
|
||||
/// Peak level reaching the shaper, after normalisation and drive, in dB.
|
||||
pub shaper_db: f32,
|
||||
/// Gain applied by Normalize and by Auto gain, in dB.
|
||||
pub normalize_db: f32,
|
||||
pub auto_db: f32,
|
||||
pub latency: u32,
|
||||
pub sample_rate: f32,
|
||||
}
|
||||
impl Default for AnalyzerFrame {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
hz: 0.,
|
||||
note: None,
|
||||
input: [-120.; SHOWN],
|
||||
output: [-120.; SHOWN],
|
||||
shaper_db: -120.,
|
||||
normalize_db: 0.,
|
||||
auto_db: 0.,
|
||||
latency: 0,
|
||||
sample_rate: 48000.,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-note input level, measured on the undelayed input so it is known at the attack.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
struct Level {
|
||||
/// RMS of the undelayed input.
|
||||
ahead: f32,
|
||||
/// Loudest `ahead` since the note started, slowly released.
|
||||
note: f32,
|
||||
}
|
||||
impl Level {
|
||||
fn event(&mut self, e: NoteEvent) {
|
||||
if let NoteEvent::Start { glide: false, .. } = e {
|
||||
// `ahead` already looks one lookahead into the new note.
|
||||
self.note = self.ahead;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Filters {
|
||||
floor: SvfCoef,
|
||||
push: SvfCoef,
|
||||
bright: SvfCoef,
|
||||
}
|
||||
|
||||
struct Channel {
|
||||
floor: Svf,
|
||||
push: Svf,
|
||||
bright: Svf,
|
||||
over: Oversampler,
|
||||
dc_x: f32,
|
||||
dc_y: f32,
|
||||
dry: [f32; DRY],
|
||||
}
|
||||
impl Channel {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
floor: Svf::default(),
|
||||
push: Svf::default(),
|
||||
bright: Svf::default(),
|
||||
over: Oversampler::new(),
|
||||
dc_x: 0.,
|
||||
dc_y: 0.,
|
||||
dry: [0.; DRY],
|
||||
}
|
||||
}
|
||||
fn reset(&mut self) {
|
||||
self.floor.reset();
|
||||
self.push.reset();
|
||||
self.bright.reset();
|
||||
self.over.reset();
|
||||
self.dc_x = 0.;
|
||||
self.dc_y = 0.;
|
||||
self.dry = [0.; DRY];
|
||||
}
|
||||
}
|
||||
|
||||
struct Smoothed {
|
||||
value: f32,
|
||||
coef: f32,
|
||||
}
|
||||
impl Smoothed {
|
||||
fn new(value: f32, coef: f32) -> Self {
|
||||
Self { value, coef }
|
||||
}
|
||||
#[inline]
|
||||
fn next(&mut self, target: f32) -> f32 {
|
||||
let d = target - self.value;
|
||||
self.value = if d.abs() < 1e-6 {
|
||||
target
|
||||
} else {
|
||||
self.value + d * self.coef
|
||||
};
|
||||
self.value
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Engine {
|
||||
rate: f32,
|
||||
channels: usize,
|
||||
settings: Settings,
|
||||
latency: usize,
|
||||
delay: Vec<[f32; 2]>,
|
||||
delay_at: usize,
|
||||
dry_at: usize,
|
||||
tracker: Tracker,
|
||||
pitch: PitchFollower,
|
||||
hz_coef: f32,
|
||||
countdown: usize,
|
||||
filters: Filters,
|
||||
channel: [Channel; 2],
|
||||
level: Level,
|
||||
rms_coef: f32,
|
||||
release: f32,
|
||||
norm_db: Smoothed,
|
||||
drive: Smoothed,
|
||||
bias: Smoothed,
|
||||
mix: Smoothed,
|
||||
output: Smoothed,
|
||||
bypass: Smoothed,
|
||||
auto_db: Smoothed,
|
||||
power_in: f32,
|
||||
power_out: f32,
|
||||
power_coef: f32,
|
||||
dc_r: f32,
|
||||
shaper_peak: 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 lookahead = tracker.latency();
|
||||
let smooth = coefficient(rate, 10.);
|
||||
let settings = Settings::default();
|
||||
let mut e = Self {
|
||||
rate,
|
||||
channels,
|
||||
settings,
|
||||
latency: lookahead + Oversampler::latency(),
|
||||
delay: vec![[0.; 2]; lookahead + 1],
|
||||
delay_at: 0,
|
||||
dry_at: 0,
|
||||
tracker,
|
||||
pitch: PitchFollower::default(),
|
||||
hz_coef: coefficient(rate, 5.),
|
||||
countdown: 0,
|
||||
filters: Filters {
|
||||
floor: SvfCoef::IDENTITY,
|
||||
push: SvfCoef::IDENTITY,
|
||||
bright: SvfCoef::IDENTITY,
|
||||
},
|
||||
channel: [Channel::new(), Channel::new()],
|
||||
level: Level::default(),
|
||||
rms_coef: coefficient(rate, 10.),
|
||||
release: 1. - coefficient(rate, 1500.),
|
||||
norm_db: Smoothed::new(0., coefficient(rate, 5.)),
|
||||
drive: Smoothed::new(db_to_gain(settings.drive), smooth),
|
||||
bias: Smoothed::new(0., smooth),
|
||||
mix: Smoothed::new(1., smooth),
|
||||
output: Smoothed::new(1., smooth),
|
||||
bypass: Smoothed::new(0., smooth),
|
||||
auto_db: Smoothed::new(0., coefficient(rate, 50.)),
|
||||
power_in: 0.,
|
||||
power_out: 0.,
|
||||
power_coef: coefficient(rate, 300.),
|
||||
dc_r: 1. - std::f32::consts::TAU * 10. / rate,
|
||||
shaper_peak: 0.,
|
||||
meter_in: HarmonicMeter::new(rate, 85.),
|
||||
meter_out: HarmonicMeter::new(rate, 85.),
|
||||
fresh: true,
|
||||
};
|
||||
e.set_settings(settings)?;
|
||||
e.fresh = true;
|
||||
Ok(e)
|
||||
}
|
||||
/// Lookahead plus the oversampling filters.
|
||||
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, true);
|
||||
if std::mem::take(&mut self.fresh) {
|
||||
self.drive.value = db_to_gain(s.drive);
|
||||
self.bias.value = s.bias * 0.008;
|
||||
self.mix.value = s.mix * 0.01;
|
||||
self.output.value = db_to_gain(s.output);
|
||||
self.bypass.value = f32::from(s.bypass);
|
||||
}
|
||||
self.settings = s;
|
||||
Ok(())
|
||||
}
|
||||
pub fn reset(&mut self) {
|
||||
self.delay.fill([0.; 2]);
|
||||
self.tracker.reset();
|
||||
for c in &mut self.channel {
|
||||
c.reset();
|
||||
}
|
||||
self.level = Level::default();
|
||||
self.power_in = 0.;
|
||||
self.power_out = 0.;
|
||||
self.shaper_peak = 0.;
|
||||
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);
|
||||
}
|
||||
fn retune(&mut self, hz: f32) {
|
||||
let s = &self.settings;
|
||||
let limit = 0.45 * self.rate;
|
||||
let tuned = |mult: f32| hz > 0. && mult > 0. && hz * mult < limit;
|
||||
self.filters.floor = if tuned(s.floor) {
|
||||
SvfCoef::highpass(self.rate, hz * s.floor, std::f32::consts::FRAC_1_SQRT_2)
|
||||
} else {
|
||||
SvfCoef::IDENTITY
|
||||
};
|
||||
let k = s.push_harmonic as f32;
|
||||
self.filters.push = if tuned(k) && s.push_gain != 0. {
|
||||
SvfCoef::bell(self.rate, hz * k, k / 0.6, s.push_gain)
|
||||
} else {
|
||||
SvfCoef::IDENTITY
|
||||
};
|
||||
self.filters.bright = if tuned(s.bright) {
|
||||
SvfCoef::lowpass(self.rate, hz * s.bright, std::f32::consts::FRAC_1_SQRT_2)
|
||||
} else {
|
||||
SvfCoef::IDENTITY
|
||||
};
|
||||
}
|
||||
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]
|
||||
};
|
||||
// Level of the input one lookahead ahead of the audio that is about to be shaped.
|
||||
let a = &mut self.level;
|
||||
a.ahead += (mono * mono - a.ahead) * self.rms_coef;
|
||||
a.note = (a.note * self.release).max(a.ahead);
|
||||
let (pitch, level) = (&mut self.pitch, &mut self.level);
|
||||
self.tracker.process(mono, |e| {
|
||||
pitch.event(false, e);
|
||||
level.event(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 (hz, jump) = self.pitch.step(self.hz_coef);
|
||||
if jump || self.countdown == 0 {
|
||||
self.retune(hz);
|
||||
self.countdown = RETUNE;
|
||||
}
|
||||
self.countdown -= 1;
|
||||
|
||||
let s = self.settings;
|
||||
let rms_db = 10. * self.level.note.max(1e-12).log10();
|
||||
// Below −60 dBFS there is nothing to normalise; hold the last gain.
|
||||
let norm_target = if rms_db > -60. {
|
||||
(s.normalize * 0.01 * (TARGET_DB - rms_db)).clamp(-24., 36.)
|
||||
} else {
|
||||
self.norm_db.value
|
||||
};
|
||||
let norm = db_to_gain(self.norm_db.next(norm_target));
|
||||
let drive = self.drive.next(db_to_gain(s.drive));
|
||||
let bias = self.bias.next(s.bias * 0.008);
|
||||
let mix = self.mix.next(s.mix * 0.01);
|
||||
let output = self.output.next(db_to_gain(s.output));
|
||||
let bypass = self.bypass.next(f32::from(s.bypass));
|
||||
let curve = s.curve;
|
||||
let offset = curve.shape(bias);
|
||||
let f = self.filters;
|
||||
let dry_at = self.dry_at;
|
||||
let back = (dry_at + DRY - Oversampler::latency()) % DRY;
|
||||
let mut wet = [0.; 2];
|
||||
let mut dry = [0.; 2];
|
||||
let mut peak = self.shaper_peak;
|
||||
for c in 0..self.channels {
|
||||
let ch = &mut self.channel[c];
|
||||
ch.dry[dry_at] = y[c];
|
||||
dry[c] = ch.dry[back];
|
||||
let v = ch.floor.process(&f.floor, y[c]);
|
||||
let v = ch.push.process(&f.push, v) * norm * drive;
|
||||
let up = ch.over.up(v);
|
||||
let shaped = up.map(|u| {
|
||||
peak = peak.max(u.abs());
|
||||
curve.shape(u + bias) - offset
|
||||
});
|
||||
let v = ch.over.down(shaped);
|
||||
let v = ch.bright.process(&f.bright, v);
|
||||
// DC blocker: bias and asymmetric curves leave an offset.
|
||||
let d = v - ch.dc_x + self.dc_r * ch.dc_y;
|
||||
ch.dc_x = v;
|
||||
ch.dc_y = d;
|
||||
wet[c] = d;
|
||||
}
|
||||
self.shaper_peak = peak;
|
||||
self.dry_at = (dry_at + 1) % DRY;
|
||||
|
||||
let (dry_mono, wet_mono) = if self.channels == 2 {
|
||||
(0.5 * (dry[0] + dry[1]), 0.5 * (wet[0] + wet[1]))
|
||||
} else {
|
||||
(dry[0], wet[0])
|
||||
};
|
||||
self.power_in += (dry_mono * dry_mono - self.power_in) * self.power_coef;
|
||||
self.power_out += (wet_mono * wet_mono - self.power_out) * self.power_coef;
|
||||
let auto_target = if !s.auto_gain {
|
||||
0.
|
||||
} else if self.power_in > 1e-7 && self.power_out > 1e-9 {
|
||||
(10. * (self.power_in / self.power_out).log10()).clamp(-36., 24.)
|
||||
} else {
|
||||
self.auto_db.value
|
||||
};
|
||||
let auto = db_to_gain(self.auto_db.next(auto_target));
|
||||
let mut out = [0.; 2];
|
||||
for c in 0..self.channels {
|
||||
let v = (mix * wet[c] * auto + (1. - mix) * dry[c]) * output;
|
||||
out[c] = v * (1. - bypass) + dry[c] * bypass;
|
||||
}
|
||||
let tone = if self.tracker.sounding() { hz } else { 0. };
|
||||
let o = if self.channels == 2 {
|
||||
0.5 * (out[0] + out[1])
|
||||
} else {
|
||||
out[0]
|
||||
};
|
||||
self.meter_in.push(dry_mono, tone);
|
||||
self.meter_out.push(o, tone);
|
||||
out
|
||||
}
|
||||
pub fn take_analyzer(&mut self) -> AnalyzerFrame {
|
||||
let hz = self.pitch.hz();
|
||||
let mut f = AnalyzerFrame {
|
||||
hz,
|
||||
latency: self.latency as u32,
|
||||
sample_rate: self.rate,
|
||||
shaper_db: gain_to_db(self.shaper_peak),
|
||||
normalize_db: self.norm_db.value,
|
||||
auto_db: self.auto_db.value,
|
||||
..AnalyzerFrame::default()
|
||||
};
|
||||
self.shaper_peak = 0.;
|
||||
f.input
|
||||
.copy_from_slice(&self.meter_in.levels()[..SHOWN.min(HARMONICS)]);
|
||||
f.output
|
||||
.copy_from_slice(&self.meter_out.levels()[..SHOWN.min(HARMONICS)]);
|
||||
if self.tracker.sounding() && hz > 0. {
|
||||
f.note = Some(hz_to_midi(hz).round().clamp(0., 127.) as u8);
|
||||
}
|
||||
f
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
//! Host-independent controls. Levels in dB, harmonic positions as multiples of the fundamental.
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[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, Eq, Default)]
|
||||
pub enum Curve {
|
||||
/// tanh: smooth, odd harmonics, rounded top.
|
||||
#[default]
|
||||
Soft,
|
||||
/// Clipping with a narrow knee: dense, square-like.
|
||||
Hard,
|
||||
/// Sine wavefolder: drive folds the wave back, adding moving upper harmonics.
|
||||
Fold,
|
||||
/// Asymmetric: the negative half clips earlier, adding even harmonics.
|
||||
Tube,
|
||||
}
|
||||
impl Curve {
|
||||
pub const ALL: [Curve; 4] = [Curve::Soft, Curve::Hard, Curve::Fold, Curve::Tube];
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Curve::Soft => "Soft",
|
||||
Curve::Hard => "Hard",
|
||||
Curve::Fold => "Fold",
|
||||
Curve::Tube => "Tube",
|
||||
}
|
||||
}
|
||||
/// Transfer function; maps 0 to 0.
|
||||
#[inline]
|
||||
pub fn shape(self, u: f32) -> f32 {
|
||||
match self {
|
||||
Curve::Soft => u.tanh(),
|
||||
Curve::Hard => {
|
||||
let u = u.clamp(-8., 8.);
|
||||
u / (1. + u.abs().powi(8)).powf(0.125)
|
||||
}
|
||||
// Scaled so full drive gives about five folds; more is mostly aliasing noise.
|
||||
Curve::Fold => (std::f32::consts::FRAC_PI_2 * 0.4 * u.clamp(-64., 64.)).sin(),
|
||||
Curve::Tube => {
|
||||
if u >= 0. {
|
||||
u.tanh()
|
||||
} else {
|
||||
0.6 * (u / 0.6).tanh()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Settings {
|
||||
pub source: Source,
|
||||
/// Gain into the shaper after level normalisation.
|
||||
pub drive: f32,
|
||||
pub curve: Curve,
|
||||
/// Asymmetry in percent: shifts the curve's operating point, adding even harmonics.
|
||||
pub bias: f32,
|
||||
/// How far the input level is normalised per note before the shaper, in percent. At 100 %
|
||||
/// a quiet patch and a loud patch are driven the same.
|
||||
pub normalize: f32,
|
||||
/// Highpass in front of the shaper at this multiple of the fundamental; 0 is off.
|
||||
pub floor: f32,
|
||||
/// Harmonic that `push_gain` boosts or cuts before the shaper.
|
||||
pub push_harmonic: u32,
|
||||
pub push_gain: f32,
|
||||
/// Lowpass after the shaper at this harmonic number; 0 is off.
|
||||
pub bright: f32,
|
||||
/// Matches output loudness to the input, so Drive changes character, not level.
|
||||
pub auto_gain: bool,
|
||||
/// Detection threshold in dBFS for note starts (Audio source).
|
||||
pub gate: f32,
|
||||
pub mix: f32,
|
||||
pub output: f32,
|
||||
pub bypass: bool,
|
||||
}
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
source: Source::Audio,
|
||||
drive: 12.,
|
||||
curve: Curve::Soft,
|
||||
bias: 0.,
|
||||
normalize: 100.,
|
||||
floor: 0.,
|
||||
push_harmonic: 3,
|
||||
push_gain: 0.,
|
||||
bright: 0.,
|
||||
auto_gain: true,
|
||||
gate: -42.,
|
||||
mix: 100.,
|
||||
output: 0.,
|
||||
bypass: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Settings {
|
||||
pub fn validate(&self) -> Result<(), &'static str> {
|
||||
let finite = [
|
||||
self.drive,
|
||||
self.bias,
|
||||
self.normalize,
|
||||
self.floor,
|
||||
self.push_gain,
|
||||
self.bright,
|
||||
self.gate,
|
||||
self.mix,
|
||||
self.output,
|
||||
]
|
||||
.iter()
|
||||
.all(|v| v.is_finite());
|
||||
if !finite {
|
||||
return Err("non-finite setting");
|
||||
}
|
||||
let ok = (0.0..=36.).contains(&self.drive)
|
||||
&& (0.0..=100.).contains(&self.bias)
|
||||
&& (0.0..=100.).contains(&self.normalize)
|
||||
&& (self.floor == 0. || (0.25..=2.).contains(&self.floor))
|
||||
&& (1..=16).contains(&self.push_harmonic)
|
||||
&& (-12.0..=12.).contains(&self.push_gain)
|
||||
&& (self.bright == 0. || (4.0..=64.).contains(&self.bright))
|
||||
&& (-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")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
use common_dsp::meter::HarmonicMeter;
|
||||
use common_dsp::Saw;
|
||||
use std::f32::consts::TAU;
|
||||
use temper_core::{Curve, 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()
|
||||
}
|
||||
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()
|
||||
}
|
||||
/// Harmonics 1–n relative to the fundamental.
|
||||
fn profile(x: &[f32], hz: f32, n: usize) -> Vec<f32> {
|
||||
let h = harmonics(x, hz);
|
||||
(0..n).map(|k| h[k] - h[0]).collect()
|
||||
}
|
||||
fn rms_db(x: &[f32]) -> f32 {
|
||||
10. * (x.iter().map(|v| v * v).sum::<f32>() / x.len() as f32).log10()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quiet_and_loud_patches_distort_the_same() {
|
||||
let s = Settings {
|
||||
drive: 18.,
|
||||
auto_gain: false,
|
||||
..Settings::default()
|
||||
};
|
||||
let mut profiles = vec![];
|
||||
for amp in [0.5, 0.06] {
|
||||
let (mut e, _) = engine(s);
|
||||
let y = render(&mut e, &saw(55., 1.2, amp));
|
||||
profiles.push(profile(&y[y.len() / 2..], 55., 8));
|
||||
}
|
||||
for k in 1..8 {
|
||||
let d = profiles[0][k] - profiles[1][k];
|
||||
assert!(d.abs() < 1., "harmonic {}: {profiles:?}", k + 1);
|
||||
}
|
||||
// Without normalisation the quiet patch is barely distorted.
|
||||
let s = Settings { normalize: 0., ..s };
|
||||
let (mut e, _) = engine(s);
|
||||
let y = render(&mut e, &saw(55., 1.2, 0.06));
|
||||
let quiet = profile(&y[y.len() / 2..], 55., 8);
|
||||
assert!(
|
||||
(quiet[2] - profiles[0][2]).abs() > 2.,
|
||||
"{quiet:?} vs {profiles:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bright_follows_the_note() {
|
||||
let s = Settings {
|
||||
drive: 24.,
|
||||
curve: Curve::Hard,
|
||||
bright: 8.,
|
||||
..Settings::default()
|
||||
};
|
||||
let mut profiles = vec![];
|
||||
for hz in [43.65, 87.31] {
|
||||
let (mut e, _) = engine(s);
|
||||
let y = render(&mut e, &saw(hz, 1.2, 0.4));
|
||||
profiles.push(profile(&y[y.len() / 2..], hz, 14));
|
||||
}
|
||||
for k in 1..14 {
|
||||
let d = profiles[0][k] - profiles[1][k];
|
||||
assert!(d.abs() < 1.5, "harmonic {}: {profiles:?}", k + 1);
|
||||
}
|
||||
// Above the cutoff the harmonics fall away on both notes.
|
||||
assert!(profiles[0][12] < profiles[0][4] - 10.);
|
||||
}
|
||||
|
||||
/// Energy away from the harmonics of `hz`, relative to the harmonics, in dB.
|
||||
fn alias_ratio(curve: Curve, drive: f32, hz: f32) -> f32 {
|
||||
let s = Settings {
|
||||
drive,
|
||||
curve,
|
||||
auto_gain: false,
|
||||
..Settings::default()
|
||||
};
|
||||
let (mut e, _) = engine(s);
|
||||
let x: Vec<f32> = (0..36000)
|
||||
.map(|i| 0.3 * (TAU * hz * i as f32 / RATE).sin())
|
||||
.collect();
|
||||
let y = render(&mut e, &x);
|
||||
let tail = &y[12000..];
|
||||
let n = tail.len();
|
||||
let window: Vec<f32> = (0..n)
|
||||
.map(|i| 0.5 - 0.5 * (TAU * i as f32 / n as f32).cos())
|
||||
.collect();
|
||||
let (mut harmonic, mut other) = (0f64, 0f64);
|
||||
for f in (20..23000).step_by(10) {
|
||||
// Goertzel power at f.
|
||||
let c = 2. * (TAU as f64 * f as f64 / RATE as f64).cos();
|
||||
let (mut s1, mut s2) = (0f64, 0f64);
|
||||
for (v, w) in tail.iter().zip(&window) {
|
||||
let s0 = (v * w) as f64 + c * s1 - s2;
|
||||
s2 = s1;
|
||||
s1 = s0;
|
||||
}
|
||||
let p = s1 * s1 + s2 * s2 - c * s1 * s2;
|
||||
let near = (f as f32 / hz - (f as f32 / hz).round()).abs() * hz < 30.;
|
||||
if near {
|
||||
harmonic += p;
|
||||
} else {
|
||||
other += p;
|
||||
}
|
||||
}
|
||||
(10. * (other / harmonic).log10()) as f32
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversampling_keeps_aliasing_down_in_the_bass_range() {
|
||||
// 2 kHz stands for the upper harmonics of a growl, 440 Hz for a high bass fundamental.
|
||||
for curve in Curve::ALL {
|
||||
let r = alias_ratio(curve, 24., 2000.);
|
||||
assert!(r < -60., "{} 2 kHz: {r}", curve.name());
|
||||
let r = alias_ratio(curve, 36., 440.);
|
||||
assert!(r < -55., "{} 440 Hz: {r}", curve.name());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn print_alias_ratios() {
|
||||
for curve in Curve::ALL {
|
||||
for hz in [440., 2000., 5000.] {
|
||||
for drive in [12., 24., 36.] {
|
||||
println!(
|
||||
"{} {hz} {drive}: {:.1}",
|
||||
curve.name(),
|
||||
alias_ratio(curve, drive, hz)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_gain_matches_input_loudness() {
|
||||
for drive in [6., 24., 36.] {
|
||||
let s = Settings {
|
||||
drive,
|
||||
..Settings::default()
|
||||
};
|
||||
let (mut e, l) = engine(s);
|
||||
let x = saw(55., 2., 0.3);
|
||||
let y = render(&mut e, &x);
|
||||
let d = rms_db(&y[y.len() / 2..]) - rms_db(&x[x.len() / 2 - l..x.len() - l]);
|
||||
assert!(d.abs() < 1., "{drive}: {d}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_mix_is_the_delayed_dry_signal_and_latency_is_exact() {
|
||||
let s = Settings {
|
||||
mix: 0.,
|
||||
..Settings::default()
|
||||
};
|
||||
let (mut e, l) = engine(s);
|
||||
let x = saw(55., 1., 0.5);
|
||||
let y = render(&mut e, &x);
|
||||
for i in RATE as usize / 2..x.len() {
|
||||
assert_eq!(y[i], x[i - l], "{i}");
|
||||
}
|
||||
// With the shaper nearly linear the wet path lines up with the dry one.
|
||||
let s = Settings {
|
||||
drive: 0.,
|
||||
normalize: 0.,
|
||||
curve: Curve::Soft,
|
||||
auto_gain: false,
|
||||
..Settings::default()
|
||||
};
|
||||
let (mut e, l) = engine(s);
|
||||
let mut x = vec![0f32; 9600];
|
||||
x[100] = 0.01;
|
||||
let y = render(&mut e, &x);
|
||||
let at = y
|
||||
.iter()
|
||||
.enumerate()
|
||||
.max_by(|a, b| a.1.abs().total_cmp(&b.1.abs()))
|
||||
.unwrap()
|
||||
.0;
|
||||
assert_eq!(at, 100 + l);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn midi_source_tunes_filters_at_the_delayed_note_time() {
|
||||
let s = Settings {
|
||||
source: Source::Midi,
|
||||
bright: 4.,
|
||||
drive: 18.,
|
||||
curve: Curve::Hard,
|
||||
..Settings::default()
|
||||
};
|
||||
let (mut e, _) = engine(s);
|
||||
e.note_on(29);
|
||||
let y = render(&mut e, &saw(43.65, 1., 0.4));
|
||||
let p = profile(&y[y.len() / 2..], 43.65, 12);
|
||||
assert!(p[10] < p[2] - 12., "{p:?}");
|
||||
let f = e.take_analyzer();
|
||||
assert_eq!(f.note, Some(29));
|
||||
}
|
||||
|
||||
#[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);
|
||||
for bad in [
|
||||
Settings { floor: 0.1, ..s },
|
||||
Settings { bright: 2., ..s },
|
||||
Settings {
|
||||
push_harmonic: 0,
|
||||
..s
|
||||
},
|
||||
Settings {
|
||||
drive: f32::NAN,
|
||||
..s
|
||||
},
|
||||
] {
|
||||
assert!(bad.validate().is_err(), "{bad:?}");
|
||||
}
|
||||
for c in Curve::ALL {
|
||||
assert_eq!(c.shape(0.), 0.);
|
||||
assert!(c.shape(100.).abs() <= 1.0001);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
use std::{
|
||||
alloc::{GlobalAlloc, Layout, System},
|
||||
cell::Cell,
|
||||
};
|
||||
use temper_core::{Curve, Engine, Settings, Source};
|
||||
|
||||
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.curve = Curve::ALL[(i / 4800) % 4];
|
||||
settings.bright = if i % 9600 == 0 { 8. } else { 0. };
|
||||
settings.floor = if i % 9600 == 0 { 0. } else { 0.5 };
|
||||
settings.push_gain = ((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 = "temper"
|
||||
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" }
|
||||
temper-core = { path = "../core" }
|
||||
temper-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,183 @@
|
||||
//! 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::TemperParams;
|
||||
use std::sync::Arc;
|
||||
use temper_core::{AnalyzerFrame, Engine};
|
||||
|
||||
struct EditorData {
|
||||
ui: temper_ui::State,
|
||||
gestures: [bool; 9],
|
||||
}
|
||||
pub struct Temper {
|
||||
params: Arc<TemperParams>,
|
||||
analyzer: Arc<ArrayQueue<AnalyzerFrame>>,
|
||||
engine: Option<Engine>,
|
||||
publish_count: usize,
|
||||
publish_interval: usize,
|
||||
}
|
||||
impl Default for Temper {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
params: Arc::new(TemperParams::default()),
|
||||
analyzer: Arc::new(ArrayQueue::new(2)),
|
||||
engine: None,
|
||||
publish_count: 0,
|
||||
publish_interval: 1600,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Plugin for Temper {
|
||||
const NAME: &'static str = "Temper";
|
||||
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: temper_ui::State::default(),
|
||||
gestures: [false; 9],
|
||||
},
|
||||
|ctx, _| temper_ui::style(ctx),
|
||||
move |ctx, setter, data| {
|
||||
while let Some(frame) = analyzer.pop() {
|
||||
data.ui.accept_frame(frame);
|
||||
}
|
||||
let before = params.settings();
|
||||
let mut edited = before;
|
||||
nih_plug_egui::resizable_window::ResizableWindow::new("temper-editor")
|
||||
.min_size(egui::vec2(
|
||||
temper_ui::WIDTH as f32 - 80.,
|
||||
temper_ui::HEIGHT as f32 - 40.,
|
||||
))
|
||||
.show(ctx, ¶ms.editor, |ui| {
|
||||
temper_ui::show(ui, &mut edited, &mut data.ui)
|
||||
});
|
||||
params.apply(
|
||||
setter,
|
||||
&before,
|
||||
&edited,
|
||||
data.ui.gesture_active,
|
||||
&mut data.gestures,
|
||||
);
|
||||
// Meters 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;
|
||||
};
|
||||
if engine.set_settings(self.params.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 _ = engine.set_settings(self.params.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, oversampling filters and tails must drain after input stops.
|
||||
ProcessStatus::KeepAlive
|
||||
}
|
||||
}
|
||||
impl ClapPlugin for Temper {
|
||||
const CLAP_ID: &'static str = "io.storyboard.tracked-distortion";
|
||||
const CLAP_DESCRIPTION: Option<&'static str> = Some(
|
||||
"Distortion whose drive and tone filters follow the note, so every note distorts the same",
|
||||
);
|
||||
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::Stereo,
|
||||
ClapFeature::Mono,
|
||||
];
|
||||
}
|
||||
nih_export_clap!(Temper);
|
||||
@@ -0,0 +1,207 @@
|
||||
use nih_plug::prelude::*;
|
||||
use nih_plug_egui::EguiState;
|
||||
use std::sync::Arc;
|
||||
use temper_core::{Curve, Settings, Source};
|
||||
|
||||
#[derive(Enum, Debug, PartialEq, Eq, Clone, Copy)]
|
||||
pub enum SourceParam {
|
||||
#[id = "audio"]
|
||||
Audio,
|
||||
#[id = "midi"]
|
||||
#[name = "MIDI"]
|
||||
Midi,
|
||||
}
|
||||
#[derive(Enum, Debug, PartialEq, Eq, Clone, Copy)]
|
||||
pub enum CurveParam {
|
||||
#[id = "soft"]
|
||||
Soft,
|
||||
#[id = "hard"]
|
||||
Hard,
|
||||
#[id = "fold"]
|
||||
Fold,
|
||||
#[id = "tube"]
|
||||
Tube,
|
||||
}
|
||||
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)
|
||||
}
|
||||
const FLOATS: usize = 9;
|
||||
|
||||
#[derive(Params)]
|
||||
pub struct TemperParams {
|
||||
#[persist = "editor"]
|
||||
pub editor: Arc<EguiState>,
|
||||
#[id = "source"]
|
||||
pub source: EnumParam<SourceParam>,
|
||||
#[id = "curve"]
|
||||
pub curve: EnumParam<CurveParam>,
|
||||
#[id = "drive"]
|
||||
pub drive: FloatParam,
|
||||
#[id = "bias"]
|
||||
pub bias: FloatParam,
|
||||
#[id = "normalize"]
|
||||
pub normalize: FloatParam,
|
||||
#[id = "floor"]
|
||||
pub floor: FloatParam,
|
||||
#[id = "push"]
|
||||
pub push_gain: FloatParam,
|
||||
#[id = "bright"]
|
||||
pub bright: FloatParam,
|
||||
#[id = "gate"]
|
||||
pub gate: FloatParam,
|
||||
#[id = "mix"]
|
||||
pub mix: FloatParam,
|
||||
#[id = "output"]
|
||||
pub output: FloatParam,
|
||||
#[id = "push-at"]
|
||||
pub push_harmonic: IntParam,
|
||||
#[id = "auto-gain"]
|
||||
pub auto_gain: BoolParam,
|
||||
#[id = "bypass"]
|
||||
pub bypass: BoolParam,
|
||||
}
|
||||
impl Default for TemperParams {
|
||||
fn default() -> Self {
|
||||
let d = Settings::default();
|
||||
Self {
|
||||
editor: EguiState::from_size(temper_ui::WIDTH, temper_ui::HEIGHT),
|
||||
source: EnumParam::new("Pitch source", SourceParam::Audio),
|
||||
curve: EnumParam::new("Curve", CurveParam::Soft),
|
||||
drive: linear("Drive", d.drive, 0., 36., " dB"),
|
||||
bias: linear("Bias", d.bias, 0., 100., " %"),
|
||||
normalize: linear("Normalize", d.normalize, 0., 100., " %"),
|
||||
floor: linear("Floor", d.floor, 0., 2., " ×f0"),
|
||||
push_gain: linear("Push", d.push_gain, -12., 12., " dB"),
|
||||
bright: linear("Bright", d.bright, 0., 64., " ×f0"),
|
||||
gate: linear("Gate", d.gate, -60., -20., " dB"),
|
||||
mix: linear("Mix", d.mix, 0., 100., " %"),
|
||||
output: linear("Output", d.output, -12., 12., " dB"),
|
||||
push_harmonic: IntParam::new(
|
||||
"Push at",
|
||||
d.push_harmonic as i32,
|
||||
IntRange::Linear { min: 1, max: 16 },
|
||||
),
|
||||
auto_gain: BoolParam::new("Auto gain", d.auto_gain),
|
||||
bypass: BoolParam::new("Bypass", false).make_bypass(),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn curve_to(c: CurveParam) -> Curve {
|
||||
match c {
|
||||
CurveParam::Soft => Curve::Soft,
|
||||
CurveParam::Hard => Curve::Hard,
|
||||
CurveParam::Fold => Curve::Fold,
|
||||
CurveParam::Tube => Curve::Tube,
|
||||
}
|
||||
}
|
||||
fn curve_from(c: Curve) -> CurveParam {
|
||||
match c {
|
||||
Curve::Soft => CurveParam::Soft,
|
||||
Curve::Hard => CurveParam::Hard,
|
||||
Curve::Fold => CurveParam::Fold,
|
||||
Curve::Tube => CurveParam::Tube,
|
||||
}
|
||||
}
|
||||
impl TemperParams {
|
||||
pub fn settings(&self) -> Settings {
|
||||
// Floor and Bright are continuous for automation; below their ranges they are off.
|
||||
let floor = self.floor.value();
|
||||
let bright = self.bright.value();
|
||||
Settings {
|
||||
source: match self.source.value() {
|
||||
SourceParam::Audio => Source::Audio,
|
||||
SourceParam::Midi => Source::Midi,
|
||||
},
|
||||
curve: curve_to(self.curve.value()),
|
||||
drive: self.drive.value(),
|
||||
bias: self.bias.value(),
|
||||
normalize: self.normalize.value(),
|
||||
floor: if floor < 0.25 { 0. } else { floor },
|
||||
push_harmonic: self.push_harmonic.value() as u32,
|
||||
push_gain: self.push_gain.value(),
|
||||
bright: if bright < 4. { 0. } else { bright },
|
||||
auto_gain: self.auto_gain.value(),
|
||||
gate: self.gate.value(),
|
||||
mix: self.mix.value(),
|
||||
output: self.output.value(),
|
||||
bypass: self.bypass.value(),
|
||||
}
|
||||
}
|
||||
fn floats(&self) -> [&FloatParam; FLOATS] {
|
||||
[
|
||||
&self.drive,
|
||||
&self.bias,
|
||||
&self.normalize,
|
||||
&self.floor,
|
||||
&self.push_gain,
|
||||
&self.bright,
|
||||
&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.
|
||||
pub fn apply(
|
||||
&self,
|
||||
setter: &ParamSetter,
|
||||
old: &Settings,
|
||||
new: &Settings,
|
||||
dragging: bool,
|
||||
open: &mut [bool; FLOATS],
|
||||
) {
|
||||
let values = [
|
||||
(old.drive, new.drive),
|
||||
(old.bias, new.bias),
|
||||
(old.normalize, new.normalize),
|
||||
(old.floor, new.floor),
|
||||
(old.push_gain, new.push_gain),
|
||||
(old.bright, new.bright),
|
||||
(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.push_harmonic != old.push_harmonic {
|
||||
setter.begin_set_parameter(&self.push_harmonic);
|
||||
setter.set_parameter(&self.push_harmonic, new.push_harmonic as i32);
|
||||
setter.end_set_parameter(&self.push_harmonic);
|
||||
}
|
||||
for (p, a, b) in [
|
||||
(&self.auto_gain, old.auto_gain, new.auto_gain),
|
||||
(&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.curve != old.curve {
|
||||
setter.begin_set_parameter(&self.curve);
|
||||
setter.set_parameter(&self.curve, curve_from(new.curve));
|
||||
setter.end_set_parameter(&self.curve);
|
||||
}
|
||||
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,211 @@
|
||||
//! 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 = &temper::clap_entry;
|
||||
assert!(entry.init.unwrap()(c"temper.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"Temper");
|
||||
assert_eq!(
|
||||
CStr::from_ptr((*descriptor).id),
|
||||
c"io.storyboard.tracked-distortion"
|
||||
);
|
||||
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("drive".into(), ParamValue::F32(24.));
|
||||
envelope
|
||||
.params
|
||||
.insert("curve".into(), ParamValue::String("fold".into()));
|
||||
envelope.params.insert("push-at".into(), ParamValue::I32(5));
|
||||
envelope
|
||||
.params
|
||||
.insert("source".into(), ParamValue::String("midi".into()));
|
||||
// Mix 0: the output must be the dry signal, delayed by the reported latency.
|
||||
envelope.params.insert("mix".into(), ParamValue::F32(0.));
|
||||
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;
|
||||
// About 67 ms lookahead plus the oversampling filters.
|
||||
assert!((delay as f64 / rate - 0.068).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 = "temper-ui"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
egui = "0.31.1"
|
||||
temper-core = { path = "../core" }
|
||||
common-ui = { path = "../../common/ui" }
|
||||
common-dsp = { path = "../../common/dsp" }
|
||||
@@ -0,0 +1,413 @@
|
||||
//! Temper editor, shared by the CLAP wrapper and the headless renderer.
|
||||
use common_dsp::db_to_gain;
|
||||
use common_ui::*;
|
||||
use egui::{self, Color32, FontId, Pos2, Rect, RichText, Sense, Stroke, Vec2};
|
||||
use temper_core::{AnalyzerFrame, Curve, Settings, Source, SHOWN};
|
||||
|
||||
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,
|
||||
}
|
||||
impl Default for State {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
analyzer: AnalyzerFrame::default(),
|
||||
gesture_active: false,
|
||||
help: DEFAULT_HELP.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
const DEFAULT_HELP: &str =
|
||||
"Every note is driven the same: the input level is normalised per note and the tone filters follow the pitch.";
|
||||
impl State {
|
||||
pub fn accept_frame(&mut self, frame: AnalyzerFrame) {
|
||||
let old = self.analyzer;
|
||||
self.analyzer = frame;
|
||||
for k in 0..SHOWN {
|
||||
self.analyzer.input[k] = frame.input[k].max(old.input[k] - 3.);
|
||||
self.analyzer.output[k] = frame.output[k].max(old.output[k] - 3.);
|
||||
}
|
||||
self.analyzer.shaper_db = frame.shaper_db.max(old.shaper_db - 1.5);
|
||||
}
|
||||
}
|
||||
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);
|
||||
/// Input peak at which a normalised note reaches the shaper before Drive.
|
||||
const NOMINAL: f32 = 0.35;
|
||||
|
||||
fn transfer(ui: &mut egui::Ui, settings: &Settings, size: f32) {
|
||||
let (rect, _) = ui.allocate_exact_size(Vec2::splat(size), Sense::hover());
|
||||
let p = ui.painter_at(rect);
|
||||
p.rect_filled(rect, 2., SCREEN);
|
||||
let c = rect.center();
|
||||
let half = rect.width() * 0.45;
|
||||
for t in [-1., -0.5, 0.5, 1.] {
|
||||
p.line_segment(
|
||||
[
|
||||
Pos2::new(c.x + t * half, rect.top()),
|
||||
Pos2::new(c.x + t * half, rect.bottom()),
|
||||
],
|
||||
Stroke::new(1.0_f32, GRID),
|
||||
);
|
||||
p.line_segment(
|
||||
[
|
||||
Pos2::new(rect.left(), c.y - t * half),
|
||||
Pos2::new(rect.right(), c.y - t * half),
|
||||
],
|
||||
Stroke::new(1.0_f32, GRID),
|
||||
);
|
||||
}
|
||||
p.line_segment(
|
||||
[Pos2::new(rect.left(), c.y), Pos2::new(rect.right(), c.y)],
|
||||
Stroke::new(1.0_f32, EDGE),
|
||||
);
|
||||
p.line_segment(
|
||||
[Pos2::new(c.x, rect.top()), Pos2::new(c.x, rect.bottom())],
|
||||
Stroke::new(1.0_f32, EDGE),
|
||||
);
|
||||
p.line_segment(
|
||||
[
|
||||
Pos2::new(c.x - half, c.y + half),
|
||||
Pos2::new(c.x + half, c.y - half),
|
||||
],
|
||||
Stroke::new(1.0_f32, DIM),
|
||||
);
|
||||
// Input axis: a normalised note's peak at ±1; output: the shaper's ±1.
|
||||
let gain = db_to_gain(settings.drive) * NOMINAL;
|
||||
let bias = settings.bias * 0.008;
|
||||
let offset = settings.curve.shape(bias);
|
||||
let points: Vec<Pos2> = (0..=160)
|
||||
.map(|i| {
|
||||
let x = -1.1 + 2.2 * i as f32 / 160.;
|
||||
let y = settings.curve.shape(x * gain + bias) - offset;
|
||||
Pos2::new(c.x + x * half, c.y - y.clamp(-1.1, 1.1) * half)
|
||||
})
|
||||
.collect();
|
||||
p.add(egui::Shape::line(points, Stroke::new(2.0_f32, ACCENT)));
|
||||
p.text(
|
||||
rect.left_top() + Vec2::new(8., 6.),
|
||||
egui::Align2::LEFT_TOP,
|
||||
"TRANSFER",
|
||||
FontId::proportional(11.),
|
||||
MUTED,
|
||||
);
|
||||
p.rect_stroke(
|
||||
rect,
|
||||
2.,
|
||||
Stroke::new(1.0_f32, EDGE),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
}
|
||||
|
||||
fn spectrum(ui: &mut egui::Ui, frame: &AnalyzerFrame, settings: &Settings, height: f32) {
|
||||
let size = Vec2::new(ui.available_width(), height);
|
||||
let (outer, response) = ui.allocate_exact_size(size, Sense::hover());
|
||||
let p = ui.painter_at(outer);
|
||||
p.rect_filled(outer, 2., SCREEN);
|
||||
let area = Rect::from_min_max(
|
||||
outer.left_top() + Vec2::new(34., 24.),
|
||||
outer.right_bottom() - Vec2::new(10., 24.),
|
||||
);
|
||||
let floor = -72.;
|
||||
let y = |db: f32| area.bottom() - area.height() * ((db - floor) / -floor).clamp(0., 1.);
|
||||
for db in [0., -12., -24., -36., -48., -60.] {
|
||||
let yy = y(db);
|
||||
p.line_segment(
|
||||
[Pos2::new(area.left(), yy), Pos2::new(area.right(), yy)],
|
||||
Stroke::new(1.0_f32, GRID),
|
||||
);
|
||||
p.text(
|
||||
Pos2::new(outer.left() + 6., yy),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
format!("{db:.0}"),
|
||||
FontId::proportional(10.),
|
||||
DIM,
|
||||
);
|
||||
}
|
||||
let col = area.width() / SHOWN as f32;
|
||||
for k in 0..SHOWN {
|
||||
let x0 = area.left() + col * k as f32;
|
||||
for (i, (db, color)) in [(frame.input[k], STEEL), (frame.output[k], ACCENT)]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
if db <= floor {
|
||||
continue;
|
||||
}
|
||||
let w = col * 0.32;
|
||||
let x = x0 + col * 0.16 + i as f32 * (w + col * 0.04);
|
||||
p.rect_filled(
|
||||
Rect::from_min_max(Pos2::new(x, y(db)), Pos2::new(x + w, area.bottom())),
|
||||
0.,
|
||||
color,
|
||||
);
|
||||
}
|
||||
let marked = (k + 1) as u32 == settings.push_harmonic && settings.push_gain != 0.;
|
||||
p.text(
|
||||
Pos2::new(x0 + col * 0.5, area.bottom() + 4.),
|
||||
egui::Align2::CENTER_TOP,
|
||||
format!("{}", k + 1),
|
||||
FontId::proportional(10.),
|
||||
if marked { ACCENT } else { MUTED },
|
||||
);
|
||||
}
|
||||
// Tracked filter positions, in harmonic numbers.
|
||||
let mark = |h: f32, label: &str| {
|
||||
if h > 0. && h <= SHOWN as f32 + 0.5 {
|
||||
let x = area.left() + col * (h - 0.5);
|
||||
p.line_segment(
|
||||
[Pos2::new(x, area.top()), Pos2::new(x, area.bottom())],
|
||||
Stroke::new(1.0_f32, FOCUS),
|
||||
);
|
||||
p.text(
|
||||
Pos2::new(x + 4., area.top()),
|
||||
egui::Align2::LEFT_TOP,
|
||||
label,
|
||||
FontId::proportional(10.),
|
||||
FOCUS,
|
||||
);
|
||||
}
|
||||
};
|
||||
mark(settings.floor, "FLOOR");
|
||||
mark(settings.bright, "BRIGHT");
|
||||
p.text(
|
||||
outer.left_top() + Vec2::new(34., 6.),
|
||||
egui::Align2::LEFT_TOP,
|
||||
"HARMONICS",
|
||||
FontId::proportional(11.),
|
||||
MUTED,
|
||||
);
|
||||
p.text(
|
||||
outer.right_top() + Vec2::new(-10., 6.),
|
||||
egui::Align2::RIGHT_TOP,
|
||||
"IN · OUT",
|
||||
FontId::proportional(11.),
|
||||
MUTED,
|
||||
);
|
||||
p.rect_stroke(
|
||||
outer,
|
||||
2.,
|
||||
Stroke::new(1.0_f32, EDGE),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
let _ = response;
|
||||
}
|
||||
|
||||
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, "TEMPER", "TRACKED DISTORTION", |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;
|
||||
}
|
||||
let r = ui
|
||||
.selectable_label(settings.auto_gain, RichText::new("AUTO GAIN").size(13.))
|
||||
.on_hover_text(
|
||||
"Match output loudness to the input, so Drive changes character, not level.",
|
||||
);
|
||||
if r.clicked() {
|
||||
settings.auto_gain = !settings.auto_gain;
|
||||
}
|
||||
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, &frame));
|
||||
});
|
||||
ui.add_space(4.);
|
||||
panel(ui, |ui| {
|
||||
ui.set_min_height(TOP);
|
||||
ui.vertical(|ui| {
|
||||
transfer(ui, settings, 236.);
|
||||
ui.add_space(4.);
|
||||
ui.horizontal(|ui| {
|
||||
for curve in Curve::ALL {
|
||||
let r = ui.selectable_label(
|
||||
settings.curve == curve,
|
||||
RichText::new(curve.name().to_uppercase()).size(12.),
|
||||
);
|
||||
if r.clicked() {
|
||||
settings.curve = curve;
|
||||
}
|
||||
hint(&r, state, match curve {
|
||||
Curve::Soft => "Soft: tanh. Smooth, odd harmonics, rounded top.",
|
||||
Curve::Hard => "Hard: clipping with a narrow knee. Dense, square-like.",
|
||||
Curve::Fold => "Fold: the wave folds back on itself. Drive moves the upper harmonics.",
|
||||
Curve::Tube => "Tube: the negative half clips earlier. Adds even harmonics.",
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
ui.add_space(4.);
|
||||
panel(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
spectrum(ui, &frame, settings, 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 = 290.;
|
||||
|
||||
fn note_panel(ui: &mut egui::Ui, settings: &Settings, 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, "INTO SHAPER");
|
||||
let (rect, _) = ui.allocate_exact_size(Vec2::new(180., 10.), Sense::hover());
|
||||
let p = ui.painter();
|
||||
p.rect_filled(rect, 1., SCREEN);
|
||||
// −24..+24 dB around the curve's knee at 0 dB.
|
||||
let t = ((frame.shaper_db + 24.) / 48.).clamp(0., 1.);
|
||||
let mut fill = rect;
|
||||
fill.set_width(rect.width() * t);
|
||||
p.rect_filled(fill, 1., ACCENT);
|
||||
let knee = rect.left() + rect.width() * 0.5;
|
||||
p.line_segment(
|
||||
[
|
||||
Pos2::new(knee, rect.top() - 2.),
|
||||
Pos2::new(knee, rect.bottom() + 2.),
|
||||
],
|
||||
Stroke::new(1.0_f32, TEXT),
|
||||
);
|
||||
p.rect_stroke(
|
||||
rect,
|
||||
1.,
|
||||
Stroke::new(1.0_f32, EDGE),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
ui.label(
|
||||
RichText::new(if frame.shaper_db < -60. {
|
||||
"—".to_string()
|
||||
} else {
|
||||
format!("{:+.1} dB over the knee", frame.shaper_db)
|
||||
})
|
||||
.monospace()
|
||||
.size(12.)
|
||||
.color(TEXT),
|
||||
);
|
||||
ui.add_space(8.);
|
||||
readout(
|
||||
ui,
|
||||
"NORMALIZE GAIN",
|
||||
format!("{:+.1} dB", frame.normalize_db),
|
||||
STEEL,
|
||||
);
|
||||
readout(
|
||||
ui,
|
||||
"AUTO GAIN",
|
||||
if settings.auto_gain {
|
||||
format!("{:+.1} dB", frame.auto_db)
|
||||
} else {
|
||||
"off".into()
|
||||
},
|
||||
STEEL,
|
||||
);
|
||||
}
|
||||
|
||||
fn controls(ui: &mut egui::Ui, settings: &mut Settings, state: &mut State) {
|
||||
let d = Settings::default();
|
||||
ui.columns(10, |c| {
|
||||
knob(&mut c[0], state, "Drive", &mut settings.drive, 0. ..=36., d.drive, " dB", 80.,
|
||||
"Gain into the curve. With Normalize at 100 % every note starts from the same level.");
|
||||
knob(&mut c[1], state, "Bias", &mut settings.bias, 0. ..=100., d.bias, " %", 80.,
|
||||
"Shift the curve's operating point: asymmetric clipping, even harmonics.");
|
||||
knob(&mut c[2], state, "Push", &mut settings.push_gain, -12. ..=12., d.push_gain, " dB", 80.,
|
||||
"Boost or cut one harmonic before the curve, so the distortion bites there on every note.");
|
||||
knob(&mut c[3], state, "Mix", &mut settings.mix, 0. ..=100., d.mix, " %", 80.,
|
||||
"Blend with the delayed dry signal.");
|
||||
let mut push = settings.push_harmonic as f32;
|
||||
knob(&mut c[4], state, "Push at", &mut push, 1. ..=16., d.push_harmonic as f32, "", 54.,
|
||||
"Harmonic number that Push boosts or cuts.");
|
||||
settings.push_harmonic = push.round().clamp(1., 16.) as u32;
|
||||
knob(&mut c[5], state, "Floor", &mut settings.floor, 0. ..=2., d.floor, " ×f0", 54.,
|
||||
"Highpass before the curve at this multiple of the note. 0 is off. Keeps sub mud out of the distortion.");
|
||||
if settings.floor < 0.25 {
|
||||
settings.floor = 0.;
|
||||
}
|
||||
knob(&mut c[6], state, "Bright", &mut settings.bright, 0. ..=64., d.bright, " ×f0", 54.,
|
||||
"Lowpass after the curve at this harmonic. 0 is off. The top end stops at the same harmonic on every note.");
|
||||
if settings.bright < 4. {
|
||||
settings.bright = 0.;
|
||||
}
|
||||
knob(&mut c[7], state, "Normalize", &mut settings.normalize, 0. ..=100., d.normalize, " %", 54.,
|
||||
"How far each note's level is evened out before Drive. 100 %: quiet and loud patches distort the same.");
|
||||
knob(&mut c[8], 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[9], state, "Output", &mut settings.output, -12. ..=12., d.output, " dB", 54.,
|
||||
"Output trim.");
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user