360 lines
12 KiB
Luau
360 lines
12 KiB
Luau
--!strict
|
|
-- codecs/audio/MidiRender: 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/audio/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. Shared by every format that
|
|
-- decodes to a Types.Midi (music/midi, mus, xmi, hmp): attach() adds the meta summary and the render method.
|
|
local Err = require("@formats/core/Err")
|
|
local Types = require("@formats/Types")
|
|
local SoundFont = require("@formats/codecs/audio/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) :: { number }, status = table.create(#items) :: { number }, d1 = table.create(#items) :: { number }, d2 = table.create(#items) :: { number }, 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/audio/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: { number } = table.create(nev) :: { number }
|
|
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,
|
|
}
|
|
local mtags = type(midi.meta) == "table" and midi.meta.tags
|
|
if type(mtags) == "table" then
|
|
for k, v in mtags do
|
|
if type(k) == "string" and type(v) == "string" then
|
|
dec.tags[k] = v
|
|
end
|
|
end
|
|
end
|
|
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
|
|
|
|
-- 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)
|
|
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
|
|
|
|
-- summarize(midi): meta.tempos / timeSignatures / keySignatures / length from the events
|
|
function Render.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
|
|
|
|
-- attach(midi, source): what every MIDI-like decoder does last: the meta summary, meta.source and the render method
|
|
function Render.attach(midi: Types.Midi, source: { [string]: any })
|
|
Render.summarize(midi)
|
|
midi.meta.source = source
|
|
midi.render = render
|
|
end
|
|
|
|
return Render
|