Skip to content

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

Fix boundary effects before (and after) some pitch shift operations.

Peter Sobota7855dc66a16
diff --git a/pedalboard/RubberbandPlugin.h b/pedalboard/RubberbandPlugin.h
index 05553a2..33b83d0 100644
--- a/pedalboard/RubberbandPlugin.h
+++ b/pedalboard/RubberbandPlugin.h
@@ -81,6 +81,22 @@ public:
}
}
+ RubberBandStretcher &getStretcher() {
+ return *rbPtr;
+ }
+
+ virtual int getLatencyHint() override {
+ if (!rbPtr)
+ return 0;
+
+ initialSamplesRequired =
+ std::max(initialSamplesRequired,
+ (int)(rbPtr->getSamplesRequired() + rbPtr->getLatency() +
+ lastSpec.maximumBlockSize));
+
+ return initialSamplesRequired;
+ }
+
private:
int processSamples(const float *const *inBlock, float **outBlock,
size_t samples, size_t numChannels) {
@@ -117,18 +133,6 @@ private:
}
protected:
- virtual int getLatencyHint() override {
- if (!rbPtr)
- return 0;
-
- initialSamplesRequired =
- std::max(initialSamplesRequired,
- (int)(rbPtr->getSamplesRequired() + rbPtr->getLatency() +
- lastSpec.maximumBlockSize));
-
- return initialSamplesRequired;
- }
-
std::unique_ptr<RubberBandStretcher> rbPtr;
int initialSamplesRequired = 0;
};
diff --git a/pedalboard/plugin_templates/PrimeWithSilence.h b/pedalboard/plugin_templates/PrimeWithSilence.h
new file mode 100644
index 0000000..a2a67a3
--- /dev/null
+++ b/pedalboard/plugin_templates/PrimeWithSilence.h
@@ -0,0 +1,179 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include "../JuceHeader.h"
+#include "../Plugin.h"
+#include "../plugins/AddLatency.h"
+#include <mutex>
+
+namespace Pedalboard {
+
+/**
+ * A dummy plugin that buffers audio data internally, used to test Pedalboard's
+ * automatic latency compensation.
+ */
+template <typename T, typename SampleType = float>
+class PrimeWithSilence
+ : public JucePlugin<juce::dsp::DelayLine<
+ SampleType, juce::dsp::DelayLineInterpolationTypes::None>> {
+public:
+ virtual ~PrimeWithSilence(){};
+
+ virtual void prepare(const juce::dsp::ProcessSpec &spec) {
+ JucePlugin<juce::dsp::DelayLine<
+ SampleType,
+ juce::dsp::DelayLineInterpolationTypes::None>>::prepare(spec);
+ plugin.prepare(spec);
+ }
+
+ virtual void reset() override {
+ this->getDSP().reset();
+ this->getDSP().setMaximumDelayInSamples(silenceLengthSamples);
+ this->getDSP().setDelay(silenceLengthSamples);
+ plugin.reset();
+ samplesOutput = 0;
+ }
+
+ virtual int
+ process(const juce::dsp::ProcessContextReplacing<float> &context) override {
+ this->getDSP().process(context);
+
+ // Context now has a delayed signal in it:
+ int samplesProcessed = plugin.process(context);
+ samplesOutput += samplesProcessed;
+
+ return std::max(
+ 0, std::min((int)samplesProcessed,
+ (int)samplesOutput - (int)this->getDSP().getDelay()));
+ }
+
+ virtual int getLatencyHint() override {
+ return this->getDSP().getDelay() + getNestedPlugin().getLatencyHint();
+ }
+
+ T &getNestedPlugin() { return plugin; }
+
+ void setSilenceLengthSamples(int newSilenceLengthSamples) {
+ this->getDSP().setMaximumDelayInSamples(newSilenceLengthSamples);
+ this->getDSP().setDelay(newSilenceLengthSamples);
+ silenceLengthSamples = newSilenceLengthSamples;
+
+ reset();
+ }
+
+ int getSilenceLengthSamples() const { return silenceLengthSamples; }
+
+private:
+ T plugin;
+ int samplesOutput = 0;
+ int silenceLengthSamples = 0;
+};
+
+/**
+ * A test plugin used to verify the behaviour of the PrimingPlugin wrapper.
+ */
+class ExpectsToBePrimed : public AddLatency {
+public:
+ virtual ~ExpectsToBePrimed(){};
+
+ virtual void prepare(const juce::dsp::ProcessSpec &spec) {
+ getDSP().setMaximumDelayInSamples(10);
+ getDSP().setDelay(10);
+
+ AddLatency::prepare(spec);
+ }
+
+ virtual int
+ process(const juce::dsp::ProcessContextReplacing<float> &context) {
+ auto inputBlock = context.getInputBlock();
+
+ for (int i = 0; i < inputBlock.getNumSamples(); i++) {
+ bool allChannelsSilent = true;
+
+ for (int c = 0; c < inputBlock.getNumChannels(); c++) {
+ if (inputBlock.getChannelPointer(c)[i] != 0) {
+ allChannelsSilent = false;
+ }
+ }
+
+ if (!allChannelsSilent) {
+ // If we get here, we've got our first non-zero sample.
+ if (seenSilentSamples < expectedSilentSamples) {
+ throw std::runtime_error("Expected to see " +
+ std::to_string(expectedSilentSamples) +
+ " silent samples, but only saw " +
+ std::to_string(seenSilentSamples) +
+ " before first non-zero value.");
+ }
+ break;
+ }
+
+ seenSilentSamples++;
+ }
+
+ return AddLatency::process(context);
+ }
+
+ virtual void reset() {
+ seenSilentSamples = 0;
+ AddLatency::reset();
+ }
+
+ void setExpectedSilentSamples(int newExpectedSilentSamples) {
+ expectedSilentSamples = newExpectedSilentSamples;
+ }
+
+private:
+ int expectedSilentSamples = 0;
+ int seenSilentSamples = 0;
+};
+
+class PrimeWithSilenceTestPlugin : public PrimeWithSilence<ExpectsToBePrimed> {
+public:
+ void setExpectedSilentSamples(int newExpectedSilentSamples) {
+ setSilenceLengthSamples(newExpectedSilentSamples);
+ getNestedPlugin().setExpectedSilentSamples(getSilenceLengthSamples());
+ }
+
+ int getExpectedSilentSamples() const { return getSilenceLengthSamples(); }
+
+private:
+ int expectedBlockSize = 0;
+};
+
+inline void init_prime_with_silence_test_plugin(py::module &m) {
+ py::class_<PrimeWithSilenceTestPlugin, Plugin>(m,
+ "PrimeWithSilenceTestPlugin")
+ .def(py::init([](int expectedSilentSamples) {
+ auto plugin = new PrimeWithSilenceTestPlugin();
+ plugin->setExpectedSilentSamples(expectedSilentSamples);
+ return plugin;
+ }),
+ py::arg("expected_silent_samples") = 160)
+ .def("__repr__", [](const PrimeWithSilenceTestPlugin &plugin) {
+ std::ostringstream ss;
+ ss << "<pedalboard.PrimeWithSilenceTestPlugin";
+ ss << " expected_silent_samples=" << plugin.getExpectedSilentSamples();
+ ss << " at " << &plugin;
+ ss << ">";
+ return ss.str();
+ });
+}
+
+} // namespace Pedalboard
\ No newline at end of file
diff --git a/pedalboard/plugins/PitchShift.h b/pedalboard/plugins/PitchShift.h
index 836c0f9..f3507f0 100644
--- a/pedalboard/plugins/PitchShift.h
+++ b/pedalboard/plugins/PitchShift.h
@@ -21,14 +21,14 @@
namespace py = pybind11;
#include "../RubberbandPlugin.h"
+#include "../plugin_templates/PrimeWithSilence.h"
namespace Pedalboard {
-/*
-Modifies pitch of an audio without affecting duration
-*/
-class PitchShift : public RubberbandPlugin
-{
+/*
+ * Modifies pitch of an audio without affecting duration.
+ */
+class PitchShift : public PrimeWithSilence<RubberbandPlugin> {
private:
double _semitones = 0.0;
@@ -47,16 +47,14 @@ public:
}
_semitones = semitones;
-
- if (rbPtr)
- rbPtr->setPitchScale(getScaleFactor());
}
double getSemitones() { return _semitones; }
void prepare(const juce::dsp::ProcessSpec &spec) override final {
- RubberbandPlugin::prepare(spec);
- rbPtr->setPitchScale(getScaleFactor());
+ setSilenceLengthSamples(spec.sampleRate);
+ PrimeWithSilence<RubberbandPlugin>::prepare(spec);
+ getNestedPlugin().getStretcher().setPitchScale(getScaleFactor());
}
};
diff --git a/pedalboard/process.h b/pedalboard/process.h
index 58731df..5ff269f 100644
--- a/pedalboard/process.h
+++ b/pedalboard/process.h
@@ -305,13 +305,14 @@ process<float>(const py::array_t<float, py::array::c_style> inputArray,
int pluginSamplesReceived = 0;
+ unsigned int blockSize = bufferSize;
for (unsigned int blockStart = startOfOutputInBuffer;
blockStart < (unsigned int)intendedOutputBufferSize;
- blockStart += bufferSize) {
+ blockStart += blockSize) {
unsigned int blockEnd =
std::min(blockStart + bufferSize,
static_cast<unsigned int>(intendedOutputBufferSize));
- unsigned int blockSize = blockEnd - blockStart;
+ blockSize = blockEnd - blockStart;
auto ioBlock = juce::dsp::AudioBlock<float>(
ioBuffer.getArrayOfWritePointers(), ioBuffer.getNumChannels(),
diff --git a/pedalboard/python_bindings.cpp b/pedalboard/python_bindings.cpp
index 7a16bd0..170809e 100644
--- a/pedalboard/python_bindings.cpp
+++ b/pedalboard/python_bindings.cpp
@@ -50,6 +50,8 @@ namespace py = pybind11;
#include "plugins/PitchShift.h"
#include "plugins/Reverb.h"
+#include "plugin_templates/PrimeWithSilence.h"
+
using namespace Pedalboard;
static constexpr int DEFAULT_BUFFER_SIZE = 8192;
@@ -158,4 +160,5 @@ PYBIND11_MODULE(pedalboard_native, m) {
// Internal plugins for testing, debugging, etc:
py::module internal = m.def_submodule("_internal");
init_add_latency(internal);
+ init_prime_with_silence_test_plugin(internal);
};
diff --git a/tests/test_pitch_shift.py b/tests/test_pitch_shift.py
index 964804f..0298aff 100644
--- a/tests/test_pitch_shift.py
+++ b/tests/test_pitch_shift.py
@@ -50,15 +50,13 @@ def test_pitch_shift_extremes(semitones, sample_rate, buffer_size):
@pytest.mark.parametrize("semitones", [0])
[email protected]("fundamental_hz", [440.0, 880.0])
@pytest.mark.parametrize("sample_rate", [22050, 44100, 48000])
[email protected]("buffer_size", [512, 8192])
-def test_pitch_shift_latency_compensation(semitones, sample_rate, buffer_size):
- num_seconds = 10.0
- fundamental_hz = 440.0
[email protected]("buffer_size", [32, 512, 513, 1024, 1029, 2048, 8192])
+def test_pitch_shift_latency_compensation(semitones, fundamental_hz, sample_rate, buffer_size):
+ num_seconds = 5.0
samples = np.arange(num_seconds * sample_rate)
sine_wave = np.sin(2 * np.pi * fundamental_hz * samples / sample_rate)
plugin = Pedalboard([PitchShift(semitones), PitchShift(-semitones)])
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
- )
+ np.testing.assert_allclose(sine_wave, output, rtol=0.01, atol=0.01)
diff --git a/tests/test_prime_with_silence.py b/tests/test_prime_with_silence.py
new file mode 100644
index 0000000..03f29c0
--- /dev/null
+++ b/tests/test_prime_with_silence.py
@@ -0,0 +1,34 @@
+#! /usr/bin/env python
+#
+# 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.
+
+
+import pytest
+import numpy as np
+from pedalboard_native._internal import PrimeWithSilenceTestPlugin
+
+
[email protected]("sample_rate", [22050, 44100, 48000])
[email protected]("buffer_size", [16, 40, 128, 160, 8192, 8193])
[email protected]("silent_samples_to_add", [1, 16, 40, 128, 160, 8192, 8193])
[email protected]("num_channels", [1, 2])
+def test_prime_with_silence(sample_rate, buffer_size, silent_samples_to_add, num_channels):
+ num_seconds = 5.0
+ noise = np.random.rand(int(num_seconds * sample_rate))
+ if num_channels == 2:
+ noise = np.stack([noise, noise])
+ plugin = PrimeWithSilenceTestPlugin(silent_samples_to_add)
+ output = plugin.process(noise, sample_rate, buffer_size=buffer_size)
+ np.testing.assert_allclose(output, noise)