Skip to content

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

Cleanup.

Peter Sobot5f444c81da00
diff --git a/pedalboard/io/ResampledReadableAudioFile.h b/pedalboard/io/ResampledReadableAudioFile.h
index 63af50b..aece1b0 100644
--- a/pedalboard/io/ResampledReadableAudioFile.h
+++ b/pedalboard/io/ResampledReadableAudioFile.h
@@ -95,9 +95,6 @@ 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);
@@ -158,28 +155,9 @@ 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) {
@@ -224,28 +202,6 @@ 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) {
long long positionToSeekToIncludingBuffers = targetPosition;
@@ -254,72 +210,28 @@ public:
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());
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());
+ std::max(0.0, ((double)targetPositionInSourceSampleRate *
+ resampler.getTargetSampleRate()) /
+ resampler.getSourceSampleRate());
positionInTargetSampleRate =
(long long)(floatingPositionInTargetSampleRate);
- int overflowSamples = resampler.getOverflowSamples();
resampler.reset();
- 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));
+ long long inputSamplesUsed =
+ resampler.advanceResamplerState(positionInTargetSampleRate);
+ targetPositionInSourceSampleRate = inputSamplesUsed;
- 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()));
+ audioFile->seek(std::max(0LL, targetPositionInSourceSampleRate));
outputBuffer.setSize(0, 0);
@@ -327,8 +239,6 @@ public:
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.h
index 8cd24e1..2f2eb72 100644
--- a/pedalboard/io/StreamResampler.h
+++ b/pedalboard/io/StreamResampler.h
@@ -96,12 +96,6 @@ 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]);
}
@@ -186,9 +180,6 @@ 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
@@ -201,20 +192,47 @@ public:
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;
+
+ static const bool USE_CONSTANT_TIME_CALCULATION = false;
+ if (USE_CONSTANT_TIME_CALCULATION) {
+ /**
+ * NOTE(psobot): This calculation is faster than the below (as it runs in
+ * constant time) _but_ due to floating point accumulation errors, this
+ * produces slightly different output than the `while` loops below. This
+ * would mean that users who call seek() on a resampled stream would end
+ * up with a very slightly different copy of the stream. This
+ * nondeterminism is not worth the speedup.
+ *
+ * The probable way to fix this is to rewrite juce::GenericInterpolator to
+ * use two `long long` variables to track the subsample position, rather
+ * than relying on a single `double` whose precision errors can accumulate
+ * over time. That is not a refactor I want to start at 4:44pm on a
+ * Friday.
+ */
+
+ double numInputSamplesNeeded =
+ std::max(0, numOutputSamplesToProduce - 1) * resamplerRatio;
+ numInputSamplesUsed = std::ceil(numInputSamplesNeeded);
+ newSubSamplePos = numInputSamplesNeeded - numInputSamplesUsed + 1;
+
+ if (numOutputSamplesToProduce) {
+ while (newSubSamplePos >= 1.0) {
+ numInputSamplesUsed++;
+ newSubSamplePos -= 1.0;
+ }
+ newSubSamplePos += resamplerRatio;
}
+ } else {
+ while (numOutputSamplesToProduce > 0) {
+ while (newSubSamplePos >= 1.0) {
+ numInputSamplesUsed++;
+ newSubSamplePos -= 1.0;
+ }
- newSubSamplePos += resamplerRatio;
- --numOutputSamplesToProduce;
+ newSubSamplePos += resamplerRatio;
+ --numOutputSamplesToProduce;
+ }
}
float zero = 0.0;
@@ -222,16 +240,12 @@ 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(); }
+ totalSamplesOutput += numOutputSamples;
+ totalSamplesInput += numInputSamplesUsed;
- std::vector<float> getBuffer() const { return resamplers[0].getBuffer(); }
+ return numInputSamplesUsed;
+ }
void setLastChannelLayout(ChannelLayout last) { lastChannelLayout = last; }
diff --git a/pedalboard/plugin_templates/Resample.h b/pedalboard/plugin_templates/Resample.h
index 83cbbb2..20ab47a 100644
--- a/pedalboard/plugin_templates/Resample.h
+++ b/pedalboard/plugin_templates/Resample.h
@@ -144,75 +144,6 @@ 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.py
index 388f147..b806a2f 100644
--- a/tests/test_resampled_io.py
+++ b/tests/test_resampled_io.py
@@ -116,9 +116,12 @@ 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])
[email protected]("offset", [2, 10, 100])
[email protected]("chunk_size", [2, 10, 50, 100, 1_000_000])
@pytest.mark.parametrize("quality", QUALITIES)
-def test_seek_resampled(sample_rate: float, target_sample_rate: float, chunk_size: int, quality):
+def test_seek_resampled(
+ sample_rate: float, target_sample_rate: float, offset: int, chunk_size: int, quality
+):
signal = np.linspace(1, sample_rate, sample_rate).astype(np.float32)
read_buffer = BytesIO()
@@ -127,37 +130,31 @@ def test_seek_resampled(sample_rate: float, target_sample_rate: float, chunk_siz
f.write(signal)
with AudioFile(BytesIO(read_buffer.getvalue())).resampled_to(target_sample_rate, quality) as f:
- offset = chunk_size * 3
- for _ in range(offset):
- f.read(1)
- print(f"\033[91m========= reading {chunk_size} samples from {offset} =========\033[0m")
+ f.read(offset)
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)
[email protected]("sample_rate", [8000, 11025, 22050, 44100, 48000])
[email protected]("target_sample_rate", [8000, 11025, 12345.67, 22050, 44100, 48000])
[email protected]("quality", QUALITIES)
-def test_seek_resampled_is_constant_time(sample_rate: float, target_sample_rate: float, quality):
- signal = np.linspace(1, sample_rate, sample_rate).astype(np.float32)
[email protected]("sample_rate", [8000, 11025])
[email protected]("target_sample_rate", [8000, 11025, 12345.67])
+def test_seek_resampled_is_constant_time(sample_rate: float, target_sample_rate: float):
+ signal = np.random.rand(sample_rate * 60).astype(np.float32)
read_buffer = BytesIO()
read_buffer.name = "test.wav"
- with AudioFile(read_buffer, "w", sample_rate, 1, bit_depth=32) as f:
+ with AudioFile(read_buffer, "w", sample_rate, 1) as f:
f.write(signal)
- with AudioFile(BytesIO(read_buffer.getvalue())).resampled_to(target_sample_rate, quality) as f:
+ with AudioFile(BytesIO(read_buffer.getvalue())).resampled_to(target_sample_rate) as f:
timings = []
- for i in range(f.frames):
+ for i in range(0, f.frames, sample_rate):
a = time.time()
f.seek(i)
b = time.time()
timings.append(b - a)
- assert np.std(timings) < 0.1
+ assert np.std(timings) < 0.01
@pytest.mark.parametrize("sample_rate", [8000, 11025, 22050, 44100, 48000])