C2, the hierarchy (tools/move.py, every reference rewritten mechanically): - codecs/compress: Deflate Lzma Zstd Brotli Bzip2 Lzw; codecs/entropy: Huffman (from core) RangeCoder; codecs/image: Jpeg Dct Vp8 Vp8L Yuv Quantize Raster Blend Pixels; codecs/audio: Mdct Aac Alac Pcm Resample VorbisComment Tracker SoundFont Stream; codecs/video: H264 Mpeg1 Video; codecs/text: Json Xml Text Url; codecs/font: TrueType Cff; codecs/model: MeshFlatten Mat4. containers/ stays flat; core/ keeps Bytes Bits Err Crc32 Adler32 Base64 Md5 Input Sniff. - LAYERS lint: codecs must sit in a domain folder; gen_registry lists codecs by domain (docs/FORMATS.md). - Checked: build.py both targets, rojo build of build/roblox, the full suite on both runtimes. C3, generic code out of format folders: - containers/Chunks (new): the chunked-file walker (RIFF / RIFX / IFF / PNG / CAF layouts: endianness, size first, trailer, padding, lenient missing pad, open-ended ids, size hooks). containers/Riff walks with it (RF64 ds64 through the resize hook); image/png, audio/aiff and audio/caf list their chunk handlers over it. - codecs/audio/Stream (new): Stream.packets, the packet-decoder Decoder (read / seek with pre-roll / position, priming and end trimming) that aac, caf and m4a each carried (~70 lines each). - codecs/image/Pixels: image/bmp/Pixels promoted (+ rgb555); image/ico's DIB decoder uses its row loops instead of its own (the AND mask / alpha rule stay ICO's). - codecs/model/Mat4 (new): matrices / quaternions / TRS shared by FBX (Xform keeps only the FBX transform model), Collada (Math keeps only <lookat> / <skew>) and USD (its matrix helpers and general 4x4 inverse); Mat4.mul is Types.Scene.mul. The Collada normal matrix is now the inverse transpose (it was the inverse; same result for the fixtures' bind shapes). - README rewritten (install for Rojo and LÖVE / LuaJIT, quick start per category, F.* and F.ops, host notes: FORMATS_NO_JIT_TUNE, paths, layout); docs/STYLE.md: the codec domains, "what belongs in a format folder" with the shared building blocks and the DUP rule, conventions (WAVE order, lower-case tags, loops, the api hooks decodeImage / encodeImage / openAudio / plugins / resolve, the codecs/video/Video registry), Err.from, the type baseline. New tests: tests/containers/chunks, tests/codecs/mat4. Type baseline 93.
137 lines
5.9 KiB
Luau
137 lines
5.9 KiB
Luau
--!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
|