4d8464282e
Each CC binding gains an "Invert" toggle in the mapping sheet (shown once the control is bound). Inverting swaps the sweep — CC 0 drives the control to its max, 127 to its min — so a single expression pedal can crossfade two controls: map both to the same CC and invert one. The MIDICCBinding.inverted field and applyCC already honored inversion; this adds isCCInverted / setCCInverted plus the sheet toggle, and the binding label now notes "· inverted". Test: an inverted binding reverses the mapped output. 321 green; both app targets build. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
418 lines
18 KiB
Swift
418 lines
18 KiB
Swift
// 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<Double> = 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,
|
|
let resolved: ResolvedCC = resolveCC(target) else { return }
|
|
|
|
let binding: MIDIMap.CCBinding = MIDIMap.CCBinding(
|
|
controller: controller,
|
|
channel: channel,
|
|
target: resolved.hinted
|
|
)
|
|
var map: MIDIMap = shoeGaze.midiMap ?? MIDIMap.empty
|
|
// One control → one CC, and reassigning a CC (same controller + channel) steals it from any
|
|
// other control so a given expression pedal drives exactly one thing.
|
|
map.ccs.removeAll {
|
|
$0.target.addresses(resolved.hinted) || ($0.controller == controller && $0.channel == channel)
|
|
}
|
|
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 }
|
|
guard let resolved: ResolvedCC = resolveCC(binding.target) else { continue }
|
|
let ccMax: Double = 127.0
|
|
var norm: Double = Double(value) / ccMax
|
|
if binding.inverted { norm = 1.0 - norm }
|
|
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<Double>
|
|
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(boardIndex, pedalIndex, controlIndex, nameHint, labelHint):
|
|
guard let pedal: Pedal = pedal(boardIndex: boardIndex, pedalIndex: pedalIndex),
|
|
controlIndex >= 0, controlIndex < pedal.ccMappableControls.count else { return nil }
|
|
let control: PedalControl = pedal.ccMappableControls[controlIndex]
|
|
if let nameHint: String = nameHint, nameHint != pedal.displayName { return nil }
|
|
if let labelHint: String = labelHint, labelHint != control.label { return nil }
|
|
let hinted: MIDIMap.CCTarget = .pedalControl(
|
|
boardIndex: boardIndex,
|
|
pedalIndex: pedalIndex,
|
|
controlIndex: controlIndex,
|
|
pedalNameHint: pedal.displayName,
|
|
controlLabelHint: control.label
|
|
)
|
|
return ResolvedCC(node: control.node, range: control.range, hinted: hinted)
|
|
case let .boardLevel(boardIndex, labelHint):
|
|
guard let board: PedalBoard = board(at: boardIndex),
|
|
let node: UIParamNode = board.masterGainNode else { return nil }
|
|
if let labelHint: String = labelHint, labelHint != board.label { return nil }
|
|
let hinted: MIDIMap.CCTarget = .boardLevel(boardIndex: boardIndex, boardLabelHint: board.label)
|
|
return ResolvedCC(node: node, range: boardLevelRange, hinted: hinted)
|
|
}
|
|
}
|
|
|
|
// 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 .allBoards:
|
|
// One-shot: cancel any solo and bring every board back up.
|
|
shoeGaze.selectAllBoards(crossfadeSeconds: boardActionCrossfade)
|
|
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, .allBoards:
|
|
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
|
|
}
|
|
}
|