Files
Lyrebird/Sources/Lyrebird/Score/MIDIFile+Score.swift
T

326 lines
13 KiB
Swift

// MIDIFile+Score.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
extension MIDIFile {
/// Convert this parsed Standard MIDI File into a ``Score``.
///
/// One ``ScorePart`` is emitted per SMF track. Each track's `noteOn` /
/// `noteOff` events are paired into ``ScoreEvent`` instances with
/// `duration = offBeat - onBeat`. The first matching `noteOff` in beat
/// order ends the most-recent unmatched `noteOn` for the same
/// `(channel, note)` pair (LIFO — handles overlapping repeats on the
/// same pitch by ending the latest first).
///
/// ## What is preserved
///
/// - Beat positions and durations (via the file's `ticksPerQuarter`).
/// - MIDI channel — written into ``ScoreEvent/channel``.
/// - Velocity — `MIDI / 127` written into ``ScoreEvent/velocity`` and
/// exposed as ``Dynamic/raw(_:)`` if you re-import the result.
/// - Track names — applied to ``ScorePart/name``.
/// - First ``Score/bpm`` taken from the file's first tempo meta event
/// (defaults to `120.0` when absent).
/// - First time signature taken from the file's first
/// `timeSignature` meta event (defaults to `(4, 4)`).
///
/// ## What is NOT preserved
///
/// - **Pitch spelling.** SMF carries no spelling information — every
/// pitch is reconstructed as ``Pitch/midi(_:)`` which loses
/// sharp/flat distinctions. To preserve spelling end-to-end, drive
/// from MusicXML, which preserves spelling end-to-end.
/// - Mid-piece tempo changes — only the first tempo event is honoured
/// on the Score side because ``Score/bpm`` is a single value.
/// - Articulation. All events get ``Articulation/normal``.
/// - Tuplet structure. Note durations are emitted as
/// ``NoteDuration/beats(_:)`` — exact beat values, but no
/// `Tuplet(actual: inTimeOf:)` wrapper is reconstructed.
///
/// - Parameters:
/// - partNamePrefix: Fallback name for tracks whose ``MIDIFileTrack/name``
/// is `nil`. The track index is appended (`"<prefix> 0"`,
/// `"<prefix> 1"`, …). Default `"Track"`.
/// - skipChannelLessTracks: When `true` (default), tracks with no
/// channel events at all are dropped from the resulting `Score`.
/// Pass `false` to keep them as empty parts.
public func toScore(
partNamePrefix: String = "Track",
skipChannelLessTracks: Bool = true
) -> Score {
// Tempo + time signature from the earliest meta events of each kind
// when the merged Score.allEvents-equivalent stream is walked in
// (beat, trackIndex) order. Both queries traverse the same `allEvents`
// list to keep the source policy symmetric.
var bpm: Double = MIDIFile.defaultBPM
var timeSignature: (Int, Int) = MIDIFile.defaultTimeSignature
var sawTempo: Bool = false
var sawTimeSig: Bool = false
for event: MIDIFileEvent in allEvents {
switch event.kind {
case .tempo:
if !sawTempo, let parsedBPM: Double = event.kind.bpm {
bpm = parsedBPM
sawTempo = true
}
case .timeSignature(let num, let denPow2, _, _):
if !sawTimeSig {
let safePow2: Int = min(Int(denPow2),
MIDIFile.maxTimeSignaturePow2)
timeSignature = (max(1, Int(num)), 1 << safePow2)
sawTimeSig = true
}
default:
break
}
if sawTempo && sawTimeSig { break }
}
// Build one ScorePart per SMF track.
var parts: [ScorePart] = []
for track: MIDIFileTrack in tracks {
let scoreEvents: [ScoreEvent] = MIDIFile.pairNoteOnOff(
trackEvents: track.events,
trackEnd: track.lastBeat
)
if skipChannelLessTracks && scoreEvents.isEmpty {
continue
}
// Pick the part-level channel from the first channel event in the
// track. Default to 0 if the track has no channel events.
let partChannel: Int = MIDIFile.firstChannel(in: track.events) ?? 0
// Track-name preferred; fall back to "<prefix> N" using the track's
// index in the source file.
let name: String = track.name
?? "\(partNamePrefix) \(track.index)"
// Wrap the flat ScoreEvents as `.note(...)` ScoreElements so the
// Score round-trips through `flatten()` losslessly. No tuplet
// reconstruction — every duration is an exact `.beats(Double)`.
let elements: [ScoreElement] = MIDIFile.elementsFromScoreEvents(scoreEvents)
parts.append(ScorePart(
name: name,
channel: partChannel,
elements: elements
))
}
return Score(
bpm: bpm,
timeSignature: TimeSignature(timeSignature),
parts: parts
)
}
// MARK: - Private helpers
/// Default BPM when the SMF file contains no tempo meta event.
/// 120 BPM is the SMF spec's implicit default (`mpq = 500_000`).
private static let defaultBPM: Double = 120.0
/// Default time signature when none is present in the SMF.
private static let defaultTimeSignature: (Int, Int) = (4, 4)
/// Cap on `denPow2` when reconstructing a time-signature denominator.
/// `2^30` (a billion-something) is well past any musical denominator;
/// values above this are clamped to prevent `1 << denPow2` from
/// overflowing or trapping on malformed SMF input.
private static let maxTimeSignaturePow2: Int = 30
/// Index encoding for the per-(channel, note) note-on stack.
private struct NoteKey: Hashable {
let channel: UInt8
let note: UInt8
}
/// One unmatched `noteOn` waiting for a `noteOff`.
private struct PendingNoteOn {
let beat: Double
let velocity: UInt8
}
/// Pair `noteOn` / `noteOff` events from a single SMF track's event list
/// into a flat `[ScoreEvent]` keyed off beat 0. Orphan `noteOn` events
/// (no matching `noteOff` before the track ends) are emitted with
/// `duration = trackEnd - onBeat` so they remain audible.
private static func pairNoteOnOff(
trackEvents: [MIDIFileEvent],
trackEnd: Double
) -> [ScoreEvent] {
var pending: [NoteKey: [PendingNoteOn]] = [:]
var output: [ScoreEvent] = []
for event: MIDIFileEvent in trackEvents {
guard case .midi(let message) = event.kind else { continue }
switch message {
case .noteOn(let ch, let note, let vel):
// `MIDIMessage.from` rewrites velocity-0 noteOn → noteOff at
// parse time, so this case always carries `vel >= 1` for
// events coming from `MIDIFile.parse(_:)`. Guard
// anyway so manually-built `MIDIFileEvent.midi(.noteOn(_,_,0))`
// still pairs correctly.
if vel == 0 {
if let off: MIDIFile.PendingNoteOn = popPending(&pending, channel: ch, note: note) {
output.append(makeScoreEvent(
on: off,
offBeat: event.beat,
channel: ch,
note: note
))
}
} else {
pending[NoteKey(channel: ch, note: note), default: []]
.append(PendingNoteOn(beat: event.beat, velocity: vel))
}
case .noteOff(let ch, let note, _):
if let off: MIDIFile.PendingNoteOn = popPending(&pending, channel: ch, note: note) {
output.append(makeScoreEvent(
on: off,
offBeat: event.beat,
channel: ch,
note: note
))
}
default:
break
}
}
// Close any remaining unmatched note-ons at the end of the track.
for (key, pendingList) in pending {
for on: MIDIFile.PendingNoteOn in pendingList {
output.append(makeScoreEvent(
on: on,
offBeat: max(on.beat, trackEnd),
channel: key.channel,
note: key.note
))
}
}
// Final beat-order sort; pairing stack is LIFO so out-of-order
// appends are possible when overlaps are present.
output.sort { lhs, rhs in
if lhs.beat != rhs.beat { return lhs.beat < rhs.beat }
return (lhs.pitch.midiNote ?? 0) < (rhs.pitch.midiNote ?? 0)
}
return output
}
/// LIFO pop of the most-recent pending noteOn for `(channel, note)`.
/// Returns `nil` if no matching noteOn is pending.
private static func popPending(
_ pending: inout [NoteKey: [PendingNoteOn]],
channel: UInt8,
note: UInt8
) -> PendingNoteOn? {
let key: MIDIFile.NoteKey = NoteKey(channel: channel, note: note)
guard var stack: [MIDIFile.PendingNoteOn] = pending[key], !stack.isEmpty else { return nil }
let popped: MIDIFile.PendingNoteOn = stack.removeLast()
pending[key] = stack.isEmpty ? nil : stack
return popped
}
/// Build a `ScoreEvent` from a `(noteOn, offBeat, channel, note)` quad.
private static func makeScoreEvent(
on: PendingNoteOn,
offBeat: Double,
channel: UInt8,
note: UInt8
) -> ScoreEvent {
let duration: Double = max(0.0, offBeat - on.beat)
let velocity: Double = Double(on.velocity) / Dynamic.midiMaxVelocity
return ScoreEvent(
beat: on.beat,
duration: duration,
pitch: .midi(Int(note)),
velocity: velocity,
voice: 0,
articulation: .normal,
channel: Int(channel)
)
}
/// First channel encountered across the channel events of a track,
/// or `nil` for channel-less tracks.
private static func firstChannel(in trackEvents: [MIDIFileEvent]) -> Int? {
for event: MIDIFileEvent in trackEvents {
if case .midi(let m) = event.kind {
switch m {
case .noteOn(let ch, _, _),
.noteOff(let ch, _, _),
.controlChange(let ch, _, _),
.pitchBend(let ch, _),
.programChange(let ch, _),
.aftertouch(let ch, _),
.polyAftertouch(let ch, _, _):
return Int(ch)
default:
continue
}
}
}
return nil
}
/// Wrap each `ScoreEvent` (already absolute-beat) as a sequence of
/// `Rest` + `Note` `ScoreElement` instances. Cursor walks beat 0 →
/// last event start; rests fill any gap between consecutive notes.
/// `NoteDuration.beats(_:)` is used everywhere (no tuplet
/// reconstruction).
///
/// ## Polyphony
///
/// The emitted element list is monophonic in the cursor sense — it
/// advances by each note's NOMINAL duration. When the source
/// `ScoreEvent` list contains overlapping notes (chord-like
/// simultaneity OR voiced polyphony), the second-and-later events at
/// the overlap point will land at incorrect beat positions when the
/// `Score` is re-flattened. Use this conversion path for
/// monophonic-per-track SMF input. Polyphony is preserved in the raw
/// `ScoreEvent` list available via ``ScorePart/flatten()`` after
/// construction — only the unflattened element tree is lossy.
private static func elementsFromScoreEvents(
_ events: [ScoreEvent]
) -> [ScoreElement] {
let sorted: [ScoreEvent] = events.sorted { $0.beat < $1.beat }
let pairs: [(position: Double, element: ScoreElement)] = sorted.map { event in
(
position: event.beat,
element: ScoreElement.note(
event.pitch,
duration: .beats(event.duration),
dynamic: .raw(event.velocity),
articulation: event.articulation,
voice: event.voice,
tie: false
)
)
}
// Shared gap-fill in Double space (preserves `.beats` representation).
// onOverlap is a no-op to keep the documented lossy monophonic behavior
// for overlapping SMF input — overlaps are not rejected here.
return fillRests(
sorted: pairs,
duration: { element in
if case .note(_, let dur, _, _, _, _) = element { return dur.beats }
if case .rest(let dur) = element { return dur.beats }
return 0.0
},
makeRest: { gap in .rest(duration: .beats(gap)) },
onOverlap: { _, _, _ in }
)
}
}