Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions src/audio/effects/pitch_shifter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ static constexpr int P_MIX = 2;
// Grain window size in seconds (~23 ms at 48kHz = 1024 samples)
static constexpr float GRAIN_WINDOW_SEC = 0.023f;

static float wrap_phase(float phase, int buf_size) {
phase = std::fmod(phase, static_cast<float>(buf_size));
if (phase < 0.0f) phase += static_cast<float>(buf_size);
return phase;
}

PitchShifter::PitchShifter() {
params_ = {
{"Shift", 0.0f, -12.0f, 12.0f, 0.0f, "st",
Expand All @@ -35,9 +41,7 @@ void PitchShifter::set_sample_rate(int sample_rate) {
}

float PitchShifter::read_linear(float phase) const {
// Wrap phase into [0, buf_size_)
phase = std::fmod(phase, static_cast<float>(buf_size_));
if (phase < 0.0f) phase += buf_size_;
phase = wrap_phase(phase, buf_size_);

int pos0 = static_cast<int>(phase);
int pos1 = (pos0 + 1) % buf_size_;
Expand Down Expand Up @@ -77,11 +81,9 @@ void PitchShifter::process(float* buffer, int num_samples) {
read_phase_a_ += drift;
read_phase_b_ += drift;

// Wrap phases into [0, buf_size_)
while (read_phase_a_ < 0.0f) read_phase_a_ += buf_size_;
while (read_phase_a_ >= buf_size_) read_phase_a_ -= buf_size_;
while (read_phase_b_ < 0.0f) read_phase_b_ += buf_size_;
while (read_phase_b_ >= buf_size_) read_phase_b_ -= buf_size_;
// Wrap phases into [0, buf_size_) in constant time.
read_phase_a_ = wrap_phase(read_phase_a_, buf_size_);
read_phase_b_ = wrap_phase(read_phase_b_, buf_size_);

// Compute absolute read positions in the buffer
float pos_a = static_cast<float>(write_pos_) - read_phase_a_;
Expand Down
17 changes: 17 additions & 0 deletions tests/test_effects.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1365,6 +1365,23 @@ TEST(pitch_shifter_with_mix_and_shift_differs_from_dry) {
ASSERT_GT(mag_shifted, mag_440 * 0.5f);
}

TEST(pitch_shifter_extreme_shift_wraps_phase_without_instability) {
PitchShifter ps;
ps.set_sample_rate(48000);
ps.params()[0].value = 120.0f;
ps.params()[1].value = 500.0f;
ps.params()[2].value = 1.0f;
ps.reset();

std::vector<float> buf(4096);
fill_sine(buf.data(), static_cast<int>(buf.size()), 440.0f, 48000);

ps.process(buf.data(), static_cast<int>(buf.size()));

ASSERT_TRUE(buffer_is_finite(buf.data(), static_cast<int>(buf.size())));
ASSERT_GT(rms(buf.data(), static_cast<int>(buf.size())), 0.001f);
}

// ============================================================
// MultiBandCompressor tests
// ============================================================
Expand Down
Loading