ws-m4a: codecs/Aac (AAC-LC decoder: ASC / PCE / ADTS, all tools, SBR/PS extension hook), codecs/Alac (decoder + encoder), audio/m4a (AAC + ALAC read, ALAC write, tags, gapless, seek), audio/aac (ADTS), audio/caf (lpcm/alac/aac/ulaw/alaw read, lpcm/alac write); fixtures checked by ffmpeg / fdkaac / MP4Box

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
4DBugandClaude Opus 5.5 committed 2026-10-31 09:03:04 -05:00
1 parent 8b29568e0f
commit f66594908c
22 files changed
+5380

No files matched your search

+12
View File
@@ -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 },
}
+42
View File
@@ -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
+117
View File
@@ -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()
+177
View File
@@ -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()
+218
View File
@@ -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()
+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()