284 lines
12 KiB
Swift
284 lines
12 KiB
Swift
// MIDITests.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
import Testing
|
|
import Foundation
|
|
import CoreMIDI
|
|
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
|
|
|
@MainActor
|
|
@Suite("MIDIMessage")
|
|
struct MIDIMessageTests {
|
|
|
|
// MARK: - Parse
|
|
|
|
@Test func noteOnParsed() {
|
|
let msg: MIDIMessage = MIDIMessage.from(status: 0x91, data1: 60, data2: 100)
|
|
#expect(msg == .noteOn(channel: 1, note: 60, velocity: 100))
|
|
}
|
|
|
|
@Test func noteOnZeroVelocityBecomesNoteOff() {
|
|
let msg: MIDIMessage = MIDIMessage.from(status: 0x91, data1: 60, data2: 0)
|
|
#expect(msg == .noteOff(channel: 1, note: 60, velocity: 0))
|
|
}
|
|
|
|
@Test func noteOffParsed() {
|
|
let msg: MIDIMessage = MIDIMessage.from(status: 0x83, data1: 48, data2: 64)
|
|
#expect(msg == .noteOff(channel: 3, note: 48, velocity: 64))
|
|
}
|
|
|
|
@Test func controlChangeParsed() {
|
|
let msg: MIDIMessage = MIDIMessage.from(status: 0xB0, data1: 7, data2: 100)
|
|
#expect(msg == .controlChange(channel: 0, controller: 7, value: 100))
|
|
}
|
|
|
|
@Test func pitchBendCentreIsZero() {
|
|
// Centre position: LSB=0, MSB=64 → raw=8192 → value=0
|
|
let msg: MIDIMessage = MIDIMessage.from(status: 0xE0, data1: 0, data2: 64)
|
|
if case .pitchBend(let ch, let v) = msg {
|
|
#expect(ch == 0)
|
|
#expect(v == 0)
|
|
} else {
|
|
Issue.record("Expected pitchBend, got \(msg)")
|
|
}
|
|
}
|
|
|
|
@Test func pitchBendFullRange() {
|
|
let minMsg: MIDIMessage = MIDIMessage.from(status: 0xE0, data1: 0, data2: 0)
|
|
if case .pitchBend(_, let v) = minMsg { #expect(v == -8192) }
|
|
let maxMsg: MIDIMessage = MIDIMessage.from(status: 0xE0, data1: 127, data2: 127)
|
|
if case .pitchBend(_, let v) = maxMsg { #expect(v == 8191) }
|
|
}
|
|
|
|
@Test func programChangeParsed() {
|
|
let msg: MIDIMessage = MIDIMessage.from(status: 0xC2, data1: 5)
|
|
#expect(msg == .programChange(channel: 2, program: 5))
|
|
}
|
|
|
|
@Test func channelAftertouchParsed() {
|
|
let msg: MIDIMessage = MIDIMessage.from(status: 0xD0, data1: 80)
|
|
#expect(msg == .aftertouch(channel: 0, pressure: 80))
|
|
}
|
|
|
|
@Test func polyAftertouchParsed() {
|
|
let msg: MIDIMessage = MIDIMessage.from(status: 0xA1, data1: 60, data2: 70)
|
|
#expect(msg == .polyAftertouch(channel: 1, note: 60, pressure: 70))
|
|
}
|
|
|
|
@Test func systemRealtimeParsed() {
|
|
#expect(MIDIMessage.from(status: 0xF8) == .clock)
|
|
#expect(MIDIMessage.from(status: 0xFA) == .start)
|
|
#expect(MIDIMessage.from(status: 0xFC) == .stop)
|
|
#expect(MIDIMessage.from(status: 0xFE) == .activeSensing)
|
|
#expect(MIDIMessage.from(status: 0xFF) == .reset)
|
|
}
|
|
|
|
@Test func unknownStatusFallsThrough() {
|
|
let msg: MIDIMessage = MIDIMessage.from(status: 0xF1, data1: 10, data2: 20)
|
|
if case .other(let s, let d1, _) = msg {
|
|
#expect(s == 0xF1)
|
|
#expect(d1 == 10)
|
|
} else {
|
|
Issue.record("Expected .other, got \(msg)")
|
|
}
|
|
}
|
|
|
|
// MARK: - Round-trip encode → parse
|
|
|
|
@Test func noteOnRoundTrip() {
|
|
let original: MIDIMessage = MIDIMessage.noteOn(channel: 5, note: 72, velocity: 90)
|
|
let (s, d1, d2) = original.bytes()
|
|
#expect(MIDIMessage.from(status: s, data1: d1, data2: d2) == original)
|
|
}
|
|
|
|
@Test func controlChangeRoundTrip() {
|
|
let original: MIDIMessage = MIDIMessage.controlChange(channel: 0, controller: 1, value: 64)
|
|
let (s, d1, d2) = original.bytes()
|
|
#expect(MIDIMessage.from(status: s, data1: d1, data2: d2) == original)
|
|
}
|
|
|
|
@Test func pitchBendRoundTrip() {
|
|
for value: Int16 in [-8192, 0, 8191] {
|
|
let original: MIDIMessage = MIDIMessage.pitchBend(channel: 0, value: value)
|
|
let (s, d1, d2) = original.bytes()
|
|
#expect(MIDIMessage.from(status: s, data1: d1, data2: d2) == original)
|
|
}
|
|
}
|
|
|
|
@Test func systemRealtimeRoundTrip() {
|
|
let messages: [MIDIMessage] = [.clock, .start, .stop, .activeSensing, .reset]
|
|
for msg: MIDIMessage in messages {
|
|
let (s, _, _) = msg.bytes()
|
|
#expect(MIDIMessage.from(status: s) == msg)
|
|
}
|
|
}
|
|
|
|
@Test func allChannelsBoundary() {
|
|
for ch: UInt8 in [0, 7, 15] {
|
|
let msg: MIDIMessage = MIDIMessage.noteOn(channel: ch, note: 60, velocity: 100)
|
|
let (s, d1, d2) = msg.bytes()
|
|
#expect(MIDIMessage.from(status: s, data1: d1, data2: d2) == msg)
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - MIDI handler token management
|
|
|
|
@MainActor
|
|
@Suite("MIDI tokens")
|
|
struct MIDITokenTests {
|
|
|
|
@Test func addHandlerReturnsUniqueTokens() {
|
|
let engine: SynthesisEngine = makeTestEngine()
|
|
let midi: MIDI = MIDI(engine: engine)
|
|
let t1: MIDIHandlerToken = midi.addHandler(name: "a") { _, _ in }
|
|
let t2: MIDIHandlerToken = midi.addHandler(name: "b") { _, _ in }
|
|
#expect(t1 != t2)
|
|
midi.removeHandler(t1)
|
|
midi.removeHandler(t2)
|
|
}
|
|
|
|
@Test func removeHandlerIsIdempotent() {
|
|
let engine: SynthesisEngine = makeTestEngine()
|
|
let midi: MIDI = MIDI(engine: engine)
|
|
let token: MIDIHandlerToken = midi.addHandler(name: "x") { _, _ in }
|
|
midi.removeHandler(token)
|
|
midi.removeHandler(token) // double-remove must not crash
|
|
}
|
|
}
|
|
|
|
private let handlerPropagationDelay: UInt64 = 50_000_000 // 50 ms — time for async dispatch + actor hop
|
|
|
|
// MARK: - MIDI dispatch integration
|
|
|
|
@MainActor
|
|
@Suite("MIDI dispatch")
|
|
struct MIDIDispatchTests {
|
|
|
|
/// Build a 24-byte MIDIEventList buffer containing one channel-voice UMP word.
|
|
///
|
|
/// Layout (all fields native byte order):
|
|
/// offset 0: MIDIProtocolID (Int32) = 1 (MIDI 1.0)
|
|
/// offset 4: numPackets (UInt32) = 1
|
|
/// offset 8: timeStamp (UInt64) = 0
|
|
/// offset 16: wordCount (UInt32) = 1
|
|
/// offset 20: UMP word (UInt32)
|
|
/// Build a buffer containing one MIDIEventPacket with `words.count` UMP words.
|
|
private func makeUMPBufferMultiWord(words: [UInt32]) -> [UInt8] {
|
|
let eventListHeaderSize: Int = 8
|
|
let eventPacketHeaderSize: Int = 12
|
|
var buf: [UInt8] = [UInt8](repeating: 0, count: eventListHeaderSize + eventPacketHeaderSize + words.count * 4)
|
|
buf.withUnsafeMutableBytes { raw in
|
|
guard let base: UnsafeMutableRawPointer = raw.baseAddress else { return }
|
|
base.storeBytes(of: Int32(1), toByteOffset: 0, as: Int32.self)
|
|
base.storeBytes(of: UInt32(1), toByteOffset: 4, as: UInt32.self)
|
|
base.storeBytes(of: UInt64(0), toByteOffset: 8, as: UInt64.self)
|
|
base.storeBytes(of: UInt32(words.count), toByteOffset: 16, as: UInt32.self)
|
|
for (i, w) in words.enumerated() {
|
|
base.storeBytes(of: w, toByteOffset: 20 + i * 4, as: UInt32.self)
|
|
}
|
|
}
|
|
return buf
|
|
}
|
|
|
|
private func makeUMPBuffer(word: UInt32) -> [UInt8] {
|
|
var buf: [UInt8] = [UInt8](repeating: 0, count: 24)
|
|
buf.withUnsafeMutableBytes { raw in
|
|
guard let base: UnsafeMutableRawPointer = raw.baseAddress else { return }
|
|
base.storeBytes(of: Int32(1), toByteOffset: 0, as: Int32.self) // MIDIProtocolID
|
|
base.storeBytes(of: UInt32(1), toByteOffset: 4, as: UInt32.self) // numPackets
|
|
base.storeBytes(of: UInt64(0), toByteOffset: 8, as: UInt64.self) // timeStamp
|
|
base.storeBytes(of: UInt32(1), toByteOffset: 16, as: UInt32.self) // wordCount
|
|
base.storeBytes(of: word, toByteOffset: 20, as: UInt32.self) // UMP word
|
|
}
|
|
return buf
|
|
}
|
|
|
|
@Test func receiveNoteOnDispatchesToHandler() async {
|
|
let engine: SynthesisEngine = makeTestEngine()
|
|
let midi: MIDI = MIDI(engine: engine)
|
|
|
|
actor Collector { var received: [MIDIMessage] = []; func add(_ m: MIDIMessage) { received.append(m) } }
|
|
let collector: Collector = Collector()
|
|
|
|
_ = midi.addHandler(name: "test") { msg, _ in Task { await collector.add(msg) } }
|
|
|
|
// UMP type 0x2 (channel voice), NoteOn ch0 (0x90), note 60, velocity 100
|
|
let midiNote: UInt32 = 60
|
|
let midiVelocity: UInt32 = 100
|
|
let word: UInt32 = (0x2 << 28) | (0x90 << 16) | (midiNote << 8) | midiVelocity
|
|
let buf: [UInt8] = makeUMPBuffer(word: word)
|
|
let ctx: LyrebirdMessageContext = LyrebirdMessageContext(engine: engine)
|
|
buf.withUnsafeBytes { raw in
|
|
guard let base: UnsafeRawPointer = raw.baseAddress else { Issue.record("nil baseAddress"); return }
|
|
midi._receive(base.assumingMemoryBound(to: MIDIEventList.self), ctx: ctx)
|
|
}
|
|
|
|
try? await Task.sleep(nanoseconds: handlerPropagationDelay)
|
|
let messages: [MIDIMessage] = await collector.received
|
|
#expect(messages.count == 1)
|
|
#expect(messages[0] == .noteOn(channel: 0, note: UInt8(midiNote), velocity: UInt8(midiVelocity)))
|
|
}
|
|
|
|
@Test func receiveControlChangeDispatchesToHandler() async {
|
|
let engine: SynthesisEngine = makeTestEngine()
|
|
let midi: MIDI = MIDI(engine: engine)
|
|
|
|
actor Collector { var received: [MIDIMessage] = []; func add(_ m: MIDIMessage) { received.append(m) } }
|
|
let collector: Collector = Collector()
|
|
|
|
_ = midi.addHandler(name: "cc") { msg, _ in Task { await collector.add(msg) } }
|
|
|
|
// UMP type 0x2, CC ch0 (0xB0), controller 7, value 64
|
|
let ccController: UInt32 = 7
|
|
let ccValue: UInt32 = 64
|
|
let word: UInt32 = (0x2 << 28) | (0xB0 << 16) | (ccController << 8) | ccValue
|
|
let buf: [UInt8] = makeUMPBuffer(word: word)
|
|
let ctx: LyrebirdMessageContext = LyrebirdMessageContext(engine: engine)
|
|
buf.withUnsafeBytes { raw in
|
|
guard let base: UnsafeRawPointer = raw.baseAddress else { Issue.record("nil baseAddress"); return }
|
|
midi._receive(base.assumingMemoryBound(to: MIDIEventList.self), ctx: ctx)
|
|
}
|
|
|
|
try? await Task.sleep(nanoseconds: handlerPropagationDelay)
|
|
let messages: [MIDIMessage] = await collector.received
|
|
#expect(messages.count == 1)
|
|
#expect(messages[0] == .controlChange(channel: 0, controller: UInt8(ccController), value: UInt8(ccValue)))
|
|
}
|
|
|
|
@Test func receiveSysEx7CompleteSinglePacketDispatchesToHandler() async {
|
|
let engine: SynthesisEngine = makeTestEngine()
|
|
let midi: MIDI = MIDI(engine: engine)
|
|
|
|
actor Collector { var received: [MIDIMessage] = []; func add(_ m: MIDIMessage) { received.append(m) } }
|
|
let collector: Collector = Collector()
|
|
|
|
_ = midi.addHandler(name: "sysex") { msg, _ in Task { await collector.add(msg) } }
|
|
|
|
// UMP SysEx7 complete message (status 0x0) with 1 payload byte (0x42).
|
|
// Type 0x3 always occupies exactly 2 words; second word is zero-padded.
|
|
let sysexPayload: UInt32 = 0x42
|
|
let sysexByteCount: UInt32 = 1
|
|
let w0: UInt32 = (0x3 << 28) | (0x0 << 20) | (sysexByteCount << 16) | (sysexPayload << 8)
|
|
let w1: UInt32 = 0
|
|
let buf: [UInt8] = makeUMPBufferMultiWord(words: [w0, w1])
|
|
let ctx: LyrebirdMessageContext = LyrebirdMessageContext(engine: engine)
|
|
buf.withUnsafeBytes { raw in
|
|
guard let base: UnsafeRawPointer = raw.baseAddress else { Issue.record("nil baseAddress"); return }
|
|
midi._receive(base.assumingMemoryBound(to: MIDIEventList.self), ctx: ctx)
|
|
}
|
|
|
|
try? await Task.sleep(nanoseconds: handlerPropagationDelay)
|
|
let messages: [MIDIMessage] = await collector.received
|
|
#expect(messages.count == 1)
|
|
if case .sysex(let bytes) = messages.first {
|
|
#expect(bytes == [UInt8(sysexPayload)])
|
|
} else {
|
|
Issue.record("Expected .sysex, got \(String(describing: messages.first))")
|
|
}
|
|
}
|
|
}
|