ws-h264: merge ws/video; codecs/Video registers h264 (avc1/avc3/H264/... FourCCs, V_MPEG4/ISO/AVC) via H264.newVideoDecoder; video/h264 raw Annex B format (demux by access unit, copy-writer from MP4/MKV samples); MMCO 5 resets frame_num (JVT MR2/MR4/MR5); meta.yuv from the VUI
This commit is contained in:
commit
d4486dccce
211 files changed
+43039
-552
No files matched your search
@@ -0,0 +1,12 @@
|
||||
-- tests/audio/_encode_cases: the files our ALAC / CAF writers produce for the reference check (tools/fixtures/m4a.py
|
||||
-- runs tools/fixtures/_m4a_encode.luau over them; tests/audio/m4a.luau and caf.luau re-encode and compare).
|
||||
return {
|
||||
{ name = "ours_alac16_stereo", container = "m4a", rate = 44100, frames = 4096 * 3 + 1234, channels = 2, bits = 16, seed = 1, tags = { title = "Our Title \u{e9}", artist = "formats-luau", album = "Tests", track = "5", tracktotal = "10", date = "2026", genre = "Test", comment = "round trip" } },
|
||||
{ name = "ours_alac16_mono", container = "m4a", rate = 22050, frames = 5000, channels = 1, bits = 16, seed = 2 },
|
||||
{ name = "ours_alac24_stereo", container = "m4a", rate = 48000, frames = 9000, channels = 2, bits = 24, seed = 3 },
|
||||
{ name = "ours_alac16_6ch", container = "m4a", rate = 48000, frames = 4500, channels = 6, bits = 16, seed = 4 },
|
||||
{ name = "ours_alac20_stereo", container = "m4a", rate = 96000, frames = 3000, channels = 2, bits = 20, seed = 5 },
|
||||
{ name = "ours_caf_alac16", container = "caf", codec = "alac", rate = 44100, frames = 7000, channels = 2, bits = 16, seed = 6 },
|
||||
{ name = "ours_caf_pcm16", container = "caf", codec = "pcm", rate = 44100, frames = 3000, channels = 2, bits = 16, seed = 7 },
|
||||
{ name = "ours_caf_pcm24", container = "caf", codec = "pcm", rate = 48000, frames = 2000, channels = 1, bits = 24, seed = 8 },
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
-- tests/audio/_opus_cases: the inputs of the CELT encoder reference check (tools/fixtures/opus_celt.py runs
|
||||
-- tools/fixtures/_opus_encode.luau over them; tests/audio/opus_encode.luau re-encodes and compares): a deterministic
|
||||
-- music-like signal (chord + vibrato + chirp + clicks + a silent stretch) at a given rate / channel count.
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local Cases = {}
|
||||
|
||||
Cases.list = {
|
||||
{ name = "celt_mono_64k", rate = 48000, channels = 1, seconds = 1.5, bitrate = 64000, minSnr = 15 },
|
||||
{ name = "celt_stereo_128k", rate = 48000, channels = 2, seconds = 1.5, bitrate = 128000, minSnr = 15 },
|
||||
{ name = "celt_stereo_256k", rate = 48000, channels = 2, seconds = 1, bitrate = 256000, minSnr = 22 },
|
||||
{ name = "celt_mono_24k", rate = 48000, channels = 1, seconds = 1, bitrate = 24000, minSnr = 8 },
|
||||
{ name = "celt_44k_stereo_96k", rate = 44100, channels = 2, seconds = 1, bitrate = 96000, minSnr = 0, tags = { title = "Celt \u{e9}", artist = "formats-luau", album = "Opus" } },
|
||||
{ name = "celt_short", rate = 48000, channels = 1, seconds = 0.01, bitrate = 48000, minSnr = -100 },
|
||||
}
|
||||
|
||||
function Cases.signal(c: any): Types.Audio
|
||||
local n = math.floor(c.seconds * c.rate + 0.5)
|
||||
local a = Types.Audio.new(c.rate, c.channels, n)
|
||||
local s = 7
|
||||
for i = 0, n - 1 do
|
||||
local t = i / c.rate
|
||||
for ch = 0, c.channels - 1 do
|
||||
s = (s * 48271) % 2147483647
|
||||
local v = 0.18 * math.sin(2 * math.pi * 220 * t + 2 * math.sin(2 * math.pi * 5 * t))
|
||||
v += 0.12 * math.sin(2 * math.pi * (277.2 + ch * 2) * t) + 0.1 * math.sin(2 * math.pi * 329.6 * t)
|
||||
v += 0.08 * math.sin(2 * math.pi * (1000 + 3000 * t) * t)
|
||||
v += 0.01 * (s / 2147483647 - 0.5)
|
||||
if i % (c.rate // 4) < 30 then
|
||||
v += 0.4 * (if (i // 5) % 2 == 0 then 1 else -1)
|
||||
end
|
||||
if t > 0.6 and t < 0.75 then
|
||||
v = 0 -- digital silence (the encoder's silence frames)
|
||||
end
|
||||
buffer.writef32(a.samples, (i * c.channels + ch) * 4, v)
|
||||
end
|
||||
end
|
||||
a.tags = c.tags or {}
|
||||
return a
|
||||
end
|
||||
|
||||
return Cases
|
||||
@@ -0,0 +1,42 @@
|
||||
-- tests/audio/_signal: the deterministic integer test signal of tools/fixtures/_m4a_signal.py (the same numbers), as
|
||||
-- an interleaved integer array and as a Types.Audio (f32, exact for up to 24 bits). Used by the m4a / caf tests and the
|
||||
-- fixture-time encoder runs (tools/fixtures/_m4a_encode.luau).
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local Signal = {}
|
||||
|
||||
function Signal.ints(frames: number, channels: number, bits: number, seed: number): { number }
|
||||
local s = seed
|
||||
local peak = 2 ^ (bits - 1) - 1
|
||||
local out = table.create(frames * channels, 0)
|
||||
local k = 1
|
||||
for i = 0, frames - 1 do
|
||||
for c = 0, channels - 1 do
|
||||
s = (s * 48271) % 2147483647
|
||||
local p1 = 97 + 31 * c
|
||||
local tri = math.abs((i % p1) * 2 - p1) * 2 - p1
|
||||
local v = tri * (peak // (4 * p1))
|
||||
local p2 = 1500 + 200 * c
|
||||
v += if (i // p2) % 2 == 0 then peak // 6 else -(peak // 6)
|
||||
v += ((s // 65536) % 4096 - 2048) * (peak // 65536 + 1)
|
||||
if i % 7001 < 3 then
|
||||
v += peak // 2
|
||||
end
|
||||
out[k] = math.clamp(v, -peak - 1, peak)
|
||||
k += 1
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
function Signal.audio(rate: number, frames: number, channels: number, bits: number, seed: number): Types.Audio
|
||||
local ints = Signal.ints(frames, channels, bits, seed)
|
||||
local a = Types.Audio.new(rate, channels, frames)
|
||||
local scale = 1 / 2 ^ (bits - 1)
|
||||
for i, v in ints do
|
||||
buffer.writef32(a.samples, (i - 1) * 4, v * scale)
|
||||
end
|
||||
return a
|
||||
end
|
||||
|
||||
return Signal
|
||||
@@ -0,0 +1,117 @@
|
||||
-- audio/aac tests: ADTS streams from ffmpeg and fdkaac (stereo, mono 32 kHz) against ffmpeg's float decode (SNR,
|
||||
-- length); an HE-AAC ADTS stream plays its core; a leading ID3v2 tag (skipped, text frames as tags) and garbage before
|
||||
-- the first frame (resync); a truncated last frame; streaming + seek; sniff; errors; the fuzz no-throw pass.
|
||||
-- Fixtures: tools/fixtures/m4a.py.
|
||||
local T = require("@tests/T")
|
||||
local AacF = require("@formats/audio/aac")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Fx = require("@tests/gen/m4a_aac")
|
||||
local He = require("@tests/gen/m4a_he")
|
||||
|
||||
local t = T.suite("aac")
|
||||
|
||||
local function reader(s: string): Bytes.Reader
|
||||
return Bytes.reader(buffer.fromstring(s))
|
||||
end
|
||||
|
||||
local function snr(a: any, ref: string, skip: number?): number
|
||||
local off = (skip or 0) * a.channels
|
||||
local n = math.min(a.frames * a.channels - off, #ref // 4)
|
||||
local rb = buffer.fromstring(ref)
|
||||
local sig, err = 0, 0
|
||||
for i = 0, n - 1 do
|
||||
local r = buffer.readf32(rb, i * 4)
|
||||
local d = buffer.readf32(a.samples, (off + i) * 4) - r
|
||||
sig += r * r
|
||||
err += d * d
|
||||
end
|
||||
return if err == 0 then math.huge else 10 * math.log10(sig / err)
|
||||
end
|
||||
|
||||
t:eq(AacF.name, "aac", "name")
|
||||
t:check(AacF.caps.decode and not AacF.caps.encode and AacF.encode == nil, "caps: decode only")
|
||||
|
||||
local first
|
||||
for _, c in Fx do
|
||||
if c.container ~= "adts" then
|
||||
continue
|
||||
end
|
||||
first = first or c
|
||||
local r = reader(c.data)
|
||||
t:check(AacF.sniff(r) >= 0.9, c.name .. ": sniff")
|
||||
local a, err = AacF.decode(r)
|
||||
t:check(a, c.name .. ": " .. tostring(err))
|
||||
t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format")
|
||||
t:eq(a.frames, c.frames, c.name .. ": frames (ADTS keeps the priming)")
|
||||
local s = snr(a, c.ref)
|
||||
t:check(s > 90, string.format("%s: SNR %.1f dB", c.name, s))
|
||||
t:note("%s: %d ch %d Hz, %d frames, SNR %.1f dB vs ffmpeg", c.name, c.channels, c.rate, a.frames, s)
|
||||
end
|
||||
|
||||
-- HE-AAC ADTS: the core
|
||||
for _, c in He do
|
||||
if string.sub(c.name, -4) == ".aac" then
|
||||
local a, err = AacF.decode(reader(c.data))
|
||||
t:check(a and a.sampleRate == c.rate // 2 and a.frames > 0, c.name .. ": core decode: " .. tostring(err))
|
||||
end
|
||||
end
|
||||
|
||||
-- ID3v2 in front + garbage, truncated tail
|
||||
do
|
||||
local function frame(id: string, text: string): string
|
||||
local body = "\3" .. text
|
||||
local n = #body
|
||||
return id .. string.char(0, 0, n // 128, n % 128) .. "\0\0" .. body
|
||||
end
|
||||
local frames = frame("TIT2", "Adts Title") .. frame("TPE1", "Someone")
|
||||
local n = #frames
|
||||
local id3 = "ID3\4\0\0" .. string.char(0, 0, n // 128, n % 128) .. frames
|
||||
local data = id3 .. "\0\1\2garbage" .. first.data
|
||||
local a, err = AacF.decode(reader(data))
|
||||
t:check(a, "id3 + garbage: " .. tostring(err))
|
||||
t:check(a.tags.title == "Adts Title" and a.tags.artist == "Someone", "id3 tags")
|
||||
t:eq(a.frames, first.frames, "id3 + garbage: same frames")
|
||||
t:check(snr(a, first.ref) > 90, "id3 + garbage: same audio")
|
||||
local cut = AacF.decode(reader(string.sub(first.data, 1, #first.data - 5))) :: any
|
||||
t:check(cut and cut.frames == first.frames - 1024, "truncated last frame dropped")
|
||||
end
|
||||
|
||||
-- streaming + seek
|
||||
do
|
||||
local whole = AacF.decode(reader(first.data)) :: any
|
||||
local dec = AacF.open(reader(first.data)) :: any
|
||||
for _, at in { 0.3, 0.0, 0.5123 } do
|
||||
dec:seek(at)
|
||||
local b, n = dec:read(600)
|
||||
local f0 = math.floor(at * whole.sampleRate + 0.5)
|
||||
local maxd = 0
|
||||
for i = 0, n * whole.channels - 1 do
|
||||
maxd = math.max(maxd, math.abs(buffer.readf32(b, i * 4) - buffer.readf32(whole.samples, (f0 * whole.channels + i) * 4)))
|
||||
end
|
||||
-- (the stream has no PNS: noise substitution would draw different noise after a seek)
|
||||
t:check(n == 600 and maxd < 1e-6, string.format("seek %.3f s (max diff %g)", at, maxd))
|
||||
end
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
t:eq(AacF.sniff(reader("RIFF....WAVE")), 0, "sniff a WAV")
|
||||
local _, e = AacF.decode(reader(string.rep("\0", 100)))
|
||||
t:check(e and e.code == Err.CORRUPT, "no frames: " .. tostring(e))
|
||||
end
|
||||
|
||||
-- fuzz
|
||||
do
|
||||
local samples = {}
|
||||
for _, c in Fx do
|
||||
if c.container == "adts" then
|
||||
table.insert(samples, string.sub(c.data, 1, 6000))
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return AacF.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 30 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,183 @@
|
||||
-- audio/aiff tests: files written by ffmpeg and sox in every sample format (AIFF 8 / 12 / 16 / 24 / 32-bit, AIFF-C
|
||||
-- sowt / fl32 / fl64 / ulaw / alaw, 6 channels, text chunks) against ffmpeg's decode; streaming reads and seeks;
|
||||
-- our encoder's output for every sample format decoded by ffmpeg (fixture step) and by us; errors; fuzz.
|
||||
-- Fixtures: tools/fixtures/aiff.py.
|
||||
local T = require("@tests/T")
|
||||
local Aiff = require("@formats/audio/aiff")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Cases = require("@tests/gen/aiff_cases")
|
||||
local Enc = require("@tests/gen/aiff_enc")
|
||||
local Sig = require("@tests/gen/aiff_sig")
|
||||
|
||||
local t = T.suite("aiff")
|
||||
|
||||
local function reader(s: string): Bytes.Reader
|
||||
return Bytes.reader(buffer.fromstring(s))
|
||||
end
|
||||
-- max |a - b| over n f32 samples (a at byte ao, b at byte bo)
|
||||
local function maxDiff(a: buffer, ao: number, b: buffer, bo: number, n: number): number
|
||||
local m = 0
|
||||
for i = 0, n - 1 do
|
||||
local d = math.abs(buffer.readf32(a, ao + i * 4) - buffer.readf32(b, bo + i * 4))
|
||||
if d > m then
|
||||
m = d
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
-- the contract
|
||||
t:eq(Aiff.name, "aiff", "name")
|
||||
t:eq(Aiff.category, "audio", "category")
|
||||
t:check(Aiff.caps.decode and Aiff.caps.encode and table.find(Aiff.extensions, "aif") ~= nil, "caps / extensions")
|
||||
|
||||
-- reference files: decode, stream, seek
|
||||
for _, c in Cases do
|
||||
local a, err = Aiff.decode(reader(c.data))
|
||||
t:check(a, c.name .. ": " .. tostring(err))
|
||||
t:check(a.kind == "audio" and a.sampleRate == c.rate and a.channels == c.channels, c.name .. ": format")
|
||||
t:eq(a.frames, c.frames, c.name .. ": frames")
|
||||
local ref = buffer.fromstring(c.ref)
|
||||
local n = c.frames * c.channels
|
||||
t:check(maxDiff(a.samples, 0, ref, 0, n) < 1e-6, c.name .. ": samples match ffmpeg")
|
||||
-- streaming in odd chunks
|
||||
local dec = Aiff.open(reader(c.data)) :: Types.Decoder
|
||||
local got, out = 0, buffer.create(0)
|
||||
local ok = true
|
||||
while true do
|
||||
local b, k = dec:read(777, out)
|
||||
if k == 0 then
|
||||
break
|
||||
end
|
||||
out = b
|
||||
ok = ok and maxDiff(b, 0, ref, got * c.channels * 4, k * c.channels) < 1e-6
|
||||
got += k
|
||||
end
|
||||
t:check(ok and got == c.frames, c.name .. ": streamed reads")
|
||||
dec:seek(1000 / c.rate)
|
||||
t:check(math.abs(dec:position() - 1000 / c.rate) < 1e-9, c.name .. ": position")
|
||||
local b, k = dec:read(50)
|
||||
t:check(k == 50 and maxDiff(b, 0, ref, 1000 * c.channels * 4, 50 * c.channels) < 1e-6, c.name .. ": seek")
|
||||
end
|
||||
t:note("%d reference files match ffmpeg", #Cases)
|
||||
|
||||
-- details of particular files
|
||||
local function case(name: string): any
|
||||
for _, c in Cases do
|
||||
if c.name == name then
|
||||
return c
|
||||
end
|
||||
end
|
||||
error("no case " .. name)
|
||||
end
|
||||
do
|
||||
local a = Aiff.decode(reader(case("ffmpeg-tags").data)) :: Types.Audio
|
||||
t:eq(a.tags.title, "Song Name", "NAME chunk")
|
||||
t:eq(a.tags.artist, "Some One", "AUTH chunk")
|
||||
local fl = Aiff.decode(reader(case("ffmpeg-fl32").data)) :: Types.Audio
|
||||
t:check(fl.meta.source.aifc and fl.meta.source.compression == "fl32", "fl32 meta")
|
||||
-- a 12-bit sample size: samples sit left-justified in 16-bit containers
|
||||
local s16 = case("sox-aiff-s16")
|
||||
local q = string.find(s16.data, "COMM", 1, true) :: number
|
||||
local d12 = string.sub(s16.data, 1, q + 13) .. "\0\12" .. string.sub(s16.data, q + 16)
|
||||
local s12 = Aiff.decode(reader(d12)) :: Types.Audio
|
||||
t:check(s12.meta.source.bitDepth == 12 and maxDiff(s12.samples, 0, buffer.fromstring(s16.ref), 0, s16.frames * 2) < 1e-6, "12-bit sample size")
|
||||
local sw = Aiff.info(reader(case("ffmpeg-sowt").data))
|
||||
t:check(sw and sw.compression == "sowt" and sw.format == "s16le", "info: sowt")
|
||||
-- inside a bigger buffer
|
||||
local c = case("ffmpeg-s16be")
|
||||
local big = buffer.create(#c.data + 9)
|
||||
buffer.writestring(big, 5, c.data)
|
||||
local a2 = Aiff.decode(Bytes.reader(big, 5, #c.data)) :: Types.Audio
|
||||
t:check(a2 and maxDiff(a2.samples, 0, buffer.fromstring(c.ref), 0, c.frames * c.channels) < 1e-6, "decode from a sub-range")
|
||||
-- truncated sample data: the frames present
|
||||
local cut = string.sub(c.data, 1, #c.data - 1001)
|
||||
local a3 = Aiff.decode(reader(cut)) :: Types.Audio
|
||||
t:check(a3 and a3.frames < c.frames and a3.frames > 0 and a3.meta.source.truncated, "truncated SSND")
|
||||
end
|
||||
|
||||
-- our encoder: ffmpeg decodes every sample format (fixture step), within the format's step; streamed == from Audio
|
||||
local TOL = { s8 = 0.5 / 128, ["s16-mono"] = 0.5 / 32768, s16 = 0.5 / 32768, sowt16 = 0.5 / 32768, ["aifc-s16"] = 0.5 / 32768, s24 = 0.5 / 8388608, sowt24 = 0.5 / 8388608, s32 = 1e-7, f32 = 0, f64 = 0, ulaw = 0.04, alaw = 0.04 }
|
||||
local sig = buffer.fromstring(Sig.data)
|
||||
for _, e in Enc do
|
||||
t:eq(e.ffmpegErrors, "", e.name .. ": ffmpeg reads our file without errors")
|
||||
t:check(e.frames == Sig.frames and e.rate == Sig.rate, e.name .. ": ffmpeg frames / rate")
|
||||
t:check(e.maxDiff <= TOL[e.name] + 1e-7, string.format("%s: ffmpeg decode within %g (max diff %g)", e.name, TOL[e.name], e.maxDiff))
|
||||
t:check(e.sameStreamed, e.name .. ": encoding a Decoder gives the same bytes")
|
||||
local back = Aiff.decode(reader(e.data)) :: Types.Audio
|
||||
t:check(back and back.frames == Sig.frames and back.channels == e.channels, e.name .. ": our decoder reads our file")
|
||||
if e.channels == 2 then
|
||||
t:check(maxDiff(back.samples, 0, sig, 0, Sig.frames * 2) <= TOL[e.name] + 1e-7, e.name .. ": round trip")
|
||||
end
|
||||
end
|
||||
t:note("%d encoder outputs read back by ffmpeg and by us", #Enc)
|
||||
|
||||
-- encoder: tags, odd sizes, errors
|
||||
do
|
||||
local a = Types.Audio.new(44100, 1, 3)
|
||||
buffer.writef32(a.samples, 0, 0.5)
|
||||
buffer.writef32(a.samples, 4, -1)
|
||||
buffer.writef32(a.samples, 8, 2) -- clips
|
||||
a.tags = { title = "odd", artist = "me", comment = "x" }
|
||||
local b = Aiff.encode(a, { sampleFormat = "s8" }) :: buffer
|
||||
local back = Aiff.decode(Bytes.reader(b)) :: Types.Audio
|
||||
t:check(back.frames == 3 and back.tags.title == "odd" and back.tags.artist == "me" and back.tags.comment == "x", "odd length + tags")
|
||||
t:check(buffer.readf32(back.samples, 0) == 0.5 and buffer.readf32(back.samples, 4) == -1 and buffer.readf32(back.samples, 8) == 127 / 128, "s8 values, clipping")
|
||||
t:eq(buffer.len(b) % 2, 0, "chunks padded to even sizes")
|
||||
t:check(Aiff.info(Bytes.reader(b)).sampleRate == 44100, "80-bit rate round trip")
|
||||
local empty = Aiff.encode(Types.Audio.new(8000, 2, 0)) :: buffer
|
||||
local e0 = Aiff.decode(Bytes.reader(empty))
|
||||
t:check(e0 and e0.frames == 0, "empty audio")
|
||||
local _, e1 = Aiff.encode({} :: any)
|
||||
t:check(e1 and e1.code == Err.ARG, "encode junk: ARG")
|
||||
local _, e2 = Aiff.encode(a, { sampleFormat = "s12" } :: any)
|
||||
t:check(e2 and e2.code == Err.ARG, "bad sampleFormat: ARG")
|
||||
local _, e3 = Aiff.encode(a, { sampleFormat = "f32", littleEndian = true })
|
||||
t:check(e3 and e3.code == Err.ARG, "littleEndian float: ARG")
|
||||
local _, e5 = Aiff.encode(a, { sampleFormat = "s24", littleEndian = true })
|
||||
t:check(e5 and e5.code == Err.ARG, "littleEndian 24-bit: ARG")
|
||||
t:eq(Aiff.sniff(Bytes.reader(b)), 1, "sniff")
|
||||
t:eq(Aiff.sniff(reader("RIFF....WAVE")), 0, "sniff wav")
|
||||
t:eq(Aiff.sniff(reader("")), 0, "sniff nothing")
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local _, e = Aiff.decode(reader("FORM\0\0\0\4WAVE"))
|
||||
t:check(e and e.code == Err.CORRUPT, "wrong FORM type: " .. tostring(e))
|
||||
local c = case("ffmpeg-fl32").data
|
||||
local p = string.find(c, "fl32", 1, true) :: number
|
||||
local ima = string.sub(c, 1, p - 1) .. "ima4" .. string.sub(c, p + 4)
|
||||
local _, e2 = Aiff.decode(reader(ima))
|
||||
t:check(e2 and e2.code == Err.UNSUPPORTED, "ima4: UNSUPPORTED: " .. tostring(e2))
|
||||
local _, e3 = Aiff.decode(reader(string.sub(c, 1, 30)))
|
||||
t:check(e3 and (e3.code == Err.TRUNCATED or e3.code == Err.CORRUPT), "cut in COMM: " .. tostring(e3))
|
||||
local _, e4 = Aiff.decode(reader(case("ffmpeg-s16be").data), { maxFrames = 10 })
|
||||
t:check(e4 and e4.code == Err.LIMIT, "maxFrames: LIMIT")
|
||||
end
|
||||
|
||||
-- fuzz
|
||||
do
|
||||
local samples = {}
|
||||
for i, c in Cases do
|
||||
if i % 3 == 1 then
|
||||
table.insert(samples, string.sub(c.data, 1, 600))
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Aiff.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 30, keepHeader = 0 })
|
||||
t:fuzz("open + read", function(b: buffer)
|
||||
local d = Aiff.open(Bytes.reader(b))
|
||||
if d then
|
||||
d:read(100)
|
||||
d:seek(0.001)
|
||||
d:read(100)
|
||||
end
|
||||
return d
|
||||
end, samples, { mutations = 10, garbage = 50 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,147 @@
|
||||
-- audio/au tests: files written by ffmpeg and sox in every encoding (8 / 16 / 24 / 32-bit, float, double, mu-law,
|
||||
-- A-law, an annotation) against ffmpeg's decode; streaming reads and seeks; our encoder's output for every encoding
|
||||
-- decoded by ffmpeg (fixture step) and by us; an unknown data size; errors; fuzz. Fixtures: tools/fixtures/au.py.
|
||||
local T = require("@tests/T")
|
||||
local Au = require("@formats/audio/au")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Cases = require("@tests/gen/au_cases")
|
||||
local Enc = require("@tests/gen/au_enc")
|
||||
local Sig = require("@tests/gen/au_sig")
|
||||
|
||||
local t = T.suite("au")
|
||||
|
||||
local function reader(s: string): Bytes.Reader
|
||||
return Bytes.reader(buffer.fromstring(s))
|
||||
end
|
||||
local function maxDiff(a: buffer, ao: number, b: buffer, bo: number, n: number): number
|
||||
local m = 0
|
||||
for i = 0, n - 1 do
|
||||
local d = math.abs(buffer.readf32(a, ao + i * 4) - buffer.readf32(b, bo + i * 4))
|
||||
if d > m then
|
||||
m = d
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
local function case(name: string): any
|
||||
for _, c in Cases do
|
||||
if c.name == name then
|
||||
return c
|
||||
end
|
||||
end
|
||||
error("no case " .. name)
|
||||
end
|
||||
|
||||
t:eq(Au.name, "au", "name")
|
||||
t:eq(Au.category, "audio", "category")
|
||||
t:check(Au.caps.decode and Au.caps.encode and table.find(Au.extensions, "snd") ~= nil, "caps / extensions")
|
||||
|
||||
for _, c in Cases do
|
||||
local a, err = Au.decode(reader(c.data))
|
||||
t:check(a, c.name .. ": " .. tostring(err))
|
||||
t:check(a.sampleRate == c.rate and a.channels == c.channels, c.name .. ": format")
|
||||
t:eq(a.frames, c.frames, c.name .. ": frames")
|
||||
local ref = buffer.fromstring(c.ref)
|
||||
t:check(maxDiff(a.samples, 0, ref, 0, c.frames * c.channels) < 1e-6, c.name .. ": samples match ffmpeg")
|
||||
local dec = Au.open(reader(c.data)) :: Types.Decoder
|
||||
local got, ok = 0, true
|
||||
while true do
|
||||
local b, k = dec:read(1000)
|
||||
if k == 0 then
|
||||
break
|
||||
end
|
||||
ok = ok and maxDiff(b, 0, ref, got * c.channels * 4, k * c.channels) < 1e-6
|
||||
got += k
|
||||
end
|
||||
t:check(ok and got == c.frames, c.name .. ": streamed reads")
|
||||
dec:seek(700 / c.rate)
|
||||
local b, k = dec:read(40)
|
||||
t:check(k == 40 and maxDiff(b, 0, ref, 700 * c.channels * 4, 40 * c.channels) < 1e-6, c.name .. ": seek")
|
||||
end
|
||||
t:note("%d reference files match ffmpeg", #Cases)
|
||||
|
||||
do
|
||||
local a = Au.decode(reader(case("sox-comment").data)) :: Types.Audio
|
||||
t:check(a.tags.comment ~= nil and string.find(a.tags.comment, "hello sun", 1, true) ~= nil, "annotation as comment")
|
||||
-- an unknown data size (0xFFFFFFFF) runs to the end of the file
|
||||
local c = case("ffmpeg-s16be")
|
||||
local unk = string.sub(c.data, 1, 8) .. "\255\255\255\255" .. string.sub(c.data, 13)
|
||||
local a2 = Au.decode(reader(unk)) :: Types.Audio
|
||||
t:check(a2 and a2.frames == c.frames, "unknown data size")
|
||||
local cut = Au.decode(reader(string.sub(c.data, 1, #c.data - 400))) :: Types.Audio
|
||||
t:check(cut and cut.frames == c.frames - 100 and cut.meta.source.truncated, "truncated data")
|
||||
local big = buffer.create(#c.data + 3)
|
||||
buffer.writestring(big, 3, c.data)
|
||||
local a3 = Au.decode(Bytes.reader(big, 3, #c.data)) :: Types.Audio
|
||||
t:check(a3 and maxDiff(a3.samples, 0, buffer.fromstring(c.ref), 0, c.frames * 2) < 1e-6, "decode from a sub-range")
|
||||
end
|
||||
|
||||
local TOL = { s8 = 0.5 / 128, ["s16-mono"] = 0.5 / 32768, s16 = 0.5 / 32768, s24 = 0.5 / 8388608, s32 = 1e-7, f32 = 0, f64 = 0, ulaw = 0.04, alaw = 0.04 }
|
||||
local sig = buffer.fromstring(Sig.data)
|
||||
for _, e in Enc do
|
||||
t:eq(e.ffmpegErrors, "", e.name .. ": ffmpeg reads our file without errors")
|
||||
t:check(e.frames == Sig.frames and e.rate == Sig.rate, e.name .. ": ffmpeg frames / rate")
|
||||
t:check(e.maxDiff <= TOL[e.name] + 1e-7, string.format("%s: ffmpeg decode within %g (max diff %g)", e.name, TOL[e.name], e.maxDiff))
|
||||
t:check(e.sameStreamed, e.name .. ": encoding a Decoder gives the same bytes")
|
||||
local back = Au.decode(reader(e.data)) :: Types.Audio
|
||||
t:check(back and back.frames == Sig.frames and back.channels == e.channels, e.name .. ": our decoder reads our file")
|
||||
if e.channels == 2 then
|
||||
t:check(maxDiff(back.samples, 0, sig, 0, Sig.frames * 2) <= TOL[e.name] + 1e-7, e.name .. ": round trip")
|
||||
end
|
||||
end
|
||||
t:note("%d encoder outputs read back by ffmpeg and by us", #Enc)
|
||||
|
||||
do
|
||||
local a = Types.Audio.new(8000, 1, 2)
|
||||
buffer.writef32(a.samples, 0, 0.25)
|
||||
buffer.writef32(a.samples, 4, -0.25)
|
||||
a.tags = { comment = "annotated!" }
|
||||
local b = Au.encode(a) :: buffer
|
||||
t:eq(bit32.byteswap(buffer.readu32(b, 4)) % 8, 0, "data offset is a multiple of 8")
|
||||
local back = Au.decode(Bytes.reader(b)) :: Types.Audio
|
||||
t:check(back.frames == 2 and back.tags.comment == "annotated!" and buffer.readf32(back.samples, 0) == 0.25, "comment + samples")
|
||||
local _, e1 = Au.encode(42 :: any)
|
||||
t:check(e1 and e1.code == Err.ARG, "encode junk: ARG")
|
||||
local _, e2 = Au.encode(a, { sampleFormat = "u8" } :: any)
|
||||
t:check(e2 and e2.code == Err.ARG, "bad sampleFormat: ARG")
|
||||
local frac = Types.Audio.new(8000.5, 1, 1)
|
||||
local _, e3 = Au.encode(frac)
|
||||
t:check(e3 and e3.code == Err.ARG, "fractional rate: ARG")
|
||||
t:eq(Au.sniff(Bytes.reader(b)), 1, "sniff")
|
||||
t:eq(Au.sniff(reader("FORM")), 0, "sniff other")
|
||||
-- G.721 ADPCM (encoding 23): unsupported
|
||||
local adpcm = string.sub(buffer.tostring(b), 1, 12) .. "\0\0\0\23" .. string.sub(buffer.tostring(b), 17)
|
||||
local _, e4 = Au.decode(reader(adpcm))
|
||||
t:check(e4 and e4.code == Err.UNSUPPORTED, "encoding 23: UNSUPPORTED")
|
||||
local _, e5 = Au.decode(reader(".snd\0\0\0\24"))
|
||||
t:check(e5 and e5.code == Err.CORRUPT, "short header: CORRUPT")
|
||||
local _, e6 = Au.decode(reader(case("ffmpeg-s16be").data), { maxFrames = 5 })
|
||||
t:check(e6 and e6.code == Err.LIMIT, "maxFrames: LIMIT")
|
||||
end
|
||||
|
||||
do
|
||||
local samples = {}
|
||||
for i, c in Cases do
|
||||
if i % 2 == 1 then
|
||||
table.insert(samples, string.sub(c.data, 1, 400))
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Au.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 30 })
|
||||
t:fuzz("open + read", function(b: buffer)
|
||||
local d = Au.open(Bytes.reader(b))
|
||||
if d then
|
||||
d:read(64)
|
||||
d:seek(1e9)
|
||||
d:read(64)
|
||||
d:seek(-1)
|
||||
d:read(64)
|
||||
end
|
||||
return d
|
||||
end, samples, { mutations = 10, garbage = 50 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,177 @@
|
||||
-- audio/caf tests: ALAC CAF from ffmpeg bit-exact; AAC CAF (ffmpeg's ADTS frames wrapped by the fixture) against
|
||||
-- ffmpeg's float decode; our CAF writer (PCM 16 / 24-bit, ALAC; re-encoded here and compared with the bytes ffmpeg
|
||||
-- decoded bit-exactly); PCM layouts (little / big endian, float) through our writer + a hand-built header; info tags;
|
||||
-- seek; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/m4a.py.
|
||||
local T = require("@tests/T")
|
||||
local Caf = require("@formats/audio/caf")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Signal = require("@tests/audio/_signal")
|
||||
local Cases = require("@tests/audio/_encode_cases")
|
||||
local Alac = require("@tests/gen/m4a_alac")
|
||||
local Aac = require("@tests/gen/m4a_aac")
|
||||
local Ours = require("@tests/gen/m4a_ours")
|
||||
|
||||
local t = T.suite("caf")
|
||||
|
||||
local function reader(s: string | buffer): Bytes.Reader
|
||||
return Bytes.reader(if type(s) == "string" then buffer.fromstring(s) else s)
|
||||
end
|
||||
|
||||
local function intCrc(a: any, bits: number): number
|
||||
local n = a.frames * a.channels
|
||||
local b = buffer.create(n * 4)
|
||||
local scale = 2 ^ (bits - 1)
|
||||
for i = 0, n - 1 do
|
||||
buffer.writei32(b, i * 4, math.floor(buffer.readf32(a.samples, i * 4) * scale + 0.5))
|
||||
end
|
||||
return Crc32.of(b)
|
||||
end
|
||||
|
||||
t:eq(Caf.name, "caf", "name")
|
||||
t:check(Caf.caps.decode and Caf.caps.encode, "caps")
|
||||
|
||||
for _, c in Alac do
|
||||
if c.container == "caf" then
|
||||
local r = reader(c.data)
|
||||
t:eq(Caf.sniff(r), 1, c.name .. ": sniff")
|
||||
local a, err = Caf.decode(r)
|
||||
t:check(a, c.name .. ": " .. tostring(err))
|
||||
t:check(a.channels == c.channels and a.sampleRate == c.rate and a.frames == c.frames, c.name .. ": format / length (pakt)")
|
||||
t:eq(intCrc(a, c.bits), c.crc, c.name .. ": bit-exact")
|
||||
end
|
||||
end
|
||||
|
||||
for _, c in Aac do
|
||||
if c.container == "caf" then
|
||||
local a, err = Caf.decode(reader(c.data))
|
||||
t:check(a, c.name .. ": " .. tostring(err))
|
||||
t:eq(a.frames, c.frames, c.name .. ": frames")
|
||||
local rb = buffer.fromstring(c.ref)
|
||||
local sig, e = 0, 0
|
||||
for i = 0, a.frames * a.channels - 1 do
|
||||
local r = buffer.readf32(rb, i * 4)
|
||||
sig += r * r
|
||||
e += (buffer.readf32(a.samples, i * 4) - r) ^ 2
|
||||
end
|
||||
local snr = if e == 0 then math.huge else 10 * math.log10(sig / e)
|
||||
t:check(snr > 90, string.format("%s: SNR %.1f dB", c.name, snr))
|
||||
t:note("%s: SNR %.1f dB vs ffmpeg", c.name, snr)
|
||||
end
|
||||
end
|
||||
|
||||
-- our writer: the bytes ffmpeg validated
|
||||
do
|
||||
local byName = {}
|
||||
for _, o in Ours do
|
||||
byName[o.name] = o
|
||||
end
|
||||
for _, c in Cases do
|
||||
if c.container ~= "caf" then
|
||||
continue
|
||||
end
|
||||
local o = byName[c.name]
|
||||
t:check(o and o.ffmpeg, c.name .. ": ffmpeg decoded it bit-exactly")
|
||||
local a = Signal.audio(c.rate, c.frames, c.channels, c.bits, c.seed)
|
||||
local file = Caf.encode(a, { codec = c.codec, bitDepth = c.bits }) :: buffer
|
||||
t:eq(string.format("%08x", Crc32.of(file)), string.format("%08x", o.crc), c.name .. ": the validated bytes")
|
||||
local back = Caf.decode(reader(file)) :: any
|
||||
t:check(back and back.frames == c.frames, c.name .. ": our length")
|
||||
local ints = Signal.ints(c.frames, c.channels, c.bits, c.seed)
|
||||
local ok = true
|
||||
local scale = 2 ^ (c.bits - 1)
|
||||
for i = 1, #ints do
|
||||
ok = ok and math.floor(buffer.readf32(back.samples, (i - 1) * 4) * scale + 0.5) == ints[i]
|
||||
end
|
||||
t:check(ok, c.name .. ": round trip")
|
||||
end
|
||||
end
|
||||
|
||||
-- float PCM, tags, a decoder as the source, a hand-built little-endian header
|
||||
do
|
||||
local a = Signal.audio(32000, 3000, 3, 16, 12)
|
||||
a.tags = { title = "Caf Title", artist = "A", date = "1999", comment = "c", custom = "x" }
|
||||
local file = Caf.encode(a, { codec = "pcm", bitDepth = 32 }) :: buffer
|
||||
local back = Caf.decode(reader(file)) :: any
|
||||
t:check(back.frames == 3000 and buffer.tostring(back.samples) == buffer.tostring(a.samples), "float PCM round trip")
|
||||
for k, v in a.tags do
|
||||
t:eq(back.tags[k], v, "tag " .. k)
|
||||
end
|
||||
local dec = Caf.open(reader(file)) :: any
|
||||
local again = Caf.encode(dec, { codec = "alac" }) :: buffer
|
||||
local b2 = Caf.decode(reader(again)) :: any
|
||||
t:check(b2.frames == 3000 and buffer.tostring(b2.samples) == buffer.tostring(a.samples), "ALAC from a streaming decoder")
|
||||
-- little-endian 24-bit integer PCM, data chunk of unknown size (-1)
|
||||
local w = Bytes.writer(64)
|
||||
w:string("caff")
|
||||
w:u16be(1)
|
||||
w:u16be(0)
|
||||
w:string("desc")
|
||||
w:u64be(32)
|
||||
w:f64be(8000)
|
||||
w:string("lpcm")
|
||||
w:u32be(2)
|
||||
w:u32be(3)
|
||||
w:u32be(1)
|
||||
w:u32be(1)
|
||||
w:u32be(24)
|
||||
w:string("data")
|
||||
w:u32be(0xFFFFFFFF)
|
||||
w:u32be(0xFFFFFFFF)
|
||||
w:u32be(0)
|
||||
for _, v in { 0, 4194304, -4194304, 8388607, -8388608 } do
|
||||
w:u24le(v % 16777216)
|
||||
end
|
||||
local le = Caf.decode(Bytes.reader(w:finish())) :: any
|
||||
t:check(le and le.frames == 5, "24-bit LE, data size -1")
|
||||
t:check(le and math.abs(buffer.readf32(le.samples, 4) - 0.5) < 1e-7 and math.abs(buffer.readf32(le.samples, 16) + 1) < 1e-7, "24-bit LE values")
|
||||
end
|
||||
|
||||
-- seek
|
||||
do
|
||||
local c = Alac[#Alac]
|
||||
local whole = Caf.decode(reader(c.data)) :: any
|
||||
local dec = Caf.open(reader(c.data)) :: any
|
||||
for _, at in { 0.1, 0.0, 0.15 } do
|
||||
dec:seek(at)
|
||||
local b, n = dec:read(400)
|
||||
local f0 = math.floor(at * whole.sampleRate + 0.5)
|
||||
local same = n == 400
|
||||
for i = 0, n * whole.channels - 1 do
|
||||
same = same and buffer.readf32(b, i * 4) == buffer.readf32(whole.samples, (f0 * whole.channels + i) * 4)
|
||||
end
|
||||
t:check(same, string.format("seek %.2f s", at))
|
||||
end
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
t:eq(Caf.sniff(reader("caff\0\2\0\0")), 0, "sniff: wrong version")
|
||||
local _, e = Caf.decode(reader("caff\0\1\0\0"))
|
||||
t:check(e and e.code == Err.CORRUPT, "no desc: " .. tostring(e))
|
||||
local _, e2 = Caf.encode(Signal.audio(8000, 10, 1, 16, 1), { codec = "mp3" } :: any)
|
||||
t:check(e2 and e2.code == Err.ARG, "bad codec: " .. tostring(e2))
|
||||
end
|
||||
|
||||
-- fuzz
|
||||
do
|
||||
local samples = {}
|
||||
for _, c in Alac do
|
||||
if c.container == "caf" then
|
||||
table.insert(samples, string.sub(c.data, 1, 9000))
|
||||
end
|
||||
end
|
||||
for _, c in Aac do
|
||||
if c.container == "caf" then
|
||||
table.insert(samples, string.sub(c.data, 1, 6000))
|
||||
end
|
||||
end
|
||||
local pcm = Caf.encode(Signal.audio(8000, 300, 2, 16, 3), { codec = "pcm" }) :: buffer
|
||||
table.insert(samples, buffer.tostring(pcm))
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Caf.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 30 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -22,7 +22,7 @@ for _, c in Cases do
|
||||
end
|
||||
|
||||
t:eq(Flac.name, "flac", "name")
|
||||
t:check(Flac.caps.decode and not Flac.caps.encode, "caps")
|
||||
t:check(Flac.caps.decode and Flac.caps.encode, "caps") -- encode: ws-audio (tests/audio/flac_encode.luau)
|
||||
|
||||
local seekChecks = 0
|
||||
for _, fx in Cases do
|
||||
@@ -156,8 +156,8 @@ do
|
||||
t:check(a and a.frames == fx.frames, "F.audio.load")
|
||||
local d = F.audio.open(byName.s16_l3.data)
|
||||
t:check(d and d.frames == byName.s16_l3.frames, "F.audio.open")
|
||||
local _, se = F.save(a, nil, { format = "flac" })
|
||||
t:check(se and se.code == Err.UNSUPPORTED, "F.save flac is read-only here: " .. tostring(se))
|
||||
local saved, se = F.save(a, nil, { format = "flac" }) -- the encoder (ws-audio)
|
||||
t:check(saved and F.audio.load(saved).frames == fx.frames, "F.save flac: " .. tostring(se))
|
||||
end
|
||||
|
||||
-- a damaged frame is dropped, the rest decodes
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
-- audio/flac encoder tests: every fixture-step encode (levels 0-8, 1 / 2 / 6 channels, 8 / 12 / 16 / 20 / 24 bits,
|
||||
-- odd lengths and block sizes, odd rates, seek tables, padding) passed `flac -t` and carries the MD5 of the quantized
|
||||
-- input; sizes within 10% of libFLAC at the same level; each decodes bit-exactly through our own decoder; streaming
|
||||
-- from a Decoder gives the same bytes; tags; option errors. Fixtures: tools/fixtures/flac_enc.py.
|
||||
local T = require("@tests/T")
|
||||
local Flac = require("@formats/audio/flac")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/Pcm")
|
||||
local Enc = require("@tests/gen/flac_enc")
|
||||
local Sigs = require("@tests/gen/flac_enc_sigs")
|
||||
|
||||
local t = T.suite("flac_encode")
|
||||
|
||||
local sigCache: { [string]: any } = {}
|
||||
local function sig(name: string): Types.Audio
|
||||
local s = sigCache[name]
|
||||
if not s then
|
||||
local m = Sigs[name]
|
||||
s = Types.Audio.new(m.rate, m.channels, m.frames)
|
||||
buffer.writestring(s.samples, 0, m.data)
|
||||
sigCache[name] = s
|
||||
end
|
||||
return s
|
||||
end
|
||||
|
||||
t:check(Flac.caps.encode and Flac.encode ~= nil, "caps.encode")
|
||||
|
||||
local worst = 0
|
||||
for _, e in Enc do
|
||||
t:eq(e.flacTest, "", e.name .. ": flac -t")
|
||||
t:eq(e.md5, e.wantMd5, e.name .. ": STREAMINFO MD5 = MD5 of the quantized input")
|
||||
if e.refSize then
|
||||
local ratio = e.size / e.refSize
|
||||
worst = math.max(worst, ratio)
|
||||
t:check(ratio < 1.1, string.format("%s: %d bytes, libFLAC %d (%.3f)", e.name, e.size, e.refSize, ratio))
|
||||
end
|
||||
-- our decoder: bit-exact against the input quantized to e.bits
|
||||
local a = sig(e.sig)
|
||||
local back, err = Flac.decode(Bytes.reader(buffer.fromstring(e.data)))
|
||||
t:check(back, e.name .. ": our decoder: " .. tostring(err))
|
||||
t:check(back.frames == a.frames and back.channels == a.channels and back.sampleRate == a.sampleRate, e.name .. ": format")
|
||||
local s = 2 ^ (e.bits - 1)
|
||||
local exact = true
|
||||
for i = 0, a.frames * a.channels - 1 do
|
||||
local want = math.clamp(math.floor(buffer.readf32(a.samples, i * 4) * s + 0.5), -s, s - 1)
|
||||
if math.floor(buffer.readf32(back.samples, i * 4) * s + 0.5) ~= want then
|
||||
exact = false
|
||||
break
|
||||
end
|
||||
end
|
||||
t:check(exact, e.name .. ": bit-exact round trip")
|
||||
t:eq(back.meta.source.bitDepth, e.bits, e.name .. ": bits per sample")
|
||||
end
|
||||
t:note("%d encodes pass flac -t with the right MD5 and decode bit-exactly; worst size vs libFLAC %.3f", #Enc, worst)
|
||||
|
||||
-- streaming: a Decoder source gives the same bytes as the Audio
|
||||
do
|
||||
local a = sig("flacsig_music_2_7000_44100")
|
||||
local f1 = Flac.encode(a, { level = 5 }) :: buffer
|
||||
local f2 = Flac.encode(Pcm.audioDecoder(a), { level = 5 }) :: buffer
|
||||
t:check(buffer.tostring(f1) == buffer.tostring(f2), "Decoder source = Audio source")
|
||||
-- a decoder of our own output re-encodes to the same stream (its bit depth carries over)
|
||||
local dec = Flac.open(Bytes.reader(f1)) :: any
|
||||
local f3 = Flac.encode(dec, { level = 5 }) :: buffer
|
||||
t:check(buffer.tostring(f3) == buffer.tostring(f1), "FLAC -> FLAC through the streaming decoder")
|
||||
end
|
||||
|
||||
-- tags, bit depth from the source
|
||||
do
|
||||
local a = Types.Audio.new(48000, 1, 3000)
|
||||
for i = 0, 2999 do
|
||||
buffer.writef32(a.samples, i * 4, math.floor(math.sin(i / 7) * 100) / 128)
|
||||
end
|
||||
a.tags = { title = "Tïtle", artist = "Artist", track = "3" }
|
||||
a.meta.source = { format = "wav", bitDepth = 8 }
|
||||
local f = Flac.encode(a) :: buffer
|
||||
local back = Flac.decode(Bytes.reader(f)) :: Types.Audio
|
||||
t:eq(back.meta.source.bitDepth, 8, "bit depth from meta.source")
|
||||
-- (the absorbed FLAC decoder keeps Vorbis comment keys upper case)
|
||||
local tags = back.tags :: any
|
||||
t:eq(tags.title or tags.TITLE, "Tïtle", "title")
|
||||
t:eq(tags.artist or tags.ARTIST, "Artist", "artist")
|
||||
t:eq(tags.track or tags.TRACKNUMBER, "3", "track number")
|
||||
local empty = Flac.encode(Types.Audio.new(44100, 2, 0)) :: buffer
|
||||
local e0 = Flac.decode(Bytes.reader(empty))
|
||||
t:check(e0 and e0.frames == 0, "empty audio")
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local a = Types.Audio.new(44100, 2, 10)
|
||||
local function code(v: any, o: any): string?
|
||||
local _, e = Flac.encode(v, o)
|
||||
return e and e.code
|
||||
end
|
||||
t:eq(code({}, nil), Err.ARG, "junk value")
|
||||
t:eq(code(a, { level = 9 }), Err.ARG, "level 9")
|
||||
t:eq(code(a, { level = 2.5 }), Err.ARG, "level 2.5")
|
||||
t:eq(code(a, { bits = 32 }), Err.ARG, "32 bits")
|
||||
t:eq(code(a, { bits = 3 }), Err.ARG, "3 bits")
|
||||
t:eq(code(a, { blockSize = 8 }), Err.ARG, "block size 8")
|
||||
t:eq(code(Types.Audio.new(44100, 9, 1), nil), Err.ARG, "9 channels")
|
||||
t:eq(code(Types.Audio.new(44100.5, 1, 1), nil), Err.ARG, "fractional rate")
|
||||
end
|
||||
|
||||
-- (the decoder's fuzz pass is in tests/audio/flac.luau; the encoder takes no untrusted bytes)
|
||||
t:done()
|
||||
@@ -0,0 +1,218 @@
|
||||
-- audio/m4a tests: ALAC files from ffmpeg decode bit-exactly (16 / 24-bit, mono / stereo / 5.1, partial frames);
|
||||
-- AAC-LC files from ffmpeg and fdkaac (stereo / mono / 5.1, 8 - 96 kHz, PNS / intensity / M/S / TNS) against ffmpeg's
|
||||
-- float decode (SNR, gapless length through the edit list); HE-AAC / HE-AACv2 play their core; our ALAC writer
|
||||
-- (re-encoded here, compared with the bytes ffmpeg decoded bit-exactly and MP4Box accepted in the fixture step); tags
|
||||
-- and cover art round trips; streaming reads, seeking; the contract; the fuzz no-throw pass.
|
||||
-- Fixtures: tools/fixtures/m4a.py.
|
||||
local T = require("@tests/T")
|
||||
local M4a = require("@formats/audio/m4a")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Signal = require("@tests/audio/_signal")
|
||||
local Cases = require("@tests/audio/_encode_cases")
|
||||
local Alac = require("@tests/gen/m4a_alac")
|
||||
local Aac = require("@tests/gen/m4a_aac")
|
||||
local He = require("@tests/gen/m4a_he")
|
||||
local Ours = require("@tests/gen/m4a_ours")
|
||||
|
||||
local t = T.suite("m4a")
|
||||
|
||||
local function reader(s: string | buffer): Bytes.Reader
|
||||
return Bytes.reader(if type(s) == "string" then buffer.fromstring(s) else s)
|
||||
end
|
||||
|
||||
-- the integers of a decoded Audio (exact for <= 24-bit sources), CRC-32 as little-endian int32
|
||||
local function intCrc(a: any, bits: number): number
|
||||
local n = a.frames * a.channels
|
||||
local b = buffer.create(n * 4)
|
||||
local scale = 2 ^ (bits - 1)
|
||||
for i = 0, n - 1 do
|
||||
buffer.writei32(b, i * 4, math.floor(buffer.readf32(a.samples, i * 4) * scale + 0.5))
|
||||
end
|
||||
return Crc32.of(b)
|
||||
end
|
||||
|
||||
local function snr(a: any, ref: string): (number, number)
|
||||
local n = math.min(a.frames * a.channels, #ref // 4)
|
||||
local rb = buffer.fromstring(ref)
|
||||
local sig, err = 0, 0
|
||||
for i = 0, n - 1 do
|
||||
local r = buffer.readf32(rb, i * 4)
|
||||
local d = buffer.readf32(a.samples, i * 4) - r
|
||||
sig += r * r
|
||||
err += d * d
|
||||
end
|
||||
if err == 0 then
|
||||
return math.huge, n
|
||||
end
|
||||
return 10 * math.log10(sig / err), n
|
||||
end
|
||||
|
||||
-- the contract
|
||||
t:eq(M4a.name, "m4a", "name")
|
||||
t:eq(M4a.category, "audio", "category")
|
||||
t:check(M4a.caps.decode and M4a.caps.encode, "caps")
|
||||
|
||||
-- ALAC from ffmpeg: bit-exact
|
||||
for _, c in Alac do
|
||||
if c.container ~= "m4a" then
|
||||
continue
|
||||
end
|
||||
local r = reader(c.data)
|
||||
t:check(M4a.sniff(r) == 1, c.name .. ": sniff")
|
||||
local a, err = M4a.decode(r)
|
||||
t:check(a, c.name .. ": " .. tostring(err))
|
||||
t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format")
|
||||
t:eq(a.frames, c.frames, c.name .. ": frames")
|
||||
t:eq(intCrc(a, c.bits), c.crc, c.name .. ": samples bit-exact")
|
||||
t:eq(a.meta.source.codec, "alac", c.name .. ": codec")
|
||||
end
|
||||
t:note("%d ffmpeg ALAC files decode bit-exactly", #Alac - 1)
|
||||
|
||||
-- AAC: against ffmpeg's float decode
|
||||
local worst = math.huge
|
||||
for _, c in Aac do
|
||||
if c.container ~= "m4a" then
|
||||
continue
|
||||
end
|
||||
local a, err = M4a.decode(reader(c.data))
|
||||
t:check(a, c.name .. ": " .. tostring(err))
|
||||
t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format")
|
||||
t:eq(a.frames, c.frames, c.name .. ": gapless length")
|
||||
local s = snr(a, c.ref)
|
||||
worst = math.min(worst, s)
|
||||
t:check(s > 90, string.format("%s: SNR %.1f dB vs ffmpeg", c.name, s))
|
||||
t:note("%s: %d ch %d Hz, %d frames, SNR %.1f dB vs ffmpeg", c.name, c.channels, c.rate, a.frames, s)
|
||||
end
|
||||
|
||||
-- HE-AAC: the AAC-LC core at half the rate, SBR seen
|
||||
for _, c in He do
|
||||
if string.sub(c.name, -4) ~= ".m4a" then
|
||||
continue
|
||||
end
|
||||
local dec, err = M4a.open(reader(c.data))
|
||||
t:check(dec, c.name .. ": " .. tostring(err))
|
||||
t:eq(dec.sampleRate, c.rate // 2, c.name .. ": core rate")
|
||||
local b, n = dec:read(8192)
|
||||
local e = 0
|
||||
for i = 0, n * dec.channels - 1 do
|
||||
e += buffer.readf32(b, i * 4) ^ 2
|
||||
end
|
||||
t:check(n == 8192 and e > 1, c.name .. ": the core decodes (energy " .. e .. ")")
|
||||
end
|
||||
|
||||
-- our ALAC writer: the bytes ffmpeg validated
|
||||
do
|
||||
local byName = {}
|
||||
for _, o in Ours do
|
||||
byName[o.name] = o
|
||||
end
|
||||
for _, c in Cases do
|
||||
if c.container ~= "m4a" then
|
||||
continue
|
||||
end
|
||||
local o = byName[c.name]
|
||||
t:check(o and o.ffmpeg and o.mp4box and o.codec == "alac", c.name .. ": ffmpeg decoded it bit-exactly, MP4Box read it")
|
||||
t:eq(o.frames, c.frames, c.name .. ": ffmpeg's length")
|
||||
local a = Signal.audio(c.rate, c.frames, c.channels, c.bits, c.seed)
|
||||
a.tags = c.tags or {}
|
||||
local file, err = M4a.encode(a, { bitDepth = c.bits })
|
||||
t:check(file, c.name .. ": encode: " .. tostring(err))
|
||||
t:eq(string.format("%08x", Crc32.of(file :: buffer)), string.format("%08x", o.crc), c.name .. ": the validated bytes")
|
||||
-- and our own decoder gets the integers back
|
||||
local back = M4a.decode(Bytes.reader(file :: buffer)) :: any
|
||||
local ints = Signal.ints(c.frames, c.channels, c.bits, c.seed)
|
||||
local ok = back.frames == c.frames
|
||||
local scale = 2 ^ (c.bits - 1)
|
||||
for i = 1, #ints, 7 do
|
||||
ok = ok and math.floor(buffer.readf32(back.samples, (i - 1) * 4) * scale + 0.5) == ints[i]
|
||||
end
|
||||
t:check(ok, c.name .. ": round trip")
|
||||
if c.tags then
|
||||
for k, v in c.tags do
|
||||
t:eq(back.tags[k], v, c.name .. ": tag " .. k)
|
||||
end
|
||||
t:eq(o.tags.title, c.tags.title, c.name .. ": ffprobe title")
|
||||
t:eq(o.tags.track, c.tags.track .. "/" .. c.tags.tracktotal, c.name .. ": ffprobe track")
|
||||
t:eq(o.tags.artist, c.tags.artist, c.name .. ": ffprobe artist")
|
||||
end
|
||||
t:note("%s: %d bytes (%.0f%% of PCM)", c.name, buffer.len(file :: buffer), 100 * buffer.len(file :: buffer) / (c.frames * c.channels * c.bits / 8))
|
||||
end
|
||||
end
|
||||
|
||||
-- cover art + streaming a decoder into the encoder
|
||||
do
|
||||
local a = Signal.audio(44100, 5000, 2, 16, 9)
|
||||
a.meta.pictures = { { mime = "image/png", data = buffer.fromstring("\137PNG fake") } }
|
||||
a.tags = { title = "Pic" }
|
||||
local file = M4a.encode(a) :: buffer
|
||||
local back = M4a.decode(Bytes.reader(file)) :: any
|
||||
t:check(back.meta.pictures and #back.meta.pictures == 1 and back.meta.pictures[1].mime == "image/png", "cover art round trip")
|
||||
local dec = M4a.open(Bytes.reader(file)) :: any
|
||||
local again = M4a.encode(dec) :: buffer
|
||||
local back2 = M4a.decode(Bytes.reader(again)) :: any
|
||||
t:check(back2.frames == 5000 and buffer.tostring(back2.samples) == buffer.tostring(back.samples), "encode from a streaming decoder")
|
||||
local _, e = M4a.encode({} :: any)
|
||||
t:check(e and e.code == Err.ARG, "encode of a non-audio returns Err.ARG")
|
||||
local _, e2 = M4a.encode(a, { bitDepth = 12 })
|
||||
t:check(e2 and e2.code == Err.ARG, "bad bitDepth returns Err.ARG")
|
||||
end
|
||||
|
||||
-- streaming + seek (AAC without PNS: its noise is random, so a seek changes it; and ALAC)
|
||||
for _, c in { Aac[1], Alac[1] } do
|
||||
local whole = M4a.decode(reader(c.data)) :: any
|
||||
local dec = M4a.open(reader(c.data)) :: any
|
||||
t:eq(dec.frames, whole.frames, c.name .. ": decoder frames")
|
||||
-- read in odd chunks
|
||||
local got, out = 0, buffer.create(whole.frames * whole.channels * 4)
|
||||
while true do
|
||||
local b, n = dec:read(777)
|
||||
if n == 0 then
|
||||
break
|
||||
end
|
||||
buffer.copy(out, got * whole.channels * 4, b, 0, n * whole.channels * 4)
|
||||
got += n
|
||||
end
|
||||
t:check(got == whole.frames and buffer.tostring(out) == buffer.tostring(whole.samples), c.name .. ": chunked reads equal the whole decode")
|
||||
for _, at in { 0.1, 0.0, 0.05 } do
|
||||
dec:seek(at)
|
||||
local b, n = dec:read(500)
|
||||
local f0 = math.floor(at * whole.sampleRate + 0.5)
|
||||
local maxd = 0
|
||||
for i = 0, n * whole.channels - 1 do
|
||||
maxd = math.max(maxd, math.abs(buffer.readf32(b, i * 4) - buffer.readf32(whole.samples, (f0 * whole.channels + i) * 4)))
|
||||
end
|
||||
t:check(n == 500 and maxd < 1e-6, string.format("%s: seek %.2f s (max diff %g)", c.name, at, maxd))
|
||||
t:check(math.abs(dec:position() - (f0 + 500) / whole.sampleRate) < 1e-9, c.name .. ": position after seek")
|
||||
end
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local _, e = M4a.decode(reader("\0\0\0\8ftypM4A "))
|
||||
t:check(e ~= nil, "a lone ftyp: " .. tostring(e))
|
||||
local _, e2 = M4a.decode(reader("hello world, not an mp4"))
|
||||
t:check(e2 ~= nil and Err.is(e2), "junk: " .. tostring(e2))
|
||||
t:eq(M4a.sniff(reader("hello")), 0, "sniff junk")
|
||||
end
|
||||
|
||||
-- fuzz
|
||||
do
|
||||
local samples = {}
|
||||
for i, c in Alac do
|
||||
if c.container == "m4a" and i <= 2 then
|
||||
table.insert(samples, string.sub(c.data, 1, 12000))
|
||||
end
|
||||
end
|
||||
for i, c in Aac do
|
||||
if c.container == "m4a" and i <= 2 then
|
||||
table.insert(samples, string.sub(c.data, 1, 9000))
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return M4a.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 25 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -82,7 +82,7 @@ local rand = T.rng(12345)
|
||||
t:eq(Mp3.name, "mp3", "name")
|
||||
t:eq(Mp3.category, "audio", "category")
|
||||
t:check(table.find(Mp3.extensions, "mp3") ~= nil and table.find(Mp3.extensions, "mp2") ~= nil, "extensions")
|
||||
t:check(Mp3.caps.decode and not Mp3.caps.encode and Mp3.open ~= nil, "caps")
|
||||
t:check(Mp3.caps.decode and Mp3.caps.encode and Mp3.open ~= nil, "caps") -- encode: ws-audio (tests/audio/mp3_encode.luau)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode vs references
|
||||
for _, c in Cases do
|
||||
@@ -487,8 +487,8 @@ do
|
||||
t:check(a and a.kind == "audio" and a.frames == 22050 and a.tags.title == "Test Title", "F.audio.load: " .. tostring(err))
|
||||
local dec = F.audio.open(data)
|
||||
t:check(dec and dec.sampleRate == 44100 and dec.frames == 22050, "F.audio.open")
|
||||
local _, serr = F.save(a, nil, { format = "mp3" })
|
||||
t:check(serr and serr.code == Err.UNSUPPORTED, "F.save mp3: read-only")
|
||||
local saved, serr = F.save(a, nil, { format = "mp3" }) -- the layer III encoder (ws-audio)
|
||||
t:check(saved and F.audio.load(saved).sampleRate == 44100, "F.save mp3: " .. tostring(serr))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ fuzz
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
-- audio/mp3 encoder tests (layer III and layer II): every fixture-step encode (sample rates of MPEG-1 / 2 / 2.5,
|
||||
-- bit rates 24 .. 384 kbps, stereo / joint / mono) decodes in ffmpeg without errors and in LAME, with the expected
|
||||
-- length and an SNR over a per-bit-rate floor after aligning the decoder delay; our own decoder (the minimp3 port)
|
||||
-- agrees; streaming from a Decoder gives the same bytes; the ID3v2 tag round-trips; option errors.
|
||||
-- Fixtures: tools/fixtures/mp3_enc.py.
|
||||
local T = require("@tests/T")
|
||||
local Mp3 = require("@formats/audio/mp3")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/Pcm")
|
||||
local Enc = require("@tests/gen/mp3_enc")
|
||||
local Sigs = require("@tests/gen/mp3_enc_sigs")
|
||||
|
||||
local t = T.suite("mp3_encode")
|
||||
|
||||
local function audio(name: string): Types.Audio
|
||||
local s = Sigs[name]
|
||||
local a = Types.Audio.new(s.rate, s.channels, s.frames)
|
||||
buffer.writestring(a.samples, 0, s.data)
|
||||
return a
|
||||
end
|
||||
|
||||
-- SNR of y (delayed by lag frames) against x over frames [from, to)
|
||||
local function snr(x: Types.Audio, y: Types.Audio, lag: number, from: number, to: number): number
|
||||
local ch = x.channels
|
||||
local sig, er = 0, 0
|
||||
for i = from, to - 1 do
|
||||
local j = i + lag
|
||||
if j >= 0 and j < y.frames then
|
||||
for c = 0, ch - 1 do
|
||||
local a = buffer.readf32(x.samples, (i * ch + c) * 4)
|
||||
local b = buffer.readf32(y.samples, (j * y.channels + math.min(c, y.channels - 1)) * 4)
|
||||
sig += a * a
|
||||
er += (a - b) * (a - b)
|
||||
end
|
||||
end
|
||||
end
|
||||
if er == 0 then
|
||||
return 200
|
||||
end
|
||||
return if sig > 0 then 10 * math.log10(sig / er) else -200
|
||||
end
|
||||
|
||||
-- the SNR floors (dB) on the music / sine / sweep signals, by layer and bit rate per channel
|
||||
local function floorFor(e: any): number
|
||||
if string.find(e.name, "silence", 1, true) then
|
||||
return -math.huge
|
||||
elseif string.find(e.name, "noise", 1, true) then
|
||||
return 8 -- white noise has no spectral structure to exploit
|
||||
end
|
||||
local perCh = e.bitrate / (if e.mode == "mono" then 1 else 2)
|
||||
local nyquistBand = e.rate <= 16000 -- low rates lose little to the encoder's band limit
|
||||
if e.layer == 3 then
|
||||
if perCh >= 64 then
|
||||
return 14
|
||||
elseif perCh >= 32 or nyquistBand then
|
||||
return 8
|
||||
end
|
||||
return 4
|
||||
end
|
||||
if perCh >= 96 then
|
||||
return 14
|
||||
elseif perCh >= 48 then
|
||||
return 8
|
||||
end
|
||||
return 4
|
||||
end
|
||||
|
||||
t:check(Mp3.caps.encode and Mp3.encode ~= nil, "caps.encode")
|
||||
|
||||
local minByLayer = { [2] = math.huge, [3] = math.huge }
|
||||
for _, e in Enc do
|
||||
t:eq(e.ffErrors, "", e.name .. ": ffmpeg decodes without errors")
|
||||
t:check(e.ffRate == e.rate, e.name .. ": rate")
|
||||
t:check(e.ffChannels == (if e.mode == "mono" then 1 else 2), e.name .. ": channels")
|
||||
-- the stream covers the input: the encoder adds one frame of flush and the filterbank delay
|
||||
local spf = if e.layer == 3 and e.rate < 32000 then 576 else 1152
|
||||
t:check(e.ffFrames >= e.frames and e.ffFrames <= e.frames + 3 * spf, string.format("%s: %d decoded frames for %d", e.name, e.ffFrames, e.frames))
|
||||
local f = floorFor(e)
|
||||
t:check(e.ffSnr >= f, string.format("%s: ffmpeg SNR %.1f dB (floor %g)", e.name, e.ffSnr, f))
|
||||
if e.lameSnr then
|
||||
t:check(e.lameSnr >= f, string.format("%s: LAME SNR %.1f dB (floor %g)", e.name, e.lameSnr, f))
|
||||
end
|
||||
if f > -math.huge then
|
||||
minByLayer[e.layer] = math.min(minByLayer[e.layer], e.ffSnr)
|
||||
end
|
||||
-- our decoder agrees with ffmpeg
|
||||
local x = audio(e.sig)
|
||||
local y, err = Mp3.decode(Bytes.reader(buffer.fromstring(e.data)))
|
||||
t:check(y, e.name .. ": our decoder: " .. tostring(err))
|
||||
if e.channels == y.channels then
|
||||
local s = snr(x, y, e.ffLag, 200, x.frames)
|
||||
t:check(s >= f and math.abs(s - e.ffSnr) < 3, string.format("%s: our decoder %.1f dB, ffmpeg %.1f dB", e.name, s, e.ffSnr))
|
||||
end
|
||||
end
|
||||
t:note("%d encodes: ffmpeg + LAME decode them; lowest SNR layer III %.1f dB, layer II %.1f dB", #Enc, minByLayer[3], minByLayer[2])
|
||||
|
||||
-- streaming, tags, defaults
|
||||
do
|
||||
local a = audio("music_2_44100")
|
||||
local f1 = Mp3.encode(a, { bitrate = 128 }) :: buffer
|
||||
local f2 = Mp3.encode(Pcm.audioDecoder(a), { bitrate = 128 }) :: buffer
|
||||
t:check(buffer.tostring(f1) == buffer.tostring(f2), "Decoder source = Audio source")
|
||||
a.tags = { title = "Ünïcode title", artist = "An Artist", album = "Album", track = "4", comment = "made here" }
|
||||
local f3 = Mp3.encode(a, { layer = 2 }) :: buffer
|
||||
t:eq(buffer.readstring(f3, 0, 3), "ID3", "an ID3v2 tag in front")
|
||||
local back = Mp3.open(Bytes.reader(f3)) :: any
|
||||
t:eq(back.tags.title, "Ünïcode title", "title")
|
||||
t:eq(back.tags.artist, "An Artist", "artist")
|
||||
t:eq(back.tags.album, "Album", "album")
|
||||
t:eq(back.tags.track, "4", "track")
|
||||
t:eq(back.layer, 2, "layer II by default bit rate 192")
|
||||
local f4 = Mp3.encode(a, { id3 = false }) :: buffer
|
||||
t:check(buffer.readu8(f4, 0) == 0xFF, "id3 = false")
|
||||
local m = Types.Audio.new(22050, 1, 3000)
|
||||
local fm = Mp3.encode(m) :: buffer
|
||||
local dm = Mp3.open(Bytes.reader(fm)) :: any
|
||||
t:check(dm.channels == 1 and dm.sampleRate == 22050, "mono MPEG-2 default")
|
||||
local empty = Mp3.encode(Types.Audio.new(44100, 2, 0)) :: buffer
|
||||
t:check(empty and buffer.len(empty) > 0, "empty input: one flush frame")
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local function code(v: any, o: any): string?
|
||||
local _, e = Mp3.encode(v, o)
|
||||
return e and e.code
|
||||
end
|
||||
local a = Types.Audio.new(44100, 2, 100)
|
||||
t:eq(code({}, nil), Err.ARG, "junk")
|
||||
t:eq(code(a, { layer = 1 }), Err.ARG, "layer I")
|
||||
t:eq(code(a, { bitrate = 100 }), Err.ARG, "100 kbps")
|
||||
t:eq(code(a, { mode = "dual" }), Err.ARG, "dual mode")
|
||||
t:eq(code(Types.Audio.new(44000, 2, 10), nil), Err.ARG, "44 kHz")
|
||||
t:eq(code(Types.Audio.new(8000, 2, 10), { layer = 2 }), Err.ARG, "layer II at 8 kHz")
|
||||
t:eq(code(Types.Audio.new(44100, 3, 10), nil), Err.ARG, "3 channels")
|
||||
t:eq(code(a, { layer = 2, bitrate = 32 }), Err.ARG, "layer II stereo at 32 kbps")
|
||||
t:eq(code(Types.Audio.new(44100, 1, 10), { layer = 2, bitrate = 320 }), Err.ARG, "layer II mono at 320 kbps")
|
||||
end
|
||||
|
||||
-- (the decoder's fuzz pass is in tests/audio/mp3.luau; the encoders take no untrusted bytes)
|
||||
t:done()
|
||||
@@ -81,7 +81,7 @@ end
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
t:eq(Opus.name, "opus", "name")
|
||||
t:eq(Opus.category, "audio", "category")
|
||||
t:check(Opus.caps.decode and not Opus.caps.encode and Opus.open ~= nil and Opus.decode ~= nil, "caps")
|
||||
t:check(Opus.caps.decode and Opus.caps.encode and Opus.open ~= nil and Opus.decode ~= nil and Opus.encode ~= nil, "caps (the CELT encoder: tests/audio/opus_encode.luau)")
|
||||
t:eq(Opus.sniff(Bytes.reader(FX.celt_st_128.data)), 1, "sniff an Opus file")
|
||||
t:eq(Opus.sniff(Bytes.reader(buffer.fromstring("OggS" .. string.rep("\0", 40)))), 0, "sniff another Ogg")
|
||||
t:eq(Opus.sniff(Bytes.reader(buffer.create(0))), 0, "sniff nothing")
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
-- audio/opus encoder tests (the CELT-only writer, ws-m4a; mono and mid / side stereo): our Ogg Opus files (re-encoded here, compared with the bytes
|
||||
-- checked in the fixture step) decode in libopus' opusdec to the input's exact length (pre-skip + end trimming) with a
|
||||
-- minimum SNR, opusinfo finds no problem, ffmpeg reads them, OpusTags carry the tags; our decoder agrees with opusdec;
|
||||
-- resampled 44.1 kHz input; silence frames; streaming input; errors; a fuzz no-throw pass over our files.
|
||||
-- Fixtures: tools/fixtures/opus_celt.py.
|
||||
local T = require("@tests/T")
|
||||
local Opus = require("@formats/audio/opus")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Cases = require("@tests/audio/_opus_cases")
|
||||
local Fx = require("@tests/gen/opus_celt")
|
||||
|
||||
local t = T.suite("opus-encode")
|
||||
|
||||
t:check(Opus.caps.encode and Opus.encode ~= nil, "caps: encode")
|
||||
|
||||
local byName = {}
|
||||
for _, f in Fx do
|
||||
byName[f.name] = f
|
||||
end
|
||||
|
||||
local function snr(ref: buffer, refBase: number, got: buffer, n: number): number
|
||||
local s, e = 0, 0
|
||||
for i = 0, n - 1 do
|
||||
local x = buffer.readf32(ref, (refBase + i) * 4)
|
||||
local d = buffer.readf32(got, (refBase + i) * 4) - x
|
||||
s += x * x
|
||||
e += d * d
|
||||
end
|
||||
return if e == 0 then math.huge else 10 * math.log10(s / math.max(e, 1e-30))
|
||||
end
|
||||
|
||||
local files = {}
|
||||
for _, c in Cases.list do
|
||||
local fx = byName[c.name]
|
||||
t:check(fx, c.name .. ": fixture")
|
||||
local input = Cases.signal(c)
|
||||
local file, err = Opus.encode(input, { bitrate = c.bitrate })
|
||||
t:check(file, c.name .. ": encode: " .. tostring(err))
|
||||
table.insert(files, file)
|
||||
t:eq(string.format("%08x", Crc32.of(file :: buffer)), string.format("%08x", fx.crc), c.name .. ": the bytes the reference tools checked")
|
||||
t:check(fx.opusinfo, c.name .. ": opusinfo reports no problem")
|
||||
t:check(fx.ffmpeg, c.name .. ": ffmpeg decodes it")
|
||||
local frames48 = math.floor(input.frames * 48000 / c.rate + 0.5)
|
||||
local ch = c.channels
|
||||
t:eq(#fx.opusdec // (4 * ch), frames48, c.name .. ": opusdec length = the input's (pre-skip + end trimming)")
|
||||
t:eq(fx.ffmpegFrames, frames48, c.name .. ": ffmpeg length")
|
||||
-- our decoder vs opusdec
|
||||
local ours = Opus.decode(Bytes.reader(file :: buffer)) :: any
|
||||
t:eq(ours.frames, frames48, c.name .. ": our decoder's length")
|
||||
local ref = buffer.fromstring(fx.opusdec)
|
||||
local agree = snr(ref, 0, ours.samples, frames48 * ch)
|
||||
t:check(agree > 60, string.format("%s: our decoder vs opusdec %.1f dB", c.name, agree))
|
||||
-- quality vs the input (48 kHz inputs; skip the edges)
|
||||
if c.rate == 48000 and frames48 > 4000 then
|
||||
local s = snr(input.samples, 960 * ch, ref, (frames48 - 1920) * ch)
|
||||
t:check(s >= c.minSnr, string.format("%s: SNR %.1f dB (minimum %d)", c.name, s, c.minSnr))
|
||||
t:note("%s: %d bytes, SNR %.1f dB vs the input, our decoder vs opusdec %.1f dB", c.name, buffer.len(file :: buffer), s, agree)
|
||||
end
|
||||
if c.tags then
|
||||
for k, v in c.tags do
|
||||
t:eq(fx.comments[k], v, c.name .. ": opusinfo comment " .. k)
|
||||
t:eq(ours.tags[k], v, c.name .. ": our tag " .. k)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- silence frames decode to silence
|
||||
do
|
||||
local c = Cases.list[1]
|
||||
local ref = buffer.fromstring(byName[c.name].opusdec)
|
||||
local peak = 0
|
||||
for i = math.floor(0.62 * 48000), math.floor(0.73 * 48000) do
|
||||
peak = math.max(peak, math.abs(buffer.readf32(ref, i * 4)))
|
||||
end
|
||||
t:check(peak < 1e-3, "digital silence stays silent (peak " .. peak .. ")")
|
||||
end
|
||||
|
||||
-- a streaming decoder as the input
|
||||
do
|
||||
local c = Cases.list[1]
|
||||
local dec = Opus.open(Bytes.reader(files[1] :: buffer)) :: any
|
||||
local again, err = Opus.encode(dec, { bitrate = 64000 })
|
||||
t:check(again, "encode from a decoder: " .. tostring(err))
|
||||
local back = Opus.decode(Bytes.reader(again :: buffer)) :: any
|
||||
t:eq(back.frames, math.floor(c.seconds * 48000 + 0.5), "re-encoded length")
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local three = Cases.signal({ rate = 48000, channels = 3, seconds = 0.05 })
|
||||
local _, e = Opus.encode(three)
|
||||
t:check(e and e.code == Err.UNSUPPORTED, "3 channels: " .. tostring(e))
|
||||
local _, e2 = Opus.encode(Cases.signal(Cases.list[6]), { bitrate = 1000 })
|
||||
t:check(e2 and e2.code == Err.ARG, "bitrate too low")
|
||||
local _, e3 = Opus.encode({} :: any)
|
||||
t:check(e3 and e3.code == Err.ARG, "not audio")
|
||||
end
|
||||
|
||||
-- fuzz the decoder over our files
|
||||
do
|
||||
local samples = {}
|
||||
for i, f in files do
|
||||
if i <= 3 then
|
||||
table.insert(samples, string.sub(buffer.tostring(f :: buffer), 1, 4000))
|
||||
end
|
||||
end
|
||||
t:fuzz("decode our files", function(b: buffer)
|
||||
return Opus.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 10, garbage = 30 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,129 @@
|
||||
-- audio/voc tests: files written by ffmpeg (type 1 + 8 blocks for 8-bit, type 9 otherwise) and sox against ffmpeg's
|
||||
-- decode; silence / text / continuation blocks and repeat markers built here; streaming reads and seeks; our
|
||||
-- encoder's output for every sample format decoded by ffmpeg (fixture step) and by us; errors; fuzz.
|
||||
-- Fixtures: tools/fixtures/voc.py.
|
||||
local T = require("@tests/T")
|
||||
local Voc = require("@formats/audio/voc")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Cases = require("@tests/gen/voc_cases")
|
||||
local Enc = require("@tests/gen/voc_enc")
|
||||
local Sig = require("@tests/gen/voc_sig")
|
||||
|
||||
local t = T.suite("voc")
|
||||
|
||||
local function reader(s: string): Bytes.Reader
|
||||
return Bytes.reader(buffer.fromstring(s))
|
||||
end
|
||||
local function maxDiff(a: buffer, ao: number, b: buffer, bo: number, n: number): number
|
||||
local m = 0
|
||||
for i = 0, n - 1 do
|
||||
local d = math.abs(buffer.readf32(a, ao + i * 4) - buffer.readf32(b, bo + i * 4))
|
||||
if d > m then
|
||||
m = d
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
|
||||
t:eq(Voc.name, "voc", "name")
|
||||
t:eq(Voc.category, "audio", "category")
|
||||
t:check(Voc.caps.decode and Voc.caps.encode, "caps")
|
||||
|
||||
for _, c in Cases do
|
||||
local a, err = Voc.decode(reader(c.data))
|
||||
t:check(a, c.name .. ": " .. tostring(err))
|
||||
t:check(a.sampleRate == c.rate and a.channels == c.channels, string.format("%s: format %d Hz x %d, want %d x %d", c.name, a.sampleRate, a.channels, c.rate, c.channels))
|
||||
t:eq(a.frames, c.frames, c.name .. ": frames")
|
||||
local ref = buffer.fromstring(c.ref)
|
||||
t:check(maxDiff(a.samples, 0, ref, 0, c.frames * c.channels) < 1e-6, c.name .. ": samples match ffmpeg")
|
||||
local dec = Voc.open(reader(c.data)) :: Types.Decoder
|
||||
dec:seek(500 / c.rate)
|
||||
local b, k = dec:read(64)
|
||||
t:check(k == 64 and maxDiff(b, 0, ref, 500 * c.channels * 4, 64 * c.channels) < 1e-6, c.name .. ": seek")
|
||||
end
|
||||
t:note("%d reference files match ffmpeg", #Cases)
|
||||
|
||||
-- hand-built blocks: text, type 1 u8, silence, continuation, repeat markers, terminator
|
||||
do
|
||||
local hdr = "Creative Voice File\26\26\0\10\1\41\17"
|
||||
local function blk(typ: number, payload: string): string
|
||||
local n = #payload
|
||||
return string.char(typ, n % 256, (n // 256) % 256, n // 65536) .. payload
|
||||
end
|
||||
local data = hdr
|
||||
.. blk(5, "made by hand\0")
|
||||
.. blk(1, string.char(156, 0) .. string.char(128, 192, 64)) -- 10 kHz, 3 samples
|
||||
.. blk(3, string.char(4, 0, 156)) -- 5 frames of silence
|
||||
.. blk(6, string.char(2, 0)) -- repeat start (ignored)
|
||||
.. blk(2, string.char(255, 0)) -- continuation
|
||||
.. blk(7, "") -- repeat end
|
||||
.. blk(4, string.char(1, 0)) -- marker
|
||||
.. "\0"
|
||||
local a, err = Voc.decode(reader(data))
|
||||
t:check(a, "hand-built: " .. tostring(err))
|
||||
t:check(a.sampleRate == 10000 and a.channels == 1 and a.frames == 10, "hand-built: 10 kHz, 3 + 5 + 2 frames")
|
||||
t:eq(a.tags.comment, "made by hand", "text block")
|
||||
local want = { 0, 0.5, -0.5, 0, 0, 0, 0, 0, 127 / 128, -1 }
|
||||
local ok = true
|
||||
for i, v in want do
|
||||
ok = ok and buffer.readf32(a.samples, (i - 1) * 4) == v
|
||||
end
|
||||
t:check(ok, "hand-built samples")
|
||||
-- no terminator, a block cut short: the data present
|
||||
local cut = Voc.decode(reader(string.sub(data, 1, 26 + 17 + 4 + 2 + 2)))
|
||||
t:check(cut and cut.frames == 2 and cut.meta.source.truncated, "cut in a block")
|
||||
-- Creative ADPCM: unsupported
|
||||
local _, e = Voc.decode(reader(hdr .. blk(1, string.char(156, 1) .. "\0\0") .. "\0"))
|
||||
t:check(e and e.code == Err.UNSUPPORTED, "ADPCM: UNSUPPORTED")
|
||||
local _, e2 = Voc.decode(reader(hdr .. blk(2, "\0\0") .. "\0"))
|
||||
t:check(e2 and e2.code == Err.CORRUPT, "continuation first: CORRUPT")
|
||||
local _, e3 = Voc.decode(reader(hdr .. "\0"))
|
||||
t:check(e3 and e3.code == Err.CORRUPT, "no sound: CORRUPT")
|
||||
local _, e4 = Voc.decode(reader("Creative Voice Fil"))
|
||||
t:check(e4 and e4.code == Err.CORRUPT, "short: CORRUPT")
|
||||
t:eq(Voc.sniff(reader(data)), 1, "sniff")
|
||||
t:eq(Voc.sniff(reader(".snd")), 0, "sniff other")
|
||||
end
|
||||
|
||||
local TOL = { s16 = 0.5 / 32768, ["s16-mono"] = 0.5 / 32768, u8 = 0.5 / 128, ulaw = 0.04, alaw = 0.04 }
|
||||
local sig = buffer.fromstring(Sig.data)
|
||||
for _, e in Enc do
|
||||
t:eq(e.ffmpegErrors, "", e.name .. ": ffmpeg reads our file without errors")
|
||||
t:check(e.frames == Sig.frames and e.rate == Sig.rate, e.name .. ": ffmpeg frames / rate")
|
||||
t:check(e.maxDiff <= TOL[e.name] + 1e-7, string.format("%s: ffmpeg decode within %g (max diff %g)", e.name, TOL[e.name], e.maxDiff))
|
||||
t:check(e.sameStreamed, e.name .. ": encoding a Decoder gives the same bytes")
|
||||
local back = Voc.decode(reader(e.data)) :: Types.Audio
|
||||
t:check(back and back.frames == Sig.frames and back.channels == e.channels, e.name .. ": our decoder reads our file")
|
||||
if e.channels == 2 then
|
||||
t:check(maxDiff(back.samples, 0, sig, 0, Sig.frames * 2) <= TOL[e.name] + 1e-7, e.name .. ": round trip")
|
||||
end
|
||||
end
|
||||
t:note("%d encoder outputs read back by ffmpeg and by us", #Enc)
|
||||
|
||||
do
|
||||
local a = Types.Audio.new(22050, 2, 1)
|
||||
a.tags = { comment = "hi" }
|
||||
local b = Voc.encode(a) :: buffer
|
||||
local back = Voc.decode(Bytes.reader(b)) :: Types.Audio
|
||||
t:check(back.frames == 1 and back.tags.comment == "hi", "one frame + comment")
|
||||
local _, e1 = Voc.encode(nil :: any)
|
||||
t:check(e1 and e1.code == Err.ARG, "encode nil: ARG")
|
||||
local _, e2 = Voc.encode(a, { sampleFormat = "s24" } :: any)
|
||||
t:check(e2 and e2.code == Err.ARG, "bad sampleFormat: ARG")
|
||||
local _, e3 = Voc.decode(reader(Cases[1].data), { maxFrames = 5 })
|
||||
t:check(e3 and e3.code == Err.LIMIT, "maxFrames: LIMIT")
|
||||
end
|
||||
|
||||
do
|
||||
local samples = {}
|
||||
for _, c in Cases do
|
||||
table.insert(samples, string.sub(c.data, 1, 300))
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Voc.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 30 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,193 @@
|
||||
-- audio/vorbis tests: oggenc / ffmpeg streams (qualities -1 .. 10, managed bitrate, 8 .. 96 kHz, mono / stereo / 5.1,
|
||||
-- transients, silence, tags, sub-block lengths) against oggdec (libvorbisfile: sample counts and 16-bit samples, so
|
||||
-- start / end trimming is exact) and ffmpeg's f32 decode (SNR); streaming reads; seeking (sample-exact against the
|
||||
-- reference at the target); the packet-level decoder; errors; fuzz. Fixtures: tools/fixtures/vorbis.py.
|
||||
local T = require("@tests/T")
|
||||
local Vorbis = require("@formats/audio/vorbis")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Ogg = require("@formats/containers/Ogg")
|
||||
local Cases = require("@tests/gen/vorbis_cases")
|
||||
|
||||
local t = T.suite("vorbis")
|
||||
|
||||
local function reader(s: string): Bytes.Reader
|
||||
return Bytes.reader(buffer.fromstring(s))
|
||||
end
|
||||
local function s16(x: number): number
|
||||
local v = math.floor(x * 32768 + 0.5)
|
||||
return math.clamp(v, -32768, 32767)
|
||||
end
|
||||
-- the largest |our sample as s16 - oggdec's| over n samples of ours at byte a0 against ref16 from sample r0
|
||||
local function maxDiff16(a: buffer, a0: number, ref: buffer, r0: number, n: number): number
|
||||
local m = 0
|
||||
for i = 0, n - 1 do
|
||||
local d = math.abs(s16(buffer.readf32(a, a0 + i * 4)) - buffer.readi16(ref, (r0 + i) * 2))
|
||||
if d > m then
|
||||
m = d
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
local function snr(a: buffer, ref: buffer, n: number): number
|
||||
local sig, er = 0, 0
|
||||
for i = 0, n - 1 do
|
||||
local x = buffer.readf32(ref, i * 4)
|
||||
local d = x - buffer.readf32(a, i * 4)
|
||||
sig += x * x
|
||||
er += d * d
|
||||
end
|
||||
if er == 0 then
|
||||
return 200
|
||||
end
|
||||
return if sig > 0 then 10 * math.log10(sig / er) else -200
|
||||
end
|
||||
|
||||
t:eq(Vorbis.name, "vorbis", "name")
|
||||
t:eq(Vorbis.category, "audio", "category")
|
||||
t:check(Vorbis.caps.decode and Vorbis.open ~= nil, "caps")
|
||||
|
||||
local minSnr = math.huge
|
||||
for _, c in Cases do
|
||||
local a, err = Vorbis.decode(reader(c.data))
|
||||
t:check(a, c.name .. ": " .. tostring(err))
|
||||
t:check(a.sampleRate == c.rate and a.channels == c.channels, c.name .. ": format")
|
||||
t:eq(a.frames, c.frames, c.name .. ": frames = oggdec's")
|
||||
t:eq(a.frames, c.inputFrames, c.name .. ": frames = the encoder's input")
|
||||
local ref16 = buffer.fromstring(c.ref16)
|
||||
local n = c.frames * c.channels
|
||||
local d = maxDiff16(a.samples, 0, ref16, 0, n)
|
||||
t:check(d <= 1, string.format("%s: within 1 LSB of oggdec (max %d)", c.name, d))
|
||||
if c.ffRef then
|
||||
local s = snr(a.samples, buffer.fromstring(c.ffRef), n)
|
||||
minSnr = math.min(minSnr, s)
|
||||
t:check(s > 100, string.format("%s: SNR vs ffmpeg %.1f dB", c.name, s))
|
||||
end
|
||||
-- streaming in odd chunks gives the same samples
|
||||
local dec = Vorbis.open(reader(c.data)) :: Types.Decoder
|
||||
t:eq(dec.frames, c.frames, c.name .. ": Decoder.frames")
|
||||
local got, ok = 0, true
|
||||
while true do
|
||||
local b, k = dec:read(1013)
|
||||
if k == 0 then
|
||||
break
|
||||
end
|
||||
for i = 0, k * c.channels - 1, 7 do
|
||||
ok = ok and buffer.readf32(b, i * 4) == buffer.readf32(a.samples, got * c.channels * 4 + i * 4)
|
||||
end
|
||||
got += k
|
||||
end
|
||||
t:check(ok and got == c.frames, c.name .. ": streamed reads")
|
||||
-- seeks: sample-exact against the full decode
|
||||
for _, frac in { 0.5, 0.1, 0.93, 0 } do
|
||||
local target = math.floor(c.frames * frac)
|
||||
dec:seek(target / c.rate)
|
||||
t:check(math.abs(dec:position() - target / c.rate) < 1e-9, c.name .. ": position after seek")
|
||||
local b, k = dec:read(300)
|
||||
local want = math.min(300, c.frames - target)
|
||||
t:eq(k, want, string.format("%s: frames after seek to %d", c.name, target))
|
||||
local same = true
|
||||
for i = 0, k * c.channels - 1 do
|
||||
same = same and buffer.readf32(b, i * 4) == buffer.readf32(a.samples, (target * c.channels + i) * 4)
|
||||
end
|
||||
t:check(same, string.format("%s: samples after seek to %d", c.name, target))
|
||||
end
|
||||
end
|
||||
t:note("%d streams match oggdec (counts, 1 LSB) and ffmpeg (min SNR %.1f dB)", #Cases, minSnr)
|
||||
|
||||
local function case(name: string): any
|
||||
for _, c in Cases do
|
||||
if c.name == name then
|
||||
return c
|
||||
end
|
||||
end
|
||||
error("no case " .. name)
|
||||
end
|
||||
|
||||
-- tags, meta, sniff, sub-range
|
||||
do
|
||||
local c = case("q2-stereo-32k-tags")
|
||||
local dec = Vorbis.open(reader(c.data)) :: any
|
||||
t:eq(dec.tags.title, "A Title", "title tag")
|
||||
t:eq(dec.tags.artist, "An Artist", "artist tag")
|
||||
t:eq(dec.tags.album, "The Album", "album tag")
|
||||
t:eq(dec.tags.track, "7", "track tag")
|
||||
t:eq(dec.tags.comment, "hello vorbis", "comment tag")
|
||||
t:check(type(dec.vendor) == "string" and string.find(dec.vendor, "Xiph", 1, true) ~= nil, "vendor")
|
||||
t:check(dec.bitrate > 0 and math.abs(dec.duration - c.frames / c.rate) < 1e-9, "bitrate / duration")
|
||||
t:eq(Vorbis.sniff(reader(c.data)), 1, "sniff")
|
||||
t:eq(Vorbis.sniff(reader("OggS")), 0, "sniff short")
|
||||
t:eq(Vorbis.sniff(reader("RIFF")), 0, "sniff other")
|
||||
local big = buffer.create(#c.data + 11)
|
||||
buffer.writestring(big, 11, c.data)
|
||||
local a = Vorbis.decode(Bytes.reader(big, 11, #c.data))
|
||||
t:check(a and a.frames == c.frames, "decode from a sub-range")
|
||||
end
|
||||
|
||||
-- the packet-level decoder (as Matroska / MP4 would use it) gives the same samples, minus the Ogg trimming
|
||||
do
|
||||
local c = case("q5-stereo-44k-music")
|
||||
local full = Vorbis.decode(reader(c.data)) :: Types.Audio
|
||||
local demux = Ogg.open(buffer.fromstring(c.data))
|
||||
local serial = demux:find("vorbis")
|
||||
local h = {}
|
||||
for i = 1, 3 do
|
||||
h[i] = Ogg.copy(demux:nextPacket(serial))
|
||||
end
|
||||
local pd = Vorbis.packetDecoder(h[1], h[2], h[3])
|
||||
t:check(pd and pd.channels == 2 and pd.sampleRate == 44100, "packetDecoder")
|
||||
local total, same = 0, true
|
||||
for p in demux:packets(serial) do
|
||||
local n = pd:decode(p.data, p.offset, p.size)
|
||||
for i = 1, n, 13 do
|
||||
if total + i <= full.frames then
|
||||
same = same and math.abs(pd.out[1][i] - buffer.readf32(full.samples, (total + i - 1) * 8)) < 1e-6
|
||||
end
|
||||
end
|
||||
total += math.max(n, 0)
|
||||
end
|
||||
t:check(same and total >= full.frames, "packetDecoder samples")
|
||||
local _, e = Vorbis.packetDecoder(h[2], h[1], h[3])
|
||||
t:check(e and e.code == Err.CORRUPT, "packetDecoder with headers swapped")
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local _, e1 = Vorbis.decode(reader("OggS but not really"))
|
||||
t:check(e1 and Err.is(e1), "junk: " .. tostring(e1))
|
||||
local c = case("short-100").data
|
||||
local _, e2 = Vorbis.decode(reader(string.sub(c, 1, 60)))
|
||||
t:check(e2 and Err.is(e2), "cut in the headers: " .. tostring(e2))
|
||||
-- a truncated stream decodes what is there
|
||||
local q = case("q5-stereo-44k-music")
|
||||
local cut = Vorbis.decode(reader(string.sub(q.data, 1, #q.data // 2)), { verify = false })
|
||||
t:check(cut and cut.frames > 0 and cut.frames < q.frames, "truncated stream")
|
||||
end
|
||||
|
||||
-- fuzz: whole streams with mutations past the headers, truncations, garbage
|
||||
do
|
||||
local samples = {}
|
||||
for _, name in { "short-100", "short-3000-mono", "q-1-mono-8k-music", "ffmpeg-mono-16k" } do
|
||||
table.insert(samples, case(name).data)
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Vorbis.decode(Bytes.reader(b), { verify = false })
|
||||
end, samples, { mutations = 40 })
|
||||
t:fuzz("decode (CRC checked)", function(b: buffer)
|
||||
return Vorbis.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 5, garbage = 20 })
|
||||
t:fuzz("open + seek", function(b: buffer)
|
||||
local d = Vorbis.open(Bytes.reader(b), { verify = false })
|
||||
if d then
|
||||
d:read(500)
|
||||
d:seek(0.05)
|
||||
d:read(500)
|
||||
d:seek(1e9)
|
||||
d:read(10)
|
||||
end
|
||||
return d
|
||||
end, samples, { mutations = 10, garbage = 20 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,110 @@
|
||||
-- audio/vorbis encoder tests: every fixture-step encode (qualities -1 .. 10, mono / stereo / 5.1, 8 .. 96 kHz, odd
|
||||
-- lengths, silence) passes ogginfo, decodes in oggdec (libvorbisfile) with the exact input length and an SNR over a
|
||||
-- per-quality floor, and in ffmpeg; our own decoder gives the same; the codebooks are valid prefix codes; streaming
|
||||
-- from a Decoder gives the same bytes; tags round-trip; option errors. Fixtures: tools/fixtures/vorbis_enc.py.
|
||||
local T = require("@tests/T")
|
||||
local Vorbis = require("@formats/audio/vorbis")
|
||||
local VEnc = require("@formats/audio/vorbis/Encode")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Pcm = require("@formats/codecs/Pcm")
|
||||
local Enc = require("@tests/gen/vorbis_enc")
|
||||
local Sigs = require("@tests/gen/vorbis_enc_sigs")
|
||||
|
||||
local t = T.suite("vorbis_encode")
|
||||
|
||||
local function audio(name: string): Types.Audio
|
||||
local s = Sigs[name]
|
||||
local a = Types.Audio.new(s.rate, s.channels, s.frames)
|
||||
buffer.writestring(a.samples, 0, s.data)
|
||||
return a
|
||||
end
|
||||
local function snr(x: Types.Audio, y: Types.Audio): number
|
||||
local sig, er = 0, 0
|
||||
for i = 0, math.min(x.frames, y.frames) * x.channels - 1 do
|
||||
local a = buffer.readf32(x.samples, i * 4)
|
||||
local d = a - buffer.readf32(y.samples, i * 4)
|
||||
sig += a * a
|
||||
er += d * d
|
||||
end
|
||||
if er == 0 then
|
||||
return 200
|
||||
end
|
||||
return if sig > 0 then 10 * math.log10(sig / er) else -200
|
||||
end
|
||||
local function floorFor(q: number): number
|
||||
return 8 + 1.2 * math.max(q, 0)
|
||||
end
|
||||
|
||||
t:check(Vorbis.caps.encode and Vorbis.encode ~= nil, "caps.encode")
|
||||
|
||||
-- the codebooks: Kraft sums of exactly 1 (complete prefix codes) and lengths 1 .. 24
|
||||
for i, b in VEnc.BOOKS do
|
||||
local k, okLen = 0, true
|
||||
for _, l in b.lengths do
|
||||
k += 2 ^ -l
|
||||
okLen = okLen and l >= 1 and l <= 24
|
||||
end
|
||||
t:check(math.abs(k - 1) < 1e-9 and okLen, "codebook " .. (i - 1) .. ": complete prefix code")
|
||||
end
|
||||
|
||||
local minSnr = math.huge
|
||||
for _, e in Enc do
|
||||
t:eq(e.ogginfo, "", e.name .. ": ogginfo reports no warnings / errors")
|
||||
t:eq(e.oggdecFrames, e.frames, e.name .. ": oggdec frames = input frames")
|
||||
t:eq(e.ffErrors, "", e.name .. ": ffmpeg decodes without errors")
|
||||
local silent = string.find(e.name, "silence", 1, true) ~= nil
|
||||
local f = if silent then -math.huge else floorFor(e.quality)
|
||||
t:check(e.oggdecSnr >= f, string.format("%s: oggdec SNR %.1f dB (floor %.1f)", e.name, e.oggdecSnr, f))
|
||||
if e.frames >= 2048 then
|
||||
-- (ffmpeg does not trim the end of a stream that fits on one Ogg page: up to a block more)
|
||||
t:check(e.ffFrames >= e.frames and e.ffFrames <= e.frames + 1024, string.format("%s: ffmpeg frames %d", e.name, e.ffFrames))
|
||||
t:check(e.ffSnr >= f, string.format("%s: ffmpeg SNR %.1f dB", e.name, e.ffSnr))
|
||||
end
|
||||
if not silent then
|
||||
minSnr = math.min(minSnr, e.oggdecSnr)
|
||||
end
|
||||
-- our decoder: the same length and quality (it is sample-exact with libvorbis)
|
||||
local x = audio(e.sig)
|
||||
local y, err = Vorbis.decode(Bytes.reader(buffer.fromstring(e.data)))
|
||||
t:check(y, e.name .. ": our decoder: " .. tostring(err))
|
||||
t:eq(y.frames, e.frames, e.name .. ": our decoder's frames")
|
||||
local s = snr(x, y)
|
||||
t:check(math.abs(s - e.oggdecSnr) < 0.5 or s >= 100, string.format("%s: our decoder %.1f dB, oggdec %.1f dB", e.name, s, e.oggdecSnr))
|
||||
end
|
||||
t:note("%d encodes pass ogginfo / oggdec / ffmpeg; lowest SNR %.1f dB", #Enc, minSnr)
|
||||
|
||||
-- streaming, tags
|
||||
do
|
||||
local a = audio("music_2_3000_44100")
|
||||
local f1 = Vorbis.encode(a) :: buffer
|
||||
local f2 = Vorbis.encode(Pcm.audioDecoder(a)) :: buffer
|
||||
t:check(buffer.tostring(f1) == buffer.tostring(f2), "Decoder source = Audio source")
|
||||
a.tags = { title = "Tïtle", artist = "Artist", track = "9" }
|
||||
local f3 = Vorbis.encode(a, { quality = 1, serial = 77 }) :: buffer
|
||||
local d = Vorbis.open(Bytes.reader(f3)) :: any
|
||||
t:eq(d.tags.title, "Tïtle", "title tag")
|
||||
t:eq(d.tags.track, "9", "track tag")
|
||||
t:check(string.find(d.vendor, "formats-luau", 1, true) ~= nil, "vendor")
|
||||
local empty = Vorbis.encode(Types.Audio.new(44100, 1, 0)) :: buffer
|
||||
local e0 = Vorbis.decode(Bytes.reader(empty))
|
||||
t:check(e0 and e0.frames == 0, "empty input")
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local a = Types.Audio.new(44100, 2, 10)
|
||||
local function code(v: any, o: any): string?
|
||||
local _, e = Vorbis.encode(v, o)
|
||||
return e and e.code
|
||||
end
|
||||
t:eq(code("x", nil), Err.ARG, "junk")
|
||||
t:eq(code(a, { quality = 11 }), Err.ARG, "quality 11")
|
||||
t:eq(code(a, { quality = -2 }), Err.ARG, "quality -2")
|
||||
t:eq(code(a, { serial = -1 }), Err.ARG, "serial -1")
|
||||
t:eq(code(Types.Audio.new(44100.5, 1, 1), nil), Err.ARG, "fractional rate")
|
||||
end
|
||||
|
||||
-- (the decoder's fuzz pass is in tests/audio/vorbis.luau; the encoder takes no untrusted bytes)
|
||||
t:done()
|
||||
@@ -0,0 +1,182 @@
|
||||
-- codecs/Aac tests: AudioSpecificConfig parsing (every fixture's esds, explicit SBR / PS signalling from fdkaac,
|
||||
-- crafted configs: PCE channel counts, 960-sample frames, Main / LTP object types), ADTS headers, raw frames decoded
|
||||
-- straight from ADTS against ffmpeg's float decode, the FIL extension hook on HE-AAC (implicit SBR), reset, errors,
|
||||
-- the fuzz no-throw pass on raw frames. Fixtures: tools/fixtures/m4a.py.
|
||||
local T = require("@tests/T")
|
||||
local Aac = require("@formats/codecs/Aac")
|
||||
local IsoBmff = require("@formats/containers/IsoBmff")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Bits = require("@formats/core/Bits")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Fx = require("@tests/gen/m4a_aac")
|
||||
local He = require("@tests/gen/m4a_he")
|
||||
|
||||
local t = T.suite("aac-codec")
|
||||
|
||||
-- ADTS frames of a stream: { offset, size } of the raw blocks
|
||||
local function frames(data: buffer): ({ { number } }, Aac.Adts?)
|
||||
local out, p, first = {}, 0, nil
|
||||
while true do
|
||||
local h = Aac.adts(data, p, buffer.len(data))
|
||||
if not h or p + h.frameSize > buffer.len(data) then
|
||||
break
|
||||
end
|
||||
first = first or h
|
||||
table.insert(out, { p + h.headerSize, h.frameSize - h.headerSize })
|
||||
p += h.frameSize
|
||||
end
|
||||
return out, first
|
||||
end
|
||||
|
||||
-- ASCs from the M4A fixtures
|
||||
for _, c in Fx do
|
||||
if c.container == "m4a" then
|
||||
local r = Bytes.reader(buffer.fromstring(c.data))
|
||||
local movie = IsoBmff.parse(r) :: IsoBmff.Movie
|
||||
local cfg, err = Aac.config(movie.tracks[1].config :: buffer)
|
||||
t:check(cfg, c.name .. ": " .. tostring(err))
|
||||
t:check(cfg.objectType == 2 and cfg.sampleRate == c.rate and cfg.channels == c.channels and not cfg.sbr, c.name .. ": AAC-LC config")
|
||||
end
|
||||
end
|
||||
for _, c in He do
|
||||
if string.sub(c.name, -4) == ".m4a" then
|
||||
local r = Bytes.reader(buffer.fromstring(c.data))
|
||||
local movie = IsoBmff.parse(r) :: IsoBmff.Movie
|
||||
local cfg, err = Aac.config(movie.tracks[1].config :: buffer)
|
||||
t:check(cfg, c.name .. ": " .. tostring(err))
|
||||
t:check(cfg.sbr and cfg.sampleRate == c.rate // 2 and cfg.extensionRate == c.rate, c.name .. ": SBR signalled, core at half rate")
|
||||
t:eq(cfg.ps, c.ps, c.name .. ": PS signalled")
|
||||
end
|
||||
end
|
||||
|
||||
-- crafted configs
|
||||
do
|
||||
local asc = Aac.asc(2, 4, 2)
|
||||
local cfg = Aac.config(asc) :: Aac.Config
|
||||
t:check(cfg and cfg.sampleRate == 44100 and cfg.channels == 2, "asc(2, 44.1 kHz, stereo)")
|
||||
local _, e1 = Aac.config(Aac.asc(1, 4, 2))
|
||||
t:check(e1 and e1.code == Err.UNSUPPORTED, "AAC Main: " .. tostring(e1))
|
||||
local _, e2 = Aac.config(Aac.asc(23, 4, 2))
|
||||
t:check(e2 and e2.code == Err.UNSUPPORTED, "ER AAC LD")
|
||||
local b960 = Aac.asc(2, 3, 1)
|
||||
buffer.writeu8(b960, 1, bit32.bor(buffer.readu8(b960, 1), 4)) -- frameLengthFlag
|
||||
local _, e3 = Aac.config(b960)
|
||||
t:check(e3 and e3.code == Err.UNSUPPORTED, "960-sample frames")
|
||||
-- channel configuration 0 with a PCE: front C (SCE) + L/R (CPE), back L/R (CPE), one LFE = 6 channels
|
||||
local bw = Bits.msbWriter()
|
||||
bw:write(2, 5)
|
||||
bw:write(3, 4)
|
||||
bw:write(0, 4)
|
||||
bw:write(0, 3) -- GASpecificConfig flags
|
||||
bw:write(0, 4) -- PCE: tag
|
||||
bw:write(1, 2)
|
||||
bw:write(3, 4)
|
||||
bw:write(2, 4) -- front
|
||||
bw:write(0, 4) -- side
|
||||
bw:write(1, 4) -- back
|
||||
bw:write(1, 2) -- lfe
|
||||
bw:write(0, 3)
|
||||
bw:write(0, 4)
|
||||
bw:write(0, 3) -- mixdowns
|
||||
bw:write(0, 5)
|
||||
bw:write(16 + 1, 5) -- front: SCE 0, CPE 1
|
||||
bw:write(16 + 2, 5) -- back: CPE 2
|
||||
bw:write(0, 4) -- lfe tag
|
||||
bw:align()
|
||||
bw:write(0, 8) -- comment
|
||||
local pcfg, perr = Aac.config(bw:finish())
|
||||
t:check(pcfg and pcfg.channels == 6 and pcfg.channelConfig == 0, "PCE: 6 channels: " .. tostring(perr))
|
||||
local _, e4 = Aac.decoder("nope" :: any)
|
||||
t:check(e4 and e4.code == Err.ARG, "decoder of a string")
|
||||
end
|
||||
|
||||
-- ADTS headers + raw frames against ffmpeg
|
||||
for _, c in Fx do
|
||||
if c.container ~= "adts" then
|
||||
continue
|
||||
end
|
||||
local data = buffer.fromstring(c.data)
|
||||
local list, h = frames(data)
|
||||
t:check(h and h.objectType == 2 and h.sampleRate == c.rate, c.name .. ": ADTS header")
|
||||
local dec = Aac.decoder({ sfIndex = (h :: Aac.Adts).sfIndex, channels = c.channels }) :: Aac.Decoder
|
||||
local ref = buffer.fromstring(c.ref)
|
||||
local sig, err = 0, 0
|
||||
local o = 0
|
||||
for _, f in list do
|
||||
local n, e = dec:decode(data, f[1], f[2])
|
||||
t:check(n == 1024, c.name .. ": frame: " .. tostring(e))
|
||||
for k = 1, 1024 * c.channels do
|
||||
local r = buffer.readf32(ref, o)
|
||||
sig += r * r
|
||||
err += (dec.pcm[k] - r) ^ 2
|
||||
o += 4
|
||||
end
|
||||
end
|
||||
local snr = 10 * math.log10(sig / math.max(err, 1e-30))
|
||||
t:check(snr > 90, string.format("%s: SNR %.1f dB", c.name, snr))
|
||||
t:note("%s: %d raw frames, SNR %.1f dB vs ffmpeg", c.name, #list, snr)
|
||||
-- reset: decoding again from the start gives the same first frames
|
||||
dec:reset()
|
||||
dec:decode(data, list[1][1], list[1][2])
|
||||
local again = table.clone(dec.pcm)
|
||||
local dec2 = Aac.decoder({ sfIndex = (h :: Aac.Adts).sfIndex, channels = c.channels }) :: Aac.Decoder
|
||||
dec2:decode(data, list[1][1], list[1][2])
|
||||
local same = true
|
||||
for k = 1, 1024 * c.channels do
|
||||
same = same and again[k] == dec2.pcm[k]
|
||||
end
|
||||
t:check(same, c.name .. ": reset clears the overlap")
|
||||
end
|
||||
|
||||
-- the extension hook on HE-AAC (implicit SBR in ADTS)
|
||||
for _, c in He do
|
||||
if string.sub(c.name, -4) == ".aac" then
|
||||
local data = buffer.fromstring(c.data)
|
||||
local list, h = frames(data)
|
||||
local dec = Aac.decoder({ sfIndex = (h :: Aac.Adts).sfIndex, channels = 2 }) :: Aac.Decoder
|
||||
local seen, bits = 0, 0
|
||||
dec.onExtension = function(kind: number, _element: number, _buf: buffer, _pos: number, n: number)
|
||||
if kind == 13 or kind == 14 then
|
||||
seen += 1
|
||||
bits += n
|
||||
end
|
||||
end
|
||||
for _, f in list do
|
||||
dec:decode(data, f[1], f[2])
|
||||
end
|
||||
t:check(seen == #list and dec.sbr, string.format("%s: an SBR payload per frame (%d of %d, %d bits)", c.name, seen, #list, bits))
|
||||
end
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local dec = Aac.decoder(Aac.asc(2, 4, 2)) :: Aac.Decoder
|
||||
local _, e = dec:decode(buffer.fromstring("\x20\x00\x00\x00\x00"))
|
||||
t:check(e and e.code == Err.CORRUPT, "garbage frame: " .. tostring(e))
|
||||
local _, e2 = dec:decode(buffer.create(4), 3, 10)
|
||||
t:check(e2 and e2.code == Err.ARG, "range out of the buffer")
|
||||
t:check(Aac.adts(buffer.fromstring("\255\241"), 0, 2) == nil, "short ADTS header")
|
||||
end
|
||||
|
||||
-- fuzz raw frames (stereo with every tool, mono, 5.1)
|
||||
do
|
||||
local pick = {}
|
||||
for _, c in Fx do
|
||||
if c.container == "adts" then
|
||||
local data = buffer.fromstring(c.data)
|
||||
local list, h = frames(data)
|
||||
local f = list[math.min(#list, 9)]
|
||||
local raw = buffer.create(f[2])
|
||||
buffer.copy(raw, 0, data, f[1], f[2])
|
||||
table.insert(pick, { raw, (h :: Aac.Adts).sfIndex, c.channels })
|
||||
end
|
||||
end
|
||||
for _, p in pick do
|
||||
local dec = Aac.decoder({ sfIndex = p[2], channels = p[3] }) :: Aac.Decoder
|
||||
t:fuzz("raw frame " .. p[3] .. " ch", function(b: buffer)
|
||||
return dec:decode(b)
|
||||
end, { p[1] }, { mutations = 60, garbage = 100 })
|
||||
end
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,181 @@
|
||||
-- codecs/Alac tests: encoder -> decoder round trips over silence (zero runs), full-scale noise (uncompressed frames),
|
||||
-- tones, steps, 1 - 8 channels, 16 / 20 / 24 bits, partial and tiny frames, custom frame lengths; ffmpeg's ALAC
|
||||
-- packets (through containers/IsoBmff) decode to the source integers; the magic cookie (plain, behind frma / alac atoms,
|
||||
-- bad versions / depths); errors; the fuzz no-throw pass on packets. Fixtures: tools/fixtures/m4a.py.
|
||||
local T = require("@tests/T")
|
||||
local Alac = require("@formats/codecs/Alac")
|
||||
local IsoBmff = require("@formats/containers/IsoBmff")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Fx = require("@tests/gen/m4a_alac")
|
||||
|
||||
local t = T.suite("alac")
|
||||
local rand = T.rng(42)
|
||||
|
||||
local function roundTrip(label: string, ch: number, bits: number, frames: number, gen: (number, number) -> number, fl: number?)
|
||||
local enc = Alac.encoder({ sampleRate = 44100, channels = ch, bitDepth = bits, frameLength = fl }) :: Alac.Encoder
|
||||
t:check(enc, label .. ": encoder")
|
||||
local per = enc.config.frameLength
|
||||
local src = table.create(frames * ch, 0)
|
||||
for i = 0, frames - 1 do
|
||||
for c = 1, ch do
|
||||
src[i * ch + c] = gen(i, c)
|
||||
end
|
||||
end
|
||||
local packets = {}
|
||||
local bytes = 0
|
||||
local f = 0
|
||||
while f < frames do
|
||||
local n = math.min(per, frames - f)
|
||||
local p, err = enc:encode(src, f * ch + 1, n)
|
||||
t:check(p, label .. ": encode: " .. tostring(err))
|
||||
table.insert(packets, { p, n })
|
||||
bytes += buffer.len(p :: buffer)
|
||||
f += n
|
||||
end
|
||||
local cfg = Alac.config(Alac.cookie(enc.config)) :: Alac.Config
|
||||
t:check(cfg and cfg.maxFrameBytes >= 1 and cfg.channels == ch and cfg.bitDepth == bits, label .. ": cookie")
|
||||
local dec = Alac.decoder(cfg)
|
||||
local ok = true
|
||||
local at = 0
|
||||
for _, pk in packets do
|
||||
local n, err = dec:decode(pk[1])
|
||||
if n ~= pk[2] then
|
||||
ok = false
|
||||
t:check(false, label .. ": decode: " .. tostring(err))
|
||||
break
|
||||
end
|
||||
for k = 1, n * ch do
|
||||
if dec.pcm[k] ~= src[at * ch + k] then
|
||||
ok = false
|
||||
end
|
||||
end
|
||||
at += n
|
||||
end
|
||||
t:check(ok, label .. ": round trip")
|
||||
return bytes / (frames * ch * bits / 8)
|
||||
end
|
||||
|
||||
local peakOf = function(bits: number): number
|
||||
return 2 ^ (bits - 1)
|
||||
end
|
||||
|
||||
for _, bits in { 16, 20, 24 } do
|
||||
local pk = peakOf(bits)
|
||||
for _, ch in { 1, 2, 3, 6, 8 } do
|
||||
local r1 = roundTrip(string.format("tone %d-bit %d ch", bits, ch), ch, bits, 9000, function(i, c)
|
||||
return math.floor(math.sin(i * 0.031 * c) * (pk * 0.6) + math.sin(i * 0.0071) * pk * 0.2)
|
||||
end)
|
||||
if ch == 2 then
|
||||
t:note("%d-bit stereo tone: %.0f%% of PCM", bits, r1 * 100)
|
||||
end
|
||||
end
|
||||
roundTrip(bits .. "-bit silence (zero runs)", 2, bits, 10000, function()
|
||||
return 0
|
||||
end)
|
||||
local r = roundTrip(bits .. "-bit full-scale noise (escape frames)", 2, bits, 5000, function()
|
||||
return rand(2 ^ bits) - pk
|
||||
end)
|
||||
t:check(r < 1.01, bits .. "-bit noise stays near PCM size")
|
||||
roundTrip(bits .. "-bit extremes", 1, bits, 600, function(i)
|
||||
return if i % 2 == 0 then pk - 1 else -pk
|
||||
end)
|
||||
roundTrip(bits .. "-bit sparse clicks (zero runs + values)", 2, bits, 7000, function(i, c)
|
||||
return if i % 997 == c then pk // 3 else 0
|
||||
end)
|
||||
end
|
||||
for _, n in { 1, 2, 3, 5, 9, 17, 4095 } do
|
||||
roundTrip("partial frame of " .. n, 2, 16, n, function(i, c)
|
||||
return (i * 37 + c * 1000) % 3000 - 1500
|
||||
end)
|
||||
end
|
||||
roundTrip("frame length 1024", 2, 16, 5000, function(i)
|
||||
return math.floor(math.sin(i * 0.05) * 10000)
|
||||
end, 1024)
|
||||
roundTrip("identical channels", 2, 16, 5000, function(i)
|
||||
return math.floor(math.sin(i * 0.02) * 20000)
|
||||
end)
|
||||
|
||||
-- ffmpeg's packets
|
||||
for _, c in Fx do
|
||||
if c.container == "m4a" then
|
||||
local r = Bytes.reader(buffer.fromstring(c.data))
|
||||
local movie = IsoBmff.parse(r) :: IsoBmff.Movie
|
||||
local tr = movie.tracks[1]
|
||||
local cfg = Alac.config(tr.config :: buffer) :: Alac.Config
|
||||
t:check(cfg and cfg.bitDepth == c.bits and cfg.channels == c.channels, c.name .. ": cookie")
|
||||
local dec = Alac.decoder(cfg)
|
||||
local out = buffer.create(c.frames * c.channels * 4)
|
||||
local o = 0
|
||||
for i = 1, tr.sampleCount do
|
||||
local n, err = dec:decode(r.buf, tr.offsets[i], tr.sizes[i])
|
||||
t:check(n, c.name .. ": packet " .. i .. ": " .. tostring(err))
|
||||
for k = 1, (n :: number) * c.channels do
|
||||
buffer.writei32(out, o, dec.pcm[k])
|
||||
o += 4
|
||||
end
|
||||
end
|
||||
t:eq(Crc32.of(out), c.crc, c.name .. ": ffmpeg's packets decode to the source")
|
||||
end
|
||||
end
|
||||
|
||||
-- the cookie behind QuickTime atoms, bad cookies
|
||||
do
|
||||
local enc = Alac.encoder({ sampleRate = 48000, channels = 2 }) :: Alac.Encoder
|
||||
local plain = Alac.cookie(enc.config)
|
||||
local w = Bytes.writer(64)
|
||||
w:u32be(12)
|
||||
w:string("frma")
|
||||
w:string("alac")
|
||||
w:u32be(36)
|
||||
w:string("alac")
|
||||
w:u32be(0)
|
||||
w:bytes(plain)
|
||||
local cfg = Alac.config(w:finish())
|
||||
t:check(cfg and cfg.sampleRate == 48000 and cfg.frameLength == 4096, "cookie behind frma / alac atoms")
|
||||
local bad = buffer.fromstring(buffer.tostring(plain))
|
||||
buffer.writeu8(bad, 5, 12)
|
||||
local _, e = Alac.config(bad)
|
||||
t:check(e and e.code == Err.UNSUPPORTED, "12-bit cookie: " .. tostring(e))
|
||||
local _, e2 = Alac.config(buffer.create(10))
|
||||
t:check(e2 and e2.code == Err.TRUNCATED, "short cookie")
|
||||
local _, e3 = Alac.encoder({ sampleRate = 44100, channels = 9 })
|
||||
t:check(e3 and e3.code == Err.ARG, "9 channels")
|
||||
local _, e4 = enc:encode({ 1, 2 }, 1, 5)
|
||||
t:check(e4 and e4.code == Err.ARG, "too few samples")
|
||||
local dec = Alac.decoder(cfg :: Alac.Config)
|
||||
local _, e5 = dec:decode(buffer.fromstring("\1\255\255\255"))
|
||||
t:check(e5 and e5.code == Err.CORRUPT, "bad packet: " .. tostring(e5))
|
||||
end
|
||||
|
||||
-- fuzz the packet decoder
|
||||
do
|
||||
local enc = Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 }) :: Alac.Encoder
|
||||
local src = table.create(2 * 3000, 0)
|
||||
for i = 1, #src do
|
||||
src[i] = math.floor(math.sin(i * 0.01) * 8000) + rand(64)
|
||||
end
|
||||
local samples = {}
|
||||
table.insert(samples, (enc:encode(src, 1, 3000)))
|
||||
for i = 1, #src do
|
||||
src[i] = if i % 300 < 3 then 5000 else 0
|
||||
end
|
||||
table.insert(samples, (enc:encode(src, 1, 3000)))
|
||||
local dec = Alac.decoder(enc.config)
|
||||
local enc24 = Alac.encoder({ sampleRate = 44100, channels = 1, bitDepth = 24 }) :: Alac.Encoder
|
||||
local dec24 = Alac.decoder(enc24.config)
|
||||
local s24 = table.create(2000, 0)
|
||||
for i = 1, 2000 do
|
||||
s24[i] = rand(2 ^ 24) - 2 ^ 23
|
||||
end
|
||||
local p24 = enc24:encode(s24, 1, 2000) :: buffer
|
||||
t:fuzz("decode packet", function(b: buffer)
|
||||
return dec:decode(b)
|
||||
end, samples, { mutations = 40 })
|
||||
t:fuzz("decode 24-bit escape packet", function(b: buffer)
|
||||
return dec24:decode(b)
|
||||
end, { p24 }, { mutations = 20, garbage = 50 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,273 @@
|
||||
-- codecs/Jpeg tests (the Motion-JPEG side; tests/image/jpeg.luau covers the still-image decoder and encoder through
|
||||
-- image/jpeg): ffmpeg mjpeg frames (4:2:0, 4:2:2, 4:4:4, odd sizes, stripped DHT, AVI1 + junk after EOI) decoded
|
||||
-- to yuv420p bit-exact with libjpeg-turbo's IDCT planes (TurboJPEG) and to rgba8 bit-exact with djpeg, and within
|
||||
-- PSNR thresholds of ffmpeg's own decode; an interlaced AVI1 frame (two fields) woven; the yuv420p encoder
|
||||
-- byte-identical to TurboJPEG's tj3CompressFromYUV8, read back by djpeg (exact) and ffmpeg (PSNR); the API's
|
||||
-- arguments; the fuzz no-throw pass. Fixtures: tools/fixtures/mjpeg.py.
|
||||
local T = require("@tests/T")
|
||||
local Jpeg = require("@formats/codecs/Jpeg")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Base64 = require("@formats/core/Base64")
|
||||
local Deflate = require("@formats/codecs/Deflate")
|
||||
local Fx = require("@tests/gen/mjpeg_cases")
|
||||
local Enc = require("@tests/gen/mjpeg_enc")
|
||||
|
||||
local t = T.suite("codecs/jpeg")
|
||||
|
||||
-- the fixtures' binary fields: base64, and base64 of zlib data for raw planes / pixels
|
||||
local function b64(s: string): string
|
||||
return buffer.tostring(Base64.decode(s) :: buffer)
|
||||
end
|
||||
local function z64(s: string): buffer
|
||||
return Deflate.zlib(Base64.decode(s) :: buffer) :: buffer
|
||||
end
|
||||
for _, s in Fx.streams do
|
||||
for _, f in s.frames do
|
||||
f.data = b64(f.data)
|
||||
end
|
||||
s.ff.yuv = z64(s.ff.yuv)
|
||||
if s.ff.rgba then
|
||||
s.ff.rgba = z64(s.ff.rgba)
|
||||
end
|
||||
end
|
||||
Fx.fields.data = b64(Fx.fields.data)
|
||||
for _, c in Enc do
|
||||
c.want = b64(c.want)
|
||||
end
|
||||
|
||||
-- PSNR of n bytes of a at ao against b at bo
|
||||
local function psnr(a: buffer, ao: number, b: buffer, bo: number, n: number): number
|
||||
local se = 0
|
||||
for i = 0, n - 1 do
|
||||
local d = buffer.readu8(a, ao + i) - buffer.readu8(b, bo + i)
|
||||
se += d * d
|
||||
end
|
||||
if se == 0 then
|
||||
return 99
|
||||
end
|
||||
return 10 * math.log10(255 * 255 * n / se)
|
||||
end
|
||||
|
||||
-- PSNR of the RGB channels of two rgba8 buffers of n pixels
|
||||
local function psnrRgb(a: buffer, b: buffer, n: number): number
|
||||
local se = 0
|
||||
for i = 0, n - 1 do
|
||||
for k = 0, 2 do
|
||||
local d = buffer.readu8(a, i * 4 + k) - buffer.readu8(b, i * 4 + k)
|
||||
se += d * d
|
||||
end
|
||||
end
|
||||
if se == 0 then
|
||||
return 99
|
||||
end
|
||||
return 10 * math.log10(255 * 255 * n * 3 / se)
|
||||
end
|
||||
|
||||
local function hasDht(s: string): boolean
|
||||
local at = string.find(s, "\255\196", 1, true)
|
||||
local sos = string.find(s, "\255\218", 1, true)
|
||||
return at ~= nil and sos ~= nil and at < sos
|
||||
end
|
||||
|
||||
-- 1. ffmpeg's frames: yuv420p (TurboJPEG planes) and rgba8 (djpeg) bit-exact, PSNR against ffmpeg's decode
|
||||
do
|
||||
local frames, worstY, worstC, worstRgb = 0, 99, 99, 99
|
||||
for _, s in Fx.streams do
|
||||
local w, h = s.width, s.height
|
||||
local cw, ch = (w + 1) // 2, (h + 1) // 2
|
||||
for i, f in s.frames do
|
||||
local label = string.format("%s frame %d", s.name, i)
|
||||
local b = buffer.fromstring(f.data)
|
||||
local img, err = Jpeg.decode(b, 0, buffer.len(b), { yuv = true })
|
||||
t:check(img, label .. ": " .. tostring(err))
|
||||
t:check(img.format == "yuv420p" and img.width == w and img.height == h, label .. ": a yuv420p " .. w .. "x" .. h .. " Image")
|
||||
t:eq(buffer.len(img.pixels), w * h + 2 * cw * ch, label .. ": plane sizes")
|
||||
t:check(img.meta.source.yuv == s.sampling and img.meta.source.range == "full", label .. ": meta.source.yuv " .. tostring(img.meta.source.yuv))
|
||||
t:check(not img.meta.truncated, label .. ": not truncated")
|
||||
t:eq(Crc32.of(img.pixels), f.yuv, label .. ": yuv420p planes = TurboJPEG's")
|
||||
local rgba = Jpeg.decode(b) :: Types.Image
|
||||
t:check(rgba and rgba.format == "rgba8", label .. ": rgba8")
|
||||
t:eq(Crc32.of(rgba.pixels), f.rgba, label .. ": rgba8 = djpeg")
|
||||
if i == 1 then
|
||||
local ref = s.ff.yuv
|
||||
local py = psnr(img.pixels, 0, ref, 0, w * h)
|
||||
local pc = math.min(psnr(img.pixels, w * h, ref, w * h, cw * ch), psnr(img.pixels, w * h + cw * ch, ref, w * h + cw * ch, cw * ch))
|
||||
-- ffmpeg's IDCT differs from libjpeg's islow by rounding only; its 4:2:2 / 4:4:4 -> 4:2:0 is a filter
|
||||
t:check(py > 55, string.format("%s: luma PSNR %.1f dB against ffmpeg", s.name, py))
|
||||
t:check(pc > (if s.sampling == "420" then 55 else 20), string.format("%s: chroma PSNR %.1f dB against ffmpeg", s.name, pc))
|
||||
worstY, worstC = math.min(worstY, py), math.min(worstC, pc)
|
||||
if s.ff.rgba then
|
||||
local pr = psnrRgb(rgba.pixels, s.ff.rgba, w * h)
|
||||
-- swscale upsamples chroma differently from libjpeg (fancy): testsrc2's sharp colour edges cost ~10 dB
|
||||
t:check(pr > 25, string.format("%s: rgba PSNR %.1f dB against ffmpeg", s.name, pr))
|
||||
worstRgb = math.min(worstRgb, pr)
|
||||
end
|
||||
end
|
||||
if string.find(s.name, "nodht") then
|
||||
t:check(not hasDht(f.data), label .. ": no DHT segment")
|
||||
end
|
||||
if s.name == "avi1_junk" then
|
||||
t:eq(img.meta.source.avi1, 0, label .. ": AVI1 polarity")
|
||||
t:eq(Jpeg.info(b).avi1, 0, label .. ": info.avi1")
|
||||
end
|
||||
frames += 1
|
||||
end
|
||||
end
|
||||
t:note("%d ffmpeg mjpeg frames bit-exact (yuv420p: TurboJPEG, rgba8: djpeg); worst PSNR against ffmpeg: luma %.1f, chroma %.1f, rgba %.1f dB", frames, worstY, worstC, worstRgb)
|
||||
end
|
||||
|
||||
-- 2. an interlaced frame: two fields (AVI1 polarity 1) woven, field 1 on the even rows
|
||||
do
|
||||
local F = Fx.fields
|
||||
local b = buffer.fromstring(F.data)
|
||||
local img = Jpeg.decode(b, 0, nil, { yuv = true }) :: Types.Image
|
||||
t:check(img and img.width == F.width and img.height == F.height and img.format == "yuv420p", "fields: one 320x240 yuv420p frame")
|
||||
t:eq(img.meta.source.fields, 2, "fields: meta.source.fields")
|
||||
t:eq(Crc32.of(img.pixels), F.yuv, "fields: woven yuv420p planes = TurboJPEG's fields woven")
|
||||
local src = z64(F.src)
|
||||
local p = psnr(img.pixels, 0, src, 0, F.width * F.height)
|
||||
t:check(p > 35, string.format("fields: luma PSNR %.1f dB against the source frame", p))
|
||||
local rgba = Jpeg.decode(b) :: Types.Image
|
||||
t:check(rgba.height == F.height and Crc32.of(rgba.pixels) == F.rgba, "fields: woven rgba8 = djpeg's fields woven")
|
||||
local one = Jpeg.decode(b, 0, nil, { yuv = true, fields = false }) :: Types.Image
|
||||
t:check(one.height == F.height // 2 and one.meta.source.fields == 1, "fields = false: the first field only")
|
||||
-- the first field alone (no second JPEG): a half-height frame, not an error
|
||||
local first = string.find(F.data, "\255\217", 1, true) :: number
|
||||
local half = Jpeg.decode(buffer.fromstring(string.sub(F.data, 1, first + 1)), 0, nil, { yuv = true }) :: Types.Image
|
||||
t:check(half and half.height == F.height // 2 and half.meta.source.fields == 1, "a missing second field leaves the first")
|
||||
t:check(Jpeg.info(b).avi1 == 1, "fields: info.avi1")
|
||||
end
|
||||
|
||||
-- 3. the yuv420p encoder: byte-identical with TurboJPEG, read back by djpeg (exact) and ffmpeg (PSNR)
|
||||
do
|
||||
local exact = 0
|
||||
for _, c in Enc do
|
||||
local img = Types.Image.new(c.width, c.height, "yuv420p")
|
||||
img.pixels = z64(c.yuv)
|
||||
local out, err = Jpeg.encode(img, { quality = c.quality })
|
||||
t:check(out, c.name .. ": " .. tostring(err))
|
||||
local s = buffer.tostring(out :: buffer)
|
||||
if s ~= c.want then
|
||||
local at = 0
|
||||
for i = 1, math.min(#s, #c.want) do
|
||||
if string.byte(s, i) ~= string.byte(c.want, i) then
|
||||
at = i
|
||||
break
|
||||
end
|
||||
end
|
||||
t:check(false, string.format("%s: differs from tj3CompressFromYUV8 at byte %d (ours %d bytes, TurboJPEG %d)", c.name, at, #s, #c.want))
|
||||
end
|
||||
exact += 1
|
||||
local back = Jpeg.decode(out :: buffer) :: Types.Image
|
||||
t:eq(Crc32.of(back.pixels), c.rgba, c.name .. ": our decode of it = djpeg's")
|
||||
local floor = if c.quality >= 75 then 30 else 26
|
||||
if c.width * c.height >= 1000 then
|
||||
t:check(c.ffpsnr > floor, string.format("%s: ffmpeg reads it at %.1f dB luma PSNR", c.name, c.ffpsnr))
|
||||
local y = Jpeg.decode(out :: buffer, 0, nil, { yuv = true }) :: Types.Image
|
||||
local p = psnr(y.pixels, 0, img.pixels, 0, c.width * c.height)
|
||||
t:check(p > floor, string.format("%s: yuv round trip %.1f dB", c.name, p))
|
||||
end
|
||||
end
|
||||
t:note("%d yuv420p encodes byte-identical with tj3CompressFromYUV8", exact)
|
||||
-- grey from yuv420p: the luma plane only
|
||||
local c = Enc[1]
|
||||
local img = Types.Image.new(c.width, c.height, "yuv420p")
|
||||
img.pixels = z64(c.yuv)
|
||||
local g = Jpeg.encode(img, { quality = 80, gray = true }) :: buffer
|
||||
local gi = Jpeg.info(g)
|
||||
t:check(gi and gi.components == 1, "yuv420p with gray = true: one component")
|
||||
local gy = Jpeg.decode(g, 0, nil, { yuv = true }) :: Types.Image
|
||||
t:check(gy.format == "yuv420p" and gy.meta.source.yuv == "gray" and buffer.readu8(gy.pixels, c.width * c.height) == 128, "grey decodes to yuv420p with chroma 128")
|
||||
local p = Jpeg.encode(img, { quality = 80, progressive = true, restart = 2 }) :: buffer
|
||||
local pi = Jpeg.info(p)
|
||||
t:check(pi and pi.progressive and pi.sampling[1][1] == 2 and pi.sampling[1][2] == 2, "yuv420p progressive")
|
||||
local pd = Jpeg.decode(p, 0, nil, { yuv = true }) :: Types.Image
|
||||
t:check(psnr(pd.pixels, 0, img.pixels, 0, c.width * c.height) > 30, "yuv420p progressive round trip")
|
||||
local s4 = Jpeg.encode(img, { subsampling = "444" }) :: buffer
|
||||
t:eq(Jpeg.info(s4).sampling[1][1], 2, "yuv420p input is always 4:2:0")
|
||||
-- extra segments and density
|
||||
local seg = Jpeg.encode(img, { segments = { { marker = 0xFE, data = buffer.fromstring("hello") } }, density = { unit = 1, x = 72, y = 72 } }) :: buffer
|
||||
local sd = Jpeg.decode(seg) :: Types.Image
|
||||
t:check(sd.meta.text and sd.meta.text.comment == "hello" and sd.meta.dpi and sd.meta.dpi.x == 72, "segments and density")
|
||||
end
|
||||
|
||||
-- 4. the API: ranges, options, fallbacks, errors
|
||||
do
|
||||
local s = Fx.streams[1]
|
||||
local data = s.frames[1].data
|
||||
local big = buffer.create(#data + 30)
|
||||
buffer.writestring(big, 17, data)
|
||||
local a = Jpeg.decode(big, 17, #data, { yuv = true }) :: Types.Image
|
||||
t:eq(Crc32.of(a.pixels), s.frames[1].yuv, "decode from a sub-range")
|
||||
local i = Jpeg.info(big, 17, #data)
|
||||
t:check(i and i.width == s.width and i.colorSpace == "ycbcr" and i.sampling[1][2] == 2, "info from a sub-range")
|
||||
local sc = Jpeg.decode(buffer.fromstring(data), 0, nil, { yuv = true, scale = 2 }) :: Types.Image
|
||||
t:check(sc.format == "rgba8" and sc.width == s.width // 2, "yuv with scale 2 falls back to rgba8")
|
||||
local _, e1 = Jpeg.decode("nope" :: any)
|
||||
t:check(e1 and e1.code == Err.ARG, "decode(string)")
|
||||
local _, e2 = Jpeg.decode(buffer.fromstring("nope"))
|
||||
t:check(e2 and e2.code == Err.CORRUPT, "junk")
|
||||
local _, e3 = Jpeg.decode(buffer.fromstring(data), 0, nil, { maxPixels = 100, yuv = true })
|
||||
t:check(e3 and e3.code == Err.LIMIT, "maxPixels")
|
||||
local _, e4 = Jpeg.decode(buffer.fromstring(data), 0, nil, 5 :: any)
|
||||
t:check(e4 and e4.code == Err.ARG, "non-table options")
|
||||
local _, e5 = Jpeg.encode(Types.Image.new(4, 4, "rgba16"))
|
||||
t:check(e5 and e5.code == Err.ARG, "rgba16 is refused")
|
||||
local short = Types.Image.new(8, 8, "yuv420p")
|
||||
short.pixels = buffer.create(70)
|
||||
local _, e6 = Jpeg.encode(short)
|
||||
t:check(e6 and e6.code == Err.ARG, "a short yuv420p buffer")
|
||||
local _, e7 = Jpeg.encode(Types.Image.new(8, 8), { segments = { { marker = 0xC4, data = buffer.create(1) } } })
|
||||
t:check(e7 and e7.code == Err.ARG, "a bad segment marker")
|
||||
local _, e8 = Jpeg.info(buffer.create(0))
|
||||
t:check(e8 and Err.is(e8), "info of nothing")
|
||||
-- truncated frames decode as far as they go or fail with an Err
|
||||
local cuts, partial = 0, 0
|
||||
for cut = 0, #data - 1, #data // 37 do
|
||||
local img, err = Jpeg.decode(buffer.fromstring(string.sub(data, 1, cut)), 0, nil, { yuv = true })
|
||||
t:check(img or Err.is(err), "cut at " .. cut .. ": no image and no Err")
|
||||
if img then
|
||||
partial += 1
|
||||
t:check(img.meta.truncated, "cut at " .. cut .. ": flagged truncated")
|
||||
end
|
||||
cuts += 1
|
||||
end
|
||||
t:note("%d truncated frames, %d decoded partially", cuts, partial)
|
||||
end
|
||||
|
||||
-- 5. speed (a note; tools/bench.luau has the real numbers)
|
||||
do
|
||||
local s = Fx.streams[1]
|
||||
local frames = {}
|
||||
for _, f in s.frames do
|
||||
table.insert(frames, buffer.fromstring(f.data))
|
||||
end
|
||||
local t0, n = os.clock(), 0
|
||||
while os.clock() - t0 < 0.3 do
|
||||
for _, b in frames do
|
||||
Jpeg.decode(b, 0, nil, { yuv = true })
|
||||
n += 1
|
||||
end
|
||||
end
|
||||
t:note("%dx%d yuv420p decode: %.0f fps", s.width, s.height, n / (os.clock() - t0))
|
||||
end
|
||||
|
||||
-- 6. fuzz
|
||||
do
|
||||
local samples = {}
|
||||
for k, s in Fx.streams do
|
||||
if k % 2 == 1 then
|
||||
table.insert(samples, s.frames[1].data)
|
||||
end
|
||||
end
|
||||
t:fuzz("decode yuv", function(b: buffer)
|
||||
return Jpeg.decode(b, 0, nil, { yuv = true })
|
||||
end, samples, { mutations = 4, keepHeader = 2 })
|
||||
t:fuzz("decode fields", function(b: buffer)
|
||||
return Jpeg.decode(b, 0, nil, { fields = true })
|
||||
end, { Fx.fields.data }, { mutations = 3, garbage = 10 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,134 @@
|
||||
-- codecs/Mdct tests: the FFT against a direct DFT for mixed-radix sizes, the forward / inverse MDCT and the DCT-IV
|
||||
-- against their O(N^2) definitions (AAC, Vorbis and CELT sizes), perfect reconstruction (TDAC) with the sine, KBD and
|
||||
-- Vorbis windows, window power complementarity, bad sizes. No fixtures (the definitions are the reference).
|
||||
local T = require("@tests/T")
|
||||
local Mdct = require("@formats/codecs/Mdct")
|
||||
|
||||
local t = T.suite("mdct")
|
||||
local rand = T.rng(7)
|
||||
local cos, sin, pi = math.cos, math.sin, math.pi
|
||||
|
||||
local function noise(n: number): { number }
|
||||
local a = table.create(n, 0)
|
||||
for i = 1, n do
|
||||
a[i] = rand(20001) / 10000 - 1
|
||||
end
|
||||
return a
|
||||
end
|
||||
|
||||
-- FFT vs DFT
|
||||
for _, n in { 1, 2, 3, 4, 5, 6, 7, 8, 12, 15, 16, 30, 49, 60, 64, 120, 240, 480, 77 } do
|
||||
local plan = Mdct.fft(n)
|
||||
t:check(plan, "fft plan " .. n)
|
||||
local re, im = noise(n), noise(n)
|
||||
local wr, wi = table.create(n, 0), table.create(n, 0)
|
||||
for k = 0, n - 1 do
|
||||
local sr, si = 0, 0
|
||||
for j = 0, n - 1 do
|
||||
local a = -2 * pi * j * k / n
|
||||
sr += re[j + 1] * cos(a) - im[j + 1] * sin(a)
|
||||
si += re[j + 1] * sin(a) + im[j + 1] * cos(a)
|
||||
end
|
||||
wr[k + 1], wi[k + 1] = sr, si
|
||||
end
|
||||
Mdct.Fft.forward(plan :: any, re, im)
|
||||
local err = 0
|
||||
for k = 1, n do
|
||||
err = math.max(err, math.abs(re[k] - wr[k]), math.abs(im[k] - wi[k]))
|
||||
end
|
||||
t:check(err < 1e-9 * n, string.format("fft %d: max error %g", n, err))
|
||||
end
|
||||
|
||||
-- MDCT / IMDCT vs the definitions
|
||||
local maxErr = 0
|
||||
for _, n in { 4, 8, 16, 64, 240, 256, 480, 1920, 2048 } do
|
||||
local plan = Mdct.new(n) :: Mdct.Plan
|
||||
t:check(plan, "mdct plan " .. n)
|
||||
local m = n // 2
|
||||
local x = noise(n)
|
||||
local X = table.create(m, 0)
|
||||
Mdct.forward(plan, x, 1, X, 1)
|
||||
local Y = noise(m)
|
||||
local y = table.create(n, 0)
|
||||
Mdct.inverse(plan, Y, 1, 1, y, 1)
|
||||
local step = if n > 500 then 37 else 1 -- spot-check the big sizes
|
||||
local ef, ei = 0, 0
|
||||
for k = 0, m - 1, step do
|
||||
local s = 0
|
||||
for j = 0, n - 1 do
|
||||
s += x[j + 1] * cos(2 * pi / n * (j + 0.5 + n / 4) * (k + 0.5))
|
||||
end
|
||||
ef = math.max(ef, math.abs(s - X[k + 1]))
|
||||
end
|
||||
for j = 0, n - 1, step do
|
||||
local s = 0
|
||||
for k = 0, m - 1 do
|
||||
s += Y[k + 1] * cos(2 * pi / n * (j + 0.5 + n / 4) * (k + 0.5))
|
||||
end
|
||||
ei = math.max(ei, math.abs(s - y[j + 1]))
|
||||
end
|
||||
t:check(ef < 1e-9 * n and ei < 1e-9 * n, string.format("mdct %d: forward error %g, inverse error %g", n, ef, ei))
|
||||
maxErr = math.max(maxErr, ef, ei)
|
||||
-- strided coefficients + offsets + scale
|
||||
local X2 = table.create(m * 3 + 5, 0)
|
||||
Mdct.forward(plan, x, 1, X2, 3, 3, 0.5)
|
||||
local ok = true
|
||||
for k = 0, m - 1 do
|
||||
ok = ok and math.abs(X2[3 + 3 * k] - 0.5 * X[k + 1]) < 1e-9
|
||||
end
|
||||
t:check(ok, "mdct " .. n .. ": strided / scaled forward")
|
||||
end
|
||||
t:note("mdct vs definition: max error %.3g", maxErr)
|
||||
|
||||
-- TDAC: windowed forward + inverse + overlap-add reproduces the signal
|
||||
for _, kind in { "sine", "kbd", "vorbis" } do
|
||||
for _, n in { 256, 2048, 240 } do
|
||||
local w = Mdct.window(kind, n, if n == 256 then 6 else 4) :: { number }
|
||||
local m = n // 2
|
||||
local plan = Mdct.new(n) :: Mdct.Plan
|
||||
local pc = 0
|
||||
for i = 1, m do
|
||||
pc = math.max(pc, math.abs(w[i] ^ 2 + w[i + m] ^ 2 - 1))
|
||||
end
|
||||
t:check(pc < 1e-12, kind .. " " .. n .. ": power complementary")
|
||||
local frames = 6
|
||||
local sig = noise(m * (frames + 1))
|
||||
local out = table.create(m * (frames + 1), 0)
|
||||
local buf, X, y = table.create(n, 0), table.create(m, 0), table.create(n, 0)
|
||||
for f = 0, frames - 1 do
|
||||
for i = 1, n do
|
||||
buf[i] = sig[f * m + i] * w[i]
|
||||
end
|
||||
Mdct.forward(plan, buf, 1, X, 1)
|
||||
Mdct.inverse(plan, X, 1, 1, y, 1, 4 / n)
|
||||
for i = 1, n do
|
||||
out[f * m + i] += y[i] * w[i]
|
||||
end
|
||||
end
|
||||
local e = 0
|
||||
for i = m + 1, m * frames do
|
||||
e = math.max(e, math.abs(out[i] - sig[i]))
|
||||
end
|
||||
t:check(e < 1e-9, string.format("%s %d: reconstruction error %g", kind, n, e))
|
||||
end
|
||||
end
|
||||
|
||||
-- DCT-IV is its own inverse (times 2 / M)
|
||||
do
|
||||
local plan = Mdct.new(512) :: Mdct.Plan
|
||||
local u = noise(256)
|
||||
local c, back = table.create(256, 0), table.create(256, 0)
|
||||
Mdct.dct4(plan, u, 1, 1, c, 1, 1)
|
||||
Mdct.dct4(plan, c, 1, 1, back, 1, 1, 2 / 256)
|
||||
local e = 0
|
||||
for i = 1, 256 do
|
||||
e = math.max(e, math.abs(back[i] - u[i]))
|
||||
end
|
||||
t:check(e < 1e-10, "dct4 involution: " .. e)
|
||||
end
|
||||
|
||||
-- bad sizes
|
||||
t:check(Mdct.new(6) == nil and Mdct.new(0) == nil and Mdct.new(-8) == nil and Mdct.new(8.5) == nil and Mdct.new("x" :: any) == nil, "bad mdct sizes")
|
||||
t:check(Mdct.fft(0) == nil and Mdct.window("nope", 8) == nil and Mdct.window("sine", 7) == nil, "bad fft sizes / windows")
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,413 @@
|
||||
-- codecs/Mpeg1 tests, ported from mpeg1-luau tests/decode.luau and tests/robust.luau. Against ffmpeg
|
||||
-- (tools/fixtures/mpeg1.py): every stream decodes, one access unit at a time, to as many frames as ffmpeg's decode,
|
||||
-- in display order; each frame's RGBA channel means within 1.5 of ffmpeg's; whole sampled frames within 2 MAE per
|
||||
-- channel (IDCT and colour rounding) and, as yuv420p (frameImage), within a PSNR floor of ffmpeg -pix_fmt yuv420p;
|
||||
-- the same stream written in random pieces through write() / decodeFrame() gives identical frames; a size change.
|
||||
-- Robustness / API: bad arguments, pictures before the first sequence header, reset(), rgba = false, tags through
|
||||
-- B-frame reordering, string input, truncated units, bit flips and garbage (never throws, recovers at an
|
||||
-- I-picture), an oversized sequence header; frameImage; the fuzz no-throw pass.
|
||||
local T = require("@tests/T")
|
||||
local Mpeg1 = require("@formats/codecs/Mpeg1")
|
||||
local Base64 = require("@formats/core/Base64")
|
||||
local Deflate = require("@formats/codecs/Deflate")
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local STREAMS = {
|
||||
require("@tests/gen/mpeg1_qcif_200k"),
|
||||
require("@tests/gen/mpeg1_main_450k"),
|
||||
require("@tests/gen/mpeg1_zoom_150k"),
|
||||
require("@tests/gen/mpeg1_zoom_1500k"),
|
||||
require("@tests/gen/mpeg1_big_1000k"),
|
||||
require("@tests/gen/mpeg1_odd_173x95"),
|
||||
require("@tests/gen/mpeg1_matrix"),
|
||||
require("@tests/gen/mpeg1_q1"),
|
||||
require("@tests/gen/mpeg1_q31"),
|
||||
require("@tests/gen/mpeg1_zeromv"),
|
||||
require("@tests/gen/mpeg1_bframes"),
|
||||
require("@tests/gen/mpeg1_bframes_zoom"),
|
||||
}
|
||||
local SizeChange = require("@tests/gen/mpeg1_sizechange")
|
||||
|
||||
local t = T.suite("codecs/mpeg1")
|
||||
local rand = T.rng(7)
|
||||
local function between(a: number, b: number): number
|
||||
return a + rand(b - a + 1)
|
||||
end
|
||||
|
||||
local function b64(s: string): buffer
|
||||
return Base64.decode(s) :: buffer
|
||||
end
|
||||
local function z64(s: string): buffer
|
||||
return Deflate.zlib(b64(s)) :: buffer
|
||||
end
|
||||
|
||||
-- mean absolute error per channel (r, g, b) between two RGBA8 buffers of n pixels, and the largest difference
|
||||
local function mae(a: buffer, b: buffer, n: number): (number, number, number, number)
|
||||
local sr, sg, sb, mx = 0, 0, 0, 0
|
||||
for i = 0, n - 1 do
|
||||
local o = i * 4
|
||||
local dr = math.abs(buffer.readu8(a, o) - buffer.readu8(b, o))
|
||||
local dg = math.abs(buffer.readu8(a, o + 1) - buffer.readu8(b, o + 1))
|
||||
local db = math.abs(buffer.readu8(a, o + 2) - buffer.readu8(b, o + 2))
|
||||
sr += dr
|
||||
sg += dg
|
||||
sb += db
|
||||
mx = math.max(mx, dr, dg, db)
|
||||
end
|
||||
return sr / n, sg / n, sb / n, mx
|
||||
end
|
||||
|
||||
local function means(a: buffer, n: number): (number, number, number)
|
||||
local r, g, b = 0, 0, 0
|
||||
for i = 0, n - 1 do
|
||||
local o = i * 4
|
||||
r += buffer.readu8(a, o)
|
||||
g += buffer.readu8(a, o + 1)
|
||||
b += buffer.readu8(a, o + 2)
|
||||
end
|
||||
return r / n, g / n, b / n
|
||||
end
|
||||
|
||||
local function psnr(a: buffer, ao: number, b: buffer, bo: number, n: number): number
|
||||
local se = 0
|
||||
for i = 0, n - 1 do
|
||||
local d = buffer.readu8(a, ao + i) - buffer.readu8(b, bo + i)
|
||||
se += d * d
|
||||
end
|
||||
if se == 0 then
|
||||
return 99
|
||||
end
|
||||
return 10 * math.log10(255 * 255 * n / se)
|
||||
end
|
||||
|
||||
local MAE_LIMIT = 2
|
||||
local MEAN_LIMIT = 1.5
|
||||
|
||||
-- 1. every stream against ffmpeg
|
||||
local worst, worstY, worstC = 0, 99, 99
|
||||
for _, fx in STREAMS do
|
||||
local name = fx.name
|
||||
local file = b64(fx.file)
|
||||
local w, h = fx.width, fx.height
|
||||
local n = w * h
|
||||
local cw, ch = (w + 1) // 2, (h + 1) // 2
|
||||
local rgbaRef, yuvRef = {}, {}
|
||||
for _, s in fx.rgba do
|
||||
rgbaRef[s.index] = z64(s.pixels)
|
||||
end
|
||||
for _, s in fx.yuv do
|
||||
yuvRef[s.index] = z64(s.planes)
|
||||
end
|
||||
local hasB = string.find(name, "bframes") ~= nil
|
||||
local dec = Mpeg1.new({ reorder = hasB })
|
||||
local frames = 0
|
||||
local maxMae, maxMeanErr = 0, 0
|
||||
local sums = {}
|
||||
local function onFrame(f: any)
|
||||
frames += 1
|
||||
t:check(f.width == w and f.height == h, string.format("%s: size %dx%d", name, f.width, f.height))
|
||||
t:eq(f.index, frames, name .. ": frame index")
|
||||
local px = f.pixels :: buffer
|
||||
t:eq(buffer.len(px), n * 4, name .. ": pixels size")
|
||||
local ref = fx.means[frames]
|
||||
t:check(ref ~= nil, string.format("%s: more frames than ffmpeg (%d)", name, frames))
|
||||
local r, g, b = means(px, n)
|
||||
local me = math.max(math.abs(r - ref[1]), math.abs(g - ref[2]), math.abs(b - ref[3]))
|
||||
maxMeanErr = math.max(maxMeanErr, me)
|
||||
t:check(me <= MEAN_LIMIT, string.format("%s frame %d: channel means off by %.2f", name, frames, me))
|
||||
local s = rgbaRef[frames]
|
||||
if s then
|
||||
local mr, mg, mb = mae(px, s, n)
|
||||
local m = math.max(mr, mg, mb)
|
||||
maxMae = math.max(maxMae, m)
|
||||
t:check(m <= MAE_LIMIT, string.format("%s frame %d: MAE %.3f %.3f %.3f", name, frames, mr, mg, mb))
|
||||
local again = Mpeg1.frameImage(f, true) :: Types.Image
|
||||
t:check(again.format == "rgba8" and buffer.tostring(again.pixels) == buffer.tostring(px), name .. ": frameImage(f, true) = frame.pixels")
|
||||
end
|
||||
local y = yuvRef[frames]
|
||||
if y then
|
||||
local img = Mpeg1.frameImage(f) :: Types.Image
|
||||
t:check(img.format == "yuv420p" and img.width == w and img.height == h and buffer.len(img.pixels) == n + 2 * cw * ch, name .. ": frameImage yuv420p")
|
||||
t:check(img.meta.source.range == "limited" and img.meta.source.pictureType == f.pictureType, name .. ": frameImage meta")
|
||||
local py = psnr(img.pixels, 0, y, 0, n)
|
||||
local pc = psnr(img.pixels, n, y, n, 2 * cw * ch)
|
||||
worstY, worstC = math.min(worstY, py), math.min(worstC, pc)
|
||||
t:check(py > 50 and pc > 50, string.format("%s frame %d: yuv420p PSNR %.1f / %.1f dB against ffmpeg", name, frames, py, pc))
|
||||
end
|
||||
t:check(buffer.readu8(px, 3) == 255 and buffer.readu8(px, n * 4 - 1) == 255, "alpha 255")
|
||||
sums[frames] = buffer.tostring(px)
|
||||
end
|
||||
local t0 = os.clock()
|
||||
for _, u in fx.units do
|
||||
local f = dec:decode(file, u[1], u[2])
|
||||
if f then
|
||||
onFrame(f)
|
||||
end
|
||||
end
|
||||
while true do
|
||||
local f = dec:flush()
|
||||
if f == nil then
|
||||
break
|
||||
end
|
||||
onFrame(f)
|
||||
end
|
||||
local dt = os.clock() - t0
|
||||
t:eq(frames, fx.frames, name .. ": frames (ffmpeg's count)")
|
||||
t:eq(dec.stats.errors, 0, name .. ": no bitstream errors")
|
||||
worst = math.max(worst, maxMae)
|
||||
t:note("%-13s %4dx%-4d %3d frames worst MAE %.3f means err %.3f %6.1f fps (with the checks)", name, w, h, frames, maxMae, maxMeanErr, frames / dt)
|
||||
|
||||
-- streamed: random pieces through write / decodeFrame, then flush
|
||||
local d2 = Mpeg1.new({ reorder = hasB })
|
||||
local got = 0
|
||||
local p, total = 0, buffer.len(file)
|
||||
local function take(f: any)
|
||||
got += 1
|
||||
t:check(sums[got] == buffer.tostring(f.pixels :: buffer), string.format("%s streamed frame %d identical", name, got))
|
||||
end
|
||||
while p < total do
|
||||
local k = math.min(total - p, between(1, 6000))
|
||||
t:check(d2:write(file, p, k), "write")
|
||||
p += k
|
||||
while true do
|
||||
local f = d2:decodeFrame()
|
||||
if f == nil then
|
||||
break
|
||||
end
|
||||
take(f)
|
||||
end
|
||||
end
|
||||
while true do
|
||||
local f = d2:flush()
|
||||
if f == nil then
|
||||
break
|
||||
end
|
||||
take(f)
|
||||
end
|
||||
t:eq(got, frames, name .. ": streamed frame count")
|
||||
end
|
||||
t:note("worst sampled-frame MAE %.3f (limit %d); worst yuv420p PSNR luma %.1f, chroma %.1f dB", worst, MAE_LIMIT, worstY, worstC)
|
||||
|
||||
-- 2. a size change mid-stream
|
||||
do
|
||||
local file = b64(SizeChange.file)
|
||||
local dec = Mpeg1.new()
|
||||
dec:write(file)
|
||||
local list = {}
|
||||
while true do
|
||||
local f = dec:decodeFrame() or dec:flush()
|
||||
if f == nil then
|
||||
break
|
||||
end
|
||||
table.insert(list, { w = f.width, h = f.height, px = buffer.tostring(f.pixels :: buffer) })
|
||||
end
|
||||
local a, b = SizeChange.parts[1], SizeChange.parts[2]
|
||||
t:eq(#list, a.frames + b.frames, "sizechange: frame count")
|
||||
t:check(list[1].w == a.width and list[1].h == a.height, "sizechange: first size")
|
||||
t:check(list[a.frames].w == a.width and list[a.frames + 1].w == b.width and list[#list].h == b.height, "sizechange: second size")
|
||||
for k, part in { a, b } do
|
||||
local last = list[if k == 1 then a.frames else #list]
|
||||
local mr, mg, mb = mae(buffer.fromstring(last.px), z64(part.last), part.width * part.height)
|
||||
t:check(math.max(mr, mg, mb) <= MAE_LIMIT, string.format("sizechange part %d MAE %.3f %.3f %.3f", k, mr, mg, mb))
|
||||
end
|
||||
end
|
||||
|
||||
-- 3. robustness and the API
|
||||
local function slice(b: buffer, from: number, n: number): buffer
|
||||
local out = buffer.create(n)
|
||||
buffer.copy(out, 0, b, from, n)
|
||||
return out
|
||||
end
|
||||
local main = STREAMS[2]
|
||||
local mainFile = b64(main.file)
|
||||
local W, H = main.width, main.height
|
||||
local ref = {}
|
||||
do
|
||||
local dec = Mpeg1.new()
|
||||
for _, u in main.units do
|
||||
local f = dec:decode(mainFile, u[1], u[2])
|
||||
table.insert(ref, buffer.tostring((f :: any).pixels))
|
||||
end
|
||||
t:eq(#ref, #main.units, "reference decode")
|
||||
end
|
||||
|
||||
do -- bad arguments
|
||||
local dec = Mpeg1.new()
|
||||
t:check(dec:decode((nil :: any)) == nil, "decode(nil)")
|
||||
t:check(dec:decode((42 :: any)) == nil, "decode(number)")
|
||||
t:check(dec:write(buffer.create(4), 10) == false, "write offset past the end")
|
||||
t:check(dec:write(buffer.create(4), 0, 9) == false, "write length past the end")
|
||||
t:check(dec:write(buffer.create(4), -1) == false, "write negative offset")
|
||||
t:check(dec:decodeFrame() == nil, "decodeFrame with no data")
|
||||
t:check(dec:flush() == nil, "flush with no data")
|
||||
t:check(Mpeg1.new((5 :: any)) ~= nil, "new(non-table)")
|
||||
t:check(dec:decode(buffer.create(0)) == nil, "empty unit")
|
||||
t:check(Mpeg1.frameImage(nil :: any) == nil and Mpeg1.frameImage({} :: any) == nil, "frameImage of a non-frame")
|
||||
end
|
||||
|
||||
do -- string input; pictures before the first sequence header are skipped
|
||||
local dec = Mpeg1.new()
|
||||
local u2 = main.units[2]
|
||||
t:check(dec:decode(buffer.tostring(slice(mainFile, u2[1], u2[2]))) == nil, "P picture before any sequence header")
|
||||
local u1 = main.units[1]
|
||||
local f = dec:decode(buffer.tostring(slice(mainFile, u1[1], u1[2])))
|
||||
t:check(f ~= nil and buffer.tostring((f :: any).pixels) == ref[1], "string unit decodes")
|
||||
t:check(dec.width == W and dec.height == H and math.abs(dec.frameRate - 24) < 0.01, "sequence fields")
|
||||
t:check(f.pictureType == Mpeg1.PICTURE_I and f.codedWidth == 320 and buffer.len(f.y) == 320 * 192, "frame fields")
|
||||
t:eq(dec.stats.skipped, 1, "stats.skipped")
|
||||
end
|
||||
|
||||
do -- rgba = false: planes only, frameImage still gives both
|
||||
local dec = Mpeg1.new({ rgba = false })
|
||||
local u1 = main.units[1]
|
||||
local f = dec:decode(mainFile, u1[1], u1[2]) :: any
|
||||
t:check(f ~= nil and f.pixels == nil and buffer.len(f.y) > 0 and buffer.len(f.cb) == buffer.len(f.y) // 4, "rgba = false")
|
||||
local img = Mpeg1.frameImage(f, true) :: Types.Image
|
||||
t:check(img and buffer.tostring(img.pixels) == ref[1], "frameImage(f, true) after rgba = false")
|
||||
local y = Mpeg1.frameImage(f) :: Types.Image
|
||||
t:check(y.format == "yuv420p" and buffer.readu8(y.pixels, W) == buffer.readu8(f.y, f.codedWidth), "frameImage crops the coded width")
|
||||
end
|
||||
|
||||
do -- reset (seek): the next picture must be an I-picture again
|
||||
local dec = Mpeg1.new()
|
||||
for i = 1, 5 do
|
||||
local u = main.units[i]
|
||||
dec:decode(mainFile, u[1], u[2])
|
||||
end
|
||||
dec:reset()
|
||||
local u = main.units[10]
|
||||
t:check(dec:decode(mainFile, u[1], u[2]) == nil, "P after reset has no reference")
|
||||
u = main.units[1]
|
||||
local f = dec:decode(mainFile, u[1], u[2])
|
||||
t:check(f ~= nil and buffer.tostring((f :: any).pixels) == ref[1], "I after reset")
|
||||
end
|
||||
|
||||
do -- tags (pts) follow pictures through reordering
|
||||
local fx = STREAMS[11]
|
||||
local b = b64(fx.file)
|
||||
local dec = Mpeg1.new({ reorder = true, rgba = false })
|
||||
local order = {}
|
||||
for i, u in fx.units do
|
||||
local f = dec:decode(b, u[1], u[2], i)
|
||||
if f then
|
||||
table.insert(order, f)
|
||||
end
|
||||
end
|
||||
while true do
|
||||
local f = dec:flush()
|
||||
if f == nil then
|
||||
break
|
||||
end
|
||||
table.insert(order, f)
|
||||
end
|
||||
t:eq(#order, #fx.units, "bframes: every picture out")
|
||||
local sawB = false
|
||||
for i = 2, #order do
|
||||
local a, c = order[i - 1], order[i]
|
||||
if c.temporalReference ~= 0 then
|
||||
t:check(c.temporalReference == a.temporalReference + 1, "display order at " .. i)
|
||||
end
|
||||
if c.pictureType == Mpeg1.PICTURE_B then
|
||||
sawB = true
|
||||
t:check(c.tag == a.tag + 1 or a.pictureType ~= Mpeg1.PICTURE_B, "B tag order")
|
||||
end
|
||||
end
|
||||
t:check(sawB, "the stream has B-frames")
|
||||
local d2 = Mpeg1.new()
|
||||
for i, u in fx.units do
|
||||
local f = d2:decode(b, u[1], u[2], i)
|
||||
t:check(f ~= nil and f.tag == i, "decode order tag " .. i)
|
||||
end
|
||||
end
|
||||
|
||||
do -- truncated units: every prefix length of a picture, then recovery
|
||||
local dec = Mpeg1.new()
|
||||
local u1 = main.units[1]
|
||||
for k = 0, u1[2], 97 do
|
||||
Mpeg1.new():decode(mainFile, u1[1], k)
|
||||
end
|
||||
for i = 1, 6 do
|
||||
local u = main.units[i]
|
||||
dec:decode(mainFile, u[1], u[2] // 2)
|
||||
end
|
||||
local f = dec:decode(mainFile, main.units[1][1], main.units[1][2])
|
||||
t:check(f ~= nil and buffer.tostring((f :: any).pixels) == ref[1], "recovers at an I-picture after truncation")
|
||||
end
|
||||
|
||||
-- bit flips and byte garbage in every unit: no throw, sane frames
|
||||
local rounds = 0
|
||||
for _, k in { 2, 11, 8, 6 } do
|
||||
local fx = STREAMS[k]
|
||||
local b = b64(fx.file)
|
||||
for round = 1, 6 do
|
||||
local dec = Mpeg1.new({ reorder = round % 2 == 0 })
|
||||
for _, u in fx.units do
|
||||
local unit = slice(b, u[1], u[2])
|
||||
local nflip = if round <= 3 then round * 3 else 40
|
||||
for _ = 1, nflip do
|
||||
local at = between(0, u[2] - 1)
|
||||
if round == 6 then
|
||||
buffer.writeu8(unit, at, between(0, 255))
|
||||
else
|
||||
buffer.writeu8(unit, at, bit32.bxor(buffer.readu8(unit, at), bit32.lshift(1, between(0, 7))))
|
||||
end
|
||||
end
|
||||
local ok, f = pcall(dec.decode, dec, unit)
|
||||
t:check(ok, fx.name .. ": corrupt unit threw " .. tostring(f))
|
||||
if f then
|
||||
t:check(buffer.len((f :: any).pixels) == f.width * f.height * 4, "frame size")
|
||||
end
|
||||
end
|
||||
while dec:flush() do
|
||||
end
|
||||
rounds += 1
|
||||
end
|
||||
end
|
||||
t:note("%d corrupted-stream rounds", rounds)
|
||||
|
||||
do -- streamed garbage and random units
|
||||
local dec = Mpeg1.new()
|
||||
for _ = 1, 300 do
|
||||
local n = between(0, 3000)
|
||||
local g = buffer.create(n)
|
||||
for i = 0, n - 1 do
|
||||
local r = between(0, 9)
|
||||
buffer.writeu8(g, i, if r < 3 then 0 elseif r == 3 then 1 elseif r == 4 then 0xB3 else between(0, 255))
|
||||
end
|
||||
dec:write(g)
|
||||
while dec:decodeFrame() do
|
||||
end
|
||||
dec:decode(g)
|
||||
end
|
||||
dec:reset()
|
||||
local f = dec:decode(mainFile, main.units[1][1], main.units[1][2])
|
||||
t:check(f ~= nil and buffer.tostring((f :: any).pixels) == ref[1], "clean after garbage")
|
||||
end
|
||||
|
||||
do -- a hostile sequence header: a huge size is rejected
|
||||
local b = buffer.create(16)
|
||||
buffer.writestring(b, 0, "\0\0\1\xB3\xFF\xFF\xFF\x13\xFF\xFF\xE0\x18\0\0\1\xB8")
|
||||
local dec = Mpeg1.new({ maxPixels = 1000 * 1000 })
|
||||
dec:decode(b)
|
||||
t:eq(dec.width, 0, "oversized sequence header rejected")
|
||||
end
|
||||
|
||||
-- 4. the fuzz pass: whole elementary streams (cut, mutated, garbage) through one decoder each
|
||||
do
|
||||
local samples = {}
|
||||
for _, k in { 1, 9 } do
|
||||
local fx = STREAMS[k]
|
||||
local b = b64(fx.file)
|
||||
local u = fx.units
|
||||
table.insert(samples, buffer.tostring(slice(b, 0, u[4][1] + u[4][2])))
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local dec = Mpeg1.new({ reorder = true })
|
||||
local out = { dec:decode(b) }
|
||||
while dec:flush() do
|
||||
end
|
||||
return table.unpack(out)
|
||||
end, samples, { mutations = 12, keepHeader = 4 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -56,7 +56,7 @@ do
|
||||
local inter = buffer.fromstring(frames[1])
|
||||
buffer.writeu8(inter, 0, bit32.bor(buffer.readu8(inter, 0), 1))
|
||||
local _, e1 = Vp8.decodeFrame(inter)
|
||||
t:check(e1 and e1.code == Err.UNSUPPORTED, "inter frame: " .. tostring(e1))
|
||||
t:check(e1 and e1.code == Err.CORRUPT, "inter frame without a key frame: " .. tostring(e1))
|
||||
local bad = buffer.fromstring(frames[1])
|
||||
buffer.writeu8(bad, 3, 0)
|
||||
local _, e2 = Vp8.decodeFrame(bad)
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
-- codecs/Vp8 video tests: whole IVF streams through one decoder object, every shown frame bit-exact against ffmpeg's
|
||||
-- native vp8 decoder (yuv420p CRC32): the official VP8 test vectors (vp80-00-comprehensive-001..018 and others) and
|
||||
-- libvpx clips at many settings (alt-ref / hidden frames, golden, token partitions, error resilience, profiles 1-3,
|
||||
-- sharpness, segmentation, q extremes, short key frame intervals, motion off the frame, odd sizes). Also hidden
|
||||
-- frames, reset() and inter frames without a key frame, and the fuzz no-throw pass over damaged streams.
|
||||
-- Fixtures: tools/fixtures/vp8video.py.
|
||||
local T = require("@tests/T")
|
||||
local Vp8 = require("@formats/codecs/Vp8")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Cases = require("@tests/gen/vp8video_cases")
|
||||
|
||||
local t = T.suite("vp8video")
|
||||
|
||||
-- the frames of an IVF file: { offset, length }
|
||||
local function ivfFrames(b: buffer): { { number } }
|
||||
local out = {}
|
||||
local p = buffer.readu16(b, 6) -- header length (32)
|
||||
while p + 12 <= buffer.len(b) do
|
||||
local n = buffer.readu32(b, p)
|
||||
if p + 12 + n > buffer.len(b) then
|
||||
break
|
||||
end
|
||||
table.insert(out, { p + 12, n })
|
||||
p += 12 + n
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local total, hidden, vectors = 0, 0, 0
|
||||
local samples: { buffer } = {}
|
||||
for _, c in Cases do
|
||||
local b = buffer.fromstring(c.ivf)
|
||||
local fr = ivfFrames(b)
|
||||
local dec = Vp8.newDecoder()
|
||||
local shown, bad, firstBad = 0, 0, ""
|
||||
local ok = true
|
||||
for i, f in fr do
|
||||
local img, err = dec:decodeFrame(b, f[1], f[2])
|
||||
if not img then
|
||||
ok = false
|
||||
firstBad = "frame " .. i .. ": " .. tostring(err)
|
||||
break
|
||||
end
|
||||
local src = img.meta.source
|
||||
if src.show then
|
||||
shown += 1
|
||||
if buffer.len(img.pixels) ~= c.sizes[shown] or Crc32.of(img.pixels) ~= c.crcs[shown] then
|
||||
bad += 1
|
||||
if bad == 1 then
|
||||
firstBad = string.format("frame %d (shown %d, %s)", i, shown, if src.keyFrame then "key" else "inter")
|
||||
end
|
||||
end
|
||||
else
|
||||
hidden += 1
|
||||
end
|
||||
end
|
||||
t:check(ok and bad == 0 and shown == #c.crcs, string.format("%s: %d / %d frames bit-exact, %d shown of %d; first bad: %s", c.name, shown - bad, #c.crcs, shown, #fr, firstBad))
|
||||
total += shown
|
||||
if string.sub(c.name, 1, 5) == "vp80-" then
|
||||
vectors += 1
|
||||
end
|
||||
if #samples < 6 and #c.ivf < 20000 then
|
||||
table.insert(samples, b)
|
||||
end
|
||||
end
|
||||
t:note("%d streams (%d official test vectors), %d shown frames bit-exact with ffmpeg, %d hidden frames", #Cases, vectors, total, hidden)
|
||||
|
||||
-- hidden frames, reset(), inter frames without a key frame
|
||||
do
|
||||
local c
|
||||
for _, x in Cases do
|
||||
if x.name == "altref_352x288" then
|
||||
c = x
|
||||
end
|
||||
end
|
||||
local b = buffer.fromstring(c.ivf)
|
||||
local fr = ivfFrames(b)
|
||||
local dec = Vp8.newDecoder()
|
||||
local _, e0 = dec:decodeFrame(b, fr[2][1], fr[2][2])
|
||||
t:check(e0 and e0.code == Err.CORRUPT, "inter frame first: " .. tostring(e0))
|
||||
local key = dec:decodeFrame(b, fr[1][1], fr[1][2]) :: any
|
||||
t:check(key and key.meta.source.keyFrame and key.meta.source.show and key.meta.source.format == "vp8", "key frame meta")
|
||||
local sawHidden = false
|
||||
for i = 2, #fr do
|
||||
local img = dec:decodeFrame(b, fr[i][1], fr[i][2]) :: any
|
||||
if img and not img.meta.source.show then
|
||||
sawHidden = true
|
||||
t:check(not img.meta.source.keyFrame and img.width == c.width, "hidden frame is an Image")
|
||||
end
|
||||
end
|
||||
t:check(sawHidden, "the alt-ref stream has a hidden frame")
|
||||
-- the returned planes are a copy: decoding more frames leaves an earlier image alone
|
||||
local d2 = Vp8.newDecoder()
|
||||
local first = d2:decodeFrame(b, fr[1][1], fr[1][2]) :: any
|
||||
local crc = Crc32.of(first.pixels)
|
||||
d2:decodeFrame(b, fr[2][1], fr[2][2])
|
||||
d2:decodeFrame(b, fr[3][1], fr[3][2])
|
||||
t:eq(Crc32.of(first.pixels), crc, "images are fresh buffers")
|
||||
dec:reset()
|
||||
local _, e1 = dec:decodeFrame(b, fr[3][1], fr[3][2])
|
||||
t:check(e1 and e1.code == Err.CORRUPT, "inter frame after reset: " .. tostring(e1))
|
||||
local again = dec:decodeFrame(b, fr[1][1], fr[1][2]) :: any
|
||||
t:eq(again and Crc32.of(again.pixels), c.crcs[1], "key frame after reset")
|
||||
local nxt = dec:decodeFrame(b, fr[2][1], fr[2][2]) :: any
|
||||
t:check(nxt ~= nil, "inter frame after the key frame")
|
||||
local _, e2 = Vp8.decodeFrame(b, fr[2][1], fr[2][2])
|
||||
t:check(e2 and e2.code == Err.CORRUPT, "one-shot decodeFrame of an inter frame")
|
||||
local _, e3 = dec:decodeFrame(b, fr[2][1], 2)
|
||||
t:check(e3 and e3.code == Err.TRUNCATED, "truncated frame tag: " .. tostring(e3))
|
||||
end
|
||||
|
||||
-- fuzz: whole damaged streams through one decoder (truncated / mutated frames after valid ones)
|
||||
local function feed(b: buffer)
|
||||
local dec = Vp8.newDecoder()
|
||||
local any = false
|
||||
local p, n = 32, buffer.len(b)
|
||||
while p + 12 <= n do
|
||||
local len = math.min(buffer.readu32(b, p), n - p - 12)
|
||||
local img = dec:decodeFrame(b, p + 12, len, { maxPixels = 2 ^ 20 })
|
||||
any = any or img ~= nil
|
||||
p += 12 + len
|
||||
end
|
||||
return any, nil
|
||||
end
|
||||
-- damage aimed at inter frames: one frame truncated, or bytes changed in its headers / modes (first 48 bytes)
|
||||
local damaged: { buffer } = {}
|
||||
local rand = T.rng(8)
|
||||
for _, b in samples do
|
||||
local fr = ivfFrames(b)
|
||||
for _ = 1, 12 do
|
||||
local k = 2 + rand(#fr - 1)
|
||||
local parts = {}
|
||||
for i, f in fr do
|
||||
local data = buffer.readstring(b, f[1], f[2])
|
||||
if i == k then
|
||||
if rand(2) == 0 then
|
||||
data = string.sub(data, 1, rand(#data))
|
||||
else
|
||||
for _ = 1, 1 + rand(3) do
|
||||
local at = 1 + rand(math.min(48, #data))
|
||||
data = string.sub(data, 1, at - 1) .. string.char(rand(256)) .. string.sub(data, at + 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
local hdr = buffer.create(12)
|
||||
buffer.writeu32(hdr, 0, #data)
|
||||
table.insert(parts, buffer.tostring(hdr) .. data)
|
||||
end
|
||||
table.insert(damaged, buffer.fromstring(buffer.readstring(b, 0, 32) .. table.concat(parts)))
|
||||
end
|
||||
end
|
||||
local throws = 0
|
||||
for _, b in damaged do
|
||||
if not pcall(feed, b) then
|
||||
throws += 1
|
||||
end
|
||||
end
|
||||
t:eq(throws, 0, #damaged .. " streams with one damaged inter frame: no throw")
|
||||
t:fuzz("stream", feed, samples, { mutations = 5, keepHeader = 32 })
|
||||
t:fuzz("stream (more damage)", feed, samples, { mutations = 15, keepHeader = 32, garbage = 20 })
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,241 @@
|
||||
-- containers/IsoBmff tests: ffmpeg / MP4Box files (H.264 + AAC with B-frames, fast start, QuickTime MJPEG + PCM, HEVC,
|
||||
-- fragmented by ffmpeg and MP4Box, stz2 + co64, ALAC) demuxed packet for packet against ffprobe (-ignore_editlist);
|
||||
-- track facts and codec configurations; iTunes tags and cover art; AVIF items (libavif, plain and with alpha); the
|
||||
-- muxer round-trips through the demuxer (sizes, times, cts, sync, tags, 64-bit sizes); a sub-range reader; the fuzz
|
||||
-- no-throw pass. Fixtures: tools/fixtures/isobmff.py.
|
||||
local T = require("@tests/T")
|
||||
local IsoBmff = require("@formats/containers/IsoBmff")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Fx = require("@tests/gen/isobmff")
|
||||
|
||||
local t = T.suite("isobmff")
|
||||
|
||||
local CODEC = { h264 = "h264", aac = "aac", mjpeg = "mjpeg", pcm_s16be = "pcm", hevc = "hevc", alac = "alac" }
|
||||
|
||||
local function reader(s: string, pad: number?): Bytes.Reader
|
||||
if pad then
|
||||
local b = buffer.create(#s + pad * 2)
|
||||
buffer.writestring(b, pad, s)
|
||||
return Bytes.reader(b, pad, #s)
|
||||
end
|
||||
return Bytes.reader(buffer.fromstring(s))
|
||||
end
|
||||
|
||||
-- every fixture against ffprobe
|
||||
for _, c in Fx.cases do
|
||||
for _, pad in { 0, 5 } do
|
||||
local r = reader(c.data, if pad > 0 then pad else nil)
|
||||
local label = c.name .. (if pad > 0 then " (sub-range)" else "")
|
||||
t:check(IsoBmff.sniff(r) ~= nil, label .. ": sniff")
|
||||
local dmx, err = IsoBmff.demux(r)
|
||||
t:check(dmx, label .. ": " .. tostring(err))
|
||||
t:eq(#dmx.tracks, #c.streams, label .. ": track count")
|
||||
for i, s in c.streams do
|
||||
local tr = dmx.tracks[i]
|
||||
t:eq(tr.kind, s.kind, label .. ": track " .. i .. " kind")
|
||||
t:eq(tr.codec, CODEC[s.codec] or s.codec, label .. ": track " .. i .. " codec")
|
||||
t:eq(tr.timescale, s.timescale, label .. ": timescale")
|
||||
if s.width then
|
||||
t:check(tr.width == s.width and tr.height == s.height, label .. ": video size")
|
||||
end
|
||||
if s.sampleRate then
|
||||
t:check(tr.sampleRate == s.sampleRate and tr.channels == s.channels, label .. ": audio format")
|
||||
end
|
||||
if s.extradata > 0 and s.codec ~= "alac" then
|
||||
t:eq(if tr.config then buffer.len(tr.config) else 0, s.extradata, label .. ": codec config size")
|
||||
end
|
||||
end
|
||||
-- packets in file order
|
||||
local n, bad = 0, nil
|
||||
local base = r.base
|
||||
for p in dmx:packets() do
|
||||
n += 1
|
||||
local want = c.packets[n]
|
||||
if not want then
|
||||
bad = bad or ("extra packet " .. n)
|
||||
break
|
||||
end
|
||||
local tr = dmx.tracks[want.stream]
|
||||
if p.track ~= tr.id then
|
||||
bad = bad or ("packet " .. n .. " track")
|
||||
end
|
||||
local off = tr.offsets[p.index]
|
||||
if off - base ~= want.pos or buffer.len(p.data) ~= want.size or p.dts ~= want.dts or p.pts ~= want.pts or p.keyframe ~= want.key then
|
||||
bad = bad or string.format("packet %d: pos %d/%d size %d/%d dts %d/%d pts %d/%d key %s/%s", n, off - base, want.pos, buffer.len(p.data), want.size, p.dts, want.dts, p.pts, want.pts, tostring(p.keyframe), tostring(want.key))
|
||||
end
|
||||
end
|
||||
t:check(bad == nil, label .. ": " .. tostring(bad))
|
||||
t:eq(n, #c.packets, label .. ": packet count")
|
||||
if pad == 0 then
|
||||
t:note("%s: %d tracks, %d packets match ffprobe", c.name, #c.streams, n)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- per-track packets, seek
|
||||
do
|
||||
local c = Fx.cases[1]
|
||||
local dmx = IsoBmff.demux(reader(c.data))
|
||||
local v = dmx.tracks[1]
|
||||
local count = 0
|
||||
for p in dmx:packets(v.id) do
|
||||
count += 1
|
||||
t:eq(p.track, v.id, "per-track packets")
|
||||
end
|
||||
t:eq(count, v.sampleCount, "per-track packet count")
|
||||
dmx:seek(0.75)
|
||||
local p = dmx:packets(v.id)()
|
||||
t:check(p and p.keyframe and p.dts / v.timescale <= 0.75, "seek lands on a keyframe before the time")
|
||||
t:check(v.skip >= 0 and v.edits ~= nil, "edit list parsed")
|
||||
end
|
||||
|
||||
-- tags and cover
|
||||
do
|
||||
local r = reader(Fx.tagged.data)
|
||||
local movie = IsoBmff.parse(r) :: IsoBmff.Movie
|
||||
local tags, pics = IsoBmff.tags(r, movie)
|
||||
for k, v in Fx.tagged.tags do
|
||||
t:eq(tags[k], v, "tag " .. k)
|
||||
end
|
||||
t:check(tags.encoder ~= nil, "encoder tag")
|
||||
t:eq(#pics, 1, "one cover")
|
||||
t:eq(pics[1] and buffer.len(pics[1].data), Fx.tagged.cover, "cover bytes")
|
||||
t:eq(pics[1] and pics[1].mime, "image/png", "cover mime")
|
||||
end
|
||||
|
||||
-- AVIF items
|
||||
for _, c in Fx.avif do
|
||||
local r = reader(c.data)
|
||||
t:check(IsoBmff.sniff(r) == "avif", c.name .. ": brand")
|
||||
local movie = IsoBmff.parse(r) :: IsoBmff.Movie
|
||||
t:check(movie and #movie.tracks == 0, c.name .. ": no tracks")
|
||||
local items, err = IsoBmff.items(r, movie)
|
||||
t:check(items, c.name .. ": items: " .. tostring(err))
|
||||
local prim = items.items[items.primary]
|
||||
t:check(prim and prim.type == "av01", c.name .. ": primary item is av01")
|
||||
local ispe, av1C
|
||||
for _, p in prim.properties do
|
||||
if p.type == "ispe" then
|
||||
ispe = p
|
||||
elseif p.type == "av1C" then
|
||||
av1C = p
|
||||
end
|
||||
end
|
||||
t:check(ispe and ispe.width == c.width and ispe.height == c.height, c.name .. ": ispe")
|
||||
t:check(av1C and av1C.config and buffer.readu8(av1C.config, 0) == 0x81, c.name .. ": av1C marker / version")
|
||||
local data = IsoBmff.itemData(r, items, items.primary :: number)
|
||||
t:check(data and buffer.len(data) > 10, c.name .. ": item data")
|
||||
-- an AV1 OBU stream: the first OBU is a sequence header (type 1) or a temporal delimiter (2)
|
||||
local obu = data and bit32.band(bit32.rshift(buffer.readu8(data, 0), 3), 15)
|
||||
t:check(obu == 1 or obu == 2, c.name .. ": AV1 OBU stream")
|
||||
local auxl = nil
|
||||
for _, id in items.order do
|
||||
local it = items.items[id]
|
||||
if it.refs.auxl then
|
||||
auxl = it
|
||||
end
|
||||
end
|
||||
t:eq(auxl ~= nil, c.alpha, c.name .. ": alpha auxiliary item")
|
||||
end
|
||||
|
||||
-- the muxer: round trip through the demuxer
|
||||
do
|
||||
local rand = T.rng(5)
|
||||
local function sample(n: number): buffer
|
||||
local b = buffer.create(n)
|
||||
for i = 0, n - 1 do
|
||||
buffer.writeu8(b, i, rand(256))
|
||||
end
|
||||
return b
|
||||
end
|
||||
local aud, vid = {}, {}
|
||||
for i = 1, 90 do
|
||||
aud[i] = sample(50 + rand(200))
|
||||
end
|
||||
for i = 1, 30 do
|
||||
vid[i] = sample(100 + rand(900))
|
||||
end
|
||||
local cts = {}
|
||||
local sync = {}
|
||||
for i = 1, 30 do
|
||||
cts[i] = (i % 3) * 512
|
||||
sync[i] = i % 10 == 1
|
||||
end
|
||||
local cfg = buffer.fromstring("\x12\x10")
|
||||
local file, err = IsoBmff.mux({
|
||||
brand = "mp42",
|
||||
compatible = { "mp42", "isom" },
|
||||
tracks = {
|
||||
{ kind = "video", entry = "avc1", timescale = 15360, samples = vid, durations = 512, cts = cts, sync = sync, width = 64, height = 48, config = buffer.fromstring("\1\100\0\10\255") },
|
||||
{ kind = "audio", entry = "mp4a", timescale = 44100, samples = aud, durations = 1024, sampleRate = 44100, channels = 2, config = cfg, skip = 1024, playDuration = 44100 * 2 },
|
||||
},
|
||||
tags = { title = "Mux Test", artist = "Me", track = "2", tracktotal = "9", custom = "free form", bpm = "120" },
|
||||
pictures = { { mime = "image/jpeg", data = buffer.fromstring("\255\216\255\217") } },
|
||||
chunkDuration = 0.25,
|
||||
})
|
||||
t:check(file, "mux: " .. tostring(err))
|
||||
local r = Bytes.reader(file :: buffer)
|
||||
local dmx = IsoBmff.demux(r)
|
||||
t:check(dmx and #dmx.tracks == 2, "mux: demux our file")
|
||||
local v, a = dmx.tracks[1], dmx.tracks[2]
|
||||
t:check(v.codec == "h264" and v.width == 64 and v.height == 48 and v.config and buffer.len(v.config) == 5, "mux: video track")
|
||||
t:check(a.codec == "aac" and a.sampleRate == 44100 and a.channels == 2 and a.config and buffer.tostring(a.config) == "\x12\x10", "mux: audio track + esds")
|
||||
t:check(a.skip == 1024 and a.playDuration == 88200, "mux: edit list")
|
||||
local ok = true
|
||||
for i = 1, 30 do
|
||||
local s = IsoBmff.sample(r, v, i) :: buffer
|
||||
ok = ok and buffer.tostring(s) == buffer.tostring(vid[i]) and v.dts[i] == (i - 1) * 512 and (v.cts :: any)[i] == cts[i] and ((v.sync :: any)[i] == true) == sync[i]
|
||||
end
|
||||
t:check(ok, "mux: video samples, times, cts, sync")
|
||||
ok = true
|
||||
for i = 1, 90 do
|
||||
ok = ok and buffer.tostring(IsoBmff.sample(r, a, i) :: buffer) == buffer.tostring(aud[i]) and a.durations[i] == 1024
|
||||
end
|
||||
t:check(ok, "mux: audio samples")
|
||||
-- interleaved: offsets alternate between the tracks
|
||||
t:check(v.offsets[30] > a.offsets[1] and a.offsets[90] > v.offsets[1], "mux: interleaved chunks")
|
||||
local tags, pics = IsoBmff.tags(r, dmx.movie)
|
||||
t:check(tags.title == "Mux Test" and tags.artist == "Me" and tags.track == "2" and tags.tracktotal == "9" and tags.custom == "free form" and tags.bpm == "120", "mux: tags round trip")
|
||||
t:check(#pics == 1 and buffer.len(pics[1].data) == 4, "mux: cover round trip")
|
||||
t:note("mux: %d bytes, crc %08x", buffer.len(file :: buffer), Crc32.of(file :: buffer))
|
||||
-- data + sizes form, bad specs
|
||||
local f2 = IsoBmff.mux({ tracks = { { kind = "audio", entry = "alac", timescale = 8000, data = buffer.create(30), sizes = { 10, 10, 10 }, durations = { 4096, 4096, 100 }, config = buffer.create(24) } } })
|
||||
local d2 = IsoBmff.demux(Bytes.reader(f2 :: buffer))
|
||||
t:check(d2 and d2.tracks[1].codec == "alac" and d2.tracks[1].sampleCount == 3 and d2.tracks[1].durations[3] == 100 and buffer.len(d2.tracks[1].config) == 24, "mux: data + sizes, alac cookie")
|
||||
for _, bad in { {}, { tracks = {} }, { tracks = { { kind = "audio", entry = "toolong", timescale = 1, samples = {}, durations = 1 } } }, { tracks = { { kind = "x", entry = "abcd", timescale = 1, samples = {}, durations = 1 } } }, { tracks = { { kind = "audio", entry = "abcd", timescale = 1 } } } } do
|
||||
local f, e = IsoBmff.mux(bad :: any)
|
||||
t:check(f == nil and e and e.code == "ARG", "mux: bad spec -> ARG")
|
||||
end
|
||||
end
|
||||
|
||||
-- fuzz
|
||||
do
|
||||
local samples = {}
|
||||
for _, c in Fx.cases do
|
||||
table.insert(samples, string.sub(c.data, 1, 6000))
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
for _, c in Fx.avif do
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
t:fuzz("demux", function(b: buffer)
|
||||
local r = Bytes.reader(b)
|
||||
local dmx = IsoBmff.demux(r)
|
||||
if dmx then
|
||||
for p in dmx:packets() do
|
||||
local _ = p
|
||||
end
|
||||
IsoBmff.tags(r, dmx.movie)
|
||||
local items = IsoBmff.items(r, dmx.movie)
|
||||
if items then
|
||||
for _, id in items.order do
|
||||
IsoBmff.itemData(r, items, id)
|
||||
end
|
||||
end
|
||||
end
|
||||
return dmx
|
||||
end, samples, { mutations = 12 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,30 @@
|
||||
-- core/Md5 tests: the RFC 1321 test suite, incremental updates at every split, sub-ranges, a long input.
|
||||
local T = require("@tests/T")
|
||||
local Md5 = require("@formats/core/Md5")
|
||||
|
||||
local t = T.suite("md5")
|
||||
local VECTORS = {
|
||||
{ "", "d41d8cd98f00b204e9800998ecf8427e" },
|
||||
{ "a", "0cc175b9c0f1b6a831c399e269772661" },
|
||||
{ "abc", "900150983cd24fb0d6963f7d28e17f72" },
|
||||
{ "message digest", "f96b697d7cb7938d525a2f31aaf161d0" },
|
||||
{ "abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b" },
|
||||
{ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "d174ab98d277d9f5a5611c2c9f419d9f" },
|
||||
{ string.rep("1234567890", 8), "57edf4a22be3c955ac49da2e2107b67a" },
|
||||
}
|
||||
for _, v in VECTORS do
|
||||
t:eq(Md5.of(buffer.fromstring(v[1])), v[2], "md5 of " .. string.format("%q", v[1]))
|
||||
end
|
||||
-- incremental: every split point of a 130-byte message, three pieces
|
||||
local msg = string.rep("The quick brown fox jumps over the lazy dog. ", 3)
|
||||
local want = Md5.of(buffer.fromstring(msg))
|
||||
for cut = 0, #msg, 7 do
|
||||
local h = Md5.new()
|
||||
h:update(buffer.fromstring(string.sub(msg, 1, cut)))
|
||||
h:update(buffer.fromstring(string.sub(msg, cut + 1, cut + 20)))
|
||||
h:update(buffer.fromstring(string.sub(msg, cut + 21)))
|
||||
t:eq(Md5.hex(h:digest()), want, "split at " .. cut)
|
||||
end
|
||||
t:eq(Md5.of(buffer.fromstring("xxabcyy"), 2, 3), "900150983cd24fb0d6963f7d28e17f72", "sub-range")
|
||||
t:eq(Md5.of(buffer.fromstring(string.rep("a", 1000000))), "7707d6ae4e027c70eea2a935c2296f21", "a million a's")
|
||||
t:done()
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,209 @@
|
||||
-- tests/music/_similar: shared helper of the tracker tests (not a test itself): renders a module through a Decoder and
|
||||
-- compares it with a reference render's features (tools/fixtures/_tracker.py: per 2048-frame block the RMS of left,
|
||||
-- right and mid, and 40 log-spaced band magnitudes of mid from a Hann-windowed FFT). Same definitions on both sides.
|
||||
local S = {}
|
||||
|
||||
local SR, HOP, BANDS = 44100, 2048, 40
|
||||
local F_LO, F_HI = 150, 16000
|
||||
S.SR = SR
|
||||
|
||||
local WINDOW = table.create(HOP, 0)
|
||||
for i = 0, HOP - 1 do
|
||||
WINDOW[i + 1] = 0.5 - 0.5 * math.cos(2 * math.pi * i / HOP)
|
||||
end
|
||||
local BAND_OF = table.create(HOP // 2, -1)
|
||||
for b = 1, HOP // 2 - 1 do
|
||||
local f = b * SR / HOP
|
||||
if f >= F_LO and f < F_HI then
|
||||
BAND_OF[b + 1] = math.min(BANDS - 1, math.floor(math.log(f / F_LO) / math.log(F_HI / F_LO) * BANDS))
|
||||
end
|
||||
end
|
||||
|
||||
local function fft(re: { number }, im: { number }, n: number)
|
||||
local j = 0
|
||||
for i = 1, n - 1 do
|
||||
local bit = n // 2
|
||||
while bit > 0 and j >= bit and (j // bit) % 2 == 1 do
|
||||
j -= bit
|
||||
bit //= 2
|
||||
end
|
||||
j += bit
|
||||
if i < j then
|
||||
re[i + 1], re[j + 1] = re[j + 1], re[i + 1]
|
||||
im[i + 1], im[j + 1] = im[j + 1], im[i + 1]
|
||||
end
|
||||
end
|
||||
local size = 2
|
||||
while size <= n do
|
||||
local ang = -2 * math.pi / size
|
||||
local wr, wi = math.cos(ang), math.sin(ang)
|
||||
local half = size // 2
|
||||
for start = 0, n - 1, size do
|
||||
local cr, ci = 1, 0
|
||||
for k = 0, half - 1 do
|
||||
local a, b = start + k + 1, start + k + half + 1
|
||||
local tr = re[b] * cr - im[b] * ci
|
||||
local ti = re[b] * ci + im[b] * cr
|
||||
re[b], im[b] = re[a] - tr, im[a] - ti
|
||||
re[a], im[a] = re[a] + tr, im[a] + ti
|
||||
cr, ci = cr * wr - ci * wi, cr * wi + ci * wr
|
||||
end
|
||||
end
|
||||
size *= 2
|
||||
end
|
||||
end
|
||||
|
||||
-- features(samples (interleaved stereo f32 buffer), frames) -> { frames, rmsL, rmsR, rmsM, bands }
|
||||
function S.features(buf: buffer, frames: number): any
|
||||
local n = frames // HOP
|
||||
local out = { frames = n, rmsL = {}, rmsR = {}, rmsM = {}, bands = {} }
|
||||
local re, im = table.create(HOP, 0), table.create(HOP, 0)
|
||||
for k = 0, n - 1 do
|
||||
local sl, sr, sm = 0, 0, 0
|
||||
for i = 0, HOP - 1 do
|
||||
local o = ((k * HOP + i) * 2) * 4
|
||||
local l, r = buffer.readf32(buf, o), buffer.readf32(buf, o + 4)
|
||||
local m = (l + r) / 2
|
||||
sl += l * l
|
||||
sr += r * r
|
||||
sm += m * m
|
||||
re[i + 1] = m * WINDOW[i + 1]
|
||||
im[i + 1] = 0
|
||||
end
|
||||
table.insert(out.rmsL, math.sqrt(sl / HOP))
|
||||
table.insert(out.rmsR, math.sqrt(sr / HOP))
|
||||
table.insert(out.rmsM, math.sqrt(sm / HOP))
|
||||
fft(re, im, HOP)
|
||||
local e = table.create(BANDS, 0)
|
||||
for b = 1, HOP // 2 - 1 do
|
||||
local j = BAND_OF[b + 1]
|
||||
if j >= 0 then
|
||||
e[j + 1] += re[b + 1] * re[b + 1] + im[b + 1] * im[b + 1]
|
||||
end
|
||||
end
|
||||
for j = 1, BANDS do
|
||||
table.insert(out.bands, math.sqrt(e[j]))
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- renderAll(decoder, maxFrames) -> interleaved buffer, frames
|
||||
function S.renderAll(dec: any, maxFrames: number): (buffer, number)
|
||||
local total = math.min(dec.frames, maxFrames)
|
||||
local out = buffer.create(math.max(1, total) * 8)
|
||||
local pos = 0
|
||||
local chunk = buffer.create(4096 * 8)
|
||||
while pos < total do
|
||||
local _, n = dec:read(math.min(4096, total - pos), chunk)
|
||||
if n == 0 then
|
||||
break
|
||||
end
|
||||
buffer.copy(out, pos * 8, chunk, 0, n * 8)
|
||||
pos += n
|
||||
end
|
||||
return out, pos
|
||||
end
|
||||
|
||||
local function db(x: number): number
|
||||
return 20 * math.log10(x + 1e-6)
|
||||
end
|
||||
|
||||
-- compare(ours, ref) -> { gainDb, envCorr, spectral, balance } over the common frames:
|
||||
-- gainDb total mid energy ratio in dB (ours / ref)
|
||||
-- envCorr Pearson correlation of the per-block mid loudness in dB (blocks above -60 dB in either)
|
||||
-- envErr mean absolute difference of the per-block mid loudness in dB, after removing gainDb (same blocks)
|
||||
-- spectral mean cosine similarity of the band magnitude vectors (blocks where ref is above -50 dB)
|
||||
-- balance mean absolute difference of the per-block left / right balance (L - R) / (L + R) (loud blocks)
|
||||
function S.compare(a: any, b: any): any
|
||||
local n = math.min(a.frames, b.frames)
|
||||
local ea, eb = 0, 0
|
||||
for k = 1, n do
|
||||
ea += a.rmsM[k] ^ 2
|
||||
eb += b.rmsM[k] ^ 2
|
||||
end
|
||||
local gainDb = 10 * math.log10((ea + 1e-12) / (eb + 1e-12))
|
||||
local xs, ys = {}, {}
|
||||
for k = 1, n do
|
||||
local x, y = db(a.rmsM[k]), db(b.rmsM[k])
|
||||
if x > -60 or y > -60 then
|
||||
table.insert(xs, x)
|
||||
table.insert(ys, y)
|
||||
end
|
||||
end
|
||||
local mx, my = 0, 0
|
||||
for i = 1, #xs do
|
||||
mx += xs[i]
|
||||
my += ys[i]
|
||||
end
|
||||
mx /= math.max(1, #xs)
|
||||
my /= math.max(1, #ys)
|
||||
local sxy, sxx, syy = 0, 0, 0
|
||||
for i = 1, #xs do
|
||||
sxy += (xs[i] - mx) * (ys[i] - my)
|
||||
sxx += (xs[i] - mx) ^ 2
|
||||
syy += (ys[i] - my) ^ 2
|
||||
end
|
||||
local envCorr = if sxx > 0 and syy > 0 then sxy / math.sqrt(sxx * syy) else 1
|
||||
-- the mean loudness difference per block once the overall gain is taken out (dB, each side clamped at -60)
|
||||
local envErr = 0
|
||||
for i = 1, #xs do
|
||||
envErr += math.abs(math.max(xs[i], -60) - math.max(ys[i], -60) - gainDb)
|
||||
end
|
||||
envErr /= math.max(1, #xs)
|
||||
local cs, cn = 0, 0
|
||||
local bal, bn = 0, 0
|
||||
for k = 1, n do
|
||||
if db(b.rmsM[k]) > -50 then
|
||||
local dot, na, nb = 0, 0, 0
|
||||
for j = 1, BANDS do
|
||||
local x, y = a.bands[(k - 1) * BANDS + j], b.bands[(k - 1) * BANDS + j]
|
||||
dot += x * y
|
||||
na += x * x
|
||||
nb += y * y
|
||||
end
|
||||
cs += if na > 0 and nb > 0 then dot / math.sqrt(na * nb) else 0
|
||||
cn += 1
|
||||
end
|
||||
local la, ra, lb, rb = a.rmsL[k], a.rmsR[k], b.rmsL[k], b.rmsR[k]
|
||||
if lb + rb > 0.01 then
|
||||
bal += math.abs((la - ra) / (la + ra + 1e-9) - (lb - rb) / (lb + rb))
|
||||
bn += 1
|
||||
end
|
||||
end
|
||||
return {
|
||||
gainDb = gainDb,
|
||||
envCorr = envCorr,
|
||||
envErr = envErr,
|
||||
spectral = if cn > 0 then cs / cn else 1,
|
||||
balance = if bn > 0 then bal / bn else 0,
|
||||
frames = n,
|
||||
}
|
||||
end
|
||||
|
||||
-- worst(ours, ref, count) -> the blocks with the lowest spectral similarity (for debugging): { {block, sim} }
|
||||
function S.worst(a: any, b: any, count: number): { { number } }
|
||||
local list = {}
|
||||
for k = 1, math.min(a.frames, b.frames) do
|
||||
if db(b.rmsM[k]) > -50 then
|
||||
local dot, na, nb = 0, 0, 0
|
||||
for j = 1, BANDS do
|
||||
local x, y = a.bands[(k - 1) * BANDS + j], b.bands[(k - 1) * BANDS + j]
|
||||
dot += x * y
|
||||
na += x * x
|
||||
nb += y * y
|
||||
end
|
||||
table.insert(list, { k, if na > 0 and nb > 0 then dot / math.sqrt(na * nb) else 0, db(a.rmsM[k]), db(b.rmsM[k]) })
|
||||
end
|
||||
end
|
||||
table.sort(list, function(x, y)
|
||||
return x[2] < y[2]
|
||||
end)
|
||||
local out = {}
|
||||
for i = 1, math.min(count, #list) do
|
||||
out[i] = list[i]
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
return S
|
||||
@@ -0,0 +1,84 @@
|
||||
-- music/it tests: generated Impulse Tracker modules (tools/fixtures/it.py) parsed, rendered through codecs/Tracker and
|
||||
-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the contract,
|
||||
-- and the fuzz no-throw pass.
|
||||
local T = require("@tests/T")
|
||||
local S = require("@tests/music/_similar")
|
||||
local It = require("@formats/music/it")
|
||||
local Tracker = require("@formats/codecs/Tracker")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/it_cases")
|
||||
|
||||
local t = T.suite("it")
|
||||
|
||||
t:eq(It.name, "it", "name")
|
||||
t:eq(It.category, "music", "category")
|
||||
t:check(It.caps.decode and not It.caps.encode, "caps")
|
||||
|
||||
local function load(data: string): any
|
||||
return It.decode(Bytes.reader(buffer.fromstring(data)))
|
||||
end
|
||||
|
||||
local THRESH = { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }
|
||||
|
||||
for _, c in Cases do
|
||||
local m, err = load(c.data)
|
||||
t:check(m, c.name .. ": " .. tostring(err))
|
||||
t:check(It.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff")
|
||||
local dec = m:render({ sampleRate = S.SR })
|
||||
t:check(dec, c.name .. ": render")
|
||||
t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration))
|
||||
local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR))
|
||||
local r = S.compare(S.features(buf, frames), c.ref)
|
||||
t:note("%-7s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envErr, r.spectral, r.balance, dec.duration)
|
||||
if r.spectral < THRESH.spectral or r.envErr > THRESH.envErr then
|
||||
for _, w in S.worst(S.features(buf, frames), c.ref, 6) do
|
||||
t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4])
|
||||
end
|
||||
end
|
||||
t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness")
|
||||
t:check(r.envErr < THRESH.envErr, c.name .. ": loudness envelope")
|
||||
t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum")
|
||||
t:check(r.balance < THRESH.balance, c.name .. ": stereo balance")
|
||||
end
|
||||
|
||||
-- compressed samples (IT 2.14 / 2.15, 8 and 16-bit, mono and stereo) decode to exactly the uncompressed data
|
||||
for _, c in Cases do
|
||||
if c.plain then
|
||||
local a, b = load(c.data), load(c.plain)
|
||||
local same = #a.samples == #b.samples
|
||||
for i, s in a.samples do
|
||||
local o = b.samples[i]
|
||||
same = same and s.length == o.length and s.channels == o.channels and buffer.tostring(s.data) == buffer.tostring(o.data)
|
||||
end
|
||||
t:check(same, c.name .. ": samples equal the uncompressed ones")
|
||||
end
|
||||
end
|
||||
|
||||
-- seek: the position after a seek and the output continuing
|
||||
do
|
||||
local m = load(Cases[1].data)
|
||||
local dec = m:render()
|
||||
dec:seek(2)
|
||||
t:check(math.abs(dec:position() - 2) < 0.001, "seek position")
|
||||
local _, n = dec:read(1000)
|
||||
t:eq(n, 1000, "read after seek")
|
||||
t:check(Tracker.duration(m) == dec.duration, "duration()")
|
||||
end
|
||||
|
||||
-- the fuzz pass: decode, and a short render of whatever decodes
|
||||
local samples = {}
|
||||
for _, c in Cases do
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local m = It.decode(Bytes.reader(b))
|
||||
if m then
|
||||
local dec = Tracker.render(m, { maxDuration = 0.5, sampleRate = 8000 })
|
||||
if dec then
|
||||
dec:read(4000)
|
||||
end
|
||||
end
|
||||
return m
|
||||
end, samples, { mutations = 30 })
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,272 @@
|
||||
-- music/midi tests: SMF formats 0 / 1 / 2 + SMPTE + RMID parsed exactly as python mido parses them, mido's own files
|
||||
-- re-encoded byte for byte, round trips without running status, the tempo map against mido's message times and
|
||||
-- lengths, meta summaries, crafted bad files, truncation (lenient / strict), the fallback-synth render (duration,
|
||||
-- level, seek), and the fuzz no-throw pass (decode, and decode + a short render). Fixtures: tools/fixtures/midi.py.
|
||||
local T = require("@tests/T")
|
||||
local Midi = require("@formats/music/midi")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Cases = require("@tests/gen/midi_cases")
|
||||
local Bad = require("@tests/gen/midi_bad")
|
||||
local Trunc = require("@tests/gen/midi_trunc")
|
||||
|
||||
local t = T.suite("midi")
|
||||
|
||||
local function decode(data: any, opts: any?): (any, any)
|
||||
local b = if type(data) == "string" then buffer.fromstring(data) else data
|
||||
return Midi.decode(Bytes.reader(b), opts)
|
||||
end
|
||||
|
||||
-- the contract
|
||||
t:eq(Midi.name, "midi", "name")
|
||||
t:eq(Midi.category, "music", "category")
|
||||
t:check(table.find(Midi.extensions, "mid") ~= nil, "extensions")
|
||||
t:check(Midi.caps.decode and Midi.caps.encode, "caps")
|
||||
t:eq(Midi.sniff(Bytes.reader(buffer.fromstring("MThd\0\0\0\6"))), 1, "sniff MThd")
|
||||
t:eq(Midi.sniff(Bytes.reader(buffer.fromstring("RIFF\0\0\0\0RMID"))), 1, "sniff RMID")
|
||||
t:eq(Midi.sniff(Bytes.reader(buffer.fromstring("RIFF\0\0\0\0WAVE"))), 0, "sniff WAVE")
|
||||
|
||||
local function sameEvents(got: { any }, want: { any }, label: string)
|
||||
t:eq(#got, #want, label .. ": event count")
|
||||
for i, w in want do
|
||||
local g = got[i]
|
||||
local l = label .. " event " .. i
|
||||
t:eq(g.tick, w[1], l .. " tick")
|
||||
t:eq(g.type, w[2], l .. " type")
|
||||
t:eq(g.channel or -1, w[3], l .. " channel")
|
||||
t:eq(if g.type == "meta" then g.meta else -1, w[5], l .. " meta type")
|
||||
local d = g.data or {}
|
||||
t:eq(#d, #w[4], l .. " data length")
|
||||
for k, v in w[4] do
|
||||
if d[k] ~= v then
|
||||
t:eq(d[k], v, l .. " data byte " .. k)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function trackEvents(m: any): { { any } }
|
||||
local out = {}
|
||||
for ti, tr in m.tracks do
|
||||
local evs = {}
|
||||
for _, ev in tr.events do
|
||||
table.insert(evs, { ev.tick, ev.type, ev.channel or -1, ev.data or {}, if ev.type == "meta" then ev.meta else -1 })
|
||||
end
|
||||
out[ti] = evs
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local byName = {}
|
||||
for _, c in Cases do
|
||||
byName[c.name] = c
|
||||
local m, err = decode(c.data)
|
||||
t:check(m, c.name .. ": " .. tostring(err))
|
||||
t:eq(m.kind, "midi", c.name .. ": kind")
|
||||
t:eq(m.format, c.type, c.name .. ": format")
|
||||
t:eq(m.division, c.division, c.name .. ": division")
|
||||
t:eq(#m.tracks, #c.tracks, c.name .. ": tracks")
|
||||
for ti, want in c.tracks do
|
||||
sameEvents(m.tracks[ti].events, want, c.name .. " track " .. ti)
|
||||
end
|
||||
-- mido's own bytes come back exactly (running status as mido writes it)
|
||||
if c.exact then
|
||||
local out, eerr = Midi.encode(m)
|
||||
t:check(out, c.name .. ": encode " .. tostring(eerr))
|
||||
t:eq(buffer.tostring(out :: buffer) == c.data, true, c.name .. ": re-encoded bytes equal mido's")
|
||||
end
|
||||
-- without running status: longer (or equal), and the same events
|
||||
local plain = Midi.encode(m, { runningStatus = false }) :: buffer
|
||||
local withRs = Midi.encode(m) :: buffer
|
||||
t:check(buffer.len(plain) >= buffer.len(withRs), c.name .. ": running status saves bytes")
|
||||
local back = decode(plain)
|
||||
t:check(back, c.name .. ": re-decode")
|
||||
for ti, want in trackEvents(m) do
|
||||
sameEvents(back.tracks[ti].events, want, c.name .. " round trip track " .. ti)
|
||||
end
|
||||
-- tempo map: every event's time against mido's merged message times
|
||||
if c.times then
|
||||
local secs = {}
|
||||
for _, tr in m.tracks do
|
||||
for _, ev in tr.events do
|
||||
if not (ev.type == "meta" and ev.meta == 0x2F) then -- mido merges the end-of-track events into one
|
||||
table.insert(secs, Midi.tickToSeconds(m, ev.tick))
|
||||
end
|
||||
end
|
||||
end
|
||||
table.sort(secs)
|
||||
t:eq(#secs, #c.times - 1, c.name .. ": event count vs mido")
|
||||
local worst = 0
|
||||
for i, s in secs do
|
||||
worst = math.max(worst, math.abs(s - c.times[i]))
|
||||
end
|
||||
t:check(worst < 1e-6, c.name .. ": event times match mido (worst " .. worst .. " s)")
|
||||
t:check(math.abs(Midi.length(m) - c.length) < 1e-6, c.name .. ": length " .. Midi.length(m) .. " vs mido " .. c.length)
|
||||
t:check(math.abs(m.meta.length - c.length) < 1e-6, c.name .. ": meta.length")
|
||||
end
|
||||
end
|
||||
t:note("%d files parse as mido parses them; mido's files re-encode byte for byte", #Cases)
|
||||
|
||||
-- meta summaries
|
||||
do
|
||||
local m = decode(byName.format0.data)
|
||||
t:eq(m.tracks[1].name, "format zero", "track name")
|
||||
t:eq(#m.meta.tempos, 3, "tempo changes")
|
||||
t:eq(m.meta.tempos[1].usPerQuarter, 500000, "first tempo")
|
||||
t:eq(m.meta.tempos[1].bpm, 120, "bpm")
|
||||
t:eq(#m.meta.timeSignatures, 2, "time signatures")
|
||||
t:eq(m.meta.timeSignatures[1].numerator, 3, "3/4 numerator")
|
||||
t:eq(m.meta.timeSignatures[1].denominator, 4, "3/4 denominator")
|
||||
t:eq(m.meta.timeSignatures[2].denominator, 8, "6/8 denominator")
|
||||
t:eq(m.meta.keySignatures[1].sharps, -3, "Eb: 3 flats")
|
||||
t:eq(m.meta.keySignatures[1].minor, false, "Eb major")
|
||||
local s = decode(byName.smpte.data)
|
||||
t:eq(s.meta.smpte.fps, 25, "smpte fps")
|
||||
t:eq(s.meta.smpte.ticksPerFrame, 40, "smpte ticks per frame")
|
||||
t:check(math.abs(Midi.tickToSeconds(s, 1000) - 1) < 1e-12, "smpte: 1000 ticks at 25 x 40 = 1 s")
|
||||
t:eq(decode(byName.rmid.data).meta.rmid, true, "rmid flag")
|
||||
-- format 2: per-track tempo maps, the tracks one after another
|
||||
local f2 = decode(byName.format2.data)
|
||||
local total = 0
|
||||
for ti, tr in f2.tracks do
|
||||
local last = tr.events[#tr.events].tick
|
||||
total += Midi.tickToSeconds(f2, last, ti)
|
||||
end
|
||||
t:check(math.abs(Midi.length(f2) - total) < 1e-9, "format 2 length = the tracks in sequence")
|
||||
end
|
||||
|
||||
-- a value built by hand: unsorted events are written in tick order, end of track added, bad values refused
|
||||
do
|
||||
local m = Types.Midi.new(96)
|
||||
m.format = 0
|
||||
m.tracks[1] = { events = {
|
||||
{ tick = 50, type = "noteOff", channel = 2, data = { 60, 0 } },
|
||||
{ tick = 0, type = "noteOn", channel = 2, data = { 60, 100 } },
|
||||
{ tick = 50, type = "meta", meta = 0x2F, data = {} },
|
||||
{ tick = 20, type = "controller", channel = 2, data = { 64, 127 } },
|
||||
} }
|
||||
local b = Midi.encode(m) :: buffer
|
||||
local back = decode(b)
|
||||
sameEvents(back.tracks[1].events, {
|
||||
{ 0, "noteOn", 2, { 60, 100 }, -1 }, { 20, "controller", 2, { 64, 127 }, -1 }, { 50, "noteOff", 2, { 60, 0 }, -1 },
|
||||
{ 50, "meta", -1, {}, 0x2F },
|
||||
}, "sorted on write")
|
||||
local function refuses(mut: (any) -> (), label: string)
|
||||
local x = Types.Midi.new(96)
|
||||
x.tracks[1] = { events = { { tick = 0, type = "noteOn", channel = 0, data = { 60, 100 } } } }
|
||||
mut(x)
|
||||
local out, err = Midi.encode(x)
|
||||
t:check(out == nil and Err.is(err) and err.code == Err.ARG, "encode refuses " .. label)
|
||||
end
|
||||
refuses(function(x) x.tracks[1].events[1].channel = 16 end, "channel 16")
|
||||
refuses(function(x) x.tracks[1].events[1].data = { 60, 128 } end, "data byte 128")
|
||||
refuses(function(x) x.tracks[1].events[1].tick = -1 end, "negative tick")
|
||||
refuses(function(x) x.tracks[1].events[1].type = "wobble" end, "unknown type")
|
||||
refuses(function(x) x.division = 0 end, "zero division")
|
||||
refuses(function(x) x.format = 0; x.tracks[2] = { events = {} } end, "format 0 with two tracks")
|
||||
local nope, nerr = Midi.encode(nil :: any)
|
||||
t:check(nope == nil and nerr.code == Err.ARG, "encode refuses nil")
|
||||
end
|
||||
|
||||
-- crafted bad files
|
||||
for _, c in Bad do
|
||||
local ok, m, err = pcall(decode, c.data)
|
||||
t:check(ok, c.name .. ": threw " .. tostring(m))
|
||||
t:check(m == nil and Err.is(err), c.name .. ": decoded")
|
||||
t:eq(err.code, c.code, c.name .. ": error code (" .. tostring(err) .. ")")
|
||||
end
|
||||
|
||||
-- truncation: lenient keeps what it read, strict fails
|
||||
do
|
||||
local m = decode(Trunc.data)
|
||||
t:check(m and m.meta.truncated, "truncated file decodes leniently, flagged")
|
||||
local n = 0
|
||||
for _, tr in m.tracks do
|
||||
n += #tr.events
|
||||
end
|
||||
t:check(n > 50, "truncated file keeps its events (" .. n .. ")")
|
||||
local s, err = decode(Trunc.data, { strict = true })
|
||||
t:check(s == nil and err.code == Err.TRUNCATED, "strict: TRUNCATED")
|
||||
t:eq(decode(byName.format1.data, { strict = true }).meta.truncated, false, "strict: a whole file passes")
|
||||
local l, lerr = decode(byName.random.data, { maxEvents = 100 })
|
||||
t:check(l == nil and lerr.code == Err.LIMIT, "maxEvents: LIMIT")
|
||||
end
|
||||
|
||||
-- render through the built-in waveform set
|
||||
do
|
||||
local song = decode(byName.song.data)
|
||||
local dec = song:render({ tail = 0.5 })
|
||||
local want = math.ceil((byName.song.length + 0.5) * 44100)
|
||||
t:eq(dec.frames, want, "render: frames = (length + tail) * rate")
|
||||
t:eq(dec.channels, 2, "render: stereo")
|
||||
t:eq(dec.sampleRate, 44100, "render: rate")
|
||||
local total, sumsq, peak = 0, 0, 0
|
||||
local out = buffer.create(4096 * 8)
|
||||
while true do
|
||||
local b, n = dec:read(4096, out)
|
||||
if n == 0 then
|
||||
break
|
||||
end
|
||||
for i = 0, n * 2 - 1 do
|
||||
local v = buffer.readf32(b, i * 4)
|
||||
sumsq += v * v
|
||||
peak = math.max(peak, math.abs(v))
|
||||
end
|
||||
total += n
|
||||
end
|
||||
t:eq(total, want, "render: reads every frame")
|
||||
local rms = math.sqrt(sumsq / (total * 2))
|
||||
t:check(rms > 0.01 and peak < 4 and peak == peak, string.format("render: audible and sane (rms %.3f, peak %.3f)", rms, peak))
|
||||
t:note("fallback render: %.2f s, rms %.3f, peak %.3f", total / 44100, rms, peak)
|
||||
-- seek: the same samples as playing through
|
||||
local a = song:render({ tail = 0.5 })
|
||||
a:seek(1.5)
|
||||
t:check(math.abs(a:position() - 1.5) < 1e-4, "seek position")
|
||||
local x = buffer.create(1024 * 8)
|
||||
a:read(1024, x)
|
||||
local c = song:render({ tail = 0.5 })
|
||||
c:read(66150)
|
||||
local y = c:read(1024)
|
||||
local same = true
|
||||
for i = 0, 2047 do
|
||||
if buffer.readf32(x, i * 4) ~= buffer.readf32(y, i * 4) then
|
||||
same = false
|
||||
break
|
||||
end
|
||||
end
|
||||
t:check(same, "seek renders the same samples as reading through")
|
||||
a:seek(0.25) -- backwards
|
||||
t:check(math.abs(a:position() - 0.25) < 1e-4, "seek backwards")
|
||||
-- open = decode + render
|
||||
local o = Midi.open(Bytes.reader(buffer.fromstring(byName.song.data)), { sampleRate = 22050, tail = 0 })
|
||||
t:check(o and o.sampleRate == 22050, "open: a Decoder at the asked rate")
|
||||
local bad, berr = Midi.render(song, { sampleRate = 5 })
|
||||
t:check(bad == nil and berr.code == Err.ARG, "render: bad sampleRate")
|
||||
local bs, bserr = Midi.render(song, { soundfont = "not a soundfont" })
|
||||
t:check(bs == nil and Err.is(bserr), "render: bad soundfont bytes")
|
||||
end
|
||||
|
||||
-- the fuzz no-throw pass
|
||||
local samples = {}
|
||||
for _, c in Cases do
|
||||
if #c.data < 20000 then
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return decode(b)
|
||||
end, samples, { mutations = 40 })
|
||||
t:fuzz("decode + render", function(b: buffer)
|
||||
local m = decode(b)
|
||||
if m then
|
||||
local dec = Midi.render(m, { tail = 0.1 })
|
||||
if dec then
|
||||
dec:read(2048)
|
||||
dec:read(2048)
|
||||
end
|
||||
Midi.encode(m)
|
||||
end
|
||||
end, samples, { mutations = 20, garbage = 50 })
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,127 @@
|
||||
-- music/mod tests: generated ProTracker modules (tools/fixtures/mod.py) parsed, rendered through codecs/Tracker and
|
||||
-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the MOD writer's
|
||||
-- round trip, the contract, and the fuzz no-throw pass.
|
||||
local T = require("@tests/T")
|
||||
local S = require("@tests/music/_similar")
|
||||
local Mod = require("@formats/music/mod")
|
||||
local Tracker = require("@formats/codecs/Tracker")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/mod_cases")
|
||||
|
||||
local t = T.suite("mod")
|
||||
|
||||
t:eq(Mod.name, "mod", "name")
|
||||
t:eq(Mod.category, "music", "category")
|
||||
t:check(Mod.caps.decode and Mod.caps.encode, "caps")
|
||||
|
||||
local function load(data: string): any
|
||||
return Mod.decode(Bytes.reader(buffer.fromstring(data)))
|
||||
end
|
||||
|
||||
local THRESH = { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }
|
||||
|
||||
for _, c in Cases do
|
||||
local m, err = load(c.data)
|
||||
t:check(m, c.name .. ": " .. tostring(err))
|
||||
t:check(Mod.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff")
|
||||
local dec = m:render({ sampleRate = S.SR })
|
||||
t:check(dec, c.name .. ": render")
|
||||
t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration))
|
||||
local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR))
|
||||
local r = S.compare(S.features(buf, frames), c.ref)
|
||||
t:note("%-7s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envErr, r.spectral, r.balance, dec.duration)
|
||||
if r.spectral < THRESH.spectral or r.envErr > THRESH.envErr then
|
||||
for _, w in S.worst(S.features(buf, frames), c.ref, 6) do
|
||||
t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4])
|
||||
end
|
||||
end
|
||||
t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness")
|
||||
t:check(r.envErr < THRESH.envErr, c.name .. ": loudness envelope")
|
||||
t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum")
|
||||
t:check(r.balance < THRESH.balance, c.name .. ": stereo balance")
|
||||
-- the writer: MOD -> MOD gives the same bytes back (the fixtures are canonical ProTracker files)
|
||||
local out, werr = Mod.encode(m)
|
||||
t:check(out, c.name .. ": encode " .. tostring(werr))
|
||||
local m2 = Mod.decode(Bytes.reader(out :: buffer))
|
||||
t:check(m2, c.name .. ": re-decode")
|
||||
t:eq(buffer.tostring(out :: buffer), c.data, c.name .. ": round trip bytes")
|
||||
end
|
||||
|
||||
-- MOD -> XM: the converted module plays as long, and sounds alike (XM has no channel panning and uses FT2's NTSC
|
||||
-- Amiga clock, so only the duration and the band spectrum are compared)
|
||||
local Xm = require("@formats/music/xm")
|
||||
for _, c in Cases do
|
||||
local m = load(c.data)
|
||||
local xb, xerr = Xm.encode(m)
|
||||
t:check(xb, c.name .. ": mod -> xm " .. tostring(xerr))
|
||||
local x = Xm.decode(Bytes.reader(xb :: buffer))
|
||||
t:check(x and x.format == "xm" and #x.instruments == #m.samples, c.name .. ": the xm decodes")
|
||||
local dec = x:render()
|
||||
t:check(math.abs(dec.duration - c.duration) < THRESH.duration, c.name .. ": xm duration")
|
||||
local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR))
|
||||
local r = S.compare(S.features(buf, frames), c.ref)
|
||||
t:check(r.spectral > 0.9, string.format("%s: xm spectrum %.3f", c.name, r.spectral))
|
||||
end
|
||||
|
||||
-- through the API: load sniffs the MOD, open gives a Decoder, save converts to XM, load(as audio) renders
|
||||
do
|
||||
local F = require("@formats")
|
||||
local m, err = F.load(Cases[1].data)
|
||||
t:check(m and m.kind == "music" and m.format == "mod", "F.load: " .. tostring(err))
|
||||
local dec = F.open(Cases[1].data)
|
||||
t:check(dec and dec.channels == 2 and dec.sampleRate == 44100, "F.open: a Decoder")
|
||||
local xb = F.save(m, nil, { format = "xm" })
|
||||
t:check(xb and F.load(xb).format == "xm", "F.save as xm")
|
||||
t:eq(F.saveString(m, { format = "mod" }), Cases[1].data, "F.saveString keeps the MOD bytes")
|
||||
end
|
||||
|
||||
-- seek: the position after a seek and the output continuing
|
||||
do
|
||||
local m = load(Cases[1].data)
|
||||
local dec = m:render()
|
||||
dec:seek(2)
|
||||
t:check(math.abs(dec:position() - 2) < 0.001, "seek position")
|
||||
local _, n = dec:read(1000)
|
||||
t:eq(n, 1000, "read after seek")
|
||||
t:check(Tracker.duration(m) == dec.duration, "duration()")
|
||||
-- the same samples as playing up to that point (after the short fade-in that follows a seek)
|
||||
local a, b = m:render(), m:render()
|
||||
a:seek(3.5)
|
||||
local at = math.floor(3.5 * S.SR)
|
||||
while at > 0 do
|
||||
local _, n = b:read(math.min(at, 8192))
|
||||
at -= n
|
||||
end
|
||||
local x, y = a:read(4096), b:read(4096)
|
||||
local worst = 0
|
||||
for i = 256, 4095 * 2 do
|
||||
worst = math.max(worst, math.abs(buffer.readf32(x, i * 4) - buffer.readf32(y, i * 4)))
|
||||
end
|
||||
t:check(worst < 1e-4, "seek then read matches reading through (" .. worst .. ")")
|
||||
-- loop = true keeps playing past the end (frames / duration still give one pass)
|
||||
local l = m:render({ loop = true, sampleRate = 8000 })
|
||||
local total = 0
|
||||
for _ = 1, 30 do
|
||||
local _, n = l:read(8000)
|
||||
total += n
|
||||
end
|
||||
t:check(total == 240000 and math.abs(l.duration - dec.duration) < 0.01, "loop plays past the end")
|
||||
end
|
||||
|
||||
-- the fuzz pass: decode, and a short render of whatever decodes
|
||||
local samples = {}
|
||||
for _, c in Cases do
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local m = Mod.decode(Bytes.reader(b))
|
||||
if m then
|
||||
local dec = Tracker.render(m, { maxDuration = 0.5, sampleRate = 8000 })
|
||||
if dec then
|
||||
dec:read(4000)
|
||||
end
|
||||
end
|
||||
return m
|
||||
end, samples, { mutations = 30 })
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,71 @@
|
||||
-- music/s3m tests: generated Scream Tracker 3 modules (tools/fixtures/s3m.py) parsed, rendered through codecs/Tracker and
|
||||
-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the contract,
|
||||
-- and the fuzz no-throw pass.
|
||||
local T = require("@tests/T")
|
||||
local S = require("@tests/music/_similar")
|
||||
local S3m = require("@formats/music/s3m")
|
||||
local Tracker = require("@formats/codecs/Tracker")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/s3m_cases")
|
||||
|
||||
local t = T.suite("s3m")
|
||||
|
||||
t:eq(S3m.name, "s3m", "name")
|
||||
t:eq(S3m.category, "music", "category")
|
||||
t:check(S3m.caps.decode and not S3m.caps.encode, "caps")
|
||||
|
||||
local function load(data: string): any
|
||||
return S3m.decode(Bytes.reader(buffer.fromstring(data)))
|
||||
end
|
||||
|
||||
local THRESH = { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }
|
||||
|
||||
for _, c in Cases do
|
||||
local m, err = load(c.data)
|
||||
t:check(m, c.name .. ": " .. tostring(err))
|
||||
t:check(S3m.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff")
|
||||
local dec = m:render({ sampleRate = S.SR })
|
||||
t:check(dec, c.name .. ": render")
|
||||
t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration))
|
||||
local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR))
|
||||
local r = S.compare(S.features(buf, frames), c.ref)
|
||||
t:note("%-7s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envErr, r.spectral, r.balance, dec.duration)
|
||||
if r.spectral < THRESH.spectral or r.envErr > THRESH.envErr then
|
||||
for _, w in S.worst(S.features(buf, frames), c.ref, 6) do
|
||||
t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4])
|
||||
end
|
||||
end
|
||||
t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness")
|
||||
t:check(r.envErr < THRESH.envErr, c.name .. ": loudness envelope")
|
||||
t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum")
|
||||
t:check(r.balance < THRESH.balance, c.name .. ": stereo balance")
|
||||
end
|
||||
|
||||
-- seek: the position after a seek and the output continuing
|
||||
do
|
||||
local m = load(Cases[1].data)
|
||||
local dec = m:render()
|
||||
dec:seek(2)
|
||||
t:check(math.abs(dec:position() - 2) < 0.001, "seek position")
|
||||
local _, n = dec:read(1000)
|
||||
t:eq(n, 1000, "read after seek")
|
||||
t:check(Tracker.duration(m) == dec.duration, "duration()")
|
||||
end
|
||||
|
||||
-- the fuzz pass: decode, and a short render of whatever decodes
|
||||
local samples = {}
|
||||
for _, c in Cases do
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local m = S3m.decode(Bytes.reader(b))
|
||||
if m then
|
||||
local dec = Tracker.render(m, { maxDuration = 0.5, sampleRate = 8000 })
|
||||
if dec then
|
||||
dec:read(4000)
|
||||
end
|
||||
end
|
||||
return m
|
||||
end, samples, { mutations = 30 })
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,338 @@
|
||||
-- music/sf2 + codecs/SoundFont tests: a self-made SF2 parsed (INFO, presets, sample headers, instruments, generator
|
||||
-- merging with preset / instrument global zones, 16-bit and sm24 samples), a test song rendered through it compared
|
||||
-- with FluidSynth's render (loudness envelope and per-segment band spectra by correlation, pitch peaks), bad files,
|
||||
-- the built-in fallback waveform set, and the fuzz no-throw pass. Fixtures: tools/fixtures/sf2.py.
|
||||
local T = require("@tests/T")
|
||||
local Sf2 = require("@formats/music/sf2")
|
||||
local Midi = require("@formats/music/midi")
|
||||
local SoundFont = require("@formats/codecs/SoundFont")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Fx = require("@tests/gen/sf2_cases")
|
||||
|
||||
local t = T.suite("sf2")
|
||||
|
||||
local function reader(s: string): Bytes.Reader
|
||||
return Bytes.reader(buffer.fromstring(s))
|
||||
end
|
||||
|
||||
-- the contract
|
||||
t:eq(Sf2.name, "sf2", "name")
|
||||
t:eq(Sf2.category, "music", "category")
|
||||
t:check(Sf2.caps.decode and not Sf2.caps.encode, "caps")
|
||||
t:eq(Sf2.sniff(reader(Fx.sf2)), 1, "sniff")
|
||||
t:eq(Sf2.sniff(reader("RIFF\0\0\0\0WAVE")), 0, "sniff WAVE")
|
||||
|
||||
-- parse
|
||||
local sf, err = Sf2.decode(reader(Fx.sf2))
|
||||
t:check(sf, "decode: " .. tostring(err))
|
||||
local E = Fx.expect
|
||||
t:eq(sf.kind, "soundfont", "kind")
|
||||
t:eq(sf.info.name, E.info.name, "INAM")
|
||||
t:eq(sf.info.engine, E.info.engine, "isng")
|
||||
t:eq(sf.meta.source.version, E.info.version, "ifil")
|
||||
t:eq(#sf.presets, #E.presets, "preset count")
|
||||
for i, p in E.presets do
|
||||
t:eq(sf.presets[i].name, p.name, "preset " .. i .. " name")
|
||||
t:eq(sf.presets[i].bank, p.bank, "preset " .. i .. " bank")
|
||||
t:eq(sf.presets[i].preset, p.preset, "preset " .. i .. " number")
|
||||
end
|
||||
t:eq(#sf.sampleHeaders, #E.samples, "sample headers")
|
||||
for i, s in E.samples do
|
||||
for k, v in s do
|
||||
t:eq(sf.sampleHeaders[i][k], v, "sample " .. i .. " " .. k)
|
||||
end
|
||||
end
|
||||
for i, n in E.instruments do
|
||||
t:eq(sf.instruments[i].name, n, "instrument " .. i)
|
||||
end
|
||||
local function preset(name: string): any
|
||||
for _, p in sf.presets do
|
||||
if p.name == name then
|
||||
return p
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
do
|
||||
local sine, saw, drums = preset("Sine"), preset("Saw"), preset("Drums")
|
||||
t:eq(#sine.regions, 1, "Sine: the preset global zone is not a region")
|
||||
t:check(math.abs(sine.regions[1].attenuation - 30 * 0.04) < 1e-9, "Sine: the preset global zone's attenuation applies")
|
||||
t:check(math.abs(sine.regions[1].aRelease - 0.2) < 0.001, "Sine: release in seconds")
|
||||
t:check(math.abs(sine.regions[1].aSustain - 10 ^ (-6 / 20)) < 1e-6, "Sine: sustain 60 cB = -6 dB")
|
||||
t:eq(sine.regions[1].loopMode, 1, "Sine: looped")
|
||||
t:eq(sine.regions[1].keycenter, 69, "Sine: root key from the sample header")
|
||||
t:eq(sine.regions[1].tune, -4, "Sine: pitch correction")
|
||||
t:eq(#saw.regions, 1, "Saw: the instrument global zone is not a region")
|
||||
t:check(math.abs(saw.regions[1].filterFc - math.floor(1200 * math.log(2500 / 8.176, 2) + 0.5)) <= 1, "Saw: the instrument global zone's filter applies")
|
||||
t:eq(saw.regions[1].modEnvToFilterFc, 2400, "Saw: mod env to filter")
|
||||
t:eq(#drums.regions, 4, "Drums: four key zones")
|
||||
local groups = 0
|
||||
for _, r in drums.regions do
|
||||
t:check(math.abs(r.aRelease - 0.05) < 0.001, "Drums: release from the instrument global zone")
|
||||
if r.group == 1 then
|
||||
groups += 1
|
||||
end
|
||||
end
|
||||
t:eq(groups, 2, "Drums: two hats in exclusive class 1")
|
||||
t:eq(drums.regions[1].lokey, 35, "Drums: key range lo")
|
||||
t:eq(drums.regions[1].hikey, 36, "Drums: key range hi")
|
||||
end
|
||||
-- samples: 16-bit, and 24-bit with sm24
|
||||
do
|
||||
local sf24 = Sf2.decode(reader(Fx.sf2_24))
|
||||
t:check(sf24 and sf24.meta.source.sm24, "sm24 read")
|
||||
t:eq(sf.meta.source.sm24, false, "no sm24")
|
||||
for _, v in E.values do
|
||||
local i, hi, lo = v[1], v[2], v[3]
|
||||
local a = buffer.readf32(sf.samples, i * 4)
|
||||
local b = buffer.readf32(sf24.samples, i * 4)
|
||||
t:check(math.abs(a - hi / 32767) < 1e-6, "16-bit sample " .. i)
|
||||
t:check(math.abs(b - (hi * 256 + lo) / 8388607) < 1e-6, "24-bit sample " .. i)
|
||||
end
|
||||
t:eq(buffer.len(sf.samples), (sf.sampleCount + 1) * 4, "samples: one pad sample")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ vs FluidSynth
|
||||
local F = Fx.fluid
|
||||
local song = Midi.decode(reader(Fx.song))
|
||||
t:check(song, "song decodes")
|
||||
local dec = assert(Midi.render(song, { soundfont = sf, tail = 2 }))
|
||||
local frames = math.min(dec.frames, F.frames)
|
||||
local mono = table.create(frames, 0)
|
||||
do
|
||||
local got = 0
|
||||
while got < frames do
|
||||
local b, n = dec:read(math.min(8192, frames - got))
|
||||
if n == 0 then
|
||||
break
|
||||
end
|
||||
for i = 0, n - 1 do
|
||||
mono[got + i + 1] = (buffer.readf32(b, i * 8) + buffer.readf32(b, i * 8 + 4)) * 0.5
|
||||
end
|
||||
got += n
|
||||
end
|
||||
t:eq(got, frames, "rendered the compared length")
|
||||
end
|
||||
|
||||
local function pearson(a: { number }, b: { number }): number
|
||||
local n = math.min(#a, #b)
|
||||
local ma, mb = 0, 0
|
||||
for i = 1, n do
|
||||
ma += a[i]
|
||||
mb += b[i]
|
||||
end
|
||||
ma /= n
|
||||
mb /= n
|
||||
local sab, saa, sbb = 0, 0, 0
|
||||
for i = 1, n do
|
||||
local x, y = a[i] - ma, b[i] - mb
|
||||
sab += x * y
|
||||
saa += x * x
|
||||
sbb += y * y
|
||||
end
|
||||
return sab / math.sqrt(saa * sbb + 1e-30)
|
||||
end
|
||||
|
||||
-- in-place radix-2 FFT of re / im (1-based arrays of length n, a power of two)
|
||||
local function fft(re: { number }, im: { number }, n: number)
|
||||
local j = 0
|
||||
for i = 0, n - 2 do
|
||||
if i < j then
|
||||
re[i + 1], re[j + 1] = re[j + 1], re[i + 1]
|
||||
im[i + 1], im[j + 1] = im[j + 1], im[i + 1]
|
||||
end
|
||||
local m = n // 2
|
||||
while m >= 1 and j >= m do
|
||||
j -= m
|
||||
m //= 2
|
||||
end
|
||||
j += m
|
||||
end
|
||||
local len = 2
|
||||
while len <= n do
|
||||
local ang = -2 * math.pi / len
|
||||
local wr, wi = math.cos(ang), math.sin(ang)
|
||||
for s = 0, n - 1, len do
|
||||
local cr, ci = 1, 0
|
||||
for k = 0, len // 2 - 1 do
|
||||
local a, b = s + k + 1, s + k + len // 2 + 1
|
||||
local xr = re[b] * cr - im[b] * ci
|
||||
local xi = re[b] * ci + im[b] * cr
|
||||
re[b], im[b] = re[a] - xr, im[a] - xi
|
||||
re[a], im[a] = re[a] + xr, im[a] + xi
|
||||
cr, ci = cr * wr - ci * wi, cr * wi + ci * wr
|
||||
end
|
||||
end
|
||||
len *= 2
|
||||
end
|
||||
end
|
||||
|
||||
local function power(start: number, n: number): { number }
|
||||
local re, im = table.create(n, 0), table.create(n, 0)
|
||||
for i = 0, n - 1 do
|
||||
re[i + 1] = (mono[start + i + 1] or 0) * (0.5 - 0.5 * math.cos(2 * math.pi * i / n))
|
||||
end
|
||||
fft(re, im, n)
|
||||
local p = table.create(n // 2 + 1, 0)
|
||||
for k = 0, n // 2 do
|
||||
p[k + 1] = re[k + 1] ^ 2 + im[k + 1] ^ 2
|
||||
end
|
||||
return p
|
||||
end
|
||||
|
||||
local rate = F.rate
|
||||
-- the loudness envelope (50 ms RMS)
|
||||
local env = {}
|
||||
for i = 0, frames - 2205, 2205 do
|
||||
local s = 0
|
||||
for k = 1, 2205 do
|
||||
local v = mono[i + k]
|
||||
s += v * v
|
||||
end
|
||||
table.insert(env, math.sqrt(s / 2205))
|
||||
end
|
||||
local envCorr = pearson(env, F.env)
|
||||
local ENV_MIN = 0.95
|
||||
t:check(envCorr > ENV_MIN, string.format("loudness envelope correlation %.3f > %.2f", envCorr, ENV_MIN))
|
||||
t:note("loudness envelope vs FluidSynth: r = %.3f (%d windows)", envCorr, #env)
|
||||
|
||||
-- per-segment band spectra
|
||||
local BAND_MIN = 0.93
|
||||
local worstBand = 1
|
||||
for si, seg in F.segments do
|
||||
local acc = table.create(24, 0)
|
||||
local count = 0
|
||||
for s = math.floor(seg[1] * rate), math.floor(seg[2] * rate) - 2048, 1024 do
|
||||
local p = power(s, 2048)
|
||||
for k = 0, 1024 do
|
||||
local f = k * rate / 2048
|
||||
for b = 1, 24 do
|
||||
if f >= F.edges[b] and f < F.edges[b + 1] then
|
||||
acc[b] += p[k + 1]
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
count += 1
|
||||
end
|
||||
local db = table.create(24, 0)
|
||||
for b = 1, 24 do
|
||||
db[b] = 10 * math.log10(acc[b] / math.max(count, 1) + 1e-12)
|
||||
end
|
||||
local r = pearson(db, F.bands[si])
|
||||
worstBand = math.min(worstBand, r)
|
||||
t:check(r > BAND_MIN, string.format("segment %d band spectrum correlation %.3f > %.2f", si, r, BAND_MIN))
|
||||
t:note("segment %d (%g-%g s) band spectrum vs FluidSynth: r = %.3f", si, seg[1], seg[2], r)
|
||||
end
|
||||
|
||||
-- pitch peaks (vibrato square, a note bent an octave with an RPN 0 range of 12, the saw melody's first note)
|
||||
for wi, w in F.windows do
|
||||
local acc = table.create(4097, 0)
|
||||
for s = math.floor(w[1] * rate), math.floor(w[2] * rate) - 8192, 2048 do
|
||||
local p = power(s, 8192)
|
||||
for k = 1, 4097 do
|
||||
acc[k] += p[k]
|
||||
end
|
||||
end
|
||||
local best, bk = -1, 2
|
||||
for k = 2, 4096 do
|
||||
if acc[k] > best then
|
||||
best, bk = acc[k], k
|
||||
end
|
||||
end
|
||||
local y0, y1, y2 = math.log(acc[bk - 1] + 1e-30), math.log(acc[bk] + 1e-30), math.log(acc[bk + 1] + 1e-30)
|
||||
local hz = ((bk - 1) + 0.5 * (y0 - y2) / (y0 - 2 * y1 + y2)) * rate / 8192
|
||||
local ratio = hz / F.peaks[wi]
|
||||
t:check(math.abs(ratio - 1) < 0.015, string.format("window %d peak %.1f Hz vs FluidSynth %.1f Hz", wi, hz, F.peaks[wi]))
|
||||
t:note("window %g-%g s: peak %.1f Hz (FluidSynth %.1f Hz)", w[1], w[2], hz, F.peaks[wi])
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ bad files
|
||||
local function bad(data: string, code: string, label: string)
|
||||
local ok, v, e = pcall(Sf2.decode, reader(data))
|
||||
t:check(ok, label .. ": threw " .. tostring(v))
|
||||
t:check(v == nil and Err.is(e) and e.code == code, label .. ": " .. tostring(e))
|
||||
end
|
||||
bad("RIFX\0\0\0\0sfbk", Err.CORRUPT, "not RIFF")
|
||||
bad("RIFF\4\0\0\0WAVE", Err.CORRUPT, "not sfbk")
|
||||
bad("RIFF\4\0\0\0sfbk", Err.CORRUPT, "no chunks")
|
||||
bad(string.sub(Fx.sf2, 1, 40), Err.CORRUPT, "truncated in INFO")
|
||||
local lim, lerr = Sf2.decode(reader(Fx.sf2), { maxSamples = 100 })
|
||||
t:check(lim == nil and lerr.code == Err.LIMIT, "maxSamples: LIMIT")
|
||||
local lim2, lerr2 = Sf2.decode(reader(Fx.sf2), { maxRegions = 3 })
|
||||
t:check(lim2 == nil and lerr2.code == Err.LIMIT, "maxRegions: LIMIT")
|
||||
local p, perr = SoundFont.parse(42 :: any)
|
||||
t:check(p == nil and perr.code == Err.ARG, "parse: bad argument")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ fallback
|
||||
do
|
||||
local fb = SoundFont.fallback()
|
||||
t:eq(#fb.presets, 129, "fallback: 128 programs + a drum kit")
|
||||
local s = SoundFont.synth(nil, 22050)
|
||||
local Synth = SoundFont.Synth
|
||||
local out = buffer.create(2205 * 8)
|
||||
for program = 0, 127, 8 do
|
||||
Synth.reset(s)
|
||||
Synth.midi(s, 0xC0, program, 0)
|
||||
Synth.midi(s, 0x90, 60, 100)
|
||||
buffer.fill(out, 0, 0)
|
||||
Synth.render(s, out, 0, 2205)
|
||||
local e = 0
|
||||
for i = 0, 2205 * 2 - 1 do
|
||||
local v = buffer.readf32(out, i * 4)
|
||||
t:check(v == v and math.abs(v) < 4, "fallback: finite samples")
|
||||
e += v * v
|
||||
end
|
||||
t:check(e > 0.01, "fallback program " .. program .. " sounds")
|
||||
end
|
||||
for _, key in { 35, 36, 38, 42, 46, 49, 51, 60 } do
|
||||
Synth.reset(s)
|
||||
Synth.midi(s, 0x99, key, 120)
|
||||
buffer.fill(out, 0, 0)
|
||||
Synth.render(s, out, 0, 2205)
|
||||
local e = 0
|
||||
for i = 0, 2205 * 2 - 1 do
|
||||
e += buffer.readf32(out, i * 4) ^ 2
|
||||
end
|
||||
t:check(e > 0.01, "fallback drum " .. key .. " sounds")
|
||||
end
|
||||
-- exclusive class: a closed hat cuts the open hat
|
||||
Synth.reset(s)
|
||||
Synth.midi(s, 0x99, 46, 120)
|
||||
t:eq(Synth.active(s), 1, "open hat")
|
||||
Synth.midi(s, 0x99, 42, 120)
|
||||
Synth.render(s, out, 0, 2205)
|
||||
t:eq(Synth.active(s), 1, "closed hat ends the open hat (exclusive class)")
|
||||
-- render range clipping: never writes past the buffer
|
||||
Synth.render(s, out, 2200, 100000)
|
||||
Synth.render(s, out, -5, 10)
|
||||
t:check(true, "out-of-range render requests are clipped")
|
||||
end
|
||||
|
||||
-- the fuzz no-throw pass (parse, then a few notes through whatever parsed)
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local f = Sf2.decode(Bytes.reader(b))
|
||||
if f then
|
||||
local s = SoundFont.synth(f, 22050)
|
||||
for ch = 0, 15 do
|
||||
SoundFont.Synth.midi(s, 0xC0 + ch, ch * 8, 0)
|
||||
SoundFont.Synth.midi(s, 0x90 + ch, 30 + ch * 5, 100)
|
||||
end
|
||||
local out = buffer.create(512 * 8)
|
||||
SoundFont.Synth.render(s, out, 0, 512)
|
||||
end
|
||||
end, { Fx.sf2 }, { mutations = 60, garbage = 100 })
|
||||
-- mutations inside the hydra (the last ~1 KB) exercise the zone / index clamping
|
||||
t:fuzz("hydra", function(b: buffer)
|
||||
local f = Sf2.decode(Bytes.reader(b))
|
||||
if f then
|
||||
local s = SoundFont.synth(f, 22050)
|
||||
SoundFont.Synth.midi(s, 0x90, 60, 100)
|
||||
SoundFont.Synth.midi(s, 0x99, 36, 100)
|
||||
local out = buffer.create(256 * 8)
|
||||
SoundFont.Synth.render(s, out, 0, 256)
|
||||
end
|
||||
end, { Fx.sf2 }, { mutations = 200, garbage = 0, keepHeader = #Fx.sf2 - 1200 })
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,77 @@
|
||||
-- music/xm tests: generated FastTracker 2 modules (tools/fixtures/xm.py) parsed, rendered through codecs/Tracker and
|
||||
-- compared with openmpt123's render (loudness envelope, band spectrum, stereo balance, song length), the XM writer's
|
||||
-- round trip, the contract, and the fuzz no-throw pass.
|
||||
local T = require("@tests/T")
|
||||
local S = require("@tests/music/_similar")
|
||||
local Xm = require("@formats/music/xm")
|
||||
local Tracker = require("@formats/codecs/Tracker")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/xm_cases")
|
||||
|
||||
local t = T.suite("xm")
|
||||
|
||||
t:eq(Xm.name, "xm", "name")
|
||||
t:eq(Xm.category, "music", "category")
|
||||
t:check(Xm.caps.decode and Xm.caps.encode, "caps")
|
||||
|
||||
local function load(data: string): any
|
||||
return Xm.decode(Bytes.reader(buffer.fromstring(data)))
|
||||
end
|
||||
|
||||
local THRESH = { gainDb = 0.5, envErr = 1.0, spectral = 0.95, balance = 0.04, duration = 0.01 }
|
||||
|
||||
for _, c in Cases do
|
||||
local m, err = load(c.data)
|
||||
t:check(m, c.name .. ": " .. tostring(err))
|
||||
t:check(Xm.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, c.name .. ": sniff")
|
||||
local dec = m:render({ sampleRate = S.SR })
|
||||
t:check(dec, c.name .. ": render")
|
||||
t:check(math.abs(dec.duration - c.duration) < THRESH.duration, string.format("%s: duration %.3f s, openmpt %.3f s", c.name, dec.duration, c.duration))
|
||||
local buf, frames = S.renderAll(dec, math.floor(c.duration * S.SR))
|
||||
local r = S.compare(S.features(buf, frames), c.ref)
|
||||
t:note("%-7s gain %+.2f dB, loudness error %.2f dB, spectrum %.3f, balance %.3f, %.2f s", c.name, r.gainDb, r.envErr, r.spectral, r.balance, dec.duration)
|
||||
if r.spectral < THRESH.spectral or r.envErr > THRESH.envErr then
|
||||
for _, w in S.worst(S.features(buf, frames), c.ref, 6) do
|
||||
t:note(" block %d (%.2f s): spectrum %.3f, ours %.1f dB, ref %.1f dB", w[1], (w[1] - 1) * 2048 / S.SR, w[2], w[3], w[4])
|
||||
end
|
||||
end
|
||||
t:check(math.abs(r.gainDb) < THRESH.gainDb, c.name .. ": loudness")
|
||||
t:check(r.envErr < THRESH.envErr, c.name .. ": loudness envelope")
|
||||
t:check(r.spectral > THRESH.spectral, c.name .. ": spectrum")
|
||||
t:check(r.balance < THRESH.balance, c.name .. ": stereo balance")
|
||||
-- the writer: XM -> XM gives the same bytes back (the fixtures use the FT2 layout)
|
||||
local out, werr = Xm.encode(m)
|
||||
t:check(out, c.name .. ": encode " .. tostring(werr))
|
||||
local m2 = Xm.decode(Bytes.reader(out :: buffer))
|
||||
t:check(m2, c.name .. ": re-decode")
|
||||
t:eq(buffer.tostring(out :: buffer), c.data, c.name .. ": round trip bytes")
|
||||
end
|
||||
|
||||
-- seek: the position after a seek and the output continuing
|
||||
do
|
||||
local m = load(Cases[1].data)
|
||||
local dec = m:render()
|
||||
dec:seek(2)
|
||||
t:check(math.abs(dec:position() - 2) < 0.001, "seek position")
|
||||
local _, n = dec:read(1000)
|
||||
t:eq(n, 1000, "read after seek")
|
||||
t:check(Tracker.duration(m) == dec.duration, "duration()")
|
||||
end
|
||||
|
||||
-- the fuzz pass: decode, and a short render of whatever decodes
|
||||
local samples = {}
|
||||
for _, c in Cases do
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local m = Xm.decode(Bytes.reader(b))
|
||||
if m then
|
||||
local dec = Tracker.render(m, { maxDuration = 0.5, sampleRate = 8000 })
|
||||
if dec then
|
||||
dec:read(4000)
|
||||
end
|
||||
end
|
||||
return m
|
||||
end, samples, { mutations = 30 })
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,221 @@
|
||||
-- tests/video/_common: shared checks for the video container tests (mkv, avi, y4m, mpegts, mpegps, mp4): a demuxer's
|
||||
-- tracks and packets against ffprobe's, decoded frames against ffmpeg's (CRC-32 for bit-exact codecs, PSNR for the
|
||||
-- others), audio through the api's hook against ffmpeg's f32 decode, seeking. Not a test by itself.
|
||||
local F = require("@formats")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Video = require("@formats/codecs/Video")
|
||||
|
||||
local C = {}
|
||||
|
||||
-- the codecs whose decode must equal ffmpeg's bit for bit
|
||||
C.EXACT = { vp8 = true, rawvideo = true }
|
||||
|
||||
-- psnr(a, b, off?, n?) -> dB between two byte strings / buffers (math.huge when equal)
|
||||
function C.psnr(a: buffer, b: buffer, n: number?): number
|
||||
local len = n or math.min(buffer.len(a), buffer.len(b))
|
||||
local se = 0
|
||||
for i = 0, len - 1 do
|
||||
local d = buffer.readu8(a, i) - buffer.readu8(b, i)
|
||||
se += d * d
|
||||
end
|
||||
if se == 0 then
|
||||
return math.huge
|
||||
end
|
||||
return 10 * math.log10(255 * 255 * len / se)
|
||||
end
|
||||
|
||||
-- snr(ours f32 buffer, reference f32 string, n samples) -> dB
|
||||
function C.snr(ours: buffer, ref: string, n: number): number
|
||||
local rb = buffer.fromstring(ref)
|
||||
local sig, err = 0, 0
|
||||
for i = 0, n - 1 do
|
||||
local r = buffer.readf32(rb, i * 4)
|
||||
local d = buffer.readf32(ours, i * 4) - r
|
||||
sig += r * r
|
||||
err += d * d
|
||||
end
|
||||
if err == 0 then
|
||||
return math.huge
|
||||
end
|
||||
return 10 * math.log10(sig / err)
|
||||
end
|
||||
|
||||
-- packets(t, dmx, c, label, opts?): every track's packets against ffprobe's (in order): size, CRC, time, keyframe.
|
||||
-- opts.skipStream(ffprobePacket, track) -> true skips a stream (ffmpeg's parsers re-split some, e.g. MPEG audio in TS)
|
||||
function C.packets(t: any, dmx: any, c: any, label: string, opts: any?)
|
||||
local o = opts or {}
|
||||
local trackOf = {} -- ffprobe stream index -> our track
|
||||
for i, s in c.streams do
|
||||
trackOf[s.index] = o.trackFor and o.trackFor(dmx, s) or dmx.tracks[i]
|
||||
end
|
||||
local k: { [number]: number } = {}
|
||||
local total, bad = 0, 0
|
||||
local first = nil
|
||||
for _, want in c.packets do
|
||||
local tr = trackOf[want.stream]
|
||||
if not (o.skipStream and o.skipStream(want, tr)) then
|
||||
total += 1
|
||||
local id = if tr then tr.id else -1
|
||||
k[id] = (k[id] or 0) + 1
|
||||
local p = if tr then dmx:get(id, k[id]) else nil
|
||||
local ok = p ~= nil and buffer.len(p.data) == want.size and Crc32.of(p.data) == want.crc
|
||||
local s = c.streams[want.stream + 1]
|
||||
if ok and p and want.pts and s and not o.noPts then
|
||||
local ours = p.pts / tr.timescale - (tr.codecDelay or 0) -- ffmpeg shifts by Matroska's CodecDelay
|
||||
local theirs = want.pts * s.tbn / s.tbd
|
||||
ok = math.abs(ours - theirs) < 0.0015
|
||||
end
|
||||
if ok and p and not o.noKey and tr and tr.kind == "video" then
|
||||
ok = p.keyframe == want.key
|
||||
end
|
||||
if not ok then
|
||||
bad += 1
|
||||
if not first then
|
||||
first = string.format("track %s packet %d: size %s/%d pts %s/%s key %s/%s crc %s", tostring(id), k[id], tostring(p and buffer.len(p.data)), want.size, tostring(p and p.pts), tostring(want.pts), tostring(p and p.keyframe), tostring(want.key), tostring(p and Crc32.of(p.data) == want.crc))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local extra = 0
|
||||
for id, n in k do
|
||||
extra += math.max(0, dmx:count(id) - n)
|
||||
end
|
||||
t:check(bad == 0, label .. ": " .. total .. " packets equal ffprobe's (" .. bad .. " differ" .. (if first then "; first: " .. first else "") .. ")")
|
||||
t:check(extra == 0, label .. ": no extra packets (" .. extra .. ")")
|
||||
end
|
||||
|
||||
-- frames(t, v, c, label): every decoded frame against ffmpeg's (CRC for EXACT codecs, else PSNR of the raw ones)
|
||||
function C.frames(t: any, v: any, c: any, label: string, minPsnr: number?)
|
||||
if not c.frames then
|
||||
return
|
||||
end
|
||||
if not Video.canDecode(v.codec) then
|
||||
t:note("%s: no %s decoder, frames not checked", label, v.codec)
|
||||
return
|
||||
end
|
||||
v:reset()
|
||||
local n, bad, worst = 0, 0, math.huge
|
||||
local firstBad = nil
|
||||
while true do
|
||||
local f, err = v:nextFrame()
|
||||
if not f then
|
||||
t:check(err == nil, label .. ": decode error " .. tostring(err))
|
||||
break
|
||||
end
|
||||
n += 1
|
||||
local img = f.image
|
||||
if img.format ~= "yuv420p" then
|
||||
t:check(false, label .. ": frame " .. n .. " is " .. img.format)
|
||||
break
|
||||
end
|
||||
if C.EXACT[v.codec] then
|
||||
if Crc32.of(img.pixels) ~= c.frames[n] then
|
||||
bad += 1
|
||||
firstBad = firstBad or n
|
||||
end
|
||||
elseif c.yuv and c.yuv[n] then
|
||||
local p = C.psnr(img.pixels, buffer.fromstring(c.yuv[n]))
|
||||
worst = math.min(worst, p)
|
||||
end
|
||||
end
|
||||
t:eq(n, #c.frames, label .. ": frame count")
|
||||
if C.EXACT[v.codec] then
|
||||
t:check(bad == 0, label .. ": every frame bit-exact with ffmpeg (" .. bad .. " differ, first " .. tostring(firstBad) .. ")")
|
||||
elseif c.yuv then
|
||||
t:check(worst >= (minPsnr or 38), string.format("%s: PSNR vs ffmpeg %.1f dB", label, worst))
|
||||
end
|
||||
end
|
||||
|
||||
-- audio(t, v, c, label, exact?): the audio decoder (through the api hook) against ffmpeg's f32
|
||||
function C.audio(t: any, v: any, c: any, label: string, exact: boolean?, minSnr: number?)
|
||||
if not c.pcm then
|
||||
return
|
||||
end
|
||||
if not v.audio then
|
||||
local code = v.audioError and v.audioError.code
|
||||
t:check(code == F.Err.UNKNOWN_FORMAT or code == F.Err.UNSUPPORTED, label .. ": audio missing only for a missing audio format (" .. tostring(v.audioError) .. ")")
|
||||
return
|
||||
end
|
||||
local a = v.audio
|
||||
a:seek(0)
|
||||
local want = #c.pcm // 4
|
||||
local out = buffer.create(want * 4)
|
||||
local got = 0
|
||||
while got * a.channels < want do
|
||||
local chunk, k = a:read(want // a.channels - got)
|
||||
if not chunk or k <= 0 then
|
||||
break
|
||||
end
|
||||
buffer.copy(out, got * a.channels * 4, chunk, 0, k * a.channels * 4)
|
||||
got += k
|
||||
end
|
||||
local n = got * a.channels
|
||||
t:check(n == want or n * 4 == c.pcmBytes, label .. ": " .. n .. " samples read of " .. want)
|
||||
n = math.min(n, want)
|
||||
if exact then
|
||||
local same = true
|
||||
local rb = buffer.fromstring(c.pcm)
|
||||
for i = 0, n - 1 do
|
||||
if math.abs(buffer.readf32(out, i * 4) - buffer.readf32(rb, i * 4)) > 1e-6 then
|
||||
same = false
|
||||
break
|
||||
end
|
||||
end
|
||||
t:check(same, label .. ": PCM equal to ffmpeg's")
|
||||
else
|
||||
local s = C.snr(out, c.pcm, n)
|
||||
t:check(s >= (minSnr or 30), string.format("%s: audio SNR vs ffmpeg %.1f dB", label, s))
|
||||
end
|
||||
end
|
||||
|
||||
-- seek(t, v, c, label, at): after seek(at) the next frame is the first at or after `at`
|
||||
function C.seek(t: any, v: any, c: any, label: string, at: number)
|
||||
if not (c.frames or c.rgba) or not Video.canDecode(v.codec) then
|
||||
return
|
||||
end
|
||||
if v.duration > 0 and at > v.duration * 0.6 then
|
||||
at = math.floor(v.duration * 50) / 100
|
||||
end
|
||||
v:seek(at)
|
||||
local f = v:nextFrame()
|
||||
t:check(f ~= nil and f.pts >= at - 1e-6 and f.pts < at + 0.2, label .. ": seek to " .. at .. " lands at " .. tostring(f and f.pts))
|
||||
if f and C.EXACT[v.codec] and c.frames then
|
||||
local idx = math.floor(f.pts * v.frameRate + 0.5) + 1
|
||||
t:eq(Crc32.of(f.image.pixels), c.frames[idx], label .. ": the frame after seeking equals ffmpeg's frame " .. idx)
|
||||
end
|
||||
v:reset()
|
||||
end
|
||||
|
||||
-- fuzzOpen(Fmt) -> a fuzz function: open, read every packet, decode up to 8 frames, read some audio
|
||||
function C.fuzzOpen(Fmt: any): (buffer) -> any
|
||||
return function(b: buffer): any
|
||||
local v = Fmt.open(Bytes.reader(b), { openAudio = function(d: any, tr: any): any
|
||||
local AudioWrap = require("@formats/containers/AudioWrap")
|
||||
AudioWrap.wrap(d, tr)
|
||||
return nil
|
||||
end })
|
||||
if not v then
|
||||
return nil
|
||||
end
|
||||
for _ = 1, 8 do
|
||||
local f = v:nextFrame()
|
||||
if not f then
|
||||
break
|
||||
end
|
||||
end
|
||||
if v.demuxer then
|
||||
v.demuxer:rewind()
|
||||
while v.demuxer:read() do
|
||||
end
|
||||
end
|
||||
return v
|
||||
end
|
||||
end
|
||||
|
||||
-- open(data, opts?) -> VideoDecoder through the api (category video)
|
||||
function C.open(data: string, opts: any?): (any, any)
|
||||
return F.video.open(buffer.fromstring(data), opts)
|
||||
end
|
||||
|
||||
return C
|
||||
@@ -0,0 +1,97 @@
|
||||
-- video/avi tests: AVI files from ffmpeg (MJPEG + PCM s16 / u8 / IMA ADPCM, MPEG-1 + MP2, uncompressed BGR24 / BGRA /
|
||||
-- I420) read through the OpenDML indexes, idx1 alone, and a movi scan: tracks and every packet against ffprobe,
|
||||
-- frames against ffmpeg, audio through the api hook, seeking; our muxer (MJPEG + PCM) read back; a GIF converted to
|
||||
-- AVI. Fixtures: tools/fixtures/avi.py.
|
||||
local T = require("@tests/T")
|
||||
local C = require("@tests/video/_common")
|
||||
local F = require("@formats")
|
||||
local AviFormat = require("@formats/video/avi")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Fx = require("@tests/gen/avi_cases")
|
||||
|
||||
local t = T.suite("avi")
|
||||
|
||||
t:eq(AviFormat.name, "avi", "name")
|
||||
t:eq(AviFormat.category, "video", "category")
|
||||
|
||||
local EXACT_AUDIO = { pcm_s16le = true, pcm_u8 = true, adpcm_ima_wav = true }
|
||||
local byName = {}
|
||||
for _, c in Fx do
|
||||
byName[c.name] = c
|
||||
end
|
||||
|
||||
for _, c in Fx do
|
||||
local label = c.name
|
||||
t:check(AviFormat.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, label .. ": sniff")
|
||||
local v, err = C.open(c.data)
|
||||
if c.truncated then
|
||||
t:check(v ~= nil or err ~= nil, label .. ": opens or fails cleanly")
|
||||
else
|
||||
t:check(v ~= nil, label .. ": open: " .. tostring(err))
|
||||
if v then
|
||||
local dmx = v.demuxer
|
||||
t:eq(#dmx.tracks, #c.streams, label .. ": track count")
|
||||
C.packets(t, dmx, c, label)
|
||||
if c.rgba then
|
||||
v:reset()
|
||||
local n, bad = 0, 0
|
||||
while true do
|
||||
local f = v:nextFrame()
|
||||
if not f then
|
||||
break
|
||||
end
|
||||
n += 1
|
||||
if f.image.format ~= "rgba8" or Crc32.of(f.image.pixels) ~= c.rgba[n] then
|
||||
bad += 1
|
||||
end
|
||||
end
|
||||
t:check(n == #c.rgba and bad == 0, label .. ": " .. n .. " rgba frames equal ffmpeg's (" .. bad .. " differ)")
|
||||
else
|
||||
C.frames(t, v, c, label)
|
||||
end
|
||||
local at = dmx:track("audio")
|
||||
if at then
|
||||
C.audio(t, v, c, label, EXACT_AUDIO[at.codec], 30)
|
||||
end
|
||||
C.seek(t, v, c, label, 0.5)
|
||||
end
|
||||
end
|
||||
end
|
||||
t:eq(C.open(byName["mjpeg_pcm.avi"].data).demuxer.meta.index, "idx1", "ffmpeg's AVI: idx1 used")
|
||||
t:eq(C.open(byName["odml.avi"].data).demuxer.meta.index, "odml", "OpenDML indexes used")
|
||||
t:eq(C.open(byName["idx1_only.avi"].data).demuxer.meta.index, "idx1", "idx1 used without OpenDML indexes")
|
||||
t:eq(C.open(byName["no_index.avi"].data).demuxer.meta.index, "scan", "movi scanned without indexes")
|
||||
|
||||
-- our muxer: MJPEG copied + PCM, read back packet for packet
|
||||
do
|
||||
local v = C.open(byName["mjpeg_pcm.avi"].data)
|
||||
local out, err = F.save(v, nil, { format = "avi" })
|
||||
t:check(out ~= nil, "mux avi: " .. tostring(err))
|
||||
if out then
|
||||
local v2 = F.video.open(out)
|
||||
t:check(v2 ~= nil, "mux avi: reads back")
|
||||
if v2 then
|
||||
local a, b = v.demuxer, v2.demuxer
|
||||
local same = a:count(1) == b:count(1)
|
||||
for k = 1, a:count(1) do
|
||||
local p, q = a:get(1, k), b:get(1, k)
|
||||
if not q or buffer.tostring(p.data) ~= buffer.tostring(q.data) then
|
||||
same = false
|
||||
end
|
||||
end
|
||||
t:check(same, "mux avi: identical MJPEG packets")
|
||||
t:eq(v2.frameRate, 10, "mux avi: frame rate")
|
||||
C.audio(t, v2, byName["mjpeg_pcm.avi"], "mux avi", true)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- fuzz
|
||||
local samples = {}
|
||||
for _, n in { "mjpeg_pcm.avi", "mjpeg_ima.avi", "idx1_only.avi", "i420.avi" } do
|
||||
local d = byName[n].data
|
||||
table.insert(samples, string.sub(d, 1, math.min(#d, 40000)))
|
||||
end
|
||||
t:fuzz("open", C.fuzzOpen(AviFormat), samples, { mutations = 6, garbage = 100 })
|
||||
t:done()
|
||||
@@ -0,0 +1,116 @@
|
||||
-- video writer tests: files our muxers wrote (tools/fixtures/_video_encode.luau: WebM remux, MJPEG Matroska / AVI
|
||||
-- copied and re-encoded from VP8 / MPEG-1, an animated GIF with uneven delays to AVI / Matroska / Y4M, WebM to Y4M)
|
||||
-- were probed by ffprobe and decoded by ffmpeg at fixture time; here our demuxers must see the same packets, our
|
||||
-- decoders the same frames (CRC for VP8 / raw, PSNR for MJPEG) and audio; the writers are rerun and must give the same
|
||||
-- bytes. Fixtures: tools/fixtures/videoenc.py.
|
||||
local T = require("@tests/T")
|
||||
local C = require("@tests/video/_common")
|
||||
local F = require("@formats")
|
||||
local Fx = require("@tests/gen/videoenc_cases")
|
||||
local Src = require("@tests/gen/videoenc_src")
|
||||
|
||||
local t = T.suite("video encode")
|
||||
|
||||
local byName = {}
|
||||
for _, c in Fx do
|
||||
byName[c.name] = c
|
||||
end
|
||||
|
||||
for _, c in Fx do
|
||||
local label = c.name
|
||||
if c.err then
|
||||
t:note("%s: not written at fixture time: %s", label, c.err)
|
||||
else
|
||||
local v, err = C.open(c.data)
|
||||
t:check(v ~= nil, label .. ": opens: " .. tostring(err))
|
||||
if v then
|
||||
t:eq(#v.demuxer.tracks, #c.streams, label .. ": track count (ffprobe)")
|
||||
-- (ffmpeg's AVI demuxer cuts PCM chunks into 1024-sample packets: AVI audio is compared decoded)
|
||||
local avi = string.sub(label, -4) == ".avi"
|
||||
C.packets(t, v.demuxer, c, label, { skipStream = function(_: any, tr: any): boolean
|
||||
return avi and tr ~= nil and tr.kind == "audio"
|
||||
end })
|
||||
C.frames(t, v, c, label, 40)
|
||||
local at = v.demuxer:track("audio")
|
||||
if at then
|
||||
C.audio(t, v, c, label, string.sub(at.codec, 1, 4) == "pcm_", 30)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- the GIF (100 / 50 / 200 / 100 ms) at a constant 20 fps: 2 + 1 + 4 + 2 frames
|
||||
do
|
||||
local c = byName["gif.avi"]
|
||||
if c and c.frames then
|
||||
t:eq(#c.frames, 9, "gif.avi: 9 frames at 20 fps (ffmpeg)")
|
||||
local v = C.open(c.data)
|
||||
t:eq(v.frameRate, 20, "gif.avi: 20 fps")
|
||||
end
|
||||
local y = byName["gif.y4m"]
|
||||
if y and y.frames then
|
||||
t:eq(#y.frames, 9, "gif.y4m: 9 frames (ffmpeg)")
|
||||
end
|
||||
-- F.video.open on the GIF itself: a frames-backed video
|
||||
local g = F.video.open(buffer.fromstring(Src.gif))
|
||||
t:check(g ~= nil and g.codec == "frames" and g.frames == 4, "F.video.open(gif): 4 frames")
|
||||
if g then
|
||||
local f1 = g:nextFrame()
|
||||
local f2 = g:nextFrame()
|
||||
t:check(f1 and f1.image.format == "rgba8" and f1.duration == 0.1 and f2 and f2.pts == 0.1 and f2.duration == 0.05, "gif frames: rgba8 with the GIF's times")
|
||||
g:seek(0.2)
|
||||
local f3 = g:nextFrame()
|
||||
t:check(f3 ~= nil and f3.index == 3, "gif seek: frame 3 at 0.15 s holds 0.2 s")
|
||||
end
|
||||
end
|
||||
|
||||
-- animated WebP through F.video.open: frames-backed, the canvases equal Pillow's (libwebp's WebPAnimDecoder)
|
||||
do
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Anims = require("@tests/gen/webp_anim")
|
||||
for _, a in Anims do
|
||||
local v = F.video.open(buffer.fromstring(a.data))
|
||||
t:check(v ~= nil and v.codec == "frames" and v.frames == #a.frames, a.name .. ": opens as a " .. #a.frames .. "-frame video")
|
||||
if v then
|
||||
local bad, n, t0 = 0, 0, 0
|
||||
while true do
|
||||
local f = v:nextFrame()
|
||||
if not f then
|
||||
break
|
||||
end
|
||||
n += 1
|
||||
local px = f.image.pixels
|
||||
if a.rgba == false then
|
||||
px = buffer.create(buffer.len(f.image.pixels))
|
||||
buffer.copy(px, 0, f.image.pixels)
|
||||
for i = 3, buffer.len(px) - 1, 4 do
|
||||
buffer.writeu8(px, i, 255)
|
||||
end
|
||||
end
|
||||
if Crc32.of(px) ~= a.frames[n].crc or math.abs(f.pts - t0) > 1e-6 then
|
||||
bad += 1
|
||||
end
|
||||
t0 += a.frames[n].ms / 1000
|
||||
end
|
||||
t:check(n == #a.frames and bad == 0, a.name .. ": video frames equal Pillow's canvases and times (" .. bad .. " differ)")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- the writers are deterministic: the same bytes again
|
||||
do
|
||||
local Mkv = require("@tests/gen/mkv_cases")
|
||||
local remux = byName["remux.webm"]
|
||||
for _, m in Mkv do
|
||||
if m.name == "vp8_opus.webm" and remux and remux.data then
|
||||
local out = F.convert(buffer.fromstring(m.data), "webm")
|
||||
t:check(out ~= nil and buffer.tostring(out) == remux.data, "remux.webm: written again byte for byte")
|
||||
end
|
||||
end
|
||||
local gifAvi = byName["gif.avi"]
|
||||
if gifAvi and gifAvi.data then
|
||||
local out = F.convert(buffer.fromstring(Src.gif), "avi", { quality = 95 })
|
||||
t:check(out ~= nil and buffer.tostring(out) == gifAvi.data, "gif.avi: F.convert(gif, 'avi') again byte for byte")
|
||||
end
|
||||
end
|
||||
t:done()
|
||||
@@ -0,0 +1,128 @@
|
||||
-- video/mkv tests: Matroska / WebM files from ffmpeg and mkvmerge (VP8 + Opus / Vorbis, MJPEG + PCM, MPEG-1 + MP2,
|
||||
-- VP8 + FLAC, srt subtitles, Xiph / EBML / fixed lacing, zlib compression, unknown-size clusters, a truncated file):
|
||||
-- tracks and every packet against ffprobe, frames against ffmpeg (bit-exact VP8, PSNR for MJPEG / MPEG-1), audio
|
||||
-- through the api hook against ffmpeg, seeking, subtitles; our muxer's output (remux and MJPEG) read back. Fixtures:
|
||||
-- tools/fixtures/mkv.py.
|
||||
local T = require("@tests/T")
|
||||
local C = require("@tests/video/_common")
|
||||
local F = require("@formats")
|
||||
local Mkv = require("@formats/video/mkv")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Fx = require("@tests/gen/mkv_cases")
|
||||
|
||||
local t = T.suite("mkv")
|
||||
|
||||
-- 1. contract
|
||||
t:eq(Mkv.name, "mkv", "name")
|
||||
t:eq(Mkv.category, "video", "category")
|
||||
t:check(table.find(Mkv.extensions, "webm") ~= nil, "webm extension")
|
||||
|
||||
local EXACT_AUDIO = { pcm_s16le = true, flac = true }
|
||||
local byName = {}
|
||||
for _, c in Fx do
|
||||
byName[c.name] = c
|
||||
end
|
||||
|
||||
-- 2. every fixture
|
||||
for _, c in Fx do
|
||||
local label = c.name
|
||||
t:check(Mkv.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, label .. ": sniff")
|
||||
if c.truncated then
|
||||
local v, err = C.open(c.data)
|
||||
t:check(v ~= nil or err ~= nil, label .. ": opens or fails cleanly")
|
||||
if v then
|
||||
local n = 0
|
||||
while v:nextFrame() do
|
||||
n += 1
|
||||
end
|
||||
t:note("%s: %d frames before the cut", label, n)
|
||||
end
|
||||
else
|
||||
local v, err = C.open(c.data)
|
||||
t:check(v ~= nil, label .. ": open: " .. tostring(err))
|
||||
if v then
|
||||
local dmx = v.demuxer
|
||||
t:eq(#dmx.tracks, #c.streams, label .. ": track count")
|
||||
for i, s in c.streams do
|
||||
local tr = dmx.tracks[i]
|
||||
if tr then
|
||||
t:eq(tr.kind, s.kind, label .. ": track " .. i .. " kind")
|
||||
if s.width then
|
||||
t:check(tr.width == s.width and tr.height == s.height, label .. ": track " .. i .. " size")
|
||||
end
|
||||
if s.rate then
|
||||
t:check(tr.sampleRate == s.rate and tr.channels == s.channels, label .. ": track " .. i .. " rate / channels")
|
||||
end
|
||||
end
|
||||
end
|
||||
-- Vorbis frames inside a lace carry no time of their own (ffmpeg derives them from the Vorbis block sizes)
|
||||
C.packets(t, dmx, c, label, { noPts = c.name == "laced_vorbis.mkv" or c.name == "zlib_vorbis.mka" })
|
||||
C.frames(t, v, c, label)
|
||||
local at = dmx:track("audio")
|
||||
if at then
|
||||
C.audio(t, v, c, label, EXACT_AUDIO[at.codec], if at.codec == "vorbis" then 20 else 30)
|
||||
end
|
||||
C.seek(t, v, c, label, 0.6)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- 3. specific files
|
||||
do
|
||||
local v = C.open(byName["vp8_opus.webm"].data)
|
||||
t:eq(v.format, "webm", "webm: format")
|
||||
t:eq(v.codec, "vp8", "webm: codec")
|
||||
t:eq(v.width, 160, "webm: width")
|
||||
t:check(math.abs(v.duration - 1) < 0.1, "webm: duration " .. v.duration)
|
||||
t:check(#v.demuxer.meta.cues > 0, "webm: cues read")
|
||||
local subs = Mkv.subtitles(C.open(byName["subs.mkv"].data).demuxer)
|
||||
t:check(subs ~= nil and #subs.cues == 2, "subtitles: two cues")
|
||||
if subs then
|
||||
t:eq(subs.cues[1].text, "Hello", "subtitles: text")
|
||||
t:check(math.abs(subs.cues[1].start - 0.1) < 0.002 and math.abs(subs.cues[1].stop - 0.5) < 0.002, "subtitles: times")
|
||||
end
|
||||
local lv = C.open(byName["lacing.mka"].data)
|
||||
t:eq(lv.demuxer:count(1), 10, "lacing: 10 frames from three laced blocks")
|
||||
local _, _, _, _, len = lv.demuxer:info(1, 4)
|
||||
t:eq(len, 160, "lacing: EBML-laced frame size")
|
||||
end
|
||||
|
||||
-- 4. our muxer: remux WebM (VP8 + Opus copied) and read it back packet for packet
|
||||
do
|
||||
local src = byName["vp8_opus.webm"]
|
||||
local v = C.open(src.data)
|
||||
local out, err = F.save(v, nil, { format = "webm" })
|
||||
t:check(out ~= nil, "remux webm: " .. tostring(err))
|
||||
if out then
|
||||
local v2 = F.video.open(out)
|
||||
t:check(v2 ~= nil and v2.format == "webm", "remux webm: reads back as webm")
|
||||
if v2 then
|
||||
local a, b = v.demuxer, v2.demuxer
|
||||
t:eq(#b.tracks, 2, "remux webm: two tracks")
|
||||
local same = a:count(1) == b:count(1) and a:count(2) == b:count(2)
|
||||
for k = 1, a:count(1) do
|
||||
local p, q = a:get(1, k), b:get(1, k)
|
||||
if not q or p.pts ~= q.pts or buffer.tostring(p.data) ~= buffer.tostring(q.data) or p.keyframe ~= q.keyframe then
|
||||
same = false
|
||||
end
|
||||
end
|
||||
t:check(same, "remux webm: identical video packets")
|
||||
C.frames(t, v2, src, "remux webm")
|
||||
C.audio(t, v2, src, "remux webm", false, 30)
|
||||
end
|
||||
end
|
||||
local bad, berr = F.save(C.open(byName["mjpeg_pcm.mkv"].data), nil, { format = "webm" })
|
||||
t:check(bad == nil and berr ~= nil and berr.code == Err.UNSUPPORTED, "webm refuses MJPEG: " .. tostring(berr))
|
||||
end
|
||||
|
||||
-- 5. errors and the fuzz pass
|
||||
local e1 = select(2, Mkv.open(Bytes.reader(buffer.fromstring("\26\69\223\163\128"))))
|
||||
t:check(e1 ~= nil, "empty EBML header fails")
|
||||
local samples = {}
|
||||
for _, n in { "vp8_opus.webm", "mjpeg_pcm.mkv", "lacing.mka", "zlib_vorbis.mka", "subs.mkv" } do
|
||||
local d = byName[n].data
|
||||
table.insert(samples, string.sub(d, 1, math.min(#d, 60000)))
|
||||
end
|
||||
t:fuzz("open", C.fuzzOpen(Mkv), samples, { mutations = 6, garbage = 100 })
|
||||
t:done()
|
||||
@@ -0,0 +1,74 @@
|
||||
-- video/mp4 tests: MP4 / MOV files from ffmpeg (MJPEG + AAC / PCM / FLAC / MP2, H.264 with B-frames and edit lists +
|
||||
-- AAC, fragmented MP4, MPEG-1 + Opus): tracks and every packet against ffprobe (pts moved by the edit lists, as ffmpeg),
|
||||
-- frames against ffmpeg (PSNR), audio through the api hook (AAC priming dropped), seeking, our MP4 / MOV writer read
|
||||
-- back, fuzz. Fixtures: tools/fixtures/mp4.py.
|
||||
local T = require("@tests/T")
|
||||
local C = require("@tests/video/_common")
|
||||
local F = require("@formats")
|
||||
local Mp4 = require("@formats/video/mp4")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Fx = require("@tests/gen/mp4_cases")
|
||||
|
||||
local t = T.suite("mp4")
|
||||
t:eq(Mp4.name, "mp4", "name")
|
||||
|
||||
local EXACT_AUDIO = { pcm_s16le = true, flac = true }
|
||||
local byName = {}
|
||||
for _, c in Fx do
|
||||
byName[c.name] = c
|
||||
end
|
||||
|
||||
for _, c in Fx do
|
||||
local label = c.name
|
||||
t:check(Mp4.sniff(Bytes.reader(buffer.fromstring(c.data))) >= 0.6, label .. ": sniff")
|
||||
local v, err = C.open(c.data)
|
||||
t:check(v ~= nil, label .. ": open " .. tostring(err))
|
||||
if v then
|
||||
local dmx = v.demuxer
|
||||
t:eq(#dmx.tracks, #c.streams, label .. ": track count")
|
||||
C.packets(t, dmx, c, label)
|
||||
C.frames(t, v, c, label, 38)
|
||||
local at = dmx:track("audio")
|
||||
if at then
|
||||
C.audio(t, v, c, label, EXACT_AUDIO[at.codec], 30)
|
||||
end
|
||||
C.seek(t, v, c, label, 0.5)
|
||||
end
|
||||
end
|
||||
|
||||
-- our writer: MP4 (MJPEG + AAC copied) and MOV (MJPEG + PCM) read back packet for packet
|
||||
for _, job in { { "mjpeg_aac.mp4", "mp4" }, { "mjpeg_pcm.mov", "mov" }, { "h264_aac.mp4", "mp4" } } do
|
||||
local src = byName[job[1]]
|
||||
local v = C.open(src.data)
|
||||
local out, err = F.save(v, nil, { format = job[2] })
|
||||
t:check(out ~= nil, "write " .. job[2] .. " from " .. job[1] .. ": " .. tostring(err))
|
||||
if out then
|
||||
local v2 = F.video.open(out)
|
||||
t:check(v2 ~= nil, "write " .. job[1] .. ": reads back")
|
||||
if v2 then
|
||||
local a, b = v.demuxer, v2.demuxer
|
||||
local same = #a.tracks == #b.tracks
|
||||
for i, tr in a.tracks do
|
||||
local tr2 = b.tracks[i]
|
||||
if not tr2 or a:count(tr.id) ~= b:count(tr2.id) then
|
||||
same = false
|
||||
else
|
||||
for k = 1, a:count(tr.id) do
|
||||
local p, q = a:get(tr.id, k), b:get(tr2.id, k)
|
||||
if not q or buffer.tostring(p.data) ~= buffer.tostring(q.data) or math.abs(p.pts / tr.timescale - q.pts / tr2.timescale) > 0.002 then
|
||||
same = false
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
t:check(same, "write " .. job[1] .. ": same packets and times")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for _, n in { "mjpeg_aac.mp4", "fragmented.mp4", "h264_aac.mp4" } do
|
||||
table.insert(samples, string.sub(byName[n].data, 1, 30000))
|
||||
end
|
||||
t:fuzz("open", C.fuzzOpen(Mp4), samples, { mutations = 6, garbage = 100 })
|
||||
t:done()
|
||||
@@ -0,0 +1,48 @@
|
||||
-- video/mpegps tests: program streams from ffmpeg (MPEG-1 system stream, B-frames, MPEG-2 PS / VOB packs, a raw .m1v
|
||||
-- elementary stream): tracks, picture packets (count and timestamps against ffmpeg's frames), frames against ffmpeg
|
||||
-- (PSNR) once an MPEG-1 decoder is registered, audio through the api hook (SNR), seeking, fuzz. Fixtures:
|
||||
-- tools/fixtures/mpegts.py.
|
||||
local T = require("@tests/T")
|
||||
local C = require("@tests/video/_common")
|
||||
local Ps = require("@formats/video/mpegps")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Fx = require("@tests/gen/mpegps_cases")
|
||||
|
||||
local t = T.suite("mpegps")
|
||||
t:eq(Ps.name, "mpegps", "name")
|
||||
|
||||
for _, c in Fx do
|
||||
local label = c.name
|
||||
t:check(Ps.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, label .. ": sniff")
|
||||
local v, err = C.open(c.data)
|
||||
t:check(v ~= nil, label .. ": open " .. tostring(err))
|
||||
if v then
|
||||
local dmx = v.demuxer
|
||||
local vt = dmx:track("video")
|
||||
t:check(vt ~= nil and vt.codec == "mpeg1", label .. ": an MPEG-1 video track")
|
||||
t:eq(dmx:count(vt.id), #c.frames, label .. ": one packet per picture")
|
||||
-- presentation times: one per frame slot
|
||||
local seen, ok = {}, true
|
||||
for k = 1, dmx:count(vt.id) do
|
||||
local pts = dmx:info(vt.id, k)
|
||||
local slot = math.floor((pts - dmx:info(vt.id, 1)) / 3600 + 0.5)
|
||||
if seen[slot] then
|
||||
ok = false
|
||||
end
|
||||
seen[slot] = true
|
||||
end
|
||||
t:check(ok, label .. ": distinct presentation times")
|
||||
C.frames(t, v, c, label, 36)
|
||||
if dmx:track("audio") then
|
||||
C.audio(t, v, c, label, false, 30)
|
||||
end
|
||||
C.seek(t, v, c, label, 0.5)
|
||||
end
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for _, c in Fx do
|
||||
table.insert(samples, string.sub(c.data, 1, 30000))
|
||||
end
|
||||
t:fuzz("open", C.fuzzOpen(Ps), samples, { mutations = 6, garbage = 100 })
|
||||
t:done()
|
||||
@@ -0,0 +1,64 @@
|
||||
-- video/mpegts tests: transport streams from ffmpeg (MPEG-1 + MP2, B-frames, H.264 + AAC, M2TS, garbage before the
|
||||
-- first packet, a truncated file): tracks and the video packets against ffprobe (time, size, CRC, keyframe), frames
|
||||
-- against ffmpeg (PSNR) once an MPEG-1 decoder is registered, audio through the api hook (SNR), seeking, fuzz.
|
||||
-- Fixtures: tools/fixtures/mpegts.py.
|
||||
local T = require("@tests/T")
|
||||
local C = require("@tests/video/_common")
|
||||
local Ts = require("@formats/video/mpegts")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Fx = require("@tests/gen/mpegts_cases")
|
||||
|
||||
local t = T.suite("mpegts")
|
||||
t:eq(Ts.name, "mpegts", "name")
|
||||
|
||||
local byName = {}
|
||||
for _, c in Fx do
|
||||
byName[c.name] = c
|
||||
end
|
||||
|
||||
local function audioStream(want: any, tr: any): boolean
|
||||
return tr == nil or tr.kind ~= "video" -- ffmpeg's parser re-splits PES audio into frames
|
||||
end
|
||||
|
||||
for _, c in Fx do
|
||||
local label = c.name
|
||||
local v, err = C.open(c.data)
|
||||
if c.truncated then
|
||||
t:check(v ~= nil or err ~= nil, label .. ": opens or fails cleanly")
|
||||
else
|
||||
t:check(Ts.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0 or label == "garbage.ts", label .. ": sniff")
|
||||
t:check(v ~= nil, label .. ": open " .. tostring(err))
|
||||
if v then
|
||||
local dmx = v.demuxer
|
||||
t:eq(#dmx.tracks, #c.streams, label .. ": track count")
|
||||
for i, s in c.streams do
|
||||
local tr = dmx.tracks[i]
|
||||
t:check(tr ~= nil and tr.kind == s.kind, label .. ": track " .. i .. " kind")
|
||||
if tr and s.width and tr.width then -- (H.264 sizes come from its SPS, read by the codec)
|
||||
t:check(tr.width == s.width and tr.height == s.height, label .. ": track " .. i .. " size")
|
||||
end
|
||||
end
|
||||
if c.packets then
|
||||
C.packets(t, dmx, c, label, { skipStream = audioStream })
|
||||
end
|
||||
C.frames(t, v, c, label, 36)
|
||||
if dmx:track("audio") then
|
||||
C.audio(t, v, c, label, false, 30)
|
||||
end
|
||||
C.seek(t, v, c, label, 0.5)
|
||||
end
|
||||
end
|
||||
end
|
||||
do
|
||||
local v = C.open(byName["mpeg1_mp2.ts"].data)
|
||||
t:eq(v.codec, "mpeg1", "stream type 0x02 without a sequence extension is MPEG-1")
|
||||
t:eq(v.demuxer.tracks[2].codec, "mp2", "MPEG audio layer II")
|
||||
t:eq(C.open(byName["h264_aac.ts"].data).codec, "h264", "H.264 track")
|
||||
end
|
||||
|
||||
local samples = {}
|
||||
for _, n in { "mpeg1_mp2.ts", "bframes.ts", "h264_aac.ts" } do
|
||||
table.insert(samples, string.sub(byName[n].data, 1, 188 * 120))
|
||||
end
|
||||
t:fuzz("open", C.fuzzOpen(Ts), samples, { mutations = 6, garbage = 100 })
|
||||
t:done()
|
||||
@@ -0,0 +1,103 @@
|
||||
-- video/y4m tests: YUV4MPEG2 streams from ffmpeg (C420jpeg at an odd size, C420mpeg2, C422, C444, Cmono, C420p10)
|
||||
-- against ffmpeg's yuv420p decode (bit-exact for 4:2:0 8-bit, PSNR for the converted layouts), the header fields,
|
||||
-- our writer round trip (and from an rgba frames-backed video), errors and the fuzz pass. Fixtures:
|
||||
-- tools/fixtures/y4m.py.
|
||||
local T = require("@tests/T")
|
||||
local C = require("@tests/video/_common")
|
||||
local F = require("@formats")
|
||||
local Y4m = require("@formats/video/y4m")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Fx = require("@tests/gen/y4m_cases")
|
||||
|
||||
local t = T.suite("y4m")
|
||||
t:eq(Y4m.name, "y4m", "name")
|
||||
|
||||
for _, c in Fx do
|
||||
local label = c.name
|
||||
t:check(Y4m.sniff(Bytes.reader(buffer.fromstring(c.data))) == 1, label .. ": sniff")
|
||||
local v, err = Y4m.open(Bytes.reader(buffer.fromstring(c.data)))
|
||||
t:check(v ~= nil, label .. ": open " .. tostring(err))
|
||||
if v then
|
||||
t:check(v.width == c.width and v.height == c.height, label .. ": size")
|
||||
t:check(math.abs(v.frameRate - c.rate[1] / c.rate[2]) < 1e-9, label .. ": frame rate")
|
||||
local n, bad, worst = 0, 0, math.huge
|
||||
while true do
|
||||
local f = v:nextFrame()
|
||||
if not f then
|
||||
break
|
||||
end
|
||||
n += 1
|
||||
if c.exact then
|
||||
if Crc32.of(f.image.pixels) ~= c.frames[n] then
|
||||
bad += 1
|
||||
end
|
||||
elseif c.yuv[n] then
|
||||
worst = math.min(worst, C.psnr(f.image.pixels, buffer.fromstring(c.yuv[n])))
|
||||
end
|
||||
end
|
||||
t:eq(n, #c.frames, label .. ": frame count")
|
||||
if c.exact then
|
||||
t:check(bad == 0, label .. ": frames bit-exact with ffmpeg")
|
||||
else
|
||||
t:check(worst > 30, string.format("%s: PSNR vs ffmpeg %.1f dB", label, worst))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- writer: a y4m stream back to y4m is byte-identical in its frames; header as ffmpeg writes it
|
||||
do
|
||||
local c = Fx[1]
|
||||
local v = F.video.open(buffer.fromstring(c.data))
|
||||
local out, err = F.save(v, nil, { format = "y4m" })
|
||||
t:check(out ~= nil, "write: " .. tostring(err))
|
||||
if out then
|
||||
local s = buffer.tostring(out)
|
||||
t:check(string.find(s, "YUV4MPEG2 W173 H95 F30000:1001 Ip A1:1 C420jpeg XYSCSS=420JPEG\n", 1, true) == 1, "write: header " .. string.sub(s, 1, 60))
|
||||
local v2 = Y4m.open(Bytes.reader(out))
|
||||
local n, same = 0, true
|
||||
while true do
|
||||
local f = v2:nextFrame()
|
||||
if not f then
|
||||
break
|
||||
end
|
||||
n += 1
|
||||
same = same and Crc32.of(f.image.pixels) == c.frames[n]
|
||||
end
|
||||
t:check(n == #c.frames and same, "write: frames round trip")
|
||||
end
|
||||
-- an rgba frames-backed video (a 2-frame animation) to y4m
|
||||
local a = Types.Image.new(4, 2)
|
||||
buffer.fill(a.pixels, 0, 255)
|
||||
local b = Types.Image.new(4, 2)
|
||||
a.frames = { { image = a, delay = 0.5, x = 0, y = 0, dispose = "none", blend = "source" }, { image = b, delay = 0.5, x = 0, y = 0, dispose = "none", blend = "source" } }
|
||||
local y, yerr = F.save(a, nil, { format = "y4m" })
|
||||
t:check(y ~= nil, "write from frames: " .. tostring(yerr))
|
||||
if y then
|
||||
local v3 = Y4m.open(Bytes.reader(y))
|
||||
local f1 = v3:nextFrame()
|
||||
local f2 = v3:nextFrame()
|
||||
t:check(f1 ~= nil and f2 ~= nil and v3:nextFrame() == nil, "write from frames: 2 frames")
|
||||
t:eq(v3.frameRate, 2, "write from frames: frame rate from the delays")
|
||||
t:eq(buffer.readu8(f1.image.pixels, 0), 235, "write from frames: white -> Y 235 (limited range)")
|
||||
t:eq(buffer.readu8(f2.image.pixels, 0), 16, "write from frames: black -> Y 16")
|
||||
end
|
||||
end
|
||||
|
||||
-- errors
|
||||
local function code(s: string): string?
|
||||
local _, e = Y4m.open(Bytes.reader(buffer.fromstring(s)))
|
||||
return e and e.code
|
||||
end
|
||||
t:eq(code("YUV4MPEG2 W0 H0\n"), Err.CORRUPT, "zero size")
|
||||
t:eq(code("YUV4MPEG2 W16 H16 Cfoo\n"), Err.UNSUPPORTED, "unknown colour space")
|
||||
t:eq(code("YUV4MPEG2 W99999999 H99999 C420\n"), Err.CORRUPT, "huge size")
|
||||
t:eq(code("YUV4MPEG2 W16 H16"), Err.TRUNCATED, "no header end")
|
||||
local samples = {}
|
||||
for _, c in Fx do
|
||||
table.insert(samples, string.sub(c.data, 1, 30000))
|
||||
end
|
||||
t:fuzz("open", C.fuzzOpen(Y4m), samples, { mutations = 6, garbage = 100 })
|
||||
t:done()
|
||||
Reference in new issue
Block a user