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

+33 -8
View File
@@ -6,7 +6,8 @@
-- past garbage, mono / stereo switches (upmixed), ID3v2.2 / 2.3 / 2.4 and ID3v1 / 1.1 tags (APEv2 skipped).
-- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Encode (ws-audio, audio/mp3/Encode3 + Encode2): layer III
-- (shine-style CBR, MPEG-1 / 2 / 2.5) and layer II (MPEG-1 / 2), mono / stereo / joint stereo, an ID3v2.4 tag from
-- the tags. Not supported: MPEG-2 multichannel extension, CRC checks, VBR / Xing output, encoder resampling.
-- the tags; input at rates the layer cannot hold is resampled (codecs/Resample). Not supported: MPEG-2 multichannel
-- extension, CRC checks, VBR / Xing output.
--
-- local dec = Mp3.open(Bytes.reader(buf)) -- the streaming Types.Decoder (+ layer, version, vbr, delay,
-- local pcm, n = dec:read(4096) -- padding, mpegFrames, id3, :seekFrame(i), :readAll())
@@ -23,6 +24,7 @@ local Stream = require("@formats/audio/mp3/Stream")
local Encode3 = require("@formats/audio/mp3/Encode3")
local Encode2 = require("@formats/audio/mp3/Encode2")
local Pcm = require("@formats/codecs/Pcm")
local Resample = require("@formats/codecs/Resample")
-- ------------------------------------------------------------------------------------------------ contract
local Mp3 = {
@@ -30,7 +32,7 @@ local Mp3 = {
category = "audio",
extensions = { "mp3", "mp2", "mp1", "mpga" },
mime = { "audio/mpeg", "audio/mp3", "audio/mpa" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm", "codecs/Resample" },
caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 },
}
@@ -45,6 +47,9 @@ export type EncodeOptions = {
mode: ("stereo" | "joint" | "mono")?, -- default "joint" (mid / side) for stereo layer III, "stereo" for layer II,
-- "mono" for mono input; layer II has no joint stereo (intensity) and writes "joint" as "stereo"
id3: boolean?, -- write an ID3v2.4 tag from the tags (default true when there are tags)
sampleRate: number?, -- output rate (one the layer holds); default the input rate if possible, else the nearest
-- higher one (input at other rates is resampled through codecs/Resample)
resampleQuality: ("low" | "medium" | "high")?, -- codecs/Resample quality (default "medium")
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -101,7 +106,7 @@ local ID3_FRAMES = {
{ "title", "TIT2" },
{ "artist", "TPE1" },
{ "album", "TALB" },
{ "albumArtist", "TPE2" },
{ "albumartist", "TPE2" },
{ "year", "TDRC" },
{ "date", "TDRC" },
{ "track", "TRCK" },
@@ -170,10 +175,30 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
return nil, Err.new(Err.ARG, "layer must be 2 or 3")
end
local Enc = if layer == 3 then Encode3 else Encode2
local info = Enc.RATES[src.sampleRate]
if not info then
return nil, Err.new(Err.ARG, string.format("layer %d cannot hold %s Hz (no resampling)", layer, tostring(src.sampleRate)))
-- the output rate: opts.sampleRate, else the input's when the layer has it, else the nearest rate above it (else
-- the highest); other input rates go through codecs/Resample
local rate = o.sampleRate or src.sampleRate
if o.sampleRate and not Enc.RATES[o.sampleRate] then
return nil, Err.new(Err.ARG, string.format("layer %d cannot hold %s Hz", layer, tostring(o.sampleRate)))
end
if not Enc.RATES[rate] then
local best, top = nil, 0
for r in Enc.RATES do
top = math.max(top, r)
if r >= rate and (best == nil or r < best) then
best = r
end
end
rate = best or top
end
if rate ~= src.sampleRate then
local rs, rerr = Resample.source(src, rate, { quality = o.resampleQuality })
if not rs then
return nil, Err.new(Err.ARG, tostring(rerr))
end
src = rs
end
local info = Enc.RATES[rate]
local mpeg1 = info[1] == 3
local mode = o.mode or (if src.channels == 1 then "mono" elseif layer == 3 then "joint" else "stereo")
if mode ~= "stereo" and mode ~= "joint" and mode ~= "mono" then
@@ -187,7 +212,7 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
local bitrate = o.bitrate or (if mpeg1 then (if layer == 3 then 128 else 192) else (if layer == 3 then 64 else 96))
if not table.find(Enc.BITRATES[if mpeg1 then 1 else 2], bitrate) then
return nil, Err.new(Err.ARG, string.format("%s kbps is not a layer %d bit rate at %d Hz", tostring(bitrate), layer, src.sampleRate))
return nil, Err.new(Err.ARG, string.format("%s kbps is not a layer %d bit rate at %d Hz", tostring(bitrate), layer, rate))
end
if layer == 2 and mpeg1 then
-- the standard's allowed bit rate / mode combinations
@@ -206,7 +231,7 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ open
-- the string-valued tag fields (title, artist, album, albumArtist, year, track, disc, genre, composer, comment)
-- the string-valued tag fields (title, artist, album, albumartist, date, track, disc, genre, composer, comment)
local function stringTags(t: any): { [string]: string }
local out: { [string]: string } = {}
for k, v in t do
+1 -1
View File
@@ -7,7 +7,7 @@
--
-- Arrays are Luau tables of numbers. All normalised-band data (X, Y, the folding memory `norm` and the scratch
-- copies) lives in one table W, and the "pointers" of the C code are 0-based offsets into it.
local RD = require("@formats/audio/opus/RangeDecoder")
local RD = require("@formats/codecs/RangeCoder/Decoder")
local Mdct = require("@formats/audio/opus/Mdct")
local T = require("@formats/audio/opus/CeltTables")
+1 -1
View File
@@ -7,7 +7,7 @@
-- (celt_encoder.c, quant_bands.c, laplace.c, rate.c, bands.c, vq.c, cwrs.c; BSD: licenses/libopus-BSD.txt) that
-- mirror audio/opus/Celt's decoder step for step; the analysis is simplified. The MDCT is codecs/Mdct.
-- Never throws.
local RE = require("@formats/audio/opus/RangeEncoder")
local RE = require("@formats/codecs/RangeCoder/Encoder")
local T = require("@formats/audio/opus/CeltTables")
local Mdct = require("@formats/codecs/Mdct")
+1 -1
View File
@@ -4,7 +4,7 @@
-- audio/opus/Decoder: The Opus decoder proper (libopus src/opus_decoder.c and opus_multistream_decoder.c): per-frame mode switching
-- between SILK, hybrid and CELT, the redundant CELT frames of mode transitions, cross-fades, PLC fallbacks, the
-- multi-frame packet loop and multistream (channel mapping) decoding. Output is 48 kHz float in Luau arrays.
local RD = require("@formats/audio/opus/RangeDecoder")
local RD = require("@formats/codecs/RangeCoder/Decoder")
local Packet = require("@formats/audio/opus/Packet")
local Celt = require("@formats/audio/opus/Celt")
local Silk = require("@formats/audio/opus/Silk")
+31 -99
View File
@@ -2,10 +2,14 @@
-- 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.
-- other rates is resampled to 48 kHz (codecs/Resample); the input is a Types.Audio or a Decoder (codecs/Pcm). New in
-- formats-luau.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Ogg = require("@formats/containers/Ogg")
local Pcm = require("@formats/codecs/Pcm")
local Resample = require("@formats/codecs/Resample")
local VorbisComment = require("@formats/codecs/VorbisComment")
local CeltEncoder = require("@formats/audio/opus/CeltEncoder")
local Encode = {}
@@ -17,69 +21,20 @@ export type Options = {
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",
}
local floor = math.floor
-- 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")
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local ch = value.channels
local ch = src.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
local rate = src.sampleRate
if rate < 1000 or rate > 768000 then
return nil, Err.new(Err.ARG, "bad sample rate " .. tostring(rate))
end
@@ -87,40 +42,24 @@ function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?)
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")
-- the whole input at 48 kHz (codecs/Resample for other rates), then as floats
if rate ~= 48000 then
local rs, rerr = Resample.source(src, 48000)
if not rs then
return nil, Err.new(Err.ARG, tostring(rerr))
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")
src = rs
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)
local all, aerr = Pcm.collect(src :: Pcm.Source)
if not all then
return nil, aerr
end
local n48 = all.frames
local samples = all.samples
local pcm: { number } = table.create(n48 * ch, 0)
local readf32 = buffer.readf32
for i = 1, n48 * ch do
pcm[i] = readf32(samples, (i - 1) * 4)
end
local FRAME = CeltEncoder.FRAME
local preSkip = CeltEncoder.DELAY
@@ -144,22 +83,15 @@ function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?)
head:u8(0)
s:packet(head:finish(), 0, { flush = true })
-- OpusTags
local tags = o.tags or value.tags or {}
local tags = o.tags or src.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]
local fields = VorbisComment.fields(tags)
tw:u32le(#fields)
for _, field in fields do
tw:u32le(#field)
tw:string(field)
end
+4
View File
@@ -4,6 +4,10 @@
-- audio/opus/Mdct: CELT inverse MDCT (libopus celt/mdct.c clt_mdct_backward) over a mixed-radix complex FFT (a port of the
-- kiss_fft stages used by libopus: radix 5, 3, 4 and 2). The 48 kHz mode uses N = 1920 >> shift for
-- shift = 0..3 (FFT sizes 480, 240, 120, 60). Arrays are Luau tables of numbers, 1-based.
-- Why not codecs/Mdct (measured by the cleanup pass): the shared transform computes the full N-sample IMDCT through a
-- DCT-IV, of which CELT keeps the middle N / 2, so routing the decoder through it made CELT decoding 2-3x slower
-- (luau: 25 -> 54-76 ms for 3 s of 32 kbps stereo) and changed the output bits (same SNR against opusdec). This
-- fused libopus port (pre-rotation, a kiss_fft with fixed factors, post-rotation, TDAC) stays private.
local Mdct = {}
local sin, cos, pi = math.sin, math.cos, math.pi
+1 -1
View File
@@ -14,7 +14,7 @@
--
-- Fixed-point emulation: all values are Luau numbers holding C int32 / int16 values. Products of two int32 values
-- (64-bit in C) are split so that every intermediate stays below 2^53 and therefore exact.
local RD = require("@formats/audio/opus/RangeDecoder")
local RD = require("@formats/codecs/RangeCoder/Decoder")
local T = require("@formats/audio/opus/SilkTables")
local icdf = RD.icdf
+33 -31
View File
@@ -24,7 +24,9 @@ local Types = require("@formats/Types")
local Ogg = require("@formats/containers/Ogg")
local Decoder = require("@formats/audio/opus/Decoder")
local Packet = require("@formats/audio/opus/Packet")
local RangeDecoder = require("@formats/audio/opus/RangeDecoder")
local VorbisComment = require("@formats/codecs/VorbisComment")
local Pcm = require("@formats/codecs/Pcm")
local RangeDecoder = require("@formats/codecs/RangeCoder/Decoder")
local Celt = require("@formats/audio/opus/Celt")
local Silk = require("@formats/audio/opus/Silk")
local Encode = require("@formats/audio/opus/Encode")
@@ -35,7 +37,7 @@ local Opus = {
category = "audio",
extensions = { "opus" },
mime = { "audio/opus", "audio/ogg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/RangeCoder/Decoder", "codecs/RangeCoder/Encoder", "codecs/Pcm", "codecs/Resample", "codecs/VorbisComment" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" } },
}
@@ -124,46 +126,40 @@ local function parseHead(b: buffer, off: number, size: number): (Head?, string?)
return head, nil
end
-- OpusTags (RFC 7845 section 5.2): vendor string and a table of lower-cased field names to values (repeated
-- fields joined with "; ").
local function parseTags(b: buffer, off: number, size: number): (string, { [string]: string })
local tags = {}
-- OpusTags (RFC 7845 section 5.2) -> vendor, tags (codecs/VorbisComment: lower-case keys, repeated fields joined
-- with "; "), the raw fields
local function parseTags(b: buffer, off: number, size: number): (string, { [string]: string }, { VorbisComment.Field })
if size < 16 or buffer.readstring(b, off, 8) ~= "OpusTags" then
return "", tags
return "", {}, {}
end
local p = off + 8
local e = off + size
local vlen = buffer.readu32(b, p)
p += 4
if p + vlen > e then
return "", tags
return "", {}, {}
end
local vendor = buffer.readstring(b, p, vlen)
p += vlen
if p + 4 > e then
return vendor, tags
end
local n = buffer.readu32(b, p)
p += 4
for _ = 1, n do
if p + 4 > e then
break
end
local l = buffer.readu32(b, p)
local list = {}
if p + 4 <= e then
local n = buffer.readu32(b, p)
p += 4
if p + l > e then
break
end
local s = buffer.readstring(b, p, l)
p += l
local eq = string.find(s, "=", 1, true)
if eq then
local k = string.lower(string.sub(s, 1, eq - 1))
local v = string.sub(s, eq + 1)
tags[k] = if tags[k] then tags[k] .. "; " .. v else v
for _ = 1, n do
if p + 4 > e then
break
end
local l = buffer.readu32(b, p)
p += 4
if p + l > e then
break
end
table.insert(list, buffer.readstring(b, p, l))
p += l
end
end
return vendor, tags
local tags, raw = VorbisComment.tags(list)
return vendor, tags, raw
end
Opus.Decoder = Decoder
@@ -213,7 +209,7 @@ function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?)
a.frames = total
end
a.tags = dec.tags
a.meta.source = { format = "opus", channels = dec.sourceChannels, preSkip = dec.preSkip, vendor = dec.vendor, mappingFamily = dec.head.mappingFamily, inputSampleRate = dec.head.inputSampleRate }
a.meta.source = { format = "opus", channels = dec.sourceChannels, preSkip = dec.preSkip, vendor = dec.vendor, comments = dec.comments, mappingFamily = dec.head.mappingFamily, inputSampleRate = dec.head.inputSampleRate }
return a, nil
end
@@ -288,6 +284,9 @@ function Stream.read(self: any, maxFrames: number, into: buffer?): (buffer, numb
Decoder.writeDownmix(self.pend, self.pendPos * self.sourceChannels, n, self.sourceChannels, self.downmix, gain, out, got * 8)
else
Decoder.writeF32(self.pend, self.pendPos * ch, n * ch, gain, out, got * ch * 4)
if self.order then
Pcm.reorder(out, got * ch * 4, n, ch, self.order)
end
end
self.pendPos += n
got += n
@@ -356,7 +355,7 @@ function Opus.open(r: any, opts: OpenOptions?): (any, Err.Err?)
if tp == nil then
return nil, Err.new(Err.TRUNCATED, "missing OpusTags")
end
local vendor, tags = parseTags(tp.data, tp.offset, tp.size)
local vendor, tags, rawTags = parseTags(tp.data, tp.offset, tp.size)
-- granule of the first audio sample: first page granule minus the packets that end on it
local startGranule = 0
local sum = 0
@@ -391,6 +390,9 @@ function Opus.open(r: any, opts: OpenOptions?): (any, Err.Err?)
head = head,
vendor = vendor,
tags = tags,
comments = rawTags,
-- mapping family 1 is in Vorbis channel order; the output is WAVE order (codecs/Pcm)
order = if not downmix and head.mappingFamily == 1 and head.channels > 2 then Pcm.WAVE_FROM_VORBIS[head.channels] else nil,
sampleRate = SAMPLE_RATE,
channels = if downmix then 2 else head.channels,
sourceChannels = head.channels,
+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
+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()