merge ws/music
This commit is contained in:
commit
c56d2ac71d
40 files changed
+9933
No files matched your search
@@ -0,0 +1,209 @@
|
||||
-- tests/music/_similar: shared helper of the tracker tests (not a test itself): renders a module through a Decoder and
|
||||
-- compares it with a reference render's features (tools/fixtures/_tracker.py: per 2048-frame block the RMS of left,
|
||||
-- right and mid, and 40 log-spaced band magnitudes of mid from a Hann-windowed FFT). Same definitions on both sides.
|
||||
local S = {}
|
||||
|
||||
local SR, HOP, BANDS = 44100, 2048, 40
|
||||
local F_LO, F_HI = 150, 16000
|
||||
S.SR = SR
|
||||
|
||||
local WINDOW = table.create(HOP, 0)
|
||||
for i = 0, HOP - 1 do
|
||||
WINDOW[i + 1] = 0.5 - 0.5 * math.cos(2 * math.pi * i / HOP)
|
||||
end
|
||||
local BAND_OF = table.create(HOP // 2, -1)
|
||||
for b = 1, HOP // 2 - 1 do
|
||||
local f = b * SR / HOP
|
||||
if f >= F_LO and f < F_HI then
|
||||
BAND_OF[b + 1] = math.min(BANDS - 1, math.floor(math.log(f / F_LO) / math.log(F_HI / F_LO) * BANDS))
|
||||
end
|
||||
end
|
||||
|
||||
local function fft(re: { number }, im: { number }, n: number)
|
||||
local j = 0
|
||||
for i = 1, n - 1 do
|
||||
local bit = n // 2
|
||||
while bit > 0 and j >= bit and (j // bit) % 2 == 1 do
|
||||
j -= bit
|
||||
bit //= 2
|
||||
end
|
||||
j += bit
|
||||
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
|
||||
end
|
||||
local size = 2
|
||||
while size <= n do
|
||||
local ang = -2 * math.pi / size
|
||||
local wr, wi = math.cos(ang), math.sin(ang)
|
||||
local half = size // 2
|
||||
for start = 0, n - 1, size do
|
||||
local cr, ci = 1, 0
|
||||
for k = 0, half - 1 do
|
||||
local a, b = start + k + 1, start + k + half + 1
|
||||
local tr = re[b] * cr - im[b] * ci
|
||||
local ti = re[b] * ci + im[b] * cr
|
||||
re[b], im[b] = re[a] - tr, im[a] - ti
|
||||
re[a], im[a] = re[a] + tr, im[a] + ti
|
||||
cr, ci = cr * wr - ci * wi, cr * wi + ci * wr
|
||||
end
|
||||
end
|
||||
size *= 2
|
||||
end
|
||||
end
|
||||
|
||||
-- features(samples (interleaved stereo f32 buffer), frames) -> { frames, rmsL, rmsR, rmsM, bands }
|
||||
function S.features(buf: buffer, frames: number): any
|
||||
local n = frames // HOP
|
||||
local out = { frames = n, rmsL = {}, rmsR = {}, rmsM = {}, bands = {} }
|
||||
local re, im = table.create(HOP, 0), table.create(HOP, 0)
|
||||
for k = 0, n - 1 do
|
||||
local sl, sr, sm = 0, 0, 0
|
||||
for i = 0, HOP - 1 do
|
||||
local o = ((k * HOP + i) * 2) * 4
|
||||
local l, r = buffer.readf32(buf, o), buffer.readf32(buf, o + 4)
|
||||
local m = (l + r) / 2
|
||||
sl += l * l
|
||||
sr += r * r
|
||||
sm += m * m
|
||||
re[i + 1] = m * WINDOW[i + 1]
|
||||
im[i + 1] = 0
|
||||
end
|
||||
table.insert(out.rmsL, math.sqrt(sl / HOP))
|
||||
table.insert(out.rmsR, math.sqrt(sr / HOP))
|
||||
table.insert(out.rmsM, math.sqrt(sm / HOP))
|
||||
fft(re, im, HOP)
|
||||
local e = table.create(BANDS, 0)
|
||||
for b = 1, HOP // 2 - 1 do
|
||||
local j = BAND_OF[b + 1]
|
||||
if j >= 0 then
|
||||
e[j + 1] += re[b + 1] * re[b + 1] + im[b + 1] * im[b + 1]
|
||||
end
|
||||
end
|
||||
for j = 1, BANDS do
|
||||
table.insert(out.bands, math.sqrt(e[j]))
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- renderAll(decoder, maxFrames) -> interleaved buffer, frames
|
||||
function S.renderAll(dec: any, maxFrames: number): (buffer, number)
|
||||
local total = math.min(dec.frames, maxFrames)
|
||||
local out = buffer.create(math.max(1, total) * 8)
|
||||
local pos = 0
|
||||
local chunk = buffer.create(4096 * 8)
|
||||
while pos < total do
|
||||
local _, n = dec:read(math.min(4096, total - pos), chunk)
|
||||
if n == 0 then
|
||||
break
|
||||
end
|
||||
buffer.copy(out, pos * 8, chunk, 0, n * 8)
|
||||
pos += n
|
||||
end
|
||||
return out, pos
|
||||
end
|
||||
|
||||
local function db(x: number): number
|
||||
return 20 * math.log10(x + 1e-6)
|
||||
end
|
||||
|
||||
-- compare(ours, ref) -> { gainDb, envCorr, spectral, balance } over the common frames:
|
||||
-- gainDb total mid energy ratio in dB (ours / ref)
|
||||
-- envCorr Pearson correlation of the per-block mid loudness in dB (blocks above -60 dB in either)
|
||||
-- envErr mean absolute difference of the per-block mid loudness in dB, after removing gainDb (same blocks)
|
||||
-- spectral mean cosine similarity of the band magnitude vectors (blocks where ref is above -50 dB)
|
||||
-- balance mean absolute difference of the per-block left / right balance (L - R) / (L + R) (loud blocks)
|
||||
function S.compare(a: any, b: any): any
|
||||
local n = math.min(a.frames, b.frames)
|
||||
local ea, eb = 0, 0
|
||||
for k = 1, n do
|
||||
ea += a.rmsM[k] ^ 2
|
||||
eb += b.rmsM[k] ^ 2
|
||||
end
|
||||
local gainDb = 10 * math.log10((ea + 1e-12) / (eb + 1e-12))
|
||||
local xs, ys = {}, {}
|
||||
for k = 1, n do
|
||||
local x, y = db(a.rmsM[k]), db(b.rmsM[k])
|
||||
if x > -60 or y > -60 then
|
||||
table.insert(xs, x)
|
||||
table.insert(ys, y)
|
||||
end
|
||||
end
|
||||
local mx, my = 0, 0
|
||||
for i = 1, #xs do
|
||||
mx += xs[i]
|
||||
my += ys[i]
|
||||
end
|
||||
mx /= math.max(1, #xs)
|
||||
my /= math.max(1, #ys)
|
||||
local sxy, sxx, syy = 0, 0, 0
|
||||
for i = 1, #xs do
|
||||
sxy += (xs[i] - mx) * (ys[i] - my)
|
||||
sxx += (xs[i] - mx) ^ 2
|
||||
syy += (ys[i] - my) ^ 2
|
||||
end
|
||||
local envCorr = if sxx > 0 and syy > 0 then sxy / math.sqrt(sxx * syy) else 1
|
||||
-- the mean loudness difference per block once the overall gain is taken out (dB, each side clamped at -60)
|
||||
local envErr = 0
|
||||
for i = 1, #xs do
|
||||
envErr += math.abs(math.max(xs[i], -60) - math.max(ys[i], -60) - gainDb)
|
||||
end
|
||||
envErr /= math.max(1, #xs)
|
||||
local cs, cn = 0, 0
|
||||
local bal, bn = 0, 0
|
||||
for k = 1, n do
|
||||
if db(b.rmsM[k]) > -50 then
|
||||
local dot, na, nb = 0, 0, 0
|
||||
for j = 1, BANDS do
|
||||
local x, y = a.bands[(k - 1) * BANDS + j], b.bands[(k - 1) * BANDS + j]
|
||||
dot += x * y
|
||||
na += x * x
|
||||
nb += y * y
|
||||
end
|
||||
cs += if na > 0 and nb > 0 then dot / math.sqrt(na * nb) else 0
|
||||
cn += 1
|
||||
end
|
||||
local la, ra, lb, rb = a.rmsL[k], a.rmsR[k], b.rmsL[k], b.rmsR[k]
|
||||
if lb + rb > 0.01 then
|
||||
bal += math.abs((la - ra) / (la + ra + 1e-9) - (lb - rb) / (lb + rb))
|
||||
bn += 1
|
||||
end
|
||||
end
|
||||
return {
|
||||
gainDb = gainDb,
|
||||
envCorr = envCorr,
|
||||
envErr = envErr,
|
||||
spectral = if cn > 0 then cs / cn else 1,
|
||||
balance = if bn > 0 then bal / bn else 0,
|
||||
frames = n,
|
||||
}
|
||||
end
|
||||
|
||||
-- worst(ours, ref, count) -> the blocks with the lowest spectral similarity (for debugging): { {block, sim} }
|
||||
function S.worst(a: any, b: any, count: number): { { number } }
|
||||
local list = {}
|
||||
for k = 1, math.min(a.frames, b.frames) do
|
||||
if db(b.rmsM[k]) > -50 then
|
||||
local dot, na, nb = 0, 0, 0
|
||||
for j = 1, BANDS do
|
||||
local x, y = a.bands[(k - 1) * BANDS + j], b.bands[(k - 1) * BANDS + j]
|
||||
dot += x * y
|
||||
na += x * x
|
||||
nb += y * y
|
||||
end
|
||||
table.insert(list, { k, if na > 0 and nb > 0 then dot / math.sqrt(na * nb) else 0, db(a.rmsM[k]), db(b.rmsM[k]) })
|
||||
end
|
||||
end
|
||||
table.sort(list, function(x, y)
|
||||
return x[2] < y[2]
|
||||
end)
|
||||
local out = {}
|
||||
for i = 1, math.min(count, #list) do
|
||||
out[i] = list[i]
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
return S
|
||||
@@ -0,0 +1,84 @@
|
||||
-- music/it tests: generated Impulse Tracker modules (tools/fixtures/it.py) parsed, rendered through codecs/Tracker and
|
||||
-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the contract,
|
||||
-- and the fuzz no-throw pass.
|
||||
local T = require("@tests/T")
|
||||
local S = require("@tests/music/_similar")
|
||||
local It = require("@formats/music/it")
|
||||
local Tracker = require("@formats/codecs/Tracker")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/it_cases")
|
||||
|
||||
local t = T.suite("it")
|
||||
|
||||
t:eq(It.name, "it", "name")
|
||||
t:eq(It.category, "music", "category")
|
||||
t:check(It.caps.decode and not It.caps.encode, "caps")
|
||||
|
||||
local function load(data: string): any
|
||||
return It.decode(Bytes.reader(buffer.fromstring(data)))
|
||||
end
|
||||
|
||||
local THRESH = { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }
|
||||
|
||||
for _, c in Cases do
|
||||
local m, err = load(c.data)
|
||||
t:check(m, c.name .. ": " .. tostring(err))
|
||||
t:check(It.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff")
|
||||
local dec = m:render({ sampleRate = S.SR })
|
||||
t:check(dec, c.name .. ": render")
|
||||
t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration))
|
||||
local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR))
|
||||
local r = S.compare(S.features(buf, frames), c.ref)
|
||||
t:note("%-7s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envErr, r.spectral, r.balance, dec.duration)
|
||||
if r.spectral < THRESH.spectral or r.envErr > THRESH.envErr then
|
||||
for _, w in S.worst(S.features(buf, frames), c.ref, 6) do
|
||||
t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4])
|
||||
end
|
||||
end
|
||||
t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness")
|
||||
t:check(r.envErr < THRESH.envErr, c.name .. ": loudness envelope")
|
||||
t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum")
|
||||
t:check(r.balance < THRESH.balance, c.name .. ": stereo balance")
|
||||
end
|
||||
|
||||
-- compressed samples (IT 2.14 / 2.15, 8 and 16-bit, mono and stereo) decode to exactly the uncompressed data
|
||||
for _, c in Cases do
|
||||
if c.plain then
|
||||
local a, b = load(c.data), load(c.plain)
|
||||
local same = #a.samples == #b.samples
|
||||
for i, s in a.samples do
|
||||
local o = b.samples[i]
|
||||
same = same and s.length == o.length and s.channels == o.channels and buffer.tostring(s.data) == buffer.tostring(o.data)
|
||||
end
|
||||
t:check(same, c.name .. ": samples equal the uncompressed ones")
|
||||
end
|
||||
end
|
||||
|
||||
-- seek: the position after a seek and the output continuing
|
||||
do
|
||||
local m = load(Cases[1].data)
|
||||
local dec = m:render()
|
||||
dec:seek(2)
|
||||
t:check(math.abs(dec:position() - 2) < 0.001, "seek position")
|
||||
local _, n = dec:read(1000)
|
||||
t:eq(n, 1000, "read after seek")
|
||||
t:check(Tracker.duration(m) == dec.duration, "duration()")
|
||||
end
|
||||
|
||||
-- the fuzz pass: decode, and a short render of whatever decodes
|
||||
local samples = {}
|
||||
for _, c in Cases do
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local m = It.decode(Bytes.reader(b))
|
||||
if m then
|
||||
local dec = Tracker.render(m, { maxDuration = 0.5, sampleRate = 8000 })
|
||||
if dec then
|
||||
dec:read(4000)
|
||||
end
|
||||
end
|
||||
return m
|
||||
end, samples, { mutations = 30 })
|
||||
|
||||
t:done()
|
||||
@@ -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,127 @@
|
||||
-- music/mod tests: generated ProTracker modules (tools/fixtures/mod.py) parsed, rendered through codecs/Tracker and
|
||||
-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the MOD writer's
|
||||
-- round trip, the contract, and the fuzz no-throw pass.
|
||||
local T = require("@tests/T")
|
||||
local S = require("@tests/music/_similar")
|
||||
local Mod = require("@formats/music/mod")
|
||||
local Tracker = require("@formats/codecs/Tracker")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/mod_cases")
|
||||
|
||||
local t = T.suite("mod")
|
||||
|
||||
t:eq(Mod.name, "mod", "name")
|
||||
t:eq(Mod.category, "music", "category")
|
||||
t:check(Mod.caps.decode and Mod.caps.encode, "caps")
|
||||
|
||||
local function load(data: string): any
|
||||
return Mod.decode(Bytes.reader(buffer.fromstring(data)))
|
||||
end
|
||||
|
||||
local THRESH = { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }
|
||||
|
||||
for _, c in Cases do
|
||||
local m, err = load(c.data)
|
||||
t:check(m, c.name .. ": " .. tostring(err))
|
||||
t:check(Mod.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff")
|
||||
local dec = m:render({ sampleRate = S.SR })
|
||||
t:check(dec, c.name .. ": render")
|
||||
t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration))
|
||||
local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR))
|
||||
local r = S.compare(S.features(buf, frames), c.ref)
|
||||
t:note("%-7s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envErr, r.spectral, r.balance, dec.duration)
|
||||
if r.spectral < THRESH.spectral or r.envErr > THRESH.envErr then
|
||||
for _, w in S.worst(S.features(buf, frames), c.ref, 6) do
|
||||
t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4])
|
||||
end
|
||||
end
|
||||
t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness")
|
||||
t:check(r.envErr < THRESH.envErr, c.name .. ": loudness envelope")
|
||||
t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum")
|
||||
t:check(r.balance < THRESH.balance, c.name .. ": stereo balance")
|
||||
-- the writer: MOD -> MOD gives the same bytes back (the fixtures are canonical ProTracker files)
|
||||
local out, werr = Mod.encode(m)
|
||||
t:check(out, c.name .. ": encode " .. tostring(werr))
|
||||
local m2 = Mod.decode(Bytes.reader(out :: buffer))
|
||||
t:check(m2, c.name .. ": re-decode")
|
||||
t:eq(buffer.tostring(out :: buffer), c.data, c.name .. ": round trip bytes")
|
||||
end
|
||||
|
||||
-- MOD -> XM: the converted module plays as long, and sounds alike (XM has no channel panning and uses FT2's NTSC
|
||||
-- Amiga clock, so only the duration and the band spectrum are compared)
|
||||
local Xm = require("@formats/music/xm")
|
||||
for _, c in Cases do
|
||||
local m = load(c.data)
|
||||
local xb, xerr = Xm.encode(m)
|
||||
t:check(xb, c.name .. ": mod -> xm " .. tostring(xerr))
|
||||
local x = Xm.decode(Bytes.reader(xb :: buffer))
|
||||
t:check(x and x.format == "xm" and #x.instruments == #m.samples, c.name .. ": the xm decodes")
|
||||
local dec = x:render()
|
||||
t:check(math.abs(dec.duration - c.duration) < THRESH.duration, c.name .. ": xm duration")
|
||||
local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR))
|
||||
local r = S.compare(S.features(buf, frames), c.ref)
|
||||
t:check(r.spectral > 0.9, string.format("%s: xm spectrum %.3f", c.name, r.spectral))
|
||||
end
|
||||
|
||||
-- through the API: load sniffs the MOD, open gives a Decoder, save converts to XM, load(as audio) renders
|
||||
do
|
||||
local F = require("@formats")
|
||||
local m, err = F.load(Cases[1].data)
|
||||
t:check(m and m.kind == "music" and m.format == "mod", "F.load: " .. tostring(err))
|
||||
local dec = F.open(Cases[1].data)
|
||||
t:check(dec and dec.channels == 2 and dec.sampleRate == 44100, "F.open: a Decoder")
|
||||
local xb = F.save(m, nil, { format = "xm" })
|
||||
t:check(xb and F.load(xb).format == "xm", "F.save as xm")
|
||||
t:eq(F.saveString(m, { format = "mod" }), Cases[1].data, "F.saveString keeps the MOD bytes")
|
||||
end
|
||||
|
||||
-- seek: the position after a seek and the output continuing
|
||||
do
|
||||
local m = load(Cases[1].data)
|
||||
local dec = m:render()
|
||||
dec:seek(2)
|
||||
t:check(math.abs(dec:position() - 2) < 0.001, "seek position")
|
||||
local _, n = dec:read(1000)
|
||||
t:eq(n, 1000, "read after seek")
|
||||
t:check(Tracker.duration(m) == dec.duration, "duration()")
|
||||
-- the same samples as playing up to that point (after the short fade-in that follows a seek)
|
||||
local a, b = m:render(), m:render()
|
||||
a:seek(3.5)
|
||||
local at = math.floor(3.5 * S.SR)
|
||||
while at > 0 do
|
||||
local _, n = b:read(math.min(at, 8192))
|
||||
at -= n
|
||||
end
|
||||
local x, y = a:read(4096), b:read(4096)
|
||||
local worst = 0
|
||||
for i = 256, 4095 * 2 do
|
||||
worst = math.max(worst, math.abs(buffer.readf32(x, i * 4) - buffer.readf32(y, i * 4)))
|
||||
end
|
||||
t:check(worst < 1e-4, "seek then read matches reading through (" .. worst .. ")")
|
||||
-- loop = true keeps playing past the end (frames / duration still give one pass)
|
||||
local l = m:render({ loop = true, sampleRate = 8000 })
|
||||
local total = 0
|
||||
for _ = 1, 30 do
|
||||
local _, n = l:read(8000)
|
||||
total += n
|
||||
end
|
||||
t:check(total == 240000 and math.abs(l.duration - dec.duration) < 0.01, "loop plays past the end")
|
||||
end
|
||||
|
||||
-- the fuzz pass: decode, and a short render of whatever decodes
|
||||
local samples = {}
|
||||
for _, c in Cases do
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local m = Mod.decode(Bytes.reader(b))
|
||||
if m then
|
||||
local dec = Tracker.render(m, { maxDuration = 0.5, sampleRate = 8000 })
|
||||
if dec then
|
||||
dec:read(4000)
|
||||
end
|
||||
end
|
||||
return m
|
||||
end, samples, { mutations = 30 })
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,71 @@
|
||||
-- music/s3m tests: generated Scream Tracker 3 modules (tools/fixtures/s3m.py) parsed, rendered through codecs/Tracker and
|
||||
-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the contract,
|
||||
-- and the fuzz no-throw pass.
|
||||
local T = require("@tests/T")
|
||||
local S = require("@tests/music/_similar")
|
||||
local S3m = require("@formats/music/s3m")
|
||||
local Tracker = require("@formats/codecs/Tracker")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/s3m_cases")
|
||||
|
||||
local t = T.suite("s3m")
|
||||
|
||||
t:eq(S3m.name, "s3m", "name")
|
||||
t:eq(S3m.category, "music", "category")
|
||||
t:check(S3m.caps.decode and not S3m.caps.encode, "caps")
|
||||
|
||||
local function load(data: string): any
|
||||
return S3m.decode(Bytes.reader(buffer.fromstring(data)))
|
||||
end
|
||||
|
||||
local THRESH = { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }
|
||||
|
||||
for _, c in Cases do
|
||||
local m, err = load(c.data)
|
||||
t:check(m, c.name .. ": " .. tostring(err))
|
||||
t:check(S3m.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff")
|
||||
local dec = m:render({ sampleRate = S.SR })
|
||||
t:check(dec, c.name .. ": render")
|
||||
t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration))
|
||||
local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR))
|
||||
local r = S.compare(S.features(buf, frames), c.ref)
|
||||
t:note("%-7s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envErr, r.spectral, r.balance, dec.duration)
|
||||
if r.spectral < THRESH.spectral or r.envErr > THRESH.envErr then
|
||||
for _, w in S.worst(S.features(buf, frames), c.ref, 6) do
|
||||
t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4])
|
||||
end
|
||||
end
|
||||
t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness")
|
||||
t:check(r.envErr < THRESH.envErr, c.name .. ": loudness envelope")
|
||||
t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum")
|
||||
t:check(r.balance < THRESH.balance, c.name .. ": stereo balance")
|
||||
end
|
||||
|
||||
-- seek: the position after a seek and the output continuing
|
||||
do
|
||||
local m = load(Cases[1].data)
|
||||
local dec = m:render()
|
||||
dec:seek(2)
|
||||
t:check(math.abs(dec:position() - 2) < 0.001, "seek position")
|
||||
local _, n = dec:read(1000)
|
||||
t:eq(n, 1000, "read after seek")
|
||||
t:check(Tracker.duration(m) == dec.duration, "duration()")
|
||||
end
|
||||
|
||||
-- the fuzz pass: decode, and a short render of whatever decodes
|
||||
local samples = {}
|
||||
for _, c in Cases do
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local m = S3m.decode(Bytes.reader(b))
|
||||
if m then
|
||||
local dec = Tracker.render(m, { maxDuration = 0.5, sampleRate = 8000 })
|
||||
if dec then
|
||||
dec:read(4000)
|
||||
end
|
||||
end
|
||||
return m
|
||||
end, samples, { mutations = 30 })
|
||||
|
||||
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()
|
||||
@@ -0,0 +1,77 @@
|
||||
-- music/xm tests: generated FastTracker 2 modules (tools/fixtures/xm.py) parsed, rendered through codecs/Tracker and
|
||||
-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the XM writer's
|
||||
-- round trip, the contract, and the fuzz no-throw pass.
|
||||
local T = require("@tests/T")
|
||||
local S = require("@tests/music/_similar")
|
||||
local Xm = require("@formats/music/xm")
|
||||
local Tracker = require("@formats/codecs/Tracker")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/xm_cases")
|
||||
|
||||
local t = T.suite("xm")
|
||||
|
||||
t:eq(Xm.name, "xm", "name")
|
||||
t:eq(Xm.category, "music", "category")
|
||||
t:check(Xm.caps.decode and Xm.caps.encode, "caps")
|
||||
|
||||
local function load(data: string): any
|
||||
return Xm.decode(Bytes.reader(buffer.fromstring(data)))
|
||||
end
|
||||
|
||||
local THRESH = { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }
|
||||
|
||||
for _, c in Cases do
|
||||
local m, err = load(c.data)
|
||||
t:check(m, c.name .. ": " .. tostring(err))
|
||||
t:check(Xm.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff")
|
||||
local dec = m:render({ sampleRate = S.SR })
|
||||
t:check(dec, c.name .. ": render")
|
||||
t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration))
|
||||
local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR))
|
||||
local r = S.compare(S.features(buf, frames), c.ref)
|
||||
t:note("%-7s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envErr, r.spectral, r.balance, dec.duration)
|
||||
if r.spectral < THRESH.spectral or r.envErr > THRESH.envErr then
|
||||
for _, w in S.worst(S.features(buf, frames), c.ref, 6) do
|
||||
t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4])
|
||||
end
|
||||
end
|
||||
t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness")
|
||||
t:check(r.envErr < THRESH.envErr, c.name .. ": loudness envelope")
|
||||
t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum")
|
||||
t:check(r.balance < THRESH.balance, c.name .. ": stereo balance")
|
||||
-- the writer: XM -> XM gives the same bytes back (the fixtures use the FT2 layout)
|
||||
local out, werr = Xm.encode(m)
|
||||
t:check(out, c.name .. ": encode " .. tostring(werr))
|
||||
local m2 = Xm.decode(Bytes.reader(out :: buffer))
|
||||
t:check(m2, c.name .. ": re-decode")
|
||||
t:eq(buffer.tostring(out :: buffer), c.data, c.name .. ": round trip bytes")
|
||||
end
|
||||
|
||||
-- seek: the position after a seek and the output continuing
|
||||
do
|
||||
local m = load(Cases[1].data)
|
||||
local dec = m:render()
|
||||
dec:seek(2)
|
||||
t:check(math.abs(dec:position() - 2) < 0.001, "seek position")
|
||||
local _, n = dec:read(1000)
|
||||
t:eq(n, 1000, "read after seek")
|
||||
t:check(Tracker.duration(m) == dec.duration, "duration()")
|
||||
end
|
||||
|
||||
-- the fuzz pass: decode, and a short render of whatever decodes
|
||||
local samples = {}
|
||||
for _, c in Cases do
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local m = Xm.decode(Bytes.reader(b))
|
||||
if m then
|
||||
local dec = Tracker.render(m, { maxDuration = 0.5, sampleRate = 8000 })
|
||||
if dec then
|
||||
dec:read(4000)
|
||||
end
|
||||
end
|
||||
return m
|
||||
end, samples, { mutations = 30 })
|
||||
|
||||
t:done()
|
||||
Reference in new issue
Block a user