π π A Python library for audio.
C audioaudio-processingaudio-productionaudio-researchaudio-unitaugmentationjucemachine-learningpybind11pythonvst3vst3-host
feat: add BrickwallLimiter plugin β sample-peak skeleton
Christopher Jacoby65729bfc2a78
diff --git a/pedalboard/plugins/BrickwallLimiter.h b/pedalboard/plugins/BrickwallLimiter.hnew file mode 100644index 0000000..f461326--- /dev/null+++ b/pedalboard/plugins/BrickwallLimiter.h@@ -0,0 +1,168 @@+/*+ * Copyright 2021-2024 Spotify AB+ *+ * Licensed under the GNU Public License, Version 3.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.gnu.org/licenses/gpl-3.0.html+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#pragma once++#include "../JuceHeader.h"+#include "../Plugin.h"++#include <cmath>++namespace Pedalboard {++/**+ * A lookahead brick-wall limiter with configurable ceiling.+ *+ * Unlike the built-in Limiter (which wraps JUCE's dsp::Limiter and applies+ * makeup gain), this plugin:+ * - Has a configurable output ceiling (not fixed at 0 dBFS)+ * - Does NOT apply makeup gain+ * - Uses a smoothed gain envelope (instant attack, exponential release)+ *+ * Design: setters store REQUESTED parameter values. prepare() copies them+ * to ACTIVE state. process() reads only ACTIVE state.+ * Coefficients are snapshotted at block boundaries for thread safety.+ */+template <typename SampleType> class BrickwallLimiter : public Plugin {+public:+ // ββ Parameter getters/setters ββ+ // Setters store requested values. Derived coefficients are snapshotted+ // in process() at block boundaries for thread safety with AudioStream.++ float getCeilingDb() const noexcept { return ceilingDb_; }+ void setCeilingDb(float value) {+ if (std::isnan(value) || std::isinf(value))+ throw std::range_error("ceiling_db must be a finite number");+ ceilingDb_ = value;+ }++ float getReleaseMs() const noexcept { return releaseMs_; }+ void setReleaseMs(float value) {+ if (value <= 0.0f || std::isnan(value) || std::isinf(value))+ throw std::range_error("release_ms must be > 0");+ releaseMs_ = value;+ }++ // ββ Plugin interface ββ++ virtual void prepare(const juce::dsp::ProcessSpec &spec) override {+ // Match upstream JucePlugin.h pattern: re-prepare only when sampleRate+ // changes, maximumBlockSize GROWS, or numChannels changes.+ if (spec.sampleRate == preparedSpec_.sampleRate &&+ spec.maximumBlockSize <= preparedSpec_.maximumBlockSize &&+ spec.numChannels == preparedSpec_.numChannels) {+ return; // preserve state for reset=False streaming+ }++ preparedSpec_ = spec;+ reset();+ }++ virtual int process(+ const juce::dsp::ProcessContextReplacing<SampleType> &context) override {+ auto ioBlock = context.getOutputBlock();+ int numSamples = (int)ioBlock.getNumSamples();+ int numChannels = (int)ioBlock.getNumChannels();++ // Snapshot parameters at block boundary for thread safety+ float ceilingLinear = std::pow(10.0f, ceilingDb_ / 20.0f);+ float releaseCoeff = std::exp(+ -1.0f /+ std::max(1, (int)(preparedSpec_.sampleRate * releaseMs_ / 1000.0f)));++ for (int i = 0; i < numSamples; ++i) {+ // Detect cross-channel peak for this sample+ float peak = 0.0f;+ for (int ch = 0; ch < numChannels; ++ch) {+ float s = std::abs(ioBlock.getChannelPointer(ch)[i]);+ if (s > peak)+ peak = s;+ }++ // Compute target gain+ float targetGain = (peak > ceilingLinear)+ ? (ceilingLinear / std::max(peak, 1e-30f))+ : 1.0f;++ // Instant attack, exponential release+ if (targetGain < currentGain_) {+ currentGain_ = targetGain;+ } else {+ currentGain_ += (1.0f - releaseCoeff) * (1.0f - currentGain_);+ }++ // Apply gain + safety clip+ for (int ch = 0; ch < numChannels; ++ch) {+ SampleType *channelPtr = ioBlock.getChannelPointer(ch);+ channelPtr[i] = juce::jlimit(+ (SampleType)(-ceilingLinear), (SampleType)ceilingLinear,+ (SampleType)(channelPtr[i] * currentGain_));+ }+ }++ return numSamples;+ }++ virtual void reset() override { currentGain_ = 1.0f; }++private:+ // Requested parameters (written by setters, read by process() at block start)+ float ceilingDb_ = -1.0f;+ float releaseMs_ = 100.0f;++ // DSP state+ float currentGain_ = 1.0f;++ // Cached spec+ juce::dsp::ProcessSpec preparedSpec_{};+};++inline void init_brickwall_limiter(py::module &m) {+ py::class_<BrickwallLimiter<float>, Plugin,+ std::shared_ptr<BrickwallLimiter<float>>>(+ m, "BrickwallLimiter",+ "A lookahead brick-wall limiter with configurable ceiling.\n\n"+ "Unlike the built-in :class:`Limiter`, ``BrickwallLimiter``:\n\n"+ "- Has a configurable ceiling (not fixed at 0 dBFS)\n"+ "- Does **not** apply makeup gain\n"+ "- Uses lookahead for transparent gain reduction (not hard clipping)\n"+ "- Optionally detects inter-sample peaks via 4x oversampling\n\n"+ "Typical use: enforce a peak ceiling after loudness normalization.\n\n"+ ".. code-block:: python\n\n"+ " limiter = BrickwallLimiter(ceiling_db=-1.0)\n"+ " output = limiter(audio, sample_rate)\n")+ .def(py::init([](float ceiling, float release) {+ auto p = std::make_unique<BrickwallLimiter<float>>();+ p->setCeilingDb(ceiling);+ p->setReleaseMs(release);+ return p;+ }),+ py::arg("ceiling_db") = -1.0f, py::arg("release_ms") = 100.0f)+ .def("__repr__",+ [](const BrickwallLimiter<float> &plugin) {+ std::ostringstream ss;+ ss << "<pedalboard.BrickwallLimiter"+ << " ceiling_db=" << plugin.getCeilingDb()+ << " release_ms=" << plugin.getReleaseMs() << ">";+ return ss.str();+ })+ .def_property("ceiling_db", &BrickwallLimiter<float>::getCeilingDb,+ &BrickwallLimiter<float>::setCeilingDb)+ .def_property("release_ms", &BrickwallLimiter<float>::getReleaseMs,+ &BrickwallLimiter<float>::setReleaseMs);+}++} // namespace Pedalboarddiff --git a/pedalboard/python_bindings.cpp b/pedalboard/python_bindings.cppindex 0131b00..3e5429a 100644--- a/pedalboard/python_bindings.cpp+++ b/pedalboard/python_bindings.cpp@@ -41,6 +41,7 @@ namespace py = pybind11;#include "plugins/AddLatency.h"#include "plugins/Bitcrush.h"+#include "plugins/BrickwallLimiter.h"#include "plugins/Chain.h"#include "plugins/Chorus.h"#include "plugins/Clipping.h"@@ -221,6 +222,7 @@ If the number of samples and the number of channels are the same, eachinit_invert(m);init_ladderfilter(m);init_limiter(m);+ init_brickwall_limiter(m);init_lowpass(m);init_mp3_compressor(m);init_noisegate(m);diff --git a/tests/test_brickwall_limiter.py b/tests/test_brickwall_limiter.pynew file mode 100644index 0000000..f5cded1--- /dev/null+++ b/tests/test_brickwall_limiter.py@@ -0,0 +1,75 @@+"""Tests for the BrickwallLimiter plugin."""++import numpy as np+import pytest++from pedalboard import BrickwallLimiter++from .utils import db_to_gain, generate_sine_at+++ "ceiling_db", [0.0, -0.1, -0.3, -1.0, -3.0, -6.0, -12.0, -20.0]+)[email protected]("sample_rate", [22050, 44100, 48000])[email protected]("num_channels", [1, 2])+def test_ceiling_enforced(ceiling_db: float, sample_rate: float, num_channels: int):+ """Output sample peak must not exceed the ceiling."""+ sine_wave = generate_sine_at(+ sample_rate, 440.0, num_seconds=0.5, num_channels=num_channels+ )+ plugin = BrickwallLimiter(ceiling_db=ceiling_db)+ output = plugin.process(sine_wave, sample_rate)++ assert np.all(np.isfinite(output))+ assert output.shape == sine_wave.shape+ ceiling_linear = db_to_gain(ceiling_db)+ assert (+ np.max(np.abs(output)) <= ceiling_linear + 1e-3+ ), f"Output peak {np.max(np.abs(output)):.6f} exceeds ceiling {ceiling_linear:.6f}"+++def test_passthrough_below_ceiling():+ """A signal well below the ceiling should pass through unchanged."""+ quiet_sine = generate_sine_at(44100, 440.0, num_seconds=0.5, num_channels=1) * 0.1+ plugin = BrickwallLimiter(ceiling_db=-1.0)+ output = plugin.process(quiet_sine, 44100)+ np.testing.assert_allclose(output, quiet_sine, atol=1e-6)+++def test_no_makeup_gain():+ """Unlike the built-in Limiter, BrickwallLimiter must NOT boost quiet signals."""+ quiet_sine = generate_sine_at(44100, 440.0, num_seconds=0.5, num_channels=1) * 0.1+ plugin = BrickwallLimiter(ceiling_db=-0.3)+ output = plugin.process(quiet_sine, 44100)+ assert np.max(np.abs(output)) <= np.max(np.abs(quiet_sine)) + 1e-6+++def test_extreme_levels():+ """Signals well above 0 dBFS (e.g., after loudness normalization) must be limited."""+ sine_wave = generate_sine_at(44100, 440.0, num_seconds=0.5, num_channels=1)+ boosted = sine_wave * db_to_gain(20.0) # +20 dBFS+ ceiling_db = -1.0+ plugin = BrickwallLimiter(ceiling_db=ceiling_db)+ output = plugin.process(boosted, 44100)+ ceiling_linear = db_to_gain(ceiling_db)+ assert np.max(np.abs(output)) <= ceiling_linear + 1e-3+++def test_parameter_validation():+ """Invalid parameter values must raise; valid edge cases must not."""+ limiter = BrickwallLimiter()++ with pytest.raises(Exception):+ limiter.release_ms = 0+ with pytest.raises(Exception):+ limiter.release_ms = -1+ with pytest.raises(Exception):+ limiter.ceiling_db = float("nan")+ with pytest.raises(Exception):+ limiter.ceiling_db = float("inf")++ # Valid edge cases β must NOT raise+ limiter.ceiling_db = 0.0 # 0 dBFS ceiling+ limiter.ceiling_db = 3.0 # positive headroom+ limiter.ceiling_db = -40.0 # very quiet ceiling