324 lines
13 KiB
Luau
324 lines
13 KiB
Luau
-- music/midi tests: SMF formats 0 / 1 / 2 + SMPTE + RMID parsed exactly as python mido parses them, mido's own files
|
|
-- re-encoded byte for byte, round trips without running status, the tempo map against mido's message times and
|
|
-- lengths, meta summaries, crafted bad files, truncation (lenient / strict), the fallback-synth render (duration,
|
|
-- level, seek), and the fuzz no-throw pass (decode, and decode + a short render). Fixtures: tools/fixtures/midi.py.
|
|
local T = require("@tests/T")
|
|
local Midi = require("@rosetta/music/midi")
|
|
local Bytes = require("@rosetta/core/Bytes")
|
|
local Err = require("@rosetta/core/Err")
|
|
local Types = require("@rosetta/Types")
|
|
local Cases = require("@tests/gen/midi_cases")
|
|
local Bad = require("@tests/gen/midi_bad")
|
|
local Trunc = require("@tests/gen/midi_trunc")
|
|
|
|
local t = T.suite("midi")
|
|
|
|
local function decode(data: any, opts: any?): (any, any)
|
|
local b = if type(data) == "string" then buffer.fromstring(data) else data
|
|
return Midi.decode(Bytes.reader(b), opts)
|
|
end
|
|
|
|
-- the contract
|
|
t:eq(Midi.name, "midi", "name")
|
|
t:eq(Midi.category, "music", "category")
|
|
t:check(table.find(Midi.extensions, "mid") ~= nil, "extensions")
|
|
t:check(Midi.caps.decode and Midi.caps.encode, "caps")
|
|
t:eq(Midi.sniff(Bytes.reader(buffer.fromstring("MThd\0\0\0\6"))), 1, "sniff MThd")
|
|
t:eq(Midi.sniff(Bytes.reader(buffer.fromstring("RIFF\0\0\0\0RMID"))), 1, "sniff RMID")
|
|
t:eq(Midi.sniff(Bytes.reader(buffer.fromstring("RIFF\0\0\0\0WAVE"))), 0, "sniff WAVE")
|
|
|
|
local function sameEvents(got: { any }, want: { any }, label: string)
|
|
t:eq(#got, #want, label .. ": event count")
|
|
for i, w in want do
|
|
local g = got[i]
|
|
local l = label .. " event " .. i
|
|
t:eq(g.tick, w[1], l .. " tick")
|
|
t:eq(g.type, w[2], l .. " type")
|
|
t:eq(g.channel or -1, w[3], l .. " channel")
|
|
t:eq(if g.type == "meta" then g.meta else -1, w[5], l .. " meta type")
|
|
local d = g.data or {}
|
|
t:eq(#d, #w[4], l .. " data length")
|
|
for k, v in w[4] do
|
|
if d[k] ~= v then
|
|
t:eq(d[k], v, l .. " data byte " .. k)
|
|
end
|
|
end
|
|
end
|
|
end
|
|
|
|
local function trackEvents(m: any): { { any } }
|
|
local out = {}
|
|
for ti, tr in m.tracks do
|
|
local evs = {}
|
|
for _, ev in tr.events do
|
|
table.insert(evs, { ev.tick, ev.type, ev.channel or -1, ev.data or {}, if ev.type == "meta" then ev.meta else -1 })
|
|
end
|
|
out[ti] = evs
|
|
end
|
|
return out
|
|
end
|
|
|
|
local byName = {}
|
|
for _, c in Cases do
|
|
byName[c.name] = c
|
|
local m, err = decode(c.data)
|
|
t:check(m, c.name .. ": " .. tostring(err))
|
|
t:eq(m.kind, "midi", c.name .. ": kind")
|
|
t:eq(m.format, c.type, c.name .. ": format")
|
|
t:eq(m.division, c.division, c.name .. ": division")
|
|
t:eq(#m.tracks, #c.tracks, c.name .. ": tracks")
|
|
for ti, want in c.tracks do
|
|
sameEvents(m.tracks[ti].events, want, c.name .. " track " .. ti)
|
|
end
|
|
-- mido's own bytes come back exactly (running status as mido writes it)
|
|
if c.exact then
|
|
local out, eerr = Midi.encode(m)
|
|
t:check(out, c.name .. ": encode " .. tostring(eerr))
|
|
t:eq(buffer.tostring(out :: buffer) == c.data, true, c.name .. ": re-encoded bytes equal mido's")
|
|
end
|
|
-- without running status: longer (or equal), and the same events
|
|
local plain = Midi.encode(m, { runningStatus = false }) :: buffer
|
|
local withRs = Midi.encode(m) :: buffer
|
|
t:check(buffer.len(plain) >= buffer.len(withRs), c.name .. ": running status saves bytes")
|
|
local back = decode(plain)
|
|
t:check(back, c.name .. ": re-decode")
|
|
for ti, want in trackEvents(m) do
|
|
sameEvents(back.tracks[ti].events, want, c.name .. " round trip track " .. ti)
|
|
end
|
|
-- tempo map: every event's time against mido's merged message times
|
|
if c.times then
|
|
local secs = {}
|
|
for _, tr in m.tracks do
|
|
for _, ev in tr.events do
|
|
if not (ev.type == "meta" and ev.meta == 0x2F) then -- mido merges the end-of-track events into one
|
|
table.insert(secs, Midi.tickToSeconds(m, ev.tick))
|
|
end
|
|
end
|
|
end
|
|
table.sort(secs)
|
|
t:eq(#secs, #c.times - 1, c.name .. ": event count vs mido")
|
|
local worst = 0
|
|
for i, s in secs do
|
|
worst = math.max(worst, math.abs(s - c.times[i]))
|
|
end
|
|
t:check(worst < 1e-6, c.name .. ": event times match mido (worst " .. worst .. " s)")
|
|
t:check(math.abs(Midi.length(m) - c.length) < 1e-6, c.name .. ": length " .. Midi.length(m) .. " vs mido " .. c.length)
|
|
t:check(math.abs(m.meta.length - c.length) < 1e-6, c.name .. ": meta.length")
|
|
end
|
|
end
|
|
t:note("%d files parse as mido parses them; mido's files re-encode byte for byte", #Cases)
|
|
|
|
-- meta summaries
|
|
do
|
|
local m = decode(byName.format0.data)
|
|
t:eq(m.tracks[1].name, "format zero", "track name")
|
|
t:eq(#m.meta.tempos, 3, "tempo changes")
|
|
t:eq(m.meta.tempos[1].usPerQuarter, 500000, "first tempo")
|
|
t:eq(m.meta.tempos[1].bpm, 120, "bpm")
|
|
t:eq(#m.meta.timeSignatures, 2, "time signatures")
|
|
t:eq(m.meta.timeSignatures[1].numerator, 3, "3/4 numerator")
|
|
t:eq(m.meta.timeSignatures[1].denominator, 4, "3/4 denominator")
|
|
t:eq(m.meta.timeSignatures[2].denominator, 8, "6/8 denominator")
|
|
t:eq(m.meta.keySignatures[1].sharps, -3, "Eb: 3 flats")
|
|
t:eq(m.meta.keySignatures[1].minor, false, "Eb major")
|
|
local s = decode(byName.smpte.data)
|
|
t:eq(s.meta.smpte.fps, 25, "smpte fps")
|
|
t:eq(s.meta.smpte.ticksPerFrame, 40, "smpte ticks per frame")
|
|
t:check(math.abs(Midi.tickToSeconds(s, 1000) - 1) < 1e-12, "smpte: 1000 ticks at 25 x 40 = 1 s")
|
|
t:eq(decode(byName.rmid.data).meta.rmid, true, "rmid flag")
|
|
-- format 2: per-track tempo maps, the tracks one after another
|
|
local f2 = decode(byName.format2.data)
|
|
local total = 0
|
|
for ti, tr in f2.tracks do
|
|
local last = tr.events[#tr.events].tick
|
|
total += Midi.tickToSeconds(f2, last, ti)
|
|
end
|
|
t:check(math.abs(Midi.length(f2) - total) < 1e-9, "format 2 length = the tracks in sequence")
|
|
end
|
|
|
|
-- a value built by hand: unsorted events are written in tick order, end of track added, bad values refused
|
|
do
|
|
local m = Types.Midi.new(96)
|
|
m.format = 0
|
|
m.tracks[1] = { events = {
|
|
{ tick = 50, type = "noteOff", channel = 2, data = { 60, 0 } },
|
|
{ tick = 0, type = "noteOn", channel = 2, data = { 60, 100 } },
|
|
{ tick = 50, type = "meta", meta = 0x2F, data = {} },
|
|
{ tick = 20, type = "controller", channel = 2, data = { 64, 127 } },
|
|
} }
|
|
local b = Midi.encode(m) :: buffer
|
|
local back = decode(b)
|
|
sameEvents(back.tracks[1].events, {
|
|
{ 0, "noteOn", 2, { 60, 100 }, -1 }, { 20, "controller", 2, { 64, 127 }, -1 }, { 50, "noteOff", 2, { 60, 0 }, -1 },
|
|
{ 50, "meta", -1, {}, 0x2F },
|
|
}, "sorted on write")
|
|
local function refuses(mut: (any) -> (), label: string)
|
|
local x = Types.Midi.new(96)
|
|
x.tracks[1] = { events = { { tick = 0, type = "noteOn", channel = 0, data = { 60, 100 } } } }
|
|
mut(x)
|
|
local out, err = Midi.encode(x)
|
|
t:check(out == nil and Err.is(err) and err.code == Err.ARG, "encode refuses " .. label)
|
|
end
|
|
refuses(function(x) x.tracks[1].events[1].channel = 16 end, "channel 16")
|
|
refuses(function(x) x.tracks[1].events[1].data = { 60, 128 } end, "data byte 128")
|
|
refuses(function(x) x.tracks[1].events[1].tick = -1 end, "negative tick")
|
|
refuses(function(x) x.tracks[1].events[1].type = "wobble" end, "unknown type")
|
|
refuses(function(x) x.division = 0 end, "zero division")
|
|
refuses(function(x) x.format = 0; x.tracks[2] = { events = {} } end, "format 0 with two tracks")
|
|
local nope, nerr = Midi.encode(nil :: any)
|
|
t:check(nope == nil and nerr.code == Err.ARG, "encode refuses nil")
|
|
end
|
|
|
|
-- track.name is written as a 0x03 meta event at tick 0 when the track has none; an existing one wins
|
|
do
|
|
local m = Types.Midi.new(96)
|
|
local notes = { { tick = 0, type = "noteOn", channel = 0, data = { 60, 100 } }, { tick = 96, type = "noteOff", channel = 0, data = { 60, 0 } } }
|
|
m.tracks[1] = { name = "Lead", events = notes }
|
|
m.tracks[2] = { name = "Ignored", events = { { tick = 0, type = "meta", meta = 0x03, data = { string.byte("Bass", 1, -1) } } } }
|
|
m.tracks[3] = { name = "", events = {} }
|
|
local back = decode(Midi.encode(m) :: buffer)
|
|
t:eq(back.tracks[1].name, "Lead", "track.name written")
|
|
local first = back.tracks[1].events[1]
|
|
t:check(first.type == "meta" and first.meta == 0x03 and first.tick == 0, "as a 0x03 event at tick 0")
|
|
t:eq(#back.tracks[1].events, 4, "name + 2 notes + end of track")
|
|
t:eq(back.tracks[2].name, "Bass", "the track's own 0x03 event wins")
|
|
t:eq(back.tracks[3].name, nil, "empty name: nothing written")
|
|
t:eq(#m.tracks[1].events, 2, "the caller's events are not changed")
|
|
end
|
|
|
|
-- crafted bad files
|
|
for _, c in Bad do
|
|
local ok, m, err = pcall(decode, c.data)
|
|
t:check(ok, c.name .. ": threw " .. tostring(m))
|
|
t:check(m == nil and Err.is(err), c.name .. ": decoded")
|
|
t:eq(err.code, c.code, c.name .. ": error code (" .. tostring(err) .. ")")
|
|
end
|
|
|
|
-- truncation: lenient keeps what it read, strict fails
|
|
do
|
|
local m = decode(Trunc.data)
|
|
t:check(m and m.meta.truncated, "truncated file decodes leniently, flagged")
|
|
local n = 0
|
|
for _, tr in m.tracks do
|
|
n += #tr.events
|
|
end
|
|
t:check(n > 50, "truncated file keeps its events (" .. n .. ")")
|
|
local s, err = decode(Trunc.data, { strict = true })
|
|
t:check(s == nil and err.code == Err.TRUNCATED, "strict: TRUNCATED")
|
|
t:eq(decode(byName.format1.data, { strict = true }).meta.truncated, false, "strict: a whole file passes")
|
|
local l, lerr = decode(byName.random.data, { maxEvents = 100 })
|
|
t:check(l == nil and lerr.code == Err.LIMIT, "maxEvents: LIMIT")
|
|
end
|
|
|
|
-- render through the built-in waveform set
|
|
do
|
|
local song = decode(byName.song.data)
|
|
local dec = song:render({ tail = 0.5 })
|
|
local want = math.ceil((byName.song.length + 0.5) * 44100)
|
|
t:eq(dec.frames, want, "render: frames = (length + tail) * rate")
|
|
t:eq(dec.channels, 2, "render: stereo")
|
|
t:eq(dec.sampleRate, 44100, "render: rate")
|
|
local total, sumsq, peak = 0, 0, 0
|
|
local out = buffer.create(4096 * 8)
|
|
while true do
|
|
local b, n = dec:read(4096, out)
|
|
if n == 0 then
|
|
break
|
|
end
|
|
for i = 0, n * 2 - 1 do
|
|
local v = buffer.readf32(b, i * 4)
|
|
sumsq += v * v
|
|
peak = math.max(peak, math.abs(v))
|
|
end
|
|
total += n
|
|
end
|
|
t:eq(total, want, "render: reads every frame")
|
|
local rms = math.sqrt(sumsq / (total * 2))
|
|
t:check(rms > 0.01 and peak < 4 and peak == peak, string.format("render: audible and sane (rms %.3f, peak %.3f)", rms, peak))
|
|
t:note("fallback render: %.2f s, rms %.3f, peak %.3f", total / 44100, rms, peak)
|
|
-- seek: the same samples as playing through
|
|
local a = song:render({ tail = 0.5 })
|
|
a:seek(1.5)
|
|
t:check(math.abs(a:position() - 1.5) < 1e-4, "seek position")
|
|
local x = buffer.create(1024 * 8)
|
|
a:read(1024, x)
|
|
local c = song:render({ tail = 0.5 })
|
|
c:read(66150)
|
|
local y = c:read(1024)
|
|
local same = true
|
|
for i = 0, 2047 do
|
|
if buffer.readf32(x, i * 4) ~= buffer.readf32(y, i * 4) then
|
|
same = false
|
|
break
|
|
end
|
|
end
|
|
t:check(same, "seek renders the same samples as reading through")
|
|
a:seek(0.25) -- backwards
|
|
t:check(math.abs(a:position() - 0.25) < 1e-4, "seek backwards")
|
|
-- open = decode + render
|
|
local o = Midi.open(Bytes.reader(buffer.fromstring(byName.song.data)), { sampleRate = 22050, tail = 0 })
|
|
t:check(o and o.sampleRate == 22050, "open: a Decoder at the asked rate")
|
|
local bad, berr = Midi.render(song, { sampleRate = 5 })
|
|
t:check(bad == nil and berr.code == Err.ARG, "render: bad sampleRate")
|
|
local bs, bserr = Midi.render(song, { soundfont = "not a soundfont" })
|
|
t:check(bs == nil and Err.is(bserr), "render: bad soundfont bytes")
|
|
end
|
|
|
|
-- the fuzz no-throw pass
|
|
local samples = {}
|
|
for _, c in Cases do
|
|
if #c.data < 20000 then
|
|
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 })
|
|
t:fuzz("decode + render", function(b: buffer)
|
|
local m = decode(b)
|
|
if m then
|
|
local dec = Midi.render(m, { tail = 0.1 })
|
|
if dec then
|
|
dec:read(2048)
|
|
dec:read(2048)
|
|
end
|
|
Midi.encode(m)
|
|
end
|
|
end, samples, { mutations = 20, garbage = 50 })
|
|
|
|
t:done()
|