Files
rosetta/src/Formats/music/mus/init.luau
T

164 lines
6.8 KiB
Luau

--!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