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

+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);
}
}
}