Skip to content

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

Working Chain/Mix implementation with correct latency compensation. Could be cleaner, though.

Peter Sobot4a7e8110c5fa
diff --git a/pedalboard/ChainPlugin.h b/pedalboard/ChainPlugin.h
deleted file mode 100644
index 69e7bba..0000000
--- a/pedalboard/ChainPlugin.h
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * 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/Plugin.h b/pedalboard/Plugin.h
index 3dff016..5b3d206 100644
--- a/pedalboard/Plugin.h
+++ b/pedalboard/Plugin.h
@@ -70,6 +70,12 @@ public:
*/
virtual int getLatencyHint() { return 0; }
+ /*
+ * Some plugins can host/contain other plugins (i.e.: Mix, Chain).
+ * This method can be used to traverse the plugin tree when necessary.
+ */
+ virtual std::vector<Plugin *> getNestedPlugins() const { return {}; }
+
// A mutex to gate access to this plugin, as its internals may not be
// thread-safe. Note: use std::lock or std::scoped_lock when locking multiple
// plugins to avoid deadlocking.
diff --git a/pedalboard/__init__.py b/pedalboard/__init__.py
index 36404dc..598a67b 100644
--- a/pedalboard/__init__.py
+++ b/pedalboard/__init__.py
@@ -16,6 +16,7 @@
from pedalboard_native import * # noqa: F403, F401
+from pedalboard_native.utils import * # noqa: F401
from .pedalboard import Pedalboard, AVAILABLE_PLUGIN_CLASSES, load_plugin # noqa: F401
from .version import __version__ # noqa: F401
diff --git a/pedalboard/pedalboard.py b/pedalboard/pedalboard.py
index f2c2628..263589e 100644
--- a/pedalboard/pedalboard.py
+++ b/pedalboard/pedalboard.py
@@ -14,16 +14,85 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+import os
import collections
import platform
import weakref
from functools import update_wrapper
from contextlib import contextmanager
-from typing import List, Optional, Dict, Union, Tuple, Iterable
+from typing import List, Optional, Dict, Union, Tuple, Set, Iterable, Union
import numpy as np
from pedalboard_native import Plugin, process, _AudioProcessorParameter
+from pedalboard_native.utils import Mix, Chain
+
+
+# A concrete type for all ways to define a Pedalboard with zero or more plugins:
+PedalboardDefinition = Union[
+ # The standard Pedalboard is a list of plugins,
+ # although nested lists will be unpacked.
+ List[Union[Plugin, 'PedalboardDefinition']],
+ # Tuples can be used in place of lists when necessary,
+ # if putting a chain inside of a mix plugin.
+ Tuple[Union[Plugin, 'PedalboardDefinition']],
+ # Pedalboards can be nested, and the contained
+ # pedalboard's plugins will be treated as a list:
+ 'Pedalboard',
+ # Passing a set of plugins will result in them being processed in parallel
+ # (i.e: they will all accept the same input and their outputs will be mixed)
+ Set[Union[Plugin, 'PedalboardDefinition']],
+]
+
+
+def _coalesce_plugin_definitions(
+ _input: Optional[PedalboardDefinition], level: int = 0
+) -> List[Plugin]:
+ """
+ Given a PedalboardDefinition, return a concrete list of plugins that can be executed.
+ Basically: remove the syntactic sugar and add the appropriate Mix() and Chain() plugins.
+ """
+ if isinstance(_input, Plugin):
+ return _input
+ elif hasattr(_input, "plugins"):
+ return _coalesce_plugin_definitions(_input.plugins, level + 1)
+ elif isinstance(_input, List) or isinstance(_input, Tuple):
+ plugins = [
+ _coalesce_plugin_definitions(element, level + 1)
+ for element in _input
+ if element is not None
+ ]
+ if level > 0:
+ return Chain(plugins)
+ else:
+ return plugins
+ elif isinstance(_input, Set):
+ return Mix(
+ [
+ _coalesce_plugin_definitions(element, level + 1)
+ for element in _input
+ if element is not None
+ ]
+ )
+ else:
+ raise TypeError(
+ "Pedalboard(...) expected a list (or set) of plugins (or lists or sets of plugins),"
+ " but found an element of type: {}".format(type(_input))
+ )
+
+
+def _flatten_all_plugins(_input: Optional[PedalboardDefinition]) -> List[Plugin]:
+ """
+ Given a PedalboardDefinition, return a concrete list of plugins that can be executed.
+ Basically: remove the syntactic sugar and add the appropriate Mix() and Chain() plugins.
+ """
+ if hasattr(_input, "plugins"):
+ return _input.plugins
+ elif isinstance(_input, Plugin):
+ return [_input]
+ elif isinstance(_input, List) or isinstance(_input, List) or isinstance(_input, Tuple):
+ return sum([_flatten_all_plugins(element) for element in _input if element is not None], [])
+ return []
class Pedalboard(collections.abc.MutableSequence):
@@ -31,25 +100,20 @@ class Pedalboard(collections.abc.MutableSequence):
A container for a chain of plugins, to use for processing audio.
"""
- 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):
- raise TypeError(
- "An object of type {} cannot be included in a {}.".format(
- type(plugin), self.__class__.__name__
- )
- )
- if plugins.count(plugin) > 1:
- raise ValueError(
- "The same plugin object ({}) was included multiple times in a {}. Please"
- " create unique instances if the same effect is required multiple times in"
- " series.".format(plugin, self.__class__.__name__)
- )
- self.plugins = plugins
+ def __init__(
+ self, plugins: Optional[PedalboardDefinition] = None, sample_rate: Optional[float] = None
+ ):
+ all_plugins = _flatten_all_plugins(plugins)
+ for plugin in all_plugins:
+ if plugin is not None and all_plugins.count(plugin) > 1:
+ raise ValueError(
+ "The same plugin object ({}) was included multiple times in a {}. Please"
+ " create unique instances if the same effect is required multiple times."
+ .format(plugin, self.__class__.__name__)
+ )
+ self.plugins = _coalesce_plugin_definitions(plugins)
+ if not isinstance(self.plugins, list):
+ self.plugins = [self.plugins]
if sample_rate is not None and not isinstance(sample_rate, (int, float)):
raise TypeError("sample_rate must be None, an integer, or a floating-point number.")
diff --git a/pedalboard/plugins/Chain.h b/pedalboard/plugins/Chain.h
new file mode 100644
index 0000000..90e04d5
--- /dev/null
+++ b/pedalboard/plugins/Chain.h
@@ -0,0 +1,106 @@
+/*
+ * 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 list of plugins within another.
+ */
+class Chain : public Plugin {
+public:
+ Chain(std::vector<Plugin *> plugins) : plugins(plugins) {}
+ virtual ~Chain(){};
+
+ virtual void prepare(const juce::dsp::ProcessSpec &spec) {
+ for (auto plugin : plugins)
+ plugin->prepare(spec);
+ lastSpec = spec;
+ }
+
+ virtual int
+ process(const juce::dsp::ProcessContextReplacing<float> &context) {
+ // assuming process context replacing
+ auto ioBlock = context.getOutputBlock();
+
+ float **channels =
+ (float **)alloca(ioBlock.getNumChannels() * sizeof(float *));
+ 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, plugins, false);
+ }
+
+ virtual void reset() {
+ for (auto plugin : plugins)
+ plugin->reset();
+ }
+
+ virtual int getLatencyHint() {
+ int hint = 0;
+ for (auto plugin : plugins)
+ hint += plugin->getLatencyHint();
+ return hint;
+ }
+
+ virtual std::vector<Plugin *> getNestedPlugins() const override { return plugins; }
+
+protected:
+ std::vector<Plugin *> plugins;
+};
+
+inline void init_chain(py::module &m) {
+ py::class_<Chain, Plugin>(m, "Chain",
+ "Run zero or more plugins as a plugin. Useful when "
+ "used with the Mix plugin.")
+ .def(py::init([](std::vector<Plugin *> plugins) {
+ return new Chain(plugins);
+ }),
+ py::arg("plugins"), py::keep_alive<1, 2>())
+ .def("__repr__",
+ [](const Chain &plugin) {
+ std::ostringstream ss;
+ ss << "<pedalboard.Chain with " << plugin.getNestedPlugins().size()
+ << " plugin";
+ if (plugin.getNestedPlugins().size() != 1) {
+ ss << "s";
+ }
+ ss << ": [";
+ for (int i = 0; i < plugin.getNestedPlugins().size(); i++) {
+ py::object nestedPlugin = py::cast(plugin.getNestedPlugins()[i]);
+ ss << nestedPlugin.attr("__repr__")();
+ if (i < plugin.getNestedPlugins().size() - 1) {
+ ss << ", ";
+ }
+ }
+ ss << "] at " << &plugin;
+ ss << ">";
+ return ss.str();
+ })
+ .def_property_readonly("plugins", &Chain::getNestedPlugins);
+}
+
+} // namespace Pedalboard
\ No newline at end of file
diff --git a/pedalboard/MixPlugin.h b/pedalboard/plugins/Mix.h
similarity index 50%
rename from pedalboard/MixPlugin.h
rename to pedalboard/plugins/Mix.h
index dfb33a9..ab9dd82 100644
--- a/pedalboard/MixPlugin.h
+++ b/pedalboard/plugins/Mix.h
@@ -17,26 +17,32 @@
#pragma once
-#include "JuceHeader.h"
+#include "../JuceHeader.h"
#include <mutex>
-#include "Plugin.h"
+#include "../Plugin.h"
namespace Pedalboard {
/**
- * A class that allows parallel processing of two separate plugin chains.
+ * A class that allows parallel processing of zero or more separate plugin
+ * chains.
*/
-class MixPlugin : public Plugin {
+class Mix : public Plugin {
public:
- MixPlugin(std::vector<Plugin *> plugins) : plugins(plugins), pluginBuffers(plugins.size()), samplesAvailablePerPlugin(plugins.size()) {}
- virtual ~MixPlugin(){};
+ Mix(std::vector<Plugin *> plugins)
+ : plugins(plugins), pluginBuffers(plugins.size()),
+ samplesAvailablePerPlugin(plugins.size()) {}
+ virtual ~Mix(){};
virtual void prepare(const juce::dsp::ProcessSpec &spec) {
- for (auto plugin : plugins) plugin->prepare(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;
+ for (auto &buffer : pluginBuffers)
+ buffer.setSize(spec.numChannels, maximumBufferSize);
+ for (int i = 0; i < samplesAvailablePerPlugin.size(); i++)
+ samplesAvailablePerPlugin[i] = 0;
lastSpec = spec;
}
@@ -50,25 +56,23 @@ public:
int startInBuffer = samplesAvailablePerPlugin[i];
int endInBuffer = startInBuffer + ioBlock.getNumSamples();
- // If we don't have enough space, reallocate. (Reluctantly. This is the "audio thread!")
+ // 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] = {};
+ float **channelPointers =
+ (float **)alloca(ioBlock.getNumChannels() * sizeof(float *));
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()
- );
+ channelPointers, buffer.getNumChannels(), ioBlock.getNumSamples());
juce::dsp::ProcessContextReplacing<float> subContext(subBlock);
int samplesRendered = plugin->process(subContext);
@@ -78,11 +82,10 @@ public:
// 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
- );
+ std::memmove(channelPointers[c],
+ channelPointers[c] +
+ (subBlock.getNumSamples() - samplesRendered),
+ sizeof(float) * samplesRendered);
}
}
}
@@ -91,14 +94,15 @@ public:
// 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);
+ 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);
+ auto subBlock = ioBlock.getSubBlock(leftEdge, maxSamplesAvailable);
for (auto &pluginBuffer : pluginBuffers) {
// Right-align exactly `maxSamplesAvailable` samples from each buffer:
@@ -110,33 +114,44 @@ public:
}
}
- // 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);
+ // Delete the samples we just returned from each buffer and shift the
+ // remaining content left:
+ int samplesToDelete = maxSamplesAvailable;
+ if (samplesToDelete) {
+ for (int i = 0; i < plugins.size(); i++) {
+ int samplesRemaining = samplesAvailablePerPlugin[i] - samplesToDelete;
+ 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);
+ // Shift the remaining samples to the start of the buffer:
+ std::memmove(channelBuffer, channelBuffer + samplesToDelete,
+ sizeof(float) * samplesRemaining);
+ }
+ samplesAvailablePerPlugin[i] -= samplesToDelete;
}
- samplesAvailablePerPlugin[i] -= samplesToDelete;
}
return maxSamplesAvailable;
}
virtual void reset() {
- for (auto plugin : plugins) plugin->reset();
- for (auto buffer : pluginBuffers) buffer.clear();
+ 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());
+ for (auto plugin : plugins)
+ maxHint = std::max(maxHint, plugin->getLatencyHint());
return maxHint;
}
+ virtual std::vector<Plugin *> getNestedPlugins() const override {
+ return plugins;
+ }
+
protected:
std::vector<juce::AudioBuffer<float>> pluginBuffers;
std::vector<Plugin *> plugins;
@@ -144,12 +159,33 @@ protected:
};
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>());
+ py::class_<Mix, Plugin>(
+ m, "Mix",
+ "A utility plugin that allows running other plugins in parallel. All "
+ "plugins provided will be mixed equally.")
+ .def(py::init(
+ [](std::vector<Plugin *> plugins) { return new Mix(plugins); }),
+ py::arg("plugins"), py::keep_alive<1, 2>())
+ .def("__repr__",
+ [](const Mix &plugin) {
+ std::ostringstream ss;
+ ss << "<pedalboard.Mix with " << plugin.getNestedPlugins().size()
+ << " plugin";
+ if (plugin.getNestedPlugins().size() != 1) {
+ ss << "s";
+ }
+ ss << ": [";
+ for (int i = 0; i < plugin.getNestedPlugins().size(); i++) {
+ py::object nestedPlugin = py::cast(plugin.getNestedPlugins()[i]);
+ ss << nestedPlugin.attr("__repr__")();
+ if (i < plugin.getNestedPlugins().size() - 1) {
+ ss << ", ";
+ }
+ }
+ ss << "] at " << &plugin;
+ ss << ">";
+ return ss.str();
+ })
+ .def_property_readonly("plugins", &Mix::getNestedPlugins);
}
} // namespace Pedalboard
\ No newline at end of file
diff --git a/pedalboard/process.h b/pedalboard/process.h
index dd7d185..69aac96 100644
--- a/pedalboard/process.h
+++ b/pedalboard/process.h
@@ -321,6 +321,15 @@ inline int process(juce::AudioBuffer<float> &ioBuffer,
return intendedOutputBufferSize - totalOutputLatencySamples;
}
+void flattenPluginTree(Plugin *plugin, std::vector<Plugin *> &output) {
+ if (std::find(output.begin(), output.end(), plugin) == output.end())
+ output.push_back(plugin);
+
+ for (auto *nestedPlugin : plugin->getNestedPlugins()) {
+ flattenPluginTree(nestedPlugin, output);
+ }
+}
+
/**
* Process a given audio buffer through a list of
* Pedalboard plugins at a given sample rate.
@@ -356,11 +365,7 @@ process<float>(const py::array_t<float, py::array::c_style> inputArray,
for (auto *plugin : plugins) {
if (plugin == nullptr)
continue;
-
- if (std::find(uniquePluginsSortedByPointer.begin(),
- uniquePluginsSortedByPointer.end(),
- plugin) == uniquePluginsSortedByPointer.end())
- uniquePluginsSortedByPointer.push_back(plugin);
+ flattenPluginTree(plugin, uniquePluginsSortedByPointer);
}
if (uniquePluginsSortedByPointer.size() < countOfPluginsIgnoringNull) {
diff --git a/pedalboard/python_bindings.cpp b/pedalboard/python_bindings.cpp
index 270d268..14f03c9 100644
--- a/pedalboard/python_bindings.cpp
+++ b/pedalboard/python_bindings.cpp
@@ -29,12 +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/Chain.h"
#include "plugins/Chorus.h"
#include "plugins/Compressor.h"
#include "plugins/Convolution.h"
@@ -46,7 +45,7 @@ namespace py = pybind11;
#include "plugins/LadderFilter.h"
#include "plugins/Limiter.h"
#include "plugins/LowpassFilter.h"
-#include "plugins/MP3Compressor.h"
+#include "plugins/Mix.h"
#include "plugins/NoiseGate.h"
#include "plugins/Phaser.h"
#include "plugins/PitchShift.h"
@@ -138,7 +137,6 @@ 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);
@@ -151,7 +149,6 @@ 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);
@@ -159,6 +156,11 @@ PYBIND11_MODULE(pedalboard_native, m) {
init_external_plugins(m);
+ // Plugins that don't perform any audio effects, but that add other utilities:
+ py::module utils = m.def_submodule("utils");
+ init_mix(utils);
+ init_chain(utils);
+
// Internal plugins for testing, debugging, etc:
py::module internal = m.def_submodule("_internal");
init_add_latency(internal);
diff --git a/tests/test_mix.py b/tests/test_mix.py
new file mode 100644
index 0000000..43ad6ab
--- /dev/null
+++ b/tests/test_mix.py
@@ -0,0 +1,206 @@
+#! /usr/bin/env python
+#
+# 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.
+
+
+import pytest
+import numpy as np
+from pedalboard import Pedalboard, Compressor, Delay, Distortion, Gain, Mix, Chain, PitchShift, Reverb
+from pedalboard_native._internal import AddLatency
+
+
+NUM_SECONDS = 4
+
+
+def test_chain_syntactic_sugar():
+ sr = 44100
+ _input = np.random.rand(int(NUM_SECONDS * sr), 2).astype(np.float32)
+
+ # Nested chains should work fine when passed as lists:
+ pb = Pedalboard([Gain(6), [Gain(-6), Gain(1)], Gain(-1)])
+ output = pb(_input, sr)
+
+ assert isinstance(pb[0], Gain)
+ assert pb[0].gain_db == 6
+
+ assert isinstance(pb[1], Chain)
+ assert pb[1].plugins[0].gain_db == -6
+ assert pb[1].plugins[1].gain_db == 1
+
+ assert isinstance(pb[2], Gain)
+ assert pb[2].gain_db == -1
+
+ np.testing.assert_allclose(_input, output, rtol=0.01)
+
+
+def test_mix_syntactic_sugar():
+ sr = 44100
+ _input = np.random.rand(int(NUM_SECONDS * sr), 2).astype(np.float32)
+
+ # Nested mixes should work fine when passed as sets:
+ pb = Pedalboard([Gain(6), {Gain(-6), Gain(-6)}, Gain(-6)])
+ output = pb(_input, sr)
+
+ assert isinstance(pb[0], Gain)
+ assert pb[0].gain_db == 6
+
+ assert isinstance(pb[1], Mix)
+ assert set([plugin.gain_db for plugin in pb[1].plugins]) == set([-6, -6])
+
+ assert isinstance(pb[2], Gain)
+ assert pb[2].gain_db == -6
+
+ np.testing.assert_allclose(_input, output, rtol=0.01)
+
+
+def test_deep_nesting():
+ sr = 44100
+ _input = np.random.rand(int(NUM_SECONDS * sr), 2).astype(np.float32)
+
+ pb = Pedalboard(
+ [
+ # This parallel chain should boost by 6dB, but due to
+ # there being 2 outputs, the result will be +12dB.
+ {tuple([Gain(1) for _ in range(6)]), tuple([Gain(1) for _ in range(6)])},
+ # This parallel chain should cut by -24dB, but due to
+ # there being 2 outputs, the result will be -18dB.
+ {tuple([Gain(-1) for _ in range(24)]), tuple([Gain(-1) for _ in range(24)])},
+ ]
+ )
+ output = pb(_input, sr)
+ np.testing.assert_allclose(_input * 0.5, output, rtol=0.01)
+
+
+def test_nesting_pedalboards():
+ sr = 44100
+ _input = np.random.rand(int(NUM_SECONDS * sr), 2).astype(np.float32)
+
+ pb = Pedalboard(
+ [
+ # This parallel chain should boost by 6dB, but due to
+ # there being 2 outputs, the result will be +12dB.
+ {Pedalboard([Gain(1) for _ in range(6)]), Pedalboard([Gain(1) for _ in range(6)])},
+ # This parallel chain should cut by -24dB, but due to
+ # there being 2 outputs, the result will be -18dB.
+ {Pedalboard([Gain(-1) for _ in range(24)]), Pedalboard([Gain(-1) for _ in range(24)])},
+ ]
+ )
+ output = pb(_input, sr)
+ np.testing.assert_allclose(_input * 0.5, output, rtol=0.01)
+
+
+def test_chain_latency_compensation():
+ sr = 44100
+ _input = np.random.rand(int(NUM_SECONDS * sr), 2).astype(np.float32)
+
+ pb = Pedalboard(
+ [
+ # This parallel chain should boost by 6dB, but due to
+ # there being 2 outputs, the result will be +12dB.
+ {tuple([Gain(1) for _ in range(6)]), tuple([Gain(1) for _ in range(6)])},
+ # This parallel chain should cut by -24dB, but due to
+ # there being 2 outputs, the result will be -18dB.
+ {tuple([Gain(-1) for _ in range(24)]), tuple([Gain(-1) for _ in range(24)])},
+ ]
+ )
+ output = pb(_input, sr)
+ np.testing.assert_allclose(_input * 0.5, output, rtol=0.01)
+
+
[email protected]("sample_rate", [22050, 44100, 48000])
[email protected]("buffer_size", [128, 8192, 22050, 65536])
[email protected]("latency_a_seconds", [0.25, 1, NUM_SECONDS / 2])
[email protected]("latency_b_seconds", [0.25, 1, NUM_SECONDS / 2])
+def test_mix_latency_compensation(sample_rate, buffer_size, latency_a_seconds, latency_b_seconds):
+ noise = np.random.rand(int(NUM_SECONDS * sample_rate))
+ pb = Pedalboard(
+ [
+ {
+ AddLatency(int(latency_a_seconds * sample_rate)),
+ AddLatency(int(latency_b_seconds * sample_rate)),
+ },
+ ]
+ )
+ output = pb(noise, sample_rate, buffer_size=buffer_size)
+
+ # * 2 here as the mix plugin mixes each plugin at 100% by default
+ np.testing.assert_allclose(output, noise * 2, rtol=0.01)
+
+
[email protected]("sample_rate", [22050, 44100, 48000])
[email protected]("buffer_size", [128, 8192, 65536])
[email protected]("latency_a_seconds", [0.25, 1, 2, 10])
[email protected]("latency_b_seconds", [0.25, 1, 2, 10])
+def test_chain_latency_compensation(sample_rate, buffer_size, latency_a_seconds, latency_b_seconds):
+ noise = np.random.rand(int(NUM_SECONDS * sample_rate))
+ pb = Pedalboard(
+ [
+ [
+ AddLatency(int(latency_a_seconds * sample_rate)),
+ AddLatency(int(latency_b_seconds * sample_rate)),
+ ],
+ [
+ AddLatency(int(latency_a_seconds * sample_rate)),
+ AddLatency(int(latency_b_seconds * sample_rate)),
+ ],
+ ]
+ )
+ output = pb(noise, sample_rate, buffer_size=buffer_size)
+ np.testing.assert_allclose(output, noise, rtol=0.01)
+
+
[email protected]("sample_rate", [22050, 44100, 48000])
[email protected]("buffer_size", [128, 8192, 65536])
+def test_readme_example_does_not_crash(sample_rate, buffer_size):
+ noise = np.random.rand(int(NUM_SECONDS * sample_rate))
+
+ passthrough = Gain(gain_db=0)
+
+ delay_and_pitch_shift = Pedalboard(
+ [
+ Delay(delay_seconds=0.25, mix=1.0),
+ PitchShift(semitones=7),
+ Gain(gain_db=-3),
+ ]
+ )
+
+ delay_longer_and_more_pitch_shift = Pedalboard(
+ [
+ Delay(delay_seconds=0.25, mix=1.0),
+ PitchShift(semitones=12),
+ Gain(gain_db=-6),
+ ]
+ )
+
+ original_plus_delayed_harmonies = Pedalboard(
+ {passthrough, delay_and_pitch_shift, delay_longer_and_more_pitch_shift}
+ )
+ # TODO: Allow passing a Pedalboard into Mix (which will require Pedalboard to be a subclass of Plugin)
+ original_plus_delayed_harmonies(noise, sample_rate=sample_rate, buffer_size=buffer_size)
+
+ # or mix and match in more complex ways:
+ original_plus_delayed_harmonies = Pedalboard([
+ # Put a compressor at the front of the chain:
+ Compressor(),
+ # Split the chain and mix three different effects equally:
+ {
+ (passthrough, Distortion(drive_db=36)),
+ (delay_and_pitch_shift, Reverb(room_size=1)),
+ delay_longer_and_more_pitch_shift
+ },
+ # Add a reverb on the final mix:
+ Reverb()
+ ])
+ original_plus_delayed_harmonies(noise, sample_rate=sample_rate, buffer_size=buffer_size)
\ No newline at end of file