π π A Python library for audio.
C audioaudio-processingaudio-productionaudio-researchaudio-unitaugmentationjucemachine-learningpybind11pythonvst3vst3-host
Add delay plugin with feedback.
Peter Sobot85a607f47f18
diff --git a/pedalboard/plugins/Delay.h b/pedalboard/plugins/Delay.hnew file mode 100644index 0000000..e965cf7--- /dev/null+++ b/pedalboard/plugins/Delay.h@@ -0,0 +1,125 @@+/*+ * pedalboard+ * Copyright 2022 Spotify AB+ *+ * Licensed under the GNU Public License, Version 3.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.gnu.org/licenses/gpl-3.0.html+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#include "../JucePlugin.h"++namespace Pedalboard {+template <typename SampleType>+class Delay : public JucePlugin<juce::dsp::DelayLine<SampleType, juce::dsp::DelayLineInterpolationTypes::None>> {+public:+ SampleType getDelaySeconds() const { return delaySeconds; }+ void setDelaySeconds(const SampleType value) {+ if (value < 0.0 || value > MAXIMUM_DELAY_TIME_SECONDS) {+ throw std::range_error("Delay (in seconds) must be between 0.0s and " ++ std::to_string(MAXIMUM_DELAY_TIME_SECONDS) + "s.");+ }+ delaySeconds = value;+ };+ SampleType getFeedback() const { return feedback; }+ void setFeedback(const SampleType value) {+ if (value < 0.0 || value > 1.0) {+ throw std::range_error("Feedback must be between 0.0 and 1.0.");+ }+ feedback = value;+ };+ SampleType getMix() const { return mix; }+ void setMix(const SampleType value) {+ if (value < 0.0 || value > 1.0) {+ throw std::range_error("Mix must be between 0.0 and 1.0.");+ }+ mix = value;+ };++ virtual void prepare(const juce::dsp::ProcessSpec &spec) override {+ if (this->lastSpec.sampleRate != spec.sampleRate ||+ this->lastSpec.maximumBlockSize < spec.maximumBlockSize ||+ spec.numChannels != this->lastSpec.numChannels) {+ this->getDSP().setMaximumDelayInSamples(+ (int)(MAXIMUM_DELAY_TIME_SECONDS * spec.sampleRate));+ this->getDSP().prepare(spec);+ this->lastSpec = spec;+ }++ this->getDSP().setDelay((int)(getDelaySeconds() * spec.sampleRate));+ }++ virtual void reset() override { this->getDSP().reset(); }++ virtual int process(+ const juce::dsp::ProcessContextReplacing<SampleType> &context) override {+ // TODO: More advanced mixing rules than "linear?"+ SampleType dryVolume = 1.0f - getMix();+ SampleType wetVolume = getMix();++ this->getDSP().setDelay((int)(getDelaySeconds() * this->lastSpec.sampleRate));++ // Pass samples through the delay line with feedback:+ for (size_t c = 0; c < context.getInputBlock().getNumChannels(); c++) {+ jassert(context.getInputBlock().getChannelPointer(c) ==+ context.getOutputBlock().getChannelPointer(c));+ SampleType *channelBuffer = context.getOutputBlock().getChannelPointer(c);++ for (size_t i = 0; i < context.getInputBlock().getNumSamples(); i++) {+ SampleType delayOutput = this->getDSP().popSample(c);+ this->getDSP().pushSample(c,+ channelBuffer[i] + (getFeedback() * delayOutput));+ channelBuffer[i] =+ (channelBuffer[i] * dryVolume) + (wetVolume * delayOutput);+ }+ }+ return context.getInputBlock().getNumSamples();+ }++private:+ SampleType delaySeconds = 1.0f;+ SampleType feedback = 0.0f;+ SampleType mix = 1.0f;+ static constexpr int MAXIMUM_DELAY_TIME_SECONDS = 30;+};++inline void init_delay(py::module &m) {+ py::class_<Delay<float>, Plugin>(+ m, "Delay",+ "A digital delay plugin with controllable delay time, feedback "+ "percentage, and dry/wet mix.")+ .def(py::init([](float delaySeconds, float feedback, float mix) {+ auto delay = new Delay<float>();+ delay->setDelaySeconds(delaySeconds);+ delay->setFeedback(feedback);+ delay->setMix(mix);+ return delay;+ }),+ py::arg("delay_seconds") = 0.5, py::arg("feedback") = 0.0,+ py::arg("mix") = 0.5)+ .def("__repr__",+ [](const Delay<float> &plugin) {+ std::ostringstream ss;+ ss << "<pedalboard.Delay";+ ss << " delay_seconds=" << plugin.getDelaySeconds();+ ss << " feedback=" << plugin.getFeedback();+ ss << " mix=" << plugin.getMix();+ ss << " at " << &plugin;+ ss << ">";+ return ss.str();+ })+ .def_property("delay_seconds", &Delay<float>::getDelaySeconds,+ &Delay<float>::setDelaySeconds)+ .def_property("feedback", &Delay<float>::getFeedback,+ &Delay<float>::setFeedback)+ .def_property("mix", &Delay<float>::getMix, &Delay<float>::setMix);+}+}; // namespace Pedalboarddiff --git a/pedalboard/python_bindings.cpp b/pedalboard/python_bindings.cppindex b267f91..61bf115 100644--- a/pedalboard/python_bindings.cpp+++ b/pedalboard/python_bindings.cpp@@ -36,6 +36,7 @@ namespace py = pybind11;#include "plugins/Chorus.h"#include "plugins/Compressor.h"#include "plugins/Convolution.h"+#include "plugins/Delay.h"#include "plugins/Distortion.h"#include "plugins/Gain.h"#include "plugins/HighpassFilter.h"@@ -136,6 +137,7 @@ PYBIND11_MODULE(pedalboard_native, m) {init_chorus(m);init_compressor(m);init_convolution(m);+ init_delay(m);init_distortion(m);init_gain(m);init_highpass(m);diff --git a/tests/test_native_module.py b/tests/test_native_module.pyindex 4df3863..1475212 100644--- a/tests/test_native_module.py+++ b/tests/test_native_module.py@@ -18,7 +18,7 @@import osimport pytestimport numpy as np-from pedalboard import process, Distortion, Gain, Compressor, Convolution, Reverb+from pedalboard import process, Delay, Distortion, Gain, Compressor, Convolution, ReverbIMPULSE_RESPONSE_PATH = os.path.join(os.path.dirname(__file__), "impulse_response.wav")@@ -91,6 +91,30 @@ def test_distortion(gain_db, shape, sr=44100):np.testing.assert_allclose(np.tanh(full_scale_noise * gain_scale), result, rtol=4e-7, atol=2e-7)+def test_delay():+ delay_seconds = 2.5+ feedback = 0.0+ mix = 0.5+ duration = 10.0+ sr = 44100++ full_scale_noise = np.random.rand(int(sr * duration)).astype(np.float32)+ result = Delay(delay_seconds, feedback, mix)(full_scale_noise, sr)++ # Manually do what a delay plugin would do:+ dry_volume = 1.0 - mix+ wet_volume = mix++ delayed_line = np.concatenate([+ np.zeros(int(delay_seconds * sr)),+ full_scale_noise+ ])[:len(result)]+ expected = (dry_volume * full_scale_noise) + (wet_volume * delayed_line)++ np.testing.assert_equal(result.shape, expected.shape)+ np.testing.assert_allclose(expected, result, rtol=4e-7, atol=2e-7)++@pytest.mark.parametrize("reset", (True, False))def test_plugin_state_not_cleared_between_invocations(reset: bool):"""