feat(ballast): add Ballast switch-up leveller

Ballast gives every part of a bassline one gain that brings it to the target
loudness, with no compression inside a part. Parts start at note starts,
detected from the audio or taken from MIDI, or on the host's beat grid, so a
patch change on the same note counts too.

- Loudness is K-weighted over each part's first 100 ms, in 10 ms blocks with
  a relative gate, and every part is weighted from rest so the last part does
  not ring into it.
- The audio path is delayed by the tracker's lookahead, the window and a
  5 ms glide, so each gain is in place on its part's first sample.
- Learn takes the next part's loudness as the target. Amount, Range, Measure
  from (leave the sub out), Gate, Output, Bypass.
- Editor shows the last 32 parts in and out, the target, and the spread of
  the last 16 parts.
- Registered in the catalog, workflows, editor-check, README, chain and
  development docs, and the website copy.
This commit is contained in:
nvrl committed 2026-11-06 16:05:19 +01:00
1 parent d77b88c7a9
commit d93dd942a8
28 files changed
+4716 -21

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
[package]
name = "ballast-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 }
+474
View File
@@ -0,0 +1,474 @@
//! Levels each part of a bassline, a note or a step of the beat grid, to one loudness with a
//! single gain per part. No compression: the gain does not move inside a part, so a patch
//! keeps its own envelope and punch.
//!
//! A part's loudness is the K-weighted (ITU-R BS.1770) mean square of its first 100 ms, or
//! of all of it when it is shorter, counted in 10 ms blocks; blocks 20 dB under the loudest
//! one are left out, so a gap at the start does not pull the reading down. Each part is
//! weighted from rest, as if it played alone. The audio path is delayed by the note tracker's lookahead
//! plus that window plus a 5 ms ramp, so every part's gain is known before its attack leaves
//! the plugin, and the ramp to it ends exactly on the attack.
mod settings;
use common_dsp::loudness::{lufs, KWeighting};
use common_dsp::svf::{Svf, SvfCoef};
use common_dsp::tracker::{NoteEvent, Tracker, TrackerConfig};
use common_dsp::{coefficient, db_to_gain, gain_to_db};
pub use settings::{
Grid, Segment, Settings, Source, FROM_MAX, FROM_MIN, RANGE_MAX, TARGET_MAX, TARGET_MIN,
};
/// Each part is measured over this much of its start.
pub const WINDOW_MS: f32 = 100.;
/// The gain glides to a new part's value over this long, ending on its first sample.
pub const RAMP_MS: f32 = 5.;
/// A boundary closer than this to the last one is ignored: the parts are merged.
const MIN_PART_MS: f32 = 10.;
/// The window is measured in blocks of this length.
const BLOCK_MS: f32 = 10.;
const BLOCKS: usize = (WINDOW_MS / BLOCK_MS) as usize;
/// Blocks this far under the part's loudest block do not count: a note start found by a
/// pitch change can come early, inside the gap before the note.
const RELATIVE_GATE_DB: f64 = 20.;
/// Parts shown in the editor.
pub const HISTORY: usize = 32;
/// Parts used for the spread readout.
const SPREAD: usize = 16;
const PENDING: usize = 32;
const Q: f32 = std::f32::consts::FRAC_1_SQRT_2;
/// Tempo the grid runs at before the host reports one.
const FALLBACK_BPM: f64 = 120.;
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Part {
/// Loudness of the part's measured start, in LUFS.
pub loudness: f32,
/// Gain given to the part, in dB.
pub gain: f32,
/// Under the gate: the part kept the previous gain.
pub gated: bool,
}
#[derive(Clone, Copy, Debug)]
pub struct AnalyzerFrame {
/// Latest parts, oldest first; the first `count` entries are valid.
pub history: [Part; HISTORY],
pub count: usize,
/// Gain applied at the output right now, in dB.
pub gain: f32,
/// Standard deviation of the loudness of the last 16 parts over the gate, before and after
/// Ballast. NaN with fewer than two.
pub spread_in: f32,
pub spread_out: f32,
/// Waiting for the next part to take as the target.
pub learning: bool,
/// The loudness last taken by Learn, and a number that changes each time one is taken.
pub learned: f32,
pub learn_id: u32,
pub tempo: f64,
pub synced: bool,
pub latency: u32,
pub sample_rate: f32,
}
impl Default for AnalyzerFrame {
fn default() -> Self {
Self {
history: [Part::default(); HISTORY],
count: 0,
gain: 0.,
spread_in: f32::NAN,
spread_out: f32::NAN,
learning: false,
learned: f32::NAN,
learn_id: 0,
tempo: FALLBACK_BPM,
synced: false,
latency: 0,
sample_rate: 48000.,
}
}
}
/// Gain in dB that brings `loudness` to the target, at `amount` (0–1), within ±`range`.
pub fn part_gain(loudness: f32, target: f32, amount: f32, range: f32) -> f32 {
((target - loudness) * amount).clamp(-range, range)
}
#[derive(Clone, Copy, Default)]
struct Pending {
start: u64,
gain: f32,
}
pub struct Engine {
rate: f32,
channels: usize,
settings: Settings,
tracker: Tracker,
lookahead: usize,
window: usize,
ramp: usize,
min_part: usize,
delay: Vec<[f32; 2]>,
delay_at: usize,
weighting: [KWeighting; 2],
from: [[Svf; 2]; 2],
from_coef: SvfCoef,
/// Samples of the aligned stream: the input delayed by the tracker's lookahead.
clock: u64,
open: bool,
part_start: u64,
block: usize,
blocks: [(f64, usize); BLOCKS],
measured: usize,
last_gain: f32,
queue: [Pending; PENDING],
queue_head: usize,
queue_len: usize,
gain: f32,
ramp_from: f32,
ramp_to: f32,
ramp_left: usize,
history: [Part; HISTORY],
history_at: usize,
history_len: usize,
learn: bool,
learned: f32,
learn_id: u32,
tempo: f64,
/// Beat position of the aligned stream.
beats: f64,
synced: bool,
cell: i64,
output: f32,
bypass: f32,
smooth: f32,
fresh: bool,
}
impl Engine {
pub fn new(rate: f32, channels: usize) -> Result<Self, &'static str> {
if !(8000.0..=384000.).contains(&rate) {
return Err("unsupported sample rate");
}
if !(1..=2).contains(&channels) {
return Err("unsupported channel count");
}
let tracker = Tracker::new(rate, TrackerConfig::BASS);
let lookahead = tracker.latency();
let samples = |ms: f32| ((rate * ms * 0.001).round() as usize).max(1);
let (window, ramp) = (samples(WINDOW_MS), samples(RAMP_MS));
let mut e = Self {
rate,
channels,
settings: Settings::default(),
tracker,
lookahead,
window,
ramp,
min_part: samples(MIN_PART_MS),
delay: vec![[0.; 2]; lookahead + window + ramp + 1],
delay_at: 0,
weighting: [KWeighting::new(rate); 2],
from: [[Svf::default(); 2]; 2],
from_coef: SvfCoef::IDENTITY,
clock: 0,
open: false,
part_start: 0,
block: samples(BLOCK_MS),
blocks: [(0., 0); BLOCKS],
measured: 0,
last_gain: 0.,
queue: [Pending::default(); PENDING],
queue_head: 0,
queue_len: 0,
gain: 1.,
ramp_from: 1.,
ramp_to: 1.,
ramp_left: 0,
history: [Part::default(); HISTORY],
history_at: 0,
history_len: 0,
learn: false,
learned: f32::NAN,
learn_id: 0,
tempo: FALLBACK_BPM,
beats: 0.,
synced: false,
cell: 0,
output: 1.,
bypass: 0.,
smooth: coefficient(rate, 10.),
fresh: true,
};
e.set_settings(Settings::default())?;
e.fresh = true;
Ok(e)
}
/// Lookahead of the tracker, the measuring window and the ramp.
pub fn latency_samples(&self) -> u32 {
(self.lookahead + self.window + self.ramp) 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, false);
if s.from != self.settings.from || self.fresh {
self.from_coef = if s.from > FROM_MIN {
SvfCoef::highpass(self.rate, s.from, Q)
} else {
SvfCoef::IDENTITY
};
}
self.settings = s;
if std::mem::take(&mut self.fresh) {
self.output = db_to_gain(s.output);
self.bypass = f32::from(s.bypass);
}
Ok(())
}
/// Host tempo in BPM and, while playing, the beat position at the block's first sample.
pub fn set_transport(&mut self, tempo: Option<f64>, position: Option<f64>) {
if let Some(t) = tempo.filter(|t| t.is_finite() && *t > 0.) {
self.tempo = t;
}
match position.filter(|p| p.is_finite()) {
Some(p) => {
// The parts are cut on the aligned stream, `lookahead` samples behind the input.
self.beats = p - self.lookahead as f64 / self.rate as f64 * self.tempo / 60.;
self.synced = true;
}
None => self.synced = false,
}
}
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);
}
/// Takes the loudness of the next part over the gate as the new target.
pub fn learn(&mut self) {
self.learn = true;
}
pub fn reset(&mut self) {
self.tracker.reset();
self.delay.fill([0.; 2]);
self.delay_at = 0;
for k in &mut self.weighting {
k.reset();
}
self.from = [[Svf::default(); 2]; 2];
self.clock = 0;
self.open = false;
self.blocks = [(0., 0); BLOCKS];
self.measured = 0;
self.last_gain = 0.;
self.queue_len = 0;
self.gain = 1.;
self.ramp_left = 0;
self.history_len = 0;
self.learn = false;
self.fresh = true;
let s = self.settings;
let _ = self.set_settings(s);
}
/// Mean square of the measured blocks, without those far under the loudest.
fn gated_mean(&self) -> f64 {
let used = self.measured.div_ceil(self.block).min(BLOCKS);
let blocks = &self.blocks[..used];
let loudest = blocks
.iter()
.map(|(s, n)| s / (*n).max(1) as f64)
.fold(0., f64::max);
let floor = loudest * 10f64.powf(-RELATIVE_GATE_DB / 10.);
let (sum, n) = blocks
.iter()
.filter(|(s, n)| s / (*n).max(1) as f64 >= floor)
.fold((0., 0), |(a, b), (s, n)| (a + s, b + n));
sum / n.max(1) as f64
}
fn close(&mut self) {
self.open = false;
let s = self.settings;
let loudness = lufs(self.gated_mean());
let gated = loudness < s.gate;
let gain = if gated {
self.last_gain
} else {
part_gain(loudness, s.target, s.amount * 0.01, s.range)
};
if !gated {
self.last_gain = gain;
if std::mem::take(&mut self.learn) {
self.learned = loudness;
self.learn_id = self.learn_id.wrapping_add(1);
}
}
if self.queue_len < PENDING {
let at = (self.queue_head + self.queue_len) % PENDING;
self.queue[at] = Pending {
start: self.part_start,
gain,
};
self.queue_len += 1;
}
self.history[self.history_at] = Part {
loudness,
gain,
gated,
};
self.history_at = (self.history_at + 1) % HISTORY;
self.history_len = (self.history_len + 1).min(HISTORY);
}
// Channels index the delayed frame, the filters and the output at once.
#[allow(clippy::needless_range_loop)]
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 mut started = false;
self.tracker.process(mono, |e| {
if matches!(e, NoteEvent::Start { .. }) {
started = true;
}
});
let len = self.delay.len();
self.delay[self.delay_at] = x;
let aligned = self.delay[(self.delay_at + len - self.lookahead) % len];
self.delay_at = (self.delay_at + 1) % len;
let delayed = self.delay[self.delay_at];
// Grid lines are counted on the aligned stream even in Notes mode, so switching modes
// does not cut a part.
let cell = (self.beats / self.settings.grid.quarters()).floor() as i64;
self.beats += self.tempo / 60. / self.rate as f64;
let crossed = cell != self.cell;
self.cell = cell;
let boundary = match self.settings.segment {
Segment::Notes => started,
Segment::Grid => crossed,
};
if boundary && !(self.open && self.measured < self.min_part) {
if self.open {
self.close();
}
self.open = true;
self.part_start = self.clock;
self.blocks = [(0., 0); BLOCKS];
self.measured = 0;
// Each part is weighted from rest, as if it played alone: the filters' memory of
// the last part would otherwise ring into this one.
for k in &mut self.weighting {
k.reset();
}
self.from = [[Svf::default(); 2]; 2];
}
let mut power = 0f64;
for c in 0..self.channels {
let f = &mut self.from[c];
let v = f[0].process(&self.from_coef, aligned[c]);
let v = f[1].process(&self.from_coef, v);
let w = self.weighting[c].process(v) as f64;
power += w * w;
}
if self.open {
let b = &mut self.blocks[(self.measured / self.block).min(BLOCKS - 1)];
b.0 += power;
b.1 += 1;
self.measured += 1;
if self.measured >= self.window {
self.close();
}
}
// A part's ramp starts `ramp` samples before its first sample reaches the output.
if self.queue_len > 0 {
let next = self.queue[self.queue_head];
if self.clock >= next.start + self.window as u64 {
self.queue_head = (self.queue_head + 1) % PENDING;
self.queue_len -= 1;
self.ramp_from = self.gain;
self.ramp_to = db_to_gain(next.gain);
self.ramp_left = self.ramp;
}
}
if self.ramp_left > 0 {
self.ramp_left -= 1;
let t = 1. - self.ramp_left as f32 / self.ramp as f32;
let t = t * t * (3. - 2. * t);
self.gain = self.ramp_from + (self.ramp_to - self.ramp_from) * t;
}
self.clock += 1;
let s = self.settings;
self.output += (db_to_gain(s.output) - self.output) * self.smooth;
self.bypass += (f32::from(s.bypass) - self.bypass) * self.smooth;
if (f32::from(s.bypass) - self.bypass).abs() < 1e-6 {
self.bypass = f32::from(s.bypass);
}
let mut out = [0.; 2];
for c in 0..self.channels {
let wet = delayed[c] * self.gain * self.output;
out[c] = if self.bypass >= 1. {
delayed[c]
} else {
wet + (delayed[c] - wet) * self.bypass
};
}
out
}
fn spread(&self, after: bool) -> f32 {
let (mut n, mut sum, mut sq) = (0usize, 0f64, 0f64);
for i in 0..self.history_len {
if n == SPREAD {
break;
}
let p = self.history[(self.history_at + HISTORY - 1 - i) % HISTORY];
if p.gated {
continue;
}
let v = (p.loudness + if after { p.gain } else { 0. }) as f64;
n += 1;
sum += v;
sq += v * v;
}
if n < 2 {
return f32::NAN;
}
let mean = sum / n as f64;
((sq / n as f64 - mean * mean).max(0.)).sqrt() as f32
}
/// Readings for the editor. Never allocates.
pub fn take_analyzer(&self) -> AnalyzerFrame {
let mut f = AnalyzerFrame {
count: self.history_len,
gain: gain_to_db(self.gain),
spread_in: self.spread(false),
spread_out: self.spread(true),
learning: self.learn,
learned: self.learned,
learn_id: self.learn_id,
tempo: self.tempo,
synced: self.synced,
latency: self.latency_samples(),
sample_rate: self.rate,
..AnalyzerFrame::default()
};
let first = (self.history_at + HISTORY - self.history_len) % HISTORY;
for i in 0..self.history_len {
f.history[i] = self.history[(first + i) % HISTORY];
}
f
}
}
+133
View File
@@ -0,0 +1,133 @@
//! Host-independent controls. Loudness in LUFS, gains in dB, amounts in percent.
use serde::{Deserialize, Serialize};
pub const TARGET_MIN: f32 = -40.;
pub const TARGET_MAX: f32 = 0.;
pub const RANGE_MAX: f32 = 24.;
/// Lowest frequency the measurement can start from. At or under this the measurement hears
/// the full band.
pub const FROM_MIN: f32 = 20.;
pub const FROM_MAX: f32 = 300.;
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
pub enum Source {
/// Note starts are detected from the incoming bass.
#[default]
Audio,
/// Note starts come from MIDI note input.
Midi,
}
/// Where one leveled part ends and the next begins.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
pub enum Segment {
/// Every note start.
#[default]
Notes,
/// Every line of the host's beat grid, so a patch change on the same note counts too.
Grid,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
pub enum Grid {
Bar,
Half,
#[default]
Quarter,
Eighth,
Sixteenth,
}
impl Grid {
pub const ALL: [Grid; 5] = [
Grid::Bar,
Grid::Half,
Grid::Quarter,
Grid::Eighth,
Grid::Sixteenth,
];
/// Length in quarter notes.
pub fn quarters(self) -> f64 {
match self {
Grid::Bar => 4.,
Grid::Half => 2.,
Grid::Quarter => 1.,
Grid::Eighth => 0.5,
Grid::Sixteenth => 0.25,
}
}
pub fn label(self) -> &'static str {
match self {
Grid::Bar => "1 BAR",
Grid::Half => "1/2",
Grid::Quarter => "1/4",
Grid::Eighth => "1/8",
Grid::Sixteenth => "1/16",
}
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Settings {
pub source: Source,
pub segment: Segment,
pub grid: Grid,
/// Loudness every part should land at, measured over its first 100 ms.
pub target: f32,
/// Share of the correction that is applied.
pub amount: f32,
/// Most boost or cut, in dB.
pub range: f32,
/// The measurement hears only what is above this frequency; the gain still applies to
/// the full band. Set it to Anvil's Split when Anvil makes the sub.
pub from: f32,
/// Note-start threshold (Audio source), and the loudness under which a part keeps the
/// last gain instead of being lifted.
pub gate: f32,
pub output: f32,
pub bypass: bool,
}
impl Default for Settings {
fn default() -> Self {
Self {
source: Source::Audio,
segment: Segment::Notes,
grid: Grid::Quarter,
target: -14.,
amount: 100.,
range: 12.,
from: FROM_MIN,
gate: -48.,
output: 0.,
bypass: false,
}
}
}
impl Settings {
pub fn validate(&self) -> Result<(), &'static str> {
let finite = [
self.target,
self.amount,
self.range,
self.from,
self.gate,
self.output,
]
.iter()
.all(|v| v.is_finite());
if !finite {
return Err("non-finite setting");
}
let ok = (TARGET_MIN..=TARGET_MAX).contains(&self.target)
&& (0.0..=100.).contains(&self.amount)
&& (0.0..=RANGE_MAX).contains(&self.range)
&& (FROM_MIN..=FROM_MAX).contains(&self.from)
&& (-60.0..=-20.).contains(&self.gate)
&& (-12.0..=12.).contains(&self.output);
if ok {
Ok(())
} else {
Err("setting out of range")
}
}
}
+332
View File
@@ -0,0 +1,332 @@
use ballast_core::{part_gain, Engine, Grid, Segment, Settings, Source, RAMP_MS, WINDOW_MS};
use common_dsp::loudness::{lufs, KWeighting};
use std::f64::consts::TAU;
const RATE: f32 = 48000.;
const BPM: f64 = 120.;
/// One quarter at 120 BPM.
const QUARTER: usize = 24000;
/// Two patches a switch-up might alternate: a loud saw and a quiet sine, an octave apart.
fn patch(i: usize, which: usize) -> f32 {
let t = i as f64 / RATE as f64;
if which.is_multiple_of(2) {
let phase = (55. * t).fract();
(0.5 * (2. * phase - 1.)) as f32
} else {
(0.1 * (TAU * 110. * t).sin()) as f32
}
}
fn grid_engine(s: Settings) -> Engine {
let mut e = Engine::new(RATE, 2).unwrap();
e.set_settings(Settings {
segment: Segment::Grid,
grid: Grid::Quarter,
..s
})
.unwrap();
e
}
/// Runs `input` through the engine in 512-sample blocks with the transport playing from 0.
fn run(e: &mut Engine, input: &[f32]) -> Vec<f32> {
let mut out = Vec::with_capacity(input.len());
for (i, &v) in input.iter().enumerate() {
if i % 512 == 0 {
e.set_transport(Some(BPM), Some(i as f64 / RATE as f64 * BPM / 60.));
}
out.push(e.process_sample([v, v])[0]);
}
out
}
/// K-weighted loudness of both channels (the same signal) over `window` samples from `start`.
fn loudness(x: &[f32], start: usize, window: usize) -> f32 {
let mut k = KWeighting::new(RATE);
// Settle the filter on what came before, as the engine's own measurement does.
for &v in &x[start.saturating_sub(4800)..start] {
k.process(v);
}
let sum: f64 = x[start..start + window]
.iter()
.map(|&v| (k.process(v) as f64).powi(2))
.sum();
lufs(2. * sum / window as f64)
}
fn window() -> usize {
(RATE * WINDOW_MS * 0.001) as usize
}
#[test]
fn every_part_lands_at_the_target() {
let target = -18.;
let mut e = grid_engine(Settings {
target,
..Settings::default()
});
let latency = e.latency_samples() as usize;
let parts = 10;
let input: Vec<f32> = (0..parts * QUARTER + latency)
.map(|i| patch(i, i / QUARTER))
.collect();
let out = run(&mut e, &input);
for p in 2..parts {
let start = p * QUARTER;
let before = loudness(&input, start, window());
let after = loudness(&out, start + latency, window());
assert!(
(after - target).abs() < 0.3,
"part {p}: {before:.1} → {after:.1}"
);
}
let f = e.take_analyzer();
assert!(f.spread_in > 5., "{}", f.spread_in);
assert!(f.spread_out < 0.1, "{}", f.spread_out);
}
#[test]
fn the_gain_holds_still_inside_a_part_and_is_in_place_on_its_attack() {
let mut e = grid_engine(Settings {
target: -18.,
..Settings::default()
});
let latency = e.latency_samples() as usize;
let ramp = (RATE * RAMP_MS * 0.001) as usize;
let input: Vec<f32> = (0..6 * QUARTER + latency)
.map(|i| patch(i, i / QUARTER) + 0.2)
.collect();
let out = run(&mut e, &input);
for p in 2..5 {
let start = p * QUARTER;
assert!(input[start].abs() > 0.05);
let gain = out[start + latency] / input[start];
for n in start..start + QUARTER - ramp {
if input[n].abs() < 0.05 {
continue;
}
let g = out[n + latency] / input[n];
assert!(
(g / gain - 1.).abs() < 1e-4,
"part {p}, sample {n}: {g} vs {gain}"
);
}
}
}
#[test]
fn note_starts_from_the_audio_cut_the_parts() {
let target = -18.;
let mut e = Engine::new(RATE, 2).unwrap();
e.set_settings(Settings {
target,
..Settings::default()
})
.unwrap();
let latency = e.latency_samples() as usize;
// 300 ms notes with 100 ms gaps, alternating the two patches.
let note = 19200;
let input: Vec<f32> = (0..8 * note + latency)
.map(|i| {
if i % note < 14400 && i < 8 * note {
patch(i, i / note)
} else {
0.
}
})
.collect();
let out = run(&mut e, &input);
let f = e.take_analyzer();
let parts = f.history[..f.count].iter().filter(|p| !p.gated).count();
assert_eq!(parts, 8, "{:?}", &f.history[..f.count]);
for n in 2..8 {
// The tracker finds the start a few milliseconds in; measure past that.
let start = n * note + 960;
let after = loudness(&out, start + latency, window());
assert!((after - target).abs() < 0.5, "note {n}: {after:.1}");
}
}
#[test]
fn midi_note_starts_cut_legato_parts() {
let target = -18.;
let mut e = Engine::new(RATE, 2).unwrap();
e.set_settings(Settings {
target,
source: Source::Midi,
..Settings::default()
})
.unwrap();
let latency = e.latency_samples() as usize;
let note = QUARTER;
let mut out = Vec::new();
let input: Vec<f32> = (0..6 * note + latency)
.map(|i| patch(i, i / note))
.collect();
for (i, &v) in input.iter().enumerate() {
if i % note == 0 {
// Legato: the new note starts before the old one ends, on the same pitch.
e.note_on(33);
if i > 0 {
e.note_off(33);
e.note_on(33);
}
}
out.push(e.process_sample([v, v])[0]);
}
for n in 2..6 {
let after = loudness(&out, n * note + latency, window());
assert!((after - target).abs() < 0.3, "note {n}: {after:.1}");
}
}
#[test]
fn quiet_parts_keep_the_last_gain() {
let mut e = grid_engine(Settings {
target: -18.,
gate: -40.,
..Settings::default()
});
// A loud part, then a part far under the gate, then the loud patch again. The parts change
// on zero crossings of a 110 Hz sine, so no step rings into the quiet part.
let input: Vec<f32> = (0..4 * QUARTER)
.map(|i| {
let v = 0.5 * (TAU * 110. * i as f64 / RATE as f64).sin() as f32;
if i / QUARTER == 2 {
v * 0.001
} else {
v
}
})
.collect();
run(&mut e, &input);
let f = e.take_analyzer();
let parts = &f.history[..f.count];
// The first part is the silence before the input reaches the measurement.
let quiet = 1 + parts[1..]
.iter()
.position(|p| p.gated)
.expect("a gated part");
assert_eq!(parts[quiet].gain, parts[quiet - 1].gain);
}
#[test]
fn amount_and_range_scale_the_correction() {
assert_eq!(part_gain(-10., -14., 1., 12.), -4.);
assert_eq!(part_gain(-10., -14., 0.5, 12.), -2.);
assert_eq!(part_gain(-40., -14., 1., 12.), 12.);
assert_eq!(part_gain(0., -14., 1., 6.), -6.);
let mut e = grid_engine(Settings {
target: -18.,
amount: 50.,
..Settings::default()
});
let input: Vec<f32> = (0..4 * QUARTER).map(|i| patch(i, i / QUARTER)).collect();
run(&mut e, &input);
let f = e.take_analyzer();
for p in &f.history[1..f.count] {
let full = -18. - p.loudness;
assert!((p.gain - 0.5 * full).abs() < 1e-3, "{p:?}");
}
}
#[test]
fn learn_takes_the_next_part_as_the_target() {
let mut e = grid_engine(Settings::default());
let input: Vec<f32> = (0..3 * QUARTER).map(|i| patch(i, i / QUARTER)).collect();
run(&mut e, &input[..QUARTER + 100]);
e.learn();
assert!(e.take_analyzer().learning);
let before = e.take_analyzer().learn_id;
run(&mut e, &input[QUARTER + 100..]);
let f = e.take_analyzer();
assert!(!f.learning);
assert_ne!(f.learn_id, before);
let taken = f.history[..f.count]
.iter()
.find(|p| p.loudness == f.learned)
.expect("learned a part's loudness");
assert!(!taken.gated);
}
#[test]
fn the_measurement_can_leave_out_the_sub() {
// The same top, once with a loud sub under it.
let top = |i: usize| (0.05 * (TAU * 1000. * i as f64 / RATE as f64).sin()) as f32;
let sub = |i: usize| (0.5 * (TAU * 50. * i as f64 / RATE as f64).sin()) as f32;
let gains = |from: f32| {
let mut e = grid_engine(Settings {
target: -24.,
range: 24.,
from,
..Settings::default()
});
let input: Vec<f32> = (0..4 * QUARTER)
.map(|i| {
top(i)
+ if (i / QUARTER).is_multiple_of(2) {
sub(i)
} else {
0.
}
})
.collect();
run(&mut e, &input);
let f = e.take_analyzer();
let p = &f.history[..f.count];
(p[p.len() - 2].gain - p[p.len() - 1].gain).abs()
};
assert!(gains(20.) > 10.);
assert!(gains(200.) < 1., "{}", gains(200.));
}
#[test]
fn bypass_is_the_input_delayed_by_the_latency() {
let mut e = grid_engine(Settings {
bypass: true,
target: -30.,
..Settings::default()
});
let latency = e.latency_samples() as usize;
let lookahead = latency - window() - (RATE * RAMP_MS * 0.001) as usize;
// The tracker's lookahead: two periods of 30 Hz and a margin, about 67 ms.
assert!((lookahead as f32 / RATE - 0.067).abs() < 0.005);
let input: Vec<f32> = (0..2 * QUARTER).map(|i| patch(i, i / QUARTER)).collect();
let out = run(&mut e, &input);
for i in latency..input.len() {
assert_eq!(out[i], input[i - latency]);
}
}
#[test]
fn settings_are_validated_and_serialise() {
assert!(Settings::default().validate().is_ok());
for bad in [
Settings {
target: 3.,
..Settings::default()
},
Settings {
range: 30.,
..Settings::default()
},
Settings {
from: 10.,
..Settings::default()
},
Settings {
amount: f32::NAN,
..Settings::default()
},
] {
assert!(bad.validate().is_err());
assert!(Engine::new(RATE, 2).unwrap().set_settings(bad).is_err());
}
let s = Settings {
segment: Segment::Grid,
grid: Grid::Eighth,
source: Source::Midi,
target: -9.,
..Settings::default()
};
let json = serde_json::to_string(&s).unwrap();
assert_eq!(serde_json::from_str::<Settings>(&json).unwrap(), s);
assert!(serde_json::from_str::<Settings>(r#"{"target":0,"oops":1}"#).is_err());
}
+86
View File
@@ -0,0 +1,86 @@
use ballast_core::{Engine, Grid, Segment, 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_transport_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 % 512 == 0 {
let playing = (i / 24000) % 2 == 0;
engine.set_transport(
Some(140.),
playing.then_some(i as f64 / 48000. * 140. / 60.),
);
}
if i % 4800 == 0 {
let step = i / 4800;
settings.segment = if step % 2 == 0 {
Segment::Grid
} else {
Segment::Notes
};
settings.grid = Grid::ALL[step % Grid::ALL.len()];
settings.source = if step % 4 < 2 {
Source::Audio
} else {
Source::Midi
};
settings.from = 20. + 30. * (step % 5) as f32;
settings.bypass = step % 7 == 6;
engine.set_settings(settings).unwrap();
engine.note_on(33 + (step % 12) as u8);
if step % 3 == 0 {
engine.learn();
}
}
if i % 4800 == 2400 {
engine.note_off(33 + (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);
}
+2381
View File
File diff suppressed because it is too large. Load diff
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "ballast"
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" }
ballast-core = { path = "../core" }
ballast-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"
+210
View File
@@ -0,0 +1,210 @@
//! CLAP audio effect. All DSP state is owned by the processing thread.
mod params;
use ballast_core::{AnalyzerFrame, Engine};
use crossbeam_queue::ArrayQueue;
use nih_plug::prelude::*;
use nih_plug_egui::{create_egui_editor, egui};
use params::{BallastParams, FLOATS};
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
struct Shared {
analyzer: ArrayQueue<AnalyzerFrame>,
/// Set by the editor's Learn button, taken by the audio thread.
learn: AtomicBool,
}
struct EditorData {
ui: ballast_ui::State,
gestures: [bool; FLOATS],
}
pub struct Ballast {
params: Arc<BallastParams>,
shared: Arc<Shared>,
engine: Option<Engine>,
publish_count: usize,
publish_interval: usize,
}
impl Default for Ballast {
fn default() -> Self {
Self {
params: Arc::new(BallastParams::default()),
shared: Arc::new(Shared {
analyzer: ArrayQueue::new(2),
learn: AtomicBool::new(false),
}),
engine: None,
publish_count: 0,
publish_interval: 1600,
}
}
}
impl Plugin for Ballast {
const NAME: &'static str = "Ballast";
const VENDOR: &'static str = "Bass Foundry";
const URL: &'static str = "";
const EMAIL: &'static str = "";
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
const AUDIO_IO_LAYOUTS: &'static [AudioIOLayout] = &[
AudioIOLayout {
main_input_channels: NonZeroU32::new(2),
main_output_channels: NonZeroU32::new(2),
..AudioIOLayout::const_default()
},
AudioIOLayout {
main_input_channels: NonZeroU32::new(1),
main_output_channels: NonZeroU32::new(1),
..AudioIOLayout::const_default()
},
];
const 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 shared = self.shared.clone();
create_egui_editor(
params.editor.clone(),
EditorData {
ui: ballast_ui::State::default(),
gestures: [false; FLOATS],
},
|ctx, _| ballast_ui::style(ctx),
move |ctx, setter, data| {
while let Some(frame) = shared.analyzer.pop() {
data.ui.accept_frame(frame);
}
let before = params.settings();
let mut edited = before;
nih_plug_egui::resizable_window::ResizableWindow::new("ballast-editor")
.min_size(egui::vec2(
ballast_ui::WIDTH as f32 - 80.,
ballast_ui::HEIGHT as f32 - 40.,
))
.show(ctx, &params.editor, |ui| {
ballast_ui::show(ui, &mut edited, &mut data.ui)
});
params.apply(
setter,
&before,
&edited,
data.ui.gesture_active,
&mut data.gestures,
);
if std::mem::take(&mut data.ui.learn_request) {
shared.learn.store(true, Ordering::Release);
}
ctx.request_repaint_after(std::time::Duration::from_millis(40));
},
)
}
fn initialize(
&mut self,
layout: &AudioIOLayout,
config: &BufferConfig,
context: &mut impl InitContext<Self>,
) -> bool {
let Ok(mut engine) = Engine::new(
config.sample_rate,
layout.main_input_channels.map_or(0, |v| v.get() as usize),
) else {
return false;
};
let settings = self.params.settings();
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();
let _ = engine.set_settings(settings);
if self.shared.learn.swap(false, Ordering::AcqRel) {
engine.learn();
}
let transport = context.transport();
engine.set_transport(
transport.tempo,
if transport.playing {
transport.pos_beats()
} else {
None
},
);
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 {
let _ = self.shared.analyzer.force_push(engine.take_analyzer());
self.publish_count = 0;
}
}
// The lookahead delay must drain after input stops.
ProcessStatus::KeepAlive
}
}
impl ClapPlugin for Ballast {
const CLAP_ID: &'static str = "io.narl.bass-foundry.ballast";
const CLAP_DESCRIPTION: Option<&'static str> =
Some("Levels every note or switch-up to one loudness with a single gain each");
const CLAP_MANUAL_URL: Option<&'static str> = None;
const CLAP_SUPPORT_URL: Option<&'static str> = None;
const CLAP_FEATURES: &'static [ClapFeature] = &[
ClapFeature::AudioEffect,
ClapFeature::Utility,
ClapFeature::Stereo,
ClapFeature::Mono,
];
}
nih_export_clap!(Ballast);
+203
View File
@@ -0,0 +1,203 @@
use ballast_core::{
Grid, Segment, Settings, Source, FROM_MAX, FROM_MIN, RANGE_MAX, TARGET_MAX, TARGET_MIN,
};
use nih_plug::prelude::*;
use nih_plug_egui::EguiState;
use std::sync::Arc;
#[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 SegmentParam {
#[id = "notes"]
Notes,
#[id = "grid"]
Grid,
}
#[derive(Enum, Debug, PartialEq, Eq, Clone, Copy)]
pub enum GridParam {
#[id = "bar"]
#[name = "1 bar"]
Bar,
#[id = "1-2"]
#[name = "1/2"]
Half,
#[id = "1-4"]
#[name = "1/4"]
Quarter,
#[id = "1-8"]
#[name = "1/8"]
Eighth,
#[id = "1-16"]
#[name = "1/16"]
Sixteenth,
}
const GRIDS: [(GridParam, Grid); 5] = [
(GridParam::Bar, Grid::Bar),
(GridParam::Half, Grid::Half),
(GridParam::Quarter, Grid::Quarter),
(GridParam::Eighth, Grid::Eighth),
(GridParam::Sixteenth, Grid::Sixteenth),
];
fn grid_param(g: Grid) -> GridParam {
GRIDS
.iter()
.find(|(_, v)| *v == g)
.map_or(GridParam::Quarter, |(p, _)| *p)
}
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.
pub const FLOATS: usize = 6;
#[derive(Params)]
pub struct BallastParams {
#[persist = "editor"]
pub editor: Arc<EguiState>,
#[id = "source"]
pub source: EnumParam<SourceParam>,
#[id = "segment"]
pub segment: EnumParam<SegmentParam>,
#[id = "grid"]
pub grid: EnumParam<GridParam>,
#[id = "target"]
pub target: FloatParam,
#[id = "amount"]
pub amount: FloatParam,
#[id = "range"]
pub range: FloatParam,
#[id = "from"]
pub from: FloatParam,
#[id = "gate"]
pub gate: FloatParam,
#[id = "output"]
pub output: FloatParam,
#[id = "bypass"]
pub bypass: BoolParam,
}
impl Default for BallastParams {
fn default() -> Self {
let d = Settings::default();
Self {
editor: EguiState::from_size(ballast_ui::WIDTH, ballast_ui::HEIGHT),
source: EnumParam::new("Note source", SourceParam::Audio),
segment: EnumParam::new("Parts from", SegmentParam::Notes),
grid: EnumParam::new("Grid", grid_param(d.grid)),
target: linear("Target", d.target, TARGET_MIN, TARGET_MAX, " LUFS"),
amount: linear("Amount", d.amount, 0., 100., " %"),
range: linear("Range", d.range, 0., RANGE_MAX, " dB"),
from: FloatParam::new(
"Measure from",
d.from,
FloatRange::Skewed {
min: FROM_MIN,
max: FROM_MAX,
factor: FloatRange::skew_factor(-1.),
},
)
.with_unit(" Hz"),
gate: linear("Gate", d.gate, -60., -20., " dB"),
output: linear("Output", d.output, -12., 12., " dB"),
bypass: BoolParam::new("Bypass", false).make_bypass(),
}
}
}
impl BallastParams {
pub fn settings(&self) -> Settings {
let grid = self.grid.value();
Settings {
source: match self.source.value() {
SourceParam::Audio => Source::Audio,
SourceParam::Midi => Source::Midi,
},
segment: match self.segment.value() {
SegmentParam::Notes => Segment::Notes,
SegmentParam::Grid => Segment::Grid,
},
grid: GRIDS
.iter()
.find(|(p, _)| *p == grid)
.map_or(Grid::Quarter, |(_, g)| *g),
target: self.target.value(),
amount: self.amount.value(),
range: self.range.value(),
from: self.from.value(),
gate: self.gate.value(),
output: self.output.value(),
bypass: self.bypass.value(),
}
}
fn floats(&self) -> [&FloatParam; FLOATS] {
[
&self.target,
&self.amount,
&self.range,
&self.from,
&self.gate,
&self.output,
]
}
fn values(s: &Settings) -> [f32; FLOATS] {
[s.target, s.amount, s.range, s.from, s.gate, s.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 pairs = Self::values(old).into_iter().zip(Self::values(new));
for (i, (p, (a, b))) in self.floats().into_iter().zip(pairs).enumerate() {
if a != b {
if !open[i] {
open[i] = true;
setter.begin_set_parameter(p);
}
setter.set_parameter(p, b);
}
if !dragging && open[i] {
setter.end_set_parameter(p);
open[i] = false;
}
}
if new.bypass != old.bypass {
setter.begin_set_parameter(&self.bypass);
setter.set_parameter(&self.bypass, new.bypass);
setter.end_set_parameter(&self.bypass);
}
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);
}
if new.segment != old.segment {
let v = match new.segment {
Segment::Notes => SegmentParam::Notes,
Segment::Grid => SegmentParam::Grid,
};
setter.begin_set_parameter(&self.segment);
setter.set_parameter(&self.segment, v);
setter.end_set_parameter(&self.segment);
}
if new.grid != old.grid {
setter.begin_set_parameter(&self.grid);
setter.set_parameter(&self.grid, grid_param(new.grid));
setter.end_set_parameter(&self.grid);
}
}
}
+216
View File
@@ -0,0 +1,216 @@
//! 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 = &ballast::clap_entry;
assert!(entry.init.unwrap()(c"ballast.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"Ballast");
assert_eq!(
CStr::from_ptr((*descriptor).id),
c"io.narl.bass-foundry.ballast"
);
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;
// Amount 0 passes the input through the lookahead delay unchanged.
envelope.params.insert("amount".into(), ParamValue::F32(0.));
envelope
.params
.insert("target".into(), ParamValue::F32(-20.));
envelope.params.insert("from".into(), ParamValue::F32(100.));
envelope
.params
.insert("segment".into(), ParamValue::String("grid".into()));
envelope
.params
.insert("grid".into(), ParamValue::String("1-8".into()));
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()
);
for rate in [44100., 48000., 96000.] {
assert!(p.activate.unwrap()(plugin, rate, 1, 512));
let delay = (*latency).get.unwrap()(plugin) as usize;
// The tracker's 67 ms, the 100 ms measuring window and the 5 ms ramp.
assert!((delay as f64 / rate - 0.172).abs() < 0.005, "{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 at amount 0.
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()();
}
}
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "ballast-ui"
version = "0.1.0"
edition.workspace = true
license.workspace = true
[dependencies]
egui = "0.31.1"
ballast-core = { path = "../core" }
common-ui = { path = "../../common/ui" }
common-dsp = { path = "../../common/dsp" }
+376
View File
@@ -0,0 +1,376 @@
//! Ballast editor, shared by the CLAP wrapper and the headless renderer.
use ballast_core::{
AnalyzerFrame, Grid, Segment, Settings, Source, FROM_MAX, FROM_MIN, HISTORY, RANGE_MAX,
TARGET_MAX, TARGET_MIN,
};
use common_ui::*;
use egui::{self, Color32, FontId, Pos2, Rect, RichText, Sense, Stroke, Vec2};
pub use common_ui::style;
pub const WIDTH: u32 = 980;
pub const HEIGHT: u32 = 660;
pub struct State {
pub analyzer: AnalyzerFrame,
/// Set by the Learn button; the wrapper passes it to the engine and clears it.
pub learn_request: bool,
/// The last Learn result already applied. None until the first frame arrives, so an old
/// result is not applied again when the editor opens.
learn_seen: Option<u32>,
learned: Option<f32>,
/// 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(),
learn_request: false,
learn_seen: None,
learned: None,
gesture_active: false,
help: DEFAULT_HELP.into(),
}
}
}
const DEFAULT_HELP: &str = "Put Ballast on the bass after its sound design. Press LEARN on the \
switch-up that sits right, or set Target.";
impl State {
pub fn accept_frame(&mut self, frame: AnalyzerFrame) {
match self.learn_seen {
Some(id) if id != frame.learn_id && frame.learned.is_finite() => {
self.learned = Some(frame.learned);
}
_ => {}
}
self.learn_seen = Some(frame.learn_id);
self.analyzer = frame;
}
}
fn hint(r: &egui::Response, state: &mut State, text: &str) {
if r.hovered() || r.has_focus() {
state.help = text.into();
}
}
#[allow(clippy::too_many_arguments)]
fn knob(
ui: &mut egui::Ui,
state: &mut State,
name: &str,
value: &mut f32,
range: std::ops::RangeInclusive<f32>,
default: f32,
unit: &str,
help: &str,
) {
ui.vertical_centered(|ui| {
let r = rotary(ui, name, value, range, default, unit, 72., ACCENT);
hint(&r, state, help);
});
}
const LOW: f32 = -42.;
const HIGH: f32 = 0.;
/// The last parts: their loudness in (bars), after Ballast (marks) and the target.
fn parts(ui: &mut egui::Ui, settings: &Settings, frame: &AnalyzerFrame, height: f32) {
let (rect, _) = ui.allocate_exact_size(Vec2::new(ui.available_width(), height), Sense::hover());
let p = ui.painter_at(rect);
p.rect_filled(rect, 2., SCREEN);
p.text(
rect.left_top() + Vec2::new(10., 8.),
egui::Align2::LEFT_TOP,
format!("LAST {HISTORY} PARTS · LOUDNESS OF THE FIRST 100 MS"),
FontId::proportional(11.),
MUTED,
);
p.text(
rect.right_top() + Vec2::new(-12., 8.),
egui::Align2::RIGHT_TOP,
"bar: in · mark: out",
FontId::proportional(11.),
MUTED,
);
let area = Rect::from_min_max(
rect.left_top() + Vec2::new(44., 30.),
rect.right_bottom() - Vec2::new(12., 12.),
);
let y = |lufs: f32| {
let t = ((lufs - LOW) / (HIGH - LOW)).clamp(0., 1.);
area.bottom() - t * area.height()
};
for db in [-36., -24., -12., 0.] {
p.line_segment(
[
Pos2::new(area.left(), y(db)),
Pos2::new(area.right(), y(db)),
],
Stroke::new(1.0_f32, Color32::from_rgb(32, 35, 40)),
);
p.text(
Pos2::new(area.left() - 6., y(db)),
egui::Align2::RIGHT_CENTER,
format!("{db:.0}"),
FontId::monospace(10.),
DIM,
);
}
let column = area.width() / HISTORY as f32;
// Newest part on the right.
let offset = HISTORY - frame.count;
for i in 0..frame.count {
let part = frame.history[i];
let x = area.left() + column * (offset + i) as f32;
let bar = Rect::from_min_max(
Pos2::new(x + column * 0.2, y(part.loudness)),
Pos2::new(x + column * 0.8, area.bottom()),
);
let color = if part.gated {
DIM.gamma_multiply(0.6)
} else {
STEEL.gamma_multiply(0.45)
};
p.rect_filled(bar, 1., color);
if !part.gated {
let out = y(part.loudness + part.gain);
p.line_segment(
[
Pos2::new(x + column * 0.1, out),
Pos2::new(x + column * 0.9, out),
],
Stroke::new(3.0_f32, ACCENT),
);
}
}
let t = y(settings.target);
p.line_segment(
[Pos2::new(area.left(), t), Pos2::new(area.right(), t)],
Stroke::new(1.0_f32, ACCENT.gamma_multiply(0.5)),
);
p.text(
Pos2::new(area.left() + 4., t - 3.),
egui::Align2::LEFT_BOTTOM,
format!("TARGET {:.1} LUFS", settings.target),
FontId::proportional(10.),
ACCENT,
);
p.rect_stroke(
rect,
2.,
Stroke::new(1.0_f32, EDGE),
egui::StrokeKind::Inside,
);
}
pub fn show(ui: &mut egui::Ui, settings: &mut Settings, state: &mut State) {
backdrop(ui);
state.help = DEFAULT_HELP.into();
state.gesture_active = ui.input(|i| i.pointer.any_down());
if let Some(l) = state.learned.take() {
settings.target = l.clamp(TARGET_MIN, TARGET_MAX);
}
ui.add_space(2.);
header(ui, "BALLAST", "SWITCH-UP LEVELLER", |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();
if settings.segment == Segment::Notes {
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, "NOTES FROM");
ui.separator();
}
for (segment, label) in [(Segment::Grid, "GRID"), (Segment::Notes, "NOTES")] {
let r =
ui.selectable_label(settings.segment == segment, RichText::new(label).size(13.));
if r.clicked() {
settings.segment = segment;
}
}
caption(ui, "PARTS FROM");
});
ui.add_space(6.);
let frame = state.analyzer;
ui.horizontal_top(|ui| {
panel(ui, |ui| {
ui.set_width(250.);
ui.set_min_height(TOP);
ui.vertical(|ui| readings(ui, settings, state, &frame));
});
ui.add_space(4.);
panel(ui, |ui| {
ui.set_width(ui.available_width());
parts(ui, settings, &frame, TOP);
});
});
ui.add_space(6.);
panel(ui, |ui| {
ui.set_width(ui.available_width());
ui.vertical(|ui| controls(ui, settings, state));
});
ui.separator();
ui.label(RichText::new(&state.help).color(MUTED));
}
const TOP: f32 = 300.;
fn readings(ui: &mut egui::Ui, settings: &Settings, state: &mut State, frame: &AnalyzerFrame) {
caption(ui, "SPREAD OF THE LAST PARTS");
let known = frame.spread_in.is_finite();
ui.label(
RichText::new(if known {
format!("{:.1} · {:.1} dB", frame.spread_in, frame.spread_out)
} else {
"—".into()
})
.font(FontId::new(34., egui::FontFamily::Name("medium".into())))
.color(if known { TEXT } else { DIM }),
);
ui.label(
RichText::new("in · out, standard deviation")
.size(12.)
.color(MUTED),
);
ui.add_space(12.);
readout(ui, "GAIN NOW", format!("{:+.1} dB", frame.gain), ACCENT);
readout(ui, "TARGET", format!("{:.1} LUFS", settings.target), TEXT);
let label = if frame.learning || state.learn_request {
"LISTENING"
} else {
"LEARN"
};
let r = ui.selectable_label(
frame.learning || state.learn_request,
RichText::new(label).size(13.),
);
if r.clicked() {
state.learn_request = true;
}
hint(
&r,
state,
"Takes the loudness of the next part over the gate as the target. Press it just \
before the switch-up that sits right in the mix.",
);
ui.add_space(10.);
ui.label(
RichText::new(format!(
"{:.0} ms lookahead · {}",
frame.latency as f32 / frame.sample_rate.max(1.) * 1000.,
match settings.segment {
Segment::Notes => match settings.source {
Source::Audio => "parts at detected notes".to_string(),
Source::Midi => "parts at MIDI notes".to_string(),
},
Segment::Grid => format!(
"grid at {:.1} BPM, {}",
frame.tempo,
if frame.synced {
"host transport"
} else {
"free running"
}
),
}
))
.size(12.)
.color(MUTED),
);
}
fn controls(ui: &mut egui::Ui, settings: &mut Settings, state: &mut State) {
let d = Settings::default();
if settings.segment == Segment::Grid {
ui.horizontal(|ui| {
caption(ui, "ONE PART EVERY");
ui.add_space(6.);
for grid in Grid::ALL {
let r = ui
.selectable_label(settings.grid == grid, RichText::new(grid.label()).size(13.));
if r.clicked() {
settings.grid = grid;
}
hint(
&r,
state,
"A new part starts on every line of this grid, also when the note does not \
change.",
);
}
});
ui.add_space(8.);
ui.separator();
}
ui.columns(6, |c| {
knob(
&mut c[0],
state,
"Target",
&mut settings.target,
TARGET_MIN..=TARGET_MAX,
d.target,
" LUFS",
"Loudness every part lands at, over its first 100 ms.",
);
knob(
&mut c[1],
state,
"Amount",
&mut settings.amount,
0. ..=100.,
d.amount,
" %",
"Share of the correction. 50 % halves the differences between parts.",
);
knob(
&mut c[2],
state,
"Range",
&mut settings.range,
0. ..=RANGE_MAX,
d.range,
" dB",
"Most boost or cut a part gets.",
);
knob(
&mut c[3],
state,
"Measure from",
&mut settings.from,
FROM_MIN..=FROM_MAX,
d.from,
" Hz",
"The measurement hears only what is above this. Set it to Anvil's Split when \
Anvil makes the sub; the gain still applies to the whole signal.",
);
knob(
&mut c[4],
state,
"Gate",
&mut settings.gate,
-60. ..=-20.,
d.gate,
" dB",
"Note-start threshold, and the loudness under which a part keeps the last gain.",
);
knob(
&mut c[5],
state,
"Output",
&mut settings.output,
-12. ..=12.,
d.output,
" dB",
"Output trim.",
);
});
}
+17
View File
@@ -182,5 +182,22 @@
"quench-core",
"quench-ui"
]
},
"ballast": {
"name": "Ballast",
"description": "Levels every note or switch-up to one loudness with a single gain each",
"manifest": "plugins/ballast/plugin/Cargo.toml",
"library": "ballast",
"documentation": "docs/ballast",
"clap_id": "io.narl.bass-foundry.ballast",
"licenses": {
"plugins/common/ui/assets/OFL.txt": "licenses/Roboto-OFL.txt"
},
"packages": [
"common-ui",
"common-dsp",
"ballast-core",
"ballast-ui"
]
}
}