ws-music: music/midi (SMF 0/1/2 read/write, tempo map, render), codecs/SoundFont (SF2 parser + TinySoundFont-port synth + fallback waveform set), midi tests vs mido

Types.luau: Midi gets an optional render(self, opts) -> Decoder field (backward compatible; set by music/midi decode).
This commit is contained in:
4DBug committed 2026-10-31 08:37:25 -05:00
1 parent ccb06775c5
commit d2280d3b77
14 files changed
+2955

No files matched your search

+183
View File
@@ -0,0 +1,183 @@
# MIDI reference cases (run by tools/fixtures/midi.py through ctx.python(["mido"], ...); not a generator itself).
# Builds Standard MIDI Files with python mido (formats 0 / 1 / 2, tempo changes, time / key signatures, running
# status, sysex, pitch bend, every channel message, a random stress file), saves them with mido, and prints JSON:
# per file the bytes, mido's parse in formats-luau's event shape and mido's lengths / message times.
import io, json, random, sys
import mido
from mido import Message, MetaMessage, MidiFile, MidiTrack
def ours(msg):
"""a mido message -> [type, channel, data, meta] in formats-luau's shape (data = raw bytes)"""
t = msg.type
if msg.is_meta:
b = msg.bytes()
i = 2
while b[i] & 0x80:
i += 1
return ["meta", -1, list(b[i + 1:]), b[1]]
if t == "sysex":
return ["sysex", -1, list(msg.data) + [0xF7], -1]
if t == "note_on":
return ["noteOn", msg.channel, [msg.note, msg.velocity], -1]
if t == "note_off":
return ["noteOff", msg.channel, [msg.note, msg.velocity], -1]
if t == "polytouch":
return ["aftertouch", msg.channel, [msg.note, msg.value], -1]
if t == "control_change":
return ["controller", msg.channel, [msg.control, msg.value], -1]
if t == "program_change":
return ["program", msg.channel, [msg.program], -1]
if t == "aftertouch":
return ["channelPressure", msg.channel, [msg.value], -1]
if t == "pitchwheel":
v = msg.pitch + 8192
return ["pitchBend", msg.channel, [v & 127, v >> 7], -1]
raise ValueError(t)
def describe(name, mid):
buf = io.BytesIO()
mid.save(file=buf)
data = buf.getvalue()
back = MidiFile(file=io.BytesIO(data))
tracks = []
for tr in back.tracks:
tick, evs = 0, []
for msg in tr:
tick += msg.time
evs.append([tick] + ours(msg))
tracks.append(evs)
case = {"name": name, "hex": data.hex(), "type": back.type, "division": back.ticks_per_beat, "tracks": tracks}
if back.type != 2 and back.ticks_per_beat > 0:
case["length"] = back.length
t, times = 0.0, []
for msg in back:
t += msg.time
times.append(t)
case["times"] = times
return case
def notes(track, ch, rng, n, prog=None, start=0):
if prog is not None:
track.append(Message("program_change", channel=ch, program=prog, time=start))
start = 0
for i in range(n):
note = rng.randint(30, 90)
track.append(Message("note_on", channel=ch, note=note, velocity=rng.randint(1, 127), time=start if i == 0 else rng.randint(0, 120)))
track.append(Message("note_off", channel=ch, note=note, velocity=rng.randint(0, 127), time=rng.randint(1, 480)))
cases = []
rng = random.Random(7)
# format 0: one track with everything
mid = MidiFile(type=0, ticks_per_beat=480)
t = MidiTrack()
mid.tracks.append(t)
t.append(MetaMessage("track_name", name="format zero"))
t.append(MetaMessage("set_tempo", tempo=500000))
t.append(MetaMessage("time_signature", numerator=3, denominator=4, clocks_per_click=24, notated_32nd_notes_per_beat=8))
t.append(MetaMessage("key_signature", key="Eb"))
t.append(MetaMessage("text", text="hello"))
t.append(Message("program_change", channel=0, program=5))
t.append(Message("control_change", channel=0, control=7, value=100))
t.append(Message("control_change", channel=0, control=10, value=20))
t.append(Message("note_on", channel=0, note=60, velocity=100, time=0))
t.append(Message("note_on", channel=0, note=64, velocity=90, time=10)) # running status
t.append(Message("note_on", channel=0, note=67, velocity=80, time=10))
t.append(Message("pitchwheel", channel=0, pitch=-8192, time=100))
t.append(Message("pitchwheel", channel=0, pitch=8191, time=100))
t.append(Message("pitchwheel", channel=0, pitch=0, time=100))
t.append(Message("polytouch", channel=0, note=60, value=33, time=5))
t.append(Message("aftertouch", channel=0, value=44, time=5))
t.append(Message("sysex", data=[0x7E, 0x7F, 0x09, 0x01], time=0))
t.append(MetaMessage("set_tempo", tempo=300000, time=240))
t.append(Message("note_off", channel=0, note=60, velocity=0, time=480))
t.append(Message("note_on", channel=0, note=64, velocity=0, time=0)) # note on, velocity 0
t.append(Message("note_off", channel=0, note=67, velocity=64, time=0))
t.append(Message("note_on", channel=9, note=36, velocity=127, time=100))
t.append(Message("note_off", channel=9, note=36, velocity=0, time=100))
t.append(MetaMessage("time_signature", numerator=6, denominator=8, time=0))
t.append(MetaMessage("set_tempo", tempo=1000000, time=10))
t.append(Message("note_on", channel=1, note=72, velocity=50, time=0))
t.append(Message("note_off", channel=1, note=72, velocity=50, time=960))
cases.append(describe("format0", mid))
# format 1: a conductor track + 3 instrument tracks, tempo changes in the conductor
mid = MidiFile(type=1, ticks_per_beat=96)
cond = MidiTrack()
mid.tracks.append(cond)
cond.append(MetaMessage("track_name", name="conductor"))
cond.append(MetaMessage("time_signature", numerator=4, denominator=4))
for i, tempo in enumerate([500000, 400000, 600000, 250000, 750000]):
cond.append(MetaMessage("set_tempo", tempo=tempo, time=0 if i == 0 else 384))
for ch in range(3):
tr = MidiTrack()
mid.tracks.append(tr)
tr.append(MetaMessage("track_name", name="part %d" % ch))
notes(tr, ch, rng, 40, prog=ch * 10)
cases.append(describe("format1", mid))
# format 2: independent patterns, each with its own tempo
mid = MidiFile(type=2, ticks_per_beat=240)
for k in range(3):
tr = MidiTrack()
mid.tracks.append(tr)
tr.append(MetaMessage("set_tempo", tempo=400000 + 100000 * k))
notes(tr, k, rng, 10)
cases.append(describe("format2", mid))
# a random stress file: many tracks / channels / controller streams (long running-status runs)
mid = MidiFile(type=1, ticks_per_beat=480)
for k in range(6):
tr = MidiTrack()
mid.tracks.append(tr)
if k == 0:
for j in range(20):
tr.append(MetaMessage("set_tempo", tempo=rng.randint(200000, 1500000), time=rng.randint(0, 2000)))
continue
ch = rng.randint(0, 15)
for j in range(400):
r = rng.random()
dt = rng.choice([0, 0, 1, 7, 120, 480, 20000])
if r < 0.4:
tr.append(Message("note_on", channel=ch, note=rng.randint(0, 127), velocity=rng.randint(0, 127), time=dt))
elif r < 0.6:
tr.append(Message("note_off", channel=ch, note=rng.randint(0, 127), velocity=rng.randint(0, 127), time=dt))
elif r < 0.8:
tr.append(Message("control_change", channel=ch, control=rng.randint(0, 127), value=rng.randint(0, 127), time=dt))
elif r < 0.9:
tr.append(Message("pitchwheel", channel=ch, pitch=rng.randint(-8192, 8191), time=dt))
elif r < 0.95:
tr.append(Message("program_change", channel=ch, program=rng.randint(0, 127), time=dt))
else:
tr.append(Message("sysex", data=[rng.randint(0, 127) for _ in range(rng.randint(0, 200))], time=dt))
cases.append(describe("random", mid))
# SMPTE time (25 fps, 40 ticks per frame): division = -(25 << 8) + 40 as a signed 16-bit value
mid = MidiFile(type=0, ticks_per_beat=-6360)
t = MidiTrack()
mid.tracks.append(t)
t.append(Message("note_on", note=60, velocity=64, time=0))
t.append(Message("note_off", note=60, velocity=64, time=1000))
cases.append(describe("smpte", mid))
# the song the fallback / SoundFont render tests play (tools/fixtures/sf2.py has its own); its mido length
mid = MidiFile(type=1, ticks_per_beat=480)
cond = MidiTrack()
mid.tracks.append(cond)
cond.append(MetaMessage("set_tempo", tempo=500000))
cond.append(MetaMessage("set_tempo", tempo=250000, time=1920))
tr = MidiTrack()
mid.tracks.append(tr)
notes(tr, 0, rng, 12, prog=0)
dr = MidiTrack()
mid.tracks.append(dr)
for k in range(16):
dr.append(Message("note_on", channel=9, note=[36, 38, 42, 46][k % 4], velocity=110, time=0 if k == 0 else 120))
dr.append(Message("note_off", channel=9, note=[36, 38, 42, 46][k % 4], velocity=0, time=120))
cases.append(describe("song", mid))
json.dump(cases, sys.stdout)
+72
View File
@@ -0,0 +1,72 @@
# MIDI fixtures (tools/fixtures.py). Reference parses from python mido (tools/fixtures/_midi_ref.py, run in a nix
# python with mido) plus hand-made byte strings for what mido does not write.
# tests/gen/midi_cases.luau { { name, data, type, division, tracks = { { {tick, type, channel, data, meta} } },
# length?, times?, exact? } }: channel / meta = -1 when absent; exact = the bytes are
# what an encoder with running status writes (mido's own output)
# tests/gen/midi_bad.luau { { name, data, code } }: crafted bad files and the Err code expected
# tests/gen/midi_trunc.luau { name, data }: a mido file cut short (lenient decode keeps the events, strict fails)
import json, struct
INPUTS = ["tools/fixtures/_midi_ref.py"]
def vlq(v):
out = [v & 127]
v >>= 7
while v:
out.insert(0, (v & 127) | 128)
v >>= 7
return bytes(out)
def smf(tracks, fmt=0, division=96, extra=b""):
out = b"MThd" + struct.pack(">IHHh", 6, fmt, len(tracks), division) + extra
for body in tracks:
out += b"MTrk" + struct.pack(">I", len(body)) + body
return out
def generate(ctx):
ref = json.loads(ctx.python(["mido"], ctx.read("tools/fixtures/_midi_ref.py").decode()))
cases = []
by_name = {}
for c in ref:
case = {"name": c["name"], "data": bytes.fromhex(c["hex"]), "type": c["type"], "division": c["division"],
"tracks": c["tracks"], "exact": True}
if "length" in c:
case["length"] = c["length"]
case["times"] = c["times"]
cases.append(case)
by_name[c["name"]] = case
# running status across meta and escape events (mido's writer never relies on it), and an F7 escape
body = (b"\x00\x90\x3c\x40" + b"\x00\xff\x01\x01\x41" + b"\x10\x3c\x00" + b"\x00\xf7\x02\xf3\x01" + b"\x05\x3e\x7f"
+ b"\x00\xff\x2f\x00")
cases.append({"name": "running-after-meta", "data": smf([body]), "type": 0, "division": 96, "exact": False, "tracks": [[
[0, "noteOn", 0, [60, 64], -1], [0, "meta", -1, [0x41], 1], [16, "noteOn", 0, [60, 0], -1],
[16, "escape", -1, [0xF3, 0x01], -1], [21, "noteOn", 0, [62, 127], -1], [21, "meta", -1, [], 0x2F]]]})
# an unknown chunk between MThd and MTrk, a longer MThd, and an RMID wrapper
f0 = by_name["format0"]
raw = f0["data"]
hdr, rest = raw[:14], raw[14:]
cases.append(dict(f0, name="unknown-chunk", exact=False, data=hdr + b"XFIH" + struct.pack(">I", 5) + b"abcde" + rest))
long_hdr = b"MThd" + struct.pack(">I", 8) + raw[8:14] + b"\x00\x00" + rest
cases.append(dict(f0, name="long-mthd", exact=False, data=long_hdr))
riff = b"RMID" + b"data" + struct.pack("<I", len(raw)) + raw + (b"\x00" if len(raw) % 2 else b"")
cases.append(dict(f0, name="rmid", exact=False, data=b"RIFF" + struct.pack("<I", len(riff)) + riff))
ctx.emit("midi_cases", cases)
bad = [
{"name": "not-midi", "data": b"MTrk\x00\x00\x00\x00", "code": "CORRUPT"},
{"name": "data-over-127", "data": smf([b"\x00\x90\x3c\x80\x00\xff\x2f\x00"]), "code": "CORRUPT"},
{"name": "running-without-status", "data": smf([b"\x00\x3c\x40\x00\xff\x2f\x00"]), "code": "CORRUPT"},
{"name": "long-delta", "data": smf([b"\x81\x81\x81\x81\x01\x90\x3c\x40"]), "code": "CORRUPT"},
{"name": "format-3", "data": b"MThd" + struct.pack(">IHHh", 6, 3, 0, 96), "code": "UNSUPPORTED"},
{"name": "zero-division", "data": b"MThd" + struct.pack(">IHHh", 6, 0, 0, 0), "code": "CORRUPT"},
{"name": "short-header", "data": b"MThd\x00\x00\x00\x06\x00", "code": "TRUNCATED"},
{"name": "system-common", "data": smf([b"\x00\xf2\x01\x02"]), "code": "CORRUPT"},
{"name": "rmid-without-data", "data": b"RIFF\x0c\x00\x00\x00RMIDLIST\x00\x00\x00\x00", "code": "CORRUPT"},
]
ctx.emit("midi_bad", bad)
f1 = by_name["format1"]["data"]
ctx.emit("midi_trunc", {"name": "format1-cut", "data": f1[: len(f1) * 3 // 5]})