feat(poly-octave): EHX POG-style polyphonic octave pedal

Add PolyOctavePedal: a fixed-interval polyphonic octave generator. Four
PitchShift voices at exact power-of-two ratios — −2, −1, +1, +2 octaves,
each single-stage within PitchShift's [0.25, 4.0] clamp — stacked under a
dry voice, each with its own level. Because the ratios need no pitch
tracking, chords stack as cleanly as single notes.

A Tone low-pass shapes the shifted voices (dry stays clean). An Attack
knob adds the POG's volume swell via a "slow-gear" gain: the ratio of a
slow envelope follower to a fast one, clamped to [0, 1] and guarded
against divide-by-zero — unity (instant) at Attack 0, blooming in as it
rises, independent of playing level. The five voice levels sum without an
internal limiter (as with BassOctaver); the level knob and board master
set final gain.

Wire into PedalType, the registry, and the pitch category; add to the
README pitch catalog. 12 tests: per-voice pitch (±1/±2 oct + unison) by
autocorrelation, swell neutral-vs-bloom, seeded determinism, a click-free
bypass flip at the real 512-sample block, knob labels, preset round-trip,
registry presence.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-24 09:53:43 -08:00
parent 3edd64e782
commit 20b2034fed
7 changed files with 659 additions and 1 deletions
@@ -0,0 +1,412 @@
// PolyOctavePedalTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
/// A steady sine source for pitch tests — a known, stable fundamental the octave voices can shift
/// so a test can measure the output pitch.
@MainActor
private final class TestSineSource: SynthesizerBase {
private let targetBus: Int
private let freq: Double
private let amp: Double
init(targetBus: Int, freq: Double, amplitude: Double = 0.5) {
self.targetBus = targetBus
self.freq = freq
self.amp = amplitude
super.init()
}
override func build() {
output(bus: targetBus, source: OscSin.Audio(freq: freq, mul: amp))
}
}
@MainActor
@Suite("PolyOctavePedal")
struct PolyOctavePedalTests {
// MARK: - Analysis constants
/// Engine sample rate (matches `makeNRTEngine`'s default).
private let sampleRate: Double = 44_100.0
/// Render long enough that the analysis window lands well past the shifter's warm-up.
private let renderDuration: Double = 0.8
/// Test tone fundamental. Mid-range so ±2 octaves stays inside `[20, Nyquist]`.
private let sineHz: Double = 220.0
/// Interleaved-stereo frame offset to start analysis at — clears the shifter's warm-up.
private let analysisSkipFrames: Int = 13_230 // ~0.3 s
/// Analysis window length in frames. ~0.37 s → ≥10 cycles even at −2 octaves.
private let analysisWindowFrames: Int = 16_384
// MARK: - Render helpers
/// Renders the pedal driven by a steady sine at `sineHz`, over `renderDuration`.
private func renderSine(
configure: (PolyOctavePedal) -> Void
) throws -> [Float] {
try renderSine(duration: renderDuration, configure: configure)
}
/// Renders the pedal driven by a steady sine at `sineHz`, over a caller-chosen duration (the
/// swell test needs a longer window to see the bloom develop).
private func renderSine(
duration: Double,
configure: (PolyOctavePedal) -> Void
) throws -> [Float] {
let numAudioBuses: Int = 64
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: duration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: sineHz)
let pedal: PolyOctavePedal = PolyOctavePedal(
inputBus: srcBus.index,
outputBus: dstBus.index
)
configure(pedal)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
return readStereoCAF(url: url)
}
// MARK: - Signal analysis
/// Estimates the fundamental of the left channel by autocorrelation. Searches lags in
/// `[20 Hz, maxHz]`; a deep down-shift carries strong grain-rate HF that a wide search would lock
/// onto, so callers testing those pass a ceiling near the expected Hz.
private func fundamentalHz(_ samples: [Float], minHz: Double = 20.0, maxHz: Double = 1_500.0) -> Double {
let needed: Int = analysisSkipFrames + analysisWindowFrames
guard samples.count >= 2 * needed else { return 0.0 }
var x: [Double] = []
x.reserveCapacity(analysisWindowFrames)
for i: Int in analysisSkipFrames ..< needed {
x.append(Double(samples[2 * i])) // left channel of the interleaved pair
}
let mean: Double = x.reduce(0.0, +) / Double(x.count)
for i: Int in x.indices { x[i] -= mean }
let minLag: Int = Int(sampleRate / maxHz)
let maxLag: Int = min(Int(sampleRate / minHz), x.count - 1)
guard maxLag > minLag else { return 0.0 }
var bestLag: Int = minLag
var bestCorr: Double = -Double.infinity
for lag: Int in minLag ... maxLag {
var c: Double = 0.0
for i: Int in 0 ..< (x.count - lag) {
c += x[i] * x[i + lag]
}
if c > bestCorr {
bestCorr = c
bestLag = lag
}
}
return sampleRate / Double(bestLag)
}
/// RMS of the left channel over an interleaved-frame range `[lo, hi)`.
private func rms(_ samples: [Float], loFrame: Int, hiFrame: Int) -> Double {
let a: Int = max(0, loFrame)
let b: Int = min(hiFrame, samples.count / 2)
guard b > a else { return 0.0 }
var sum: Double = 0.0
for i: Int in a ..< b {
let v: Double = Double(samples[2 * i])
sum += v * v
}
return (sum / Double(b - a)).squareRoot()
}
/// Max absolute first difference (per-sample step) over `[lo, hi)`. An impulsive click shows up
/// as a step far larger than the signal's own slope.
private func maxStep(_ x: [Float], lo: Int, hi: Int) -> Double {
let a: Int = max(1, lo)
let b: Int = min(hi, x.count)
guard b > a else { return 0.0 }
var m: Double = 0.0
for i: Int in a ..< b {
let d: Double = abs(Double(x[i]) - Double(x[i - 1]))
if d > m { m = d }
}
return m
}
// MARK: - Pitch behaviour (one voice isolated at a time, dry muted)
@Test func upOneVoiceRaisesPitchAnOctave() throws {
// +1 oct voice alone (ratio 2.0): 220 Hz should land near 440 Hz.
let out: [Float] = try renderSine { pedal in
pedal.dry = 0.0
pedal.upOne = 1.0
}
let hz: Double = fundamentalHz(out)
#expect(hasNonSilentOutput(out), "+1 oct render was silent")
// ±12% is tight enough to reject a wrong interval (a fifth is +50%) but clears the
// autocorrelation lag quantisation (~1% here) and the shifter's warble.
#expect(abs(hz - sineHz * 2.0) < sineHz * 2.0 * 0.12, "+1 oct should be ~440 Hz, got \(hz)")
}
@Test func subOneVoiceLowersPitchAnOctave() throws {
// −1 oct voice alone (ratio 0.5): 220 Hz should land near 110 Hz.
let out: [Float] = try renderSine { pedal in
pedal.dry = 0.0
pedal.subOne = 1.0
}
let hz: Double = fundamentalHz(out)
#expect(hasNonSilentOutput(out), "−1 oct render was silent")
#expect(abs(hz - sineHz * 0.5) < sineHz * 0.5 * 0.12, "−1 oct should be ~110 Hz, got \(hz)")
}
@Test func upTwoVoiceRaisesPitchTwoOctaves() throws {
// +2 oct voice alone (ratio 4.0, single stage at the clamp edge): 220 Hz → ~880 Hz.
let out: [Float] = try renderSine { pedal in
pedal.dry = 0.0
pedal.upTwo = 1.0
}
// Search a band around +2 oct so the autocorrelation can't lock onto the 441 Hz subharmonic
// lag (an 880 Hz tone is also periodic at 440 Hz, a near-tie in the correlation).
let hz: Double = fundamentalHz(out, minHz: 500.0)
#expect(hasNonSilentOutput(out), "+2 oct render was silent")
#expect(abs(hz - sineHz * 4.0) < sineHz * 4.0 * 0.15, "+2 oct should be ~880 Hz, got \(hz)")
}
@Test func subTwoVoiceLowersPitchTwoOctaves() throws {
// −2 oct voice alone (ratio 0.25, single stage at the clamp edge): 220 Hz → ~55 Hz.
// Cap the search near the expected low fundamental so deep-shift grain HF can't win.
let out: [Float] = try renderSine { pedal in
pedal.dry = 0.0
pedal.subTwo = 1.0
}
let hz: Double = fundamentalHz(out, maxHz: 160.0)
#expect(hasNonSilentOutput(out), "−2 oct render was silent")
#expect(abs(hz - sineHz * 0.25) < sineHz * 0.25 * 0.15, "−2 oct should be ~55 Hz, got \(hz)")
}
@Test func dryVoicePassesAtUnison() throws {
// Dry voice alone (no octaves): output stays at the input pitch.
let out: [Float] = try renderSine { pedal in
pedal.dry = 1.0
pedal.upOne = 0.0
}
let hz: Double = fundamentalHz(out)
#expect(hasNonSilentOutput(out), "dry-only render was silent")
#expect(abs(hz - sineHz) < sineHz * 0.2, "dry should stay ~220 Hz, got \(hz)")
}
// MARK: - Swell
@Test func swellIsNeutralAtZeroAttackAndBloomsAtHighAttack() throws {
// Isolate the +1 oct voice (dry muted). The sine starts from silence at engine start, so the
// swell's slow-gear gain shapes the voice's onset: at attack 0 the voice is present from the
// first cycles (early RMS ≈ late RMS); at attack 1 it blooms in over ~1.5 s (early RMS well
// below late RMS). Compare the early/late RMS ratio between the two settings.
let duration: Double = 2.0
let warmupFrames: Int = Int(0.15 * sampleRate) // past the shifter warm-up
let earlyLo: Int = warmupFrames
let earlyHi: Int = warmupFrames + Int(0.2 * sampleRate) // ~0.15–0.35 s
let lateLo: Int = Int(1.5 * sampleRate)
let lateHi: Int = Int(1.9 * sampleRate)
let instant: [Float] = try renderSine(duration: duration) { pedal in
pedal.dry = 0.0
pedal.upOne = 1.0
pedal.attack = 0.0
}
let swelled: [Float] = try renderSine(duration: duration) { pedal in
pedal.dry = 0.0
pedal.upOne = 1.0
pedal.attack = 1.0
}
let instantRatio: Double =
rms(instant, loFrame: earlyLo, hiFrame: earlyHi)
/ max(rms(instant, loFrame: lateLo, hiFrame: lateHi), 1.0e-9)
let swelledRatio: Double =
rms(swelled, loFrame: earlyLo, hiFrame: earlyHi)
/ max(rms(swelled, loFrame: lateLo, hiFrame: lateHi), 1.0e-9)
#expect(hasNonSilentOutput(swelled), "swelled render was silent")
// Instant: roughly flat onset (early ≈ late).
#expect(instantRatio > 0.6, "attack 0 should have a near-flat onset, early/late ratio \(instantRatio)")
// Swell: the early window is markedly quieter than steady state, and quieter than the
// instant setting's early window.
#expect(swelledRatio < instantRatio * 0.6,
"attack 1 should bloom in (swelled early/late \(swelledRatio) vs instant \(instantRatio))")
}
@Test func renderIsDeterministic() throws {
// Every PitchShift voice is seeded and the sine source is RNG-free, so two identical renders
// must be bit-identical.
let a: [Float] = try renderSine { pedal in
pedal.subTwo = 0.3
pedal.upOne = 0.7
pedal.upTwo = 0.4
}
let b: [Float] = try renderSine { pedal in
pedal.subTwo = 0.3
pedal.upOne = 0.7
pedal.upTwo = 0.4
}
#expect(a == b, "seeded renders of the same setting should be bit-identical")
}
// MARK: - Bypass transition
/// Renders the pedal manually block-by-block through a no-op `OfflineDriver`, flipping `bypass`
/// from engaged (`0`) to bypassed (`1`) at `flipFrame`, and returns the left hardware-output
/// channel. Hand-stepping `processBlock` is the only way to change a live `@UIParam` mid-render.
private func renderBypassFlip(
flipFrame: Int,
totalFrames: Int,
blockSize: Int,
configure: (PolyOctavePedal) -> Void
) throws -> [Float] {
let numAudioBuses: Int = 64
let numControlBuses: Int = 512
let driver: OfflineDriver = OfflineDriver()
let engine: SynthesisEngine = SynthesisEngine(
blockSize: blockSize,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: numAudioBuses,
numControlBuses: numControlBuses,
driver: driver
)
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: sineHz)
let pedal: PolyOctavePedal = PolyOctavePedal(inputBus: srcBus.index, outputBus: dstBus.index)
configure(pedal)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
let noInput: [[Float]] = []
var left: [Float] = []
left.reserveCapacity(totalFrames)
var frame: Int = 0
var flipped: Bool = false
while frame < totalFrames {
if !flipped, frame >= flipFrame {
pedal.bypass = 1.0 // engage → bypassed, mid-render
flipped = true
}
engine.processBlock(inputSamples: noInput)
let bus: [Float] = engine.audioBuses[0] // hardware output, left
left.append(contentsOf: bus)
frame += blockSize
}
engine.stop()
return left
}
@Test func bypassSwitchIsClickFree() throws {
// Clocking a wet-only octave-up voice (dry muted, +1 oct at full) on/off crossfades the dry
// note against a fully decorrelated shifted voice. The audio-rate linear equal-power bypass
// crossfade must keep that click-free at the engine's real 512-sample block — a block-rate
// smoother would leak a coarse step here.
let blockSize: Int = 512
let totalFrames: Int = 26_460 // 0.6 s
let flipFrame: Int = 15_435 // ~0.35 s
let left: [Float] = try renderBypassFlip(
flipFrame: flipFrame,
totalFrames: totalFrames,
blockSize: blockSize
) { pedal in
pedal.dry = 0.0
pedal.upOne = 1.0
pedal.attack = 0.0 // no swell, so the voice is full-scale at the seam
}
#expect(hasNonSilentOutput(left), "bypass-flip render was silent")
let steadyLo: Int = 9_700 // ~0.22 s
let steadyHi: Int = 14_500 // ~0.33 s
let fadeFrames: Int = Int(0.03 * sampleRate)
let transLo: Int = flipFrame - blockSize
let transHi: Int = flipFrame + fadeFrames + 2_000
let steadyStep: Double = maxStep(left, lo: steadyLo, hi: steadyHi)
let transStep: Double = maxStep(left, lo: transLo, hi: transHi)
#expect(transStep <= steadyStep * 4.0,
"bypass transition stepped \(transStep) vs steady \(steadyStep) — a click leaked through")
}
// MARK: - Build / wiring
@Test func buildsAndProducesNonSilentOutput() throws {
let samples: [Float] = try renderSine { pedal in
pedal.dry = 1.0
pedal.upOne = 0.5
}
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "poly-octave output was silent")
}
@Test func exposesSevenVoiceKnobs() throws {
let pedal: PolyOctavePedal = PolyOctavePedal()
#expect(pedal.effectKnobs.map { $0.label }
== ["-2 Oct", "-1 Oct", "+1 Oct", "+2 Oct", "Dry", "Attack", "Tone"])
}
@Test func presetRoundTripPreservesKnobs() throws {
let pedal: PolyOctavePedal = PolyOctavePedal()
pedal.subTwo = 0.2
pedal.subOne = 0.3
pedal.upOne = 0.4
pedal.upTwo = 0.5
pedal.dry = 0.6
pedal.attack = 0.7
pedal.tone = 6000.0
let state: PedalState = pedal.captureState()
let restored: PolyOctavePedal = PolyOctavePedal()
restored.applyState(state)
#expect(restored.subTwo == 0.2)
#expect(restored.subOne == 0.3)
#expect(restored.upOne == 0.4)
#expect(restored.upTwo == 0.5)
#expect(restored.dry == 0.6)
#expect(restored.attack == 0.7)
#expect(restored.tone == 6000.0)
}
@Test func registeredInBuiltInRegistry() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "Poly Octave")
#expect(pedal is PolyOctavePedal)
}
}