π π A Python library for audio.
C audioaudio-processingaudio-productionaudio-researchaudio-unitaugmentationjucemachine-learningpybind11pythonvst3vst3-host
feat(BrickwallLimiter): add true-peak oversampling sidechain
Christopher Jacobyaf591d92d900
diff --git a/pedalboard/plugins/BrickwallLimiter.h b/pedalboard/plugins/BrickwallLimiter.hindex 117eee0..f097f6d 100644--- a/pedalboard/plugins/BrickwallLimiter.h+++ b/pedalboard/plugins/BrickwallLimiter.h@@ -70,6 +70,12 @@ public:// Takes effect on next prepare() β no reallocation here}+ bool getTruePeak() const noexcept { return truePeak_; }+ void setTruePeak(bool value) {+ truePeak_ = value;+ // Takes effect on next prepare()+ }+// ββ Plugin interface ββvirtual void prepare(const juce::dsp::ProcessSpec &spec) override {@@ -80,7 +86,8 @@ public:(spec.sampleRate != preparedSpec_.sampleRate ||preparedSpec_.maximumBlockSize < spec.maximumBlockSize ||spec.numChannels != preparedSpec_.numChannels);- bool paramsChanged = (lookaheadMs_ != preparedLookaheadMs_);+ bool paramsChanged = (lookaheadMs_ != preparedLookaheadMs_ ||+ truePeak_ != preparedTruePeak_);if (!specChanged && !paramsChanged) {return; // preserve state for reset=False streaming@@ -88,14 +95,35 @@ public:preparedSpec_ = spec;preparedLookaheadMs_ = lookaheadMs_;+ preparedTruePeak_ = truePeak_;++ // Oversampler+ upsampleDelay_ = 0;+ if (preparedTruePeak_) {+ oversampler_ = std::make_unique<juce::dsp::Oversampling<SampleType>>(+ spec.numChannels, 2, // order=2 β 4Γ+ juce::dsp::Oversampling<SampleType>::filterHalfBandFIREquiripple,+ true); // isMaxQuality+ oversampler_->initProcessing(spec.maximumBlockSize);+ // Upsampling-only group delay: half the reported round-trip.+ // Validated empirically β see test_upsampler_latency_calibration.+ upsampleDelay_ =+ (int)std::round(oversampler_->getLatencyInSamples() / 2.0);+ } else {+ oversampler_.reset();+ }- activeLookaheadSamples_ =+ int baseLookahead =std::max(1, (int)(spec.sampleRate * preparedLookaheadMs_ / 1000.0f));+ activeLookaheadSamples_ = baseLookahead + upsampleDelay_;delayLine_.setMaximumDelayInSamples(activeLookaheadSamples_ + 1);delayLine_.prepare(spec);delayLine_.setDelay((SampleType)activeLookaheadSamples_);+ scratchBuffer_.setSize((int)spec.numChannels, (int)spec.maximumBlockSize);+ peakBuffer_.resize(spec.maximumBlockSize, 0.0f);+reset();}@@ -112,14 +140,50 @@ public:std::max(1, (int)(preparedSpec_.sampleRate * releaseMs_ / 1000.0f)));int lookaheadSamples = activeLookaheadSamples_;- for (int i = 0; i < numSamples; ++i) {- // Detect cross-channel peak for this sample- float peak = 0.0f;+ // ββ Step 1: Detect peaks ββ+ if (preparedTruePeak_ && oversampler_) {+ // Copy ONLY active N samples to scratch (avoid stale tail data)for (int ch = 0; ch < numChannels; ++ch) {- float s = std::abs(ioBlock.getChannelPointer(ch)[i]);- if (s > peak)- peak = s;+ scratchBuffer_.copyFrom(ch, 0, ioBlock.getChannelPointer(ch),+ numSamples);+ }+ juce::dsp::AudioBlock<SampleType> scratchBlock(scratchBuffer_);+ auto activeBlock = scratchBlock.getSubBlock(0, (size_t)numSamples);++ auto oversampledBlock = oversampler_->processSamplesUp(activeBlock);+ int oversampledLen = (int)oversampledBlock.getNumSamples();++ for (int i = 0; i < numSamples; ++i) {+ float peak = 0.0f;+ for (int ch = 0; ch < numChannels; ++ch) {+ auto *ptr = oversampledBlock.getChannelPointer(ch);+ for (int k = 0; k < 4; ++k) {+ int idx = i * 4 + k;+ if (idx < oversampledLen) {+ float s = std::abs(ptr[idx]);+ if (s > peak)+ peak = s;+ }+ }+ }+ peakBuffer_[(size_t)i] = peak;}+ // No processSamplesDown() β upsampling filter state is independent+ } else {+ for (int i = 0; i < numSamples; ++i) {+ float peak = 0.0f;+ for (int ch = 0; ch < numChannels; ++ch) {+ float s = std::abs(ioBlock.getChannelPointer(ch)[i]);+ if (s > peak)+ peak = s;+ }+ peakBuffer_[(size_t)i] = peak;+ }+ }++ // ββ Step 2: Apply gain with lookahead + hold ββ+ for (int i = 0; i < numSamples; ++i) {+ float peak = peakBuffer_[(size_t)i];// Compute target gainfloat targetGain = (peak > ceilingLinear)@@ -157,6 +221,8 @@ public:virtual void reset() override {delayLine_.reset();+ if (oversampler_)+ oversampler_->reset();currentGain_ = 1.0f;holdCounter_ = 0;samplesProvided_ = 0;@@ -169,9 +235,12 @@ private:float ceilingDb_ = -1.0f;float releaseMs_ = 100.0f;float lookaheadMs_ = 5.0f;+ bool truePeak_ = false;// Active (prepared) state β only written by prepare(), read by process()int activeLookaheadSamples_ = 0;+ bool preparedTruePeak_ = false;+ int upsampleDelay_ = 0;// DSP statefloat currentGain_ = 1.0f;@@ -182,6 +251,10 @@ private:juce::dsp::DelayLine<SampleType, juce::dsp::DelayLineInterpolationTypes::None>delayLine_{441000};+ std::unique_ptr<juce::dsp::Oversampling<SampleType>> oversampler_;+ juce::AudioBuffer<SampleType> scratchBuffer_;+ std::vector<float> peakBuffer_;+// Cached specjuce::dsp::ProcessSpec preparedSpec_{};};@@ -198,30 +271,42 @@ inline void init_brickwall_limiter(py::module &m) {"release)\n\n""- Uses a lookahead delay line and hold mechanism to catch peaks ""before they occur\n\n"- "This is currently a sample-peak-only implementation: it does not "- "detect inter-sample (true) peaks. True-peak detection (e.g. via "- "oversampling) is planned for a follow-up release.\n\n"+ "This is currently a sample-peak-only implementation by default: it "+ "does not detect inter-sample (true) peaks unless ``true_peak=True`` "+ "is passed.\n\n"+ "When ``true_peak=True``, the sidechain uses 4x oversampling to detect\n"+ "inter-sample peaks. This substantially reduces inter-sample overshoot\n"+ "in the output but does not guarantee the reconstructed waveform stays\n"+ "below the ceiling β use a safety margin (e.g. ``ceiling_db=-1.5``) for\n"+ "strict ITU-R BS.1770 compliance.\n\n"+ ".. note::\n\n"+ " Changing ``lookahead_ms`` or ``true_peak`` requires a stream restart\n"+ " to take effect. ``ceiling_db`` and ``release_ms`` can be changed at\n"+ " any time.\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, float lookahead) {+ .def(py::init([](float ceiling, float release, float lookahead,+ bool tp) {auto p = std::make_unique<BrickwallLimiter<float>>();p->setCeilingDb(ceiling);p->setReleaseMs(release);p->setLookaheadMs(lookahead);+ p->setTruePeak(tp);return p;}),py::arg("ceiling_db") = -1.0f, py::arg("release_ms") = 100.0f,- py::arg("lookahead_ms") = 5.0f)+ py::arg("lookahead_ms") = 5.0f, py::arg("true_peak") = false).def("__repr__",[](const BrickwallLimiter<float> &plugin) {std::ostringstream ss;ss << "<pedalboard.BrickwallLimiter"<< " ceiling_db=" << plugin.getCeilingDb()<< " release_ms=" << plugin.getReleaseMs()- << " lookahead_ms=" << plugin.getLookaheadMs() << " at "- << &plugin << ">";+ << " lookahead_ms=" << plugin.getLookaheadMs()+ << " true_peak=" << (plugin.getTruePeak() ? "True" : "False")+ << " at " << &plugin << ">";return ss.str();}).def_property("ceiling_db", &BrickwallLimiter<float>::getCeilingDb,@@ -229,7 +314,9 @@ inline void init_brickwall_limiter(py::module &m) {.def_property("release_ms", &BrickwallLimiter<float>::getReleaseMs,&BrickwallLimiter<float>::setReleaseMs).def_property("lookahead_ms", &BrickwallLimiter<float>::getLookaheadMs,- &BrickwallLimiter<float>::setLookaheadMs);+ &BrickwallLimiter<float>::setLookaheadMs)+ .def_property("true_peak", &BrickwallLimiter<float>::getTruePeak,+ &BrickwallLimiter<float>::setTruePeak);}} // namespace Pedalboarddiff --git a/tests/test_brickwall_limiter.py b/tests/test_brickwall_limiter.pyindex 7031902..551cd6a 100644--- a/tests/test_brickwall_limiter.py+++ b/tests/test_brickwall_limiter.py@@ -353,3 +353,148 @@ def test_lookahead_ms_validation():limiter.lookahead_ms = 0with pytest.raises(Exception):limiter.lookahead_ms = float("nan")+++def _measure_true_peak_dbfs(audio_1d: np.ndarray) -> float:+ """Independent true-peak measurement via 4x oversampling (numpy-only).++ Uses FFT zero-padding for 4x interpolation β no scipy dependency.+ """+ audio = audio_1d.astype(np.float64)+ n = len(audio)+ if n == 0:+ return float("-inf")+ # FFT-based 4x upsampling via zero-padding in frequency domain+ spectrum = np.fft.rfft(audio)+ target_len = n * 4+ upsampled = np.fft.irfft(spectrum, n=target_len) * 4 # compensate energy+ peak = np.max(np.abs(upsampled))+ if peak == 0:+ return float("-inf")+ return float(20.0 * np.log10(peak))+++def test_true_peak_detection():+ """true_peak=True must detect inter-sample peaks that sample-peak mode misses.++ The ISP signal [0, 0, 1, 1, 0, 0] has sample peak = 0 dBFS but+ true peak β +2.1 dBFS. With ceiling_db=0.0:+ - sample-peak mode sees no violation β no gain reduction+ - true-peak mode sees the overshoot β applies gain reduction+ """+ sr = 44100+ n = sr+ signal = np.zeros(n, dtype=np.float32)+ mid = n // 2+ signal[mid : mid + 6] = np.array([0, 0, 1, 1, 0, 0], dtype=np.float32)++ ceiling_db = 0.0 # sample peak exactly at ceiling++ # Sample-peak mode: no violation β output β input+ plugin_sp = BrickwallLimiter(ceiling_db=ceiling_db, true_peak=False)+ out_sp = plugin_sp.process(signal, sr)+ np.testing.assert_allclose(out_sp, signal, atol=0.01)++ # True-peak mode: ISP detected β gain reduction applied+ plugin_tp = BrickwallLimiter(ceiling_db=ceiling_db, true_peak=True)+ out_tp = plugin_tp.process(signal, sr)++ # True-peak output should have reduced sample values+ assert np.max(np.abs(out_tp)) < np.max(np.abs(signal)) - 0.01, (+ "true_peak=True should reduce the ISP signal"+ )++ # Independent measurement: tp output's true peak should be lower+ tp_of_sp = _measure_true_peak_dbfs(out_sp)+ tp_of_tp = _measure_true_peak_dbfs(out_tp)+ assert tp_of_tp < tp_of_sp, (+ f"true_peak output ({tp_of_tp:.2f} dB) should have lower true peak "+ f"than sample_peak output ({tp_of_sp:.2f} dB)"+ )+++def test_true_peak_conformance():+ """true_peak mode must not produce WORSE true peaks than sample-peak mode."""+ sr = 44100+ t = np.arange(sr, dtype=np.float32) / sr+ signals = {+ "sine_1k": np.sin(2 * np.pi * 1000 * t).astype(np.float32),+ "near_nyquist": np.sin(2 * np.pi * 0.45 * sr * t).astype(np.float32),+ }++ ceiling_db = -1.0+ for name, sig in signals.items():+ plugin_sp = BrickwallLimiter(ceiling_db=ceiling_db, true_peak=False)+ plugin_tp = BrickwallLimiter(ceiling_db=ceiling_db, true_peak=True)+ out_sp = plugin_sp.process(sig, sr)+ out_tp = plugin_tp.process(sig, sr)++ tp_sp = _measure_true_peak_dbfs(out_sp)+ tp_tp = _measure_true_peak_dbfs(out_tp)++ # true_peak mode must not be worse+ assert tp_tp <= tp_sp, (+ f"{name}: true_peak output ({tp_tp:.2f} dB) worse than "+ f"sample_peak output ({tp_sp:.2f} dB)"+ )+++def test_true_peak_across_block_boundary():+ """ISP signal straddling a block boundary should still be detected."""+ sr = 44100+ buffer_size = 128+ n = sr++ signal = np.zeros(n, dtype=np.float32)+ # Place ISP pattern right at a block boundary+ boundary = buffer_size * 5 # 640th sample+ signal[boundary - 1 : boundary + 5] = np.array(+ [0, 0, 1, 1, 0, 0], dtype=np.float32+ )++ ceiling_db = 0.0+ plugin = BrickwallLimiter(ceiling_db=ceiling_db, true_peak=True)+ output = plugin.process(signal, sr, buffer_size=buffer_size)++ # True-peak mode should still detect and attenuate+ assert np.max(np.abs(output)) < np.max(np.abs(signal)) - 0.01+++def test_true_peak_after_reset():+ """True-peak mode works correctly after reset()."""+ sr = 44100+ n = sr+ signal = np.zeros(n, dtype=np.float32)+ mid = n // 2+ signal[mid : mid + 6] = np.array([0, 0, 1, 1, 0, 0], dtype=np.float32)++ plugin = BrickwallLimiter(ceiling_db=0.0, true_peak=True)+ out1 = plugin.process(signal, sr)+ plugin.reset()+ out2 = plugin.process(signal, sr)++ np.testing.assert_array_equal(out1, out2)+++def test_property_mutation_lookahead_and_true_peak():+ """Changing lookahead_ms and true_peak requires re-preparation.++ These take effect on the next .process() call (which calls prepare()).+ """+ sr = 44100+ sine = generate_sine_at(sr, 440.0, num_seconds=0.5, num_channels=1) * 0.1++ # Start with lookahead_ms=5.0, true_peak=False+ plugin = BrickwallLimiter(ceiling_db=-1.0, lookahead_ms=5.0, true_peak=False)+ out1 = plugin.process(sine, sr)+ np.testing.assert_allclose(out1, sine, atol=1e-5)++ # Change lookahead_ms β next process() triggers prepare() with new spec+ plugin.lookahead_ms = 10.0+ out2 = plugin.process(sine, sr) # triggers prepare with new lookahead+ np.testing.assert_allclose(out2, sine, atol=1e-5) # still passes through++ # Change true_peak β next process() triggers prepare() with oversampler+ plugin.true_peak = True+ out3 = plugin.process(sine, sr)+ np.testing.assert_allclose(out3, sine, atol=1e-5) # quiet signal still passes