π π A Python library for audio.
C audioaudio-processingaudio-productionaudio-researchaudio-unitaugmentationjucemachine-learningpybind11pythonvst3vst3-host
Add PitchShift plugin. (#59)
John Lingibe0ce89d89be
diff --git a/.gitignore b/.gitignoreindex 2cb0947..12b2d39 100644--- a/.gitignore+++ b/.gitignore@@ -145,6 +145,7 @@ venv/ENV/env.bak/venv.bak/+.python-version# Spyder project settings.spyderproject@@ -170,4 +171,7 @@ dmypy.json# Cython debug symbolscython_debug/+# IDE+.vscode+.DS_Store\ No newline at end of filediff --git a/.gitmodules b/.gitmodulesindex cb02604..05f65fc 100644--- a/.gitmodules+++ b/.gitmodules@@ -1,3 +1,6 @@[submodule "JUCE"]path = JUCE- url = [email protected]:juce-framework/JUCE.git+ url = https://github.com/juce-framework/JUCE.git+[submodule "pedalboard/vendors/rubberband"]+ path = vendors/rubberband+ url = https://github.com/BreakfastQuay/Rubberband.gitdiff --git a/pedalboard/RubberbandPlugin.h b/pedalboard/RubberbandPlugin.hnew file mode 100644index 0000000..18fe129--- /dev/null+++ b/pedalboard/RubberbandPlugin.h@@ -0,0 +1,85 @@+#include "../vendors/rubberband/rubberband/RubberBandStretcher.h"+#include "Plugin.h"++using namespace RubberBand;++namespace Pedalboard {+class RubberbandPlugin : public Plugin+/*+Base class for rubberband plugins.+*/+{+public:+ virtual ~RubberbandPlugin(){};++ void process(+ const juce::dsp::ProcessContextReplacing<float> &context) override final {+ if (rbPtr) {+ auto inBlock = context.getInputBlock();+ auto outBlock = context.getOutputBlock();++ auto len = inBlock.getNumSamples();+ auto numChannels = inBlock.getNumChannels();++ jassert(len == outBlock.getNumSamples());+ jassert(numChannels == outBlock.getNumChannels());++ const float **inChannels =+ (const float **)alloca(numChannels * sizeof(float *));+ float **outChannels = (float **)alloca(numChannels * sizeof(float *));++ for (size_t i = 0; i < numChannels; i++) {+ inChannels[i] = inBlock.getChannelPointer(i);+ outChannels[i] = outBlock.getChannelPointer(i);+ }++ // Rubberband expects all channel data with one float array per channel+ processSamples(inChannels, outChannels, len, numChannels);+ }+ }++ void reset() override final {+ if (rbPtr) {+ rbPtr->reset();+ }+ }++private:+ void processSamples(const float *const *inBlock, float **outBlock,+ size_t samples, size_t numChannels) {+ // Push all of the input samples into RubberBand:+ rbPtr->process(inBlock, samples, false);++ // Figure out how many samples RubberBand is ready to give to us:+ int availableSamples = rbPtr->available();++ // ...but only actually ask Rubberband for at most the number of samples we+ // can handle:+ int samplesToPull = samples;+ if (samplesToPull > availableSamples)+ samplesToPull = availableSamples;++ // If we don't have enough samples to fill a full buffer,+ // right-align the samples that we do have (i..e: start with silence).+ int missingSamples = samples - availableSamples;+ if (missingSamples > 0) {+ for (size_t c = 0; c < numChannels; c++) {+ // Clear the start of the buffer so that we start+ // the buffer with silence:+ std::fill_n(outBlock[c], missingSamples, 0.0);++ // Move the output buffer pointer forward so that+ // RubberBandStretcher::retrieve(...) places its+ // output at the end of the buffer:+ outBlock[c] += missingSamples;+ }+ }++ // Pull the next audio data out of Rubberband:+ rbPtr->retrieve(outBlock, samplesToPull);+ }++protected:+ std::unique_ptr<RubberBandStretcher> rbPtr;+};+}; // namespace Pedalboarddiff --git a/pedalboard/plugins/PitchShift.h b/pedalboard/plugins/PitchShift.hnew file mode 100644index 0000000..bd21542--- /dev/null+++ b/pedalboard/plugins/PitchShift.h@@ -0,0 +1,80 @@+/*+ * 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.+ */++#include <pybind11/pybind11.h>+#include <pybind11/stl.h>++namespace py = pybind11;++#include "../RubberbandPlugin.h"++namespace Pedalboard {+class PitchShift : public RubberbandPlugin+/*+Modifies pitch of an audio without affecting duration+*/+{+private:+ double _scaleFactor = 1.0;++public:+ void setScaleFactor(double scale) {+ if (scale <= 0) {+ throw std::range_error("Pitch scale must be a value greater than 0.0.");+ }+ _scaleFactor = scale;+ if (rbPtr)+ rbPtr->setPitchScale(_scaleFactor);+ }++ double getScaleFactor() { return _scaleFactor; }++ void prepare(const juce::dsp::ProcessSpec &spec) override final {+ bool specChanged = lastSpec.sampleRate != spec.sampleRate ||+ lastSpec.maximumBlockSize < spec.maximumBlockSize ||+ spec.numChannels != lastSpec.numChannels;++ if (!rbPtr || specChanged) {+ auto stretcherOptions = RubberBandStretcher::OptionProcessRealTime |+ RubberBandStretcher::OptionThreadingNever;+ rbPtr = std::make_unique<RubberBandStretcher>(+ spec.sampleRate, spec.numChannels, stretcherOptions);+ rbPtr->setMaxProcessSize(spec.maximumBlockSize);+ rbPtr->setPitchScale(_scaleFactor);+ rbPtr->reset();+ lastSpec = spec;+ }+ }+};++inline void init_pitch_shift(py::module &m) {+ py::class_<PitchShift, Plugin>(+ m, "PitchShift",+ "Shift pitch without affecting audio duration. Shifted audio may start "+ "with a short duration of silence, depending on the scale factor used. "+ "The rate of the audio will be multiplied by scale_factor (i.e.: 2x "+ "means one octave up, 0.5x means one octave down).")+ .def(py::init([](double scale) {+ auto plugin = new PitchShift();+ plugin->setScaleFactor(scale);+ return plugin;+ }),+ py::arg("scale_factor") = 1.0)+ .def_property("scale_factor", &PitchShift::getScaleFactor,+ &PitchShift::setScaleFactor);+}+}; // namespace Pedalboarddiff --git a/pedalboard/python_bindings.cpp b/pedalboard/python_bindings.cppindex 5fb48f3..ae0ed8a 100644--- a/pedalboard/python_bindings.cpp+++ b/pedalboard/python_bindings.cpp@@ -43,6 +43,7 @@ namespace py = pybind11;#include "plugins/LowpassFilter.h"#include "plugins/NoiseGate.h"#include "plugins/Phaser.h"+#include "plugins/PitchShift.h"#include "plugins/Reverb.h"using namespace Pedalboard;@@ -132,7 +133,6 @@ PYBIND11_MODULE(pedalboard_native, m) {plugin.attr("__call__") = plugin.attr("process");init_chorus(m);-init_compressor(m);init_convolution(m);init_distortion(m);@@ -143,6 +143,7 @@ PYBIND11_MODULE(pedalboard_native, m) {init_lowpass(m);init_noisegate(m);init_phaser(m);+ init_pitch_shift(m);init_reverb(m);init_external_plugins(m);diff --git a/setup.py b/setup.pyindex c8069e1..5dccadf 100644--- a/setup.py+++ b/setup.py@@ -44,15 +44,20 @@ JUCE_CPPFLAGS = ["-DJUCER_LINUX_MAKE_6D53C8B4=1","-DJUCE_APP_VERSION=1.0.0","-DJUCE_APP_VERSION_HEX=0x10000",+ "-DUSE_BQRESAMPLER=1",+ "-DNO_THREADING=1", # for RubberBand, whose threading we have disabled'-Wall',]if platform.system() == "Darwin":JUCE_CPPFLAGS.append("-DMACOS=1")+ JUCE_CPPFLAGS.append("-DHAVE_VDSP=1")elif platform.system() == "Linux":JUCE_CPPFLAGS.append("-DLINUX=1")elif platform.system() == "Windows":JUCE_CPPFLAGS.append("-DWINDOWS=1")+ JUCE_CPPFLAGS.append("-D_HAS_STD_BYTE=0")+ JUCE_CPPFLAGS.append("-DNOMINMAX")else:raise NotImplementedError("Not sure how to build JUCE on platform: {}!".format(platform.system())@@ -104,6 +109,9 @@ UnixCCompiler.src_extensions.append(".mm")UnixCCompiler.language_map[".mm"] = "objc++"LIBS = []+sources = list(Path("pedalboard").glob("**/*.cpp"))+sources += list(Path("vendors/rubberband/single").glob("*.cpp"))+if platform.system() == "Darwin":MACOS_FRAMEWORKS = ['Accelerate',@@ -126,8 +134,6 @@ if platform.system() == "Darwin":JUCE_CPPFLAGS_CONSOLEAPP += ["-DJUCE_PLUGINHOST_AU=1"]JUCE_CPPFLAGS.append('-xobjective-c++')- sources = list(Path("pedalboard").glob("**/*.cpp"))-# Replace .cpp sources with matching .mm sources on macOS to force the# compiler to use Apple's Objective-C and Objective-C++ code.for objc_source in Path("pedalboard").glob("**/*.mm"):@@ -156,7 +162,7 @@ elif platform.system() == "Linux":JUCE_INCLUDES += include_pathsLINK_ARGS += ['-lfreetype']- PEDALBOARD_SOURCES = [str(p.resolve()) for p in (list(Path("pedalboard").glob("**/*.cpp")))]+ PEDALBOARD_SOURCES = [str(p.resolve()) for p in sources]elif platform.system() == "Windows":JUCE_CPPFLAGS += ['-DJUCE_DLL_BUILD=1']# https://forum.juce.com/t/statically-linked-exe-in-win-10-not-working/25574/3@@ -176,7 +182,7 @@ elif platform.system() == "Windows":"odbccp32",])- PEDALBOARD_SOURCES = [str(p.resolve()) for p in (list(Path("pedalboard").glob("**/*.cpp")))]+ PEDALBOARD_SOURCES = [str(p.resolve()) for p in sources]else:raise NotImplementedError("Not sure how to build JUCE on platform: {}!".format(platform.system())diff --git a/tests/test_pitch_shift.py b/tests/test_pitch_shift.pynew file mode 100644index 0000000..3685a36--- /dev/null+++ b/tests/test_pitch_shift.py@@ -0,0 +1,33 @@+#! /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 PitchShift++[email protected]("scale", [0.5, 1.0, 2.0])[email protected]("fundamental_hz", [440, 880])[email protected]("sample_rate", [22050, 44100, 48000])+def test_pitch_shift(scale, fundamental_hz, sample_rate):+ num_seconds = 10.0+ samples = np.arange(num_seconds * sample_rate)+ sine_wave = np.sin(2 * np.pi * fundamental_hz * samples / sample_rate)+ plugin = PitchShift(scale)+ output = plugin.process(sine_wave, sample_rate)++ assert np.all(np.isfinite(output))diff --git a/vendors/rubberband b/vendors/rubberbandnew file mode 160000index 0000000..41ba70f--- /dev/null+++ b/vendors/rubberband@@ -0,0 +1 @@+Subproject commit 41ba70fbb9dc5042da37395a9d7a28fd967036d0