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
@@ -0,0 +1,272 @@
|
||||
-- music/midi tests: SMF formats 0 / 1 / 2 + SMPTE + RMID parsed exactly as python mido parses them, mido's own files
|
||||
-- re-encoded byte for byte, round trips without running status, the tempo map against mido's message times and
|
||||
-- lengths, meta summaries, crafted bad files, truncation (lenient / strict), the fallback-synth render (duration,
|
||||
-- level, seek), and the fuzz no-throw pass (decode, and decode + a short render). Fixtures: tools/fixtures/midi.py.
|
||||
local T = require("@tests/T")
|
||||
local Midi = require("@formats/music/midi")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Cases = require("@tests/gen/midi_cases")
|
||||
local Bad = require("@tests/gen/midi_bad")
|
||||
local Trunc = require("@tests/gen/midi_trunc")
|
||||
|
||||
local t = T.suite("midi")
|
||||
|
||||
local function decode(data: any, opts: any?): (any, any)
|
||||
local b = if type(data) == "string" then buffer.fromstring(data) else data
|
||||
return Midi.decode(Bytes.reader(b), opts)
|
||||
end
|
||||
|
||||
-- the contract
|
||||
t:eq(Midi.name, "midi", "name")
|
||||
t:eq(Midi.category, "music", "category")
|
||||
t:check(table.find(Midi.extensions, "mid") ~= nil, "extensions")
|
||||
t:check(Midi.caps.decode and Midi.caps.encode, "caps")
|
||||
t:eq(Midi.sniff(Bytes.reader(buffer.fromstring("MThd\0\0\0\6"))), 1, "sniff MThd")
|
||||
t:eq(Midi.sniff(Bytes.reader(buffer.fromstring("RIFF\0\0\0\0RMID"))), 1, "sniff RMID")
|
||||
t:eq(Midi.sniff(Bytes.reader(buffer.fromstring("RIFF\0\0\0\0WAVE"))), 0, "sniff WAVE")
|
||||
|
||||
local function sameEvents(got: { any }, want: { any }, label: string)
|
||||
t:eq(#got, #want, label .. ": event count")
|
||||
for i, w in want do
|
||||
local g = got[i]
|
||||
local l = label .. " event " .. i
|
||||
t:eq(g.tick, w[1], l .. " tick")
|
||||
t:eq(g.type, w[2], l .. " type")
|
||||
t:eq(g.channel or -1, w[3], l .. " channel")
|
||||
t:eq(if g.type == "meta" then g.meta else -1, w[5], l .. " meta type")
|
||||
local d = g.data or {}
|
||||
t:eq(#d, #w[4], l .. " data length")
|
||||
for k, v in w[4] do
|
||||
if d[k] ~= v then
|
||||
t:eq(d[k], v, l .. " data byte " .. k)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function trackEvents(m: any): { { any } }
|
||||
local out = {}
|
||||
for ti, tr in m.tracks do
|
||||
local evs = {}
|
||||
for _, ev in tr.events do
|
||||
table.insert(evs, { ev.tick, ev.type, ev.channel or -1, ev.data or {}, if ev.type == "meta" then ev.meta else -1 })
|
||||
end
|
||||
out[ti] = evs
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local byName = {}
|
||||
for _, c in Cases do
|
||||
byName[c.name] = c
|
||||
local m, err = decode(c.data)
|
||||
t:check(m, c.name .. ": " .. tostring(err))
|
||||
t:eq(m.kind, "midi", c.name .. ": kind")
|
||||
t:eq(m.format, c.type, c.name .. ": format")
|
||||
t:eq(m.division, c.division, c.name .. ": division")
|
||||
t:eq(#m.tracks, #c.tracks, c.name .. ": tracks")
|
||||
for ti, want in c.tracks do
|
||||
sameEvents(m.tracks[ti].events, want, c.name .. " track " .. ti)
|
||||
end
|
||||
-- mido's own bytes come back exactly (running status as mido writes it)
|
||||
if c.exact then
|
||||
local out, eerr = Midi.encode(m)
|
||||
t:check(out, c.name .. ": encode " .. tostring(eerr))
|
||||
t:eq(buffer.tostring(out :: buffer) == c.data, true, c.name .. ": re-encoded bytes equal mido's")
|
||||
end
|
||||
-- without running status: longer (or equal), and the same events
|
||||
local plain = Midi.encode(m, { runningStatus = false }) :: buffer
|
||||
local withRs = Midi.encode(m) :: buffer
|
||||
t:check(buffer.len(plain) >= buffer.len(withRs), c.name .. ": running status saves bytes")
|
||||
local back = decode(plain)
|
||||
t:check(back, c.name .. ": re-decode")
|
||||
for ti, want in trackEvents(m) do
|
||||
sameEvents(back.tracks[ti].events, want, c.name .. " round trip track " .. ti)
|
||||
end
|
||||
-- tempo map: every event's time against mido's merged message times
|
||||
if c.times then
|
||||
local secs = {}
|
||||
for _, tr in m.tracks do
|
||||
for _, ev in tr.events do
|
||||
if not (ev.type == "meta" and ev.meta == 0x2F) then -- mido merges the end-of-track events into one
|
||||
table.insert(secs, Midi.tickToSeconds(m, ev.tick))
|
||||
end
|
||||
end
|
||||
end
|
||||
table.sort(secs)
|
||||
t:eq(#secs, #c.times - 1, c.name .. ": event count vs mido")
|
||||
local worst = 0
|
||||
for i, s in secs do
|
||||
worst = math.max(worst, math.abs(s - c.times[i]))
|
||||
end
|
||||
t:check(worst < 1e-6, c.name .. ": event times match mido (worst " .. worst .. " s)")
|
||||
t:check(math.abs(Midi.length(m) - c.length) < 1e-6, c.name .. ": length " .. Midi.length(m) .. " vs mido " .. c.length)
|
||||
t:check(math.abs(m.meta.length - c.length) < 1e-6, c.name .. ": meta.length")
|
||||
end
|
||||
end
|
||||
t:note("%d files parse as mido parses them; mido's files re-encode byte for byte", #Cases)
|
||||
|
||||
-- meta summaries
|
||||
do
|
||||
local m = decode(byName.format0.data)
|
||||
t:eq(m.tracks[1].name, "format zero", "track name")
|
||||
t:eq(#m.meta.tempos, 3, "tempo changes")
|
||||
t:eq(m.meta.tempos[1].usPerQuarter, 500000, "first tempo")
|
||||
t:eq(m.meta.tempos[1].bpm, 120, "bpm")
|
||||
t:eq(#m.meta.timeSignatures, 2, "time signatures")
|
||||
t:eq(m.meta.timeSignatures[1].numerator, 3, "3/4 numerator")
|
||||
t:eq(m.meta.timeSignatures[1].denominator, 4, "3/4 denominator")
|
||||
t:eq(m.meta.timeSignatures[2].denominator, 8, "6/8 denominator")
|
||||
t:eq(m.meta.keySignatures[1].sharps, -3, "Eb: 3 flats")
|
||||
t:eq(m.meta.keySignatures[1].minor, false, "Eb major")
|
||||
local s = decode(byName.smpte.data)
|
||||
t:eq(s.meta.smpte.fps, 25, "smpte fps")
|
||||
t:eq(s.meta.smpte.ticksPerFrame, 40, "smpte ticks per frame")
|
||||
t:check(math.abs(Midi.tickToSeconds(s, 1000) - 1) < 1e-12, "smpte: 1000 ticks at 25 x 40 = 1 s")
|
||||
t:eq(decode(byName.rmid.data).meta.rmid, true, "rmid flag")
|
||||
-- format 2: per-track tempo maps, the tracks one after another
|
||||
local f2 = decode(byName.format2.data)
|
||||
local total = 0
|
||||
for ti, tr in f2.tracks do
|
||||
local last = tr.events[#tr.events].tick
|
||||
total += Midi.tickToSeconds(f2, last, ti)
|
||||
end
|
||||
t:check(math.abs(Midi.length(f2) - total) < 1e-9, "format 2 length = the tracks in sequence")
|
||||
end
|
||||
|
||||
-- a value built by hand: unsorted events are written in tick order, end of track added, bad values refused
|
||||
do
|
||||
local m = Types.Midi.new(96)
|
||||
m.format = 0
|
||||
m.tracks[1] = { events = {
|
||||
{ tick = 50, type = "noteOff", channel = 2, data = { 60, 0 } },
|
||||
{ tick = 0, type = "noteOn", channel = 2, data = { 60, 100 } },
|
||||
{ tick = 50, type = "meta", meta = 0x2F, data = {} },
|
||||
{ tick = 20, type = "controller", channel = 2, data = { 64, 127 } },
|
||||
} }
|
||||
local b = Midi.encode(m) :: buffer
|
||||
local back = decode(b)
|
||||
sameEvents(back.tracks[1].events, {
|
||||
{ 0, "noteOn", 2, { 60, 100 }, -1 }, { 20, "controller", 2, { 64, 127 }, -1 }, { 50, "noteOff", 2, { 60, 0 }, -1 },
|
||||
{ 50, "meta", -1, {}, 0x2F },
|
||||
}, "sorted on write")
|
||||
local function refuses(mut: (any) -> (), label: string)
|
||||
local x = Types.Midi.new(96)
|
||||
x.tracks[1] = { events = { { tick = 0, type = "noteOn", channel = 0, data = { 60, 100 } } } }
|
||||
mut(x)
|
||||
local out, err = Midi.encode(x)
|
||||
t:check(out == nil and Err.is(err) and err.code == Err.ARG, "encode refuses " .. label)
|
||||
end
|
||||
refuses(function(x) x.tracks[1].events[1].channel = 16 end, "channel 16")
|
||||
refuses(function(x) x.tracks[1].events[1].data = { 60, 128 } end, "data byte 128")
|
||||
refuses(function(x) x.tracks[1].events[1].tick = -1 end, "negative tick")
|
||||
refuses(function(x) x.tracks[1].events[1].type = "wobble" end, "unknown type")
|
||||
refuses(function(x) x.division = 0 end, "zero division")
|
||||
refuses(function(x) x.format = 0; x.tracks[2] = { events = {} } end, "format 0 with two tracks")
|
||||
local nope, nerr = Midi.encode(nil :: any)
|
||||
t:check(nope == nil and nerr.code == Err.ARG, "encode refuses nil")
|
||||
end
|
||||
|
||||
-- crafted bad files
|
||||
for _, c in Bad do
|
||||
local ok, m, err = pcall(decode, c.data)
|
||||
t:check(ok, c.name .. ": threw " .. tostring(m))
|
||||
t:check(m == nil and Err.is(err), c.name .. ": decoded")
|
||||
t:eq(err.code, c.code, c.name .. ": error code (" .. tostring(err) .. ")")
|
||||
end
|
||||
|
||||
-- truncation: lenient keeps what it read, strict fails
|
||||
do
|
||||
local m = decode(Trunc.data)
|
||||
t:check(m and m.meta.truncated, "truncated file decodes leniently, flagged")
|
||||
local n = 0
|
||||
for _, tr in m.tracks do
|
||||
n += #tr.events
|
||||
end
|
||||
t:check(n > 50, "truncated file keeps its events (" .. n .. ")")
|
||||
local s, err = decode(Trunc.data, { strict = true })
|
||||
t:check(s == nil and err.code == Err.TRUNCATED, "strict: TRUNCATED")
|
||||
t:eq(decode(byName.format1.data, { strict = true }).meta.truncated, false, "strict: a whole file passes")
|
||||
local l, lerr = decode(byName.random.data, { maxEvents = 100 })
|
||||
t:check(l == nil and lerr.code == Err.LIMIT, "maxEvents: LIMIT")
|
||||
end
|
||||
|
||||
-- render through the built-in waveform set
|
||||
do
|
||||
local song = decode(byName.song.data)
|
||||
local dec = song:render({ tail = 0.5 })
|
||||
local want = math.ceil((byName.song.length + 0.5) * 44100)
|
||||
t:eq(dec.frames, want, "render: frames = (length + tail) * rate")
|
||||
t:eq(dec.channels, 2, "render: stereo")
|
||||
t:eq(dec.sampleRate, 44100, "render: rate")
|
||||
local total, sumsq, peak = 0, 0, 0
|
||||
local out = buffer.create(4096 * 8)
|
||||
while true do
|
||||
local b, n = dec:read(4096, out)
|
||||
if n == 0 then
|
||||
break
|
||||
end
|
||||
for i = 0, n * 2 - 1 do
|
||||
local v = buffer.readf32(b, i * 4)
|
||||
sumsq += v * v
|
||||
peak = math.max(peak, math.abs(v))
|
||||
end
|
||||
total += n
|
||||
end
|
||||
t:eq(total, want, "render: reads every frame")
|
||||
local rms = math.sqrt(sumsq / (total * 2))
|
||||
t:check(rms > 0.01 and peak < 4 and peak == peak, string.format("render: audible and sane (rms %.3f, peak %.3f)", rms, peak))
|
||||
t:note("fallback render: %.2f s, rms %.3f, peak %.3f", total / 44100, rms, peak)
|
||||
-- seek: the same samples as playing through
|
||||
local a = song:render({ tail = 0.5 })
|
||||
a:seek(1.5)
|
||||
t:check(math.abs(a:position() - 1.5) < 1e-4, "seek position")
|
||||
local x = buffer.create(1024 * 8)
|
||||
a:read(1024, x)
|
||||
local c = song:render({ tail = 0.5 })
|
||||
c:read(66150)
|
||||
local y = c:read(1024)
|
||||
local same = true
|
||||
for i = 0, 2047 do
|
||||
if buffer.readf32(x, i * 4) ~= buffer.readf32(y, i * 4) then
|
||||
same = false
|
||||
break
|
||||
end
|
||||
end
|
||||
t:check(same, "seek renders the same samples as reading through")
|
||||
a:seek(0.25) -- backwards
|
||||
t:check(math.abs(a:position() - 0.25) < 1e-4, "seek backwards")
|
||||
-- open = decode + render
|
||||
local o = Midi.open(Bytes.reader(buffer.fromstring(byName.song.data)), { sampleRate = 22050, tail = 0 })
|
||||
t:check(o and o.sampleRate == 22050, "open: a Decoder at the asked rate")
|
||||
local bad, berr = Midi.render(song, { sampleRate = 5 })
|
||||
t:check(bad == nil and berr.code == Err.ARG, "render: bad sampleRate")
|
||||
local bs, bserr = Midi.render(song, { soundfont = "not a soundfont" })
|
||||
t:check(bs == nil and Err.is(bserr), "render: bad soundfont bytes")
|
||||
end
|
||||
|
||||
-- the fuzz no-throw pass
|
||||
local samples = {}
|
||||
for _, c in Cases do
|
||||
if #c.data < 20000 then
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return decode(b)
|
||||
end, samples, { mutations = 40 })
|
||||
t:fuzz("decode + render", function(b: buffer)
|
||||
local m = decode(b)
|
||||
if m then
|
||||
local dec = Midi.render(m, { tail = 0.1 })
|
||||
if dec then
|
||||
dec:read(2048)
|
||||
dec:read(2048)
|
||||
end
|
||||
Midi.encode(m)
|
||||
end
|
||||
end, samples, { mutations = 20, garbage = 50 })
|
||||
|
||||
t:done()
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user