// 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 } }