-- music/sf2 + codecs/audio/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/audio/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()