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
@@ -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)")
}
}