# PitchShift A/B experiment — current pool model vs SC 4-head SOLA Status: **resolved**. After A/B listening, the SC-faithful 4-head SOLA variant was adopted as the primary granular pitch shifter and renamed to `PitchShift.Audio`. The former dynamic grain-pool `PitchShift.Audio` was preserved (its tunable `overlap` and selectable grain-read `interpolation` remain valuable) and renamed to `TuneablePitchShift.Audio`. Tests, demos, benchmark, and `PitchShifting.md` were updated end-to-end as part of the rename. The rest of this document is kept as the historical experiment plan. ## Background `Sources/Lyrebird/Generators/Granular/PitchShift.swift` currently uses a dynamic grain pool: triggers fire every `windowSamples / overlap` ticks and allocate a free `GrainState` slot. Default `overlap = 8`, pool size = 64. The SuperCollider `PitchShift` UGen (`server/plugins/DelayUGens.cpp:4581–5044`) uses a **fixed 4-read-head SOLA** model: - Single power-of-two circular delay buffer, write head with `& mask` wrap. - Always exactly four read heads. Each head re-triggered every `framesize / 4` samples (cyclic stage 0→3). - Window envelope is an inline accumulator: each head carries `ramp` and `ramp_slope` floats; slope flips sign at quarter-window boundaries. Heads 1/3 form one inverted-slope pair, 2/4 another → 4-way constant-power cross-fade. - `samp_slope = 1 - pchratio`; read at `iwrphase - dsamp`. `startpos` is set so the head trails the writer for any clamped pitchRatio. - Output normalized by `value *= 0.5` to compensate triangle OLA gain of 2.0. After the recent fixes ([PitchShift.swift:140](Sources/Lyrebird/Generators/Granular/PitchShift.swift) lookback formula + inline triangle envelope) the Lyrebird implementation is correct at all clamped pitchRatios but still spends per-grain bookkeeping time the SC version doesn't. ## Goal Determine whether replacing the current pool model with the SC 4-head SOLA model is worth the migration cost. Decision based on three axes: 1. **Sound quality** — listening tests at typical and extreme settings. 2. **CPU cost** — measured at `overlap = 4` (matched comparison) and at `overlap = 8` (Lyrebird's default). 3. **API surface** — what features (overlap parameter, pitchDispersion, timeDispersion) survive in the 4-head model and which do not. ## Approach ### Side-by-side implementation Add a second class `PitchShift.Audio4` (working name) implementing the SC 4-head SOLA model alongside the existing `PitchShift.Audio`. Both live in `Sources/Lyrebird/Generators/Granular/PitchShift.swift` (or a new `PitchShift4Head.swift`) and share `_Base`-like configuration where useful. The 4-head class: - Drops the `overlap` parameter (fixed at 4 by construction). - Drops the dynamic `_grains: [GrainState]` pool and `lyrebirdGrainPoolSize` dependency. - Stores per-head fields directly on the class: ```swift var dsamp1, dsamp2, dsamp3, dsamp4: Double var dsampSlope1, dsampSlope2, dsampSlope3, dsampSlope4: Double var ramp1, ramp2, ramp3, ramp4: Double var rampSlope1, rampSlope2, rampSlope3, rampSlope4: Double var stage: Int = 3 var counter: Int let slope: Double // 2 / framesize let framesize: Int ``` - Uses a power-of-two capture buffer (round `captureSize` up at init) and a precomputed `_captureMask = captureSize - 1` for `& mask` wrap. - Normalizes output by `* 0.5` to match SC's triangle OLA gain compensation. - Keeps `pitchDispersion`: applied at each stage trigger, identical to SC. - Keeps `timeDispersion`: applied to `startpos` via `+= timedisp * frand()`, identical to SC. ### Surface decision Two viable shapes: **Option 1 — separate type** - `PitchShift.Audio` keeps current grain-pool model, retains `overlap`. - `PitchShift.Audio4` exposes the 4-head model, no `overlap` parameter. - User picks. Both ship. **Option 2 — switchable mode** - `PitchShift.Audio` gains a `mode: PitchShiftMode` enum: `.pool` (current), `.fourHead` (SC). Init dispatches to one or the other internally. - Smaller API footprint; one type covers both. Recommend **Option 1** for the experiment (cleanest diff, easiest to delete the loser). Decision on long-term shape comes after measurement. ### Benchmark harness Add a benchmark in `Sources/LyrebirdBenchmark/`: - Single-instance stress: 1 PitchShift driven by a sine, 60 s render at 48 kHz, blockSize 256. Measure wall-clock and per-block min/max/avg. - Polyphonic stress: 32 instances in parallel groups, same render. - Run for: pool model `overlap=4`, pool model `overlap=8`, 4-head model. - Use Instruments (Time Profiler) for hot-path attribution if anything looks off. ### A/B listening test Render six audio files via NRT (`docs/tooling/nrt-guide.md`) using a fixed input (sine sweep + percussive sample + sustained voice): | File | Model | pitchRatio | windowSize | overlap | Notes | |------|-------|------------|------------|---------|-------| | 1 | pool | 1.5 | 0.05 | 4 | matched comparison | | 2 | 4-head | 1.5 | 0.05 | — | matched comparison | | 3 | pool | 0.5 | 0.05 | 4 | octave down | | 4 | 4-head | 0.5 | 0.05 | — | octave down | | 5 | pool | 4.0 | 0.05 | 4 | extreme up — was the buggy region | | 6 | 4-head | 4.0 | 0.05 | — | extreme up | Save to a stable directory. Subjective listening + spectrogram inspection (LyrebirdSpectrumView NRT capture, or external tool) for transient artifacts, spectral leakage, periodic flutter. ### Test parity Mirror the existing `PitchShiftTests` suite for `PitchShift.Audio4`: - silence in → silence out - pitchRatio clamp behavior - deterministic output with fixed seed - mul/add scaling - high-pitchRatio read-head safety regression Plus 4-head-specific: - output gain compensation (`* 0.5`) verified against constant input - `overlap` parameter not present (compile-time check or doc note) ## Decision criteria After benchmarks + listening tests, switch architectures if **all three** hold: 1. 4-head CPU cost ≤ pool model at matched `overlap=4` (expected — fewer indirections, fewer field loads, no slot scan). 2. 4-head sound quality is subjectively equal or better at the three pitchRatio test points. 3. Loss of `overlap` parameter is acceptable. (The current docs already note `overlap > 16` is a CPU-vs-quality knob with diminishing returns, so a fixed 4 may be fine for most users.) If any fail, keep both via Option 1 indefinitely or scrap the 4-head class. ## Files involved | File | Role | |---|---| | `Sources/Lyrebird/Generators/Granular/PitchShift.swift` | current pool model, untouched until decision | | `Sources/Lyrebird/Generators/Granular/PitchShift4Head.swift` | new 4-head class (Option 1) | | `Tests/LyrebirdTests/PitchShift4HeadTests.swift` | parity test suite | | `Sources/LyrebirdBenchmark/main.swift` | add PitchShift A/B benchmark | | `docs/stdlib/generators.md` | document new type / mode if shipped | ## Estimated effort - 4-head implementation + tests: ~half day. - Benchmark harness + run: ~half day. - A/B render + listening notes: ~half day. - Decision + cleanup or merge: ~half day. Total ~2 days when scheduled. Not blocking any current phase. ## Open questions — resolved at implementation time 1. **Param compatibility.** `windowSize > 0` precondition retained; internal `framesize` clamps to ≥ 4 samples after rounding to a multiple of 4. Audible difference at < ~3 samples is moot. 2. **`pitchRatio` clamp.** Kept at Lyrebird `[0.25, 4]` for cross-variant consistency. SC's `[0, 4]` not adopted. 3. **MCE expansion.** Both mono; nothing to change. ## Implementation log Landed: - `Sources/Lyrebird/Generators/Granular/PitchShift4Head.swift` — `PitchShift.Audio4` - `Tests/LyrebirdTests/PitchShift4HeadTests.swift` — 10 parity tests - `Sources/LyrebirdBenchmark/main.swift` — A/B benchmark section - `Sources/Lyrebird/Lyrebird.docc/Generators/PitchShifting.md` — variant section Bench results (release build, 16 instances in parallel, 10 000 iterations): ``` PitchShift.Audio overlap=4 ×16 2968 ns/block PitchShift.Audio overlap=8 ×16 2877 ns/block PitchShift.Audio4 ×16 2864 ns/block ``` Single-instance numbers are dominated by `OscSin → Pan2 → Out` overhead, so the inter-variant difference is small (≈ 2 % spread). At polyphony of 16, the 4-head model is the fastest variant, edging the `overlap = 8` pool by ~0.5 % and the matched `overlap = 4` pool by ~3.5 %. CPU criterion (1) is met. ## Pending — listening test + decision Plan above (NRT renders at three pitchRatios, subjective listening + spectrogram inspection) is unchanged. After listening: - If `Audio4` is judged equal-or-better at all three pitchRatios: deprecate `PitchShift.Audio` over a phase or two, keep `Audio4`. - If both have niches: keep both indefinitely. Update DocC to nudge users toward the right one (steady tonal material → Audio4; transient / textural material with higher `overlap` → Audio). - If `Audio4` is worse: revert the file, keep the bench as historical context.