ws-music: music/midi (SMF 0/1/2 read/write, tempo map, render), codecs/SoundFont (SF2 parser + TinySoundFont-port synth + fallback waveform set), midi tests vs mido
Types.luau: Midi gets an optional render(self, opts) -> Decoder field (backward compatible; set by music/midi decode).
This commit is contained in:
1 parent
cdcb5b0b77
commit
08af33d82a
14 files changed
+2955
No files matched your search
@@ -0,0 +1,261 @@
|
||||
--!strict
|
||||
-- music/midi/Render: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list,
|
||||
-- and the audio Decoder that plays a Midi through codecs/SoundFont's synth (a SoundFont bank, or the built-in
|
||||
-- waveform set). Format 0 / 1: one tempo map from every track's tempo events, tracks merged (ties keep track order).
|
||||
-- Format 2: each track is its own song with its own tempo map, played one after another.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local SoundFont = require("@formats/codecs/SoundFont")
|
||||
|
||||
local Synth = SoundFont.Synth
|
||||
|
||||
local Render = {}
|
||||
|
||||
export type TempoMap = { ticks: { number }, secs: { number }, us: { number }, division: number }
|
||||
|
||||
local STATUS = { noteOff = 0x80, noteOn = 0x90, aftertouch = 0xA0, controller = 0xB0, program = 0xC0, channelPressure = 0xD0, pitchBend = 0xE0 }
|
||||
|
||||
local function tempoOf(ev: any): number?
|
||||
if ev.type == "meta" and ev.meta == 0x51 and type(ev.data) == "table" and #ev.data >= 3 then
|
||||
return ev.data[1] * 65536 + ev.data[2] * 256 + ev.data[3]
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- tempoMap(midi, track?) -> TempoMap: from every track (format 0 / 1) or from one track (format 2)
|
||||
function Render.tempoMap(midi: Types.Midi, track: number?): TempoMap
|
||||
local changes: { { number } } = {}
|
||||
for ti, t in midi.tracks do
|
||||
if track == nil or track == ti then
|
||||
for i, ev in t.events do
|
||||
local us = tempoOf(ev)
|
||||
if us then
|
||||
table.insert(changes, { ev.tick, ti, i, us })
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
table.sort(changes, function(a: { number }, b: { number }): boolean
|
||||
if a[1] ~= b[1] then
|
||||
return a[1] < b[1]
|
||||
end
|
||||
if a[2] ~= b[2] then
|
||||
return a[2] < b[2]
|
||||
end
|
||||
return a[3] < b[3]
|
||||
end)
|
||||
local map: TempoMap = { ticks = { 0 }, secs = { 0 }, us = { 500000 }, division = midi.division }
|
||||
local div = midi.division
|
||||
for _, c in changes do
|
||||
local n = #map.ticks
|
||||
local tick = c[1]
|
||||
local sec = map.secs[n] + (tick - map.ticks[n]) * map.us[n] * 1e-6 / div
|
||||
if tick == map.ticks[n] then
|
||||
map.us[n] = c[4]
|
||||
else
|
||||
table.insert(map.ticks, tick)
|
||||
table.insert(map.secs, sec)
|
||||
table.insert(map.us, c[4])
|
||||
end
|
||||
end
|
||||
return map
|
||||
end
|
||||
|
||||
-- seconds(map, tick) -> seconds (PPQ through the tempo map; SMPTE divisions are fixed time)
|
||||
function Render.seconds(map: TempoMap, tick: number): number
|
||||
local div = map.division
|
||||
if div < 0 then
|
||||
local fps = -(div // 256)
|
||||
local tpf = div % 256
|
||||
if tpf == 0 then
|
||||
return 0
|
||||
end
|
||||
return tick / ((if fps == 29 then 29.97 else fps) * tpf)
|
||||
end
|
||||
local ticks = map.ticks
|
||||
-- binary search for the last change at or before tick
|
||||
local lo, hi = 1, #ticks
|
||||
while lo < hi do
|
||||
local mid = (lo + hi + 1) // 2
|
||||
if ticks[mid] <= tick then
|
||||
lo = mid
|
||||
else
|
||||
hi = mid - 1
|
||||
end
|
||||
end
|
||||
return map.secs[lo] + (tick - ticks[lo]) * map.us[lo] * 1e-6 / div
|
||||
end
|
||||
|
||||
-- length(midi) -> seconds to the last event (format 2: the tracks one after another)
|
||||
function Render.length(midi: Types.Midi): number
|
||||
if #midi.tracks == 0 then
|
||||
return 0
|
||||
end
|
||||
if midi.format == 2 then
|
||||
local total = 0
|
||||
for ti, t in midi.tracks do
|
||||
local map = Render.tempoMap(midi, ti)
|
||||
local last = 0
|
||||
for _, ev in t.events do
|
||||
last = math.max(last, ev.tick)
|
||||
end
|
||||
total += Render.seconds(map, last)
|
||||
end
|
||||
return total
|
||||
end
|
||||
local map = Render.tempoMap(midi)
|
||||
local last = 0
|
||||
for _, t in midi.tracks do
|
||||
for _, ev in t.events do
|
||||
last = math.max(last, ev.tick)
|
||||
end
|
||||
end
|
||||
return Render.seconds(map, last)
|
||||
end
|
||||
|
||||
export type Timeline = { time: { number }, status: { number }, d1: { number }, d2: { number }, length: number }
|
||||
|
||||
-- timeline(midi) -> the channel messages in play order with their times in seconds
|
||||
function Render.timeline(midi: Types.Midi): Timeline
|
||||
local items: { { any } } = {}
|
||||
local offset = 0
|
||||
local function add(map: TempoMap, ti: number, t: any, base: number)
|
||||
for i, ev in t.events do
|
||||
local st = STATUS[ev.type]
|
||||
if st and type(ev.data) == "table" then
|
||||
local ch = ev.channel or 0
|
||||
table.insert(items, { base + Render.seconds(map, ev.tick), ti, i, st + ch % 16, ev.data[1] or 0, ev.data[2] or 0 })
|
||||
end
|
||||
end
|
||||
end
|
||||
if midi.format == 2 then
|
||||
for ti, t in midi.tracks do
|
||||
local map = Render.tempoMap(midi, ti)
|
||||
add(map, ti, t, offset)
|
||||
local last = 0
|
||||
for _, ev in t.events do
|
||||
last = math.max(last, ev.tick)
|
||||
end
|
||||
offset += Render.seconds(map, last)
|
||||
end
|
||||
else
|
||||
local map = Render.tempoMap(midi)
|
||||
for ti, t in midi.tracks do
|
||||
add(map, ti, t, 0)
|
||||
end
|
||||
end
|
||||
table.sort(items, function(a: { any }, b: { any }): boolean
|
||||
if a[1] ~= b[1] then
|
||||
return a[1] < b[1]
|
||||
end
|
||||
if a[2] ~= b[2] then
|
||||
return a[2] < b[2]
|
||||
end
|
||||
return a[3] < b[3]
|
||||
end)
|
||||
local tl: Timeline = { time = table.create(#items), status = table.create(#items), d1 = table.create(#items), d2 = table.create(#items), length = Render.length(midi) }
|
||||
for i, it in items do
|
||||
tl.time[i], tl.status[i], tl.d1[i], tl.d2[i] = it[1], it[4], it[5] % 128, it[6] % 128
|
||||
end
|
||||
return tl
|
||||
end
|
||||
|
||||
export type RenderOptions = {
|
||||
sampleRate: number?, -- default 44100
|
||||
soundfont: any?, -- a SoundFont (music/sf2 decode, codecs/SoundFont.parse) or SF2 bytes (buffer / string); default the built-in waveforms
|
||||
gain: number?, -- linear output gain, default 0.5
|
||||
tail: number?, -- seconds rendered after the last event (release tails), default 1
|
||||
maxVoices: number?, -- default 256
|
||||
}
|
||||
|
||||
-- decoder(midi, opts?) -> Types.Decoder | nil, Err
|
||||
function Render.decoder(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?, Err.Err?)
|
||||
if type(midi) ~= "table" or type(midi.tracks) ~= "table" or type(midi.division) ~= "number" or midi.division == 0 then
|
||||
return nil, Err.new(Err.ARG, "render: needs a Midi value")
|
||||
end
|
||||
local o: RenderOptions = opts or {}
|
||||
local rate = o.sampleRate or 44100
|
||||
if type(rate) ~= "number" or rate < 1000 or rate > 384000 then
|
||||
return nil, Err.new(Err.ARG, "render: sampleRate must be 1000..384000")
|
||||
end
|
||||
local sf = o.soundfont
|
||||
if sf == nil then
|
||||
sf = SoundFont.fallback()
|
||||
elseif not SoundFont.isSoundFont(sf) then
|
||||
local parsed, err = SoundFont.parse(sf)
|
||||
if not parsed then
|
||||
return nil, err
|
||||
end
|
||||
sf = parsed
|
||||
end
|
||||
local tl = Render.timeline(midi)
|
||||
local tail = o.tail or 1
|
||||
local frames = math.max(0, math.ceil((tl.length + tail) * rate))
|
||||
local nev = #tl.time
|
||||
local evFrame = table.create(nev)
|
||||
for i = 1, nev do
|
||||
evFrame[i] = math.floor(tl.time[i] * rate + 0.5)
|
||||
end
|
||||
local gain, maxVoices = o.gain, o.maxVoices
|
||||
local state = Synth.new(sf, rate, gain, maxVoices)
|
||||
local pos, nextEv = 0, 1
|
||||
|
||||
local dec = {
|
||||
sampleRate = rate,
|
||||
channels = 2,
|
||||
frames = frames,
|
||||
duration = frames / rate,
|
||||
bitrate = 0,
|
||||
tags = {} :: Types.Tags,
|
||||
}
|
||||
for _, t in midi.tracks do
|
||||
if t.name and not dec.tags.title then
|
||||
dec.tags.title = t.name
|
||||
end
|
||||
end
|
||||
|
||||
local function read(_self: any, n: number, out: buffer?): (buffer, number)
|
||||
n = math.max(0, math.min(math.floor(n), frames - pos))
|
||||
local buf = out
|
||||
if not buf or buffer.len(buf) < n * 8 then
|
||||
buf = buffer.create(math.max(n, 1) * 8)
|
||||
end
|
||||
local b = buf :: buffer
|
||||
buffer.fill(b, 0, 0, n * 8)
|
||||
local i = 0
|
||||
while i < n do
|
||||
while nextEv <= nev and evFrame[nextEv] <= pos + i do
|
||||
Synth.midi(state, tl.status[nextEv], tl.d1[nextEv], tl.d2[nextEv])
|
||||
nextEv += 1
|
||||
end
|
||||
local stop = n
|
||||
if nextEv <= nev then
|
||||
stop = math.min(n, evFrame[nextEv] - pos)
|
||||
end
|
||||
if stop > i then
|
||||
Synth.render(state, b, i, stop - i)
|
||||
i = stop
|
||||
end
|
||||
end
|
||||
pos += n
|
||||
return b, n
|
||||
end
|
||||
dec.read = read :: any
|
||||
local scratch = buffer.create(4096 * 8)
|
||||
dec.seek = function(_self: any, seconds: number)
|
||||
local target = math.clamp(math.floor((tonumber(seconds) or 0) * rate), 0, frames)
|
||||
if target < pos then
|
||||
Synth.reset(state)
|
||||
pos, nextEv = 0, 1
|
||||
end
|
||||
while pos < target do
|
||||
read(nil, math.min(4096, target - pos), scratch)
|
||||
end
|
||||
end :: any
|
||||
dec.position = function(_self: any): number
|
||||
return pos / rate
|
||||
end :: any
|
||||
return (dec :: any) :: Types.Decoder, nil
|
||||
end
|
||||
|
||||
return Render
|
||||
@@ -0,0 +1,402 @@
|
||||
--!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 = 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
|
||||
@@ -0,0 +1,136 @@
|
||||
--!strict
|
||||
-- music/midi: Standard MIDI Files (SMF 1.0: formats 0, 1 and 2; PPQ and SMPTE time; RIFF RMID read). Written from the
|
||||
-- specification (no third-party code); rendering goes through codecs/SoundFont (a TinySoundFont port).
|
||||
-- Supports: decode to a Types.Midi (absolute ticks; channel events noteOff / noteOn / aftertouch / controller /
|
||||
-- program / channelPressure / pitchBend with their raw data bytes, sysex / escape with the bytes after the length,
|
||||
-- meta events with meta = the meta type; meta.tempos / timeSignatures / keySignatures, track names), encode (running
|
||||
-- status optional, byte-identical to python mido's writer by default), the tempo map (tickToSeconds, length), and
|
||||
-- render / open: an audio Decoder (stereo f32) through an SF2 SoundFont (opts.soundfont) or the built-in waveform set.
|
||||
-- Not supported: RMID write, XMF / RMI DLS banks, system common / realtime bytes inside tracks (CORRUPT).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Smf = require("@formats/music/midi/Smf")
|
||||
local Render = require("@formats/music/midi/Render")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Midi = {
|
||||
name = "midi",
|
||||
category = "music",
|
||||
extensions = { "mid", "midi", "smf", "kar", "rmi" },
|
||||
mime = { "audio/midi", "audio/x-midi" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/SoundFont", "Types" },
|
||||
caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = Smf.ReadOptions -- strict (default false), maxEvents (default 2^24)
|
||||
export type EncodeOptions = Smf.WriteOptions -- runningStatus (default true)
|
||||
export type RenderOptions = Render.RenderOptions -- sampleRate, soundfont, gain, tail, maxVoices
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Midi.sniff(r: Bytes.Reader): number
|
||||
if r:peek(4) == "MThd" then
|
||||
return 1
|
||||
end
|
||||
if r:peek(4) == "RIFF" and r:peek(4, 8) == "RMID" then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function render(self: Types.Midi, opts: RenderOptions?): Types.Decoder
|
||||
local dec, err = Render.decoder(self, opts)
|
||||
if not dec then
|
||||
-- the Types contract returns a Decoder; a failed render is an empty one (Midi.render returns the Err)
|
||||
local empty: any = {
|
||||
sampleRate = 44100, channels = 2, frames = 0, duration = 0, bitrate = 0, tags = {}, err = err,
|
||||
read = function(_self: any, _n: number, out: buffer?): (buffer, number)
|
||||
return out or buffer.create(0), 0
|
||||
end,
|
||||
seek = function() end,
|
||||
position = function(): number
|
||||
return 0
|
||||
end,
|
||||
}
|
||||
return empty
|
||||
end
|
||||
return dec
|
||||
end
|
||||
|
||||
local function summarize(midi: Types.Midi)
|
||||
local tempos, sigs, keys = {}, {}, {}
|
||||
local map = Render.tempoMap(midi)
|
||||
for ti, t in midi.tracks do
|
||||
for _, ev in t.events do
|
||||
if ev.type == "meta" then
|
||||
local d = ev.data :: { number }
|
||||
if ev.meta == 0x51 and #d >= 3 then
|
||||
table.insert(tempos, { tick = ev.tick, track = ti, usPerQuarter = d[1] * 65536 + d[2] * 256 + d[3], bpm = 60000000 / math.max(1, d[1] * 65536 + d[2] * 256 + d[3]), seconds = Render.seconds(map, ev.tick) })
|
||||
elseif ev.meta == 0x58 and #d >= 4 then
|
||||
table.insert(sigs, { tick = ev.tick, track = ti, numerator = d[1], denominator = 2 ^ math.min(d[2], 31), clocksPerClick = d[3], notated32ndsPerBeat = d[4] })
|
||||
elseif ev.meta == 0x59 and #d >= 2 then
|
||||
table.insert(keys, { tick = ev.tick, track = ti, sharps = if d[1] >= 128 then d[1] - 256 else d[1], minor = d[2] == 1 })
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
midi.meta.tempos = tempos
|
||||
midi.meta.timeSignatures = sigs
|
||||
midi.meta.keySignatures = keys
|
||||
midi.meta.length = Render.length(midi)
|
||||
end
|
||||
|
||||
function Midi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?)
|
||||
local midi, err = Smf.read(r, opts)
|
||||
if not midi then
|
||||
return nil, err
|
||||
end
|
||||
summarize(midi)
|
||||
midi.meta.source = { format = "midi", smf = midi.format }
|
||||
midi.render = render
|
||||
return midi, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Midi.encode(midi: Types.Midi, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
return Smf.write(midi, opts)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open
|
||||
-- open(r, opts?) -> the rendered audio Decoder (opts: DecodeOptions + RenderOptions)
|
||||
function Midi.open(r: Bytes.Reader, opts: any?): (Types.Decoder?, Err.Err?)
|
||||
local midi, err = Midi.decode(r, opts)
|
||||
if not midi then
|
||||
return nil, err
|
||||
end
|
||||
return Render.decoder(midi, opts)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- render(midi, opts?) -> Decoder | nil, Err (also works on a Midi built by hand with Types.Midi.new)
|
||||
function Midi.render(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder?, Err.Err?)
|
||||
return Render.decoder(midi, opts)
|
||||
end
|
||||
|
||||
-- tickToSeconds(midi, tick, track?) -> seconds (track: format 2's per-track tempo map)
|
||||
function Midi.tickToSeconds(midi: Types.Midi, tick: number, track: number?): number
|
||||
return Render.seconds(Render.tempoMap(midi, track), tick)
|
||||
end
|
||||
|
||||
-- tempoMap(midi, track?) -> { ticks, secs, us, division } (change points)
|
||||
Midi.tempoMap = Render.tempoMap
|
||||
Midi.seconds = Render.seconds
|
||||
|
||||
-- length(midi) -> seconds to the last event (what python mido's MidiFile.length reports for formats 0 / 1)
|
||||
function Midi.length(midi: Types.Midi): number
|
||||
return Render.length(midi)
|
||||
end
|
||||
|
||||
-- text(data) -> the bytes of a text meta event as a string
|
||||
Midi.text = Smf.text
|
||||
|
||||
return Midi
|
||||
@@ -0,0 +1,44 @@
|
||||
--!strict
|
||||
-- music/sf2: SoundFont 2 banks (SoundFont 2.04 specification), read-only. A thin wrapper over codecs/SoundFont (the
|
||||
-- parser and the TinySoundFont-port synth music/midi renders with). Supports: INFO, 16-bit samples (+ sm24 24-bit),
|
||||
-- presets / instruments / sample headers with global zones, generator merging into playable regions.
|
||||
-- Not supported: writing, SF3 (Ogg Vorbis samples), modulators (read past, not applied).
|
||||
-- decode returns the SoundFont value (kind "soundfont"): pass it to music/midi render as opts.soundfont.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local SoundFont = require("@formats/codecs/SoundFont")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Sf2 = {
|
||||
name = "sf2",
|
||||
category = "music",
|
||||
extensions = { "sf2" },
|
||||
mime = { "audio/x-soundfont" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/SoundFont" },
|
||||
caps = { decode = true, encode = false, sm24 = true, sf3 = false },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxRegions: number?, -- default 10^6
|
||||
maxSamples: number?, -- default 2^28
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Sf2.sniff(r: Bytes.Reader): number
|
||||
return if SoundFont.sniff(r) then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Sf2.decode(r: Bytes.Reader, opts: DecodeOptions?): (SoundFont.SoundFont?, Err.Err?)
|
||||
return SoundFont.parse(r, opts)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- synth(sf?, sampleRate?, opts?) -> a synth State (codecs/SoundFont.Synth drives it)
|
||||
Sf2.synth = SoundFont.synth
|
||||
Sf2.fallback = SoundFont.fallback
|
||||
|
||||
return Sf2
|
||||
Reference in new issue
Block a user