Files

228 lines
9.3 KiB
Python

# 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("rosetta 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": "rosetta 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})