Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX DJ9// File : Packages/ORIXDJCore/Tests/ORIXMIDITests/MIDIParserTests.swift10// Description : Table and fuzz tests of the MIDI 1.0 byte parser and of11// the message conversions.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 Foundation90import Testing91@testable import ORIXMIDI9293@Suite struct MIDIParserTests {94 @Test func tableOfSingleMessages() {95 let table: [([UInt8], [MIDIMessage])] = [96 ([0x90, 60, 100], [.noteOn(channel: 0, note: 60, velocity: 100)]),97 ([0x9F, 127, 1], [.noteOn(channel: 15, note: 127, velocity: 1)]),98 ([0x80, 60, 64], [.noteOff(channel: 0, note: 60, velocity: 64)]),99 ([0x93, 60, 0], [.noteOff(channel: 3, note: 60, velocity: 0)]), // note-on velocity 0100 ([0xB1, 7, 127], [.controlChange(channel: 1, controller: 7, value: 127)]),101 ([0xE0, 0x00, 0x40], [.pitchBend(channel: 0, value: 8192)]),102 ([0xE2, 0x7F, 0x7F], [.pitchBend(channel: 2, value: 16383)]),103 ([0xE2, 0x01, 0x00], [.pitchBend(channel: 2, value: 1)]),104 ([0xC5, 42], [.programChange(channel: 5, program: 42)]),105 ([], []),106 ([0x90], []),107 ([0x90, 60], []), // truncated108 ([60, 100], []), // data without status109 ([0xA0, 60, 10], []), // poly pressure: consumed, not reported110 ([0xD0, 10], []), // channel pressure111 ]112 for (bytes, expected) in table {113 #expect(MIDIMessage.parse(bytes: bytes) == expected, "bytes \(bytes)")114 }115 }116117 @Test func runningStatus() {118 let bytes: [UInt8] = [0x90, 60, 100, 62, 101, 64, 0, 0xB0, 1, 2, 3, 4, 0xC1, 5, 6]119 expectEqual(MIDIMessage.parse(bytes: bytes), [120 .noteOn(channel: 0, note: 60, velocity: 100),121 .noteOn(channel: 0, note: 62, velocity: 101),122 .noteOff(channel: 0, note: 64, velocity: 0),123 .controlChange(channel: 0, controller: 1, value: 2),124 .controlChange(channel: 0, controller: 3, value: 4),125 .programChange(channel: 1, program: 5),126 .programChange(channel: 1, program: 6),127 ])128 }129130 @Test func runningStatusSurvivesAcrossBuffers() {131 var parser = MIDIParser()132 var out: [MIDIMessage] = []133 parser.parse([0xB0, 7]) { out.append($0) }134 #expect(out.isEmpty)135 parser.parse([100, 7]) { out.append($0) }136 parser.parse([101]) { out.append($0) }137 expectEqual(out, [138 .controlChange(channel: 0, controller: 7, value: 100),139 .controlChange(channel: 0, controller: 7, value: 101),140 ])141 parser.reset()142 parser.parse([7, 102]) { out.append($0) }143 #expect(out.count == 2)144 }145146 @Test func multipleMessagesPerPacket() {147 let bytes: [UInt8] = [0x90, 1, 2, 0x80, 1, 0, 0xB3, 4, 5, 0xE1, 0, 0x40, 0xC0, 9]148 expectEqual(MIDIMessage.parse(bytes: bytes), [149 .noteOn(channel: 0, note: 1, velocity: 2),150 .noteOff(channel: 0, note: 1, velocity: 0),151 .controlChange(channel: 3, controller: 4, value: 5),152 .pitchBend(channel: 1, value: 8192),153 .programChange(channel: 0, program: 9),154 ])155 }156157 @Test func realTimeBytesAreTransparent() {158 // Clock (F8), active sensing (FE) and start (FA) interleaved inside a message.159 let bytes: [UInt8] = [0x90, 0xF8, 60, 0xFE, 100, 0xFA, 61, 0xFF, 101]160 expectEqual(MIDIMessage.parse(bytes: bytes), [161 .noteOn(channel: 0, note: 60, velocity: 100),162 .noteOn(channel: 0, note: 61, velocity: 101),163 ])164 }165166 @Test func sysExIsSkipped() {167 // Complete SysEx, then data that must not be read with the old running status.168 expectEqual(MIDIMessage.parse(bytes: [0x90, 60, 100, 0xF0, 0x7E, 0x90, 0x01, 0xF7, 61, 100, 0xB0, 1, 2]), [169 .noteOn(channel: 0, note: 60, velocity: 100),170 // 0x90 inside the SysEx terminates it and restarts a note-on: 0x01 then (after F7) nothing.171 .controlChange(channel: 0, controller: 1, value: 2),172 ])173 // Well-formed SysEx with a real-time byte inside.174 expectEqual(MIDIMessage.parse(bytes: [0xF0, 1, 2, 0xF8, 3, 0xF7, 0xB0, 1, 2]), [175 .controlChange(channel: 0, controller: 1, value: 2)176 ])177 // Unterminated SysEx ended by a status byte.178 expectEqual(MIDIMessage.parse(bytes: [0xF0, 1, 2, 3, 0x90, 60, 100]), [179 .noteOn(channel: 0, note: 60, velocity: 100)180 ])181 // SysEx never terminated.182 #expect(MIDIMessage.parse(bytes: [0xF0, 1, 2, 3, 4, 5]).isEmpty)183 }184185 @Test func systemCommonCancelsRunningStatus() {186 // Song position (F2 + 2 data), song select (F3 + 1), MTC (F1 + 1), tune request (F6).187 expectEqual(MIDIMessage.parse(bytes: [0xB0, 1, 2, 0xF2, 3, 4, 5, 6]), [188 .controlChange(channel: 0, controller: 1, value: 2)189 ])190 expectEqual(MIDIMessage.parse(bytes: [0xB0, 1, 2, 0xF3, 3, 4, 5]), [191 .controlChange(channel: 0, controller: 1, value: 2)192 ])193 expectEqual(MIDIMessage.parse(bytes: [0xB0, 1, 2, 0xF1, 3, 4, 5]), [194 .controlChange(channel: 0, controller: 1, value: 2)195 ])196 expectEqual(MIDIMessage.parse(bytes: [0xB0, 1, 2, 0xF6, 3, 4]), [197 .controlChange(channel: 0, controller: 1, value: 2)198 ])199 }200201 @Test func bytesAndUMPRoundTrip() {202 var messages: [MIDIMessage] = []203 for channel: UInt8 in [0, 7, 15] {204 for n: UInt8 in [0, 1, 64, 127] {205 messages.append(.noteOn(channel: channel, note: n, velocity: max(n, 1)))206 messages.append(.noteOff(channel: channel, note: n, velocity: n))207 messages.append(.controlChange(channel: channel, controller: n, value: 127 - n))208 messages.append(.programChange(channel: channel, program: n))209 }210 for v: UInt16 in [0, 1, 8191, 8192, 8193, 16383] {211 messages.append(.pitchBend(channel: channel, value: v))212 }213 }214 for message in messages {215 expectEqual(MIDIMessage.parse(bytes: message.bytes), [message])216 #expect(MIDIMessage(umpWord: message.umpWord) == message)217 #expect(message.umpWord >> 28 == 2)218 }219 // All messages concatenated parse back in order.220 #expect(MIDIMessage.parse(bytes: messages.flatMap(\.bytes)) == messages)221 }222223 @Test func umpDecodingRejectsOtherTypes() {224 #expect(MIDIMessage(umpWord: 0x1_0F8_0000) == nil) // system real-time225 #expect(MIDIMessage(umpWord: 0x3016_0000) == nil) // SysEx7226 #expect(MIDIMessage(umpWord: 0x4090_3C00) == nil) // MIDI 2.0 channel voice227 #expect(MIDIMessage(umpWord: 0x20A0_3C10) == nil) // poly pressure228 #expect(MIDIMessage(umpWord: 0x20D0_1000) == nil) // channel pressure229 #expect(MIDIMessage(umpWord: 0x2090_3C00) == .noteOff(channel: 0, note: 60, velocity: 0))230 #expect(MIDIMessage(umpWord: 0x2590_3C7F) == .noteOn(channel: 0, note: 60, velocity: 127)) // group ignored231 }232233 @Test func outOfRangeFieldsAreMasked() {234 let message = MIDIMessage.controlChange(channel: 200, controller: 255, value: 255)235 expectEqual(message.bytes, [0xB8, 0x7F, 0x7F])236 expectEqual(MIDIMessage.pitchBend(channel: 16, value: .max).bytes, [0xE0, 0x7F, 0x7F])237 }238239 @Test func fuzzRandomBytesNeverCrashAndStayInRange() {240 var generator = SystemRandomNumberGenerator()241 var total = 0242 for round in 0..<4000 {243 let length = Int.random(in: 0...96, using: &generator)244 var bytes = [UInt8](repeating: 0, count: length)245 for i in 0..<length {246 // Mix of uniform bytes and a status-heavy distribution to reach every branch.247 bytes[i] = round % 2 == 0248 ? UInt8.random(in: 0...255, using: &generator)249 : (Bool.random(using: &generator) ? UInt8.random(in: 0x80...0xFF, using: &generator) : UInt8.random(in: 0...0x7F, using: &generator))250 }251 let whole = MIDIMessage.parse(bytes: bytes)252 total += whole.count253 #expect(whole.count <= max(0, length - 1))254 for message in whole {255 #expect(message.channel <= 15)256 switch message {257 case .noteOn(_, let n, let v):258 #expect(n <= 127 && v >= 1 && v <= 127)259 case .noteOff(_, let n, let v):260 #expect(n <= 127 && v <= 127)261 case .controlChange(_, let n, let v):262 #expect(n <= 127 && v <= 127)263 case .pitchBend(_, let v):264 #expect(v <= 16383)265 case .programChange(_, let p):266 #expect(p <= 127)267 }268 #expect(MIDIMessage(umpWord: message.umpWord) == message)269 }270 // Feeding the same bytes in arbitrary chunks gives the same messages (streaming invariance).271 var parser = MIDIParser()272 var chunked: [MIDIMessage] = []273 var i = 0274 while i < length {275 let n = Int.random(in: 1...8, using: &generator)276 parser.parse(bytes[i..<min(length, i + n)]) { chunked.append($0) }277 i += n278 }279 #expect(chunked == whole)280 }281 #expect(total > 0)282 }283284 @Test func fuzzRandomUMPWordsNeverCrash() {285 var generator = SystemRandomNumberGenerator()286 for _ in 0..<200_000 {287 let word = UInt32.random(in: 0...UInt32.max, using: &generator)288 if let message = MIDIMessage(umpWord: word) {289 #expect(word >> 28 == 2)290 #expect(message.channel <= 15)291 }292 }293 }294}295