π π A Python library for audio.
C audioaudio-processingaudio-productionaudio-researchaudio-unitaugmentationjucemachine-learningpybind11pythonvst3vst3-host
temp
Peter Sobot4249e64fd629
diff --git a/pedalboard/io/ResampledReadableAudioFile.h b/pedalboard/io/ResampledReadableAudioFile.hindex 54f2687..cebf306 100644--- a/pedalboard/io/ResampledReadableAudioFile.h+++ b/pedalboard/io/ResampledReadableAudioFile.h@@ -34,6 +34,22 @@ namespace py = pybind11;namespace Pedalboard {+static inline int inputBufferSizeFor(ResamplingQuality quality) {+ switch (quality) {+ case ResamplingQuality::ZeroOrderHold:+ return 1;+ case ResamplingQuality::Linear:+ return 2;+ case ResamplingQuality::CatmullRom:+ return 4;+ case ResamplingQuality::Lagrange:+ return 5;+ case ResamplingQuality::WindowedSinc:+ return 200;+ }+ return 0;+}+class ResampledReadableAudioFile: public AudioFile,public std::enable_shared_from_this<ResampledReadableAudioFile> {@@ -79,6 +95,9 @@ public:const juce::ScopedLock scopedLock(objectLock);+ printf("rraf->read(%d samples at %fHz) from position %d\n", numSamples,+ getSampleRate(), tell());+long long samplesInResampledBuffer = 0;juce::AudioBuffer<float> resampledBuffer(audioFile->getNumChannels(),numSamples);@@ -139,9 +158,28 @@ public:}// TODO: Provide an alternative interface to write to the output buffer+ printResamplerState();+ printf("\033[92mPassing input to resampler: [");+ for (int i = 0; i < resamplerInput->getNumSamples(); i++) {+ printf("%2.2f", *(resamplerInput->getReadPointer(0, i)));+ if (i < resamplerInput->getNumSamples() - 1) {+ printf(", ");+ }+ }+ printf("]\033[0m\n");juce::AudioBuffer<float> newResampledSamples =resampler.process(resamplerInput);+ printf("Got output from resampler: [");+ for (int i = 0; i < newResampledSamples.getNumSamples(); i++) {+ printf("%2.2f", *(newResampledSamples.getReadPointer(0, i)));+ if (i < newResampledSamples.getNumSamples() - 1) {+ printf(", ");+ }+ }+ printf("]\n");+ printResamplerState();+int offsetInNewResampledSamples = 0;if (newResampledSamples.getNumSamples() >numSamples - samplesInResampledBuffer) {@@ -186,18 +224,114 @@ public:ChannelLayout::NotInterleaved, 0);}+ void printResamplerState() {+ printf("Resampler state: \033[93m[subsample_pos=%9.9f, index=%d, "+ "nextInputSamples=[",+ resampler.getSubSamplePosition(), resampler.getIndexInBuffer());+ std::vector<float> overflowSamples = resampler.getOverflowSampleBuffer();+ for (int i = 0; i < overflowSamples.size(); i++) {+ printf("%2.2f", overflowSamples[i]);+ if (i < overflowSamples.size() - 1) {+ printf(", ");+ }+ }+ printf("], inputBuffer=[");+ std::vector<float> resamplerBuffer = resampler.getBuffer();+ for (int i = 0; i < resamplerBuffer.size(); i++) {+ printf("%2.2f", resamplerBuffer[i]);+ if (i < resamplerBuffer.size() - 1) {+ printf(", ");+ }+ }+ printf("]]\033[0m\n");+ }+void seek(long long targetPosition) {- // TODO: This could be done much more efficiently by- // only seeking as far back as we need to to prime the resampler.- // That logic is _very_ tricky to write correctly, though.- audioFile->seek(0);+ long long positionToSeekToIncludingBuffers = targetPosition;++ long long targetPositionInSourceSampleRate =+ std::max(0LL, (long long)(((double)positionToSeekToIncludingBuffers *+ resampler.getSourceSampleRate()) /+ resampler.getTargetSampleRate()));++ // TODO: Rounding is off somewhere here. Resampler's subsample+ // position is+ // set properly, but it's receiving the wrong stream and is+ // off by 1 or 2 (lastInputSamples is 15 after the seek,+ // instead of 13 when read pre-ssek)+ printf("Seeking to position %d in target sample rate, which "+ "is %d in source\n",+ targetPosition, targetPositionInSourceSampleRate);++ // targetPositionInSourceSampleRate -=+ // inputBufferSizeFor(resampler.getQuality());+ // printf("Moving seek position back by %d samples to account "+ // "for input buffer, now %d\n",+ // inputBufferSizeFor(resampler.getQuality()),+ // targetPositionInSourceSampleRate);++ long long maximumOverflow =+ (long long)std::ceil(resampler.getSourceSampleRate() /+ resampler.getTargetSampleRate()) *+ 2;+ targetPositionInSourceSampleRate -= std::max(0LL, maximumOverflow);+ printf("Moving seek position back by %d samples to account "+ "for maximum overflow, now %d\n",+ maximumOverflow, targetPositionInSourceSampleRate);++ double floatingPositionInTargetSampleRate =+ std::max(0.0, ((double)targetPositionInSourceSampleRate /+ resampler.getSourceSampleRate()) *+ resampler.getTargetSampleRate());++ positionInTargetSampleRate =+ (long long)(floatingPositionInTargetSampleRate);++ int overflowSamples = resampler.getOverflowSamples();resampler.reset();- positionInTargetSampleRate = 0;+ printf("Resampler being reset; had %d overflow samples, now %d.\n",+ overflowSamples, resampler.getOverflowSamples());++ printResamplerState();++ if (floatingPositionInTargetSampleRate != positionInTargetSampleRate) {+ printf("Advancing resampler state by %d output samples\n",+ positionInTargetSampleRate);+ long long inputSamplesUsed =+ resampler.advanceResamplerState(positionInTargetSampleRate);+ long long sampleDeficit =+ targetPositionInSourceSampleRate - inputSamplesUsed;+ printf("Advancing resampler state by %d output samples used up %d input "+ "samples, leaving %d that should be buffered\n",+ positionInTargetSampleRate, inputSamplesUsed, sampleDeficit);+ printResamplerState();++ if (sampleDeficit > 0) {+ targetPositionInSourceSampleRate -= sampleDeficit;+ printf("Moving seek position back by %d samples to account "+ "for subsample precision, now %d\n",+ sampleDeficit, targetPositionInSourceSampleRate);+ }+ }++ printf("\033[92maudioFile->seek(%d)\033[0m\n",+ std::max(0LL, targetPositionInSourceSampleRate));+ audioFile->seek(std::max(0LL, targetPositionInSourceSampleRate));++ printf("Set current position in target sample rate to %d, accounting for "+ "%f latency and %d input samples\n",+ positionInTargetSampleRate, resampler.getOutputLatency(),+ inputBufferSizeFor(resampler.getQuality()));+outputBuffer.setSize(0, 0);- const long long chunkSize = 1024 * 1024;- for (long long i = 0; i < targetPosition; i += chunkSize) {- this->read(std::min(chunkSize, targetPosition - i));+ const long long chunkSize = 1;+ for (long long i = positionInTargetSampleRate; i < targetPosition;+ i += chunkSize) {+ long long numSamples = std::min(chunkSize, targetPosition - i);+ printf("Reading %d samples from position %d in target sample rate.\n",+ numSamples, this->tell());+ this->read(numSamples);}}diff --git a/pedalboard/io/StreamResampler.h b/pedalboard/io/StreamResampler.hindex 05f2ebc..8cd24e1 100644--- a/pedalboard/io/StreamResampler.h+++ b/pedalboard/io/StreamResampler.h@@ -96,6 +96,12 @@ public:}if (!isFlushing) {+ if (inputSamplesConsumed < input.getNumSamples()) {+ printf("[StreamResampler] only consumed %d of %d provided samples, "+ "saving the rest for next time\n",+ inputSamplesConsumed, input.getNumSamples(),+ input.getNumSamples() - inputSamplesConsumed);+ }for (int i = inputSamplesConsumed; i < input.getNumSamples(); i++) {overflowSamples[c].push_back(input.getReadPointer(c)[i]);}@@ -180,6 +186,9 @@ public:// TODO: Rename me!int getOverflowSamples() const { return overflowSamples[0].size(); }+ std::vector<SampleType> getOverflowSampleBuffer() const {+ return overflowSamples[0];+ }/*** Advance the internal state of this resampler, as if the given@@ -188,14 +197,19 @@ public:* Note that this method will only affect the sub-sample position stored by* the resampler, but will not clear all of the samples buffered internally.*/- void advanceResamplerState(int numOutputSamples) {+ long long advanceResamplerState(int numOutputSamples) {double newSubSamplePos = 1.0;int numOutputSamplesToProduce = numOutputSamples;+ totalSamplesOutput += numOutputSamples;+ totalSamplesInput += numOutputSamples * resamplerRatio;+// TODO: Find a closed-form expression that produces the same result as// this to make this O(1) instead of O(n)!+ long long numInputSamplesUsed = 0;while (numOutputSamplesToProduce > 0) {while (newSubSamplePos >= 1.0) {+ numInputSamplesUsed++;newSubSamplePos -= 1.0;}@@ -208,8 +222,17 @@ public:// This effectively sets the new subsample position:resampler.process(newSubSamplePos, &zero, &zero, 1);}+ return numInputSamplesUsed;}+ double getSubSamplePosition() const {+ return resamplers[0].getSubSamplePosition();+ }++ long getIndexInBuffer() const { return resamplers[0].getIndexInBuffer(); }++ std::vector<float> getBuffer() const { return resamplers[0].getBuffer(); }+void setLastChannelLayout(ChannelLayout last) { lastChannelLayout = last; }std::optional<ChannelLayout> getLastChannelLayout() const {diff --git a/pedalboard/plugin_templates/Resample.h b/pedalboard/plugin_templates/Resample.hindex 20ab47a..83cbbb2 100644--- a/pedalboard/plugin_templates/Resample.h+++ b/pedalboard/plugin_templates/Resample.h@@ -144,6 +144,75 @@ public:}}+ double getSubSamplePosition() const {+ // Unfortunately, std::visit cannot be used here due to macOS version+ // issues: https://stackoverflow.com/q/52310835/679081+ if (auto *i =+ std::get_if<juce::Interpolators::ZeroOrderHold>(&interpolator)) {+ return i->getSubSamplePosition();+ } else if (auto *i =+ std::get_if<juce::Interpolators::Linear>(&interpolator)) {+ return i->getSubSamplePosition();+ } else if (auto *i = std::get_if<juce::Interpolators::CatmullRom>(+ &interpolator)) {+ return i->getSubSamplePosition();+ } else if (auto *i =+ std::get_if<juce::Interpolators::Lagrange>(&interpolator)) {+ return i->getSubSamplePosition();+ } else if (auto *i = std::get_if<juce::Interpolators::WindowedSinc>(+ &interpolator)) {+ return i->getSubSamplePosition();+ } else {+ throw std::runtime_error("Unknown resampler quality!");+ }+ }++ long getIndexInBuffer() const {+ // Unfortunately, std::visit cannot be used here due to macOS version+ // issues: https://stackoverflow.com/q/52310835/679081+ if (auto *i =+ std::get_if<juce::Interpolators::ZeroOrderHold>(&interpolator)) {+ return i->getIndexInBuffer();+ } else if (auto *i =+ std::get_if<juce::Interpolators::Linear>(&interpolator)) {+ return i->getIndexInBuffer();+ } else if (auto *i = std::get_if<juce::Interpolators::CatmullRom>(+ &interpolator)) {+ return i->getIndexInBuffer();+ } else if (auto *i =+ std::get_if<juce::Interpolators::Lagrange>(&interpolator)) {+ return i->getIndexInBuffer();+ } else if (auto *i = std::get_if<juce::Interpolators::WindowedSinc>(+ &interpolator)) {+ return i->getIndexInBuffer();+ } else {+ throw std::runtime_error("Unknown resampler quality!");+ }+ }++ std::vector<float> getBuffer() const {+ // Unfortunately, std::visit cannot be used here due to macOS version+ // issues: https://stackoverflow.com/q/52310835/679081+ if (auto *i =+ std::get_if<juce::Interpolators::ZeroOrderHold>(&interpolator)) {+ return i->getBuffer();+ } else if (auto *i =+ std::get_if<juce::Interpolators::Linear>(&interpolator)) {+ return i->getBuffer();+ } else if (auto *i = std::get_if<juce::Interpolators::CatmullRom>(+ &interpolator)) {+ return i->getBuffer();+ } else if (auto *i =+ std::get_if<juce::Interpolators::Lagrange>(&interpolator)) {+ return i->getBuffer();+ } else if (auto *i = std::get_if<juce::Interpolators::WindowedSinc>(+ &interpolator)) {+ return i->getBuffer();+ } else {+ throw std::runtime_error("Unknown resampler quality!");+ }+ }+private:std::variant<juce::Interpolators::ZeroOrderHold, juce::Interpolators::Linear,juce::Interpolators::CatmullRom, juce::Interpolators::Lagrange,diff --git a/tests/test_resampled_io.py b/tests/test_resampled_io.pyindex 6e905a2..de3de61 100644--- a/tests/test_resampled_io.py+++ b/tests/test_resampled_io.py@@ -115,8 +115,9 @@ def test_tell_resampled(sample_rate: float, target_sample_rate: float, chunk_siz@pytest.mark.parametrize("sample_rate", [8000, 11025, 22050, 44100, 48000])@pytest.mark.parametrize("target_sample_rate", [8000, 11025, 12345.67, 22050, 44100, 48000])[email protected]("chunk_size", [2, 10, 100])@pytest.mark.parametrize("quality", QUALITIES)-def test_seek_resampled(sample_rate: float, target_sample_rate: float, quality):+def test_seek_resampled(sample_rate: float, target_sample_rate: float, chunk_size: int, quality):signal = np.linspace(1, sample_rate, sample_rate).astype(np.float32)read_buffer = BytesIO()@@ -125,10 +126,15 @@ def test_seek_resampled(sample_rate: float, target_sample_rate: float, quality):f.write(signal)with AudioFile(BytesIO(read_buffer.getvalue())).resampled_to(target_sample_rate, quality) as f:- f.read(10)- expected = f.read(10)- f.seek(10)- actual = f.read(10)+ offset = chunk_size * 3+ for _ in range(offset):+ f.read(1)+ print(f"\033[91m========= reading {chunk_size} samples from {offset} =========\033[0m")+ expected = f.read(chunk_size)+ print(f"\033[91m========= seeking back to {offset} =========\033[0m")+ f.seek(offset)+ print(f"\033[91m========= reading {chunk_size} samples from {offset} =========\033[0m")+ actual = f.read(chunk_size)np.testing.assert_allclose(expected, actual)