Skip to content

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

Add latency compensation support.

Peter Sobot0b7e09d6748f
diff --git a/pedalboard/ExternalPlugin.h b/pedalboard/ExternalPlugin.h
index ea2762d..7690857 100644
--- a/pedalboard/ExternalPlugin.h
+++ b/pedalboard/ExternalPlugin.h
@@ -514,6 +514,7 @@ public:
// Force prepare() to be called again later by invalidating lastSpec:
lastSpec.maximumBlockSize = 0;
+ samplesProvided = 0;
}
}
@@ -543,8 +544,8 @@ public:
}
}
- void
- process(const juce::dsp::ProcessContextReplacing<float> &context) override {
+ int process(
+ const juce::dsp::ProcessContextReplacing<float> &context) override {
if (pluginInstance) {
juce::MidiBuffer emptyMidiBuffer;
@@ -614,7 +615,17 @@ public:
pluginBufferChannelCount,
outputBlock.getNumSamples());
pluginInstance->processBlock(audioBuffer, emptyMidiBuffer);
+ samplesProvided += outputBlock.getNumSamples();
+
+ // To compensate for any latency added by the plugin,
+ // only tell Pedalboard to use the last _n_ samples.
+ long usableSamplesProduced =
+ samplesProvided - pluginInstance->getLatencySamples();
+ return (int)std::min(usableSamplesProduced,
+ (long)outputBlock.getNumSamples());
}
+
+ return 0;
}
std::vector<juce::AudioProcessorParameter *> getParameters() const {
@@ -634,6 +645,12 @@ public:
return nullptr;
}
+ virtual int getLatencyHint() override {
+ if (!pluginInstance)
+ return 0;
+ return pluginInstance->getLatencySamples();
+ }
+
private:
constexpr static int ExternalLoadSampleRate = 44100,
ExternalLoadMaximumBlockSize = 8192;
@@ -642,6 +659,8 @@ private:
juce::AudioPluginFormatManager pluginFormatManager;
std::unique_ptr<juce::AudioPluginInstance> pluginInstance;
+ long samplesProvided = 0;
+
ExternalPluginReloadType reloadType = ExternalPluginReloadType::Unknown;
};
diff --git a/pedalboard/JucePlugin.h b/pedalboard/JucePlugin.h
index 6fad019..8c2526a 100644
--- a/pedalboard/JucePlugin.h
+++ b/pedalboard/JucePlugin.h
@@ -58,12 +58,13 @@ public:
}
}
- void process(
- const juce::dsp::ProcessContextReplacing<float> &context) override final {
+ int process(
+ const juce::dsp::ProcessContextReplacing<float> &context) override {
dspBlock.process(context);
+ return context.getOutputBlock().getNumSamples();
}
- void reset() override final { dspBlock.reset(); }
+ void reset() override { dspBlock.reset(); }
DSPType &getDSP() { return dspBlock; };
diff --git a/pedalboard/Plugin.h b/pedalboard/Plugin.h
index e9ce6f8..5acc11c 100644
--- a/pedalboard/Plugin.h
+++ b/pedalboard/Plugin.h
@@ -28,13 +28,48 @@ class Plugin {
public:
virtual ~Plugin(){};
+ /**
+ * Prepare the data structures that will be necessary for this plugin to
+ * process audio at the provided sample rate, maximum block size, and number
+ * of channels.
+ */
virtual void prepare(const juce::dsp::ProcessSpec &spec) = 0;
- virtual void
+ /**
+ * Process a single buffer of audio through this plugin.
+ * Returns the number of samples that were output.
+ *
+ * If less than a whole buffer of audio was output, the samples that
+ * were produced should be right-aligned in the buffer
+ * (i.e.: they should come last).
+ */
+ virtual int
process(const juce::dsp::ProcessContextReplacing<float> &context) = 0;
+ /**
+ * Reset this plugin's state, clearing any internal buffers or delay lines.
+ */
virtual void reset() = 0;
+ /**
+ * Get the number of samples of latency introduced by this plugin.
+ * This is the number of samples that must be provided to the plugin
+ * before meaningful output will be returned.
+ * Pedalboard will automatically compensate for this latency when processing
+ * by using the return value from the process() call, but this hint can
+ * make processing more efficient.
+ *
+ * This function will only be called after prepare(), so it can take into
+ * account variables like the current sample rate, maximum block size, and
+ * other plugin parameters.
+ *
+ * Returning a value from getLatencyHint() that is larger than necessary will
+ * allocate that many extra samples during processing, increasing memory usage.
+ * Returning a value that is too small will cause memory to be reallocated
+ * during rendering, impacting rendering speed.
+ */
+ virtual int getLatencyHint() { return 0; }
+
// A mutex to gate access to this plugin, as its internals may not be
// thread-safe. Note: use std::lock or std::scoped_lock when locking multiple
// plugins to avoid deadlocking.
diff --git a/pedalboard/plugins/DelayLine.h b/pedalboard/plugins/DelayLine.h
new file mode 100644
index 0000000..09025de
--- /dev/null
+++ b/pedalboard/plugins/DelayLine.h
@@ -0,0 +1,69 @@
+/*
+ * 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 {
+
+/**
+ * A dummy plugin that buffers audio data internally, used to test Pedalboard's
+ * automatic delay compensation.
+ */
+class DelayLine : public JucePlugin<juce::dsp::DelayLine<
+ float, juce::dsp::DelayLineInterpolationTypes::None>> {
+public:
+ virtual ~DelayLine(){};
+
+ virtual void reset() override {
+ getDSP().reset();
+ samplesProvided = 0;
+ }
+
+ virtual int
+ process(const juce::dsp::ProcessContextReplacing<float> &context) override {
+ getDSP().process(context);
+ int blockSize = context.getInputBlock().getNumSamples();
+ samplesProvided += blockSize;
+
+ return std::min((int)blockSize,
+ std::max(0, (int)(samplesProvided - getDSP().getDelay())));
+ }
+
+ virtual int getLatencyHint() override {
+ return getDSP().getDelay();
+ }
+
+private:
+ int samplesProvided = 0;
+};
+
+inline void init_delay_line(py::module &m) {
+ py::class_<DelayLine, Plugin>(
+ m, "DelayLine",
+ "A dummy plugin that delays input audio for the given number of samples "
+ "before passing it back to the output. Used internally to test "
+ "Pedalboard's automatic latency compensation. Probably not useful as a "
+ "real effect.")
+ .def(py::init([](int samples) {
+ auto dl = new DelayLine();
+ dl->getDSP().setMaximumDelayInSamples(samples);
+ dl->getDSP().setDelay(samples);
+ return dl;
+ }),
+ py::arg("samples") = 44100);
+}
+}; // namespace Pedalboard
diff --git a/pedalboard/process.h b/pedalboard/process.h
index fb1f3a2..83f1357 100644
--- a/pedalboard/process.h
+++ b/pedalboard/process.h
@@ -57,40 +57,51 @@ processSingle(const py::array_t<SampleType, py::array::c_style> inputArray,
reset);
}
-/**
- * Process a given audio buffer through a list of
- * Pedalboard plugins at a given sample rate.
- * Only supports float processing, not double, at the moment.
- */
-template <>
-py::array_t<float>
-process<float>(const py::array_t<float, py::array::c_style> inputArray,
- double sampleRate, const std::vector<Plugin *> &plugins,
- unsigned int bufferSize, bool reset) {
+template <typename T>
+ChannelLayout
+detectChannelLayout(const py::array_t<T, py::array::c_style> inputArray) {
+ py::buffer_info inputInfo = inputArray.request();
+
+ if (inputInfo.ndim == 1) {
+ return ChannelLayout::Interleaved;
+ } else if (inputInfo.ndim == 2) {
+ // Try to auto-detect the channel layout from the shape
+ if (inputInfo.shape[1] < inputInfo.shape[0]) {
+ return ChannelLayout::Interleaved;
+ } else if (inputInfo.shape[0] < inputInfo.shape[1]) {
+ return ChannelLayout::NotInterleaved;
+ } else {
+ throw std::runtime_error(
+ "Unable to determine channel layout from shape!");
+ }
+ } else {
+ throw std::runtime_error("Number of input dimensions must be 1 or 2.");
+ }
+}
+
+template <typename T>
+juce::AudioBuffer<T>
+copyPyArrayIntoJuceBuffer(const py::array_t<T, py::array::c_style> inputArray) {
// Numpy/Librosa convention is (num_samples, num_channels)
py::buffer_info inputInfo = inputArray.request();
unsigned int numChannels = 0;
unsigned int numSamples = 0;
- ChannelLayout inputChannelLayout;
+ ChannelLayout inputChannelLayout = detectChannelLayout(inputArray);
if (inputInfo.ndim == 1) {
numSamples = inputInfo.shape[0];
numChannels = 1;
- inputChannelLayout = ChannelLayout::Interleaved;
} else if (inputInfo.ndim == 2) {
// Try to auto-detect the channel layout from the shape
if (inputInfo.shape[1] < inputInfo.shape[0]) {
numSamples = inputInfo.shape[0];
numChannels = inputInfo.shape[1];
- inputChannelLayout = ChannelLayout::Interleaved;
} else if (inputInfo.shape[0] < inputInfo.shape[1]) {
numSamples = inputInfo.shape[1];
numChannels = inputInfo.shape[0];
- inputChannelLayout = ChannelLayout::NotInterleaved;
} else {
- throw std::runtime_error(
- "Unable to determine channel layout from shape!");
+ throw std::runtime_error("Unable to determine shape of audio input!");
}
} else {
throw std::runtime_error("Number of input dimensions must be 1 or 2.");
@@ -102,19 +113,105 @@ process<float>(const py::array_t<float, py::array::c_style> inputArray,
throw std::runtime_error("More than two channels received!");
}
- // Cap the buffer size in use to the size of the input data:
- bufferSize = std::min(bufferSize, numSamples);
+ juce::AudioBuffer<T> ioBuffer(numChannels, numSamples);
+
+ // Depending on the input channel layout, we need to copy data
+ // differently. This loop is duplicated here to move the if statement
+ // outside of the tight loop, as we don't need to re-check that the input
+ // channel is still the same on every iteration of the loop.
+ switch (inputChannelLayout) {
+ case ChannelLayout::Interleaved:
+ for (unsigned int i = 0; i < numChannels; i++) {
+ T *channelBuffer = ioBuffer.getWritePointer(i);
+ // We're de-interleaving the data here, so we can't use copyFrom.
+ for (unsigned int j = 0; j < numSamples; j++) {
+ channelBuffer[j] = static_cast<T *>(inputInfo.ptr)[j * numChannels + i];
+ }
+ }
+ break;
+ case ChannelLayout::NotInterleaved:
+ for (unsigned int i = 0; i < numChannels; i++) {
+ ioBuffer.copyFrom(
+ i, 0, static_cast<T *>(inputInfo.ptr) + (numSamples * i), numSamples);
+ }
+ }
+
+ return ioBuffer;
+}
+
+template <typename T>
+py::array_t<T> copyJuceBufferIntoPyArray(const juce::AudioBuffer<T> juceBuffer,
+ ChannelLayout channelLayout,
+ int offsetSamples, int ndim = 2) {
+ unsigned int numChannels = juceBuffer.getNumChannels();
+ unsigned int numSamples = juceBuffer.getNumSamples();
+ unsigned int outputSampleCount =
+ std::max((int)numSamples - (int)offsetSamples, 0);
+
+ // TODO: Avoid the need to copy here if offsetSamples is 0!
+ py::array_t<T> outputArray;
+ if (ndim == 2) {
+ switch (channelLayout) {
+ case ChannelLayout::Interleaved:
+ outputArray = py::array_t<T>({outputSampleCount, numChannels});
+ break;
+ case ChannelLayout::NotInterleaved:
+ outputArray = py::array_t<T>({numChannels, outputSampleCount});
+ break;
+ }
+ } else {
+ outputArray = py::array_t<T>(outputSampleCount);
+ }
- // JUCE uses separate channel buffers, so the output shape is (num_channels,
- // num_samples)
- py::array_t<float> outputArray =
- inputInfo.ndim == 2 ? py::array_t<float>({numChannels, numSamples})
- : py::array_t<float>(numSamples);
py::buffer_info outputInfo = outputArray.request();
+ // Depending on the input channel layout, we need to copy data
+ // differently. This loop is duplicated here to move the if statement
+ // outside of the tight loop, as we don't need to re-check that the input
+ // channel is still the same on every iteration of the loop.
+ T *outputBasePointer = static_cast<T *>(outputInfo.ptr);
+
+ switch (channelLayout) {
+ case ChannelLayout::Interleaved:
+ for (unsigned int i = 0; i < numChannels; i++) {
+ const T *channelBuffer = juceBuffer.getReadPointer(i, offsetSamples);
+ // We're interleaving the data here, so we can't use copyFrom.
+ for (unsigned int j = 0; j < outputSampleCount; j++) {
+ outputBasePointer[j * numChannels + i] = channelBuffer[j];
+ }
+ }
+ break;
+ case ChannelLayout::NotInterleaved:
+ for (unsigned int i = 0; i < numChannels; i++) {
+ const T *channelBuffer = juceBuffer.getReadPointer(i, offsetSamples);
+ std::copy(channelBuffer, channelBuffer + outputSampleCount,
+ &outputBasePointer[outputSampleCount * i]);
+ }
+ break;
+ }
+
+ return outputArray;
+}
+
+/**
+ * Process a given audio buffer through a list of
+ * Pedalboard plugins at a given sample rate.
+ * Only supports float processing, not double, at the moment.
+ */
+template <>
+py::array_t<float>
+process<float>(const py::array_t<float, py::array::c_style> inputArray,
+ double sampleRate, const std::vector<Plugin *> &plugins,
+ unsigned int bufferSize, bool reset) {
+ const ChannelLayout inputChannelLayout = detectChannelLayout(inputArray);
+ juce::AudioBuffer<float> ioBuffer = copyPyArrayIntoJuceBuffer(inputArray);
+ int totalOutputLatencySamples = 0;
+
{
py::gil_scoped_release release;
+ bufferSize = std::min(bufferSize, (unsigned int)ioBuffer.getNumSamples());
+
unsigned int countOfPluginsIgnoringNull = 0;
for (auto *plugin : plugins) {
if (plugin == nullptr)
@@ -165,75 +262,119 @@ process<float>(const py::array_t<float, py::array::c_style> inputArray,
juce::dsp::ProcessSpec spec;
spec.sampleRate = sampleRate;
spec.maximumBlockSize = static_cast<juce::uint32>(bufferSize);
- spec.numChannels = static_cast<juce::uint32>(numChannels);
+ spec.numChannels = static_cast<juce::uint32>(ioBuffer.getNumChannels());
+
+ int expectedOutputLatency = 0;
for (auto *plugin : plugins) {
if (plugin == nullptr)
continue;
plugin->prepare(spec);
+ expectedOutputLatency += plugin->getLatencyHint();
}
- // Manually construct channel pointers to pass to AudioBuffer.
- std::vector<float *> ioBufferChannelPointers(numChannels);
- for (unsigned int i = 0; i < numChannels; i++) {
- ioBufferChannelPointers[i] = ((float *)outputInfo.ptr) + (i * numSamples);
+ int intendedOutputBufferSize = ioBuffer.getNumSamples();
+
+ if (expectedOutputLatency > 0) {
+ // This is a hint - it's possible that the plugin(s) latency values
+ // will change and we'll have to reallocate again later on.
+ ioBuffer.setSize(ioBuffer.getNumChannels(),
+ ioBuffer.getNumSamples() + expectedOutputLatency,
+ /* keepExistingContent= */ true,
+ /* clearExtraSpace= */ true);
}
+
+ // Actually run the plugins over the ioBuffer, in small chunks, to minimize
+ // memory usage:
+ int startOfOutputInBuffer = 0;
+ int lastSampleInBuffer = 0;
+
+ for (auto *plugin : plugins) {
+ if (plugin == nullptr)
+ continue;
- juce::AudioBuffer<float> ioBuffer(ioBufferChannelPointers.data(),
- numChannels, numSamples);
-
- for (unsigned int blockStart = 0; blockStart < numSamples;
- blockStart += bufferSize) {
- unsigned int blockEnd = std::min(blockStart + bufferSize,
- static_cast<unsigned int>(numSamples));
- unsigned int blockSize = blockEnd - blockStart;
-
- // Copy the input audio into the ioBuffer, which will be used for
- // processing and will be returned.
-
- // Depending on the input channel layout, we need to copy data
- // differently. This loop is duplicated here to move the if statement
- // outside of the tight loop, as we don't need to re-check that the input
- // channel is still the same on every iteration of the loop.
- switch (inputChannelLayout) {
- case ChannelLayout::Interleaved:
- for (unsigned int i = 0; i < numChannels; i++) {
- // We're de-interleaving the data here, so we can't use std::copy.
- for (unsigned int j = blockStart; j < blockEnd; j++) {
- ioBufferChannelPointers[i][j] =
- static_cast<float *>(inputInfo.ptr)[j * numChannels + i];
+ int pluginSamplesReceived = 0;
+
+ for (unsigned int blockStart = startOfOutputInBuffer;
+ blockStart < (unsigned int)ioBuffer.getNumSamples();
+ blockStart += bufferSize) {
+ unsigned int blockEnd =
+ std::min(blockStart + bufferSize,
+ static_cast<unsigned int>(ioBuffer.getNumSamples()));
+ unsigned int blockSize = blockEnd - blockStart;
+
+ auto ioBlock = juce::dsp::AudioBlock<float>(
+ ioBuffer.getArrayOfWritePointers(), ioBuffer.getNumChannels(),
+ blockStart, blockSize);
+ juce::dsp::ProcessContextReplacing<float> context(ioBlock);
+
+ int outputSamples = plugin->process(context);
+ pluginSamplesReceived += outputSamples;
+
+ int missingSamples = blockSize - outputSamples;
+ if (missingSamples > 0 && pluginSamplesReceived > 0) {
+ // This can only happen if the plugin we're using is returning us more
+ // than one chunk of audio that's not completely full, which can
+ // happen sometimes. In this case, we would end up with gaps in the
+ // audio output:
+ // empty empty full part
+ // [______|______|AAAAAA|__BBBB]
+ // end of most recently rendered block-->-^
+ // We need to consolidate those gaps by moving them forward in time.
+ // To do so, we take the section from the earliest known output to the
+ // start of this block, and right-align it to the left side of the
+ // current block's content:
+ // empty empty part full
+ // [______|______|__AAAA|AABBBB]
+ // end of most recently rendered block-->-^
+ for (int c = 0; c < ioBuffer.getNumChannels(); c++) {
+ // Only move the samples received before this latest block was
+ // rendered, as audio is right-aligned within blocks by convention.
+ int samplesToMove = pluginSamplesReceived - outputSamples;
+ float *outputStart =
+ ioBuffer.getWritePointer(c) + totalOutputLatencySamples;
+ float *expectedOutputEnd =
+ ioBuffer.getWritePointer(c) + blockEnd - outputSamples;
+ float *expectedOutputStart = expectedOutputEnd - samplesToMove;
+
+ std::memmove((char *)expectedOutputStart, (char *)outputStart,
+ sizeof(float) * samplesToMove);
}
}
- break;
- case ChannelLayout::NotInterleaved:
- for (unsigned int i = 0; i < numChannels; i++) {
- const float *channelBuffer =
- static_cast<float *>(inputInfo.ptr) + (i * numSamples);
- std::copy(channelBuffer + blockStart, channelBuffer + blockEnd,
- ioBufferChannelPointers[i] + blockStart);
- }
- }
- auto ioBlock = juce::dsp::AudioBlock<float>(
- ioBufferChannelPointers.data(), numChannels, blockStart, blockSize);
- juce::dsp::ProcessContextReplacing<float> context(ioBlock);
+ lastSampleInBuffer =
+ std::max(lastSampleInBuffer, (int)(blockStart + outputSamples));
+ startOfOutputInBuffer += missingSamples;
+ totalOutputLatencySamples += missingSamples;
- // Now all of the pointers in context are pointing to valid input data,
- // so let's run the plugins.
- for (auto *plugin : plugins) {
- if (plugin == nullptr)
- continue;
- plugin->process(context);
+ if (missingSamples && reset) {
+ // Resize the IO buffer to give us a bit more room
+ // on the end, so we can continue to write delayed output.
+ // Only do this if reset=True was passed, as we can use that
+ // as a proxy for the user's intent to call `process` again.
+ intendedOutputBufferSize += missingSamples;
+
+ if (intendedOutputBufferSize > ioBuffer.getNumSamples()) {
+ ioBuffer.setSize(ioBuffer.getNumChannels(),
+ intendedOutputBufferSize,
+ /* keepExistingContent= */ true,
+ /* clearExtraSpace= */ true);
+ }
+ }
}
}
- }
- switch (inputChannelLayout) {
- case ChannelLayout::Interleaved:
- return outputArray.attr("transpose")();
- case ChannelLayout::NotInterleaved:
- default:
- return outputArray;
+ // Trim the output buffer down to size; this operation should be free.
+ jassert(intendedOutputBufferSize <= ioBuffer.getNumSamples());
+ ioBuffer.setSize(ioBuffer.getNumChannels(),
+ intendedOutputBufferSize,
+ /* keepExistingContent= */ true,
+ /* clearExtraSpace= */ true,
+ /* avoidReallocating= */ true);
}
+
+ return copyJuceBufferIntoPyArray(ioBuffer, inputChannelLayout,
+ totalOutputLatencySamples,
+ inputArray.request().ndim);
};
} // namespace Pedalboard
\ No newline at end of file
diff --git a/pedalboard/python_bindings.cpp b/pedalboard/python_bindings.cpp
index ae0ed8a..f9b6e41 100644
--- a/pedalboard/python_bindings.cpp
+++ b/pedalboard/python_bindings.cpp
@@ -35,6 +35,7 @@ namespace py = pybind11;
#include "plugins/Chorus.h"
#include "plugins/Compressor.h"
#include "plugins/Convolution.h"
+#include "plugins/DelayLine.h"
#include "plugins/Distortion.h"
#include "plugins/Gain.h"
#include "plugins/HighpassFilter.h"
@@ -147,4 +148,8 @@ PYBIND11_MODULE(pedalboard_native, m) {
init_reverb(m);
init_external_plugins(m);
+
+ // Internal plugins for testing, debugging, etc:
+ py::module internal = m.def_submodule("_internal");
+ init_delay_line(internal);
};
diff --git a/tests/test_external_plugins.py b/tests/test_external_plugins.py
index 7f1d014..6b7bd42 100644
--- a/tests/test_external_plugins.py
+++ b/tests/test_external_plugins.py
@@ -33,6 +33,7 @@ from pedalboard.pedalboard import (
import pytest
import pedalboard
import numpy as np
+from typing import Optional
TEST_PLUGIN_BASE_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), "plugins")
@@ -144,6 +145,16 @@ if os.environ.get("ENABLE_TESTING_WITH_LOCAL_PLUGINS", False):
pass
+def plugin_named(*substrings: str) -> Optional[str]:
+ """
+ Return the first plugin filename that contains all of the
+ provided substrings from the list of available test plugins.
+ """
+ for plugin_filename in AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT:
+ if all([s in plugin_filename for s in substrings]):
+ return plugin_filename
+
+
def max_volume_of(x: np.ndarray) -> float:
return np.amax(np.abs(x))
@@ -589,3 +600,24 @@ def test_wrapped_bool_requires_bool():
)
def test_parameter_name_normalization(_input: str, expected: str):
assert normalize_python_parameter_name(_input) == expected
+
+
[email protected](not plugin_named("CHOWTapeModel"), reason="Missing CHOWTapeModel plugin.")
[email protected]("buffer_size", [128, 8192, 65536])
[email protected]("oversampling", [1, 2, 4, 8, 16])
+def test_external_plugin_latency_compensation(buffer_size: int, oversampling: int):
+ """
+ This test loads CHOWTapeModel (which has non-zero latency due
+ to an internal oversampler), puts it into Bypass mode, then
+ ensures that the input matches the output exactly.
+ """
+ num_seconds = 10.0
+ sample_rate = 48000
+ noise = np.random.rand(int(num_seconds * sample_rate))
+
+ plugin = load_test_plugin(plugin_named("CHOWTapeModel"), disable_caching=True)
+ plugin.bypass = True
+ plugin.oversampling = oversampling
+
+ output = plugin.process(noise, sample_rate, buffer_size=buffer_size)
+ np.testing.assert_allclose(output, noise, atol=0.05)
diff --git a/tests/test_latency_compensation.py b/tests/test_latency_compensation.py
new file mode 100644
index 0000000..1af267a
--- /dev/null
+++ b/tests/test_latency_compensation.py
@@ -0,0 +1,31 @@
+#! /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 DelayLine
+
+
[email protected]("sample_rate", [22050, 44100, 48000])
[email protected]("buffer_size", [128, 8192, 65536])
[email protected]("latency_seconds", [0.25, 1, 2, 10])
+def test_latency_compensation(sample_rate, buffer_size, latency_seconds):
+ num_seconds = 10.0
+ noise = np.random.rand(int(num_seconds * sample_rate))
+ plugin = DelayLine(int(latency_seconds * sample_rate))
+ output = plugin.process(noise, sample_rate, buffer_size=buffer_size)
+ np.testing.assert_allclose(output, noise)