Skip to content

Commit

Permalink
Avoid a time stretch in Rubberband. (#342)
Browse files Browse the repository at this point in the history
  • Loading branch information
psobot authored Jun 18, 2024
1 parent 67511bf commit e165114
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
17 changes: 13 additions & 4 deletions pedalboard/TimeStretch.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ using namespace RubberBand;
namespace Pedalboard {

static const int MAX_SEMITONES_TO_PITCH_SHIFT = 72;
static const size_t STUDY_BLOCK_SAMPLE_SIZE = 2048;

/*
* A wrapper around Rubber Band that allows calling it independently of a plugin
Expand Down Expand Up @@ -105,8 +106,18 @@ timeStretch(const juce::AudioBuffer<float> input, double sampleRate,
rubberBandStretcher.setMaxProcessSize(input.getNumSamples());
rubberBandStretcher.setExpectedInputDuration(input.getNumSamples());

rubberBandStretcher.study(input.getArrayOfReadPointers(),
input.getNumSamples(), true);
const float **inputChannelPointers =
(const float **)alloca(sizeof(float *) * input.getNumChannels());

for (size_t i = 0; i < input.getNumSamples(); i += STUDY_BLOCK_SAMPLE_SIZE) {
size_t numSamples =
std::min(input.getNumSamples() - i, (size_t)STUDY_BLOCK_SAMPLE_SIZE);
for (int c = 0; c < input.getNumChannels(); c++) {
inputChannelPointers[c] = input.getReadPointer(c, i);
}
bool isLast = i + numSamples >= input.getNumSamples();
rubberBandStretcher.study(inputChannelPointers, numSamples, isLast);
}

size_t expectedNumberOfOutputSamples =
(((double)input.getNumSamples()) / stretchFactor);
Expand All @@ -120,8 +131,6 @@ timeStretch(const juce::AudioBuffer<float> input, double sampleRate,
/* avoidReallocating */ true);

size_t blockSize = rubberBandStretcher.getProcessSizeLimit();
const float **inputChannelPointers =
(const float **)alloca(sizeof(float *) * input.getNumChannels());
float **outputChannelPointers =
(float **)alloca(sizeof(float *) * output.getNumChannels());

Expand Down
10 changes: 9 additions & 1 deletion tests/test_time_stretch.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
# limitations under the License.


import pytest
import numpy as np
import pytest

from pedalboard import time_stretch


Expand Down Expand Up @@ -104,3 +105,10 @@ def test_time_stretch_long_passthrough(
high_quality=high_quality,
)
np.testing.assert_allclose(output[0], sine_wave, atol=0.25)


def test_time_stretch_does_not_segfault():
# https://github.com/spotify/pedalboard/issues/340
sr = 44100
x = np.random.default_rng().uniform(size=sr * 10).astype(np.float32)
time_stretch(x, sr, high_quality=False, use_time_domain_smoothing=True)

0 comments on commit e165114

Please sign in to comment.