// OversampledSaturator.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import LyrebirdSynth /// Shared zero-fill fallback block, allocated once at module load. Returned when an upstream /// input yields no channel for a `_computeSamples` call, so the RT path never allocates. private let oversampledSaturatorZeroBlock: [Double] = makeSampleBuffer() /// A waveshaping saturator that evaluates its nonlinearity at 2× or 4× the engine sample /// rate to keep the harmonics it generates from folding back into the audible band as /// aliasing. /// /// A hard or steep nonlinearity (`tanh` driven hard, a hard clipper) produces harmonics well /// above the engine Nyquist. Evaluated at the base rate those harmonics alias — an /// inharmonic, buzzy "crackle" that gets worse the louder and brighter the input and the /// harder the drive. This generator upsamples the input, applies the ``SaturationCurve`` /// per oversampled sample, then downsamples with the matching halfband FIR, so the aliased /// content is filtered out before returning to the engine rate. /// /// Linear stages (DC-block high-pass, tone low-pass, output trim) do **not** alias and should /// stay as ordinary graph nodes around this one — only the nonlinearity needs oversampling. /// /// Output is mono (channel 0 of the input is used). /// /// - Parameters: /// - input: Signal to saturate. /// - drive: Drive amount fed to the curve. Clamped to a small positive floor. Defaults to `1.0`. /// - curve: The ``SaturationCurve`` to apply per oversampled sample. /// - oversample: Oversampling factor — `2` or `4`. Use `4` for hard-clipping curves whose /// harmonics extend furthest; `2` is enough for `tanh`-family soft saturation. Defaults to `2`. public final class OversampledSaturator: GeneratorBase, AudioGenerator { /// Resolved input signal (classified once at `init`, never on the RT thread). private let inputSource: any ValidGeneratorInput /// Resolved drive control. Read once per block. private let driveInput: any ValidGeneratorInput /// The waveshaping curve applied per oversampled sample. private let curve: SaturationCurve /// Oversampling factor — `2` or `4`, fixed at init. private let oversampleFactor: Int /// Lower bound on drive so `softClipNormalized`'s `tanh(drive)` denominator is never zero. private let minDrive: Double = 1.0e-4 /// 2× halfband oversampling state (used when `oversampleFactor == 2`). private var upsampler2x: HalfbandUpsampler2x private var downsampler2x: HalfbandDownsampler2x /// 4× halfband oversampling state (used when `oversampleFactor == 4`). private var upsampler4x: HalfbandUpsampler4x private var downsampler4x: HalfbandDownsampler4x /// Creates an oversampled saturator. /// /// - Parameters: /// - input: Signal to saturate. /// - drive: Drive amount fed to the curve. Clamped to a small positive floor. Defaults to `1.0`. /// - curve: The ``SaturationCurve`` to apply per oversampled sample. /// - oversample: Oversampling factor — `2` or `4`. Defaults to `2`. public init( _ input: any ValidGeneratorInput, drive: any ValidGeneratorInput = 1.0, curve: SaturationCurve, oversample: Int = 2 ) { precondition( oversample == 2 || oversample == 4, "OversampledSaturator: oversample must be 2 or 4" ) let resolvedInput: any ValidGeneratorInput = input._resolvedInput() let resolvedDrive: any ValidGeneratorInput = drive._resolvedInput() inputSource = resolvedInput driveInput = resolvedDrive self.curve = curve oversampleFactor = oversample upsampler2x = HalfbandUpsampler2x() downsampler2x = HalfbandDownsampler2x() upsampler4x = HalfbandUpsampler4x() downsampler4x = HalfbandDownsampler4x() super.init() } public func _computeSamples( graph: SynthGraph, count: Int ) -> [[Double]] { _checkCount(count) guard count > 0 else { return _result } let input: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first ?? oversampledSaturatorZeroBlock let driveRaw: Double = driveInput.floatValue(graph: graph) let drive: Double = Swift.max(minDrive, driveRaw) let inCount: Int = input.count let useFourX: Bool = oversampleFactor == 4 _result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer) in guard let dstP: UnsafeMutablePointer = dst.baseAddress else { return } if useFourX { for i: Int in 0..