Repository Public
1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXMIDI/MIDIMappingEngine.swift3// Description: Pure mapping logic: (message, device, profile, current values) -> target events. No CoreMIDI.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai78import Foundation910/// Turns incoming messages into target events according to a profile.11///12/// Pure value type with no CoreMIDI dependency. It carries a little per-mapping state (soft-takeover13/// pickup, button edges, relative accumulators), so keep one engine per profile and feed it every message.14///15/// Conventions:16/// - **Absolute**: 7-bit values map `0 -> 0`, `64 -> 0.5`, `127 -> 1` (centre-corrected so a centre detent17/// lands exactly on 0.5); 14-bit pitch bend maps `0 -> 0`, `8192 -> 0.5`, `16383 -> 1`. The result is18/// mirrored when `invert` is set, then scaled to `minValue...maxValue`. A note sends its velocity on19/// note-on and the low end of the range on note-off.20/// - **Relative** (CC only): `new = clamp(current + steps * sensitivity / 127)` inside the min/max range.21/// `current` comes from the current-value closure; when it returns `nil` the engine uses the last value22/// it emitted for that mapping (starting from `minValue`).23/// - **Buttons** (toggle, trigger, momentary): a note-on is a press and a note-off a release; a CC is a24/// press when its value becomes non-zero and a release when it returns to 0 (edge-detected, so a25/// pressure-sensitive pad sending many non-zero values fires once).26/// - **Soft takeover** (absolute CC / pitch bend): nothing is emitted until the hardware value is within27/// two 7-bit steps of the software value or crosses it. Once picked up, the control stays live until28/// `resetSoftTakeover` is called (the app should call it when the target changes behind the control's29/// back: track load, deck switch, on-screen drag).30public struct MIDIMappingEngine: Sendable {31 private struct State: Sendable {32 var pickedUp = false33 var lastHardware = Double.nan34 var pressed = false35 var accumulator = Double.nan36 }3738 public private(set) var profile: MIDIMappingProfile?39 private var index: [MIDIControlID: [Int]] = [:]40 private var states: [State] = []4142 public init(profile: MIDIMappingProfile? = nil) {43 self.profile = profile44 guard let profile else { return }45 states = Array(repeating: State(), count: profile.mappings.count)46 for (i, mapping) in profile.mappings.enumerated() {47 index[mapping.control, default: []].append(i)48 }49 }5051 /// Forgets soft-takeover pickup for one target, or for every mapping when `target` is `nil`.52 public mutating func resetSoftTakeover(target: String? = nil) {53 guard let profile else { return }54 for i in states.indices where target == nil || profile.mappings[i].target == target {55 states[i].pickedUp = false56 states[i].lastHardware = .nan57 }58 }5960 /// Convenience wrapper returning the events as an array (empty when nothing is mapped: no allocation).61 public mutating func process(62 _ message: MIDIMessage,63 deviceUniqueID: Int32?,64 currentValue: (String) -> Double? = { _ in nil }65 ) -> [MIDITargetEvent] {66 var out: [MIDITargetEvent] = []67 process(message, deviceUniqueID: deviceUniqueID, currentValue: currentValue) { out.append($0) }68 return out69 }7071 /// Runs one message through the profile and calls `emit` for each resulting event, in mapping order.72 ///73 /// - Parameters:74 /// - deviceUniqueID: the device the message came from; `nil` only matches any-device mappings.75 /// - currentValue: current normalised value of a target, or `nil` if unknown. Called only for76 /// relative mappings and for soft-takeover mappings that have not picked up yet.77 public mutating func process(78 _ message: MIDIMessage,79 deviceUniqueID: Int32?,80 currentValue: (String) -> Double?,81 emit: (MIDITargetEvent) -> Void82 ) {83 guard let profile,84 let control = MIDIControlID(message: message),85 let indices = index[control] else { return }86 for i in indices {87 let mapping = profile.mappings[i]88 if let wanted = mapping.deviceUniqueID, wanted != deviceUniqueID { continue }89 switch mapping.mode {90 case .absolute:91 absolute(message, mapping, &states[i], currentValue, emit)92 case .relative:93 relative(message, mapping, &states[i], currentValue, emit)94 case .toggle, .trigger, .momentary:95 button(message, mapping, &states[i], emit)96 }97 }98 }99100 // MARK: Normalisation101102 /// 7-bit position to `0...1` with 64 exactly at 0.5.103 public static func normalize7(_ value: UInt8) -> Double {104 let v = Double(value & 0x7F)105 return v <= 64 ? v / 128 : 0.5 + (v - 64) / 126106 }107108 /// 14-bit position to `0...1` with 8192 exactly at 0.5.109 public static func normalize14(_ value: UInt16) -> Double {110 let v = Double(value & 0x3FFF)111 return v <= 8192 ? v / 16384 : 0.5 + (v - 8192) / 16382112 }113114 // MARK: Modes115116 private func absolute(117 _ message: MIDIMessage,118 _ mapping: MIDIMapping,119 _ state: inout State,120 _ currentValue: (String) -> Double?,121 _ emit: (MIDITargetEvent) -> Void122 ) {123 var x: Double124 var continuous = true125 switch message {126 case .controlChange(_, _, let v): x = Self.normalize7(v)127 case .pitchBend(_, let v): x = Self.normalize14(v)128 case .noteOn(_, _, let v): x = Self.normalize7(v); continuous = false129 case .noteOff: x = 0; continuous = false130 case .programChange: return131 }132 if mapping.invert { x = 1 - x }133 let value = mapping.minValue + (mapping.maxValue - mapping.minValue) * x134 guard value.isFinite else { return }135136 if mapping.softTakeover && continuous && !state.pickedUp {137 if let software = currentValue(mapping.target), software.isFinite {138 let lo = min(mapping.minValue, mapping.maxValue)139 let hi = max(mapping.minValue, mapping.maxValue)140 let s = min(max(software, lo), hi)141 let tolerance = max((hi - lo) * 2 / 127, 1e-9)142 let near = abs(value - s) <= tolerance143 let crossed = !state.lastHardware.isNaN && (state.lastHardware - s) * (value - s) <= 0144 if !(near || crossed) {145 state.lastHardware = value146 return147 }148 }149 state.pickedUp = true150 }151 state.lastHardware = value152 emit(.value(target: mapping.target, normalized: value))153 }154155 private func relative(156 _ message: MIDIMessage,157 _ mapping: MIDIMapping,158 _ state: inout State,159 _ currentValue: (String) -> Double?,160 _ emit: (MIDITargetEvent) -> Void161 ) {162 guard case .controlChange(_, _, let raw) = message else { return }163 var steps = mapping.relativeEncoding.delta(for: raw)164 if mapping.invert { steps = -steps }165 guard steps != 0, mapping.sensitivity.isFinite else { return }166 let lo = min(mapping.minValue, mapping.maxValue)167 let hi = max(mapping.minValue, mapping.maxValue)168 guard lo.isFinite, hi.isFinite else { return }169 var base = state.accumulator.isNaN ? mapping.minValue : state.accumulator170 if let software = currentValue(mapping.target), software.isFinite { base = software }171 let value = min(max(base + Double(steps) * mapping.sensitivity / 127, lo), hi)172 state.accumulator = value173 emit(.value(target: mapping.target, normalized: value))174 }175176 private func button(177 _ message: MIDIMessage,178 _ mapping: MIDIMapping,179 _ state: inout State,180 _ emit: (MIDITargetEvent) -> Void181 ) {182 var pressed: Bool183 let isEdge: Bool184 switch message {185 case .noteOn: pressed = true186 case .noteOff: pressed = false187 case .controlChange(_, _, let v): pressed = v > 0188 case .pitchBend, .programChange: return189 }190 if mapping.invert { pressed.toggle() }191 if case .controlChange = message {192 isEdge = pressed != state.pressed193 } else {194 isEdge = true // every note message is an event of its own195 }196 state.pressed = pressed197 guard isEdge else { return }198 switch mapping.mode {199 case .trigger:200 if pressed { emit(.trigger(target: mapping.target)) }201 case .toggle:202 if pressed { emit(.toggle(target: mapping.target)) }203 case .momentary:204 emit(.momentary(target: mapping.target, pressed: pressed))205 case .absolute, .relative:206 break207 }208 }209}210