--!strict -- music/midi/Smf: Standard MIDI File chunks <-> Types.Midi. Reads MThd / MTrk (formats 0, 1, 2; PPQ and SMPTE -- divisions; running status, also across meta / sysex events as most players accept), skips unknown chunks, unwraps -- RIFF RMID. Writes MThd + MTrk with optional running status; with running status on (the default) the bytes are -- those python mido writes for the same events (running status reset after meta / sysex, one end-of-track at the -- end, mid-track end-of-track events dropped). Written from the SMF 1.0 specification (no third-party code). local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Smf = {} local readu8 = buffer.readu8 local CHANNEL_TYPES = { [8] = "noteOff", [9] = "noteOn", [10] = "aftertouch", [11] = "controller", [12] = "program", [13] = "channelPressure", [14] = "pitchBend" } local TYPE_STATUS = { noteOff = 0x80, noteOn = 0x90, aftertouch = 0xA0, controller = 0xB0, program = 0xC0, channelPressure = 0xD0, pitchBend = 0xE0 } Smf.TYPE_STATUS = TYPE_STATUS export type ReadOptions = { strict: boolean?, -- a truncated track / file is an error (default false: keep the events read so far, meta.truncated) maxEvents: number?, -- default 2^24 } export type WriteOptions = { runningStatus: boolean?, -- default true } local function bytesOf(b: buffer, p: number, n: number): { number } local t: { number } = table.create(n) for i = 0, n - 1 do t[i + 1] = readu8(b, p + i) end return t end local function text(data: { number }): string local parts = table.create(#data) for i, c in data do parts[i] = string.char(c) end return table.concat(parts) end Smf.text = text -- ------------------------------------------------------------------------------------------------ read -- one MTrk body [p, e): events | nil, message, truncated local function readTrack(b: buffer, p: number, e: number, budget: { number }): ({ Types.MidiEvent }?, string?, boolean) local events: { Types.MidiEvent } = {} local tick = 0 local running = 0 while p < e do -- delta time local delta, n = 0, 0 repeat if p >= e then return events, nil, true end local c = readu8(b, p) p += 1 n += 1 delta = delta * 128 + c % 128 if n > 4 then return nil, "delta time longer than 4 bytes", false end until c < 128 tick += delta if p >= e then return events, nil, true end local status = readu8(b, p) if status < 0x80 then if running == 0 then return nil, "running status without a previous status byte", false end status = running else p += 1 if status < 0xF0 then running = status end end budget[1] -= 1 if budget[1] < 0 then return nil, "LIMIT", false end if status == 0xFF or status == 0xF0 or status == 0xF7 then local mtype = 0 if status == 0xFF then if p >= e then return events, nil, true end mtype = readu8(b, p) p += 1 end local len, m = 0, 0 repeat if p >= e then return events, nil, true end local c = readu8(b, p) p += 1 m += 1 len = len * 128 + c % 128 if m > 4 then return nil, "length longer than 4 bytes", false end until c < 128 if p + len > e then return events, nil, true end local data = bytesOf(b, p, len) p += len if status == 0xFF then table.insert(events, { tick = tick, type = "meta", meta = mtype, data = data }) else table.insert(events, { tick = tick, type = if status == 0xF0 then "sysex" else "escape", data = data }) end elseif status >= 0xF0 then return nil, string.format("unexpected status byte 0x%02x in a track", status), false else local kind = status // 16 local count = if kind == 12 or kind == 13 then 1 else 2 if p + count > e then return events, nil, true end local d1 = readu8(b, p) local d2 = if count == 2 then readu8(b, p + 1) else 0 if d1 >= 128 or d2 >= 128 then return nil, "data byte over 127", false end p += count table.insert(events, { tick = tick, type = CHANNEL_TYPES[kind], channel = status % 16, data = if count == 2 then { d1, d2 } else { d1 }, }) end end return events, nil, false end -- read(r, opts?) -> Midi | nil, Err function Smf.read(r: Bytes.Reader, opts: ReadOptions?): (Types.Midi?, Err.Err?) local strict = opts and opts.strict or false local budget = { opts and opts.maxEvents or 2 ^ 24 } local b = r.buf local base, limit = r.base, r.limit local rmid = false -- RIFF RMID: the SMF is the "data" chunk if r:peek(4) == "RIFF" and r:peek(4, 8) == "RMID" then local q = base + 12 local found = false while q + 8 <= limit do local id = buffer.readstring(b, q, 4) local size = buffer.readu32(b, q + 4) if id == "data" then base = q + 8 limit = math.min(limit, base + size) found = true break end q += 8 + size + size % 2 end if not found then return nil, Err.new(Err.CORRUPT, "RMID without a data chunk", r.base) end rmid = true end local h = Bytes.reader(b, base, limit - base) if h:string(4) ~= "MThd" then return nil, Err.new(Err.CORRUPT, "no MThd header", base) end local hlen = h:u32be() local format, ntrks, division = h:u16be(), h:u16be(), h:i16be() if h.err then return nil, h.err end if hlen < 6 then return nil, Err.new(Err.CORRUPT, "MThd shorter than 6 bytes", base + 4) end if format > 2 then return nil, Err.new(Err.UNSUPPORTED, "SMF format " .. format, base + 8) end if division == 0 then return nil, Err.new(Err.CORRUPT, "zero ticks per quarter note", base + 12) end local midi = Types.Midi.new(division) midi.format = format local truncated = false local p = base + 8 + hlen while #midi.tracks < ntrks and p + 8 <= limit do local id = buffer.readstring(b, p, 4) local size = bit32.byteswap(buffer.readu32(b, p + 4)) local s = p + 8 local e = s + size if e > limit then e = limit truncated = true end if id == "MTrk" then local events, msg, short = readTrack(b, s, e, budget) if not events then if msg == "LIMIT" then return nil, Err.new(Err.LIMIT, "over the event limit") end return nil, Err.new(Err.CORRUPT, msg or "bad track", s) end truncated = truncated or short local track: { events: { Types.MidiEvent }, name: string? } = { events = events, name = nil } for _, ev in events do if ev.type == "meta" and ev.meta == 3 then track.name = text(ev.data :: { number }) break end end table.insert(midi.tracks, track) end p = s + size end if #midi.tracks < ntrks and p < limit then truncated = true elseif #midi.tracks < ntrks then truncated = true end if truncated and strict then return nil, Err.new(Err.TRUNCATED, "the file ends inside a track (or before all tracks)") end midi.meta.declaredTracks = ntrks midi.meta.truncated = truncated midi.meta.rmid = rmid if division < 0 then local fps = -(division // 256) midi.meta.smpte = { fps = if fps == 29 then 29.97 else fps, ticksPerFrame = division % 256 } end return midi, nil end -- ------------------------------------------------------------------------------------------------ write local function vlq(w: Bytes.Writer, v: number) if v < 128 then w:u8(v) return end local bytes = {} while v > 0 do table.insert(bytes, 1, v % 128) v = v // 128 end for i, c in bytes do w:u8(if i < #bytes then c + 128 else c) end end local function byteList(d: any, want: number?): { number }? if type(d) ~= "table" then return if want == 0 then {} else nil end for i, v in d do if type(i) ~= "number" or type(v) ~= "number" or v < 0 or v > 255 or v % 1 ~= 0 then return nil end end if want and #d < want then return nil end return d end -- write(midi, opts?) -> buffer | nil, Err function Smf.write(midi: Types.Midi, opts: WriteOptions?): (buffer?, Err.Err?) if type(midi) ~= "table" or type(midi.tracks) ~= "table" then return nil, Err.new(Err.ARG, "midi encode: needs a Midi value with tracks") end local running = not (opts and opts.runningStatus == false) local format = midi.format or 1 local division = midi.division or 480 if type(format) ~= "number" or format < 0 or format > 2 or format % 1 ~= 0 then return nil, Err.new(Err.ARG, "midi encode: format must be 0, 1 or 2") end if type(division) ~= "number" or division == 0 or division < -32768 or division > 32767 or division % 1 ~= 0 then return nil, Err.new(Err.ARG, "midi encode: division must be a non-zero 16-bit integer") end if format == 0 and #midi.tracks ~= 1 then return nil, Err.new(Err.ARG, "midi encode: format 0 needs exactly one track") end if #midi.tracks > 65535 then return nil, Err.new(Err.ARG, "midi encode: too many tracks") end local w = Bytes.writer(1024) w:string("MThd") w:u32be(6) w:u16be(format) w:u16be(#midi.tracks) w:u16be(if division < 0 then division + 65536 else division) for ti, track in midi.tracks do local events = if type(track) == "table" then track.events else nil if type(events) ~= "table" then return nil, Err.new(Err.ARG, "midi encode: track " .. ti .. " has no events list") end -- stable order by tick local sorted = true local last = 0 for i, ev in events do if type(ev) ~= "table" or type(ev.tick) ~= "number" or ev.tick < 0 or ev.tick % 1 ~= 0 then return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d needs a whole non-negative tick", ti, i)) end if ev.tick < last then sorted = false end last = ev.tick end local list = events if not sorted then list = table.clone(events) local order: { [any]: number } = {} for i, ev in list do order[ev] = i end table.sort(list, function(a: any, c: any): boolean if a.tick ~= c.tick then return a.tick < c.tick end return order[a] < order[c] end) end w:string("MTrk") local lenAt = w:tell() w:u32be(0) local start = w:tell() local prev = 0 local status = 0 local endTick = 0 for i, ev in list do local t = ev.type endTick = ev.tick if t == "meta" and ev.meta == 0x2F then continue -- written once at the end end local delta = ev.tick - prev if delta > 0x0FFFFFFF then return nil, Err.new(Err.ARG, "midi encode: a delta time over 0x0FFFFFFF ticks") end local base = TYPE_STATUS[t] if base then local ch = ev.channel or 0 if type(ch) ~= "number" or ch < 0 or ch > 15 or ch % 1 ~= 0 then return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: channel must be 0..15", ti, i)) end local n = if base == 0xC0 or base == 0xD0 then 1 else 2 local d = byteList(ev.data, n) if not d or d[1] > 127 or (n == 2 and d[2] > 127) then return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: %s needs %d data bytes 0..127", ti, i, t, n)) end vlq(w, delta) local st = base + ch if not (running and st == status) then w:u8(st) end status = st w:u8(d[1]) if n == 2 then w:u8(d[2]) end elseif t == "meta" or t == "sysex" or t == "escape" then local d = byteList(ev.data, 0) if not d then return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: data must be bytes", ti, i)) end vlq(w, delta) if t == "meta" then local m = ev.meta if type(m) ~= "number" or m < 0 or m > 127 or m % 1 ~= 0 then return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: meta type must be 0..127", ti, i)) end w:u8(0xFF) w:u8(m) else w:u8(if t == "sysex" then 0xF0 else 0xF7) end if #d > 0x0FFFFFFF then return nil, Err.new(Err.ARG, "midi encode: event data too long") end vlq(w, #d) for _, c in d do w:u8(c) end status = 0 else return nil, Err.new(Err.ARG, string.format("midi encode: track %d event %d: unknown type %s", ti, i, tostring(t))) end prev = ev.tick end vlq(w, math.max(0, endTick - prev)) w:u8(0xFF) w:u8(0x2F) w:u8(0) w:setU32be(lenAt, w:tell() - start) end return w:finish(), nil end return Smf