ws-m4a: CELT-only Opus encoder in audio/opus (RangeEncoder + CeltEncoder ported from the libopus 1.6 encoder paths to mirror the absorbed decoder: 20 ms full-band CBR, mono and mid/side stereo, silence frames; Encode: Ogg Opus with OpusHead/OpusTags, end trimming, 48 kHz resampling); checked by opusdec / opusinfo / ffmpeg; Opus.caps.encode = true (opus test updated), deps += codecs/Mdct

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
4DBugandClaude Opus 5.5 committed 2026-10-31 09:22:52 -05:00
1 parent c3cf73e29f
commit c43c56eadd
13 files changed
+1761 -8

No files matched your search

+1 -1
View File
@@ -12,7 +12,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| audio | flac | .flac .oga | yes | - | streaming: true, depths: 4, 8, 12, 16, 20, 24, 32, ogg: true, seek: true | `tests/audio/flac.luau` |
| audio | m4a | .m4a .m4b .m4r .aac.mp4 | yes | yes | codecs: "aac", "alac", encodeCodecs: "alac", tags: true, streaming: true | `tests/audio/m4a.luau` |
| audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | - | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` |
| audio | opus | .opus | yes | - | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000 | `tests/audio/opus.luau` |
| audio | opus | .opus | yes | yes | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000, encodeModes: "celt" | `tests/audio/opus.luau` |
| audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` |
| archive | zip | .zip .wsz | yes | yes | methods: "store", "deflate", zip64: true | `tests/archive/zip.luau` |
| playlist | m3u | .m3u .m3u8 | yes | yes | hls: true | `tests/playlist/m3u.luau` |
+1
View File
@@ -16,6 +16,7 @@
| `src/Formats/playlist/` (m3u, pls; xspf is new), `src/Formats/codecs/Url/`, `src/Formats/codecs/Text/` | playlist-luau 3fc7fd3 (same author), written from RFC 3986 / RFC 8216 | no licence chosen yet; no third-party code |
| `src/Formats/codecs/Aac/Tables.luau` | the Huffman codebooks, scalefactor band offsets and TNS limits of ISO/IEC 14496-3 (Annex 4.A), transcribed mechanically from FFmpeg's `libavcodec/aactab.c` (tables of the standard only; no FFmpeg code) | FFmpeg is LGPL-2.1-or-later; the tables are the standard's data |
| `src/Formats/codecs/Aac/`, `codecs/Alac/`, `codecs/Mdct/`, `containers/IsoBmff/`, `audio/m4a`, `audio/aac`, `audio/caf` | written for this library from ISO/IEC 14496-3 / 14496-12 / 23008-12, Apple's ALAC and CAF specifications | no third-party code |
| `src/Formats/audio/opus/CeltEncoder.luau`, `src/Formats/audio/opus/RangeEncoder.luau` | the encoder side of libopus 1.6 (celt_encoder.c, entenc.c, quant_bands.c, laplace.c, rate.c, bands.c, vq.c, cwrs.c), ported to mirror the absorbed decoder; analysis simplified (ws-m4a) | libopus BSD 3-clause: [libopus-BSD.txt](libopus-BSD.txt) |
| `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) |
Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this
+2 -2
View File
@@ -104,8 +104,8 @@ local list: { Entry } = {
path = "audio/opus",
extensions = { "opus" },
mime = { "audio/opus", "audio/ogg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" },
caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 } },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" } },
load = function()
return require("@formats/audio/opus")
end,
File diff suppressed because it is too large. Load diff
+181
View File
@@ -0,0 +1,181 @@
--!strict
-- audio/opus/Encode: Ogg Opus writing (RFC 7845) around audio/opus/CeltEncoder: CELT-only packets (TOC config 31:
-- full band, 20 ms, code 0), OpusHead (mapping family 0, the pre-skip = the encoder's delay), OpusTags (vendor +
-- the tags as Vorbis comments), granule positions with end trimming, pages through containers/Ogg's muxer. Input at
-- other rates is resampled to 48 kHz (a Kaiser-windowed sinc; quality enough for a codec input). New in formats-luau.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Ogg = require("@formats/containers/Ogg")
local CeltEncoder = require("@formats/audio/opus/CeltEncoder")
local Encode = {}
export type Options = {
bitrate: number?, -- bits per second (default 64000 per channel; 6000 .. 510000, constant)
tags: { [string]: string }?, -- default: the audio's tags
vendor: string?, -- OpusTags vendor (default "formats-luau")
serial: number?, -- Ogg stream serial (default 0x4f707573)
}
local floor, sin, pi, sqrt = math.floor, math.sin, math.pi, math.sqrt
local function besselI0(x: number): number
local sum, term = 1, 1
for k = 1, 60 do
term *= (x / (2 * k)) ^ 2
sum += term
if term < sum * 1e-15 then
break
end
end
return sum
end
-- resample(src (interleaved f32 buffer), frames, channels, from, to) -> { number } interleaved, frames out
local function resample(src: buffer, frames: number, channels: number, from: number, to: number): ({ number }, number)
local outFrames = floor(frames * to / from + 0.5)
local out = table.create(outFrames * channels, 0)
local ratio = to / from
local cutoff = 0.97 * math.min(1, ratio) -- of the input Nyquist
local half = 16 -- zero crossings each side (at the cutoff)
local width = half / cutoff
local beta = 8
local i0b = besselI0(beta)
local readf32 = buffer.readf32
for j = 0, outFrames - 1 do
local t = j / ratio -- the input position
local first = math.max(0, floor(t - width) + 1)
local last = math.min(frames - 1, floor(t + width))
for c = 0, channels - 1 do
local acc, wsum = 0, 0
for i = first, last do
local d = i - t
local x = d * cutoff
local s = if x == 0 then 1 else sin(pi * x) / (pi * x)
local r = d / width
local w = besselI0(beta * sqrt(math.max(0, 1 - r * r))) / i0b
local h = s * w
acc += readf32(src, (i * channels + c) * 4) * h
wsum += h
end
out[j * channels + c + 1] = if wsum ~= 0 then acc / wsum else 0
end
end
return out, outFrames
end
local TAG_NAMES: { [string]: string } = {
title = "TITLE", artist = "ARTIST", album = "ALBUM", albumartist = "ALBUMARTIST", date = "DATE", genre = "GENRE",
track = "TRACKNUMBER", tracktotal = "TRACKTOTAL", disc = "DISCNUMBER", comment = "COMMENT", composer = "COMPOSER",
}
-- encode(audio | decoder, opts) -> buffer | nil, Err
function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?)
local o = opts or {}
if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
end
local ch = value.channels
if ch ~= 1 and ch ~= 2 then
return nil, Err.new(Err.UNSUPPORTED, "the CELT encoder writes mono or stereo (got " .. ch .. " channels)")
end
local rate = value.sampleRate
if rate < 1000 or rate > 768000 then
return nil, Err.new(Err.ARG, "bad sample rate " .. tostring(rate))
end
local bitrate = o.bitrate or 64000 * ch
if type(bitrate) ~= "number" or bitrate < 6000 or bitrate > 510000 then
return nil, Err.new(Err.ARG, "bitrate 6000 .. 510000")
end
-- the whole input as an interleaved f32 buffer
local samples: buffer, frames: number
if value.kind == "audio" and type(value.samples) == "buffer" then
samples, frames = value.samples, value.frames
if buffer.len(samples) < frames * ch * 4 then
return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels")
end
elseif type(value.read) == "function" then
local w = Bytes.writer(65536)
frames = 0
local chunk: buffer? = nil
while true do
local b, n = value:read(16384, chunk)
chunk = b
if n <= 0 then
break
end
w:bytes(b, 0, n * ch * 4)
frames += n
end
samples = w:finish()
else
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
end
-- 48 kHz floats
local pcm: { number }, n48: number
if rate == 48000 then
n48 = frames
pcm = table.create(frames * ch, 0)
for i = 1, frames * ch do
pcm[i] = buffer.readf32(samples, (i - 1) * 4)
end
else
pcm, n48 = resample(samples, frames, ch, rate, 48000)
end
local FRAME = CeltEncoder.FRAME
local preSkip = CeltEncoder.DELAY
local packets = (n48 + preSkip + FRAME - 1) // FRAME
-- zero padding to whole frames
for i = n48 * ch + 1, packets * FRAME * ch do
pcm[i] = 0
end
local bytes = math.clamp(floor(bitrate * FRAME / 48000 / 8), if ch == 2 then 40 else 20, 1275 - 1)
local st = CeltEncoder.new(ch)
local mux = Ogg.muxer({ pageSize = 4096 })
local s = mux:stream(o.serial or 0x4f707573)
-- OpusHead
local head = Bytes.writer(19)
head:string("OpusHead")
head:u8(1)
head:u8(ch)
head:u16le(preSkip)
head:u32le(floor(rate))
head:u16le(0)
head:u8(0)
s:packet(head:finish(), 0, { flush = true })
-- OpusTags
local tags = o.tags or value.tags or {}
local tw = Bytes.writer(256)
tw:string("OpusTags")
local vendor = o.vendor or "formats-luau"
tw:u32le(#vendor)
tw:string(vendor)
local keys = {}
for k, v in tags do
if type(k) == "string" and type(v) == "string" then
table.insert(keys, k)
end
end
table.sort(keys)
tw:u32le(#keys)
for _, k in keys do
local field = (TAG_NAMES[k] or string.upper(k)) .. "=" .. tags[k]
tw:u32le(#field)
tw:string(field)
end
s:packet(tw:finish(), 0, { flush = true })
-- audio
local toc = 31 * 8 + (if ch == 2 then 4 else 0)
for p = 0, packets - 1 do
local frame = CeltEncoder.encodeFrame(st, pcm, p * FRAME * ch + 1, ch, bytes)
local pkt = buffer.create(bytes + 1)
buffer.writeu8(pkt, 0, toc)
buffer.copy(pkt, 1, frame, 0, bytes)
local last = p == packets - 1
local granule = if last then preSkip + n48 else (p + 1) * FRAME
s:packet(pkt, granule, { eos = last })
end
return mux:finish(), nil
end
return Encode
+252
View File
@@ -0,0 +1,252 @@
--!strict
--!native
--!optimize 2
-- audio/opus/RangeEncoder: the range encoder (RFC 6716 section 5.1), a port of libopus celt/entenc.c (BSD:
-- licenses/libopus-BSD.txt), the mirror of audio/opus/RangeDecoder. Writes one fixed-size frame: the range-coded
-- symbols from the front, the raw bits (ec_enc_bits) from the back, zeros between. Values stay below 2^32 as plain
-- numbers. Never throws: running out of room sets `error`.
local RangeEncoder = {}
export type Enc = {
buf: buffer,
storage: number,
offs: number,
end_offs: number,
end_window: number,
nend_bits: number,
nbits_total: number,
rng: number,
val: number,
rem: number,
ext: number,
error: number,
}
local CODE_TOP = 2147483648 -- 1 << 31
local CODE_BOT = 8388608 -- CODE_TOP >> 8
local CODE_SHIFT = 23
local SYM_MAX = 255
local countlz = bit32.countlz
local band = bit32.band
local readu8, writeu8 = buffer.readu8, buffer.writeu8
local floor = math.floor
local function ilog(x: number): number
return 32 - countlz(x)
end
RangeEncoder.ilog = ilog
-- new(storage) -> Enc over a fresh zeroed buffer of storage bytes
function RangeEncoder.new(storage: number): Enc
return {
buf = buffer.create(math.max(storage, 1)),
storage = storage,
offs = 0,
end_offs = 0,
end_window = 0,
nend_bits = 0,
nbits_total = 33, -- EC_CODE_BITS + 1
rng = CODE_TOP,
val = 0,
rem = -1,
ext = 0,
error = 0,
}
end
local function writeByte(e: Enc, v: number)
if e.offs + e.end_offs >= e.storage then
e.error = -1
return
end
writeu8(e.buf, e.offs, band(v, 255))
e.offs += 1
end
local function writeByteAtEnd(e: Enc, v: number)
if e.offs + e.end_offs >= e.storage then
e.error = -1
return
end
e.end_offs += 1
writeu8(e.buf, e.storage - e.end_offs, band(v, 255))
end
local function carryOut(e: Enc, c: number)
if c ~= SYM_MAX then
local carry = if c >= 256 then 1 else 0
if e.rem >= 0 then
writeByte(e, e.rem + carry)
end
if e.ext > 0 then
local sym = band(SYM_MAX + carry, 255)
repeat
writeByte(e, sym)
e.ext -= 1
until e.ext <= 0
end
e.rem = band(c, 255)
else
e.ext += 1
end
end
local function normalize(e: Enc)
while e.rng <= CODE_BOT do
carryOut(e, floor(e.val / 8388608))
e.val = (e.val * 256) % CODE_TOP
e.rng *= 256
e.nbits_total += 8
end
end
-- encode(fl, fh, ft): the symbol [fl, fh) of ft
function RangeEncoder.encode(e: Enc, fl: number, fh: number, ft: number)
local r = floor(e.rng / ft)
if fl > 0 then
e.val += e.rng - r * (ft - fl)
e.rng = r * (fh - fl)
else
e.rng -= r * (ft - fh)
end
normalize(e)
end
-- encodeBin(fl, fh, bits): ft = 2^bits
function RangeEncoder.encodeBin(e: Enc, fl: number, fh: number, bits: number)
local ft = 2 ^ bits
local r = floor(e.rng / ft)
if fl > 0 then
e.val += e.rng - r * (ft - fl)
e.rng = r * (fh - fl)
else
e.rng -= r * (ft - fh)
end
normalize(e)
end
-- bitLogp(v, logp): a bit whose probability of being 1 is 2^-logp
function RangeEncoder.bitLogp(e: Enc, v: boolean, logp: number)
local r = e.rng
local s = floor(r / 2 ^ logp)
r -= s
if v then
e.val += r
e.rng = s
else
e.rng = r
end
normalize(e)
end
-- icdf(s, icdf, ftb): symbol s (0-based) of an inverse CDF table (1-based Luau array) with 2^ftb total
function RangeEncoder.icdf(e: Enc, s: number, icdf: { number }, ftb: number)
local r = floor(e.rng / 2 ^ ftb)
if s > 0 then
e.val += e.rng - r * icdf[s]
e.rng = r * (icdf[s] - icdf[s + 1])
else
e.rng -= r * icdf[s + 1]
end
normalize(e)
end
-- bits(fl, n): n raw bits (n <= 25), written from the end of the frame
function RangeEncoder.bits(e: Enc, fl: number, n: number)
local window = e.end_window
local used = e.nend_bits
if used + n > 32 then
repeat
writeByteAtEnd(e, window % 256)
window = floor(window / 256)
used -= 8
until used < 8
end
window += fl * 2 ^ used
used += n
e.end_window = window
e.nend_bits = used
e.nbits_total += n
end
-- uint(fl, ft): fl uniformly in [0, ft), ft up to 2^32
function RangeEncoder.uint(e: Enc, fl: number, ft: number)
ft -= 1
local ftb = ilog(ft)
if ftb > 8 then
ftb -= 8
local sh = 2 ^ ftb
local ft1 = floor(ft / sh) + 1
local hi = floor(fl / sh)
RangeEncoder.encode(e, hi, hi + 1, ft1)
RangeEncoder.bits(e, fl - hi * sh, ftb)
else
RangeEncoder.encode(e, fl, fl + 1, ft + 1)
end
end
function RangeEncoder.tell(e: Enc): number
return e.nbits_total - ilog(e.rng)
end
local CORRECTION = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 }
function RangeEncoder.tellFrac(e: Enc): number
local nbits = e.nbits_total * 8
local l = ilog(e.rng)
local r = floor(e.rng / 2 ^ (l - 16))
local b = floor(r / 4096) - 8
if r > CORRECTION[b + 1] then
b += 1
end
return nbits - (l * 8 + b)
end
-- done(): flush; the frame is e.buf (storage bytes)
function RangeEncoder.done(e: Enc)
local l = 32 - ilog(e.rng)
local msk = floor((CODE_TOP - 1) / 2 ^ l)
local stop = floor((e.val + msk) / (msk + 1)) * (msk + 1)
if stop + msk >= e.val + e.rng then
l += 1
msk = floor(msk / 2)
stop = floor((e.val + msk) / (msk + 1)) * (msk + 1)
end
while l > 0 do
carryOut(e, floor(stop / 8388608))
stop = (stop * 256) % CODE_TOP
l -= 8
end
if e.rem >= 0 or e.ext > 0 then
carryOut(e, 0)
end
local window = e.end_window
local used = e.nend_bits
while used >= 8 do
writeByteAtEnd(e, window % 256)
window = floor(window / 256)
used -= 8
end
if e.error == 0 then
local a, b = e.offs, e.storage - e.end_offs
if b > a then
buffer.fill(e.buf, a, 0, b - a)
end
if used > 0 then
if e.end_offs >= e.storage then
e.error = -1
else
l = -l
if e.offs + e.end_offs >= e.storage and l < used then
window = window % 2 ^ l
e.error = -1
end
local p = e.storage - e.end_offs - 1
writeu8(e.buf, p, bit32.bor(readu8(e.buf, p), window))
end
end
end
end
local _ = CODE_SHIFT
return RangeEncoder
+14 -4
View File
@@ -5,14 +5,17 @@
-- Supports: decode of every Opus mode / bandwidth / frame size, mono, stereo and surround (optional stereo downmix,
-- opts.stereo), pre-skip, end trimming, output gain, OpusTags, sample-accurate seeking (granule bisection + 80 ms
-- pre-roll), damaged files (concealment). Output is always 48 kHz f32.
-- Not supported: encoding, mapping family 3 (ambisonics projection), chained streams (the first Opus stream is
-- decoded), CELT pitch PLC (noise PLC only).
-- Encoding (audio/opus/Encode + CeltEncoder, ws-m4a): a CELT-only fixed-frame encoder (20 ms, full band, constant
-- bit rate, mono or dual stereo; other input rates resampled to 48 kHz) writing Ogg Opus with OpusTags.
-- Not supported: SILK / hybrid encoding, transients / pitch pre-filter in the encoder, mapping family 3 (ambisonics
-- projection), chained streams (the first Opus stream is decoded), CELT pitch PLC (noise PLC only).
-- Changes from opus-luau: the injected Ogg demuxer is containers/Ogg; errors are core/Err values; read() takes an
-- optional output buffer; decode() fully decodes to an Audio.
--
-- local dec, err = Opus.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(n, out?), dec:seek(s), ...
-- local audio = Opus.decode(Bytes.reader(buf)) -- a Types.Audio
-- Opus.Decoder.new(channels) + Opus.Decoder.decode(st, buf, off, len, pcm, base, maxFrames) -- raw packets
-- local file = Opus.encode(audio, { bitrate = 96000 }) -- Ogg Opus (CELT only)
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
@@ -24,6 +27,7 @@ local Packet = require("@formats/audio/opus/Packet")
local RangeDecoder = require("@formats/audio/opus/RangeDecoder")
local Celt = require("@formats/audio/opus/Celt")
local Silk = require("@formats/audio/opus/Silk")
local Encode = require("@formats/audio/opus/Encode")
-- ------------------------------------------------------------------------------------------------ contract
local Opus = {
@@ -31,8 +35,8 @@ local Opus = {
category = "audio",
extensions = { "opus" },
mime = { "audio/opus", "audio/ogg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" },
caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 } },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" } },
}
-- ------------------------------------------------------------------------------------------------ types
@@ -213,6 +217,12 @@ function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?)
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(audio | decoder, opts?) -> Ogg Opus buffer | nil, Err (CELT only; see audio/opus/Encode)
function Opus.encode(value: any, opts: Encode.Options?): (buffer?, Err.Err?)
return Encode.encode(value, opts)
end
-- ------------------------------------------------------------------------------------------------ open
local Stream = {}
Stream.__index = Stream
+42
View File
@@ -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
+1 -1
View File
@@ -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")
+114
View File
@@ -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()
+10
View File
@@ -184,3 +184,13 @@ do
end
end)
end
do
local Opus = require("@formats/audio/opus")
local Cases = require("@tests/audio/_opus_cases")
local c = Cases.list[2]
local a = Cases.signal(c)
local dt = bench("opus celt encode 128k (1.5 s st)", 2, a.frames * a.channels * 2, function()
Opus.encode(a, { bitrate = 128000 })
end)
local _ = dt
end
+17
View File
@@ -0,0 +1,17 @@
-- tools/fixtures/_opus_encode: run by tools/fixtures/opus_celt.py (luau, from the repo root): encodes
-- tests/audio/_opus_cases with audio/opus's CELT encoder and prints "<name> <hex>" lines for opusdec / ffmpeg.
local Opus = require("@formats/audio/opus")
local Cases = require("@tests/audio/_opus_cases")
for _, c in Cases.list do
local out, err = Opus.encode(Cases.signal(c), { bitrate = c.bitrate })
if not out then
print(c.name .. " ERROR " .. tostring(err))
else
local t = table.create(buffer.len(out))
for i = 0, buffer.len(out) - 1 do
t[i + 1] = string.format("%02x", buffer.readu8(out, i))
end
print(c.name .. " " .. table.concat(t))
end
end
+48
View File
@@ -0,0 +1,48 @@
# The CELT encoder reference check (tools/fixtures.py): runs tools/fixtures/_opus_encode.luau (our encoder over
# tests/audio/_opus_cases.luau), then the reference tools through nix: opusdec --float (libopus), opusinfo (stream
# structure), ffmpeg (an independent Ogg / Opus reader).
# tests/gen/opus_celt.luau { { name, crc (of our bytes), opusdec (f32le 48 kHz decode), opusinfo (exit 0),
# ffmpeg (decoded), ffmpegFrames, comments (opusinfo's user comments) } }
import os, re, shutil, subprocess, tempfile, zlib
INPUTS = ["src/Formats/audio/opus", "src/Formats/codecs/Mdct", "src/Formats/containers/Ogg",
"tests/audio/_opus_cases.luau", "tools/fixtures/_opus_encode.luau"]
def generate(ctx):
luau = os.environ.get("LUAU") or shutil.which("luau")
script = os.path.join(ctx.root, "tools/fixtures/_opus_encode.luau")
if luau:
out = subprocess.run([luau, script], capture_output=True, check=True, cwd=ctx.root).stdout
else:
out = ctx.nix("luau", ["luau", script])
d = tempfile.mkdtemp(prefix="opus-celt-fx-")
try:
cases = []
for line in out.decode().split("\n"):
if not line.strip():
continue
name, hx = line.split(" ", 1)
if hx.startswith("ERROR"):
raise RuntimeError("opus_celt fixtures: our encoder failed on %s: %s" % (name, hx))
data = bytes.fromhex(hx)
path = os.path.join(d, name + ".opus")
with open(path, "wb") as f:
f.write(data)
raw = os.path.join(d, name + ".f32")
ctx.nix("opus-tools", ["opusdec", "--quiet", "--float", "--rate", "48000", path, raw])
with open(raw, "rb") as f:
pcm = f.read()
info = subprocess.run(["nix", "shell", "nixpkgs#opus-tools", "-c", "opusinfo", path], capture_output=True)
text = info.stdout.decode(errors="replace")
comments = {}
for m in re.finditer(r"^\s*([A-Za-z]+)=(.*)$", text, re.M):
comments[m.group(1).lower()] = m.group(2)
ok = info.returncode == 0 and "WARNING" not in text and "ERROR" not in text.upper().replace("ERRORS", "")
ff = subprocess.run(["nix", "shell", "nixpkgs#ffmpeg", "-c", "ffmpeg", "-v", "error", "-i", path, "-f", "f32le", "-ac", "1", "-"], capture_output=True)
cases.append({"name": name, "crc": zlib.crc32(data), "opusdec": pcm, "opusinfo": ok,
"ffmpeg": ff.returncode == 0 and len(ff.stderr) == 0, "ffmpegFrames": len(ff.stdout) // 4,
"comments": comments})
ctx.emit("opus_celt", cases)
finally:
shutil.rmtree(d, ignore_errors=True)