ws-m4a: merge ws/absorb (audio/opus, containers/Ogg, ...) for the CELT encoder; m4a fixtures load their helper by path (tools/fixtures/ on sys.path shadowed the xml package)
No files matched your search
@@ -0,0 +1,268 @@
|
||||
-- archive/zip + containers/Zip tests: generated archives (comment with a fake end record, data descriptors,
|
||||
-- force_zip64, an all-ZIP64 archive, 66000 entries, a prefix stub, a wrong local header, unicode, empty) read entry by
|
||||
-- entry against Python's zipfile listing (and every Webamp demo skin when SKINS_DIR is set); lookup rules; bad CRC,
|
||||
-- encrypted and unsupported entries; the writer (stored / deflated, levels, UTF-8 names, DOS times, comments, ZIP64,
|
||||
-- raw copies) read back; the Archive API (list / read / add / remove / write, create, encode of a table) and the api;
|
||||
-- corrupt input never throws. The writer's output was also checked by hand: `unzip -t`, Python zipfile and 7z read it.
|
||||
-- Ported from zip-luau tests/zip.luau. Fixtures: tools/fixtures/zip.py.
|
||||
local T = require("@tests/T")
|
||||
local Zip = require("@formats/containers/Zip")
|
||||
local ZipF = require("@formats/archive/zip")
|
||||
local Deflate = require("@formats/codecs/Deflate")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local F = require("@formats")
|
||||
local Fx = require("@tests/gen/zip_cases")
|
||||
|
||||
local t = T.suite("zip")
|
||||
|
||||
local function dataOf(a: any): string
|
||||
if a.data then
|
||||
return a.data
|
||||
end
|
||||
return buffer.tostring(Deflate.zlib(buffer.fromstring(a.dataZ)) :: buffer)
|
||||
end
|
||||
|
||||
-- open an archive and compare it with zipfile's listing; read every entry
|
||||
local function verify(a: any, label: string): (any, number)
|
||||
local z, err = Zip.open(dataOf(a))
|
||||
t:check(z, label .. ": open: " .. tostring(err))
|
||||
local list = z:list()
|
||||
t:eq(#list, a.count, label .. ": entries")
|
||||
local bytes = 0
|
||||
for i, want in a.entries do
|
||||
local e = list[i]
|
||||
t:check(e.rawName == want[1] or e.name == string.gsub(want[1], "\\", "/"), label .. ": name " .. e.rawName)
|
||||
t:check(e.size == want[2] and e.crc32 == want[3] and e.method == want[4], label .. ": " .. e.name .. " size / crc / method")
|
||||
local data, rerr = z:read(e)
|
||||
t:check(data, label .. ": read " .. e.name .. ": " .. tostring(rerr))
|
||||
t:check(buffer.len(data :: buffer) == want[2] and Crc32.of(data :: buffer) == want[3], label .. ": " .. e.name .. " content")
|
||||
bytes += want[2]
|
||||
end
|
||||
return z, bytes
|
||||
end
|
||||
|
||||
local byName = {}
|
||||
for _, a in Fx.archives do
|
||||
byName[a.name] = a
|
||||
a.zip = verify(a, a.name)
|
||||
end
|
||||
t:note("%d generated archives match Python zipfile", #Fx.archives)
|
||||
local total, nent = 0, 0
|
||||
for _, s in Fx.skins do
|
||||
local _, bytes = verify(s, s.name)
|
||||
total += bytes
|
||||
nent += s.count
|
||||
end
|
||||
if #Fx.skins > 0 then
|
||||
t:note("%d skins, %d entries, %.2f MB read and CRC-checked", #Fx.skins, nent, total / 1e6)
|
||||
else
|
||||
t:note("(no skins: set SKINS_DIR to the Webamp demo skins)")
|
||||
end
|
||||
|
||||
-- lookup and specifics
|
||||
do
|
||||
local z = byName.basic.zip
|
||||
t:eq(z:find("readme.txt").name, "readme.txt", "find exact")
|
||||
t:eq(z:find("README.TXT").name, "readme.txt", "find case-insensitive")
|
||||
t:eq(z:find("main.bmp").name, "Skin/Main.BMP", "find by basename skips __MACOSX")
|
||||
t:eq(z:find("skin\\MAIN.bmp").name, "Skin/Main.BMP", "find with backslashes")
|
||||
t:check(z:find("__MACOSX/Skin/._Main.BMP") ~= nil, "junk still found by its full path")
|
||||
t:check(z:find("Skin/") == nil, "directories are not found")
|
||||
t:check(z:find("nope.bmp") == nil, "missing")
|
||||
t:eq(z:find("deep.txt").name, "Skin/sub/deep.txt", "basename in a deeper folder")
|
||||
t:eq(z:readString("DEEP.TXT"), "deep", "readString by name")
|
||||
t:eq(z:readString("Other/\u{fc}nicode.txt"), "h\u{e9}llo", "unicode basename")
|
||||
local u = z:find("sk\u{ef}n/\u{fc}nicode.txt")
|
||||
t:check(u and u.utf8 and z:readString(u) == "h\u{e9}llo", "unicode name")
|
||||
local m = z:find("readme.txt").modified
|
||||
t:check(m.year == 2020 and m.month == 5 and m.day == 17 and m.hour == 13 and m.min == 37 and m.sec == 42, "dos time")
|
||||
t:eq(z:find("readme.txt").mtime, 1589722662, "mtime (unix seconds)")
|
||||
local _, e = z:read("nope")
|
||||
t:check(e and e.code == Err.ARG, "read a missing name")
|
||||
t:eq(string.sub(byName.comment.zip.comment, 1, 14), "a comment with", "archive comment")
|
||||
t:check(byName.zip64_by_hand.zip.zip64 and byName.many.zip.zip64, "zip64 records detected")
|
||||
t:check(bit32.band(byName.descriptors.zip:list()[1].flags, 8) ~= 0, "data descriptor flag")
|
||||
t:check(not byName.basic.zip.zip64, "basic is not zip64")
|
||||
t:eq(byName.many.zip:readString("d/65999.txt"), "65999", "last of 66000 entries")
|
||||
t:eq(#byName.empty.zip:list(), 0, "empty archive")
|
||||
t:check(Zip.isZip(byName.basic.data) and Zip.isZip(byName.empty.data) and not Zip.isZip("GIF89a"), "isZip")
|
||||
-- a sub-range reader
|
||||
local s = byName.basic.data
|
||||
local big = buffer.create(#s + 10)
|
||||
buffer.writestring(big, 4, s)
|
||||
local zs = Zip.open(Bytes.reader(big, 4, #s))
|
||||
t:check(zs and zs:readString("readme.txt") ~= nil, "open a sub-range Reader")
|
||||
end
|
||||
|
||||
-- a bad CRC, encrypted and unsupported entries
|
||||
do
|
||||
local data = buffer.fromstring(byName.basic.data)
|
||||
local z = Zip.open(byName.basic.data)
|
||||
local st = z:find("stored.bin")
|
||||
local p = st.offset + 30 + buffer.readu16(data, st.offset + 26) + buffer.readu16(data, st.offset + 28) + 10
|
||||
buffer.writeu8(data, p, bit32.bxor(buffer.readu8(data, p), 0xFF))
|
||||
local z2 = Zip.open(data)
|
||||
local out, err = z2:read("stored.bin")
|
||||
t:check(out == nil and err.code == Err.CHECKSUM, "stored CRC mismatch: " .. tostring(err))
|
||||
t:check(z2:read("stored.bin", false) ~= nil, "verify = false")
|
||||
local e = table.clone(z:find("readme.txt"))
|
||||
e.flags = 1
|
||||
local _, ee = z:read(e)
|
||||
t:check(ee and ee.code == Err.UNSUPPORTED, "encrypted refused")
|
||||
e.flags, e.method = 0, 12
|
||||
local _, merr = z:read(e)
|
||||
t:check(merr and merr.code == Err.UNSUPPORTED and string.find(merr.message, "method 12", 1, true), "bzip2 refused: " .. tostring(merr))
|
||||
local _, oe = Zip.open(5 :: any)
|
||||
t:check(oe and oe.code == Err.ARG, "a non-buffer argument")
|
||||
end
|
||||
|
||||
-- the writer
|
||||
do
|
||||
local rand = T.rng(5)
|
||||
local w = Zip.writer()
|
||||
local files = {}
|
||||
local text = string.rep("the quick brown fox jumps over the lazy dog ", 2000)
|
||||
local noise = buffer.create(5000)
|
||||
for i = 0, 4999 do
|
||||
buffer.writeu8(noise, i, rand(2147483648) // 8388608)
|
||||
end
|
||||
local function put(name: string, data: any, opts: any?)
|
||||
t:check(w:add(name, data, opts), "add " .. name)
|
||||
table.insert(files, { name, if type(data) == "string" then data elseif data then buffer.tostring(data) else "" })
|
||||
end
|
||||
put("text.txt", text, { level = 9, mtime = 1589722662 })
|
||||
put("stored.txt", text, { method = "store" })
|
||||
put("noise.bin", noise) -- deflate is not smaller: stored
|
||||
put("empty.txt", "")
|
||||
put("dir/", nil)
|
||||
put("dir/\u{fc}nicode.txt", "h\u{e9}llo", { comment = "a file comment" })
|
||||
put("level0.txt", text, { level = 0 })
|
||||
local out, err = w:finish({ comment = "archive comment" })
|
||||
t:check(out, "finish: " .. tostring(err))
|
||||
local z = Zip.open(out :: buffer)
|
||||
t:check(z, "our archive opens")
|
||||
local list = z:list()
|
||||
t:eq(#list, #files, "entry count")
|
||||
for i, f in files do
|
||||
t:eq(list[i].name, f[1], "name " .. i)
|
||||
t:eq(z:readString(list[i]), f[2], "content " .. f[1])
|
||||
end
|
||||
t:eq(list[1].method, 8, "deflated")
|
||||
t:check(list[1].compressedSize < #text // 10, "compressed")
|
||||
t:eq(list[2].method, 0, "stored")
|
||||
t:eq(list[3].method, 0, "incompressible data is stored")
|
||||
t:check(list[5].isDir, "directory entry")
|
||||
t:check(list[6].utf8 and not list[1].utf8, "UTF-8 flag only for non-ASCII names")
|
||||
t:eq(list[6].comment, "a file comment", "entry comment")
|
||||
t:eq(list[1].mtime, 1589722662, "mtime round trip")
|
||||
local md = list[1].modified
|
||||
t:check(md.year == 2020 and md.month == 5 and md.day == 17 and md.hour == 13 and md.min == 37 and md.sec == 42, "dos time written")
|
||||
t:check(list[2].modified.year == 1980 and list[2].modified.month == 1 and list[2].modified.day == 1, "default time 1980-01-01")
|
||||
t:eq(z.comment, "archive comment", "archive comment written")
|
||||
t:check(not z.zip64, "small archive is not ZIP64")
|
||||
-- forced ZIP64
|
||||
local w64 = Zip.writer()
|
||||
w64:add("a.txt", text)
|
||||
w64:add("b.txt", "bee", { method = "store" })
|
||||
local z64 = Zip.open(w64:finish({ zip64 = true }) :: buffer)
|
||||
t:check(z64 and z64.zip64 and z64:readString("a.txt") == text and z64:readString("b.txt") == "bee", "forced ZIP64 round trip")
|
||||
-- over 65535 entries: the ZIP64 end record
|
||||
local wm = Zip.writer()
|
||||
for i = 0, 65999 do
|
||||
wm:add(string.format("d/%05d.txt", i), tostring(i), { method = "store" })
|
||||
end
|
||||
local zm = Zip.open(wm:finish() :: buffer)
|
||||
t:check(zm and zm.zip64 and #zm:list() == 66000 and zm:readString("d/65999.txt") == "65999", "66000 entries")
|
||||
-- dates
|
||||
for _, s in { 315532800, 946684799, 1700000000, 4354819198 } do
|
||||
local tm, dt = Zip.dosTime(s)
|
||||
t:eq(Zip.unixTime(tm, dt), s - s % 2, "dos time of " .. s)
|
||||
end
|
||||
t:check(select(2, Zip.dosTime(0)) == 0x21, "before 1980 clamps")
|
||||
-- bad arguments
|
||||
t:check(not w:add("", "x"), "empty name")
|
||||
t:check(not w:add("x", 5 :: any), "bad data")
|
||||
t:check(not w:add("x", "y", { method = "lzma" } :: any), "bad method")
|
||||
end
|
||||
|
||||
-- the Archive (archive/zip)
|
||||
do
|
||||
t:eq(ZipF.name, "zip", "name")
|
||||
t:eq(ZipF.category, "archive", "category")
|
||||
local a, err = ZipF.decode(Bytes.reader(buffer.fromstring(byName.basic.data)))
|
||||
t:check(a and a.kind == "archive" and a.format == "zip", "decode: " .. tostring(err))
|
||||
local list = a:list()
|
||||
t:eq(#list, byName.basic.count, "list")
|
||||
t:check(list[1].name == "readme.txt" and list[1].method == "deflate" and not list[1].dir and list[1].mtime == 1589722662, "entry fields")
|
||||
t:check(list[4].dir, "dir entry")
|
||||
local rd = a:read("readme.txt")
|
||||
t:check(rd and Crc32.of(rd :: buffer) == byName.basic.entries[1][3], "read")
|
||||
t:check(a:read("MAIN.bmp") ~= nil, "read by the lookup rules")
|
||||
-- edit: replace, add, remove, then write; unchanged entries are copied raw
|
||||
a:add("readme.txt", "replaced")
|
||||
a:add("new/one.txt", string.rep("x", 1000), { level = 9 })
|
||||
t:check(a:remove("Skin/stored.bin") and not a:remove("nope"), "remove")
|
||||
local out = a:write() :: buffer
|
||||
local b = ZipF.decode(Bytes.reader(out)) :: any
|
||||
t:check(b, "rewritten archive opens")
|
||||
t:eq(buffer.tostring(b:read("readme.txt")), "replaced", "replaced entry")
|
||||
t:eq(buffer.tostring(b:read("new/one.txt")), string.rep("x", 1000), "added entry")
|
||||
t:check(b:read("Skin/stored.bin") == nil, "removed entry")
|
||||
t:check(b:read("Skin/Main.BMP") and Crc32.of(b:read("Skin/Main.BMP")) == byName.basic.entries[2][3], "copied entry")
|
||||
local names = {}
|
||||
for _, e in b:list() do
|
||||
table.insert(names, e.name)
|
||||
end
|
||||
t:eq(table.concat(names, ","), "readme.txt,Skin/Main.BMP,Skin/,Skin/sub/deep.txt,empty.txt,__MACOSX/Skin/._Main.BMP,Sk\u{ef}n/\u{fc}nicode.txt,new/one.txt", "order kept")
|
||||
-- create, encode of a table, encode of another Archive
|
||||
local c = ZipF.create()
|
||||
c:add("hello.txt", "hi")
|
||||
local cz = ZipF.decode(Bytes.reader(ZipF.encode(c) :: buffer)) :: any
|
||||
t:eq(buffer.tostring(cz:read("hello.txt")), "hi", "create + encode")
|
||||
local tz = ZipF.decode(Bytes.reader(ZipF.encode({ ["b.txt"] = "bee", ["a.txt"] = buffer.fromstring("ay") }) :: buffer)) :: any
|
||||
t:check(tz:list()[1].name == "a.txt" and buffer.tostring(tz:read("b.txt")) == "bee", "encode a { name = data } table")
|
||||
local _, ee = ZipF.encode(5 :: any)
|
||||
t:check(ee and ee.code == Err.ARG, "encode a number")
|
||||
-- comments survive a rewrite
|
||||
local cm = ZipF.decode(Bytes.reader(buffer.fromstring(byName.comment.data))) :: any
|
||||
t:eq(string.sub(Zip.open(cm:write()).comment, 1, 14), "a comment with", "comment kept on write")
|
||||
-- the api
|
||||
local la = F.archive.load(byName.basic.data)
|
||||
t:check(la and la.kind == "archive" and #la:list() == byName.basic.count, "F.archive.load")
|
||||
t:eq(F.detect(byName.basic.data), "zip", "F.detect")
|
||||
local saved = F.save(la, nil, { format = "zip" })
|
||||
t:check(saved and #Zip.open(saved):list() == byName.basic.count, "F.save zip")
|
||||
local saved2 = F.save(la)
|
||||
t:check(saved2 ~= nil, "F.save without a format uses the source format")
|
||||
end
|
||||
|
||||
-- corrupt archives never throw
|
||||
local samples = {}
|
||||
for _, a in Fx.archives do
|
||||
if a.data then
|
||||
table.insert(samples, a.data)
|
||||
end
|
||||
end
|
||||
t:fuzz("open + read every entry", function(b: buffer)
|
||||
local z = Zip.open(b)
|
||||
if z then
|
||||
for _, e in z:list() do
|
||||
z:read(e)
|
||||
end
|
||||
end
|
||||
return z
|
||||
end, samples, { mutations = 40 })
|
||||
t:fuzz("archive decode + write", function(b: buffer)
|
||||
local a = ZipF.decode(Bytes.reader(b))
|
||||
if a then
|
||||
for _, e in a:list() do
|
||||
a:read(e.name)
|
||||
end
|
||||
a:write()
|
||||
end
|
||||
return a
|
||||
end, samples, { mutations = 10, garbage = 50 })
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,203 @@
|
||||
-- audio/flac tests: every fixture from tools/fixtures/flac.py (flac 0-8, 4-32 bits, 1-6 channels, odd rates and block
|
||||
-- sizes, LPC order 32, wasted bits, every stereo mode, ffmpeg's encoder, Ogg FLAC, ID3v2 in front) decoded bit-exact
|
||||
-- against `flac -d`; sample-accurate seeking; f32 scaling and output reuse; decode() to an Audio from a sub-range
|
||||
-- Reader; tags and pictures; the length from the last frame; sniff; the api; damaged frames skipped; the fuzz pass.
|
||||
-- Ported from flac-luau tests/flac.luau. Fixtures: tools/fixtures/flac.py.
|
||||
local T = require("@tests/T")
|
||||
local Flac = require("@formats/audio/flac")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local F = require("@formats")
|
||||
local Cases = require("@tests/gen/flac_cases")
|
||||
|
||||
local t = T.suite("flac")
|
||||
|
||||
local function open(b: any, opts: any?): (any, any)
|
||||
return Flac.open(Bytes.reader(if type(b) == "string" then buffer.fromstring(b) else b), opts)
|
||||
end
|
||||
local byName = {}
|
||||
for _, c in Cases do
|
||||
byName[c.name] = c
|
||||
end
|
||||
|
||||
t:eq(Flac.name, "flac", "name")
|
||||
t:check(Flac.caps.decode and not Flac.caps.encode, "caps")
|
||||
|
||||
local seekChecks = 0
|
||||
for _, fx in Cases do
|
||||
local name = fx.name
|
||||
local dec, err = open(fx.data)
|
||||
t:check(dec, name .. ": open: " .. tostring(err))
|
||||
t:check(dec.sampleRate == fx.rate and dec.channels == fx.channels and dec.bitsPerSample == fx.bps, name .. ": format")
|
||||
t:eq(dec.frames, fx.frames, name .. ": frames")
|
||||
t:check(math.abs(dec.duration - fx.frames / fx.rate) < 1e-9, name .. ": duration")
|
||||
t:eq(dec.container, if fx.ogg then "ogg" else "flac", name .. ": container")
|
||||
local ch = dec.channels
|
||||
local all = table.create(fx.frames * ch, 0)
|
||||
local crc, n, k = 0, 0, 0
|
||||
local sizes = { 4096, 1, 777, 10000, 3 }
|
||||
while true do
|
||||
k += 1
|
||||
local out, got = dec:readInt(sizes[k % #sizes + 1])
|
||||
if got == 0 then
|
||||
break
|
||||
end
|
||||
crc = Crc32.of(out, 0, got * ch * 4, crc)
|
||||
for i = 0, got * ch - 1 do
|
||||
all[n * ch + i + 1] = buffer.readi32(out, i * 4)
|
||||
end
|
||||
n += got
|
||||
end
|
||||
t:eq(n, fx.frames, name .. ": decoded frames")
|
||||
t:eq(crc, fx.crc, name .. ": samples identical to flac -d")
|
||||
t:eq(select(2, dec:position()), fx.frames, name .. ": position at end")
|
||||
-- f32 scaling, output reuse
|
||||
dec:seekSample(0)
|
||||
local reuse = buffer.create(100 * ch * 4)
|
||||
local f, gotf = dec:read(100, reuse)
|
||||
t:check(f == reuse, name .. ": output buffer reused")
|
||||
local scale = 2 ^ (fx.bps - 1)
|
||||
local bad = 0
|
||||
for i = 0, math.min(gotf, 100) * ch - 1 do
|
||||
if math.abs(buffer.readf32(f, i * 4) - all[i + 1] / scale) >= 1e-7 then
|
||||
bad += 1
|
||||
end
|
||||
end
|
||||
t:eq(bad, 0, name .. ": f32 samples")
|
||||
-- seeking
|
||||
local rand = T.rng(99)
|
||||
local targets = { 0, 1, fx.frames - 1, fx.frames // 2, 4096, 4095, 4097, 1152, 1151 }
|
||||
for _ = 1, 12 do
|
||||
table.insert(targets, rand(fx.frames))
|
||||
end
|
||||
for _, s in targets do
|
||||
if s >= 0 and s < fx.frames then
|
||||
t:check(dec:seekSample(s), name .. ": seek " .. s)
|
||||
t:eq(select(2, dec:position()), s, name .. ": position after seek " .. s)
|
||||
local out, got = dec:readInt(50)
|
||||
t:eq(got, math.min(50, fx.frames - s), name .. ": read after seek")
|
||||
local diff = 0
|
||||
for i = 0, got * ch - 1 do
|
||||
if buffer.readi32(out, i * 4) ~= all[s * ch + i + 1] then
|
||||
diff += 1
|
||||
end
|
||||
end
|
||||
t:eq(diff, 0, name .. ": samples after seek " .. s)
|
||||
seekChecks += 1
|
||||
end
|
||||
end
|
||||
dec:seek(dec.duration / 3)
|
||||
local _, pos = dec:position()
|
||||
t:check(math.abs(pos - fx.frames / 3) <= 1, name .. ": seek seconds")
|
||||
dec:seek(dec.duration + 5)
|
||||
t:eq(select(2, dec:read(10)), 0, name .. ": read past the end")
|
||||
for key, v in fx.tags or {} do
|
||||
t:eq(dec.tags[key], v, name .. ": tag " .. key)
|
||||
end
|
||||
t:eq(Flac.sniff(Bytes.reader(buffer.fromstring(fx.data))), 1, name .. ": sniff")
|
||||
end
|
||||
t:note("%d fixtures bit-exact against flac -d, %d seeks", #Cases, seekChecks)
|
||||
|
||||
-- decode() from a sub-range Reader
|
||||
for _, name in { "s16_l5", "ogg_s16", "id3", "s24_96k" } do
|
||||
local fx = byName[name]
|
||||
local big = buffer.create(#fx.data + 13)
|
||||
buffer.writestring(big, 6, fx.data)
|
||||
local a, err = Flac.decode(Bytes.reader(big, 6, #fx.data))
|
||||
t:check(a and a.kind == "audio" and a.frames == fx.frames and a.channels == fx.channels, name .. ": decode: " .. tostring(err))
|
||||
local d = open(fx.data)
|
||||
local ref = d:read(fx.frames)
|
||||
t:check(buffer.tostring(ref) == buffer.tostring(a.samples), name .. ": decode = read")
|
||||
t:eq(a.meta.source.bitDepth, fx.bps, name .. ": meta.source")
|
||||
end
|
||||
|
||||
-- tags and pictures
|
||||
do
|
||||
local dec = open(byName.s16_noseek.data)
|
||||
t:check(#dec.pictures == 1 and dec.pictures[1].mime == "image/png" and dec.pictures[1].width == 1, "picture")
|
||||
t:eq(#dec.seekTable, 0, "no seek table")
|
||||
t:check(string.find(dec.vendor, "reference libFLAC", 1, true), "vendor")
|
||||
t:eq(#dec.md5, 32, "md5")
|
||||
end
|
||||
|
||||
-- STREAMINFO without a total length: found from the last frame
|
||||
for _, name in { "s16_l5", "varblock", "bs17" } do
|
||||
local fx = byName[name]
|
||||
local b = buffer.fromstring(fx.data)
|
||||
buffer.writeu8(b, 8 + 13, bit32.band(buffer.readu8(b, 8 + 13), 0xF0))
|
||||
buffer.writeu32(b, 8 + 14, 0)
|
||||
local dec = open(b)
|
||||
t:check(dec and dec.frames == fx.frames, name .. ": length from the last frame")
|
||||
local crc, n = 0, 0
|
||||
while true do
|
||||
local out, got = dec:readInt(5000)
|
||||
if got == 0 then
|
||||
break
|
||||
end
|
||||
crc = Crc32.of(out, 0, got * dec.channels * 4, crc)
|
||||
n += got
|
||||
end
|
||||
t:check(n == fx.frames and crc == fx.crc, name .. ": decode without total length")
|
||||
end
|
||||
|
||||
-- sniff, errors, the api
|
||||
do
|
||||
t:eq(Flac.sniff(Bytes.reader(buffer.fromstring("ID3\4\0\0\0\0\0\2xxfLaC"))), 1, "sniff ID3 + fLaC")
|
||||
t:eq(Flac.sniff(Bytes.reader(buffer.fromstring("ID3\4\0\0\0\0\0\2xx\255\251"))), 0, "sniff ID3 + mp3")
|
||||
t:eq(Flac.sniff(Bytes.reader(buffer.fromstring("RIFF"))), 0, "sniff RIFF")
|
||||
local _, e1 = open("fLaC")
|
||||
t:check(e1 and Err.is(e1), "no metadata: " .. tostring(e1))
|
||||
local _, e2 = open(buffer.create(0))
|
||||
t:check(e2 and e2.code == Err.CORRUPT, "empty")
|
||||
local fx = byName.ogg_s16
|
||||
t:eq(F.detect(fx.data), "flac", "F.detect Ogg FLAC")
|
||||
local a = F.audio.load(fx.data)
|
||||
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))
|
||||
end
|
||||
|
||||
-- a damaged frame is dropped, the rest decodes
|
||||
do
|
||||
local src = buffer.fromstring(byName.s16_l5.data)
|
||||
local len = buffer.len(src)
|
||||
buffer.writeu8(src, len // 2, bit32.bxor(buffer.readu8(src, len // 2), 0x55))
|
||||
local d = open(src)
|
||||
local total = 0
|
||||
while true do
|
||||
local _, got = d:read(4096)
|
||||
if got == 0 then
|
||||
break
|
||||
end
|
||||
total += got
|
||||
end
|
||||
t:check(total < d.frames and total >= d.frames - 2 * 4096, "one damaged frame dropped: " .. total)
|
||||
end
|
||||
|
||||
-- fuzz
|
||||
local samples = {}
|
||||
for _, name in { "s16_l5", "ogg_s16", "id3", "varblock", "s32_rice2", "u8_mono", "bits4" } do
|
||||
table.insert(samples, byName[name].data)
|
||||
end
|
||||
t:fuzz("open + read + seek", function(b: buffer)
|
||||
local d = Flac.open(Bytes.reader(b))
|
||||
if d then
|
||||
local guard = 0
|
||||
while select(2, d:read(4096)) > 0 and guard < 200 do
|
||||
guard += 1
|
||||
end
|
||||
d:seek(0.1)
|
||||
d:read(100)
|
||||
d:seekSample(d.frames // 2)
|
||||
d:read(100)
|
||||
end
|
||||
return d
|
||||
end, samples, { mutations = 12, keepHeader = 42 })
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Flac.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 6, garbage = 60 })
|
||||
|
||||
t:done()
|
||||
@@ -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,210 @@
|
||||
-- codecs/Json tests: the JSONTestSuite parsing corpus (y_ must parse to Python's value, n_ must fail, i_ must not
|
||||
-- throw), Python json.dumps output in four styles parsed and reproduced byte for byte (compact sorted, ordered,
|
||||
-- indent 2, ensure_ascii), events / lines / decodeAt / writer, options, error codes, and the fuzz pass.
|
||||
-- Fixtures: tools/fixtures/json.py.
|
||||
local T = require("@tests/T")
|
||||
local Json = require("@formats/codecs/Json")
|
||||
local Types = require("@formats/Types")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Canon = require("@tests/data/Canon")
|
||||
local Suite = require("@tests/gen/json_suite")
|
||||
local Corpus = require("@tests/gen/json_corpus")
|
||||
|
||||
local t = T.suite("json")
|
||||
|
||||
-- events() rebuilt into a value (checks the pull tokenizer agrees with decode)
|
||||
local function fromEvents(s: string): (any, any)
|
||||
local stack, keys = {}, {}
|
||||
local top: any = nil
|
||||
local key: any = nil
|
||||
local function add(v: any)
|
||||
local cur = stack[#stack]
|
||||
if cur == nil then
|
||||
top = v
|
||||
elseif keys[#stack] ~= false then
|
||||
cur[key] = v
|
||||
else
|
||||
table.insert(cur, v)
|
||||
end
|
||||
end
|
||||
for ev, v in Json.events(s) do
|
||||
if ev == "error" then
|
||||
return nil, v
|
||||
elseif ev == "object" or ev == "array" then
|
||||
local tbl = if ev == "object" then Types.object() else {}
|
||||
add(tbl)
|
||||
table.insert(stack, tbl)
|
||||
keys[#stack] = if ev == "object" then true else false
|
||||
elseif ev == "endObject" or ev == "endArray" then
|
||||
keys[#stack] = nil
|
||||
table.remove(stack)
|
||||
elseif ev == "key" then
|
||||
key = v
|
||||
else
|
||||
add(v)
|
||||
end
|
||||
end
|
||||
return top, nil
|
||||
end
|
||||
|
||||
-- 1. JSONTestSuite
|
||||
local counts = { y = 0, n = 0, i = 0, iok = 0 }
|
||||
for _, c in Suite do
|
||||
local v, err = Json.decode(c.data)
|
||||
local ev, everr = fromEvents(c.data)
|
||||
if c.expect == "y" then
|
||||
t:check(v ~= nil, c.name .. ": parses (" .. tostring(err) .. ")")
|
||||
t:eq(Canon.of(v), c.canon, c.name .. ": value")
|
||||
t:check(ev ~= nil, c.name .. ": events parse (" .. tostring(everr) .. ")")
|
||||
t:eq(Canon.of(ev), c.canon, c.name .. ": events value")
|
||||
-- and our output reads back the same
|
||||
local s = Json.encode(v)
|
||||
t:check(s ~= nil, c.name .. ": encodes")
|
||||
t:eq(Canon.of(Json.decode(s :: string)), c.canon, c.name .. ": round trip")
|
||||
elseif c.expect == "n" then
|
||||
t:check(v == nil and Err.is(err), c.name .. ": rejected")
|
||||
t:check(ev == nil, c.name .. ": events reject")
|
||||
else
|
||||
counts.iok += if v ~= nil then 1 else 0
|
||||
end
|
||||
counts[c.expect] += 1
|
||||
end
|
||||
t:note("JSONTestSuite: %d y_ accepted, %d n_ rejected, %d of %d i_ accepted", counts.y, counts.n, counts.iok, counts.i)
|
||||
|
||||
-- 2. Python's json.dumps output: parse, compare, re-encode byte for byte
|
||||
for i, c in Corpus do
|
||||
local v, err = Json.decode(c.compact)
|
||||
t:check(v ~= nil, "corpus " .. i .. ": " .. tostring(err))
|
||||
t:eq(Canon.of(v), c.canon, "corpus " .. i .. ": value")
|
||||
t:eq(Json.encode(v), c.compact, "corpus " .. i .. ": compact text")
|
||||
t:eq(Json.encode(v, { indent = 2 }), c.pretty, "corpus " .. i .. ": indent 2 text")
|
||||
t:eq(Json.encode(v, { ascii = true }), c.ascii, "corpus " .. i .. ": ensure_ascii text")
|
||||
local o = Json.decode(c.ordered, { ordered = true })
|
||||
t:eq(Json.encode(o), c.ordered, "corpus " .. i .. ": ordered text")
|
||||
t:eq(Canon.of(Json.decode(c.ascii)), c.canon, "corpus " .. i .. ": ascii parse")
|
||||
t:eq(Canon.of(Json.decode(c.pretty)), c.canon, "corpus " .. i .. ": pretty parse")
|
||||
end
|
||||
|
||||
-- 3. options and API
|
||||
do
|
||||
local v = Json.decode('[12345678901234567890, -9007199254740993, 9007199254740991, 1.5e300]', { bigInts = "string" })
|
||||
t:eq(v[1], "12345678901234567890", "bigInts string")
|
||||
t:eq(v[2], "-9007199254740993", "bigInts negative")
|
||||
t:eq(v[3], 9007199254740991, "2^53 - 1 stays a number")
|
||||
t:eq(v[4], 1.5e300, "floats stay numbers")
|
||||
t:eq(Json.decode("[null]", { null = false })[1], false, "opts.null")
|
||||
t:eq(Json.decode("null"), Types.null, "top-level null")
|
||||
t:eq(Json.decode("\239\187\191[1]")[1], 1, "BOM skipped")
|
||||
t:eq(Json.decode(buffer.fromstring(" 7 ")), 7, "buffer input")
|
||||
local e = Json.decode('{"b":1,"a":{},"c":[]}')
|
||||
t:eq(Json.encode(e), '{"a":{},"b":1,"c":[]}', "empty object stays an object")
|
||||
local o = Json.decode('{"z":1,"a":2,"m":{"y":1,"b":2}}', { ordered = true })
|
||||
t:eq(Json.encode(o), '{"z":1,"a":2,"m":{"y":1,"b":2}}', "ordered keys")
|
||||
Types.set(o, "b", 3)
|
||||
o.a = nil
|
||||
t:eq(Json.encode(o), '{"z":1,"m":{"y":1,"b":2},"b":3}', "ordered set / remove")
|
||||
t:eq(Json.encode({}, { emptyTable = "object" }), "{}", "emptyTable object")
|
||||
t:eq(Json.encode({ [1] = "a", [3] = "c" }), '{"1":"a","3":"c"}', "sparse array -> object")
|
||||
t:eq(Json.encode({ 1, 2, x = 1 }), '{"1":1,"2":2,"x":1}', "mixed table -> object")
|
||||
t:eq(Json.encode("a/b", { escapeSlash = true }), '"a\\/b"', "escapeSlash")
|
||||
t:eq(Json.encode(0 / 0, { nan = "null" }), "null", "nan null")
|
||||
local _, ne = Json.encode(math.huge)
|
||||
t:eq(ne and ne.code, Err.ARG, "inf is an error")
|
||||
local cyc = {}
|
||||
cyc.self = cyc
|
||||
local _, ce = Json.encode(cyc)
|
||||
t:eq(ce and ce.code, Err.ARG, "cycle is an error")
|
||||
local _, fe = Json.encode({ f = print })
|
||||
t:eq(fe and fe.code, Err.ARG, "function is an error")
|
||||
t:eq(Json.encode(Types.Date.parse("1979-05-27T07:32:00Z")), '"1979-05-27T07:32:00Z"', "dates as strings")
|
||||
for _, x in { 0.1, 1 / 3, -2.5e-8, 1e300, 123456789012345, 2 ^ 53, 5e-324, 1.7976931348623157e308 } do
|
||||
t:eq(Json.decode(Json.encode(x) :: string), x, "number round trip " .. string.format("%.17g", x))
|
||||
end
|
||||
end
|
||||
|
||||
-- 4. streaming: lines, decodeAt, writer
|
||||
do
|
||||
local got = {}
|
||||
for _, v in Json.lines('{"a":1}\n[2]\n"x"\n 3 ') do
|
||||
table.insert(got, (Json.encode(v)))
|
||||
end
|
||||
t:eq(table.concat(got, "|"), '{"a":1}|[2]|"x"|3', "lines")
|
||||
local n, last = 0, nil
|
||||
for _, v, e in Json.lines("1 2 [") do
|
||||
if e then
|
||||
last = e
|
||||
else
|
||||
n += 1
|
||||
end
|
||||
end
|
||||
t:eq(n, 2, "lines stop at the bad value")
|
||||
t:eq(last and last.code, Err.TRUNCATED, "lines report the error")
|
||||
local v, p = Json.decodeAt("[1] [2]", 1)
|
||||
t:eq(v[1], 1, "decodeAt value")
|
||||
t:eq(p, 4, "decodeAt next")
|
||||
t:eq(Json.decodeAt(" ", 1), nil, "decodeAt at the end")
|
||||
|
||||
local w = Json.writer({ indent = 2 })
|
||||
w:beginObject():key("a"):value({ 1, 2 }):key("b"):beginArray():value("x"):beginObject():endObject():endArray():endObject()
|
||||
local s = w:tostring()
|
||||
t:eq(s, Json.encode(Json.decode('{"a":[1,2],"b":["x",{}]}', { ordered = true }), { indent = 2 }), "writer pretty")
|
||||
local w2 = Json.writer()
|
||||
w2:beginArray()
|
||||
local parts = {}
|
||||
for i = 1, 5 do
|
||||
w2:value(i)
|
||||
table.insert(parts, w2:flush())
|
||||
end
|
||||
w2:endArray()
|
||||
table.insert(parts, w2:flush())
|
||||
t:eq(table.concat(parts), "[1,2,3,4,5]", "writer flush chunks")
|
||||
t:eq(w2:tostring(), "[1,2,3,4,5]", "writer tostring after flushes")
|
||||
local w3 = Json.writer()
|
||||
w3:beginArray():key("x")
|
||||
t:check(w3.err ~= nil, "writer: key in array")
|
||||
local w4 = Json.writer()
|
||||
w4:beginObject():value(1)
|
||||
t:check(w4.err ~= nil, "writer: value without key")
|
||||
local w5 = Json.writer()
|
||||
w5:beginObject()
|
||||
t:check(w5:tostring() == nil, "writer: unclosed")
|
||||
end
|
||||
|
||||
-- 5. errors
|
||||
local function code(s: string, opts: any?): string?
|
||||
local _, e = Json.decode(s, opts)
|
||||
return e and e.code
|
||||
end
|
||||
t:eq(code('{"a":'), Err.TRUNCATED, "truncated object")
|
||||
t:eq(code('"abc'), Err.TRUNCATED, "truncated string")
|
||||
t:eq(code("[1 2]"), Err.CORRUPT, "missing comma")
|
||||
t:eq(code("[1] x"), Err.CORRUPT, "trailing data")
|
||||
t:eq(code(string.rep("[", 50) .. string.rep("]", 50), { maxDepth = 10 }), Err.LIMIT, "maxDepth")
|
||||
t:eq(code(string.rep("[", 100000)), Err.LIMIT, "100000 opening brackets")
|
||||
t:eq(code(""), Err.TRUNCATED, "empty input")
|
||||
local _, ae = Json.decode(42 :: any)
|
||||
t:eq(ae and ae.code, Err.ARG, "bad argument")
|
||||
do
|
||||
local _, e = Json.decode('{"a": tru}')
|
||||
t:eq(e and e.offset, 6, "error offset")
|
||||
end
|
||||
|
||||
-- 6. fuzz
|
||||
local samples = {}
|
||||
for i = 1, 40 do
|
||||
table.insert(samples, Corpus[i].compact)
|
||||
end
|
||||
for _, c in Suite do
|
||||
if #samples < 120 and c.expect == "y" and #c.data < 200 then
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Json.decode(b)
|
||||
end, samples)
|
||||
t:fuzz("events", function(b: buffer)
|
||||
for _ in Json.events(b) do
|
||||
end
|
||||
return nil
|
||||
end, samples, { garbage = 50 })
|
||||
t:done()
|
||||
@@ -0,0 +1,108 @@
|
||||
-- codecs/Url + codecs/Text tests: every example of RFC 3986 section 5.4 (normal and abnormal), dot-segment removal,
|
||||
-- splitting, encoding and the location helpers (ported from playlist-luau tests/url.luau); random references against
|
||||
-- Python's urllib.parse.urljoin; Url.locate / Url.base; Windows-1252 decoding against Python's cp1252 codec; lines,
|
||||
-- BOM, trim; the fuzz pass. Fixtures: tools/fixtures/playlist.py.
|
||||
local T = require("@tests/T")
|
||||
local Url = require("@formats/codecs/Url")
|
||||
local Text = require("@formats/codecs/Text")
|
||||
local Ref = require("@tests/gen/playlist_url")
|
||||
local Cp = require("@tests/gen/playlist_cp1252")
|
||||
|
||||
local t = T.suite("url")
|
||||
local function eq(got: any, want: any, label: string)
|
||||
t:eq(got, want, label)
|
||||
end
|
||||
|
||||
local BASE = "http://a/b/c/d;p?q"
|
||||
local cases = {
|
||||
-- 5.4.1 normal
|
||||
{ "g:h", "g:h" }, { "g", "http://a/b/c/g" }, { "./g", "http://a/b/c/g" }, { "g/", "http://a/b/c/g/" },
|
||||
{ "/g", "http://a/g" }, { "//g", "http://g" }, { "?y", "http://a/b/c/d;p?y" }, { "g?y", "http://a/b/c/g?y" },
|
||||
{ "#s", "http://a/b/c/d;p?q#s" }, { "g#s", "http://a/b/c/g#s" }, { "g?y#s", "http://a/b/c/g?y#s" },
|
||||
{ ";x", "http://a/b/c/;x" }, { "g;x", "http://a/b/c/g;x" }, { "g;x?y#s", "http://a/b/c/g;x?y#s" },
|
||||
{ "", "http://a/b/c/d;p?q" }, { ".", "http://a/b/c/" }, { "./", "http://a/b/c/" }, { "..", "http://a/b/" },
|
||||
{ "../", "http://a/b/" }, { "../g", "http://a/b/g" }, { "../..", "http://a/" }, { "../../", "http://a/" },
|
||||
{ "../../g", "http://a/g" },
|
||||
-- 5.4.2 abnormal
|
||||
{ "../../../g", "http://a/g" }, { "../../../../g", "http://a/g" }, { "/./g", "http://a/g" },
|
||||
{ "/../g", "http://a/g" }, { "g.", "http://a/b/c/g." }, { ".g", "http://a/b/c/.g" }, { "g..", "http://a/b/c/g.." },
|
||||
{ "..g", "http://a/b/c/..g" }, { "./../g", "http://a/b/g" }, { "./g/.", "http://a/b/c/g/" },
|
||||
{ "g/./h", "http://a/b/c/g/h" }, { "g/../h", "http://a/b/c/h" }, { "g;x=1/./y", "http://a/b/c/g;x=1/y" },
|
||||
{ "g;x=1/../y", "http://a/b/c/y" }, { "g?y/./x", "http://a/b/c/g?y/./x" }, { "g?y/../x", "http://a/b/c/g?y/../x" },
|
||||
{ "g#s/./x", "http://a/b/c/g#s/./x" }, { "g#s/../x", "http://a/b/c/g#s/../x" }, { "http:g", "http:g" },
|
||||
}
|
||||
for _, c in cases do
|
||||
eq(Url.resolve(c[1], BASE), c[2], "resolve " .. c[1])
|
||||
end
|
||||
-- base with an empty path
|
||||
eq(Url.resolve("g", "http://a"), "http://a/g", "empty base path")
|
||||
eq(Url.resolve("g", "http://a?x"), "http://a/g", "empty base path with query")
|
||||
|
||||
eq(Url.removeDotSegments("/a/b/c/./../../g"), "/a/g", "remove_dot_segments 1")
|
||||
eq(Url.removeDotSegments("mid/content=5/../6"), "mid/6", "remove_dot_segments 2")
|
||||
|
||||
local p = Url.split("https://user@host:8080/p/a.mp3?x=1&y#frag")
|
||||
eq(p.scheme, "https", "split scheme")
|
||||
eq(p.authority, "user@host:8080", "split authority")
|
||||
eq(p.path, "/p/a.mp3", "split path")
|
||||
eq(p.query, "x=1&y", "split query")
|
||||
eq(p.fragment, "frag", "split fragment")
|
||||
eq(Url.join(p), "https://user@host:8080/p/a.mp3?x=1&y#frag", "join")
|
||||
local q = Url.split("a/b")
|
||||
eq(q.scheme, nil, "relative has no scheme")
|
||||
eq(q.authority, nil, "relative has no authority")
|
||||
|
||||
eq(Url.encodeUnsafe("a b/ü%20?x=\"1\"#f"), "a%20b/%C3%BC%20?x=%221%22#f", "encodeUnsafe")
|
||||
eq(Url.isWindowsPath("C:\\Music\\a.mp3"), true, "windows drive")
|
||||
eq(Url.isWindowsPath("d:/x.mp3"), true, "windows drive with slash")
|
||||
eq(Url.isWindowsPath("\\\\server\\share\\a.mp3"), true, "UNC")
|
||||
eq(Url.isWindowsPath("http://x/a"), false, "http is not windows")
|
||||
eq(Url.scheme("C:\\a.mp3"), nil, "a drive letter is not a scheme")
|
||||
eq(Url.scheme("HTTPS://x"), "https", "scheme lower-cased")
|
||||
eq(Url.scheme("music/a.mp3"), nil, "relative has no scheme")
|
||||
|
||||
|
||||
-- Python's urljoin
|
||||
for _, c in Ref do
|
||||
eq(Url.resolve(c[1], c[2]), c[3], "urljoin " .. c[1] .. " against " .. c[2])
|
||||
end
|
||||
t:note("%d random references resolve as urllib.parse.urljoin", #Ref)
|
||||
|
||||
-- locate / base
|
||||
do
|
||||
local w = {}
|
||||
local base, scheme = Url.base("https://h/a/list.m3u", w)
|
||||
t:check(base == "https://h/a/list.m3u" and scheme == "https", "base")
|
||||
local l = Url.locate(" b c.mp3 ", base, scheme)
|
||||
t:check(l.url == "https://h/a/b%20c.mp3" and l.playable, "locate relative")
|
||||
t:check(Url.locate("C:\\x.mp3", base, scheme).reason == "local path", "locate windows")
|
||||
t:check(Url.locate("ftp://x/y", base, scheme).reason == "scheme ftp", "locate ftp")
|
||||
local nb, ns = Url.base("lists/x.m3u", w)
|
||||
t:check(nb == nil and ns == nil and #w == 1, "a relative base is ignored with a warning")
|
||||
t:check(select(2, Url.base("C:\\Music\\l.m3u")) == "windows", "windows base")
|
||||
end
|
||||
|
||||
-- Text
|
||||
do
|
||||
for _, c in Cp do
|
||||
eq(Text.toUtf8("x" .. string.char(c[1]) .. "y"), "x" .. c[2] .. "y", string.format("cp1252 0x%02x", c[1]))
|
||||
end
|
||||
local w = {}
|
||||
Text.toUtf8("\150", w)
|
||||
t:check(#w == 1, "cp1252 warning")
|
||||
eq(Text.toUtf8("\239\187\191abc"), "abc", "BOM stripped")
|
||||
eq(Text.toUtf8("h\u{e9}"), "h\u{e9}", "UTF-8 kept")
|
||||
local ls = Text.lines("a\r\nb\rc\nd")
|
||||
t:check(#ls == 4 and ls[1] == "a" and ls[2] == "b" and ls[3] == "c" and ls[4] == "d", "lines")
|
||||
eq(Text.trim(" x y \t"), "x y", "trim")
|
||||
end
|
||||
|
||||
t:fuzz("resolve + locate", function(b: buffer)
|
||||
local s = buffer.tostring(b)
|
||||
Url.resolve(s, "http://a/b/c/d;p?q")
|
||||
Url.resolve("g/../h", s)
|
||||
Url.locate(s, "http://h/", "http")
|
||||
return Text.lines(Text.toUtf8(s))
|
||||
end, { "http://a/b/../c?x#y", "C:\\a\\b.mp3", "\239\187\191#EXTM3U\r\n" }, { mutations = 30 })
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,197 @@
|
||||
-- codecs/Xml tests: random documents (namespaces, escapes, CDATA, comments, PIs, DOCTYPE entities, UTF-16, Latin-1)
|
||||
-- against Python's ElementTree trees; encode -> decode round trips; well-formedness verdicts against expat
|
||||
-- (hand-written cases and random mutations); events, helpers, options, error codes; the fuzz pass.
|
||||
-- Fixtures: tools/fixtures/xml.py.
|
||||
local T = require("@tests/T")
|
||||
local Xml = require("@formats/codecs/Xml")
|
||||
local Types = require("@formats/Types")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Docs = require("@tests/gen/xml_docs")
|
||||
local Wf = require("@tests/gen/xml_wf")
|
||||
|
||||
local t = T.suite("xml")
|
||||
|
||||
-- ElementTree's view of an element (tools/fixtures/xml.py canon): Clark names, xmlns attributes dropped, text / tail
|
||||
local function s(x: string?): string
|
||||
x = x or ""
|
||||
return #(x :: string) .. ":" .. (x :: string)
|
||||
end
|
||||
local function canon(e: any, tail: string?): string
|
||||
local out = { "(" .. s(Xml.clark(e)) }
|
||||
local keys = {}
|
||||
local vals = {}
|
||||
for _, k in Types.keys(e.attrs) do
|
||||
if k ~= "xmlns" and string.sub(k, 1, 6) ~= "xmlns:" then
|
||||
local ck = Xml.clark(e, k)
|
||||
table.insert(keys, ck)
|
||||
vals[ck] = e.attrs[k]
|
||||
end
|
||||
end
|
||||
table.sort(keys)
|
||||
for _, k in keys do
|
||||
table.insert(out, "|" .. s(k) .. "=" .. s(vals[k]))
|
||||
end
|
||||
-- text: strings before the first element child; each child's tail: strings after it
|
||||
local text = {}
|
||||
local i = 1
|
||||
local ch = e.children
|
||||
while i <= #ch and (type(ch[i]) == "string" or ch[i].name == "#cdata") do
|
||||
table.insert(text, Xml.text(ch[i]))
|
||||
i += 1
|
||||
end
|
||||
table.insert(out, "|t" .. s(table.concat(text)))
|
||||
while i <= #ch do
|
||||
local c = ch[i]
|
||||
i += 1
|
||||
local tl = {}
|
||||
while i <= #ch and (type(ch[i]) == "string" or ch[i].name == "#cdata") do
|
||||
table.insert(tl, Xml.text(ch[i]))
|
||||
i += 1
|
||||
end
|
||||
table.insert(out, canon(c, table.concat(tl)))
|
||||
end
|
||||
return table.concat(out) .. ")t" .. s(tail)
|
||||
end
|
||||
|
||||
-- 1. documents vs ElementTree, and round trips
|
||||
for i, d in Docs do
|
||||
local doc, err = Xml.decode(d.data, { whitespace = true })
|
||||
t:check(doc, "doc " .. i .. ": " .. tostring(err))
|
||||
t:eq(canon((doc :: any).root), d.canon, "doc " .. i .. ": tree")
|
||||
-- keep everything, encode, decode again: the same tree
|
||||
local full = Xml.decode(d.data, { whitespace = true, comments = true, cdata = true, pi = true }) :: any
|
||||
local out, eerr = Xml.encode(full)
|
||||
t:check(out, "doc " .. i .. ": encodes (" .. tostring(eerr) .. ")")
|
||||
local again, aerr = Xml.decode(out :: string, { whitespace = true })
|
||||
t:check(again, "doc " .. i .. ": re-decodes (" .. tostring(aerr) .. ")")
|
||||
t:eq(canon((again :: any).root), d.canon, "doc " .. i .. ": round trip")
|
||||
local pretty = Xml.encode(full, { indent = 2 }) :: string
|
||||
t:check(Xml.decode(pretty), "doc " .. i .. ": pretty output parses")
|
||||
-- the namespace option agrees with the clark helper
|
||||
local nsdoc = Xml.decode(d.data, { namespaces = true }) :: any
|
||||
local root = nsdoc.root
|
||||
local want = string.match(Xml.clark(root), "^{([^}]*)}")
|
||||
t:eq(root.ns, want, "doc " .. i .. ": node.ns")
|
||||
end
|
||||
|
||||
-- 2. well-formedness against expat
|
||||
local agree, total, accepted, rejected = 0, 0, 0, 0
|
||||
for i, c in Wf do
|
||||
local doc = Xml.decode(c.data)
|
||||
local ok = doc ~= nil
|
||||
total += 1
|
||||
if ok == c.ok then
|
||||
agree += 1
|
||||
elseif i <= 60 then
|
||||
t:check(false, "wf case " .. i .. " " .. string.format("%q", c.data) .. ": expat says " .. tostring(c.ok))
|
||||
end
|
||||
if c.ok then
|
||||
accepted += 1
|
||||
else
|
||||
rejected += 1
|
||||
end
|
||||
end
|
||||
t:note("well-formedness: %d of %d verdicts agree with expat (%d well-formed, %d not)", agree, total, accepted, rejected)
|
||||
t:check(agree >= total * 0.99, "well-formedness agreement >= 99%")
|
||||
|
||||
-- 3. API details
|
||||
do
|
||||
local src = '<?xml version="1.0"?>\n<!DOCTYPE r [<!ENTITY e "E&#38;">]>\n<!--c--><r xmlns="urn:d" xmlns:p="urn:p" z="1" a="2"><p:x p:k="v">t<![CDATA[<c>]]>u</p:x><?go now?><y/>\n</r>'
|
||||
local doc = Xml.decode(src, { comments = true, cdata = true, pi = true, namespaces = true }) :: any
|
||||
t:eq(doc.declaration.version, "1.0", "declaration")
|
||||
t:eq(doc.doctype.name, "r", "doctype name")
|
||||
t:eq(doc.doctype.entities.e, "E&", "doctype entities (char refs expanded once)")
|
||||
t:eq(doc.children[1].name, "#comment", "prolog comment kept")
|
||||
local r = doc.root
|
||||
t:eq(table.concat(Types.keys(r.attrs), ","), "xmlns,xmlns:p,z,a", "attribute order")
|
||||
t:eq(r.ns, "urn:d", "default namespace")
|
||||
local x = Xml.child(r, "x") :: any
|
||||
t:eq(x.name, "p:x", "child by local name")
|
||||
t:eq(x.ns, "urn:p", "prefixed namespace")
|
||||
t:eq(Xml.clark(x, "p:k"), "{urn:p}k", "attribute clark")
|
||||
t:eq(x.children[2].name, "#cdata", "cdata node")
|
||||
t:eq(Xml.text(x), "t<c>u", "text with cdata")
|
||||
t:eq(r.children[2].name, "#pi", "pi node")
|
||||
t:eq(r.children[2].target .. "|" .. r.children[2].text, "go|now", "pi target / data")
|
||||
t:eq(#Xml.children(r), 2, "element children")
|
||||
t:eq(#Xml.descendants(doc), 3, "descendants")
|
||||
t:eq(x.parent, r, "parent link")
|
||||
t:eq(Xml.decode("<a>&e;</a>") == nil, true, "undefined entity")
|
||||
local d2 = Xml.decode('<!DOCTYPE r [<!ENTITY e "E&#38;">]><r a="&e;">&e;</r>') :: any
|
||||
t:eq(d2.root.attrs.a, "E&", "entity in attribute")
|
||||
t:eq(Xml.text(d2.root), "E&", "entity in text")
|
||||
-- whitespace handling
|
||||
local w = Xml.decode("<a>\n <b> x </b>\n <c xml:space='preserve'> </c>\n</a>") :: any
|
||||
t:eq(#w.root.children, 2, "whitespace-only text dropped")
|
||||
t:eq(Xml.text(w.root.children[1]), " x ", "other text kept as is")
|
||||
t:eq(w.root.children[2].children[1], " ", "xml:space preserve")
|
||||
t:eq(#(Xml.decode("<a>\n <b/>\n</a>", { whitespace = true }) :: any).root.children, 3, "opts.whitespace")
|
||||
-- attribute normalization and line endings
|
||||
local n = Xml.decode("<a b='x\ty\r\nz '>l1\r\nl2\rl3</a>") :: any
|
||||
t:eq(n.root.attrs.b, "x y z\n", "attribute value normalization")
|
||||
t:eq(Xml.text(n.root), "l1\nl2\nl3", "line endings")
|
||||
-- builders and encode
|
||||
local e = Xml.element("svg", { width = "10", height = "5" }, { Xml.element("rect", { x = "1" }), "a<b & \"c\"" })
|
||||
Xml.setAttr(e, "id", "q\"\n")
|
||||
t:eq(Xml.encode(e), '<svg height="5" width="10" id="q" "><rect x="1"/>a<b & "c"</svg>', "encode element")
|
||||
local d3 = Xml.document(Xml.element("r", nil, { Xml.element("a"), Xml.element("b", nil, { "t" }) }))
|
||||
t:eq(Xml.encode(d3, { indent = 2 }), '<?xml version="1.0" encoding="UTF-8"?>\n<r>\n <a/>\n <b>t</b>\n</r>\n', "pretty document")
|
||||
t:eq(Xml.encode(Xml.element("a"), { selfClose = false }), "<a></a>", "selfClose false")
|
||||
local _, be = Xml.encode(Xml.element("1bad"))
|
||||
t:eq(be and be.code, Err.ARG, "bad name on encode")
|
||||
local cyc = Xml.element("a")
|
||||
table.insert(cyc.children, cyc)
|
||||
local _, ce = Xml.encode(cyc)
|
||||
t:eq(ce and ce.code, Err.ARG, "cycle on encode")
|
||||
t:eq(Xml.encode({ name = "#cdata", attrs = Types.object(), children = {}, text = "a]]>b" } :: any), "<![CDATA[a]]]]><![CDATA[>b]]>", "cdata split")
|
||||
-- events
|
||||
local evs = {}
|
||||
for ev, a in Xml.events("<a x='1'><b>t</b><!--c--></a>") do
|
||||
table.insert(evs, ev .. (if type(a) == "string" then ":" .. a else ""))
|
||||
end
|
||||
t:eq(table.concat(evs, " "), "start:a start:b text:t end:b comment:c end:a", "events")
|
||||
local last
|
||||
for ev, a in Xml.events("<a><b></a>") do
|
||||
last = { ev, a }
|
||||
end
|
||||
t:eq(last[1], "error", "events error")
|
||||
t:eq(last[2].code, Err.CORRUPT, "events error code")
|
||||
-- UTF-16 without BOM and encodings
|
||||
local u16 = buffer.create(8)
|
||||
for k, ch in { 60, 0, 97, 0, 47, 0, 62, 0 } do
|
||||
buffer.writeu8(u16, k - 1, ch)
|
||||
end
|
||||
t:eq((Xml.decode(u16) :: any).root.name, "a", "UTF-16LE without BOM")
|
||||
local _, ue = Xml.decode("<?xml version='1.0' encoding='EBCDIC'?><a/>")
|
||||
t:eq(ue and ue.code, Err.UNSUPPORTED, "unsupported encoding")
|
||||
end
|
||||
|
||||
-- 4. errors and limits
|
||||
local function code(src: string, opts: any?): string?
|
||||
local _, e = Xml.decode(src, opts)
|
||||
return e and e.code
|
||||
end
|
||||
t:eq(code("<a><b>"), Err.TRUNCATED, "unclosed")
|
||||
t:eq(code("<a></b>"), Err.CORRUPT, "mismatch")
|
||||
t:eq(code("<a b='1' b='2'/>"), Err.CORRUPT, "duplicate attribute")
|
||||
t:eq(code(string.rep("<a>", 60) .. string.rep("</a>", 60), { maxDepth = 50 }), Err.LIMIT, "maxDepth")
|
||||
t:eq(code('<!DOCTYPE r [<!ENTITY a "aaaaaaaaaa"><!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;"><!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;"><!ENTITY d "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;"><!ENTITY e "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">]><r>&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;</r>', { maxExpansion = 100000 }), Err.LIMIT, "billion laughs")
|
||||
t:eq(code('<!DOCTYPE r [<!ENTITY a "&a;">]><r>&a;</r>'), Err.CORRUPT, "recursive entity")
|
||||
t:eq(code('<!DOCTYPE r [<!ENTITY x SYSTEM "file.xml">]><r>&x;</r>'), Err.UNSUPPORTED, "external entity")
|
||||
t:eq(code("<p:a/>", { namespaces = true }), Err.CORRUPT, "undeclared prefix")
|
||||
local _, ae = Xml.decode(5 :: any)
|
||||
t:eq(ae and ae.code, Err.ARG, "bad argument")
|
||||
|
||||
-- 5. fuzz
|
||||
local samples = {}
|
||||
for i = 1, 40 do
|
||||
table.insert(samples, Docs[i].data)
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Xml.decode(b, { comments = true, namespaces = true })
|
||||
end, samples)
|
||||
t:fuzz("encode(decode)", function(b: buffer)
|
||||
local d = Xml.decode(b, { comments = true, cdata = true, pi = true })
|
||||
return d and Xml.encode(d, { indent = 1 })
|
||||
end, samples, { garbage = 20 })
|
||||
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()
|
||||
@@ -0,0 +1,86 @@
|
||||
-- tests/data/Canon: the canonical text of a decoded data value, the same as tools/fixtures/_data_common.py canon() on
|
||||
-- Python's parse: null n, true t, false f, numbers #%d (integral under 2^53) or #%.17g, strings s<len>:<bytes>,
|
||||
-- buffers b<len>:<bytes>, arrays [x,...], objects {k=v,...} sorted by key text, dates d<rfc3339>. A module the data
|
||||
-- tests require (running it alone does nothing).
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local Canon = {}
|
||||
|
||||
local function num(x: number): string
|
||||
if x ~= x then
|
||||
return "#nan"
|
||||
elseif x == math.huge then
|
||||
return "#inf"
|
||||
elseif x == -math.huge then
|
||||
return "#-inf"
|
||||
elseif x == math.floor(x) and math.abs(x) < 2 ^ 53 then
|
||||
return string.format("#%d", x)
|
||||
end
|
||||
return "#" .. string.format("%.17g", x)
|
||||
end
|
||||
|
||||
local function isArray(t: { [any]: any }): boolean
|
||||
if Types.isObject(t) then
|
||||
return false
|
||||
end
|
||||
local n = #t
|
||||
local c = 0
|
||||
for _ in next, t do
|
||||
c += 1
|
||||
end
|
||||
return c == n
|
||||
end
|
||||
|
||||
local function canon(v: any, out: { string })
|
||||
local tv = type(v)
|
||||
if v == Types.null then
|
||||
table.insert(out, "n")
|
||||
elseif tv == "boolean" then
|
||||
table.insert(out, if v then "t" else "f")
|
||||
elseif tv == "number" then
|
||||
table.insert(out, num(v))
|
||||
elseif tv == "string" then
|
||||
table.insert(out, "s" .. #v .. ":" .. v)
|
||||
elseif tv == "buffer" then
|
||||
table.insert(out, "b" .. buffer.len(v) .. ":" .. buffer.tostring(v))
|
||||
elseif tv == "table" and Types.Date.is(v) then
|
||||
table.insert(out, "d" .. tostring(v))
|
||||
elseif tv == "table" then
|
||||
if isArray(v) then
|
||||
table.insert(out, "[")
|
||||
for i = 1, #v do
|
||||
canon(v[i], out)
|
||||
table.insert(out, ",")
|
||||
end
|
||||
table.insert(out, "]")
|
||||
else
|
||||
local items = {}
|
||||
for k, x in next, v do
|
||||
local ko = {}
|
||||
canon(k, ko)
|
||||
table.insert(items, { table.concat(ko), x })
|
||||
end
|
||||
table.sort(items, function(a, b)
|
||||
return a[1] < b[1]
|
||||
end)
|
||||
table.insert(out, "{")
|
||||
for _, it in items do
|
||||
table.insert(out, it[1] .. "=")
|
||||
canon(it[2], out)
|
||||
table.insert(out, ",")
|
||||
end
|
||||
table.insert(out, "}")
|
||||
end
|
||||
else
|
||||
table.insert(out, "?" .. tv)
|
||||
end
|
||||
end
|
||||
|
||||
-- of(v) -> the canonical text
|
||||
function Canon.of(v: any): string
|
||||
local out = {}
|
||||
canon(v, out)
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
return Canon
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 9.0 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 9.0 KiB |
|
After Width: | Height: | Size: 4.2 KiB |
|
After Width: | Height: | Size: 4.2 KiB |
|
After Width: | Height: | Size: 4.2 KiB |
|
After Width: | Height: | Size: 9.0 KiB |
|
After Width: | Height: | Size: 9.0 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 8.4 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 8.6 KiB |
|
After Width: | Height: | Size: 273 B |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 4.1 KiB |
|
After Width: | Height: | Size: 4.1 KiB |
|
After Width: | Height: | Size: 3.7 KiB |
|
After Width: | Height: | Size: 9.1 KiB |
|
After Width: | Height: | Size: 9.0 KiB |
|
After Width: | Height: | Size: 9.0 KiB |
|
After Width: | Height: | Size: 5.0 KiB |
|
After Width: | Height: | Size: 8.8 KiB |
|
After Width: | Height: | Size: 8.6 KiB |
|
After Width: | Height: | Size: 9.0 KiB |
|
After Width: | Height: | Size: 9.1 KiB |
|
After Width: | Height: | Size: 9.1 KiB |
|
After Width: | Height: | Size: 8.4 KiB |
|
After Width: | Height: | Size: 8.8 KiB |
|
After Width: | Height: | Size: 8.9 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
|
After Width: | Height: | Size: 4.2 KiB |
|
After Width: | Height: | Size: 9.1 KiB |
|
After Width: | Height: | Size: 8.8 KiB |
|
After Width: | Height: | Size: 8.8 KiB |
|
After Width: | Height: | Size: 8.8 KiB |
|
After Width: | Height: | Size: 9.0 KiB |
|
After Width: | Height: | Size: 9.0 KiB |
|
After Width: | Height: | Size: 9.1 KiB |
|
After Width: | Height: | Size: 9.1 KiB |
|
After Width: | Height: | Size: 9.2 KiB |
|
After Width: | Height: | Size: 7.8 KiB |
|
After Width: | Height: | Size: 9.0 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 2.4 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 32 KiB |