ws-music: merge ws/music-midi (music/midi, music/sf2, codecs/SoundFont)
This commit is contained in:
commit
8bdf67d1a4
21 files changed
+3652
-1
No files matched your search
@@ -56,3 +56,63 @@ do
|
||||
Png.encode(img)
|
||||
end)
|
||||
end
|
||||
|
||||
-- MIDI through the SoundFont synth (tools/fixtures/sf2.py's test song; tools/fixtures/midi.py's "song" through the
|
||||
-- built-in waveform set): seconds of stereo 44.1 kHz audio rendered per second of CPU
|
||||
do
|
||||
local Midi = require("@formats/music/midi")
|
||||
local Sf2 = require("@formats/music/sf2")
|
||||
local SF = require("@tests/gen/sf2_cases")
|
||||
local MC = require("@tests/gen/midi_cases")
|
||||
local sf = assert(Sf2.decode(Bytes.reader(buffer.fromstring(SF.sf2))))
|
||||
local function realtime(label: string, data: string, font: any)
|
||||
local song = assert(Midi.decode(Bytes.reader(buffer.fromstring(data))))
|
||||
local best = math.huge
|
||||
local frames = 0
|
||||
for _ = 1, 3 do
|
||||
local dec = assert(Midi.render(song, { soundfont = font, tail = 0 }))
|
||||
local out = buffer.create(4096 * 8)
|
||||
local t0 = os.clock()
|
||||
frames = 0
|
||||
while true do
|
||||
local _, n = dec:read(4096, out)
|
||||
if n == 0 then
|
||||
break
|
||||
end
|
||||
frames += n
|
||||
end
|
||||
best = math.min(best, os.clock() - t0)
|
||||
end
|
||||
print(string.format("%-8s %-30s %8.2f ms %7.1f x realtime", runtime, label, best * 1000, frames / 44100 / best))
|
||||
end
|
||||
realtime("midi render sf2 (test song)", SF.song, sf)
|
||||
for _, c in MC do
|
||||
if c.name == "song" then
|
||||
realtime("midi render fallback", c.data, nil)
|
||||
end
|
||||
end
|
||||
end
|
||||
-- the synth's per-voice cost: 32 sustained, filtered, looped voices (sf2 saw preset with a mod env) for 2 s
|
||||
do
|
||||
local SoundFont = require("@formats/codecs/SoundFont")
|
||||
local Sf2 = require("@formats/music/sf2")
|
||||
local SF = require("@tests/gen/sf2_cases")
|
||||
local sf = assert(Sf2.decode(Bytes.reader(buffer.fromstring(SF.sf2))))
|
||||
local frames = 88200
|
||||
local out = buffer.create(frames * 8)
|
||||
local best = math.huge
|
||||
for _ = 1, 3 do
|
||||
local s = SoundFont.synth(sf, 44100)
|
||||
SoundFont.Synth.midi(s, 0xC0, 1, 0)
|
||||
for k = 0, 31 do
|
||||
SoundFont.Synth.midi(s, 0x90, 40 + k, 100)
|
||||
end
|
||||
buffer.fill(out, 0, 0)
|
||||
local t0 = os.clock()
|
||||
for f = 0, frames - 1, 1024 do
|
||||
SoundFont.Synth.render(s, out, f, 1024)
|
||||
end
|
||||
best = math.min(best, os.clock() - t0)
|
||||
end
|
||||
print(string.format("%-8s %-30s %8.2f ms %7.1f M voice-samples/s", runtime, "synth 32 voices x 2 s", best * 1000, 32 * frames / best / 1e6))
|
||||
end
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
cd "$(dirname "$0")/.." || exit 1
|
||||
LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')}
|
||||
LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')}
|
||||
python3 -I tools/fixtures.py deflate png > /dev/null || exit 1
|
||||
python3 -I tools/fixtures.py deflate png midi sf2 > /dev/null || exit 1
|
||||
python3 -I tools/build.py luajit > /dev/null || exit 1
|
||||
"$LUAU" --codegen -O2 tools/bench.luau
|
||||
"$LUAJIT" -e 'package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path' build/luajit/tools/bench.lua
|
||||
@@ -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)
|
||||
@@ -0,0 +1,61 @@
|
||||
# Audio features of a WAV on stdin (run by tools/fixtures/sf2.py through ctx.python(["numpy"], ...); not a generator).
|
||||
# tests/music/sf2.luau computes the same features from formats-luau's render and compares them:
|
||||
# env RMS of the mono mix per 50 ms window (2205 frames)
|
||||
# bands per 2 s segment: mean power in 24 log-spaced bands (60 Hz .. 16 kHz) of 2048-point Hann frames (hop 1024),
|
||||
# in dB
|
||||
# peaks the strongest frequency (parabolic interpolation) of the mean 8192-point Hann spectrum in a few windows
|
||||
import io, json, sys, wave
|
||||
import numpy as np
|
||||
|
||||
w = wave.open(io.BytesIO(sys.stdin.buffer.read()))
|
||||
rate, ch, width, n = w.getframerate(), w.getnchannels(), w.getsampwidth(), w.getnframes()
|
||||
raw = w.readframes(n)
|
||||
assert width == 2, width
|
||||
x = np.frombuffer(raw, dtype="<i2").astype(np.float64).reshape(-1, ch) / 32768.0
|
||||
mono = x.mean(axis=1)
|
||||
|
||||
ENV = 2205
|
||||
env = [float(np.sqrt(np.mean(mono[i:i + ENV] ** 2))) for i in range(0, len(mono) - ENV + 1, ENV)]
|
||||
|
||||
N, HOP = 2048, 1024
|
||||
edges = [float(e) for e in np.geomspace(60, 16000, 25)]
|
||||
freqs = np.arange(N // 2 + 1) * rate / N
|
||||
han = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(N) / N)
|
||||
SEGMENTS = [(0, 2), (2, 4), (4, 6), (6, 8), (8, 10), (10, 12)]
|
||||
|
||||
|
||||
def bands(a, b):
|
||||
acc, frames = np.zeros(24), 0
|
||||
for s in range(int(a * rate), int(b * rate) - N + 1, HOP):
|
||||
p = np.abs(np.fft.rfft(mono[s:s + N] * han)) ** 2
|
||||
for k in range(24):
|
||||
acc[k] += p[(freqs >= edges[k]) & (freqs < edges[k + 1])].sum()
|
||||
frames += 1
|
||||
return [float(10 * np.log10(v / max(frames, 1) + 1e-12)) for v in acc]
|
||||
|
||||
|
||||
PN = 8192
|
||||
phan = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(PN) / PN)
|
||||
WINDOWS = [(4.2, 5.4), (8.05, 8.45), (8.55, 8.95), (2.02, 2.33)]
|
||||
|
||||
|
||||
def peak(a, b):
|
||||
acc = np.zeros(PN // 2 + 1)
|
||||
for s in range(int(a * rate), int(b * rate) - PN + 1, PN // 4):
|
||||
acc += np.abs(np.fft.rfft(mono[s:s + PN] * phan)) ** 2
|
||||
k = int(np.argmax(acc[1:-1])) + 1
|
||||
y0, y1, y2 = np.log(acc[k - 1] + 1e-30), np.log(acc[k] + 1e-30), np.log(acc[k + 1] + 1e-30)
|
||||
d = 0.5 * (y0 - y2) / (y0 - 2 * y1 + y2)
|
||||
return float((k + d) * rate / PN)
|
||||
|
||||
|
||||
json.dump({
|
||||
"rate": rate,
|
||||
"frames": len(mono),
|
||||
"env": env,
|
||||
"edges": edges,
|
||||
"segments": [list(s) for s in SEGMENTS],
|
||||
"bands": [bands(a, b) for a, b in SEGMENTS],
|
||||
"windows": [list(wd) for wd in WINDOWS],
|
||||
"peaks": [peak(a, b) for a, b in WINDOWS],
|
||||
}, sys.stdout)
|
||||
@@ -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]})
|
||||
@@ -0,0 +1,227 @@
|
||||
# SoundFont fixtures (tools/fixtures.py): a small self-made SF2 (band-limited sine / saw / square loops + a noise
|
||||
# burst; melodic presets with envelopes, a filter + mod envelope, vibrato, a preset global zone, an instrument global
|
||||
# zone, a drum kit on bank 128 with exclusive classes), a 12.5 s test song (SMF written here) that plays each preset in
|
||||
# its own 2 s segment (chords, pitch bend with an RPN 0 range of 12, sustain pedal, CC7 / CC11), the song rendered by
|
||||
# FluidSynth (nixpkgs#fluidsynth, reverb and chorus off) and analysed with numpy (tools/fixtures/_sf2_features.py):
|
||||
# tests/gen/sf2_cases.luau { sf2, sf2_24 (the same with an sm24 chunk), song, fluid = { env, bands, peaks },
|
||||
# expect = { presets, samples, instruments, info, values } }
|
||||
import json, math, os, random, struct, subprocess, tempfile
|
||||
|
||||
INPUTS = ["tools/fixtures/_sf2_features.py"]
|
||||
RATE = 44100
|
||||
PERIOD = 100 # 441 Hz loops
|
||||
CYCLES = 50
|
||||
|
||||
|
||||
def tc(sec):
|
||||
return int(round(1200 * math.log2(sec)))
|
||||
|
||||
|
||||
def hz_cents(hz):
|
||||
return int(round(1200 * math.log2(hz / 8.176)))
|
||||
|
||||
|
||||
def wave(kind, rng):
|
||||
n = PERIOD * CYCLES
|
||||
out = []
|
||||
for i in range(n):
|
||||
ph = 2 * math.pi * i / PERIOD
|
||||
if kind == "sine":
|
||||
v = math.sin(ph) * 0.8
|
||||
elif kind == "saw":
|
||||
v = sum(math.sin(k * ph) / k for k in range(1, 50)) * 0.45
|
||||
else:
|
||||
v = sum(math.sin(k * ph) / k for k in range(1, 50, 2)) * 0.6
|
||||
out.append(v)
|
||||
return out
|
||||
|
||||
|
||||
def chunk(cid, data):
|
||||
pad = b"\x00" if len(data) % 2 else b""
|
||||
return cid + struct.pack("<I", len(data)) + data + pad
|
||||
|
||||
|
||||
def lst(kind, chunks):
|
||||
body = kind + b"".join(chunks)
|
||||
return b"LIST" + struct.pack("<I", len(body)) + body
|
||||
|
||||
|
||||
def zstr(s):
|
||||
b = s.encode() + b"\x00"
|
||||
return b + (b"\x00" if len(b) % 2 else b"")
|
||||
|
||||
|
||||
def name20(s):
|
||||
return s.encode()[:19].ljust(20, b"\x00")
|
||||
|
||||
|
||||
def build_sf2(with24):
|
||||
rng = random.Random(3)
|
||||
waves = [("sine", wave("sine", rng)), ("saw", wave("saw", rng)), ("square", wave("square", rng)),
|
||||
("noise", [rng.uniform(-0.7, 0.7) for _ in range(RATE // 2)])]
|
||||
pcm, pcm24, headers = bytearray(), bytearray(), []
|
||||
pos = 0
|
||||
for name, w in waves:
|
||||
start = pos
|
||||
for v in w:
|
||||
x = int(round(v * 8388607))
|
||||
hi, lo = x >> 8, x & 255
|
||||
pcm += struct.pack("<h", hi)
|
||||
pcm24.append(lo)
|
||||
pos += len(w)
|
||||
end = pos
|
||||
pcm += b"\x00\x00" * 46
|
||||
pcm24 += b"\x00" * 46
|
||||
pos += 46
|
||||
# sine: 441 Hz = A4 + 3.93 cents -> root 69, correction -4 makes it play 440 Hz-ish at key 69
|
||||
headers.append((name, start, end, start, end, RATE, 69, -4, 0, 1))
|
||||
if len(pcm24) % 2:
|
||||
pcm24 += b"\x00"
|
||||
info = lst(b"INFO", [chunk(b"ifil", struct.pack("<HH", 2, 4)), chunk(b"isng", zstr("EMU8000")),
|
||||
chunk(b"INAM", zstr("formats-luau test bank")), chunk(b"ICMT", zstr("generated by tools/fixtures/sf2.py"))])
|
||||
sd = [chunk(b"smpl", bytes(pcm))] + ([chunk(b"sm24", bytes(pcm24))] if with24 else [])
|
||||
sdta = lst(b"sdta", sd)
|
||||
|
||||
# instruments: lists of zones, a zone = [(op, amount)], amounts as signed 16 (key ranges: lo | hi << 8)
|
||||
def rng_(lo, hi):
|
||||
return lo | (hi << 8)
|
||||
insts = [
|
||||
("sine inst", [[(34, tc(0.01)), (36, tc(0.5)), (37, 60), (38, tc(0.2)), (54, 1), (53, 0)]]),
|
||||
("saw inst", [[(8, hz_cents(2500))], # the instrument global zone: a low-pass
|
||||
[(34, tc(0.005)), (38, tc(0.15)), (28, tc(0.4)), (29, 1000), (11, 2400), (54, 1), (53, 1)]]),
|
||||
("square inst", [[(34, tc(0.02)), (38, tc(0.1)), (6, 50), (24, hz_cents(5)), (54, 1), (53, 2)]]),
|
||||
("drum inst", [[(38, tc(0.05))],
|
||||
[(43, rng_(35, 36)), (36, tc(0.3)), (37, 1440), (54, 1), (53, 0)],
|
||||
[(43, rng_(38, 38)), (8, hz_cents(5000)), (36, tc(0.15)), (37, 1440), (53, 3)],
|
||||
[(43, rng_(42, 42)), (36, tc(0.06)), (37, 1440), (57, 1), (58, 81), (53, 3)],
|
||||
[(43, rng_(46, 46)), (36, tc(0.6)), (37, 1440), (57, 1), (58, 81), (53, 3)]]),
|
||||
]
|
||||
presets = [
|
||||
("Sine", 0, 0, [[(48, 30)], [(41, 0)]]), # a preset global zone (attenuation), then the instrument
|
||||
("Saw", 1, 0, [[(41, 1)]]),
|
||||
("Square", 2, 0, [[(41, 2)]]),
|
||||
("Drums", 0, 128, [[(41, 3)]]),
|
||||
]
|
||||
phdr, pbag, pgen = bytearray(), bytearray(), bytearray()
|
||||
bag = gen = 0
|
||||
for name, prog, bank, zones in presets:
|
||||
phdr += name20(name) + struct.pack("<HHHIII", prog, bank, bag, 0, 0, 0)
|
||||
for z in zones:
|
||||
pbag += struct.pack("<HH", gen, 0)
|
||||
bag += 1
|
||||
for op, amt in z:
|
||||
pgen += struct.pack("<Hh" if op != 43 else "<HH", op, amt)
|
||||
gen += 1
|
||||
phdr += name20("EOP") + struct.pack("<HHHIII", 0, 0, bag, 0, 0, 0)
|
||||
pbag += struct.pack("<HH", gen, 0)
|
||||
pgen += struct.pack("<HH", 0, 0)
|
||||
inst, ibag, igen = bytearray(), bytearray(), bytearray()
|
||||
bag = gen = 0
|
||||
for name, zones in insts:
|
||||
inst += name20(name) + struct.pack("<H", bag)
|
||||
for z in zones:
|
||||
ibag += struct.pack("<HH", gen, 0)
|
||||
bag += 1
|
||||
for op, amt in z:
|
||||
igen += struct.pack("<Hh" if op != 43 else "<HH", op, amt)
|
||||
gen += 1
|
||||
inst += name20("EOI") + struct.pack("<H", bag)
|
||||
ibag += struct.pack("<HH", gen, 0)
|
||||
igen += struct.pack("<HH", 0, 0)
|
||||
shdr = bytearray()
|
||||
for (name, s, e, ls, le, rate, pitch, corr, link, typ) in headers:
|
||||
shdr += name20(name) + struct.pack("<IIIIIBbHH", s, e, ls, le, rate, pitch, corr, link, typ)
|
||||
shdr += name20("EOS") + b"\x00" * 26
|
||||
pmod = b"\x00" * 10
|
||||
pdta = lst(b"pdta", [chunk(b"phdr", bytes(phdr)), chunk(b"pbag", bytes(pbag)), chunk(b"pmod", pmod),
|
||||
chunk(b"pgen", bytes(pgen)), chunk(b"inst", bytes(inst)), chunk(b"ibag", bytes(ibag)),
|
||||
chunk(b"imod", pmod), chunk(b"igen", bytes(igen)), chunk(b"shdr", bytes(shdr))])
|
||||
body = b"sfbk" + info + sdta + pdta
|
||||
data = b"RIFF" + struct.pack("<I", len(body)) + body
|
||||
expect = {
|
||||
"presets": [{"name": n, "preset": p, "bank": b} for n, p, b, _ in sorted(presets, key=lambda x: (x[2], x[1]))],
|
||||
"samples": [{"name": h[0], "start": h[1], "stop": h[2], "loopStart": h[3], "loopEnd": h[4], "sampleRate": h[5],
|
||||
"originalPitch": h[6], "pitchCorrection": h[7]} for h in headers],
|
||||
"instruments": [n for n, _ in insts],
|
||||
"info": {"name": "formats-luau test bank", "engine": "EMU8000", "version": "2.04"},
|
||||
# a few raw sample values (16-bit and 24-bit) for the sample decoding check
|
||||
"values": [[i, struct.unpack_from("<h", pcm, i * 2)[0], pcm24[i]] for i in (0, 1, 25, 77, 5000 + 46 + 13, 20000)],
|
||||
}
|
||||
return data, expect
|
||||
|
||||
|
||||
def vlq(v):
|
||||
out = [v & 127]
|
||||
v >>= 7
|
||||
while v:
|
||||
out.insert(0, (v & 127) | 128)
|
||||
v >>= 7
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def song():
|
||||
tpq, us = 480, 500000 # 1 beat = 0.5 s
|
||||
ev = [] # (seconds, bytes)
|
||||
|
||||
def at(sec, *b):
|
||||
ev.append((sec, bytes(b)))
|
||||
at(0, 0xC0, 0)
|
||||
at(0, 0xC1, 1)
|
||||
at(0, 0xC2, 2)
|
||||
# seg 0: a sine chord
|
||||
for n in (60, 64, 67):
|
||||
at(0.0, 0x90, n, 127)
|
||||
at(1.5, 0x80, n, 0)
|
||||
# seg 1: a saw melody (filter + mod env)
|
||||
for k, n in enumerate((48, 52, 55, 60)):
|
||||
at(2.0 + 0.4 * k, 0x91, n, 127)
|
||||
at(2.35 + 0.4 * k, 0x81, n, 0)
|
||||
# seg 2: a square with vibrato
|
||||
at(4.0, 0x92, 69, 127)
|
||||
at(5.5, 0x82, 69, 0)
|
||||
# seg 3: drums (hats cut each other: exclusive class)
|
||||
for sec, n in ((6.0, 36), (6.25, 42), (6.5, 38), (6.75, 42), (7.0, 46), (7.25, 42), (7.5, 36)):
|
||||
at(sec, 0x99, n, 127)
|
||||
at(sec + 0.1, 0x89, n, 0)
|
||||
# seg 4: sine with a pitch-bend range of 12 (RPN 0), a bend up an octave, the sustain pedal
|
||||
at(7.9, 0xB0, 101, 0)
|
||||
at(7.9, 0xB0, 100, 0)
|
||||
at(7.9, 0xB0, 6, 12)
|
||||
at(8.0, 0x90, 72, 127)
|
||||
at(8.5, 0xE0, 0x7F, 0x7F)
|
||||
at(9.0, 0xE0, 0x00, 0x40)
|
||||
at(9.1, 0xB0, 64, 127)
|
||||
at(9.2, 0x80, 72, 0)
|
||||
at(9.6, 0xB0, 64, 0)
|
||||
# seg 5: saw with volume and expression changes
|
||||
at(10.0, 0x91, 57, 127)
|
||||
at(10.75, 0xB1, 7, 60)
|
||||
at(11.25, 0xB1, 11, 64)
|
||||
at(11.6, 0x81, 57, 0)
|
||||
ev.sort(key=lambda e: e[0])
|
||||
body, last = bytearray(), 0
|
||||
body += b"\x00\xff\x51\x03" + struct.pack(">I", us)[1:]
|
||||
for sec, b in ev:
|
||||
tick = int(round(sec * tpq * 1e6 / us))
|
||||
body += vlq(tick - last) + b
|
||||
last = tick
|
||||
end = int(round(12.5 * tpq * 1e6 / us))
|
||||
body += vlq(end - last) + b"\xff\x2f\x00"
|
||||
return b"MThd" + struct.pack(">IHHH", 6, 0, 1, tpq) + b"MTrk" + struct.pack(">I", len(body)) + bytes(body)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
sf2, expect = build_sf2(False)
|
||||
sf2_24, _ = build_sf2(True)
|
||||
mid = song()
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
fp, mp, wp = os.path.join(d, "t.sf2"), os.path.join(d, "t.mid"), os.path.join(d, "t.wav")
|
||||
with open(fp, "wb") as f:
|
||||
f.write(sf2)
|
||||
with open(mp, "wb") as f:
|
||||
f.write(mid)
|
||||
ctx.nix("fluidsynth", ["fluidsynth", "-ni", "-q", "-R", "0", "-C", "0", "-g", "0.5", "-r", "44100", "-F", wp, fp, mp])
|
||||
with open(wp, "rb") as f:
|
||||
wav = f.read()
|
||||
fluid = json.loads(ctx.python(["numpy"], ctx.read("tools/fixtures/_sf2_features.py").decode(), input=wav))
|
||||
ctx.emit("sf2_cases", {"sf2": sf2, "sf2_24": sf2_24, "song": mid, "fluid": fluid, "expect": expect})
|
||||
Reference in new issue
Block a user