ws-audio2: MUS, XMI, HMP / HMI (music/mus, music/xmi, music/hmp) -> Types.Midi through codecs/audio/MidiRender (merge, tempoBytes); event streams match wildmidi -x

This commit is contained in:
4DBug committed 2026-10-31 14:27:51 -05:00
1 parent 848e4bfff6
commit a3e234cc0d
14 files changed
+1439

No files matched your search

+36
View File
@@ -842,6 +842,18 @@ local list: { Entry } = {
return require("@formats/music/ahx")
end,
},
{
name = "hmp",
category = "music",
path = "music/hmp",
extensions = { "hmp", "hmi" },
mime = { "audio/x-hmp" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" },
caps = { decode = true, encode = false, render = true, hmi = true },
load = function()
return require("@formats/music/hmp")
end,
},
{
name = "hvl",
category = "music",
@@ -890,6 +902,18 @@ local list: { Entry } = {
return require("@formats/music/mod")
end,
},
{
name = "mus",
category = "music",
path = "music/mus",
extensions = { "mus" },
mime = { "audio/x-mus" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" },
caps = { decode = true, encode = false, render = true },
load = function()
return require("@formats/music/mus")
end,
},
{
name = "s3m",
category = "music",
@@ -926,6 +950,18 @@ local list: { Entry } = {
return require("@formats/music/xm")
end,
},
{
name = "xmi",
category = "music",
path = "music/xmi",
extensions = { "xmi", "xmidi" },
mime = { "audio/x-xmidi" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/MidiRender" },
caps = { decode = true, encode = false, render = true, songs = true },
load = function()
return require("@formats/music/xmi")
end,
},
{
name = "m3u",
category = "playlist",
+38
View File
@@ -267,6 +267,44 @@ function Render.decoder(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?
return (dec :: any) :: Types.Decoder, nil
end
-- tempoBytes(division, ticksPerSecond) -> the 3 data bytes of a tempo meta event making each tick last
-- 1 / ticksPerSecond seconds at that division (for formats with a fixed tick rate: MUS, XMIDI, HMP / HMI)
function Render.tempoBytes(division: number, ticksPerSecond: number): { number }
local us = math.clamp(math.floor(division * 1e6 / ticksPerSecond + 0.5), 1, 0xFFFFFF)
return { us // 65536, (us // 256) % 256, us % 256 }
end
-- ------------------------------------------------------------------------------------------------ durations
export type PendingOff = { tick: number, onTick: number, ev: Types.MidiEvent }
-- merge(events, offs) -> one tick-ordered event list: for formats that store a duration with each note (XMIDI, HMI).
-- events are in file order (ticks never decrease); offs are the generated note-offs. At equal ticks an off whose note
-- started earlier goes before the file's events, an off of a zero-length note after them.
function Render.merge(events: { Types.MidiEvent }, offs: { PendingOff }): { Types.MidiEvent }
for i, o in offs do
(o :: any).seq = i
end
table.sort(offs, function(a: any, b: any): boolean
if a.tick ~= b.tick then
return a.tick < b.tick
end
return a.seq < b.seq
end)
local out: { Types.MidiEvent } = table.create(#events + #offs)
local k = 1
for _, ev in events do
while k <= #offs and (offs[k].tick < ev.tick or (offs[k].tick == ev.tick and offs[k].onTick < ev.tick)) do
table.insert(out, offs[k].ev)
k += 1
end
table.insert(out, ev)
end
for j = k, #offs do
table.insert(out, offs[j].ev)
end
return out
end
-- ------------------------------------------------------------------------------------------------ attach
local function render(self: Types.Midi, opts: RenderOptions?): Types.Decoder
local dec, err = Render.decoder(self, opts)
+273
View File
@@ -0,0 +1,273 @@
--!strict
-- music/hmp: Human Machine Interfaces SOS music: HMP ("HMIMIDIP", and the newer "HMIMIDIP013195" with the bigger header)
-- and HMI ("HMI-MIDISONG061595"), as used by Descent, Duke Nukem 3D's predecessors and other DOS games. Written from the
-- HMP / HMI layout notes (header fields, chunk tables, the reversed delta encoding of HMP, HMI's note durations and FE
-- events); wildmidi was used only as a reference converter in tests. Decodes to a Types.Midi (format 1, one track per
-- chunk): HMP deltas (7-bit groups least significant first, the last byte flagged) and running status; loop marker
-- controllers 110 / 111 with a value above 127 are skipped (meta.source.loops counts them); HMI note-ons carry a
-- duration that becomes a note-off (velocity 64), HMI-only FE events are skipped. Time: the header's tick rate (HMP
-- at 0x38, HMI byte 212) in ticks per second, as division 60 at 60000000 / rate us per quarter; tempo events in the
-- tracks apply on top. Renders through codecs/audio/MidiRender.
-- Not supported: writing; HMP branch tables (skipped).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Render = require("@formats/codecs/audio/MidiRender")
-- ------------------------------------------------------------------------------------------------ contract
local Hmp = {
name = "hmp",
category = "music",
extensions = { "hmp", "hmi" },
mime = { "audio/x-hmp" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" },
caps = { decode = true, encode = false, render = true, hmi = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxEvents: number?, -- default 2^24
}
-- ------------------------------------------------------------------------------------------------ sniff
local HMI_MAGIC = "HMI-MIDISONG061595"
function Hmp.sniff(r: Bytes.Reader): number
return if r:peek(8) == "HMIMIDIP" or r:peek(18) == HMI_MAGIC then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
local readu8, readu32 = buffer.readu8, buffer.readu32
local DATA = { [8] = 2, [9] = 2, [10] = 2, [11] = 2, [12] = 1, [13] = 1, [14] = 2 }
local TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" }
-- a delta at p -> value, next p (nil past e). hmp: least significant group first, the last byte has bit 7 set;
-- otherwise the MIDI encoding
local function delta(b: buffer, p: number, e: number, hmp: boolean): (number?, number)
local v, shift = 0, 1
for _ = 1, 5 do
if p >= e then
return nil, p
end
local c = readu8(b, p)
p += 1
if hmp then
v += (c % 128) * shift
shift *= 128
if c >= 128 then
return v, p
end
else
v = v * 128 + c % 128
if c < 128 then
return v, p
end
end
end
return nil, p
end
local function bytes(b: buffer, p: number, n: number): { number }
local t = table.create(n)
for i = 1, n do
t[i] = readu8(b, p + i - 1)
end
return t
end
type Ctx = { loops: number, budget: number }
-- one track [p, e) -> events (note-offs merged in) | nil, message
local function track(b: buffer, p: number, e: number, hmp: boolean, ctx: Ctx): ({ Types.MidiEvent }?, string?)
local list: { Types.MidiEvent }, offs: { Render.PendingOff } = {}, {}
local tick, running = 0, 0
while p < e do
local d, q = delta(b, p, e, hmp)
if not d then
break -- (a track cut inside its last delta: keep what was read)
end
tick += d
p = q
if p >= e then
return nil, "truncated event"
end
local st = readu8(b, p)
if st == 0xFE and not hmp then
-- HMI-only events: FE 10 (with a length at +4), FE 15, others 4 bytes
local n = 4
if p + 1 < e and readu8(b, p + 1) == 0x10 then
n = if p + 4 < e then readu8(b, p + 4) + 9 else e - p + 1
elseif p + 1 < e and readu8(b, p + 1) == 0x15 then
n = 8
end
if p + n > e then
return nil, "truncated FE event"
end
p += n
elseif st == 0xFF then
local kind = if p + 1 < e then readu8(b, p + 1) else -1
local n, r = delta(b, p + 2, e, false)
if kind < 0 or not n or r + n > e then
return nil, "truncated meta event"
end
if kind == 0x2F then
break
end
table.insert(list, { tick = tick, type = "meta", meta = kind, data = bytes(b, r, n) })
p = r + n
elseif st == 0xF0 or st == 0xF7 then
local n, r = delta(b, p + 1, e, false)
if not n or r + n > e then
return nil, "truncated sysex"
end
table.insert(list, { tick = tick, type = if st == 0xF0 then "sysex" else "escape", data = bytes(b, r, n) })
p = r + n
running = 0
else
if st >= 0x80 then
if st >= 0xF0 then
return nil, string.format("unexpected status byte 0x%02X", st)
end
running = st
p += 1
elseif running == 0 then
return nil, "running status without a status byte"
end
local hi, ch = running // 16, running % 16
local n = DATA[hi]
if p + n > e then
return nil, "truncated event"
end
local data = bytes(b, p, n)
p += n
if hmp and hi == 11 and (data[1] == 110 or data[1] == 111) and data[2] > 127 then
ctx.loops += 1
else
for i = 1, n do
data[i] %= 128
end
table.insert(list, { tick = tick, type = TYPES[hi], channel = ch, data = data })
end
if hi == 9 and not hmp then
local dur, r = delta(b, p, e, false)
if not dur then
return nil, "truncated note duration"
end
p = r
table.insert(offs, { tick = tick + dur, onTick = tick, ev = { tick = tick + dur, type = "noteOff", channel = ch, data = { data[1], 64 } } })
end
end
ctx.budget -= 1
if ctx.budget < 0 then
return nil, "limit: too many events"
end
end
-- (notes still sounding at the end of an HMI track keep their full duration, as wildmidi plays them)
local out = Render.merge(list, offs)
table.insert(out, { tick = math.max(tick, if #out > 0 then out[#out].tick else 0), type = "meta", meta = 0x2F, data = {} })
return out, nil
end
-- the chunk table -> { { start, stop } } track ranges | nil, message, kind
local function hmpTracks(b: buffer, base: number, limit: number): ({ { number } }?, string?, string?)
local new = buffer.readstring(b, base + 8, 6) == "013195"
local n = readu32(b, base + 0x30)
local p = base + (if new then 0x388 else 0x308)
if n == 0 or n > 256 then
return nil, string.format("bad track count %d", n)
end
local ranges = {}
for _ = 1, n do
if p + 12 > limit then
return nil, "truncated chunk header", "truncated"
end
local len = readu32(b, p + 4)
if len < 12 or p + len > limit then
return nil, "truncated chunk", "truncated"
end
table.insert(ranges, { p + 12, p + len })
p += len
end
return ranges, nil, nil
end
local function hmiTracks(b: buffer, base: number, limit: number): ({ { number } }?, string?, string?)
local n = readu8(b, base + 228)
if n == 0 then
return nil, "no tracks"
end
if base + 370 + n * 4 > limit then
return nil, "truncated track table", "truncated"
end
local ranges, heads = {}, {}
for i = 0, n - 1 do
local at = base + readu32(b, base + 370 + i * 4)
if at < base or at + 0x5B > limit or buffer.readstring(b, at, 13) ~= "HMI-MIDITRACK" then
return nil, string.format("bad track %d header", i)
end
local start = at + readu32(b, at + 0x57)
if start >= limit then
return nil, "truncated track", "truncated"
end
table.insert(ranges, { start, limit })
table.insert(heads, at)
end
-- a track ends where the next track header starts (or at the end of the file)
for _, rg in ranges do
for _, h in heads do
if h >= rg[1] and h < rg[2] then
rg[2] = h
end
end
end
return ranges, nil, nil
end
function Hmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?)
local b, base, limit = r.buf, r.base, r.limit
local hmi = r:peek(18) == HMI_MAGIC
if not hmi and r:peek(8) ~= "HMIMIDIP" then
return nil, Err.new(Err.CORRUPT, "not an HMP / HMI file")
end
if limit - base < (if hmi then 371 else 0x40) then
return nil, Err.new(Err.TRUNCATED, "truncated header")
end
local rate = if hmi then readu8(b, base + 212) else readu32(b, base + 0x38)
if rate == 0 or rate > 100000 then
return nil, Err.new(Err.CORRUPT, "bad tick rate " .. rate)
end
local ranges, msg, kind = (if hmi then hmiTracks else hmpTracks)(b, base, limit)
if not ranges then
return nil, Err.from(msg :: string, nil, kind)
end
local ctx: Ctx = { loops = 0, budget = (opts and opts.maxEvents) or 2 ^ 24 }
local midi = Types.Midi.new(60)
for i, rg in ranges do
local evs, err = track(b, rg[1], rg[2], not hmi, ctx)
if not evs then
return nil, Err.from(err :: string, rg[1])
end
if i == 1 then
local us = math.min(60000000 // rate, 0xFFFFFF)
table.insert(evs, 1, { tick = 0, type = "meta", meta = 0x51, data = { us // 65536, (us // 256) % 256, us % 256 } })
end
midi.tracks[i] = { events = evs }
end
local version = if hmi then "hmi" elseif buffer.readstring(b, base + 8, 6) == "013195" then "013195" else "hmp"
Render.attach(midi, { format = if hmi then "hmi" else "hmp", version = version, rate = rate, loops = ctx.loops })
return midi, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions)
function Hmp.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
local midi, err = Hmp.decode(r, opts)
if not midi then
return nil, err
end
return Render.decoder(midi, opts)
end
return Hmp
+163
View File
@@ -0,0 +1,163 @@
--!strict
-- music/mus: DMX MUS, the music format of Doom, Heretic, Hexen and Strife ("MUS\x1a"). Written from the MUS format
-- description (Vladimir Arnost's "MUS File Format", the DMX event set); wildmidi was used only as a reference converter
-- in tests. Decodes to a Types.Midi (format 0, one track) the way the usual MUS-to-MIDI converters map it: MUS channel
-- 15 is the percussion channel 9, the others get MIDI channels 0..8, 10..15 in order of first use (each starting at
-- volume 127), MUS controllers / system events become MIDI controllers (controller 0 = program change), notes without
-- a volume reuse the channel's last one (127 at first), pitch wheel 0..255 becomes a 14-bit bend. Time: 140 ticks per
-- second (opts.rate), as division 70 at 500000 us per quarter. Renders through codecs/audio/MidiRender (SoundFont /
-- built-in waveforms). meta.source: primaryChannels, secondaryChannels, instruments (the patch list), rate.
-- Not supported: writing (save as .mid through the midi format's encoder).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Render = require("@formats/codecs/audio/MidiRender")
-- ------------------------------------------------------------------------------------------------ contract
local Mus = {
name = "mus",
category = "music",
extensions = { "mus" },
mime = { "audio/x-mus" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/MidiRender" },
caps = { decode = true, encode = false, render = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
rate: number?, -- ticks per second, default 140 (Doom); some players use 70
maxEvents: number?, -- default 2^24
}
-- ------------------------------------------------------------------------------------------------ constants
-- MUS controller / system event number -> MIDI controller (0 is the program change)
local CONTROLLER = { [0] = 0, 0, 0x01, 0x07, 0x0A, 0x0B, 0x5B, 0x5D, 0x40, 0x43, 0x78, 0x7B, 0x7E, 0x7F, 0x79 }
-- ------------------------------------------------------------------------------------------------ sniff
function Mus.sniff(r: Bytes.Reader): number
return if r:peek(4) == "MUS\x1a" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
local readu8 = buffer.readu8
-- the score [p, e) -> events | nil, message
local function score(b: buffer, p: number, e: number, primary: number, maxEvents: number): ({ Types.MidiEvent }?, string?, boolean)
local events: { Types.MidiEvent } = { { tick = 0, type = "controller", channel = 9, data = { 0x07, 127 } } }
local map: { [number]: number } = { [15] = 9 }
local volume: { [number]: number } = {}
local nextChannel = 0
local tick = 0
while p < e do
local ev = readu8(b, p)
p += 1
local kind, mch = bit32.band(bit32.rshift(ev, 4), 7), bit32.band(ev, 15)
if kind == 6 then
return events, nil, false
end
local ch = map[mch]
if not ch then
ch = nextChannel
map[mch] = ch
nextChannel += if nextChannel == 8 then 2 else 1
table.insert(events, { tick = tick, type = "controller", channel = ch, data = { 0x07, 127 } })
end
local need = if kind == 1 then (if p < e and readu8(b, p) >= 128 then 2 else 1) elseif kind == 4 then 2 elseif kind == 5 then 0 else 1
if kind == 7 then
return nil, "unknown event type 7", false
elseif p + need > e then
return events, nil, true
end
local d1, d2 = if need > 0 then readu8(b, p) else 0, if need > 1 then readu8(b, p + 1) else 0
p += need
if kind == 0 then
table.insert(events, { tick = tick, type = "noteOff", channel = ch, data = { d1 % 128, 64 } })
elseif kind == 1 then
if need == 2 then
volume[ch] = math.min(d2, 127)
end
table.insert(events, { tick = tick, type = "noteOn", channel = ch, data = { d1 % 128, volume[ch] or 127 } })
elseif kind == 2 then
table.insert(events, { tick = tick, type = "pitchBend", channel = ch, data = { bit32.band(d1, 1) * 64, bit32.rshift(d1, 1) } })
elseif kind == 3 or kind == 4 then
local c, v = d1, if kind == 3 then (if d1 == 12 then math.min(primary + 1, 127) else 0) else math.min(d2, 127)
if CONTROLLER[c] == nil then
return nil, string.format("unknown controller %d", c), false
end
if kind == 4 and c == 0 then
table.insert(events, { tick = tick, type = "program", channel = ch, data = { v } })
else
table.insert(events, { tick = tick, type = "controller", channel = ch, data = { CONTROLLER[c], v } })
end
end
if #events > maxEvents then
return nil, "limit: more than " .. maxEvents .. " events", false
end
if ev >= 128 then
local delay = 0
repeat
if p >= e then
return events, nil, true
end
local c = readu8(b, p)
p += 1
delay = delay * 128 + c % 128
until c < 128 or delay > 2 ^ 28
tick += delay
end
end
return events, nil, true
end
function Mus.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?)
local o: DecodeOptions = opts or {}
local rate = o.rate or 140
if type(rate) ~= "number" or rate < 1 or rate > 100000 then
return nil, Err.new(Err.ARG, "rate must be 1..100000 ticks per second")
end
if r:peek(4) ~= "MUS\x1a" then
return nil, Err.new(Err.CORRUPT, "not a MUS file")
end
r:skip(4)
local len, start, primary, secondary, ninst = r:u16le(), r:u16le(), r:u16le(), r:u16le(), r:u16le()
r:skip(2)
local instruments = {}
for i = 1, ninst do
instruments[i] = r:u16le()
end
if r.err then
return nil, r.err
end
local size = r.limit - r.base
if start > size then
return nil, Err.new(Err.TRUNCATED, "score starts past the end")
end
local p = r.base + start
local events, msg, truncated = score(r.buf, p, math.min(p + len, r.limit), primary, o.maxEvents or 2 ^ 24)
if not events then
return nil, Err.from(msg :: string, p)
end
local last = events[#events].tick
table.insert(events, 1, { tick = 0, type = "meta", meta = 0x51, data = Render.tempoBytes(70, rate) })
table.insert(events, { tick = last, type = "meta", meta = 0x2F, data = {} })
local midi = Types.Midi.new(70)
midi.format = 0
midi.tracks = { { events = events } }
Render.attach(midi, { format = "mus", primaryChannels = primary, secondaryChannels = secondary, instruments = instruments, rate = rate })
midi.meta.truncated = truncated or p + len > r.limit
return midi, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions)
function Mus.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
local midi, err = Mus.decode(r, opts)
if not midi then
return nil, err
end
return Render.decoder(midi, opts)
end
return Mus
+213
View File
@@ -0,0 +1,213 @@
--!strict
-- music/xmi: Miles Sound System XMIDI (IFF: an optional FORM XDIR with the song count, then CAT XMID of FORM XMID songs,
-- or one FORM XMID; each with TIMB / RBRN chunks and the EVNT event stream). Written from the XMIDI format description
-- (Miles AIL; Ryan Nunn's notes); wildmidi was used only as a reference converter in tests. Decodes one song (opts.track,
-- 1-based, default 1) to a Types.Midi (format 0): interval bytes (< 0x80, summed) become absolute ticks, each note-on's
-- duration becomes a note-off (velocity 64; notes still sounding at the end-of-track event end there), tempo events are dropped: XMIDI plays at a fixed 120 ticks per second
-- (division 60 at 500000 us per quarter). meta.source: songs, song, timbres ({ patch, bank } from TIMB), tempo (the
-- first tempo event's value, unused). Renders through codecs/audio/MidiRender.
-- Not supported: writing; the RBRN branch table (kept as meta.source.branches = count); MT-32 -> GM program mapping.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Chunks = require("@formats/containers/Chunks")
local Render = require("@formats/codecs/audio/MidiRender")
-- ------------------------------------------------------------------------------------------------ contract
local Xmi = {
name = "xmi",
category = "music",
extensions = { "xmi", "xmidi" },
mime = { "audio/x-xmidi" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/audio/MidiRender" },
caps = { decode = true, encode = false, render = true, songs = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
track: number?, -- the song (1-based), default 1
maxEvents: number?, -- default 2^24
}
-- ------------------------------------------------------------------------------------------------ sniff
function Xmi.sniff(r: Bytes.Reader): number
local id, kind = r:peek(4), r:peek(4, 8)
if id == "FORM" and (kind == "XDIR" or kind == "XMID") then
return 1
end
return if id == "CAT " and kind == "XMID" then 0.9 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
local readu8 = buffer.readu8
local DATA = { [8] = 2, [9] = 2, [10] = 2, [11] = 2, [12] = 1, [13] = 1, [14] = 2 }
local TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" }
-- a MIDI variable-length number at p -> value, next p (nil past e)
local function vlq(b: buffer, p: number, e: number): (number?, number)
local v = 0
for _ = 1, 4 do
if p >= e then
return nil, p
end
local c = readu8(b, p)
p += 1
v = v * 128 + c % 128
if c < 128 then
return v, p
end
end
return nil, p
end
local function bytes(b: buffer, p: number, n: number): { number }
local t = table.create(n)
for i = 1, n do
t[i] = readu8(b, p + i - 1)
end
return t
end
-- the EVNT stream [p, e) -> events (note-offs merged in), end tick, first tempo | nil, message
local function events(b: buffer, p: number, e: number, maxEvents: number): ({ Types.MidiEvent }?, any, number?)
local list: { Types.MidiEvent }, offs: { Render.PendingOff } = {}, {}
local tick, tempo = 0, nil
while p < e do
local st = readu8(b, p)
p += 1
if st < 0x80 then
tick += st
elseif st == 0xFF then
if p >= e then
return nil, "truncated meta event"
end
local kind = readu8(b, p)
local n, q = vlq(b, p + 1, e)
if not n or q + n > e then
return nil, "truncated meta event"
end
if kind == 0x2F then
break
elseif kind == 0x51 and n >= 3 then
tempo = tempo or readu8(b, q) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q + 2)
else
table.insert(list, { tick = tick, type = "meta", meta = kind, data = bytes(b, q, n) })
end
p = q + n
elseif st == 0xF0 or st == 0xF7 then
local n, q = vlq(b, p, e)
if not n or q + n > e then
return nil, "truncated sysex"
end
table.insert(list, { tick = tick, type = if st == 0xF0 then "sysex" else "escape", data = bytes(b, q, n) })
p = q + n
elseif st < 0xF0 then
local hi, ch = st // 16, st % 16
local n = DATA[hi]
if p + n > e then
return nil, "truncated event"
end
local d = bytes(b, p, n)
p += n
table.insert(list, { tick = tick, type = TYPES[hi], channel = ch, data = d })
if hi == 9 then
local dur, q = vlq(b, p, e)
if not dur then
return nil, "truncated note duration"
end
p = q
table.insert(offs, { tick = tick + dur, onTick = tick, ev = { tick = tick + dur, type = "noteOff", channel = ch, data = { d[1] % 128, 64 } } })
end
else
return nil, string.format("unexpected status byte 0x%02X", st)
end
if #list + #offs > maxEvents then
return nil, "limit: more than " .. maxEvents .. " events"
end
end
-- the sequence stops at its end-of-track event: notes still sounding end there (wildmidi leaves them hanging)
for _, o in offs do
if o.tick > tick then
o.tick = tick
o.ev.tick = tick
end
end
return Render.merge(list, offs), tick, tempo
end
-- the songs: { { evnt = Chunk, timb = Chunk? } } from the IFF tree
local function songs(b: buffer, base: number, limit: number): { { [string]: Chunks.Chunk } }
local out = {}
local function form(c: Chunks.Chunk)
local song = {}
for _, s in Chunks.walk(b, c.offset + 4, c.offset + c.avail, Chunks.IFF) do
song[s.id] = song[s.id] or s
end
if song.EVNT then
table.insert(out, song)
end
end
for _, c in Chunks.walk(b, base, limit, Chunks.IFF) do
local kind = if c.avail >= 4 then buffer.readstring(b, c.offset, 4) else ""
if c.id == "FORM" and kind == "XMID" then
form(c)
elseif c.id == "CAT " and kind == "XMID" then
for _, s in Chunks.walk(b, c.offset + 4, c.offset + c.avail, Chunks.IFF) do
if s.id == "FORM" and s.avail >= 4 and buffer.readstring(b, s.offset, 4) == "XMID" then
form(s)
end
end
end
end
return out
end
function Xmi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?)
local o: DecodeOptions = opts or {}
if Xmi.sniff(r) == 0 then
return nil, Err.new(Err.CORRUPT, "not an XMIDI file")
end
local list = songs(r.buf, r.base, r.limit)
local index = o.track or 1
if #list == 0 then
return nil, Err.new(Err.CORRUPT, "no XMID song with an EVNT chunk")
elseif type(index) ~= "number" or index < 1 or index > #list or index % 1 ~= 0 then
return nil, Err.new(Err.ARG, string.format("track must be 1..%d", #list))
end
local song = list[index]
local ev = song.EVNT
local evs, endTick, tempo = events(r.buf, ev.offset, ev.offset + ev.avail, o.maxEvents or 2 ^ 24)
if not evs then
return nil, Err.from(endTick :: string, ev.offset)
end
local last = math.max(endTick :: number, if #evs > 0 then evs[#evs].tick else 0)
table.insert(evs, 1, { tick = 0, type = "meta", meta = 0x51, data = Render.tempoBytes(60, 120) })
table.insert(evs, { tick = last, type = "meta", meta = 0x2F, data = {} })
local timbres = {}
local tb = song.TIMB
if tb and tb.avail >= 2 then
for i = 0, math.min(buffer.readu16(r.buf, tb.offset), (tb.avail - 2) // 2) - 1 do
table.insert(timbres, { patch = readu8(r.buf, tb.offset + 2 + i * 2), bank = readu8(r.buf, tb.offset + 3 + i * 2) })
end
end
local midi = Types.Midi.new(60)
midi.format = 0
midi.tracks = { { events = evs } }
Render.attach(midi, { format = "xmi", songs = #list, song = index, timbres = timbres, tempo = tempo, branches = if song.RBRN and song.RBRN.avail >= 2 then buffer.readu16(r.buf, song.RBRN.offset) else 0 })
midi.meta.truncated = ev.truncated
return midi, nil
end
-- ------------------------------------------------------------------------------------------------ open
-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + MidiRender.RenderOptions)
function Xmi.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
local midi, err = Xmi.decode(r, opts)
if not midi then
return nil, err
end
return Render.decoder(midi, opts)
end
return Xmi