// Pedal.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Foundation 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 /// Optional path to an external resource this pedal references (e.g. a neural-amp model file). /// Not a `@UIParam` — it's a `String`, applied at `build()`, and persisted separately in /// ``PedalState/resourcePath``. Default `nil`. Pedals that don't use an external file ignore it. public var resourcePath: String? // 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: - Tempo / engine (injected) /// Shared tempo clock, injected by `PedalBoard.add(_:)` for tempo-aware pedals (the /// looper's beat-quantized transport). `nil` for pedals added to a board that was /// created without a clock (e.g. a bare parallel sub-board). Weak: the clock is owned /// by `ShoeGaze` and outlives every pedal. public internal(set) weak var clock: LyrebirdClock? /// The engine that owns this pedal's nodes, injected by `PedalBoard.add(_:)`. Needed by /// tempo-aware pedals to start a `LyrebirdRoutine` that waits on beat boundaries. Weak: /// the engine owns the node tree, not the reverse. public internal(set) weak var hostEngine: SynthesisEngine? // MARK: - Tempo sync /// Sync state per tempo-syncable parameter, keyed by ``TempoSyncableParam/key``. A missing /// key means ``TempoSync/free``. Persisted in ``PedalState`` and restored on rig load. public internal(set) var tempoSync: [String: TempoSync] = [:] /// Observable signal bumped on every ``tempoSync`` change so a SwiftUI badge re-renders when the /// sync state changes through any path (the picker, a preset load, or a lightweight recall). public let tempoSyncRevision: TempoSyncRevision = TempoSyncRevision() // MARK: - Identity / routing /// Stable identity for this pedal instance, persisted in ``PedalState`` and used by MIDI /// bindings to address the pedal by id rather than by chain position. Defaults to a fresh /// `UUID` for a newly-created pedal; a rebuild from a saved rig restores the saved id /// (`board.add(_:)` / preset apply sets it), so a pedal keeps its identity across edits. public internal(set) var id: UUID = UUID() /// 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 } /// Whether the UI shows the common wet/dry `Mix` control for this pedal. Defaults to `true`. /// A pedal that manages its own dry/wet balance internally (e.g. the looper, where the clean /// signal always passes through) overrides this to `false` so the confusing Mix knob is hidden /// and `mix` stays at its fully-wet default. open var showsMixControl: Bool { true } /// Called on the main thread when the audio engine is stopped by the user (via /// `ShoeGaze.stopEngine()`), not during a transient stop-around-rebuild. Stateful pedals /// (e.g. the looper) override this to return to a clean state. Default: no-op. open func engineDidStop() {} /// Called on the main thread just before the rig is torn down (rig load / clear / input-source /// change), while the pedal is still live. Stateful pedals override this to stop any background /// work and return to a clean state before their instance is discarded. Default: no-op. /// /// - Important: Fired from `ShoeGaze.teardown()`, which — like all node-removal paths — must /// run with the engine already stopped. An override that clears buffers or stops RT-adjacent /// work relies on that precondition; do not call `teardown()` with the engine running. open func rigWillTeardown() {} /// Number of standard enclosure widths this pedal's card occupies in the UI. Defaults /// to `1`. A control-dense pedal (e.g. the looper) overrides to `2` for a wider card. /// The UI multiplies its base enclosure width by this factor; `1` is the normal stompbox. open var widthUnits: Int { 1 } /// `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] { [] } /// Current values of every ``effectSelectors`` and ``effectSwitches`` entry flagged /// `rebuildsOnChange` — the controls whose choice changes the graph topology (e.g. a cabinet /// voice or a clean/drive channel). A lightweight recall compares this before/after applying a /// snapshot to decide whether the board must be rebuilt (a plain node write does not re-enter /// `effect(_:)`). Empty for pedals with no such controls. public var rebuildTopologyValues: [Double] { // Sanitize non-finite to a fixed sentinel: the before/after compare in a recall uses `!=`, // and `NaN != NaN` would force a spurious rebuild on every recall. let selectorValues: [Double] = effectSelectors .filter { $0.rebuildsOnChange } .map { $0.node.value.isFinite ? $0.node.value : 0.0 } let switchValues: [Double] = effectSwitches .filter { $0.rebuildsOnChange } .map { $0.node.value.isFinite ? $0.node.value : 0.0 } return selectorValues + switchValues } /// Effect-specific transport controls, rendered as a row directly below the knobs — above /// ``effectButtons``. Use for the persistent state toggles and transport stops that read as /// a group distinct from the momentary "do it now" actions (e.g. a looper's Loop / Stop / /// Cue Stop / Reverse). Defaults to empty; a pedal with none simply skips the row. open var effectTransportButtons: [PedalButton] { [] } /// Effect-specific action buttons for this pedal, rendered as a row of stomp-style /// buttons beneath the transport row. /// /// Override in subclasses to publish momentary actions (e.g. "Record / Stop", "Reset") /// that need a non-RT side effect beyond writing a single parameter value — see /// ``PedalButton``. Defaults to empty. open var effectButtons: [PedalButton] { [] } /// 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), ] } /// Every continuous control on this pedal that a MIDI Control Change can drive — the pedal's /// knobs (effect knobs + Mix + Level) followed by its vertical-fader sliders. Discrete controls /// (switches, stepped selectors) are excluded; they suit Program Change toggles, not CC sweeps. /// /// Ordering is stable — knobs first, then sliders — so a persisted CC binding addressed by index /// keeps resolving to the same control across launches. Used by MIDI mapping. public var ccMappableControls: [PedalControl] { let knobControls: [PedalControl] = knobs.map { PedalControl(label: $0.label, node: $0.node, range: $0.range) } let sliderControls: [PedalControl] = effectSliders.map { PedalControl(label: $0.label, node: $0.node, range: $0.range) } return knobControls + sliderControls } // MARK: - Tempo sync /// Parameters this pedal exposes to tempo sync (delay times, LFO rates). Empty by default — /// override in subclasses whose time- or rate-based parameters can lock to the tempo. /// /// Each descriptor's ``TempoSyncableParam/key`` must be unique within the pedal and stable /// across versions (it is the persistence key). Order is the order the sync controls appear. open var tempoSyncableParams: [TempoSyncableParam] { [] } /// Recomputes and writes every parameter currently locked to a note division, from the shared /// clock's tempo. Main-thread only — writing a `@UIParam` is the same path as a knob turn. /// /// A no-op when no clock is injected. Free parameters are left untouched. A synced value that /// falls outside the parameter's range (a long division past a delay's maximum time) is clamped. /// Called by `ShoeGaze` whenever the tempo changes and whenever a parameter's sync state changes. public func applyTempoSync() { guard let clock: LyrebirdClock = clock else { return } let bpm: Double = clock.bpm guard bpm > 0 else { return } for param: TempoSyncableParam in tempoSyncableParams { guard case .division(let division) = tempoSync[param.key] ?? .free else { continue } param.node.update(param.value(for: division, bpm: bpm).value) } } /// Sets one parameter's sync state and immediately recomputes it. Pass ``TempoSync/free`` to /// return the parameter to knob control (its value stays at the last synced number until the /// knob moves it), or `.division(_:)` to lock it to a note value of the live tempo. /// /// - Parameters: /// - sync: The new sync state. /// - key: The ``TempoSyncableParam/key`` of the parameter to update. public func setSync(_ sync: TempoSync, for key: String) { tempoSync[key] = sync tempoSyncRevision.bump() applyTempoSync() } /// Whether `node` backs a tempo-syncable parameter currently locked to a note division. /// /// Used by MIDI to leave a synced parameter alone: its value is derived from the tempo, so a CC /// write would be immediately overwritten on the next tempo change. Matches by node identity, so /// it stays correct regardless of control ordering. Returns `false` for a free or non-syncable node. public func isNodeTempoSynced(_ node: UIParamNode) -> Bool { for param: TempoSyncableParam in tempoSyncableParams where param.node === node { if case .division = tempoSync[param.key] ?? .free { return true } } return false } // 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)) } } } }