From 18935767187609aaecf980ffd6958c23e6efcecf Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Wed, 1 Jul 2026 08:18:09 -0700 Subject: [PATCH] Add MIDI foot-controller control; board/rig bypass; iOS fixes Headline: MIDI control for a Behringer FCB1010 (four phases). - MIDIController (Lyrebird MIDI client): connection indicator via source polling, background-queue->main-actor hop, MIDI Learn. - Volume and Wah pedals (Wah reuses the SVF bandpass sweep, driven by pedal position instead of an envelope follower). - CC -> any pedal knob (0-127 mapped across the knob range). - Program Change -> pedal/board/rig toggles: software latch for booleans, exclusive radio for board solo. Positional addressing with display-name hints; stale/out-of-range bindings are skipped, not fired. - Per-rig MIDIMap embedded in ShoeGazeState as an optional field (old rigs decode to nil; no preset version bump). Central MIDI Mapping sheet with Learn/Clear per control. Also included (same working branch): - Full board bypass and rig bypass (dry passthrough via cascaded crossfades in BoardOutputMaster), with UI toggles. - Horizontal pedal picker grouped by category in filter order. - Drag a palette pedal onto a chain card to insert before it (ShoeGaze.insertPedal); tap still appends. - iOS: guard macOS-only .menuStyle(.borderlessButton) to silence the _UIReparentingView warning; iCloud-unavailable alert; keep the device awake while audio runs. Tests: 24 added (Volume/Wah, MIDIMap Codable incl. legacy decode, CC and PC controller behavior, insert/bypass API). Full suite green; macOS and iOS app targets build. Co-Authored-By: Claude Opus 4.8 --- Demo/ShoeGazeBuilder/AppDelegate.swift | 14 +- .../ShoeGazeBuilderiOSApp.swift | 3 +- .../ShoeGazeBuilderiOSAppModel.swift | 16 + .../LyrebirdShoeGaze/BoardOutputMaster.swift | 56 ++- .../MIDI/MIDIController.swift | 397 ++++++++++++++++++ Sources/LyrebirdShoeGaze/MIDI/MIDIMap.swift | 168 ++++++++ Sources/LyrebirdShoeGaze/PedalBoard.swift | 8 + Sources/LyrebirdShoeGaze/PedalType.swift | 4 + .../LyrebirdShoeGaze/Pedals/VolumePedal.swift | 73 ++++ .../LyrebirdShoeGaze/Pedals/WahPedal.swift | 105 +++++ .../Presets/PedalRegistry.swift | 2 + .../Presets/ShoeGaze+Edit.swift | 59 +++ .../Presets/ShoeGaze+Preset.swift | 5 +- .../Presets/ShoeGazeState.swift | 12 +- .../Routing/ChainRouter.swift | 9 +- Sources/LyrebirdShoeGaze/ShoeGaze.swift | 75 +++- Sources/LyrebirdShoeGazeUI/BoardBarView.swift | 21 + .../LyrebirdShoeGazeUI/BoardFlowView.swift | 16 +- .../MIDIIndicatorView.swift | 64 +++ .../LyrebirdShoeGazeUI/MIDIMappingSheet.swift | 217 ++++++++++ .../LyrebirdShoeGazeUI/PedalCategory.swift | 4 +- .../LyrebirdShoeGazeUI/PedalPaletteView.swift | 37 +- Sources/LyrebirdShoeGazeUI/PedalView.swift | 2 + .../RigLibrarySidebarView.swift | 28 +- .../ShoeGazeBuilderView.swift | 116 ++++- .../BoardEditAPITests.swift | 162 +++++++ .../MIDIControllerCCTests.swift | 113 +++++ .../MIDIControllerPCTests.swift | 151 +++++++ .../MIDIMapCodableTests.swift | 55 +++ .../VolumePedalTests.swift | 73 ++++ .../LyrebirdShoeGazeTests/WahPedalTests.swift | 80 ++++ 31 files changed, 2117 insertions(+), 28 deletions(-) create mode 100644 Sources/LyrebirdShoeGaze/MIDI/MIDIController.swift create mode 100644 Sources/LyrebirdShoeGaze/MIDI/MIDIMap.swift create mode 100644 Sources/LyrebirdShoeGaze/Pedals/VolumePedal.swift create mode 100644 Sources/LyrebirdShoeGaze/Pedals/WahPedal.swift create mode 100644 Sources/LyrebirdShoeGazeUI/MIDIIndicatorView.swift create mode 100644 Sources/LyrebirdShoeGazeUI/MIDIMappingSheet.swift create mode 100644 Tests/LyrebirdShoeGazeTests/MIDIControllerCCTests.swift create mode 100644 Tests/LyrebirdShoeGazeTests/MIDIControllerPCTests.swift create mode 100644 Tests/LyrebirdShoeGazeTests/MIDIMapCodableTests.swift create mode 100644 Tests/LyrebirdShoeGazeTests/VolumePedalTests.swift create mode 100644 Tests/LyrebirdShoeGazeTests/WahPedalTests.swift diff --git a/Demo/ShoeGazeBuilder/AppDelegate.swift b/Demo/ShoeGazeBuilder/AppDelegate.swift index 2d61830..c6fe550 100644 --- a/Demo/ShoeGazeBuilder/AppDelegate.swift +++ b/Demo/ShoeGazeBuilder/AppDelegate.swift @@ -55,6 +55,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate { private let shoeGaze: ShoeGaze private let window: LyrebirdWindow + /// Foot-controller MIDI input. The macOS engine is never rebuilt, so this is created once and + /// started at launch. + private let midi: MIDIController + /// The rig library; constructed in `init`, resolved + loaded asynchronously after launch. private let library: RigLibraryStore @@ -80,6 +84,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { self.coreDriver = coreDriver self.engine = engine self.shoeGaze = shoeGaze + self.midi = MIDIController(engine: engine, shoeGaze: shoeGaze) self.window = LyrebirdWindow( title: "ShoeGaze Builder — Lyrebird Pedalboard", width: AppDelegate.windowWidth, @@ -114,14 +119,21 @@ final class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ notification: Notification) { installMainMenu() + midi.start() + midi.onMapChanged = { [weak self] in + guard let self: AppDelegate = self else { return } + RigStore.save(self.shoeGaze) + } let session: ShoeGaze = shoeGaze let driver: CoreAudioDriver = coreDriver let rigLibrary: RigLibraryStore = library + let midiController: MIDIController = midi window.open { ShoeGazeBuilderView( shoeGaze: session, library: rigLibrary, - hardwareSampleRate: { driver.deviceSampleRate } + hardwareSampleRate: { driver.deviceSampleRate }, + midi: midiController ) } anchorWindowLeft() diff --git a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift index 2fadaf9..db6a477 100644 --- a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift +++ b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift @@ -28,7 +28,8 @@ struct ShoeGazeBuilderiOSApp: App { shoeGaze: model.shoeGaze, library: model.library, hardwareSampleRate: { model.hardwareSampleRate }, - onEnableLiveInput: { model.enableLiveInput() } + onEnableLiveInput: { model.enableLiveInput() }, + midi: model.midi ) .navigationTitle("ShoeGaze Builder") .navigationBarTitleDisplayMode(.inline) diff --git a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift index 644b65f..afc79d5 100644 --- a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift +++ b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift @@ -49,6 +49,10 @@ final class ShoeGazeBuilderiOSAppModel { private var engine: SynthesisEngine private var iosDriver: iOSAudioDriver + /// Foot-controller MIDI input. Owned here so it outlives the live-input engine rebuild; the + /// underlying Core MIDI client is engine-bound, so it is recreated against each new engine. + private(set) var midi: MIDIController + /// The shared rig library (iCloud-or-local). Independent of the engine, so it survives the /// live-input engine rebuild. private(set) var library: RigLibraryStore @@ -83,6 +87,11 @@ final class ShoeGazeBuilderiOSAppModel { // Construct the library instantly; it resolves iCloud + loads asynchronously via // startLibrary() from the app's .task. self.library = RigLibraryBootstrap.makeStore() + + // Connect MIDI foot-controller input and begin listening for devices. + self.midi = MIDIController(engine: built.engine, shoeGaze: shoeGaze) + self.midi.start() + self.midi.onMapChanged = { [weak self] in self?.save() } } /// Persists the current rig. Call when the app moves to the background. @@ -201,6 +210,13 @@ final class ShoeGazeBuilderiOSAppModel { ShoeGazeBuilderiOSAppModel.seedFallbackBoard(into: shoeGaze) } + // The Core MIDI client is bound to the old engine — recreate it against the new one and + // point it at the rebuilt rig, preserving the "MIDI outlives the rebuild" contract. + midi.stop() + midi = MIDIController(engine: rebuilt.engine, shoeGaze: shoeGaze) + midi.start() + midi.onMapChanged = { [weak self] in self?.save() } + selectLiveInputAndPersist() if wasRunning { try? engine.start() } diff --git a/Sources/LyrebirdShoeGaze/BoardOutputMaster.swift b/Sources/LyrebirdShoeGaze/BoardOutputMaster.swift index b3021e5..7cd8c09 100644 --- a/Sources/LyrebirdShoeGaze/BoardOutputMaster.swift +++ b/Sources/LyrebirdShoeGaze/BoardOutputMaster.swift @@ -28,6 +28,14 @@ final class BoardOutputMaster: SynthesizerBase { /// Defaults to a short 20 ms so normal use is click-free; raise it for a slow crossfade. @UIParam var crossfadeTime: Double = 0.02 + /// Per-board full-bypass state. `0` = board engaged (processed output), `1` = bypassed + /// (dry input passes straight through, skipping every pedal). Smoothed by `bypassLagTime`. + @UIParam var boardBypass: Double = 0.0 + + /// Rig-wide full-bypass state, driven across every board at once. `0` = engaged, + /// `1` = bypassed (dry). Independent of `boardBypass`; either engaged routes to dry. + @UIParam var rigBypass: Double = 0.0 + /// The live `UIParamNode` backing `masterGain`, exposed so the board (and its UI) /// can bind a master-volume knob to this stage. var gainNode: UIParamNode { $masterGain } @@ -38,6 +46,12 @@ final class BoardOutputMaster: SynthesizerBase { /// The live `UIParamNode` backing `crossfadeTime` (board crossfade seconds). var crossfadeTimeNode: UIParamNode { $crossfadeTime } + /// The live `UIParamNode` backing `boardBypass` (per-board full bypass). + var boardBypassNode: UIParamNode { $boardBypass } + + /// The live `UIParamNode` backing `rigBypass` (rig-wide full bypass). + var rigBypassNode: UIParamNode { $rigBypass } + // MARK: - Routing /// Left / mono board output bus index. @@ -48,11 +62,23 @@ final class BoardOutputMaster: SynthesizerBase { /// bypassing the mono `Pan2` spread. private let boardOutputBusRightIndex: Int? + /// The board's dry head-bus index (the mono input feeding the first pedal). Read as the + /// bypass source so a bypassed board passes its untouched input straight through. + private let dryInputBusIndex: Int + // MARK: - Constants /// Pan position for the board in the stereo field. Centre = 0.0. Used only for a mono board. private let stereoPan: Double = 0.0 + /// Lag time constant in seconds for the bypass crossfades — smooths engaged ↔ bypassed + /// transitions to prevent clicks. Matches the per-pedal bypass lag. + private let bypassLagTime: Double = 0.02 + + /// Remaps a `[0, 1]` bypass value to CrossFade's `[-1, +1]` equal-power pan. + private let bipolarSpan: Double = 2.0 + private let bipolarOffset: Double = 1.0 + // MARK: - Init /// Creates a board output master. @@ -61,9 +87,11 @@ final class BoardOutputMaster: SynthesizerBase { /// - boardOutputBusIndex: Left / mono board output bus index. /// - boardOutputBusRightIndex: Right board output bus index for a stereo (width-2) board, /// or `nil` for a mono board (the signal is panned to centre instead). - init(boardOutputBusIndex: Int, boardOutputBusRightIndex: Int? = nil) { + /// - dryInputBusIndex: The board's head-bus index, read as the dry bypass source. + init(boardOutputBusIndex: Int, boardOutputBusRightIndex: Int? = nil, dryInputBusIndex: Int) { self.boardOutputBusIndex = boardOutputBusIndex self.boardOutputBusRightIndex = boardOutputBusRightIndex + self.dryInputBusIndex = dryInputBusIndex super.init() } @@ -74,13 +102,19 @@ final class BoardOutputMaster: SynthesizerBase { // seconds rather than clicking. The user master-gain knob is applied directly. let smoothedSelect: Lag.Control = Lag.Control(input: $selectGain, time: $crossfadeTime) + // The dry input tap — read once, used as the bypass source for both channels (the head + // bus is mono, so a bypassed stereo board passes the same dry signal to both sides). + let dry: In.Audio = input(bus: dryInputBusIndex) + let boardOutLeft: In.Audio = input(bus: boardOutputBusIndex) - let gainedLeft: any ValidGeneratorInput = (boardOutLeft * smoothedSelect) * $masterGain + let switchedLeft: any ValidGeneratorInput = applyBypass(wet: boardOutLeft, dry: dry) + let gainedLeft: any ValidGeneratorInput = (switchedLeft * smoothedSelect) * $masterGain if let rightIndex: Int = boardOutputBusRightIndex { // Stereo board: left tail → hardware 0, right tail → hardware 1, no pan spread. let boardOutRight: In.Audio = input(bus: rightIndex) - let gainedRight: any ValidGeneratorInput = (boardOutRight * smoothedSelect) * $masterGain + let switchedRight: any ValidGeneratorInput = applyBypass(wet: boardOutRight, dry: dry) + let gainedRight: any ValidGeneratorInput = (switchedRight * smoothedSelect) * $masterGain output(bus: 0, source: gainedLeft) output(bus: 1, source: gainedRight) } else { @@ -88,4 +122,20 @@ final class BoardOutputMaster: SynthesizerBase { output(bus: 0, source: Pan2(input: gainedLeft, pan: stereoPan)) } } + + /// Routes `wet` to `dry` when either the per-board or rig-wide bypass is engaged. Two cascaded + /// equal-power crossfades (each lagged to prevent clicks) give an independent "OR" of the two + /// bypass sources: rig bypass overrides even a board that is otherwise engaged. + private func applyBypass( + wet: any ValidGeneratorInput, + dry: any ValidGeneratorInput + ) -> any ValidGeneratorInput { + let boardLagged: Lag.Control = Lag.Control(input: $boardBypass, time: bypassLagTime) + let boardPan: any ValidGeneratorInput = (boardLagged * bipolarSpan) - bipolarOffset + let afterBoard: CrossFade.Audio = CrossFade.Audio(inA: wet, inB: dry, pan: boardPan) + + let rigLagged: Lag.Control = Lag.Control(input: $rigBypass, time: bypassLagTime) + let rigPan: any ValidGeneratorInput = (rigLagged * bipolarSpan) - bipolarOffset + return CrossFade.Audio(inA: afterBoard, inB: dry, pan: rigPan) + } } diff --git a/Sources/LyrebirdShoeGaze/MIDI/MIDIController.swift b/Sources/LyrebirdShoeGaze/MIDI/MIDIController.swift new file mode 100644 index 0000000..e980337 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/MIDI/MIDIController.swift @@ -0,0 +1,397 @@ +// MIDIController.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import LyrebirdSynth +import LyrebirdUI + +/// Owns the Core MIDI connection for a ShoeGaze session and routes incoming messages to the rig. +/// +/// Constructed once by the app (it must outlive `ShoeGaze` rebuilds), started with ``start()``, and +/// re-pointed at a fresh `ShoeGaze` via ``retarget(_:)`` after an engine/rig rebuild. Handlers fire +/// on Lyrebird's background MIDI queue; this controller hops to the main actor before touching any +/// `@MainActor` rig state. +/// +/// This is the Phase 1 surface: it establishes the connection, publishes device-connection state +/// for the UI indicator, and installs a message handler whose body is filled in by later phases +/// (CC → pedal position, Program Change → toggle actions). +@MainActor +@Observable +public final class MIDIController { + + // MARK: - Connection state + + /// `true` when at least one MIDI input source is currently connected. + public private(set) var isConnected: Bool = false + + /// Names of the connected MIDI input sources (e.g. `"FCB1010"`), for the indicator's tooltip. + public private(set) var connectedDeviceNames: [String] = [] + + // MARK: - Learn + + /// A control armed for MIDI Learn: the next matching message captures a binding to it. + public enum LearnTarget: Equatable, Sendable { + /// A pedal knob awaiting a Control Change. Addressed positionally (see ``MIDIMap/CCTarget``). + case cc(boardIndex: Int, pedalIndex: Int, knobIndex: Int) + /// A toggle action awaiting a Program Change. + case action(MIDIMap.Action) + } + + /// The control currently armed for Learn, or `nil` when not learning. Observable so the UI can + /// show a "Listening…" state and a global learn banner. + public private(set) var learnTarget: LearnTarget? + + /// Invoked on the main actor after the map changes (a binding learned or cleared), so the host + /// can persist the rig. Optional — when unset, the map still persists on the next rig autosave. + public var onMapChanged: (() -> Void)? + + // MARK: - Private + + private let midi: MIDI + private var handlerToken: MIDIHandlerToken? + + /// The rig this controller drives. Weak + retargetable: the app owns both, and an iOS engine + /// rebuild swaps `ShoeGaze` out from under us. + private weak var shoeGaze: ShoeGaze? + + /// Main-queue timer that re-reads `midi.sources` to publish connection state. Polling is used + /// because Lyrebird 1.2.0's `MIDI` refreshes endpoints internally but exposes no change callback. + private var detectionTimer: DispatchSourceTimer? + + /// Poll interval for connection state, in seconds. A foot controller is plugged in before a set, + /// so ~1 s latency is imperceptible. + private let detectionInterval: Double = 1.0 + + /// Crossfade time (seconds) applied to board solo/audible changes triggered by a footswitch. + private let boardActionCrossfade: Double = 0.05 + + // MARK: - Init + + /// Creates a MIDI controller bound to an engine. + /// + /// - Parameters: + /// - engine: The engine the underlying `MIDI` client attaches to. On iOS this is rebuilt when + /// live input is enabled; recreate the controller against the new engine in that case. + /// - shoeGaze: The rig to drive. May be set later via ``retarget(_:)``. + /// - clientName: Core MIDI client name. Defaults to `"ShoeGaze"`. + public init( + engine: SynthesisEngine, + shoeGaze: ShoeGaze? = nil, + clientName: String = "ShoeGaze" + ) { + self.midi = MIDI(engine: engine, clientName: clientName) + self.shoeGaze = shoeGaze + } + + // MARK: - Lifecycle + + /// Starts the MIDI client, installs the message handler, and begins polling for devices. + /// Safe to call once; a failed `MIDI.start()` is logged and leaves the controller inert. + public func start() { + do { + try midi.start() + } catch { + print("[MIDIController] MIDI start failed: \(error)") + } + installHandler() + refreshDevices() + startDetectionTimer() + } + + /// Removes the handler, stops polling, and tears down the MIDI client. + public func stop() { + stopDetectionTimer() + if let token: MIDIHandlerToken = handlerToken { + midi.removeHandler(token) + handlerToken = nil + } + midi.stop() + } + + /// Re-points the controller at a fresh `ShoeGaze` after an engine/rig rebuild. + public func retarget(_ shoeGaze: ShoeGaze) { + self.shoeGaze = shoeGaze + } + + // MARK: - Message handling + + private func installHandler() { + handlerToken = midi.addHandler(name: "shoegaze.midi") { [weak self] message, _ in + // Handlers fire on the background `lyrebird.midi` queue. Hop to the main actor (FIFO on + // the main queue) before touching any `@MainActor` rig state. + DispatchQueue.main.async { + MainActor.assumeIsolated { + self?.handle(message) + } + } + } + } + + /// Routes one incoming message to the rig: captures a binding when armed for Learn, otherwise + /// applies any matching binding. (Program Change handling is added in a later phase.) + private func handle(_ message: MIDIMessage) { + switch message { + case .controlChange(let channel, let controller, let value): + if case .cc(let boardIndex, let pedalIndex, let knobIndex) = learnTarget { + captureCC( + controller: controller, + channel: channel, + boardIndex: boardIndex, + pedalIndex: pedalIndex, + knobIndex: knobIndex + ) + } else { + applyCC(controller: controller, channel: channel, value: value) + } + case .programChange(let channel, let program): + if case .action(let action) = learnTarget { + captureSwitch(program: program, channel: channel, action: action) + } else { + applyProgram(program: program, channel: channel) + } + default: + break + } + } + + #if DEBUG + /// Test hook: routes a message synchronously, bypassing the background-queue hop. The queue hop + /// is exercised only in a live session; tests drive `handle` directly on the main actor. + func ingestForTesting(_ message: MIDIMessage) { + handle(message) + } + #endif + + // MARK: - Learn API + + /// Arms MIDI Learn for a pedal knob: the next incoming Control Change binds to it. + public func armCCLearn(boardIndex: Int, pedalIndex: Int, knobIndex: Int) { + learnTarget = .cc(boardIndex: boardIndex, pedalIndex: pedalIndex, knobIndex: knobIndex) + } + + /// Cancels any in-progress Learn. + public func cancelLearn() { + learnTarget = nil + } + + /// The CC binding currently assigned to a pedal knob, or `nil` if unbound. + public func ccBinding(boardIndex: Int, pedalIndex: Int, knobIndex: Int) -> MIDIMap.CCBinding? { + shoeGaze?.midiMap?.ccs.first { $0.target.boardIndex == boardIndex + && $0.target.pedalIndex == pedalIndex + && $0.target.knobIndex == knobIndex } + } + + /// Removes any CC binding assigned to a pedal knob. + public func clearCCBinding(boardIndex: Int, pedalIndex: Int, knobIndex: Int) { + guard let shoeGaze: ShoeGaze = shoeGaze, var map: MIDIMap = shoeGaze.midiMap else { return } + let before: Int = map.ccs.count + map.ccs.removeAll { $0.target.boardIndex == boardIndex + && $0.target.pedalIndex == pedalIndex + && $0.target.knobIndex == knobIndex } + guard map.ccs.count != before else { return } + shoeGaze.midiMap = map + onMapChanged?() + } + + // MARK: - CC handling + + /// Captures a learned CC binding for the armed knob and clears the Learn state. + private func captureCC( + controller: UInt8, + channel: UInt8, + boardIndex: Int, + pedalIndex: Int, + knobIndex: Int + ) { + learnTarget = nil + guard let shoeGaze: ShoeGaze = shoeGaze, + let pedal: Pedal = pedal(boardIndex: boardIndex, pedalIndex: pedalIndex), + knobIndex >= 0, knobIndex < pedal.knobs.count else { return } + + let target: MIDIMap.CCTarget = MIDIMap.CCTarget( + boardIndex: boardIndex, + pedalIndex: pedalIndex, + knobIndex: knobIndex, + pedalNameHint: pedal.displayName, + knobLabelHint: pedal.knobs[knobIndex].label + ) + let binding: MIDIMap.CCBinding = MIDIMap.CCBinding( + controller: controller, + channel: channel, + target: target + ) + + var map: MIDIMap = shoeGaze.midiMap ?? MIDIMap.empty + // One knob → one CC, and reassigning a CC steals it from any other knob. + map.ccs.removeAll { $0.target == target || $0.controller == controller } + map.ccs.append(binding) + shoeGaze.midiMap = map + onMapChanged?() + } + + /// Applies an incoming CC to the pedal knob it is bound to, if any. + private func applyCC(controller: UInt8, channel: UInt8, value: UInt8) { + guard let shoeGaze: ShoeGaze = shoeGaze, let map: MIDIMap = shoeGaze.midiMap else { return } + for binding: MIDIMap.CCBinding in map.ccs where binding.controller == controller { + if let boundChannel: UInt8 = binding.channel, boundChannel != channel { continue } + applyCCBinding(binding, value: value) + } + } + + /// Resolves a CC binding's target knob (skipping stale bindings) and writes the mapped value. + private func applyCCBinding(_ binding: MIDIMap.CCBinding, value: UInt8) { + let target: MIDIMap.CCTarget = binding.target + guard let pedal: Pedal = pedal(boardIndex: target.boardIndex, pedalIndex: target.pedalIndex), + target.knobIndex >= 0, target.knobIndex < pedal.knobs.count else { return } + let knob: PedalKnob = pedal.knobs[target.knobIndex] + // Stale-binding guard: the chain may have been edited under the positional address. + if let nameHint: String = target.pedalNameHint, nameHint != pedal.displayName { return } + if let labelHint: String = target.knobLabelHint, labelHint != knob.label { return } + + let ccMax: Double = 127.0 + var norm: Double = Double(value) / ccMax + if binding.inverted { norm = 1.0 - norm } + let mapped: Double = knob.range.lowerBound + + norm * (knob.range.upperBound - knob.range.lowerBound) + knob.node.update(mapped) + } + + // MARK: - Switch (Program Change) learn + apply + + /// Arms MIDI Learn for a toggle action: the next incoming Program Change binds to it. + public func armSwitchLearn(_ action: MIDIMap.Action) { + learnTarget = .action(action) + } + + /// The switch binding currently assigned to an action, or `nil` if unbound. + public func switchBinding(for action: MIDIMap.Action) -> MIDIMap.SwitchBinding? { + shoeGaze?.midiMap?.switches.first { $0.action == action } + } + + /// Removes any switch binding assigned to an action. + public func clearSwitchBinding(for action: MIDIMap.Action) { + guard let shoeGaze: ShoeGaze = shoeGaze, var map: MIDIMap = shoeGaze.midiMap else { return } + let before: Int = map.switches.count + map.switches.removeAll { $0.action == action } + guard map.switches.count != before else { return } + shoeGaze.midiMap = map + onMapChanged?() + } + + /// Captures a learned switch binding for the armed action and clears the Learn state. + private func captureSwitch(program: UInt8, channel: UInt8, action: MIDIMap.Action) { + learnTarget = nil + guard let shoeGaze: ShoeGaze = shoeGaze else { return } + let binding: MIDIMap.SwitchBinding = MIDIMap.SwitchBinding( + program: program, + channel: channel, + action: action, + displayNameHint: hint(for: action) + ) + var map: MIDIMap = shoeGaze.midiMap ?? MIDIMap.empty + // One action → one program, and reassigning a program steals it from any other action. + map.switches.removeAll { $0.action == action || $0.program == program } + map.switches.append(binding) + shoeGaze.midiMap = map + onMapChanged?() + } + + /// Performs every action bound to an incoming Program Change (channel-filtered). + private func applyProgram(program: UInt8, channel: UInt8) { + guard let shoeGaze: ShoeGaze = shoeGaze, let map: MIDIMap = shoeGaze.midiMap else { return } + for binding: MIDIMap.SwitchBinding in map.switches where binding.program == program { + if let boundChannel: UInt8 = binding.channel, boundChannel != channel { continue } + perform(binding.action, hint: binding.displayNameHint) + } + } + + /// Executes a toggle action by reading the live rig state and flipping it. Boolean actions latch; + /// `boardSolo` is exclusive (radio). Stale bindings (chain edited under the positional address) + /// are skipped via bounds + display-name checks. + private func perform(_ action: MIDIMap.Action, hint: String?) { + guard let shoeGaze: ShoeGaze = shoeGaze else { return } + switch action { + case .rigBypass: + shoeGaze.toggleRigBypassed() + case .boardSolo(let boardIndex): + guard let board: PedalBoard = board(at: boardIndex), matchesBoard(board, hint) else { return } + shoeGaze.soloBoard(board, crossfadeSeconds: boardActionCrossfade) + case .boardAudible(let boardIndex): + guard let board: PedalBoard = board(at: boardIndex), matchesBoard(board, hint) else { return } + shoeGaze.setBoard(board, audible: !shoeGaze.isBoardAudible(board), + crossfadeSeconds: boardActionCrossfade) + case .boardBypass(let boardIndex): + guard let board: PedalBoard = board(at: boardIndex), matchesBoard(board, hint) else { return } + shoeGaze.setBoard(board, bypassed: !shoeGaze.isBoardBypassed(board)) + case .pedalBypass(let boardIndex, let pedalIndex): + guard let pedal: Pedal = pedal(boardIndex: boardIndex, pedalIndex: pedalIndex) else { return } + if let hint: String = hint, hint != pedal.displayName { return } + let engagedThreshold: Double = 0.5 + let node: UIParamNode = pedal.$bypass + node.update(node.value < engagedThreshold ? 1.0 : 0.0) + } + } + + /// A display-name hint for an action, captured at learn time for stale-binding detection. + private func hint(for action: MIDIMap.Action) -> String? { + switch action { + case .rigBypass: + return nil + case .boardSolo(let index), .boardAudible(let index), .boardBypass(let index): + return board(at: index)?.label + case .pedalBypass(let boardIndex, let pedalIndex): + return pedal(boardIndex: boardIndex, pedalIndex: pedalIndex)?.displayName + } + } + + /// `true` when a board still matches its captured hint (or no hint was captured). + private func matchesBoard(_ board: PedalBoard, _ hint: String?) -> Bool { + guard let hint: String = hint else { return true } + return board.label == hint + } + + /// Resolves a board by index, or `nil` if out of range. + private func board(at index: Int) -> PedalBoard? { + guard let shoeGaze: ShoeGaze = shoeGaze, index >= 0, index < shoeGaze.boards.count else { + return nil + } + return shoeGaze.boards[index] + } + + /// Resolves a pedal by board + pedal index, or `nil` if either index is out of range. + private func pedal(boardIndex: Int, pedalIndex: Int) -> Pedal? { + guard let shoeGaze: ShoeGaze = shoeGaze, + boardIndex >= 0, boardIndex < shoeGaze.boards.count else { return nil } + let board: PedalBoard = shoeGaze.boards[boardIndex] + guard pedalIndex >= 0, pedalIndex < board.pedals.count else { return nil } + return board.pedals[pedalIndex] + } + + // MARK: - Device detection + + private func refreshDevices() { + let names: [String] = midi.sources.map { $0.name } + connectedDeviceNames = names + isConnected = !names.isEmpty + } + + private func startDetectionTimer() { + let timer: DispatchSourceTimer = DispatchSource.makeTimerSource(queue: .main) + timer.schedule(deadline: .now() + detectionInterval, repeating: detectionInterval) + timer.setEventHandler { [weak self] in + MainActor.assumeIsolated { + self?.refreshDevices() + } + } + timer.resume() + detectionTimer = timer + } + + private func stopDetectionTimer() { + detectionTimer?.cancel() + detectionTimer = nil + } +} diff --git a/Sources/LyrebirdShoeGaze/MIDI/MIDIMap.swift b/Sources/LyrebirdShoeGaze/MIDI/MIDIMap.swift new file mode 100644 index 0000000..b40d08b --- /dev/null +++ b/Sources/LyrebirdShoeGaze/MIDI/MIDIMap.swift @@ -0,0 +1,168 @@ +// MIDIMap.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// A per-rig map of MIDI foot-controller bindings — which Program Change toggles which control, and +/// which Control Change drives which pedal knob. +/// +/// Stored inside the rig (embedded in `ShoeGazeState`) so it travels with a saved rig. Controls are +/// addressed **positionally** (board index, pedal index, knob index) since boards and pedals have no +/// stable identity; the `*Hint` fields carry the resolved display name at learn time so a binding +/// that no longer matches (chain edited) can be detected and skipped rather than mis-fire. +public struct MIDIMap: Codable, Equatable, Sendable { + + /// Program-Change → action bindings (footswitch toggles). Populated in the switch phase. + public var switches: [SwitchBinding] + + /// Control-Change → pedal-knob bindings (expression pedals). + public var ccs: [CCBinding] + + /// An empty map (no bindings). + public static let empty: MIDIMap = MIDIMap() + + /// Creates a MIDI map. + /// + /// - Parameters: + /// - switches: Program-Change bindings. Defaults to empty. + /// - ccs: Control-Change bindings. Defaults to empty. + public init( + switches: [SwitchBinding] = [], + ccs: [CCBinding] = [] + ) { + self.switches = switches + self.ccs = ccs + } + + // MARK: - Action + + /// A toggle-style control a footswitch (Program Change) can drive. Program Change is momentary, + /// so boolean actions latch in software; `boardSolo` is exclusive (radio). + public enum Action: Codable, Equatable, Sendable { + case rigBypass + case boardSolo(boardIndex: Int) + case boardAudible(boardIndex: Int) + case boardBypass(boardIndex: Int) + case pedalBypass(boardIndex: Int, pedalIndex: Int) + } + + // MARK: - Switch binding + + /// A Program-Change number bound to a toggle ``Action``. + public struct SwitchBinding: Codable, Equatable, Sendable { + + /// The Program Change number (0–127) that triggers the action. + public var program: UInt8 + + /// The MIDI channel (0–15), or `nil` to match any channel (omni). + public var channel: UInt8? + + /// The control to toggle. + public var action: Action + + /// The resolved control's display name at learn time, for stale-binding detection. + public var displayNameHint: String? + + /// Creates a switch binding. + /// + /// - Parameters: + /// - program: Program Change number (0–127). + /// - channel: MIDI channel (0–15), or `nil` for omni. Defaults to `nil`. + /// - action: The toggle action to perform. + /// - displayNameHint: Resolved control name at learn time. Defaults to `nil`. + public init( + program: UInt8, + channel: UInt8? = nil, + action: Action, + displayNameHint: String? = nil + ) { + self.program = program + self.channel = channel + self.action = action + self.displayNameHint = displayNameHint + } + } + + // MARK: - CC target + + /// Addresses a single pedal knob to be driven by an expression pedal. `knobIndex` indexes into + /// the pedal's `knobs` list (effect knobs, then Mix and Level). + public struct CCTarget: Codable, Equatable, Sendable { + + /// Index of the board in `ShoeGaze.boards`. + public var boardIndex: Int + + /// Index of the pedal in `board.pedals`. + public var pedalIndex: Int + + /// Index of the knob in `pedal.knobs`. + public var knobIndex: Int + + /// The pedal's `displayName` at learn time, for stale-binding detection. + public var pedalNameHint: String? + + /// The knob's label at learn time, for stale-binding detection. + public var knobLabelHint: String? + + /// Creates a CC target. + /// + /// - Parameters: + /// - boardIndex: Index of the board in `ShoeGaze.boards`. + /// - pedalIndex: Index of the pedal in `board.pedals`. + /// - knobIndex: Index of the knob in `pedal.knobs`. + /// - pedalNameHint: Pedal display name at learn time. Defaults to `nil`. + /// - knobLabelHint: Knob label at learn time. Defaults to `nil`. + public init( + boardIndex: Int, + pedalIndex: Int, + knobIndex: Int, + pedalNameHint: String? = nil, + knobLabelHint: String? = nil + ) { + self.boardIndex = boardIndex + self.pedalIndex = pedalIndex + self.knobIndex = knobIndex + self.pedalNameHint = pedalNameHint + self.knobLabelHint = knobLabelHint + } + } + + // MARK: - CC binding + + /// A Control-Change number bound to a pedal knob. The incoming value (0–127) is mapped across + /// the knob's own range; `inverted` swaps heel/toe for reversed expression pedals. + public struct CCBinding: Codable, Equatable, Sendable { + + /// The Control Change number (0–127). + public var controller: UInt8 + + /// The MIDI channel (0–15), or `nil` to match any channel (omni). + public var channel: UInt8? + + /// The pedal knob this CC drives. + public var target: CCTarget + + /// When `true`, CC 0 maps to the knob's maximum and 127 to its minimum. + public var inverted: Bool + + /// Creates a CC binding. + /// + /// - Parameters: + /// - controller: Control Change number (0–127). + /// - channel: MIDI channel (0–15), or `nil` for omni. Defaults to `nil`. + /// - target: The pedal knob to drive. + /// - inverted: Reverse the sweep direction. Defaults to `false`. + public init( + controller: UInt8, + channel: UInt8? = nil, + target: CCTarget, + inverted: Bool = false + ) { + self.controller = controller + self.channel = channel + self.target = target + self.inverted = inverted + } + } +} diff --git a/Sources/LyrebirdShoeGaze/PedalBoard.swift b/Sources/LyrebirdShoeGaze/PedalBoard.swift index 4ab93a9..6b462d2 100644 --- a/Sources/LyrebirdShoeGaze/PedalBoard.swift +++ b/Sources/LyrebirdShoeGaze/PedalBoard.swift @@ -105,6 +105,14 @@ public final class PedalBoard { /// `nil` until `finalizeBoard(_:)`. public internal(set) var crossfadeTimeNode: UIParamNode? + /// The live per-board full-bypass `UIParamNode` (`0` = engaged, `1` = dry passthrough). + /// `nil` until `finalizeBoard(_:)`. Driven by `ShoeGaze.setBoard(_:bypassed:)`. + public internal(set) var boardBypassNode: UIParamNode? + + /// The live rig-wide full-bypass `UIParamNode` (`0` = engaged, `1` = dry passthrough), + /// driven across every board by `ShoeGaze.setRigBypassed(_:)`. `nil` until `finalizeBoard(_:)`. + public internal(set) var rigBypassNode: UIParamNode? + /// The output master synth for this board. Set by `ShoeGaze.finalizeBoard(_:)`; /// used by `ShoeGaze.removeBoard(_:)` to tear down just this board's master. internal var outputMaster: BoardOutputMaster? diff --git a/Sources/LyrebirdShoeGaze/PedalType.swift b/Sources/LyrebirdShoeGaze/PedalType.swift index f58c22b..d820c38 100644 --- a/Sources/LyrebirdShoeGaze/PedalType.swift +++ b/Sources/LyrebirdShoeGaze/PedalType.swift @@ -54,6 +54,7 @@ public extension PedalType { // EQ & filter static let graphicEQ = PedalType("Graphic EQ") static let autoWah = PedalType("Auto-Wah") + static let wah = PedalType("Wah") static let mutant = PedalType("Mutant") static let phaser = PedalType("Phaser") @@ -73,6 +74,9 @@ public extension PedalType { // Dynamics (additional) static let sustainer = PedalType("Sustainer") + // Gain (additional) + static let volume = PedalType("Volume") + // Delay & reverb static let delay = PedalType("Delay") static let feedbackDelay = PedalType("Feedback Delay") diff --git a/Sources/LyrebirdShoeGaze/Pedals/VolumePedal.swift b/Sources/LyrebirdShoeGaze/Pedals/VolumePedal.swift new file mode 100644 index 0000000..2509059 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/VolumePedal.swift @@ -0,0 +1,73 @@ +// VolumePedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Foot-controlled volume pedal — a single smoothed gain sweep from silence to unity. +/// +/// The `position` knob is the expression-pedal position: `0` = heel down (silent), `1` = toe +/// down (unity gain). It is smoothed with a short `Lag` so sweeping the position (by hand or from +/// a MIDI expression pedal) is click-free. +/// +/// ## Knobs +/// - `position`: Volume sweep in `[0, 1]`. `0` = silent, `1` = unity. +public final class VolumePedal: Pedal { + + /// One-line description shown in the picker and info panel. + public override var summary: String { + "Foot-controlled volume — sweep from silence to unity gain." + } + + // MARK: - Parameters + + /// Expression-pedal position in `[0, 1]`. `0` = heel (silent), `1` = toe (unity gain). + @UIParam public var position: Double = 1.0 + + // MARK: - Constants + + private static let defaultMix: Double = 1.0 + + /// Smoothing time constant in seconds for the position sweep — prevents zipper noise when + /// the position jumps (e.g. coarse 0–127 steps from a MIDI expression pedal). + private let smoothingTime: Double = 0.02 + + // MARK: - Ranges + + private let positionRange: ClosedRange = 0.0 ... 1.0 + + // MARK: - Knobs + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Position", node: $position, range: positionRange), + ] + } + + // MARK: - Init + + /// Creates a volume pedal. + /// + /// - Parameters: + /// - inputBus: Audio bus to read the dry input from. Defaults to `0`; set by the board. + /// - outputBus: Audio bus to write the scaled output to. Defaults to `0`; set by the board. + public init(inputBus: Int = 0, outputBus: Int = 0) { + super.init( + name: "Volume", + inputBus: inputBus, + outputBus: outputBus, + initialMix: VolumePedal.defaultMix + ) + } + + // MARK: - Effect + + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + // Smooth the position so hand/MIDI sweeps don't zipper, then scale the dry signal. + let smoothed: Lag.Control = Lag.Control(input: $position, time: smoothingTime) + return dry * smoothed + } +} diff --git a/Sources/LyrebirdShoeGaze/Pedals/WahPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/WahPedal.swift new file mode 100644 index 0000000..c977e97 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/WahPedal.swift @@ -0,0 +1,105 @@ +// WahPedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Foot-swept wah pedal — a resonant bandpass whose cutoff follows the expression-pedal position. +/// +/// Reuses the same filter voice as ``AutoWahPedal`` (a resonant `SVF` bandpass swept through an +/// exponential `LinExp` frequency map) but drives the sweep from the `position` knob instead of an +/// amplitude follower: `0` = heel (low, dark) → `1` = toe (high, bright). The position is smoothed +/// so hand or MIDI sweeps are click-free. +/// +/// ## Signal path +/// ``` +/// position → Lag → LinExp(freqLo…freqHi) → SVF.bandpass(q: resonance) +/// ↑freq +/// ``` +/// +/// ## Knobs +/// - `position`: Sweep position in `[0, 1]`. `0` = low cutoff, `1` = high cutoff. +/// - `resonance`: Bandpass Q. Higher values sharpen the wah vowel. +public final class WahPedal: Pedal { + + /// One-line description shown in the picker and info panel. + public override var summary: String { + "Foot-swept resonant filter — the classic wah voice, driven by pedal position." + } + + // MARK: - Parameters + + /// Expression-pedal position in `[0, 1]`. `0` = heel (low cutoff), `1` = toe (high cutoff). + @UIParam public var position: Double = 0.5 + + /// Bandpass resonance (SVF quality factor). Higher values sharpen the wah vowel. + @UIParam public var resonance: Double = 3.0 + + // MARK: - Constants + + private static let defaultMix: Double = 1.0 + + /// Cutoff at heel (`position == 0`), in Hz. `LinExp` requires a strictly positive lower bound. + private let freqLo: Double = 400.0 + + /// Cutoff at toe (`position == 1`), in Hz. + private let freqHi: Double = 2200.0 + + /// Smoothing time constant in seconds for the position sweep — prevents zipper noise when the + /// position jumps (e.g. coarse 0–127 steps from a MIDI expression pedal). + private let smoothingTime: Double = 0.02 + + // MARK: - Ranges + + private let positionRange: ClosedRange = 0.0 ... 1.0 + private let resonanceRange: ClosedRange = 0.5 ... 8.0 + + // MARK: - Knobs + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Position", node: $position, range: positionRange), + PedalKnob(label: "Resonance", node: $resonance, range: resonanceRange), + ] + } + + // MARK: - Init + + /// Creates a wah pedal. + /// + /// - Parameters: + /// - inputBus: Audio bus to read the dry input from. Defaults to `0`; set by the board. + /// - outputBus: Audio bus to write the filtered output to. Defaults to `0`; set by the board. + public init(inputBus: Int = 0, outputBus: Int = 0) { + super.init( + name: "Wah", + inputBus: inputBus, + outputBus: outputBus, + initialMix: WahPedal.defaultMix + ) + } + + // MARK: - Effect + + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + // Smooth the position, map it exponentially to a cutoff sweep, and drive a resonant + // bandpass — the wah voice following the pedal rather than the signal envelope. + let smoothed: Lag.Control = Lag.Control(input: $position, time: smoothingTime) + let cutoff: LinExp.Audio = LinExp.Audio( + smoothed, + inLo: 0.0, + inHi: 1.0, + outLo: freqLo, + outHi: freqHi + ) + let filtered: SVF.Audio = SVF.Audio( + input: dry, + freq: cutoff, + q: $resonance + ) + return filtered.bandpass + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift index fb177ce..4e0a5f7 100644 --- a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift +++ b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift @@ -42,6 +42,8 @@ public enum PedalRegistry { "Compressor": { CompressorPedal() }, "Mutant": { MutantPedal() }, "Auto-Wah": { AutoWahPedal() }, + "Wah": { WahPedal() }, + "Volume": { VolumePedal() }, "Feedback Delay": { FeedbackDelayPedal() }, "Multi-Tap Delay": { MultiTapDelayPedal() }, "Octave Splitter": { OctaveUpSplitterPedal() }, diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Edit.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Edit.swift index 7e0e6a8..c415216 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Edit.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Edit.swift @@ -59,6 +59,65 @@ extension ShoeGaze { return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) } + /// Inserts a pedal of the given type at `index` within a lane, shifting later pedals along. + /// + /// `index` addresses the lane's own pedal order (`board.pedals` for ``PedalLane/main``; the + /// branch's pedal list for a branch lane) and follows insert-before semantics: the new pedal + /// lands immediately before the pedal currently at `index`. An `index` equal to the lane's pedal + /// count appends to the end (same placement as ``appendPedal(_:to:lane:)``). The pedal is created + /// at its constructor defaults and the board is rebuilt via ``rebuildBoard(_:from:)``. + /// + /// - Important: Editing rebuilds the board through the same path as preset load; safe on a + /// running engine with at most one block of glitch (see ``rebuildBoard(_:from:)``). + /// + /// - Parameters: + /// - kind: The pedal type. Its `rawValue` must be a key in `PedalRegistry.builtIn`. + /// - index: Insert-before position in the lane's pedal order. Valid range `0...laneCount`. + /// - board: The board to edit. Must have been returned by `addBoard()` on this instance. + /// - lane: Which lane to insert into. Defaults to ``PedalLane/main``. + /// - Returns: The rebuilt board occupying the same slot in `boards`. + /// - Throws: `ShoeGazeError.unknownPedalType`, `.pedalIndexOutOfRange`, `.notABranchRegion`, or + /// any error from ``rebuildBoard(_:from:)``. + @discardableResult + public func insertPedal( + _ kind: PedalType, + at index: Int, + to board: PedalBoard, + lane: PedalLane = .main + ) throws -> PedalBoard { + let type: String = kind.rawValue + guard PedalRegistry.builtIn[type] != nil else { + throw ShoeGazeError.unknownPedalType(type) + } + let newState: PedalState = PedalState(type: type, knobValues: [], switchValues: [], bypass: 0.0) + + var segments: [BoardSegmentState] = board.captureState().segments + switch lane { + case .main: + let pedalPositions: [Int] = linearPedalSegmentIndices(segments) + guard index >= 0 && index <= pedalPositions.count else { + throw ShoeGazeError.pedalIndexOutOfRange(index: index, count: pedalPositions.count) + } + if index < pedalPositions.count { + segments.insert(.pedal(newState), at: pedalPositions[index]) + } else if let lastPedalIndex: Int = pedalPositions.last { + // Inserting at the end: land right after the last linear pedal, before any trailing + // routing node — mirrors `appendPedal`'s placement rule. + segments.insert(.pedal(newState), at: lastPedalIndex + 1) + } else { + segments.append(.pedal(newState)) + } + case .left, .right: + try mutateBranch(&segments, lane: lane) { branch in + guard index >= 0 && index <= branch.count else { + throw ShoeGazeError.pedalIndexOutOfRange(index: index, count: branch.count) + } + branch.insert(newState, at: index) + } + } + return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) + } + /// Removes the pedal at `index` within a lane. /// /// `index` addresses the lane's own pedal order (`board.pedals` for ``PedalLane/main``; the diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift index 642ad7e..e124d43 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift @@ -18,7 +18,7 @@ extension ShoeGaze { /// - Returns: A `ShoeGazeState` reflecting the current rig. public func captureState() -> ShoeGazeState { let boardStates: [BoardState] = boards.map { $0.captureState() } - return ShoeGazeState(boards: boardStates) + return ShoeGazeState(boards: boardStates, midiMap: midiMap) } /// Captures the current rig as a named ``RigEntry`` suitable for the rig library. @@ -95,6 +95,9 @@ extension ShoeGaze { teardown() try rebuildAllBoards(from: state) + // Restore the rig's MIDI bindings after the boards exist, so a MIDIController re-reading the + // map resolves against the freshly rebuilt boards. + midiMap = state.midiMap } /// Rebuilds every board from a snapshot with all-or-nothing semantics. diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift index 1deafe0..030397c 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift @@ -27,16 +27,26 @@ public struct ShoeGazeState: Codable, Equatable { /// All board snapshots in the order they were created. public let boards: [BoardState] + /// The rig's MIDI foot-controller bindings, or `nil` for a rig saved without any. + /// + /// Optional so rigs written before MIDI mapping existed decode cleanly (the synthesized + /// `init(from:)` uses `decodeIfPresent`, yielding `nil` for the missing key) — no format + /// version bump is required for this additive field. + public let midiMap: MIDIMap? + /// Creates a rig state snapshot. /// /// - Parameters: /// - version: Preset format version. Defaults to `presetFormatVersion`. /// - boards: Ordered list of board state snapshots. + /// - midiMap: The rig's MIDI bindings, or `nil` when there are none. Defaults to `nil`. public init( version: Int = presetFormatVersion, - boards: [BoardState] + boards: [BoardState], + midiMap: MIDIMap? = nil ) { self.version = version self.boards = boards + self.midiMap = midiMap } } diff --git a/Sources/LyrebirdShoeGaze/Routing/ChainRouter.swift b/Sources/LyrebirdShoeGaze/Routing/ChainRouter.swift index cf40190..0860596 100644 --- a/Sources/LyrebirdShoeGaze/Routing/ChainRouter.swift +++ b/Sources/LyrebirdShoeGaze/Routing/ChainRouter.swift @@ -280,8 +280,13 @@ public final class ChainRouter { try engine.add(builtMerger, position: .after(mergerPredecessor)) self.merger = builtMerger - // Finalize step 2 — create the output master and insert it after the merger. - let master: BoardOutputMaster = BoardOutputMaster(boardOutputBusIndex: mixBus.index) + // Finalize step 2 — create the output master and insert it after the merger. The router's + // full-bypass params are never driven (it isn't a board-bar board), so its dry source is + // the mix bus itself — the bypass crossfade is a permanent no-op here. + let master: BoardOutputMaster = BoardOutputMaster( + boardOutputBusIndex: mixBus.index, + dryInputBusIndex: mixBus.index + ) try engine.add(master, position: .after(builtMerger)) self.outputMaster = master self.masterGainNode = master.gainNode diff --git a/Sources/LyrebirdShoeGaze/ShoeGaze.swift b/Sources/LyrebirdShoeGaze/ShoeGaze.swift index 928a7de..a225350 100644 --- a/Sources/LyrebirdShoeGaze/ShoeGaze.swift +++ b/Sources/LyrebirdShoeGaze/ShoeGaze.swift @@ -66,6 +66,11 @@ public final class ShoeGaze { /// Input source policy. Affects how `addBoard()` routes signal to the head bus. public var inputSource: InputSource + /// The rig's MIDI foot-controller bindings, or `nil` when none are set. Embedded in the rig + /// snapshot by `captureState()` and restored by `loadRig`, so the map travels with the rig. + /// Read and mutated by `MIDIController`; survives an input-source switch (same rig). + public var midiMap: MIDIMap? + // MARK: - Recording state /// The folder into which `startRecording()` writes timestamped WAV files. @@ -237,7 +242,8 @@ public final class ShoeGaze { public func finalizeBoard(_ board: PedalBoard) throws { let master: BoardOutputMaster = BoardOutputMaster( boardOutputBusIndex: board.outputBus.index, - boardOutputBusRightIndex: board.outputBusRight?.index + boardOutputBusRightIndex: board.outputBusRight?.index, + dryInputBusIndex: board.headBus.index ) // The master evaluates after the entire chain (pedals, splitters, mergers). // `board.tailNode` returns the last inserted node (any Synthesizer), which covers @@ -256,6 +262,8 @@ public final class ShoeGaze { board.masterGainNode = master.gainNode board.selectGainNode = master.selectGainNode board.crossfadeTimeNode = master.crossfadeTimeNode + board.boardBypassNode = master.boardBypassNode + board.rigBypassNode = master.rigBypassNode // If a board is currently soloed, a newly-finalized board must come up silent // (select-gain 0) so it doesn't leak audio past the active solo. @@ -264,6 +272,12 @@ public final class ShoeGaze { newIndex != soloIndex { master.selectGainNode.update(0.0) } + + // A board finalized while the rig is bypassed must come up bypassed too, so it doesn't + // leak processed audio past the global bypass. + if rigBypassed { + master.rigBypassNode.update(1.0) + } } // MARK: - Board selection / crossfade @@ -272,6 +286,14 @@ public final class ShoeGaze { /// are audible (the default — every board's output sums to the hardware output). public private(set) var activeBoardIndex: Int? + /// `true` when the whole rig is bypassed — every board passes its dry input straight through. + /// A live performance toggle (not persisted); cleared on input-source / engine rebuild. + public private(set) var rigBypassed: Bool = false + + /// Identities of boards currently in per-board full bypass. Observable so UI toggles refresh; + /// authoritative bypass value lives on each board's `boardBypassNode`. Transient (not persisted). + public private(set) var bypassedBoards: Set = [] + /// Crossfades so only `board` is audible, fading the others out. /// /// Sets every board's crossfade time to `crossfadeSeconds`, then ramps the selected @@ -348,6 +370,50 @@ public final class ShoeGaze { return (board.selectGainNode?.value ?? 0.0) > selectGainOnThreshold } + // MARK: - Full bypass (board / rig) + + /// Fully bypasses or re-engages a single board. When bypassed, the board's dry input passes + /// straight through, skipping every pedal; the board's master volume and select-gain still + /// apply. The transition is a click-free crossfade. Independent of ``setRigBypassed(_:)``. + /// + /// - Parameters: + /// - board: A board managed by this instance. No-op otherwise. + /// - bypassed: `true` to bypass (dry), `false` to re-engage the pedal chain. + public func setBoard(_ board: PedalBoard, bypassed: Bool) { + guard boards.contains(where: { $0 === board }) else { return } + board.boardBypassNode?.update(bypassed ? 1.0 : 0.0) + if bypassed { + bypassedBoards.insert(ObjectIdentifier(board)) + } else { + bypassedBoards.remove(ObjectIdentifier(board)) + } + } + + /// Whether `board` is currently in per-board full bypass. + /// + /// - Parameter board: A board managed by this instance. + /// - Returns: `true` when the board's per-board bypass is engaged. + public func isBoardBypassed(_ board: PedalBoard) -> Bool { + bypassedBoards.contains(ObjectIdentifier(board)) + } + + /// Fully bypasses or re-engages the entire rig — every board passes its dry input straight + /// through at once. Independent of any per-board bypass (either routes a board to dry). The + /// transition is a click-free crossfade on every board. + /// + /// - Parameter bypassed: `true` to bypass the whole rig, `false` to re-engage. + public func setRigBypassed(_ bypassed: Bool) { + for managed: PedalBoard in boards { + managed.rigBypassNode?.update(bypassed ? 1.0 : 0.0) + } + rigBypassed = bypassed + } + + /// Toggles rig-wide full bypass. See ``setRigBypassed(_:)``. + public func toggleRigBypassed() { + setRigBypassed(!rigBypassed) + } + /// Removes a single board and its associated input source and output master from /// the engine, then releases the board's buses. The other boards are unaffected. /// @@ -388,6 +454,7 @@ public final class ShoeGaze { // Remove the pedals and release the board's buses. board.teardown() boards.remove(at: index) + bypassedBoards.remove(ObjectIdentifier(board)) // Keep the soloed-board index valid: clear it if the soloed board was removed, // otherwise shift it down when a board before it was removed. @@ -531,5 +598,11 @@ public final class ShoeGaze { router.teardown() } routers.removeAll() + + // Live performance toggles are transient — a rebuild starts from a clean slate. Board + // identities also change across a rebuild, so the per-board bypass set would be stale. + activeBoardIndex = nil + rigBypassed = false + bypassedBoards.removeAll() } } diff --git a/Sources/LyrebirdShoeGazeUI/BoardBarView.swift b/Sources/LyrebirdShoeGazeUI/BoardBarView.swift index f2c72d9..d2d99c6 100644 --- a/Sources/LyrebirdShoeGazeUI/BoardBarView.swift +++ b/Sources/LyrebirdShoeGazeUI/BoardBarView.swift @@ -162,6 +162,7 @@ public struct BoardBarView: View { let isEditing: Bool = index == editingBoardIndex let isAudible: Bool = shoeGaze.isBoardAudible(board) let isSoloed: Bool = shoeGaze.activeBoardIndex == index + let isBypassed: Bool = shoeGaze.isBoardBypassed(board) VStack(spacing: BoardBarView.cellInnerSpacing) { Text(boardLabel(index: index, board: board)) @@ -175,6 +176,7 @@ public struct BoardBarView: View { HStack(spacing: BoardBarView.cellSpacing) { ledButton(board: board, isAudible: isAudible) soloButton(board: board, isSoloed: isSoloed) + bypassButton(board: board, isBypassed: isBypassed) } levelFader(board: board) @@ -257,6 +259,25 @@ public struct BoardBarView: View { .help("Solo this board (exclusive)") } + /// Full-bypass footswitch — lit when this board is bypassed (dry passthrough, pedals skipped). + private func bypassButton(board: PedalBoard, isBypassed: Bool) -> some View { + Button { + shoeGaze.setBoard(board, bypassed: !isBypassed) + } label: { + Text("B") + .font(.system(size: BoardBarView.nameFontSize, weight: .bold)) + .foregroundStyle(isBypassed ? Color.black : Color.white) + .frame(width: BoardBarView.soloButtonSize, height: BoardBarView.soloButtonSize) + .background( + RoundedRectangle(cornerRadius: 4) + .fill(isBypassed ? Color.orange : Color(white: BoardBarView.ledDimBrightness)) + ) + } + .buttonStyle(.plain) + .help(isBypassed ? "Board bypassed — tap to re-engage the pedals" + : "Bypass this board (dry passthrough)") + } + /// Board master-gain fader. Hidden until the board's output master is connected. @ViewBuilder private func levelFader(board: PedalBoard) -> some View { diff --git a/Sources/LyrebirdShoeGazeUI/BoardFlowView.swift b/Sources/LyrebirdShoeGazeUI/BoardFlowView.swift index bb9e38e..93e7231 100644 --- a/Sources/LyrebirdShoeGazeUI/BoardFlowView.swift +++ b/Sources/LyrebirdShoeGazeUI/BoardFlowView.swift @@ -18,8 +18,8 @@ import LyrebirdShoeGaze /// cached. Region segments are addressed by their index in `board.orderedSegments`. /// /// Interaction: -/// - Drag a palette pedal (`"add:"`) onto a lane to append it there; tap a palette pedal to -/// append to the main chain. +/// - Drag a palette pedal (`"add:"`) onto an existing card to insert it before that card, or +/// onto empty lane space to append there; tap a palette pedal to append to the main chain. /// - Drag a card onto another card in the same lane to reorder; the corner trash removes it. /// - Connector lines render mono (single) or stereo (double) based on the running channel width. /// @@ -393,7 +393,8 @@ public struct BoardFlowView: View { dropTarget = nil guard let payload: String = parse(items) else { return false } if let type: String = payload.afterPrefix("add:") { - append(type: type, lane: .main) + // Dropped a palette pedal ONTO a chain card → insert before that card. + insert(type: type, at: ontoLinear, lane: .main) return true } if let src: Int = payload.afterPrefix("movemain:").flatMap(Int.init) { @@ -426,7 +427,8 @@ public struct BoardFlowView: View { return false } if let type: String = payload.afterPrefix("add:") { - append(type: type, lane: lane) + // Dropped a palette pedal ONTO a branch card → insert before that card. + insert(type: type, at: ontoIndex, lane: lane) return true } // Reorder within the same lane: "movebranch:::". @@ -482,6 +484,12 @@ public struct BoardFlowView: View { catch { print("[BoardFlowView] appendPedal failed: \(error)") } } + private func insert(type: String, at index: Int, lane: PedalLane) { + guard let board: PedalBoard = board else { return } + do { _ = try shoeGaze.insertPedal(PedalType(type), at: index, to: board, lane: lane) } + catch { print("[BoardFlowView] insertPedal failed: \(error)") } + } + private func reorderMain(from source: Int, onto target: Int) { guard source != target, let board: PedalBoard = board else { return } // Convert "dropped ONTO the card at `target`" into movePedal's insert-before `toOffset`: diff --git a/Sources/LyrebirdShoeGazeUI/MIDIIndicatorView.swift b/Sources/LyrebirdShoeGazeUI/MIDIIndicatorView.swift new file mode 100644 index 0000000..25c2df2 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/MIDIIndicatorView.swift @@ -0,0 +1,64 @@ +// MIDIIndicatorView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdShoeGaze + +/// A compact transport-row indicator showing whether a MIDI device is connected. +/// +/// Green when at least one input source is present, gray otherwise; a badge shows the count when +/// more than one device is connected. Tapping invokes `onTap` (the host presents the MIDI mapping +/// sheet). Observes the `@Observable` ``MIDIController`` so it refreshes automatically as devices +/// connect and disconnect. +public struct MIDIIndicatorView: View { + + // MARK: - Constants + + private static let iconSize: CGFloat = 13 + private static let spacing: CGFloat = 3 + private static let badgeFontSize: CGFloat = 10 + private static let disconnectedOpacity: Double = 0.5 + + // MARK: - Inputs + + private let controller: MIDIController + private let onTap: () -> Void + + /// Creates a MIDI connection indicator. + /// + /// - Parameters: + /// - controller: The MIDI controller whose connection state is displayed. + /// - onTap: Invoked when the indicator is tapped (present the MIDI mapping sheet). Defaults to + /// a no-op. + public init(controller: MIDIController, onTap: @escaping () -> Void = {}) { + self.controller = controller + self.onTap = onTap + } + + // MARK: - Body + + public var body: some View { + let connected: Bool = controller.isConnected + return Button(action: onTap) { + HStack(spacing: MIDIIndicatorView.spacing) { + Image(systemName: connected ? "pianokeys" : "pianokeys.inverse") + .font(.system(size: MIDIIndicatorView.iconSize)) + .foregroundStyle(connected + ? Color.green + : Color.white.opacity(MIDIIndicatorView.disconnectedOpacity)) + if controller.connectedDeviceNames.count > 1 { + Text("\(controller.connectedDeviceNames.count)") + .font(.system(size: MIDIIndicatorView.badgeFontSize, weight: .semibold).monospacedDigit()) + .foregroundStyle(Color.green) + } + } + } + .buttonStyle(.plain) + .help(connected + ? "MIDI connected: \(controller.connectedDeviceNames.joined(separator: ", "))" + : "No MIDI device detected") + } +} diff --git a/Sources/LyrebirdShoeGazeUI/MIDIMappingSheet.swift b/Sources/LyrebirdShoeGazeUI/MIDIMappingSheet.swift new file mode 100644 index 0000000..daaa348 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/MIDIMappingSheet.swift @@ -0,0 +1,217 @@ +// MIDIMappingSheet.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdShoeGaze +import LyrebirdUI + +/// The MIDI mapping panel: shows connected devices and lets the user bind expression-pedal CCs to +/// pedal knobs via MIDI Learn. +/// +/// Presented from the transport-row ``MIDIIndicatorView``. Rows are generated by walking the live +/// `ShoeGaze.boards` / `board.pedals` / `pedal.knobs`, so bindings address controls positionally. +/// (The Program-Change switch section is added in a later phase.) +public struct MIDIMappingSheet: View { + + // MARK: - Constants + + private static let sheetMinWidth: CGFloat = 460 + private static let sheetMinHeight: CGFloat = 520 + private static let rowVerticalPadding: CGFloat = 2 + + // MARK: - Inputs + + private let controller: MIDIController + private let shoeGaze: ShoeGaze + + @Environment(\.dismiss) private var dismiss + + /// Creates a MIDI mapping sheet. + /// + /// - Parameters: + /// - controller: The MIDI controller that owns the connection, learn state, and bindings. + /// - shoeGaze: The rig whose boards / pedals / knobs are enumerated as binding targets. + public init(controller: MIDIController, shoeGaze: ShoeGaze) { + self.controller = controller + self.shoeGaze = shoeGaze + } + + // MARK: - Body + + public var body: some View { + NavigationStack { + List { + devicesSection + switchesSection + expressionSection + } + .navigationTitle("MIDI Mapping") + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("Done") { + controller.cancelLearn() + dismiss() + } + } + } + } + .frame(minWidth: MIDIMappingSheet.sheetMinWidth, minHeight: MIDIMappingSheet.sheetMinHeight) + } + + // MARK: - Devices + + private var devicesSection: some View { + Section("Devices") { + if controller.isConnected { + ForEach(controller.connectedDeviceNames, id: \.self) { name in + Label(name, systemImage: "pianokeys") + .foregroundStyle(Color.green) + } + } else { + Label("No MIDI device detected", systemImage: "pianokeys.inverse") + .foregroundStyle(.secondary) + } + } + } + + // MARK: - Switches (Program Change) + + private var switchesSection: some View { + Section("Switches (Program Change)") { + switchRow(action: .rigBypass, label: "Rig Bypass") + ForEach(Array(shoeGaze.boards.enumerated()), id: \.offset) { boardPair in + let boardIndex: Int = boardPair.offset + let board: PedalBoard = boardPair.element + switchRow(action: .boardSolo(boardIndex: boardIndex), label: "\(board.label) · Solo") + switchRow(action: .boardAudible(boardIndex: boardIndex), label: "\(board.label) · Audible") + switchRow(action: .boardBypass(boardIndex: boardIndex), label: "\(board.label) · Bypass") + ForEach(Array(board.pedals.enumerated()), id: \.offset) { pedalPair in + switchRow( + action: .pedalBypass(boardIndex: boardIndex, pedalIndex: pedalPair.offset), + label: "\(board.label) · \(pedalPair.element.displayName) · Bypass" + ) + } + } + } + } + + private func switchRow(action: MIDIMap.Action, label: String) -> some View { + let isArmed: Bool = controller.learnTarget == .action(action) + let binding: MIDIMap.SwitchBinding? = controller.switchBinding(for: action) + return HStack { + VStack(alignment: .leading, spacing: 1) { + Text(label) + Text(switchBindingLabel(isArmed: isArmed, binding: binding)) + .font(.caption) + .foregroundStyle(isArmed ? Color.orange : .secondary) + } + Spacer() + if binding != nil { + Button("Clear") { controller.clearSwitchBinding(for: action) } + .buttonStyle(.borderless) + } + Button(isArmed ? "Cancel" : "Learn") { + if isArmed { + controller.cancelLearn() + } else { + controller.armSwitchLearn(action) + } + } + .buttonStyle(.bordered) + .tint(.orange) + } + .padding(.vertical, MIDIMappingSheet.rowVerticalPadding) + } + + private func switchBindingLabel(isArmed: Bool, binding: MIDIMap.SwitchBinding?) -> String { + if isArmed { return "Listening — press a footswitch…" } + guard let binding: MIDIMap.SwitchBinding = binding else { return "Unassigned" } + let channelText: String = binding.channel.map { " · ch \($0 + 1)" } ?? "" + return "PC \(binding.program)\(channelText)" + } + + // MARK: - Expression (CC) + + private var expressionSection: some View { + Section("Expression (Control Change)") { + if shoeGaze.boards.isEmpty { + Text("Add a pedal to assign expression control.") + .foregroundStyle(.secondary) + } + ForEach(Array(shoeGaze.boards.enumerated()), id: \.offset) { boardPair in + let boardIndex: Int = boardPair.offset + let board: PedalBoard = boardPair.element + ForEach(Array(board.pedals.enumerated()), id: \.offset) { pedalPair in + pedalRows(boardIndex: boardIndex, pedalIndex: pedalPair.offset, pedal: pedalPair.element) + } + } + } + } + + @ViewBuilder + private func pedalRows(boardIndex: Int, pedalIndex: Int, pedal: Pedal) -> some View { + ForEach(Array(pedal.knobs.enumerated()), id: \.offset) { knobPair in + knobRow( + boardIndex: boardIndex, + pedalIndex: pedalIndex, + knobIndex: knobPair.offset, + pedalName: pedal.displayName, + knobLabel: knobPair.element.label + ) + } + } + + private func knobRow( + boardIndex: Int, + pedalIndex: Int, + knobIndex: Int, + pedalName: String, + knobLabel: String + ) -> some View { + let isArmed: Bool = controller.learnTarget == .cc( + boardIndex: boardIndex, pedalIndex: pedalIndex, knobIndex: knobIndex + ) + let binding: MIDIMap.CCBinding? = controller.ccBinding( + boardIndex: boardIndex, pedalIndex: pedalIndex, knobIndex: knobIndex + ) + return HStack { + VStack(alignment: .leading, spacing: 1) { + Text("\(pedalName) · \(knobLabel)") + Text(bindingLabel(isArmed: isArmed, binding: binding)) + .font(.caption) + .foregroundStyle(isArmed ? Color.orange : .secondary) + } + Spacer() + if binding != nil { + Button("Clear") { + controller.clearCCBinding( + boardIndex: boardIndex, pedalIndex: pedalIndex, knobIndex: knobIndex + ) + } + .buttonStyle(.borderless) + } + Button(isArmed ? "Cancel" : "Learn") { + if isArmed { + controller.cancelLearn() + } else { + controller.armCCLearn( + boardIndex: boardIndex, pedalIndex: pedalIndex, knobIndex: knobIndex + ) + } + } + .buttonStyle(.bordered) + .tint(.orange) + } + .padding(.vertical, MIDIMappingSheet.rowVerticalPadding) + } + + private func bindingLabel(isArmed: Bool, binding: MIDIMap.CCBinding?) -> String { + if isArmed { return "Listening — move an expression pedal…" } + guard let binding: MIDIMap.CCBinding = binding else { return "Unassigned" } + let channelText: String = binding.channel.map { " · ch \($0 + 1)" } ?? "" + return "CC \(binding.controller)\(channelText)" + } +} diff --git a/Sources/LyrebirdShoeGazeUI/PedalCategory.swift b/Sources/LyrebirdShoeGazeUI/PedalCategory.swift index b659ea2..0265d4e 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalCategory.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalCategory.swift @@ -42,9 +42,9 @@ enum PedalCategory: String, CaseIterable, Identifiable { } private static let mapping: [String: PedalCategory] = [ - "Overdrive": .gain, "Distortion": .gain, "Fuzz": .gain, + "Overdrive": .gain, "Distortion": .gain, "Fuzz": .gain, "Volume": .gain, "Compressor": .dynamics, "Sustainer": .dynamics, "Limiter": .dynamics, "Noise Gate": .dynamics, - "Graphic EQ": .filter, "Auto-Wah": .filter, "Mutant": .filter, + "Graphic EQ": .filter, "Auto-Wah": .filter, "Wah": .filter, "Mutant": .filter, "Tremolo": .modulation, "Phaser": .modulation, "Modulation": .modulation, "Chorus": .modulation, "Flanger": .modulation, "Vibrato": .modulation, "Rotary": .modulation, "Ring Modulator": .modulation, "Bass Octaver": .pitch, "Octave Splitter": .pitch, "Harmonizer": .pitch, diff --git a/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift b/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift index 1878d83..f8c3dcc 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift @@ -55,8 +55,9 @@ public struct PedalPaletteView: View { /// appended afterwards (sorted) so the palette never silently drops a newly added pedal. private static let preferredOrder: [String] = [ "Overdrive", "Distortion", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz", + "Volume", "Graphic EQ", "Tremolo", "Phaser", "Modulation", "Chorus", "Flanger", "Vibrato", "Rotary", - "Auto-Wah", "Mutant", "Ring Modulator", "Diffuser", "Bitcrusher", "Granulator", + "Auto-Wah", "Wah", "Mutant", "Ring Modulator", "Diffuser", "Bitcrusher", "Granulator", "Auto Granulator", "Bass Octaver", "Octave Splitter", "Harmonizer", "Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverse Delay", "Reverb", "Shimmer Reverb", @@ -123,6 +124,17 @@ public struct PedalPaletteView: View { return orderedPedalNames.filter { PedalCategory.category(for: $0) == filter } } + /// Visible pedals bucketed by category, in the same order the filter menu lists them + /// (`PedalCategory.allCases`). Within a bucket the preferred order is preserved; empty + /// buckets are dropped so the picker shows only categories that have visible pedals. + private var groupedVisiblePedals: [(category: PedalCategory, names: [String])] { + let visible: [String] = visiblePedalNames + return PedalCategory.allCases.compactMap { category in + let names: [String] = visible.filter { PedalCategory.category(for: $0) == category } + return names.isEmpty ? nil : (category, names) + } + } + // MARK: - Body public var body: some View { @@ -159,13 +171,20 @@ public struct PedalPaletteView: View { /// row stacked beneath it. private var horizontalBody: some View { VStack(alignment: .leading, spacing: PedalPaletteView.sectionSpacing) { - HStack(alignment: .top, spacing: PedalPaletteView.rowSpacing) { + HStack(alignment: .top, spacing: PedalPaletteView.sectionSpacing) { VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) { sectionTitle("PEDALS") filterMenu } - ForEach(visiblePedalNames, id: \.self) { name in - pedalRow(name) + ForEach(groupedVisiblePedals, id: \.category) { group in + VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) { + categoryLabel(group.category) + HStack(alignment: .top, spacing: PedalPaletteView.rowSpacing) { + ForEach(group.names, id: \.self) { name in + pedalRow(name) + } + } + } } } HStack(alignment: .top, spacing: PedalPaletteView.rowSpacing) { @@ -185,6 +204,14 @@ public struct PedalPaletteView: View { .foregroundStyle(Color.white.opacity(PedalPaletteView.titleOpacity)) } + /// A per-group header in the horizontal picker — the category name tinted in its accent colour. + private func categoryLabel(_ category: PedalCategory) -> some View { + Text(category.rawValue.uppercased()) + .font(.system(size: PedalPaletteView.titleFontSize, weight: .semibold)) + .foregroundStyle(category.color.opacity(0.9)) + .lineLimit(1) + } + /// "Filter by type" menu — defaults to **All** (no filtering). private var filterMenu: some View { Menu { @@ -201,8 +228,10 @@ public struct PedalPaletteView: View { .font(.system(size: PedalPaletteView.titleFontSize)) .foregroundStyle((filter?.color ?? Color.white).opacity(0.9)) } + #if os(macOS) .menuStyle(.borderlessButton) .fixedSize() + #endif } /// A full-width pedal row: tap appends to the main chain; drag carries `"add:"` so it can diff --git a/Sources/LyrebirdShoeGazeUI/PedalView.swift b/Sources/LyrebirdShoeGazeUI/PedalView.swift index 97b814b..09f3b20 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalView.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalView.swift @@ -28,6 +28,8 @@ private func enclosureColor(for displayName: String) -> Color { case "Compressor": return Color(red: 0.18, green: 0.42, blue: 0.32) // forest green case "Mutant": return Color(red: 0.70, green: 0.12, blue: 0.48) // magenta / plum case "Auto-Wah": return Color(red: 0.80, green: 0.62, blue: 0.10) // gold + case "Wah": return Color(red: 0.72, green: 0.50, blue: 0.06) // amber gold + case "Volume": return Color(red: 0.30, green: 0.30, blue: 0.34) // graphite case "Feedback Delay": return Color(red: 0.48, green: 0.30, blue: 0.14) // tape sepia case "Multi-Tap Delay": return Color(red: 0.08, green: 0.48, blue: 0.68) // cyan case "Reverse Delay": return Color(red: 0.10, green: 0.44, blue: 0.60) // deep cyan-teal diff --git a/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift b/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift index 4d310bb..e73adc0 100644 --- a/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift +++ b/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift @@ -45,6 +45,10 @@ struct RigLibrarySidebarView: View { let onImportArchive: () -> Void let onExportArchive: () -> Void + /// Invoked when the local-only (iCloud-unavailable) status icon is tapped, so the host can + /// explain how to re-enable iCloud sync. Defaults to a no-op. + var onShowCloudStatus: () -> Void = {} + private static let timestampFormat: Date.FormatStyle = Date.FormatStyle(date: .abbreviated, time: .shortened) @@ -69,13 +73,27 @@ struct RigLibrarySidebarView: View { .font(.headline) .foregroundStyle(Color.white) Spacer() - // Cloud icon when the library is iCloud-backed; a slash when local-only. - Image(systemName: store.isICloud ? "icloud" : "icloud.slash") + cloudStatusIcon + } + } + + /// Cloud icon when the library is iCloud-backed; a tappable slash when local-only (tap explains + /// how to re-enable sync). + @ViewBuilder + private var cloudStatusIcon: some View { + if store.isICloud { + Image(systemName: "icloud") .font(.caption) .foregroundStyle(Color.white.opacity(RigLibrarySidebarView.headerOpacity)) - .help(store.isICloud - ? "Synced with iCloud across your devices" - : "iCloud unavailable — rigs are stored on this device only") + .help("Synced with iCloud across your devices") + } else { + Button { onShowCloudStatus() } label: { + Image(systemName: "icloud.slash") + .font(.caption) + .foregroundStyle(Color.white.opacity(RigLibrarySidebarView.headerOpacity)) + } + .buttonStyle(.plain) + .help("iCloud unavailable — tap for details. Rigs are stored on this device only") } } diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index c8f7f56..d5c17a8 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -7,6 +7,9 @@ #if canImport(AppKit) import AppKit #endif +#if canImport(UIKit) +import UIKit +#endif import SwiftUI import UniformTypeIdentifiers import LyrebirdSynth @@ -73,6 +76,10 @@ public struct ShoeGazeBuilderView: View { private let library: RigLibraryStore private let hardwareSampleRate: () -> Double? + /// The MIDI controller for foot-controller input, or `nil` when MIDI is unavailable/disabled. + /// When present, the transport row shows a connection indicator. + private let midi: MIDIController? + /// Host hook to enable live input when the current engine has no input channel (iOS). /// The host requests microphone access and rebuilds the engine with one input channel, /// preserving the rig, then swaps in a new `ShoeGaze`. `nil` on platforms (macOS) whose @@ -91,6 +98,13 @@ public struct ShoeGazeBuilderView: View { /// Shown when live input is selected but microphone access is denied/restricted. @State private var showMicDeniedAlert: Bool = false + /// Presents the "iCloud unavailable" guidance alert (rigs saved locally only). + @State private var showICloudUnavailableAlert: Bool = false + + /// Guards the automatic one-shot iCloud-unavailable alert so it fires at most once per launch + /// (the tappable status icon can still re-present it on demand). + @State private var didCheckICloudStatus: Bool = false + /// Guards the one-time input-source restore in `.onAppear`. @State private var didRestoreInput: Bool = false @@ -136,6 +150,9 @@ public struct ShoeGazeBuilderView: View { /// Archive import state (cross-platform). @State private var showImporter: Bool = false + /// MIDI mapping sheet presentation flag. + @State private var showMIDISheet: Bool = false + #if !os(macOS) /// iOS recording-folder picker presentation flag. (macOS uses the Record menu.) @State private var showRecordingFolderImporter: Bool = false @@ -158,16 +175,20 @@ public struct ShoeGazeBuilderView: View { /// - library: The rig library store. The host should `start()` it (e.g. via /// `RigLibraryBootstrap`); the view shows a loading state until then and highlights the /// persisted current rig once the library has loaded. + /// - midi: The MIDI controller for foot-controller input. When non-`nil`, the transport row + /// shows a connection indicator. Defaults to `nil`. public init( shoeGaze: ShoeGaze, library: RigLibraryStore, hardwareSampleRate: @escaping () -> Double? = { nil }, - onEnableLiveInput: (() -> Void)? = nil + onEnableLiveInput: (() -> Void)? = nil, + midi: MIDIController? = nil ) { self.shoeGaze = shoeGaze self.library = library self.hardwareSampleRate = hardwareSampleRate self.onEnableLiveInput = onEnableLiveInput + self.midi = midi } // MARK: - Body @@ -197,8 +218,15 @@ public struct ShoeGazeBuilderView: View { .onAppear { restoreInputSelection() restoreCurrentRig() + syncIdleTimer() + maybeWarnICloudUnavailable() + } + .onDisappear { releaseIdleTimer() } + .onChange(of: transportTick) { syncIdleTimer() } + .onChange(of: library.isLoaded) { + restoreCurrentRig() + maybeWarnICloudUnavailable() } - .onChange(of: library.isLoaded) { restoreCurrentRig() } .onChange(of: currentRigID) { persistCurrentRigID() } .background(boardsSheetAnchor) .background(rigExportAnchor) @@ -261,9 +289,37 @@ public struct ShoeGazeBuilderView: View { Text("Live input needs microphone access. Enable it in System Settings › Privacy & " + "Security › Microphone, then select the input again.") } + .alert("iCloud Unavailable", isPresented: $showICloudUnavailableAlert) { + Button("OK", role: .cancel) { } + } message: { + Text("Your rigs are saved on this device only. To sync them across your devices, " + + "sign in to iCloud and turn on iCloud Drive in " + + ShoeGazeBuilderView.settingsAppName + + ", then reopen ShoeGaze.") + } #if !os(macOS) .background(recordingFolderImportAnchor) #endif + .sheet(isPresented: $showMIDISheet) { + if let midi: MIDIController = midi { + MIDIMappingSheet(controller: midi, shoeGaze: shoeGaze) + } + } + .overlay(alignment: .top) { midiLearnBanner } + } + + /// A banner shown while a control is armed for MIDI Learn, prompting the user to move it. + @ViewBuilder + private var midiLearnBanner: some View { + if let midi: MIDIController = midi, midi.learnTarget != nil { + Text("MIDI Learn — press a footswitch or move an expression pedal to assign it") + .font(.callout.weight(.semibold)) + .foregroundStyle(Color.black) + .padding(.horizontal, 14) + .padding(.vertical, 8) + .background(Capsule().fill(Color.orange)) + .padding(.top, 6) + } } /// The rig library listing on the far left: every saved rig plus new/save/duplicate/rename/ @@ -281,10 +337,45 @@ public struct ShoeGazeBuilderView: View { onDelete: { entry in deleteEntry(entry) }, onEraseAll: { showEraseAllDialog = true }, onImportArchive: { showImporter = true }, - onExportArchive: { exportArchiveAction() } + onExportArchive: { exportArchiveAction() }, + onShowCloudStatus: { showICloudUnavailableAlert = true } ) } + // MARK: - Sleep / iCloud status + + /// Platform name for the settings app, used in the iCloud guidance alert. + private static let settingsAppName: String = { + #if os(macOS) + return "System Settings" + #else + return "Settings" + #endif + }() + + /// Keeps the device awake while audio is running so a live pedalboard session isn't cut off by + /// auto-lock; the assertion is released as soon as the engine stops. iOS/iPadOS only. + private func syncIdleTimer() { + #if os(iOS) + UIApplication.shared.isIdleTimerDisabled = shoeGaze.engine.isRunning + #endif + } + + /// Clears the keep-awake assertion (view left the screen / app backgrounded). + private func releaseIdleTimer() { + #if os(iOS) + UIApplication.shared.isIdleTimerDisabled = false + #endif + } + + /// Once the library has resolved, warn the user a single time if it fell back to local-only + /// storage (iCloud Drive signed out or disabled). The status icon can re-present on demand. + private func maybeWarnICloudUnavailable() { + guard library.isLoaded, !library.isICloud, !didCheckICloudStatus else { return } + didCheckICloudStatus = true + showICloudUnavailableAlert = true + } + /// The main builder column: transport, IO, the scope-plus-mixer/picker top section, then the /// board canvas. private var builderColumn: some View { @@ -454,6 +545,10 @@ public struct ShoeGazeBuilderView: View { } } Spacer() + if let midi: MIDIController = midi { + MIDIIndicatorView(controller: midi) { showMIDISheet = true } + } + rigBypassButton EngineConfigView( shoeGaze: shoeGaze, hardwareSampleRate: hardwareSampleRate, @@ -462,6 +557,21 @@ public struct ShoeGazeBuilderView: View { } } + /// Global rig bypass — routes every board to its dry input at once (pedals skipped). Lit when + /// engaged. A live performance panic/compare control. + private var rigBypassButton: some View { + let bypassed: Bool = shoeGaze.rigBypassed + return Button { + shoeGaze.toggleRigBypassed() + } label: { + Label(bypassed ? "Rig Bypassed" : "Bypass Rig", systemImage: "power") + .font(.subheadline) + } + .buttonStyle(.bordered) + .tint(bypassed ? .orange : .gray) + .help("Bypass the entire rig — every board passes your dry input straight through") + } + // MARK: - Input + board + save/load row private var ioRow: some View { diff --git a/Tests/LyrebirdShoeGazeTests/BoardEditAPITests.swift b/Tests/LyrebirdShoeGazeTests/BoardEditAPITests.swift index 2ea70a4..c18c898 100644 --- a/Tests/LyrebirdShoeGazeTests/BoardEditAPITests.swift +++ b/Tests/LyrebirdShoeGazeTests/BoardEditAPITests.swift @@ -118,6 +118,168 @@ struct BoardEditAPITests { } } + // MARK: - Insert + + @Test func insertPlacesPedalBeforeTargetAndRenders() throws { + let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay", "Reverb"]) + defer { try? FileManager.default.removeItem(at: url) } + + // Insert before linear index 1 (the Delay) → lands between Overdrive and Delay. + let edited: PedalBoard = try sg.insertPedal(.fuzz, at: 1, to: board) + #expect(names(edited) == ["Overdrive", "Fuzz", "Delay", "Reverb"]) + #expect(sg.boards.count == 1, "insert should not change board count") + + let samples: [Float] = try render(engine, url) + #expect(hasNonSilentOutput(samples), "board should still render after insert") + } + + @Test func insertAtZeroPrependsToChain() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay"]) + defer { try? FileManager.default.removeItem(at: url) } + + let edited: PedalBoard = try sg.insertPedal(.reverb, at: 0, to: board) + #expect(names(edited) == ["Reverb", "Overdrive", "Delay"]) + } + + @Test func insertAtCountAppendsToChain() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay"]) + defer { try? FileManager.default.removeItem(at: url) } + + // index == pedal count → append, matching appendPedal placement. + let edited: PedalBoard = try sg.insertPedal(.reverb, at: 2, to: board) + #expect(names(edited) == ["Overdrive", "Delay", "Reverb"]) + } + + @Test func insertUnknownTypeThrows() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + #expect(throws: ShoeGazeError.unknownPedalType("Nope")) { + try sg.insertPedal(PedalType("Nope"), at: 0, to: board) + } + } + + @Test func insertOutOfRangeThrows() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay"]) + defer { try? FileManager.default.removeItem(at: url) } + + // Past the end (count is 2, so valid inserts are 0...2): index 3 is out of range. + #expect(throws: ShoeGazeError.pedalIndexOutOfRange(index: 3, count: 2)) { + try sg.insertPedal(.reverb, at: 3, to: board) + } + } + + @Test func insertBeforeTrailingRegionStaysInLinearChain() throws { + // Board: [Overdrive, Delay, ]. Inserting at the end of the linear chain must + // land before the split region, not after it. + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay"]) + defer { try? FileManager.default.removeItem(at: url) } + + var live: PedalBoard = try sg.appendStereoSplit(to: board) // segment index 2 + live = try sg.insertPedal(.fuzz, at: 2, to: live, lane: .main) // end of linear chain + + #expect(names(live) == ["Overdrive", "Delay", "Fuzz"], "Fuzz appends to the linear chain") + guard case .stereoSplit = live.captureState().segments.last else { + Issue.record("Stereo split should remain the trailing segment; pedal jumped past it") + return + } + } + + @Test func insertIntoBranchLaneBeforeTarget() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + var live: PedalBoard = try sg.appendStereoSplit(to: board) + live = try sg.appendPedal(.delay, to: live, lane: .left(region: 1)) + live = try sg.appendPedal(.reverb, to: live, lane: .left(region: 1)) + // Left lane is [Delay, Reverb]; insert Fuzz before index 1 → [Delay, Fuzz, Reverb]. + live = try sg.insertPedal(.fuzz, at: 1, to: live, lane: .left(region: 1)) + + #expect(stereoState(live)?.left.map { $0.type } == ["Delay", "Fuzz", "Reverb"], + "Fuzz should land between Delay and Reverb in the left lane") + } + + // MARK: - Full bypass (board / rig) + + @Test func boardBypassTogglesStateAndStillRenders() throws { + let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay"]) + defer { try? FileManager.default.removeItem(at: url) } + + #expect(!sg.isBoardBypassed(board), "board starts engaged") + sg.setBoard(board, bypassed: true) + #expect(sg.isBoardBypassed(board), "board reports bypassed after toggle") + + // Dry passes straight through — the board still produces audio when bypassed. + let samples: [Float] = try render(engine, url) + #expect(hasNonSilentOutput(samples), "bypassed board should pass dry audio") + } + + @Test func boardBypassReengages() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + sg.setBoard(board, bypassed: true) + sg.setBoard(board, bypassed: false) + #expect(!sg.isBoardBypassed(board), "board should re-engage") + } + + @Test func rigBypassTogglesFlagAndRenders() throws { + let (sg, engine, url, _): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay"]) + defer { try? FileManager.default.removeItem(at: url) } + + #expect(!sg.rigBypassed, "rig starts engaged") + sg.toggleRigBypassed() + #expect(sg.rigBypassed, "rig reports bypassed after toggle") + + let samples: [Float] = try render(engine, url) + #expect(hasNonSilentOutput(samples), "bypassed rig should pass dry audio") + + sg.setRigBypassed(false) + #expect(!sg.rigBypassed, "rig should re-engage") + } + + @Test func boardFinalizedWhileRigBypassedComesUpBypassed() throws { + let (sg, _, url, _): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + sg.setRigBypassed(true) + // A board added after the rig is bypassed must not leak processed audio: its rig-bypass + // node should come up engaged. We can at least confirm the new board joins cleanly and the + // rig flag stays set. + let board2: PedalBoard = try sg.addBoard() + try board2.add(DelayPedal()) + try sg.finalizeBoard(board2) + #expect(sg.rigBypassed, "rig stays bypassed after adding a board") + #expect(board2.rigBypassNode?.value == 1.0, "new board comes up rig-bypassed") + } + + @Test func rigRebuildClearsTransientBypass() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay"], numAudioBuses: 256) + defer { try? FileManager.default.removeItem(at: url) } + + sg.setBoard(board, bypassed: true) + sg.setRigBypassed(true) + + // Reconfiguring the engine tears down and rebuilds every board — transient bypass state + // (which is keyed by board identity) must reset rather than linger stale. + try sg.reconfigureEngine(sampleRate: 48_000, inputChannels: 0, outputChannels: 2) + + #expect(!sg.rigBypassed, "rig bypass cleared on rebuild") + #expect(sg.bypassedBoards.isEmpty, "per-board bypass set cleared on rebuild") + } + // MARK: - Branch preservation @Test func editingLinearPedalPreservesStereoSplitRegion() throws { diff --git a/Tests/LyrebirdShoeGazeTests/MIDIControllerCCTests.swift b/Tests/LyrebirdShoeGazeTests/MIDIControllerCCTests.swift new file mode 100644 index 0000000..35f6f09 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/MIDIControllerCCTests.swift @@ -0,0 +1,113 @@ +// MIDIControllerCCTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import LyrebirdSynth +import LyrebirdUI +@testable import LyrebirdShoeGaze + +@MainActor +@Suite("MIDIController CC") +struct MIDIControllerCCTests { + + /// Builds an engine + a one-board rig whose first pedal is a Volume pedal, plus a controller. + private func makeRig() throws -> (MIDIController, ShoeGaze, Pedal, URL) { + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 128) + let sg: ShoeGaze = ShoeGaze(engine: engine) + let board: PedalBoard = try sg.addBoard() + // Add the pedal directly (not via appendPedal, which rebuilds and replaces the board and + // would leave this `board` reference stale). + try board.add(VolumePedal()) + try sg.finalizeBoard(board) + let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg) + return (controller, sg, board.pedals[0], url) + } + + @Test func learnCapturesBindingAndFiresCallback() throws { + let (controller, sg, pedal, url): (MIDIController, ShoeGaze, Pedal, URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + var mapChanged: Bool = false + controller.onMapChanged = { mapChanged = true } + + // Position is knob 0 on a Volume pedal. + controller.armCCLearn(boardIndex: 0, pedalIndex: 0, knobIndex: 0) + controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 64)) + + #expect(controller.learnTarget == nil, "learn should clear after capture") + #expect(mapChanged, "onMapChanged should fire on capture") + let binding: MIDIMap.CCBinding? = controller.ccBinding(boardIndex: 0, pedalIndex: 0, knobIndex: 0) + #expect(binding?.controller == 20) + #expect(binding?.target.pedalNameHint == "Volume") + #expect(binding?.target.knobLabelHint == "Position") + #expect(sg.midiMap?.ccs.count == 1) + _ = pedal + } + + @Test func boundCCDrivesKnobAcrossItsRange() throws { + // `sg` must be retained: MIDIController holds it weakly, so binding it to `_` would let the + // rig deallocate and every message no-op. + let (controller, sg, pedal, url): (MIDIController, ShoeGaze, Pedal, URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + try withExtendedLifetime(sg) { + controller.armCCLearn(boardIndex: 0, pedalIndex: 0, knobIndex: 0) + controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0)) + + let node: UIParamNode = pedal.knobs[0].node // Position, range 0...1 + controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 127)) + #expect(abs(node.value - 1.0) < 1e-9, "CC 127 should map to the knob max") + controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 64)) + #expect(abs(node.value - 64.0 / 127.0) < 1e-9, "CC 64 should map mid-range") + controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0)) + #expect(abs(node.value - 0.0) < 1e-9, "CC 0 should map to the knob min") + } + } + + @Test func unboundCCIsIgnored() throws { + let (controller, sg, pedal, url): (MIDIController, ShoeGaze, Pedal, URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + try withExtendedLifetime(sg) { + let node: UIParamNode = pedal.knobs[0].node + let before: Double = node.value + // No binding learned → an incoming CC must not touch anything. + controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 127)) + #expect(node.value == before) + } + } + + @Test func channelFilterBlocksOtherChannels() throws { + let (controller, sg, pedal, url): (MIDIController, ShoeGaze, Pedal, URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + try withExtendedLifetime(sg) { + // Learn on channel 0 (the binding captures that channel). + controller.armCCLearn(boardIndex: 0, pedalIndex: 0, knobIndex: 0) + controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0)) + + let node: UIParamNode = pedal.knobs[0].node + node.update(0.5) + // A CC on a different channel must not drive the channel-0 binding. + controller.ingestForTesting(.controlChange(channel: 5, controller: 20, value: 127)) + #expect(abs(node.value - 0.5) < 1e-9, "CC on a non-matching channel should be ignored") + } + } + + @Test func clearRemovesBinding() throws { + let (controller, sg, _, url): (MIDIController, ShoeGaze, Pedal, URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + controller.armCCLearn(boardIndex: 0, pedalIndex: 0, knobIndex: 0) + controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0)) + #expect(sg.midiMap?.ccs.isEmpty == false) + + controller.clearCCBinding(boardIndex: 0, pedalIndex: 0, knobIndex: 0) + #expect(controller.ccBinding(boardIndex: 0, pedalIndex: 0, knobIndex: 0) == nil) + #expect(sg.midiMap?.ccs.isEmpty == true) + } +} diff --git a/Tests/LyrebirdShoeGazeTests/MIDIControllerPCTests.swift b/Tests/LyrebirdShoeGazeTests/MIDIControllerPCTests.swift new file mode 100644 index 0000000..cb1201f --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/MIDIControllerPCTests.swift @@ -0,0 +1,151 @@ +// MIDIControllerPCTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import LyrebirdSynth +import LyrebirdUI +@testable import LyrebirdShoeGaze + +@MainActor +@Suite("MIDIController Program Change") +struct MIDIControllerPCTests { + + /// Builds an engine + a rig of `boardCount` boards (each with one Volume pedal) + a controller. + private func makeRig(boardCount: Int = 1) throws -> (MIDIController, ShoeGaze, [PedalBoard], URL) { + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256) + let sg: ShoeGaze = ShoeGaze(engine: engine) + var boards: [PedalBoard] = [] + for index: Int in 0 ..< boardCount { + let board: PedalBoard = try sg.addBoard() + board.label = "Board \(index + 1)" + try board.add(VolumePedal()) + try sg.finalizeBoard(board) + boards.append(board) + } + let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg) + return (controller, sg, boards, url) + } + + @Test func learnCapturesSwitchAndFiresCallback() throws { + let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + try withExtendedLifetime(sg) { + var changed: Bool = false + controller.onMapChanged = { changed = true } + controller.armSwitchLearn(.rigBypass) + controller.ingestForTesting(.programChange(channel: 0, program: 7)) + + #expect(controller.learnTarget == nil) + #expect(changed) + #expect(controller.switchBinding(for: .rigBypass)?.program == 7) + #expect(sg.midiMap?.switches.count == 1) + } + } + + @Test func rigBypassLatchesOnEachPress() throws { + let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + try withExtendedLifetime(sg) { + controller.armSwitchLearn(.rigBypass) + controller.ingestForTesting(.programChange(channel: 0, program: 1)) // learn only + #expect(sg.rigBypassed == false, "learn must not toggle") + + controller.ingestForTesting(.programChange(channel: 0, program: 1)) + #expect(sg.rigBypassed == true, "first press engages") + controller.ingestForTesting(.programChange(channel: 0, program: 1)) + #expect(sg.rigBypassed == false, "second press releases") + } + } + + @Test func pedalBypassLatches() throws { + let (controller, sg, boards, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + try withExtendedLifetime(sg) { + let node: UIParamNode = boards[0].pedals[0].$bypass + controller.armSwitchLearn(.pedalBypass(boardIndex: 0, pedalIndex: 0)) + controller.ingestForTesting(.programChange(channel: 0, program: 5)) // learn + #expect(node.value == 0.0) + controller.ingestForTesting(.programChange(channel: 0, program: 5)) + #expect(abs(node.value - 1.0) < 1e-9, "first press bypasses") + controller.ingestForTesting(.programChange(channel: 0, program: 5)) + #expect(abs(node.value - 0.0) < 1e-9, "second press re-engages") + } + } + + @Test func boardBypassLatches() throws { + let (controller, sg, boards, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + try withExtendedLifetime(sg) { + controller.armSwitchLearn(.boardBypass(boardIndex: 0)) + controller.ingestForTesting(.programChange(channel: 0, program: 3)) // learn + controller.ingestForTesting(.programChange(channel: 0, program: 3)) + #expect(sg.isBoardBypassed(boards[0]) == true) + controller.ingestForTesting(.programChange(channel: 0, program: 3)) + #expect(sg.isBoardBypassed(boards[0]) == false) + } + } + + @Test func boardSoloIsExclusiveRadio() throws { + let (controller, sg, boards, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = + try makeRig(boardCount: 2) + defer { try? FileManager.default.removeItem(at: url) } + + try withExtendedLifetime(sg) { + controller.armSwitchLearn(.boardSolo(boardIndex: 1)) + controller.ingestForTesting(.programChange(channel: 0, program: 2)) // learn + controller.ingestForTesting(.programChange(channel: 0, program: 2)) // solo board 2 + #expect(sg.activeBoardIndex == 1) + #expect(sg.isBoardAudible(boards[1]) == true) + #expect(sg.isBoardAudible(boards[0]) == false) + } + } + + @Test func channelFilterBlocksOtherChannels() throws { + let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + try withExtendedLifetime(sg) { + controller.armSwitchLearn(.rigBypass) + controller.ingestForTesting(.programChange(channel: 0, program: 1)) // learn on ch 0 + controller.ingestForTesting(.programChange(channel: 4, program: 1)) // other channel + #expect(sg.rigBypassed == false, "PC on a non-matching channel should be ignored") + } + } + + @Test func staleOutOfRangeBindingIsIgnored() throws { + let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + try withExtendedLifetime(sg) { + // Bind to a pedal index that doesn't exist; applying it must be a safe no-op. + controller.armSwitchLearn(.pedalBypass(boardIndex: 0, pedalIndex: 9)) + controller.ingestForTesting(.programChange(channel: 0, program: 6)) // learn + controller.ingestForTesting(.programChange(channel: 0, program: 6)) // apply — no crash + #expect(controller.switchBinding(for: .pedalBypass(boardIndex: 0, pedalIndex: 9)) != nil) + } + } + + @Test func reassigningProgramStealsFromPriorAction() throws { + let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + try withExtendedLifetime(sg) { + controller.armSwitchLearn(.rigBypass) + controller.ingestForTesting(.programChange(channel: 0, program: 8)) + controller.armSwitchLearn(.boardBypass(boardIndex: 0)) + controller.ingestForTesting(.programChange(channel: 0, program: 8)) // same PC steals it + + #expect(controller.switchBinding(for: .rigBypass) == nil, "prior action loses the PC") + #expect(controller.switchBinding(for: .boardBypass(boardIndex: 0))?.program == 8) + #expect(sg.midiMap?.switches.count == 1) + } + } +} diff --git a/Tests/LyrebirdShoeGazeTests/MIDIMapCodableTests.swift b/Tests/LyrebirdShoeGazeTests/MIDIMapCodableTests.swift new file mode 100644 index 0000000..ef06072 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/MIDIMapCodableTests.swift @@ -0,0 +1,55 @@ +// MIDIMapCodableTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +@testable import LyrebirdShoeGaze + +@MainActor +@Suite("MIDIMap persistence") +struct MIDIMapCodableTests { + + private func sampleMap() -> MIDIMap { + MIDIMap( + switches: [ + MIDIMap.SwitchBinding(program: 3, channel: 0, action: .rigBypass, displayNameHint: "Rig"), + MIDIMap.SwitchBinding(program: 4, action: .boardSolo(boardIndex: 1), displayNameHint: "Board 2"), + ], + ccs: [ + MIDIMap.CCBinding( + controller: 7, + channel: 0, + target: MIDIMap.CCTarget( + boardIndex: 0, pedalIndex: 1, knobIndex: 0, + pedalNameHint: "Volume", knobLabelHint: "Position" + ) + ), + ] + ) + } + + @Test func mapRoundTrips() throws { + let map: MIDIMap = sampleMap() + let data: Data = try JSONEncoder().encode(map) + let decoded: MIDIMap = try JSONDecoder().decode(MIDIMap.self, from: data) + #expect(decoded == map) + } + + @Test func rigStateEmbedsAndRestoresMap() throws { + let state: ShoeGazeState = ShoeGazeState(boards: [], midiMap: sampleMap()) + let data: Data = try JSONEncoder().encode(state) + let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data) + #expect(decoded.midiMap == sampleMap()) + } + + @Test func oldRigWithoutMapDecodesToNil() throws { + // A rig saved before MIDI mapping existed has no `midiMap` key at all. + let legacyJSON: String = #"{"version":1,"boards":[]}"# + let data: Data = Data(legacyJSON.utf8) + let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data) + #expect(decoded.midiMap == nil, "legacy rig JSON should decode with a nil midiMap") + } +} diff --git a/Tests/LyrebirdShoeGazeTests/VolumePedalTests.swift b/Tests/LyrebirdShoeGazeTests/VolumePedalTests.swift new file mode 100644 index 0000000..33824b3 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/VolumePedalTests.swift @@ -0,0 +1,73 @@ +// VolumePedalTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import LyrebirdSynth +import LyrebirdUI +@testable import LyrebirdShoeGaze + +@MainActor +@Suite("VolumePedal") +struct VolumePedalTests { + + /// Renders a Volume pedal at the given position and returns the stereo output samples. + private func render(position: Double) throws -> [Float] { + let renderDuration: Double = 0.2 + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration) + defer { try? FileManager.default.removeItem(at: url) } + + let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + defer { + engine.busAllocator.releaseAudioBus(srcBus) + engine.busAllocator.releaseAudioBus(dstBus) + } + + let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index) + let pedal: VolumePedal = VolumePedal(inputBus: srcBus.index, outputBus: dstBus.index) + pedal.position = position + let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index) + + try engine.add(source) + try engine.add(pedal, position: NodePosition.after(source)) + try engine.add(master, position: NodePosition.after(pedal)) + try engine.start() + + return readStereoCAF(url: url) + } + + private func rms(_ samples: [Float]) -> Double { + guard !samples.isEmpty else { return 0 } + let sumSquares: Double = samples.reduce(0) { $0 + Double($1) * Double($1) } + return (sumSquares / Double(samples.count)).squareRoot() + } + + @Test func buildsAndProducesNonSilentOutputAtUnity() throws { + let samples: [Float] = try render(position: 1.0) + #expect(!samples.isEmpty) + #expect(hasNonSilentOutput(samples), "VolumePedal at unity produced silence") + } + + @Test func zeroPositionIsSilent() throws { + let samples: [Float] = try render(position: 0.0) + #expect(!hasNonSilentOutput(samples), "VolumePedal at position 0 should be silent") + } + + @Test func positionScalesLevelMonotonically() throws { + let full: Double = rms(try render(position: 1.0)) + let half: Double = rms(try render(position: 0.5)) + let quarter: Double = rms(try render(position: 0.25)) + #expect(full > half, "position 1.0 should be louder than 0.5") + #expect(half > quarter, "position 0.5 should be louder than 0.25") + } + + @Test func exposesPositionKnob() throws { + let pedal: VolumePedal = VolumePedal() + // Effect knob (before the common Mix/Level pair) is Position. + #expect(pedal.effectKnobs.map { $0.label } == ["Position"]) + } +} diff --git a/Tests/LyrebirdShoeGazeTests/WahPedalTests.swift b/Tests/LyrebirdShoeGazeTests/WahPedalTests.swift new file mode 100644 index 0000000..2925d67 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/WahPedalTests.swift @@ -0,0 +1,80 @@ +// WahPedalTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import LyrebirdSynth +import LyrebirdUI +@testable import LyrebirdShoeGaze + +@MainActor +@Suite("WahPedal") +struct WahPedalTests { + + /// Renders a Wah pedal at the given position / resonance and returns the stereo output. + private func render(position: Double, resonance: Double = 3.0) throws -> [Float] { + let renderDuration: Double = 0.2 + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration) + defer { try? FileManager.default.removeItem(at: url) } + + let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + defer { + engine.busAllocator.releaseAudioBus(srcBus) + engine.busAllocator.releaseAudioBus(dstBus) + } + + let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index) + let pedal: WahPedal = WahPedal(inputBus: srcBus.index, outputBus: dstBus.index) + pedal.position = position + pedal.resonance = resonance + let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index) + + try engine.add(source) + try engine.add(pedal, position: NodePosition.after(source)) + try engine.add(master, position: NodePosition.after(pedal)) + try engine.start() + + return readStereoCAF(url: url) + } + + /// Mean absolute difference between two equal-length renders. + private func meanAbsDiff(_ a: [Float], _ b: [Float]) -> Double { + let count: Int = min(a.count, b.count) + guard count > 0 else { return 0 } + var sum: Double = 0 + for i: Int in 0 ..< count { + sum += abs(Double(a[i]) - Double(b[i])) + } + return sum / Double(count) + } + + @Test func buildsAndProducesNonSilentOutput() throws { + let samples: [Float] = try render(position: 0.5) + #expect(!samples.isEmpty) + #expect(hasNonSilentOutput(samples), "WahPedal produced silence") + } + + @Test func differentPositionsProduceDifferentOutput() throws { + let heel: [Float] = try render(position: 0.0) + let toe: [Float] = try render(position: 1.0) + // Sweeping the cutoff must audibly change the filtered signal. + let diff: Double = meanAbsDiff(heel, toe) + #expect(diff > 1e-4, "heel and toe positions produced near-identical output (diff \(diff))") + } + + @Test func resonanceChangesOutput() throws { + let low: [Float] = try render(position: 0.5, resonance: 0.7) + let high: [Float] = try render(position: 0.5, resonance: 8.0) + let diff: Double = meanAbsDiff(low, high) + #expect(diff > 1e-4, "resonance change produced near-identical output (diff \(diff))") + } + + @Test func exposesPositionAndResonanceKnobs() throws { + let pedal: WahPedal = WahPedal() + #expect(pedal.effectKnobs.map { $0.label } == ["Position", "Resonance"]) + } +}