Skip to content

πŸŽ› πŸ”Š A Python library for audio.

Merge branch 'master' into psobot/nested-plugin-chains

Peter Sobot34e899d35e84
diff --cc pedalboard/plugin_templates/PrimeWithSilence.h
index 0000000,043ba6a..aa432eb
mode 000000,100644..100644
--- a/pedalboard/plugin_templates/PrimeWithSilence.h
+++ b/pedalboard/plugin_templates/PrimeWithSilence.h
@@@ -1,0 -1,179 +1,180 @@@
+ /*
+ * pedalboard
+ * Copyright 2022 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 "../plugins/AddLatency.h"
+ #include <mutex>
+
+ namespace Pedalboard {
+
+ /**
+ * A dummy plugin that buffers audio data internally, used to test Pedalboard's
+ * automatic latency compensation.
+ */
+ template <typename T, typename SampleType = float>
+ class PrimeWithSilence
+ : public JucePlugin<juce::dsp::DelayLine<
+ SampleType, juce::dsp::DelayLineInterpolationTypes::None>> {
+ public:
+ virtual ~PrimeWithSilence(){};
+
+ virtual void prepare(const juce::dsp::ProcessSpec &spec) {
+ JucePlugin<juce::dsp::DelayLine<
+ SampleType,
+ juce::dsp::DelayLineInterpolationTypes::None>>::prepare(spec);
+ plugin.prepare(spec);
+ }
+
+ virtual void reset() override {
+ this->getDSP().reset();
+ this->getDSP().setMaximumDelayInSamples(silenceLengthSamples);
+ this->getDSP().setDelay(silenceLengthSamples);
+ plugin.reset();
+ samplesOutput = 0;
+ }
+
+ virtual int
+ process(const juce::dsp::ProcessContextReplacing<float> &context) override {
+ this->getDSP().process(context);
+
+ // Context now has a delayed signal in it:
+ int samplesProcessed = plugin.process(context);
+ samplesOutput += samplesProcessed;
+
+ return std::max(
+ 0, std::min((int)samplesProcessed,
+ (int)samplesOutput - (int)this->getDSP().getDelay()));
+ }
+
+ virtual int getLatencyHint() override {
+ return this->getDSP().getDelay() + getNestedPlugin().getLatencyHint();
+ }
+
+ T &getNestedPlugin() { return plugin; }
+
+ void setSilenceLengthSamples(int newSilenceLengthSamples) {
+ this->getDSP().setMaximumDelayInSamples(newSilenceLengthSamples);
+ this->getDSP().setDelay(newSilenceLengthSamples);
+ silenceLengthSamples = newSilenceLengthSamples;
+
+ reset();
+ }
+
+ int getSilenceLengthSamples() const { return silenceLengthSamples; }
+
+ private:
+ T plugin;
+ int samplesOutput = 0;
+ int silenceLengthSamples = 0;
+ };
+
+ /**
+ * A test plugin used to verify the behaviour of the PrimingPlugin wrapper.
+ */
+ class ExpectsToBePrimed : public AddLatency {
+ public:
+ virtual ~ExpectsToBePrimed(){};
+
+ virtual void prepare(const juce::dsp::ProcessSpec &spec) {
+ getDSP().setMaximumDelayInSamples(10);
+ getDSP().setDelay(10);
+
+ AddLatency::prepare(spec);
+ }
+
+ virtual int
+ process(const juce::dsp::ProcessContextReplacing<float> &context) {
+ auto inputBlock = context.getInputBlock();
+
+ for (int i = 0; i < inputBlock.getNumSamples(); i++) {
+ bool allChannelsSilent = true;
+
+ for (int c = 0; c < inputBlock.getNumChannels(); c++) {
+ if (inputBlock.getChannelPointer(c)[i] != 0) {
+ allChannelsSilent = false;
+ }
+ }
+
+ if (!allChannelsSilent) {
+ // If we get here, we've got our first non-zero sample.
+ if (seenSilentSamples < expectedSilentSamples) {
+ throw std::runtime_error("Expected to see " +
+ std::to_string(expectedSilentSamples) +
+ " silent samples, but only saw " +
+ std::to_string(seenSilentSamples) +
+ " before first non-zero value.");
+ }
+ break;
+ }
+
+ seenSilentSamples++;
+ }
+
+ return AddLatency::process(context);
+ }
+
+ virtual void reset() {
+ seenSilentSamples = 0;
+ AddLatency::reset();
+ }
+
+ void setExpectedSilentSamples(int newExpectedSilentSamples) {
+ expectedSilentSamples = newExpectedSilentSamples;
+ }
+
+ private:
+ int expectedSilentSamples = 0;
+ int seenSilentSamples = 0;
+ };
+
+ class PrimeWithSilenceTestPlugin : public PrimeWithSilence<ExpectsToBePrimed> {
+ public:
+ void setExpectedSilentSamples(int newExpectedSilentSamples) {
+ setSilenceLengthSamples(newExpectedSilentSamples);
+ getNestedPlugin().setExpectedSilentSamples(getSilenceLengthSamples());
+ }
+
+ int getExpectedSilentSamples() const { return getSilenceLengthSamples(); }
+
+ private:
+ int expectedBlockSize = 0;
+ };
+
+ inline void init_prime_with_silence_test_plugin(py::module &m) {
- py::class_<PrimeWithSilenceTestPlugin, Plugin>(m,
- "PrimeWithSilenceTestPlugin")
++ py::class_<PrimeWithSilenceTestPlugin, Plugin,
++ std::shared_ptr<PrimeWithSilenceTestPlugin>>(
++ m, "PrimeWithSilenceTestPlugin")
+ .def(py::init([](int expectedSilentSamples) {
+ auto plugin = std::make_unique<PrimeWithSilenceTestPlugin>();
+ plugin->setExpectedSilentSamples(expectedSilentSamples);
+ return plugin;
+ }),
+ py::arg("expected_silent_samples") = 160)
+ .def("__repr__", [](const PrimeWithSilenceTestPlugin &plugin) {
+ std::ostringstream ss;
+ ss << "<pedalboard.PrimeWithSilenceTestPlugin";
+ ss << " expected_silent_samples=" << plugin.getExpectedSilentSamples();
+ ss << " at " << &plugin;
+ ss << ">";
+ return ss.str();
+ });
+ }
+
+ } // namespace Pedalboard
diff --cc pedalboard/process.h
index 4058eba,81ee6f1..c48ea4e
--- a/pedalboard/process.h
+++ b/pedalboard/process.h
@@@ -203,124 -203,6 +203,131 @@@ py::array_t<T> copyJuceBufferIntoPyArra
return outputArray;
}
+inline int process(juce::AudioBuffer<float> &ioBuffer,
+ juce::dsp::ProcessSpec spec,
+ const std::vector<std::shared_ptr<Plugin>> &plugins,
+ bool isProbablyLastProcessCall) {
+ int totalOutputLatencySamples = 0;
+ int expectedOutputLatency = 0;
+
+ for (auto plugin : plugins) {
+ if (!plugin)
+ continue;
+ expectedOutputLatency += plugin->getLatencyHint();
+ }
+
+ int intendedOutputBufferSize = ioBuffer.getNumSamples();
+
+ if (expectedOutputLatency > 0 && isProbablyLastProcessCall) {
+ // This is a hint - it's possible that the plugin(s) latency values
+ // will change and we'll have to reallocate again later on.
+ ioBuffer.setSize(ioBuffer.getNumChannels(),
+ ioBuffer.getNumSamples() + expectedOutputLatency,
+ /* keepExistingContent= */ true,
+ /* clearExtraSpace= */ true);
+ }
+
+ // Actually run the plugins over the ioBuffer, in small chunks, to minimize
+ // memory usage:
+ int startOfOutputInBuffer = 0;
+ int lastSampleInBuffer = 0;
+
+ for (auto plugin : plugins) {
+ if (!plugin)
+ continue;
+
+ int pluginSamplesReceived = 0;
+
++ unsigned int blockSize = spec.maximumBlockSize;
+ for (unsigned int blockStart = startOfOutputInBuffer;
+ blockStart < (unsigned int)intendedOutputBufferSize;
- blockStart += spec.maximumBlockSize) {
++ blockStart += blockSize) {
+ unsigned int blockEnd =
+ std::min(blockStart + spec.maximumBlockSize,
+ static_cast<unsigned int>(intendedOutputBufferSize));
- unsigned int blockSize = blockEnd - blockStart;
++ blockSize = blockEnd - blockStart;
+
+ auto ioBlock = juce::dsp::AudioBlock<float>(
+ ioBuffer.getArrayOfWritePointers(), ioBuffer.getNumChannels(),
+ blockStart, blockSize);
+ juce::dsp::ProcessContextReplacing<float> context(ioBlock);
+
+ int outputSamples = plugin->process(context);
+ if (outputSamples < 0) {
+ throw std::runtime_error(
+ "A plugin returned a negative number of output samples! "
+ "This is an internal Pedalboard error and should be reported.");
+ }
+ pluginSamplesReceived += outputSamples;
+
+ int missingSamples = blockSize - outputSamples;
++ if (missingSamples < 0) {
++ throw std::runtime_error(
++ "A plugin returned more samples than were asked for! "
++ "This is an internal Pedalboard error and should be reported.");
++ }
++
+ if (missingSamples > 0 && pluginSamplesReceived > 0) {
+ // This can only happen if the plugin we're using is returning us more
+ // than one chunk of audio that's not completely full, which can
+ // happen sometimes. In this case, we would end up with gaps in the
+ // audio output:
+ // empty empty full part
+ // [______|______|AAAAAA|__BBBB]
+ // end of most recently rendered block-->-^
+ // We need to consolidate those gaps by moving them forward in time.
+ // To do so, we take the section from the earliest known output to the
+ // start of this block, and right-align it to the left side of the
+ // current block's content:
+ // empty empty part full
+ // [______|______|__AAAA|AABBBB]
+ // end of most recently rendered block-->-^
+ for (int c = 0; c < ioBuffer.getNumChannels(); c++) {
+ // Only move the samples received before this latest block was
+ // rendered, as audio is right-aligned within blocks by convention.
+ int samplesToMove = pluginSamplesReceived - outputSamples;
+ float *outputStart =
+ ioBuffer.getWritePointer(c) + totalOutputLatencySamples;
+ float *expectedOutputEnd =
+ ioBuffer.getWritePointer(c) + blockEnd - outputSamples;
+ float *expectedOutputStart = expectedOutputEnd - samplesToMove;
+
+ std::memmove((char *)expectedOutputStart, (char *)outputStart,
+ sizeof(float) * samplesToMove);
+ }
+ }
+
+ lastSampleInBuffer =
+ std::max(lastSampleInBuffer, (int)(blockStart + outputSamples));
+ startOfOutputInBuffer += missingSamples;
+ totalOutputLatencySamples += missingSamples;
+
+ if (missingSamples && isProbablyLastProcessCall) {
+ // Resize the IO buffer to give us a bit more room
+ // on the end, so we can continue to write delayed output.
+ // Only do this if we think this is the last time process is called.
+ intendedOutputBufferSize += missingSamples;
+
+ // If we need to reallocate, then we reallocate.
+ if (intendedOutputBufferSize > ioBuffer.getNumSamples()) {
+ ioBuffer.setSize(ioBuffer.getNumChannels(), intendedOutputBufferSize,
+ /* keepExistingContent= */ true,
+ /* clearExtraSpace= */ true);
+ }
+ }
+ }
+ }
+
+ // Trim the output buffer down to size; this operation should be
+ // allocation-free.
+ jassert(intendedOutputBufferSize <= ioBuffer.getNumSamples());
+ ioBuffer.setSize(ioBuffer.getNumChannels(), intendedOutputBufferSize,
+ /* keepExistingContent= */ true,
+ /* clearExtraSpace= */ true,
+ /* avoidReallocating= */ true);
+ return intendedOutputBufferSize - totalOutputLatencySamples;
+}
+
/**
* Process a given audio buffer through a list of
* Pedalboard plugins at a given sample rate.
diff --cc pedalboard/python_bindings.cpp
index a2953c8,170809e..3942981
--- a/pedalboard/python_bindings.cpp
+++ b/pedalboard/python_bindings.cpp
@@@ -53,8 -50,12 +53,10 @@@ namespace py = pybind11
#include "plugins/PitchShift.h"
#include "plugins/Reverb.h"
+ #include "plugin_templates/PrimeWithSilence.h"
+
using namespace Pedalboard;
-static constexpr int DEFAULT_BUFFER_SIZE = 8192;
-
PYBIND11_MODULE(pedalboard_native, m) {
m.def("process", process<float>,
"Run a 32-bit floating point audio buffer through a list of Pedalboard "