merge ws/m4a

This commit is contained in:
4DBug committed 2026-10-31 09:23:57 -05:00
commit e1ffb21494
42 files changed
+10353 -8

No files matched your search

+182
View File
@@ -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()
+181
View File
@@ -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()
+134
View File
@@ -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()