--!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("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Types = require("@rosetta/Types") local Chunks = require("@rosetta/containers/Chunks") local Render = require("@rosetta/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: { number } = table.create(n) :: { number } 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 rb = song.RBRN local branches = if rb and rb.avail >= 2 then buffer.readu16(r.buf, rb.offset) else 0 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 = branches }) 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