Files
rosetta/tests/audio/opus.luau
T
4DBugandClaude Opus 5.5 6b68c2ffab ws-cleanup: codecs/Resample, codecs/RangeCoder; Opus / MP3 / MP2 encoders resample through it
- codecs/Resample (new): Kaiser-windowed sinc resampler, polyphase (exact phases when to / gcd <= 4096, else 4096
  interpolated phases), quality low / medium / high (8 / 16 / 32 zero crossings), streaming (new / process / flush),
  whole buffer (Resample.buffer) and a codecs/Pcm source wrapper (Resample.source). tests/codecs/resample: SNR
  87 dB (44.1 -> 48 kHz, medium) .. 108 dB (high), alias rejection, streamed = whole, identity.
- audio/opus/Encode: input through codecs/Pcm (Pcm.source + collect) and codecs/Resample instead of its private
  resampler and Decoder loop; tags through codecs/VorbisComment.
- audio/mp3 encode: rates the layer cannot hold are resampled to the next rate up (opts.sampleRate picks one,
  opts.resampleQuality); was Err.ARG "no resampling".
- codecs/RangeCoder/{Decoder,Encoder}: the RFC 6716 range coder moved out of audio/opus (same code, no speed change).
- audio/opus/Mdct stays private: routing CELT through codecs/Mdct measured 2-3x slower CELT decoding and different
  output bits (documented in its header).
- (this commit also carries the Opus side of the tags / channel order consistency: codecs/VorbisComment for OpusTags,
  meta.source.comments, mapping family 1 decoded to WAVE channel order with Pcm.reorder / Pcm.WAVE_FROM_VORBIS.)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-31 10:50:56 -05:00

455 lines
18 KiB
Luau

-- audio/opus tests: every fixture (opusenc / ffmpeg libopus: CELT frame sizes and bitrates, SILK NB / MB / WB, hybrid,
-- mode transitions, 5.1 multistream, a long tagged file) through open / read against opusdec --float (frame counts,
-- SNR per fixture), CELT-only and SILK-only decoding with the private decoders alone, SILK packet loss concealment,
-- tags, seeking, the stereo downmix, decode() to an Audio, the contract, sniff, error codes, random / bit-flipped
-- packets through the packet decoder, and the fuzz no-throw pass over whole files.
-- Ported from opus-luau tests/opus.luau, celt.luau, silk.luau, fuzz.luau. Fixtures: tools/fixtures/opus.py.
local T = require("@tests/T")
local Opus = require("@formats/audio/opus")
local Packet = require("@formats/audio/opus/Packet")
local Celt = require("@formats/audio/opus/Celt")
local Silk = require("@formats/audio/opus/Silk")
local RD = require("@formats/codecs/RangeCoder/Decoder")
local Decoder = require("@formats/audio/opus/Decoder")
local Ogg = require("@formats/containers/Ogg")
local Bytes = require("@formats/core/Bytes")
local Pcm = require("@formats/codecs/Pcm")
local Err = require("@formats/core/Err")
local t = T.suite("opus")
local FX: { [string]: any } = {}
for _, f in
{
require("@tests/gen/opus_celt_st_128"),
require("@tests/gen/opus_celt_st_32"),
require("@tests/gen/opus_celt_st_64"),
require("@tests/gen/opus_celt_st_256"),
require("@tests/gen/opus_celt_mono_64"),
require("@tests/gen/opus_celt_fs2_5"),
require("@tests/gen/opus_celt_fs5"),
require("@tests/gen/opus_celt_fs10"),
require("@tests/gen/opus_celt_fs40"),
require("@tests/gen/opus_celt_fs60"),
require("@tests/gen/opus_silk_nb"),
require("@tests/gen/opus_silk_mb"),
require("@tests/gen/opus_silk_wb"),
require("@tests/gen/opus_silk_wb_st"),
require("@tests/gen/opus_silk_nb_st"),
require("@tests/gen/opus_hybrid_swb"),
require("@tests/gen/opus_hybrid_fb"),
require("@tests/gen/opus_hybrid_st"),
require("@tests/gen/opus_mix_st_24"),
require("@tests/gen/opus_surround51"),
require("@tests/gen/opus_long_128"),
require("@tests/gen/opus_ff_cbr"),
require("@tests/gen/opus_ff_voip"),
require("@tests/gen/opus_ff_lowdelay"),
}
do
FX[f.name] = { data = buffer.fromstring(f.data), ref = buffer.fromstring(f.ref), raw = f.data }
end
-- opusdec's raw output keeps the Vorbis channel order of mapping family 1; the decoder returns WAVE order
do
local fx = FX.surround51
fx.vorbisRef = fx.ref
fx.ref = buffer.create(buffer.len(fx.vorbisRef))
buffer.copy(fx.ref, 0, fx.vorbisRef)
Pcm.reorder(fx.ref, 0, buffer.len(fx.ref) // 24, 6, Pcm.WAVE_FROM_VORBIS[6])
end
-- SNR in dB of f32 samples against a reference over n samples; returns snr, max abs error
local function snr(out: buffer, ref: buffer, n: number, outOff: number?, refOff: number?): (number, number)
local oo, ro = outOff or 0, refOff or 0
local sig, err, maxe = 0, 0, 0
for i = 0, n - 1 do
local r = buffer.readf32(ref, ro + i * 4)
local e = buffer.readf32(out, oo + i * 4) - r
sig += r * r
err += e * e
if math.abs(e) > maxe then
maxe = math.abs(e)
end
end
if err == 0 then
return 999, 0
end
return 10 * math.log10(sig / err), maxe
end
-- the packets of the first stream: { data, offset, size }
local function packets(buf: buffer): { any }
local d = Ogg.open(buf)
local out = {}
for p in d:packets(d:streams()[1].serial) do
table.insert(out, p)
end
return out
end
-- ------------------------------------------------------------------------------------------------ contract
t:eq(Opus.name, "opus", "name")
t:eq(Opus.category, "audio", "category")
t:check(Opus.caps.decode and 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")
-- ------------------------------------------------------------------------------------------------ open / read vs opusdec
-- name, minimum SNR (dB). CELT is float-exact (> 130 dB in practice), SILK bit-exact; hybrid / transitions mix both.
local cases = {
{ "celt_st_128", 100 }, { "celt_st_32", 100 }, { "celt_st_64", 100 }, { "celt_st_256", 100 },
{ "celt_mono_64", 100 }, { "celt_fs2_5", 100 }, { "celt_fs5", 100 }, { "celt_fs10", 100 },
{ "celt_fs40", 100 }, { "celt_fs60", 100 }, { "ff_cbr", 100 }, { "ff_lowdelay", 100 },
{ "silk_nb", 90 }, { "silk_nb_st", 90 }, { "silk_mb", 90 }, { "silk_wb", 90 }, { "silk_wb_st", 90 },
{ "hybrid_swb", 60 }, { "hybrid_fb", 60 }, { "hybrid_st", 60 }, { "mix_st_24", 60 }, { "ff_voip", 60 },
{ "surround51", 100 }, { "long_128", 100 },
}
for _, case in cases do
local name, minSnr = case[1], case[2]
local fx = FX[name]
local dec, err = Opus.open(Bytes.reader(fx.data))
t:check(dec, name .. ": open: " .. tostring(err))
local ch = dec.channels
local refFrames = buffer.len(fx.ref) // 4 // ch
t:eq(dec.frames, refFrames, name .. ": frames")
t:check(dec.sampleRate == 48000 and type(dec.duration) == "number" and type(dec.bitrate) == "number" and type(dec.tags) == "table", name .. ": Decoder fields")
local out = buffer.create(dec.frames * ch * 4 + 4096)
local total = 0
local t0 = os.clock()
while true do
local pcm, n = dec:read(1000 + total % 3001)
if n == 0 then
break
end
t:eq(buffer.len(pcm), n * ch * 4, name .. ": read buffer size")
buffer.copy(out, total * ch * 4, pcm, 0, n * ch * 4)
total += n
end
local dt = os.clock() - t0
t:eq(total, refFrames, name .. ": decoded frames")
local db, maxe = snr(out, fx.ref, refFrames * ch)
t:note("%-12s %d ch %7d frames SNR %6.1f dB max err %.2g %.0fx real time", name, ch, total, db, maxe, dec.duration / math.max(dt, 1e-6))
t:check(db >= minSnr, string.format("%s: SNR %.1f >= %d dB", name, db, minSnr))
t:check(math.abs(dec:position() - dec.duration) < 1e-9, name .. ": position at end")
end
-- read into a caller buffer, decode() to an Audio, a sub-range Reader
do
local fx = FX.hybrid_st
local dec = Opus.open(Bytes.reader(fx.data))
local into = buffer.create(4096 * 2 * 4)
local pcm, n = dec:read(4096, into)
t:check(pcm == into and n == 4096, "read(n, out) reuses out")
local big = buffer.create(buffer.len(fx.data) + 33)
buffer.copy(big, 17, fx.data)
local a, err = Opus.decode(Bytes.reader(big, 17, buffer.len(fx.data)))
t:check(a, "decode from a sub-range: " .. tostring(err))
t:check(a.kind == "audio" and a.sampleRate == 48000 and a.channels == 2, "decode: an Audio")
t:eq(a.frames, buffer.len(fx.ref) // 8, "decode: frames")
t:check(snr(a.samples, fx.ref, a.frames * 2) >= 60, "decode: samples")
t:eq(a.meta.source.format, "opus", "decode: meta.source")
end
-- ------------------------------------------------------------------------------------------------ tags, seeking
do
local dec = Opus.open(Bytes.reader(FX.long_128.data))
t:eq(dec.tags.title, "Long Test", "tags: title")
t:eq(dec.tags.artist, "opus-luau", "tags: artist")
t:check(dec.sampleRate == 48000 and dec.channels == 2, "info")
t:check(math.abs(dec.duration - 12) < 0.01, "duration ~12 s")
t:check(dec.bitrate > 100000 and dec.bitrate < 200000, "bitrate ~128 kbps: " .. dec.bitrate)
-- 80 ms pre-roll makes the decoder state converge after a seek
local ref = FX.long_128.ref
for _, s in { 0, 0.001, 1.5, 3.21, 6.0, 9.99, 11.7, 2.0, 0.05 } do
dec:seek(s)
local p = math.floor(s * 48000 + 0.5)
t:check(math.abs(dec:position() - p / 48000) < 1e-9, string.format("seek %.3f: position", s))
local pcm, n = dec:read(12000)
t:eq(n, math.min(12000, dec.frames - p), string.format("seek %.3f: read", s))
local db = snr(pcm, ref, n * 2, 0, p * 2 * 4)
t:check(db > 50, string.format("seek %.3f: SNR %.1f > 50 dB", s, db))
end
dec:seek(100)
local _, n = dec:read(100)
t:eq(n, 0, "seek past the end reads nothing")
dec:seek(0)
local _, n2 = dec:read(100)
t:eq(n2, 100, "seek back to 0")
dec:seek(0 / 0)
t:eq(dec:position(), 0, "seek(nan) goes to 0")
end
-- stereo downmix of the 5.1 file: the same matrix applied to the reference
do
local fx = FX.surround51
local dec = Opus.open(Bytes.reader(fx.data), { stereo = true })
t:check(dec.channels == 2 and dec.sourceChannels == 6, "downmix: 2 output channels")
local pcm, n = dec:read(dec.frames)
t:eq(n, dec.frames, "downmix: all frames")
local m = { 0.529, 0, 0.3741, 0.3741, 0, 0.529, 0.4582, 0.2645, 0.2645, 0.4582, 0.3741, 0.3741 }
local exp = buffer.create(n * 8)
for i = 0, n - 1 do
local l, r = 0, 0
for c = 0, 5 do
local v = buffer.readf32(fx.vorbisRef, (i * 6 + c) * 4)
l += v * m[c * 2 + 1]
r += v * m[c * 2 + 2]
end
buffer.writef32(exp, i * 8, l)
buffer.writef32(exp, i * 8 + 4, r)
end
local db = snr(pcm, exp, n * 2)
t:check(db > 100, string.format("downmix SNR %.1f", db))
end
-- ------------------------------------------------------------------------------------------------ CELT alone
do
local endbands = { [Packet.BW_NB] = 13, [Packet.BW_MB] = 17, [Packet.BW_WB] = 17, [Packet.BW_SWB] = 19, [Packet.BW_FB] = 21 }
for _, name in { "celt_st_128", "celt_st_32", "celt_st_64", "celt_st_256", "celt_mono_64", "celt_fs2_5", "celt_fs5", "celt_fs10", "celt_fs40", "celt_fs60", "ff_cbr", "ff_lowdelay" } do
local fx = FX[name]
local pk = packets(fx.data)
local head = pk[1]
local channels = buffer.readu8(head.data, head.offset + 9)
local preskip = buffer.readu16(head.data, head.offset + 10)
local st = Celt.new(channels)
local out = {}
local total = 0
local offs, sizes = {}, {}
local allOk = true
for p = 3, #pk do
local P = pk[p]
local count, toc = Packet.parse(P.data, P.offset, P.size, offs, sizes)
allOk = allOk and count > 0 and Packet.mode(toc) == Packet.MODE_CELT_ONLY
local fs48 = Packet.samplesPerFrame(toc, 48000)
st["end"] = endbands[Packet.bandwidth(toc)]
st.stream_channels = Packet.channels(toc)
for f = 1, count do
local ret = Celt.decode(st, P.data, offs[f], sizes[f], out, 1 + total * channels, fs48, nil, false)
allOk = allOk and ret == fs48
total += fs48
end
end
t:check(allOk, name .. ": every packet is CELT-only and decodes")
local refFrames = buffer.len(fx.ref) // 4 // channels
t:check(total - preskip >= refFrames and total - preskip - refFrames < 960 * 3, name .. ": CELT sample count")
local n = refFrames * channels
local ob = buffer.create(n * 4)
for i = 0, n - 1 do
buffer.writef32(ob, i * 4, out[preskip * channels + i + 1])
end
local db = snr(ob, fx.ref, n)
t:check(db > 60, string.format("%s: CELT alone SNR %.1f > 60 dB", name, db))
end
end
-- ------------------------------------------------------------------------------------------------ SILK alone
do
local rates = { [Packet.BW_NB] = 8000, [Packet.BW_MB] = 12000, [Packet.BW_WB] = 16000 }
local function decodeSilk(name: string, hybridOk: boolean?, lose: boolean?): ({ number }, number, number, number)
local pk = packets(FX[name].data)
local channels = buffer.readu8(pk[1].data, pk[1].offset + 9)
local preskip = buffer.readu16(pk[1].data, pk[1].offset + 10)
local st = Silk.new(channels)
local out = {}
local total = 0
local offs, sizes = {}, {}
local allOk = true
for p = 3, #pk do
local P = pk[p]
local count, toc = Packet.parse(P.data, P.offset, P.size, offs, sizes)
local mode = Packet.mode(toc)
allOk = allOk and count > 0 and (mode == Packet.MODE_SILK_ONLY or (hybridOk == true and mode == Packet.MODE_HYBRID))
local fs48 = Packet.samplesPerFrame(toc, 48000)
local lostPacket = lose and p % 7 == 0 and p < #pk - 80
local ctrl = {
nChannelsAPI = channels,
nChannelsInternal = Packet.channels(toc),
API_sampleRate = 48000,
internalSampleRate = if mode == Packet.MODE_HYBRID then 16000 else rates[Packet.bandwidth(toc)],
payloadSize_ms = math.max(10, fs48 // 48),
}
for f = 1, count do
local lost = if lostPacket or sizes[f] <= 1 then 1 else 0
local ec = RD.new(P.data, offs[f], sizes[f])
local decoded = 0
repeat
local ret, n = Silk.decode(st, ctrl, lost, decoded == 0, ec, out, 1 + (total + decoded) * channels)
allOk = allOk and ret == 0
decoded += n
until decoded >= fs48 or n <= 0
total += decoded
end
end
t:check(allOk, name .. ": every packet is SILK and decodes")
return out, total, channels, preskip
end
for _, name in { "silk_nb", "silk_nb_st", "silk_mb", "silk_wb", "silk_wb_st" } do
local out, total, channels, preskip = decodeSilk(name)
local ref = FX[name].ref
local refFrames = buffer.len(ref) // 4 // channels
t:check(total - preskip >= refFrames and total - preskip - refFrames < 960 * 3, name .. ": SILK sample count")
local n = refFrames * channels
local ob = buffer.create(n * 4)
for i = 0, n - 1 do
buffer.writef32(ob, i * 4, out[preskip * channels + i + 1])
end
local db = snr(ob, ref, n)
t:check(db > 90, string.format("%s: SILK alone SNR %.1f > 90 dB", name, db))
end
local _, total = decodeSilk("hybrid_swb", true)
t:check(total > 0, "hybrid_swb: SILK layer decodes")
-- packet loss concealment: every 7th packet lost; output bounded, the last second matches again
for _, name in { "silk_nb", "silk_wb_st" } do
local out, tot, channels, preskip = decodeSilk(name, false, true)
local finite = true
for i = 1, tot * channels do
local v = out[i]
if v ~= v or math.abs(v) > 1 then
finite = false
end
end
t:check(finite, name .. ": PLC output bounded")
local ref = FX[name].ref
local refFrames = buffer.len(ref) // 4 // channels
local n = 48000 * channels
local from = (refFrames - 48000) * channels
local ob = buffer.create(n * 4)
for i = 0, n - 1 do
buffer.writef32(ob, i * 4, out[preskip * channels + from + i + 1])
end
local db = snr(ob, ref, n, 0, from * 4)
t:check(db > 15, string.format("%s: recovers after losses (last second SNR %.1f)", name, db))
end
end
-- ------------------------------------------------------------------------------------------------ errors
do
local d, err = Opus.open(Bytes.reader(buffer.fromstring("not an ogg file at all")))
t:check(d == nil and err and err.code == Err.CORRUPT, "garbage is CORRUPT: " .. tostring(err))
local _, e2 = Opus.open(Bytes.reader(FX.celt_st_128.data, 0, 40))
t:check(e2 and Err.is(e2), "a cut header is an Err: " .. tostring(e2))
local _, e3 = Opus.decode(Bytes.reader(buffer.create(0)))
t:check(e3 and Err.is(e3), "empty decode is an Err")
-- a truncated file opens and decodes its first half
local file = FX.hybrid_st.data
local cut = buffer.create(buffer.len(file) // 2)
buffer.copy(cut, 0, file, 0, buffer.len(cut))
local dec = Opus.open(Bytes.reader(cut))
t:check(dec, "truncated file opens")
local total = 0
while true do
local _, n = dec:read(4096)
if n == 0 then
break
end
total += n
end
t:check(total > 0, "truncated file decodes its first half")
local a = Opus.decode(Bytes.reader(cut))
t:check(a and a.frames == total, "decode of a truncated file keeps what decoded")
-- damaged packets (CRC checks off, so they reach the decoder) never throw
for _, name in { "celt_st_128", "hybrid_st", "silk_wb_st", "surround51" } do
local g = buffer.create(buffer.len(FX[name].data))
buffer.copy(g, 0, FX[name].data)
local seed = 12345
for i = 400, buffer.len(g) - 1, 97 do
seed = (seed * 1103515245 + 12345) % 2147483648
buffer.writeu8(g, i, bit32.bxor(buffer.readu8(g, i), seed % 256))
end
local dd = Opus.open(Bytes.reader(g), { verify = false })
t:check(dd, name .. ": damaged file opens")
local ok, e = pcall(function()
while true do
local _, n = dd:read(4096)
if n == 0 then
break
end
end
end)
t:check(ok, name .. ": damaged data decodes without error: " .. tostring(e))
end
end
-- ------------------------------------------------------------------------------------------------ packet fuzz
-- random packets (every TOC config, random payloads) and bit-flipped real packets: never throw, output finite
do
local rand = T.rng(987654321)
local pcm = table.create(5760 * 2, 0)
local decoded, rejected, bad = 0, 0, 0
local function run(dec: any, b: buffer, len: number)
local ok, n = pcall(Decoder.decode, dec, b, 0, len, pcm, 1, 5760)
if not ok then
bad += 1
return
end
if n > 0 then
decoded += 1
for i = 1, n * dec.channels do
local v = pcm[i]
if v ~= v or v == math.huge or v == -math.huge then
bad += 1
break
end
end
else
rejected += 1
end
end
for _, ch in { 1, 2 } do
local dec = Decoder.new(ch)
for i = 1, 1500 do
local len = 1 + rand(if rand(4) == 0 then 1275 else 120)
local b = buffer.create(len)
for k = 0, len - 1 do
buffer.writeu8(b, k, rand(256))
end
buffer.writeu8(b, 0, (i * 7 + ch) % 256) -- cycle through every TOC
run(dec, b, len)
if rand(50) == 0 then
Decoder.decode(dec, nil, 0, 0, pcm, 1, 960) -- concealment in between
end
end
end
for _, name in { "celt_st_128", "hybrid_st", "silk_wb_st", "mix_st_24", "celt_fs2_5" } do
local pk = packets(FX[name].data)
local dec = Decoder.new(2)
for p = 3, #pk do
local P = pk[p]
local b = buffer.create(P.size)
buffer.copy(b, 0, P.data, P.offset, P.size)
for _ = 1, 1 + rand(4) do
local k = 1 + rand(math.max(1, P.size - 1))
if k < P.size then
buffer.writeu8(b, k, bit32.bxor(buffer.readu8(b, k), bit32.lshift(1, rand(8))))
end
end
run(dec, b, P.size)
end
end
t:eq(bad, 0, "packet fuzz: no throws, finite output")
t:note("packet fuzz: %d packets decoded, %d rejected", decoded, rejected)
end
-- ------------------------------------------------------------------------------------------------ fuzz (whole files)
do
local samples = {}
for _, name in { "hybrid_fb", "silk_nb", "celt_fs5" } do
table.insert(samples, string.sub(FX[name].raw, 1, 6000))
end
t:fuzz("open + read", function(b: buffer)
local dec = Opus.open(Bytes.reader(b), { verify = false })
if dec then
dec:read(2000)
dec:seek(0.01)
dec:read(500)
end
return dec
end, samples, { mutations = 12, keepHeader = 4 })
t:fuzz("decode", function(b: buffer)
return Opus.decode(Bytes.reader(b))
end, samples, { mutations = 4, garbage = 50 })
end
t:done()