From d7c2d2eeb54cde6323651ab3b740f008ffddc9be Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:44:56 -0500 Subject: [PATCH] ws-music: music/sf2 + SoundFont tests vs FluidSynth (envelope r 0.995, band spectra r >= 0.969, pitch peaks within 0.6%), gain ramp per block, bench lines tools/bench.sh: also generates the midi + sf2 fixtures (the bench renders their songs). licenses: TinySoundFont MIT row in NOTICE.md. --- docs/FORMATS.md | 3 + licenses/NOTICE.md | 1 + src/Formats/codecs/SoundFont/Parse.luau | 10 +- src/Formats/codecs/SoundFont/Synth.luau | 14 +- src/Formats/music/midi/Smf.luau | 2 +- tests/music/sf2.luau | 338 ++++++++++++++++++++++++ tools/bench.luau | 60 +++++ tools/bench.sh | 2 +- tools/fixtures/_sf2_features.py | 61 +++++ tools/fixtures/sf2.py | 227 ++++++++++++++++ 10 files changed, 707 insertions(+), 11 deletions(-) create mode 100644 tests/music/sf2.luau create mode 100644 tools/fixtures/_sf2_features.py create mode 100644 tools/fixtures/sf2.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 181230b..453281d 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,7 +6,10 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| | image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | +| music | midi | .mid .midi .smf .kar .rmi | yes | yes | formats: 0, 1, 2, render: true, streaming: true, rmid: true | `tests/music/midi.luau` | +| music | sf2 | .sf2 | yes | - | sm24: true, sf3: false | `tests/music/sf2.luau` | Codecs (layer 1, shared by formats; not loadable on their own): - codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. +- codecs/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index 5d28e73..b69b7e3 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -5,6 +5,7 @@ | `src/Formats/codecs/Deflate/` (Inflate, init), `src/Formats/core/Crc32.luau`, `src/Formats/core/Adler32.luau`, `src/Formats/core/Huffman.luau` (table builder) | deflate-luau 1.0.0 (same author), written from RFC 1950-1952 | no licence chosen yet; no third-party code: [deflate-luau-NOTICE.txt](deflate-luau-NOTICE.txt) | | `src/Formats/image/png/` (init, Decode) | png-luau 1.0.0 (same author), written from the PNG specification | no licence chosen yet; no third-party code | | `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) | +| `src/Formats/codecs/SoundFont/` (Synth, the zone merging in Parse) | port of TinySoundFont v0.9 (tsf.h) by Bernhard Schelling, based on SFZero by Steve Folta | MIT: [TinySoundFont-LICENSE.txt](TinySoundFont-LICENSE.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this folder (see docs/STYLE.md, "Absorbing an existing repo"). diff --git a/src/Formats/codecs/SoundFont/Parse.luau b/src/Formats/codecs/SoundFont/Parse.luau index 8e4f60a..90cdfcc 100644 --- a/src/Formats/codecs/SoundFont/Parse.luau +++ b/src/Formats/codecs/SoundFont/Parse.luau @@ -29,7 +29,7 @@ export type SoundFont = { meta: { [string]: any }, } -local GEN_INSTRUMENT, GEN_KEYRANGE, GEN_VELRANGE, GEN_SAMPLEID = 41, 43, 44, 53 +local GEN_INSTRUMENT, GEN_SAMPLEID = 41, 53 -- generator op -> { field, mode, limit }. modes: f / i (value, merged by adding then clamping), a (sample address -- add), a15 (coarse address add: * 32768), kr / vr (key / velocity range), loop, group, key (overriding root key) @@ -235,7 +235,7 @@ local LAYOUT: { [string]: { number } } = { igen = { 2, 2 }, shdr = { 20, 4, 4, 4, 4, 4, 1, -1, 2, 2 }, } -local RECSIZE = { phdr = 38, pbag = 4, pmod = 10, pgen = 4, inst = 22, ibag = 4, imod = 10, igen = 4, shdr = 46 } +local RECSIZE: { [string]: number } = { phdr = 38, pbag = 4, pmod = 10, pgen = 4, inst = 22, ibag = 4, imod = 10, igen = 4, shdr = 46 } local INFO_NAMES = { isng = "engine", INAM = "name", irom = "rom", ICRD = "date", IENG = "author", IPRD = "product", @@ -296,7 +296,7 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?) if layout and not hydra[sid] then local rs = RECSIZE[sid] local n = sub:remaining() // rs - local recs = table.create(n) + local recs: { { number } } = table.create(n) for i = 1, n do local rec = {} for _, w in layout do @@ -487,7 +487,7 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?) for _, p in presets do (p :: any)._order = nil end - local headers = table.create(nShdr) + local headers: { { [string]: any } } = table.create(nShdr) for i = 1, nShdr do local sh = shdr[i] headers[i] = { @@ -503,7 +503,7 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?) type = sh[10], } end - local instruments = table.create(nInst) + local instruments: { { name: string, zones: number } } = table.create(nInst) for i = 1, nInst do instruments[i] = { name = instNames[i], zones = math.max(0, (inst[i + 1][2] or 0) - inst[i][2]) } end diff --git a/src/Formats/codecs/SoundFont/Synth.luau b/src/Formats/codecs/SoundFont/Synth.luau index 0bde0cd..c133423 100644 --- a/src/Formats/codecs/SoundFont/Synth.luau +++ b/src/Formats/codecs/SoundFont/Synth.luau @@ -8,7 +8,7 @@ -- program / bank select (CC0 / CC32), drums (bank 128), pitch bend with RPN 0 range and RPN 1 / 2 tuning, CC7 volume, -- CC10 pan, CC11 expression, CC64 sustain, CC120 / 121 / 123. Effects (reverb, chorus) and modulators are not -- implemented (as in tsf.h). Output: interleaved stereo f32, mixed into the caller's buffer. --- Differences from tsf.h: a voice limit (oldest release voice stolen, else the note is dropped), channels 0..15 only. +-- Differences from tsf.h: the envelope gain is ramped across each 64-sample block (tsf.h steps it); a voice limit (oldest release voice stolen, else the note is dropped), channels 0..15 only. -- Native, never throws: every buffer index is in range by construction (the regions are clamped by Parse / Fallback, -- the sample buffer has a zero pad sample, the output range is checked before mixing). local Synth = {} @@ -734,7 +734,11 @@ local function voiceRender(s: State, v: Voice, out: buffer, frame: number, numSa if updateVibLfo then lfoProcess(v.viblfo, block) end - local gl, gr = gainMono * v.panL, gainMono * v.panR + -- ramp the gain across the block to the envelope's next level (tsf.h steps it per block: zipper noise) + local gainNext = noteGain * v.amp.level + local step = (gainNext - gainMono) / block + local panL, panR = v.panL, v.panR + local g = gainMono local k = block while k > 0 and pos < endD do k -= 1 @@ -748,8 +752,10 @@ local function voiceRender(s: State, v: Voice, out: buffer, frame: number, numSa z2 = val * a0 - b2 * y val = y end - writef32(out, o, readf32(out, o) + val * gl) - writef32(out, o + 4, readf32(out, o + 4) + val * gr) + val *= g + g += step + writef32(out, o, readf32(out, o) + val * panL) + writef32(out, o + 4, readf32(out, o + 4) + val * panR) o += 8 pos += pitchRatio if pos >= loopEndD and isLooping then diff --git a/src/Formats/music/midi/Smf.luau b/src/Formats/music/midi/Smf.luau index 4c0ec1f..ed69595 100644 --- a/src/Formats/music/midi/Smf.luau +++ b/src/Formats/music/midi/Smf.luau @@ -25,7 +25,7 @@ export type WriteOptions = { } local function bytesOf(b: buffer, p: number, n: number): { number } - local t = table.create(n) + local t: { number } = table.create(n) for i = 0, n - 1 do t[i + 1] = readu8(b, p + i) end diff --git a/tests/music/sf2.luau b/tests/music/sf2.luau new file mode 100644 index 0000000..057b30e --- /dev/null +++ b/tests/music/sf2.luau @@ -0,0 +1,338 @@ +-- music/sf2 + codecs/SoundFont tests: a self-made SF2 parsed (INFO, presets, sample headers, instruments, generator +-- merging with preset / instrument global zones, 16-bit and sm24 samples), a test song rendered through it compared +-- with FluidSynth's render (loudness envelope and per-segment band spectra by correlation, pitch peaks), bad files, +-- the built-in fallback waveform set, and the fuzz no-throw pass. Fixtures: tools/fixtures/sf2.py. +local T = require("@tests/T") +local Sf2 = require("@formats/music/sf2") +local Midi = require("@formats/music/midi") +local SoundFont = require("@formats/codecs/SoundFont") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/sf2_cases") + +local t = T.suite("sf2") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +-- the contract +t:eq(Sf2.name, "sf2", "name") +t:eq(Sf2.category, "music", "category") +t:check(Sf2.caps.decode and not Sf2.caps.encode, "caps") +t:eq(Sf2.sniff(reader(Fx.sf2)), 1, "sniff") +t:eq(Sf2.sniff(reader("RIFF\0\0\0\0WAVE")), 0, "sniff WAVE") + +-- parse +local sf, err = Sf2.decode(reader(Fx.sf2)) +t:check(sf, "decode: " .. tostring(err)) +local E = Fx.expect +t:eq(sf.kind, "soundfont", "kind") +t:eq(sf.info.name, E.info.name, "INAM") +t:eq(sf.info.engine, E.info.engine, "isng") +t:eq(sf.meta.source.version, E.info.version, "ifil") +t:eq(#sf.presets, #E.presets, "preset count") +for i, p in E.presets do + t:eq(sf.presets[i].name, p.name, "preset " .. i .. " name") + t:eq(sf.presets[i].bank, p.bank, "preset " .. i .. " bank") + t:eq(sf.presets[i].preset, p.preset, "preset " .. i .. " number") +end +t:eq(#sf.sampleHeaders, #E.samples, "sample headers") +for i, s in E.samples do + for k, v in s do + t:eq(sf.sampleHeaders[i][k], v, "sample " .. i .. " " .. k) + end +end +for i, n in E.instruments do + t:eq(sf.instruments[i].name, n, "instrument " .. i) +end +local function preset(name: string): any + for _, p in sf.presets do + if p.name == name then + return p + end + end + return nil +end +do + local sine, saw, drums = preset("Sine"), preset("Saw"), preset("Drums") + t:eq(#sine.regions, 1, "Sine: the preset global zone is not a region") + t:check(math.abs(sine.regions[1].attenuation - 30 * 0.04) < 1e-9, "Sine: the preset global zone's attenuation applies") + t:check(math.abs(sine.regions[1].aRelease - 0.2) < 0.001, "Sine: release in seconds") + t:check(math.abs(sine.regions[1].aSustain - 10 ^ (-6 / 20)) < 1e-6, "Sine: sustain 60 cB = -6 dB") + t:eq(sine.regions[1].loopMode, 1, "Sine: looped") + t:eq(sine.regions[1].keycenter, 69, "Sine: root key from the sample header") + t:eq(sine.regions[1].tune, -4, "Sine: pitch correction") + t:eq(#saw.regions, 1, "Saw: the instrument global zone is not a region") + t:check(math.abs(saw.regions[1].filterFc - math.floor(1200 * math.log(2500 / 8.176, 2) + 0.5)) <= 1, "Saw: the instrument global zone's filter applies") + t:eq(saw.regions[1].modEnvToFilterFc, 2400, "Saw: mod env to filter") + t:eq(#drums.regions, 4, "Drums: four key zones") + local groups = 0 + for _, r in drums.regions do + t:check(math.abs(r.aRelease - 0.05) < 0.001, "Drums: release from the instrument global zone") + if r.group == 1 then + groups += 1 + end + end + t:eq(groups, 2, "Drums: two hats in exclusive class 1") + t:eq(drums.regions[1].lokey, 35, "Drums: key range lo") + t:eq(drums.regions[1].hikey, 36, "Drums: key range hi") +end +-- samples: 16-bit, and 24-bit with sm24 +do + local sf24 = Sf2.decode(reader(Fx.sf2_24)) + t:check(sf24 and sf24.meta.source.sm24, "sm24 read") + t:eq(sf.meta.source.sm24, false, "no sm24") + for _, v in E.values do + local i, hi, lo = v[1], v[2], v[3] + local a = buffer.readf32(sf.samples, i * 4) + local b = buffer.readf32(sf24.samples, i * 4) + t:check(math.abs(a - hi / 32767) < 1e-6, "16-bit sample " .. i) + t:check(math.abs(b - (hi * 256 + lo) / 8388607) < 1e-6, "24-bit sample " .. i) + end + t:eq(buffer.len(sf.samples), (sf.sampleCount + 1) * 4, "samples: one pad sample") +end + +-- ------------------------------------------------------------------------------------------------ vs FluidSynth +local F = Fx.fluid +local song = Midi.decode(reader(Fx.song)) +t:check(song, "song decodes") +local dec = assert(Midi.render(song, { soundfont = sf, tail = 2 })) +local frames = math.min(dec.frames, F.frames) +local mono = table.create(frames, 0) +do + local got = 0 + while got < frames do + local b, n = dec:read(math.min(8192, frames - got)) + if n == 0 then + break + end + for i = 0, n - 1 do + mono[got + i + 1] = (buffer.readf32(b, i * 8) + buffer.readf32(b, i * 8 + 4)) * 0.5 + end + got += n + end + t:eq(got, frames, "rendered the compared length") +end + +local function pearson(a: { number }, b: { number }): number + local n = math.min(#a, #b) + local ma, mb = 0, 0 + for i = 1, n do + ma += a[i] + mb += b[i] + end + ma /= n + mb /= n + local sab, saa, sbb = 0, 0, 0 + for i = 1, n do + local x, y = a[i] - ma, b[i] - mb + sab += x * y + saa += x * x + sbb += y * y + end + return sab / math.sqrt(saa * sbb + 1e-30) +end + +-- in-place radix-2 FFT of re / im (1-based arrays of length n, a power of two) +local function fft(re: { number }, im: { number }, n: number) + local j = 0 + for i = 0, n - 2 do + if i < j then + re[i + 1], re[j + 1] = re[j + 1], re[i + 1] + im[i + 1], im[j + 1] = im[j + 1], im[i + 1] + end + local m = n // 2 + while m >= 1 and j >= m do + j -= m + m //= 2 + end + j += m + end + local len = 2 + while len <= n do + local ang = -2 * math.pi / len + local wr, wi = math.cos(ang), math.sin(ang) + for s = 0, n - 1, len do + local cr, ci = 1, 0 + for k = 0, len // 2 - 1 do + local a, b = s + k + 1, s + k + len // 2 + 1 + local xr = re[b] * cr - im[b] * ci + local xi = re[b] * ci + im[b] * cr + re[b], im[b] = re[a] - xr, im[a] - xi + re[a], im[a] = re[a] + xr, im[a] + xi + cr, ci = cr * wr - ci * wi, cr * wi + ci * wr + end + end + len *= 2 + end +end + +local function power(start: number, n: number): { number } + local re, im = table.create(n, 0), table.create(n, 0) + for i = 0, n - 1 do + re[i + 1] = (mono[start + i + 1] or 0) * (0.5 - 0.5 * math.cos(2 * math.pi * i / n)) + end + fft(re, im, n) + local p = table.create(n // 2 + 1, 0) + for k = 0, n // 2 do + p[k + 1] = re[k + 1] ^ 2 + im[k + 1] ^ 2 + end + return p +end + +local rate = F.rate +-- the loudness envelope (50 ms RMS) +local env = {} +for i = 0, frames - 2205, 2205 do + local s = 0 + for k = 1, 2205 do + local v = mono[i + k] + s += v * v + end + table.insert(env, math.sqrt(s / 2205)) +end +local envCorr = pearson(env, F.env) +local ENV_MIN = 0.95 +t:check(envCorr > ENV_MIN, string.format("loudness envelope correlation %.3f > %.2f", envCorr, ENV_MIN)) +t:note("loudness envelope vs FluidSynth: r = %.3f (%d windows)", envCorr, #env) + +-- per-segment band spectra +local BAND_MIN = 0.93 +local worstBand = 1 +for si, seg in F.segments do + local acc = table.create(24, 0) + local count = 0 + for s = math.floor(seg[1] * rate), math.floor(seg[2] * rate) - 2048, 1024 do + local p = power(s, 2048) + for k = 0, 1024 do + local f = k * rate / 2048 + for b = 1, 24 do + if f >= F.edges[b] and f < F.edges[b + 1] then + acc[b] += p[k + 1] + break + end + end + end + count += 1 + end + local db = table.create(24, 0) + for b = 1, 24 do + db[b] = 10 * math.log10(acc[b] / math.max(count, 1) + 1e-12) + end + local r = pearson(db, F.bands[si]) + worstBand = math.min(worstBand, r) + t:check(r > BAND_MIN, string.format("segment %d band spectrum correlation %.3f > %.2f", si, r, BAND_MIN)) + t:note("segment %d (%g-%g s) band spectrum vs FluidSynth: r = %.3f", si, seg[1], seg[2], r) +end + +-- pitch peaks (vibrato square, a note bent an octave with an RPN 0 range of 12, the saw melody's first note) +for wi, w in F.windows do + local acc = table.create(4097, 0) + for s = math.floor(w[1] * rate), math.floor(w[2] * rate) - 8192, 2048 do + local p = power(s, 8192) + for k = 1, 4097 do + acc[k] += p[k] + end + end + local best, bk = -1, 2 + for k = 2, 4096 do + if acc[k] > best then + best, bk = acc[k], k + end + end + local y0, y1, y2 = math.log(acc[bk - 1] + 1e-30), math.log(acc[bk] + 1e-30), math.log(acc[bk + 1] + 1e-30) + local hz = ((bk - 1) + 0.5 * (y0 - y2) / (y0 - 2 * y1 + y2)) * rate / 8192 + local ratio = hz / F.peaks[wi] + t:check(math.abs(ratio - 1) < 0.015, string.format("window %d peak %.1f Hz vs FluidSynth %.1f Hz", wi, hz, F.peaks[wi])) + t:note("window %g-%g s: peak %.1f Hz (FluidSynth %.1f Hz)", w[1], w[2], hz, F.peaks[wi]) +end + +-- ------------------------------------------------------------------------------------------------ bad files +local function bad(data: string, code: string, label: string) + local ok, v, e = pcall(Sf2.decode, reader(data)) + t:check(ok, label .. ": threw " .. tostring(v)) + t:check(v == nil and Err.is(e) and e.code == code, label .. ": " .. tostring(e)) +end +bad("RIFX\0\0\0\0sfbk", Err.CORRUPT, "not RIFF") +bad("RIFF\4\0\0\0WAVE", Err.CORRUPT, "not sfbk") +bad("RIFF\4\0\0\0sfbk", Err.CORRUPT, "no chunks") +bad(string.sub(Fx.sf2, 1, 40), Err.CORRUPT, "truncated in INFO") +local lim, lerr = Sf2.decode(reader(Fx.sf2), { maxSamples = 100 }) +t:check(lim == nil and lerr.code == Err.LIMIT, "maxSamples: LIMIT") +local lim2, lerr2 = Sf2.decode(reader(Fx.sf2), { maxRegions = 3 }) +t:check(lim2 == nil and lerr2.code == Err.LIMIT, "maxRegions: LIMIT") +local p, perr = SoundFont.parse(42 :: any) +t:check(p == nil and perr.code == Err.ARG, "parse: bad argument") + +-- ------------------------------------------------------------------------------------------------ fallback +do + local fb = SoundFont.fallback() + t:eq(#fb.presets, 129, "fallback: 128 programs + a drum kit") + local s = SoundFont.synth(nil, 22050) + local Synth = SoundFont.Synth + local out = buffer.create(2205 * 8) + for program = 0, 127, 8 do + Synth.reset(s) + Synth.midi(s, 0xC0, program, 0) + Synth.midi(s, 0x90, 60, 100) + buffer.fill(out, 0, 0) + Synth.render(s, out, 0, 2205) + local e = 0 + for i = 0, 2205 * 2 - 1 do + local v = buffer.readf32(out, i * 4) + t:check(v == v and math.abs(v) < 4, "fallback: finite samples") + e += v * v + end + t:check(e > 0.01, "fallback program " .. program .. " sounds") + end + for _, key in { 35, 36, 38, 42, 46, 49, 51, 60 } do + Synth.reset(s) + Synth.midi(s, 0x99, key, 120) + buffer.fill(out, 0, 0) + Synth.render(s, out, 0, 2205) + local e = 0 + for i = 0, 2205 * 2 - 1 do + e += buffer.readf32(out, i * 4) ^ 2 + end + t:check(e > 0.01, "fallback drum " .. key .. " sounds") + end + -- exclusive class: a closed hat cuts the open hat + Synth.reset(s) + Synth.midi(s, 0x99, 46, 120) + t:eq(Synth.active(s), 1, "open hat") + Synth.midi(s, 0x99, 42, 120) + Synth.render(s, out, 0, 2205) + t:eq(Synth.active(s), 1, "closed hat ends the open hat (exclusive class)") + -- render range clipping: never writes past the buffer + Synth.render(s, out, 2200, 100000) + Synth.render(s, out, -5, 10) + t:check(true, "out-of-range render requests are clipped") +end + +-- the fuzz no-throw pass (parse, then a few notes through whatever parsed) +t:fuzz("decode", function(b: buffer) + local f = Sf2.decode(Bytes.reader(b)) + if f then + local s = SoundFont.synth(f, 22050) + for ch = 0, 15 do + SoundFont.Synth.midi(s, 0xC0 + ch, ch * 8, 0) + SoundFont.Synth.midi(s, 0x90 + ch, 30 + ch * 5, 100) + end + local out = buffer.create(512 * 8) + SoundFont.Synth.render(s, out, 0, 512) + end +end, { Fx.sf2 }, { mutations = 60, garbage = 100 }) +-- mutations inside the hydra (the last ~1 KB) exercise the zone / index clamping +t:fuzz("hydra", function(b: buffer) + local f = Sf2.decode(Bytes.reader(b)) + if f then + local s = SoundFont.synth(f, 22050) + SoundFont.Synth.midi(s, 0x90, 60, 100) + SoundFont.Synth.midi(s, 0x99, 36, 100) + local out = buffer.create(256 * 8) + SoundFont.Synth.render(s, out, 0, 256) + end +end, { Fx.sf2 }, { mutations = 200, garbage = 0, keepHeader = #Fx.sf2 - 1200 }) + +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 9f6aef7..a353be8 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -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 diff --git a/tools/bench.sh b/tools/bench.sh index c5dea4a..f7164e0 100644 --- a/tools/bench.sh +++ b/tools/bench.sh @@ -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 diff --git a/tools/fixtures/_sf2_features.py b/tools/fixtures/_sf2_features.py new file mode 100644 index 0000000..09f39fb --- /dev/null +++ b/tools/fixtures/_sf2_features.py @@ -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="= 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) diff --git a/tools/fixtures/sf2.py b/tools/fixtures/sf2.py new file mode 100644 index 0000000..638d874 --- /dev/null +++ b/tools/fixtures/sf2.py @@ -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("> 8, x & 255 + pcm += struct.pack(" 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(">= 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})