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
+1
View File
@@ -23,3 +23,4 @@ review.diff
# Local working plan (not shared)
docs/plans/amp-expansion-plan.md
docs/plans/pedal-expansion-plan.md
+1 -1
View File
@@ -47,7 +47,7 @@ signal (no hardware needed) or on live guitar through an audio input.
| Dynamics | Compressor, Sustainer, Limiter, Noise Gate, Volume |
| EQ & filter | Graphic EQ, Auto-Wah, Wah, Mutant |
| Modulation | Tremolo, Phaser, Modulation, Chorus, Flanger, Vibrato, Vibe, Rotary, Ring Modulator |
| Pitch | Bass Octaver, Octave Splitter, Harmonizer, Whammy |
| Pitch | Bass Octaver, Octave Splitter, Harmonizer, Whammy, Poly Octave |
| Delay | Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverse Delay |
| Reverb | Reverb, Shimmer Reverb, Plate Reverb, Room Reverb, Spring Reverb |
| Texture | Diffuser, Bitcrusher, Granulator, Auto Granulator, Looper |
+1
View File
@@ -124,6 +124,7 @@ public extension PedalType {
static let bassOctaver = PedalType("Bass Octaver")
static let harmonizer = PedalType("Harmonizer")
static let whammy = PedalType("Whammy")
static let polyOctave = PedalType("Poly Octave")
// Looper
static let looper = PedalType("Looper")
@@ -0,0 +1,242 @@
// PolyOctavePedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Polyphonic octave generator in the EHX POG mould.
///
/// Stacks four fixed pitch-shifted voices — two octaves down, one octave down, one octave up, two
/// octaves up — under the dry note, each with its own level, so a single note becomes an
/// organ-like chord of octaves. Unlike the ``WhammyPedal`` (one voice swept by an expression
/// pedal), every voice sounds at once at a **fixed** interval, and because the ratios are exact
/// powers of two the shifter needs no pitch tracking — chords shift as cleanly as single notes.
///
/// Each voice is a `PitchShift` — Lyrebird's four-head SOLA shifter, whose `pitchRatio` clamps to
/// `[0.25, 4.0]`, i.e. exactly ±2 octaves, so every voice here is a single stage (no cascade).
///
/// The five voice levels sum without an internal limiter (as with the OC-2-style
/// ``BassOctaverPedal``), so driving several to full can push the sum above unity; the pedal's
/// `level` knob and the board output master set the final gain, like a real mixer's channel sum.
///
/// A low-pass **Tone** control tames the shifted voices (the dry stays untouched), and an
/// **Attack** control adds the POG's signature volume **swell**: turned up, the octave voices fade
/// in after each note instead of sounding instantly, for a bowed / synth-pad bloom. The swell is a
/// "slow-gear" gain — the ratio of a slow envelope follower to a fast one — so at `Attack = 0` the
/// two followers are identical and the gain is unity (voices respond instantly), and the swell
/// never depends on how loud you play.
///
/// ## Knobs
/// - `subTwo`: −2 octave voice level in `[0, 1]`.
/// - `subOne`: −1 octave voice level in `[0, 1]`.
/// - `upOne`: +1 octave voice level in `[0, 1]`.
/// - `upTwo`: +2 octave voice level in `[0, 1]`.
/// - `dry`: Dry (direct) signal level in `[0, 1]`.
/// - `attack`: Octave-voice swell in `[0, 1]`. `0` = instant; higher = slower volume bloom.
/// - `tone`: Octave-voice low-pass cutoff in Hz. Range `[500, 12000]`.
public final class PolyOctavePedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Stacks fixed octave voices under your note — organ-like, with a volume swell."
}
// MARK: - Parameters
/// −2 octave voice level in `[0, 1]`.
@UIParam public var subTwo: Double = 0.0
/// −1 octave voice level in `[0, 1]`.
@UIParam public var subOne: Double = 0.0
/// +1 octave voice level in `[0, 1]`.
@UIParam public var upOne: Double = 0.5
/// +2 octave voice level in `[0, 1]`.
@UIParam public var upTwo: Double = 0.0
/// Dry (direct) signal level in `[0, 1]`.
@UIParam public var dry: Double = 1.0
/// Octave-voice swell in `[0, 1]`. `0` = instant; higher = slower volume bloom after each note.
@UIParam public var attack: Double = 0.0
/// Octave-voice low-pass cutoff in Hz. Range `[500, 12000]`.
@UIParam public var tone: Double = 8000.0
// MARK: - Constants
/// Pedal blends everything internally via the level knobs, so the base wet/dry stays fully wet.
private static let defaultMix: Double = 1.0
/// Fixed `PitchShift` playback ratios for the four voices (exact powers of two).
private let subTwoRatio: Double = 0.25 // −2 octaves
private let subOneRatio: Double = 0.5 // −1 octave
private let upOneRatio: Double = 2.0 // +1 octave
private let upTwoRatio: Double = 4.0 // +2 octaves
/// Grain window for each `PitchShift`, in seconds. A touch over the shifter's `0.1` default to
/// soften the periodic four-head comb without adding audible lag.
private let voiceWindowSize: Double = 0.11
/// Per-head timing jitter for each `PitchShift`, in seconds. Breaks the fixed-grid comb; kept
/// small so the voices stay tight.
private let voiceTimeDispersion: Double = 0.02
/// Fixed PRNG seeds, one per voice, so a given setting renders identically every time
/// (reproducible audio and exact-pitch tests). Distinct per voice so their grain dispersion
/// sequences decorrelate instead of jittering in lockstep.
private let subTwoSeed: UInt64 = 0x9E37_79B9_7F4A_7C15
private let subOneSeed: UInt64 = 0xC2B2_AE3D_27D4_EB4F
private let upOneSeed: UInt64 = 0x1656_67B1_9E37_79F9
private let upTwoSeed: UInt64 = 0x2545_F491_4F6C_DD1D
/// Fast envelope-follower attack for the swell's denominator, in seconds — near-instant, so it
/// tracks note onsets tightly. Also the floor of the mapped slow attack, so `attack = 0` makes
/// the two followers identical and the swell gain unity (neutral).
private let swellFastAttack: Double = 0.005
/// Slowest envelope-follower attack the `attack` knob maps to, in seconds (at `attack = 1`).
private let swellMaxAttack: Double = 1.5
/// Shared release time for both swell followers, in seconds. Equal on both so only the attack
/// differs between them.
private let swellRelease: Double = 0.15
/// Floor added to the swell denominator before the reciprocal, so a silent input (both
/// followers near zero) cannot divide by zero. Kept well below any real signal level
/// (`1e-6` ≈ −120 dB) so the neutral gain stays ~1 across the whole playing range — a larger
/// floor would pull the `attack = 0` gain toward `0.5` for quiet input.
private let swellDenomFloor: Double = 1.0e-6
/// Clamp bounds for the swell gain. With equal release times the two followers track in
/// lockstep once settled, so the ratio stays `≤ 1` in normal use (it dips below `1` only during
/// the attack ramp, when the slow follower lags); the ceiling is a defensive guard against a
/// transient overshoot from the reciprocal, and the floor keeps the gain non-negative.
private let swellGainFloor: Double = 0.0
private let swellGainCeil: Double = 1.0
/// Butterworth Q (no resonant peak) for the tone low-pass.
private let toneQ: Double = 0.707
// MARK: - Ranges
private let levelRange: ClosedRange<Double> = 0.0 ... 1.0
private let attackRange: ClosedRange<Double> = 0.0 ... 1.0
private let toneRange: ClosedRange<Double> = 500.0 ... 12000.0
// MARK: - Knobs
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "-2 Oct", node: $subTwo, range: levelRange),
PedalKnob(label: "-1 Oct", node: $subOne, range: levelRange),
PedalKnob(label: "+1 Oct", node: $upOne, range: levelRange),
PedalKnob(label: "+2 Oct", node: $upTwo, range: levelRange),
PedalKnob(label: "Dry", node: $dry, range: levelRange),
PedalKnob(label: "Attack", node: $attack, range: attackRange),
PedalKnob(label: "Tone", node: $tone, range: toneRange),
]
}
// MARK: - Init
/// Creates a polyphonic octave pedal.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the output to. Defaults to `0`.
public init(
inputBus: Int = 0,
outputBus: Int = 0
) {
super.init(
name: "Poly Octave",
inputBus: inputBus,
outputBus: outputBus,
initialMix: PolyOctavePedal.defaultMix
)
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
// Four fixed-ratio voices. Each ratio is within PitchShift's ±2-octave clamp, so a single
// stage suffices (no cascade, unlike the Whammy's 3-octave Dive Bomb).
let subTwoVoice: PitchShift.Audio = makeVoice(dry: dry, ratio: subTwoRatio, seed: subTwoSeed)
let subOneVoice: PitchShift.Audio = makeVoice(dry: dry, ratio: subOneRatio, seed: subOneSeed)
let upOneVoice: PitchShift.Audio = makeVoice(dry: dry, ratio: upOneRatio, seed: upOneSeed)
let upTwoVoice: PitchShift.Audio = makeVoice(dry: dry, ratio: upTwoRatio, seed: upTwoSeed)
// Octave bus: each voice scaled by its level knob.
let octaveBus: any ValidGeneratorInput =
(subTwoVoice * $subTwo)
+ (subOneVoice * $subOne)
+ (upOneVoice * $upOne)
+ (upTwoVoice * $upTwo)
// Swell: a "slow-gear" gain applied to the octave bus only (the dry stays immediate).
let swelled: any ValidGeneratorInput = octaveBus * swellGain(dry: dry)
// Tone shapes the shifted voices, not the dry.
let octaveToned: RBJLowPass.Audio = RBJLowPass.Audio(
input: swelled,
freq: $tone,
q: toneQ
)
return (dry * $dry) + octaveToned
}
/// Builds one fixed-ratio octave voice.
///
/// - Parameters:
/// - dry: Dry input to shift.
/// - ratio: Fixed playback ratio (power of two) within PitchShift's `[0.25, 4.0]` clamp.
/// - seed: Per-voice PRNG seed for reproducible grain dispersion.
/// - Returns: The pitch-shifted voice (pre-level).
private func makeVoice(
dry: any ValidGeneratorInput,
ratio: Double,
seed: UInt64
) -> PitchShift.Audio {
PitchShift.Audio(
input: dry,
pitchRatio: ratio,
windowSize: voiceWindowSize,
timeDispersion: voiceTimeDispersion,
seed: seed
)
}
/// Builds the octave-voice swell gain: the ratio of a slow envelope follower to a fast one,
/// clamped to `[0, 1]`. Unity when `attack = 0` (both followers identical), dipping and then
/// recovering as `attack` rises, so the voices bloom in after each onset independent of level.
///
/// - Parameter dry: Dry input the swell tracks.
/// - Returns: A `[0, 1]` gain to multiply the octave bus by.
private func swellGain(dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
// attack [0, 1] → slow-follower attack [swellFastAttack, swellMaxAttack] seconds.
let attackSpan: Double = swellMaxAttack - swellFastAttack
let slowAttackTime: any ValidGeneratorInput = ($attack * attackSpan) + swellFastAttack
let fastEnv: AmplitudeFollower.Audio = AmplitudeFollower.Audio(
in: dry,
attackTime: swellFastAttack,
releaseTime: swellRelease
)
let slowEnv: AmplitudeFollower.Audio = AmplitudeFollower.Audio(
in: dry,
attackTime: slowAttackTime,
releaseTime: swellRelease
)
// gain = slowEnv / (fastEnv + floor), clamped to [0, 1].
let denom: any ValidGeneratorInput = fastEnv + swellDenomFloor
let ratio: any ValidGeneratorInput = slowEnv * Reciprocal.Audio(denom)
return Clip.Audio(ratio, lo: swellGainFloor, hi: swellGainCeil)
}
}
@@ -80,6 +80,7 @@ public enum PedalRegistry {
"Bass Octaver": { BassOctaverPedal() },
"Harmonizer": { HarmonizerPedal() },
"Whammy": { WhammyPedal() },
"Poly Octave": { PolyOctavePedal() },
"Ping-Pong": { PingPongDelayPedal() },
"Reverse Delay": { ReverseDelayPedal() },
"Shimmer Reverb": { ShimmerReverbPedal() },
@@ -54,6 +54,7 @@ public enum PedalCategory: String, CaseIterable, Identifiable, Sendable {
"Tremolo": .modulation, "Phaser": .modulation, "Modulation": .modulation, "Chorus": .modulation,
"Flanger": .modulation, "Vibrato": .modulation, "Rotary": .modulation, "Ring Modulator": .modulation,
"Bass Octaver": .pitch, "Octave Splitter": .pitch, "Harmonizer": .pitch, "Whammy": .pitch,
"Poly Octave": .pitch,
"Delay": .delay, "Feedback Delay": .delay, "Multi-Tap Delay": .delay, "Ping-Pong": .delay,
"Reverse Delay": .delay,
"Reverb": .reverb, "Shimmer Reverb": .reverb,
@@ -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)
}
}