π π A Python library for audio.
C audioaudio-processingaudio-productionaudio-researchaudio-unitaugmentationjucemachine-learningpybind11pythonvst3vst3-host
Rewrite Rubber Band integration to support latency compensation.
Peter Sobot54dfe870206c
diff --git a/pedalboard/RubberbandPlugin.h b/pedalboard/RubberbandPlugin.hindex 18fe129..16caf7b 100644--- a/pedalboard/RubberbandPlugin.h+++ b/pedalboard/RubberbandPlugin.h@@ -1,85 +1,191 @@+/*+ * 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 "../vendors/rubberband/rubberband/RubberBandStretcher.h"#include "Plugin.h"using namespace RubberBand;namespace Pedalboard {-class RubberbandPlugin : public Plugin+/*-Base class for rubberband plugins.-*/-{+ * Base class for all Rubber Band-derived plugins.+ */+class RubberbandPlugin : public Plugin {public:virtual ~RubberbandPlugin(){};- void process(+ virtual void prepare(const juce::dsp::ProcessSpec &spec) override {+ bool specChanged = lastSpec.sampleRate != spec.sampleRate ||+ lastSpec.maximumBlockSize < spec.maximumBlockSize ||+ spec.numChannels != lastSpec.numChannels;++ if (!rbPtr || specChanged) {+ auto stretcherOptions = RubberBandStretcher::OptionProcessRealTime |+ RubberBandStretcher::OptionThreadingNever |+ RubberBandStretcher::OptionChannelsTogether |+ RubberBandStretcher::OptionPitchHighQuality;+ rbPtr = std::make_unique<RubberBandStretcher>(+ spec.sampleRate, spec.numChannels, stretcherOptions);+ rbPtr->setMaxProcessSize(spec.maximumBlockSize);++ lastSpec = spec;+ reset();+ }+ }++ int process(const juce::dsp::ProcessContextReplacing<float> &context) override final {- if (rbPtr) {- auto inBlock = context.getInputBlock();- auto outBlock = context.getOutputBlock();+ if (!rbPtr) {+ throw std::runtime_error("Rubber Band plugin failed to instantiate.");+ }++ auto ioBlock = context.getOutputBlock();+ auto numChannels = ioBlock.getNumChannels();++ if (numChannels > MAX_CHANNEL_COUNT) {+ throw std::runtime_error(+ "Pitch shifting or time stretching plugins support a maximum of " ++ std::to_string(MAX_CHANNEL_COUNT) + " channels.");+ }++ float *ioChannels[MAX_CHANNEL_COUNT] = {};++ // for (size_t i = 0; i < numChannels; i++) {+ // ioChannels[i] = ioBlock.getChannelPointer(i);+ // }- auto len = inBlock.getNumSamples();- auto numChannels = inBlock.getNumChannels();+ // Push all of the input samples we have into RubberBand:+ // rbPtr->process(ioChannels, ioBlock.getNumSamples(), false);+ // printf("Pushed %d samples into Rubber Band.\n", ioBlock.getNumSamples());+ // int availableSamples = rbPtr->available();- jassert(len == outBlock.getNumSamples());- jassert(numChannels == outBlock.getNumChannels());+ int samplesProcessed = 0;+ int samplesWritten = 0;+ while (samplesProcessed < ioBlock.getNumSamples() || rbPtr->available()) {+ int samplesRequired = rbPtr->getSamplesRequired();+ int inputChunkLength = std::min(+ (int)(ioBlock.getNumSamples() - samplesProcessed), samplesRequired);- const float **inChannels =- (const float **)alloca(numChannels * sizeof(float *));- float **outChannels = (float **)alloca(numChannels * sizeof(float *));+ for (size_t i = 0; i < numChannels; i++) {+ ioChannels[i] = ioBlock.getChannelPointer(i) + samplesProcessed;+ }++ rbPtr->process(ioChannels, inputChunkLength, false);+ samplesProcessed += inputChunkLength;++ int samplesAvailable = rbPtr->available();+ int freeSpace = ioBlock.getNumSamples() - samplesWritten;+ int outputChunkLength = std::min(freeSpace, samplesAvailable);++ // Avoid overwriting input that hasn't yet been passed to Rubber Band:+ if (samplesWritten + outputChunkLength > samplesProcessed) {+ outputChunkLength = samplesProcessed - samplesWritten;+ }for (size_t i = 0; i < numChannels; i++) {- inChannels[i] = inBlock.getChannelPointer(i);- outChannels[i] = outBlock.getChannelPointer(i);+ ioChannels[i] = ioBlock.getChannelPointer(i) + samplesWritten;}+ samplesWritten += rbPtr->retrieve(ioChannels, outputChunkLength);+ if (samplesWritten == ioBlock.getNumSamples())+ break;+ }- // Rubberband expects all channel data with one float array per channel- processSamples(inChannels, outChannels, len, numChannels);+ if (samplesWritten > 0 && samplesWritten < ioBlock.getNumSamples()) {+ // Right-align the output samples in the buffer:+ int offset = ioBlock.getNumSamples() - samplesWritten;+ for (size_t i = 0; i < numChannels; i++) {+ float *channelBufferSource = ioBlock.getChannelPointer(i);+ float *channelBufferDestination = channelBufferSource + offset;+ std::memmove((char *)channelBufferDestination,+ (char *)channelBufferSource,+ sizeof(float) * samplesWritten);+ }}++ return samplesWritten;++ // Don't produce any output for this input if RubberBand isn't ready.+ // We can do this here because RubberBand buffers audio internally;+ // this might not be a safe technique to use with other plugins, as+ // their output sample buffers may overflow if passed more than+ // maximumBlockSize.++ // if (rbPtr->available() < (int) ioBlock.getNumSamples() + getLatency()) {+ // printf("Need %d samples, but Rubber Band only had %d samples+ // available.\n", ioBlock.getNumSamples() + getLatency(),+ // rbPtr->available()); return 0;+ // } else {+ // // Pull the next chunk of audio data out of RubberBand:+ // int returned = rbPtr->retrieve(ioChannels, ioBlock.getNumSamples());+ // printf("Sent %d samples into Rubber Band, and took %d samples back+ // out.\n", ioBlock.getNumSamples(), returned); return returned;+ // }++ // // ...but only actually ask Rubberband for at most the number of samples+ // we+ // // can handle:+ // int samplesToPull = ioBlock.getNumSamples();+ // 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 = ioBlock.getNumSamples() - 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(ioChannels[c], missingSamples, 0.0);++ // // Move the output buffer pointer forward so that+ // // RubberBandStretcher::retrieve(...) places its+ // // output at the end of the buffer:+ // ioChannels[c] += missingSamples;+ // }+ // }++ // // Pull the next audio data out of Rubberband:+ // int pulled = rbPtr->retrieve(ioChannels, samplesToPull);+ // printf("Pulled %d samples out of Rubber Band (%d were available).\n",+ // pulled, availableSamples); return pulled;}void reset() override final {if (rbPtr) {rbPtr->reset();}+ initialSamplesRequired = 0;}-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;- }- }+ virtual int getLatencyHint() override {+ if (!rbPtr)+ return 0;++ initialSamplesRequired =+ std::max(initialSamplesRequired,+ (int)(rbPtr->getSamplesRequired() + rbPtr->getLatency() + lastSpec.maximumBlockSize));- // Pull the next audio data out of Rubberband:- rbPtr->retrieve(outBlock, samplesToPull);+ return initialSamplesRequired;}protected:std::unique_ptr<RubberBandStretcher> rbPtr;+ int initialSamplesRequired = 0;+ static constexpr int MAX_CHANNEL_COUNT = 8;};}; // namespace Pedalboarddiff --git a/pedalboard/plugins/PitchShift.h b/pedalboard/plugins/PitchShift.hindex bd21542..49f0863 100644--- a/pedalboard/plugins/PitchShift.h+++ b/pedalboard/plugins/PitchShift.h@@ -23,20 +23,29 @@ namespace py = pybind11;#include "../RubberbandPlugin.h"namespace Pedalboard {-class PitchShift : public RubberbandPlugin/*Modifies pitch of an audio without affecting duration*/+class PitchShift : public RubberbandPlugin+{private:double _scaleFactor = 1.0;+ // Allow pitch shifting by up to 6 octaves up or down:+ static constexpr float MIN_SCALE_FACTOR = 0.015625;+ static constexpr float MAX_SCALE_FACTOR = 64.0;+public:void setScaleFactor(double scale) {- if (scale <= 0) {- throw std::range_error("Pitch scale must be a value greater than 0.0.");+ if (scale < MIN_SCALE_FACTOR || scale > MAX_SCALE_FACTOR) {+ throw std::range_error("Scale factor must be a value between " ++ std::to_string(MIN_SCALE_FACTOR) + " and " ++ std::to_string(MAX_SCALE_FACTOR) + ".");}+_scaleFactor = scale;+if (rbPtr)rbPtr->setPitchScale(_scaleFactor);}@@ -44,20 +53,8 @@ public: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;- }+ RubberbandPlugin::prepare(spec);+ rbPtr->setPitchScale(_scaleFactor);}};diff --git a/tests/test_pitch_shift.py b/tests/test_pitch_shift.pyindex 3685a36..e91e477 100644--- a/tests/test_pitch_shift.py+++ b/tests/test_pitch_shift.py@@ -17,10 +17,10 @@import pytestimport numpy as np-from pedalboard import PitchShift+from pedalboard import Pedalboard, PitchShift[email protected]("scale", [0.5, 1.0, 2.0])[email protected]("scale", [1 / 2, 1.0, 2.0])@pytest.mark.parametrize("fundamental_hz", [440, 880])@pytest.mark.parametrize("sample_rate", [22050, 44100, 48000])def test_pitch_shift(scale, fundamental_hz, sample_rate):@@ -31,3 +31,34 @@ def test_pitch_shift(scale, fundamental_hz, sample_rate):output = plugin.process(sine_wave, sample_rate)assert np.all(np.isfinite(output))++[email protected]("scale", [0.01, 65.0])+def test_pitch_shift_extremes_throws_errors(scale):+ with pytest.raises(ValueError):+ PitchShift(scale)++[email protected]("scale", [1 / 64, 1 / 8, 1 / 2, 2, 8, 64])[email protected]("sample_rate", [22050, 44100, 48000])[email protected]("buffer_size", [32, 512, 8192])+def test_pitch_shift_extremes(scale, sample_rate, buffer_size):+ noise = np.random.rand(int(5.0 * sample_rate))+ plugin = PitchShift(scale)+ output = plugin.process(noise, sample_rate, buffer_size=buffer_size)+ assert np.all(np.isfinite(output))++[email protected]("scale", [1.0])[email protected]("sample_rate", [22050, 44100, 48000])[email protected]("buffer_size", [512, 8192])+def test_pitch_shift_latency_compensation(scale, sample_rate, buffer_size):+ num_seconds = 10.0+ fundamental_hz = 440.0+ samples = np.arange(num_seconds * sample_rate)+ sine_wave = np.sin(2 * np.pi * fundamental_hz * samples / sample_rate)+ plugin = Pedalboard([PitchShift(scale), PitchShift(1 / scale)])+ output = plugin.process(sine_wave, sample_rate, buffer_size=buffer_size)+ np.testing.assert_allclose(+ sine_wave[sample_rate:-sample_rate], output[sample_rate:-sample_rate], rtol=0.01, atol=0.01+ )