SPB Git

Repository Public

MIDIManagerSystemTests.swift 33.4 KB 687 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX DJ9// File             : Packages/ORIXDJCore/Tests/ORIXMIDITests/MIDIManagerSystemTests.swift10// Description      : End-to-end tests of MIDIManager through the real CoreMIDI11//                    server, using virtual endpoints (no hardware).12// Module           : ORIXMIDITests13// 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 Foundation91import Testing92@testable import ORIXMIDI9394// These tests talk to the real MIDI server of the machine. Nothing here is skipped when CoreMIDI is95// unavailable: every helper throws, so a missing MIDI server fails the tests loudly.96// They use virtual endpoints only: no physical controller is involved.9798struct CoreMIDITestError: Error, CustomStringConvertible {99    var description: String100    init(_ operation: String, _ status: OSStatus) {101        description = "CoreMIDI unavailable or failing in the test process: \(operation) returned \(status)"102    }103}104105/// CoreMIDI binds device-change delivery to the run loop of the thread that creates the first client of106/// the process. Test threads have no run loop, so the engine's own run-loop thread must create that first107/// client: every test endpoint calls this before touching CoreMIDI. (An app gets the same effect by108/// starting `MIDIManager` before any other CoreMIDI use.)109private let coreMIDIBootstrap: Result<Void, any Error> = Result {110    let manager = MIDIManager(clientName: "ORIXDJ Test Bootstrap")111    try manager.start()112    manager.stop()113}114115func bootstrapCoreMIDI() throws {116    try coreMIDIBootstrap.get()117}118119/// Sends raw MIDI 1.0 bytes through the deprecated packet-list call, the way a legacy driver or app120/// would. The call is hidden behind a protocol witness so the deprecation does not warn at the call site.121private protocol LegacyByteSending {122    func sendBytes(_ bytes: [UInt8], from source: MIDIEndpointRef) -> OSStatus123}124125private struct LegacyByteSender: LegacyByteSending {126    @available(macOS, deprecated: 11.0)127    func sendBytes(_ bytes: [UInt8], from source: MIDIEndpointRef) -> OSStatus {128        var list = MIDIPacketList()129        return withUnsafeMutablePointer(to: &list) { pointer in130            let packet = MIDIPacketListInit(pointer)131            _ = MIDIPacketListAdd(pointer, MemoryLayout<MIDIPacketList>.size, packet, 0, bytes.count, bytes)132            return MIDIReceived(source, pointer)133        }134    }135}136137/// A test-owned CoreMIDI client with one virtual source (plays the role of a controller's output).138final class VirtualSource: @unchecked Sendable {139    let name: String140    private(set) var client = MIDIClientRef()141    private(set) var endpoint = MIDIEndpointRef()142    private(set) var uniqueID: Int32 = 0143144    init(label: String = "Source") throws {145        name = "ORIXDJ Test \(label) \(UUID().uuidString.prefix(8))"146        try bootstrapCoreMIDI()147        var status = MIDIClientCreateWithBlock("\(name) client" as CFString, &client, nil)148        guard status == noErr else { throw CoreMIDITestError("MIDIClientCreateWithBlock", status) }149        status = MIDISourceCreateWithProtocol(client, name as CFString, ._1_0, &endpoint)150        guard status == noErr else { throw CoreMIDITestError("MIDISourceCreateWithProtocol", status) }151        status = MIDIObjectGetIntegerProperty(endpoint, kMIDIPropertyUniqueID, &uniqueID)152        guard status == noErr else { throw CoreMIDITestError("MIDIObjectGetIntegerProperty", status) }153    }154155    /// Sends UMP words as one event packet. `timeStamp` 0 means "now".156    func send(words: [UInt32], timeStamp: UInt64 = 0) throws {157        var words = words158        var list = MIDIEventList()159        let status: OSStatus = withUnsafeMutablePointer(to: &list) { pointer in160            let packet = MIDIEventListInit(pointer, ._1_0)161            _ = MIDIEventListAdd(pointer, MemoryLayout<MIDIEventList>.size, packet, timeStamp, words.count, &words)162            return MIDIReceivedEventList(endpoint, pointer)163        }164        guard status == noErr else { throw CoreMIDITestError("MIDIReceivedEventList", status) }165    }166167    func send(_ messages: MIDIMessage..., timeStamp: UInt64 = 0) throws {168        try send(words: messages.map(\.umpWord), timeStamp: timeStamp)169    }170171    func sendLegacyBytes(_ bytes: [UInt8]) throws {172        let sender: any LegacyByteSending = LegacyByteSender()173        let status = sender.sendBytes(bytes, from: endpoint)174        guard status == noErr else { throw CoreMIDITestError("MIDIReceived", status) }175    }176177    func dispose() {178        if client != 0 { MIDIClientDispose(client) }179        client = 0180        endpoint = 0181    }182183    deinit { dispose() }184}185186/// A test-owned virtual destination (plays the role of a controller's input, e.g. its LEDs).187final class VirtualDestination: @unchecked Sendable {188    let name: String189    let receivedWords = Locked<[UInt32]>([])190    private var client = MIDIClientRef()191    private var endpoint = MIDIEndpointRef()192    private(set) var uniqueID: Int32 = 0193194    init() throws {195        name = "ORIXDJ Test Destination \(UUID().uuidString.prefix(8))"196        try bootstrapCoreMIDI()197        var status = MIDIClientCreateWithBlock("\(name) client" as CFString, &client, nil)198        guard status == noErr else { throw CoreMIDITestError("MIDIClientCreateWithBlock", status) }199        let sink = receivedWords200        status = MIDIDestinationCreateWithProtocol(client, name as CFString, ._1_0, &endpoint) { list, _ in201            var collected: [UInt32] = []202            for packet in list.unsafeSequence() {203                collected.append(contentsOf: packet.words())204            }205            sink.withLock { $0.append(contentsOf: collected) }206        }207        guard status == noErr else { throw CoreMIDITestError("MIDIDestinationCreateWithProtocol", status) }208        status = MIDIObjectGetIntegerProperty(endpoint, kMIDIPropertyUniqueID, &uniqueID)209        guard status == noErr else { throw CoreMIDITestError("MIDIObjectGetIntegerProperty", status) }210    }211212    func dispose() {213        if client != 0 { MIDIClientDispose(client) }214        client = 0215    }216217    deinit { dispose() }218}219220private struct Received: Equatable, Sendable {221    var deviceID: Int32222    var message: MIDIMessage223}224225/// Records the messages of one device only: other MIDI sources of the machine (or of tests running in226/// another process) must not disturb the assertions.227private func monitor(_ manager: MIDIManager, deviceID: Int32) -> Locked<[Received]> {228    let log = Locked<[Received]>([])229    manager.onMessage = { device, message, _ in230        guard device.uniqueID == deviceID else { return }231        log.withLock { $0.append(Received(deviceID: device.uniqueID, message: message)) }232    }233    return log234}235236@Suite(.serialized) struct MIDIManagerSystemTests {237    @Test func midiServerIsReachable() throws {238        // Fails loudly (throws) if the test process cannot reach the MIDI server.239        let manager = MIDIManager(clientName: "ORIXDJ Test Reachability")240        try manager.start()241        #expect(manager.isRunning)242        try manager.start() // idempotent243        manager.stop()244        #expect(!manager.isRunning)245        #expect(manager.sources.isEmpty && manager.destinations.isEmpty)246        #expect(throws: MIDIError.notStarted) { try manager.send(.noteOn(channel: 0, note: 1, velocity: 1), to: 1) }247    }248249    @Test func receivesNoteCCAndPitchBendFromVirtualSource() async throws {250        let source = try VirtualSource()251        defer { source.dispose() }252        let manager = MIDIManager(clientName: "ORIXDJ Test Receive")253        try manager.start()254        defer { manager.stop() }255256        let device = try #require(manager.sources.first { $0.uniqueID == source.uniqueID })257        #expect(device.name == source.name)258        #expect(device.kind == .source)259        #expect(device.isVirtual)260        #expect(device.isOnline)261        #expect(manager.connectedSources.contains(device))262263        let log = monitor(manager, deviceID: source.uniqueID)264        let hostTimes = Locked<[UInt64]>([])265        let inner = manager.onMessage266        manager.onMessage = { device, message, time in267            inner?(device, message, time)268            if device.uniqueID == source.uniqueID { hostTimes.withLock { $0.append(time) } }269        }270271        let sent: [MIDIMessage] = [272            .noteOn(channel: 0, note: 60, velocity: 100),273            .controlChange(channel: 3, controller: 7, value: 64),274            .pitchBend(channel: 15, value: 12345),275            .noteOff(channel: 0, note: 60, velocity: 10),276            .programChange(channel: 2, program: 9),277        ]278        let before = MIDIManager.currentHostTime()279        for message in sent { try source.send(message) }280        // Several messages in one packet, including a note-on with velocity 0.281        try source.send(words: [0x2091_3C00, 0x20B1_0A7F, 0x20E1_0040])282        let expected = sent + [283            .noteOff(channel: 1, note: 60, velocity: 0),284            .controlChange(channel: 1, controller: 10, value: 127),285            .pitchBend(channel: 1, value: 8192),286        ]287        #expect(await waitUntil { log.current.count >= expected.count })288        expectEqual(log.current.map(\.message), expected)289        #expect(log.current.allSatisfy { $0.deviceID == source.uniqueID })290        let after = MIDIManager.currentHostTime()291        #expect(hostTimes.current.allSatisfy { $0 >= before && $0 <= after })292293        let stats = manager.statistics294        #expect(stats.messagesReceived >= UInt64(expected.count))295        #expect(stats.lastMessageHostTime != nil)296    }297298    @Test func unsupportedEventsAreCountedAsDroppedNotDelivered() async throws {299        let source = try VirtualSource()300        defer { source.dispose() }301        let manager = MIDIManager(clientName: "ORIXDJ Test Dropped")302        manager.selectedSourceIDs = [source.uniqueID]303        try manager.start()304        defer { manager.stop() }305        let log = monitor(manager, deviceID: source.uniqueID)306307        try source.send(words: [0x10F8_0000]) // timing clock308        try source.send(words: [0x20D0_4000]) // channel pressure309        try source.send(words: [0x3003_7E7F, 0x0601_0000]) // complete SysEx7 (identity request)310        try source.send(.controlChange(channel: 0, controller: 1, value: 1))311        #expect(await waitUntil { log.current.count >= 1 })312        expectEqual(log.current.map(\.message), [.controlChange(channel: 0, controller: 1, value: 1)])313        let stats = manager.statistics314        #expect(stats.messagesReceived == 1)315        #expect(stats.messagesDropped == 3)316    }317318    @Test func legacyBytePacketArrivesDecoded() async throws {319        // A source fed with MIDI 1.0 bytes through the old packet-list call (several messages in one320        // packet, a velocity-0 note-on): CoreMIDI converts to UMP before the engine sees it.321        // No running status here: CoreMIDI forbids it inside a MIDIPacket, and its converter was observed322        // on macOS 27 to drop the data bytes that rely on it. Drivers expand running status themselves.323        let source = try VirtualSource()324        defer { source.dispose() }325        let manager = MIDIManager(clientName: "ORIXDJ Test Legacy")326        try manager.start()327        defer { manager.stop() }328        let log = monitor(manager, deviceID: source.uniqueID)329330        try source.sendLegacyBytes([0x90, 60, 100, 0x90, 62, 0, 0xB0, 7, 64, 0xB0, 7, 65])331        #expect(await waitUntil { log.current.count >= 4 })332        expectEqual(log.current.map(\.message), [333            .noteOn(channel: 0, note: 60, velocity: 100),334            .noteOff(channel: 0, note: 62, velocity: 0),335            .controlChange(channel: 0, controller: 7, value: 64),336            .controlChange(channel: 0, controller: 7, value: 65),337        ])338    }339340    @Test func activeProfileProducesTargetEvents() async throws {341        let source = try VirtualSource()342        defer { source.dispose() }343        let other = try VirtualSource(label: "Other")344        defer { other.dispose() }345        let manager = MIDIManager(clientName: "ORIXDJ Test Profile")346        try manager.start()347        defer { manager.stop() }348349        let id = source.uniqueID350        let profile = MIDIMappingProfile(name: "e2e", mappings: [351            MIDIMapping(control: .note(channel: 0, note: 11), deviceUniqueID: id, target: "deck.A.play", mode: .toggle),352            MIDIMapping(control: .note(channel: 0, note: 12), deviceUniqueID: id, target: "deck.A.cue", mode: .momentary),353            MIDIMapping(control: .note(channel: 0, note: 13), deviceUniqueID: id, target: "deck.A.sync", mode: .trigger),354            MIDIMapping(control: .cc(channel: 0, controller: 31), deviceUniqueID: id, target: "mixer.crossfader", mode: .absolute),355            MIDIMapping(control: .pitchBend(channel: 0), deviceUniqueID: id, target: "deck.A.tempo", mode: .absolute, invert: true),356            MIDIMapping(control: .cc(channel: 0, controller: 33), deviceUniqueID: id, target: "deck.A.jog", mode: .relative),357            MIDIMapping(control: .cc(channel: 0, controller: 40), deviceUniqueID: id, target: "mixer.ch1.volume", mode: .absolute, softTakeover: true),358        ])359        #expect(profile.validate().isEmpty)360        let events = Locked<[MIDITargetEvent]>([])361        manager.onTargetEvent = { event in events.withLock { $0.append(event) } }362        manager.currentValueProvider = { target in363            switch target {364            case "deck.A.jog": return 0.5365            case "mixer.ch1.volume": return 0.75366            default: return nil367            }368        }369        manager.activeProfile = profile370        #expect(manager.activeProfile == profile)371372        // The same controls on another device must not fire (device-scoped mappings).373        try other.send(.noteOn(channel: 0, note: 11, velocity: 127))374        try other.send(.controlChange(channel: 0, controller: 31, value: 5))375376        try source.send(.noteOn(channel: 0, note: 11, velocity: 127))377        try source.send(.noteOff(channel: 0, note: 11, velocity: 0))378        try source.send(.noteOn(channel: 0, note: 12, velocity: 127))379        try source.send(.noteOff(channel: 0, note: 12, velocity: 0))380        try source.send(.noteOn(channel: 0, note: 13, velocity: 127))381        try source.send(.controlChange(channel: 0, controller: 31, value: 64))382        try source.send(.pitchBend(channel: 0, value: 0))383        try source.send(.controlChange(channel: 0, controller: 33, value: 127)) // one step back384        try source.send(.controlChange(channel: 0, controller: 40, value: 10)) // below 0.75: gated385        try source.send(.controlChange(channel: 0, controller: 40, value: 60)) // still below: gated386        try source.send(.controlChange(channel: 0, controller: 40, value: 110)) // crossed: picked up387        try source.send(.controlChange(channel: 0, controller: 40, value: 0)) // live388        try source.send(.controlChange(channel: 0, controller: 99, value: 1)) // unmapped389390        let expected: [MIDITargetEvent] = [391            .toggle(target: "deck.A.play"),392            .momentary(target: "deck.A.cue", pressed: true),393            .momentary(target: "deck.A.cue", pressed: false),394            .trigger(target: "deck.A.sync"),395            .value(target: "mixer.crossfader", normalized: 0.5),396            .value(target: "deck.A.tempo", normalized: 1),397            .value(target: "deck.A.jog", normalized: 0.5 - 1.0 / 127),398            .value(target: "mixer.ch1.volume", normalized: MIDIMappingEngine.normalize7(110)),399            .value(target: "mixer.ch1.volume", normalized: 0),400        ]401        #expect(await waitUntil { events.current.count >= expected.count })402        try await Task.sleep(nanoseconds: 50_000_000) // nothing extra may follow403        expectEqual(events.current, expected)404        #expect(manager.statistics.targetEventsEmitted == UInt64(expected.count))405406        // Soft takeover can be re-armed, and the profile can be removed, at runtime.407        manager.resetSoftTakeover(target: "mixer.ch1.volume")408        try source.send(.controlChange(channel: 0, controller: 40, value: 20))409        try source.send(.controlChange(channel: 0, controller: 31, value: 127))410        #expect(await waitUntil { events.current.count >= expected.count + 1 })411        expectEqual(events.current.last, .value(target: "mixer.crossfader", normalized: 1))412        manager.activeProfile = nil413        let count = events.current.count414        try source.send(.controlChange(channel: 0, controller: 31, value: 1))415        try await Task.sleep(nanoseconds: 100_000_000)416        #expect(events.current.count == count)417    }418419    @Test func learnPicksTheControlThatMovedMostAndIgnoresNoteOffs() async throws {420        let source = try VirtualSource()421        defer { source.dispose() }422        let manager = MIDIManager(clientName: "ORIXDJ Test Learn")423        manager.selectedSourceIDs = [source.uniqueID]424        try manager.start()425        defer { manager.stop() }426427        let targetEvents = Locked<Int>(0)428        manager.onTargetEvent = { _ in targetEvents.withLock { $0 += 1 } }429        manager.activeProfile = MIDIMappingProfile(name: "busy", mappings: [430            MIDIMapping(control: .cc(channel: 0, controller: 20), target: "x", mode: .absolute)431        ])432433        // CC learn: a jittering neighbour (CC 10) and the fader really being moved (CC 20).434        let result = Locked<[MIDILearnResult]>([])435        manager.beginLearn(window: 0.25) { learned in result.withLock { $0.append(learned) } }436        #expect(manager.isLearning)437        try source.send(.noteOff(channel: 0, note: 5, velocity: 0)) // release of the "learn" button: ignored438        try source.send(.programChange(channel: 0, program: 1)) // ignored439        try source.send(.controlChange(channel: 0, controller: 10, value: 64))440        for value: UInt8 in stride(from: 10, through: 100, by: 10) {441            try source.send(.controlChange(channel: 0, controller: 20, value: value))442        }443        try source.send(.controlChange(channel: 0, controller: 10, value: 65))444        #expect(await waitUntil { !result.current.isEmpty })445        let learned = try #require(result.current.first)446        #expect(learned.control == .cc(channel: 0, controller: 20))447        #expect(learned.device.uniqueID == source.uniqueID)448        #expect(learned.device.name == source.name)449        #expect(learned.messageCount == 10)450        #expect(learned.minRawValue == 10 && learned.maxRawValue == 100)451        #expect(!manager.isLearning)452        #expect(targetEvents.current == 0) // mapped control did not act while learning453454        // Note learn: immediate, on the press.455        result.withLock { $0.removeAll() }456        manager.beginLearn { learned in result.withLock { $0.append(learned) } }457        try source.send(.noteOff(channel: 2, note: 40, velocity: 0))458        try source.send(.noteOn(channel: 2, note: 41, velocity: 99))459        #expect(await waitUntil { !result.current.isEmpty })460        #expect(result.current.first?.control == .note(channel: 2, note: 41))461462        // A one-direction relative encoder (same value repeated) beats a single stray CC.463        result.withLock { $0.removeAll() }464        manager.beginLearn(window: 0.2) { learned in result.withLock { $0.append(learned) } }465        try source.send(.controlChange(channel: 0, controller: 50, value: 3))466        for _ in 0..<6 { try source.send(.controlChange(channel: 0, controller: 51, value: 1)) }467        #expect(await waitUntil { !result.current.isEmpty })468        #expect(result.current.first?.control == .cc(channel: 0, controller: 51))469        #expect(result.current.first?.minRawValue == 1 && result.current.first?.maxRawValue == 1)470471        // Pitch bend can be learned too.472        result.withLock { $0.removeAll() }473        manager.beginLearn(window: 0.1) { learned in result.withLock { $0.append(learned) } }474        try source.send(.pitchBend(channel: 4, value: 100))475        try source.send(.pitchBend(channel: 4, value: 9000))476        #expect(await waitUntil { !result.current.isEmpty })477        #expect(result.current.first?.control == .pitchBend(channel: 4))478479        // Cancel: the completion is never called, and mapping resumes.480        result.withLock { $0.removeAll() }481        manager.beginLearn(window: 0.05) { learned in result.withLock { $0.append(learned) } }482        try source.send(.controlChange(channel: 0, controller: 60, value: 1))483        manager.cancelLearn()484        #expect(!manager.isLearning)485        try await Task.sleep(nanoseconds: 250_000_000)486        #expect(result.current.isEmpty)487        try source.send(.controlChange(channel: 0, controller: 20, value: 127))488        #expect(await waitUntil { targetEvents.current == 1 })489        #expect(result.current.count == 0)490    }491492    @Test func hotPlugFiresOnDevicesChangedAndReconnects() async throws {493        let manager = MIDIManager(clientName: "ORIXDJ Test HotPlug")494        let changes = Locked<Int>(0)495        manager.onDevicesChanged = { changes.withLock { $0 += 1 } }496        try manager.start()497        defer { manager.stop() }498499        // Plug in.500        let changesBefore = changes.current501        let first = try VirtualSource(label: "HotPlug")502        let firstID = first.uniqueID503        #expect(await waitUntil { manager.sources.contains { $0.uniqueID == firstID } })504        #expect(changes.current > changesBefore)505        #expect(manager.connectedSources.contains { $0.uniqueID == firstID })506507        // The engine connected by itself: messages flow without any call from the test.508        let log = Locked<[Received]>([])509        manager.onMessage = { device, message, _ in510            log.withLock { $0.append(Received(deviceID: device.uniqueID, message: message)) }511        }512        try first.send(.noteOn(channel: 0, note: 1, velocity: 1))513        #expect(await waitUntil { log.current.contains(Received(deviceID: firstID, message: .noteOn(channel: 0, note: 1, velocity: 1))) })514515        // Unplug.516        let changesPlugged = changes.current517        first.dispose()518        #expect(await waitUntil { !manager.sources.contains { $0.uniqueID == firstID } })519        #expect(changes.current > changesPlugged)520        #expect(!manager.connectedSources.contains { $0.uniqueID == firstID })521522        // Plug again (a new virtual endpoint: new unique ID): connected automatically again.523        let changesUnplugged = changes.current524        let second = try VirtualSource(label: "HotPlug")525        defer { second.dispose() }526        let secondID = second.uniqueID527        #expect(await waitUntil { manager.connectedSources.contains { $0.uniqueID == secondID } })528        #expect(changes.current > changesUnplugged)529        try second.send(.controlChange(channel: 1, controller: 2, value: 3))530        #expect(await waitUntil { log.current.contains(Received(deviceID: secondID, message: .controlChange(channel: 1, controller: 2, value: 3))) })531532        // Destinations follow hot-plug too.533        let destination = try VirtualDestination()534        let destinationID = destination.uniqueID535        #expect(await waitUntil { manager.destinations.contains { $0.uniqueID == destinationID } })536        #expect(manager.destinations.first { $0.uniqueID == destinationID }?.kind == .destination)537        destination.dispose()538        #expect(await waitUntil { !manager.destinations.contains { $0.uniqueID == destinationID } })539    }540541    @Test func selectedSubsetConnectsOnlyChosenSourcesAndWaitsForAbsentOnes() async throws {542        let wanted = try VirtualSource(label: "Wanted")543        defer { wanted.dispose() }544        let unwanted = try VirtualSource(label: "Unwanted")545        defer { unwanted.dispose() }546        let manager = MIDIManager(clientName: "ORIXDJ Test Subset")547        manager.selectedSourceIDs = [wanted.uniqueID]548        try manager.start()549        defer { manager.stop() }550551        #expect(manager.sources.contains { $0.uniqueID == unwanted.uniqueID }) // listed552        expectEqual(manager.connectedSources.map(\.uniqueID), [wanted.uniqueID]) // but not connected553554        let log = Locked<[Received]>([])555        manager.onMessage = { device, message, _ in556            log.withLock { $0.append(Received(deviceID: device.uniqueID, message: message)) }557        }558        try unwanted.send(.noteOn(channel: 0, note: 1, velocity: 1))559        try wanted.send(.noteOn(channel: 0, note: 2, velocity: 2))560        #expect(await waitUntil { !log.current.isEmpty })561        try await Task.sleep(nanoseconds: 100_000_000)562        expectEqual(log.current, [Received(deviceID: wanted.uniqueID, message: .noteOn(channel: 0, note: 2, velocity: 2))])563564        // Changing the selection at runtime reconnects.565        manager.selectedSourceIDs = [unwanted.uniqueID]566        expectEqual(manager.connectedSources.map(\.uniqueID), [unwanted.uniqueID])567        try wanted.send(.noteOn(channel: 0, note: 3, velocity: 3))568        try unwanted.send(.noteOn(channel: 0, note: 4, velocity: 4))569        #expect(await waitUntil { log.current.count >= 2 })570        try await Task.sleep(nanoseconds: 100_000_000)571        expectEqual(log.current.last, Received(deviceID: unwanted.uniqueID, message: .noteOn(channel: 0, note: 4, velocity: 4)))572        #expect(log.current.count == 2)573574        manager.selectedSourceIDs = nil575        #expect(manager.connectedSources.count >= 2)576    }577578    @Test func sendDeliversBytesToVirtualDestination() async throws {579        let destination = try VirtualDestination()580        defer { destination.dispose() }581        let manager = MIDIManager(clientName: "ORIXDJ Test Send")582        try manager.start()583        defer { manager.stop() }584585        let info = try #require(manager.destinations.first { $0.uniqueID == destination.uniqueID })586        #expect(info.name == destination.name)587        #expect(info.kind == .destination && info.isVirtual)588589        let messages: [MIDIMessage] = [590            .noteOn(channel: 0, note: 11, velocity: 127), // LED on591            .noteOn(channel: 0, note: 11, velocity: 1),592            .noteOff(channel: 0, note: 11, velocity: 0), // LED off593            .controlChange(channel: 5, controller: 20, value: 99),594            .pitchBend(channel: 1, value: 16383),595            .programChange(channel: 9, program: 3),596        ]597        try manager.send(messages[0], to: destination.uniqueID)598        try manager.send(Array(messages[1...]), to: destination.uniqueID)599        #expect(await waitUntil { destination.receivedWords.current.count >= messages.count })600601        // The bytes on the wire: status, data 1, data 2 of each UMP word.602        let words = destination.receivedWords.current603        let bytes = words.flatMap { [UInt8(truncatingIfNeeded: $0 >> 16), UInt8(truncatingIfNeeded: $0 >> 8), UInt8(truncatingIfNeeded: $0)] }604        expectEqual(bytes, [605            0x90, 11, 127,606            0x90, 11, 1,607            0x80, 11, 0,608            0xB5, 20, 99,609            0xE1, 0x7F, 0x7F,610            0xC9, 3, 0,611        ])612        #expect(words.allSatisfy { $0 >> 28 == 2 })613614        // A batch larger than one event packet is split and still arrives complete and in order.615        destination.receivedWords.withLock { $0.removeAll() }616        let many = (0..<200).map { MIDIMessage.controlChange(channel: 0, controller: UInt8($0 % 128), value: UInt8($0 % 100)) }617        try manager.send(many, to: destination.uniqueID)618        #expect(await waitUntil { destination.receivedWords.current.count >= many.count })619        expectEqual(destination.receivedWords.current, many.map(\.umpWord))620621        #expect(throws: MIDIError.destinationNotFound(uniqueID: 0x7ABC_DEF0)) {622            try manager.send(.noteOn(channel: 0, note: 1, velocity: 1), to: 0x7ABC_DEF0)623        }624    }625626    @Test func receiveLatencyOver1000Messages() async throws {627        let source = try VirtualSource(label: "Latency")628        defer { source.dispose() }629        let manager = MIDIManager(clientName: "ORIXDJ Test Latency")630        manager.selectedSourceIDs = [source.uniqueID]631        try manager.start()632        defer { manager.stop() }633634        let count = 1000635        let latencies = Locked<[UInt64]>([])636        latencies.withLock { $0.reserveCapacity(count) }637        manager.onMessage = { _, _, hostTime in638            let now = MIDIManager.currentHostTime()639            latencies.withLock { $0.append(now >= hostTime ? now - hostTime : 0) }640        }641        // A profile is active so the measurement includes the mapping stage.642        manager.onTargetEvent = { _ in }643        manager.activeProfile = MIDIMappingProfile(name: "latency", mappings: [644            MIDIMapping(control: .cc(channel: 0, controller: 1), target: "mixer.crossfader", mode: .absolute)645        ])646647        for i in 0..<count {648            // Stamped with the send time: the callback measures packet host time -> callback time.649            try source.send(.controlChange(channel: 0, controller: 1, value: UInt8(i % 128)), timeStamp: MIDIManager.currentHostTime())650            usleep(300)651        }652        #expect(await waitUntil { latencies.current.count >= count })653        let sorted = latencies.current.map { Double(MIDIManager.nanoseconds(fromHostTime: $0)) / 1000 }.sorted()654        #expect(sorted.count == count)655        func percentile(_ p: Double) -> Double { sorted[min(sorted.count - 1, Int(Double(sorted.count) * p))] }656        let line = String(657            format: "[ORIXMIDI latency] virtual source -> MIDIManager.onMessage, %d messages: min %.1f us, median %.1f us, p99 %.1f us, max %.1f us",658            sorted.count, sorted.first ?? 0, percentile(0.5), percentile(0.99), sorted.last ?? 0659        )660        print(line)661        // Sanity only (no tight bound): a message must not take a whole second.662        #expect(percentile(0.5) < 1_000_000)663        #expect(manager.statistics.messagesReceived == UInt64(count))664        #expect(manager.statistics.targetEventsEmitted == UInt64(count))665    }666667    @Test func stopAndRestartKeepWorking() async throws {668        let source = try VirtualSource()669        defer { source.dispose() }670        let manager = MIDIManager(clientName: "ORIXDJ Test Restart")671        try manager.start()672        let log = monitor(manager, deviceID: source.uniqueID)673        try source.send(.noteOn(channel: 0, note: 1, velocity: 1))674        #expect(await waitUntil { log.current.count == 1 })675        manager.stop()676        try source.send(.noteOn(channel: 0, note: 2, velocity: 2))677        try await Task.sleep(nanoseconds: 100_000_000)678        #expect(log.current.count == 1)679        try manager.start()680        defer { manager.stop() }681        #expect(manager.connectedSources.contains { $0.uniqueID == source.uniqueID })682        try source.send(.noteOn(channel: 0, note: 3, velocity: 3))683        #expect(await waitUntil { log.current.count == 2 })684        expectEqual(log.current.last?.message, .noteOn(channel: 0, note: 3, velocity: 3))685    }686}687
Files main
Menu

Theme