Skip to content

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

Add Resample plugin and plugin template.

Peter Sobot5500988c1a34
diff --git a/README.md b/README.md
index d3fee27..42b2b1f 100644
--- a/README.md
+++ b/README.md
@@ -29,6 +29,7 @@ Internally at Spotify, `pedalboard` is used for [data augmentation](https://en.w
- `LowpassFilter`
- `Phaser`
- `PitchShift` (provided by Chris Cannam's [Rubber Band Library](https://github.com/breakfastquay/rubberband))
+ - `Resample`
- `Reverb`
- Supports VST3ยฎ plugins on macOS, Windows, and Linux (`pedalboard.load_plugin`)
- Supports Audio Units on macOS
diff --git a/pedalboard/plugin_templates/Resample.h b/pedalboard/plugin_templates/Resample.h
new file mode 100644
index 0000000..3de2ed1
--- /dev/null
+++ b/pedalboard/plugin_templates/Resample.h
@@ -0,0 +1,565 @@
+/*
+ * 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 {
+
+#include <variant>
+
+/**
+ * The various levels of resampler quality available from JUCE.
+ * More could be added here, but these should cover the vast
+ * majority of use cases.
+ */
+enum class ResamplingQuality {
+ ZeroOrderHold = 0,
+ Linear = 1,
+ CatmullRom = 2,
+ Lagrange = 3,
+ WindowedSinc = 4,
+};
+
+/**
+ * A wrapper class that allows changing the quality of a resampler,
+ * as the JUCE GenericInterpolator implementations are each separate classes.
+ */
+class VariableQualityResampler {
+public:
+ void setQuality(const ResamplingQuality newQuality) {
+ switch (newQuality) {
+ case ResamplingQuality::ZeroOrderHold:
+ interpolator = juce::Interpolators::ZeroOrderHold();
+ break;
+ case ResamplingQuality::Linear:
+ interpolator = juce::Interpolators::Linear();
+ break;
+ case ResamplingQuality::CatmullRom:
+ interpolator = juce::Interpolators::CatmullRom();
+ break;
+ case ResamplingQuality::Lagrange:
+ interpolator = juce::Interpolators::Lagrange();
+ break;
+ case ResamplingQuality::WindowedSinc:
+ interpolator = juce::Interpolators::WindowedSinc();
+ break;
+ default:
+ throw std::domain_error("Unknown resampler quality received!");
+ }
+ }
+
+ ResamplingQuality getQuality() const {
+ return (ResamplingQuality)interpolator.index();
+ }
+
+ float getBaseLatency() const {
+ return std::visit([](auto &&i) -> float { return i.getBaseLatency(); },
+ interpolator);
+ }
+
+ void reset() noexcept {
+ std::visit([](auto &&i) { return i.reset(); }, interpolator);
+ }
+
+ int process(double speedRatio, const float *inputSamples,
+ float *outputSamples, int numOutputSamplesToProduce) noexcept {
+ return std::visit(
+ [speedRatio, inputSamples, outputSamples,
+ numOutputSamplesToProduce](auto &&i) -> float {
+ return i.process(speedRatio, inputSamples, outputSamples,
+ numOutputSamplesToProduce);
+ },
+ interpolator);
+ }
+
+private:
+ std::variant<juce::Interpolators::ZeroOrderHold, juce::Interpolators::Linear,
+ juce::Interpolators::CatmullRom, juce::Interpolators::Lagrange,
+ juce::Interpolators::WindowedSinc>
+ interpolator;
+};
+
+/**
+ * A test plugin used to verify the behaviour of the ResamplingPlugin wrapper.
+ */
+template <typename SampleType> class Passthrough : public Plugin {
+public:
+ virtual ~Passthrough(){};
+
+ virtual void prepare(const juce::dsp::ProcessSpec &spec) {}
+
+ virtual int
+ process(const juce::dsp::ProcessContextReplacing<float> &context) {
+ return context.getInputBlock().getNumSamples();
+ }
+
+ virtual void reset() {}
+};
+
+/**
+ * A template class that wraps a Pedalboard plugin and resamples
+ * the audio to the provided sample rate. The wrapped plugin receives
+ * resampled audio and its sampleRate and maximumBlockSize parameters
+ * are adjusted accordingly.
+ */
+template <typename T = Passthrough<float>, typename SampleType = float,
+ int DefaultSampleRate = 8000>
+class Resample : public Plugin {
+public:
+ virtual ~Resample(){};
+
+ virtual void prepare(const juce::dsp::ProcessSpec &spec) {
+ bool specChanged = lastSpec.sampleRate != spec.sampleRate ||
+ lastSpec.maximumBlockSize < spec.maximumBlockSize ||
+ lastSpec.numChannels != spec.numChannels;
+ if (specChanged || nativeToTargetResamplers.empty()) {
+ reset();
+
+ nativeToTargetResamplers.resize(spec.numChannels);
+ targetToNativeResamplers.resize(spec.numChannels);
+
+ for (int i = 0; i < spec.numChannels; i++) {
+ nativeToTargetResamplers[i].setQuality(quality);
+ nativeToTargetResamplers[i].reset();
+ targetToNativeResamplers[i].setQuality(quality);
+ targetToNativeResamplers[i].reset();
+ }
+
+ resamplerRatio = spec.sampleRate / targetSampleRate;
+ inverseResamplerRatio = targetSampleRate / spec.sampleRate;
+ maximumBlockSizeInTargetSampleRate =
+ std::ceil(spec.maximumBlockSize / resamplerRatio);
+
+ // Store the remainder of the input: any samples that weren't consumed in
+ // one pushSamples() call but would be consumable in the next one.
+ inputReservoir.setSize(spec.numChannels,
+ 2 * ((int)std::ceil(resamplerRatio) +
+ (int)std::ceil(inverseResamplerRatio)) +
+ spec.maximumBlockSize);
+
+ inStreamLatency = 0;
+
+ // Add the resamplers' latencies so the output is properly aligned:
+ inStreamLatency += std::round(
+ nativeToTargetResamplers[0].getBaseLatency() * resamplerRatio +
+ targetToNativeResamplers[0].getBaseLatency());
+
+ resampledBuffer.setSize(spec.numChannels,
+ ((maximumBlockSizeInTargetSampleRate + 1) * 3) +
+ (inStreamLatency / resamplerRatio));
+ outputBuffer.setSize(
+ spec.numChannels,
+ (int)std::ceil(resampledBuffer.getNumSamples() * resamplerRatio) +
+ spec.maximumBlockSize);
+
+ lastSpec = spec;
+ }
+
+ const juce::dsp::ProcessSpec subSpec = {
+ .numChannels = spec.numChannels,
+ .sampleRate = targetSampleRate,
+ .maximumBlockSize = maximumBlockSizeInTargetSampleRate};
+ plugin.prepare(subSpec);
+ }
+
+ int process(const juce::dsp::ProcessContextReplacing<SampleType> &context)
+ override final {
+ auto ioBlock = context.getOutputBlock();
+
+ float expectedResampledSamples = ioBlock.getNumSamples() / resamplerRatio;
+
+ if (spaceAvailableInResampledBuffer() < expectedResampledSamples) {
+ throw std::runtime_error(
+ "More samples were provided than can be buffered! This is an "
+ "internal Pedalboard error and should be reported. Buffer had " +
+ std::to_string(processedSamplesInResampledBuffer +
+ cleanSamplesInResampledBuffer) +
+ "/" + std::to_string(resampledBuffer.getNumSamples()) +
+ " samples at target sample rate, but was provided " +
+ std::to_string(expectedResampledSamples) + ".");
+ }
+
+ unsigned long samplesUsed = 0;
+ if (samplesInInputReservoir) {
+ // Copy the input samples into the input reservoir and use that as the
+ // resampler's input:
+ expectedResampledSamples +=
+ (float)samplesInInputReservoir / resamplerRatio;
+
+ for (size_t c = 0; c < ioBlock.getNumChannels(); c++) {
+ inputReservoir.copyFrom(c, samplesInInputReservoir,
+ ioBlock.getChannelPointer(c),
+ ioBlock.getNumSamples());
+ SampleType *resampledBufferPointer =
+ resampledBuffer.getWritePointer(c) +
+ processedSamplesInResampledBuffer + cleanSamplesInResampledBuffer;
+ samplesUsed = nativeToTargetResamplers[c].process(
+ resamplerRatio, inputReservoir.getReadPointer(c),
+ resampledBufferPointer, expectedResampledSamples);
+ }
+
+ if (samplesUsed < ioBlock.getNumSamples() + samplesInInputReservoir) {
+ // Take the missing samples and put them at the start of the input
+ // reservoir for next time:
+ int unusedInputSampleCount =
+ (ioBlock.getNumSamples() + samplesInInputReservoir) - samplesUsed;
+
+ juce::dsp::AudioBlock<SampleType> inputReservoirBlock(inputReservoir);
+ inputReservoirBlock.move(samplesUsed, 0, unusedInputSampleCount);
+ samplesInInputReservoir = unusedInputSampleCount;
+ } else {
+ samplesInInputReservoir = 0;
+ }
+ } else {
+ for (size_t c = 0; c < ioBlock.getNumChannels(); c++) {
+ SampleType *resampledBufferPointer =
+ resampledBuffer.getWritePointer(c) +
+ processedSamplesInResampledBuffer + cleanSamplesInResampledBuffer;
+ samplesUsed = nativeToTargetResamplers[c].process(
+ resamplerRatio, ioBlock.getChannelPointer(c),
+ resampledBufferPointer, (int)expectedResampledSamples);
+ }
+
+ if (samplesUsed < ioBlock.getNumSamples()) {
+ // Take the missing samples and put them at the start of the input
+ // reservoir for next time:
+ int unusedInputSampleCount = ioBlock.getNumSamples() - samplesUsed;
+ for (size_t c = 0; c < ioBlock.getNumChannels(); c++) {
+ inputReservoir.copyFrom(c, 0,
+ ioBlock.getChannelPointer(c) + samplesUsed,
+ unusedInputSampleCount);
+ }
+ samplesInInputReservoir = unusedInputSampleCount;
+ }
+ }
+
+ cleanSamplesInResampledBuffer += (int)expectedResampledSamples;
+
+ // Pass resampledBuffer to the plugin, in chunks:
+ juce::dsp::AudioBlock<SampleType> resampledBlock(resampledBuffer);
+
+ // Only pass in the maximumBlockSize (in target sample rate) that the
+ // sub-plugin expects:
+ while (cleanSamplesInResampledBuffer > 0) {
+ int cleanSamplesToProcess =
+ std::min((int)maximumBlockSizeInTargetSampleRate,
+ cleanSamplesInResampledBuffer);
+
+ juce::dsp::AudioBlock<SampleType> subBlock = resampledBlock.getSubBlock(
+ processedSamplesInResampledBuffer, cleanSamplesToProcess);
+ juce::dsp::ProcessContextReplacing<SampleType> subContext(subBlock);
+
+ int resampledSamplesOutput = plugin.process(subContext);
+
+ if (resampledSamplesOutput < cleanSamplesToProcess) {
+ // Move all remaining samples to the left of the buffer:
+ int offset = cleanSamplesToProcess - resampledSamplesOutput;
+
+ for (size_t c = 0; c < ioBlock.getNumChannels(); c++) {
+ // Move the contents of the resampled block to the left:
+ std::memmove(
+ (char *)resampledBuffer.getWritePointer(c) +
+ processedSamplesInResampledBuffer,
+ (char *)(resampledBuffer.getWritePointer(c) +
+ processedSamplesInResampledBuffer + offset),
+ (resampledSamplesOutput + cleanSamplesInResampledBuffer) *
+ sizeof(SampleType));
+ }
+ }
+ processedSamplesInResampledBuffer += resampledSamplesOutput;
+ cleanSamplesInResampledBuffer -= cleanSamplesToProcess;
+ }
+
+ // Resample back to the intended sample rate:
+ int expectedOutputSamples =
+ processedSamplesInResampledBuffer * resamplerRatio;
+
+ int samplesConsumed = 0;
+
+ if (spaceAvailableInOutputBuffer() < expectedOutputSamples) {
+ throw std::runtime_error(
+ "More samples were provided than can be buffered! This is an "
+ "internal Pedalboard error and should be reported. Buffer had " +
+ std::to_string(samplesInOutputBuffer) + "/" +
+ std::to_string(outputBuffer.getNumSamples()) +
+ " samples at native sample rate, but was provided " +
+ std::to_string(expectedOutputSamples) + ".");
+ }
+
+ for (size_t c = 0; c < ioBlock.getNumChannels(); c++) {
+ float *outputBufferPointer =
+ outputBuffer.getWritePointer(c) + samplesInOutputBuffer;
+ samplesConsumed = targetToNativeResamplers[c].process(
+ inverseResamplerRatio, resampledBuffer.getReadPointer(c),
+ outputBufferPointer, expectedOutputSamples);
+ }
+
+ samplesInOutputBuffer += expectedOutputSamples;
+
+ int samplesRemainingInResampledBuffer = processedSamplesInResampledBuffer +
+ cleanSamplesInResampledBuffer -
+ samplesConsumed;
+ if (samplesRemainingInResampledBuffer > 0) {
+ for (size_t c = 0; c < ioBlock.getNumChannels(); c++) {
+ // Move the contents of the resampled block to the left:
+ std::memmove(
+ (char *)resampledBuffer.getWritePointer(c),
+ (char *)(resampledBuffer.getWritePointer(c) + samplesConsumed),
+ (samplesRemainingInResampledBuffer) * sizeof(SampleType));
+ }
+ }
+
+ processedSamplesInResampledBuffer -= samplesConsumed;
+
+ // Copy from output buffer to output block:
+ int samplesToOutput =
+ std::min(ioBlock.getNumSamples(), (unsigned long)samplesInOutputBuffer);
+ ioBlock.copyFrom(outputBuffer, 0, ioBlock.getNumSamples() - samplesToOutput,
+ samplesToOutput);
+
+ int samplesRemainingInOutputBuffer =
+ samplesInOutputBuffer - samplesToOutput;
+ if (samplesRemainingInOutputBuffer > 0) {
+ for (size_t c = 0; c < ioBlock.getNumChannels(); c++) {
+ // Move the contents of the resampled block to the left:
+ std::memmove(
+ (char *)outputBuffer.getWritePointer(c),
+ (char *)(outputBuffer.getWritePointer(c) + samplesToOutput),
+ (samplesRemainingInOutputBuffer) * sizeof(SampleType));
+ }
+ }
+ samplesInOutputBuffer -= samplesToOutput;
+
+ samplesProduced += samplesToOutput;
+ int samplesToReturn = std::min((long)(samplesProduced - inStreamLatency),
+ (long)samplesToOutput);
+ if (samplesToReturn < 0)
+ samplesToReturn = 0;
+
+ return samplesToReturn;
+ }
+
+ SampleType getTargetSampleRate() const { return targetSampleRate; }
+ void setTargetSampleRate(const SampleType value) {
+ if (value <= 0.0) {
+ throw std::range_error("Target sample rate must be greater than 0Hz.");
+ }
+ targetSampleRate = value;
+ };
+
+ ResamplingQuality getQuality() const { return quality; }
+ void setQuality(const ResamplingQuality value) {
+ quality = value;
+ reset();
+ };
+
+ T &getNestedPlugin() { return plugin; }
+
+ virtual void reset() override final {
+ plugin.reset();
+
+ nativeToTargetResamplers.clear();
+ targetToNativeResamplers.clear();
+
+ resampledBuffer.clear();
+ outputBuffer.clear();
+ inputReservoir.clear();
+
+ cleanSamplesInResampledBuffer = 0;
+ processedSamplesInResampledBuffer = 0;
+ samplesInOutputBuffer = 0;
+ samplesInInputReservoir = 0;
+
+ samplesProduced = 0;
+ inStreamLatency = 0;
+ maximumBlockSizeInTargetSampleRate = 0;
+ }
+
+ virtual int getLatencyHint() override {
+ return inStreamLatency + (plugin.getLatencyHint() * resamplerRatio);
+ }
+
+private:
+ T plugin;
+ float targetSampleRate = (float)DefaultSampleRate;
+ ResamplingQuality quality = ResamplingQuality::WindowedSinc;
+
+ double resamplerRatio = 1.0;
+ double inverseResamplerRatio = 1.0;
+
+ juce::AudioBuffer<SampleType> inputReservoir;
+ int samplesInInputReservoir = 0;
+
+ std::vector<VariableQualityResampler> nativeToTargetResamplers;
+ juce::AudioBuffer<SampleType> resampledBuffer;
+ int cleanSamplesInResampledBuffer = 0;
+ int processedSamplesInResampledBuffer = 0;
+ std::vector<VariableQualityResampler> targetToNativeResamplers;
+
+ juce::AudioBuffer<SampleType> outputBuffer;
+ int samplesInOutputBuffer = 0;
+
+ int samplesProduced = 0;
+ int inStreamLatency = 0;
+ unsigned int maximumBlockSizeInTargetSampleRate = 0;
+
+ int spaceAvailableInResampledBuffer() const {
+ return resampledBuffer.getNumSamples() -
+ std::max(cleanSamplesInResampledBuffer,
+ processedSamplesInResampledBuffer);
+ }
+
+ int spaceAvailableInOutputBuffer() const {
+ return outputBuffer.getNumSamples() - samplesInOutputBuffer;
+ }
+};
+
+inline void init_resample(py::module &m) {
+ py::class_<Resample<Passthrough<float>, float>, Plugin> resample(
+ m, "Resample",
+ "A plugin that downsamples the input audio to the given sample rate, "
+ "then upsamples it again. Various quality settings will produce audible "
+ "distortion effects.");
+
+ py::enum_<ResamplingQuality>(resample, "Quality")
+ .value("ZeroOrderHold", ResamplingQuality::ZeroOrderHold,
+ "The lowest quality and fastest resampling method, with lots of "
+ "audible artifacts.")
+ .value("Linear", ResamplingQuality::Linear,
+ "A resampling method slightly less noisy than the simplest "
+ "method, but not by much.")
+ .value("CatmullRom", ResamplingQuality::CatmullRom,
+ "A moderately good-sounding resampling method which is fast to "
+ "run.")
+ .value("Lagrange", ResamplingQuality::Lagrange,
+ "A moderately good-sounding resampling method which is slow to "
+ "run.")
+ .value("WindowedSinc", ResamplingQuality::WindowedSinc,
+ "The highest quality and slowest resampling method, with no "
+ "audible artifacts.")
+ .export_values();
+
+ resample
+ .def(py::init([](float targetSampleRate, ResamplingQuality quality) {
+ auto resampler =
+ std::make_unique<Resample<Passthrough<float>, float>>();
+ resampler->setTargetSampleRate(targetSampleRate);
+ resampler->setQuality(quality);
+ return resampler;
+ }),
+ py::arg("target_sample_rate") = 8000.0,
+ py::arg("quality") = ResamplingQuality::WindowedSinc)
+ .def("__repr__",
+ [](const Resample<Passthrough<float>, float> &plugin) {
+ std::ostringstream ss;
+ ss << "<pedalboard.Resample";
+ ss << " target_sample_rate=" << plugin.getTargetSampleRate();
+ ss << " quality=";
+ switch (plugin.getQuality()) {
+ case ResamplingQuality::ZeroOrderHold:
+ ss << "ZeroOrderHold";
+ break;
+ case ResamplingQuality::Linear:
+ ss << "Linear";
+ break;
+ case ResamplingQuality::CatmullRom:
+ ss << "CatmullRom";
+ break;
+ case ResamplingQuality::Lagrange:
+ ss << "Lagrange";
+ break;
+ case ResamplingQuality::WindowedSinc:
+ ss << "WindowedSinc";
+ break;
+ default:
+ ss << "unknown";
+ break;
+ }
+ ss << " at " << &plugin;
+ ss << ">";
+ return ss.str();
+ })
+ .def_property("target_sample_rate",
+ &Resample<Passthrough<float>, float>::getTargetSampleRate,
+ &Resample<Passthrough<float>, float>::setTargetSampleRate)
+ .def_property("quality", &Resample<Passthrough<float>, float>::getQuality,
+ &Resample<Passthrough<float>, float>::setQuality);
+}
+
+/**
+ * An internal test plugin that does nothing but add latency to the resampled
+ * signal.
+ */
+inline void init_resample_with_latency(py::module &m) {
+ py::class_<Resample<AddLatency, float>, Plugin>(m, "ResampleWithLatency")
+ .def(py::init([](float targetSampleRate, int internalLatency,
+ ResamplingQuality quality) {
+ auto plugin = std::make_unique<Resample<AddLatency, float>>();
+ plugin->setTargetSampleRate(targetSampleRate);
+ plugin->getNestedPlugin().getDSP().setMaximumDelayInSamples(
+ internalLatency);
+ plugin->getNestedPlugin().getDSP().setDelay(internalLatency);
+ plugin->setQuality(quality);
+ return plugin;
+ }),
+ py::arg("target_sample_rate") = 8000.0,
+ py::arg("internal_latency") = 1024,
+ py::arg("quality") = ResamplingQuality::WindowedSinc)
+ .def("__repr__",
+ [](Resample<AddLatency, float> &plugin) {
+ std::ostringstream ss;
+ ss << "<pedalboard.ResampleWithLatency";
+ ss << " target_sample_rate=" << plugin.getTargetSampleRate();
+ ss << " internal_latency="
+ << plugin.getNestedPlugin().getDSP().getDelay();
+ ss << " quality=";
+ switch (plugin.getQuality()) {
+ case ResamplingQuality::ZeroOrderHold:
+ ss << "ZeroOrderHold";
+ break;
+ case ResamplingQuality::Linear:
+ ss << "Linear";
+ break;
+ case ResamplingQuality::CatmullRom:
+ ss << "CatmullRom";
+ break;
+ case ResamplingQuality::Lagrange:
+ ss << "Lagrange";
+ break;
+ case ResamplingQuality::WindowedSinc:
+ ss << "WindowedSinc";
+ break;
+ default:
+ ss << "unknown";
+ break;
+ }
+ ss << " at " << &plugin;
+ ss << ">";
+ return ss.str();
+ })
+ .def_property("target_sample_rate",
+ &Resample<AddLatency, float>::getTargetSampleRate,
+ &Resample<AddLatency, float>::setTargetSampleRate)
+ .def_property("quality", &Resample<AddLatency, float>::getQuality,
+ &Resample<AddLatency, float>::setQuality);
+}
+
+} // namespace Pedalboard
\ No newline at end of file
diff --git a/pedalboard/python_bindings.cpp b/pedalboard/python_bindings.cpp
index 170809e..8ddd9a5 100644
--- a/pedalboard/python_bindings.cpp
+++ b/pedalboard/python_bindings.cpp
@@ -32,6 +32,9 @@ namespace py = pybind11;
#include "Plugin.h"
#include "process.h"
+#include "plugin_templates/Resample.h"
+#include "plugin_templates/PrimeWithSilence.h"
+
#include "plugins/AddLatency.h"
#include "plugins/Chorus.h"
#include "plugins/Compressor.h"
@@ -50,8 +53,6 @@ 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;
@@ -138,6 +139,7 @@ PYBIND11_MODULE(pedalboard_native, m) {
py::arg("reset") = true);
plugin.attr("__call__") = plugin.attr("process");
+ // Publicly accessible plugins:
init_chorus(m);
init_compressor(m);
init_convolution(m);
@@ -153,6 +155,7 @@ PYBIND11_MODULE(pedalboard_native, m) {
init_noisegate(m);
init_phaser(m);
init_pitch_shift(m);
+ init_resample(m);
init_reverb(m);
init_external_plugins(m);
@@ -161,4 +164,5 @@ PYBIND11_MODULE(pedalboard_native, m) {
py::module internal = m.def_submodule("_internal");
init_add_latency(internal);
init_prime_with_silence_test_plugin(internal);
+ init_resample_with_latency(internal);
};
diff --git a/tests/test_resample.py b/tests/test_resample.py
new file mode 100644
index 0000000..5273b11
--- /dev/null
+++ b/tests/test_resample.py
@@ -0,0 +1,161 @@
+#! /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 import Pedalboard, Resample
+from pedalboard_native._internal import ResampleWithLatency
+from .utils import generate_sine_at
+
+TOLERANCE_PER_QUALITY = {
+ Resample.Quality.ZeroOrderHold: 0.65,
+ Resample.Quality.Linear: 0.35,
+ Resample.Quality.CatmullRom: 0.16,
+ Resample.Quality.Lagrange: 0.16,
+ Resample.Quality.WindowedSinc: 0.151,
+}
+
+DURATIONS = [0.345678]
+
+
[email protected]("fundamental_hz", [440])
[email protected]("sample_rate", [8000, 11025, 22050, 44100, 48000])
[email protected]("target_sample_rate", [8000, 11025, 12345.67, 22050, 44100, 48000])
[email protected]("buffer_size", [1, 32, 8192, 1_000_000])
[email protected]("duration", DURATIONS)
[email protected]("num_channels", [1, 2])
[email protected]("quality", TOLERANCE_PER_QUALITY.keys())
[email protected]("plugin_class", [Resample, ResampleWithLatency])
+def test_resample(
+ fundamental_hz: float,
+ sample_rate: float,
+ target_sample_rate: float,
+ buffer_size: int,
+ duration: float,
+ num_channels: int,
+ quality: Resample.Quality,
+ plugin_class,
+):
+ sine_wave = generate_sine_at(sample_rate, fundamental_hz, num_channels=num_channels)
+ plugin = plugin_class(target_sample_rate, quality=quality)
+ output = plugin.process(sine_wave, sample_rate, buffer_size=buffer_size)
+ np.testing.assert_allclose(sine_wave, output, atol=TOLERANCE_PER_QUALITY[quality])
+
+
+
[email protected]("fundamental_hz", [440])
[email protected]("sample_rate", [1234.56, 8000, 11025, 48000])
[email protected]("target_sample_rate", [1234.56, 8000, 11025, 48000])
[email protected]("duration", DURATIONS)
[email protected]("num_channels", [1, 2])
[email protected]("quality", TOLERANCE_PER_QUALITY.keys())
[email protected]("plugin_class", [Resample, ResampleWithLatency])
+def test_resample_invariant_to_buffer_size(
+ fundamental_hz: float,
+ sample_rate: float,
+ target_sample_rate: float,
+ duration: float,
+ num_channels: int,
+ quality: Resample.Quality,
+ plugin_class,
+):
+ sine_wave = generate_sine_at(sample_rate, fundamental_hz, num_channels=num_channels)
+ plugin = plugin_class(target_sample_rate, quality=quality)
+
+ buffer_sizes = [1, 7000, 8192, 1_000_000]
+ outputs = [
+ plugin.process(sine_wave, sample_rate, buffer_size=buffer_size)
+ for buffer_size in buffer_sizes
+ ]
+
+ for a, b in zip(outputs, outputs[1:]):
+ np.testing.assert_allclose(a, b)
+
+
[email protected]("fundamental_hz", [440])
[email protected]("sample_rate_multiple", [1, 2, 3, 4, 20])
[email protected]("sample_rate", [8000, 44100, 48000])
[email protected]("buffer_size", [1, 32, 128, 8192, 1_000_000])
[email protected]("duration", DURATIONS)
[email protected]("num_channels", [1, 2])
[email protected]("plugin_class", [Resample, ResampleWithLatency])
+def test_identical_noise_with_zero_order_hold(
+ fundamental_hz: float,
+ sample_rate_multiple: float,
+ sample_rate: float,
+ buffer_size: int,
+ duration: float,
+ num_channels: int,
+ plugin_class,
+):
+ noise = np.random.rand(int(duration * sample_rate))
+ if num_channels == 2:
+ noise = np.stack([noise, noise])
+
+ plugin = plugin_class(
+ sample_rate * sample_rate_multiple, quality=Resample.Quality.ZeroOrderHold
+ )
+ output = plugin.process(noise, sample_rate, buffer_size=buffer_size)
+ np.testing.assert_allclose(noise, output)
+
+
[email protected]("fundamental_hz", [10])
[email protected]("sample_rate", [100, 384_123.45])
[email protected]("target_sample_rate", [100, 384_123.45])
[email protected]("buffer_size", [1, 1_000_000])
[email protected]("duration", DURATIONS)
[email protected]("num_channels", [1, 2])
[email protected]("quality", TOLERANCE_PER_QUALITY.keys())
[email protected]("plugin_class", [Resample, ResampleWithLatency])
+def test_extreme_resampling(
+ fundamental_hz: float,
+ sample_rate: float,
+ target_sample_rate: float,
+ buffer_size: int,
+ duration: float,
+ num_channels: int,
+ quality: Resample.Quality,
+ plugin_class,
+):
+ sine_wave = generate_sine_at(sample_rate, fundamental_hz, num_channels=num_channels)
+ plugin = plugin_class(target_sample_rate, quality=quality)
+ output = plugin.process(sine_wave, sample_rate, buffer_size=buffer_size)
+ np.testing.assert_allclose(sine_wave, output, atol=TOLERANCE_PER_QUALITY[quality])
+
+
[email protected]("num_channels", [1, 2])
+def test_quality_can_change(
+ num_channels: int,
+ fundamental_hz: float = 440,
+ sample_rate: float = 8000,
+ buffer_size: int = 96000,
+ duration: float = DURATIONS[0],
+):
+ sine_wave = generate_sine_at(sample_rate, fundamental_hz, num_channels=num_channels)
+
+ plugin = Resample(sample_rate)
+ output1 = plugin.process(sine_wave, sample_rate, buffer_size=buffer_size)
+ np.testing.assert_allclose(sine_wave, output1, atol=TOLERANCE_PER_QUALITY[plugin.quality])
+ original_quality = plugin.quality
+
+ plugin.quality = Resample.Quality.ZeroOrderHold
+ output2 = plugin.process(sine_wave, sample_rate, buffer_size=buffer_size)
+ np.testing.assert_allclose(sine_wave, output2, atol=TOLERANCE_PER_QUALITY[plugin.quality])
+
+ plugin.quality = original_quality
+ output3 = plugin.process(sine_wave, sample_rate, buffer_size=buffer_size)
+ np.testing.assert_allclose(output1, output3)
diff --git a/tests/utils.py b/tests/utils.py
new file mode 100644
index 0000000..55ba88b
--- /dev/null
+++ b/tests/utils.py
@@ -0,0 +1,25 @@
+import numpy as np
+
+
+TEST_SINE_WAVE_CACHE = {}
+
+
+def generate_sine_at(
+ sample_rate: float,
+ fundamental_hz: float = 440.0,
+ num_seconds: float = 3.0,
+ num_channels: int = 1,
+) -> np.ndarray:
+ cache_key = "-".join([str(x) for x in [sample_rate, fundamental_hz, num_seconds, num_channels]])
+ if cache_key not in TEST_SINE_WAVE_CACHE:
+ samples = np.arange(num_seconds * sample_rate)
+ sine_wave = np.sin(2 * np.pi * fundamental_hz * samples / sample_rate)
+ # Fade the sine wave in at the start and out at the end to remove any transients:
+ fade_duration = int(sample_rate * 0.1)
+ sine_wave[:fade_duration] *= np.linspace(0, 1, fade_duration)
+ sine_wave[-fade_duration:] *= np.linspace(1, 0, fade_duration)
+ if num_channels == 2:
+ TEST_SINE_WAVE_CACHE[cache_key] = np.stack([sine_wave, sine_wave])
+ else:
+ TEST_SINE_WAVE_CACHE[cache_key] = sine_wave
+ return TEST_SINE_WAVE_CACHE[cache_key]