SPB Git

Repository Public

MIDIManager.swift 35.4 KB 837 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX DJ9// File             : Packages/ORIXDJCore/Sources/ORIXMIDI/MIDIManager.swift10// Description      : CoreMIDI front end: device discovery and hot-plug, input,11//                    mapping dispatch, MIDI learn, output.12// Module           : ORIXMIDI13// Repository       : https://git.spboucher.ai/orix-dj14// Created          : 2026-11-2115// Last Modified    : 2026-11-2116//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author           : Simon-Pierre Boucher22// Position         : Professor of Finance23// Institution      : Université du Québec en Outaouais (UQO)24// Department       : Département des sciences administratives25// Organization     : SP Boucher26//27// Website          : https://spboucher.ai28// Git              : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General          : info@spboucher.ai35// Professional     : contact@spboucher.ai36// Direct           : simon@spboucher.ai37// Research         : research@spboucher.ai38// Development      : dev@spboucher.ai39// Support          : support@spboucher.ai40// Security/Admin   : admin@spboucher.ai41// Notifications    : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification   : Public68// Distribution     : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License          : None specified (no license file in this repository)82// Maintainer       : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import CoreMIDI90import Foundation9192// MARK: - Supporting types9394public enum MIDIError: Error, Sendable, Equatable {95    /// `start()` has not been called (or `stop()` was).96    case notStarted97    case destinationNotFound(uniqueID: Int32)98    /// A CoreMIDI call failed. `operation` names the call; `status` is the OSStatus.99    case coreMIDI(operation: String, status: Int32)100}101102/// Counters for a status display. Cheap to read from any thread.103public struct MIDIStatistics: Sendable, Equatable {104    /// Supported channel voice messages received and delivered.105    public var messagesReceived: UInt64 = 0106    /// Incoming events that were not delivered: unsupported types (SysEx, system common/real-time,107    /// aftertouch, MIDI 2.0 words) and events from a source that was being disconnected.108    public var messagesDropped: UInt64 = 0109    /// Target events produced by the active profile.110    public var targetEventsEmitted: UInt64 = 0111    /// Host time (`mach_absolute_time` units) of the last delivered message; `nil` if none yet.112    public var lastMessageHostTime: UInt64?113114    public init() {}115}116117/// Result of a MIDI learn session.118public struct MIDILearnResult: Sendable, Equatable {119    public var control: MIDIControlID120    public var device: MIDIDeviceInfo121    /// Messages seen from this control during the session.122    public var messageCount: Int123    /// Lowest and highest raw values seen (7-bit, or 14-bit for pitch bend; velocity for a note).124    /// A CC that only ever sent values such as 1/127 or 63/65 is probably a relative encoder.125    public var minRawValue: UInt16126    public var maxRawValue: UInt16127}128129/// A minimal unfair lock. Held only for a few field copies, including on the CoreMIDI thread.130final class UnfairLock: @unchecked Sendable {131    private let pointer: os_unfair_lock_t132133    init() {134        pointer = .allocate(capacity: 1)135        pointer.initialize(to: os_unfair_lock())136    }137138    deinit {139        pointer.deinitialize(count: 1)140        pointer.deallocate()141    }142143    @inline(__always) func lock() { os_unfair_lock_lock(pointer) }144    @inline(__always) func unlock() { os_unfair_lock_unlock(pointer) }145146    @inline(__always) func withLock<T>(_ body: () throws -> T) rethrows -> T {147        os_unfair_lock_lock(pointer)148        defer { os_unfair_lock_unlock(pointer) }149        return try body()150    }151}152153/// The thread CoreMIDI clients are created on.154///155/// CoreMIDI delivers setup-change notifications, and refreshes the process's own view of the device156/// list, on the run loop of the thread that created the **first** MIDI client of the process (measured157/// on macOS 27: with no run loop there, `MIDIGetNumberOfSources()` never changes and no notification158/// arrives, even with the block-based client API). Rather than depend on the main run loop, the engine159/// creates its clients on this private thread, which does nothing but run its run loop.160final class MIDIRunLoopThread: @unchecked Sendable {161    static let shared = MIDIRunLoopThread()162163    private let runLoop: CFRunLoop164    private let thread: Thread165166    private init() {167        final class Box: @unchecked Sendable { var runLoop: CFRunLoop? }168        let box = Box()169        let ready = DispatchSemaphore(value: 0)170        let thread = Thread {171            box.runLoop = CFRunLoopGetCurrent()172            // A port keeps the run loop alive when CoreMIDI has not installed its source yet.173            RunLoop.current.add(Port(), forMode: .default)174            ready.signal()175            while true { RunLoop.current.run() }176        }177        thread.name = "ai.spboucher.orixdj.midi.runloop"178        thread.qualityOfService = .userInitiated179        thread.start()180        ready.wait()181        self.thread = thread182        // Set before `ready` was signalled.183        runLoop = box.runLoop ?? CFRunLoopGetMain()184    }185186    /// Runs `body` on the run-loop thread, waits for it and returns its status.187    func sync(_ body: () -> OSStatus) -> OSStatus {188        if Thread.current === thread { return body() }189        return withoutActuallyEscaping(body) { escapable in190            // The block scheduled on the run loop outlives this call by a moment (the run loop releases it after it191            // returns), so it must not own the closure: it owns a box that is emptied before the caller is woken.192            final class WorkBox: @unchecked Sendable { var work: (() -> OSStatus)?; var value: OSStatus = 0 }193            let box = WorkBox()194            box.work = escapable195            let done = DispatchSemaphore(value: 0)196            CFRunLoopPerformBlock(runLoop, CFRunLoopMode.defaultMode.rawValue) {197                box.value = box.work?() ?? 0198                box.work = nil199                done.signal()200            }201            CFRunLoopWakeUp(runLoop)202            done.wait()203            return box.value204        }205    }206}207208// MARK: - MIDIManager209210/// Owns the CoreMIDI client: lists devices, follows hot-plug, receives from every source (or a chosen211/// subset), runs messages through the active mapping profile, implements MIDI learn and sends feedback.212///213/// ## Why the event-list (UMP) API214/// Input uses `MIDIInputPortCreateWithProtocol(..., ._1_0, ...)` and output `MIDISendEventList`, the215/// non-deprecated API since macOS 11 (the packet-list calls `MIDIInputPortCreateWithBlock`, `MIDISend`216/// and `MIDIReceived` are deprecated). With the MIDI 1.0 protocol requested, CoreMIDI hands over Universal217/// MIDI Packet words in which every channel voice message is one self-contained 32-bit word: the system218/// has already resolved running status, split multi-message packets and separated SysEx, so the real-time219/// path is a fixed-size decode with no byte-stream state. It was verified on macOS 27 with virtual220/// endpoints, including a source fed with legacy byte packets. `MIDIParser` (which handles running221/// status) remains for byte-oriented sources; CoreMIDI packets themselves never carry running status.222///223/// ## Hot-plug and run loops224/// CoreMIDI reports device changes on the run loop of the thread that created the process's first MIDI225/// client. `MIDIManager` creates its client on a private run-loop thread, so hot-plug works without a226/// main run loop **as long as `start()` is the first CoreMIDI client creation in the process** (create227/// and start the manager before any other CoreMIDI use). If other code created a client earlier, that228/// thread's run loop must be running (the main run loop of an app is).229///230/// ## Threading231/// - `onMessage`, `onTargetEvent` and `currentValueProvider` are called **on CoreMIDI's high-priority232///   receive thread**. They must return quickly and must not block (no locks held for long, no file or233///   network I/O, no `DispatchQueue.main.sync`). Hop to your own queue or actor for anything heavy.234/// - `onDevicesChanged` and the learn completion are called on a private serial utility queue, never on235///   the main thread and never on the CoreMIDI thread.236/// - Every method and property is safe to call from any thread, including from inside the callbacks.237///238/// The receive path takes one short unfair lock to copy its configuration, decodes UMP words in place239/// (no heap allocation for unmapped messages) and allocates only a small array when a mapped message240/// produces target events.241public final class MIDIManager: @unchecked Sendable {242    public typealias MessageHandler = @Sendable (MIDIDeviceInfo, MIDIMessage, UInt64) -> Void243    public typealias TargetEventHandler = @Sendable (MIDITargetEvent) -> Void244    public typealias CurrentValueProvider = @Sendable (String) -> Double?245246    private final class EngineBox: @unchecked Sendable {247        let lock = UnfairLock()248        var engine: MIDIMappingEngine249        init(_ engine: MIDIMappingEngine) { self.engine = engine }250    }251252    private struct LearnKey: Hashable {253        var control: MIDIControlID254        var deviceUniqueID: Int32255    }256257    private struct LearnCandidate {258        var device: MIDIDeviceInfo259        var count = 0260        var minRaw: UInt16 = .max261        var maxRaw: UInt16 = 0262        var order = 0263    }264265    private struct LearnSession {266        var id: UInt64267        var window: TimeInterval268        var completion: @Sendable (MIDILearnResult) -> Void269        var candidates: [LearnKey: LearnCandidate] = [:]270        var timerArmed = false271    }272273    private struct Connection {274        var token: Int275        var uniqueID: Int32276    }277278    private let clientName: String279    private let workQueue = DispatchQueue(label: "ai.spboucher.orixdj.midi", qos: .utility)280281    /// Serialises topology work (start, stop, rescan). Never taken on the CoreMIDI receive thread.282    private let setupLock = NSRecursiveLock()283    // Guarded by setupLock:284    private var running = false285    private var client = MIDIClientRef()286    private var inputPort = MIDIPortRef()287    private var connections: [MIDIEndpointRef: Connection] = [:]288    private var nextToken = 0289290    /// Guards everything below. Held only for field copies.291    private let stateLock = UnfairLock()292    private var outputPort = MIDIPortRef()293    private var _sources: [MIDIDeviceInfo] = []294    private var _destinations: [MIDIDeviceInfo] = []295    private var destinationRefs: [Int32: MIDIEndpointRef] = [:]296    private var tokenDevices: [Int: MIDIDeviceInfo] = [:]297    private var _selectedSourceIDs: Set<Int32>?298    private var _onMessage: MessageHandler?299    private var _onTargetEvent: TargetEventHandler?300    private var _onDevicesChanged: (@Sendable () -> Void)?301    private var _currentValueProvider: CurrentValueProvider?302    private var _activeProfile: MIDIMappingProfile?303    private var engineBox: EngineBox?304    private var learn: LearnSession?305    private var learnCounter: UInt64 = 0306    private var stats = MIDIStatistics()307    private var rescanPending = false308309    public init(clientName: String = "ORIX DJ") {310        self.clientName = clientName311    }312313    deinit {314        if running { MIDIClientDispose(client) }315    }316317    // MARK: Lifecycle318319    public var isRunning: Bool {320        setupLock.lock()321        defer { setupLock.unlock() }322        return running323    }324325    /// Creates the CoreMIDI client and ports, lists devices and connects to the selected sources.326    /// Does nothing if already running. Throws `MIDIError.coreMIDI` if the MIDI server cannot be reached.327    public func start() throws {328        setupLock.lock()329        if running {330            setupLock.unlock()331            return332        }333        do {334            var newClient = MIDIClientRef()335            let name = clientName336            // Created on the engine's run-loop thread: see `MIDIRunLoopThread`.337            var status = MIDIRunLoopThread.shared.sync {338                MIDIClientCreateWithBlock(name as CFString, &newClient) { [weak self] _ in339                    // Run-loop thread: just schedule a rescan on the work queue.340                    self?.scheduleRescan()341                }342            }343            guard status == noErr else { throw MIDIError.coreMIDI(operation: "MIDIClientCreateWithBlock", status: status) }344345            var newInput = MIDIPortRef()346            status = MIDIInputPortCreateWithProtocol(newClient, "\(clientName) In" as CFString, ._1_0, &newInput) {347                [weak self] list, refCon in348                self?.receive(list, token: Int(bitPattern: refCon))349            }350            guard status == noErr else {351                MIDIClientDispose(newClient)352                throw MIDIError.coreMIDI(operation: "MIDIInputPortCreateWithProtocol", status: status)353            }354355            var newOutput = MIDIPortRef()356            status = MIDIOutputPortCreate(newClient, "\(clientName) Out" as CFString, &newOutput)357            guard status == noErr else {358                MIDIClientDispose(newClient)359                throw MIDIError.coreMIDI(operation: "MIDIOutputPortCreate", status: status)360            }361362            client = newClient363            inputPort = newInput364            stateLock.withLock { outputPort = newOutput }365            running = true366        } catch {367            setupLock.unlock()368            throw error369        }370        setupLock.unlock()371        rescan()372    }373374    /// Disconnects everything and disposes the CoreMIDI client. A pending learn session is cancelled.375    public func stop() {376        setupLock.lock()377        defer { setupLock.unlock() }378        guard running else { return }379        running = false380        MIDIClientDispose(client) // disposes the ports and their connections381        client = MIDIClientRef()382        inputPort = MIDIPortRef()383        connections.removeAll()384        stateLock.withLock {385            outputPort = MIDIPortRef()386            _sources = []387            _destinations = []388            destinationRefs = [:]389            tokenDevices = [:]390            learn = nil391        }392    }393394    // MARK: Devices395396    /// Sources currently visible to the system (snapshot).397    public var sources: [MIDIDeviceInfo] { stateLock.withLock { _sources } }398399    /// Destinations currently visible to the system (snapshot).400    public var destinations: [MIDIDeviceInfo] { stateLock.withLock { _destinations } }401402    /// Sources the input port is connected to right now.403    public var connectedSources: [MIDIDeviceInfo] {404        stateLock.withLock { tokenDevices.values.sorted { $0.uniqueID < $1.uniqueID } }405    }406407    /// Sources to listen to, by unique ID; `nil` (default) means every source. A selected device that is408    /// absent is connected automatically when it (re)appears.409    public var selectedSourceIDs: Set<Int32>? {410        get { stateLock.withLock { _selectedSourceIDs } }411        set {412            stateLock.withLock { _selectedSourceIDs = newValue }413            rescan()414        }415    }416417    /// Called after the source or destination list changed (private utility queue).418    public var onDevicesChanged: (@Sendable () -> Void)? {419        get { stateLock.withLock { _onDevicesChanged } }420        set { stateLock.withLock { _onDevicesChanged = newValue } }421    }422423    /// Re-reads the device lists and reconciles connections now. Normally driven by CoreMIDI424    /// notifications; public so the UI can offer a manual refresh.425    public func rescan() {426        var changed = false427        var handler: (@Sendable () -> Void)?428429        setupLock.lock()430        if running {431            let newSources = Self.enumerate(.source)432            let newDestinations = Self.enumerate(.destination)433            let filter = stateLock.withLock { _selectedSourceIDs }434            let wanted = newSources.filter { filter?.contains($0.info.uniqueID) ?? true }435            var wantedByRef: [MIDIEndpointRef: Int32] = [:]436            for s in wanted { wantedByRef[s.ref] = s.info.uniqueID }437438            // Drop connections to sources that vanished, were deselected, or whose ref was reused.439            for (ref, connection) in connections where wantedByRef[ref] != connection.uniqueID {440                MIDIPortDisconnectSource(inputPort, ref) // fails harmlessly if the endpoint is gone441                connections[ref] = nil442                stateLock.withLock { tokenDevices[connection.token] = nil }443            }444            // Connect new ones; refresh the info of existing ones (a device can be renamed).445            for s in wanted {446                if let existing = connections[s.ref] {447                    stateLock.withLock { tokenDevices[existing.token] = s.info }448                    continue449                }450                nextToken += 1451                let token = nextToken452                // Registered before connecting so the first message already finds its device.453                stateLock.withLock { tokenDevices[token] = s.info }454                let status = MIDIPortConnectSource(inputPort, s.ref, UnsafeMutableRawPointer(bitPattern: token))455                if status == noErr {456                    connections[s.ref] = Connection(token: token, uniqueID: s.info.uniqueID)457                } else {458                    stateLock.withLock { tokenDevices[token] = nil }459                }460            }461462            let sourceInfos = newSources.map(\.info)463            let destinationInfos = newDestinations.map(\.info)464            var refs: [Int32: MIDIEndpointRef] = [:]465            for d in newDestinations { refs[d.info.uniqueID] = d.ref }466            stateLock.withLock {467                changed = _sources != sourceInfos || _destinations != destinationInfos468                _sources = sourceInfos469                _destinations = destinationInfos470                destinationRefs = refs471                handler = _onDevicesChanged472            }473        }474        setupLock.unlock()475476        if changed { handler?() }477    }478479    private func scheduleRescan() {480        let alreadyPending = stateLock.withLock { () -> Bool in481            if rescanPending { return true }482            rescanPending = true483            return false484        }485        if alreadyPending { return }486        workQueue.async { [weak self] in487            guard let self else { return }488            self.stateLock.withLock { self.rescanPending = false }489            self.rescan()490        }491    }492493    private static func enumerate(_ kind: MIDIDeviceInfo.Kind) -> [(ref: MIDIEndpointRef, info: MIDIDeviceInfo)] {494        let count = kind == .source ? MIDIGetNumberOfSources() : MIDIGetNumberOfDestinations()495        var result: [(ref: MIDIEndpointRef, info: MIDIDeviceInfo)] = []496        result.reserveCapacity(count)497        for i in 0..<count {498            let ref = kind == .source ? MIDIGetSource(i) : MIDIGetDestination(i)499            guard ref != 0, let info = deviceInfo(for: ref, kind: kind) else { continue }500            result.append((ref, info))501        }502        return result503    }504505    private static func deviceInfo(for endpoint: MIDIEndpointRef, kind: MIDIDeviceInfo.Kind) -> MIDIDeviceInfo? {506        var uniqueID: Int32 = 0507        guard MIDIObjectGetIntegerProperty(endpoint, kMIDIPropertyUniqueID, &uniqueID) == noErr else { return nil }508509        // Owning entity and device, when there is a driver behind the endpoint.510        var entity = MIDIEntityRef()511        let hasEntity = MIDIEndpointGetEntity(endpoint, &entity) == noErr && entity != 0512        var device = MIDIDeviceRef()513        let hasDevice = hasEntity && MIDIEntityGetDevice(entity, &device) == noErr && device != 0514        var chain: [MIDIObjectRef] = [endpoint]515        if hasEntity { chain.append(entity) }516        if hasDevice { chain.append(device) }517518        func string(_ key: CFString) -> String {519            for object in chain {520                var value: Unmanaged<CFString>?521                if MIDIObjectGetStringProperty(object, key, &value) == noErr, let value {522                    let s = value.takeRetainedValue() as String523                    if !s.isEmpty { return s }524                }525            }526            return ""527        }528        var offline = false529        for object in chain {530            var value: Int32 = 0531            if MIDIObjectGetIntegerProperty(object, kMIDIPropertyOffline, &value) == noErr, value != 0 { offline = true }532        }533        var name = string(kMIDIPropertyDisplayName)534        if name.isEmpty { name = string(kMIDIPropertyName) }535        return MIDIDeviceInfo(536            uniqueID: uniqueID,537            name: name,538            manufacturer: string(kMIDIPropertyManufacturer),539            model: string(kMIDIPropertyModel),540            isOnline: !offline,541            isVirtual: !hasEntity,542            kind: kind543        )544    }545546    // MARK: Callbacks and mapping547548    /// Raw monitor: `(device, message, host time)`. Called on the CoreMIDI receive thread.549    /// The host time is the packet's timestamp, or the arrival time when the sender did not stamp it.550    public var onMessage: MessageHandler? {551        get { stateLock.withLock { _onMessage } }552        set { stateLock.withLock { _onMessage = newValue } }553    }554555    /// Events produced by the active profile. Called on the CoreMIDI receive thread.556    /// Not called while a learn session is in progress.557    public var onTargetEvent: TargetEventHandler? {558        get { stateLock.withLock { _onTargetEvent } }559        set { stateLock.withLock { _onTargetEvent = newValue } }560    }561562    /// Current normalised value (`0...1`) of a target, or `nil` if unknown. Used by soft takeover and563    /// relative controls. Called on the CoreMIDI receive thread: must be a quick, non-blocking read.564    public var currentValueProvider: CurrentValueProvider? {565        get { stateLock.withLock { _currentValueProvider } }566        set { stateLock.withLock { _currentValueProvider = newValue } }567    }568569    /// The profile incoming messages run through; `nil` disables mapping. Setting it (even to an equal570    /// value) resets the mapping state: soft-takeover pickup, button edges, relative accumulators.571    public var activeProfile: MIDIMappingProfile? {572        get { stateLock.withLock { _activeProfile } }573        set {574            let box = newValue.map { EngineBox(MIDIMappingEngine(profile: $0)) }575            stateLock.withLock {576                _activeProfile = newValue577                engineBox = box578            }579        }580    }581582    /// Makes soft-takeover controls wait for pickup again, for one target or for all (`nil`).583    /// Call when a target's value changed without the hardware (track load, deck switch, on-screen drag).584    public func resetSoftTakeover(target: String? = nil) {585        guard let box = stateLock.withLock({ engineBox }) else { return }586        box.lock.withLock { box.engine.resetSoftTakeover(target: target) }587    }588589    public var statistics: MIDIStatistics { stateLock.withLock { stats } }590591    public func resetStatistics() {592        stateLock.withLock { stats = MIDIStatistics() }593    }594595    // MARK: Host time596597    private static let timebase: mach_timebase_info_data_t = {598        var info = mach_timebase_info_data_t()599        mach_timebase_info(&info)600        if info.denom == 0 { info = mach_timebase_info_data_t(numer: 1, denom: 1) }601        return info602    }()603604    /// Converts a host-time interval (`mach_absolute_time` units) to nanoseconds.605    public static func nanoseconds(fromHostTime hostTime: UInt64) -> UInt64 {606        let (high, low) = hostTime.multipliedFullWidth(by: UInt64(timebase.numer))607        let denom = UInt64(timebase.denom)608        if high >= denom { return .max }609        return denom.dividingFullWidth((high, low)).quotient610    }611612    /// The current host time, in the same units as the timestamps given to `onMessage`.613    public static func currentHostTime() -> UInt64 { mach_absolute_time() }614615    // MARK: Receive path (CoreMIDI thread)616617    // Field offsets of the packed CoreMIDI structures (`#pragma pack(4)`), with the documented layout as fallback.618    private static let listPacketOffset = MemoryLayout<MIDIEventList>.offset(of: \MIDIEventList.packet) ?? 8619    private static let packetTimeOffset = MemoryLayout<MIDIEventPacket>.offset(of: \MIDIEventPacket.timeStamp) ?? 0620    private static let packetCountOffset = MemoryLayout<MIDIEventPacket>.offset(of: \MIDIEventPacket.wordCount) ?? 8621    private static let packetWordsOffset = MemoryLayout<MIDIEventPacket>.offset(of: \MIDIEventPacket.words) ?? 12622    private static let maxWordsPerPacket = 64623624    /// Number of 32-bit words of a UMP, indexed by message type (top 4 bits of the first word).625    private static let umpWordCounts: [Int] = [1, 1, 1, 2, 2, 4, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4]626627    private func receive(_ list: UnsafePointer<MIDIEventList>, token: Int) {628        let arrival = mach_absolute_time()629630        stateLock.lock()631        let device = tokenDevices[token]632        let onMessage = _onMessage633        let onTargetEvent = _onTargetEvent634        let provider = _currentValueProvider635        let box = engineBox636        let learning = learn != nil637        stateLock.unlock()638639        var received: UInt64 = 0640        var dropped: UInt64 = 0641        var emitted: UInt64 = 0642        var lastTime: UInt64 = 0643644        let packetCount = Int(list.pointee.numPackets)645        var packet = UnsafeRawPointer(list).advanced(by: Self.listPacketOffset)646        Self.umpWordCounts.withUnsafeBufferPointer { wordCounts in647            for _ in 0..<packetCount {648                let stamp = packet.loadUnaligned(fromByteOffset: Self.packetTimeOffset, as: UInt64.self)649                let hostTime = stamp == 0 ? arrival : stamp650                let wordCount = min(651                    Int(packet.loadUnaligned(fromByteOffset: Self.packetCountOffset, as: UInt32.self)),652                    Self.maxWordsPerPacket653                )654                let words = packet.advanced(by: Self.packetWordsOffset)655                var i = 0656                while i < wordCount {657                    let word = words.loadUnaligned(fromByteOffset: i * 4, as: UInt32.self)658                    let type = Int(word >> 28)659                    i += wordCounts[type]660                    if type == 0 { continue } // utility (NOOP, jitter-reduction): not a message661                    guard let device, let message = MIDIMessage(umpWord: word) else {662                        dropped += 1663                        continue664                    }665                    received += 1666                    lastTime = hostTime667                    onMessage?(device, message, hostTime)668                    if learning {669                        learnFeed(message, device: device)670                    } else if let box, let onTargetEvent {671                        box.lock.lock()672                        let events = box.engine.process(message, deviceUniqueID: device.uniqueID) { target in673                            provider?(target)674                        }675                        box.lock.unlock()676                        for event in events {677                            emitted += 1678                            onTargetEvent(event)679                        }680                    }681                }682                packet = UnsafeRawPointer(683                    MIDIEventPacketNext(packet.assumingMemoryBound(to: MIDIEventPacket.self))684                )685            }686        }687688        stateLock.lock()689        stats.messagesReceived &+= received690        stats.messagesDropped &+= dropped691        stats.targetEventsEmitted &+= emitted692        if received > 0 { stats.lastMessageHostTime = lastTime }693        stateLock.unlock()694    }695696    // MARK: MIDI learn697698    public var isLearning: Bool { stateLock.withLock { learn != nil } }699700    /// Captures the next meaningful control and reports it once.701    ///702    /// - A note-on (button, pad) is reported immediately.703    /// - Note-offs and program changes are ignored.704    /// - For CCs and pitch bend, the first message opens a window of `window` seconds; when it closes, the705    ///   control that moved the most wins (largest value travel in 7-bit steps, or number of messages for706    ///   an encoder that repeats the same value), so a neighbouring fader that jitters does not get learned.707    ///708    /// While learning, `onMessage` still fires but `onTargetEvent` does not. `completion` is called on a709    /// private utility queue, exactly once, unless `cancelLearn()` or `stop()` ends the session first (then710    /// it is never called). A new `beginLearn` replaces a pending session.711    public func beginLearn(window: TimeInterval = 0.3, completion: @escaping @Sendable (MIDILearnResult) -> Void) {712        stateLock.withLock {713            learnCounter &+= 1714            learn = LearnSession(id: learnCounter, window: max(0, window), completion: completion)715        }716    }717718    public func cancelLearn() {719        stateLock.withLock { learn = nil }720    }721722    private func learnFeed(_ message: MIDIMessage, device: MIDIDeviceInfo) {723        let raw: UInt16724        var immediate = false725        switch message {726        case .noteOn(_, _, let velocity):727            raw = UInt16(velocity)728            immediate = true729        case .controlChange(_, _, let value):730            raw = UInt16(value)731        case .pitchBend(_, let value):732            raw = value733        case .noteOff, .programChange:734            return735        }736        guard let control = MIDIControlID(message: message) else { return }737738        var finished: (completion: @Sendable (MIDILearnResult) -> Void, result: MIDILearnResult)?739        var timer: (id: UInt64, window: TimeInterval)?740741        stateLock.lock()742        if var session = learn {743            if immediate {744                learn = nil745                finished = (746                    session.completion,747                    MIDILearnResult(control: control, device: device, messageCount: 1, minRawValue: raw, maxRawValue: raw)748                )749            } else {750                let key = LearnKey(control: control, deviceUniqueID: device.uniqueID)751                var candidate = session.candidates[key]752                    ?? LearnCandidate(device: device, order: session.candidates.count)753                candidate.count += 1754                candidate.minRaw = min(candidate.minRaw, raw)755                candidate.maxRaw = max(candidate.maxRaw, raw)756                session.candidates[key] = candidate757                if !session.timerArmed {758                    session.timerArmed = true759                    timer = (session.id, session.window)760                }761                learn = session762            }763        }764        stateLock.unlock()765766        if let finished {767            workQueue.async { finished.completion(finished.result) }768        }769        if let timer {770            workQueue.asyncAfter(deadline: .now() + timer.window) { [weak self] in771                self?.finishLearn(id: timer.id)772            }773        }774    }775776    private func finishLearn(id: UInt64) {777        let session: LearnSession? = stateLock.withLock {778            guard let current = learn, current.id == id else { return nil }779            learn = nil780            return current781        }782        guard let session else { return }783784        var best: (key: LearnKey, candidate: LearnCandidate, score: Int)?785        for (key, candidate) in session.candidates {786            var travel = Int(candidate.maxRaw) - Int(candidate.minRaw)787            if key.control.kind == .pitchBend { travel /= 129 } // 14-bit travel in 7-bit steps788            let score = max(travel, candidate.count - 1)789            if let current = best {790                let better = score > current.score791                    || (score == current.score && candidate.order < current.candidate.order)792                if !better { continue }793            }794            best = (key, candidate, score)795        }796        guard let best else { return }797        session.completion(798            MIDILearnResult(799                control: best.key.control,800                device: best.candidate.device,801                messageCount: best.candidate.count,802                minRawValue: best.candidate.minRaw,803                maxRawValue: best.candidate.maxRaw804            )805        )806    }807808    // MARK: Output809810    /// Sends one message to a destination now (LED feedback, etc.). Callable from any thread.811    public func send(_ message: MIDIMessage, to destinationUniqueID: Int32) throws {812        try send([message], to: destinationUniqueID)813    }814815    /// Sends several messages to a destination, in order, in as few event lists as possible.816    public func send(_ messages: [MIDIMessage], to destinationUniqueID: Int32) throws {817        let (port, endpoint) = stateLock.withLock { (outputPort, destinationRefs[destinationUniqueID]) }818        guard port != 0 else { throw MIDIError.notStarted }819        guard let endpoint else { throw MIDIError.destinationNotFound(uniqueID: destinationUniqueID) }820821        var index = 0822        while index < messages.count {823            let end = min(index + Self.maxWordsPerPacket, messages.count)824            var words = messages[index..<end].map(\.umpWord)825            index = end826            var list = MIDIEventList()827            let status: OSStatus = withUnsafeMutablePointer(to: &list) { listPointer in828                let packet = MIDIEventListInit(listPointer, ._1_0)829                let added = MIDIEventListAdd(listPointer, MemoryLayout<MIDIEventList>.size, packet, 0, words.count, &words)830                if UInt(bitPattern: added) == 0 { return OSStatus(paramErr) }831                return MIDISendEventList(port, endpoint, listPointer)832            }833            guard status == noErr else { throw MIDIError.coreMIDI(operation: "MIDISendEventList", status: status) }834        }835    }836}837
Files main
Menu

Theme