Files
ShoeGaze/Tests/LyrebirdShoeGazeTests/OversampledSaturatorTests.swift
T
josh 8983e8829e 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>
2026-07-31 20:41:06 -07:00

175 lines
6.9 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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)")
}
}