Files
ShoeGaze/Sources/LyrebirdShoeGaze/Pedals/SustainerPedal.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

195 lines
6.9 KiB
Swift

// SustainerPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Sustainer pedal: a one-knob compressor tuned for long, even sustain.
///
/// A single `sustain` control drives a feed-forward compressor harder as it climbs — lowering
/// the threshold, raising the ratio, and adding makeup gain together — so notes bloom and hold
/// without the user juggling threshold/ratio (that's what the `Compressor` pedal is for). A
/// `tone` low-pass rounds off the squashed top end.
///
/// Signal path (inside `effect(_:)`):
/// ```
/// dry → Compressor(threshold↓, ratio↑, makeup↑ with sustain) → RBJLowPass(tone) → wet
/// ```
///
/// The wet/dry blend and bypass are handled by the `Pedal` base class.
///
/// ## Parameters
///
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - 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
/// Sustain amount in [0, 10]. Higher = more compression, makeup, and hold.
@UIParam public var sustain: Double = 5.0
/// 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
/// Compressor envelope times, in seconds — fast attack to catch picks, slow release to hold.
private let attackTime: Double = 0.005
private let releaseTime: Double = 0.4
/// Hard knee for a defined, punchy sustain.
private let kneeWidth: Double = 0.0
/// Butterworth tone low-pass (no resonant peak).
private let toneQ: Double = 0.707
/// `sustain` knob span, mapped to the compressor settings below.
private let sustainMin: Double = 0.0
private let sustainMax: Double = 10.0
/// Threshold in dB at min / max sustain (lower threshold = more of the signal compressed).
private let thresholdAtMin: Double = -6.0
private let thresholdAtMax: Double = -36.0
/// Compression ratio at min / max sustain.
private let ratioAtMin: Double = 2.0
private let ratioAtMax: Double = 10.0
/// Makeup gain in dB at min / max sustain (compensates for the added gain reduction).
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
private let toneRange: ClosedRange<Double> = 800.0 ... 8000.0
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Sustain", node: $sustain, range: sustainRange),
PedalKnob(label: "Tone", node: $tone, range: toneRange),
]
}
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.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(
inputBus: Int = 0,
outputBus: Int = 0
) {
super.init(
name: "Sustainer",
inputBus: inputBus,
outputBus: outputBus,
initialMix: SustainerPedal.defaultMix
)
}
public override var summary: String {
"Compressor tuned for long, even sustain — one knob to make notes bloom and hold."
}
// MARK: - Effect
/// Drives a compressor from the single `sustain` knob, then rolls off the top with `tone`.
///
/// - Parameter dry: Dry mono input signal.
/// - Returns: The sustained, tone-shaped wet signal.
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let threshold: LinLin.Audio = mapSustain(to: thresholdAtMin, thresholdAtMax)
let ratio: LinLin.Audio = mapSustain(to: ratioAtMin, ratioAtMax)
let makeup: LinLin.Audio = mapSustain(to: makeupAtMin, makeupAtMax)
let compressed: Compressor.Audio = Compressor.Audio(
in: dry,
threshold: threshold,
ratio: ratio,
attack: attackTime,
release: releaseTime,
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: guarded,
freq: $tone,
q: toneQ
)
}
/// Maps the `sustain` knob `[sustainMin, sustainMax]` to `[outLo, outHi]`.
private func mapSustain(to outLo: Double, _ outHi: Double) -> LinLin.Audio {
LinLin.Audio(
$sustain,
inLo: sustainMin,
inHi: sustainMax,
outLo: outLo,
outHi: outHi
)
}
}