--!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("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Types = require("@rosetta/Types") local Render = require("@rosetta/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: { number } = table.create(n) :: { number } 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), nil 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", nil 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), nil 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