ws-audio: merge ws/absorb (Ogg + muxer, Riff, wav, mp3, opus, apng)
This commit is contained in:
commit
aee2d3257e
72 files changed
+14343
-56
No files matched your search
@@ -0,0 +1,518 @@
|
||||
-- audio/mp3 tests: every fixture against its minimp3 reference decode (exact length, SNR > 90 dB on windows, block
|
||||
-- energies) and against ffmpeg (length, SNR > 75 dB), lame-written streams against ffmpeg; chunked reads, reads into
|
||||
-- a caller buffer, sample-accurate seeking; robustness (garbage, corruption, truncation, mono / stereo switches, API
|
||||
-- misuse); ID3v1 / v2.2 / 2.3 / 2.4 and APE tags; the contract, sniff, decode to Audio, the fuzz no-throw pass.
|
||||
-- Ported from mp3-luau tests/decode.luau, robust.luau, tags.luau. Fixtures: tools/fixtures/mp3.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 Cases = require("@tests/gen/mp3_cases")
|
||||
|
||||
local t = T.suite("mp3")
|
||||
|
||||
local function open(b: buffer | string, opts: any?): (any, any)
|
||||
local buf = if type(b) == "string" then buffer.fromstring(b) else b
|
||||
return Mp3.open(Bytes.reader(buf), opts)
|
||||
end
|
||||
|
||||
local byName: { [string]: any } = {}
|
||||
for _, c in Cases do
|
||||
byName[c.name] = c
|
||||
end
|
||||
local function file(name: string): buffer
|
||||
return buffer.fromstring(byName[name].data)
|
||||
end
|
||||
|
||||
-- the reference format written by the minimp3 harness (see tools/fixtures/mp3.py)
|
||||
local function parseRef(s: string): any
|
||||
local b = buffer.fromstring(s)
|
||||
local hz, ch, frames, W, N = buffer.readu32(b, 8), buffer.readu32(b, 12), buffer.readu32(b, 16), buffer.readu32(b, 20), buffer.readu32(b, 24)
|
||||
local p = 28
|
||||
local windows = {}
|
||||
for _ = 1, N do
|
||||
local start = buffer.readu32(b, p)
|
||||
p += 4
|
||||
local pcm = buffer.create(W * ch * 4)
|
||||
buffer.copy(pcm, 0, b, p, W * ch * 4)
|
||||
p += W * ch * 4
|
||||
table.insert(windows, { start = start, pcm = pcm })
|
||||
end
|
||||
local B, nb = buffer.readu32(b, p), buffer.readu32(b, p + 4)
|
||||
p += 8
|
||||
local energies = {}
|
||||
for i = 1, nb do
|
||||
energies[i] = buffer.readf64(b, p)
|
||||
p += 8
|
||||
end
|
||||
return { hz = hz, channels = ch, frames = frames, W = W, windows = windows, block = B, energies = energies }
|
||||
end
|
||||
|
||||
local function snr(x: buffer, xo: number, ref: buffer, ro: number, n: number): number
|
||||
local sig, err = 0, 0
|
||||
for i = 0, n - 1 do
|
||||
local r = buffer.readf32(ref, (ro + i) * 4)
|
||||
local d = buffer.readf32(x, (xo + i) * 4) - r
|
||||
sig += r * r
|
||||
err += d * d
|
||||
end
|
||||
if err == 0 then
|
||||
return math.huge
|
||||
end
|
||||
if sig == 0 then
|
||||
return -math.huge
|
||||
end
|
||||
return 10 * math.log10(sig / err)
|
||||
end
|
||||
|
||||
local function maxDiff(x: buffer, xo: number, y: buffer, yo: number, n: number): number
|
||||
local m = 0
|
||||
for i = 0, n - 1 do
|
||||
local d = math.abs(buffer.readf32(x, (xo + i) * 4) - buffer.readf32(y, (yo + i) * 4))
|
||||
if d > m then
|
||||
m = d
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
local rand = T.rng(12345)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
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")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode vs references
|
||||
for _, c in Cases do
|
||||
local name = c.name
|
||||
local buf = buffer.fromstring(c.data)
|
||||
local dec, err = open(buf)
|
||||
t:check(dec, name .. ": open (" .. tostring(err) .. ")")
|
||||
local ch = dec.channels
|
||||
local ref = if c.ref then parseRef(c.ref) else nil
|
||||
if ref then
|
||||
t:eq(dec.sampleRate, ref.hz, name .. ": sample rate")
|
||||
t:eq(ch, ref.channels, name .. ": channels")
|
||||
t:eq(dec.frames, ref.frames, name .. ": frames vs minimp3")
|
||||
t:check(math.abs(dec.duration - ref.frames / ref.hz) < 1e-9, name .. ": duration")
|
||||
else
|
||||
t:eq(dec.sampleRate, c.rate, name .. ": sample rate")
|
||||
t:eq(ch, c.channels, name .. ": channels")
|
||||
t:eq(dec.frames, c.srcFrames, name .. ": gapless length = the encoder's input")
|
||||
end
|
||||
t:eq(dec.frames, c.ffFrames, name .. ": frames vs ffmpeg")
|
||||
t:check(dec.bitrate > 0, name .. ": bitrate")
|
||||
|
||||
-- whole decode in chunks of varied sizes
|
||||
local all = buffer.create(dec.frames * ch * 4)
|
||||
local total = 0
|
||||
while true do
|
||||
local pcm, n = dec:read(1 + rand(3000))
|
||||
if n == 0 then
|
||||
break
|
||||
end
|
||||
t:check(buffer.len(pcm) == n * ch * 4, name .. ": chunk size")
|
||||
buffer.copy(all, total * ch * 4, pcm, 0, n * ch * 4)
|
||||
total += n
|
||||
end
|
||||
t:eq(total, dec.frames, name .. ": decoded frames")
|
||||
t:eq(dec:position(), total / dec.sampleRate, name .. ": position at the end")
|
||||
local _, n0 = dec:read(100)
|
||||
t:eq(n0, 0, name .. ": read after the end")
|
||||
|
||||
local worst, worstFF = math.huge, math.huge
|
||||
if ref then
|
||||
for _, w in ref.windows do
|
||||
local s = snr(all, w.start * ch, w.pcm, 0, ref.W * ch)
|
||||
worst = math.min(worst, s)
|
||||
t:check(s > 90, string.format("%s: window at %d SNR %.1f dB vs minimp3", name, w.start, s))
|
||||
end
|
||||
for bi, e in ref.energies do
|
||||
local a = (bi - 1) * ref.block
|
||||
local bEnd = math.min(ref.frames, a + ref.block)
|
||||
local sum = 0
|
||||
for i = a * ch, bEnd * ch - 1 do
|
||||
local v = buffer.readf32(all, i * 4)
|
||||
sum += v * v
|
||||
end
|
||||
t:check(math.abs(sum - e) <= 1e-5 * e + 1e-9, string.format("%s: block %d energy", name, bi))
|
||||
end
|
||||
end
|
||||
for _, w in c.ff do
|
||||
local pcm = buffer.fromstring(w.pcm)
|
||||
local s = snr(all, w.start * ch, pcm, 0, buffer.len(pcm) // 4)
|
||||
worstFF = math.min(worstFF, s)
|
||||
t:check(s > 75, string.format("%s: window at %d SNR %.1f dB vs ffmpeg", name, w.start, s))
|
||||
end
|
||||
|
||||
-- reading into a caller buffer (reused when big enough, ignored when too small)
|
||||
dec:seek(0)
|
||||
local out = buffer.create(500 * ch * 4)
|
||||
local got, n1 = dec:read(500, out)
|
||||
t:check(got == out and n1 == 500, name .. ": read into out")
|
||||
t:eq(maxDiff(out, 0, all, 0, 500 * ch), 0, name .. ": out matches")
|
||||
local got2, n2 = dec:read(600, out)
|
||||
t:check(got2 ~= out and n2 == 600 and maxDiff(got2, 0, all, 500 * ch, 600 * ch) == 0, name .. ": small out ignored")
|
||||
|
||||
-- seeks: every window, then random targets, compared with the straight decode (bit-identical)
|
||||
local targets = {}
|
||||
for _, w in c.ff do
|
||||
table.insert(targets, w.start)
|
||||
end
|
||||
for _ = 1, 12 do
|
||||
table.insert(targets, rand(dec.frames))
|
||||
end
|
||||
table.insert(targets, dec.frames - 1)
|
||||
for _, tg in targets do
|
||||
dec:seekFrame(tg)
|
||||
local _, pf = dec:position()
|
||||
t:eq(pf, tg, name .. ": position after seek")
|
||||
local want = math.min(1152, dec.frames - tg)
|
||||
local pcm, n = dec:read(want)
|
||||
t:eq(n, want, string.format("%s: read after seek to %d", name, tg))
|
||||
t:eq(maxDiff(pcm, 0, all, tg * ch, n * ch), 0, string.format("%s: seek to %d bit-identical", name, tg))
|
||||
end
|
||||
dec:seek(dec.duration / 3)
|
||||
local _, pf = dec:position()
|
||||
local pcm, n = dec:read(64)
|
||||
t:check(n == 64 and maxDiff(pcm, 0, all, pf * ch, 64 * ch) == 0, name .. ": seek seconds")
|
||||
dec:seek(1e9)
|
||||
t:eq(select(2, dec:read(10)), 0, name .. ": seek past the end")
|
||||
dec:seek(-5)
|
||||
local pcm0, n3 = dec:read(256)
|
||||
t:check(n3 == 256 and maxDiff(pcm0, 0, all, 0, 256 * ch) == 0, name .. ": seek back to the start")
|
||||
|
||||
-- decode to Audio, also from a sub-range of a bigger buffer
|
||||
local big = buffer.create(buffer.len(buf) + 17)
|
||||
buffer.copy(big, 9, buf)
|
||||
local a, aerr = Mp3.decode(Bytes.reader(big, 9, buffer.len(buf)))
|
||||
t:check(a and a.kind == "audio" and a.frames == dec.frames and a.channels == ch, name .. ": decode (" .. tostring(aerr) .. ")")
|
||||
t:eq(maxDiff(a.samples, 0, all, 0, dec.frames * ch), 0, name .. ": decode = stream")
|
||||
t:check(a.meta.source.format == "mp3" and a.meta.source.layer == dec.layer, name .. ": meta.source")
|
||||
t:eq(Mp3.sniff(Bytes.reader(buf)) > 0.5, true, name .. ": sniff")
|
||||
|
||||
t:note("%-20s L%d MPEG-%s %5d Hz %d ch %6d frames %3d kbps SNR minimp3 %s, ffmpeg %.1f dB", name, dec.layer, tostring(dec.version), dec.sampleRate, ch, dec.frames, dec.bitrate, if ref then string.format("%.1f", worst) else "-", worstFF)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ robustness
|
||||
local function concat(...: buffer): buffer
|
||||
local n = 0
|
||||
for _, b in { ... } do
|
||||
n += buffer.len(b)
|
||||
end
|
||||
local out = buffer.create(n)
|
||||
local o = 0
|
||||
for _, b in { ... } do
|
||||
buffer.copy(out, o, b, 0)
|
||||
o += buffer.len(b)
|
||||
end
|
||||
return out
|
||||
end
|
||||
local function slice(b: buffer, i: number, j: number): buffer
|
||||
local out = buffer.create(j - i)
|
||||
buffer.copy(out, 0, b, i, j - i)
|
||||
return out
|
||||
end
|
||||
-- decodes everything; checks every sample is finite; returns pcm, frames, decoder
|
||||
local function decodeAll(b: buffer, label: string): (buffer?, number, any)
|
||||
local ok, dec, err = pcall(open, b)
|
||||
t:check(ok, label .. ": open does not throw (" .. tostring(dec) .. ")")
|
||||
if not dec then
|
||||
return nil, 0, err
|
||||
end
|
||||
local ok2, pcm, n = pcall(dec.readAll, dec)
|
||||
t:check(ok2, label .. ": decode does not throw (" .. tostring(pcm) .. ")")
|
||||
local bad = 0
|
||||
for i = 0, n * dec.channels - 1 do
|
||||
local v = buffer.readf32(pcm, i * 4)
|
||||
if v ~= v or v == math.huge or v == -math.huge then
|
||||
bad += 1
|
||||
end
|
||||
end
|
||||
t:eq(bad, 0, label .. ": finite samples")
|
||||
return pcm, n, dec
|
||||
end
|
||||
|
||||
-- the same pseudo-random sequence as mp3-luau's robust.luau (its junk is known not to chain into frames)
|
||||
local orandRaw = T.rng(777)
|
||||
local function orand(n: number): number -- 1..n
|
||||
return orandRaw(n) + 1
|
||||
end
|
||||
local base = file("l3_cbr128_js")
|
||||
local refPcm, refN, refDec = decodeAll(base, "base")
|
||||
assert(refPcm)
|
||||
|
||||
-- garbage before the first frame (with fake sync words): same output, bit for bit
|
||||
do
|
||||
local junk = buffer.create(5000)
|
||||
for i = 0, 4999 do
|
||||
buffer.writeu8(junk, i, (orand(256) - 1))
|
||||
end
|
||||
for i = 0, 4999, 97 do
|
||||
buffer.writeu8(junk, i, 0xFF)
|
||||
if i + 1 < 5000 then
|
||||
buffer.writeu8(junk, i + 1, 0xFB)
|
||||
end
|
||||
end
|
||||
local pcm, n, dec = decodeAll(concat(junk, base), "garbage prefix")
|
||||
t:check(n == refN and dec.frames == refN, string.format("garbage prefix: same length (%d %d vs %d)", n, dec.frames, refN))
|
||||
t:check(pcm and maxDiff(pcm, 0, refPcm, 0, n * 2) == 0, "garbage prefix: same samples")
|
||||
end
|
||||
-- garbage in the middle: re-syncs, keeps going
|
||||
do
|
||||
local half = buffer.len(base) // 2
|
||||
local junk = buffer.create(3333)
|
||||
for i = 0, 3332 do
|
||||
buffer.writeu8(junk, i, (orand(256) - 1))
|
||||
end
|
||||
local _, n = decodeAll(concat(slice(base, 0, half), junk, slice(base, half, buffer.len(base))), "garbage middle")
|
||||
t:check(math.abs(n - refN) <= 4 * 1152, string.format("garbage middle: %d frames vs %d", n, refN))
|
||||
end
|
||||
-- corrupt bytes all over the stream
|
||||
do
|
||||
local b = buffer.create(buffer.len(base))
|
||||
buffer.copy(b, 0, base)
|
||||
for _ = 1, 60 do
|
||||
buffer.writeu8(b, 1000 + orand(buffer.len(b) - 1001), (orand(256) - 1))
|
||||
end
|
||||
local _, n = decodeAll(b, "corrupt bytes")
|
||||
t:check(n > refN // 2, "corrupt bytes: most frames decode")
|
||||
end
|
||||
-- truncated anywhere
|
||||
for _ = 1, 25 do
|
||||
local cut = orand(buffer.len(base))
|
||||
local _, n = decodeAll(slice(base, 0, cut), "truncated at " .. cut)
|
||||
t:check(n <= refN, "truncated: not longer")
|
||||
end
|
||||
-- a stereo stream (no Xing tag) then a mono one of the same rate -> stereo, the mono part in both channels
|
||||
do
|
||||
local stereo = file("l3_noreservoir")
|
||||
local mono = file("l3_vbr_v7_mono")
|
||||
local _, stereoN = decodeAll(stereo, "stereo alone")
|
||||
local _, monoN = decodeAll(mono, "mono alone")
|
||||
local pcm, n, dec = decodeAll(concat(stereo, mono), "stereo then mono")
|
||||
t:check(dec and dec.channels == 2, "switch: stereo output")
|
||||
t:check(n >= stereoN + monoN, "switch: both parts decode")
|
||||
local same = true
|
||||
for i = n - 3000, n - 2000 do
|
||||
if buffer.readf32(pcm :: buffer, i * 8) ~= buffer.readf32(pcm :: buffer, i * 8 + 4) then
|
||||
same = false
|
||||
end
|
||||
end
|
||||
t:check(same, "switch: mono part duplicated")
|
||||
end
|
||||
-- bad input and API misuse
|
||||
do
|
||||
local d, err = open(buffer.create(0))
|
||||
t:check(d == nil and Err.is(err) and err.code == Err.CORRUPT, "empty buffer")
|
||||
d = open(string.rep("not an mp3 file at all ", 500))
|
||||
t:check(d == nil, "text")
|
||||
t:check(open(buffer.create(100000)) == nil, "zeros")
|
||||
local ffs = buffer.create(100000)
|
||||
buffer.fill(ffs, 0, 0xFF)
|
||||
t:check(pcall(function()
|
||||
local dd = open(ffs)
|
||||
if dd then
|
||||
dd:readAll()
|
||||
end
|
||||
end), "all 0xFF")
|
||||
local _, lerr = open(base, { maxFrames = 1000 })
|
||||
t:check(lerr and lerr.code == Err.LIMIT, "maxFrames")
|
||||
local dec = refDec
|
||||
dec:seek(0)
|
||||
t:eq(select(2, dec:read(-5)), 0, "read(-5)")
|
||||
t:eq(select(2, dec:read(nil :: any)), 4096, "read(nil) = 4096 frames")
|
||||
dec:seek(nil :: any)
|
||||
t:eq(select(2, dec:position()), 0, "seek(nil)")
|
||||
dec:seek(0 / 0)
|
||||
t:check(select(2, dec:position()) >= 0, "seek(nan)")
|
||||
t:eq(select(2, dec:read(0 / 0)), 0, "read(nan)")
|
||||
t:eq(Mp3.sniff(Bytes.reader(buffer.fromstring("RIFF....WAVEfmt "))), 0, "sniff a WAV")
|
||||
t:eq(Mp3.sniff(Bytes.reader(buffer.create(0))), 0, "sniff nothing")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ tags
|
||||
local function eq(a: any, b: any, label: string)
|
||||
t:eq(a, b, label)
|
||||
end
|
||||
do
|
||||
local dec = assert(open(file("l3_tags")))
|
||||
local tg = dec.tags
|
||||
eq(dec.id3.id3v2, "2.3", "fixture id3v2")
|
||||
eq(tg.title, "Test Title", "fixture title")
|
||||
eq(tg.artist, "Some Artist", "fixture artist")
|
||||
eq(tg.album, "An Album", "fixture album")
|
||||
eq(tg.year, "2001", "fixture year")
|
||||
eq(tg.track, "7", "fixture track")
|
||||
eq(tg.genre, "Rock", "fixture genre")
|
||||
eq(tg.comment, "hello", "fixture comment")
|
||||
t:check(dec.id3.id3v1, "fixture id3v1")
|
||||
for k, v in tg do
|
||||
t:check(type(k) == "string" and type(v) == "string", "tags are strings")
|
||||
end
|
||||
end
|
||||
|
||||
local audio = file("l3_mpeg25_8k")
|
||||
local plain = assert(open(audio))
|
||||
local plainPcm, plainN = plain:readAll()
|
||||
|
||||
local function syncsafe(n: number): string
|
||||
return string.char(bit32.band(bit32.rshift(n, 21), 127), bit32.band(bit32.rshift(n, 14), 127), bit32.band(bit32.rshift(n, 7), 127), bit32.band(n, 127))
|
||||
end
|
||||
local function be32(n: number): string
|
||||
return string.char(bit32.rshift(n, 24), bit32.band(bit32.rshift(n, 16), 255), bit32.band(bit32.rshift(n, 8), 255), bit32.band(n, 255))
|
||||
end
|
||||
local function le32(n: number): string
|
||||
return string.char(bit32.band(n, 255), bit32.band(bit32.rshift(n, 8), 255), bit32.band(bit32.rshift(n, 16), 255), bit32.rshift(n, 24))
|
||||
end
|
||||
local function be24(n: number): string
|
||||
return string.char(bit32.rshift(n, 16), bit32.band(bit32.rshift(n, 8), 255), bit32.band(n, 255))
|
||||
end
|
||||
local function utf16le(s: string): string
|
||||
local out = { "\xFF\xFE" }
|
||||
for _, cp in utf8.codes(s) do
|
||||
if cp >= 0x10000 then
|
||||
local v = cp - 0x10000
|
||||
local hi, lo = 0xD800 + bit32.rshift(v, 10), 0xDC00 + bit32.band(v, 0x3FF)
|
||||
table.insert(out, string.char(bit32.band(hi, 255), bit32.rshift(hi, 8), bit32.band(lo, 255), bit32.rshift(lo, 8)))
|
||||
else
|
||||
table.insert(out, string.char(bit32.band(cp, 255), bit32.rshift(cp, 8)))
|
||||
end
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
local function withAudio(prefix: string, suffix: string?): buffer
|
||||
return buffer.fromstring(prefix .. buffer.tostring(audio) .. (suffix or ""))
|
||||
end
|
||||
local function sameAudio(dec: any, label: string)
|
||||
eq(dec.frames, plain.frames, label .. ": frames")
|
||||
local pcm, n = dec:readAll()
|
||||
t:check(n == plainN and maxDiff(pcm, 0, plainPcm, 0, n) == 0, label .. ": same samples")
|
||||
end
|
||||
|
||||
-- ID3v2.4: UTF-8, syncsafe frame sizes, an extended header, multi-value TPE1, numeric TCON, padding
|
||||
do
|
||||
local function frame(id: string, body: string): string
|
||||
return id .. syncsafe(#body) .. "\0\0" .. body
|
||||
end
|
||||
local frames = frame("TIT2", "\3Ünïcödé ★ title") .. frame("TPE1", "\3One\0Two") .. frame("TCON", "\3(17)") .. frame("TDRC", "\0" .. "1999-05-01") .. frame("COMM", "\3eng\0a comment") .. string.rep("\0", 64)
|
||||
local body = syncsafe(6) .. "\1\0" .. frames
|
||||
local tag = "ID3\4\0\x40" .. syncsafe(#body) .. body
|
||||
local dec = assert(open(withAudio(tag)))
|
||||
eq(dec.id3.id3v2, "2.4", "v2.4 version")
|
||||
eq(dec.tags.title, "Ünïcödé ★ title", "v2.4 title")
|
||||
eq(dec.tags.artist, "One / Two", "v2.4 multi-value")
|
||||
eq(dec.tags.genre, "Rock", "v2.4 genre")
|
||||
eq(dec.tags.year, "1999-05-01", "v2.4 TDRC")
|
||||
eq(dec.tags.comment, "a comment", "v2.4 COMM")
|
||||
sameAudio(dec, "v2.4")
|
||||
t:check(Mp3.sniff(Bytes.reader(withAudio(tag))) >= 0.7, "sniff behind an ID3v2 tag")
|
||||
end
|
||||
-- ID3v2.3: UTF-16 with BOM (incl. a surrogate pair), latin-1, whole-tag unsynchronisation
|
||||
do
|
||||
local function frame(id: string, body: string): string
|
||||
return id .. be32(#body) .. "\0\0" .. body
|
||||
end
|
||||
local frames = frame("TIT2", "\1" .. utf16le("Grüße 𝄞")) .. frame("TALB", "\0Caf\xE9") .. frame("TRCK", "\0" .. "3/12") .. frame("TCON", "\0" .. "Electronic")
|
||||
local unsync = string.gsub(frames, "\xFF", "\xFF\0")
|
||||
local tag = "ID3\3\0\x80" .. syncsafe(#unsync) .. unsync
|
||||
local dec = assert(open(withAudio(tag)))
|
||||
eq(dec.id3.id3v2, "2.3", "v2.3 version")
|
||||
eq(dec.tags.title, "Grüße 𝄞", "v2.3 UTF-16 title")
|
||||
eq(dec.tags.album, "Café", "v2.3 latin-1 album")
|
||||
eq(dec.tags.track, "3/12", "v2.3 track")
|
||||
eq(dec.tags.genre, "Electronic", "v2.3 genre")
|
||||
eq(dec.id3.raw.TALB, "Café", "raw frame")
|
||||
sameAudio(dec, "v2.3")
|
||||
end
|
||||
-- ID3v2.2: 3-character ids, 24-bit sizes
|
||||
do
|
||||
local function frame(id: string, body: string): string
|
||||
return id .. be24(#body) .. body
|
||||
end
|
||||
local frames = frame("TT2", "\0Old Title") .. frame("TP1", "\0Old Artist") .. frame("TCO", "\0(8)") .. frame("COM", "\0eng\0old comment")
|
||||
local tag = "ID3\2\0\0" .. syncsafe(#frames) .. frames
|
||||
local dec = assert(open(withAudio(tag)))
|
||||
eq(dec.id3.id3v2, "2.2", "v2.2 version")
|
||||
eq(dec.tags.title, "Old Title", "v2.2 title")
|
||||
eq(dec.tags.artist, "Old Artist", "v2.2 artist")
|
||||
eq(dec.tags.genre, "Jazz", "v2.2 genre")
|
||||
eq(dec.tags.comment, "old comment", "v2.2 comment")
|
||||
sameAudio(dec, "v2.2")
|
||||
end
|
||||
-- ID3v1.1 alone (track byte), then APEv2 + ID3v1 at the end
|
||||
do
|
||||
local function pad(s: string, n: number): string
|
||||
return s .. string.rep("\0", n - #s)
|
||||
end
|
||||
local v1 = "TAG" .. pad("V1 Title", 30) .. pad("V1 Artist", 30) .. pad("V1 Album", 30) .. "1987" .. pad("v1 comment", 28) .. "\0\9" .. "\17"
|
||||
local dec = assert(open(withAudio("", v1)))
|
||||
t:check(dec.id3.id3v1, "v1 flag")
|
||||
eq(dec.tags.title, "V1 Title", "v1 title")
|
||||
eq(dec.tags.artist, "V1 Artist", "v1 artist")
|
||||
eq(dec.tags.album, "V1 Album", "v1 album")
|
||||
eq(dec.tags.year, "1987", "v1 year")
|
||||
eq(dec.tags.comment, "v1 comment", "v1 comment")
|
||||
eq(dec.tags.track, "9", "v1.1 track")
|
||||
eq(dec.tags.genre, "Rock", "v1 genre")
|
||||
sameAudio(dec, "v1")
|
||||
local item = "\5\0\0\0" .. "\0\0\0\0" .. "Title\0" .. "hello"
|
||||
local size = #item + 32
|
||||
local function apeHdr(isHeader: boolean): string
|
||||
local flags = if isHeader then "\0\0\0\xA0" else "\0\0\0\x80"
|
||||
return "APETAGEX" .. "\xD0\7\0\0" .. le32(size) .. "\1\0\0\0" .. flags .. string.rep("\0", 8)
|
||||
end
|
||||
local ape = apeHdr(true) .. item .. apeHdr(false)
|
||||
local dec2 = assert(open(withAudio("", ape .. v1)))
|
||||
t:check(dec2.id3.ape, "ape flag")
|
||||
eq(dec2.tags.title, "V1 Title", "ape + v1 title")
|
||||
sameAudio(dec2, "ape + v1")
|
||||
end
|
||||
-- a truncated ID3v2 tag never throws
|
||||
do
|
||||
local tag = "ID3\3\0\0" .. syncsafe(5000) .. "TIT2" .. be32(4000) .. "\0\0\0abc"
|
||||
local ok, dec = pcall(open, withAudio(tag))
|
||||
t:check(ok, "truncated tag does not throw")
|
||||
t:check(dec == nil or dec.frames <= plain.frames, "truncated tag")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ through the api
|
||||
do
|
||||
local F = require("@formats")
|
||||
local data = byName.l3_tags.data
|
||||
t:eq(F.detect(data), "mp3", "F.detect")
|
||||
local a, err = F.audio.load(data)
|
||||
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")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ fuzz
|
||||
do
|
||||
local samples = {}
|
||||
for _, name in { "l3_cbr32_mono", "l3_mpeg2_22k", "l3_mpeg25_8k", "l2_64_mono", "l2_mpeg2_24k", "l3_tags", "lame_cbr64_mono_22k" } do
|
||||
local s = byName[name].data
|
||||
table.insert(samples, string.sub(s, 1, math.min(#s, 6000)))
|
||||
end
|
||||
t:fuzz("open + read + seek", function(b: buffer)
|
||||
local dec = Mp3.open(Bytes.reader(b))
|
||||
if dec then
|
||||
dec:read(1 + rand(5000))
|
||||
dec:seek(dec.duration * rand(100) / 100)
|
||||
dec:read(1 + rand(5000))
|
||||
dec:seekFrame(rand(dec.frames + 1))
|
||||
dec:readAll()
|
||||
end
|
||||
Mp3.sniff(Bytes.reader(b))
|
||||
return dec
|
||||
end, samples, { mutations = 12 })
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Mp3.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 4, garbage = 50 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,445 @@
|
||||
-- audio/opus tests: every fixture (opusenc / ffmpeg libopus: CELT frame sizes and bitrates, SILK NB / MB / WB, hybrid,
|
||||
-- mode transitions, 5.1 multistream, a long tagged file) through open / read against opusdec --float (frame counts,
|
||||
-- SNR per fixture), CELT-only and SILK-only decoding with the private decoders alone, SILK packet loss concealment,
|
||||
-- tags, seeking, the stereo downmix, decode() to an Audio, the contract, sniff, error codes, random / bit-flipped
|
||||
-- packets through the packet decoder, and the fuzz no-throw pass over whole files.
|
||||
-- Ported from opus-luau tests/opus.luau, celt.luau, silk.luau, fuzz.luau. Fixtures: tools/fixtures/opus.py.
|
||||
local T = require("@tests/T")
|
||||
local Opus = require("@formats/audio/opus")
|
||||
local Packet = require("@formats/audio/opus/Packet")
|
||||
local Celt = require("@formats/audio/opus/Celt")
|
||||
local Silk = require("@formats/audio/opus/Silk")
|
||||
local RD = require("@formats/audio/opus/RangeDecoder")
|
||||
local Decoder = require("@formats/audio/opus/Decoder")
|
||||
local Ogg = require("@formats/containers/Ogg")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
|
||||
local t = T.suite("opus")
|
||||
|
||||
local FX: { [string]: any } = {}
|
||||
for _, f in
|
||||
{
|
||||
require("@tests/gen/opus_celt_st_128"),
|
||||
require("@tests/gen/opus_celt_st_32"),
|
||||
require("@tests/gen/opus_celt_st_64"),
|
||||
require("@tests/gen/opus_celt_st_256"),
|
||||
require("@tests/gen/opus_celt_mono_64"),
|
||||
require("@tests/gen/opus_celt_fs2_5"),
|
||||
require("@tests/gen/opus_celt_fs5"),
|
||||
require("@tests/gen/opus_celt_fs10"),
|
||||
require("@tests/gen/opus_celt_fs40"),
|
||||
require("@tests/gen/opus_celt_fs60"),
|
||||
require("@tests/gen/opus_silk_nb"),
|
||||
require("@tests/gen/opus_silk_mb"),
|
||||
require("@tests/gen/opus_silk_wb"),
|
||||
require("@tests/gen/opus_silk_wb_st"),
|
||||
require("@tests/gen/opus_silk_nb_st"),
|
||||
require("@tests/gen/opus_hybrid_swb"),
|
||||
require("@tests/gen/opus_hybrid_fb"),
|
||||
require("@tests/gen/opus_hybrid_st"),
|
||||
require("@tests/gen/opus_mix_st_24"),
|
||||
require("@tests/gen/opus_surround51"),
|
||||
require("@tests/gen/opus_long_128"),
|
||||
require("@tests/gen/opus_ff_cbr"),
|
||||
require("@tests/gen/opus_ff_voip"),
|
||||
require("@tests/gen/opus_ff_lowdelay"),
|
||||
}
|
||||
do
|
||||
FX[f.name] = { data = buffer.fromstring(f.data), ref = buffer.fromstring(f.ref), raw = f.data }
|
||||
end
|
||||
|
||||
-- SNR in dB of f32 samples against a reference over n samples; returns snr, max abs error
|
||||
local function snr(out: buffer, ref: buffer, n: number, outOff: number?, refOff: number?): (number, number)
|
||||
local oo, ro = outOff or 0, refOff or 0
|
||||
local sig, err, maxe = 0, 0, 0
|
||||
for i = 0, n - 1 do
|
||||
local r = buffer.readf32(ref, ro + i * 4)
|
||||
local e = buffer.readf32(out, oo + i * 4) - r
|
||||
sig += r * r
|
||||
err += e * e
|
||||
if math.abs(e) > maxe then
|
||||
maxe = math.abs(e)
|
||||
end
|
||||
end
|
||||
if err == 0 then
|
||||
return 999, 0
|
||||
end
|
||||
return 10 * math.log10(sig / err), maxe
|
||||
end
|
||||
|
||||
-- the packets of the first stream: { data, offset, size }
|
||||
local function packets(buf: buffer): { any }
|
||||
local d = Ogg.open(buf)
|
||||
local out = {}
|
||||
for p in d:packets(d:streams()[1].serial) do
|
||||
table.insert(out, p)
|
||||
end
|
||||
return out
|
||||
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: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")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ open / read vs opusdec
|
||||
-- name, minimum SNR (dB). CELT is float-exact (> 130 dB in practice), SILK bit-exact; hybrid / transitions mix both.
|
||||
local cases = {
|
||||
{ "celt_st_128", 100 }, { "celt_st_32", 100 }, { "celt_st_64", 100 }, { "celt_st_256", 100 },
|
||||
{ "celt_mono_64", 100 }, { "celt_fs2_5", 100 }, { "celt_fs5", 100 }, { "celt_fs10", 100 },
|
||||
{ "celt_fs40", 100 }, { "celt_fs60", 100 }, { "ff_cbr", 100 }, { "ff_lowdelay", 100 },
|
||||
{ "silk_nb", 90 }, { "silk_nb_st", 90 }, { "silk_mb", 90 }, { "silk_wb", 90 }, { "silk_wb_st", 90 },
|
||||
{ "hybrid_swb", 60 }, { "hybrid_fb", 60 }, { "hybrid_st", 60 }, { "mix_st_24", 60 }, { "ff_voip", 60 },
|
||||
{ "surround51", 100 }, { "long_128", 100 },
|
||||
}
|
||||
for _, case in cases do
|
||||
local name, minSnr = case[1], case[2]
|
||||
local fx = FX[name]
|
||||
local dec, err = Opus.open(Bytes.reader(fx.data))
|
||||
t:check(dec, name .. ": open: " .. tostring(err))
|
||||
local ch = dec.channels
|
||||
local refFrames = buffer.len(fx.ref) // 4 // ch
|
||||
t:eq(dec.frames, refFrames, name .. ": frames")
|
||||
t:check(dec.sampleRate == 48000 and type(dec.duration) == "number" and type(dec.bitrate) == "number" and type(dec.tags) == "table", name .. ": Decoder fields")
|
||||
local out = buffer.create(dec.frames * ch * 4 + 4096)
|
||||
local total = 0
|
||||
local t0 = os.clock()
|
||||
while true do
|
||||
local pcm, n = dec:read(1000 + total % 3001)
|
||||
if n == 0 then
|
||||
break
|
||||
end
|
||||
t:eq(buffer.len(pcm), n * ch * 4, name .. ": read buffer size")
|
||||
buffer.copy(out, total * ch * 4, pcm, 0, n * ch * 4)
|
||||
total += n
|
||||
end
|
||||
local dt = os.clock() - t0
|
||||
t:eq(total, refFrames, name .. ": decoded frames")
|
||||
local db, maxe = snr(out, fx.ref, refFrames * ch)
|
||||
t:note("%-12s %d ch %7d frames SNR %6.1f dB max err %.2g %.0fx real time", name, ch, total, db, maxe, dec.duration / math.max(dt, 1e-6))
|
||||
t:check(db >= minSnr, string.format("%s: SNR %.1f >= %d dB", name, db, minSnr))
|
||||
t:check(math.abs(dec:position() - dec.duration) < 1e-9, name .. ": position at end")
|
||||
end
|
||||
|
||||
-- read into a caller buffer, decode() to an Audio, a sub-range Reader
|
||||
do
|
||||
local fx = FX.hybrid_st
|
||||
local dec = Opus.open(Bytes.reader(fx.data))
|
||||
local into = buffer.create(4096 * 2 * 4)
|
||||
local pcm, n = dec:read(4096, into)
|
||||
t:check(pcm == into and n == 4096, "read(n, out) reuses out")
|
||||
local big = buffer.create(buffer.len(fx.data) + 33)
|
||||
buffer.copy(big, 17, fx.data)
|
||||
local a, err = Opus.decode(Bytes.reader(big, 17, buffer.len(fx.data)))
|
||||
t:check(a, "decode from a sub-range: " .. tostring(err))
|
||||
t:check(a.kind == "audio" and a.sampleRate == 48000 and a.channels == 2, "decode: an Audio")
|
||||
t:eq(a.frames, buffer.len(fx.ref) // 8, "decode: frames")
|
||||
t:check(snr(a.samples, fx.ref, a.frames * 2) >= 60, "decode: samples")
|
||||
t:eq(a.meta.source.format, "opus", "decode: meta.source")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ tags, seeking
|
||||
do
|
||||
local dec = Opus.open(Bytes.reader(FX.long_128.data))
|
||||
t:eq(dec.tags.title, "Long Test", "tags: title")
|
||||
t:eq(dec.tags.artist, "opus-luau", "tags: artist")
|
||||
t:check(dec.sampleRate == 48000 and dec.channels == 2, "info")
|
||||
t:check(math.abs(dec.duration - 12) < 0.01, "duration ~12 s")
|
||||
t:check(dec.bitrate > 100000 and dec.bitrate < 200000, "bitrate ~128 kbps: " .. dec.bitrate)
|
||||
-- 80 ms pre-roll makes the decoder state converge after a seek
|
||||
local ref = FX.long_128.ref
|
||||
for _, s in { 0, 0.001, 1.5, 3.21, 6.0, 9.99, 11.7, 2.0, 0.05 } do
|
||||
dec:seek(s)
|
||||
local p = math.floor(s * 48000 + 0.5)
|
||||
t:check(math.abs(dec:position() - p / 48000) < 1e-9, string.format("seek %.3f: position", s))
|
||||
local pcm, n = dec:read(12000)
|
||||
t:eq(n, math.min(12000, dec.frames - p), string.format("seek %.3f: read", s))
|
||||
local db = snr(pcm, ref, n * 2, 0, p * 2 * 4)
|
||||
t:check(db > 50, string.format("seek %.3f: SNR %.1f > 50 dB", s, db))
|
||||
end
|
||||
dec:seek(100)
|
||||
local _, n = dec:read(100)
|
||||
t:eq(n, 0, "seek past the end reads nothing")
|
||||
dec:seek(0)
|
||||
local _, n2 = dec:read(100)
|
||||
t:eq(n2, 100, "seek back to 0")
|
||||
dec:seek(0 / 0)
|
||||
t:eq(dec:position(), 0, "seek(nan) goes to 0")
|
||||
end
|
||||
|
||||
-- stereo downmix of the 5.1 file: the same matrix applied to the reference
|
||||
do
|
||||
local fx = FX.surround51
|
||||
local dec = Opus.open(Bytes.reader(fx.data), { stereo = true })
|
||||
t:check(dec.channels == 2 and dec.sourceChannels == 6, "downmix: 2 output channels")
|
||||
local pcm, n = dec:read(dec.frames)
|
||||
t:eq(n, dec.frames, "downmix: all frames")
|
||||
local m = { 0.529, 0, 0.3741, 0.3741, 0, 0.529, 0.4582, 0.2645, 0.2645, 0.4582, 0.3741, 0.3741 }
|
||||
local exp = buffer.create(n * 8)
|
||||
for i = 0, n - 1 do
|
||||
local l, r = 0, 0
|
||||
for c = 0, 5 do
|
||||
local v = buffer.readf32(fx.ref, (i * 6 + c) * 4)
|
||||
l += v * m[c * 2 + 1]
|
||||
r += v * m[c * 2 + 2]
|
||||
end
|
||||
buffer.writef32(exp, i * 8, l)
|
||||
buffer.writef32(exp, i * 8 + 4, r)
|
||||
end
|
||||
local db = snr(pcm, exp, n * 2)
|
||||
t:check(db > 100, string.format("downmix SNR %.1f", db))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ CELT alone
|
||||
do
|
||||
local endbands = { [Packet.BW_NB] = 13, [Packet.BW_MB] = 17, [Packet.BW_WB] = 17, [Packet.BW_SWB] = 19, [Packet.BW_FB] = 21 }
|
||||
for _, name in { "celt_st_128", "celt_st_32", "celt_st_64", "celt_st_256", "celt_mono_64", "celt_fs2_5", "celt_fs5", "celt_fs10", "celt_fs40", "celt_fs60", "ff_cbr", "ff_lowdelay" } do
|
||||
local fx = FX[name]
|
||||
local pk = packets(fx.data)
|
||||
local head = pk[1]
|
||||
local channels = buffer.readu8(head.data, head.offset + 9)
|
||||
local preskip = buffer.readu16(head.data, head.offset + 10)
|
||||
local st = Celt.new(channels)
|
||||
local out = {}
|
||||
local total = 0
|
||||
local offs, sizes = {}, {}
|
||||
local allOk = true
|
||||
for p = 3, #pk do
|
||||
local P = pk[p]
|
||||
local count, toc = Packet.parse(P.data, P.offset, P.size, offs, sizes)
|
||||
allOk = allOk and count > 0 and Packet.mode(toc) == Packet.MODE_CELT_ONLY
|
||||
local fs48 = Packet.samplesPerFrame(toc, 48000)
|
||||
st["end"] = endbands[Packet.bandwidth(toc)]
|
||||
st.stream_channels = Packet.channels(toc)
|
||||
for f = 1, count do
|
||||
local ret = Celt.decode(st, P.data, offs[f], sizes[f], out, 1 + total * channels, fs48, nil, false)
|
||||
allOk = allOk and ret == fs48
|
||||
total += fs48
|
||||
end
|
||||
end
|
||||
t:check(allOk, name .. ": every packet is CELT-only and decodes")
|
||||
local refFrames = buffer.len(fx.ref) // 4 // channels
|
||||
t:check(total - preskip >= refFrames and total - preskip - refFrames < 960 * 3, name .. ": CELT sample count")
|
||||
local n = refFrames * channels
|
||||
local ob = buffer.create(n * 4)
|
||||
for i = 0, n - 1 do
|
||||
buffer.writef32(ob, i * 4, out[preskip * channels + i + 1])
|
||||
end
|
||||
local db = snr(ob, fx.ref, n)
|
||||
t:check(db > 60, string.format("%s: CELT alone SNR %.1f > 60 dB", name, db))
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ SILK alone
|
||||
do
|
||||
local rates = { [Packet.BW_NB] = 8000, [Packet.BW_MB] = 12000, [Packet.BW_WB] = 16000 }
|
||||
local function decodeSilk(name: string, hybridOk: boolean?, lose: boolean?): ({ number }, number, number, number)
|
||||
local pk = packets(FX[name].data)
|
||||
local channels = buffer.readu8(pk[1].data, pk[1].offset + 9)
|
||||
local preskip = buffer.readu16(pk[1].data, pk[1].offset + 10)
|
||||
local st = Silk.new(channels)
|
||||
local out = {}
|
||||
local total = 0
|
||||
local offs, sizes = {}, {}
|
||||
local allOk = true
|
||||
for p = 3, #pk do
|
||||
local P = pk[p]
|
||||
local count, toc = Packet.parse(P.data, P.offset, P.size, offs, sizes)
|
||||
local mode = Packet.mode(toc)
|
||||
allOk = allOk and count > 0 and (mode == Packet.MODE_SILK_ONLY or (hybridOk == true and mode == Packet.MODE_HYBRID))
|
||||
local fs48 = Packet.samplesPerFrame(toc, 48000)
|
||||
local lostPacket = lose and p % 7 == 0 and p < #pk - 80
|
||||
local ctrl = {
|
||||
nChannelsAPI = channels,
|
||||
nChannelsInternal = Packet.channels(toc),
|
||||
API_sampleRate = 48000,
|
||||
internalSampleRate = if mode == Packet.MODE_HYBRID then 16000 else rates[Packet.bandwidth(toc)],
|
||||
payloadSize_ms = math.max(10, fs48 // 48),
|
||||
}
|
||||
for f = 1, count do
|
||||
local lost = if lostPacket or sizes[f] <= 1 then 1 else 0
|
||||
local ec = RD.new(P.data, offs[f], sizes[f])
|
||||
local decoded = 0
|
||||
repeat
|
||||
local ret, n = Silk.decode(st, ctrl, lost, decoded == 0, ec, out, 1 + (total + decoded) * channels)
|
||||
allOk = allOk and ret == 0
|
||||
decoded += n
|
||||
until decoded >= fs48 or n <= 0
|
||||
total += decoded
|
||||
end
|
||||
end
|
||||
t:check(allOk, name .. ": every packet is SILK and decodes")
|
||||
return out, total, channels, preskip
|
||||
end
|
||||
for _, name in { "silk_nb", "silk_nb_st", "silk_mb", "silk_wb", "silk_wb_st" } do
|
||||
local out, total, channels, preskip = decodeSilk(name)
|
||||
local ref = FX[name].ref
|
||||
local refFrames = buffer.len(ref) // 4 // channels
|
||||
t:check(total - preskip >= refFrames and total - preskip - refFrames < 960 * 3, name .. ": SILK sample count")
|
||||
local n = refFrames * channels
|
||||
local ob = buffer.create(n * 4)
|
||||
for i = 0, n - 1 do
|
||||
buffer.writef32(ob, i * 4, out[preskip * channels + i + 1])
|
||||
end
|
||||
local db = snr(ob, ref, n)
|
||||
t:check(db > 90, string.format("%s: SILK alone SNR %.1f > 90 dB", name, db))
|
||||
end
|
||||
local _, total = decodeSilk("hybrid_swb", true)
|
||||
t:check(total > 0, "hybrid_swb: SILK layer decodes")
|
||||
-- packet loss concealment: every 7th packet lost; output bounded, the last second matches again
|
||||
for _, name in { "silk_nb", "silk_wb_st" } do
|
||||
local out, tot, channels, preskip = decodeSilk(name, false, true)
|
||||
local finite = true
|
||||
for i = 1, tot * channels do
|
||||
local v = out[i]
|
||||
if v ~= v or math.abs(v) > 1 then
|
||||
finite = false
|
||||
end
|
||||
end
|
||||
t:check(finite, name .. ": PLC output bounded")
|
||||
local ref = FX[name].ref
|
||||
local refFrames = buffer.len(ref) // 4 // channels
|
||||
local n = 48000 * channels
|
||||
local from = (refFrames - 48000) * channels
|
||||
local ob = buffer.create(n * 4)
|
||||
for i = 0, n - 1 do
|
||||
buffer.writef32(ob, i * 4, out[preskip * channels + from + i + 1])
|
||||
end
|
||||
local db = snr(ob, ref, n, 0, from * 4)
|
||||
t:check(db > 15, string.format("%s: recovers after losses (last second SNR %.1f)", name, db))
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ errors
|
||||
do
|
||||
local d, err = Opus.open(Bytes.reader(buffer.fromstring("not an ogg file at all")))
|
||||
t:check(d == nil and err and err.code == Err.CORRUPT, "garbage is CORRUPT: " .. tostring(err))
|
||||
local _, e2 = Opus.open(Bytes.reader(FX.celt_st_128.data, 0, 40))
|
||||
t:check(e2 and Err.is(e2), "a cut header is an Err: " .. tostring(e2))
|
||||
local _, e3 = Opus.decode(Bytes.reader(buffer.create(0)))
|
||||
t:check(e3 and Err.is(e3), "empty decode is an Err")
|
||||
-- a truncated file opens and decodes its first half
|
||||
local file = FX.hybrid_st.data
|
||||
local cut = buffer.create(buffer.len(file) // 2)
|
||||
buffer.copy(cut, 0, file, 0, buffer.len(cut))
|
||||
local dec = Opus.open(Bytes.reader(cut))
|
||||
t:check(dec, "truncated file opens")
|
||||
local total = 0
|
||||
while true do
|
||||
local _, n = dec:read(4096)
|
||||
if n == 0 then
|
||||
break
|
||||
end
|
||||
total += n
|
||||
end
|
||||
t:check(total > 0, "truncated file decodes its first half")
|
||||
local a = Opus.decode(Bytes.reader(cut))
|
||||
t:check(a and a.frames == total, "decode of a truncated file keeps what decoded")
|
||||
-- damaged packets (CRC checks off, so they reach the decoder) never throw
|
||||
for _, name in { "celt_st_128", "hybrid_st", "silk_wb_st", "surround51" } do
|
||||
local g = buffer.create(buffer.len(FX[name].data))
|
||||
buffer.copy(g, 0, FX[name].data)
|
||||
local seed = 12345
|
||||
for i = 400, buffer.len(g) - 1, 97 do
|
||||
seed = (seed * 1103515245 + 12345) % 2147483648
|
||||
buffer.writeu8(g, i, bit32.bxor(buffer.readu8(g, i), seed % 256))
|
||||
end
|
||||
local dd = Opus.open(Bytes.reader(g), { verify = false })
|
||||
t:check(dd, name .. ": damaged file opens")
|
||||
local ok, e = pcall(function()
|
||||
while true do
|
||||
local _, n = dd:read(4096)
|
||||
if n == 0 then
|
||||
break
|
||||
end
|
||||
end
|
||||
end)
|
||||
t:check(ok, name .. ": damaged data decodes without error: " .. tostring(e))
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ packet fuzz
|
||||
-- random packets (every TOC config, random payloads) and bit-flipped real packets: never throw, output finite
|
||||
do
|
||||
local rand = T.rng(987654321)
|
||||
local pcm = table.create(5760 * 2, 0)
|
||||
local decoded, rejected, bad = 0, 0, 0
|
||||
local function run(dec: any, b: buffer, len: number)
|
||||
local ok, n = pcall(Decoder.decode, dec, b, 0, len, pcm, 1, 5760)
|
||||
if not ok then
|
||||
bad += 1
|
||||
return
|
||||
end
|
||||
if n > 0 then
|
||||
decoded += 1
|
||||
for i = 1, n * dec.channels do
|
||||
local v = pcm[i]
|
||||
if v ~= v or v == math.huge or v == -math.huge then
|
||||
bad += 1
|
||||
break
|
||||
end
|
||||
end
|
||||
else
|
||||
rejected += 1
|
||||
end
|
||||
end
|
||||
for _, ch in { 1, 2 } do
|
||||
local dec = Decoder.new(ch)
|
||||
for i = 1, 1500 do
|
||||
local len = 1 + rand(if rand(4) == 0 then 1275 else 120)
|
||||
local b = buffer.create(len)
|
||||
for k = 0, len - 1 do
|
||||
buffer.writeu8(b, k, rand(256))
|
||||
end
|
||||
buffer.writeu8(b, 0, (i * 7 + ch) % 256) -- cycle through every TOC
|
||||
run(dec, b, len)
|
||||
if rand(50) == 0 then
|
||||
Decoder.decode(dec, nil, 0, 0, pcm, 1, 960) -- concealment in between
|
||||
end
|
||||
end
|
||||
end
|
||||
for _, name in { "celt_st_128", "hybrid_st", "silk_wb_st", "mix_st_24", "celt_fs2_5" } do
|
||||
local pk = packets(FX[name].data)
|
||||
local dec = Decoder.new(2)
|
||||
for p = 3, #pk do
|
||||
local P = pk[p]
|
||||
local b = buffer.create(P.size)
|
||||
buffer.copy(b, 0, P.data, P.offset, P.size)
|
||||
for _ = 1, 1 + rand(4) do
|
||||
local k = 1 + rand(math.max(1, P.size - 1))
|
||||
if k < P.size then
|
||||
buffer.writeu8(b, k, bit32.bxor(buffer.readu8(b, k), bit32.lshift(1, rand(8))))
|
||||
end
|
||||
end
|
||||
run(dec, b, P.size)
|
||||
end
|
||||
end
|
||||
t:eq(bad, 0, "packet fuzz: no throws, finite output")
|
||||
t:note("packet fuzz: %d packets decoded, %d rejected", decoded, rejected)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ fuzz (whole files)
|
||||
do
|
||||
local samples = {}
|
||||
for _, name in { "hybrid_fb", "silk_nb", "celt_fs5" } do
|
||||
table.insert(samples, string.sub(FX[name].raw, 1, 6000))
|
||||
end
|
||||
t:fuzz("open + read", function(b: buffer)
|
||||
local dec = Opus.open(Bytes.reader(b), { verify = false })
|
||||
if dec then
|
||||
dec:read(2000)
|
||||
dec:seek(0.01)
|
||||
dec:read(500)
|
||||
end
|
||||
return dec
|
||||
end, samples, { mutations = 12, keepHeader = 4 })
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Opus.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 4, garbage = 50 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,314 @@
|
||||
-- audio/wav tests: every format / container / damaged variant from tools/fixtures/wav.py decoded in reads of mixed
|
||||
-- sizes against ffmpeg's (or sox's) f32 decode, with tags, seeking and output-buffer reuse; hand-built files (header
|
||||
-- parsing, errors, argument clamping, EXTENSIBLE with valid bits, the truncated flag); the encoder byte-exact against
|
||||
-- ffmpeg -bitexact (u8 / s16 / s24 / s32 / f32, 1-8 channels, > 48 kHz, RF64), round trips from an Audio and from a
|
||||
-- streaming Decoder, tags, encodeParts, the RF64 switch; the api (F.audio.load / open / save); the fuzz pass.
|
||||
-- Ported from wav-luau tests/core.luau + tests/decode.luau. Fixtures: tools/fixtures/wav.py.
|
||||
local T = require("@tests/T")
|
||||
local Wav = require("@formats/audio/wav")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local F = require("@formats")
|
||||
local Cases = require("@tests/gen/wav_cases")
|
||||
local Enc = require("@tests/gen/wav_enc")
|
||||
|
||||
local t = T.suite("wav")
|
||||
local TOL = 2e-6
|
||||
|
||||
local function open(s: any): (any, any)
|
||||
local b = if type(s) == "string" then buffer.fromstring(s) else s
|
||||
return Wav.open(Bytes.reader(b))
|
||||
end
|
||||
|
||||
-- little-endian packers (no string.pack on LuaJIT)
|
||||
local function u16(v: number): string
|
||||
local b = buffer.create(2)
|
||||
buffer.writeu16(b, 0, v % 65536)
|
||||
return buffer.tostring(b)
|
||||
end
|
||||
local function u32(v: number): string
|
||||
local b = buffer.create(4)
|
||||
buffer.writeu32(b, 0, v % 4294967296)
|
||||
return buffer.tostring(b)
|
||||
end
|
||||
local function i32(v: number): string
|
||||
local b = buffer.create(4)
|
||||
buffer.writei32(b, 0, v)
|
||||
return buffer.tostring(b)
|
||||
end
|
||||
local function f32(v: number): string
|
||||
local b = buffer.create(4)
|
||||
buffer.writef32(b, 0, v)
|
||||
return buffer.tostring(b)
|
||||
end
|
||||
local function i16s(...: number): string
|
||||
local out = {}
|
||||
for i, v in { ... } do
|
||||
out[i] = u16(if v < 0 then v + 65536 else v)
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
local function chunk(id: string, body: string): string
|
||||
local s = id .. u32(#body) .. body
|
||||
return if #body % 2 == 1 then s .. "\0" else s
|
||||
end
|
||||
local function fmt(tag: number, ch: number, rate: number, bits: number, extra: string?): string
|
||||
local ba = ch * ((bits + 7) // 8)
|
||||
return chunk("fmt ", u16(tag) .. u16(ch) .. u32(rate) .. u32(rate * ba) .. u16(ba) .. u16(bits) .. (extra or ""))
|
||||
end
|
||||
local function riff(...: string): string
|
||||
local body = "WAVE" .. table.concat({ ... })
|
||||
return "RIFF" .. u32(#body) .. body
|
||||
end
|
||||
|
||||
-- the contract
|
||||
t:eq(Wav.name, "wav", "name")
|
||||
t:eq(Wav.category, "audio", "category")
|
||||
t:check(Wav.caps.decode and Wav.caps.encode and Wav.open ~= nil, "caps / open")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ fixtures
|
||||
local function readAll(dec: any, sizes: { number }): (buffer, number)
|
||||
local out = buffer.create(dec.frames * dec.channels * 4)
|
||||
local got, i = 0, 0
|
||||
while true do
|
||||
i += 1
|
||||
local c, n = dec:read(sizes[(i - 1) % #sizes + 1])
|
||||
if n == 0 then
|
||||
break
|
||||
end
|
||||
buffer.copy(out, got * dec.channels * 4, c, 0, n * dec.channels * 4)
|
||||
got += n
|
||||
end
|
||||
return out, got
|
||||
end
|
||||
local function maxDiff(a: buffer, aOff: number, b: buffer, bOff: number, count: number): number
|
||||
local m = 0
|
||||
for i = 0, count - 1 do
|
||||
local d = math.abs(buffer.readf32(a, (aOff + i) * 4) - buffer.readf32(b, (bOff + i) * 4))
|
||||
if d > m then
|
||||
m = d
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for _, fx in Cases do
|
||||
local name = fx.name
|
||||
table.insert(samples, fx.file)
|
||||
local ref = buffer.fromstring(fx.ref)
|
||||
local dec, err = open(fx.file)
|
||||
t:check(dec, name .. ": open: " .. tostring(err))
|
||||
t:eq(dec.channels, fx.channels, name .. ": channels")
|
||||
t:eq(dec.sampleRate, fx.rate, name .. ": rate")
|
||||
t:eq(dec.format, fx.format, name .. ": format")
|
||||
t:eq(dec.container, fx.container, name .. ": container")
|
||||
t:eq(dec.frames, fx.frames, name .. ": frames")
|
||||
t:check(math.abs(dec.duration - fx.frames / fx.rate) < 1e-9, name .. ": duration")
|
||||
t:check(dec.bitrate > 0, name .. ": bitrate")
|
||||
for k, v in fx.tags or {} do
|
||||
t:eq(dec.tags[k], v, name .. ": tag " .. k)
|
||||
end
|
||||
local out, got = readAll(dec, { 1, 7, 333, 1000, 4096 })
|
||||
t:eq(got, fx.frames, name .. ": frames read")
|
||||
local d = maxDiff(out, 0, ref, 0, got * fx.channels)
|
||||
t:check(d <= TOL, string.format("%s: max sample error %g", name, d))
|
||||
t:eq(dec:position(), fx.frames / fx.rate, name .. ": position at the end")
|
||||
for _, f0 in { 1234, 0, fx.frames - 20, 517, 2047 } do
|
||||
local f = math.min(f0, fx.frames)
|
||||
dec:seek(f / fx.rate)
|
||||
t:eq(dec:tell(), f, name .. ": seek to " .. f)
|
||||
local c, n = dec:read(50)
|
||||
t:eq(n, math.min(50, fx.frames - f), name .. ": read after seek " .. f)
|
||||
t:check(maxDiff(c, 0, ref, f * fx.channels, n * fx.channels) <= TOL, name .. ": samples after seek " .. f)
|
||||
end
|
||||
dec:seek(0)
|
||||
local reuse = buffer.create(64 * fx.channels * 4)
|
||||
local b2, n2 = dec:read(64, reuse)
|
||||
t:check(b2 == reuse and n2 == 64, name .. ": output buffer reused")
|
||||
-- decode() = the whole stream as an Audio, also from a sub-range reader
|
||||
local big = buffer.create(#fx.file + 9)
|
||||
buffer.writestring(big, 5, fx.file)
|
||||
local a, aerr = Wav.decode(Bytes.reader(big, 5, #fx.file))
|
||||
t:check(a and a.kind == "audio" and a.frames == fx.frames, name .. ": decode: " .. tostring(aerr))
|
||||
t:check(maxDiff(a.samples, 0, ref, 0, a.frames * fx.channels) <= TOL, name .. ": decode samples")
|
||||
t:eq(a.meta.source.codec, fx.format, name .. ": meta.source.codec")
|
||||
end
|
||||
t:note("%d fixture files match ffmpeg / sox", #Cases)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ hand-built files
|
||||
do
|
||||
local dec = open(riff(fmt(1, 2, 8000, 16), chunk("data", i16s(16384, -16384, 32767, -32768))))
|
||||
t:check(dec, "open minimal")
|
||||
t:check(dec.frames == 2 and dec.channels == 2 and dec.sampleRate == 8000 and dec.bitrate == 8000 * 4 * 8, "minimal fields")
|
||||
t:check(dec.duration == 2 / 8000 and dec.blockAlign == 4 and dec.bitsPerSample == 16 and not dec.truncated, "minimal more")
|
||||
local out, n = dec:read(10)
|
||||
t:eq(n, 2, "read clamps to the stream")
|
||||
t:check(buffer.readf32(out, 0) == 0.5 and buffer.readf32(out, 4) == -0.5, "s16 values")
|
||||
t:check(buffer.readf32(out, 8) == 32767 / 32768 and buffer.readf32(out, 12) == -1, "s16 extremes")
|
||||
t:eq(select(2, dec:read(10)), 0, "end of stream = 0 frames")
|
||||
dec:seek(-5)
|
||||
t:eq(dec:tell(), 0, "seek negative")
|
||||
dec:seek(1e9)
|
||||
t:eq(dec:tell(), 2, "seek past the end")
|
||||
dec:seek(0 / 0)
|
||||
t:eq(dec:tell(), 0, "seek NaN")
|
||||
dec:seekFrame(1)
|
||||
t:eq(dec:position(), 1 / 8000, "seekFrame / position")
|
||||
t:eq(select(2, dec:read(-3)), 0, "read negative")
|
||||
t:eq(select(2, dec:read(0 / 0)), 0, "read NaN")
|
||||
local b, n5 = dec:read(1, buffer.create(2))
|
||||
t:check(n5 == 1 and buffer.len(b) == 8, "too-small output buffer is replaced")
|
||||
end
|
||||
do
|
||||
local dec = open(riff(fmt(1, 1, 8000, 16), "data" .. u32(1000) .. i16s(1, 2, 3) .. "\9"))
|
||||
t:check(dec and dec.frames == 3 and dec.truncated, "truncated: whole frames, flagged")
|
||||
end
|
||||
do -- EXTENSIBLE: 24 valid bits in a 32-bit container
|
||||
local guid = u16(1) .. "\0\0\0\0\16\0\128\0\0\170\0\56\155\113"
|
||||
local ext = u16(22) .. u16(24) .. u32(3) .. guid
|
||||
local dec = open(riff(fmt(0xFFFE, 2, 48000, 32, ext), chunk("data", i32(0x40000000) .. i32(-0x40000000))))
|
||||
t:check(dec and dec.format == "pcm" and dec.validBits == 24 and dec.channelMask == 3, "extensible fields")
|
||||
local out = dec:read(1)
|
||||
t:check(buffer.readf32(out, 0) == 0.5 and buffer.readf32(out, 4) == -0.5, "extensible values")
|
||||
local guidF = u16(3) .. string.sub(guid, 3)
|
||||
local fd = open(riff(fmt(0xFFFE, 1, 48000, 32, u16(22) .. u16(32) .. u32(4) .. guidF), chunk("data", f32(0.25))))
|
||||
t:check(fd and fd.format == "float" and buffer.readf32(fd:read(1), 0) == 0.25, "extensible float")
|
||||
local _, e = open(riff(fmt(0xFFFE, 1, 8000, 16), chunk("data", "\0\0")))
|
||||
t:check(e and e.code == Err.CORRUPT, "extensible without extension")
|
||||
end
|
||||
do -- tags
|
||||
local info = "INFO" .. "INAM" .. u32(3) .. "abc\0" .. "IART" .. u32(6) .. "xy\0\0\0\0" .. "IXYZ" .. u32(2) .. "zz" .. "ITRK" .. u32(2) .. "7\0"
|
||||
local dec = open(riff(fmt(1, 1, 8000, 8), chunk("LIST", info), chunk("data", "\128\128\128")))
|
||||
t:check(dec and dec.tags.title == "abc" and dec.tags.artist == "xy" and dec.tags.IXYZ == "zz" and dec.tags.track == "7", "tags")
|
||||
t:check(dec and dec.frames == 3, "8-bit odd data")
|
||||
end
|
||||
do -- 8-bit, A-law and mu-law values
|
||||
local o = open(riff(fmt(1, 1, 8000, 8), chunk("data", "\0\128\255"))):read(3)
|
||||
t:check(buffer.readf32(o, 0) == -1 and buffer.readf32(o, 4) == 0 and buffer.readf32(o, 8) == 127 / 128, "u8 values")
|
||||
local m = open(riff(fmt(7, 1, 8000, 8), chunk("data", "\255\127\0\128"))):read(4)
|
||||
t:check(buffer.readf32(m, 0) == 0 and buffer.readf32(m, 4) == 0, "mu-law zero")
|
||||
t:check(buffer.readf32(m, 8) == -32124 / 32768 and buffer.readf32(m, 12) == 32124 / 32768, "mu-law extremes")
|
||||
local a = open(riff(fmt(6, 1, 8000, 8), chunk("data", "\213\85\42\170"))):read(4)
|
||||
t:check(buffer.readf32(a, 0) == 8 / 32768 and buffer.readf32(a, 4) == -8 / 32768, "A-law smallest")
|
||||
t:check(buffer.readf32(a, 8) == -32256 / 32768 and buffer.readf32(a, 12) == 32256 / 32768, "A-law extremes")
|
||||
end
|
||||
do -- errors: nil, Err
|
||||
local function fails(s: any, code: string, pattern: string, label: string)
|
||||
local ok, dec, err = pcall(open, s)
|
||||
t:check(ok, label .. ": threw " .. tostring(dec))
|
||||
t:check(dec == nil and Err.is(err) and err.code == code and string.find(err.message, pattern) ~= nil, label .. ": " .. tostring(err))
|
||||
end
|
||||
fails("RIFF", Err.TRUNCATED, "too short", "too short")
|
||||
fails("RIFF\0\0\0\0AVI LIST", Err.CORRUPT, "not a WAVE", "AVI")
|
||||
fails("OggS\0\0\0\0WAVEfmt ", Err.CORRUPT, "not a RIFF", "ogg")
|
||||
fails(riff(chunk("data", "\0\0")), Err.CORRUPT, "no fmt", "no fmt")
|
||||
fails(riff(fmt(1, 2, 8000, 16)), Err.CORRUPT, "no data", "no data")
|
||||
fails(riff(fmt(0x55, 2, 8000, 16), chunk("data", "")), Err.UNSUPPORTED, "format 0x0055", "mp3 in wav")
|
||||
fails(riff(fmt(1, 0, 8000, 16), chunk("data", "")), Err.CORRUPT, "channel", "0 channels")
|
||||
fails(riff(fmt(1, 1, 0, 16), chunk("data", "")), Err.CORRUPT, "sample rate", "rate 0")
|
||||
fails(riff(fmt(3, 1, 8000, 16), chunk("data", "")), Err.UNSUPPORTED, "float size", "float16")
|
||||
fails(riff(fmt(1, 1, 8000, 40), chunk("data", "")), Err.UNSUPPORTED, "PCM size", "pcm 40")
|
||||
fails(riff(fmt(0x11, 2, 8000, 4), chunk("data", "")), Err.CORRUPT, "block", "ima block too small")
|
||||
t:eq(Wav.sniff(Bytes.reader(buffer.fromstring(riff(fmt(1, 1, 8000, 8))))), 1, "sniff")
|
||||
t:eq(Wav.sniff(Bytes.reader(buffer.fromstring("RIFF\0\0\0\0AVI "))), 0, "sniff AVI")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encoder
|
||||
do
|
||||
for _, c in Enc do
|
||||
local a = Types.Audio.new(c.rate, c.channels, c.frames)
|
||||
buffer.writestring(a.samples, 0, c.samples)
|
||||
local out, err = Wav.encode(a, { sampleFormat = c.kind, rf64 = if c.rf64 then true else nil })
|
||||
t:check(out, c.name .. ": encode: " .. tostring(err))
|
||||
local same = buffer.tostring(out :: buffer) == c.file
|
||||
if not same then
|
||||
t:note("%s: ours %s", c.name, T.hex(out :: buffer, 80))
|
||||
t:note("%s: ffmpeg %s", c.name, T.hex(buffer.fromstring(c.file), 80))
|
||||
end
|
||||
t:check(same, c.name .. ": identical to ffmpeg -bitexact")
|
||||
-- and back
|
||||
local back = Wav.decode(Bytes.reader(out :: buffer))
|
||||
t:check(back and back.frames == c.frames and buffer.tostring(back.samples) == c.samples, c.name .. ": round trip")
|
||||
-- from a streaming Decoder (our own, over ffmpeg's file)
|
||||
local dec = Wav.open(Bytes.reader(buffer.fromstring(c.file)))
|
||||
local out2 = Wav.encode(dec, { sampleFormat = c.kind, rf64 = if c.rf64 then true else nil })
|
||||
t:check(out2 and buffer.tostring(out2) == c.file, c.name .. ": encode from a Decoder")
|
||||
end
|
||||
t:note("encoder: %d files identical to ffmpeg -bitexact", #Enc)
|
||||
-- clamping and rounding
|
||||
local a = Types.Audio.new(8000, 1, 6)
|
||||
for i, v in { 2, -2, 0.5 / 32768, -0.5 / 32768, 1.5 / 32768, 0 / 0 } do
|
||||
buffer.writef32(a.samples, (i - 1) * 4, v)
|
||||
end
|
||||
local d = Wav.decode(Bytes.reader(Wav.encode(a) :: buffer)) :: any
|
||||
local want = { 32767, -32768, 1, 0, 2, 0 }
|
||||
for i, w in want do
|
||||
t:eq(math.floor(buffer.readf32(d.samples, (i - 1) * 4) * 32768 + 0.5), w, "s16 rounding / clamping " .. i)
|
||||
end
|
||||
-- tags
|
||||
a.tags = { title = "Hello", artist = "Someone", IXYZ = "kept", comment = "" }
|
||||
local tg = Wav.decode(Bytes.reader(Wav.encode(a, { sampleFormat = "u8" }) :: buffer)) :: any
|
||||
t:check(tg.tags.title == "Hello" and tg.tags.artist == "Someone" and tg.tags.IXYZ == "kept" and tg.tags.comment == nil, "tag round trip")
|
||||
-- encodeParts, and RF64 chosen automatically past the threshold
|
||||
local big = Types.Audio.new(44100, 2, 3000)
|
||||
for i = 0, 3000 * 2 - 1 do
|
||||
buffer.writef32(big.samples, i * 4, ((i * 37) % 200 - 100) / 128)
|
||||
end
|
||||
local parts = Wav.encodeParts(big, { rf64Threshold = 1000 }) :: { buffer }
|
||||
t:check(#parts >= 2, "encodeParts: pieces")
|
||||
local w = Bytes.writer()
|
||||
for _, p in parts do
|
||||
w:bytes(p)
|
||||
end
|
||||
local joined = w:finish()
|
||||
t:eq(buffer.readstring(joined, 0, 4), "RF64", "auto RF64 past the threshold")
|
||||
local rd = Wav.open(Bytes.reader(joined)) :: any
|
||||
t:check(rd.container == "RF64" and rd.frames == 3000, "RF64 reads back")
|
||||
t:check(buffer.tostring(rd:read(3000)) == buffer.tostring(Wav.decode(Bytes.reader(Wav.encode(big) :: buffer)).samples), "RF64 samples")
|
||||
t:eq(buffer.readstring(Wav.encode(big) :: buffer, 0, 4), "RIFF", "plain RIFF below the threshold")
|
||||
-- bad arguments
|
||||
local _, e1 = Wav.encode({} :: any)
|
||||
t:check(e1 and e1.code == Err.ARG, "encode {}: " .. tostring(e1))
|
||||
local _, e2 = Wav.encode(a, { sampleFormat = "s12" } :: any)
|
||||
t:check(e2 and e2.code == Err.ARG, "bad sampleFormat")
|
||||
local bad = Types.Audio.new(8000, 2, 10)
|
||||
bad.frames = 99
|
||||
local _, e3 = Wav.encode(bad)
|
||||
t:check(e3 and e3.code == Err.ARG, "short samples buffer")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ api
|
||||
do
|
||||
local c = Enc[1]
|
||||
local a, err = F.audio.load(c.file)
|
||||
t:check(a and a.kind == "audio" and a.frames == c.frames, "F.audio.load: " .. tostring(err))
|
||||
local dec = F.audio.open(c.file)
|
||||
t:check(dec and dec.sampleRate == c.rate and type(dec.read) == "function", "F.audio.open")
|
||||
local out = F.save(a, nil, { format = "wav", sampleFormat = "s16" })
|
||||
t:check(out and buffer.tostring(out) == c.file, "F.save wav")
|
||||
t:eq(F.detect(c.file), "wav", "F.detect")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ fuzz
|
||||
t:fuzz("open + read + seek", function(b: buffer)
|
||||
local dec = Wav.open(Bytes.reader(b))
|
||||
if dec then
|
||||
for _ = 1, 100 do
|
||||
local _, n = dec:read(1000)
|
||||
if n == 0 then
|
||||
break
|
||||
end
|
||||
end
|
||||
dec:seek(dec.duration / 2)
|
||||
dec:read(17)
|
||||
end
|
||||
return dec
|
||||
end, samples, { mutations = 12 })
|
||||
t:fuzz("header mutations", function(b: buffer)
|
||||
return Wav.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 6, garbage = 50, keepHeader = 0 })
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,263 @@
|
||||
-- containers/Ogg tests: real encoder files (opusenc, flac --ogg, ffmpeg vorbis) and hand-made multiplexed files,
|
||||
-- checked packet by packet against the independent Python parser of tools/fixtures/ogg.py; seeking on each; a big
|
||||
-- multiplexed file written with the muxer (bisection seeks); muxer edge cases (lacing at 255 multiples, page breaks,
|
||||
-- continued packets, flush, eos); a sub-range Reader; truncated / garbage input never throws. The muxer was also
|
||||
-- checked by hand against opus-tools: an opusenc file remuxed through it passes opusinfo and decodes identically.
|
||||
-- Ported from ogg-luau tests/ogg.luau. Fixtures: tools/fixtures/ogg.py.
|
||||
local T = require("@tests/T")
|
||||
local Ogg = require("@formats/containers/Ogg")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Cases = require("@tests/gen/ogg_cases")
|
||||
|
||||
local t = T.suite("ogg")
|
||||
|
||||
-- seek expectations from a packet list: { size, crc, granule, bos, eos }
|
||||
local function expectSeek(list: { any }, g: number): (number, number)
|
||||
local start, idx = -1, 1
|
||||
for i, p in list do
|
||||
if p[3] ~= -1 and p[3] <= g then
|
||||
start, idx = p[3], i + 1
|
||||
end
|
||||
end
|
||||
return start, idx
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for _, fx in Cases do
|
||||
local buf = buffer.fromstring(fx.data)
|
||||
table.insert(samples, fx.data)
|
||||
local d, err = Ogg.open(buf)
|
||||
t:check(d, fx.name .. ": open " .. tostring(err))
|
||||
local streams = d:streams()
|
||||
t:eq(#streams, #fx.streams, fx.name .. ": stream count")
|
||||
for si, es in fx.streams do
|
||||
local s = streams[si]
|
||||
t:eq(s.serial, es.serial, fx.name .. ": serial")
|
||||
t:eq(s.codec, es.codec, fx.name .. ": codec")
|
||||
t:eq(s.lastGranule, es.lastGranule, fx.name .. ": lastGranule")
|
||||
t:eq(buffer.len(s.firstPacket), es.packets[1][1], fx.name .. ": first packet")
|
||||
local n, gaps = 0, 0
|
||||
for p in d:packets(s.serial) do
|
||||
n += 1
|
||||
if p.gap then
|
||||
gaps += 1
|
||||
end
|
||||
local e = es.packets[n]
|
||||
t:check(e, fx.name .. ": too many packets")
|
||||
t:eq(p.size, e[1], fx.name .. ": packet " .. n .. " size")
|
||||
t:eq(Crc32.of(p.data, p.offset, p.size), e[2], fx.name .. ": packet " .. n .. " bytes")
|
||||
t:eq(p.granule, e[3], fx.name .. ": packet " .. n .. " granule")
|
||||
t:check(p.bos == e[4] and p.eos == e[5], fx.name .. ": packet " .. n .. " bos/eos")
|
||||
end
|
||||
t:eq(n, #es.packets, fx.name .. ": packet count")
|
||||
t:eq(gaps, if fx.name == "mux_lost" and s.serial == 7 then 1 else 0, fx.name .. ": gap flags")
|
||||
t:check(d:nextPacket(s.serial) == nil, fx.name .. ": end stays at end")
|
||||
end
|
||||
if #fx.streams > 1 then
|
||||
local counts = {}
|
||||
for i in streams do
|
||||
counts[i] = 0
|
||||
end
|
||||
local d2 = Ogg.open(buf)
|
||||
local live = #streams
|
||||
while live > 0 do
|
||||
live = 0
|
||||
for i, s in streams do
|
||||
local p = d2:nextPacket(s.serial)
|
||||
if p then
|
||||
live += 1
|
||||
counts[i] += 1
|
||||
t:eq(p.size, fx.streams[i].packets[counts[i]][1], fx.name .. ": interleaved read")
|
||||
end
|
||||
end
|
||||
end
|
||||
for i in streams do
|
||||
t:eq(counts[i], #fx.streams[i].packets, fx.name .. ": interleaved count")
|
||||
end
|
||||
end
|
||||
-- seeking
|
||||
for _, es in fx.streams do
|
||||
local serial = es.serial
|
||||
local last = es.lastGranule
|
||||
local targets = { -5, 0, 1, last // 3, last // 2, last - 1, last, last + 100 }
|
||||
for _, p in es.packets do
|
||||
if p[3] > 0 then
|
||||
table.insert(targets, p[3])
|
||||
table.insert(targets, p[3] - 1)
|
||||
end
|
||||
end
|
||||
for _, g in targets do
|
||||
local start = d:seekGranule(serial, g)
|
||||
local eStart, eIdx = expectSeek(es.packets, g)
|
||||
if start == -1 then
|
||||
eIdx = 1 -- rewound: the identification packet comes next
|
||||
end
|
||||
t:eq(start, eStart, fx.name .. ": seek " .. g .. " start")
|
||||
local p = d:nextPacket(serial)
|
||||
local e = es.packets[eIdx]
|
||||
if e then
|
||||
t:check(p and p.size == e[1] and Crc32.of(p.data, p.offset, p.size) == e[2], fx.name .. ": packet after seek " .. g)
|
||||
else
|
||||
t:check(p == nil, fx.name .. ": seek past the end")
|
||||
end
|
||||
end
|
||||
end
|
||||
-- a Reader over a sub-range of a bigger buffer
|
||||
local big = buffer.create(#fx.data + 20)
|
||||
buffer.writestring(big, 11, fx.data)
|
||||
local ds = Ogg.open(Bytes.reader(big, 11, #fx.data))
|
||||
t:check(ds and #ds:streams() == #fx.streams, fx.name .. ": open from a sub-range Reader")
|
||||
local n = 0
|
||||
for _ in ds:packets(fx.streams[1].serial) do
|
||||
n += 1
|
||||
end
|
||||
t:eq(n, #fx.streams[1].packets, fx.name .. ": packets from a sub-range Reader")
|
||||
t:note("%-14s ok (%d streams)", fx.name, #streams)
|
||||
end
|
||||
|
||||
-- the muxer: a big file with 3 streams, random packet sizes, page breaks by size and count; read back + seeks
|
||||
do
|
||||
local rand = T.rng(12345)
|
||||
local mux = Ogg.muxer({ pageSize = 4096 })
|
||||
local S = {}
|
||||
for k = 1, 3 do
|
||||
S[k] = { stream = mux:stream(1000 + k), serial = 1000 + k, granNow = 0, pk = {} }
|
||||
end
|
||||
local npk = 2500
|
||||
for i = 1, npk do
|
||||
for k, st in S do
|
||||
local size = if i == 1 then 30 else (if rand(50) == 0 then rand(3000) else rand(300))
|
||||
local tag = rand(256)
|
||||
local b = buffer.create(size)
|
||||
for j = 0, size - 1 do
|
||||
buffer.writeu8(b, j, (tag + j + 1) % 256)
|
||||
end
|
||||
st.granNow += if i == 1 then 0 else (k * 120)
|
||||
local ok, e = st.stream:packet(b, st.granNow, { flush = i == 1, eos = i == npk })
|
||||
t:check(ok, "mux packet: " .. tostring(e))
|
||||
table.insert(st.pk, { size, tag, st.granNow, Crc32.of(b) })
|
||||
end
|
||||
end
|
||||
local file = mux:finish()
|
||||
local d = Ogg.open(file)
|
||||
t:check(d and #d:streams() == 3, "big: 3 streams")
|
||||
for _, st in S do
|
||||
t:eq(d:stream(st.serial).lastGranule, st.granNow, "big: lastGranule")
|
||||
local n = 0
|
||||
for p in d:packets(st.serial) do
|
||||
n += 1
|
||||
local e = st.pk[n]
|
||||
t:check(p.size == e[1] and Crc32.of(p.data, p.offset, p.size) == e[4], "big: packet " .. n)
|
||||
t:check(p.bos == (n == 1) and p.eos == (n == npk), "big: bos / eos " .. n)
|
||||
end
|
||||
t:eq(n, npk, "big: count")
|
||||
for q = 0, 100 do
|
||||
local g = math.floor(st.granNow * q / 100)
|
||||
local start = d:seekGranule(st.serial, g)
|
||||
local p = d:nextPacket(st.serial)
|
||||
t:check(start and start <= g and start >= 0, "big: seek start")
|
||||
local idx
|
||||
for i, e in st.pk do
|
||||
if e[3] == start then
|
||||
idx = i + 1
|
||||
break
|
||||
end
|
||||
end
|
||||
local e = st.pk[idx]
|
||||
if e then
|
||||
t:check(p and p.size == e[1], "big: packet after seek")
|
||||
else
|
||||
t:check(p == nil, "big: end after seek")
|
||||
end
|
||||
end
|
||||
end
|
||||
t:note("muxer: 3 x %d packets, %d bytes, read back and seeked", npk, buffer.len(file))
|
||||
table.insert(samples, buffer.readstring(file, 0, math.min(buffer.len(file), 20000)))
|
||||
end
|
||||
|
||||
-- muxer edge cases: lacing at multiples of 255, a packet over 255 segments (continued pages), empty packets,
|
||||
-- headers alone on their pages, finish() without eos, eos twice
|
||||
do
|
||||
local mux = Ogg.muxer({ pageSize = 1000 })
|
||||
local s = mux:stream(42)
|
||||
local sizes = { 19, 0, 255, 510, 254, 256, 255 * 255, 255 * 255 + 1, 70000, 1, 0, 3000 }
|
||||
local crcs = {}
|
||||
for i, n in sizes do
|
||||
local b = buffer.create(n)
|
||||
for j = 0, n - 1 do
|
||||
buffer.writeu8(b, j, (j * 7 + i) % 256)
|
||||
end
|
||||
crcs[i] = Crc32.of(b)
|
||||
t:check(s:packet(b, i * 10, { flush = i <= 2 }), "edge: packet " .. i)
|
||||
end
|
||||
local file = mux:finish()
|
||||
local ok, e = s:packet("late", 999)
|
||||
t:check(not ok and e and e.code == Err.ARG, "edge: packet after the end is Err.ARG")
|
||||
local d = Ogg.open(file) :: any
|
||||
local i = 0
|
||||
local pages = 0
|
||||
local pos = 0
|
||||
while true do
|
||||
local p = Ogg.Page.find(file, pos)
|
||||
if not p then
|
||||
break
|
||||
end
|
||||
pages += 1
|
||||
t:check(p.nsegs <= 255, "edge: segments per page")
|
||||
if pages == 1 then
|
||||
t:check(p.bos and p.nsegs == 1 and p.granule == 10, "edge: the first packet alone on the bos page")
|
||||
end
|
||||
pos = p.offset + p.size
|
||||
end
|
||||
for p in d:packets(42) do
|
||||
i += 1
|
||||
t:eq(p.size, sizes[i], "edge: size " .. i)
|
||||
t:eq(Crc32.of(p.data, p.offset, p.size), crcs[i], "edge: bytes " .. i)
|
||||
t:eq(p.eos, i == #sizes, "edge: eos " .. i)
|
||||
end
|
||||
t:eq(i, #sizes, "edge: packet count")
|
||||
t:check(pages > 70, "edge: page breaks (" .. pages .. " pages)")
|
||||
t:eq(d:stream(42).lastGranule, #sizes * 10, "edge: last granule")
|
||||
t:eq(d:stream(42).codec, "unknown", "edge: codec")
|
||||
-- strings, ranges and bad arguments
|
||||
local m2 = Ogg.muxer()
|
||||
local s2 = m2:stream()
|
||||
t:check(s2:packet("OpusHead" .. string.rep("\0", 11), 0, { flush = true }), "string packet")
|
||||
t:check(s2:packet(buffer.fromstring("xxabcxx"), 5, nil, 2, 3), "range packet")
|
||||
t:check(not s2:packet(buffer.create(3), 5, nil, 2, 3), "bad range")
|
||||
t:check(not s2:packet(42 :: any, 5), "bad data")
|
||||
local d2 = Ogg.open(m2:finish()) :: any
|
||||
t:eq(d2:streams()[1].codec, "opus", "codec of a muxed OpusHead")
|
||||
t:eq(d2:streams()[1].serial, 1, "default serial")
|
||||
d2:nextPacket(1)
|
||||
local p = d2:nextPacket(1)
|
||||
t:eq(buffer.readstring(p.data, p.offset, p.size), "abc", "range packet bytes")
|
||||
t:check(d2:nextPacket(1) == nil, "empty eos page ends the stream")
|
||||
end
|
||||
|
||||
-- errors and garbage
|
||||
do
|
||||
local _, e1 = Ogg.open(buffer.create(0))
|
||||
t:check(e1 and e1.code == Err.CORRUPT, "empty: " .. tostring(e1))
|
||||
t:check(Ogg.open(buffer.fromstring(string.rep("OggS", 100))) == nil, "garbage")
|
||||
local _, e2 = Ogg.open(42 :: any)
|
||||
t:check(e2 and e2.code == Err.ARG, "not a buffer: " .. tostring(e2))
|
||||
end
|
||||
|
||||
-- fuzz: open + read every packet + seek never throws
|
||||
t:fuzz("open + read + seek", function(b: buffer)
|
||||
local d = Ogg.open(b)
|
||||
if d then
|
||||
for _, s in d:streams() do
|
||||
for _ in d:packets(s.serial) do
|
||||
end
|
||||
d:seekGranule(s.serial, s.lastGranule // 2)
|
||||
d:nextPacket(s.serial)
|
||||
end
|
||||
end
|
||||
return d
|
||||
end, samples, { mutations = 6 })
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,114 @@
|
||||
-- containers/Riff tests: the writer (RIFF, RIFX, forced RF64 with ds64, LIST/INFO, odd pad bytes, parts) read back by
|
||||
-- the reader; lenient reading (missing pad byte, truncated chunk, open-ended data of size 0 / 0xFFFFFFFF, the ds64
|
||||
-- table, a sub-range Reader); errors; the fuzz pass. The WAVE form is checked against ffmpeg in tests/audio/wav.luau.
|
||||
local T = require("@tests/T")
|
||||
local Riff = require("@formats/containers/Riff")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
|
||||
local t = T.suite("riff")
|
||||
|
||||
local function u32(v: number): string
|
||||
local b = buffer.create(4)
|
||||
buffer.writeu32(b, 0, v)
|
||||
return buffer.tostring(b)
|
||||
end
|
||||
|
||||
-- writer -> reader
|
||||
local samples = {}
|
||||
for _, mode in { "riff", "rifx", "rf64" } do
|
||||
local w = Riff.writer("TEST", { bigEndian = mode == "rifx", rf64 = mode == "rf64", sampleCount = 77 })
|
||||
w:chunk("abcd", "odd")
|
||||
w:chunk("efgh", buffer.fromstring("xxevenxx"), 2, 4)
|
||||
w:list("INFO", { { "INAM", "name" }, { "IART", buffer.fromstring("raw") } })
|
||||
w:chunk("data", { buffer.fromstring("12345"), buffer.fromstring("678") })
|
||||
local file = w:finish() :: buffer
|
||||
table.insert(samples, buffer.tostring(file))
|
||||
local f, err = Riff.read(Bytes.reader(file))
|
||||
t:check(f, mode .. ": read: " .. tostring(err))
|
||||
t:eq(f.container, if mode == "rifx" then "RIFX" elseif mode == "rf64" then "RF64" else "RIFF", mode .. ": container")
|
||||
t:eq(f.form, "TEST", mode .. ": form")
|
||||
t:eq(f.size, buffer.len(file) - 8, mode .. ": RIFF size")
|
||||
local ids = {}
|
||||
for _, c in f.chunks do
|
||||
table.insert(ids, c.id)
|
||||
end
|
||||
t:eq(table.concat(ids, ","), if mode == "rf64" then "ds64,abcd,efgh,LIST,data" else "abcd,efgh,LIST,data", mode .. ": chunks")
|
||||
local a = Riff.find(f, "abcd") :: any
|
||||
t:check(a.size == 3 and buffer.readstring(file, a.offset, 3) == "odd", mode .. ": odd chunk")
|
||||
local e = Riff.find(f, "efgh") :: any
|
||||
t:eq(buffer.readstring(file, e.offset, e.size), "even", mode .. ": range chunk")
|
||||
local l = Riff.find(f, "LIST") :: any
|
||||
t:eq(Riff.listType(f, l), "INFO", mode .. ": list type")
|
||||
local subs = Riff.list(f, l)
|
||||
t:check(#subs == 2 and subs[1].id == "INAM" and buffer.readstring(file, subs[1].offset, subs[1].size) == "name\0", mode .. ": INFO item")
|
||||
t:check(subs[2].size == 3 and subs[2].avail == 3, mode .. ": raw item")
|
||||
local d = Riff.find(f, "data") :: any
|
||||
t:check(d.size == 8 and buffer.readstring(file, d.offset, 8) == "12345678", mode .. ": data parts")
|
||||
t:eq(buffer.tostring(Riff.body(f, d):bytes(8)), "12345678", mode .. ": body reader")
|
||||
if mode == "rf64" then
|
||||
t:check(f.ds64 and f.ds64.dataSize == 8 and f.ds64.sampleCount == 77 and d.declared == 0xFFFFFFFF, "rf64: ds64")
|
||||
end
|
||||
-- parts: the same bytes
|
||||
local parts = w:finish({ parts = true }) :: { buffer }
|
||||
local j = Bytes.writer()
|
||||
for _, p in parts do
|
||||
j:bytes(p)
|
||||
end
|
||||
t:check(buffer.tostring(j:finish()) == buffer.tostring(file), mode .. ": parts join to the file")
|
||||
end
|
||||
t:check(not Riff.writer("WAVE", { bigEndian = true, rf64 = true }):finish(), "RIFX RF64 refused")
|
||||
|
||||
-- lenient reading
|
||||
do
|
||||
-- a missing pad byte after an odd chunk
|
||||
local body = "WAVE" .. "abcd" .. u32(5) .. "12345" .. "next" .. u32(2) .. "ok"
|
||||
local f = Riff.read(buffer.fromstring("RIFF" .. u32(#body) .. body)) :: any
|
||||
t:check(#f.chunks == 2 and f.chunks[2].id == "next", "missing pad byte detected")
|
||||
-- truncated
|
||||
local tb = "WAVE" .. "data" .. u32(100) .. "short"
|
||||
local ft = Riff.read(buffer.fromstring("RIFF" .. u32(#tb) .. tb)) :: any
|
||||
t:check(ft.chunks[1].truncated and ft.chunks[1].avail == 5 and ft.chunks[1].size == 100, "truncated chunk")
|
||||
-- open-ended
|
||||
for _, sz in { 0, 0xFFFFFFFF } do
|
||||
local ob = "WAVE" .. "data" .. u32(sz) .. "abcdefLIST"
|
||||
local fo = Riff.read(buffer.fromstring("RIFF" .. u32(0) .. ob), { openEnded = { data = true } }) :: any
|
||||
t:check(#fo.chunks == 1 and fo.chunks[1].streamed and fo.chunks[1].size == 10, "open-ended data " .. sz)
|
||||
end
|
||||
-- ds64 table
|
||||
local ds = "ds64" .. u32(40) .. u32(0) .. u32(0) .. u32(4) .. u32(0) .. u32(0) .. u32(0) .. u32(1) .. "big " .. u32(3) .. u32(0)
|
||||
local rb = "WAVE" .. ds .. "big " .. u32(0xFFFFFFFF) .. "xyz" .. "\0"
|
||||
local fr = Riff.read(buffer.fromstring("RF64" .. u32(0xFFFFFFFF) .. rb)) :: any
|
||||
t:check(fr.ds64 and fr.ds64.table["big "] == 3 and fr.chunks[2].size == 3, "ds64 table")
|
||||
-- a sub-range reader
|
||||
local s = samples[1]
|
||||
local big = buffer.create(#s + 7)
|
||||
buffer.writestring(big, 3, s)
|
||||
local fs = Riff.read(Bytes.reader(big, 3, #s)) :: any
|
||||
t:check(fs and fs.form == "TEST" and #fs.chunks == 4 and fs.base == 3, "sub-range reader")
|
||||
t:eq(Riff.sniff(Bytes.reader(buffer.fromstring(s))), "TEST", "sniff")
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local _, e1 = Riff.read(buffer.fromstring("RIFF"))
|
||||
t:check(e1 and e1.code == Err.TRUNCATED, "too short")
|
||||
local _, e2 = Riff.read(buffer.fromstring("OggS00000000"))
|
||||
t:check(e2 and e2.code == Err.CORRUPT, "not RIFF")
|
||||
local _, e3 = Riff.read(42 :: any)
|
||||
t:check(e3 and e3.code == Err.ARG, "not a buffer")
|
||||
end
|
||||
|
||||
t:fuzz("read + list", function(b: buffer)
|
||||
local f = Riff.read(Bytes.reader(b), { openEnded = { data = true } })
|
||||
if f then
|
||||
for _, c in f.chunks do
|
||||
if c.id == "LIST" then
|
||||
Riff.list(f, c)
|
||||
end
|
||||
end
|
||||
end
|
||||
return f
|
||||
end, samples, { mutations = 30 })
|
||||
|
||||
t:done()
|
||||
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,171 @@
|
||||
-- image/png APNG tests: animated PNGs from ffmpeg's encoder and hand-written ones (every dispose / blend op, sub-rects,
|
||||
-- palette + tRNS, grey, RGB, a hidden default image) decoded into frames and composited, compared with ffmpeg's
|
||||
-- composited canvases (CRC-32); the APNG encoder's round trips; bad sequence numbers / rectangles; the fuzz pass.
|
||||
-- Fixtures: tools/fixtures/apng.py.
|
||||
local T = require("@tests/T")
|
||||
local Png = require("@formats/image/png")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Cases = require("@tests/gen/apng_cases")
|
||||
|
||||
local t = T.suite("apng")
|
||||
|
||||
t:check(Png.caps.animation == true, "caps.animation")
|
||||
|
||||
local function decode(data: any, opts: any?): (any, any)
|
||||
local b = if type(data) == "string" then buffer.fromstring(data) else data
|
||||
return Png.decode(Bytes.reader(b), opts)
|
||||
end
|
||||
|
||||
local DISPOSE = { [0] = "none", [1] = "background", [2] = "previous" }
|
||||
|
||||
local function canvasCrc(b: buffer, opaque: boolean): number
|
||||
if opaque then
|
||||
local c = buffer.create(buffer.len(b))
|
||||
buffer.copy(c, 0, b)
|
||||
for i = 3, buffer.len(c) - 1, 4 do
|
||||
buffer.writeu8(c, i, 255)
|
||||
end
|
||||
b = c
|
||||
end
|
||||
return Crc32.of(b)
|
||||
end
|
||||
|
||||
local function same(a: Types.Image, b: Types.Image): boolean
|
||||
return a.width == b.width and a.height == b.height and buffer.tostring(a.pixels) == buffer.tostring(b.pixels)
|
||||
end
|
||||
|
||||
for _, c in Cases do
|
||||
local img, err = decode(c.data, { checkCrc = true })
|
||||
t:check(img, c.name .. ": " .. tostring(err))
|
||||
t:eq(img.width, c.width, c.name .. ": width")
|
||||
t:check(img.frames ~= nil, c.name .. ": frames")
|
||||
t:eq(#img.frames, #c.crcs, c.name .. ": frame count")
|
||||
t:eq(img.loops, c.plays, c.name .. ": loops")
|
||||
if c.frames then
|
||||
for i, e in c.frames do
|
||||
local f = img.frames[i]
|
||||
t:check(f.x == e.x and f.y == e.y and f.image.width == e.w and f.image.height == e.h, c.name .. ": frame " .. i .. " rect")
|
||||
t:check(math.abs(f.delay - e.num / (if e.den == 0 then 100 else e.den)) < 1e-12, c.name .. ": frame " .. i .. " delay")
|
||||
t:eq(f.dispose, DISPOSE[e.dispose], c.name .. ": frame " .. i .. " dispose")
|
||||
t:eq(f.blend, if e.blend == 1 then "over" else "source", c.name .. ": frame " .. i .. " blend")
|
||||
end
|
||||
end
|
||||
if c.defaultCrc then
|
||||
t:eq(Crc32.of(img.pixels), c.defaultCrc, c.name .. ": hidden default image")
|
||||
t:check(img.meta.apngDefaultHidden == true, c.name .. ": apngDefaultHidden")
|
||||
else
|
||||
t:check(img.meta.apngDefaultHidden == false, c.name .. ": default image is frame 1")
|
||||
t:check(buffer.tostring(img.pixels) == buffer.tostring(img.frames[1].image.pixels), c.name .. ": pixels = frame 1")
|
||||
end
|
||||
local canv, cerr = Png.composite(img)
|
||||
t:check(canv, c.name .. ": composite " .. tostring(cerr))
|
||||
for i, want in c.crcs do
|
||||
t:eq(canvasCrc(canv[i].pixels, c.opaque), want, c.name .. ": composited frame " .. i .. (if c.ffmpeg then " vs ffmpeg" else " vs reference"))
|
||||
end
|
||||
-- round trip through the encoder: the same frames, rectangles, ops, delays, loops and default image
|
||||
local enc, eerr = Png.encode(img)
|
||||
t:check(enc, c.name .. ": encode " .. tostring(eerr))
|
||||
local back, berr = Png.decode(Bytes.reader(enc :: buffer), { checkCrc = true })
|
||||
t:check(back, c.name .. ": decode our APNG " .. tostring(berr))
|
||||
t:check(same(back, img), c.name .. ": round trip default image")
|
||||
t:eq(back.loops, img.loops, c.name .. ": round trip loops")
|
||||
t:eq(#back.frames, #img.frames, c.name .. ": round trip frame count")
|
||||
t:eq(back.meta.apngDefaultHidden, img.meta.apngDefaultHidden, c.name .. ": round trip hidden default")
|
||||
for i, f in img.frames do
|
||||
local g = back.frames[i]
|
||||
t:check(same(g.image, f.image) and g.x == f.x and g.y == f.y and g.dispose == f.dispose and g.blend == f.blend, c.name .. ": round trip frame " .. i)
|
||||
t:check(math.abs(g.delay - f.delay) < 1e-9, c.name .. ": round trip delay " .. i)
|
||||
end
|
||||
end
|
||||
t:note("%d APNGs match the reference canvases and round-trip", #Cases)
|
||||
|
||||
-- encoder: frames built here (sub-rects, delays in seconds), opts.apng, validation
|
||||
do
|
||||
local function solid(w: number, h: number, r: number, g: number, b: number, a: number): Types.Image
|
||||
local im = Types.Image.new(w, h)
|
||||
for i = 0, w * h - 1 do
|
||||
buffer.writeu8(im.pixels, i * 4, r)
|
||||
buffer.writeu8(im.pixels, i * 4 + 1, g)
|
||||
buffer.writeu8(im.pixels, i * 4 + 2, b)
|
||||
buffer.writeu8(im.pixels, i * 4 + 3, a)
|
||||
end
|
||||
return im
|
||||
end
|
||||
local base = solid(8, 6, 10, 20, 30, 255)
|
||||
base.frames = {
|
||||
{ image = base, delay = 0.1, x = 0, y = 0, dispose = "none", blend = "source" },
|
||||
{ image = solid(3, 2, 200, 0, 0, 128), delay = 1 / 30, x = 5, y = 4, dispose = "background", blend = "over" },
|
||||
{ image = solid(1, 1, 0, 255, 0, 255), delay = 70, x = 7, y = 0, dispose = "previous", blend = "source" },
|
||||
}
|
||||
base.loops = 5
|
||||
local enc = Png.encode(base) :: buffer
|
||||
local back = decode(enc)
|
||||
t:check(back and #back.frames == 3 and back.loops == 5, "built APNG decodes")
|
||||
t:check(math.abs(back.frames[2].delay - 1 / 30) < 1e-9 and back.frames[3].delay == 70 and back.frames[1].delay == 0.1, "delays")
|
||||
t:eq(back.meta.source.colorType, "rgba", "colour type covers every frame (alpha in frame 2 only)")
|
||||
local canv = Png.composite(back) :: { Types.Image }
|
||||
-- frame 2 over: 128 alpha red over opaque (10, 20, 30)
|
||||
local o = (4 * 8 + 5) * 4
|
||||
t:eq(buffer.readu8(canv[2].pixels, o + 3), 255, "over: alpha")
|
||||
t:eq(buffer.readu8(canv[2].pixels, o), (128 * 200 + 127 * 10 + 128) * 257 // 65536, "over: red")
|
||||
t:eq(buffer.readu32(canv[3].pixels, o), 0, "background dispose cleared frame 2's rect")
|
||||
-- one frame + opts.apng; a still image stays a PNG
|
||||
local still = solid(4, 4, 1, 2, 3, 255)
|
||||
local plain = decode(Png.encode(still) :: buffer)
|
||||
t:check(plain.frames == nil, "still image: no acTL")
|
||||
local one = decode(Png.encode(still, { apng = true }) :: buffer)
|
||||
t:check(one.frames and #one.frames == 1 and same(one.frames[1].image, still), "opts.apng: a one-frame APNG")
|
||||
-- bad frames
|
||||
local function bad(frames: any, label: string)
|
||||
local im = solid(4, 4, 0, 0, 0, 255)
|
||||
im.frames = frames
|
||||
local r, e = Png.encode(im)
|
||||
t:check(r == nil and e and e.code == Err.ARG, label .. ": " .. tostring(e))
|
||||
end
|
||||
bad({ { image = still, x = 0, y = 0 }, { image = still, x = 1, y = 0 } }, "frame outside the canvas")
|
||||
bad({ { image = still }, { image = {} } }, "frame without an image")
|
||||
bad({ { image = still }, { image = still, dispose = "explode" } }, "bad dispose")
|
||||
bad({ { image = still }, { image = still, blend = "add" } }, "bad blend")
|
||||
bad({ { image = still }, { image = still, delay = -1 } }, "negative delay")
|
||||
end
|
||||
|
||||
-- crafted bad input: a broken sequence number, a frame outside the canvas
|
||||
do
|
||||
local c = Cases[1]
|
||||
local s = c.data
|
||||
-- find the second fcTL and bump its sequence number (fix the CRC so checkCrc does not mask it)
|
||||
local first = string.find(s, "fcTL", 1, true) :: number
|
||||
local second = string.find(s, "fcTL", first + 4, true) :: number
|
||||
local b = buffer.fromstring(s)
|
||||
local d = second + 3 -- 0-based offset of the chunk data
|
||||
buffer.writeu32(b, d, bit32.byteswap(bit32.byteswap(buffer.readu32(b, d)) + 1))
|
||||
local _, e = Png.decode(Bytes.reader(b))
|
||||
t:check(e and e.code == Err.CORRUPT, "bad sequence: " .. tostring(e))
|
||||
local b2 = buffer.fromstring(s)
|
||||
buffer.writeu32(b2, d + 12, bit32.byteswap(c.width)) -- x offset = the canvas width
|
||||
local _, e2 = Png.decode(Bytes.reader(b2))
|
||||
t:check(e2 and e2.code == Err.CORRUPT, "frame outside the canvas: " .. tostring(e2))
|
||||
local _, e3 = decode(s, { maxPixels = c.width * c.height + 1 })
|
||||
t:check(e3 and e3.code == Err.LIMIT, "maxPixels counts the frames: " .. tostring(e3))
|
||||
t:check(Png.composite({} :: any) == nil, "composite of a non-image")
|
||||
end
|
||||
|
||||
-- fuzz
|
||||
do
|
||||
local samples = {}
|
||||
for _, c in Cases do
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local img = Png.decode(Bytes.reader(b))
|
||||
if img and img.frames then
|
||||
Png.composite(img)
|
||||
end
|
||||
return img
|
||||
end, samples, { mutations = 30, keepHeader = 8 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
Reference in new issue
Block a user