// MIDIFilePlayerTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Testing import Foundation @testable @_spi(LyrebirdExtensions) import LyrebirdSynth @Suite("MIDIFilePlayer — SMF playback through LyrebirdClock") struct MIDIFilePlayerTests { /// Encode `value` as a SMF variable-length quantity. private func vlq(_ value: UInt32) -> [UInt8] { if value < 0x80 { return [UInt8(value)] } var v: UInt32 = value var stack: [UInt8] = [] stack.append(UInt8(v & 0x7F)) v >>= 7 while v > 0 { stack.append(UInt8(v & 0x7F) | 0x80) v >>= 7 } return stack.reversed() } /// Build a synthetic format-0 SMF with three notes spaced one beat apart. /// At 480 PPQ and 600 BPM the routine completes the 2-beat span in 200 ms. private func makeThreeNoteFile(ppq: UInt16 = 480) throws -> MIDIFile { var bytes: [UInt8] = [0x4D, 0x54, 0x68, 0x64, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x01, UInt8(ppq >> 8), UInt8(ppq & 0xFF)] var track: [UInt8] = [] let oneBeat: [UInt8] = vlq(UInt32(ppq)) track += [0x00, 0x90, 60, 100] // beat 0 track += oneBeat + [0x90, 62, 100] // beat 1 track += oneBeat + [0x90, 64, 100] // beat 2 track += [0x00, 0xFF, 0x2F, 0x00] let trackLen: UInt32 = UInt32(track.count) bytes += [0x4D, 0x54, 0x72, 0x6B, UInt8((trackLen >> 24) & 0xFF), UInt8((trackLen >> 16) & 0xFF), UInt8((trackLen >> 8) & 0xFF), UInt8(trackLen & 0xFF)] bytes += track return try MIDIFile.parse(Data(bytes)) } @Test func playerDispatchesAllChannelEvents() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: 44100) try engine.start() let file: MIDIFile = try makeThreeNoteFile() // Use 600 BPM so the 2 beats of file content elapse in ~200 ms. let clock: LyrebirdClock = LyrebirdClock(engine: engine, bpm: 600) let player: MIDIFilePlayer = MIDIFilePlayer( file: file, engine: engine, clock: clock, applyTempoMap: false ) let received: Box<[UInt8]> = Box<[UInt8]>([]) player.play { msg in if case .noteOn(_, let note, _) = msg { received.mutate { $0.append(note) } } } // Wait up to ~3 seconds for the routine to complete the three notes // (2-beat span at 600 BPM = 200 ms; deadline allows for routine startup // jitter and the routine context's wait poll interval). let deadline: Date = Date().addingTimeInterval(3.0) while received.get().count < 3 && Date() < deadline { Thread.sleep(forTimeInterval: 0.01) } player.reset() #expect(received.get() == [60, 62, 64]) } @Test func playerStopsCleanly() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: 44100) try engine.start() let file: MIDIFile = try makeThreeNoteFile() // Slow tempo so the routine cannot finish before stop(). let clock: LyrebirdClock = LyrebirdClock(engine: engine, bpm: 1.0) let player: MIDIFilePlayer = MIDIFilePlayer( file: file, engine: engine, clock: clock, applyTempoMap: false ) player.play { _ in } Thread.sleep(forTimeInterval: 0.05) player.reset() #expect(player.state == .idle) } @Test func tempoMapAppliedToClock() throws { let engine: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: 44100) try engine.start() // Build a file whose first event is a 240 BPM tempo (mpq = 250_000). let mpq: UInt32 = 250_000 let ppq: UInt16 = 480 var bytes: [UInt8] = [0x4D, 0x54, 0x68, 0x64, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x01, UInt8(ppq >> 8), UInt8(ppq & 0xFF)] var track: [UInt8] = [] track += [0x00, 0xFF, 0x51, 0x03, UInt8((mpq >> 16) & 0xFF), UInt8((mpq >> 8) & 0xFF), UInt8(mpq & 0xFF)] track += [0x00, 0x90, 60, 100] track += [0x00, 0xFF, 0x2F, 0x00] let trackLen: UInt32 = UInt32(track.count) bytes += [0x4D, 0x54, 0x72, 0x6B, UInt8((trackLen >> 24) & 0xFF), UInt8((trackLen >> 16) & 0xFF), UInt8((trackLen >> 8) & 0xFF), UInt8(trackLen & 0xFF)] bytes += track let file: MIDIFile = try MIDIFile.parse(Data(bytes)) let clock: LyrebirdClock = LyrebirdClock(engine: engine, bpm: 120.0) let player: MIDIFilePlayer = MIDIFilePlayer( file: file, engine: engine, clock: clock, applyTempoMap: true ) let done: Box = Box(false) player.play { _ in done.set(true) } let deadline: Date = Date().addingTimeInterval(0.5) while !done.get() && Date() < deadline { Thread.sleep(forTimeInterval: 0.01) } // Allow a moment for the tempo-map application before reset clobbers state. Thread.sleep(forTimeInterval: 0.02) player.reset() #expect(abs(clock.bpm - 240.0) < 1e-9, "clock.bpm should follow tempo map; got \(clock.bpm)") } } /// Lock-protected reference-typed mutable cell for cross-thread accumulation in tests. /// /// The routine thread writes via ``set(_:)`` / ``mutate(_:)`` while the test thread /// reads via ``get()``. NSLock provides the happens-before edge that prevents the /// data race a plain `var` would introduce. private final class Box: @unchecked Sendable { private var _value: T private let _lock: NSLock = NSLock() init(_ value: T) { self._value = value } func get() -> T { _lock.lock(); defer { _lock.unlock() } return _value } func set(_ newValue: T) { _lock.lock(); defer { _lock.unlock() } _value = newValue } func mutate(_ body: (inout T) -> Void) { _lock.lock(); defer { _lock.unlock() } body(&_value) } }