// 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 is recreated against a fresh engine when the engine is rebuilt), /// and started with ``start()``. Handlers fire on Lyrebird's background MIDI queue; this controller /// hops to the main actor before touching any `@MainActor` rig state. /// /// It establishes the Core MIDI connection, publishes device-connection state for the UI indicator, /// and routes incoming messages to the rig: Control Change drives bound pedal controls, and Program /// Change toggles bound pedal / board / rig actions. MIDI Learn arms a control so the next matching /// message binds to it. @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 continuous control awaiting a Control Change (address-only; hints are `nil`). case cc(MIDIMap.CCTarget) /// 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() } // 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. Control Change drives bound controls; Program Change toggles /// bound actions. private func handle(_ message: MIDIMessage) { switch message { case .controlChange(let channel, let controller, let value): if case .cc(let target) = learnTarget { captureCC(controller: controller, channel: channel, target: target) } 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 /// Master-level range for a board fader, mirroring the UI slider. private let boardLevelRange: ClosedRange = 0.0 ... 1.0 /// Arms MIDI Learn for a continuous control: the next incoming Control Change binds to it. Pass /// an address-only target (hints `nil`); hints are captured from the live rig at bind time. public func armCCLearn(_ target: MIDIMap.CCTarget) { learnTarget = .cc(target) } /// Cancels any in-progress Learn. public func cancelLearn() { learnTarget = nil } /// The CC binding currently assigned to a control, or `nil` if unbound. public func ccBinding(for target: MIDIMap.CCTarget) -> MIDIMap.CCBinding? { shoeGaze?.midiMap?.ccs.first { $0.target.addresses(target) } } /// Whether the CC binding on a control is inverted (CC 0 → control max), or `false` if unbound. public func isCCInverted(for target: MIDIMap.CCTarget) -> Bool { ccBinding(for: target)?.inverted ?? false } /// Sets the invert flag on the CC binding assigned to a control. Inverting swaps the sweep so a /// single expression pedal can crossfade — e.g. fade one control down as it moves, another up. public func setCCInverted(for target: MIDIMap.CCTarget, _ inverted: Bool) { guard let shoeGaze: ShoeGaze = shoeGaze, var map: MIDIMap = shoeGaze.midiMap, let index: Int = map.ccs.firstIndex(where: { $0.target.addresses(target) }), map.ccs[index].inverted != inverted else { return } map.ccs[index].inverted = inverted shoeGaze.midiMap = map onMapChanged?() } /// Removes any CC binding assigned to a control. public func clearCCBinding(for target: MIDIMap.CCTarget) { guard let shoeGaze: ShoeGaze = shoeGaze, var map: MIDIMap = shoeGaze.midiMap else { return } let before: Int = map.ccs.count map.ccs.removeAll { $0.target.addresses(target) } guard map.ccs.count != before else { return } shoeGaze.midiMap = map onMapChanged?() } // MARK: - CC handling /// Captures a learned CC binding for the armed control and clears the Learn state. private func captureCC(controller: UInt8, channel: UInt8, target: MIDIMap.CCTarget) { learnTarget = nil guard let shoeGaze: ShoeGaze = shoeGaze else { return } // `rigVolume` is applied via a setter (it has no single node) and is always valid, so it // needs no resolve; pedal/board targets resolve to re-stamp their display-name hints. let hinted: MIDIMap.CCTarget if case .rigVolume = target { hinted = .rigVolume } else { guard let resolved: ResolvedCC = resolveCC(target) else { return } hinted = resolved.hinted } let binding: MIDIMap.CCBinding = MIDIMap.CCBinding( controller: controller, channel: channel, target: hinted ) var map: MIDIMap = shoeGaze.midiMap ?? MIDIMap.empty // One binding per control — re-learning a control replaces its binding. A single CC may // drive MULTIPLE controls on purpose (e.g. map one expression pedal to two board levels and // invert one for a crossfade), so we deliberately do NOT steal by controller number. map.ccs.removeAll { $0.target.addresses(hinted) } map.ccs.append(binding) shoeGaze.midiMap = map onMapChanged?() } /// Applies an incoming CC to the control it is bound to, if any (channel-filtered). 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 } let ccMax: Double = 127.0 var norm: Double = Double(value) / ccMax if binding.inverted { norm = 1.0 - norm } if case .rigVolume = binding.target { shoeGaze.setRigVolume(norm) // rig volume spans [0, 1] directly continue } guard let resolved: ResolvedCC = resolveCC(binding.target) else { continue } let mapped: Double = resolved.range.lowerBound + norm * (resolved.range.upperBound - resolved.range.lowerBound) resolved.node.update(mapped) } } /// A resolved CC target: the live node + range to drive, plus the target re-stamped with the /// current display-name hints (for storing at capture time). private struct ResolvedCC { let node: UIParamNode let range: ClosedRange let hinted: MIDIMap.CCTarget } /// Resolves a CC target to its live node + range, skipping it (returns `nil`) when the positional /// address is out of range or a captured display-name hint no longer matches (stale binding). private func resolveCC(_ target: MIDIMap.CCTarget) -> ResolvedCC? { switch target { case let .pedalControl(pedalID, controlIndex, _, _): guard let pedal: Pedal = pedal(id: pedalID) else { return nil } let controls: [PedalControl] = pedal.ccMappableControls guard controlIndex >= 0, controlIndex < controls.count else { return nil } let control: PedalControl = controls[controlIndex] let hinted: MIDIMap.CCTarget = .pedalControl( pedalID: pedalID, controlIndex: controlIndex, pedalNameHint: pedal.displayName, controlLabelHint: control.label ) return ResolvedCC(node: control.node, range: control.range, hinted: hinted) case let .boardLevel(boardID, _): guard let board: PedalBoard = board(id: boardID), let node: UIParamNode = board.masterGainNode else { return nil } let hinted: MIDIMap.CCTarget = .boardLevel(boardID: boardID, boardLabelHint: board.label) return ResolvedCC(node: node, range: boardLevelRange, hinted: hinted) case .rigVolume: // Applied via `ShoeGaze.setRigVolume` (fans out to every board), not a single node. return nil } } // 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 binding per action — re-learning an action replaces its binding. A single footswitch // (program) may drive MULTIPLE actions on purpose (a "scene": e.g. bypass two pedals, or // solo a board and bypass another, from one press), so we do NOT steal by program number. map.switches.removeAll { $0.action == action } 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) } } /// Executes a toggle action by reading the live rig state and flipping it. Boolean actions latch; /// `boardSolo` is exclusive (radio). Pedals/boards resolve by UUID, so a binding whose target no /// longer exists (removed pedal/board) simply no-ops. private func perform(_ action: MIDIMap.Action) { guard let shoeGaze: ShoeGaze = shoeGaze else { return } switch action { case .rigBypass: shoeGaze.toggleRigBypassed() case .rigMute: shoeGaze.toggleRigMuted() case .allBoards: // One-shot: cancel any solo and bring every board back up. shoeGaze.selectAllBoards(crossfadeSeconds: boardActionCrossfade) case .boardSolo(let boardID): guard let board: PedalBoard = board(id: boardID) else { return } shoeGaze.soloBoard(board, crossfadeSeconds: boardActionCrossfade) case .boardAudible(let boardID): guard let board: PedalBoard = board(id: boardID) else { return } shoeGaze.setBoard(board, audible: !shoeGaze.isBoardAudible(board), crossfadeSeconds: boardActionCrossfade) case .boardBypass(let boardID): guard let board: PedalBoard = board(id: boardID) else { return } shoeGaze.setBoard(board, bypassed: !shoeGaze.isBoardBypassed(board)) case .pedalBypass(let pedalID): guard let pedal: Pedal = pedal(id: pedalID) else { return } let engagedThreshold: Double = 0.5 let node: UIParamNode = pedal.$bypass node.update(node.value < engagedThreshold ? 1.0 : 0.0) case .pedalAction(let pedalID, let kind): guard let pedal: Pedal = pedal(id: pedalID) else { return } performPedalAction(kind, on: pedal) case .tunerToggle: shoeGaze.toggleTunerEngaged() case .tapTempo: shoeGaze.tapTempo() } } /// Dispatches a pedal-specific momentary action. New `PedalActionKind` cases add a /// branch here once the pedal type they target exists. private func performPedalAction(_ kind: MIDIMap.PedalActionKind, on pedal: Pedal) { let toggleThreshold: Double = 0.5 switch kind { case .looperRecordStop: (pedal as? LooperPedal)?.toggleRecordStop() case .looperOverdubToggle: guard let looper: LooperPedal = pedal as? LooperPedal else { return } let node: UIParamNode = looper.$overdubOn node.update(node.value < toggleThreshold ? 1.0 : 0.0) case .looperLoopToggle: guard let looper: LooperPedal = pedal as? LooperPedal else { return } let node: UIParamNode = looper.$loopOn node.update(node.value < toggleThreshold ? 1.0 : 0.0) case .looperReset: (pedal as? LooperPedal)?.resetLoop() } } /// A display-name hint for an action, captured at learn time for the mapping-sheet UI label. /// Not used for resolution (bindings resolve by UUID) — purely a human-readable snapshot. private func hint(for action: MIDIMap.Action) -> String? { switch action { case .rigBypass, .rigMute, .allBoards: return nil case .boardSolo(let boardID), .boardAudible(let boardID), .boardBypass(let boardID): return board(id: boardID)?.label case .pedalBypass(let pedalID), .pedalAction(let pedalID, _): return pedal(id: pedalID)?.displayName case .tunerToggle, .tapTempo: return nil } } /// Resolves a board by its stable id, or `nil` if no board in the rig has that id. private func board(id: UUID) -> PedalBoard? { shoeGaze?.boards.first { $0.id == id } } /// Resolves a pedal by its stable id across all boards' linear pedal chains, or `nil` if no /// pedal in the rig has that id. private func pedal(id: UUID) -> Pedal? { guard let shoeGaze: ShoeGaze = shoeGaze else { return nil } for board: PedalBoard in shoeGaze.boards { if let match: Pedal = board.pedals.first(where: { $0.id == id }) { return match } } return nil } // 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 } }