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,143 @@
// OversampledRingModulator.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import Darwin
/// 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 oversampledRingModZeroBlock: [Double] = makeSampleBuffer()
/// Ring modulator (`input × sine carrier`) evaluated at 2× or 4× the engine sample rate.
///
/// A ring modulator's product produces sum-and-difference sidebands at `f_in ± f_carrier`. The
/// sum sideband can land above the engine Nyquist and fold back as an inharmonic alias —
/// worst with a high carrier and bright input. Evaluating the multiply at an oversampled rate
/// (the input upsampled through a halfband FIR, the carrier generated directly at the
/// oversampled rate) pushes the sum term below the upsampled Nyquist, then the matching
/// downsampler filters it out before returning to the engine rate.
///
/// Output is mono (channel 0 of the input is used).
///
/// - Parameters:
/// - input: Signal to modulate.
/// - freq: Carrier frequency in Hz. Read once per block. Defaults to `220.0`.
/// - oversample: Oversampling factor — `2` or `4`. Defaults to `2`.
public final class OversampledRingModulator: GeneratorBase, AudioGenerator {
/// Resolved input signal (classified once at `init`, never on the RT thread).
private let inputSource: any ValidGeneratorInput
/// Resolved carrier-frequency control. Read once per block.
private let freqInput: any ValidGeneratorInput
/// Oversampling factor — `2` or `4`, fixed at init.
private let oversampleFactor: Int
/// Carrier phase in radians, advanced at the oversampled rate and wrapped to `[0, 2π)`.
private var phase: Double = 0.0
/// 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
private let twoPi: Double = 2.0 * Double.pi
/// Creates an oversampled ring modulator.
///
/// - Parameters:
/// - input: Signal to modulate.
/// - freq: Carrier frequency in Hz. Read once per block. Defaults to `220.0`.
/// - oversample: Oversampling factor — `2` or `4`. Defaults to `2`.
public init(
_ input: any ValidGeneratorInput,
freq: any ValidGeneratorInput = 220.0,
oversample: Int = 2
) {
precondition(
oversample == 2 || oversample == 4,
"OversampledRingModulator: oversample must be 2 or 4"
)
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput()
inputSource = resolvedInput
freqInput = resolvedFreq
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
?? oversampledRingModZeroBlock
let sr: Double = graph.engine.sampleRate
// A degenerate sample rate would make phaseInc NaN/Inf and latch NaN into the
// persisted phase; zero-fill and bail, matching MoogLadder's guard.
guard sr >= 1.0 else {
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
for i: Int in 0..<count { dstP[i] = 0 }
}
return _result
}
let freq: Double = freqInput.floatValue(graph: graph)
let inCount: Int = input.count
let useFourX: Bool = oversampleFactor == 4
// Phase increment per oversampled sample.
let factor: Double = useFourX ? 4.0 : 2.0
let phaseInc: Double = twoPi * freq / (sr * factor)
var localPhase: Double = phase
_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)
let ya: Double = a * sin(localPhase); localPhase += phaseInc
let yb: Double = b * sin(localPhase); localPhase += phaseInc
let yc: Double = c * sin(localPhase); localPhase += phaseInc
let yd: Double = d * sin(localPhase); localPhase += phaseInc
// Wrap both directions — a negative carrier frequency drives phaseInc
// negative, so an upward-only wrap would let the phase grow unbounded.
if localPhase >= twoPi || localPhase < 0 {
localPhase = localPhase.truncatingRemainder(dividingBy: twoPi)
if localPhase < 0 { localPhase += twoPi }
}
dstP[i] = downsampler4x.process(ya, yb, yc, yd)
}
} else {
for i: Int in 0..<count {
let x: Double = i < inCount ? input[i] : 0
let (a, b) = upsampler2x.process(x)
let ya: Double = a * sin(localPhase); localPhase += phaseInc
let yb: Double = b * sin(localPhase); localPhase += phaseInc
// Wrap both directions (see 4× branch).
if localPhase >= twoPi || localPhase < 0 {
localPhase = localPhase.truncatingRemainder(dividingBy: twoPi)
if localPhase < 0 { localPhase += twoPi }
}
dstP[i] = downsampler2x.process(ya, yb)
}
}
}
phase = localPhase
return _result
}
}
@@ -0,0 +1,130 @@
// 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
}
}
@@ -0,0 +1,46 @@
// SaturationCurve.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Darwin
/// The waveshaping curve applied per (oversampled) sample by ``OversampledSaturator``.
///
/// Each case reproduces the nonlinearity a specific drive pedal used to build inline from
/// stock generators, so moving that pedal onto the oversampled path is voicing-preserving:
///
/// - `tanhPreGain` — `tanh(drive · x)`. Symmetric soft saturation with the drive applied
/// *before* the `tanh` (the fuzz voicing: hard pre-gain squares the wave off).
/// - `softClipNormalized` — `tanh(drive · x) / tanh(drive)`. The same curve normalised so a
/// unity-drive signal passes near-linearly (the overdrive voicing).
/// - `tanhPostGainHardClip(low:high:)` — `clip(tanh(x) · drive, low, high)`. A gentle `tanh`
/// stage, post-gained by drive into a hard clipper (the distortion voicing). The hard clip
/// is the dominant harmonic source and the reason this curve wants the highest oversampling
/// factor.
public enum SaturationCurve: Sendable {
case tanhPreGain
case softClipNormalized
case tanhPostGainHardClip(low: Double, high: Double)
/// Applies the curve to a single sample.
///
/// - Parameters:
/// - x: Input sample (already at the oversampled rate).
/// - drive: Drive amount. The caller clamps this to a small positive floor so
/// `softClipNormalized`'s `tanh(drive)` denominator is never zero.
/// - Returns: The shaped sample.
@inline(__always)
func apply(_ x: Double, drive: Double) -> Double {
switch self {
case .tanhPreGain:
return tanh(drive * x)
case .softClipNormalized:
return tanh(drive * x) / tanh(drive)
case .tanhPostGainHardClip(let low, let high):
let shaped: Double = tanh(x) * drive
return Swift.min(high, Swift.max(low, shaped))
}
}
}
@@ -9,9 +9,10 @@ import LyrebirdUI
/// Mid-gain distortion — more saturated than `OverdrivePedal`, more controlled than `FuzzPedal`.
///
/// A DC-blocking high-pass feeds a `tanh` soft-clipper driven hard by the `Drive` knob; a
/// post-clip low-pass `Tone` control tames the harmonics, and a final hard clip guarantees the
/// output stays bounded.
/// A DC-blocking high-pass feeds a `tanh` stage that is post-gained by the `Drive` knob into a
/// hard clipper — both evaluated at 4× oversampling so the clipper's harmonics don't alias. A
/// post-clip low-pass `Tone` control tames the harmonics, and a final hard clip re-bounds the
/// output (the tone low-pass can ring slightly past the ceiling on transients).
///
/// ## Knobs
/// - `drive`: Pre-clip gain into the `tanh` stage. Range `[1, 50]`.
@@ -87,12 +88,24 @@ public final class DistortionPedal: Pedal {
freq: dcBlockFreq,
q: filterQ
)
let driven: Tanh.Audio = Tanh.Audio(dcBlocked, mul: $drive)
// tanh soft stage → post-gain by drive → hard clip, all evaluated at 4× so the hard
// clipper's harmonics settle above the upsampled Nyquist instead of aliasing back.
// The tone low-pass now follows the clip (standard clip→tone order), which also
// filters any residual high-band content the downsampler leaves.
let clipped: OversampledSaturator = OversampledSaturator(
dcBlocked,
drive: $drive,
curve: .tanhPostGainHardClip(low: clipLow, high: clipHigh),
oversample: 4
)
let toned: RBJLowPass.Audio = RBJLowPass.Audio(
input: driven,
input: clipped,
freq: $tone,
q: filterQ
)
// Final hard clip re-establishes the strict output bound: the tone low-pass is linear
// and band-limited, so it can overshoot the ceiling slightly on transients, but
// clipping its (already band-limited) output adds negligible new aliasing.
return Clip.Audio(toned, lo: clipLow, hi: clipHigh)
}
}
@@ -105,11 +105,17 @@ public final class FuzzPedal: Pedal {
/// - Returns: Fuzzed and tone-shaped mono output.
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
// Pre-gain the signal hard, then saturate. `tanh` squares the waveform off as the
// drive rises while keeping the level bounded — the hallmark of a fuzz.
let driven: any ValidGeneratorInput = dry * $fuzz
let saturated: Tanh.Audio = Tanh.Audio(driven, mul: outputTrim)
// drive rises while keeping the level bounded — the hallmark of a fuzz. Evaluated at
// 2× so the high harmonics the hard pre-gain generates don't fold back as aliasing.
let saturated: OversampledSaturator = OversampledSaturator(
dry,
drive: $fuzz,
curve: .tanhPreGain,
oversample: 2
)
let trimmed: any ValidGeneratorInput = saturated * outputTrim
return RBJLowPass.Audio(
input: saturated,
input: trimmed,
freq: $tone,
q: toneQ
)
@@ -11,7 +11,7 @@ import LyrebirdUI
///
/// Signal chain (inside `effect(_:)`):
/// ```
/// dry → SoftClip(drive:) → RBJLowPass(freq: tone, q: 0.707) → mono out
/// dry → OversampledSaturator(curve: .softClipNormalized, drive:) → RBJLowPass(freq: tone, q: 0.707) → mono out
/// ```
///
/// The wet/dry mix and bypass switching are handled by the `Pedal` base class.
@@ -83,7 +83,14 @@ public final class OverdrivePedal: Pedal {
/// - Parameter dry: Dry mono input signal.
/// - Returns: Saturated and tone-shaped mono output.
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let saturated: SoftClip.Audio = SoftClip.Audio(dry, drive: $drive)
// Same normalised soft-clip curve as before (`tanh(drive·x) / tanh(drive)`), but
// evaluated at 2× so high-drive harmonics don't alias.
let saturated: OversampledSaturator = OversampledSaturator(
dry,
drive: $drive,
curve: .softClipNormalized,
oversample: 2
)
return RBJLowPass.Audio(
input: saturated,
freq: $tone,
@@ -15,7 +15,7 @@ import LyrebirdUI
///
/// Signal path (inside `effect(_:)`):
/// ```
/// dry × OscSin(frequency) → wet
/// dry → OversampledRingModulator(freq: frequency, oversample: 2) → wet
/// ```
///
/// The wet/dry blend and bypass are handled by the `Pedal` base class.
@@ -78,7 +78,8 @@ public final class RingModulatorPedal: Pedal {
/// - Parameter dry: Dry mono input signal.
/// - Returns: The ring-modulated wet signal.
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let carrier: OscSin.Audio = OscSin.Audio(freq: $frequency)
return dry * carrier
// Oversampled multiply: the sum sideband (f_in + f_carrier) can exceed Nyquist and
// fold back as an inharmonic alias, so do the product at 2× and filter on the way down.
return OversampledRingModulator(dry, freq: $frequency, oversample: 2)
}
}
@@ -29,6 +29,12 @@ import LyrebirdUI
/// - sustain: Amount of sustain/compression. `0` = gentle, `10` = maximum squash and hold.
/// Range `[0, 10]`. Defaults to `5.0`.
/// - tone: Output low-pass cutoff in Hz. Range `[800, 8000]`. Defaults to `6000.0`.
///
/// At high sustain the compressor applies a low threshold, a high ratio, and up to +18 dB of
/// makeup — a feed-forward compressor's non-zero attack lets transients overshoot before the
/// gain clamps, so a hot pick can push the output past full scale and clip. The **Safety**
/// switch inserts a brick-wall `LookAheadLimiter` after the compressor to catch those peaks;
/// it is off by default and adds a short look-ahead output delay when engaged.
public final class SustainerPedal: Pedal {
// MARK: - Parameters
@@ -39,6 +45,10 @@ public final class SustainerPedal: Pedal {
/// Output low-pass cutoff in Hz. Range [800, 8000].
@UIParam public var tone: Double = 6000.0
/// Safety limiter engage state. `0` = off (compressor may overshoot), `1` = on
/// (brick-wall look-ahead limiter catches transient peaks).
@UIParam public var safetyLimiter: Double = 0.0
// MARK: - Constants
private static let defaultMix: Double = 1.0
@@ -69,6 +79,19 @@ public final class SustainerPedal: Pedal {
private let makeupAtMin: Double = 0.0
private let makeupAtMax: Double = 18.0
/// Safety-limiter peak ceiling (linear amplitude), just below full scale.
private let safetyCeiling: Double = 0.98
/// Safety-limiter look-ahead / output delay in seconds. Only in circuit when Safety is on.
private let safetyLookAheadTime: Double = 0.005
/// Safety-limiter gain-release time in seconds.
private let safetyReleaseTime: Double = 0.05
/// Safety switch position values.
private let safetyOffValue: Double = 0.0
private let safetyOnValue: Double = 1.0
// MARK: - UI knobs
private let sustainRange: ClosedRange<Double> = 0.0 ... 10.0
@@ -81,6 +104,19 @@ public final class SustainerPedal: Pedal {
]
}
public override var effectSwitches: [PedalSwitch] {
[
PedalSwitch(
label: "Safety",
node: $safetyLimiter,
options: [
PedalSwitch.Option(title: "Off", value: safetyOffValue),
PedalSwitch.Option(title: "On", value: safetyOnValue),
]
)
]
}
// MARK: - Init
/// Creates a sustainer pedal.
@@ -124,8 +160,22 @@ public final class SustainerPedal: Pedal {
kneeWidth: kneeWidth,
makeupGain: makeup
)
// Optional brick-wall safety limiter. Both branches are always built; `Select` picks
// per the Safety switch (0 = compressor only, 1 = limited). Engaging it adds the
// limiter's short look-ahead delay.
let limited: LookAheadLimiter = LookAheadLimiter(
in: compressed,
maxAmplitude: safetyCeiling,
lookAheadTime: safetyLookAheadTime,
releaseTime: safetyReleaseTime,
sampleRate: sampleRate
)
let guarded: Select.Audio = Select.Audio(
which: $safetyLimiter,
inputs: [compressed, limited]
)
return RBJLowPass.Audio(
input: compressed,
input: guarded,
freq: $tone,
q: toneQ
)