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:
@@ -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
|
||||
)
|
||||
|
||||
@@ -84,6 +84,16 @@ struct DistortionPedalTests {
|
||||
#expect(labels == ["Drive", "Tone"])
|
||||
}
|
||||
|
||||
@Test func outputStaysBoundedAtHighDrive() throws {
|
||||
// The final hard clip (after the tone low-pass) must re-establish the ±1 output bound
|
||||
// even at extreme drive, despite the oversampled clip sitting before the low-pass.
|
||||
let samples: [Float] = try render { pedal in pedal.drive = 50.0; pedal.tone = 6000.0 }
|
||||
let skip: Int = 2048
|
||||
guard samples.count > skip else { return }
|
||||
let peak: Float = samples[skip...].reduce(0) { Swift.max($0, abs($1)) }
|
||||
#expect(peak <= 1.05, "distortion output exceeded the clip ceiling: peak=\(peak)")
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Distortion")
|
||||
#expect(pedal is DistortionPedal)
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
// OversampledRingModulatorTests.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("OversampledRingModulator")
|
||||
struct OversampledRingModulatorTests {
|
||||
|
||||
private let sampleRate: Double = 44100.0
|
||||
|
||||
/// Minimal synth: a sine through an `OversampledRingModulator`, written to a mono bus.
|
||||
private final class RingSynth: SynthesizerBase {
|
||||
private let inFreq: Double
|
||||
private let carrierFreq: Double
|
||||
private let factor: Int
|
||||
private let outBus: Int
|
||||
|
||||
init(inFreq: Double, carrierFreq: Double, factor: Int, outBus: Int) {
|
||||
self.inFreq = inFreq
|
||||
self.carrierFreq = carrierFreq
|
||||
self.factor = factor
|
||||
self.outBus = outBus
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
let osc: OscSin.Audio = OscSin.Audio(freq: inFreq)
|
||||
output(bus: outBus, source: OversampledRingModulator(
|
||||
osc, freq: carrierFreq, oversample: factor))
|
||||
}
|
||||
}
|
||||
|
||||
private func render(inFreq: Double, carrierFreq: Double, 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: RingSynth = RingSynth(
|
||||
inFreq: inFreq, carrierFreq: carrierFreq, 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)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
private func naiveRingMod(inFreq: Double, carrierFreq: Double, count: Int) -> [Double] {
|
||||
let inCps: Double = inFreq / sampleRate
|
||||
let cCps: Double = carrierFreq / sampleRate
|
||||
var out: [Double] = []
|
||||
out.reserveCapacity(count)
|
||||
for n: Int in 0..<count {
|
||||
let x: Double = sin(2.0 * Double.pi * inCps * Double(n))
|
||||
let c: Double = sin(2.0 * Double.pi * cCps * Double(n))
|
||||
out.append(x * c)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@Test func reducesSumSidebandAliasVersusNaive() throws {
|
||||
// in = 0.20·Fs, carrier = 0.35·Fs. Difference sideband = 0.15·Fs (legit, below Nyquist);
|
||||
// sum sideband = 0.55·Fs, which folds to a 0.45·Fs alias at the base rate. Measure the
|
||||
// alias relative to the legit difference sideband (self-normalising).
|
||||
let inHz: Double = 0.20 * sampleRate
|
||||
let carrierHz: Double = 0.35 * sampleRate
|
||||
let diffBin: Double = 0.15 // |0.35 − 0.20|
|
||||
let aliasBin: Double = 0.45 // |1 − 0.55|
|
||||
|
||||
let os: [Float] = try render(inFreq: inHz, carrierFreq: carrierHz, factor: 2)
|
||||
let osLeft: [Double] = leftChannel(os, skip: 2048)
|
||||
#expect(osLeft.count > 2048)
|
||||
|
||||
let osDiff: Double = goertzelMagnitude(osLeft, cyclesPerSample: diffBin)
|
||||
let osAlias: Double = goertzelMagnitude(osLeft, cyclesPerSample: aliasBin)
|
||||
let osRatio: Double = osAlias / osDiff
|
||||
|
||||
let naive: [Double] = naiveRingMod(inFreq: inHz, carrierFreq: carrierHz, count: osLeft.count)
|
||||
let nDiff: Double = goertzelMagnitude(naive, cyclesPerSample: diffBin)
|
||||
let nAlias: Double = goertzelMagnitude(naive, cyclesPerSample: aliasBin)
|
||||
let naiveRatio: Double = nAlias / nDiff
|
||||
|
||||
#expect(naiveRatio > 0.05, "baseline did not alias as expected (ratio=\(naiveRatio))")
|
||||
#expect(
|
||||
osRatio < naiveRatio * 0.5,
|
||||
"oversampling did not reduce ring-mod aliasing: os=\(osRatio) naive=\(naiveRatio)"
|
||||
)
|
||||
}
|
||||
|
||||
@Test func producesNonSilentOutput() throws {
|
||||
let os: [Float] = try render(inFreq: 440.0, carrierFreq: 220.0, factor: 2)
|
||||
#expect(hasNonSilentOutput(os), "ring modulator produced silence")
|
||||
}
|
||||
|
||||
@Test func negativeCarrierStaysFiniteAndBounded() throws {
|
||||
// A negative carrier frequency drives the phase increment negative; the phase must wrap
|
||||
// both directions rather than growing unbounded and pushing sin() out of accurate range.
|
||||
let os: [Float] = try render(inFreq: 440.0, carrierFreq: -220.0, factor: 2)
|
||||
let left: [Double] = leftChannel(os, skip: 1024)
|
||||
#expect(!left.isEmpty)
|
||||
#expect(left.allSatisfy { $0.isFinite }, "negative carrier produced non-finite output")
|
||||
let peak: Double = left.map { abs($0) }.max() ?? 0
|
||||
#expect(peak <= 1.2, "negative carrier output was not bounded: peak=\(peak)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
// 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)")
|
||||
}
|
||||
}
|
||||
@@ -61,4 +61,35 @@ struct SustainerPedalTests {
|
||||
}
|
||||
#expect(ssd > 0, "sustain knob had no effect on output")
|
||||
}
|
||||
|
||||
@Test func exposesSafetySwitch() throws {
|
||||
let pedal: SustainerPedal = SustainerPedal()
|
||||
#expect(pedal.effectSwitches.map { $0.label } == ["Safety"])
|
||||
#expect(pedal.effectSwitches.first?.options.map { $0.title } == ["Off", "On"])
|
||||
}
|
||||
|
||||
@Test func safetyLimiterCapsPeaks() throws {
|
||||
// Max sustain drives a low threshold, high ratio, and +18 dB makeup — the compressor's
|
||||
// non-zero attack lets transients overshoot. With Safety on, the output peak must stay
|
||||
// near full scale, and the two switch states must differ.
|
||||
let off: [Float] = try render {
|
||||
$0.sampleRate = 44100.0; $0.sustain = 10.0; $0.safetyLimiter = 0.0
|
||||
}
|
||||
let on: [Float] = try render {
|
||||
$0.sampleRate = 44100.0; $0.sustain = 10.0; $0.safetyLimiter = 1.0
|
||||
}
|
||||
#expect(hasNonSilentOutput(off) && hasNonSilentOutput(on))
|
||||
|
||||
let fill: Int = 2048
|
||||
guard on.count > fill else { return }
|
||||
let onPeak: Float = on[fill...].reduce(0) { Swift.max($0, abs($1)) }
|
||||
#expect(onPeak <= 1.05, "safety limiter failed to cap peak: \(onPeak)")
|
||||
|
||||
let window: Int = 2048
|
||||
guard off.count >= fill + window, on.count >= fill + window else { return }
|
||||
let ssd: Double = zip(off[fill..<(fill + window)], on[fill..<(fill + window)]).reduce(0.0) { acc, pair in
|
||||
let d: Double = Double(pair.0 - pair.1); return acc + d * d
|
||||
}
|
||||
#expect(ssd > 0, "safety switch had no effect on output")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user