5987ec7b78
Input mute: a hard gate on the signal feeding every board (guitar / mic), distinct from the rig-output mute. Each board input writer (TestLoopTap / HardwareInputPassThrough) gains a lagged @UIParam mute gain; ShoeGaze holds inputMuted (default true), drives every input node, and brings newly-added boards up at the current state. A deliberate user Start re-asserts the mute so a fresh engine is silent until the player un-mutes — cutting accidental noise. Toggle sits beside the Start/Stop transport and is MIDI mappable (MIDIMap.Action.inputMute). First launch now defaults to live In 0 instead of the test-loop arpeggio. I/O persistence: the engine's input/output channel counts now persist to UserDefaults (written by EngineConfigView, restored by the app targets at engine construction), so a multi-channel setup survives relaunch and a saved live-input channel stays valid — fixing the input selection reverting to the test loop after a restart. Tests: InputMuteTests (default-muted, node driving, per-board adoption, live path) + a MIDI PC input-mute latch test. StereoRouting render tests un-mute before rendering. 460 tests pass. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
312 lines
13 KiB
Swift
312 lines
13 KiB
Swift
// MIDIMap.swift
|
||
// Lyrebird
|
||
//
|
||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||
// SPDX-License-Identifier: MIT
|
||
|
||
import Foundation
|
||
|
||
/// 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. Pedals and
|
||
/// boards are addressed by **stable UUID** (`Pedal.id` / `PedalBoard.id`, persisted in
|
||
/// `PedalState`/`BoardState`), so a binding follows its pedal/board through insert, remove, move,
|
||
/// and reorder edits with no reindexing — the id survives the capture → rebuild round-trip. A
|
||
/// binding whose target no longer exists simply stops resolving (inert). The `*Hint` fields carry
|
||
/// the display name at learn time, for UI labels only (not resolution). Control-within-pedal is
|
||
/// still indexed into `Pedal.ccMappableControls`, which is stable for a given pedal type.
|
||
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]
|
||
|
||
/// Computer letter/digit key → action bindings. Same toggle ``Action`` set as ``switches`` —
|
||
/// a key press is a software footswitch — but keys never drive continuous CC targets.
|
||
public var keys: [KeyBinding]
|
||
|
||
/// 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.
|
||
/// - keys: Letter-key bindings. Defaults to empty.
|
||
public init(
|
||
switches: [SwitchBinding] = [],
|
||
ccs: [CCBinding] = [],
|
||
keys: [KeyBinding] = []
|
||
) {
|
||
self.switches = switches
|
||
self.ccs = ccs
|
||
self.keys = keys
|
||
}
|
||
|
||
private enum CodingKeys: String, CodingKey {
|
||
case switches
|
||
case ccs
|
||
case keys
|
||
}
|
||
|
||
/// Decodes a map, tolerating an absent `keys` list so a rig saved before keyboard mapping
|
||
/// existed still decodes with its `switches` / `ccs` intact (synthesized Codable would fail
|
||
/// the whole map on the missing key, silently dropping the MIDI bindings too). `encode(to:)`
|
||
/// stays synthesized and always writes `keys` (empty when there are none).
|
||
public init(from decoder: Decoder) throws {
|
||
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
|
||
self.switches = try container.decode([SwitchBinding].self, forKey: .switches)
|
||
self.ccs = try container.decode([CCBinding].self, forKey: .ccs)
|
||
self.keys = try container.decodeIfPresent([KeyBinding].self, forKey: .keys) ?? []
|
||
}
|
||
|
||
// 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
|
||
/// Mutes/unmutes the rig output (a hard silence, not a bypass).
|
||
case rigMute
|
||
/// Mutes/unmutes the input feeding every board (the incoming guitar / mic signal).
|
||
case inputMute
|
||
/// Cancels any solo and makes every board audible again (the "All" button).
|
||
case allBoards
|
||
case boardSolo(boardID: UUID)
|
||
case boardAudible(boardID: UUID)
|
||
case boardBypass(boardID: UUID)
|
||
case pedalBypass(pedalID: UUID)
|
||
/// A pedal-specific momentary action beyond generic bypass (e.g. a looper's
|
||
/// record/stop or reset footswitch). `kind` is opaque to `MIDIMap` — `MIDIController`
|
||
/// resolves the target pedal (by id) and dispatches on `kind` itself.
|
||
case pedalAction(pedalID: UUID, kind: PedalActionKind)
|
||
/// Toggles the rig-level tuner on/off.
|
||
case tunerToggle
|
||
/// Registers one tap-tempo press (see `ShoeGaze.tapTempo()`).
|
||
case tapTempo
|
||
}
|
||
|
||
/// A pedal-specific momentary action addressable by ``Action/pedalAction(pedalID:kind:)``.
|
||
/// New pedals with more than a simple bypass toggle add cases here.
|
||
public enum PedalActionKind: Codable, Equatable, Sendable {
|
||
/// Looper: presses the smart Loop footswitch (record → set end → overdub → play by
|
||
/// state) — same as ``looperOverdubToggle``; both dispatch to `LooperPedal.pressLoop()`.
|
||
// TODO: collapse looperRecordStop / looperOverdubToggle into one case (both call pressLoop).
|
||
case looperRecordStop
|
||
/// Looper: presses the smart Loop footswitch (toggles overdub once a loop is playing).
|
||
case looperOverdubToggle
|
||
/// Looper: flips `loopOn` (loop mute) between `0` and `1`.
|
||
case looperLoopToggle
|
||
/// Looper: reset — clears all tracks and returns to the clear state.
|
||
case looperReset
|
||
/// Looper: immediately stops playback (`LooperPedal.stopPlayback()`).
|
||
case looperStop
|
||
/// Looper: arms / cancels a stop at the loop end (`LooperPedal.toggleStopAtLoopEnd()`).
|
||
case looperCueStop
|
||
/// Looper: flips playback direction (`LooperPedal.toggleReverse()`).
|
||
case looperReverse
|
||
/// Looper: cycles the Sync/Free transport mode (`LooperPedal.cycleSyncMode()`).
|
||
case looperSyncToggle
|
||
/// Looper: taps track `index` (0 = A) — selects it, or mutes it if already selected and
|
||
/// recorded (`LooperPedal.tapTrack(_:)`), matching the A/B/C/D dots.
|
||
case looperTrack(index: 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: - Key modifiers
|
||
|
||
/// The modifier keys that qualify a ``KeyBinding``, so `a` and `⇧a` (and `⌃a`, `⌥a`) are
|
||
/// distinct triggers. Shift is a modifier here rather than being folded into the key's case,
|
||
/// which keeps the base key a single lowercased character on every platform. Command is
|
||
/// deliberately absent — it is reserved for the app's menu keyboard shortcuts.
|
||
public struct KeyModifiers: OptionSet, Codable, Equatable, Hashable, Sendable {
|
||
|
||
public let rawValue: Int
|
||
|
||
public init(rawValue: Int) {
|
||
self.rawValue = rawValue
|
||
}
|
||
|
||
/// The Shift key (`⇧`).
|
||
public static let shift: KeyModifiers = KeyModifiers(rawValue: 1 << 0)
|
||
/// The Control key (`⌃`).
|
||
public static let control: KeyModifiers = KeyModifiers(rawValue: 1 << 1)
|
||
/// The Option key (`⌥`).
|
||
public static let option: KeyModifiers = KeyModifiers(rawValue: 1 << 2)
|
||
}
|
||
|
||
// MARK: - Key binding
|
||
|
||
/// A computer letter/digit key bound to a toggle ``Action``. Fires on key-down when no text
|
||
/// field is focused; the same latch semantics as a footswitch (booleans flip in software,
|
||
/// `boardSolo` is exclusive). `key` is a single lowercased character; ``modifiers`` distinguish
|
||
/// `a` from `⇧a`, `⌃a`, and `⌥a`.
|
||
public struct KeyBinding: Codable, Equatable, Sendable {
|
||
|
||
/// The bound key as a single lowercased character (e.g. `"b"`, `"3"`).
|
||
public var key: String
|
||
|
||
/// The modifier keys held with ``key``. Empty for an unmodified press.
|
||
public var modifiers: KeyModifiers
|
||
|
||
/// 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 key binding.
|
||
///
|
||
/// - Parameters:
|
||
/// - key: The bound key, normalized to a single lowercased character.
|
||
/// - modifiers: The qualifying modifier keys. Defaults to none.
|
||
/// - action: The toggle action to perform.
|
||
/// - displayNameHint: Resolved control name at learn time. Defaults to `nil`.
|
||
public init(
|
||
key: String,
|
||
modifiers: KeyModifiers = [],
|
||
action: Action,
|
||
displayNameHint: String? = nil
|
||
) {
|
||
self.key = key
|
||
self.modifiers = modifiers
|
||
self.action = action
|
||
self.displayNameHint = displayNameHint
|
||
}
|
||
|
||
private enum CodingKeys: String, CodingKey {
|
||
case key
|
||
case modifiers
|
||
case action
|
||
case displayNameHint
|
||
}
|
||
|
||
/// Decodes a key binding, defaulting `modifiers` to none when absent so a binding saved
|
||
/// before modifiers existed still decodes (unmodified, as it was learned). `encode(to:)`
|
||
/// stays synthesized.
|
||
public init(from decoder: Decoder) throws {
|
||
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
|
||
self.key = try container.decode(String.self, forKey: .key)
|
||
self.modifiers = try container.decodeIfPresent(KeyModifiers.self, forKey: .modifiers) ?? []
|
||
self.action = try container.decode(Action.self, forKey: .action)
|
||
self.displayNameHint = try container.decodeIfPresent(String.self, forKey: .displayNameHint)
|
||
}
|
||
}
|
||
|
||
// MARK: - CC target
|
||
|
||
/// A continuous control an expression pedal can drive — either a specific pedal control (a knob
|
||
/// or slider, addressed by index into the pedal's ``Pedal/ccMappableControls``) or a board's
|
||
/// master level. The `*Hint` payloads capture the resolved display name at learn time so a
|
||
/// binding that no longer matches (chain edited) can be detected and skipped.
|
||
public enum CCTarget: Codable, Equatable, Sendable {
|
||
|
||
/// A knob or slider on a pedal, indexed into `pedal.ccMappableControls`.
|
||
case pedalControl(
|
||
pedalID: UUID,
|
||
controlIndex: Int,
|
||
pedalNameHint: String?,
|
||
controlLabelHint: String?
|
||
)
|
||
|
||
/// A board's master output level (the board fader).
|
||
case boardLevel(boardID: UUID, boardLabelHint: String?)
|
||
|
||
/// The rig-wide output volume (applies to the whole rig).
|
||
case rigVolume
|
||
|
||
/// Whether two targets address the same control, ignoring the display-name hints (used to
|
||
/// find and replace a binding regardless of the name captured at learn time).
|
||
public func addresses(_ other: CCTarget) -> Bool {
|
||
switch (self, other) {
|
||
case let (.pedalControl(p1, c1, _, _), .pedalControl(p2, c2, _, _)):
|
||
return p1 == p2 && c1 == c2
|
||
case let (.boardLevel(b1, _), .boardLevel(b2, _)):
|
||
return b1 == b2
|
||
case (.rigVolume, .rigVolume):
|
||
return true
|
||
default:
|
||
return false
|
||
}
|
||
}
|
||
}
|
||
|
||
// 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
|
||
}
|
||
}
|
||
}
|