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