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.)
This commit is contained in:
4DBug committed 2026-10-31 10:50:56 -05:00
1 parent 4f2ceec735
commit 7169f2cc2c
17 files changed
+777 -150

No files matched your search

+30
View File
@@ -24,6 +24,20 @@ local Convert = require("@formats/codecs/Pcm/Convert")
local Pcm = {}
Pcm.Convert = Convert
-- Channel order. Decoders return WAVE (WAVEFORMATEXTENSIBLE) order: FL FR C LFE BL BR (SL SR) ..., as FLAC, WAV and
-- AAC store it. Vorbis and Opus (mapping family 1) store the Vorbis order (FL C FR ... LFE last); WAVE_FROM_VORBIS[n][i]
-- is the Vorbis-order channel (1-based) that WAVE-order channel i holds, for n = 1 .. 8 channels.
Pcm.WAVE_FROM_VORBIS = {
{ 1 },
{ 1, 2 },
{ 1, 3, 2 }, -- L C R -> L R C
{ 1, 2, 3, 4 }, -- FL FR RL RR
{ 1, 3, 2, 4, 5 }, -- FL C FR RL RR -> FL FR C RL RR
{ 1, 3, 2, 6, 4, 5 }, -- FL C FR RL RR LFE -> FL FR C LFE RL RR
{ 1, 3, 2, 7, 6, 4, 5 }, -- FL C FR SL SR RC LFE -> FL FR C LFE RC SL SR
{ 1, 3, 2, 8, 6, 7, 4, 5 }, -- FL C FR SL SR RL RR LFE -> FL FR C LFE RL RR SL SR
}
export type Source = {
sampleRate: number,
channels: number,
@@ -211,6 +225,22 @@ function Pcm.encode(src: Source, fmt: string, w: Bytes.Writer): (number?, Err.Er
end
-- ------------------------------------------------------------------------------------------------ conversions
-- reorder(buf, offset, frames, channels, map): in place, frame by frame, channel i of the result = channel map[i]
-- (1-based) of the input; for converting between channel orders (Pcm.WAVE_FROM_VORBIS)
function Pcm.reorder(buf: buffer, offset: number, frames: number, channels: number, map: { number })
local tmp = table.create(channels, 0)
local readf32, writef32 = buffer.readf32, buffer.writef32
for f = 0, frames - 1 do
local p = offset + f * channels * 4
for c = 1, channels do
tmp[c] = readf32(buf, p + (map[c] - 1) * 4)
end
for c = 1, channels do
writef32(buf, p + (c - 1) * 4, tmp[c])
end
end
end
-- toInt(x, bits) -> the nearest bits-wide signed integer to x * 2^(bits-1), clipped (NaN -> 0)
function Pcm.toInt(x: number, bits: number): number
local s = 2 ^ (bits - 1)
+3 -2
View File
@@ -1,8 +1,9 @@
--!strict
--!native
--!optimize 2
-- audio/opus/RangeDecoder: Range decoder (RFC 6716 section 4.1, libopus celt/entdec.c). Reads one Opus frame from a `buffer` slice
-- [base, base + storage). Raw bits (ec_dec_bits) are read from the end of the slice backwards.
-- codecs/RangeCoder/Decoder: the Opus range decoder (RFC 6716 section 4.1, libopus celt/entdec.c). Reads one Opus
-- frame from a `buffer` slice [base, base + storage). Raw bits (ec_dec_bits) are read from the end of the slice
-- backwards.
-- All values stay below 2^32, so plain Luau numbers hold them exactly; floor division is exact below 2^52.
local RangeDecoder = {}
+2 -2
View File
@@ -1,8 +1,8 @@
--!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
-- codecs/RangeCoder/Encoder: the Opus range encoder (RFC 6716 section 5.1), a port of libopus celt/entenc.c (BSD:
-- licenses/libopus-BSD.txt), the mirror of codecs/RangeCoder/Decoder. 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 = {}
+13
View File
@@ -0,0 +1,13 @@
--!strict
-- codecs/RangeCoder: the RFC 6716 range coder (libopus celt/entdec.c + entenc.c, BSD: licenses/libopus-BSD.txt):
-- symbols range-coded from the front of a frame, raw bits from its back. Opus (CELT and SILK) uses it; LZMA, VP8 and
-- CABAC have their own (different) binary coders. Moved here from audio/opus by the cleanup pass (same code).
--
-- local RD = require("@formats/codecs/RangeCoder/Decoder") -- RD.new(buf, base, size), RD.icdf / bits / uint ...
-- local RE = require("@formats/codecs/RangeCoder/Encoder") -- RE.new(size), RE.icdf / bits / uint, RE.done
local RangeCoder = {
Decoder = require("@formats/codecs/RangeCoder/Decoder"),
Encoder = require("@formats/codecs/RangeCoder/Encoder"),
}
return RangeCoder
+378
View File
@@ -0,0 +1,378 @@
--!strict
--!native
--!optimize 2
-- codecs/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or
-- whole-buffer, any channel count, interleaved f32 (the Types.Audio / Decoder layout). Used by the Opus, MP3 and MP2
-- encoders (their input rates are fixed) and ops/AudioOps.resample. New in formats-luau (the textbook polyphase
-- filter; the kernel is the one the Opus encoder carried).
--
-- The filter is a polyphase table: exact phases when to / gcd(from, to) <= 4096 (44100 <-> 48000: 160 phases),
-- else 4096 phases with linear interpolation between them. Each phase is normalised to unit DC gain. The cutoff is a
-- fraction (opts.cutoff, default 0.97) of the lower Nyquist frequency; quality picks the taps per side at the cutoff:
--
-- quality zero crossings per side Kaiser beta stop band
-- "low" 8 6 ~ -60 dB
-- "medium" 16 (default) 8 ~ -80 dB
-- "high" 32 10 ~ -100 dB
--
-- Output frame j sits at input time j * from / to (no delay: the filter is centred, the input is zero outside its
-- range); a stream of n input frames gives floor(n * to / from + 0.5) output frames.
--
-- local out, frames = Resample.buffer(samples, frames, channels, 44100, 48000, { quality = "high" })
-- local rs = Resample.new(44100, 48000, 2) -- nil, message for bad rates
-- local b, n = rs:process(chunk, chunkFrames) -- the output frames this input completes
-- local b2, n2 = rs:flush() -- the rest (the input end padded with zeros)
-- local src2 = Resample.source(pcmSource, 48000) -- a codecs/Pcm Source at the new rate
--
-- Never throws: bad arguments return nil, message (the api turns them into Err.ARG).
local Resample = {}
export type Options = {
quality: ("low" | "medium" | "high")?, -- default "medium"
cutoff: number?, -- pass band edge as a fraction of the lower Nyquist frequency, 0.5 .. 1 (default 0.97)
}
export type Resampler = {
from: number,
to: number,
channels: number,
-- process(src, frames, out?) -> interleaved f32 buffer, output frames (out is reused when big enough)
process: (self: Resampler, src: buffer, frames: number, out: buffer?) -> (buffer, number),
-- flush(out?) -> the remaining output frames; the resampler is finished afterwards
flush: (self: Resampler, out: buffer?) -> (buffer, number),
}
local QUALITY = { low = { 8, 6 }, medium = { 16, 8 }, high = { 32, 10 } }
local MAX_EXACT = 4096
local INTERP_PHASES = 4096
local floor, sin, pi, sqrt, max, min = math.floor, math.sin, math.pi, math.sqrt, math.max, math.min
local readf32, writef32 = buffer.readf32, buffer.writef32
local function besselI0(x: number): number
local sum, term = 1, 1
for k = 1, 80 do
term *= (x / (2 * k)) ^ 2
sum += term
if term < sum * 1e-16 then
break
end
end
return sum
end
local function gcd(a: number, b: number): number
while b ~= 0 do
a, b = b, a % b
end
return a
end
type Filter = {
taps: number, -- per phase
half: number, -- taps on the left of the centre (taps = 2 * half)
phases: number,
exact: boolean,
h: { number }, -- phase p, tap k: h[p * taps + k + 1]
}
-- filter(ratio, phases, exact, opts) -> the polyphase table. Phase p is the kernel for an output at fraction
-- p / phases past an input sample; tap k multiplies input (floor(t) - half + 1 + k).
local function makeFilter(ratio: number, phases: number, exact: boolean, zc: number, beta: number, cut: number): Filter
local cutoff = cut * min(1, ratio)
local width = zc / cutoff -- in input samples, each side
local half = math.ceil(width)
local taps = 2 * half
local i0b = besselI0(beta)
local n = if exact then phases else phases + 1
local h = table.create(n * taps, 0)
for p = 0, n - 1 do
local frac = p / phases
local sum = 0
local base = p * taps
for k = 0, taps - 1 do
local d = (k - half + 1) - frac -- input position minus output position
local r = d / width
local v = 0
if r > -1 and r < 1 then
local x = d * cutoff
local s = if x == 0 then 1 else sin(pi * x) / (pi * x)
v = s * besselI0(beta * sqrt(1 - r * r)) / i0b
end
h[base + k + 1] = v
sum += v
end
if sum ~= 0 then
for k = 1, taps do
h[base + k] /= sum
end
end
end
return { taps = taps, half = half, phases = phases, exact = exact, h = h }
end
-- the stream state: the input history as an interleaved Lua array; hist[1] is frame `base` (absolute)
type State = {
from: number,
to: number,
channels: number,
f: Filter,
step: number, -- M = from / g: the input advance per output frame, in units of 1 / L
L: number, -- to / g
hist: { number },
histFrames: number,
base: number, -- the absolute input frame of hist[1]
inFrames: number, -- absolute input frames received
outPos: number, -- next output frame (absolute)
done: boolean,
process: any,
flush: any,
}
-- run(st, lastInput) -> buffer, frames: every output frame whose taps end at or before lastInput (absolute, exclusive)
local function run(st: State, limitOut: number, out: buffer?): (buffer, number)
local f = st.f
local taps, half, h = f.taps, f.half, f.h
local ch = st.channels
local hist, base, histFrames = st.hist, st.base, st.histFrames
local L, M = st.L, st.step
local j0 = st.outPos
-- outputs j with floor(j * M / L) - half + taps <= available frames (zero beyond the end after flush)
local avail = base + histFrames
local jmax = limitOut
if not st.done then
-- the last tap must be buffered: floor(j * M / L) + half <= avail - 1, i.e. j * M < (avail - half) * L
local lim = floor(((avail - half) * L - 1) / M)
if lim + 1 < jmax then
jmax = lim + 1
end
end
local n = jmax - j0
if n <= 0 then
return out or buffer.create(0), 0
end
local bytes = n * ch * 4
local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes)
local exact = f.exact
local phases = f.phases
local o = 0
for j = j0, jmax - 1 do
local num = j * M
local ip = num // L -- floor(t)
local first = ip - half + 1 -- absolute input frame of tap 0
local rel = first - base -- frame index in hist
local kLo = if rel < 0 then -rel else 0
local kHi = taps - 1
if rel + kHi >= histFrames then
kHi = histFrames - 1 - rel
end
if exact then
local hb = (num - ip * L) * taps + 1 -- phase * taps + 1
for c = 0, ch - 1 do
local acc = 0
local hi = (rel + kLo) * ch + c + 1
for k = kLo, kHi do
acc += hist[hi] * h[hb + k]
hi += ch
end
writef32(b, o, acc)
o += 4
end
else
local fp = (num - ip * L) / L * phases
local p = floor(fp)
local a = fp - p
local hb = p * taps + 1
local hb2 = hb + taps
for c = 0, ch - 1 do
local acc, acc2 = 0, 0
local hi = (rel + kLo) * ch + c + 1
for k = kLo, kHi do
local x = hist[hi]
acc += x * h[hb + k]
acc2 += x * h[hb2 + k]
hi += ch
end
writef32(b, o, acc + (acc2 - acc) * a)
o += 4
end
end
end
st.outPos = jmax
-- drop history no future output needs (keep from the next output's first tap)
local keepFrom = (jmax * M) // L - half + 1
local drop = keepFrom - base
if drop > 0 then
if drop >= histFrames then
st.hist = {}
st.histFrames = 0
st.base = base + histFrames
else
local nh = table.create((histFrames - drop) * ch)
table.move(hist, drop * ch + 1, histFrames * ch, 1, nh)
st.hist = nh
st.histFrames = histFrames - drop
st.base = base + drop
end
end
return b, n
end
local function process(self: State, src: buffer, frames: number, out: buffer?): (buffer, number)
if self.done or type(src) ~= "buffer" or type(frames) ~= "number" or frames <= 0 then
return out or buffer.create(0), 0
end
local ch = self.channels
frames = min(floor(frames), buffer.len(src) // (ch * 4))
local hist = self.hist
local p = self.histFrames * ch
for i = 0, frames * ch - 1 do
hist[p + i + 1] = readf32(src, i * 4)
end
self.histFrames += frames
self.inFrames += frames
return run(self, math.huge, out)
end
local function flush(self: State, out: buffer?): (buffer, number)
if self.done then
return out or buffer.create(0), 0
end
self.done = true
local total = floor(self.inFrames * self.to / self.from + 0.5)
return run(self, total, out)
end
-- new(from, to, channels, opts?) -> Resampler | nil, message
function Resample.new(from: number, to: number, channels: number, opts: Options?): (Resampler?, string?)
if type(from) ~= "number" or type(to) ~= "number" or from ~= from or to ~= to or from <= 0 or to <= 0 or from > 2 ^ 24 or to > 2 ^ 24 then
return nil, "bad sample rates"
end
if type(channels) ~= "number" or channels < 1 or channels > 256 or channels ~= floor(channels) then
return nil, "bad channel count"
end
local q = QUALITY[(opts and opts.quality) or "medium"]
if not q then
return nil, "quality must be low, medium or high"
end
local cut = (opts and opts.cutoff) or 0.97
if type(cut) ~= "number" or not (cut >= 0.5 and cut <= 1) then
return nil, "cutoff must be 0.5 .. 1"
end
-- positions are exact integers: output j sits at input j * M / L (non-integer rates: to 1 / 1000 Hz)
local fi, ti = from, to
if from ~= floor(from) or to ~= floor(to) then
fi, ti = floor(from * 1000 + 0.5), floor(to * 1000 + 0.5)
end
local g = gcd(fi, ti)
local L, M = ti // g, fi // g
local exact = L <= MAX_EXACT
local phases = if exact then L else INTERP_PHASES
local st: State = {
from = from,
to = to,
channels = channels,
-- the same rate: a pass-through (tap 0 is the input frame itself)
f = if L == 1 and M == 1 then { taps = 2, half = 1, phases = 1, exact = true, h = { 1, 0 } } else makeFilter(to / from, phases, exact, q[1], q[2], cut),
step = M,
L = L,
hist = {},
histFrames = 0,
base = 0,
inFrames = 0,
outPos = 0,
done = false,
process = process,
flush = flush,
}
return st :: any, nil
end
-- buffer(src, frames, channels, from, to, opts?) -> interleaved f32 buffer, frames | nil, message
function Resample.buffer(src: buffer, frames: number, channels: number, from: number, to: number, opts: Options?): (buffer?, number | string)
local rs, err = Resample.new(from, to, channels, opts)
if not rs then
return nil, err :: string
end
if type(src) ~= "buffer" or type(frames) ~= "number" or frames < 0 or buffer.len(src) < frames * channels * 4 then
return nil, "the buffer is shorter than frames * channels * 4"
end
local total = floor(frames * to / from + 0.5)
local out = buffer.create(total * channels * 4)
local got = 0
local chunk = 65536
local tmp: buffer? = nil
local pos = 0
while pos < frames do
local n = min(chunk, frames - pos)
local part = buffer.create(n * channels * 4)
buffer.copy(part, 0, src, pos * channels * 4, n * channels * 4)
local b, m = rs:process(part, n, tmp)
tmp = b
if m > 0 then
buffer.copy(out, got * channels * 4, b, 0, m * channels * 4)
got += m
end
pos += n
end
local b, m = rs:flush(tmp)
if m > 0 then
buffer.copy(out, got * channels * 4, b, 0, m * channels * 4)
got += m
end
return out, got
end
-- source(src, to, opts?) -> a pull source ({ sampleRate, channels, frames, tags, read, err }, the codecs/Pcm Source
-- shape) reading src (any such source: Pcm.source(audioOrDecoder)) at the rate `to` | nil, message
function Resample.source(src: any, to: number, opts: Options?): (any, string?)
if type(src) ~= "table" or type(src.read) ~= "function" then
return nil, "needs a source"
end
local rs, err = Resample.new(src.sampleRate, to, src.channels, opts)
if not rs then
return nil, err
end
local ch = src.channels
local pending = buffer.create(0) -- produced but not yet returned
local pendingFrames, pendingPos = 0, 0
local ended = false
local out = {
sampleRate = to,
channels = ch,
frames = if src.frames > 0 then floor(src.frames * to / src.sampleRate + 0.5) else 0,
tags = src.tags,
err = nil :: any,
}
local inTmp: buffer? = nil
function out.read(self: any, n: number, dst: buffer?): (buffer, number)
n = floor(n)
while pendingFrames - pendingPos <= 0 and not ended do
local b, m = src:read(math.max(1024, floor(n * src.sampleRate / to) + 64), inTmp)
inTmp = b
local r: buffer, k: number
if m <= 0 then
ended = true
self.err = src.err
r, k = rs:flush()
else
r, k = rs:process(b, m)
end
if k > 0 then
pending, pendingFrames, pendingPos = r, k, 0
end
end
local k = min(n, pendingFrames - pendingPos)
if k <= 0 then
return dst or buffer.create(0), 0
end
local bytes = k * ch * 4
local b = if dst and buffer.len(dst) >= bytes then dst else buffer.create(bytes)
buffer.copy(b, 0, pending, pendingPos * ch * 4, bytes)
pendingPos += k
return b, k
end
return out, nil
end
return Resample
+62
View File
@@ -0,0 +1,62 @@
--!strict
-- codecs/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags.
-- Tag keys are lower case everywhere in formats-luau (the same names ID3 / MP4 / RIFF INFO map to): title, artist,
-- album, albumartist, date, genre, track, tracktotal, disc, disctotal, comment, composer, ...; TRACKNUMBER becomes
-- track, DISCNUMBER disc, DESCRIPTION comment, other fields their lower-cased name. Repeated fields are joined with
-- "; " in tags; the raw fields stay available (decoders put them in meta.source.comments). Shared so the three
-- formats read and write tags the same way. Never throws.
--
-- local tags, raw = VorbisComment.tags({ "TITLE=x", "TRACKNUMBER=3" }) -- { title = "x", track = "3" }, raw list
-- local fields = VorbisComment.fields(tags) -- sorted { "TITLE=x", "TRACKNUMBER=3" }
local VorbisComment = {}
export type Field = { key: string, value: string } -- key as written (upper-cased), value
local TO_TAG: { [string]: string } = { tracknumber = "track", discnumber = "disc", description = "comment" }
local TO_FIELD: { [string]: string } = { track = "TRACKNUMBER", disc = "DISCNUMBER" }
-- tagKey(fieldName) -> the Types.Tags key
function VorbisComment.tagKey(name: string): string
local k = string.lower(name)
return TO_TAG[k] or k
end
-- fieldName(tagKey) -> the Vorbis comment field name
function VorbisComment.fieldName(key: string): string
return TO_FIELD[key] or string.upper(key)
end
-- tags(list of "KEY=value") -> Types.Tags, { Field } (entries without "=" are skipped)
function VorbisComment.tags(comments: { string }): ({ [string]: string }, { Field })
local tags: { [string]: string } = {}
local raw: { Field } = {}
for _, s in comments do
local eq = string.find(s, "=", 1, true)
if eq then
local name, v = string.sub(s, 1, eq - 1), string.sub(s, eq + 1)
table.insert(raw, { key = string.upper(name), value = v })
local k = VorbisComment.tagKey(name)
local old = tags[k]
tags[k] = if old then old .. "; " .. v else v
end
end
return tags, raw
end
-- fields(tags) -> "KEY=value" strings in key order (string keys and values only)
function VorbisComment.fields(tags: { [any]: any }): { string }
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)
local out = table.create(#keys)
for i, k in keys do
out[i] = VorbisComment.fieldName(k) .. "=" .. tags[k]
end
return out
end
return VorbisComment