SPB Git

Repository Public

MIDIMessage.swift 7.7 KB 186 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/MIDIMessage.swift10// Description      : MIDI 1.0 channel voice messages used by ORIX DJ, with byte11//                    and UMP (MIDI 1.0 protocol) conversions.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 Foundation9091/// The MIDI 1.0 channel voice messages ORIX DJ understands.92///93/// Channels are zero-based (`0...15`); data values are 7-bit (`0...127`) and the pitch-bend value is94/// 14-bit (`0...16383`, centre `8192`). Initialisers and conversions mask out-of-range input rather than trap.95public enum MIDIMessage: Sendable, Equatable, Codable, Hashable {96    case noteOn(channel: UInt8, note: UInt8, velocity: UInt8)97    case noteOff(channel: UInt8, note: UInt8, velocity: UInt8)98    case controlChange(channel: UInt8, controller: UInt8, value: UInt8)99    case pitchBend(channel: UInt8, value: UInt16)100    case programChange(channel: UInt8, program: UInt8)101102    /// Builds a message from a MIDI 1.0 status byte and its data bytes.103    ///104    /// A note-on with velocity 0 becomes a `noteOff` (velocity 0), as the MIDI specification requires.105    /// Returns `nil` for anything that is not one of the supported channel voice messages106    /// (polyphonic/channel pressure, system messages, data bytes used as status).107    public init?(status: UInt8, data1: UInt8, data2: UInt8) {108        let channel = status & 0x0F109        let d1 = data1 & 0x7F110        let d2 = data2 & 0x7F111        switch status & 0xF0 {112        case 0x80:113            self = .noteOff(channel: channel, note: d1, velocity: d2)114        case 0x90:115            self = d2 == 0116                ? .noteOff(channel: channel, note: d1, velocity: 0)117                : .noteOn(channel: channel, note: d1, velocity: d2)118        case 0xB0:119            self = .controlChange(channel: channel, controller: d1, value: d2)120        case 0xC0:121            self = .programChange(channel: channel, program: d1)122        case 0xE0:123            self = .pitchBend(channel: channel, value: UInt16(d1) | (UInt16(d2) << 7))124        default:125            return nil126        }127    }128129    /// Decodes one Universal MIDI Packet word of message type 2 (MIDI 1.0 channel voice).130    /// Returns `nil` for every other UMP type and for unsupported statuses.131    public init?(umpWord word: UInt32) {132        guard word >> 28 == 0x2 else { return nil }133        self.init(134            status: UInt8(truncatingIfNeeded: word >> 16),135            data1: UInt8(truncatingIfNeeded: word >> 8),136            data2: UInt8(truncatingIfNeeded: word)137        )138    }139140    /// Zero-based MIDI channel.141    public var channel: UInt8 {142        switch self {143        case .noteOn(let c, _, _), .noteOff(let c, _, _), .controlChange(let c, _, _),144             .pitchBend(let c, _), .programChange(let c, _):145            return c & 0x0F146        }147    }148149    /// Status byte and the two data bytes (the second is 0 for program change).150    public var statusAndData: (status: UInt8, data1: UInt8, data2: UInt8) {151        switch self {152        case .noteOn(let c, let n, let v):153            return (0x90 | (c & 0x0F), n & 0x7F, v & 0x7F)154        case .noteOff(let c, let n, let v):155            return (0x80 | (c & 0x0F), n & 0x7F, v & 0x7F)156        case .controlChange(let c, let n, let v):157            return (0xB0 | (c & 0x0F), n & 0x7F, v & 0x7F)158        case .pitchBend(let c, let v):159            return (0xE0 | (c & 0x0F), UInt8(v & 0x7F), UInt8((v >> 7) & 0x7F))160        case .programChange(let c, let p):161            return (0xC0 | (c & 0x0F), p & 0x7F, 0)162        }163    }164165    /// MIDI 1.0 wire bytes (3 bytes, or 2 for program change). Never uses running status.166    public var bytes: [UInt8] {167        let (s, d1, d2) = statusAndData168        if case .programChange = self { return [s, d1] }169        return [s, d1, d2]170    }171172    /// The message as one UMP word, message type 2 (MIDI 1.0 channel voice), group 0.173    public var umpWord: UInt32 {174        let (s, d1, d2) = statusAndData175        return 0x2000_0000 | (UInt32(s) << 16) | (UInt32(d1) << 8) | UInt32(d2)176    }177178    /// Parses a self-contained MIDI 1.0 byte buffer (running status allowed inside the buffer).179    public static func parse(bytes: some Sequence<UInt8>) -> [MIDIMessage] {180        var parser = MIDIParser()181        var out: [MIDIMessage] = []182        parser.parse(bytes) { out.append($0) }183        return out184    }185}186
Files main
Menu

Theme