ws-video: merge master (m4a, music, ...)
This commit is contained in:
commit
e044209ab1
118 files changed
+29274
-28
No files matched your search
@@ -0,0 +1,12 @@
|
||||
-- tests/audio/_encode_cases: the files our ALAC / CAF writers produce for the reference check (tools/fixtures/m4a.py
|
||||
-- runs tools/fixtures/_m4a_encode.luau over them; tests/audio/m4a.luau and caf.luau re-encode and compare).
|
||||
return {
|
||||
{ name = "ours_alac16_stereo", container = "m4a", rate = 44100, frames = 4096 * 3 + 1234, channels = 2, bits = 16, seed = 1, tags = { title = "Our Title \u{e9}", artist = "formats-luau", album = "Tests", track = "5", tracktotal = "10", date = "2026", genre = "Test", comment = "round trip" } },
|
||||
{ name = "ours_alac16_mono", container = "m4a", rate = 22050, frames = 5000, channels = 1, bits = 16, seed = 2 },
|
||||
{ name = "ours_alac24_stereo", container = "m4a", rate = 48000, frames = 9000, channels = 2, bits = 24, seed = 3 },
|
||||
{ name = "ours_alac16_6ch", container = "m4a", rate = 48000, frames = 4500, channels = 6, bits = 16, seed = 4 },
|
||||
{ name = "ours_alac20_stereo", container = "m4a", rate = 96000, frames = 3000, channels = 2, bits = 20, seed = 5 },
|
||||
{ name = "ours_caf_alac16", container = "caf", codec = "alac", rate = 44100, frames = 7000, channels = 2, bits = 16, seed = 6 },
|
||||
{ name = "ours_caf_pcm16", container = "caf", codec = "pcm", rate = 44100, frames = 3000, channels = 2, bits = 16, seed = 7 },
|
||||
{ name = "ours_caf_pcm24", container = "caf", codec = "pcm", rate = 48000, frames = 2000, channels = 1, bits = 24, seed = 8 },
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
-- tests/audio/_opus_cases: the inputs of the CELT encoder reference check (tools/fixtures/opus_celt.py runs
|
||||
-- tools/fixtures/_opus_encode.luau over them; tests/audio/opus_encode.luau re-encodes and compares): a deterministic
|
||||
-- music-like signal (chord + vibrato + chirp + clicks + a silent stretch) at a given rate / channel count.
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local Cases = {}
|
||||
|
||||
Cases.list = {
|
||||
{ name = "celt_mono_64k", rate = 48000, channels = 1, seconds = 1.5, bitrate = 64000, minSnr = 15 },
|
||||
{ name = "celt_stereo_128k", rate = 48000, channels = 2, seconds = 1.5, bitrate = 128000, minSnr = 15 },
|
||||
{ name = "celt_stereo_256k", rate = 48000, channels = 2, seconds = 1, bitrate = 256000, minSnr = 22 },
|
||||
{ name = "celt_mono_24k", rate = 48000, channels = 1, seconds = 1, bitrate = 24000, minSnr = 8 },
|
||||
{ name = "celt_44k_stereo_96k", rate = 44100, channels = 2, seconds = 1, bitrate = 96000, minSnr = 0, tags = { title = "Celt \u{e9}", artist = "formats-luau", album = "Opus" } },
|
||||
{ name = "celt_short", rate = 48000, channels = 1, seconds = 0.01, bitrate = 48000, minSnr = -100 },
|
||||
}
|
||||
|
||||
function Cases.signal(c: any): Types.Audio
|
||||
local n = math.floor(c.seconds * c.rate + 0.5)
|
||||
local a = Types.Audio.new(c.rate, c.channels, n)
|
||||
local s = 7
|
||||
for i = 0, n - 1 do
|
||||
local t = i / c.rate
|
||||
for ch = 0, c.channels - 1 do
|
||||
s = (s * 48271) % 2147483647
|
||||
local v = 0.18 * math.sin(2 * math.pi * 220 * t + 2 * math.sin(2 * math.pi * 5 * t))
|
||||
v += 0.12 * math.sin(2 * math.pi * (277.2 + ch * 2) * t) + 0.1 * math.sin(2 * math.pi * 329.6 * t)
|
||||
v += 0.08 * math.sin(2 * math.pi * (1000 + 3000 * t) * t)
|
||||
v += 0.01 * (s / 2147483647 - 0.5)
|
||||
if i % (c.rate // 4) < 30 then
|
||||
v += 0.4 * (if (i // 5) % 2 == 0 then 1 else -1)
|
||||
end
|
||||
if t > 0.6 and t < 0.75 then
|
||||
v = 0 -- digital silence (the encoder's silence frames)
|
||||
end
|
||||
buffer.writef32(a.samples, (i * c.channels + ch) * 4, v)
|
||||
end
|
||||
end
|
||||
a.tags = c.tags or {}
|
||||
return a
|
||||
end
|
||||
|
||||
return Cases
|
||||
@@ -0,0 +1,42 @@
|
||||
-- tests/audio/_signal: the deterministic integer test signal of tools/fixtures/_m4a_signal.py (the same numbers), as
|
||||
-- an interleaved integer array and as a Types.Audio (f32, exact for up to 24 bits). Used by the m4a / caf tests and the
|
||||
-- fixture-time encoder runs (tools/fixtures/_m4a_encode.luau).
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local Signal = {}
|
||||
|
||||
function Signal.ints(frames: number, channels: number, bits: number, seed: number): { number }
|
||||
local s = seed
|
||||
local peak = 2 ^ (bits - 1) - 1
|
||||
local out = table.create(frames * channels, 0)
|
||||
local k = 1
|
||||
for i = 0, frames - 1 do
|
||||
for c = 0, channels - 1 do
|
||||
s = (s * 48271) % 2147483647
|
||||
local p1 = 97 + 31 * c
|
||||
local tri = math.abs((i % p1) * 2 - p1) * 2 - p1
|
||||
local v = tri * (peak // (4 * p1))
|
||||
local p2 = 1500 + 200 * c
|
||||
v += if (i // p2) % 2 == 0 then peak // 6 else -(peak // 6)
|
||||
v += ((s // 65536) % 4096 - 2048) * (peak // 65536 + 1)
|
||||
if i % 7001 < 3 then
|
||||
v += peak // 2
|
||||
end
|
||||
out[k] = math.clamp(v, -peak - 1, peak)
|
||||
k += 1
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
function Signal.audio(rate: number, frames: number, channels: number, bits: number, seed: number): Types.Audio
|
||||
local ints = Signal.ints(frames, channels, bits, seed)
|
||||
local a = Types.Audio.new(rate, channels, frames)
|
||||
local scale = 1 / 2 ^ (bits - 1)
|
||||
for i, v in ints do
|
||||
buffer.writef32(a.samples, (i - 1) * 4, v * scale)
|
||||
end
|
||||
return a
|
||||
end
|
||||
|
||||
return Signal
|
||||
@@ -0,0 +1,117 @@
|
||||
-- audio/aac tests: ADTS streams from ffmpeg and fdkaac (stereo, mono 32 kHz) against ffmpeg's float decode (SNR,
|
||||
-- length); an HE-AAC ADTS stream plays its core; a leading ID3v2 tag (skipped, text frames as tags) and garbage before
|
||||
-- the first frame (resync); a truncated last frame; streaming + seek; sniff; errors; the fuzz no-throw pass.
|
||||
-- Fixtures: tools/fixtures/m4a.py.
|
||||
local T = require("@tests/T")
|
||||
local AacF = require("@formats/audio/aac")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Fx = require("@tests/gen/m4a_aac")
|
||||
local He = require("@tests/gen/m4a_he")
|
||||
|
||||
local t = T.suite("aac")
|
||||
|
||||
local function reader(s: string): Bytes.Reader
|
||||
return Bytes.reader(buffer.fromstring(s))
|
||||
end
|
||||
|
||||
local function snr(a: any, ref: string, skip: number?): number
|
||||
local off = (skip or 0) * a.channels
|
||||
local n = math.min(a.frames * a.channels - off, #ref // 4)
|
||||
local rb = buffer.fromstring(ref)
|
||||
local sig, err = 0, 0
|
||||
for i = 0, n - 1 do
|
||||
local r = buffer.readf32(rb, i * 4)
|
||||
local d = buffer.readf32(a.samples, (off + i) * 4) - r
|
||||
sig += r * r
|
||||
err += d * d
|
||||
end
|
||||
return if err == 0 then math.huge else 10 * math.log10(sig / err)
|
||||
end
|
||||
|
||||
t:eq(AacF.name, "aac", "name")
|
||||
t:check(AacF.caps.decode and not AacF.caps.encode and AacF.encode == nil, "caps: decode only")
|
||||
|
||||
local first
|
||||
for _, c in Fx do
|
||||
if c.container ~= "adts" then
|
||||
continue
|
||||
end
|
||||
first = first or c
|
||||
local r = reader(c.data)
|
||||
t:check(AacF.sniff(r) >= 0.9, c.name .. ": sniff")
|
||||
local a, err = AacF.decode(r)
|
||||
t:check(a, c.name .. ": " .. tostring(err))
|
||||
t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format")
|
||||
t:eq(a.frames, c.frames, c.name .. ": frames (ADTS keeps the priming)")
|
||||
local s = snr(a, c.ref)
|
||||
t:check(s > 90, string.format("%s: SNR %.1f dB", c.name, s))
|
||||
t:note("%s: %d ch %d Hz, %d frames, SNR %.1f dB vs ffmpeg", c.name, c.channels, c.rate, a.frames, s)
|
||||
end
|
||||
|
||||
-- HE-AAC ADTS: the core
|
||||
for _, c in He do
|
||||
if string.sub(c.name, -4) == ".aac" then
|
||||
local a, err = AacF.decode(reader(c.data))
|
||||
t:check(a and a.sampleRate == c.rate // 2 and a.frames > 0, c.name .. ": core decode: " .. tostring(err))
|
||||
end
|
||||
end
|
||||
|
||||
-- ID3v2 in front + garbage, truncated tail
|
||||
do
|
||||
local function frame(id: string, text: string): string
|
||||
local body = "\3" .. text
|
||||
local n = #body
|
||||
return id .. string.char(0, 0, n // 128, n % 128) .. "\0\0" .. body
|
||||
end
|
||||
local frames = frame("TIT2", "Adts Title") .. frame("TPE1", "Someone")
|
||||
local n = #frames
|
||||
local id3 = "ID3\4\0\0" .. string.char(0, 0, n // 128, n % 128) .. frames
|
||||
local data = id3 .. "\0\1\2garbage" .. first.data
|
||||
local a, err = AacF.decode(reader(data))
|
||||
t:check(a, "id3 + garbage: " .. tostring(err))
|
||||
t:check(a.tags.title == "Adts Title" and a.tags.artist == "Someone", "id3 tags")
|
||||
t:eq(a.frames, first.frames, "id3 + garbage: same frames")
|
||||
t:check(snr(a, first.ref) > 90, "id3 + garbage: same audio")
|
||||
local cut = AacF.decode(reader(string.sub(first.data, 1, #first.data - 5))) :: any
|
||||
t:check(cut and cut.frames == first.frames - 1024, "truncated last frame dropped")
|
||||
end
|
||||
|
||||
-- streaming + seek
|
||||
do
|
||||
local whole = AacF.decode(reader(first.data)) :: any
|
||||
local dec = AacF.open(reader(first.data)) :: any
|
||||
for _, at in { 0.3, 0.0, 0.5123 } do
|
||||
dec:seek(at)
|
||||
local b, n = dec:read(600)
|
||||
local f0 = math.floor(at * whole.sampleRate + 0.5)
|
||||
local maxd = 0
|
||||
for i = 0, n * whole.channels - 1 do
|
||||
maxd = math.max(maxd, math.abs(buffer.readf32(b, i * 4) - buffer.readf32(whole.samples, (f0 * whole.channels + i) * 4)))
|
||||
end
|
||||
-- (the stream has no PNS: noise substitution would draw different noise after a seek)
|
||||
t:check(n == 600 and maxd < 1e-6, string.format("seek %.3f s (max diff %g)", at, maxd))
|
||||
end
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
t:eq(AacF.sniff(reader("RIFF....WAVE")), 0, "sniff a WAV")
|
||||
local _, e = AacF.decode(reader(string.rep("\0", 100)))
|
||||
t:check(e and e.code == Err.CORRUPT, "no frames: " .. tostring(e))
|
||||
end
|
||||
|
||||
-- fuzz
|
||||
do
|
||||
local samples = {}
|
||||
for _, c in Fx do
|
||||
if c.container == "adts" then
|
||||
table.insert(samples, string.sub(c.data, 1, 6000))
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return AacF.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 30 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,183 @@
|
||||
-- audio/aiff tests: files written by ffmpeg and sox in every sample format (AIFF 8 / 12 / 16 / 24 / 32-bit, AIFF-C
|
||||
-- sowt / fl32 / fl64 / ulaw / alaw, 6 channels, text chunks) against ffmpeg's decode; streaming reads and seeks;
|
||||
-- our encoder's output for every sample format decoded by ffmpeg (fixture step) and by us; errors; fuzz.
|
||||
-- Fixtures: tools/fixtures/aiff.py.
|
||||
local T = require("@tests/T")
|
||||
local Aiff = require("@formats/audio/aiff")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Cases = require("@tests/gen/aiff_cases")
|
||||
local Enc = require("@tests/gen/aiff_enc")
|
||||
local Sig = require("@tests/gen/aiff_sig")
|
||||
|
||||
local t = T.suite("aiff")
|
||||
|
||||
local function reader(s: string): Bytes.Reader
|
||||
return Bytes.reader(buffer.fromstring(s))
|
||||
end
|
||||
-- max |a - b| over n f32 samples (a at byte ao, b at byte bo)
|
||||
local function maxDiff(a: buffer, ao: number, b: buffer, bo: number, n: number): number
|
||||
local m = 0
|
||||
for i = 0, n - 1 do
|
||||
local d = math.abs(buffer.readf32(a, ao + i * 4) - buffer.readf32(b, bo + i * 4))
|
||||
if d > m then
|
||||
m = d
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
-- the contract
|
||||
t:eq(Aiff.name, "aiff", "name")
|
||||
t:eq(Aiff.category, "audio", "category")
|
||||
t:check(Aiff.caps.decode and Aiff.caps.encode and table.find(Aiff.extensions, "aif") ~= nil, "caps / extensions")
|
||||
|
||||
-- reference files: decode, stream, seek
|
||||
for _, c in Cases do
|
||||
local a, err = Aiff.decode(reader(c.data))
|
||||
t:check(a, c.name .. ": " .. tostring(err))
|
||||
t:check(a.kind == "audio" and a.sampleRate == c.rate and a.channels == c.channels, c.name .. ": format")
|
||||
t:eq(a.frames, c.frames, c.name .. ": frames")
|
||||
local ref = buffer.fromstring(c.ref)
|
||||
local n = c.frames * c.channels
|
||||
t:check(maxDiff(a.samples, 0, ref, 0, n) < 1e-6, c.name .. ": samples match ffmpeg")
|
||||
-- streaming in odd chunks
|
||||
local dec = Aiff.open(reader(c.data)) :: Types.Decoder
|
||||
local got, out = 0, buffer.create(0)
|
||||
local ok = true
|
||||
while true do
|
||||
local b, k = dec:read(777, out)
|
||||
if k == 0 then
|
||||
break
|
||||
end
|
||||
out = b
|
||||
ok = ok and maxDiff(b, 0, ref, got * c.channels * 4, k * c.channels) < 1e-6
|
||||
got += k
|
||||
end
|
||||
t:check(ok and got == c.frames, c.name .. ": streamed reads")
|
||||
dec:seek(1000 / c.rate)
|
||||
t:check(math.abs(dec:position() - 1000 / c.rate) < 1e-9, c.name .. ": position")
|
||||
local b, k = dec:read(50)
|
||||
t:check(k == 50 and maxDiff(b, 0, ref, 1000 * c.channels * 4, 50 * c.channels) < 1e-6, c.name .. ": seek")
|
||||
end
|
||||
t:note("%d reference files match ffmpeg", #Cases)
|
||||
|
||||
-- details of particular files
|
||||
local function case(name: string): any
|
||||
for _, c in Cases do
|
||||
if c.name == name then
|
||||
return c
|
||||
end
|
||||
end
|
||||
error("no case " .. name)
|
||||
end
|
||||
do
|
||||
local a = Aiff.decode(reader(case("ffmpeg-tags").data)) :: Types.Audio
|
||||
t:eq(a.tags.title, "Song Name", "NAME chunk")
|
||||
t:eq(a.tags.artist, "Some One", "AUTH chunk")
|
||||
local fl = Aiff.decode(reader(case("ffmpeg-fl32").data)) :: Types.Audio
|
||||
t:check(fl.meta.source.aifc and fl.meta.source.compression == "fl32", "fl32 meta")
|
||||
-- a 12-bit sample size: samples sit left-justified in 16-bit containers
|
||||
local s16 = case("sox-aiff-s16")
|
||||
local q = string.find(s16.data, "COMM", 1, true) :: number
|
||||
local d12 = string.sub(s16.data, 1, q + 13) .. "\0\12" .. string.sub(s16.data, q + 16)
|
||||
local s12 = Aiff.decode(reader(d12)) :: Types.Audio
|
||||
t:check(s12.meta.source.bitDepth == 12 and maxDiff(s12.samples, 0, buffer.fromstring(s16.ref), 0, s16.frames * 2) < 1e-6, "12-bit sample size")
|
||||
local sw = Aiff.info(reader(case("ffmpeg-sowt").data))
|
||||
t:check(sw and sw.compression == "sowt" and sw.format == "s16le", "info: sowt")
|
||||
-- inside a bigger buffer
|
||||
local c = case("ffmpeg-s16be")
|
||||
local big = buffer.create(#c.data + 9)
|
||||
buffer.writestring(big, 5, c.data)
|
||||
local a2 = Aiff.decode(Bytes.reader(big, 5, #c.data)) :: Types.Audio
|
||||
t:check(a2 and maxDiff(a2.samples, 0, buffer.fromstring(c.ref), 0, c.frames * c.channels) < 1e-6, "decode from a sub-range")
|
||||
-- truncated sample data: the frames present
|
||||
local cut = string.sub(c.data, 1, #c.data - 1001)
|
||||
local a3 = Aiff.decode(reader(cut)) :: Types.Audio
|
||||
t:check(a3 and a3.frames < c.frames and a3.frames > 0 and a3.meta.source.truncated, "truncated SSND")
|
||||
end
|
||||
|
||||
-- our encoder: ffmpeg decodes every sample format (fixture step), within the format's step; streamed == from Audio
|
||||
local TOL = { s8 = 0.5 / 128, ["s16-mono"] = 0.5 / 32768, s16 = 0.5 / 32768, sowt16 = 0.5 / 32768, ["aifc-s16"] = 0.5 / 32768, s24 = 0.5 / 8388608, sowt24 = 0.5 / 8388608, s32 = 1e-7, f32 = 0, f64 = 0, ulaw = 0.04, alaw = 0.04 }
|
||||
local sig = buffer.fromstring(Sig.data)
|
||||
for _, e in Enc do
|
||||
t:eq(e.ffmpegErrors, "", e.name .. ": ffmpeg reads our file without errors")
|
||||
t:check(e.frames == Sig.frames and e.rate == Sig.rate, e.name .. ": ffmpeg frames / rate")
|
||||
t:check(e.maxDiff <= TOL[e.name] + 1e-7, string.format("%s: ffmpeg decode within %g (max diff %g)", e.name, TOL[e.name], e.maxDiff))
|
||||
t:check(e.sameStreamed, e.name .. ": encoding a Decoder gives the same bytes")
|
||||
local back = Aiff.decode(reader(e.data)) :: Types.Audio
|
||||
t:check(back and back.frames == Sig.frames and back.channels == e.channels, e.name .. ": our decoder reads our file")
|
||||
if e.channels == 2 then
|
||||
t:check(maxDiff(back.samples, 0, sig, 0, Sig.frames * 2) <= TOL[e.name] + 1e-7, e.name .. ": round trip")
|
||||
end
|
||||
end
|
||||
t:note("%d encoder outputs read back by ffmpeg and by us", #Enc)
|
||||
|
||||
-- encoder: tags, odd sizes, errors
|
||||
do
|
||||
local a = Types.Audio.new(44100, 1, 3)
|
||||
buffer.writef32(a.samples, 0, 0.5)
|
||||
buffer.writef32(a.samples, 4, -1)
|
||||
buffer.writef32(a.samples, 8, 2) -- clips
|
||||
a.tags = { title = "odd", artist = "me", comment = "x" }
|
||||
local b = Aiff.encode(a, { sampleFormat = "s8" }) :: buffer
|
||||
local back = Aiff.decode(Bytes.reader(b)) :: Types.Audio
|
||||
t:check(back.frames == 3 and back.tags.title == "odd" and back.tags.artist == "me" and back.tags.comment == "x", "odd length + tags")
|
||||
t:check(buffer.readf32(back.samples, 0) == 0.5 and buffer.readf32(back.samples, 4) == -1 and buffer.readf32(back.samples, 8) == 127 / 128, "s8 values, clipping")
|
||||
t:eq(buffer.len(b) % 2, 0, "chunks padded to even sizes")
|
||||
t:check(Aiff.info(Bytes.reader(b)).sampleRate == 44100, "80-bit rate round trip")
|
||||
local empty = Aiff.encode(Types.Audio.new(8000, 2, 0)) :: buffer
|
||||
local e0 = Aiff.decode(Bytes.reader(empty))
|
||||
t:check(e0 and e0.frames == 0, "empty audio")
|
||||
local _, e1 = Aiff.encode({} :: any)
|
||||
t:check(e1 and e1.code == Err.ARG, "encode junk: ARG")
|
||||
local _, e2 = Aiff.encode(a, { sampleFormat = "s12" } :: any)
|
||||
t:check(e2 and e2.code == Err.ARG, "bad sampleFormat: ARG")
|
||||
local _, e3 = Aiff.encode(a, { sampleFormat = "f32", littleEndian = true })
|
||||
t:check(e3 and e3.code == Err.ARG, "littleEndian float: ARG")
|
||||
local _, e5 = Aiff.encode(a, { sampleFormat = "s24", littleEndian = true })
|
||||
t:check(e5 and e5.code == Err.ARG, "littleEndian 24-bit: ARG")
|
||||
t:eq(Aiff.sniff(Bytes.reader(b)), 1, "sniff")
|
||||
t:eq(Aiff.sniff(reader("RIFF....WAVE")), 0, "sniff wav")
|
||||
t:eq(Aiff.sniff(reader("")), 0, "sniff nothing")
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local _, e = Aiff.decode(reader("FORM\0\0\0\4WAVE"))
|
||||
t:check(e and e.code == Err.CORRUPT, "wrong FORM type: " .. tostring(e))
|
||||
local c = case("ffmpeg-fl32").data
|
||||
local p = string.find(c, "fl32", 1, true) :: number
|
||||
local ima = string.sub(c, 1, p - 1) .. "ima4" .. string.sub(c, p + 4)
|
||||
local _, e2 = Aiff.decode(reader(ima))
|
||||
t:check(e2 and e2.code == Err.UNSUPPORTED, "ima4: UNSUPPORTED: " .. tostring(e2))
|
||||
local _, e3 = Aiff.decode(reader(string.sub(c, 1, 30)))
|
||||
t:check(e3 and (e3.code == Err.TRUNCATED or e3.code == Err.CORRUPT), "cut in COMM: " .. tostring(e3))
|
||||
local _, e4 = Aiff.decode(reader(case("ffmpeg-s16be").data), { maxFrames = 10 })
|
||||
t:check(e4 and e4.code == Err.LIMIT, "maxFrames: LIMIT")
|
||||
end
|
||||
|
||||
-- fuzz
|
||||
do
|
||||
local samples = {}
|
||||
for i, c in Cases do
|
||||
if i % 3 == 1 then
|
||||
table.insert(samples, string.sub(c.data, 1, 600))
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Aiff.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 30, keepHeader = 0 })
|
||||
t:fuzz("open + read", function(b: buffer)
|
||||
local d = Aiff.open(Bytes.reader(b))
|
||||
if d then
|
||||
d:read(100)
|
||||
d:seek(0.001)
|
||||
d:read(100)
|
||||
end
|
||||
return d
|
||||
end, samples, { mutations = 10, garbage = 50 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,147 @@
|
||||
-- audio/au tests: files written by ffmpeg and sox in every encoding (8 / 16 / 24 / 32-bit, float, double, mu-law,
|
||||
-- A-law, an annotation) against ffmpeg's decode; streaming reads and seeks; our encoder's output for every encoding
|
||||
-- decoded by ffmpeg (fixture step) and by us; an unknown data size; errors; fuzz. Fixtures: tools/fixtures/au.py.
|
||||
local T = require("@tests/T")
|
||||
local Au = require("@formats/audio/au")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Cases = require("@tests/gen/au_cases")
|
||||
local Enc = require("@tests/gen/au_enc")
|
||||
local Sig = require("@tests/gen/au_sig")
|
||||
|
||||
local t = T.suite("au")
|
||||
|
||||
local function reader(s: string): Bytes.Reader
|
||||
return Bytes.reader(buffer.fromstring(s))
|
||||
end
|
||||
local function maxDiff(a: buffer, ao: number, b: buffer, bo: number, n: number): number
|
||||
local m = 0
|
||||
for i = 0, n - 1 do
|
||||
local d = math.abs(buffer.readf32(a, ao + i * 4) - buffer.readf32(b, bo + i * 4))
|
||||
if d > m then
|
||||
m = d
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
local function case(name: string): any
|
||||
for _, c in Cases do
|
||||
if c.name == name then
|
||||
return c
|
||||
end
|
||||
end
|
||||
error("no case " .. name)
|
||||
end
|
||||
|
||||
t:eq(Au.name, "au", "name")
|
||||
t:eq(Au.category, "audio", "category")
|
||||
t:check(Au.caps.decode and Au.caps.encode and table.find(Au.extensions, "snd") ~= nil, "caps / extensions")
|
||||
|
||||
for _, c in Cases do
|
||||
local a, err = Au.decode(reader(c.data))
|
||||
t:check(a, c.name .. ": " .. tostring(err))
|
||||
t:check(a.sampleRate == c.rate and a.channels == c.channels, c.name .. ": format")
|
||||
t:eq(a.frames, c.frames, c.name .. ": frames")
|
||||
local ref = buffer.fromstring(c.ref)
|
||||
t:check(maxDiff(a.samples, 0, ref, 0, c.frames * c.channels) < 1e-6, c.name .. ": samples match ffmpeg")
|
||||
local dec = Au.open(reader(c.data)) :: Types.Decoder
|
||||
local got, ok = 0, true
|
||||
while true do
|
||||
local b, k = dec:read(1000)
|
||||
if k == 0 then
|
||||
break
|
||||
end
|
||||
ok = ok and maxDiff(b, 0, ref, got * c.channels * 4, k * c.channels) < 1e-6
|
||||
got += k
|
||||
end
|
||||
t:check(ok and got == c.frames, c.name .. ": streamed reads")
|
||||
dec:seek(700 / c.rate)
|
||||
local b, k = dec:read(40)
|
||||
t:check(k == 40 and maxDiff(b, 0, ref, 700 * c.channels * 4, 40 * c.channels) < 1e-6, c.name .. ": seek")
|
||||
end
|
||||
t:note("%d reference files match ffmpeg", #Cases)
|
||||
|
||||
do
|
||||
local a = Au.decode(reader(case("sox-comment").data)) :: Types.Audio
|
||||
t:check(a.tags.comment ~= nil and string.find(a.tags.comment, "hello sun", 1, true) ~= nil, "annotation as comment")
|
||||
-- an unknown data size (0xFFFFFFFF) runs to the end of the file
|
||||
local c = case("ffmpeg-s16be")
|
||||
local unk = string.sub(c.data, 1, 8) .. "\255\255\255\255" .. string.sub(c.data, 13)
|
||||
local a2 = Au.decode(reader(unk)) :: Types.Audio
|
||||
t:check(a2 and a2.frames == c.frames, "unknown data size")
|
||||
local cut = Au.decode(reader(string.sub(c.data, 1, #c.data - 400))) :: Types.Audio
|
||||
t:check(cut and cut.frames == c.frames - 100 and cut.meta.source.truncated, "truncated data")
|
||||
local big = buffer.create(#c.data + 3)
|
||||
buffer.writestring(big, 3, c.data)
|
||||
local a3 = Au.decode(Bytes.reader(big, 3, #c.data)) :: Types.Audio
|
||||
t:check(a3 and maxDiff(a3.samples, 0, buffer.fromstring(c.ref), 0, c.frames * 2) < 1e-6, "decode from a sub-range")
|
||||
end
|
||||
|
||||
local TOL = { s8 = 0.5 / 128, ["s16-mono"] = 0.5 / 32768, s16 = 0.5 / 32768, s24 = 0.5 / 8388608, s32 = 1e-7, f32 = 0, f64 = 0, ulaw = 0.04, alaw = 0.04 }
|
||||
local sig = buffer.fromstring(Sig.data)
|
||||
for _, e in Enc do
|
||||
t:eq(e.ffmpegErrors, "", e.name .. ": ffmpeg reads our file without errors")
|
||||
t:check(e.frames == Sig.frames and e.rate == Sig.rate, e.name .. ": ffmpeg frames / rate")
|
||||
t:check(e.maxDiff <= TOL[e.name] + 1e-7, string.format("%s: ffmpeg decode within %g (max diff %g)", e.name, TOL[e.name], e.maxDiff))
|
||||
t:check(e.sameStreamed, e.name .. ": encoding a Decoder gives the same bytes")
|
||||
local back = Au.decode(reader(e.data)) :: Types.Audio
|
||||
t:check(back and back.frames == Sig.frames and back.channels == e.channels, e.name .. ": our decoder reads our file")
|
||||
if e.channels == 2 then
|
||||
t:check(maxDiff(back.samples, 0, sig, 0, Sig.frames * 2) <= TOL[e.name] + 1e-7, e.name .. ": round trip")
|
||||
end
|
||||
end
|
||||
t:note("%d encoder outputs read back by ffmpeg and by us", #Enc)
|
||||
|
||||
do
|
||||
local a = Types.Audio.new(8000, 1, 2)
|
||||
buffer.writef32(a.samples, 0, 0.25)
|
||||
buffer.writef32(a.samples, 4, -0.25)
|
||||
a.tags = { comment = "annotated!" }
|
||||
local b = Au.encode(a) :: buffer
|
||||
t:eq(bit32.byteswap(buffer.readu32(b, 4)) % 8, 0, "data offset is a multiple of 8")
|
||||
local back = Au.decode(Bytes.reader(b)) :: Types.Audio
|
||||
t:check(back.frames == 2 and back.tags.comment == "annotated!" and buffer.readf32(back.samples, 0) == 0.25, "comment + samples")
|
||||
local _, e1 = Au.encode(42 :: any)
|
||||
t:check(e1 and e1.code == Err.ARG, "encode junk: ARG")
|
||||
local _, e2 = Au.encode(a, { sampleFormat = "u8" } :: any)
|
||||
t:check(e2 and e2.code == Err.ARG, "bad sampleFormat: ARG")
|
||||
local frac = Types.Audio.new(8000.5, 1, 1)
|
||||
local _, e3 = Au.encode(frac)
|
||||
t:check(e3 and e3.code == Err.ARG, "fractional rate: ARG")
|
||||
t:eq(Au.sniff(Bytes.reader(b)), 1, "sniff")
|
||||
t:eq(Au.sniff(reader("FORM")), 0, "sniff other")
|
||||
-- G.721 ADPCM (encoding 23): unsupported
|
||||
local adpcm = string.sub(buffer.tostring(b), 1, 12) .. "\0\0\0\23" .. string.sub(buffer.tostring(b), 17)
|
||||
local _, e4 = Au.decode(reader(adpcm))
|
||||
t:check(e4 and e4.code == Err.UNSUPPORTED, "encoding 23: UNSUPPORTED")
|
||||
local _, e5 = Au.decode(reader(".snd\0\0\0\24"))
|
||||
t:check(e5 and e5.code == Err.CORRUPT, "short header: CORRUPT")
|
||||
local _, e6 = Au.decode(reader(case("ffmpeg-s16be").data), { maxFrames = 5 })
|
||||
t:check(e6 and e6.code == Err.LIMIT, "maxFrames: LIMIT")
|
||||
end
|
||||
|
||||
do
|
||||
local samples = {}
|
||||
for i, c in Cases do
|
||||
if i % 2 == 1 then
|
||||
table.insert(samples, string.sub(c.data, 1, 400))
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Au.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 30 })
|
||||
t:fuzz("open + read", function(b: buffer)
|
||||
local d = Au.open(Bytes.reader(b))
|
||||
if d then
|
||||
d:read(64)
|
||||
d:seek(1e9)
|
||||
d:read(64)
|
||||
d:seek(-1)
|
||||
d:read(64)
|
||||
end
|
||||
return d
|
||||
end, samples, { mutations = 10, garbage = 50 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,177 @@
|
||||
-- audio/caf tests: ALAC CAF from ffmpeg bit-exact; AAC CAF (ffmpeg's ADTS frames wrapped by the fixture) against
|
||||
-- ffmpeg's float decode; our CAF writer (PCM 16 / 24-bit, ALAC; re-encoded here and compared with the bytes ffmpeg
|
||||
-- decoded bit-exactly); PCM layouts (little / big endian, float) through our writer + a hand-built header; info tags;
|
||||
-- seek; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/m4a.py.
|
||||
local T = require("@tests/T")
|
||||
local Caf = require("@formats/audio/caf")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Signal = require("@tests/audio/_signal")
|
||||
local Cases = require("@tests/audio/_encode_cases")
|
||||
local Alac = require("@tests/gen/m4a_alac")
|
||||
local Aac = require("@tests/gen/m4a_aac")
|
||||
local Ours = require("@tests/gen/m4a_ours")
|
||||
|
||||
local t = T.suite("caf")
|
||||
|
||||
local function reader(s: string | buffer): Bytes.Reader
|
||||
return Bytes.reader(if type(s) == "string" then buffer.fromstring(s) else s)
|
||||
end
|
||||
|
||||
local function intCrc(a: any, bits: number): number
|
||||
local n = a.frames * a.channels
|
||||
local b = buffer.create(n * 4)
|
||||
local scale = 2 ^ (bits - 1)
|
||||
for i = 0, n - 1 do
|
||||
buffer.writei32(b, i * 4, math.floor(buffer.readf32(a.samples, i * 4) * scale + 0.5))
|
||||
end
|
||||
return Crc32.of(b)
|
||||
end
|
||||
|
||||
t:eq(Caf.name, "caf", "name")
|
||||
t:check(Caf.caps.decode and Caf.caps.encode, "caps")
|
||||
|
||||
for _, c in Alac do
|
||||
if c.container == "caf" then
|
||||
local r = reader(c.data)
|
||||
t:eq(Caf.sniff(r), 1, c.name .. ": sniff")
|
||||
local a, err = Caf.decode(r)
|
||||
t:check(a, c.name .. ": " .. tostring(err))
|
||||
t:check(a.channels == c.channels and a.sampleRate == c.rate and a.frames == c.frames, c.name .. ": format / length (pakt)")
|
||||
t:eq(intCrc(a, c.bits), c.crc, c.name .. ": bit-exact")
|
||||
end
|
||||
end
|
||||
|
||||
for _, c in Aac do
|
||||
if c.container == "caf" then
|
||||
local a, err = Caf.decode(reader(c.data))
|
||||
t:check(a, c.name .. ": " .. tostring(err))
|
||||
t:eq(a.frames, c.frames, c.name .. ": frames")
|
||||
local rb = buffer.fromstring(c.ref)
|
||||
local sig, e = 0, 0
|
||||
for i = 0, a.frames * a.channels - 1 do
|
||||
local r = buffer.readf32(rb, i * 4)
|
||||
sig += r * r
|
||||
e += (buffer.readf32(a.samples, i * 4) - r) ^ 2
|
||||
end
|
||||
local snr = if e == 0 then math.huge else 10 * math.log10(sig / e)
|
||||
t:check(snr > 90, string.format("%s: SNR %.1f dB", c.name, snr))
|
||||
t:note("%s: SNR %.1f dB vs ffmpeg", c.name, snr)
|
||||
end
|
||||
end
|
||||
|
||||
-- our writer: the bytes ffmpeg validated
|
||||
do
|
||||
local byName = {}
|
||||
for _, o in Ours do
|
||||
byName[o.name] = o
|
||||
end
|
||||
for _, c in Cases do
|
||||
if c.container ~= "caf" then
|
||||
continue
|
||||
end
|
||||
local o = byName[c.name]
|
||||
t:check(o and o.ffmpeg, c.name .. ": ffmpeg decoded it bit-exactly")
|
||||
local a = Signal.audio(c.rate, c.frames, c.channels, c.bits, c.seed)
|
||||
local file = Caf.encode(a, { codec = c.codec, bitDepth = c.bits }) :: buffer
|
||||
t:eq(string.format("%08x", Crc32.of(file)), string.format("%08x", o.crc), c.name .. ": the validated bytes")
|
||||
local back = Caf.decode(reader(file)) :: any
|
||||
t:check(back and back.frames == c.frames, c.name .. ": our length")
|
||||
local ints = Signal.ints(c.frames, c.channels, c.bits, c.seed)
|
||||
local ok = true
|
||||
local scale = 2 ^ (c.bits - 1)
|
||||
for i = 1, #ints do
|
||||
ok = ok and math.floor(buffer.readf32(back.samples, (i - 1) * 4) * scale + 0.5) == ints[i]
|
||||
end
|
||||
t:check(ok, c.name .. ": round trip")
|
||||
end
|
||||
end
|
||||
|
||||
-- float PCM, tags, a decoder as the source, a hand-built little-endian header
|
||||
do
|
||||
local a = Signal.audio(32000, 3000, 3, 16, 12)
|
||||
a.tags = { title = "Caf Title", artist = "A", date = "1999", comment = "c", custom = "x" }
|
||||
local file = Caf.encode(a, { codec = "pcm", bitDepth = 32 }) :: buffer
|
||||
local back = Caf.decode(reader(file)) :: any
|
||||
t:check(back.frames == 3000 and buffer.tostring(back.samples) == buffer.tostring(a.samples), "float PCM round trip")
|
||||
for k, v in a.tags do
|
||||
t:eq(back.tags[k], v, "tag " .. k)
|
||||
end
|
||||
local dec = Caf.open(reader(file)) :: any
|
||||
local again = Caf.encode(dec, { codec = "alac" }) :: buffer
|
||||
local b2 = Caf.decode(reader(again)) :: any
|
||||
t:check(b2.frames == 3000 and buffer.tostring(b2.samples) == buffer.tostring(a.samples), "ALAC from a streaming decoder")
|
||||
-- little-endian 24-bit integer PCM, data chunk of unknown size (-1)
|
||||
local w = Bytes.writer(64)
|
||||
w:string("caff")
|
||||
w:u16be(1)
|
||||
w:u16be(0)
|
||||
w:string("desc")
|
||||
w:u64be(32)
|
||||
w:f64be(8000)
|
||||
w:string("lpcm")
|
||||
w:u32be(2)
|
||||
w:u32be(3)
|
||||
w:u32be(1)
|
||||
w:u32be(1)
|
||||
w:u32be(24)
|
||||
w:string("data")
|
||||
w:u32be(0xFFFFFFFF)
|
||||
w:u32be(0xFFFFFFFF)
|
||||
w:u32be(0)
|
||||
for _, v in { 0, 4194304, -4194304, 8388607, -8388608 } do
|
||||
w:u24le(v % 16777216)
|
||||
end
|
||||
local le = Caf.decode(Bytes.reader(w:finish())) :: any
|
||||
t:check(le and le.frames == 5, "24-bit LE, data size -1")
|
||||
t:check(le and math.abs(buffer.readf32(le.samples, 4) - 0.5) < 1e-7 and math.abs(buffer.readf32(le.samples, 16) + 1) < 1e-7, "24-bit LE values")
|
||||
end
|
||||
|
||||
-- seek
|
||||
do
|
||||
local c = Alac[#Alac]
|
||||
local whole = Caf.decode(reader(c.data)) :: any
|
||||
local dec = Caf.open(reader(c.data)) :: any
|
||||
for _, at in { 0.1, 0.0, 0.15 } do
|
||||
dec:seek(at)
|
||||
local b, n = dec:read(400)
|
||||
local f0 = math.floor(at * whole.sampleRate + 0.5)
|
||||
local same = n == 400
|
||||
for i = 0, n * whole.channels - 1 do
|
||||
same = same and buffer.readf32(b, i * 4) == buffer.readf32(whole.samples, (f0 * whole.channels + i) * 4)
|
||||
end
|
||||
t:check(same, string.format("seek %.2f s", at))
|
||||
end
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
t:eq(Caf.sniff(reader("caff\0\2\0\0")), 0, "sniff: wrong version")
|
||||
local _, e = Caf.decode(reader("caff\0\1\0\0"))
|
||||
t:check(e and e.code == Err.CORRUPT, "no desc: " .. tostring(e))
|
||||
local _, e2 = Caf.encode(Signal.audio(8000, 10, 1, 16, 1), { codec = "mp3" } :: any)
|
||||
t:check(e2 and e2.code == Err.ARG, "bad codec: " .. tostring(e2))
|
||||
end
|
||||
|
||||
-- fuzz
|
||||
do
|
||||
local samples = {}
|
||||
for _, c in Alac do
|
||||
if c.container == "caf" then
|
||||
table.insert(samples, string.sub(c.data, 1, 9000))
|
||||
end
|
||||
end
|
||||
for _, c in Aac do
|
||||
if c.container == "caf" then
|
||||
table.insert(samples, string.sub(c.data, 1, 6000))
|
||||
end
|
||||
end
|
||||
local pcm = Caf.encode(Signal.audio(8000, 300, 2, 16, 3), { codec = "pcm" }) :: buffer
|
||||
table.insert(samples, buffer.tostring(pcm))
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Caf.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 30 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -22,7 +22,7 @@ for _, c in Cases do
|
||||
end
|
||||
|
||||
t:eq(Flac.name, "flac", "name")
|
||||
t:check(Flac.caps.decode and not Flac.caps.encode, "caps")
|
||||
t:check(Flac.caps.decode and Flac.caps.encode, "caps") -- encode: ws-audio (tests/audio/flac_encode.luau)
|
||||
|
||||
local seekChecks = 0
|
||||
for _, fx in Cases do
|
||||
@@ -156,8 +156,8 @@ do
|
||||
t:check(a and a.frames == fx.frames, "F.audio.load")
|
||||
local d = F.audio.open(byName.s16_l3.data)
|
||||
t:check(d and d.frames == byName.s16_l3.frames, "F.audio.open")
|
||||
local _, se = F.save(a, nil, { format = "flac" })
|
||||
t:check(se and se.code == Err.UNSUPPORTED, "F.save flac is read-only here: " .. tostring(se))
|
||||
local saved, se = F.save(a, nil, { format = "flac" }) -- the encoder (ws-audio)
|
||||
t:check(saved and F.audio.load(saved).frames == fx.frames, "F.save flac: " .. tostring(se))
|
||||
end
|
||||
|
||||
-- a damaged frame is dropped, the rest decodes
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
-- audio/flac encoder tests: every fixture-step encode (levels 0-8, 1 / 2 / 6 channels, 8 / 12 / 16 / 20 / 24 bits,
|
||||
-- odd lengths and block sizes, odd rates, seek tables, padding) passed `flac -t` and carries the MD5 of the quantized
|
||||
-- input; sizes within 10% of libFLAC at the same level; each decodes bit-exactly through our own decoder; streaming
|
||||
-- from a Decoder gives the same bytes; tags; option errors. Fixtures: tools/fixtures/flac_enc.py.
|
||||
local T = require("@tests/T")
|
||||
local Flac = require("@formats/audio/flac")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/Pcm")
|
||||
local Enc = require("@tests/gen/flac_enc")
|
||||
local Sigs = require("@tests/gen/flac_enc_sigs")
|
||||
|
||||
local t = T.suite("flac_encode")
|
||||
|
||||
local sigCache: { [string]: any } = {}
|
||||
local function sig(name: string): Types.Audio
|
||||
local s = sigCache[name]
|
||||
if not s then
|
||||
local m = Sigs[name]
|
||||
s = Types.Audio.new(m.rate, m.channels, m.frames)
|
||||
buffer.writestring(s.samples, 0, m.data)
|
||||
sigCache[name] = s
|
||||
end
|
||||
return s
|
||||
end
|
||||
|
||||
t:check(Flac.caps.encode and Flac.encode ~= nil, "caps.encode")
|
||||
|
||||
local worst = 0
|
||||
for _, e in Enc do
|
||||
t:eq(e.flacTest, "", e.name .. ": flac -t")
|
||||
t:eq(e.md5, e.wantMd5, e.name .. ": STREAMINFO MD5 = MD5 of the quantized input")
|
||||
if e.refSize then
|
||||
local ratio = e.size / e.refSize
|
||||
worst = math.max(worst, ratio)
|
||||
t:check(ratio < 1.1, string.format("%s: %d bytes, libFLAC %d (%.3f)", e.name, e.size, e.refSize, ratio))
|
||||
end
|
||||
-- our decoder: bit-exact against the input quantized to e.bits
|
||||
local a = sig(e.sig)
|
||||
local back, err = Flac.decode(Bytes.reader(buffer.fromstring(e.data)))
|
||||
t:check(back, e.name .. ": our decoder: " .. tostring(err))
|
||||
t:check(back.frames == a.frames and back.channels == a.channels and back.sampleRate == a.sampleRate, e.name .. ": format")
|
||||
local s = 2 ^ (e.bits - 1)
|
||||
local exact = true
|
||||
for i = 0, a.frames * a.channels - 1 do
|
||||
local want = math.clamp(math.floor(buffer.readf32(a.samples, i * 4) * s + 0.5), -s, s - 1)
|
||||
if math.floor(buffer.readf32(back.samples, i * 4) * s + 0.5) ~= want then
|
||||
exact = false
|
||||
break
|
||||
end
|
||||
end
|
||||
t:check(exact, e.name .. ": bit-exact round trip")
|
||||
t:eq(back.meta.source.bitDepth, e.bits, e.name .. ": bits per sample")
|
||||
end
|
||||
t:note("%d encodes pass flac -t with the right MD5 and decode bit-exactly; worst size vs libFLAC %.3f", #Enc, worst)
|
||||
|
||||
-- streaming: a Decoder source gives the same bytes as the Audio
|
||||
do
|
||||
local a = sig("flacsig_music_2_7000_44100")
|
||||
local f1 = Flac.encode(a, { level = 5 }) :: buffer
|
||||
local f2 = Flac.encode(Pcm.audioDecoder(a), { level = 5 }) :: buffer
|
||||
t:check(buffer.tostring(f1) == buffer.tostring(f2), "Decoder source = Audio source")
|
||||
-- a decoder of our own output re-encodes to the same stream (its bit depth carries over)
|
||||
local dec = Flac.open(Bytes.reader(f1)) :: any
|
||||
local f3 = Flac.encode(dec, { level = 5 }) :: buffer
|
||||
t:check(buffer.tostring(f3) == buffer.tostring(f1), "FLAC -> FLAC through the streaming decoder")
|
||||
end
|
||||
|
||||
-- tags, bit depth from the source
|
||||
do
|
||||
local a = Types.Audio.new(48000, 1, 3000)
|
||||
for i = 0, 2999 do
|
||||
buffer.writef32(a.samples, i * 4, math.floor(math.sin(i / 7) * 100) / 128)
|
||||
end
|
||||
a.tags = { title = "Tïtle", artist = "Artist", track = "3" }
|
||||
a.meta.source = { format = "wav", bitDepth = 8 }
|
||||
local f = Flac.encode(a) :: buffer
|
||||
local back = Flac.decode(Bytes.reader(f)) :: Types.Audio
|
||||
t:eq(back.meta.source.bitDepth, 8, "bit depth from meta.source")
|
||||
-- (the absorbed FLAC decoder keeps Vorbis comment keys upper case)
|
||||
local tags = back.tags :: any
|
||||
t:eq(tags.title or tags.TITLE, "Tïtle", "title")
|
||||
t:eq(tags.artist or tags.ARTIST, "Artist", "artist")
|
||||
t:eq(tags.track or tags.TRACKNUMBER, "3", "track number")
|
||||
local empty = Flac.encode(Types.Audio.new(44100, 2, 0)) :: buffer
|
||||
local e0 = Flac.decode(Bytes.reader(empty))
|
||||
t:check(e0 and e0.frames == 0, "empty audio")
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local a = Types.Audio.new(44100, 2, 10)
|
||||
local function code(v: any, o: any): string?
|
||||
local _, e = Flac.encode(v, o)
|
||||
return e and e.code
|
||||
end
|
||||
t:eq(code({}, nil), Err.ARG, "junk value")
|
||||
t:eq(code(a, { level = 9 }), Err.ARG, "level 9")
|
||||
t:eq(code(a, { level = 2.5 }), Err.ARG, "level 2.5")
|
||||
t:eq(code(a, { bits = 32 }), Err.ARG, "32 bits")
|
||||
t:eq(code(a, { bits = 3 }), Err.ARG, "3 bits")
|
||||
t:eq(code(a, { blockSize = 8 }), Err.ARG, "block size 8")
|
||||
t:eq(code(Types.Audio.new(44100, 9, 1), nil), Err.ARG, "9 channels")
|
||||
t:eq(code(Types.Audio.new(44100.5, 1, 1), nil), Err.ARG, "fractional rate")
|
||||
end
|
||||
|
||||
-- (the decoder's fuzz pass is in tests/audio/flac.luau; the encoder takes no untrusted bytes)
|
||||
t:done()
|
||||
@@ -0,0 +1,218 @@
|
||||
-- audio/m4a tests: ALAC files from ffmpeg decode bit-exactly (16 / 24-bit, mono / stereo / 5.1, partial frames);
|
||||
-- AAC-LC files from ffmpeg and fdkaac (stereo / mono / 5.1, 8 - 96 kHz, PNS / intensity / M/S / TNS) against ffmpeg's
|
||||
-- float decode (SNR, gapless length through the edit list); HE-AAC / HE-AACv2 play their core; our ALAC writer
|
||||
-- (re-encoded here, compared with the bytes ffmpeg decoded bit-exactly and MP4Box accepted in the fixture step); tags
|
||||
-- and cover art round trips; streaming reads, seeking; the contract; the fuzz no-throw pass.
|
||||
-- Fixtures: tools/fixtures/m4a.py.
|
||||
local T = require("@tests/T")
|
||||
local M4a = require("@formats/audio/m4a")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Signal = require("@tests/audio/_signal")
|
||||
local Cases = require("@tests/audio/_encode_cases")
|
||||
local Alac = require("@tests/gen/m4a_alac")
|
||||
local Aac = require("@tests/gen/m4a_aac")
|
||||
local He = require("@tests/gen/m4a_he")
|
||||
local Ours = require("@tests/gen/m4a_ours")
|
||||
|
||||
local t = T.suite("m4a")
|
||||
|
||||
local function reader(s: string | buffer): Bytes.Reader
|
||||
return Bytes.reader(if type(s) == "string" then buffer.fromstring(s) else s)
|
||||
end
|
||||
|
||||
-- the integers of a decoded Audio (exact for <= 24-bit sources), CRC-32 as little-endian int32
|
||||
local function intCrc(a: any, bits: number): number
|
||||
local n = a.frames * a.channels
|
||||
local b = buffer.create(n * 4)
|
||||
local scale = 2 ^ (bits - 1)
|
||||
for i = 0, n - 1 do
|
||||
buffer.writei32(b, i * 4, math.floor(buffer.readf32(a.samples, i * 4) * scale + 0.5))
|
||||
end
|
||||
return Crc32.of(b)
|
||||
end
|
||||
|
||||
local function snr(a: any, ref: string): (number, number)
|
||||
local n = math.min(a.frames * a.channels, #ref // 4)
|
||||
local rb = buffer.fromstring(ref)
|
||||
local sig, err = 0, 0
|
||||
for i = 0, n - 1 do
|
||||
local r = buffer.readf32(rb, i * 4)
|
||||
local d = buffer.readf32(a.samples, i * 4) - r
|
||||
sig += r * r
|
||||
err += d * d
|
||||
end
|
||||
if err == 0 then
|
||||
return math.huge, n
|
||||
end
|
||||
return 10 * math.log10(sig / err), n
|
||||
end
|
||||
|
||||
-- the contract
|
||||
t:eq(M4a.name, "m4a", "name")
|
||||
t:eq(M4a.category, "audio", "category")
|
||||
t:check(M4a.caps.decode and M4a.caps.encode, "caps")
|
||||
|
||||
-- ALAC from ffmpeg: bit-exact
|
||||
for _, c in Alac do
|
||||
if c.container ~= "m4a" then
|
||||
continue
|
||||
end
|
||||
local r = reader(c.data)
|
||||
t:check(M4a.sniff(r) == 1, c.name .. ": sniff")
|
||||
local a, err = M4a.decode(r)
|
||||
t:check(a, c.name .. ": " .. tostring(err))
|
||||
t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format")
|
||||
t:eq(a.frames, c.frames, c.name .. ": frames")
|
||||
t:eq(intCrc(a, c.bits), c.crc, c.name .. ": samples bit-exact")
|
||||
t:eq(a.meta.source.codec, "alac", c.name .. ": codec")
|
||||
end
|
||||
t:note("%d ffmpeg ALAC files decode bit-exactly", #Alac - 1)
|
||||
|
||||
-- AAC: against ffmpeg's float decode
|
||||
local worst = math.huge
|
||||
for _, c in Aac do
|
||||
if c.container ~= "m4a" then
|
||||
continue
|
||||
end
|
||||
local a, err = M4a.decode(reader(c.data))
|
||||
t:check(a, c.name .. ": " .. tostring(err))
|
||||
t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format")
|
||||
t:eq(a.frames, c.frames, c.name .. ": gapless length")
|
||||
local s = snr(a, c.ref)
|
||||
worst = math.min(worst, s)
|
||||
t:check(s > 90, string.format("%s: SNR %.1f dB vs ffmpeg", c.name, s))
|
||||
t:note("%s: %d ch %d Hz, %d frames, SNR %.1f dB vs ffmpeg", c.name, c.channels, c.rate, a.frames, s)
|
||||
end
|
||||
|
||||
-- HE-AAC: the AAC-LC core at half the rate, SBR seen
|
||||
for _, c in He do
|
||||
if string.sub(c.name, -4) ~= ".m4a" then
|
||||
continue
|
||||
end
|
||||
local dec, err = M4a.open(reader(c.data))
|
||||
t:check(dec, c.name .. ": " .. tostring(err))
|
||||
t:eq(dec.sampleRate, c.rate // 2, c.name .. ": core rate")
|
||||
local b, n = dec:read(8192)
|
||||
local e = 0
|
||||
for i = 0, n * dec.channels - 1 do
|
||||
e += buffer.readf32(b, i * 4) ^ 2
|
||||
end
|
||||
t:check(n == 8192 and e > 1, c.name .. ": the core decodes (energy " .. e .. ")")
|
||||
end
|
||||
|
||||
-- our ALAC writer: the bytes ffmpeg validated
|
||||
do
|
||||
local byName = {}
|
||||
for _, o in Ours do
|
||||
byName[o.name] = o
|
||||
end
|
||||
for _, c in Cases do
|
||||
if c.container ~= "m4a" then
|
||||
continue
|
||||
end
|
||||
local o = byName[c.name]
|
||||
t:check(o and o.ffmpeg and o.mp4box and o.codec == "alac", c.name .. ": ffmpeg decoded it bit-exactly, MP4Box read it")
|
||||
t:eq(o.frames, c.frames, c.name .. ": ffmpeg's length")
|
||||
local a = Signal.audio(c.rate, c.frames, c.channels, c.bits, c.seed)
|
||||
a.tags = c.tags or {}
|
||||
local file, err = M4a.encode(a, { bitDepth = c.bits })
|
||||
t:check(file, c.name .. ": encode: " .. tostring(err))
|
||||
t:eq(string.format("%08x", Crc32.of(file :: buffer)), string.format("%08x", o.crc), c.name .. ": the validated bytes")
|
||||
-- and our own decoder gets the integers back
|
||||
local back = M4a.decode(Bytes.reader(file :: buffer)) :: any
|
||||
local ints = Signal.ints(c.frames, c.channels, c.bits, c.seed)
|
||||
local ok = back.frames == c.frames
|
||||
local scale = 2 ^ (c.bits - 1)
|
||||
for i = 1, #ints, 7 do
|
||||
ok = ok and math.floor(buffer.readf32(back.samples, (i - 1) * 4) * scale + 0.5) == ints[i]
|
||||
end
|
||||
t:check(ok, c.name .. ": round trip")
|
||||
if c.tags then
|
||||
for k, v in c.tags do
|
||||
t:eq(back.tags[k], v, c.name .. ": tag " .. k)
|
||||
end
|
||||
t:eq(o.tags.title, c.tags.title, c.name .. ": ffprobe title")
|
||||
t:eq(o.tags.track, c.tags.track .. "/" .. c.tags.tracktotal, c.name .. ": ffprobe track")
|
||||
t:eq(o.tags.artist, c.tags.artist, c.name .. ": ffprobe artist")
|
||||
end
|
||||
t:note("%s: %d bytes (%.0f%% of PCM)", c.name, buffer.len(file :: buffer), 100 * buffer.len(file :: buffer) / (c.frames * c.channels * c.bits / 8))
|
||||
end
|
||||
end
|
||||
|
||||
-- cover art + streaming a decoder into the encoder
|
||||
do
|
||||
local a = Signal.audio(44100, 5000, 2, 16, 9)
|
||||
a.meta.pictures = { { mime = "image/png", data = buffer.fromstring("\137PNG fake") } }
|
||||
a.tags = { title = "Pic" }
|
||||
local file = M4a.encode(a) :: buffer
|
||||
local back = M4a.decode(Bytes.reader(file)) :: any
|
||||
t:check(back.meta.pictures and #back.meta.pictures == 1 and back.meta.pictures[1].mime == "image/png", "cover art round trip")
|
||||
local dec = M4a.open(Bytes.reader(file)) :: any
|
||||
local again = M4a.encode(dec) :: buffer
|
||||
local back2 = M4a.decode(Bytes.reader(again)) :: any
|
||||
t:check(back2.frames == 5000 and buffer.tostring(back2.samples) == buffer.tostring(back.samples), "encode from a streaming decoder")
|
||||
local _, e = M4a.encode({} :: any)
|
||||
t:check(e and e.code == Err.ARG, "encode of a non-audio returns Err.ARG")
|
||||
local _, e2 = M4a.encode(a, { bitDepth = 12 })
|
||||
t:check(e2 and e2.code == Err.ARG, "bad bitDepth returns Err.ARG")
|
||||
end
|
||||
|
||||
-- streaming + seek (AAC without PNS: its noise is random, so a seek changes it; and ALAC)
|
||||
for _, c in { Aac[1], Alac[1] } do
|
||||
local whole = M4a.decode(reader(c.data)) :: any
|
||||
local dec = M4a.open(reader(c.data)) :: any
|
||||
t:eq(dec.frames, whole.frames, c.name .. ": decoder frames")
|
||||
-- read in odd chunks
|
||||
local got, out = 0, buffer.create(whole.frames * whole.channels * 4)
|
||||
while true do
|
||||
local b, n = dec:read(777)
|
||||
if n == 0 then
|
||||
break
|
||||
end
|
||||
buffer.copy(out, got * whole.channels * 4, b, 0, n * whole.channels * 4)
|
||||
got += n
|
||||
end
|
||||
t:check(got == whole.frames and buffer.tostring(out) == buffer.tostring(whole.samples), c.name .. ": chunked reads equal the whole decode")
|
||||
for _, at in { 0.1, 0.0, 0.05 } do
|
||||
dec:seek(at)
|
||||
local b, n = dec:read(500)
|
||||
local f0 = math.floor(at * whole.sampleRate + 0.5)
|
||||
local maxd = 0
|
||||
for i = 0, n * whole.channels - 1 do
|
||||
maxd = math.max(maxd, math.abs(buffer.readf32(b, i * 4) - buffer.readf32(whole.samples, (f0 * whole.channels + i) * 4)))
|
||||
end
|
||||
t:check(n == 500 and maxd < 1e-6, string.format("%s: seek %.2f s (max diff %g)", c.name, at, maxd))
|
||||
t:check(math.abs(dec:position() - (f0 + 500) / whole.sampleRate) < 1e-9, c.name .. ": position after seek")
|
||||
end
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local _, e = M4a.decode(reader("\0\0\0\8ftypM4A "))
|
||||
t:check(e ~= nil, "a lone ftyp: " .. tostring(e))
|
||||
local _, e2 = M4a.decode(reader("hello world, not an mp4"))
|
||||
t:check(e2 ~= nil and Err.is(e2), "junk: " .. tostring(e2))
|
||||
t:eq(M4a.sniff(reader("hello")), 0, "sniff junk")
|
||||
end
|
||||
|
||||
-- fuzz
|
||||
do
|
||||
local samples = {}
|
||||
for i, c in Alac do
|
||||
if c.container == "m4a" and i <= 2 then
|
||||
table.insert(samples, string.sub(c.data, 1, 12000))
|
||||
end
|
||||
end
|
||||
for i, c in Aac do
|
||||
if c.container == "m4a" and i <= 2 then
|
||||
table.insert(samples, string.sub(c.data, 1, 9000))
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return M4a.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 25 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -82,7 +82,7 @@ local rand = T.rng(12345)
|
||||
t:eq(Mp3.name, "mp3", "name")
|
||||
t:eq(Mp3.category, "audio", "category")
|
||||
t:check(table.find(Mp3.extensions, "mp3") ~= nil and table.find(Mp3.extensions, "mp2") ~= nil, "extensions")
|
||||
t:check(Mp3.caps.decode and not Mp3.caps.encode and Mp3.open ~= nil, "caps")
|
||||
t:check(Mp3.caps.decode and Mp3.caps.encode and Mp3.open ~= nil, "caps") -- encode: ws-audio (tests/audio/mp3_encode.luau)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode vs references
|
||||
for _, c in Cases do
|
||||
@@ -487,8 +487,8 @@ do
|
||||
t:check(a and a.kind == "audio" and a.frames == 22050 and a.tags.title == "Test Title", "F.audio.load: " .. tostring(err))
|
||||
local dec = F.audio.open(data)
|
||||
t:check(dec and dec.sampleRate == 44100 and dec.frames == 22050, "F.audio.open")
|
||||
local _, serr = F.save(a, nil, { format = "mp3" })
|
||||
t:check(serr and serr.code == Err.UNSUPPORTED, "F.save mp3: read-only")
|
||||
local saved, serr = F.save(a, nil, { format = "mp3" }) -- the layer III encoder (ws-audio)
|
||||
t:check(saved and F.audio.load(saved).sampleRate == 44100, "F.save mp3: " .. tostring(serr))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ fuzz
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
-- audio/mp3 encoder tests (layer III and layer II): every fixture-step encode (sample rates of MPEG-1 / 2 / 2.5,
|
||||
-- bit rates 24 .. 384 kbps, stereo / joint / mono) decodes in ffmpeg without errors and in LAME, with the expected
|
||||
-- length and an SNR over a per-bit-rate floor after aligning the decoder delay; our own decoder (the minimp3 port)
|
||||
-- agrees; streaming from a Decoder gives the same bytes; the ID3v2 tag round-trips; option errors.
|
||||
-- Fixtures: tools/fixtures/mp3_enc.py.
|
||||
local T = require("@tests/T")
|
||||
local Mp3 = require("@formats/audio/mp3")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/Pcm")
|
||||
local Enc = require("@tests/gen/mp3_enc")
|
||||
local Sigs = require("@tests/gen/mp3_enc_sigs")
|
||||
|
||||
local t = T.suite("mp3_encode")
|
||||
|
||||
local function audio(name: string): Types.Audio
|
||||
local s = Sigs[name]
|
||||
local a = Types.Audio.new(s.rate, s.channels, s.frames)
|
||||
buffer.writestring(a.samples, 0, s.data)
|
||||
return a
|
||||
end
|
||||
|
||||
-- SNR of y (delayed by lag frames) against x over frames [from, to)
|
||||
local function snr(x: Types.Audio, y: Types.Audio, lag: number, from: number, to: number): number
|
||||
local ch = x.channels
|
||||
local sig, er = 0, 0
|
||||
for i = from, to - 1 do
|
||||
local j = i + lag
|
||||
if j >= 0 and j < y.frames then
|
||||
for c = 0, ch - 1 do
|
||||
local a = buffer.readf32(x.samples, (i * ch + c) * 4)
|
||||
local b = buffer.readf32(y.samples, (j * y.channels + math.min(c, y.channels - 1)) * 4)
|
||||
sig += a * a
|
||||
er += (a - b) * (a - b)
|
||||
end
|
||||
end
|
||||
end
|
||||
if er == 0 then
|
||||
return 200
|
||||
end
|
||||
return if sig > 0 then 10 * math.log10(sig / er) else -200
|
||||
end
|
||||
|
||||
-- the SNR floors (dB) on the music / sine / sweep signals, by layer and bit rate per channel
|
||||
local function floorFor(e: any): number
|
||||
if string.find(e.name, "silence", 1, true) then
|
||||
return -math.huge
|
||||
elseif string.find(e.name, "noise", 1, true) then
|
||||
return 8 -- white noise has no spectral structure to exploit
|
||||
end
|
||||
local perCh = e.bitrate / (if e.mode == "mono" then 1 else 2)
|
||||
local nyquistBand = e.rate <= 16000 -- low rates lose little to the encoder's band limit
|
||||
if e.layer == 3 then
|
||||
if perCh >= 64 then
|
||||
return 14
|
||||
elseif perCh >= 32 or nyquistBand then
|
||||
return 8
|
||||
end
|
||||
return 4
|
||||
end
|
||||
if perCh >= 96 then
|
||||
return 14
|
||||
elseif perCh >= 48 then
|
||||
return 8
|
||||
end
|
||||
return 4
|
||||
end
|
||||
|
||||
t:check(Mp3.caps.encode and Mp3.encode ~= nil, "caps.encode")
|
||||
|
||||
local minByLayer = { [2] = math.huge, [3] = math.huge }
|
||||
for _, e in Enc do
|
||||
t:eq(e.ffErrors, "", e.name .. ": ffmpeg decodes without errors")
|
||||
t:check(e.ffRate == e.rate, e.name .. ": rate")
|
||||
t:check(e.ffChannels == (if e.mode == "mono" then 1 else 2), e.name .. ": channels")
|
||||
-- the stream covers the input: the encoder adds one frame of flush and the filterbank delay
|
||||
local spf = if e.layer == 3 and e.rate < 32000 then 576 else 1152
|
||||
t:check(e.ffFrames >= e.frames and e.ffFrames <= e.frames + 3 * spf, string.format("%s: %d decoded frames for %d", e.name, e.ffFrames, e.frames))
|
||||
local f = floorFor(e)
|
||||
t:check(e.ffSnr >= f, string.format("%s: ffmpeg SNR %.1f dB (floor %g)", e.name, e.ffSnr, f))
|
||||
if e.lameSnr then
|
||||
t:check(e.lameSnr >= f, string.format("%s: LAME SNR %.1f dB (floor %g)", e.name, e.lameSnr, f))
|
||||
end
|
||||
if f > -math.huge then
|
||||
minByLayer[e.layer] = math.min(minByLayer[e.layer], e.ffSnr)
|
||||
end
|
||||
-- our decoder agrees with ffmpeg
|
||||
local x = audio(e.sig)
|
||||
local y, err = Mp3.decode(Bytes.reader(buffer.fromstring(e.data)))
|
||||
t:check(y, e.name .. ": our decoder: " .. tostring(err))
|
||||
if e.channels == y.channels then
|
||||
local s = snr(x, y, e.ffLag, 200, x.frames)
|
||||
t:check(s >= f and math.abs(s - e.ffSnr) < 3, string.format("%s: our decoder %.1f dB, ffmpeg %.1f dB", e.name, s, e.ffSnr))
|
||||
end
|
||||
end
|
||||
t:note("%d encodes: ffmpeg + LAME decode them; lowest SNR layer III %.1f dB, layer II %.1f dB", #Enc, minByLayer[3], minByLayer[2])
|
||||
|
||||
-- streaming, tags, defaults
|
||||
do
|
||||
local a = audio("music_2_44100")
|
||||
local f1 = Mp3.encode(a, { bitrate = 128 }) :: buffer
|
||||
local f2 = Mp3.encode(Pcm.audioDecoder(a), { bitrate = 128 }) :: buffer
|
||||
t:check(buffer.tostring(f1) == buffer.tostring(f2), "Decoder source = Audio source")
|
||||
a.tags = { title = "Ünïcode title", artist = "An Artist", album = "Album", track = "4", comment = "made here" }
|
||||
local f3 = Mp3.encode(a, { layer = 2 }) :: buffer
|
||||
t:eq(buffer.readstring(f3, 0, 3), "ID3", "an ID3v2 tag in front")
|
||||
local back = Mp3.open(Bytes.reader(f3)) :: any
|
||||
t:eq(back.tags.title, "Ünïcode title", "title")
|
||||
t:eq(back.tags.artist, "An Artist", "artist")
|
||||
t:eq(back.tags.album, "Album", "album")
|
||||
t:eq(back.tags.track, "4", "track")
|
||||
t:eq(back.layer, 2, "layer II by default bit rate 192")
|
||||
local f4 = Mp3.encode(a, { id3 = false }) :: buffer
|
||||
t:check(buffer.readu8(f4, 0) == 0xFF, "id3 = false")
|
||||
local m = Types.Audio.new(22050, 1, 3000)
|
||||
local fm = Mp3.encode(m) :: buffer
|
||||
local dm = Mp3.open(Bytes.reader(fm)) :: any
|
||||
t:check(dm.channels == 1 and dm.sampleRate == 22050, "mono MPEG-2 default")
|
||||
local empty = Mp3.encode(Types.Audio.new(44100, 2, 0)) :: buffer
|
||||
t:check(empty and buffer.len(empty) > 0, "empty input: one flush frame")
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local function code(v: any, o: any): string?
|
||||
local _, e = Mp3.encode(v, o)
|
||||
return e and e.code
|
||||
end
|
||||
local a = Types.Audio.new(44100, 2, 100)
|
||||
t:eq(code({}, nil), Err.ARG, "junk")
|
||||
t:eq(code(a, { layer = 1 }), Err.ARG, "layer I")
|
||||
t:eq(code(a, { bitrate = 100 }), Err.ARG, "100 kbps")
|
||||
t:eq(code(a, { mode = "dual" }), Err.ARG, "dual mode")
|
||||
t:eq(code(Types.Audio.new(44000, 2, 10), nil), Err.ARG, "44 kHz")
|
||||
t:eq(code(Types.Audio.new(8000, 2, 10), { layer = 2 }), Err.ARG, "layer II at 8 kHz")
|
||||
t:eq(code(Types.Audio.new(44100, 3, 10), nil), Err.ARG, "3 channels")
|
||||
t:eq(code(a, { layer = 2, bitrate = 32 }), Err.ARG, "layer II stereo at 32 kbps")
|
||||
t:eq(code(Types.Audio.new(44100, 1, 10), { layer = 2, bitrate = 320 }), Err.ARG, "layer II mono at 320 kbps")
|
||||
end
|
||||
|
||||
-- (the decoder's fuzz pass is in tests/audio/mp3.luau; the encoders take no untrusted bytes)
|
||||
t:done()
|
||||
@@ -81,7 +81,7 @@ end
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
t:eq(Opus.name, "opus", "name")
|
||||
t:eq(Opus.category, "audio", "category")
|
||||
t:check(Opus.caps.decode and not Opus.caps.encode and Opus.open ~= nil and Opus.decode ~= nil, "caps")
|
||||
t:check(Opus.caps.decode and Opus.caps.encode and Opus.open ~= nil and Opus.decode ~= nil and Opus.encode ~= nil, "caps (the CELT encoder: tests/audio/opus_encode.luau)")
|
||||
t:eq(Opus.sniff(Bytes.reader(FX.celt_st_128.data)), 1, "sniff an Opus file")
|
||||
t:eq(Opus.sniff(Bytes.reader(buffer.fromstring("OggS" .. string.rep("\0", 40)))), 0, "sniff another Ogg")
|
||||
t:eq(Opus.sniff(Bytes.reader(buffer.create(0))), 0, "sniff nothing")
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
-- audio/opus encoder tests (the CELT-only writer, ws-m4a; mono and mid / side stereo): our Ogg Opus files (re-encoded here, compared with the bytes
|
||||
-- checked in the fixture step) decode in libopus' opusdec to the input's exact length (pre-skip + end trimming) with a
|
||||
-- minimum SNR, opusinfo finds no problem, ffmpeg reads them, OpusTags carry the tags; our decoder agrees with opusdec;
|
||||
-- resampled 44.1 kHz input; silence frames; streaming input; errors; a fuzz no-throw pass over our files.
|
||||
-- Fixtures: tools/fixtures/opus_celt.py.
|
||||
local T = require("@tests/T")
|
||||
local Opus = require("@formats/audio/opus")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Cases = require("@tests/audio/_opus_cases")
|
||||
local Fx = require("@tests/gen/opus_celt")
|
||||
|
||||
local t = T.suite("opus-encode")
|
||||
|
||||
t:check(Opus.caps.encode and Opus.encode ~= nil, "caps: encode")
|
||||
|
||||
local byName = {}
|
||||
for _, f in Fx do
|
||||
byName[f.name] = f
|
||||
end
|
||||
|
||||
local function snr(ref: buffer, refBase: number, got: buffer, n: number): number
|
||||
local s, e = 0, 0
|
||||
for i = 0, n - 1 do
|
||||
local x = buffer.readf32(ref, (refBase + i) * 4)
|
||||
local d = buffer.readf32(got, (refBase + i) * 4) - x
|
||||
s += x * x
|
||||
e += d * d
|
||||
end
|
||||
return if e == 0 then math.huge else 10 * math.log10(s / math.max(e, 1e-30))
|
||||
end
|
||||
|
||||
local files = {}
|
||||
for _, c in Cases.list do
|
||||
local fx = byName[c.name]
|
||||
t:check(fx, c.name .. ": fixture")
|
||||
local input = Cases.signal(c)
|
||||
local file, err = Opus.encode(input, { bitrate = c.bitrate })
|
||||
t:check(file, c.name .. ": encode: " .. tostring(err))
|
||||
table.insert(files, file)
|
||||
t:eq(string.format("%08x", Crc32.of(file :: buffer)), string.format("%08x", fx.crc), c.name .. ": the bytes the reference tools checked")
|
||||
t:check(fx.opusinfo, c.name .. ": opusinfo reports no problem")
|
||||
t:check(fx.ffmpeg, c.name .. ": ffmpeg decodes it")
|
||||
local frames48 = math.floor(input.frames * 48000 / c.rate + 0.5)
|
||||
local ch = c.channels
|
||||
t:eq(#fx.opusdec // (4 * ch), frames48, c.name .. ": opusdec length = the input's (pre-skip + end trimming)")
|
||||
t:eq(fx.ffmpegFrames, frames48, c.name .. ": ffmpeg length")
|
||||
-- our decoder vs opusdec
|
||||
local ours = Opus.decode(Bytes.reader(file :: buffer)) :: any
|
||||
t:eq(ours.frames, frames48, c.name .. ": our decoder's length")
|
||||
local ref = buffer.fromstring(fx.opusdec)
|
||||
local agree = snr(ref, 0, ours.samples, frames48 * ch)
|
||||
t:check(agree > 60, string.format("%s: our decoder vs opusdec %.1f dB", c.name, agree))
|
||||
-- quality vs the input (48 kHz inputs; skip the edges)
|
||||
if c.rate == 48000 and frames48 > 4000 then
|
||||
local s = snr(input.samples, 960 * ch, ref, (frames48 - 1920) * ch)
|
||||
t:check(s >= c.minSnr, string.format("%s: SNR %.1f dB (minimum %d)", c.name, s, c.minSnr))
|
||||
t:note("%s: %d bytes, SNR %.1f dB vs the input, our decoder vs opusdec %.1f dB", c.name, buffer.len(file :: buffer), s, agree)
|
||||
end
|
||||
if c.tags then
|
||||
for k, v in c.tags do
|
||||
t:eq(fx.comments[k], v, c.name .. ": opusinfo comment " .. k)
|
||||
t:eq(ours.tags[k], v, c.name .. ": our tag " .. k)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- silence frames decode to silence
|
||||
do
|
||||
local c = Cases.list[1]
|
||||
local ref = buffer.fromstring(byName[c.name].opusdec)
|
||||
local peak = 0
|
||||
for i = math.floor(0.62 * 48000), math.floor(0.73 * 48000) do
|
||||
peak = math.max(peak, math.abs(buffer.readf32(ref, i * 4)))
|
||||
end
|
||||
t:check(peak < 1e-3, "digital silence stays silent (peak " .. peak .. ")")
|
||||
end
|
||||
|
||||
-- a streaming decoder as the input
|
||||
do
|
||||
local c = Cases.list[1]
|
||||
local dec = Opus.open(Bytes.reader(files[1] :: buffer)) :: any
|
||||
local again, err = Opus.encode(dec, { bitrate = 64000 })
|
||||
t:check(again, "encode from a decoder: " .. tostring(err))
|
||||
local back = Opus.decode(Bytes.reader(again :: buffer)) :: any
|
||||
t:eq(back.frames, math.floor(c.seconds * 48000 + 0.5), "re-encoded length")
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local three = Cases.signal({ rate = 48000, channels = 3, seconds = 0.05 })
|
||||
local _, e = Opus.encode(three)
|
||||
t:check(e and e.code == Err.UNSUPPORTED, "3 channels: " .. tostring(e))
|
||||
local _, e2 = Opus.encode(Cases.signal(Cases.list[6]), { bitrate = 1000 })
|
||||
t:check(e2 and e2.code == Err.ARG, "bitrate too low")
|
||||
local _, e3 = Opus.encode({} :: any)
|
||||
t:check(e3 and e3.code == Err.ARG, "not audio")
|
||||
end
|
||||
|
||||
-- fuzz the decoder over our files
|
||||
do
|
||||
local samples = {}
|
||||
for i, f in files do
|
||||
if i <= 3 then
|
||||
table.insert(samples, string.sub(buffer.tostring(f :: buffer), 1, 4000))
|
||||
end
|
||||
end
|
||||
t:fuzz("decode our files", function(b: buffer)
|
||||
return Opus.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 10, garbage = 30 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,129 @@
|
||||
-- audio/voc tests: files written by ffmpeg (type 1 + 8 blocks for 8-bit, type 9 otherwise) and sox against ffmpeg's
|
||||
-- decode; silence / text / continuation blocks and repeat markers built here; streaming reads and seeks; our
|
||||
-- encoder's output for every sample format decoded by ffmpeg (fixture step) and by us; errors; fuzz.
|
||||
-- Fixtures: tools/fixtures/voc.py.
|
||||
local T = require("@tests/T")
|
||||
local Voc = require("@formats/audio/voc")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Cases = require("@tests/gen/voc_cases")
|
||||
local Enc = require("@tests/gen/voc_enc")
|
||||
local Sig = require("@tests/gen/voc_sig")
|
||||
|
||||
local t = T.suite("voc")
|
||||
|
||||
local function reader(s: string): Bytes.Reader
|
||||
return Bytes.reader(buffer.fromstring(s))
|
||||
end
|
||||
local function maxDiff(a: buffer, ao: number, b: buffer, bo: number, n: number): number
|
||||
local m = 0
|
||||
for i = 0, n - 1 do
|
||||
local d = math.abs(buffer.readf32(a, ao + i * 4) - buffer.readf32(b, bo + i * 4))
|
||||
if d > m then
|
||||
m = d
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
t:eq(Voc.name, "voc", "name")
|
||||
t:eq(Voc.category, "audio", "category")
|
||||
t:check(Voc.caps.decode and Voc.caps.encode, "caps")
|
||||
|
||||
for _, c in Cases do
|
||||
local a, err = Voc.decode(reader(c.data))
|
||||
t:check(a, c.name .. ": " .. tostring(err))
|
||||
t:check(a.sampleRate == c.rate and a.channels == c.channels, string.format("%s: format %d Hz x %d, want %d x %d", c.name, a.sampleRate, a.channels, c.rate, c.channels))
|
||||
t:eq(a.frames, c.frames, c.name .. ": frames")
|
||||
local ref = buffer.fromstring(c.ref)
|
||||
t:check(maxDiff(a.samples, 0, ref, 0, c.frames * c.channels) < 1e-6, c.name .. ": samples match ffmpeg")
|
||||
local dec = Voc.open(reader(c.data)) :: Types.Decoder
|
||||
dec:seek(500 / c.rate)
|
||||
local b, k = dec:read(64)
|
||||
t:check(k == 64 and maxDiff(b, 0, ref, 500 * c.channels * 4, 64 * c.channels) < 1e-6, c.name .. ": seek")
|
||||
end
|
||||
t:note("%d reference files match ffmpeg", #Cases)
|
||||
|
||||
-- hand-built blocks: text, type 1 u8, silence, continuation, repeat markers, terminator
|
||||
do
|
||||
local hdr = "Creative Voice File\26\26\0\10\1\41\17"
|
||||
local function blk(typ: number, payload: string): string
|
||||
local n = #payload
|
||||
return string.char(typ, n % 256, (n // 256) % 256, n // 65536) .. payload
|
||||
end
|
||||
local data = hdr
|
||||
.. blk(5, "made by hand\0")
|
||||
.. blk(1, string.char(156, 0) .. string.char(128, 192, 64)) -- 10 kHz, 3 samples
|
||||
.. blk(3, string.char(4, 0, 156)) -- 5 frames of silence
|
||||
.. blk(6, string.char(2, 0)) -- repeat start (ignored)
|
||||
.. blk(2, string.char(255, 0)) -- continuation
|
||||
.. blk(7, "") -- repeat end
|
||||
.. blk(4, string.char(1, 0)) -- marker
|
||||
.. "\0"
|
||||
local a, err = Voc.decode(reader(data))
|
||||
t:check(a, "hand-built: " .. tostring(err))
|
||||
t:check(a.sampleRate == 10000 and a.channels == 1 and a.frames == 10, "hand-built: 10 kHz, 3 + 5 + 2 frames")
|
||||
t:eq(a.tags.comment, "made by hand", "text block")
|
||||
local want = { 0, 0.5, -0.5, 0, 0, 0, 0, 0, 127 / 128, -1 }
|
||||
local ok = true
|
||||
for i, v in want do
|
||||
ok = ok and buffer.readf32(a.samples, (i - 1) * 4) == v
|
||||
end
|
||||
t:check(ok, "hand-built samples")
|
||||
-- no terminator, a block cut short: the data present
|
||||
local cut = Voc.decode(reader(string.sub(data, 1, 26 + 17 + 4 + 2 + 2)))
|
||||
t:check(cut and cut.frames == 2 and cut.meta.source.truncated, "cut in a block")
|
||||
-- Creative ADPCM: unsupported
|
||||
local _, e = Voc.decode(reader(hdr .. blk(1, string.char(156, 1) .. "\0\0") .. "\0"))
|
||||
t:check(e and e.code == Err.UNSUPPORTED, "ADPCM: UNSUPPORTED")
|
||||
local _, e2 = Voc.decode(reader(hdr .. blk(2, "\0\0") .. "\0"))
|
||||
t:check(e2 and e2.code == Err.CORRUPT, "continuation first: CORRUPT")
|
||||
local _, e3 = Voc.decode(reader(hdr .. "\0"))
|
||||
t:check(e3 and e3.code == Err.CORRUPT, "no sound: CORRUPT")
|
||||
local _, e4 = Voc.decode(reader("Creative Voice Fil"))
|
||||
t:check(e4 and e4.code == Err.CORRUPT, "short: CORRUPT")
|
||||
t:eq(Voc.sniff(reader(data)), 1, "sniff")
|
||||
t:eq(Voc.sniff(reader(".snd")), 0, "sniff other")
|
||||
end
|
||||
|
||||
local TOL = { s16 = 0.5 / 32768, ["s16-mono"] = 0.5 / 32768, u8 = 0.5 / 128, ulaw = 0.04, alaw = 0.04 }
|
||||
local sig = buffer.fromstring(Sig.data)
|
||||
for _, e in Enc do
|
||||
t:eq(e.ffmpegErrors, "", e.name .. ": ffmpeg reads our file without errors")
|
||||
t:check(e.frames == Sig.frames and e.rate == Sig.rate, e.name .. ": ffmpeg frames / rate")
|
||||
t:check(e.maxDiff <= TOL[e.name] + 1e-7, string.format("%s: ffmpeg decode within %g (max diff %g)", e.name, TOL[e.name], e.maxDiff))
|
||||
t:check(e.sameStreamed, e.name .. ": encoding a Decoder gives the same bytes")
|
||||
local back = Voc.decode(reader(e.data)) :: Types.Audio
|
||||
t:check(back and back.frames == Sig.frames and back.channels == e.channels, e.name .. ": our decoder reads our file")
|
||||
if e.channels == 2 then
|
||||
t:check(maxDiff(back.samples, 0, sig, 0, Sig.frames * 2) <= TOL[e.name] + 1e-7, e.name .. ": round trip")
|
||||
end
|
||||
end
|
||||
t:note("%d encoder outputs read back by ffmpeg and by us", #Enc)
|
||||
|
||||
do
|
||||
local a = Types.Audio.new(22050, 2, 1)
|
||||
a.tags = { comment = "hi" }
|
||||
local b = Voc.encode(a) :: buffer
|
||||
local back = Voc.decode(Bytes.reader(b)) :: Types.Audio
|
||||
t:check(back.frames == 1 and back.tags.comment == "hi", "one frame + comment")
|
||||
local _, e1 = Voc.encode(nil :: any)
|
||||
t:check(e1 and e1.code == Err.ARG, "encode nil: ARG")
|
||||
local _, e2 = Voc.encode(a, { sampleFormat = "s24" } :: any)
|
||||
t:check(e2 and e2.code == Err.ARG, "bad sampleFormat: ARG")
|
||||
local _, e3 = Voc.decode(reader(Cases[1].data), { maxFrames = 5 })
|
||||
t:check(e3 and e3.code == Err.LIMIT, "maxFrames: LIMIT")
|
||||
end
|
||||
|
||||
do
|
||||
local samples = {}
|
||||
for _, c in Cases do
|
||||
table.insert(samples, string.sub(c.data, 1, 300))
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Voc.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 30 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,193 @@
|
||||
-- audio/vorbis tests: oggenc / ffmpeg streams (qualities -1 .. 10, managed bitrate, 8 .. 96 kHz, mono / stereo / 5.1,
|
||||
-- transients, silence, tags, sub-block lengths) against oggdec (libvorbisfile: sample counts and 16-bit samples, so
|
||||
-- start / end trimming is exact) and ffmpeg's f32 decode (SNR); streaming reads; seeking (sample-exact against the
|
||||
-- reference at the target); the packet-level decoder; errors; fuzz. Fixtures: tools/fixtures/vorbis.py.
|
||||
local T = require("@tests/T")
|
||||
local Vorbis = require("@formats/audio/vorbis")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Ogg = require("@formats/containers/Ogg")
|
||||
local Cases = require("@tests/gen/vorbis_cases")
|
||||
|
||||
local t = T.suite("vorbis")
|
||||
|
||||
local function reader(s: string): Bytes.Reader
|
||||
return Bytes.reader(buffer.fromstring(s))
|
||||
end
|
||||
local function s16(x: number): number
|
||||
local v = math.floor(x * 32768 + 0.5)
|
||||
return math.clamp(v, -32768, 32767)
|
||||
end
|
||||
-- the largest |our sample as s16 - oggdec's| over n samples of ours at byte a0 against ref16 from sample r0
|
||||
local function maxDiff16(a: buffer, a0: number, ref: buffer, r0: number, n: number): number
|
||||
local m = 0
|
||||
for i = 0, n - 1 do
|
||||
local d = math.abs(s16(buffer.readf32(a, a0 + i * 4)) - buffer.readi16(ref, (r0 + i) * 2))
|
||||
if d > m then
|
||||
m = d
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
local function snr(a: buffer, ref: buffer, n: number): number
|
||||
local sig, er = 0, 0
|
||||
for i = 0, n - 1 do
|
||||
local x = buffer.readf32(ref, i * 4)
|
||||
local d = x - buffer.readf32(a, i * 4)
|
||||
sig += x * x
|
||||
er += d * d
|
||||
end
|
||||
if er == 0 then
|
||||
return 200
|
||||
end
|
||||
return if sig > 0 then 10 * math.log10(sig / er) else -200
|
||||
end
|
||||
|
||||
t:eq(Vorbis.name, "vorbis", "name")
|
||||
t:eq(Vorbis.category, "audio", "category")
|
||||
t:check(Vorbis.caps.decode and Vorbis.open ~= nil, "caps")
|
||||
|
||||
local minSnr = math.huge
|
||||
for _, c in Cases do
|
||||
local a, err = Vorbis.decode(reader(c.data))
|
||||
t:check(a, c.name .. ": " .. tostring(err))
|
||||
t:check(a.sampleRate == c.rate and a.channels == c.channels, c.name .. ": format")
|
||||
t:eq(a.frames, c.frames, c.name .. ": frames = oggdec's")
|
||||
t:eq(a.frames, c.inputFrames, c.name .. ": frames = the encoder's input")
|
||||
local ref16 = buffer.fromstring(c.ref16)
|
||||
local n = c.frames * c.channels
|
||||
local d = maxDiff16(a.samples, 0, ref16, 0, n)
|
||||
t:check(d <= 1, string.format("%s: within 1 LSB of oggdec (max %d)", c.name, d))
|
||||
if c.ffRef then
|
||||
local s = snr(a.samples, buffer.fromstring(c.ffRef), n)
|
||||
minSnr = math.min(minSnr, s)
|
||||
t:check(s > 100, string.format("%s: SNR vs ffmpeg %.1f dB", c.name, s))
|
||||
end
|
||||
-- streaming in odd chunks gives the same samples
|
||||
local dec = Vorbis.open(reader(c.data)) :: Types.Decoder
|
||||
t:eq(dec.frames, c.frames, c.name .. ": Decoder.frames")
|
||||
local got, ok = 0, true
|
||||
while true do
|
||||
local b, k = dec:read(1013)
|
||||
if k == 0 then
|
||||
break
|
||||
end
|
||||
for i = 0, k * c.channels - 1, 7 do
|
||||
ok = ok and buffer.readf32(b, i * 4) == buffer.readf32(a.samples, got * c.channels * 4 + i * 4)
|
||||
end
|
||||
got += k
|
||||
end
|
||||
t:check(ok and got == c.frames, c.name .. ": streamed reads")
|
||||
-- seeks: sample-exact against the full decode
|
||||
for _, frac in { 0.5, 0.1, 0.93, 0 } do
|
||||
local target = math.floor(c.frames * frac)
|
||||
dec:seek(target / c.rate)
|
||||
t:check(math.abs(dec:position() - target / c.rate) < 1e-9, c.name .. ": position after seek")
|
||||
local b, k = dec:read(300)
|
||||
local want = math.min(300, c.frames - target)
|
||||
t:eq(k, want, string.format("%s: frames after seek to %d", c.name, target))
|
||||
local same = true
|
||||
for i = 0, k * c.channels - 1 do
|
||||
same = same and buffer.readf32(b, i * 4) == buffer.readf32(a.samples, (target * c.channels + i) * 4)
|
||||
end
|
||||
t:check(same, string.format("%s: samples after seek to %d", c.name, target))
|
||||
end
|
||||
end
|
||||
t:note("%d streams match oggdec (counts, 1 LSB) and ffmpeg (min SNR %.1f dB)", #Cases, minSnr)
|
||||
|
||||
local function case(name: string): any
|
||||
for _, c in Cases do
|
||||
if c.name == name then
|
||||
return c
|
||||
end
|
||||
end
|
||||
error("no case " .. name)
|
||||
end
|
||||
|
||||
-- tags, meta, sniff, sub-range
|
||||
do
|
||||
local c = case("q2-stereo-32k-tags")
|
||||
local dec = Vorbis.open(reader(c.data)) :: any
|
||||
t:eq(dec.tags.title, "A Title", "title tag")
|
||||
t:eq(dec.tags.artist, "An Artist", "artist tag")
|
||||
t:eq(dec.tags.album, "The Album", "album tag")
|
||||
t:eq(dec.tags.track, "7", "track tag")
|
||||
t:eq(dec.tags.comment, "hello vorbis", "comment tag")
|
||||
t:check(type(dec.vendor) == "string" and string.find(dec.vendor, "Xiph", 1, true) ~= nil, "vendor")
|
||||
t:check(dec.bitrate > 0 and math.abs(dec.duration - c.frames / c.rate) < 1e-9, "bitrate / duration")
|
||||
t:eq(Vorbis.sniff(reader(c.data)), 1, "sniff")
|
||||
t:eq(Vorbis.sniff(reader("OggS")), 0, "sniff short")
|
||||
t:eq(Vorbis.sniff(reader("RIFF")), 0, "sniff other")
|
||||
local big = buffer.create(#c.data + 11)
|
||||
buffer.writestring(big, 11, c.data)
|
||||
local a = Vorbis.decode(Bytes.reader(big, 11, #c.data))
|
||||
t:check(a and a.frames == c.frames, "decode from a sub-range")
|
||||
end
|
||||
|
||||
-- the packet-level decoder (as Matroska / MP4 would use it) gives the same samples, minus the Ogg trimming
|
||||
do
|
||||
local c = case("q5-stereo-44k-music")
|
||||
local full = Vorbis.decode(reader(c.data)) :: Types.Audio
|
||||
local demux = Ogg.open(buffer.fromstring(c.data))
|
||||
local serial = demux:find("vorbis")
|
||||
local h = {}
|
||||
for i = 1, 3 do
|
||||
h[i] = Ogg.copy(demux:nextPacket(serial))
|
||||
end
|
||||
local pd = Vorbis.packetDecoder(h[1], h[2], h[3])
|
||||
t:check(pd and pd.channels == 2 and pd.sampleRate == 44100, "packetDecoder")
|
||||
local total, same = 0, true
|
||||
for p in demux:packets(serial) do
|
||||
local n = pd:decode(p.data, p.offset, p.size)
|
||||
for i = 1, n, 13 do
|
||||
if total + i <= full.frames then
|
||||
same = same and math.abs(pd.out[1][i] - buffer.readf32(full.samples, (total + i - 1) * 8)) < 1e-6
|
||||
end
|
||||
end
|
||||
total += math.max(n, 0)
|
||||
end
|
||||
t:check(same and total >= full.frames, "packetDecoder samples")
|
||||
local _, e = Vorbis.packetDecoder(h[2], h[1], h[3])
|
||||
t:check(e and e.code == Err.CORRUPT, "packetDecoder with headers swapped")
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local _, e1 = Vorbis.decode(reader("OggS but not really"))
|
||||
t:check(e1 and Err.is(e1), "junk: " .. tostring(e1))
|
||||
local c = case("short-100").data
|
||||
local _, e2 = Vorbis.decode(reader(string.sub(c, 1, 60)))
|
||||
t:check(e2 and Err.is(e2), "cut in the headers: " .. tostring(e2))
|
||||
-- a truncated stream decodes what is there
|
||||
local q = case("q5-stereo-44k-music")
|
||||
local cut = Vorbis.decode(reader(string.sub(q.data, 1, #q.data // 2)), { verify = false })
|
||||
t:check(cut and cut.frames > 0 and cut.frames < q.frames, "truncated stream")
|
||||
end
|
||||
|
||||
-- fuzz: whole streams with mutations past the headers, truncations, garbage
|
||||
do
|
||||
local samples = {}
|
||||
for _, name in { "short-100", "short-3000-mono", "q-1-mono-8k-music", "ffmpeg-mono-16k" } do
|
||||
table.insert(samples, case(name).data)
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Vorbis.decode(Bytes.reader(b), { verify = false })
|
||||
end, samples, { mutations = 40 })
|
||||
t:fuzz("decode (CRC checked)", function(b: buffer)
|
||||
return Vorbis.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 5, garbage = 20 })
|
||||
t:fuzz("open + seek", function(b: buffer)
|
||||
local d = Vorbis.open(Bytes.reader(b), { verify = false })
|
||||
if d then
|
||||
d:read(500)
|
||||
d:seek(0.05)
|
||||
d:read(500)
|
||||
d:seek(1e9)
|
||||
d:read(10)
|
||||
end
|
||||
return d
|
||||
end, samples, { mutations = 10, garbage = 20 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,110 @@
|
||||
-- audio/vorbis encoder tests: every fixture-step encode (qualities -1 .. 10, mono / stereo / 5.1, 8 .. 96 kHz, odd
|
||||
-- lengths, silence) passes ogginfo, decodes in oggdec (libvorbisfile) with the exact input length and an SNR over a
|
||||
-- per-quality floor, and in ffmpeg; our own decoder gives the same; the codebooks are valid prefix codes; streaming
|
||||
-- from a Decoder gives the same bytes; tags round-trip; option errors. Fixtures: tools/fixtures/vorbis_enc.py.
|
||||
local T = require("@tests/T")
|
||||
local Vorbis = require("@formats/audio/vorbis")
|
||||
local VEnc = require("@formats/audio/vorbis/Encode")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/Pcm")
|
||||
local Enc = require("@tests/gen/vorbis_enc")
|
||||
local Sigs = require("@tests/gen/vorbis_enc_sigs")
|
||||
|
||||
local t = T.suite("vorbis_encode")
|
||||
|
||||
local function audio(name: string): Types.Audio
|
||||
local s = Sigs[name]
|
||||
local a = Types.Audio.new(s.rate, s.channels, s.frames)
|
||||
buffer.writestring(a.samples, 0, s.data)
|
||||
return a
|
||||
end
|
||||
local function snr(x: Types.Audio, y: Types.Audio): number
|
||||
local sig, er = 0, 0
|
||||
for i = 0, math.min(x.frames, y.frames) * x.channels - 1 do
|
||||
local a = buffer.readf32(x.samples, i * 4)
|
||||
local d = a - buffer.readf32(y.samples, i * 4)
|
||||
sig += a * a
|
||||
er += d * d
|
||||
end
|
||||
if er == 0 then
|
||||
return 200
|
||||
end
|
||||
return if sig > 0 then 10 * math.log10(sig / er) else -200
|
||||
end
|
||||
local function floorFor(q: number): number
|
||||
return 8 + 1.2 * math.max(q, 0)
|
||||
end
|
||||
|
||||
t:check(Vorbis.caps.encode and Vorbis.encode ~= nil, "caps.encode")
|
||||
|
||||
-- the codebooks: Kraft sums of exactly 1 (complete prefix codes) and lengths 1 .. 24
|
||||
for i, b in VEnc.BOOKS do
|
||||
local k, okLen = 0, true
|
||||
for _, l in b.lengths do
|
||||
k += 2 ^ -l
|
||||
okLen = okLen and l >= 1 and l <= 24
|
||||
end
|
||||
t:check(math.abs(k - 1) < 1e-9 and okLen, "codebook " .. (i - 1) .. ": complete prefix code")
|
||||
end
|
||||
|
||||
local minSnr = math.huge
|
||||
for _, e in Enc do
|
||||
t:eq(e.ogginfo, "", e.name .. ": ogginfo reports no warnings / errors")
|
||||
t:eq(e.oggdecFrames, e.frames, e.name .. ": oggdec frames = input frames")
|
||||
t:eq(e.ffErrors, "", e.name .. ": ffmpeg decodes without errors")
|
||||
local silent = string.find(e.name, "silence", 1, true) ~= nil
|
||||
local f = if silent then -math.huge else floorFor(e.quality)
|
||||
t:check(e.oggdecSnr >= f, string.format("%s: oggdec SNR %.1f dB (floor %.1f)", e.name, e.oggdecSnr, f))
|
||||
if e.frames >= 2048 then
|
||||
-- (ffmpeg does not trim the end of a stream that fits on one Ogg page: up to a block more)
|
||||
t:check(e.ffFrames >= e.frames and e.ffFrames <= e.frames + 1024, string.format("%s: ffmpeg frames %d", e.name, e.ffFrames))
|
||||
t:check(e.ffSnr >= f, string.format("%s: ffmpeg SNR %.1f dB", e.name, e.ffSnr))
|
||||
end
|
||||
if not silent then
|
||||
minSnr = math.min(minSnr, e.oggdecSnr)
|
||||
end
|
||||
-- our decoder: the same length and quality (it is sample-exact with libvorbis)
|
||||
local x = audio(e.sig)
|
||||
local y, err = Vorbis.decode(Bytes.reader(buffer.fromstring(e.data)))
|
||||
t:check(y, e.name .. ": our decoder: " .. tostring(err))
|
||||
t:eq(y.frames, e.frames, e.name .. ": our decoder's frames")
|
||||
local s = snr(x, y)
|
||||
t:check(math.abs(s - e.oggdecSnr) < 0.5 or s >= 100, string.format("%s: our decoder %.1f dB, oggdec %.1f dB", e.name, s, e.oggdecSnr))
|
||||
end
|
||||
t:note("%d encodes pass ogginfo / oggdec / ffmpeg; lowest SNR %.1f dB", #Enc, minSnr)
|
||||
|
||||
-- streaming, tags
|
||||
do
|
||||
local a = audio("music_2_3000_44100")
|
||||
local f1 = Vorbis.encode(a) :: buffer
|
||||
local f2 = Vorbis.encode(Pcm.audioDecoder(a)) :: buffer
|
||||
t:check(buffer.tostring(f1) == buffer.tostring(f2), "Decoder source = Audio source")
|
||||
a.tags = { title = "Tïtle", artist = "Artist", track = "9" }
|
||||
local f3 = Vorbis.encode(a, { quality = 1, serial = 77 }) :: buffer
|
||||
local d = Vorbis.open(Bytes.reader(f3)) :: any
|
||||
t:eq(d.tags.title, "Tïtle", "title tag")
|
||||
t:eq(d.tags.track, "9", "track tag")
|
||||
t:check(string.find(d.vendor, "formats-luau", 1, true) ~= nil, "vendor")
|
||||
local empty = Vorbis.encode(Types.Audio.new(44100, 1, 0)) :: buffer
|
||||
local e0 = Vorbis.decode(Bytes.reader(empty))
|
||||
t:check(e0 and e0.frames == 0, "empty input")
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local a = Types.Audio.new(44100, 2, 10)
|
||||
local function code(v: any, o: any): string?
|
||||
local _, e = Vorbis.encode(v, o)
|
||||
return e and e.code
|
||||
end
|
||||
t:eq(code("x", nil), Err.ARG, "junk")
|
||||
t:eq(code(a, { quality = 11 }), Err.ARG, "quality 11")
|
||||
t:eq(code(a, { quality = -2 }), Err.ARG, "quality -2")
|
||||
t:eq(code(a, { serial = -1 }), Err.ARG, "serial -1")
|
||||
t:eq(code(Types.Audio.new(44100.5, 1, 1), nil), Err.ARG, "fractional rate")
|
||||
end
|
||||
|
||||
-- (the decoder's fuzz pass is in tests/audio/vorbis.luau; the encoder takes no untrusted bytes)
|
||||
t:done()
|
||||
@@ -0,0 +1,182 @@
|
||||
-- codecs/Aac tests: AudioSpecificConfig parsing (every fixture's esds, explicit SBR / PS signalling from fdkaac,
|
||||
-- crafted configs: PCE channel counts, 960-sample frames, Main / LTP object types), ADTS headers, raw frames decoded
|
||||
-- straight from ADTS against ffmpeg's float decode, the FIL extension hook on HE-AAC (implicit SBR), reset, errors,
|
||||
-- the fuzz no-throw pass on raw frames. Fixtures: tools/fixtures/m4a.py.
|
||||
local T = require("@tests/T")
|
||||
local Aac = require("@formats/codecs/Aac")
|
||||
local IsoBmff = require("@formats/containers/IsoBmff")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Bits = require("@formats/core/Bits")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Fx = require("@tests/gen/m4a_aac")
|
||||
local He = require("@tests/gen/m4a_he")
|
||||
|
||||
local t = T.suite("aac-codec")
|
||||
|
||||
-- ADTS frames of a stream: { offset, size } of the raw blocks
|
||||
local function frames(data: buffer): ({ { number } }, Aac.Adts?)
|
||||
local out, p, first = {}, 0, nil
|
||||
while true do
|
||||
local h = Aac.adts(data, p, buffer.len(data))
|
||||
if not h or p + h.frameSize > buffer.len(data) then
|
||||
break
|
||||
end
|
||||
first = first or h
|
||||
table.insert(out, { p + h.headerSize, h.frameSize - h.headerSize })
|
||||
p += h.frameSize
|
||||
end
|
||||
return out, first
|
||||
end
|
||||
|
||||
-- ASCs from the M4A fixtures
|
||||
for _, c in Fx do
|
||||
if c.container == "m4a" then
|
||||
local r = Bytes.reader(buffer.fromstring(c.data))
|
||||
local movie = IsoBmff.parse(r) :: IsoBmff.Movie
|
||||
local cfg, err = Aac.config(movie.tracks[1].config :: buffer)
|
||||
t:check(cfg, c.name .. ": " .. tostring(err))
|
||||
t:check(cfg.objectType == 2 and cfg.sampleRate == c.rate and cfg.channels == c.channels and not cfg.sbr, c.name .. ": AAC-LC config")
|
||||
end
|
||||
end
|
||||
for _, c in He do
|
||||
if string.sub(c.name, -4) == ".m4a" then
|
||||
local r = Bytes.reader(buffer.fromstring(c.data))
|
||||
local movie = IsoBmff.parse(r) :: IsoBmff.Movie
|
||||
local cfg, err = Aac.config(movie.tracks[1].config :: buffer)
|
||||
t:check(cfg, c.name .. ": " .. tostring(err))
|
||||
t:check(cfg.sbr and cfg.sampleRate == c.rate // 2 and cfg.extensionRate == c.rate, c.name .. ": SBR signalled, core at half rate")
|
||||
t:eq(cfg.ps, c.ps, c.name .. ": PS signalled")
|
||||
end
|
||||
end
|
||||
|
||||
-- crafted configs
|
||||
do
|
||||
local asc = Aac.asc(2, 4, 2)
|
||||
local cfg = Aac.config(asc) :: Aac.Config
|
||||
t:check(cfg and cfg.sampleRate == 44100 and cfg.channels == 2, "asc(2, 44.1 kHz, stereo)")
|
||||
local _, e1 = Aac.config(Aac.asc(1, 4, 2))
|
||||
t:check(e1 and e1.code == Err.UNSUPPORTED, "AAC Main: " .. tostring(e1))
|
||||
local _, e2 = Aac.config(Aac.asc(23, 4, 2))
|
||||
t:check(e2 and e2.code == Err.UNSUPPORTED, "ER AAC LD")
|
||||
local b960 = Aac.asc(2, 3, 1)
|
||||
buffer.writeu8(b960, 1, bit32.bor(buffer.readu8(b960, 1), 4)) -- frameLengthFlag
|
||||
local _, e3 = Aac.config(b960)
|
||||
t:check(e3 and e3.code == Err.UNSUPPORTED, "960-sample frames")
|
||||
-- channel configuration 0 with a PCE: front C (SCE) + L/R (CPE), back L/R (CPE), one LFE = 6 channels
|
||||
local bw = Bits.msbWriter()
|
||||
bw:write(2, 5)
|
||||
bw:write(3, 4)
|
||||
bw:write(0, 4)
|
||||
bw:write(0, 3) -- GASpecificConfig flags
|
||||
bw:write(0, 4) -- PCE: tag
|
||||
bw:write(1, 2)
|
||||
bw:write(3, 4)
|
||||
bw:write(2, 4) -- front
|
||||
bw:write(0, 4) -- side
|
||||
bw:write(1, 4) -- back
|
||||
bw:write(1, 2) -- lfe
|
||||
bw:write(0, 3)
|
||||
bw:write(0, 4)
|
||||
bw:write(0, 3) -- mixdowns
|
||||
bw:write(0, 5)
|
||||
bw:write(16 + 1, 5) -- front: SCE 0, CPE 1
|
||||
bw:write(16 + 2, 5) -- back: CPE 2
|
||||
bw:write(0, 4) -- lfe tag
|
||||
bw:align()
|
||||
bw:write(0, 8) -- comment
|
||||
local pcfg, perr = Aac.config(bw:finish())
|
||||
t:check(pcfg and pcfg.channels == 6 and pcfg.channelConfig == 0, "PCE: 6 channels: " .. tostring(perr))
|
||||
local _, e4 = Aac.decoder("nope" :: any)
|
||||
t:check(e4 and e4.code == Err.ARG, "decoder of a string")
|
||||
end
|
||||
|
||||
-- ADTS headers + raw frames against ffmpeg
|
||||
for _, c in Fx do
|
||||
if c.container ~= "adts" then
|
||||
continue
|
||||
end
|
||||
local data = buffer.fromstring(c.data)
|
||||
local list, h = frames(data)
|
||||
t:check(h and h.objectType == 2 and h.sampleRate == c.rate, c.name .. ": ADTS header")
|
||||
local dec = Aac.decoder({ sfIndex = (h :: Aac.Adts).sfIndex, channels = c.channels }) :: Aac.Decoder
|
||||
local ref = buffer.fromstring(c.ref)
|
||||
local sig, err = 0, 0
|
||||
local o = 0
|
||||
for _, f in list do
|
||||
local n, e = dec:decode(data, f[1], f[2])
|
||||
t:check(n == 1024, c.name .. ": frame: " .. tostring(e))
|
||||
for k = 1, 1024 * c.channels do
|
||||
local r = buffer.readf32(ref, o)
|
||||
sig += r * r
|
||||
err += (dec.pcm[k] - r) ^ 2
|
||||
o += 4
|
||||
end
|
||||
end
|
||||
local snr = 10 * math.log10(sig / math.max(err, 1e-30))
|
||||
t:check(snr > 90, string.format("%s: SNR %.1f dB", c.name, snr))
|
||||
t:note("%s: %d raw frames, SNR %.1f dB vs ffmpeg", c.name, #list, snr)
|
||||
-- reset: decoding again from the start gives the same first frames
|
||||
dec:reset()
|
||||
dec:decode(data, list[1][1], list[1][2])
|
||||
local again = table.clone(dec.pcm)
|
||||
local dec2 = Aac.decoder({ sfIndex = (h :: Aac.Adts).sfIndex, channels = c.channels }) :: Aac.Decoder
|
||||
dec2:decode(data, list[1][1], list[1][2])
|
||||
local same = true
|
||||
for k = 1, 1024 * c.channels do
|
||||
same = same and again[k] == dec2.pcm[k]
|
||||
end
|
||||
t:check(same, c.name .. ": reset clears the overlap")
|
||||
end
|
||||
|
||||
-- the extension hook on HE-AAC (implicit SBR in ADTS)
|
||||
for _, c in He do
|
||||
if string.sub(c.name, -4) == ".aac" then
|
||||
local data = buffer.fromstring(c.data)
|
||||
local list, h = frames(data)
|
||||
local dec = Aac.decoder({ sfIndex = (h :: Aac.Adts).sfIndex, channels = 2 }) :: Aac.Decoder
|
||||
local seen, bits = 0, 0
|
||||
dec.onExtension = function(kind: number, _element: number, _buf: buffer, _pos: number, n: number)
|
||||
if kind == 13 or kind == 14 then
|
||||
seen += 1
|
||||
bits += n
|
||||
end
|
||||
end
|
||||
for _, f in list do
|
||||
dec:decode(data, f[1], f[2])
|
||||
end
|
||||
t:check(seen == #list and dec.sbr, string.format("%s: an SBR payload per frame (%d of %d, %d bits)", c.name, seen, #list, bits))
|
||||
end
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local dec = Aac.decoder(Aac.asc(2, 4, 2)) :: Aac.Decoder
|
||||
local _, e = dec:decode(buffer.fromstring("\x20\x00\x00\x00\x00"))
|
||||
t:check(e and e.code == Err.CORRUPT, "garbage frame: " .. tostring(e))
|
||||
local _, e2 = dec:decode(buffer.create(4), 3, 10)
|
||||
t:check(e2 and e2.code == Err.ARG, "range out of the buffer")
|
||||
t:check(Aac.adts(buffer.fromstring("\255\241"), 0, 2) == nil, "short ADTS header")
|
||||
end
|
||||
|
||||
-- fuzz raw frames (stereo with every tool, mono, 5.1)
|
||||
do
|
||||
local pick = {}
|
||||
for _, c in Fx do
|
||||
if c.container == "adts" then
|
||||
local data = buffer.fromstring(c.data)
|
||||
local list, h = frames(data)
|
||||
local f = list[math.min(#list, 9)]
|
||||
local raw = buffer.create(f[2])
|
||||
buffer.copy(raw, 0, data, f[1], f[2])
|
||||
table.insert(pick, { raw, (h :: Aac.Adts).sfIndex, c.channels })
|
||||
end
|
||||
end
|
||||
for _, p in pick do
|
||||
local dec = Aac.decoder({ sfIndex = p[2], channels = p[3] }) :: Aac.Decoder
|
||||
t:fuzz("raw frame " .. p[3] .. " ch", function(b: buffer)
|
||||
return dec:decode(b)
|
||||
end, { p[1] }, { mutations = 60, garbage = 100 })
|
||||
end
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,181 @@
|
||||
-- codecs/Alac tests: encoder -> decoder round trips over silence (zero runs), full-scale noise (uncompressed frames),
|
||||
-- tones, steps, 1 - 8 channels, 16 / 20 / 24 bits, partial and tiny frames, custom frame lengths; ffmpeg's ALAC
|
||||
-- packets (through containers/IsoBmff) decode to the source integers; the magic cookie (plain, behind frma / alac atoms,
|
||||
-- bad versions / depths); errors; the fuzz no-throw pass on packets. Fixtures: tools/fixtures/m4a.py.
|
||||
local T = require("@tests/T")
|
||||
local Alac = require("@formats/codecs/Alac")
|
||||
local IsoBmff = require("@formats/containers/IsoBmff")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Fx = require("@tests/gen/m4a_alac")
|
||||
|
||||
local t = T.suite("alac")
|
||||
local rand = T.rng(42)
|
||||
|
||||
local function roundTrip(label: string, ch: number, bits: number, frames: number, gen: (number, number) -> number, fl: number?)
|
||||
local enc = Alac.encoder({ sampleRate = 44100, channels = ch, bitDepth = bits, frameLength = fl }) :: Alac.Encoder
|
||||
t:check(enc, label .. ": encoder")
|
||||
local per = enc.config.frameLength
|
||||
local src = table.create(frames * ch, 0)
|
||||
for i = 0, frames - 1 do
|
||||
for c = 1, ch do
|
||||
src[i * ch + c] = gen(i, c)
|
||||
end
|
||||
end
|
||||
local packets = {}
|
||||
local bytes = 0
|
||||
local f = 0
|
||||
while f < frames do
|
||||
local n = math.min(per, frames - f)
|
||||
local p, err = enc:encode(src, f * ch + 1, n)
|
||||
t:check(p, label .. ": encode: " .. tostring(err))
|
||||
table.insert(packets, { p, n })
|
||||
bytes += buffer.len(p :: buffer)
|
||||
f += n
|
||||
end
|
||||
local cfg = Alac.config(Alac.cookie(enc.config)) :: Alac.Config
|
||||
t:check(cfg and cfg.maxFrameBytes >= 1 and cfg.channels == ch and cfg.bitDepth == bits, label .. ": cookie")
|
||||
local dec = Alac.decoder(cfg)
|
||||
local ok = true
|
||||
local at = 0
|
||||
for _, pk in packets do
|
||||
local n, err = dec:decode(pk[1])
|
||||
if n ~= pk[2] then
|
||||
ok = false
|
||||
t:check(false, label .. ": decode: " .. tostring(err))
|
||||
break
|
||||
end
|
||||
for k = 1, n * ch do
|
||||
if dec.pcm[k] ~= src[at * ch + k] then
|
||||
ok = false
|
||||
end
|
||||
end
|
||||
at += n
|
||||
end
|
||||
t:check(ok, label .. ": round trip")
|
||||
return bytes / (frames * ch * bits / 8)
|
||||
end
|
||||
|
||||
local peakOf = function(bits: number): number
|
||||
return 2 ^ (bits - 1)
|
||||
end
|
||||
|
||||
for _, bits in { 16, 20, 24 } do
|
||||
local pk = peakOf(bits)
|
||||
for _, ch in { 1, 2, 3, 6, 8 } do
|
||||
local r1 = roundTrip(string.format("tone %d-bit %d ch", bits, ch), ch, bits, 9000, function(i, c)
|
||||
return math.floor(math.sin(i * 0.031 * c) * (pk * 0.6) + math.sin(i * 0.0071) * pk * 0.2)
|
||||
end)
|
||||
if ch == 2 then
|
||||
t:note("%d-bit stereo tone: %.0f%% of PCM", bits, r1 * 100)
|
||||
end
|
||||
end
|
||||
roundTrip(bits .. "-bit silence (zero runs)", 2, bits, 10000, function()
|
||||
return 0
|
||||
end)
|
||||
local r = roundTrip(bits .. "-bit full-scale noise (escape frames)", 2, bits, 5000, function()
|
||||
return rand(2 ^ bits) - pk
|
||||
end)
|
||||
t:check(r < 1.01, bits .. "-bit noise stays near PCM size")
|
||||
roundTrip(bits .. "-bit extremes", 1, bits, 600, function(i)
|
||||
return if i % 2 == 0 then pk - 1 else -pk
|
||||
end)
|
||||
roundTrip(bits .. "-bit sparse clicks (zero runs + values)", 2, bits, 7000, function(i, c)
|
||||
return if i % 997 == c then pk // 3 else 0
|
||||
end)
|
||||
end
|
||||
for _, n in { 1, 2, 3, 5, 9, 17, 4095 } do
|
||||
roundTrip("partial frame of " .. n, 2, 16, n, function(i, c)
|
||||
return (i * 37 + c * 1000) % 3000 - 1500
|
||||
end)
|
||||
end
|
||||
roundTrip("frame length 1024", 2, 16, 5000, function(i)
|
||||
return math.floor(math.sin(i * 0.05) * 10000)
|
||||
end, 1024)
|
||||
roundTrip("identical channels", 2, 16, 5000, function(i)
|
||||
return math.floor(math.sin(i * 0.02) * 20000)
|
||||
end)
|
||||
|
||||
-- ffmpeg's packets
|
||||
for _, c in Fx do
|
||||
if c.container == "m4a" then
|
||||
local r = Bytes.reader(buffer.fromstring(c.data))
|
||||
local movie = IsoBmff.parse(r) :: IsoBmff.Movie
|
||||
local tr = movie.tracks[1]
|
||||
local cfg = Alac.config(tr.config :: buffer) :: Alac.Config
|
||||
t:check(cfg and cfg.bitDepth == c.bits and cfg.channels == c.channels, c.name .. ": cookie")
|
||||
local dec = Alac.decoder(cfg)
|
||||
local out = buffer.create(c.frames * c.channels * 4)
|
||||
local o = 0
|
||||
for i = 1, tr.sampleCount do
|
||||
local n, err = dec:decode(r.buf, tr.offsets[i], tr.sizes[i])
|
||||
t:check(n, c.name .. ": packet " .. i .. ": " .. tostring(err))
|
||||
for k = 1, (n :: number) * c.channels do
|
||||
buffer.writei32(out, o, dec.pcm[k])
|
||||
o += 4
|
||||
end
|
||||
end
|
||||
t:eq(Crc32.of(out), c.crc, c.name .. ": ffmpeg's packets decode to the source")
|
||||
end
|
||||
end
|
||||
|
||||
-- the cookie behind QuickTime atoms, bad cookies
|
||||
do
|
||||
local enc = Alac.encoder({ sampleRate = 48000, channels = 2 }) :: Alac.Encoder
|
||||
local plain = Alac.cookie(enc.config)
|
||||
local w = Bytes.writer(64)
|
||||
w:u32be(12)
|
||||
w:string("frma")
|
||||
w:string("alac")
|
||||
w:u32be(36)
|
||||
w:string("alac")
|
||||
w:u32be(0)
|
||||
w:bytes(plain)
|
||||
local cfg = Alac.config(w:finish())
|
||||
t:check(cfg and cfg.sampleRate == 48000 and cfg.frameLength == 4096, "cookie behind frma / alac atoms")
|
||||
local bad = buffer.fromstring(buffer.tostring(plain))
|
||||
buffer.writeu8(bad, 5, 12)
|
||||
local _, e = Alac.config(bad)
|
||||
t:check(e and e.code == Err.UNSUPPORTED, "12-bit cookie: " .. tostring(e))
|
||||
local _, e2 = Alac.config(buffer.create(10))
|
||||
t:check(e2 and e2.code == Err.TRUNCATED, "short cookie")
|
||||
local _, e3 = Alac.encoder({ sampleRate = 44100, channels = 9 })
|
||||
t:check(e3 and e3.code == Err.ARG, "9 channels")
|
||||
local _, e4 = enc:encode({ 1, 2 }, 1, 5)
|
||||
t:check(e4 and e4.code == Err.ARG, "too few samples")
|
||||
local dec = Alac.decoder(cfg :: Alac.Config)
|
||||
local _, e5 = dec:decode(buffer.fromstring("\1\255\255\255"))
|
||||
t:check(e5 and e5.code == Err.CORRUPT, "bad packet: " .. tostring(e5))
|
||||
end
|
||||
|
||||
-- fuzz the packet decoder
|
||||
do
|
||||
local enc = Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 }) :: Alac.Encoder
|
||||
local src = table.create(2 * 3000, 0)
|
||||
for i = 1, #src do
|
||||
src[i] = math.floor(math.sin(i * 0.01) * 8000) + rand(64)
|
||||
end
|
||||
local samples = {}
|
||||
table.insert(samples, (enc:encode(src, 1, 3000)))
|
||||
for i = 1, #src do
|
||||
src[i] = if i % 300 < 3 then 5000 else 0
|
||||
end
|
||||
table.insert(samples, (enc:encode(src, 1, 3000)))
|
||||
local dec = Alac.decoder(enc.config)
|
||||
local enc24 = Alac.encoder({ sampleRate = 44100, channels = 1, bitDepth = 24 }) :: Alac.Encoder
|
||||
local dec24 = Alac.decoder(enc24.config)
|
||||
local s24 = table.create(2000, 0)
|
||||
for i = 1, 2000 do
|
||||
s24[i] = rand(2 ^ 24) - 2 ^ 23
|
||||
end
|
||||
local p24 = enc24:encode(s24, 1, 2000) :: buffer
|
||||
t:fuzz("decode packet", function(b: buffer)
|
||||
return dec:decode(b)
|
||||
end, samples, { mutations = 40 })
|
||||
t:fuzz("decode 24-bit escape packet", function(b: buffer)
|
||||
return dec24:decode(b)
|
||||
end, { p24 }, { mutations = 20, garbage = 50 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,134 @@
|
||||
-- codecs/Mdct tests: the FFT against a direct DFT for mixed-radix sizes, the forward / inverse MDCT and the DCT-IV
|
||||
-- against their O(N^2) definitions (AAC, Vorbis and CELT sizes), perfect reconstruction (TDAC) with the sine, KBD and
|
||||
-- Vorbis windows, window power complementarity, bad sizes. No fixtures (the definitions are the reference).
|
||||
local T = require("@tests/T")
|
||||
local Mdct = require("@formats/codecs/Mdct")
|
||||
|
||||
local t = T.suite("mdct")
|
||||
local rand = T.rng(7)
|
||||
local cos, sin, pi = math.cos, math.sin, math.pi
|
||||
|
||||
local function noise(n: number): { number }
|
||||
local a = table.create(n, 0)
|
||||
for i = 1, n do
|
||||
a[i] = rand(20001) / 10000 - 1
|
||||
end
|
||||
return a
|
||||
end
|
||||
|
||||
-- FFT vs DFT
|
||||
for _, n in { 1, 2, 3, 4, 5, 6, 7, 8, 12, 15, 16, 30, 49, 60, 64, 120, 240, 480, 77 } do
|
||||
local plan = Mdct.fft(n)
|
||||
t:check(plan, "fft plan " .. n)
|
||||
local re, im = noise(n), noise(n)
|
||||
local wr, wi = table.create(n, 0), table.create(n, 0)
|
||||
for k = 0, n - 1 do
|
||||
local sr, si = 0, 0
|
||||
for j = 0, n - 1 do
|
||||
local a = -2 * pi * j * k / n
|
||||
sr += re[j + 1] * cos(a) - im[j + 1] * sin(a)
|
||||
si += re[j + 1] * sin(a) + im[j + 1] * cos(a)
|
||||
end
|
||||
wr[k + 1], wi[k + 1] = sr, si
|
||||
end
|
||||
Mdct.Fft.forward(plan :: any, re, im)
|
||||
local err = 0
|
||||
for k = 1, n do
|
||||
err = math.max(err, math.abs(re[k] - wr[k]), math.abs(im[k] - wi[k]))
|
||||
end
|
||||
t:check(err < 1e-9 * n, string.format("fft %d: max error %g", n, err))
|
||||
end
|
||||
|
||||
-- MDCT / IMDCT vs the definitions
|
||||
local maxErr = 0
|
||||
for _, n in { 4, 8, 16, 64, 240, 256, 480, 1920, 2048 } do
|
||||
local plan = Mdct.new(n) :: Mdct.Plan
|
||||
t:check(plan, "mdct plan " .. n)
|
||||
local m = n // 2
|
||||
local x = noise(n)
|
||||
local X = table.create(m, 0)
|
||||
Mdct.forward(plan, x, 1, X, 1)
|
||||
local Y = noise(m)
|
||||
local y = table.create(n, 0)
|
||||
Mdct.inverse(plan, Y, 1, 1, y, 1)
|
||||
local step = if n > 500 then 37 else 1 -- spot-check the big sizes
|
||||
local ef, ei = 0, 0
|
||||
for k = 0, m - 1, step do
|
||||
local s = 0
|
||||
for j = 0, n - 1 do
|
||||
s += x[j + 1] * cos(2 * pi / n * (j + 0.5 + n / 4) * (k + 0.5))
|
||||
end
|
||||
ef = math.max(ef, math.abs(s - X[k + 1]))
|
||||
end
|
||||
for j = 0, n - 1, step do
|
||||
local s = 0
|
||||
for k = 0, m - 1 do
|
||||
s += Y[k + 1] * cos(2 * pi / n * (j + 0.5 + n / 4) * (k + 0.5))
|
||||
end
|
||||
ei = math.max(ei, math.abs(s - y[j + 1]))
|
||||
end
|
||||
t:check(ef < 1e-9 * n and ei < 1e-9 * n, string.format("mdct %d: forward error %g, inverse error %g", n, ef, ei))
|
||||
maxErr = math.max(maxErr, ef, ei)
|
||||
-- strided coefficients + offsets + scale
|
||||
local X2 = table.create(m * 3 + 5, 0)
|
||||
Mdct.forward(plan, x, 1, X2, 3, 3, 0.5)
|
||||
local ok = true
|
||||
for k = 0, m - 1 do
|
||||
ok = ok and math.abs(X2[3 + 3 * k] - 0.5 * X[k + 1]) < 1e-9
|
||||
end
|
||||
t:check(ok, "mdct " .. n .. ": strided / scaled forward")
|
||||
end
|
||||
t:note("mdct vs definition: max error %.3g", maxErr)
|
||||
|
||||
-- TDAC: windowed forward + inverse + overlap-add reproduces the signal
|
||||
for _, kind in { "sine", "kbd", "vorbis" } do
|
||||
for _, n in { 256, 2048, 240 } do
|
||||
local w = Mdct.window(kind, n, if n == 256 then 6 else 4) :: { number }
|
||||
local m = n // 2
|
||||
local plan = Mdct.new(n) :: Mdct.Plan
|
||||
local pc = 0
|
||||
for i = 1, m do
|
||||
pc = math.max(pc, math.abs(w[i] ^ 2 + w[i + m] ^ 2 - 1))
|
||||
end
|
||||
t:check(pc < 1e-12, kind .. " " .. n .. ": power complementary")
|
||||
local frames = 6
|
||||
local sig = noise(m * (frames + 1))
|
||||
local out = table.create(m * (frames + 1), 0)
|
||||
local buf, X, y = table.create(n, 0), table.create(m, 0), table.create(n, 0)
|
||||
for f = 0, frames - 1 do
|
||||
for i = 1, n do
|
||||
buf[i] = sig[f * m + i] * w[i]
|
||||
end
|
||||
Mdct.forward(plan, buf, 1, X, 1)
|
||||
Mdct.inverse(plan, X, 1, 1, y, 1, 4 / n)
|
||||
for i = 1, n do
|
||||
out[f * m + i] += y[i] * w[i]
|
||||
end
|
||||
end
|
||||
local e = 0
|
||||
for i = m + 1, m * frames do
|
||||
e = math.max(e, math.abs(out[i] - sig[i]))
|
||||
end
|
||||
t:check(e < 1e-9, string.format("%s %d: reconstruction error %g", kind, n, e))
|
||||
end
|
||||
end
|
||||
|
||||
-- DCT-IV is its own inverse (times 2 / M)
|
||||
do
|
||||
local plan = Mdct.new(512) :: Mdct.Plan
|
||||
local u = noise(256)
|
||||
local c, back = table.create(256, 0), table.create(256, 0)
|
||||
Mdct.dct4(plan, u, 1, 1, c, 1, 1)
|
||||
Mdct.dct4(plan, c, 1, 1, back, 1, 1, 2 / 256)
|
||||
local e = 0
|
||||
for i = 1, 256 do
|
||||
e = math.max(e, math.abs(back[i] - u[i]))
|
||||
end
|
||||
t:check(e < 1e-10, "dct4 involution: " .. e)
|
||||
end
|
||||
|
||||
-- bad sizes
|
||||
t:check(Mdct.new(6) == nil and Mdct.new(0) == nil and Mdct.new(-8) == nil and Mdct.new(8.5) == nil and Mdct.new("x" :: any) == nil, "bad mdct sizes")
|
||||
t:check(Mdct.fft(0) == nil and Mdct.window("nope", 8) == nil and Mdct.window("sine", 7) == nil, "bad fft sizes / windows")
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,241 @@
|
||||
-- containers/IsoBmff tests: ffmpeg / MP4Box files (H.264 + AAC with B-frames, fast start, QuickTime MJPEG + PCM, HEVC,
|
||||
-- fragmented by ffmpeg and MP4Box, stz2 + co64, ALAC) demuxed packet for packet against ffprobe (-ignore_editlist);
|
||||
-- track facts and codec configurations; iTunes tags and cover art; AVIF items (libavif, plain and with alpha); the
|
||||
-- muxer round-trips through the demuxer (sizes, times, cts, sync, tags, 64-bit sizes); a sub-range reader; the fuzz
|
||||
-- no-throw pass. Fixtures: tools/fixtures/isobmff.py.
|
||||
local T = require("@tests/T")
|
||||
local IsoBmff = require("@formats/containers/IsoBmff")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Fx = require("@tests/gen/isobmff")
|
||||
|
||||
local t = T.suite("isobmff")
|
||||
|
||||
local CODEC = { h264 = "h264", aac = "aac", mjpeg = "mjpeg", pcm_s16be = "pcm", hevc = "hevc", alac = "alac" }
|
||||
|
||||
local function reader(s: string, pad: number?): Bytes.Reader
|
||||
if pad then
|
||||
local b = buffer.create(#s + pad * 2)
|
||||
buffer.writestring(b, pad, s)
|
||||
return Bytes.reader(b, pad, #s)
|
||||
end
|
||||
return Bytes.reader(buffer.fromstring(s))
|
||||
end
|
||||
|
||||
-- every fixture against ffprobe
|
||||
for _, c in Fx.cases do
|
||||
for _, pad in { 0, 5 } do
|
||||
local r = reader(c.data, if pad > 0 then pad else nil)
|
||||
local label = c.name .. (if pad > 0 then " (sub-range)" else "")
|
||||
t:check(IsoBmff.sniff(r) ~= nil, label .. ": sniff")
|
||||
local dmx, err = IsoBmff.demux(r)
|
||||
t:check(dmx, label .. ": " .. tostring(err))
|
||||
t:eq(#dmx.tracks, #c.streams, label .. ": track count")
|
||||
for i, s in c.streams do
|
||||
local tr = dmx.tracks[i]
|
||||
t:eq(tr.kind, s.kind, label .. ": track " .. i .. " kind")
|
||||
t:eq(tr.codec, CODEC[s.codec] or s.codec, label .. ": track " .. i .. " codec")
|
||||
t:eq(tr.timescale, s.timescale, label .. ": timescale")
|
||||
if s.width then
|
||||
t:check(tr.width == s.width and tr.height == s.height, label .. ": video size")
|
||||
end
|
||||
if s.sampleRate then
|
||||
t:check(tr.sampleRate == s.sampleRate and tr.channels == s.channels, label .. ": audio format")
|
||||
end
|
||||
if s.extradata > 0 and s.codec ~= "alac" then
|
||||
t:eq(if tr.config then buffer.len(tr.config) else 0, s.extradata, label .. ": codec config size")
|
||||
end
|
||||
end
|
||||
-- packets in file order
|
||||
local n, bad = 0, nil
|
||||
local base = r.base
|
||||
for p in dmx:packets() do
|
||||
n += 1
|
||||
local want = c.packets[n]
|
||||
if not want then
|
||||
bad = bad or ("extra packet " .. n)
|
||||
break
|
||||
end
|
||||
local tr = dmx.tracks[want.stream]
|
||||
if p.track ~= tr.id then
|
||||
bad = bad or ("packet " .. n .. " track")
|
||||
end
|
||||
local off = tr.offsets[p.index]
|
||||
if off - base ~= want.pos or buffer.len(p.data) ~= want.size or p.dts ~= want.dts or p.pts ~= want.pts or p.keyframe ~= want.key then
|
||||
bad = bad or string.format("packet %d: pos %d/%d size %d/%d dts %d/%d pts %d/%d key %s/%s", n, off - base, want.pos, buffer.len(p.data), want.size, p.dts, want.dts, p.pts, want.pts, tostring(p.keyframe), tostring(want.key))
|
||||
end
|
||||
end
|
||||
t:check(bad == nil, label .. ": " .. tostring(bad))
|
||||
t:eq(n, #c.packets, label .. ": packet count")
|
||||
if pad == 0 then
|
||||
t:note("%s: %d tracks, %d packets match ffprobe", c.name, #c.streams, n)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- per-track packets, seek
|
||||
do
|
||||
local c = Fx.cases[1]
|
||||
local dmx = IsoBmff.demux(reader(c.data))
|
||||
local v = dmx.tracks[1]
|
||||
local count = 0
|
||||
for p in dmx:packets(v.id) do
|
||||
count += 1
|
||||
t:eq(p.track, v.id, "per-track packets")
|
||||
end
|
||||
t:eq(count, v.sampleCount, "per-track packet count")
|
||||
dmx:seek(0.75)
|
||||
local p = dmx:packets(v.id)()
|
||||
t:check(p and p.keyframe and p.dts / v.timescale <= 0.75, "seek lands on a keyframe before the time")
|
||||
t:check(v.skip >= 0 and v.edits ~= nil, "edit list parsed")
|
||||
end
|
||||
|
||||
-- tags and cover
|
||||
do
|
||||
local r = reader(Fx.tagged.data)
|
||||
local movie = IsoBmff.parse(r) :: IsoBmff.Movie
|
||||
local tags, pics = IsoBmff.tags(r, movie)
|
||||
for k, v in Fx.tagged.tags do
|
||||
t:eq(tags[k], v, "tag " .. k)
|
||||
end
|
||||
t:check(tags.encoder ~= nil, "encoder tag")
|
||||
t:eq(#pics, 1, "one cover")
|
||||
t:eq(pics[1] and buffer.len(pics[1].data), Fx.tagged.cover, "cover bytes")
|
||||
t:eq(pics[1] and pics[1].mime, "image/png", "cover mime")
|
||||
end
|
||||
|
||||
-- AVIF items
|
||||
for _, c in Fx.avif do
|
||||
local r = reader(c.data)
|
||||
t:check(IsoBmff.sniff(r) == "avif", c.name .. ": brand")
|
||||
local movie = IsoBmff.parse(r) :: IsoBmff.Movie
|
||||
t:check(movie and #movie.tracks == 0, c.name .. ": no tracks")
|
||||
local items, err = IsoBmff.items(r, movie)
|
||||
t:check(items, c.name .. ": items: " .. tostring(err))
|
||||
local prim = items.items[items.primary]
|
||||
t:check(prim and prim.type == "av01", c.name .. ": primary item is av01")
|
||||
local ispe, av1C
|
||||
for _, p in prim.properties do
|
||||
if p.type == "ispe" then
|
||||
ispe = p
|
||||
elseif p.type == "av1C" then
|
||||
av1C = p
|
||||
end
|
||||
end
|
||||
t:check(ispe and ispe.width == c.width and ispe.height == c.height, c.name .. ": ispe")
|
||||
t:check(av1C and av1C.config and buffer.readu8(av1C.config, 0) == 0x81, c.name .. ": av1C marker / version")
|
||||
local data = IsoBmff.itemData(r, items, items.primary :: number)
|
||||
t:check(data and buffer.len(data) > 10, c.name .. ": item data")
|
||||
-- an AV1 OBU stream: the first OBU is a sequence header (type 1) or a temporal delimiter (2)
|
||||
local obu = data and bit32.band(bit32.rshift(buffer.readu8(data, 0), 3), 15)
|
||||
t:check(obu == 1 or obu == 2, c.name .. ": AV1 OBU stream")
|
||||
local auxl = nil
|
||||
for _, id in items.order do
|
||||
local it = items.items[id]
|
||||
if it.refs.auxl then
|
||||
auxl = it
|
||||
end
|
||||
end
|
||||
t:eq(auxl ~= nil, c.alpha, c.name .. ": alpha auxiliary item")
|
||||
end
|
||||
|
||||
-- the muxer: round trip through the demuxer
|
||||
do
|
||||
local rand = T.rng(5)
|
||||
local function sample(n: number): buffer
|
||||
local b = buffer.create(n)
|
||||
for i = 0, n - 1 do
|
||||
buffer.writeu8(b, i, rand(256))
|
||||
end
|
||||
return b
|
||||
end
|
||||
local aud, vid = {}, {}
|
||||
for i = 1, 90 do
|
||||
aud[i] = sample(50 + rand(200))
|
||||
end
|
||||
for i = 1, 30 do
|
||||
vid[i] = sample(100 + rand(900))
|
||||
end
|
||||
local cts = {}
|
||||
local sync = {}
|
||||
for i = 1, 30 do
|
||||
cts[i] = (i % 3) * 512
|
||||
sync[i] = i % 10 == 1
|
||||
end
|
||||
local cfg = buffer.fromstring("\x12\x10")
|
||||
local file, err = IsoBmff.mux({
|
||||
brand = "mp42",
|
||||
compatible = { "mp42", "isom" },
|
||||
tracks = {
|
||||
{ kind = "video", entry = "avc1", timescale = 15360, samples = vid, durations = 512, cts = cts, sync = sync, width = 64, height = 48, config = buffer.fromstring("\1\100\0\10\255") },
|
||||
{ kind = "audio", entry = "mp4a", timescale = 44100, samples = aud, durations = 1024, sampleRate = 44100, channels = 2, config = cfg, skip = 1024, playDuration = 44100 * 2 },
|
||||
},
|
||||
tags = { title = "Mux Test", artist = "Me", track = "2", tracktotal = "9", custom = "free form", bpm = "120" },
|
||||
pictures = { { mime = "image/jpeg", data = buffer.fromstring("\255\216\255\217") } },
|
||||
chunkDuration = 0.25,
|
||||
})
|
||||
t:check(file, "mux: " .. tostring(err))
|
||||
local r = Bytes.reader(file :: buffer)
|
||||
local dmx = IsoBmff.demux(r)
|
||||
t:check(dmx and #dmx.tracks == 2, "mux: demux our file")
|
||||
local v, a = dmx.tracks[1], dmx.tracks[2]
|
||||
t:check(v.codec == "h264" and v.width == 64 and v.height == 48 and v.config and buffer.len(v.config) == 5, "mux: video track")
|
||||
t:check(a.codec == "aac" and a.sampleRate == 44100 and a.channels == 2 and a.config and buffer.tostring(a.config) == "\x12\x10", "mux: audio track + esds")
|
||||
t:check(a.skip == 1024 and a.playDuration == 88200, "mux: edit list")
|
||||
local ok = true
|
||||
for i = 1, 30 do
|
||||
local s = IsoBmff.sample(r, v, i) :: buffer
|
||||
ok = ok and buffer.tostring(s) == buffer.tostring(vid[i]) and v.dts[i] == (i - 1) * 512 and (v.cts :: any)[i] == cts[i] and ((v.sync :: any)[i] == true) == sync[i]
|
||||
end
|
||||
t:check(ok, "mux: video samples, times, cts, sync")
|
||||
ok = true
|
||||
for i = 1, 90 do
|
||||
ok = ok and buffer.tostring(IsoBmff.sample(r, a, i) :: buffer) == buffer.tostring(aud[i]) and a.durations[i] == 1024
|
||||
end
|
||||
t:check(ok, "mux: audio samples")
|
||||
-- interleaved: offsets alternate between the tracks
|
||||
t:check(v.offsets[30] > a.offsets[1] and a.offsets[90] > v.offsets[1], "mux: interleaved chunks")
|
||||
local tags, pics = IsoBmff.tags(r, dmx.movie)
|
||||
t:check(tags.title == "Mux Test" and tags.artist == "Me" and tags.track == "2" and tags.tracktotal == "9" and tags.custom == "free form" and tags.bpm == "120", "mux: tags round trip")
|
||||
t:check(#pics == 1 and buffer.len(pics[1].data) == 4, "mux: cover round trip")
|
||||
t:note("mux: %d bytes, crc %08x", buffer.len(file :: buffer), Crc32.of(file :: buffer))
|
||||
-- data + sizes form, bad specs
|
||||
local f2 = IsoBmff.mux({ tracks = { { kind = "audio", entry = "alac", timescale = 8000, data = buffer.create(30), sizes = { 10, 10, 10 }, durations = { 4096, 4096, 100 }, config = buffer.create(24) } } })
|
||||
local d2 = IsoBmff.demux(Bytes.reader(f2 :: buffer))
|
||||
t:check(d2 and d2.tracks[1].codec == "alac" and d2.tracks[1].sampleCount == 3 and d2.tracks[1].durations[3] == 100 and buffer.len(d2.tracks[1].config) == 24, "mux: data + sizes, alac cookie")
|
||||
for _, bad in { {}, { tracks = {} }, { tracks = { { kind = "audio", entry = "toolong", timescale = 1, samples = {}, durations = 1 } } }, { tracks = { { kind = "x", entry = "abcd", timescale = 1, samples = {}, durations = 1 } } }, { tracks = { { kind = "audio", entry = "abcd", timescale = 1 } } } } do
|
||||
local f, e = IsoBmff.mux(bad :: any)
|
||||
t:check(f == nil and e and e.code == "ARG", "mux: bad spec -> ARG")
|
||||
end
|
||||
end
|
||||
|
||||
-- fuzz
|
||||
do
|
||||
local samples = {}
|
||||
for _, c in Fx.cases do
|
||||
table.insert(samples, string.sub(c.data, 1, 6000))
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
for _, c in Fx.avif do
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
t:fuzz("demux", function(b: buffer)
|
||||
local r = Bytes.reader(b)
|
||||
local dmx = IsoBmff.demux(r)
|
||||
if dmx then
|
||||
for p in dmx:packets() do
|
||||
local _ = p
|
||||
end
|
||||
IsoBmff.tags(r, dmx.movie)
|
||||
local items = IsoBmff.items(r, dmx.movie)
|
||||
if items then
|
||||
for _, id in items.order do
|
||||
IsoBmff.itemData(r, items, id)
|
||||
end
|
||||
end
|
||||
end
|
||||
return dmx
|
||||
end, samples, { mutations = 12 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,30 @@
|
||||
-- core/Md5 tests: the RFC 1321 test suite, incremental updates at every split, sub-ranges, a long input.
|
||||
local T = require("@tests/T")
|
||||
local Md5 = require("@formats/core/Md5")
|
||||
|
||||
local t = T.suite("md5")
|
||||
local VECTORS = {
|
||||
{ "", "d41d8cd98f00b204e9800998ecf8427e" },
|
||||
{ "a", "0cc175b9c0f1b6a831c399e269772661" },
|
||||
{ "abc", "900150983cd24fb0d6963f7d28e17f72" },
|
||||
{ "message digest", "f96b697d7cb7938d525a2f31aaf161d0" },
|
||||
{ "abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b" },
|
||||
{ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "d174ab98d277d9f5a5611c2c9f419d9f" },
|
||||
{ string.rep("1234567890", 8), "57edf4a22be3c955ac49da2e2107b67a" },
|
||||
}
|
||||
for _, v in VECTORS do
|
||||
t:eq(Md5.of(buffer.fromstring(v[1])), v[2], "md5 of " .. string.format("%q", v[1]))
|
||||
end
|
||||
-- incremental: every split point of a 130-byte message, three pieces
|
||||
local msg = string.rep("The quick brown fox jumps over the lazy dog. ", 3)
|
||||
local want = Md5.of(buffer.fromstring(msg))
|
||||
for cut = 0, #msg, 7 do
|
||||
local h = Md5.new()
|
||||
h:update(buffer.fromstring(string.sub(msg, 1, cut)))
|
||||
h:update(buffer.fromstring(string.sub(msg, cut + 1, cut + 20)))
|
||||
h:update(buffer.fromstring(string.sub(msg, cut + 21)))
|
||||
t:eq(Md5.hex(h:digest()), want, "split at " .. cut)
|
||||
end
|
||||
t:eq(Md5.of(buffer.fromstring("xxabcyy"), 2, 3), "900150983cd24fb0d6963f7d28e17f72", "sub-range")
|
||||
t:eq(Md5.of(buffer.fromstring(string.rep("a", 1000000))), "7707d6ae4e027c70eea2a935c2296f21", "a million a's")
|
||||
t:done()
|
||||
@@ -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