Skip to content

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

Add basic plugin chaining and mixing (parallel chains) functionality.

Peter Sobot5455063b64f3
diff --git a/pedalboard/ChainPlugin.h b/pedalboard/ChainPlugin.h
new file mode 100644
index 0000000..69e7bba
--- /dev/null
+++ b/pedalboard/ChainPlugin.h
@@ -0,0 +1,78 @@
+/*
+ * pedalboard
+ * Copyright 2021 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 <mutex>
+
+#include "Plugin.h"
+#include "process.h"
+
+namespace Pedalboard {
+/**
+ * A class that allows nesting a pedalboard within another.
+ */
+class ChainPlugin : public Plugin {
+public:
+ ChainPlugin(std::vector<Plugin *> chain) : chain(chain) {}
+ virtual ~ChainPlugin(){};
+
+ virtual void prepare(const juce::dsp::ProcessSpec &spec) {
+ for (auto plugin : chain) plugin->prepare(spec);
+ lastSpec = spec;
+ }
+
+ virtual int
+ process(const juce::dsp::ProcessContextReplacing<float> &context) {
+ // assuming process context replacing
+ auto ioBlock = context.getOutputBlock();
+
+ float *channels[8] = {};
+ for (int i = 0; i < ioBlock.getNumChannels(); i++) {
+ channels[i] = ioBlock.getChannelPointer(i);
+ }
+
+ juce::AudioBuffer<float> ioBuffer(channels, ioBlock.getNumChannels(), ioBlock.getNumSamples());
+ return ::Pedalboard::process(ioBuffer, lastSpec, chain, false);
+ }
+
+ virtual void reset() {
+ for (auto plugin : chain) plugin->reset();
+ }
+
+ virtual int getLatencyHint() {
+ int hint = 0;
+ for (auto plugin : chain) hint += plugin->getLatencyHint();
+ return hint;
+ }
+
+protected:
+ std::vector<Plugin *> chain;
+};
+
+inline void init_chain(py::module &m) {
+ py::class_<ChainPlugin, Plugin>(
+ m, "ChainPlugin",
+ "Run a pedalboard within a plugin. Meta.")
+ .def(py::init([](std::vector<Plugin *> plugins) {
+ return new ChainPlugin(plugins);
+ }),
+ py::arg("plugins"), py::keep_alive<1, 2>());
+}
+
+} // namespace Pedalboard
\ No newline at end of file
diff --git a/pedalboard/MixPlugin.h b/pedalboard/MixPlugin.h
new file mode 100644
index 0000000..dfb33a9
--- /dev/null
+++ b/pedalboard/MixPlugin.h
@@ -0,0 +1,155 @@
+/*
+ * pedalboard
+ * Copyright 2021 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 <mutex>
+
+#include "Plugin.h"
+
+namespace Pedalboard {
+/**
+ * A class that allows parallel processing of two separate plugin chains.
+ */
+class MixPlugin : public Plugin {
+public:
+ MixPlugin(std::vector<Plugin *> plugins) : plugins(plugins), pluginBuffers(plugins.size()), samplesAvailablePerPlugin(plugins.size()) {}
+ virtual ~MixPlugin(){};
+
+ virtual void prepare(const juce::dsp::ProcessSpec &spec) {
+ for (auto plugin : plugins) plugin->prepare(spec);
+
+ int maximumBufferSize = getLatencyHint() + spec.maximumBlockSize;
+ for (auto &buffer : pluginBuffers) buffer.setSize(spec.numChannels, maximumBufferSize);
+ for (int i = 0; i < samplesAvailablePerPlugin.size(); i++) samplesAvailablePerPlugin[i] = 0;
+ lastSpec = spec;
+ }
+
+ virtual int
+ process(const juce::dsp::ProcessContextReplacing<float> &context) {
+ auto ioBlock = context.getOutputBlock();
+
+ for (int i = 0; i < plugins.size(); i++) {
+ Plugin *plugin = plugins[i];
+ juce::AudioBuffer<float> &buffer = pluginBuffers[i];
+
+ int startInBuffer = samplesAvailablePerPlugin[i];
+ int endInBuffer = startInBuffer + ioBlock.getNumSamples();
+ // If we don't have enough space, reallocate. (Reluctantly. This is the "audio thread!")
+ if (endInBuffer > buffer.getNumSamples()) {
+ printf("Want to write from %d to %d, but buffer is only %d long - reallocating.", startInBuffer, endInBuffer, buffer.getNumSamples());
+ buffer.setSize(buffer.getNumChannels(), endInBuffer);
+ }
+
+ // Copy the audio input into each of these buffers:
+ context.getInputBlock().copyTo(buffer, 0, samplesAvailablePerPlugin[i]);
+
+ float *channelPointers[8] = {};
+ for (int c = 0; c < buffer.getNumChannels(); c++) {
+ channelPointers[c] = buffer.getWritePointer(c, startInBuffer);
+ }
+
+ auto subBlock = juce::dsp::AudioBlock<float>(
+ channelPointers,
+ buffer.getNumChannels(),
+ ioBlock.getNumSamples()
+ );
+
+ juce::dsp::ProcessContextReplacing<float> subContext(subBlock);
+ int samplesRendered = plugin->process(subContext);
+ samplesAvailablePerPlugin[i] += samplesRendered;
+
+ if (samplesRendered < subBlock.getNumSamples()) {
+ // Left-align the results in the buffer, as we'll need all
+ // of the plugins' outputs to be aligned:
+ for (int c = 0; c < pluginBuffers[i].getNumChannels(); c++) {
+ std::memmove(
+ channelPointers[c],
+ channelPointers[c] + (subBlock.getNumSamples() - samplesRendered),
+ sizeof(float) * samplesRendered
+ );
+ }
+ }
+ }
+
+ // Figure out the maximum number of samples we can return,
+ // which is the min across all buffers:
+ int maxSamplesAvailable = ioBlock.getNumSamples();
+ for (int i = 0; i < plugins.size(); i++) {
+ maxSamplesAvailable = std::min(samplesAvailablePerPlugin[i], maxSamplesAvailable);
+ }
+
+ // Now that each plugin has rendered into its own buffer, mix the output:
+ ioBlock.clear();
+ if (maxSamplesAvailable) {
+ int leftEdge = ioBlock.getNumSamples() - maxSamplesAvailable;
+ auto subBlock = ioBlock.getSubBlock(leftEdge);
+
+ for (auto &pluginBuffer : pluginBuffers) {
+ // Right-align exactly `maxSamplesAvailable` samples from each buffer:
+ juce::dsp::AudioBlock<float> pluginBufferAsBlock(pluginBuffer);
+
+ // Add as many samples as we can (which is maxSamplesAvailable,
+ // because subBlock is only that size):
+ subBlock.add(pluginBufferAsBlock);
+ }
+ }
+
+ // Delete the samples we just returned from each buffer and shift the remaining content left:
+ for (int i = 0; i < plugins.size(); i++) {
+ int samplesToDelete = maxSamplesAvailable;
+ int samplesRemaining = pluginBuffers[i].getNumSamples() - samplesAvailablePerPlugin[i];
+ for (int c = 0; c < pluginBuffers[i].getNumChannels(); c++) {
+ float *channelBuffer = pluginBuffers[i].getWritePointer(c);
+
+ // Shift the remaining samples to the start of the buffer:
+ std::memmove(channelBuffer, channelBuffer + samplesToDelete, sizeof(float) * samplesRemaining);
+ }
+ samplesAvailablePerPlugin[i] -= samplesToDelete;
+ }
+
+ return maxSamplesAvailable;
+ }
+
+ virtual void reset() {
+ for (auto plugin : plugins) plugin->reset();
+ for (auto buffer : pluginBuffers) buffer.clear();
+ }
+
+ virtual int getLatencyHint() {
+ int maxHint = 0;
+ for (auto plugin : plugins) maxHint = std::max(maxHint, plugin->getLatencyHint());
+ return maxHint;
+ }
+
+protected:
+ std::vector<juce::AudioBuffer<float>> pluginBuffers;
+ std::vector<Plugin *> plugins;
+ std::vector<int> samplesAvailablePerPlugin;
+};
+
+inline void init_mix(py::module &m) {
+ py::class_<MixPlugin, Plugin>(
+ m, "MixPlugin",
+ "Mix multiple plugins' output together, processing each in parallel.")
+ .def(py::init([](std::vector<Plugin *> plugins) {
+ return new MixPlugin(plugins);
+ }),
+ py::arg("plugins"), py::keep_alive<1, 2>());
+}
+} // namespace Pedalboard
\ No newline at end of file
diff --git a/pedalboard/pedalboard.py b/pedalboard/pedalboard.py
index d7b792e..f2c2628 100644
--- a/pedalboard/pedalboard.py
+++ b/pedalboard/pedalboard.py
@@ -31,7 +31,10 @@ class Pedalboard(collections.abc.MutableSequence):
A container for a chain of plugins, to use for processing audio.
"""
- def __init__(self, plugins: List[Optional[Plugin]], sample_rate: Optional[float] = None):
+ def __init__(self, plugins: List[Optional[Plugin]] = None, sample_rate: Optional[float] = None):
+ if not plugins:
+ plugins = []
+
for plugin in plugins:
if plugin is not None:
if not isinstance(plugin, Plugin):
diff --git a/pedalboard/process.h b/pedalboard/process.h
index 58731df..dd7d185 100644
--- a/pedalboard/process.h
+++ b/pedalboard/process.h
@@ -203,6 +203,124 @@ py::array_t<T> copyJuceBufferIntoPyArray(const juce::AudioBuffer<T> juceBuffer,
return outputArray;
}
+inline int process(juce::AudioBuffer<float> &ioBuffer,
+ juce::dsp::ProcessSpec spec,
+ const std::vector<Plugin *> &plugins,
+ bool isProbablyLastProcessCall) {
+ int totalOutputLatencySamples = 0;
+ int expectedOutputLatency = 0;
+
+ for (auto *plugin : plugins) {
+ if (plugin == nullptr)
+ 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 == nullptr)
+ continue;
+
+ int pluginSamplesReceived = 0;
+
+ for (unsigned int blockStart = startOfOutputInBuffer;
+ blockStart < (unsigned int)intendedOutputBufferSize;
+ blockStart += spec.maximumBlockSize) {
+ unsigned int blockEnd =
+ std::min(blockStart + spec.maximumBlockSize,
+ static_cast<unsigned int>(intendedOutputBufferSize));
+ unsigned int 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 && 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.
@@ -215,7 +333,7 @@ process<float>(const py::array_t<float, py::array::c_style> inputArray,
unsigned int bufferSize, bool reset) {
const ChannelLayout inputChannelLayout = detectChannelLayout(inputArray);
juce::AudioBuffer<float> ioBuffer = copyPyArrayIntoJuceBuffer(inputArray);
- int totalOutputLatencySamples = 0;
+ int totalOutputLatencySamples;
{
py::gil_scoped_release release;
@@ -274,123 +392,19 @@ process<float>(const py::array_t<float, py::array::c_style> inputArray,
spec.maximumBlockSize = static_cast<juce::uint32>(bufferSize);
spec.numChannels = static_cast<juce::uint32>(ioBuffer.getNumChannels());
- int expectedOutputLatency = 0;
-
for (auto *plugin : plugins) {
if (plugin == nullptr)
continue;
plugin->prepare(spec);
- expectedOutputLatency += plugin->getLatencyHint();
}
- int intendedOutputBufferSize = ioBuffer.getNumSamples();
-
- if (expectedOutputLatency > 0) {
- // 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 == nullptr)
- continue;
-
- int pluginSamplesReceived = 0;
-
- for (unsigned int blockStart = startOfOutputInBuffer;
- blockStart < (unsigned int)intendedOutputBufferSize;
- blockStart += bufferSize) {
- unsigned int blockEnd =
- std::min(blockStart + bufferSize,
- static_cast<unsigned int>(intendedOutputBufferSize));
- unsigned int 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 && 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 && reset) {
- // 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 reset=True was passed, as we can use that
- // as a proxy for the user's intent to call `process` again.
- 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);
+ // Actually run the process method of all plugins.
+ int samplesReturned = process(ioBuffer, spec, plugins, reset);
+ totalOutputLatencySamples = ioBuffer.getNumSamples() - samplesReturned;
}
return copyJuceBufferIntoPyArray(ioBuffer, inputChannelLayout,
totalOutputLatencySamples,
inputArray.request().ndim);
-};
+}
} // namespace Pedalboard
\ No newline at end of file
diff --git a/pedalboard/python_bindings.cpp b/pedalboard/python_bindings.cpp
index 7a16bd0..270d268 100644
--- a/pedalboard/python_bindings.cpp
+++ b/pedalboard/python_bindings.cpp
@@ -29,9 +29,11 @@ namespace py = pybind11;
#include "ExternalPlugin.h"
#include "JucePlugin.h"
+#include "MixPlugin.h"
#include "Plugin.h"
#include "process.h"
+#include "ChainPlugin.h"
#include "plugins/AddLatency.h"
#include "plugins/Chorus.h"
#include "plugins/Compressor.h"
@@ -136,6 +138,7 @@ PYBIND11_MODULE(pedalboard_native, m) {
py::arg("reset") = true);
plugin.attr("__call__") = plugin.attr("process");
+ init_chain(m);
init_chorus(m);
init_compressor(m);
init_convolution(m);
@@ -148,6 +151,7 @@ PYBIND11_MODULE(pedalboard_native, m) {
init_limiter(m);
init_lowpass(m);
init_mp3_compressor(m);
+ init_mix(m);
init_noisegate(m);
init_phaser(m);
init_pitch_shift(m);