Skip to content

🎛 🔊 A Python library for audio.

Change inheritance hierarchy to make Pedalboard instances Plugins.

Peter Sobotd7d0748e1f9e
diff --git a/README.md b/README.md
index d3fee27..dc43da4 100644
--- a/README.md
+++ b/README.md
@@ -90,25 +90,35 @@ to the next in an undesired fashion, try:
## Examples
-A very basic example of how to use `pedalboard`'s built-in plugins:
+### Quick Start
```python
import soundfile as sf
-from pedalboard import (
- Pedalboard,
- Convolution,
- Compressor,
- Chorus,
- Gain,
- Reverb,
- Limiter,
- LadderFilter,
- Phaser,
-)
+from pedalboard import Pedalboard, Chorus, Reverb
+# Read in an audio file:
audio, sample_rate = sf.read('some-file.wav')
# Make a Pedalboard object, containing multiple plugins:
+board = Pedalboard([Chorus(), Reverb(room_size=0.25)])
+
+# Run the audio through this pedalboard!
+effected = board(audio, s)
+
+# Write the audio back as a wav file:
+sf.write('./processed-output.wav', effected, sample_rate)
+```
+
+### Making a guitar-style pedalboard
+
+```python
+import soundfile as sf
+# Don't do import *! (It just makes this example smaller)
+from pedalboard import *
+
+audio, sample_rate = sf.read('./guitar-input.wav')
+
+# Make a pretty interesting sounding guitar pedalboard:
board = Pedalboard([
Compressor(threshold_db=-50, ratio=25),
Gain(gain_db=30),
@@ -117,46 +127,38 @@ board = Pedalboard([
Phaser(),
Convolution("./guitar_amp.wav", 1.0),
Reverb(room_size=0.25),
-], sample_rate=sample_rate)
+])
# Pedalboard objects behave like lists, so you can add plugins:
board.append(Compressor(threshold_db=-25, ratio=10))
board.append(Gain(gain_db=10))
board.append(Limiter())
+# ... or change parameters easily:
+board[0].threshold_db = -40
+
# Run the audio through this pedalboard!
-effected = board(audio)
+effected = board(audio, sample_rate)
# Write the audio back as a wav file:
-with sf.SoundFile('./processed-output-stereo.wav', 'w', samplerate=sample_rate, channels=len(effected.shape)) as f:
- f.write(effected)
-
+sf.write('./guitar-output.wav', effected, sample_rate)
```
-### Loading a VST3® plugin and manipulating its parameters
+### Using VST3® or Audio Unit plugins
```python
import soundfile as sf
from pedalboard import Pedalboard, Reverb, load_plugin
-# Load a VST3 package from a known path on disk:
+# Load a VST3 or Audio Unit plugin from a known path on disk:
vst = load_plugin("./VSTs/RoughRider3.vst3")
print(vst.parameters.keys())
# dict_keys([
-# 'sc_hpf_hz',
-# 'input_lvl_db',
-# 'sensitivity_db',
-# 'ratio',
-# 'attack_ms',
-# 'release_ms',
-# 'makeup_db',
-# 'mix',
-# 'output_lvl_db',
-# 'sc_active',
-# 'full_bandwidth',
-# 'bypass',
-# 'program',
+# 'sc_hpf_hz', 'input_lvl_db', 'sensitivity_db',
+# 'ratio', 'attack_ms', 'release_ms', 'makeup_db',
+# 'mix', 'output_lvl_db', 'sc_active',
+# 'full_bandwidth', 'bypass', 'program',
# ])
# Set the "ratio" parameter to 15
@@ -164,12 +166,53 @@ vst.ratio = 15
# Use this VST to process some audio:
audio, sample_rate = sf.read('some-file.wav')
-effected = vst(audio, sample_rate=sample_rate)
+effected = vst(audio, sample_rate)
# ...or put this VST into a chain with other plugins:
-board = Pedalboard([vst, Reverb()], sample_rate=sample_rate)
+board = Pedalboard([vst, Reverb()])
# ...and run that pedalboard with the same VST instance!
-effected = board(audio)
+effected = board(audio, sample_rate)
+```
+
+### Creating parallel effects chains
+
+This example creates a delayed pitch-shift effect by running
+multiple Pedalboards in parallel on the same audio. `Pedalboard`
+objects are themselves `Plugin` objects, so you can nest them
+as much as you like:
+
+```python
+import soundfile as sf
+from pedalboard import \
+ Pedalboard, Compressor, Delay, Distortion, \
+ Gain, PitchShift, Reverb, Mix
+
+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),
+])
+
+board = Pedalboard([
+ # Put a compressor at the front of the chain:
+ Compressor(),
+ # Run all of these pedalboards simultaneously with the Mix plugin:
+ Mix([
+ passthrough,
+ delay_and_pitch_shift,
+ delay_longer_and_more_pitch_shift,
+ ]),
+ # Add a reverb on the final mix:
+ Reverb()
+])
```
For more examples, see:
diff --git a/pedalboard/ExternalPlugin.h b/pedalboard/ExternalPlugin.h
index 5344bb7..c8e5cd3 100644
--- a/pedalboard/ExternalPlugin.h
+++ b/pedalboard/ExternalPlugin.h
@@ -801,7 +801,8 @@ inline void init_external_plugins(py::module &m) {
"Returns the current value of the parameter as a string.");
#if JUCE_PLUGINHOST_VST3 && (JUCE_MAC || JUCE_WINDOWS || JUCE_LINUX)
- py::class_<ExternalPlugin<juce::VST3PluginFormat>, Plugin>(
+ py::class_<ExternalPlugin<juce::VST3PluginFormat>, Plugin,
+ std::shared_ptr<ExternalPlugin<juce::VST3PluginFormat>>>(
m, "_VST3Plugin",
"A wrapper around any Steinberg® VST3 audio effect plugin. Note that "
"plugins must already support the operating system currently in use "
@@ -842,7 +843,8 @@ inline void init_external_plugins(py::module &m) {
#endif
#if JUCE_PLUGINHOST_AU && JUCE_MAC
- py::class_<ExternalPlugin<juce::AudioUnitPluginFormat>, Plugin>(
+ py::class_<ExternalPlugin<juce::AudioUnitPluginFormat>, Plugin,
+ std::shared_ptr<ExternalPlugin<juce::AudioUnitPluginFormat>>>(
m, "_AudioUnitPlugin",
"A wrapper around any Apple Audio Unit audio effect plugin. Only "
"available on macOS.",
diff --git a/pedalboard/Plugin.h b/pedalboard/Plugin.h
index 5b3d206..9ad7d7d 100644
--- a/pedalboard/Plugin.h
+++ b/pedalboard/Plugin.h
@@ -20,6 +20,8 @@
#include "JuceHeader.h"
#include <mutex>
+static constexpr int DEFAULT_BUFFER_SIZE = 8192;
+
namespace Pedalboard {
/**
* A base class for all Pedalboard plugins, JUCE-derived or external.
@@ -70,12 +72,6 @@ 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/PluginContainer.h b/pedalboard/PluginContainer.h
new file mode 100644
index 0000000..fcc750a
--- /dev/null
+++ b/pedalboard/PluginContainer.h
@@ -0,0 +1,128 @@
+/*
+ * 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 for all Pedalboard plugins that contain one or more other plugins.
+ */
+class PluginContainer : public Plugin {
+public:
+ PluginContainer(std::vector<std::shared_ptr<Plugin>> plugins)
+ : plugins(plugins) {}
+ virtual ~PluginContainer(){};
+
+ std::vector<std::shared_ptr<Plugin>> &getPlugins() { return plugins; }
+
+ /*
+ * Get a flat list of all of the plugins contained
+ * by this plugin, not including itself.
+ */
+ std::vector<std::shared_ptr<Plugin>> getAllPlugins() {
+ std::vector<std::shared_ptr<Plugin>> flatList;
+ for (auto plugin : plugins) {
+ flatList.push_back(plugin);
+ if (auto *pluginContainer =
+ dynamic_cast<PluginContainer *>(plugin.get())) {
+ auto children = pluginContainer->getAllPlugins();
+ flatList.insert(flatList.end(), children.begin(), children.end());
+ }
+ }
+ return flatList;
+ }
+
+protected:
+ std::vector<std::shared_ptr<Plugin>> plugins;
+};
+
+inline void init_plugin_container(py::module &m) {
+ py::class_<PluginContainer, Plugin, std::shared_ptr<PluginContainer>>(
+ m, "PluginContainer",
+ "A generic audio processing plugin that contains zero or more other "
+ "plugins. Not intended for direct use.")
+ .def(py::init([](std::vector<std::shared_ptr<Plugin>> plugins) {
+ throw py::type_error(
+ "PluginContainer is an abstract base class - don't instantiate "
+ "this directly, use its subclasses instead.");
+ // This will never be hit, but is required to provide a non-void
+ // type to return from this lambda or else the compiler can't do
+ // type inference.
+ return nullptr;
+ }))
+ // Implement the Sequence protocol:
+ .def("__getitem__",
+ [](PluginContainer &s, size_t i) {
+ if (i >= s.getPlugins().size())
+ throw py::index_error("index out of range");
+ return s.getPlugins()[i];
+ })
+ .def("__setitem__",
+ [](PluginContainer &s, size_t i, std::shared_ptr<Plugin> plugin) {
+ if (i >= s.getPlugins().size())
+ throw py::index_error("index out of range");
+ s.getPlugins()[i] = plugin;
+ })
+ .def("__delitem__",
+ [](PluginContainer &s, size_t i) {
+ if (i >= s.getPlugins().size())
+ throw py::index_error("index out of range");
+ auto &plugins = s.getPlugins();
+ plugins.erase(plugins.begin() + i);
+ })
+ .def("__len__", [](PluginContainer &s) { return s.getPlugins().size(); })
+ .def("insert",
+ [](PluginContainer &s, int i, std::shared_ptr<Plugin> plugin) {
+ if (i > s.getPlugins().size())
+ throw py::index_error("index out of range");
+ auto &plugins = s.getPlugins();
+ plugins.insert(plugins.begin() + i, plugin);
+ })
+ .def("append",
+ [](PluginContainer &s, std::shared_ptr<Plugin> plugin) {
+ s.getPlugins().push_back(plugin);
+ })
+ .def("remove",
+ [](PluginContainer &s, std::shared_ptr<Plugin> plugin) {
+ auto &plugins = s.getPlugins();
+ auto position = std::find(plugins.begin(), plugins.end(), plugin);
+ if (position == plugins.end())
+ throw py::value_error("remove(x): x not in list");
+ plugins.erase(position);
+ })
+ .def(
+ "__iter__",
+ [](PluginContainer &s) {
+ return py::make_iterator(s.getPlugins().begin(),
+ s.getPlugins().end());
+ },
+ py::keep_alive<0, 1>())
+ .def("__contains__",
+ [](PluginContainer &s, std::shared_ptr<Plugin> plugin) {
+ auto &plugins = s.getPlugins();
+ return std::find(plugins.begin(), plugins.end(), plugin) !=
+ plugins.end();
+ });
+}
+
+} // namespace Pedalboard
\ No newline at end of file
diff --git a/pedalboard/pedalboard.py b/pedalboard/pedalboard.py
index 263589e..e31bfa7 100644
--- a/pedalboard/pedalboard.py
+++ b/pedalboard/pedalboard.py
@@ -95,116 +95,19 @@ def _flatten_all_plugins(_input: Optional[PedalboardDefinition]) -> List[Plugin]
return []
-class Pedalboard(collections.abc.MutableSequence):
+class Pedalboard(Chain):
"""
A container for a chain of plugins, to use for processing audio.
"""
- 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.")
- self.sample_rate = sample_rate
+ def __init__(self, plugins: Optional[PedalboardDefinition] = None):
+ plugins = _coalesce_plugin_definitions(plugins)
+ if not isinstance(plugins, list):
+ plugins = [plugins]
+ super().__init__(plugins)
def __repr__(self) -> str:
- return "<{} plugins={} sample_rate={}>".format(
- self.__class__.__name__, repr(self.plugins), repr(self.sample_rate)
- )
-
- def __len__(self) -> int:
- return len(self.plugins)
-
- def __delitem__(self, index: int) -> None:
- self.plugins.__delitem__(index)
-
- def insert(self, index: int, value: Optional[Plugin]) -> None:
- if value is not None:
- if not isinstance(value, Plugin):
- raise TypeError(
- "An object of type {} cannot be inserted into a {}.".format(
- type(value), self.__class__.__name__
- )
- )
- if value in self.plugins:
- raise ValueError(
- "The provided plugin object ({}) already exists in this {}. Please"
- " create unique instances if the same effect is required multiple times in"
- " series.".format(value, self.__class__.__name__)
- )
- self.plugins.insert(index, value)
-
- def __setitem__(self, index: int, value: Optional[Plugin]) -> None:
- if value is not None:
- if not isinstance(value, Plugin):
- raise TypeError(
- "An object of type {} cannot be added into a {}.".format(
- type(value), self.__class__.__name__
- )
- )
- if self.plugins.count(value) == 1 and self.plugins.index(value) != index:
- raise ValueError(
- "The provided plugin object ({}) already exists in this {} at index {}. Please"
- " create unique instances if the same effect is required multiple times in"
- " series.".format(value, self.__class__.__name__, self.plugins.index(value))
- )
- self.plugins.__setitem__(index, value)
-
- def __getitem__(self, index: int) -> Optional[Plugin]:
- return self.plugins.__getitem__(index)
-
- def reset(self):
- """
- Clear any internal state (e.g.: reverb tails) kept by all of the plugins in this
- Pedalboard. The values of plugin parameters will remain unchanged. For most plugins,
- this is a fast operation; for some, this will cause a full re-instantiation of the plugin.
- """
- for plugin in self.plugins:
- plugin.reset()
-
- def process(
- self,
- audio: np.ndarray,
- sample_rate: Optional[float] = None,
- buffer_size: Optional[int] = None,
- reset: bool = True,
- ) -> np.ndarray:
- 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.")
- if buffer_size is not None:
- if not isinstance(buffer_size, (int, float)):
- raise TypeError("buffer_size must be None, an integer, or a floating-point number.")
- buffer_size = int(buffer_size)
-
- effective_sample_rate = sample_rate or self.sample_rate
- if effective_sample_rate is None:
- raise ValueError(
- (
- "No sample rate available. `sample_rate` must be provided to either the {}"
- " constructor or as an argument to `process`."
- ).format(self.__class__.__name__)
- )
-
- # pyBind11 makes a copy of self.plugins when passing it into process.
- kwargs = {"sample_rate": effective_sample_rate, "plugins": self.plugins, "reset": reset}
- if buffer_size:
- kwargs["buffer_size"] = buffer_size
- return process(audio, **kwargs)
-
- # Alias process to __call__, so that people can call Pedalboards like functions.
- __call__ = process
+ return "<{} plugins={}>".format(self.__class__.__name__, list(self))
FLOAT_SUFFIXES_TO_IGNORE = set(["x", "%", "*", ",", ".", "hz"])
diff --git a/pedalboard/plugins/AddLatency.h b/pedalboard/plugins/AddLatency.h
index e2101c5..3a438e9 100644
--- a/pedalboard/plugins/AddLatency.h
+++ b/pedalboard/plugins/AddLatency.h
@@ -50,7 +50,7 @@ private:
};
inline void init_add_latency(py::module &m) {
- py::class_<AddLatency, Plugin>(
+ py::class_<AddLatency, Plugin, std::shared_ptr<AddLatency>>(
m, "AddLatency",
"A dummy plugin that delays input audio for the given number of samples "
"before passing it back to the output. Used internally to test "
diff --git a/pedalboard/plugins/Chain.h b/pedalboard/plugins/Chain.h
index 90e04d5..33c1080 100644
--- a/pedalboard/plugins/Chain.h
+++ b/pedalboard/plugins/Chain.h
@@ -20,16 +20,17 @@
#include "../JuceHeader.h"
#include <mutex>
-#include "../Plugin.h"
+#include "../PluginContainer.h"
#include "../process.h"
namespace Pedalboard {
/**
* A class that allows nesting a list of plugins within another.
*/
-class Chain : public Plugin {
+class Chain : public PluginContainer {
public:
- Chain(std::vector<Plugin *> plugins) : plugins(plugins) {}
+ Chain(std::vector<std::shared_ptr<Plugin>> plugins)
+ : PluginContainer(plugins) {}
virtual ~Chain(){};
virtual void prepare(const juce::dsp::ProcessSpec &spec) {
@@ -65,34 +66,30 @@ public:
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) {
+ py::class_<Chain, PluginContainer, std::shared_ptr<Chain>>(
+ m, "Chain",
+ "Run zero or more plugins as a plugin. Useful when "
+ "used with the Mix plugin.")
+ .def(py::init([](std::vector<std::shared_ptr<Plugin>> plugins) {
return new Chain(plugins);
}),
- py::arg("plugins"), py::keep_alive<1, 2>())
+ py::arg("plugins"))
.def("__repr__",
- [](const Chain &plugin) {
+ [](Chain &plugin) {
std::ostringstream ss;
- ss << "<pedalboard.Chain with " << plugin.getNestedPlugins().size()
+ ss << "<pedalboard.Chain with " << plugin.getPlugins().size()
<< " plugin";
- if (plugin.getNestedPlugins().size() != 1) {
+ if (plugin.getPlugins().size() != 1) {
ss << "s";
}
ss << ": [";
- for (int i = 0; i < plugin.getNestedPlugins().size(); i++) {
- py::object nestedPlugin = py::cast(plugin.getNestedPlugins()[i]);
+ for (int i = 0; i < plugin.getPlugins().size(); i++) {
+ py::object nestedPlugin = py::cast(plugin.getPlugins()[i]);
ss << nestedPlugin.attr("__repr__")();
- if (i < plugin.getNestedPlugins().size() - 1) {
+ if (i < plugin.getPlugins().size() - 1) {
ss << ", ";
}
}
@@ -100,7 +97,38 @@ inline void init_chain(py::module &m) {
ss << ">";
return ss.str();
})
- .def_property_readonly("plugins", &Chain::getNestedPlugins);
+ // If calling process() directly on Chain, pass the plugins immediately to
+ // process() itself, as that will result in slightly faster performance.
+ .def(
+ "process",
+ [](std::shared_ptr<Chain> self,
+ const py::array_t<float, py::array::c_style> inputArray,
+ double sampleRate, unsigned int bufferSize, bool reset) {
+ return process(inputArray, sampleRate, self->getPlugins(), bufferSize, reset);
+ },
+ "Run a 32-bit floating point audio buffer through this plugin."
+ "(Note: if calling this multiple times with multiple plugins, "
+ "consider using pedalboard.process(...) instead.)",
+ py::arg("input_array"), py::arg("sample_rate"),
+ py::arg("buffer_size") = DEFAULT_BUFFER_SIZE, py::arg("reset") = true)
+
+ .def(
+ "process",
+ [](std::shared_ptr<Chain> self,
+ const py::array_t<double, py::array::c_style> inputArray,
+ double sampleRate, unsigned int bufferSize, bool reset) {
+ const py::array_t<float, py::array::c_style> float32InputArray =
+ inputArray.attr("astype")("float32");
+ return process(float32InputArray, sampleRate, self->getPlugins(), bufferSize,
+ reset);
+ },
+ "Run a 64-bit floating point audio buffer through this plugin."
+ "(Note: if calling this multiple times with multiple plugins, "
+ "consider using pedalboard.process(...) instead.) The buffer "
+ "will be converted to 32-bit for processing.",
+ py::arg("input_array"), py::arg("sample_rate"),
+ py::arg("buffer_size") = DEFAULT_BUFFER_SIZE,
+ py::arg("reset") = true);
}
} // namespace Pedalboard
\ No newline at end of file
diff --git a/pedalboard/plugins/Chorus.h b/pedalboard/plugins/Chorus.h
index bee7438..9ccd8f5 100644
--- a/pedalboard/plugins/Chorus.h
+++ b/pedalboard/plugins/Chorus.h
@@ -37,7 +37,7 @@ class Chorus : public JucePlugin<juce::dsp::Chorus<SampleType>> {
};
inline void init_chorus(py::module &m) {
- py::class_<Chorus<float>, Plugin>(
+ py::class_<Chorus<float>, Plugin, std::shared_ptr<Chorus<float>>>(
m, "Chorus",
"A basic chorus effect. This audio effect can be controlled via the "
"speed and depth of the LFO controlling the frequency response, a mix "
diff --git a/pedalboard/plugins/Compressor.h b/pedalboard/plugins/Compressor.h
index 41ccb63..46aec96 100644
--- a/pedalboard/plugins/Compressor.h
+++ b/pedalboard/plugins/Compressor.h
@@ -36,7 +36,7 @@ class Compressor : public JucePlugin<juce::dsp::Compressor<SampleType>> {
};
inline void init_compressor(py::module &m) {
- py::class_<Compressor<float>, Plugin>(
+ py::class_<Compressor<float>, Plugin, std::shared_ptr<Compressor<float>>>(
m, "Compressor",
"A dynamic range compressor, used to amplify quiet sounds and reduce the "
"volume of loud sounds.")
diff --git a/pedalboard/plugins/Convolution.h b/pedalboard/plugins/Convolution.h
index b9994d1..2f3daef 100644
--- a/pedalboard/plugins/Convolution.h
+++ b/pedalboard/plugins/Convolution.h
@@ -78,7 +78,7 @@ private:
};
inline void init_convolution(py::module &m) {
- py::class_<JucePlugin<ConvolutionWithMix>, Plugin>(
+ py::class_<JucePlugin<ConvolutionWithMix>, Plugin, std::shared_ptr<JucePlugin<ConvolutionWithMix>>>(
m, "Convolution",
"An audio convolution, suitable for things like speaker simulation or "
"reverb modeling.")
diff --git a/pedalboard/plugins/Delay.h b/pedalboard/plugins/Delay.h
index 6b25162..f8010d7 100644
--- a/pedalboard/plugins/Delay.h
+++ b/pedalboard/plugins/Delay.h
@@ -100,7 +100,7 @@ private:
};
inline void init_delay(py::module &m) {
- py::class_<Delay<float>, Plugin>(
+ py::class_<Delay<float>, Plugin, std::shared_ptr<Delay<float>>>(
m, "Delay",
"A digital delay plugin with controllable delay time, feedback "
"percentage, and dry/wet mix.")
diff --git a/pedalboard/plugins/Distortion.h b/pedalboard/plugins/Distortion.h
index 9f22bc9..fb9b5a6 100644
--- a/pedalboard/plugins/Distortion.h
+++ b/pedalboard/plugins/Distortion.h
@@ -48,7 +48,7 @@ private:
};
inline void init_distortion(py::module &m) {
- py::class_<Distortion<float>, Plugin>(
+ py::class_<Distortion<float>, Plugin, std::shared_ptr<Distortion<float>>>(
m, "Distortion", "Apply soft distortion with a tanh waveshaper.")
.def(py::init([](float drive_db) {
auto plugin = std::make_unique<Distortion<float>>();
diff --git a/pedalboard/plugins/Gain.h b/pedalboard/plugins/Gain.h
index 079fdff..13fb864 100644
--- a/pedalboard/plugins/Gain.h
+++ b/pedalboard/plugins/Gain.h
@@ -29,7 +29,7 @@ class Gain : public JucePlugin<juce::dsp::Gain<SampleType>> {
};
inline void init_gain(py::module &m) {
- py::class_<Gain<float>, Plugin>(
+ py::class_<Gain<float>, Plugin, std::shared_ptr<Gain<float>>>(
m, "Gain",
"Increase or decrease the volume of a signal by applying a gain value "
"(in decibels). No distortion or other effects are applied.")
diff --git a/pedalboard/plugins/HighpassFilter.h b/pedalboard/plugins/HighpassFilter.h
index 6065f2e..d6298b9 100644
--- a/pedalboard/plugins/HighpassFilter.h
+++ b/pedalboard/plugins/HighpassFilter.h
@@ -41,7 +41,7 @@ private:
};
inline void init_highpass(py::module &m) {
- py::class_<HighpassFilter<float>, Plugin>(
+ py::class_<HighpassFilter<float>, Plugin, std::shared_ptr<HighpassFilter<float>>>(
m, "HighpassFilter",
"Apply a first-order high-pass filter with a roll-off of 6dB/octave. "
"The cutoff frequency will be attenuated by -3dB (i.e.: 0.707x as "
diff --git a/pedalboard/plugins/LadderFilter.h b/pedalboard/plugins/LadderFilter.h
index 8ac610a..ccc773a 100644
--- a/pedalboard/plugins/LadderFilter.h
+++ b/pedalboard/plugins/LadderFilter.h
@@ -58,7 +58,7 @@ class LadderFilter : public JucePlugin<juce::dsp::LadderFilter<SampleType>> {
};
inline void init_ladderfilter(py::module &m) {
- py::class_<LadderFilter<float>, Plugin> ladderFilter(
+ py::class_<LadderFilter<float>, Plugin, std::shared_ptr<LadderFilter<float>>> ladderFilter(
m, "LadderFilter",
"Multi-mode audio filter based on the classic Moog synthesizer ladder "
"filter.");
diff --git a/pedalboard/plugins/Limiter.h b/pedalboard/plugins/Limiter.h
index e722912..d4047c1 100644
--- a/pedalboard/plugins/Limiter.h
+++ b/pedalboard/plugins/Limiter.h
@@ -30,7 +30,7 @@ class Limiter : public JucePlugin<juce::dsp::Limiter<SampleType>> {
};
inline void init_limiter(py::module &m) {
- py::class_<Limiter<float>, Plugin>(
+ py::class_<Limiter<float>, Plugin, std::shared_ptr<Limiter<float>>>(
m, "Limiter",
"A simple limiter with standard threshold and release time controls, "
"featuring two compressors and a hard clipper at 0 dB.")
diff --git a/pedalboard/plugins/LowpassFilter.h b/pedalboard/plugins/LowpassFilter.h
index d22afa1..090ccc5 100644
--- a/pedalboard/plugins/LowpassFilter.h
+++ b/pedalboard/plugins/LowpassFilter.h
@@ -41,7 +41,7 @@ private:
};
inline void init_lowpass(py::module &m) {
- py::class_<LowpassFilter<float>, Plugin>(
+ py::class_<LowpassFilter<float>, Plugin, std::shared_ptr<LowpassFilter<float>>>(
m, "LowpassFilter",
"Apply a first-order low-pass filter with a roll-off of 6dB/octave. "
"The cutoff frequency will be attenuated by -3dB (i.e.: 0.707x as "
diff --git a/pedalboard/plugins/Mix.h b/pedalboard/plugins/Mix.h
index ab9dd82..40e828b 100644
--- a/pedalboard/plugins/Mix.h
+++ b/pedalboard/plugins/Mix.h
@@ -20,17 +20,17 @@
#include "../JuceHeader.h"
#include <mutex>
-#include "../Plugin.h"
+#include "../PluginContainer.h"
namespace Pedalboard {
/**
* A class that allows parallel processing of zero or more separate plugin
* chains.
*/
-class Mix : public Plugin {
+class Mix : public PluginContainer {
public:
- Mix(std::vector<Plugin *> plugins)
- : plugins(plugins), pluginBuffers(plugins.size()),
+ Mix(std::vector<std::shared_ptr<Plugin>> plugins)
+ : PluginContainer(plugins), pluginBuffers(plugins.size()),
samplesAvailablePerPlugin(plugins.size()) {}
virtual ~Mix(){};
@@ -51,7 +51,7 @@ public:
auto ioBlock = context.getOutputBlock();
for (int i = 0; i < plugins.size(); i++) {
- Plugin *plugin = plugins[i];
+ std::shared_ptr<Plugin> plugin = plugins[i];
juce::AudioBuffer<float> &buffer = pluginBuffers[i];
int startInBuffer = samplesAvailablePerPlugin[i];
@@ -66,7 +66,7 @@ public:
context.getInputBlock().copyTo(buffer, 0, samplesAvailablePerPlugin[i]);
float **channelPointers =
- (float **)alloca(ioBlock.getNumChannels() * sizeof(float *));
+ (float **)alloca(ioBlock.getNumChannels() * sizeof(float *));
for (int c = 0; c < buffer.getNumChannels(); c++) {
channelPointers[c] = buffer.getWritePointer(c, startInBuffer);
}
@@ -125,7 +125,7 @@ public:
// Shift the remaining samples to the start of the buffer:
std::memmove(channelBuffer, channelBuffer + samplesToDelete,
- sizeof(float) * samplesRemaining);
+ sizeof(float) * samplesRemaining);
}
samplesAvailablePerPlugin[i] -= samplesToDelete;
}
@@ -148,44 +148,38 @@ public:
return maxHint;
}
- virtual std::vector<Plugin *> getNestedPlugins() const override {
- return plugins;
- }
-
protected:
std::vector<juce::AudioBuffer<float>> pluginBuffers;
- std::vector<Plugin *> plugins;
std::vector<int> samplesAvailablePerPlugin;
};
inline void init_mix(py::module &m) {
- py::class_<Mix, Plugin>(
+ py::class_<Mix, PluginContainer, std::shared_ptr<Mix>>(
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);
+ .def(py::init([](std::vector<std::shared_ptr<Plugin>> plugins) {
+ return new Mix(plugins);
+ }),
+ py::arg("plugins"))
+ .def("__repr__", [](Mix &plugin) {
+ std::ostringstream ss;
+ ss << "<pedalboard.Mix with " << plugin.getPlugins().size()
+ << " plugin";
+ if (plugin.getPlugins().size() != 1) {
+ ss << "s";
+ }
+ ss << ": [";
+ for (int i = 0; i < plugin.getPlugins().size(); i++) {
+ py::object nestedPlugin = py::cast(plugin.getPlugins()[i]);
+ ss << nestedPlugin.attr("__repr__")();
+ if (i < plugin.getPlugins().size() - 1) {
+ ss << ", ";
+ }
+ }
+ ss << "] at " << &plugin;
+ ss << ">";
+ return ss.str();
+ });
}
} // namespace Pedalboard
\ No newline at end of file
diff --git a/pedalboard/plugins/NoiseGate.h b/pedalboard/plugins/NoiseGate.h
index e849273..da1bb4e 100644
--- a/pedalboard/plugins/NoiseGate.h
+++ b/pedalboard/plugins/NoiseGate.h
@@ -33,7 +33,7 @@ class NoiseGate : public JucePlugin<juce::dsp::NoiseGate<SampleType>> {
inline void init_noisegate(py::module &m) {
- py::class_<NoiseGate<float>, Plugin>(
+ py::class_<NoiseGate<float>, Plugin, std::shared_ptr<NoiseGate<float>>>(
m, "NoiseGate",
"A simple noise gate with standard threshold, ratio, attack time and "
"release time controls. Can be used as an expander if the ratio is low.")
diff --git a/pedalboard/plugins/Phaser.h b/pedalboard/plugins/Phaser.h
index c65226f..c9181a3 100644
--- a/pedalboard/plugins/Phaser.h
+++ b/pedalboard/plugins/Phaser.h
@@ -34,7 +34,7 @@ class Phaser : public JucePlugin<juce::dsp::Phaser<SampleType>> {
inline void init_phaser(py::module &m) {
- py::class_<Phaser<float>, Plugin>(
+ py::class_<Phaser<float>, Plugin, std::shared_ptr<Phaser<float>>>(
m, "Phaser",
"A 6 stage phaser that modulates first order all-pass filters to create "
"sweeping notches in the magnitude frequency response. This audio effect "
diff --git a/pedalboard/plugins/PitchShift.h b/pedalboard/plugins/PitchShift.h
index ed97e0d..74e7191 100644
--- a/pedalboard/plugins/PitchShift.h
+++ b/pedalboard/plugins/PitchShift.h
@@ -61,7 +61,7 @@ public:
};
inline void init_pitch_shift(py::module &m) {
- py::class_<PitchShift, Plugin>(
+ py::class_<PitchShift, Plugin, std::shared_ptr<PitchShift>>(
m, "PitchShift", "Shift pitch without affecting audio duration.")
.def(py::init([](double scale) {
auto plugin = std::make_unique<PitchShift>();
diff --git a/pedalboard/plugins/Reverb.h b/pedalboard/plugins/Reverb.h
index be735be..8d51722 100644
--- a/pedalboard/plugins/Reverb.h
+++ b/pedalboard/plugins/Reverb.h
@@ -77,7 +77,7 @@ public:
};
inline void init_reverb(py::module &m) {
- py::class_<Reverb, Plugin>(
+ py::class_<Reverb, Plugin, std::shared_ptr<Reverb>>(
m, "Reverb",
"Performs a simple reverb effect on a stream of audio data. This is a "
"simple stereo reverb, based on the technique and tunings used in "
diff --git a/pedalboard/process.h b/pedalboard/process.h
index 69aac96..4058eba 100644
--- a/pedalboard/process.h
+++ b/pedalboard/process.h
@@ -37,7 +37,7 @@ enum class ChannelLayout {
template <typename SampleType>
py::array_t<float>
process(const py::array_t<SampleType, py::array::c_style> inputArray,
- double sampleRate, const std::vector<Plugin *> &plugins,
+ double sampleRate, const std::vector<std::shared_ptr<Plugin>> plugins,
unsigned int bufferSize, bool reset) {
const py::array_t<float, py::array::c_style> float32InputArray =
inputArray.attr("astype")("float32");
@@ -50,9 +50,9 @@ process(const py::array_t<SampleType, py::array::c_style> inputArray,
template <typename SampleType>
py::array_t<float>
processSingle(const py::array_t<SampleType, py::array::c_style> inputArray,
- double sampleRate, Plugin &plugin, unsigned int bufferSize,
- bool reset) {
- std::vector<Plugin *> plugins{&plugin};
+ double sampleRate, std::shared_ptr<Plugin> plugin,
+ unsigned int bufferSize, bool reset) {
+ std::vector<std::shared_ptr<Plugin>> plugins{plugin};
return process<SampleType>(inputArray, sampleRate, plugins, bufferSize,
reset);
}
@@ -205,13 +205,13 @@ py::array_t<T> copyJuceBufferIntoPyArray(const juce::AudioBuffer<T> juceBuffer,
inline int process(juce::AudioBuffer<float> &ioBuffer,
juce::dsp::ProcessSpec spec,
- const std::vector<Plugin *> &plugins,
+ const std::vector<std::shared_ptr<Plugin>> &plugins,
bool isProbablyLastProcessCall) {
int totalOutputLatencySamples = 0;
int expectedOutputLatency = 0;
- for (auto *plugin : plugins) {
- if (plugin == nullptr)
+ for (auto plugin : plugins) {
+ if (!plugin)
continue;
expectedOutputLatency += plugin->getLatencyHint();
}
@@ -232,8 +232,8 @@ inline int process(juce::AudioBuffer<float> &ioBuffer,
int startOfOutputInBuffer = 0;
int lastSampleInBuffer = 0;
- for (auto *plugin : plugins) {
- if (plugin == nullptr)
+ for (auto plugin : plugins) {
+ if (!plugin)
continue;
int pluginSamplesReceived = 0;
@@ -321,15 +321,6 @@ 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.
@@ -338,7 +329,7 @@ void flattenPluginTree(Plugin *plugin, std::vector<Plugin *> &output) {
template <>
py::array_t<float>
process<float>(const py::array_t<float, py::array::c_style> inputArray,
- double sampleRate, const std::vector<Plugin *> &plugins,
+ double sampleRate, std::vector<std::shared_ptr<Plugin>> plugins,
unsigned int bufferSize, bool reset) {
const ChannelLayout inputChannelLayout = detectChannelLayout(inputArray);
juce::AudioBuffer<float> ioBuffer = copyPyArrayIntoJuceBuffer(inputArray);
@@ -349,44 +340,49 @@ process<float>(const py::array_t<float, py::array::c_style> inputArray,
bufferSize = std::min(bufferSize, (unsigned int)ioBuffer.getNumSamples());
- unsigned int countOfPluginsIgnoringNull = 0;
- for (auto *plugin : plugins) {
- if (plugin == nullptr)
- continue;
- countOfPluginsIgnoringNull++;
- }
-
// We'd pass multiple arguments to scoped_lock here, but we don't know how
// many plugins have been passed at compile time - so instead, we do our own
// deadlock-avoiding multiple-lock algorithm here. By locking each plugin
// only in order of its pointers, we're guaranteed to avoid deadlocks with
// other threads that may be running this same code on the same plugins.
- std::vector<Plugin *> uniquePluginsSortedByPointer;
- for (auto *plugin : plugins) {
- if (plugin == nullptr)
+ std::vector<std::shared_ptr<Plugin>> allPlugins;
+ for (auto plugin : plugins) {
+ if (!plugin)
continue;
- flattenPluginTree(plugin, uniquePluginsSortedByPointer);
+ allPlugins.push_back(plugin);
+ if (auto pluginContainer =
+ dynamic_cast<PluginContainer *>(plugin.get())) {
+ auto children = pluginContainer->getAllPlugins();
+ allPlugins.insert(allPlugins.end(), children.begin(), children.end());
+ }
}
- if (uniquePluginsSortedByPointer.size() < countOfPluginsIgnoringNull) {
+ std::sort(allPlugins.begin(), allPlugins.end(),
+ [](const std::shared_ptr<Plugin> lhs,
+ const std::shared_ptr<Plugin> rhs) {
+ return lhs.get() < rhs.get();
+ });
+
+ bool containsDuplicates =
+ std::adjacent_find(allPlugins.begin(), allPlugins.end()) !=
+ allPlugins.end();
+
+ if (containsDuplicates) {
throw std::runtime_error(
"The same plugin instance is being used multiple times in the same "
- "chain of plugins, which would cause undefined results.");
+ "chain of plugins, which would cause undefined results. Please "
+ "ensure that no duplicate plugins are present before calling.");
}
- std::sort(uniquePluginsSortedByPointer.begin(),
- uniquePluginsSortedByPointer.end(),
- [](const Plugin *lhs, const Plugin *rhs) { return lhs < rhs; });
-
std::vector<std::unique_ptr<std::scoped_lock<std::mutex>>> pluginLocks;
- for (auto *plugin : uniquePluginsSortedByPointer) {
+ for (auto plugin : allPlugins) {
pluginLocks.push_back(
std::make_unique<std::scoped_lock<std::mutex>>(plugin->mutex));
}
if (reset) {
- for (auto *plugin : plugins) {
- if (plugin == nullptr)
+ for (auto plugin : plugins) {
+ if (!plugin)
continue;
plugin->reset();
}
@@ -397,8 +393,8 @@ 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());
- for (auto *plugin : plugins) {
- if (plugin == nullptr)
+ for (auto plugin : plugins) {
+ if (!plugin)
continue;
plugin->prepare(spec);
}
diff --git a/pedalboard/python_bindings.cpp b/pedalboard/python_bindings.cpp
index 14f03c9..a14b5d2 100644
--- a/pedalboard/python_bindings.cpp
+++ b/pedalboard/python_bindings.cpp
@@ -30,6 +30,7 @@ namespace py = pybind11;
#include "ExternalPlugin.h"
#include "JucePlugin.h"
#include "Plugin.h"
+#include "PluginContainer.h"
#include "process.h"
#include "plugins/AddLatency.h"
@@ -53,8 +54,6 @@ namespace py = pybind11;
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 "
@@ -84,9 +83,10 @@ PYBIND11_MODULE(pedalboard_native, m) {
py::arg("buffer_size") = DEFAULT_BUFFER_SIZE, py::arg("reset") = true);
auto plugin =
- py::class_<Plugin>(m, "Plugin",
- "A generic audio processing plugin. Base class of all "
- "Pedalboard plugins.")
+ py::class_<Plugin, std::shared_ptr<Plugin>>(
+ m, "Plugin",
+ "A generic audio processing plugin. Base class of all "
+ "Pedalboard plugins.")
.def(py::init([]() {
throw py::type_error(
"Plugin is an abstract base class - don't instantiate this "
@@ -104,7 +104,7 @@ PYBIND11_MODULE(pedalboard_native, m) {
"cause a full re-instantiation of the plugin.")
.def(
"process",
- [](Plugin *self,
+ [](std::shared_ptr<Plugin> self,
const py::array_t<float, py::array::c_style> inputArray,
double sampleRate, unsigned int bufferSize, bool reset) {
return process(inputArray, sampleRate, {self}, bufferSize,
@@ -119,7 +119,7 @@ PYBIND11_MODULE(pedalboard_native, m) {
.def(
"process",
- [](Plugin *self,
+ [](std::shared_ptr<Plugin> self,
const py::array_t<double, py::array::c_style> inputArray,
double sampleRate, unsigned int bufferSize, bool reset) {
const py::array_t<float, py::array::c_style> float32InputArray =
@@ -130,13 +130,14 @@ PYBIND11_MODULE(pedalboard_native, m) {
"Run a 64-bit floating point audio buffer through this plugin."
"(Note: if calling this multiple times with multiple plugins, "
"consider using pedalboard.process(...) instead.) The buffer "
- "will be "
- "converted to 32-bit for processing.",
+ "will be converted to 32-bit for processing.",
py::arg("input_array"), py::arg("sample_rate"),
py::arg("buffer_size") = DEFAULT_BUFFER_SIZE,
py::arg("reset") = true);
plugin.attr("__call__") = plugin.attr("process");
+ init_plugin_container(m);
+
init_chorus(m);
init_compressor(m);
init_convolution(m);
diff --git a/tests/test_external_plugins.py b/tests/test_external_plugins.py
index 3a5448e..4b5f66a 100644
--- a/tests/test_external_plugins.py
+++ b/tests/test_external_plugins.py
@@ -586,17 +586,17 @@ def test_explicit_reset(plugin_filename: str):
@pytest.mark.parametrize("plugin_filename", AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT)
def test_explicit_reset_in_pedalboard(plugin_filename: str):
sr = 44100
- board = pedalboard.Pedalboard([load_test_plugin(plugin_filename, disable_caching=True)], sr)
+ board = pedalboard.Pedalboard([load_test_plugin(plugin_filename, disable_caching=True)])
noise = np.random.rand(sr, 2)
assert max_volume_of(noise) > 0.95
silence = np.zeros_like(noise)
assert max_volume_of(silence) == 0.0
- assert max_volume_of(board(silence, reset=False)) < 0.00001
- assert max_volume_of(board(noise, reset=False)) > 0.00001
+ assert max_volume_of(board(silence, reset=False, sample_rate=sr)) < 0.00001
+ assert max_volume_of(board(noise, reset=False, sample_rate=sr)) > 0.00001
board.reset()
- assert max_volume_of(board(silence, reset=False)) < 0.00001
+ assert max_volume_of(board(silence, reset=False, sample_rate=sr)) < 0.00001
@pytest.mark.parametrize("value", (True, False))
diff --git a/tests/test_locking.py b/tests/test_locking.py
index 03c7be8..e50c2dd 100644
--- a/tests/test_locking.py
+++ b/tests/test_locking.py
@@ -42,19 +42,19 @@ def test_multiple_threads_using_same_plugin_instances(num_concurrent_chains: int
# we take locks (if we didn't have logic for it) would be
# the pathologically worst-case.
plugins.reverse()
- pedalboards.append(pedalboard.Pedalboard(list(plugins), sample_rate=sr))
+ pedalboards.append(pedalboard.Pedalboard(list(plugins)))
for _ in range(0, num_concurrent_chains // 2):
# Shuffle the list of plugins so that the order in which
# we pass plugins into the method is non-deterministic:
random.shuffle(plugins)
- pedalboards.append(pedalboard.Pedalboard(list(plugins), sample_rate=sr))
+ pedalboards.append(pedalboard.Pedalboard(list(plugins)))
futures = []
with ThreadPoolExecutor(max_workers=num_concurrent_chains) as e:
noise = np.random.rand(1, sr)
for pb in pedalboards:
- futures.append(e.submit(pb.process, np.copy(noise)))
+ futures.append(e.submit(pb.process, np.copy(noise), sample_rate=sr))
# This will throw an exception if we exceed the timeout:
processed = [future.result(timeout=2 * num_concurrent_chains) for future in futures]
diff --git a/tests/test_mix.py b/tests/test_mix_and_chain.py
similarity index 73%
rename from tests/test_mix.py
rename to tests/test_mix_and_chain.py
index 43ad6ab..3e1c345 100644
--- a/tests/test_mix.py
+++ b/tests/test_mix_and_chain.py
@@ -17,7 +17,17 @@
import pytest
import numpy as np
-from pedalboard import Pedalboard, Compressor, Delay, Distortion, Gain, Mix, Chain, PitchShift, Reverb
+from pedalboard import (
+ Pedalboard,
+ Compressor,
+ Delay,
+ Distortion,
+ Gain,
+ Mix,
+ Chain,
+ PitchShift,
+ Reverb,
+)
from pedalboard_native._internal import AddLatency
@@ -36,8 +46,8 @@ def test_chain_syntactic_sugar():
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 pb[1][0].gain_db == -6
+ assert pb[1][1].gain_db == 1
assert isinstance(pb[2], Gain)
assert pb[2].gain_db == -1
@@ -57,7 +67,7 @@ def test_mix_syntactic_sugar():
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 set([plugin.gain_db for plugin in pb[1]]) == set([-6, -6])
assert isinstance(pb[2], Gain)
assert pb[2].gain_db == -6
@@ -191,16 +201,66 @@ def test_readme_example_does_not_crash(sample_rate, buffer_size):
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
+ 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)
+
+
[email protected]("sample_rate", [22050, 44100, 48000])
[email protected]("buffer_size", [128, 8192, 65536])
+def test_pedalboard_is_a_plugin(sample_rate, buffer_size):
+ noise = np.random.rand(int(NUM_SECONDS * sample_rate))
+
+ passthrough = Gain(gain_db=0)
+
+ delay_and_pitch_shift = Chain(
+ [
+ Delay(delay_seconds=0.25, mix=1.0),
+ PitchShift(semitones=7),
+ Gain(gain_db=-3),
+ ]
+ )
+
+ delay_longer_and_more_pitch_shift = Chain(
+ [
+ Delay(delay_seconds=0.25, mix=1.0),
+ PitchShift(semitones=12),
+ Gain(gain_db=-6),
+ ]
+ )
+
+ original_plus_delayed_harmonies = Pedalboard(
+ [Mix([passthrough, delay_and_pitch_shift, delay_longer_and_more_pitch_shift])]
+ )
+ 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:
+ Mix(
+ [
+ Chain([passthrough, Distortion(drive_db=36)]),
+ Chain([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)
diff --git a/tests/test_python_interface.py b/tests/test_python_interface.py
index f4fe267..82ae34c 100644
--- a/tests/test_python_interface.py
+++ b/tests/test_python_interface.py
@@ -24,7 +24,7 @@ from pedalboard import Pedalboard, Gain
def test_no_transforms(shape, sr=44100):
_input = np.random.rand(*shape).astype(np.float32)
- output = Pedalboard([], sr).process(_input)
+ output = Pedalboard([]).process(_input, sr)
assert _input.shape == output.shape
assert np.allclose(_input, output, rtol=0.0001)
@@ -32,12 +32,10 @@ def test_no_transforms(shape, sr=44100):
def test_fail_on_invalid_plugin():
with pytest.raises(TypeError):
- Pedalboard(["I want a reverb please"], 44100)
+ Pedalboard(["I want a reverb please"])
def test_fail_on_invalid_sample_rate():
- with pytest.raises(TypeError):
- Pedalboard([], "fourty four one hundred")
with pytest.raises(TypeError):
Pedalboard([]).process([], "fourty four one hundred")
@@ -50,23 +48,21 @@ def test_fail_on_invalid_buffer_size():
def test_repr():
sr = 44100
gain = Gain(-6)
- value = repr(Pedalboard([gain], sr))
+ value = repr(Pedalboard([gain]))
# Allow flexibility; all we care about is that these values exist in the repr.
assert "Pedalboard" in value
- assert str(sr) in value
assert "plugins=" in value
assert repr(gain) in value
- assert "sample_rate=" in value
def test_is_list_like():
sr = 44100
gain = Gain(-6)
- assert len(Pedalboard([gain], sr)) == 1
- assert len(Pedalboard([gain, Gain(-6)], sr)) == 2
+ assert len(Pedalboard([gain])) == 1
+ assert len(Pedalboard([gain, Gain(-6)])) == 2
- pb = Pedalboard([gain], sr)
+ pb = Pedalboard([gain])
assert len(pb) == 1
# Allow adding elements, like a list:
@@ -89,19 +85,3 @@ def test_is_list_like():
with pytest.raises(TypeError):
pb[0] = "not a plugin"
-
-
-def test_process_validates_sample_rate():
- sr = 44100
- full_scale_noise = np.random.rand(sr, 1).astype(np.float32)
-
- # Sample rate can be provided in the constructor:
- pb = Pedalboard([Gain(-6)], sr).process(full_scale_noise)
-
- # ...or in the `process` call:
- pb = Pedalboard([Gain(-6)]).process(full_scale_noise, sr)
-
- # But if not passed in either, an exception will be raised:
- pb = Pedalboard([Gain(-6)])
- with pytest.raises(ValueError):
- pb.process(full_scale_noise)