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

+40 -2
View File
@@ -121,6 +121,44 @@ do
t:check(empty and buffer.len(empty) > 0, "empty input: one flush frame")
end
-- other input rates are resampled (codecs/Resample) to the next rate up: 44 kHz -> 44.1 kHz, 46 kHz -> 48 kHz,
-- layer II 8 kHz -> 16 kHz, opts.sampleRate
do
local function tone(rate: number, f: number): any
local n = rate
local a = Types.Audio.new(rate, 1, n)
for i = 0, n - 1 do
buffer.writef32(a.samples, i * 4, 0.5 * math.sin(2 * math.pi * f * i / rate))
end
return a
end
-- the share of the decoded energy at f (a DFT bin over the middle half)
local function purity(d: any, f: number): number
local pcm, n = d:read(d.frames)
local re, im, e = 0, 0, 0
local lo, hi = n // 4, 3 * n // 4
for i = lo, hi - 1 do
local x = buffer.readf32(pcm, i * d.channels * 4)
re += x * math.cos(2 * math.pi * f * i / d.sampleRate)
im += x * math.sin(2 * math.pi * f * i / d.sampleRate)
e += x * x
end
return 2 * (re * re + im * im) / (hi - lo) / math.max(e, 1e-30)
end
for _, c in { { 44000, nil, nil, 44100 }, { 46000, nil, nil, 48000 }, { 8000, 2, nil, 16000 }, { 44100, 3, 22050, 22050 }, { 11000, 3, nil, 11025 } } do
local f, err = Mp3.encode(tone(c[1], 600), { layer = c[2], sampleRate = c[3], bitrate = if c[4] < 32000 then 64 else 128 })
t:check(f, c[1] .. " Hz input: " .. tostring(err))
if f then
local d = Mp3.open(Bytes.reader(f)) :: any
t:eq(d.sampleRate, c[4], c[1] .. " Hz input: written at " .. c[4])
-- (no LAME gapless header: the encoder delay and the last frame's padding stay)
t:check(d.frames >= c[4] and d.frames <= c[4] + 3 * 1152, c[1] .. " Hz input: length " .. d.frames)
local p = purity(d, 600)
t:check(p > 0.98, string.format("%d Hz input: tone purity %.4f", c[1], p))
end
end
end
-- errors
do
local function code(v: any, o: any): string?
@@ -132,8 +170,8 @@ do
t:eq(code(a, { layer = 1 }), Err.ARG, "layer I")
t:eq(code(a, { bitrate = 100 }), Err.ARG, "100 kbps")
t:eq(code(a, { mode = "dual" }), Err.ARG, "dual mode")
t:eq(code(Types.Audio.new(44000, 2, 10), nil), Err.ARG, "44 kHz")
t:eq(code(Types.Audio.new(8000, 2, 10), { layer = 2 }), Err.ARG, "layer II at 8 kHz")
t:eq(code(a, { sampleRate = 44000 }), Err.ARG, "opts.sampleRate 44 kHz")
t:eq(code(a, { layer = 2, sampleRate = 8000 }), Err.ARG, "layer II at 8 kHz")
t:eq(code(Types.Audio.new(44100, 3, 10), nil), Err.ARG, "3 channels")
t:eq(code(a, { layer = 2, bitrate = 32 }), Err.ARG, "layer II stereo at 32 kbps")
t:eq(code(Types.Audio.new(44100, 1, 10), { layer = 2, bitrate = 320 }), Err.ARG, "layer II mono at 320 kbps")
+11 -2
View File
@@ -9,10 +9,11 @@ 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/audio/opus/RangeDecoder")
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")
@@ -48,6 +49,14 @@ for _, f in
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)
@@ -183,7 +192,7 @@ do
for i = 0, n - 1 do
local l, r = 0, 0
for c = 0, 5 do
local v = buffer.readf32(fx.ref, (i * 6 + c) * 4)
local v = buffer.readf32(fx.vorbisRef, (i * 6 + c) * 4)
l += v * m[c * 2 + 1]
r += v * m[c * 2 + 2]
end
+133
View File
@@ -0,0 +1,133 @@
-- codecs/Resample tests: sines through common rate pairs (44100 <-> 48000, 8000 -> 48000, 48000 -> 22050, an inexact
-- ratio) against the analytic signal, alias rejection when downsampling, output lengths, streaming in odd chunks =
-- the whole-buffer result, multichannel, a Pcm source wrapper, bad arguments, and a no-throw pass over garbage.
local T = require("@tests/T")
local Resample = require("@formats/codecs/Resample")
local Pcm = require("@formats/codecs/Pcm")
local Types = require("@formats/Types")
local t = T.suite("resample")
local function sine(frames: number, ch: number, rate: number, freqs: { number }): buffer
local b = buffer.create(frames * ch * 4)
for i = 0, frames - 1 do
for c = 0, ch - 1 do
local f = freqs[c + 1] or freqs[1]
buffer.writef32(b, (i * ch + c) * 4, 0.5 * math.sin(2 * math.pi * f * i / rate))
end
end
return b
end
-- snr(out, frames, ch, rate, freqs, skip) -> dB of the analytic sine against the error, away from the edges
local function snr(b: buffer, frames: number, ch: number, rate: number, freqs: { number }, skip: number): number
local sig, err = 0, 0
for i = skip, frames - 1 - skip do
for c = 0, ch - 1 do
local f = freqs[c + 1] or freqs[1]
local want = 0.5 * math.sin(2 * math.pi * f * i / rate)
local got = buffer.readf32(b, (i * ch + c) * 4)
sig += want * want
err += (got - want) ^ 2
end
end
return 10 * math.log10(sig / math.max(err, 1e-30))
end
local function rms(b: buffer, frames: number, skip: number): number
local s = 0
for i = skip, frames - 1 - skip do
s += buffer.readf32(b, i * 4) ^ 2
end
return math.sqrt(s / math.max(1, frames - 2 * skip))
end
-- 1. accuracy on in-band sines
for _, c in { { 44100, 48000, 1000, "medium", 80 }, { 48000, 44100, 3000, "medium", 80 }, { 8000, 48000, 440, "medium", 80 }, { 48000, 22050, 5000, "high", 90 }, { 44100, 48000, 1000, "low", 55 }, { 44100, 47999, 1000, "medium", 75 } } do
local from, to, f, q, want = c[1], c[2], c[3], c[4], c[5]
local n = from // 4
local out, frames = Resample.buffer(sine(n, 1, from, { f }), n, 1, from, to, { quality = q })
t:check(out ~= nil, "resample " .. from .. " -> " .. to)
if out then
local fr = frames :: number
t:eq(fr, math.floor(n * to / from + 0.5), from .. " -> " .. to .. ": length")
local db = snr(out, fr, 1, to, { f }, to // 50)
t:note("%d -> %d (%s), %d Hz: %.1f dB", from, to, q, f, db)
t:check(db > want, string.format("%d -> %d %s: %.1f dB > %d", from, to, q, db, want))
end
end
-- 2. a tone above the new Nyquist is removed when downsampling (48 kHz -> 16 kHz, 10 kHz tone)
do
local n = 12000
local out, frames = Resample.buffer(sine(n, 1, 48000, { 10000 }), n, 1, 48000, 16000)
local level = rms(out :: buffer, frames :: number, 200) / (0.5 / math.sqrt(2))
t:check(level < 1e-3, string.format("alias rejection: %.2e", level))
end
-- 3. streaming in odd chunk sizes gives the whole-buffer result; stereo channels stay apart
do
local n, ch = 10007, 2
local src = sine(n, ch, 44100, { 700, 1900 })
local whole, wf = Resample.buffer(src, n, ch, 44100, 48000)
local rs = Resample.new(44100, 48000, ch) :: Resample.Resampler
local got = buffer.create((wf :: number) * ch * 4)
local gf = 0
local pos = 0
local rand = T.rng(7)
while pos < n do
local k = math.min(n - pos, 1 + rand(3000))
local part = buffer.create(k * ch * 4)
buffer.copy(part, 0, src, pos * ch * 4, k * ch * 4)
local b, m = rs:process(part, k)
buffer.copy(got, gf * ch * 4, b, 0, m * ch * 4)
gf += m
pos += k
end
local b, m = rs:flush()
buffer.copy(got, gf * ch * 4, b, 0, m * ch * 4)
gf += m
t:eq(gf, wf, "streamed length")
t:check(buffer.tostring(got) == buffer.tostring(whole :: buffer), "streamed = whole")
t:check(snr(got, gf, ch, 48000, { 700, 1900 }, 500) > 80, "stereo accuracy")
end
-- 4. a codecs/Pcm source at a new rate
do
local a = Types.Audio.new(22050, 1, 5000)
a.samples = sine(5000, 1, 22050, { 500 })
local src = Resample.source(Pcm.source(a), 32000)
t:check(src and src.frames == math.floor(5000 * 32000 / 22050 + 0.5), "source frames")
local col = Pcm.collect(src)
t:check(col and col.sampleRate == 32000 and col.frames == src.frames, "source collects every frame")
t:check(col and snr(col.samples, col.frames, 1, 32000, { 500 }, 300) > 80, "source accuracy")
end
-- 5. identity, empty input, bad arguments
do
local src = sine(1000, 1, 48000, { 1000 })
local out = Resample.buffer(src, 1000, 1, 48000, 48000)
t:check(out and snr(out, 1000, 1, 48000, { 1000 }, 50) > 100, "identity")
local e, ef = Resample.buffer(buffer.create(0), 0, 2, 44100, 48000)
t:check(e and ef == 0, "empty input")
t:check(Resample.new(0, 48000, 1) == nil, "zero rate")
t:check(Resample.new(44100, 48000, 0) == nil, "zero channels")
t:check(Resample.new(44100, 48000, 1, { quality = "insane" :: any }) == nil, "bad quality")
t:check(Resample.buffer(buffer.create(4), 10, 1, 44100, 48000) == nil, "short buffer")
end
-- 6. no throw on garbage (NaN / Inf samples, odd lengths, chunk sizes)
local samples = {}
for i = 1, 4 do
table.insert(samples, buffer.tostring(sine(100 * i, 1, 8000, { 300 })))
end
t:fuzz("resample", function(b: buffer)
local rs = Resample.new(11025, 44100, 2, { quality = "low" })
if not rs then
return nil
end
local _, n = rs:process(b, buffer.len(b) // 8)
local _, m = rs:flush()
return n + m
end, samples)
t:done()