Files
ShoeGaze/Sources/LyrebirdShoeGaze/Generators/OversampledSaturator.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

131 lines
5.5 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.
// 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<Double>) in
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
if useFourX {
for i: Int in 0..<count {
let x: Double = i < inCount ? input[i] : 0
let (a, b, c, d) = upsampler4x.process(x)
dstP[i] = downsampler4x.process(
curve.apply(a, drive: drive),
curve.apply(b, drive: drive),
curve.apply(c, drive: drive),
curve.apply(d, drive: drive)
)
}
} else {
for i: Int in 0..<count {
let x: Double = i < inCount ? input[i] : 0
let (a, b) = upsampler2x.process(x)
dstP[i] = downsampler2x.process(
curve.apply(a, drive: drive),
curve.apply(b, drive: drive)
)
}
}
}
return _result
}
}