// 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) /// → TriodeStage(power-amp drive) (power-amp warmth) /// → shapeVoice(_:) (subclass signature filter) /// → ConvolutionReverb(cab IR) (speaker cabinet — voice-selectable, rebuild on change) /// → TriodeStage(bias: 0) → Clip(±1) (output soft-limit + hard safety ceiling) /// ``` /// 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 // 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 } /// Drive into the power-amp `TriodeStage`. Defaults to the fixed power-amp drive; a /// master-volume amp overrides this to return a live `Master` knob mapped to a drive range, so /// turning Master up pushes the power-amp stage into saturation — the real master-volume /// behaviour — rather than merely attenuating the finished output the way `level` does. Non- /// master amps leave it at the fixed value and are unaffected. open var powerAmpDriveInput: any ValidGeneratorInput { powerAmpDrive } /// Oversampling factor for the power-amp stage — `2` or `4`. Amps that drive the power amp hard /// (a `Master` control) 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 non-master amps). open var powerAmpOversample: Int { 2 } // 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 /// Fixed power-amp stage drive/bias (gentler than the preamp). private let powerAmpDrive: Double = 1.5 private let powerAmpBias: Double = 0.0 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 private static let cabStops: [PedalSelectorKnob.Stop] = CabinetVoice.allCases .enumerated() .map { (index: Int, voice: CabinetVoice) in PedalSelectorKnob.Stop(title: voice.displayName, value: Double(index)) } // 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), ] } // MARK: - Effect /// Preamp → fixed tone stack → power amp → signature shaping → cabinet → output soft-limit. /// /// > Note: only the voice named by the live `cab` selector is instantiated, so exactly one /// > `ConvolutionReverb` runs. The `cab` selector is `rebuildsOnChange`, so switching cabs /// > rebuilds the board (re-entering `effect(_:)` with the new voice) rather than running every /// > voice at once. /// /// The closing `TriodeStage(bias: 0)` is a symmetric `tanh` output limiter: the cab convolution /// and signature shelves can push peaks past ±1, which a real analog output would soft-compress /// rather than hard-clip. Unit small-signal gain keeps clean tones intact; peaks soft-limit /// toward ±1. The trailing `Clip(±1)` is a hard safety clamp for the sub-percent overshoot the /// `tanh`'s DC-blocker and the halfband filters can leave — so no sample can clip the DAC. /// /// - Parameter dry: Dry mono input signal. /// - Returns: The amped, 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: TriodeStage = TriodeStage(input: preShaped, drive: $gain, bias: preampBias, oversample: 4) let toned: ToneStack = ToneStack( input: preamp, bass: $bass, mid: $mid, treble: $treble, model: toneStackModel) let processed: any ValidGeneratorInput = onboardEffects(toned) let powerAmp: TriodeStage = TriodeStage( input: processed, drive: powerAmpDriveInput, bias: powerAmpBias, oversample: powerAmpOversample) return shapeVoice(powerAmp) } /// The per-channel cabinet + output stage: the selected `CabinetVoice` convolver → `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 cab-convolved, soft-limited, ceiling-clamped signal. func cabinetAndLimit(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput { let voice: CabinetVoice = CabinetVoice.voice(atSelectorValue: cab) let cabinet: ConvolutionReverb.Audio = ConvolutionReverb.Audio( input: signal, ir: CabinetIRFactory.makeIR(voice: voice, sampleRate: sampleRate), mix: cabinetMix ) let softLimited: TriodeStage = TriodeStage( input: cabinet, drive: outputStageDrive, bias: outputStageBias, oversample: outputStageOversample ) // Hard safety clamp: the tanh keeps the signal near ±1, but its DC-blocker and the halfband // filters can leave a sub-percent transient overshoot — clamp it so no sample can clip the DAC. return Clip.Audio(softLimited, lo: -outputCeiling, hi: outputCeiling) } }