From 4dd6cd14002c367004c6c881d40fb8222160b39d Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 13:57:25 -0500 Subject: [PATCH] ws-audio2: move music/midi/Render to codecs/audio/MidiRender (attach: summary + render method, shared by the MIDI variants); .kar lyrics -> meta.lyrics / karaoke / tags --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 2 +- .../audio/MidiRender.luau} | 64 +++++++++++- src/Formats/music/midi/init.luau | 98 +++++++++++-------- tests/music/midi.luau | 34 +++++++ 5 files changed, 156 insertions(+), 43 deletions(-) rename src/Formats/{music/midi/Render.luau => codecs/audio/MidiRender.luau} (75%) diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..bd4f9e8 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -90,6 +90,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1). - codecs/audio/Flac: FLAC frames without the container: frame header parsing, subframe decoding (constant, verbatim, - codecs/audio/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point + - codecs/audio/MidiRender: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list, - codecs/audio/Mpa: MPEG audio layers I / II / III (ISO/IEC 11172-3, 13818-3, MPEG-2.5) without the file around it: - codecs/audio/Opus: the Opus codec (RFC 6716) without its container: TOC / packet framing (Packet), the SILK and CELT - codecs/audio/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources. diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..ee48276 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -848,7 +848,7 @@ local list: { Entry } = { path = "music/midi", extensions = { "mid", "midi", "smf", "kar", "rmi" }, mime = { "audio/midi", "audio/x-midi" }, - deps = { "core/Err", "core/Bytes", "codecs/audio/SoundFont", "Types" }, + deps = { "core/Err", "core/Bytes", "codecs/audio/MidiRender", "Types" }, caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true }, load = function() return require("@formats/music/midi") diff --git a/src/Formats/music/midi/Render.luau b/src/Formats/codecs/audio/MidiRender.luau similarity index 75% rename from src/Formats/music/midi/Render.luau rename to src/Formats/codecs/audio/MidiRender.luau index 9b4e1e5..8e41b63 100644 --- a/src/Formats/music/midi/Render.luau +++ b/src/Formats/codecs/audio/MidiRender.luau @@ -1,8 +1,9 @@ --!strict --- music/midi/Render: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list, +-- 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. +-- 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") @@ -208,6 +209,14 @@ function Render.decoder(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder? 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 @@ -258,4 +267,55 @@ function Render.decoder(midi: Types.Midi, opts: RenderOptions?): (Types.Decoder? return (dec :: any) :: Types.Decoder, nil 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 diff --git a/src/Formats/music/midi/init.luau b/src/Formats/music/midi/init.luau index ac60034..aa8cb1f 100644 --- a/src/Formats/music/midi/init.luau +++ b/src/Formats/music/midi/init.luau @@ -3,7 +3,9 @@ -- 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 +-- meta events with meta = the meta type; meta.tempos / timeSignatures / keySignatures, track names; .kar karaoke: +-- meta.lyrics = { { time, tick, text } } from the "Words" track's text events (FF 01; the @ headers go to +-- meta.karaoke and meta.tags) and from lyric events (FF 05), in time order), 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). @@ -13,7 +15,7 @@ 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") +local Render = require("@formats/codecs/audio/MidiRender") -- ------------------------------------------------------------------------------------------------ contract local Midi = { @@ -21,7 +23,7 @@ local Midi = { category = "music", extensions = { "mid", "midi", "smf", "kar", "rmi" }, mime = { "audio/midi", "audio/x-midi" }, - deps = { "core/Err", "core/Bytes", "codecs/audio/SoundFont", "Types" }, + deps = { "core/Err", "core/Bytes", "codecs/audio/MidiRender", "Types" }, caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true }, } @@ -42,46 +44,63 @@ function Midi.sniff(r: Bytes.Reader): number 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 = {}, {}, {} +-- karaoke(midi): .kar text (FF 01 in a track named "Words", or in any track once an "@K" / "@T" header shows up) and +-- FF 05 lyric events -> meta.lyrics; "@X" headers -> meta.karaoke[X] (lists of lines) and meta.tags +local function karaoke(midi: Types.Midi) + local lyrics: { { time: number, tick: number, text: string } } = {} + local headers: { [string]: { string } } = {} local map = Render.tempoMap(midi) - for ti, t in midi.tracks do + local kar, hasWords = false, false + for _, t in midi.tracks do + if t.name == "Words" then + kar, hasWords = true, true + end 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 }) + if ev.type == "meta" and ev.meta == 1 and type(ev.data) == "table" and ev.data[1] == 64 then + local c = ev.data[2] + if c == 75 or c == 84 then -- @K, @T + kar = true end end end end - midi.meta.tempos = tempos - midi.meta.timeSignatures = sigs - midi.meta.keySignatures = keys - midi.meta.length = Render.length(midi) + for ti, t in midi.tracks do + local tmap = if midi.format == 2 then Render.tempoMap(midi, ti) else map + local words = kar and (t.name == "Words" or not hasWords) + for _, ev in t.events do + if ev.type == "meta" and type(ev.data) == "table" and (ev.meta == 5 or (ev.meta == 1 and words)) then + local text = Smf.text(ev.data :: { number }) + if ev.meta == 1 and string.sub(text, 1, 1) == "@" and #text >= 2 then + local key = string.sub(text, 2, 2) + local list = headers[key] or {} + headers[key] = list + table.insert(list, string.sub(text, 3)) + else + table.insert(lyrics, { time = Render.seconds(tmap, ev.tick), tick = ev.tick, text = text }) + end + end + end + end + if #lyrics == 0 and next(headers) == nil then + return + end + table.sort(lyrics, function(a, b): boolean + return a.time < b.time + end) + midi.meta.lyrics = lyrics + midi.meta.karaoke = headers + local tags: { [string]: string } = {} + if headers.T then + tags.title = headers.T[1] + tags.artist = headers.T[2] + end + if headers.L then + tags.language = headers.L[1] + end + if headers.I then + tags.comment = table.concat(headers.I, "\n") + end + midi.meta.tags = tags end function Midi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.Err?) @@ -89,9 +108,8 @@ function Midi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Midi?, Err.E if not midi then return nil, err end - summarize(midi) - midi.meta.source = { format = "midi", smf = midi.format } - midi.render = render + Render.attach(midi, { format = "midi", smf = midi.format }) + karaoke(midi) return midi, nil end diff --git a/tests/music/midi.luau b/tests/music/midi.luau index a906337..f1bfbe0 100644 --- a/tests/music/midi.luau +++ b/tests/music/midi.luau @@ -254,6 +254,40 @@ for _, c in Cases do table.insert(samples, c.data) end end +-- .kar karaoke: the "Words" track's text events (FF 01) with @ headers, plus FF 05 lyrics, timed through the tempo map +do + local function txt(tick: number, meta: number, s: string): any + return { tick = tick, type = "meta", meta = meta, data = { string.byte(s, 1, -1) } } + end + local k = Types.Midi.new(96) + table.insert(k.tracks, { events = { + { tick = 0, type = "meta", meta = 0x51, data = { 0x0F, 0x42, 0x40 } }, -- 1 s per quarter + txt(0, 1, "Copyright notice, not a lyric"), + { tick = 192, type = "noteOn", channel = 0, data = { 60, 100 } }, + { tick = 288, type = "noteOff", channel = 0, data = { 60, 0 } }, + } }) + table.insert(k.tracks, { events = { + txt(0, 3, "Words"), txt(0, 1, "@KMIDI KARAOKE FILE"), txt(0, 1, "@LENG"), txt(0, 1, "@TSong title"), + txt(0, 1, "@TThe artist"), txt(0, 1, "@Isome info"), txt(96, 1, "\\Hel"), txt(144, 1, "lo"), + txt(192, 1, "/world"), txt(240, 5, "!"), + } }) + local m = assert(decode(Midi.encode(k))) + local ly = m.meta.lyrics + t:eq(#ly, 4, "kar: lyric count") + t:eq(ly[1].text, "\\Hel", "kar: first lyric (paragraph marker kept)") + t:eq(ly[1].tick, 96, "kar: tick") + t:check(math.abs(ly[1].time - 1) < 1e-9 and math.abs(ly[3].time - 2) < 1e-9, "kar: times through the tempo map") + t:eq(ly[4].text, "!", "kar: FF 05 lyric") + t:eq(m.meta.karaoke.T[2], "The artist", "kar: @T lines") + t:eq(m.meta.karaoke.K[1], "MIDI KARAOKE FILE", "kar: @K") + t:eq(m.meta.tags.title, "Song title", "kar: tags.title") + t:eq(m.meta.tags.artist, "The artist", "kar: tags.artist") + t:eq(m.meta.tags.language, "ENG", "kar: tags.language") + t:eq(m:render().tags.title, "Song title", "kar: decoder title") + local plain = assert(decode(Midi.encode(Types.Midi.new(96)))) + t:eq(plain.meta.lyrics, nil, "no lyrics without text events") +end + t:fuzz("decode", function(b: buffer) return decode(b) end, samples, { mutations = 40 })