feat(pedals): oversample nonlinear drive stages; Sustainer safety limiter

Anti-aliasing (Tier 1): every hard nonlinearity ran at the engine rate, so the
harmonics it generated folded back as inharmonic aliasing — worst on loud/bright
input at high drive. Add two oversampled RT generators built on Lyrebird's
halfband up/down-samplers and move the drive pedals onto them:

- OversampledSaturator (+ SaturationCurve) — tanh / normalised soft-clip /
  tanh+hard-clip curves at 2× or 4×. DistortionPedal now does its tanh→gain→hard
  clip at 4× (clip before the tone low-pass), with a final hard clip after the
  low-pass to re-establish the strict output bound; FuzzPedal (tanh) and
  OverdrivePedal (soft-clip) at 2×.
- OversampledRingModulator — input × sine carrier at 2×, carrier synthesized at
  the oversampled rate so the sum sideband can't alias. Phase wraps both
  directions (safe for negative carrier frequencies) and a sampleRate guard
  prevents NaN latching. RingModulatorPedal uses it.

Dynamics (Tier 2): SustainerPedal gains an opt-in Safety switch (off by default)
that inserts a brick-wall LookAheadLimiter after its compressor to catch the
transient overshoot a low-threshold/high-makeup setting can push past full scale.

Tests: generator-level alias-reduction proofs (Goertzel alias/fundamental ratio
vs a naive base-rate baseline) for both oversampled generators, hard-clip/soft
bounds, negative-carrier stability, distortion output-bound at high drive, and
Sustainer safety switch exposure + peak-capping. Full suite 478 pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-31 20:26:44 -07:00
parent e697789bd7
commit 8983e8829e
12 changed files with 765 additions and 15 deletions
@@ -84,6 +84,16 @@ struct DistortionPedalTests {
#expect(labels == ["Drive", "Tone"])
}
@Test func outputStaysBoundedAtHighDrive() throws {
// The final hard clip (after the tone low-pass) must re-establish the ±1 output bound
// even at extreme drive, despite the oversampled clip sitting before the low-pass.
let samples: [Float] = try render { pedal in pedal.drive = 50.0; pedal.tone = 6000.0 }
let skip: Int = 2048
guard samples.count > skip else { return }
let peak: Float = samples[skip...].reduce(0) { Swift.max($0, abs($1)) }
#expect(peak <= 1.05, "distortion output exceeded the clip ceiling: peak=\(peak)")
}
@Test func registeredInBuiltInRegistry() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "Distortion")
#expect(pedal is DistortionPedal)
@@ -0,0 +1,139 @@
// OversampledRingModulatorTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("OversampledRingModulator")
struct OversampledRingModulatorTests {
private let sampleRate: Double = 44100.0
/// Minimal synth: a sine through an `OversampledRingModulator`, written to a mono bus.
private final class RingSynth: SynthesizerBase {
private let inFreq: Double
private let carrierFreq: Double
private let factor: Int
private let outBus: Int
init(inFreq: Double, carrierFreq: Double, factor: Int, outBus: Int) {
self.inFreq = inFreq
self.carrierFreq = carrierFreq
self.factor = factor
self.outBus = outBus
super.init()
}
override func build() {
let osc: OscSin.Audio = OscSin.Audio(freq: inFreq)
output(bus: outBus, source: OversampledRingModulator(
osc, freq: carrierFreq, oversample: factor))
}
}
private func render(inFreq: Double, carrierFreq: Double, factor: Int) throws -> [Float] {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.15, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: url) }
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer { engine.busAllocator.releaseAudioBus(dstBus) }
let synth: RingSynth = RingSynth(
inFreq: inFreq, carrierFreq: carrierFreq, factor: factor, outBus: dstBus.index)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(synth)
try engine.add(master, position: NodePosition.after(synth))
try engine.start()
return readStereoCAF(url: url, sampleRate: sampleRate)
}
private func leftChannel(_ samples: [Float], skip: Int) -> [Double] {
var out: [Double] = []
var i: Int = skip * 2
while i < samples.count {
out.append(Double(samples[i]))
i += 2
}
return out
}
private func goertzelMagnitude(_ x: [Double], cyclesPerSample: Double) -> Double {
let omega: Double = 2.0 * Double.pi * cyclesPerSample
let cosine: Double = cos(omega)
let sine: Double = sin(omega)
let coeff: Double = 2.0 * cosine
var s1: Double = 0.0
var s2: Double = 0.0
for v: Double in x {
let s0: Double = v + coeff * s1 - s2
s2 = s1
s1 = s0
}
let real: Double = s1 - s2 * cosine
let imag: Double = s2 * sine
return (real * real + imag * imag).squareRoot()
}
private func naiveRingMod(inFreq: Double, carrierFreq: Double, count: Int) -> [Double] {
let inCps: Double = inFreq / sampleRate
let cCps: Double = carrierFreq / sampleRate
var out: [Double] = []
out.reserveCapacity(count)
for n: Int in 0..<count {
let x: Double = sin(2.0 * Double.pi * inCps * Double(n))
let c: Double = sin(2.0 * Double.pi * cCps * Double(n))
out.append(x * c)
}
return out
}
@Test func reducesSumSidebandAliasVersusNaive() throws {
// in = 0.20·Fs, carrier = 0.35·Fs. Difference sideband = 0.15·Fs (legit, below Nyquist);
// sum sideband = 0.55·Fs, which folds to a 0.45·Fs alias at the base rate. Measure the
// alias relative to the legit difference sideband (self-normalising).
let inHz: Double = 0.20 * sampleRate
let carrierHz: Double = 0.35 * sampleRate
let diffBin: Double = 0.15 // |0.35 − 0.20|
let aliasBin: Double = 0.45 // |1 − 0.55|
let os: [Float] = try render(inFreq: inHz, carrierFreq: carrierHz, factor: 2)
let osLeft: [Double] = leftChannel(os, skip: 2048)
#expect(osLeft.count > 2048)
let osDiff: Double = goertzelMagnitude(osLeft, cyclesPerSample: diffBin)
let osAlias: Double = goertzelMagnitude(osLeft, cyclesPerSample: aliasBin)
let osRatio: Double = osAlias / osDiff
let naive: [Double] = naiveRingMod(inFreq: inHz, carrierFreq: carrierHz, count: osLeft.count)
let nDiff: Double = goertzelMagnitude(naive, cyclesPerSample: diffBin)
let nAlias: Double = goertzelMagnitude(naive, cyclesPerSample: aliasBin)
let naiveRatio: Double = nAlias / nDiff
#expect(naiveRatio > 0.05, "baseline did not alias as expected (ratio=\(naiveRatio))")
#expect(
osRatio < naiveRatio * 0.5,
"oversampling did not reduce ring-mod aliasing: os=\(osRatio) naive=\(naiveRatio)"
)
}
@Test func producesNonSilentOutput() throws {
let os: [Float] = try render(inFreq: 440.0, carrierFreq: 220.0, factor: 2)
#expect(hasNonSilentOutput(os), "ring modulator produced silence")
}
@Test func negativeCarrierStaysFiniteAndBounded() throws {
// A negative carrier frequency drives the phase increment negative; the phase must wrap
// both directions rather than growing unbounded and pushing sin() out of accurate range.
let os: [Float] = try render(inFreq: 440.0, carrierFreq: -220.0, factor: 2)
let left: [Double] = leftChannel(os, skip: 1024)
#expect(!left.isEmpty)
#expect(left.allSatisfy { $0.isFinite }, "negative carrier produced non-finite output")
let peak: Double = left.map { abs($0) }.max() ?? 0
#expect(peak <= 1.2, "negative carrier output was not bounded: peak=\(peak)")
}
}
@@ -0,0 +1,174 @@
// OversampledSaturatorTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("OversampledSaturator")
struct OversampledSaturatorTests {
private let sampleRate: Double = 44100.0
/// Minimal synth: a sine through an `OversampledSaturator`, written to a mono bus.
private final class SaturatorSynth: SynthesizerBase {
private let freq: Double
private let drive: Double
private let curve: SaturationCurve
private let factor: Int
private let outBus: Int
init(freq: Double, drive: Double, curve: SaturationCurve, factor: Int, outBus: Int) {
self.freq = freq
self.drive = drive
self.curve = curve
self.factor = factor
self.outBus = outBus
super.init()
}
override func build() {
let osc: OscSin.Audio = OscSin.Audio(freq: freq)
output(bus: outBus, source: OversampledSaturator(
osc, drive: drive, curve: curve, oversample: factor))
}
}
private func render(
freq: Double,
drive: Double,
curve: SaturationCurve,
factor: Int
) throws -> [Float] {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.15, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: url) }
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer { engine.busAllocator.releaseAudioBus(dstBus) }
let synth: SaturatorSynth = SaturatorSynth(
freq: freq, drive: drive, curve: curve, factor: factor, outBus: dstBus.index)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(synth)
try engine.add(master, position: NodePosition.after(synth))
try engine.start()
return readStereoCAF(url: url, sampleRate: sampleRate)
}
/// Left channel (interleaved stereo), warm-up frames skipped.
private func leftChannel(_ samples: [Float], skip: Int) -> [Double] {
var out: [Double] = []
var i: Int = skip * 2
while i < samples.count {
out.append(Double(samples[i]))
i += 2
}
return out
}
/// Goertzel magnitude at normalised frequency `cyclesPerSample`.
private func goertzelMagnitude(_ x: [Double], cyclesPerSample: Double) -> Double {
let omega: Double = 2.0 * Double.pi * cyclesPerSample
let cosine: Double = cos(omega)
let sine: Double = sin(omega)
let coeff: Double = 2.0 * cosine
var s1: Double = 0.0
var s2: Double = 0.0
for v: Double in x {
let s0: Double = v + coeff * s1 - s2
s2 = s1
s1 = s0
}
let real: Double = s1 - s2 * cosine
let imag: Double = s2 * sine
return (real * real + imag * imag).squareRoot()
}
/// A naive base-rate hard clipper on the same sine — the alias-generating baseline the
/// oversampled path is meant to beat.
private func naiveHardClip(
freq: Double,
drive: Double,
low: Double,
high: Double,
count: Int
) -> [Double] {
let cyclesPerSample: Double = freq / sampleRate
var out: [Double] = []
out.reserveCapacity(count)
for n: Int in 0..<count {
let x: Double = sin(2.0 * Double.pi * cyclesPerSample * Double(n))
let shaped: Double = tanh(x) * drive
out.append(Swift.min(high, Swift.max(low, shaped)))
}
return out
}
@Test func reducesAliasingVersusNaiveHardClip() throws {
// 13230 Hz = 0.3·Fs. A symmetric clipper's dominant 3rd harmonic lands at 0.9·Fs,
// which folds to a 0.1·Fs (4410 Hz) alias at the base rate. Measure the alias energy
// RELATIVE to the fundamental (self-normalising, so downstream routing gain cancels).
let fundamentalHz: Double = 0.3 * sampleRate
let aliasHz: Double = 0.1 * sampleRate // |3·0.3 − 1|·Fs
let drive: Double = 5.0
let low: Double = -1.0
let high: Double = 1.0
let os: [Float] = try render(
freq: fundamentalHz, drive: drive,
curve: .tanhPostGainHardClip(low: low, high: high), factor: 4)
let osLeft: [Double] = leftChannel(os, skip: 2048)
#expect(osLeft.count > 2048)
let fundamentalBin: Double = fundamentalHz / sampleRate
let aliasBin: Double = aliasHz / sampleRate
let osFund: Double = goertzelMagnitude(osLeft, cyclesPerSample: fundamentalBin)
let osAlias: Double = goertzelMagnitude(osLeft, cyclesPerSample: aliasBin)
let osRatio: Double = osAlias / osFund
let naive: [Double] = naiveHardClip(
freq: fundamentalHz, drive: drive, low: low, high: high, count: osLeft.count)
let nFund: Double = goertzelMagnitude(naive, cyclesPerSample: fundamentalBin)
let nAlias: Double = goertzelMagnitude(naive, cyclesPerSample: aliasBin)
let naiveRatio: Double = nAlias / nFund
// The naive clipper must actually alias (sanity), and oversampling must cut the
// alias-to-fundamental ratio by at least half. In practice the 4× halfband path
// attenuates it far more; 0.5 is a conservative, non-flaky bound.
#expect(naiveRatio > 0.05, "baseline did not alias as expected (ratio=\(naiveRatio))")
#expect(
osRatio < naiveRatio * 0.5,
"oversampling did not reduce aliasing: os=\(osRatio) naive=\(naiveRatio)"
)
}
@Test func hardClipCurveRespectsBounds() throws {
// With a hard-clip curve the output must stay within [low, high] (plus a small margin
// for halfband ripple / routing) regardless of how hard it is driven.
let low: Double = -0.5
let high: Double = 0.5
let samples: [Float] = try render(
freq: 2000.0, drive: 10.0,
curve: .tanhPostGainHardClip(low: low, high: high), factor: 4)
let left: [Double] = leftChannel(samples, skip: 2048)
#expect(!left.isEmpty)
let peak: Double = left.map { abs($0) }.max() ?? 0
let margin: Double = 0.1
#expect(peak <= high + margin, "hard-clip curve exceeded its ceiling: peak=\(peak)")
}
@Test func softCurvesStayBounded() throws {
// tanh-family curves saturate toward ±1; output must stay bounded well under runaway.
let samples: [Float] = try render(
freq: 2000.0, drive: 30.0, curve: .tanhPreGain, factor: 2)
let left: [Double] = leftChannel(samples, skip: 2048)
#expect(!left.isEmpty)
let peak: Double = left.map { abs($0) }.max() ?? 0
#expect(peak <= 1.2, "tanh saturator output was not bounded near ±1: peak=\(peak)")
}
}
@@ -61,4 +61,35 @@ struct SustainerPedalTests {
}
#expect(ssd > 0, "sustain knob had no effect on output")
}
@Test func exposesSafetySwitch() throws {
let pedal: SustainerPedal = SustainerPedal()
#expect(pedal.effectSwitches.map { $0.label } == ["Safety"])
#expect(pedal.effectSwitches.first?.options.map { $0.title } == ["Off", "On"])
}
@Test func safetyLimiterCapsPeaks() throws {
// Max sustain drives a low threshold, high ratio, and +18 dB makeup — the compressor's
// non-zero attack lets transients overshoot. With Safety on, the output peak must stay
// near full scale, and the two switch states must differ.
let off: [Float] = try render {
$0.sampleRate = 44100.0; $0.sustain = 10.0; $0.safetyLimiter = 0.0
}
let on: [Float] = try render {
$0.sampleRate = 44100.0; $0.sustain = 10.0; $0.safetyLimiter = 1.0
}
#expect(hasNonSilentOutput(off) && hasNonSilentOutput(on))
let fill: Int = 2048
guard on.count > fill else { return }
let onPeak: Float = on[fill...].reduce(0) { Swift.max($0, abs($1)) }
#expect(onPeak <= 1.05, "safety limiter failed to cap peak: \(onPeak)")
let window: Int = 2048
guard off.count >= fill + window, on.count >= fill + window else { return }
let ssd: Double = zip(off[fill..<(fill + window)], on[fill..<(fill + window)]).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1); return acc + d * d
}
#expect(ssd > 0, "safety switch had no effect on output")
}
}