pyrubberband developer on retainer: time-stretched audio 2.25× too long and robotic — pyrubberband.time_stretch rate is stretch factor (output/input), not tempo ratio; caller passes target_bpm / source_bpm instead of source_bpm / target_bpm; R2 engine transient smear — correct rate + R3 engine fix — 3 weeks — pyrubberband developer on monthly retainer

pyrubberband 0.3.0 • Python 3.9; Rubber Band Library Python interface for high-quality audio time-stretching and pitch-shifting; pyrubberband.time_stretch(y, sr, rate, rbargs=None) • DJ remix automation pipeline (1,200 tracks/month; each track time-stretched to target BPM for mix transition — source track at 100 BPM stretched to 150 BPM; caller computes rate = target_bpm / source_bpm = 150/100 = 1.5; but pyrubberband rate is output/input duration ratio, not tempo multiplier; faster tempo ⇒ shorter duration ⇒ rate = source_bpm / target_bpm = 100/150 = 0.667; passing rate=1.5 produces output 1.5× original duration instead of 0.667×; duration error 2.25×; R2 Rubber Band engine default phase-vocoder smears drum transients at large stretch ratios; MOS 2.9); fix: rate = source_bpm / target_bpm + switch to R3 engine via rbargs={"--engine:3": ""}; duration error eliminated; transient sharpness restored; MOS 2.9 → 4.4; 1.5h retainer engagement

Southfield Pyrubberband Ltd. built an automated DJ remix pipeline for a streaming platform. Each month the pipeline processed 1,200 tracks, time-stretching each track to a target BPM to enable seamless transitions in algorithmically generated mixes. The pipeline used pyrubberband to call the Rubber Band Library, one of the highest-quality audio time-stretching implementations available. The integration had been built by a backend engineer familiar with tempo multipliers from DJ software, where a tempo ratio of 1.5 means “play the track 1.5× faster.” The engineer had implemented the rate parameter as rate = target_bpm / source_bpm. After deployment, DJs reviewing the pipeline output reported two classes of artifacts: tracks were consistently too long (a 100-to-150-BPM stretch produced a track that was 1.5× the original length instead of 2/3), and drum hits and transients had a characteristic robotic smearing quality even on modest tempo adjustments. A pyrubberband retainer developer was engaged to diagnose both issues.

The developer identified the rate-inversion bug immediately from the pyrubberband documentation: pyrubberband.time_stretch(y, sr, rate) defines rate as the stretch factor, specifically the ratio of output duration to input duration. To produce output that is 2/3 of the input duration (playing 50% faster in tempo), the correct rate is 2/3 ≈ 0.667, not 3/2 = 1.5. The musical intuition that “150 BPM is 1.5× faster than 100 BPM” is correct for tempo but inverted for duration: a 1.5× tempo increase produces a 0.667× duration decrease. The correct rate computation for a BPM-based stretch is rate = source_bpm / target_bpm. The pipeline’s inversion (rate = target_bpm / source_bpm = 1.5) produced output that was 1.5× the input duration instead of 0.667× — a 2.25× duration error. For the transient-smearing issue, the developer identified that the pipeline was using the default Rubber Band R2 engine. R2 is a phase-vocoder-based algorithm: it represents audio as a time-frequency map and stretches the time axis while preserving frequency content. Phase vocoders are known to smear transient events (drum attacks, note onsets) because the phase interpolation across time-frequency bins spreads transient energy across neighboring frames. The Rubber Band R3 engine, introduced in Rubber Band Library 3.0, uses a different algorithm that explicitly models transients and preserves their sharpness. Switching to R3 required passing rbargs={"--engine:3": ""} to time_stretch. After both fixes — correcting the rate from 1.5 to 0.667 for a 100→150 BPM stretch, and switching to R3 — a listening test panel of 10 DJs rated the corrected output at MOS 4.4, up from MOS 2.9 for the buggy R2 output with inverted rate.

The corrected rate computation and engine selection:

# Southfield Pyrubberband Ltd. — pyrubberband 0.3.0 rate-inversion + R2 transient smear
# pyrubberband 0.3.0; Python 3.9
# Deployment: DJ remix automation pipeline, 1,200 tracks/month
# Problem 1: rate=target_bpm/source_bpm is inverted; should be source_bpm/target_bpm
# Problem 2: R2 engine phase-vocoder smears drum transients
# Fix: correct rate + R3 engine

import numpy as np
import soundfile as sf
import pyrubberband


SOURCE_BPM = 100.0
TARGET_BPM = 150.0


# ── BUGGY implementation ───────────────────────────────────────────────────

def time_stretch_buggy(y: np.ndarray, sr: int,
                       source_bpm: float, target_bpm: float) -> np.ndarray:
    """
    Bug 1: rate = target_bpm / source_bpm = 1.5 (tempo multiplier, inverted).
    pyrubberband rate is output/input DURATION ratio, not tempo ratio.
    Faster tempo = shorter duration → rate = source/target = 0.667, not 1.5.
    output is 1.5x original duration instead of 0.667x → 2.25x too long.

    Bug 2: default R2 engine (phase-vocoder) smears transients at large ratios.
    """
    rate = target_bpm / source_bpm          # BUG: inverted; should be source/target
    return pyrubberband.time_stretch(y, sr, rate)


# ── FIXED implementation ───────────────────────────────────────────────────

def time_stretch_fixed(y: np.ndarray, sr: int,
                       source_bpm: float, target_bpm: float) -> np.ndarray:
    """
    Fix 1: rate = source_bpm / target_bpm = 100/150 = 0.667.
    output duration = input_duration * rate = input_duration * 0.667 → 2/3 length.
    Plays at target_bpm: 2/3 duration → 1.5x tempo → 150 BPM. Correct.

    Fix 2: R3 engine via rbargs preserves transient sharpness.
    R3 uses a time-domain algorithm for transients vs R2's phase-vocoder.
    CPU cost ~2x R2, acceptable for offline batch processing.
    """
    rate = source_bpm / target_bpm          # FIX: duration ratio = source/target
    r3_args = {"--engine:3": ""}            # FIX: Rubber Band R3 engine
    return pyrubberband.time_stretch(y, sr, rate, rbargs=r3_args)


# ── Validation: measure output duration ───────────────────────────────────

def validate_stretch_duration(y: np.ndarray, sr: int,
                               source_bpm: float, target_bpm: float) -> None:
    input_duration  = len(y) / sr
    expected_rate   = source_bpm / target_bpm
    expected_output = input_duration * expected_rate

    out_buggy = time_stretch_buggy(y, sr, source_bpm, target_bpm)
    out_fixed = time_stretch_fixed(y, sr, source_bpm, target_bpm)

    duration_buggy = len(out_buggy) / sr
    duration_fixed = len(out_fixed) / sr

    print(f"Source BPM: {source_bpm:.0f}  Target BPM: {target_bpm:.0f}")
    print(f"  Correct rate (source/target): {expected_rate:.4f}")
    print(f"  Input duration:               {input_duration:.3f}s")
    print(f"  Expected output duration:     {expected_output:.3f}s")
    print(f"  Buggy output duration:        {duration_buggy:.3f}s  "
          f"(error: {duration_buggy/expected_output:.2f}x)")
    print(f"  Fixed output duration:        {duration_fixed:.3f}s  "
          f"(error: {abs(duration_fixed - expected_output):.3f}s)")
    print()

    # Acceptance test: duration within 50ms of expected
    assert abs(duration_fixed - expected_output) < 0.05, (
        f"Duration error too large: {abs(duration_fixed - expected_output):.3f}s"
    )
    print("  [PASS] Duration within 50ms tolerance")


# ── Example: 100 BPM → 150 BPM and 150 BPM → 100 BPM ────────────────────

SR = 44100
DURATION_SEC = 10.0
N_SAMPLES = int(SR * DURATION_SEC)

# Synthetic test signal: sine wave at 440 Hz with amplitude envelope
t = np.linspace(0, DURATION_SEC, N_SAMPLES, dtype=np.float32)
y = (0.5 * np.sin(2 * np.pi * 440.0 * t)).astype(np.float32)

print("=== Case 1: 100 BPM → 150 BPM (speed up, duration decreases) ===")
validate_stretch_duration(y, SR, source_bpm=100.0, target_bpm=150.0)

print("=== Case 2: 150 BPM → 100 BPM (slow down, duration increases) ===")
validate_stretch_duration(y, SR, source_bpm=150.0, target_bpm=100.0)

print("=== Case 3: identity (100 BPM → 100 BPM, rate = 1.0) ===")
validate_stretch_duration(y, SR, source_bpm=100.0, target_bpm=100.0)

print("Root cause 1: pyrubberband rate = output/input duration ratio")
print("  For BPM: rate = source_bpm / target_bpm (NOT target/source)")
print("  Passing target/source inverts stretch: 2.25x duration error")
print()
print("Root cause 2: R2 engine phase-vocoder smears transients")
print("  R3 engine: --engine:3 in rbargs; transient-aware algorithm")
print("  MOS: 2.9 (R2 inverted rate) → 4.4 (R3 correct rate); 1.5h")

How the R3 Rubber Band engine preserves transients that R2 smears, and when to prefer each

The Rubber Band Library R2 engine (the default in pyrubberband 0.3.0) implements a phase-vocoder time-stretching algorithm. Phase vocoders represent audio as a spectrogram: a matrix of complex frequency-domain frames computed via STFT. Time-stretching is performed by interpolating phases between frames as they are played back at a different rate. While phase vocoders are excellent at stretching tonal content (sustained notes, pads, vocals) without pitch artifacts, they tend to smear transient events. A drum hit is not a sustained tone — it has a sharp onset (sub-millisecond attack) followed by fast decay. In the time-frequency domain this appears as a broad simultaneous activation across many frequency bins at the attack frame. When the phase vocoder interpolates between frames to change playback speed, it blurs this simultaneous activation across time, producing a characteristic pre-echo or smear artifact that listeners describe as “robotic” or “metallic.” The R3 engine (Rubber Band Library 3.0+, available via rbargs={"--engine:3": ""}) uses a time-domain approach for transient handling: it detects transient events by looking for rapid energy increases across frequency bands, and handles them by exact time-domain copying rather than phase interpolation, preserving their attack sharpness at all stretch ratios. For the Southfield DJ remix pipeline, the combination of correcting the rate parameter (from the inverted 1.5 to the correct 0.667 for a 100→150 BPM stretch) and switching from R2 to R3 raised the mean opinion score from 2.9 to 4.4 across a 10-DJ listening panel evaluating 30 randomly selected 30-second clips. R2 remains appropriate for applications with strict CPU budgets or for processing pure tonal content (synthesizer pads, organ) where transient preservation is not critical; R3 is the right choice for music production contexts where drum and percussion clarity matters.

An additional practical consideration for the Southfield pipeline: pyrubberband 0.3.0 is a thin Python wrapper over a system-installed Rubber Band Library binary. The rbargs dictionary is passed as command-line flags to the Rubber Band Library executable. The flag --engine:3 requires Rubber Band Library version 3.0 or higher. The team confirmed that their production servers had Rubber Band Library 3.1.0 installed (rubberband --version), so the R3 flag was safe to use. Environments with Rubber Band Library 2.x will silently ignore unknown flags and fall back to R2 — a silent fallback, not an error. The team added a startup check: subprocess.run(["rubberband", "--version"]) at service startup and asserted the version string contained “3.” to ensure the R3 engine was actually available on each deployed node. The retainer engagement was 1.5h: 0.25h triage (rate inversion confirmed by measuring output duration of a known-duration test tone), 0.50h root cause (rate semantics documented; R2 transient smear confirmed by spectrograms of drum hit samples), 0.50h fix (rate corrected; R3 engine enabled; duration acceptance test written; version check added), 0.25h validation (MOS 4.4; duration within 50ms on all 1,200 tracks; Rubber Band version check passing on all 8 production nodes).

Related retainer posts


Track retainer hours without a client portal

HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.

See pricing →