// AmpVoicePedal.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import LyrebirdSynth import LyrebirdUI /// Shared base for the tube-amp voice pedals — the fixed-voicing amps and the full-surface amps /// (those adding onboard reverb / tremolo / chorus and switches via the hooks below). /// /// Each concrete amp fixes one tone-stack ``ToneStackModel`` and adds one signature control, but /// shares the common chain built here: /// ``` /// dry → inputShaping(_:) (subclass hook — e.g. bright switch; default identity) /// → TriodeStage(drive: gain) (preamp) /// → ToneStack(bass, mid, treble, model) (fixed per amp) /// → onboardEffects(_:) (subclass hook — e.g. reverb + tremolo; default identity) /// → powerAmpStage(_:) (power amp — two TriodeStage halves blended by /// Bias X; single-stage tone at biasX = 0) /// → shapeVoice(_:) (subclass signature filter) /// → applySag(_:) (shared power-supply Sag droop; identity at sag = 0) /// → ConvolutionReverb(cab IR) (speaker cabinet — voice-selectable, or None for a /// separate cab block; rebuild on change) /// → TriodeStage(bias: 0) → Clip(±1) (output soft-limit + hard safety ceiling — always on) /// ``` /// Fully wet (the amp replaces the dry signal); `Level` is the master. Double-width amp-head card. /// /// The `tanh` output stage models output-transformer / speaker compression: a real amp has no /// brickwall, and its analog output can't digital-clip. Small signals pass at ~unit gain (clean /// playing largely intact); peaks soft-limit toward ±1, adding gentle output compression. Because /// that soft-limit sits *after* the cab (the overshoot it guards is a digital convolution / /// oversampling artifact, not literal circuit order) and the `tanh`'s own DC-blocker can leave a /// sub-percent overshoot, a final `Clip(±1)` hard-clamps the residue so the amp stage never emits a /// sample past ±1. At the normal master `Level` (≤ 1) that ceiling carries through to the output. /// /// Subclasses override ``toneStackModel``, ``summaryText``, ``signatureKnobs``, and /// ``shapeVoice(_:)``, and may set a voice-appropriate default `gain` in their `init`. open class AmpVoicePedal: Pedal { // MARK: - Common parameters /// Preamp drive into the first tube stage. Range [1, 30]. @UIParam public var gain: Double = 6.0 /// Tone-stack bass control in [0, 1]. @UIParam public var bass: Double = 0.5 /// Tone-stack mid control in [0, 1]. @UIParam public var mid: Double = 0.5 /// Tone-stack treble control in [0, 1]. @UIParam public var treble: Double = 0.6 /// Selected cabinet voice as an index into `CabinetVoice.allCases`. @UIParam public var cab: Double = 0.0 /// Power-amp **Sag** in `[0, 1]`: `0` = stiff (no droop), `1` = heavy power-supply sag/bloom. /// Surfaced in the advanced pop-over, not on the pedal face. See ``applySag(_:)``. @UIParam public var sag: Double = 0.0 /// Power-amp **Bias** in `[0, 1]`, mapped to the power-amp `TriodeStage` grid bias. `0.5` = the /// neutral (symmetric) operating point; lower = colder (tighter, more odd harmonics), higher = /// hotter (warmer, more even harmonics). Surfaced in the advanced pop-over. See /// ``powerAmpBiasInput``. @UIParam public var bias: Double = 0.5 /// Power-amp **Bias X** (bias balance) in `[0, 1]`, default `0` = balanced. At `0` the power amp /// is a single stage — the shipped tone, exactly. Turning it up spreads the two power-amp /// half-stages' bias operating points and averages them, re-shaping the saturation knee for a /// distinct power-amp character (named after the "bias balance" trim on amps that expose one). /// Surfaced in the advanced pop-over. See `powerAmpStage(_:)`. @UIParam public var biasX: Double = 0.0 // MARK: - Subclass configuration /// The fixed tone-stack model for this amp voice. Subclasses override. open var toneStackModel: ToneStackModel { .fender } /// One-line description. Subclasses override. open var summaryText: String { "Tube amp." } /// The amp's signature knob(s), appended after Gain/Bass/Mid/Treble. Default none. open var signatureKnobs: [PedalKnob] { [] } /// Applies the amp's signature post-power-amp shaping (e.g. a bright/presence shelf or a cut /// low-pass). Default: identity. Subclasses override. /// /// - Parameter signal: The post-power-amp signal. /// - Returns: The shaped signal fed to the cabinet. open func shapeVoice(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput { signal } /// Shaping applied to the dry input *before* the preamp — e.g. a bright-switch treble lift that /// hits the tubes pre-distortion. Default: identity. Subclasses override. /// /// - Parameter signal: The dry input signal. /// - Returns: The shaped signal fed into the preamp. open func inputShaping(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput { signal } /// Onboard effects inserted *after* the tone stack and *before* the power amp — the slot a /// combo amp's built-in reverb and tremolo occupy. Default: identity. Subclasses override. /// /// - Parameter signal: The post-tone-stack signal. /// - Returns: The signal fed into the power-amp stage. open func onboardEffects(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput { signal } /// Depth scale for the shared ``tremolo(_:speed:depth:enabled:)`` helper — at full depth the /// unipolar sine swings over half the normalised range, so the peak gain is `1.0` and the trough /// is `1 − depth`. private static let tremoloDepthScale: Double = 0.5 /// A unipolar-sine tremolo: `signal ×` an LFO over `[1 − depth·enabled, 1]`. Returns a bit-exact /// pass-through (a constant-`1.0` LFO) when `depth·enabled == 0`, so a zeroed depth or a /// footswitch `enabled = 0` is a true identity. Shared by the combo amps' `onboardEffects(_:)`. /// /// - Parameters: /// - signal: The signal to amplitude-modulate. /// - speed: LFO rate in Hz. /// - depth: Modulation depth in `[0, 1]`. /// - enabled: Footswitch gate (`0` or `1`) multiplied into the depth. /// - Returns: The amplitude-modulated signal. func tremolo( _ signal: any ValidGeneratorInput, speed: any ValidGeneratorInput, depth: any ValidGeneratorInput, enabled: any ValidGeneratorInput ) -> any ValidGeneratorInput { let swing: any ValidGeneratorInput = (depth * enabled) * AmpVoicePedal.tremoloDepthScale let lfo: OscSin.Audio = OscSin.Audio(freq: speed, mul: swing, add: 1.0 - swing) return signal * lfo } /// Maps a `Master` knob `[0, 1]` to a power-amp drive range — the canonical body of a /// master-volume amp's ``powerAmpDriveInput`` override. Turning Master up drives the power-amp /// stage harder (real master-volume saturation, unlike `level`). /// /// - Parameters: /// - master: The `Master` knob node (`[0, 1]`). /// - minDrive: Power-amp drive at `master = 0`. /// - maxDrive: Power-amp drive at `master = 1`. /// - Returns: The mapped drive to feed the power-amp stage. func masterDrive( _ master: any ValidGeneratorInput, minDrive: Double, maxDrive: Double ) -> any ValidGeneratorInput { LinLin.Audio(master, inLo: 0.0, inHi: 1.0, outLo: minDrive, outHi: maxDrive) } /// The preamp gain stage — the (post-`inputShaping`) input driven through the first tube stage /// at `Gain`. Default: one `TriodeStage`. A channel-switching amp overrides this to cascade an /// extra stage on its drive channel (call `super.preampStage(_:)` for the clean stage first). /// /// - Parameter signal: The post-`inputShaping` input signal. /// - Returns: The preamp output fed into the tone stack. open func preampStage(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput { TriodeStage(input: signal, drive: $gain, bias: preampBias, oversample: preampOversample) } /// Drive into the power-amp `TriodeStage`. Defaults to the fixed power-amp drive. Two kinds of /// amp override it: a **master-volume** amp returns a live `Master` knob mapped to a drive range /// (turning Master up pushes the power-amp stage into saturation — the real master-volume /// behaviour, unlike `level`, which only attenuates the finished output); a **lower-headroom /// variant** returns a fixed value *higher* than the default to model an amp that breaks up /// earlier. Either way, higher drive = more power-amp saturation. open var powerAmpDriveInput: any ValidGeneratorInput { powerAmpDrive } /// Oversampling factor for the power-amp stage — `2` or `4`. Any amp that drives the power amp /// harder than the default fixed value (a `Master` control, or a lower-headroom variant with a /// higher fixed drive) should override to `4` for more anti-alias headroom, since higher drive /// generates more high-order harmonics. Defaults to `2` (ample for the lightly-driven fixed /// power stage of the standard voices). open var powerAmpOversample: Int { 2 } /// Grid bias fed to the power-amp `TriodeStage`, from the live `Bias` knob: `[0, 1]` mapped to /// `[coldPowerAmpBias, hotPowerAmpBias]`. The neutral `bias = 0.5` maps to `0.0`, so the default /// leaves the power-amp stage symmetric (unchanged from the old fixed bias). var powerAmpBiasInput: any ValidGeneratorInput { LinLin.Audio($bias, inLo: 0.0, inHi: 1.0, outLo: coldPowerAmpBias, outHi: hotPowerAmpBias) } /// The power-amp stage. **Bias X** (``biasX``) spreads the two `TriodeStage` halves' bias /// operating points to `powerAmpBiasInput ± (biasX · biasXMaxSpread)` and averages them. At /// `biasX = 0` both halves share the base bias, so the average is bit-identical to a single stage /// (the shipped tone); turning `biasX` up widens the spread, re-shaping the saturation character. /// /// > Note: a deliberate approximation — a *character* control on the single-ended power-stage /// > model, not a literal push-pull topology (which would re-voice every amp). It reduces to the /// > exact prior tone at `biasX = 0`. Both halves are always built, so an amp pays two oversampled /// > stages even at `biasX = 0` — a smooth, live knob was preferred over a rebuild-on-change /// > single-stage fast path. /// /// - Parameter signal: The post-`onboardEffects` signal into the power amp. /// - Returns: The blended power-amp output. func powerAmpStage(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput { let imbalance: any ValidGeneratorInput = $biasX * biasXMaxSpread let hotHalf: TriodeStage = TriodeStage( input: signal, drive: powerAmpDriveInput, bias: powerAmpBiasInput + imbalance, oversample: powerAmpOversample ) let coldHalf: TriodeStage = TriodeStage( input: signal, drive: powerAmpDriveInput, bias: powerAmpBiasInput - imbalance, oversample: powerAmpOversample ) return (hotHalf + coldHalf) * powerAmpHalfBlend } /// Applies power-supply **Sag**: an `AmplitudeFollower` on `signal` reduces gain as it gets loud /// (droop) and recovers slowly (bloom). `Sag` scales the depth; at `sag = 0` the droop is `0` and /// the gain is a constant `1.0` (an identity multiply), so a sag-less amp is unchanged. /// /// The droop gain is clamped to `[sagGainFloor, 1]`: the envelope tracks a post-power-amp, /// post-`shapeVoice` signal that can exceed 1 (Presence/Depth shelves), so an unclamped /// `1 − sag·env` would go negative and phase-invert loud content instead of attenuating it. /// /// - Parameter signal: The post-`shapeVoice` signal to apply sag to. /// - Returns: The sagged signal. func applySag(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput { let envelope: AmplitudeFollower.Audio = AmplitudeFollower.Audio( in: signal, attackTime: sagAttackSeconds, releaseTime: sagReleaseSeconds) let sagGain: any ValidGeneratorInput = Clip.Audio( 1.0 - ($sag * envelope), lo: sagGainFloor, hi: 1.0) return signal * sagGain } // MARK: - Constants private static let defaultMix: Double = 1.0 /// Preamp grid bias — a little asymmetry for even-harmonic warmth. private let preampBias: Double = 0.2 /// Oversampling factor for the preamp stage (4× — the preamp can be driven hard by `Gain`). let preampOversample: Int = 4 /// Grid bias of a cascaded lead/drive `TriodeStage` — a little asymmetry for even-harmonic /// grind. Shared by the channel/master amps' cascaded ``preampStage(_:)`` overrides. let leadBias: Double = 0.15 /// Generic `PedalSwitch` off / on values, shared by every amp that publishes switches. let switchOffValue: Double = 0.0 let switchOnValue: Double = 1.0 /// Fixed power-amp stage drive (gentler than the preamp). private let powerAmpDrive: Double = 1.5 /// Power-amp grid bias at `bias = 0` (coldest) and `bias = 1` (hottest). Symmetric about `0`, so /// the neutral `bias = 0.5` maps to `0.0` — the old fixed power-amp bias — leaving every amp's /// default tone unchanged. Modest magnitude so the control colours the harmonics without /// drastically re-voicing the amp. private let coldPowerAmpBias: Double = -0.25 private let hotPowerAmpBias: Double = 0.25 /// Maximum push-pull bias imbalance at `biasX = 1` — the offset applied oppositely to the two /// power-amp half-stages. Modest so the control colours the harmonics without destabilising the amp. private let biasXMaxSpread: Double = 0.35 /// Equal-weight blend of the two power-amp half-stages. `0.5·(hot + cold)` averages them, so at /// `biasX = 0` (identical halves) the result is bit-identical to a single stage. private let powerAmpHalfBlend: Double = 0.5 /// Sag envelope-follower attack — moderately fast (the supply starts drooping under load). private let sagAttackSeconds: Double = 0.02 /// Sag envelope-follower release — slow, so the sag lingers and blooms back (supply recovery). private let sagReleaseSeconds: Double = 0.30 /// Lowest the sag gain can droop to (~-16 dB). Bounds sag depth and — crucially — keeps the gain /// strictly positive: the envelope tracks a post-shelf signal that can exceed 1, so an unclamped /// `1 − sag·env` would go negative and phase-invert loud content instead of drooping. private let sagGainFloor: Double = 0.15 private let cabinetMix: Double = 1.0 /// Output soft-limit drive. `1.0` gives unit small-signal gain (clean playing untouched) with a /// hard `tanh` asymptote at ±1 — models output-transformer / speaker compression and keeps the /// amp from ever digital-clipping the DAC. private let outputStageDrive: Double = 1.0 /// Symmetric output stage (no even-harmonic bias) — a pure `tanh` limiter, not a tube colour. private let outputStageBias: Double = 0.0 /// 2× is enough: the cab low-pass already band-limits the signal feeding this stage. private let outputStageOversample: Int = 2 /// Absolute digital ceiling. The `tanh` stage does the musical soft-limiting; this hard clamp /// only ever catches the sub-percent overshoot the oversampling filters and DC-blocker can leave /// just above ±1, guaranteeing the amp stage never emits a sample the DAC would clip. private let outputCeiling: Double = 1.0 let gainRange: ClosedRange = 1.0 ... 30.0 let toneRange: ClosedRange = 0.0 ... 1.0 /// Range for a signature control that maps [0, 1] (Bright / Presence / Cut amount). let signatureRange: ClosedRange = 0.0 ... 1.0 /// Cab selector value for the "None (direct)" stop — no speaker convolution. Placed one past the /// last `CabinetVoice` index so every existing voice keeps its saved index (append-only). static let cabinetBypassValue: Double = Double(CabinetVoice.allCases.count) private static let cabStops: [PedalSelectorKnob.Stop] = CabinetVoice.allCases .enumerated() .map { (index: Int, voice: CabinetVoice) in PedalSelectorKnob.Stop(title: voice.displayName, value: Double(index)) } + [PedalSelectorKnob.Stop(title: "None (direct)", value: cabinetBypassValue)] // MARK: - Chrome /// The amp is fully wet (it replaces the dry signal); hide the Mix control. public override var showsMixControl: Bool { false } /// Amp-head-style double-width card. public override var widthUnits: Int { 2 } public override var summary: String { summaryText } // MARK: - Init /// Creates an amp voice pedal. /// /// - Parameters: /// - name: Display name (the amp voice, e.g. "California"). /// - 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( name: String, inputBus: Int = 0, outputBus: Int = 0 ) { super.init( name: name, inputBus: inputBus, outputBus: outputBus, initialMix: AmpVoicePedal.defaultMix ) } // MARK: - UI public override var effectKnobs: [PedalKnob] { [ PedalKnob(label: "Gain", node: $gain, range: gainRange), PedalKnob(label: "Bass", node: $bass, range: toneRange), PedalKnob(label: "Mid", node: $mid, range: toneRange), PedalKnob(label: "Treble", node: $treble, range: toneRange), ] + signatureKnobs } public override var effectSelectors: [PedalSelectorKnob] { [ PedalSelectorKnob( label: "Cab", node: $cab, stops: AmpVoicePedal.cabStops, rebuildsOnChange: true), ] } /// Power-amp deep-cut controls, tucked behind the pedal card's advanced pop-over: **Sag** /// (power-supply droop/bloom), **Bias** (power-amp grid-bias operating point), and **Bias X** /// (power-amp bias balance). None is a topology control — all are live nodes that round-trip /// through the rig save format. Order is append-only (persisted positionally in `advancedValues`). public override var advancedKnobs: [PedalKnob] { [ PedalKnob(label: "Sag", node: $sag, range: signatureRange), PedalKnob(label: "Bias", node: $bias, range: toneRange), PedalKnob(label: "Bias X", node: $biasX, range: signatureRange), ] } // MARK: - Effect /// Preamp → fixed tone stack → power amp → signature shaping → cabinet (or None) → output /// soft-limit. /// /// > Note: at most one `ConvolutionReverb` runs — only the voice named by the live `cab` selector /// > is instantiated, and the "None (direct)" stop instantiates none. The `cab` selector is /// > `rebuildsOnChange`, so switching cabs (or to/from None) rebuilds the board rather than /// > running every voice at once. /// /// The output soft-limit (``outputLimit(_:)``) always runs, cabinet or not, so the ±1 ceiling /// holds even when the cabinet is bypassed for a separate downstream cab block. /// /// - Parameter dry: Dry mono input signal. /// - Returns: The amped, (optionally) cab-convolved, soft-limited, ceiling-clamped mono output. public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { cabinetAndLimit(preCabinetCore(dry)) } /// The mono pre-cabinet core: `inputShaping → preamp → tone stack → onboardEffects → power amp → /// shapeVoice`. Factored out of `effect(_:)` so a stereo (widener) amp can split into a stereo /// stage (e.g. a stereo chorus) between the core and a per-channel ``cabinetAndLimit(_:)``. /// /// - Parameter dry: Dry mono input signal. /// - Returns: The post-power-amp, pre-cabinet mono signal. func preCabinetCore(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { let preShaped: any ValidGeneratorInput = inputShaping(dry) let preamp: any ValidGeneratorInput = preampStage(preShaped) let toned: ToneStack = ToneStack( input: preamp, bass: $bass, mid: $mid, treble: $treble, model: toneStackModel) let processed: any ValidGeneratorInput = onboardEffects(toned) let powerAmp: any ValidGeneratorInput = powerAmpStage(processed) return applySag(shapeVoice(powerAmp)) } /// True when the `Cab` selector is on the "None (direct)" stop — the amp emits its limited /// power-amp signal with **no** speaker convolution, so the player can place a separate cabinet /// block (the standalone `Cabinet` pedal, or a future IR loader) downstream. Read at board-build /// time; the selector is `rebuildsOnChange`, so toggling it rebuilds the graph. /// /// > Warning: with no cabinet, the amp sounds raw and fizzy (the power-amp `tanh` with no speaker /// > low-pass) — expected; a cabinet is what tames the top end. var isCabinetBypassed: Bool { guard cab.isFinite else { return false } // Clamp in Double space before converting: a huge finite `cab` (from a corrupted/hand-edited // rig) would otherwise trap `Int(_:)` — same defense as `CabinetVoice.voice(atSelectorValue:)`. let bounded: Double = Swift.min(Swift.max(cab, 0.0), Double(CabinetVoice.allCases.count)) return Int(bounded.rounded()) >= CabinetVoice.allCases.count } /// The per-channel cabinet + output stage: cabinet convolver (or a straight pass at the "None" /// stop) → `tanh` soft-limit → `Clip(±1)` safety clamp. Applied once in mono, or once per channel /// by a widener amp. /// /// - Parameter signal: The post-core signal for one channel. /// - Returns: The (optionally) cab-convolved, soft-limited, ceiling-clamped signal. func cabinetAndLimit(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput { outputLimit(cabinet(signal)) } /// The selected `CabinetVoice` speaker convolver, or `signal` unchanged when the `Cab` selector /// is on "None (direct)". Only the voice named by the live `cab` selector is instantiated, so at /// most one `ConvolutionReverb` runs. /// /// - Parameter signal: The post-core signal for one channel. /// - Returns: The cab-convolved signal, or `signal` unchanged when the cabinet is bypassed. func cabinet(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput { guard !isCabinetBypassed else { return signal } let voice: CabinetVoice = CabinetVoice.voice(atSelectorValue: cab) return ConvolutionReverb.Audio( input: signal, ir: CabinetIRFactory.makeIR(voice: voice, sampleRate: sampleRate), mix: cabinetMix ) } /// The output soft-limit + hard `Clip(±1)` safety ceiling — **always** applied on the amp, /// cabinet or not, so the ±1 guarantee holds even at the "None (direct)" stop. /// /// The `TriodeStage(bias: 0)` is a symmetric `tanh` output limiter: cab convolution and signature /// shelves can push peaks past ±1, which a real analog output soft-compresses rather than /// hard-clips. Unit small-signal gain keeps clean tones intact; peaks soft-limit toward ±1. The /// trailing `Clip(±1)` hard-clamps the sub-percent overshoot the `tanh`'s DC-blocker and the /// halfband filters can leave, so no sample can clip the DAC. /// /// - Parameter signal: The (optionally cab-convolved) signal for one channel. /// - Returns: The soft-limited, ceiling-clamped signal. func outputLimit(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput { let softLimited: TriodeStage = TriodeStage( input: signal, drive: outputStageDrive, bias: outputStageBias, oversample: outputStageOversample ) return Clip.Audio(softLimited, lo: -outputCeiling, hi: outputCeiling) } }