diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 35547d4..07ec114 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -74,13 +74,16 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | subtitle | srt | .srt | yes | yes | styles: false | `tests/subtitle/srt.luau` | | subtitle | vtt | .vtt .webvtt | yes | yes | styles: true | `tests/subtitle/vtt.luau` | | music | ahx | .ahx .thx | yes | - | render: true, channels: 4, 4, subsongs: true | `tests/music/ahx.luau` | +| music | hmp | .hmp .hmi | yes | - | render: true, hmi: true | `tests/music/hmp.luau` | | music | hvl | .hvl | yes | - | render: true, channels: 4, 16, subsongs: true | `tests/music/hvl.luau` | | music | it | .it | yes | - | render: true, channels: 1, 64, compressedSamples: true | `tests/music/it.luau` | | music | midi | .mid .midi .smf .kar .rmi | yes | yes | formats: 0, 1, 2, render: true, streaming: true, rmid: true | `tests/music/midi.luau` | | music | mod | .mod .m15 .stk .nst | yes | yes | render: true, channels: 1, 32 | `tests/music/mod.luau` | +| music | mus | .mus | yes | - | render: true | `tests/music/mus.luau` | | music | s3m | .s3m | yes | - | render: true, channels: 1, 32 | `tests/music/s3m.luau` | | music | sf2 | .sf2 | yes | - | sm24: true, sf3: false | `tests/music/sf2.luau` | | music | xm | .xm | yes | yes | render: true, channels: 1, 64 | `tests/music/xm.luau` | +| music | xmi | .xmi .xmidi | yes | - | render: true, songs: true | `tests/music/xmi.luau` | | playlist | m3u | .m3u .m3u8 | yes | yes | hls: true | `tests/playlist/m3u.luau` | | playlist | pls | .pls | yes | yes | | `tests/playlist/pls.luau` | | playlist | xspf | .xspf | yes | yes | | `tests/playlist/xspf.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 65a6e9b..a3d7698 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -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", diff --git a/src/Formats/codecs/audio/MidiRender.luau b/src/Formats/codecs/audio/MidiRender.luau index 8e41b63..e2ed3df 100644 --- a/src/Formats/codecs/audio/MidiRender.luau +++ b/src/Formats/codecs/audio/MidiRender.luau @@ -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) diff --git a/src/Formats/music/hmp/init.luau b/src/Formats/music/hmp/init.luau new file mode 100644 index 0000000..7645f67 --- /dev/null +++ b/src/Formats/music/hmp/init.luau @@ -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 diff --git a/src/Formats/music/mus/init.luau b/src/Formats/music/mus/init.luau new file mode 100644 index 0000000..c36d954 --- /dev/null +++ b/src/Formats/music/mus/init.luau @@ -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 diff --git a/src/Formats/music/xmi/init.luau b/src/Formats/music/xmi/init.luau new file mode 100644 index 0000000..47bc433 --- /dev/null +++ b/src/Formats/music/xmi/init.luau @@ -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 diff --git a/tests/music/_midivar.luau b/tests/music/_midivar.luau new file mode 100644 index 0000000..2461821 --- /dev/null +++ b/tests/music/_midivar.luau @@ -0,0 +1,92 @@ +-- tests/music/_midivar: shared helper of the MUS / XMI / HMP tests (not a test itself): compares a decoded Midi's +-- channel events (codecs/audio/MidiRender.timeline: play order, seconds) with wildmidi -x's conversion +-- (tools/fixtures/_midivar.py): notes on / off, program changes, pitch bends (MSB) and controllers, matched per +-- (kind, channel, data) in time order, times within 0.1 ms + 1e-5 relative. +local Render = require("@formats/codecs/audio/MidiRender") + +local M = {} + +local function kindOf(status: number, d1: number, d2: number): string? + local hi = status // 16 + if hi == 9 and d2 > 0 then + return "on" + elseif hi == 8 or hi == 9 then + return "off" + elseif hi == 12 then + return "program" + elseif hi == 14 then + return "bend" + elseif hi == 11 then + return "cc" + end + return nil +end + +-- the comparable events of a list of { seconds, status, d1, d2 }: key -> { seconds } +local function index(list: { { number } }, opts: any): ({ [string]: { number } }, { [string]: number }) + local by: { [string]: { number } }, counts: { [string]: number } = {}, {} + for _, e in list do + local k = kindOf(e[2], e[3], e[4]) + if k and not (opts.skip and opts.skip[k]) then + local d = if k == "bend" then e[4] elseif k == "cc" then e[3] * 256 + e[4] else e[3] + local key = string.format("%s %d %d", k, e[2] % 16, d) + by[key] = by[key] or {} + table.insert(by[key], e[1]) + counts[k] = (counts[k] or 0) + 1 + end + end + return by, counts +end + +-- compare(t, midi, ref, label, opts?) -> worst time difference (s). opts.skip = { cc = true, ... } +function M.compare(t: any, midi: any, ref: any, label: string, opts: any?): number + local o = opts or {} + local tl = Render.timeline(midi) + local ours = {} + local refEnd = 0 + for _, e in ref.events do + refEnd = math.max(refEnd, e[1]) + end + for i = 1, #tl.time do + -- o.hangingOffs: wildmidi drops the note-offs past the end of the song (we end those notes at the end) + local hanging = o.hangingOffs and kindOf(tl.status[i], tl.d1[i], tl.d2[i]) == "off" and tl.time[i] > refEnd + 1e-6 + if not hanging then + table.insert(ours, { tl.time[i], tl.status[i], tl.d1[i], tl.d2[i] }) + end + end + local a, ca = index(ours, o) + local b, cb = index(ref.events, o) + for _, k in { "on", "off", "program", "bend", "cc" } do + if not (o.skip and o.skip[k]) then + t:eq(ca[k] or 0, cb[k] or 0, label .. ": " .. k .. " events") + end + end + local worst, bad = 0, 0 + for key, times in b do + local mine = a[key] or {} + table.sort(times) + table.sort(mine) + if #mine ~= #times then + bad += 1 + if bad <= 3 then + t:check(false, string.format("%s: %s: %d events, wildmidi %d", label, key, #mine, #times)) + end + else + for i, tm in times do + local d = math.abs(mine[i] - tm) + worst = math.max(worst, d) + if d > 1e-4 + 1e-5 * tm then + bad += 1 + if bad <= 3 then + t:check(false, string.format("%s: %s at %.4f s, wildmidi %.4f s", label, key, mine[i], tm)) + end + end + end + end + end + t:check(bad == 0, label .. ": event times match wildmidi's") + t:note("%-12s %4d notes, worst time difference %.2g s", label, ca.on or 0, worst) + return worst +end + +return M diff --git a/tests/music/hmp.luau b/tests/music/hmp.luau new file mode 100644 index 0000000..944f2a8 --- /dev/null +++ b/tests/music/hmp.luau @@ -0,0 +1,57 @@ +-- music/hmp tests: HMP (old and "013195" headers, several tick rates) and HMI files (tools/fixtures/hmp.py) decoded and +-- compared with wildmidi -x's conversion (notes, HMI note durations, programs, bends, controllers), the FE / loop +-- events skipped, a render, bad input, and the fuzz no-throw pass. +local T = require("@tests/T") +local V = require("@tests/music/_midivar") +local Hmp = require("@formats/music/hmp") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Cases = require("@tests/gen/hmp_cases") + +local t = T.suite("hmp") + +local function decode(s: string, opts: any?): (any, any) + return Hmp.decode(Bytes.reader(buffer.fromstring(s)), opts) +end + +t:eq(Hmp.name, "hmp", "name") +t:check(Hmp.caps.decode and not Hmp.caps.encode, "caps") +t:eq(Hmp.sniff(Bytes.reader(buffer.fromstring("HMIMIDIP013195"))), 1, "sniff HMP") +t:eq(Hmp.sniff(Bytes.reader(buffer.fromstring("HMI-MIDISONG061595"))), 1, "sniff HMI") +t:eq(Hmp.sniff(Bytes.reader(buffer.fromstring("HMI-MIDITRACK"))), 0, "sniff other") + +local samples = {} +for _, c in Cases do + local m, err = decode(c.data) + t:check(m, c.name .. ": " .. tostring(err)) + if m then + t:eq(m.meta.source.format, c.kind, c.name .. ": kind") + t:eq(m.meta.source.rate, c.rate, c.name .. ": tick rate") + V.compare(t, m, c.ref, c.name) + end + table.insert(samples, buffer.fromstring(c.data)) +end + +do + local m = assert(decode(Cases[1].data)) + local dec = m:render({ sampleRate = 22050, tail = 0.2 }) + t:check(math.abs(dec.duration - (m.meta.length + 0.2)) < 0.01, "render duration") +end + +local _, e1 = decode("HMIMIDIP") +t:eq(e1 and e1.code, Err.TRUNCATED, "short header") +local bad = string.sub(Cases[1].data, 1, 0x308 + 20) +local _, e2 = decode(bad) +t:eq(e2 and e2.code, Err.TRUNCATED, "truncated chunk") + +t:fuzz("decode", function(b: buffer) + return Hmp.decode(Bytes.reader(b)) +end, samples) +t:fuzz("decode + render", function(b: buffer) + local m = Hmp.decode(Bytes.reader(b)) + if m and m.meta.length < 30 then + m:render({ sampleRate = 8000 }):read(2000) + end + return m +end, samples, { mutations = 60, garbage = 10 }) +t:done() diff --git a/tests/music/mus.luau b/tests/music/mus.luau new file mode 100644 index 0000000..8194775 --- /dev/null +++ b/tests/music/mus.luau @@ -0,0 +1,93 @@ +-- music/mus tests: Doom MUS files (tools/fixtures/mus.py) decoded and compared with wildmidi -x's conversion (notes, +-- programs, pitch bend MSB, controllers; times at wildmidi's tick rate), system events / measure ends, the tick rate +-- option, a render, bad input, and the fuzz no-throw pass. +local T = require("@tests/T") +local V = require("@tests/music/_midivar") +local Mus = require("@formats/music/mus") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Render = require("@formats/codecs/audio/MidiRender") +local Cases = require("@tests/gen/mus_cases") +local Measures = require("@tests/gen/mus_measures") + +local t = T.suite("mus") + +local function decode(s: string, opts: any?): (any, any) + return Mus.decode(Bytes.reader(buffer.fromstring(s)), opts) +end + +t:eq(Mus.name, "mus", "name") +t:check(Mus.caps.decode and not Mus.caps.encode, "caps") +t:eq(Mus.sniff(Bytes.reader(buffer.fromstring("MUS\x1a"))), 1, "sniff") +t:eq(Mus.sniff(Bytes.reader(buffer.fromstring("MThd"))), 0, "sniff MThd") + +local samples = {} +for _, c in Cases do + local m, err = decode(c.data, { rate = c.rate }) + t:check(m, c.name .. ": " .. tostring(err)) + if m then + t:eq(m.kind, "midi", c.name .. ": kind") + t:eq(m.meta.source.format, "mus", c.name .. ": source") + t:eq(#m.meta.source.instruments, 3, c.name .. ": instrument list") + V.compare(t, m, c.ref, c.name) + -- Doom's 140 Hz: the same events, times scaled by rate / 140 + local d = assert(decode(c.data)) + t:check(math.abs(d.meta.length * 140 - m.meta.length * c.rate) < 1e-5 * d.meta.length * 140 + 1e-6, c.name .. ": 140 Hz default") + end + table.insert(samples, buffer.fromstring(c.data)) +end + +-- system events and measure ends inserted with no delay: the same notes at the same times, more controllers +do + local p, q = assert(decode(Measures.plain)), assert(decode(Measures.marked)) + local a, b = Render.timeline(p), Render.timeline(q) + local function notes(tl: any): { string } + local out = {} + for i = 1, #tl.time do + if tl.status[i] // 16 == 8 or tl.status[i] // 16 == 9 then + table.insert(out, string.format("%.6f %d %d %d", tl.time[i], tl.status[i], tl.d1[i], tl.d2[i])) + end + end + return out + end + local na, nb = notes(a), notes(b) + t:eq(#nb, #na, "measures: note count") + t:eq(table.concat(nb, ","), table.concat(na, ","), "measures: same notes") + t:check(#b.time > #a.time, "measures: system events become controllers") + t:eq(q.meta.length, p.meta.length, "measures: same length") +end + +-- a render through the built-in waveforms +do + local m = assert(decode(Cases[1].data)) + local dec = m:render({ sampleRate = 22050, tail = 0.2 }) + t:check(dec.frames > 0 and math.abs(dec.duration - (m.meta.length + 0.2)) < 0.01, "render duration") + local buf, n = dec:read(dec.frames) + local peak = 0 + for i = 0, n * 2 - 1 do + peak = math.max(peak, math.abs(buffer.readf32(buf, i * 4))) + end + t:check(peak > 0.01, "render makes sound") +end + +-- bad input +local _, e1 = decode("MUS\x1a\1\0") +t:eq(e1 and e1.code, Err.TRUNCATED, "short header") +local _, e2 = decode("MUS\x1a\2\0\200\0\1\0\0\0\0\0\0\0") +t:eq(e2 and e2.code, Err.TRUNCATED, "score past the end") +local _, e3 = decode("MUS\x1a\2\0\16\0\1\0\0\0\0\0\0\0\112\0") +t:eq(e3 and e3.code, Err.CORRUPT, "event type 7") +local _, e4 = decode(Cases[1].data, { rate = 0 }) +t:eq(e4 and e4.code, Err.ARG, "bad rate") + +t:fuzz("decode", function(b: buffer) + return Mus.decode(Bytes.reader(b)) +end, samples) +t:fuzz("decode + render", function(b: buffer) + local m = Mus.decode(Bytes.reader(b)) + if m and m.meta.length < 30 then + m:render({ sampleRate = 8000 }):read(2000) + end + return m +end, samples, { mutations = 60, garbage = 10 }) +t:done() diff --git a/tests/music/xmi.luau b/tests/music/xmi.luau new file mode 100644 index 0000000..e1552f4 --- /dev/null +++ b/tests/music/xmi.luau @@ -0,0 +1,73 @@ +-- music/xmi tests: XMIDI files (tools/fixtures/xmi.py: XDIR + CAT XMID with one or two songs, a bare FORM XMID, with +-- and without TIMB) decoded and compared with wildmidi -x's conversion of song 1 (notes from durations, programs, +-- bends, controllers; 120 Hz), song selection, export to SMF, a render, bad input, and the fuzz no-throw pass. +local T = require("@tests/T") +local V = require("@tests/music/_midivar") +local Xmi = require("@formats/music/xmi") +local Midi = require("@formats/music/midi") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Cases = require("@tests/gen/xmi_cases") + +local t = T.suite("xmi") + +local function decode(s: string, opts: any?): (any, any) + return Xmi.decode(Bytes.reader(buffer.fromstring(s)), opts) +end + +t:eq(Xmi.name, "xmi", "name") +t:check(Xmi.caps.decode and not Xmi.caps.encode, "caps") +t:eq(Xmi.sniff(Bytes.reader(buffer.fromstring("FORM\0\0\0\0XDIR"))), 1, "sniff XDIR") +t:eq(Xmi.sniff(Bytes.reader(buffer.fromstring("FORM\0\0\0\0AIFF"))), 0, "sniff AIFF") + +local samples = {} +for _, c in Cases do + local m, err = decode(c.data) + t:check(m, c.name .. ": " .. tostring(err)) + if m then + t:eq(m.meta.source.songs, c.songs, c.name .. ": songs") + t:eq(m.division, 60, c.name .. ": division") + V.compare(t, m, c.ref, c.name, { hangingOffs = true }) + if c.songs > 1 then + local s2 = assert(decode(c.data, { track = 2 })) + t:eq(s2.meta.source.song, 2, c.name .. ": song 2") + t:check(#s2.tracks[1].events ~= #m.tracks[1].events, c.name .. ": song 2 differs") + local _, e = decode(c.data, { track = 3 }) + t:eq(e and e.code, Err.ARG, c.name .. ": no song 3") + end + -- export to a Standard MIDI File and back: the same timeline + local smf = assert(Midi.encode(m)) + local back = assert(Midi.decode(Bytes.reader(smf))) + t:check(math.abs(back.meta.length - m.meta.length) < 1e-9, c.name .. ": SMF export keeps the timing") + end + table.insert(samples, buffer.fromstring(c.data)) +end + +do + local m = assert(decode(Cases[1].data)) + local dec = m:render({ sampleRate = 22050, tail = 0.2 }) + t:check(math.abs(dec.duration - (m.meta.length + 0.2)) < 0.01, "render duration") + local buf, n = dec:read(dec.frames) + local peak = 0 + for i = 0, n * 2 - 1 do + peak = math.max(peak, math.abs(buffer.readf32(buf, i * 4))) + end + t:check(peak > 0.01, "render makes sound") +end + +local _, e1 = decode("FORM\0\0\0\4XDIR") +t:eq(e1 and e1.code, Err.CORRUPT, "no songs") +local _, e2 = decode("FORM\0\0\0\14XMIDEVNT\0\0\0\2\144\60") +t:eq(e2 and e2.code, Err.TRUNCATED, "truncated note") + +t:fuzz("decode", function(b: buffer) + return Xmi.decode(Bytes.reader(b)) +end, samples) +t:fuzz("decode + render", function(b: buffer) + local m = Xmi.decode(Bytes.reader(b)) + if m and m.meta.length < 30 then + m:render({ sampleRate = 8000 }):read(2000) + end + return m +end, samples, { mutations = 60, garbage = 10 }) +t:done() diff --git a/tools/fixtures/_midivar.py b/tools/fixtures/_midivar.py new file mode 100644 index 0000000..c360848 --- /dev/null +++ b/tools/fixtures/_midivar.py @@ -0,0 +1,320 @@ +# MIDI-variant fixture helpers (not a generator; tools/fixtures/mus.py, xmi.py and hmp.py load it): small writers for +# Doom MUS, Miles XMIDI and HMI HMP, random event streams, and the reference conversion through wildmidi -x +# (nixpkgs#wildmidi: it writes a Standard MIDI File; only its event stream is used, read back by the small SMF reader +# below into channel events with times in seconds). +import os, random, struct, subprocess, tempfile + + +def vlq(v): + out = [v & 127] + v >>= 7 + while v: + out.insert(0, (v & 127) | 128) + v >>= 7 + return bytes(out) + + +def vlq_hmp(v): + """HMP deltas: 7-bit groups least significant first, the last byte has bit 7 set""" + out = [] + while True: + b = v & 127 + v >>= 7 + if v == 0: + out.append(b | 128) + return bytes(out) + out.append(b) + + +# ---------------------------------------------------------------------------------------------------- MUS +def write_mus(events, instruments=(), primary=4, secondary=0): + """events: [(delay_after, type, channel, data bytes)]; the last flag is set when delay_after > 0""" + score = b"" + for delay, typ, ch, data in events: + score += bytes([(0x80 if delay else 0) | (typ << 4) | ch]) + bytes(data) + if delay: + score += vlq(delay) + hdr_len = 16 + 2 * len(instruments) + hdr = b"MUS\x1a" + struct.pack(" 0 inserts that many system events (type 3, which wildmidi misreads: it takes two data + bytes) and measure ends (type 5, which wildmidi refuses), each with no delay, without changing anything else""" + ev = [] + held = {} + for ch in [0, 1, 2, 15]: + ev.append((0, 4, ch, [0, rng.randint(0, 127) if ch != 15 else 0])) # program change + for _ in range(n): + ch = rng.choice([0, 1, 2, 3, 15, 9]) + r = rng.random() + delay = rng.choice([0, 0, 1, 5, 17, 140, 200]) + if r < 0.45: + note = rng.randint(30, 90) + if rng.random() < 0.6: + ev.append((delay, 1, ch, [note | 0x80, rng.randint(1, 127)])) + else: + ev.append((delay, 1, ch, [note])) + held.setdefault(ch, []).append(note) + elif r < 0.75 and held.get(ch): + ev.append((delay, 0, ch, [held[ch].pop(0)])) + elif r < 0.85: + ev.append((delay, 2, ch, [rng.randint(0, 255)])) + else: + ev.append((delay, 4, ch, [rng.randint(0, 9), rng.randint(0, 127)])) + for ch, notes in held.items(): + for nt in notes: + ev.append((3, 0, ch, [nt])) + xr = random.Random(extras) + for _ in range(extras): + at = xr.randint(1, len(ev) - 1) + ch = ev[at][2] + ev.insert(at, (0, 5, ch, []) if xr.random() < 0.5 else (0, 3, ch, [xr.choice([10, 11, 12, 13, 14])])) + ev.append((0, 6, 0, [])) + return write_mus(ev, instruments=[1, 30, 128 + 7]) + + +# ---------------------------------------------------------------------------------------------------- XMI +def iff(cid, body): + return cid + struct.pack(">I", len(body)) + body + (b"\0" if len(body) % 2 else b"") + + +def xmi_events(events): + """events: [(delay, bytes)]: a delay is written as interval bytes (each <= 0x7F) before the event""" + out = b"" + for delay, ev in events: + while delay > 0x7f: + out += b"\x7f" + delay -= 0x7f + if delay: + out += bytes([delay]) + out += ev + return out + + +def write_xmi(songs, with_xdir=True, timb=True): + forms = [] + for evs in songs: + body = b"XMID" + if timb: + body += iff(b"TIMB", struct.pack(" HMP track data (ends with an end-of-track meta)""" + return b"".join(vlq_hmp(d) + e for d, e in events) + + +def random_hmp_tracks(rng, ntracks=3, n=60, running=True): + tracks = [hmp_track([(0, b"\xff\x2f\x00")])] # track 0: tempo / meta only, as in game files + for t in range(1, ntracks): + ch = t - 1 if t < 4 else 9 + ev = [(0, bytes([0xC0 | ch, rng.randint(0, 127)]))] + on = [] + running_ok, running = running, False + for _ in range(n): + d = rng.choice([0, 0, 5, 30, 60, 120, 400]) + r = rng.random() + if r < 0.5: + note = rng.randint(30, 90) + on.append(note) + # running status (status byte left out) now and then + ev.append((d, (b"" if running else bytes([0x90 | ch])) + bytes([note, rng.randint(1, 127)]))) + running = running_ok and rng.random() < 0.5 + elif r < 0.8 and on: + ev.append((d, bytes([0x80 | ch, on.pop(0), 64]))) + running = False + elif r < 0.9: + ev.append((d, bytes([0xB0 | ch, rng.choice([7, 10, 64]), rng.randint(0, 127)]))) + running = False + else: + ev.append((d, bytes([0xE0 | ch, rng.randint(0, 127), rng.randint(0, 127)]))) + running = False + for note in on: + ev.append((10, bytes([0x80 | ch, note, 0]))) + ev.append((0, b"\xff\x2f\x00")) + tracks.append(hmp_track(ev)) + return tracks + + +# ---------------------------------------------------------------------------------------------------- wildmidi +def read_smf(data): + """-> (division, [(tick, track, status, d1, d2)] channel events, [(tick, us)] tempos); format 2: track 1 only (its + first song: wildmidi writes every XMIDI song as a track of a format 2 file)""" + assert data[:4] == b"MThd" + fmt, ntrk, div = struct.unpack(">HHH", data[8:14]) + if fmt == 2: + ntrk = 1 + p = 8 + struct.unpack(">I", data[4:8])[0] + events, tempos = [], [] + for ti in range(ntrk): + assert data[p:p + 4] == b"MTrk" + n = struct.unpack(">I", data[p + 4:p + 8])[0] + q, e = p + 8, p + 8 + n + tick, run = 0, 0 + while q < e: + d = 0 + while True: + c = data[q] + q += 1 + d = d * 128 + (c & 127) + if c < 128: + break + tick += d + st = data[q] + if st < 0x80: + st = run + else: + q += 1 + if st == 0xFF: + typ = data[q] + q += 1 + ln = 0 + while True: + c = data[q] + q += 1 + ln = ln * 128 + (c & 127) + if c < 128: + break + if typ == 0x51: + tempos.append((tick, int.from_bytes(data[q:q + 3], "big"))) + q += ln + elif st in (0xF0, 0xF7): + ln = 0 + while True: + c = data[q] + q += 1 + ln = ln * 128 + (c & 127) + if c < 128: + break + q += ln + else: + run = st + k = 1 if st >> 4 in (0xC, 0xD) else 2 + d1 = data[q] + d2 = data[q + 1] if k == 2 else 0 + q += k + events.append((tick, ti, st, d1, d2)) + p = e + return div, events, tempos + + +def seconds(div, tempos, tick): + tempos = sorted(tempos) + t, last, us = 0.0, 0, 500000 + for tk, u in tempos: + if tk >= tick: + break + t += (tk - last) * us / 1e6 / div + last, us = tk, u + return t + (tick - last) * us / 1e6 / div + + +def wildmidi(ctx, data, ext, args=()): + """the reference: wildmidi -x's SMF as { division, tempo (first), events = { {time, status, d1, d2} } }""" + with tempfile.TemporaryDirectory() as d: + src = os.path.join(d, "in." + ext) + out = os.path.join(d, "out.mid") + with open(src, "wb") as f: + f.write(data) + r = subprocess.run(["nix", "shell", "nixpkgs#wildmidi", "-c", "wildmidi"] + list(args) + ["-x", out, src], + capture_output=True) + if not os.path.exists(out): + raise RuntimeError("wildmidi failed: " + r.stdout.decode(errors="replace")[-400:] + r.stderr.decode(errors="replace")[-400:]) + smf = open(out, "rb").read() + div, events, tempos = read_smf(smf) + events.sort(key=lambda e: (e[0], e[1])) + return {"division": div, "tempo": tempos[0][1] if tempos else 500000, + "events": [[seconds(div, tempos, tk), st, d1, d2] for tk, _, st, d1, d2 in events]} + + +# ---------------------------------------------------------------------------------------------------- HMI +def write_hmi(tracks, bpm=120): + """tracks: [bytes of event data (MIDI deltas; note-ons followed by a duration)]""" + hdr_len = 0x5B + head = bytearray(b"HMI-MIDISONG061595".ljust(370, b"\0")) + head[212] = bpm + head[228] = len(tracks) + table = b"" + body = b"" + at = 370 + 4 * len(tracks) + for data in tracks: + table += struct.pack("