// Pedal.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import LyrebirdSynth import LyrebirdUI /// Abstract base class for a single-signal-chain guitar pedal effect. /// /// Each pedal reads from `inputBus`, applies `effect(_:)` (implemented by subclasses), /// then crossfades wet/dry and bypass before writing to `outputBus`. /// /// ## Signal chain /// /// ``` /// inputBus → dry → effect(_:) → wet /// ↕ mix (equal-power crossfade) /// blended /// ↕ bypass (lagged equal-power crossfade with dry) /// switched → × level → outputBus /// ``` /// /// ## Subclassing /// /// Override `effect(_:)` to return a mono processed signal. The base `build()` handles /// wet/dry mixing, smooth bypass switching, and output gain automatically. /// /// ## Parameters /// /// - `mix`: Wet/dry blend in `[0, 1]`. `0` = fully dry, `1` = fully wet. /// - `bypass`: Bypass state. `0` = engaged (effect active), `1` = bypassed (pure dry). /// Transitions are smoothed with a 20 ms lag to avoid clicks. /// - `level`: Output gain as a linear multiplier. `1.0` = unity gain. /// /// - Parameters: /// - mix: Wet/dry ratio in [0, 1]. `0` = dry only, `1` = wet only. Defaults to `1.0`. /// - bypass: Bypass flag. `0` = engaged, `1` = bypassed. Defaults to `0.0`. /// - level: Output gain multiplier in [0, ∞). Defaults to `1.0`. open class Pedal: SynthesizerBase { // MARK: - Parameters /// Wet/dry blend ratio in [0, 1]. `0` = dry only, `1` = wet only. @UIParam public var mix: Double = 1.0 /// Bypass state. `0` = engaged (effect active), `1` = bypassed (dry signal only). /// Transitions are smoothed by `bypassLagTime` seconds to prevent clicks. @UIParam public var bypass: Double = 0.0 /// Output gain as a linear multiplier. `1.0` = unity gain. @UIParam public var level: Double = 1.0 // MARK: - Sample rate /// Engine sample rate, injected by `PedalBoard.add(_:)` before the pedal is added /// to the engine; effect stages that need the sample rate read this. Defaults to a /// safe 48 kHz fallback. public var sampleRate: Double = 48000.0 // MARK: - Identity / routing /// Human-readable name for the pedal (e.g. "Overdrive", "Delay"). public let displayName: String /// Index of the audio bus from which this pedal reads its dry input (channel 0 / /// left / mono). public internal(set) var inputBus: Int /// Index of the audio bus to which this pedal writes its output (channel 0 / /// left / mono). public internal(set) var outputBus: Int /// Right-channel input bus index, or `nil` for a mono input. When the board places /// this pedal in a stereo (width-2) region it sets this to the right tail bus. A /// `stereoNative` pedal entering a mono region leaves this `nil` and broadcasts the /// mono input to both channels. public internal(set) var inputBusRight: Int? /// Right-channel output bus index, or `nil` for a mono output. Non-nil exactly when /// the pedal is part of a stereo region; `build()` emits a second channel only when /// this is set. public internal(set) var outputBusRight: Int? /// Declares this pedal's channel topology. Defaults to ``PedalChannelKind/mono``. /// Override in a widener or stereo-native subclass. open var channelKind: PedalChannelKind { .mono } /// `true` when the board has placed this pedal in a stereo (width-2) region. public var isStereo: Bool { outputBusRight != nil } // MARK: - Constants /// Lag time constant in seconds (60 dB convergence) for the bypass crossfade. /// Smooths engaged ↔ bypassed transitions to prevent audible clicks. private let bypassLagTime: Double = 0.02 // Bipolar-span constant used to remap a [0, 1] value to [-1, +1] // for CrossFade's equal-power pan parameter. private let bipolarSpan: Double = 2.0 private let bipolarOffset: Double = 1.0 // MARK: - Init /// Creates a pedal with a display name and initial bus assignments. /// /// Bus assignments are updated by `PedalBoard.add(_:)` before `engine.add`; the /// defaults here are only placeholders. Always configure via the board. /// /// - Parameters: /// - name: Human-readable pedal name shown in UI and debug output. /// - 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`. /// - initialMix: Initial wet/dry blend in `[0, 1]`. Time-based pedals (delay, /// reverb, modulation) pass a partial blend so the dry signal stays present; /// gain-shaping pedals (overdrive) leave the default fully-wet `1.0`. public init( name: String, inputBus: Int = 0, outputBus: Int = 0, initialMix: Double = 1.0 ) { self.displayName = name self.inputBus = inputBus self.outputBus = outputBus super.init() self.mix = initialMix } // MARK: - Description /// One-line, user-facing description of what this pedal does. /// /// Shown as a subtitle in the pedal picker and as the body of the pedal's info panel. /// **Every pedal must override this** with a short, non-proprietary sentence — the empty /// default is a placeholder only (a test asserts every registered pedal sets it). open var summary: String { "" } // MARK: - UI knob descriptors /// Effect-specific knobs for this pedal, listed before the common knobs in the UI. /// /// Override in subclasses to publish each `@UIParam` effect parameter with its /// display label and value range. Defaults to an empty list. open var effectKnobs: [PedalKnob] { [] } /// Effect-specific discrete switches for this pedal, rendered as a row of segmented /// controls beneath the knob grid. /// /// Override in subclasses to publish each discrete `@UIParam` parameter as a two- or /// three-state ``PedalSwitch`` (sweep direction, filter mode, …). Defaults to empty. open var effectSwitches: [PedalSwitch] { [] } /// Effect-specific continuous sliders for this pedal, rendered as a row of vertical /// faders beneath the knob grid and switches. /// /// Override in subclasses to publish each `@UIParam` parameter that reads best as a /// vertical fader rather than a rotary knob — graphic-EQ band gains, a master output /// fader, and similar bank-style controls. Defaults to empty. open var effectSliders: [PedalSlider] { [] } /// Effect-specific stepped "knob picker" controls for this pedal, rendered as a row of rotary /// knobs that snap to labelled stops, beneath the knob grid. /// /// Override in subclasses to publish each discrete `@UIParam` parameter that reads best as a /// knob that snaps through fixed positions (e.g. a harmony interval selector). Defaults to empty. open var effectSelectors: [PedalSelectorKnob] { [] } /// All knobs a generic UI should render for this pedal: effect-specific knobs /// first, then the common `mix` and `level` knobs. The `bypass` parameter is /// surfaced separately as a header toggle, not as a knob. public var knobs: [PedalKnob] { effectKnobs + [ PedalKnob(label: "Mix", node: $mix, range: 0.0 ... 1.0), PedalKnob(label: "Level", node: $level, range: 0.0 ... 1.0), ] } // MARK: - Subclass hook /// Returns the processed (wet) mono signal for this pedal. /// /// The default implementation is a pass-through — override in subclasses to apply /// the desired effect. The return value must be mono. /// /// - Parameter dry: The dry signal read from `inputBus`. /// - Returns: The wet processed signal (mono). open func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { dry } /// Returns the two distinct wet outputs for a ``PedalChannelKind/widener`` pedal. /// /// Called once with the mono dry input; the returned pair becomes the left and right /// wet signals of the now-stereo region. The default applies `effect(_:)` to both, /// which is rarely useful — widener subclasses override this to produce genuinely /// different channels (e.g. dry left, octave-up right). /// /// - Parameter dry: The dry mono signal read from `inputBus`. /// - Returns: The left and right wet signals. open func wideEffect(_ dry: any ValidGeneratorInput) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) { (effect(dry), effect(dry)) } /// Returns the coupled stereo wet outputs for a ``PedalChannelKind/stereoNative`` pedal. /// /// Called with both dry channels; the returned pair becomes the wet left and right /// signals. The default applies `effect(_:)` per channel independently — stereo-native /// subclasses override this to introduce cross-channel coupling (e.g. ping-pong feedback). /// /// - Parameters: /// - left: The left dry channel. /// - right: The right dry channel (equals `left` when the pedal entered a mono region). /// - Returns: The left and right wet signals. open func stereoEffect( left: any ValidGeneratorInput, right: any ValidGeneratorInput ) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) { (effect(left), effect(right)) } // MARK: - Build /// Builds the signal graph for one channel: dry → wet/dry blend → bypass switch → × level. /// /// Returns the final post-`level` source for the channel. The `mix`, `bypass`, and `level` /// `@UIParam` nodes are shared across channels; each channel gets its own `Lag.Control` /// for the bypass crossfade so smoothing is per-channel state driven by the same target. /// /// - Parameters: /// - dry: The dry signal for this channel. /// - wet: The processed signal for this channel. /// - Returns: The channel's output source (post mix/bypass/level). private func applyChain( dry: any ValidGeneratorInput, wet: any ValidGeneratorInput ) -> any ValidGeneratorInput { // Map mix [0, 1] → pan [-1, +1] for CrossFade (−1 = full inA/dry, +1 = full inB/wet). let mixPan: any ValidGeneratorInput = ($mix * bipolarSpan) - bipolarOffset // Equal-power crossfade between dry and wet signal. let blended: CrossFade.Audio = CrossFade.Audio( inA: dry, inB: wet, pan: mixPan ) // Smooth bypass transitions with a 20 ms lag to prevent clicks. let bypassLagged: Lag.Control = Lag.Control( input: $bypass, time: bypassLagTime ) // Map bypass [0, 1] → pan [-1, +1]: −1 = blended (engaged), +1 = dry (bypassed). let bypassPan: any ValidGeneratorInput = (bypassLagged * bipolarSpan) - bipolarOffset // Equal-power crossfade: engaged → blended; bypassed → dry. let switched: CrossFade.Audio = CrossFade.Audio( inA: blended, inB: dry, pan: bypassPan ) return switched * $level } /// Builds the pedal's signal graph, dispatching on ``channelKind`` and emitting a second /// channel only when `outputBusRight` is set (a stereo region). public override func build() { switch channelKind { case .mono: // One independent `effect(_:)` graph per output channel; shared knobs. let dryLeft: In.Audio = input(bus: inputBus) output(bus: outputBus, source: applyChain(dry: dryLeft, wet: effect(dryLeft))) if let rightOut: Int = outputBusRight { // Broadcast the mono input to the right channel when no right input exists. let dryRight: In.Audio = input(bus: inputBusRight ?? inputBus) output(bus: rightOut, source: applyChain(dry: dryRight, wet: effect(dryRight))) } case .widener: let dry: In.Audio = input(bus: inputBus) let wet: (left: any ValidGeneratorInput, right: any ValidGeneratorInput) = wideEffect(dry) output(bus: outputBus, source: applyChain(dry: dry, wet: wet.left)) if let rightOut: Int = outputBusRight { output(bus: rightOut, source: applyChain(dry: dry, wet: wet.right)) } case .stereoNative: let dryLeft: In.Audio = input(bus: inputBus) let dryRight: In.Audio = input(bus: inputBusRight ?? inputBus) let wet: (left: any ValidGeneratorInput, right: any ValidGeneratorInput) = stereoEffect(left: dryLeft, right: dryRight) output(bus: outputBus, source: applyChain(dry: dryLeft, wet: wet.left)) if let rightOut: Int = outputBusRight { output(bus: rightOut, source: applyChain(dry: dryRight, wet: wet.right)) } } } }