// 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.. 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)") } }