audio: codecs/Mdct (FFT, DCT-IV, MDCT/IMDCT, windows) + test; codecs/Pcm (Audio|Decoder pull source for encoders, int<->float); tools/fixtures/_audio.py (signals, ffmpeg decode, SNR, run Luau in the fixture step)
This commit is contained in:
1 parent
ccb06775c5
commit
d77d2370f5
5 files changed
+766
No files matched your search
@@ -10,3 +10,5 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
Codecs (layer 1, shared by formats; not loadable on their own):
|
||||
|
||||
- codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
|
||||
- codecs/Mdct: the shared audio transforms: radix-2 complex FFT, DCT-IV and MDCT / IMDCT (power-of-two sizes).
|
||||
- codecs/Pcm: PCM plumbing for audio encoders: one pull interface over an Audio or a Decoder, int <-> float samples.
|
||||
@@ -0,0 +1,288 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/Mdct: the shared audio transforms: radix-2 complex FFT, DCT-IV and MDCT / IMDCT (power-of-two sizes).
|
||||
-- The MDCT (any power of two N >= 16) runs as a DCT-IV on an N/4-point complex FFT (pre-twiddle, FFT, post-twiddle).
|
||||
-- Used by the Vorbis decoder and encoder, and open to AAC / Opus (CELT). New code (the textbook algorithm; no port).
|
||||
--
|
||||
-- local Mdct = require("@formats/codecs/Mdct")
|
||||
-- local m = Mdct.new(2048) -- N = 2048: 2048 time samples <-> 1024 coefficients (cached per N)
|
||||
-- m:forward(x, xo, X, Xo, scale?) -- X[Xo+1 .. Xo+N/2] = scale * sum_n x[xo+1+n] cos(pi/M (n + 1/2 + M/2)(k + 1/2))
|
||||
-- m:inverse(X, Xo, y, yo) -- y[yo+1 .. yo+N] = sum_k X[Xo+1+k] cos(pi/M (n + 1/2 + M/2)(k + 1/2))
|
||||
-- local f = Mdct.fft(256) -- complex FFT plan (cached per n)
|
||||
-- f:forward(re, im) -- in place, 1-based arrays of n numbers: X[k] = sum x[j] e^(-2 pi i jk/n)
|
||||
-- f:inverse(re, im) -- in place, unscaled (e^(+2 pi i jk/n))
|
||||
-- Mdct.dct4(u, uo, X, Xo, M, scale?) -- DCT-IV, M a power of two >= 4: X[k] = sum u[n] cos(pi/M (n+1/2)(k+1/2))
|
||||
--
|
||||
-- M = N/2. Both MDCT directions are unscaled (the Vorbis convention): windowing with a Princen-Bradley window (sine,
|
||||
-- Vorbis) before forward and after inverse, then overlap-adding, gives x * N/4, so an encoder for an unscaled decoder
|
||||
-- passes scale = 4/N (as libvorbis does; tests/codecs/mdct.luau checks this). Arrays are plain 1-based Luau arrays
|
||||
-- with explicit 0-based offsets; work arrays live in the plan (calls never yield, so sharing a plan is safe).
|
||||
-- Never throws: a bad size returns nil.
|
||||
local Mdct = {}
|
||||
|
||||
local cos, sin, pi = math.cos, math.sin, math.pi
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ FFT
|
||||
export type Fft = {
|
||||
n: number,
|
||||
rev: { number }, -- bit reversal permutation (1-based targets)
|
||||
cr: { number }, -- twiddles cos(2 pi k / n), k = 0 .. n/2 - 1
|
||||
ci: { number }, -- sin(2 pi k / n)
|
||||
forward: (self: Fft, re: { number }, im: { number }) -> (),
|
||||
inverse: (self: Fft, re: { number }, im: { number }) -> (),
|
||||
}
|
||||
|
||||
local function isPow2(n: number): boolean
|
||||
if n < 1 or n ~= math.floor(n) then
|
||||
return false
|
||||
end
|
||||
while n > 1 do
|
||||
if n % 2 ~= 0 then
|
||||
return false
|
||||
end
|
||||
n //= 2
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- the radix-2 decimation-in-time butterflies; sign = -1 forward, +1 inverse
|
||||
local function transform(p: Fft, re: { number }, im: { number }, sign: number)
|
||||
local n = p.n
|
||||
local rev, cr, ci = p.rev, p.cr, p.ci
|
||||
for i = 1, n do
|
||||
local j = rev[i]
|
||||
if j > i then
|
||||
re[i], re[j] = re[j], re[i]
|
||||
im[i], im[j] = im[j], im[i]
|
||||
end
|
||||
end
|
||||
-- size-2 butterflies first (twiddle 1)
|
||||
for i = 1, n - 1, 2 do
|
||||
local ar, ai, br, bi = re[i], im[i], re[i + 1], im[i + 1]
|
||||
re[i], im[i] = ar + br, ai + bi
|
||||
re[i + 1], im[i + 1] = ar - br, ai - bi
|
||||
end
|
||||
local half = 2
|
||||
while half < n do
|
||||
local size = half * 2
|
||||
local step = n // size
|
||||
for start = 1, n, size do
|
||||
local t = 1
|
||||
for k = start, start + half - 1 do
|
||||
local wr, wi = cr[t], sign * ci[t]
|
||||
local m = k + half
|
||||
local xr, xi = re[m], im[m]
|
||||
-- (xr + i xi) * (wr + i wi)
|
||||
local tr = xr * wr - xi * wi
|
||||
local ti = xr * wi + xi * wr
|
||||
local ar, ai = re[k], im[k]
|
||||
re[k], im[k] = ar + tr, ai + ti
|
||||
re[m], im[m] = ar - tr, ai - ti
|
||||
t += step
|
||||
end
|
||||
end
|
||||
half = size
|
||||
end
|
||||
end
|
||||
|
||||
local function fftForward(self: Fft, re: { number }, im: { number })
|
||||
transform(self, re, im, -1)
|
||||
end
|
||||
local function fftInverse(self: Fft, re: { number }, im: { number })
|
||||
transform(self, re, im, 1)
|
||||
end
|
||||
|
||||
local fftCache: { [number]: Fft } = {}
|
||||
|
||||
-- fft(n) -> Fft plan for a power-of-two n >= 2 | nil
|
||||
function Mdct.fft(n: number): Fft?
|
||||
local c = fftCache[n]
|
||||
if c then
|
||||
return c
|
||||
end
|
||||
if not isPow2(n) or n < 2 or n > 2 ^ 20 then
|
||||
return nil
|
||||
end
|
||||
local bits = 0
|
||||
while 2 ^ bits < n do
|
||||
bits += 1
|
||||
end
|
||||
local rev = table.create(n, 0)
|
||||
for i = 0, n - 1 do
|
||||
local r, v = 0, i
|
||||
for _ = 1, bits do
|
||||
r = r * 2 + v % 2
|
||||
v //= 2
|
||||
end
|
||||
rev[i + 1] = r + 1
|
||||
end
|
||||
local cr, ci = table.create(n // 2, 0), table.create(n // 2, 0)
|
||||
for k = 0, n // 2 - 1 do
|
||||
cr[k + 1] = cos(2 * pi * k / n)
|
||||
ci[k + 1] = sin(2 * pi * k / n)
|
||||
end
|
||||
local p: Fft = { n = n, rev = rev, cr = cr, ci = ci, forward = fftForward, inverse = fftInverse }
|
||||
fftCache[n] = p
|
||||
return p
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ DCT-IV
|
||||
type Dct4 = {
|
||||
m: number,
|
||||
fft: Fft,
|
||||
pr: { number }, -- pre-twiddle exp(-i pi (n + 1/4) / M), n = 0 .. M/2 - 1
|
||||
pi_: { number },
|
||||
qr: { number }, -- post-twiddle exp(-i pi k / M)
|
||||
qi: { number },
|
||||
re: { number }, -- work
|
||||
im: { number },
|
||||
}
|
||||
local dctCache: { [number]: Dct4 } = {}
|
||||
|
||||
local function dctPlan(m: number): Dct4?
|
||||
local c = dctCache[m]
|
||||
if c then
|
||||
return c
|
||||
end
|
||||
if not isPow2(m) or m < 4 then
|
||||
return nil
|
||||
end
|
||||
local h = m // 2
|
||||
local f = Mdct.fft(h)
|
||||
if not f then
|
||||
return nil
|
||||
end
|
||||
local pr, pim, qr, qi = table.create(h, 0), table.create(h, 0), table.create(h, 0), table.create(h, 0)
|
||||
for n = 0, h - 1 do
|
||||
local a = -pi * (n + 0.25) / m
|
||||
pr[n + 1], pim[n + 1] = cos(a), sin(a)
|
||||
local b = -pi * n / m
|
||||
qr[n + 1], qi[n + 1] = cos(b), sin(b)
|
||||
end
|
||||
local p: Dct4 = { m = m, fft = f, pr = pr, pi_ = pim, qr = qr, qi = qi, re = table.create(h, 0), im = table.create(h, 0) }
|
||||
dctCache[m] = p
|
||||
return p
|
||||
end
|
||||
|
||||
-- X[Xo+1+k] = scale * sum_n u[uo+1+n] cos(pi/M (n+1/2)(k+1/2)); u and X may be the same array only at distinct ranges
|
||||
local function dct4(p: Dct4, u: { number }, uo: number, X: { number }, Xo: number, scale: number)
|
||||
local m = p.m
|
||||
local h = m // 2
|
||||
local re, im, pr, pim, qr, qi = p.re, p.im, p.pr, p.pi_, p.qr, p.qi
|
||||
for n = 0, h - 1 do
|
||||
local a, b = u[uo + 2 * n + 1], u[uo + m - 2 * n]
|
||||
local wr, wi = pr[n + 1], pim[n + 1]
|
||||
re[n + 1] = a * wr - b * wi
|
||||
im[n + 1] = a * wi + b * wr
|
||||
end
|
||||
p.fft:forward(re, im)
|
||||
for k = 0, h - 1 do
|
||||
local vr, vi = re[k + 1], im[k + 1]
|
||||
local wr, wi = qr[k + 1], qi[k + 1]
|
||||
X[Xo + 2 * k + 1] = (vr * wr - vi * wi) * scale
|
||||
X[Xo + m - 2 * k] = -(vr * wi + vi * wr) * scale
|
||||
end
|
||||
end
|
||||
|
||||
-- dct4(u, uo, X, Xo, M, scale?): a DCT-IV of length M (power of two >= 4). Returns false for a bad M.
|
||||
function Mdct.dct4(u: { number }, uo: number, X: { number }, Xo: number, m: number, scale: number?): boolean
|
||||
local p = dctPlan(m)
|
||||
if not p then
|
||||
return false
|
||||
end
|
||||
dct4(p, u, uo, X, Xo, scale or 1)
|
||||
return true
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ MDCT
|
||||
export type Plan = {
|
||||
n: number,
|
||||
forward: (self: Plan, x: { number }, xo: number, X: { number }, Xo: number, scale: number?) -> (),
|
||||
inverse: (self: Plan, X: { number }, Xo: number, y: { number }, yo: number) -> (),
|
||||
dct: Dct4,
|
||||
fold: { number }, -- work, M
|
||||
}
|
||||
|
||||
-- forward: fold N inputs into M (the transpose of the inverse unfolding below), then the DCT-IV
|
||||
local function forward(self: Plan, x: { number }, xo: number, X: { number }, Xo: number, scale: number?)
|
||||
local n = self.n
|
||||
local m = n // 2
|
||||
local q = m // 2
|
||||
local f = self.fold
|
||||
-- m' = n' + M/2 for input index n'
|
||||
-- n' < M/2 : f[n' + M/2] += x
|
||||
-- M/2 <= n' < 3M/2 : f[3M/2 - 1 - n'] -= x
|
||||
-- n' >= 3M/2 : f[n' - 3M/2] -= x
|
||||
for i = 0, q - 1 do
|
||||
-- f[i] (i < M/2) gets -x[3M/2 + i] (third range) and -x[3M/2 - 1 - i] (second range)
|
||||
f[i + 1] = -x[xo + 3 * q + i + 1] - x[xo + 3 * q - i]
|
||||
end
|
||||
for i = q, m - 1 do
|
||||
-- f[i] (i >= M/2) gets x[i - M/2] (first range) and -x[3M/2 - 1 - i] (second range)
|
||||
f[i + 1] = x[xo + i - q + 1] - x[xo + 3 * q - i]
|
||||
end
|
||||
dct4(self.dct, f, 0, X, Xo, scale or 1)
|
||||
end
|
||||
|
||||
local function inverse(self: Plan, X: { number }, Xo: number, y: { number }, yo: number)
|
||||
local n = self.n
|
||||
local m = n // 2
|
||||
local q = m // 2
|
||||
local u = self.fold
|
||||
dct4(self.dct, X, Xo, u, 0, 1)
|
||||
-- y[n'] with m' = n' + M/2: m' < M -> u[m']; M <= m' < 2M -> -u[2M-1-m']; m' >= 2M -> -u[m'-2M]
|
||||
for i = 0, q * 3 - 1 do
|
||||
local mm = i + q
|
||||
if mm < m then
|
||||
y[yo + i + 1] = u[mm + 1]
|
||||
else
|
||||
y[yo + i + 1] = -u[2 * m - mm]
|
||||
end
|
||||
end
|
||||
for i = q * 3, n - 1 do
|
||||
y[yo + i + 1] = -u[i + q - 2 * m + 1]
|
||||
end
|
||||
end
|
||||
|
||||
local mdctCache: { [number]: Plan } = {}
|
||||
|
||||
-- new(N) -> Plan for an MDCT of N time samples (N/2 coefficients); N a power of two >= 16 | nil
|
||||
function Mdct.new(n: number): Plan?
|
||||
local c = mdctCache[n]
|
||||
if c then
|
||||
return c
|
||||
end
|
||||
if not isPow2(n) or n < 16 or n > 2 ^ 18 then
|
||||
return nil
|
||||
end
|
||||
local d = dctPlan(n // 2)
|
||||
if not d then
|
||||
return nil
|
||||
end
|
||||
local p: Plan = { n = n, forward = forward, inverse = inverse, dct = d, fold = table.create(n // 2, 0) }
|
||||
mdctCache[n] = p
|
||||
return p
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ windows
|
||||
-- the Vorbis power-complementary window rising over n samples: sin(pi/2 sin^2(pi (i + 1/2) / (2n))), i = 0 .. n-1
|
||||
function Mdct.vorbisWindow(n: number): { number }
|
||||
local w = table.create(n, 0)
|
||||
for i = 0, n - 1 do
|
||||
local s = sin((i + 0.5) / n * pi / 2)
|
||||
w[i + 1] = sin(pi / 2 * s * s)
|
||||
end
|
||||
return w
|
||||
end
|
||||
|
||||
-- the sine window over the whole block of n samples: sin(pi (i + 1/2) / n)
|
||||
function Mdct.sineWindow(n: number): { number }
|
||||
local w = table.create(n, 0)
|
||||
for i = 0, n - 1 do
|
||||
w[i + 1] = sin(pi * (i + 0.5) / n)
|
||||
end
|
||||
return w
|
||||
end
|
||||
|
||||
return Mdct
|
||||
@@ -0,0 +1,151 @@
|
||||
--!strict
|
||||
-- codecs/Pcm: PCM plumbing for audio encoders: one pull interface over an Audio or a Decoder, int <-> float samples.
|
||||
-- An encoder accepts a Types.Audio (fully decoded) or a
|
||||
-- Types.Decoder (streamed); Pcm.source turns either into one pull interface, so encoders stream in blocks without
|
||||
-- caring which they got. Also the float <-> integer sample conversions (the same rounding and clipping everywhere).
|
||||
--
|
||||
-- local src, err = Pcm.source(audioOrDecoder) -- nil, Err.ARG for anything else
|
||||
-- local buf, n = src:read(4096) -- interleaved f32, n frames (0 at the end), like Decoder:read
|
||||
-- local s16 = Pcm.toInt(x, 16) -- round, clip to [-32768, 32767]
|
||||
-- local x = Pcm.fromInt(s16, 16) -- s / 32768
|
||||
-- local audio = Pcm.collect(src) -- read everything into a Types.Audio
|
||||
--
|
||||
-- Never throws (a decoder's read that throws is caught and ends the stream).
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
|
||||
local Pcm = {}
|
||||
|
||||
export type Source = {
|
||||
sampleRate: number,
|
||||
channels: number,
|
||||
frames: number, -- total frames, 0 = unknown (a streaming decoder without an index)
|
||||
tags: Types.Tags,
|
||||
-- read(n, out?) -> interleaved f32 buffer, frames read (0 at the end)
|
||||
read: (self: Source, n: number, out: buffer?) -> (buffer, number),
|
||||
err: Err.Err?, -- set when the underlying decoder failed mid-stream
|
||||
}
|
||||
|
||||
local function audioRead(self: any, n: number, out: buffer?): (buffer, number)
|
||||
local a = self._audio
|
||||
local ch = a.channels
|
||||
local left = a.frames - self._pos
|
||||
if n > left then
|
||||
n = left
|
||||
end
|
||||
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)
|
||||
buffer.copy(b, 0, a.samples, self._pos * ch * 4, bytes)
|
||||
self._pos += n
|
||||
return b, n
|
||||
end
|
||||
|
||||
local function decoderRead(self: any, n: number, out: buffer?): (buffer, number)
|
||||
if self._done then
|
||||
return out or buffer.create(0), 0
|
||||
end
|
||||
local ok, b, got = pcall(self._dec.read, self._dec, n, out)
|
||||
if not ok then
|
||||
self._done = true
|
||||
self.err = Err.new(Err.CORRUPT, "source decoder failed: " .. tostring(b))
|
||||
return out or buffer.create(0), 0
|
||||
end
|
||||
if type(b) ~= "buffer" or type(got) ~= "number" or got <= 0 then
|
||||
self._done = true
|
||||
return out or buffer.create(0), 0
|
||||
end
|
||||
local ch = self.channels
|
||||
if buffer.len(b) < got * ch * 4 then
|
||||
got = buffer.len(b) // (ch * 4)
|
||||
end
|
||||
return b, got
|
||||
end
|
||||
|
||||
-- source(v) -> Source | nil, Err.ARG: v is a Types.Audio or a Types.Decoder (anything with sampleRate, channels, read)
|
||||
function Pcm.source(v: any): (Source?, Err.Err?)
|
||||
if type(v) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder")
|
||||
end
|
||||
local sr, ch = v.sampleRate, v.channels
|
||||
if type(sr) ~= "number" or sr <= 0 or sr ~= sr or type(ch) ~= "number" or ch < 1 or ch ~= math.floor(ch) then
|
||||
return nil, Err.new(Err.ARG, "bad sampleRate or channels")
|
||||
end
|
||||
if v.kind == "audio" and type(v.samples) == "buffer" then
|
||||
local frames = v.frames
|
||||
if type(frames) ~= "number" or frames < 0 or buffer.len(v.samples) < frames * ch * 4 then
|
||||
return nil, Err.new(Err.ARG, "the Audio's samples buffer is shorter than frames * channels * 4")
|
||||
end
|
||||
return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = audioRead, _audio = v, _pos = 0 } :: any, nil
|
||||
end
|
||||
if type(v.read) == "function" then
|
||||
local frames = if type(v.frames) == "number" and v.frames > 0 then v.frames else 0
|
||||
return { sampleRate = sr, channels = ch, frames = frames, tags = v.tags or {}, read = decoderRead, _dec = v, _done = false } :: any, nil
|
||||
end
|
||||
return nil, Err.new(Err.ARG, "needs an Audio or an audio Decoder")
|
||||
end
|
||||
|
||||
-- collect(src, maxFrames?) -> Types.Audio | nil, Err (everything the source has; Err.LIMIT past maxFrames)
|
||||
function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?)
|
||||
local ch = src.channels
|
||||
local cap = math.max(src.frames, 4096)
|
||||
local data = buffer.create(cap * ch * 4)
|
||||
local total = 0
|
||||
local limit = maxFrames or 2 ^ 31
|
||||
local tmp: buffer? = nil
|
||||
while true do
|
||||
local b, n = src:read(16384, tmp)
|
||||
if n <= 0 then
|
||||
break
|
||||
end
|
||||
tmp = b
|
||||
if total + n > limit then
|
||||
return nil, Err.new(Err.LIMIT, string.format("more than %d frames", limit))
|
||||
end
|
||||
if total + n > cap then
|
||||
cap = math.max(cap * 2, total + n)
|
||||
local nd = buffer.create(cap * ch * 4)
|
||||
buffer.copy(nd, 0, data, 0, total * ch * 4)
|
||||
data = nd
|
||||
end
|
||||
buffer.copy(data, total * ch * 4, b, 0, n * ch * 4)
|
||||
total += n
|
||||
end
|
||||
if src.err then
|
||||
return nil, src.err
|
||||
end
|
||||
local a = Types.Audio.new(src.sampleRate, ch, 0)
|
||||
a.frames = total
|
||||
if buffer.len(data) == total * ch * 4 then
|
||||
a.samples = data
|
||||
else
|
||||
a.samples = buffer.create(total * ch * 4)
|
||||
buffer.copy(a.samples, 0, data, 0, total * ch * 4)
|
||||
end
|
||||
a.tags = table.clone(src.tags)
|
||||
return a, nil
|
||||
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)
|
||||
local v = math.floor(x * s + 0.5)
|
||||
if v ~= v then
|
||||
return 0
|
||||
end
|
||||
if v >= s then
|
||||
return s - 1
|
||||
elseif v < -s then
|
||||
return -s
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
-- fromInt(v, bits) -> v / 2^(bits-1)
|
||||
function Pcm.fromInt(v: number, bits: number): number
|
||||
return v / 2 ^ (bits - 1)
|
||||
end
|
||||
|
||||
return Pcm
|
||||
@@ -0,0 +1,131 @@
|
||||
-- codecs/Mdct tests: the FFT against a direct DFT, the DCT-IV against its definition, the MDCT / IMDCT against their
|
||||
-- O(N^2) definitions at offsets, perfect reconstruction (TDAC) with the sine and Vorbis windows at scale 4/N, and bad
|
||||
-- sizes. No fixtures (the definitions are the reference).
|
||||
local T = require("@tests/T")
|
||||
local Mdct = require("@formats/codecs/Mdct")
|
||||
|
||||
local t = T.suite("mdct")
|
||||
local rand = T.rng(7)
|
||||
local function rnd(): number
|
||||
return rand(20001) / 10000 - 1
|
||||
end
|
||||
local cos, sin, pi = math.cos, math.sin, math.pi
|
||||
|
||||
-- FFT vs DFT
|
||||
for _, n in { 2, 4, 8, 64, 256 } do
|
||||
local f = Mdct.fft(n) :: Mdct.Fft
|
||||
local re, im, r0, i0 = {}, {}, {}, {}
|
||||
for i = 1, n do
|
||||
re[i], im[i] = rnd(), rnd()
|
||||
r0[i], i0[i] = re[i], im[i]
|
||||
end
|
||||
f:forward(re, im)
|
||||
local worst = 0
|
||||
for k = 0, n - 1 do
|
||||
local sr, si = 0, 0
|
||||
for j = 0, n - 1 do
|
||||
local a = -2 * pi * j * k / n
|
||||
sr += r0[j + 1] * cos(a) - i0[j + 1] * sin(a)
|
||||
si += r0[j + 1] * sin(a) + i0[j + 1] * cos(a)
|
||||
end
|
||||
worst = math.max(worst, math.abs(sr - re[k + 1]), math.abs(si - im[k + 1]))
|
||||
end
|
||||
t:check(worst < 1e-9, "fft " .. n .. ": error " .. worst)
|
||||
f:inverse(re, im)
|
||||
local back = 0
|
||||
for i = 1, n do
|
||||
back = math.max(back, math.abs(re[i] / n - r0[i]), math.abs(im[i] / n - i0[i]))
|
||||
end
|
||||
t:check(back < 1e-12, "fft " .. n .. ": inverse")
|
||||
end
|
||||
|
||||
-- DCT-IV
|
||||
for _, m in { 4, 8, 32, 128 } do
|
||||
local u, X = {}, {}
|
||||
for i = 1, m do
|
||||
u[i] = rnd()
|
||||
end
|
||||
t:check(Mdct.dct4(u, 0, X, 0, m), "dct4 plan " .. m)
|
||||
local worst = 0
|
||||
for k = 0, m - 1 do
|
||||
local s = 0
|
||||
for n = 0, m - 1 do
|
||||
s += u[n + 1] * cos(pi / m * (n + 0.5) * (k + 0.5))
|
||||
end
|
||||
worst = math.max(worst, math.abs(s - X[k + 1]))
|
||||
end
|
||||
t:check(worst < 1e-9, "dct4 " .. m .. ": error " .. worst)
|
||||
end
|
||||
|
||||
-- MDCT / IMDCT vs the definitions, with offsets
|
||||
for _, n in { 16, 32, 64, 256, 512 } do
|
||||
local p = Mdct.new(n) :: Mdct.Plan
|
||||
local m = n // 2
|
||||
local x = {}
|
||||
for i = 1, n + 3 do
|
||||
x[i] = rnd()
|
||||
end
|
||||
local X = table.create(m + 5, 0)
|
||||
p:forward(x, 3, X, 5)
|
||||
local worst = 0
|
||||
for k = 0, m - 1 do
|
||||
local s = 0
|
||||
for i = 0, n - 1 do
|
||||
s += x[3 + i + 1] * cos(pi / m * (i + 0.5 + m / 2) * (k + 0.5))
|
||||
end
|
||||
worst = math.max(worst, math.abs(s - X[5 + k + 1]))
|
||||
end
|
||||
t:check(worst < 1e-8, "mdct " .. n .. ": error " .. worst)
|
||||
local y = table.create(n + 2, 0)
|
||||
p:inverse(X, 5, y, 2)
|
||||
worst = 0
|
||||
for i = 0, n - 1 do
|
||||
local s = 0
|
||||
for k = 0, m - 1 do
|
||||
s += X[5 + k + 1] * cos(pi / m * (i + 0.5 + m / 2) * (k + 0.5))
|
||||
end
|
||||
worst = math.max(worst, math.abs(s - y[2 + i + 1]))
|
||||
end
|
||||
t:check(worst < 1e-8, "imdct " .. n .. ": error " .. worst)
|
||||
end
|
||||
|
||||
-- TDAC: window, forward (scale 4/N), inverse, window, overlap-add reconstructs the middle blocks
|
||||
for _, wname in { "sine", "vorbis" } do
|
||||
local n = 256
|
||||
local m = n // 2
|
||||
local p = Mdct.new(n) :: Mdct.Plan
|
||||
local w = if wname == "sine" then Mdct.sineWindow(n) else Mdct.vorbisWindow(m)
|
||||
local function win(i: number): number -- i = 0 .. n-1
|
||||
if wname == "sine" then
|
||||
return w[i + 1]
|
||||
end
|
||||
return if i < m then w[i + 1] else w[n - i]
|
||||
end
|
||||
local len = m * 6
|
||||
local sig = {}
|
||||
for i = 1, len do
|
||||
sig[i] = rnd()
|
||||
end
|
||||
local out = table.create(len, 0)
|
||||
local blk, X, y = table.create(n, 0), table.create(m, 0), table.create(n, 0)
|
||||
for start = 0, len - n, m do
|
||||
for i = 0, n - 1 do
|
||||
blk[i + 1] = sig[start + i + 1] * win(i)
|
||||
end
|
||||
p:forward(blk, 0, X, 0, 4 / n)
|
||||
p:inverse(X, 0, y, 0)
|
||||
for i = 0, n - 1 do
|
||||
out[start + i + 1] += y[i + 1] * win(i)
|
||||
end
|
||||
end
|
||||
local worst = 0
|
||||
for i = m + 1, len - m do
|
||||
worst = math.max(worst, math.abs(out[i] - sig[i]))
|
||||
end
|
||||
t:check(worst < 1e-9, wname .. " window TDAC: error " .. worst)
|
||||
end
|
||||
|
||||
t:check(Mdct.new(100) == nil and Mdct.new(8) == nil and Mdct.fft(3) == nil and Mdct.new(0.5) == nil, "bad sizes")
|
||||
t:check(Mdct.new(64) == Mdct.new(64), "plans are cached")
|
||||
-- (Mdct is a codec without a decoder of untrusted bytes: there is nothing to fuzz.)
|
||||
t:done()
|
||||
@@ -0,0 +1,194 @@
|
||||
# Shared helpers for the audio fixture generators (aiff, au, voc, vorbis, flac encoder, mp3 / mp2 encoders):
|
||||
# A = _audio.load() in a generator: import this file (generators are loaded by path, not as a package)
|
||||
# A.signal(kind, rate, ch, frames) deterministic test signals -> list of float frames-interleaved samples
|
||||
# A.f32le(samples) / A.from_f32le(b) float list <-> raw little-endian f32 bytes
|
||||
# A.wav(samples, rate, ch, bits=16) a WAV file (PCM 8/16/24/32 or float 32) for reference tools to read
|
||||
# A.ffdecode(ctx, data, fmt=None) decode any file with ffmpeg -> (rate, ch, floats)
|
||||
# A.tool(ctx, pkg, argv, data, ext) run a nix reference tool on a temp input file, return its stdout
|
||||
# A.snr(ref, test, ch, max_lag=0) SNR in dB of test against ref (searching an alignment lag up to max_lag frames,
|
||||
# either direction), and the lag found
|
||||
# A.luau(ctx, code) run Luau code (luau --codegen -O2 from the repo root, the .luaurc aliases
|
||||
# apply) and return its stdout bytes. Encoder fixtures use it to encode with our
|
||||
# encoder in the fixture step, then decode the output with the reference tool:
|
||||
# print(buffer.tostring(buf)) writes the raw bytes (plus one newline, stripped).
|
||||
import array, math, os, random, shutil, struct, subprocess, sys, tempfile, importlib.util
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
|
||||
def load():
|
||||
return sys.modules[__name__]
|
||||
|
||||
|
||||
def signal(kind, rate, ch, frames, seed=1):
|
||||
"""kinds: sine (440 Hz + 1 kHz per channel), sweep (50 Hz .. rate/2.2 log sweep), noise (white, -12 dBFS),
|
||||
music (a few harmonic notes with an envelope + a little noise), silence, square (aliased square, a stress test),
|
||||
loud (a full-scale sine near clipping)."""
|
||||
rng = random.Random(seed)
|
||||
out = [0.0] * (frames * ch)
|
||||
for c in range(ch):
|
||||
ph = 0.0
|
||||
notes = [(220.0 * 2 ** (rng.randrange(0, 24) / 12.0), rng.random() * 0.25 + 0.05) for _ in range(4)]
|
||||
for i in range(frames):
|
||||
t = i / rate
|
||||
if kind == "sine":
|
||||
v = 0.5 * math.sin(2 * math.pi * (440 + 110 * c) * t) + 0.2 * math.sin(2 * math.pi * 1000 * t + c)
|
||||
elif kind == "sweep":
|
||||
f0, f1 = 50.0, rate / 2.2
|
||||
dur = frames / rate
|
||||
f = f0 * (f1 / f0) ** (t / dur)
|
||||
ph += 2 * math.pi * f / rate
|
||||
v = 0.6 * math.sin(ph + c)
|
||||
elif kind == "noise":
|
||||
v = (rng.random() * 2 - 1) * 0.25
|
||||
elif kind == "music":
|
||||
v = 0.0
|
||||
for k, (f, a) in enumerate(notes):
|
||||
seg = (i // max(1, rate // 4) + k) % 4
|
||||
env = math.exp(-3.0 * ((i % max(1, rate // 4)) / rate))
|
||||
if seg != 3:
|
||||
v += a * env * (math.sin(2 * math.pi * f * t) + 0.3 * math.sin(4 * math.pi * f * t) + 0.1 * math.sin(6 * math.pi * f * t))
|
||||
v += (rng.random() * 2 - 1) * 0.01
|
||||
elif kind == "silence":
|
||||
v = 0.0
|
||||
elif kind == "square":
|
||||
v = 0.4 if math.sin(2 * math.pi * (300 + 50 * c) * t) >= 0 else -0.4
|
||||
elif kind == "loud":
|
||||
v = 0.98 * math.sin(2 * math.pi * 330 * t + c)
|
||||
else:
|
||||
raise ValueError(kind)
|
||||
out[i * ch + c] = v
|
||||
return out
|
||||
|
||||
|
||||
def quantize(samples, bits):
|
||||
s = 2 ** (bits - 1)
|
||||
return [max(-s, min(s - 1, int(math.floor(v * s + 0.5)))) / s for v in samples]
|
||||
|
||||
|
||||
def f32le(samples):
|
||||
a = array.array("f", samples)
|
||||
if sys.byteorder != "little":
|
||||
a.byteswap()
|
||||
return a.tobytes()
|
||||
|
||||
|
||||
def from_f32le(b):
|
||||
a = array.array("f")
|
||||
a.frombytes(b[: len(b) // 4 * 4])
|
||||
if sys.byteorder != "little":
|
||||
a.byteswap()
|
||||
return a.tolist()
|
||||
|
||||
|
||||
def wav(samples, rate, ch, bits=16, float_=False):
|
||||
n = len(samples) // ch
|
||||
if float_:
|
||||
data = f32le(samples)
|
||||
fmt = struct.pack("<HHIIHH", 3, ch, rate, rate * ch * 4, ch * 4, 32)
|
||||
else:
|
||||
bps = bits // 8
|
||||
s = 2 ** (bits - 1)
|
||||
out = bytearray()
|
||||
for v in samples:
|
||||
q = max(-s, min(s - 1, int(math.floor(v * s + 0.5))))
|
||||
if bits == 8:
|
||||
out.append(q + 128)
|
||||
else:
|
||||
out += (q & ((1 << bits) - 1)).to_bytes(bps, "little")
|
||||
data = bytes(out)
|
||||
fmt = struct.pack("<HHIIHH", 1, ch, rate, rate * ch * bps, ch * bps, bits)
|
||||
body = b"WAVE" + b"fmt " + struct.pack("<I", len(fmt)) + fmt + b"data" + struct.pack("<I", len(data)) + data
|
||||
if len(data) % 2:
|
||||
body += b"\0"
|
||||
return b"RIFF" + struct.pack("<I", len(body)) + body
|
||||
|
||||
|
||||
def tool(ctx, packages, argv, data=None, ext="bin", outext=None):
|
||||
"""run argv (a list; "{in}" / "{out}" are replaced by temp paths) under nix; returns stdout, or the {out} file"""
|
||||
d = tempfile.mkdtemp(prefix="fmt-audio-")
|
||||
try:
|
||||
inp = os.path.join(d, "in." + ext)
|
||||
out = os.path.join(d, "out." + (outext or "bin"))
|
||||
if data is not None:
|
||||
with open(inp, "wb") as f:
|
||||
f.write(data)
|
||||
args = [a.replace("{in}", inp).replace("{out}", out) for a in argv]
|
||||
stdout = ctx.nix(packages, args)
|
||||
if outext:
|
||||
with open(out, "rb") as f:
|
||||
return f.read()
|
||||
return stdout
|
||||
finally:
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
|
||||
|
||||
def ffdecode(ctx, data, fmt=None, ext="bin", extra=None):
|
||||
"""(rate, channels, floats) of any file ffmpeg reads"""
|
||||
probe = tool(ctx, "ffmpeg", ["ffprobe", "-v", "error", "-show_entries", "stream=sample_rate,channels", "-of", "csv=p=0"]
|
||||
+ (["-f", fmt] if fmt else []) + ["{in}"], data, ext).decode().strip().split("\n")[0].split(",")
|
||||
rate, ch = int(probe[0]), int(probe[1])
|
||||
raw = tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error"] + (["-f", fmt] if fmt else []) + ["-i", "{in}"] + (extra or [])
|
||||
+ ["-f", "f32le", "-acodec", "pcm_f32le", "-"], data, ext)
|
||||
return rate, ch, from_f32le(raw)
|
||||
|
||||
|
||||
def snr(ref, test, ch, max_lag=0, skip=0):
|
||||
"""SNR (dB) of test vs ref over their common frames (after `skip` frames), best lag in [-max_lag, max_lag]
|
||||
(test[i + lag] ~ ref[i]). Returns (snr, lag)."""
|
||||
best = (-1e9, 0)
|
||||
nref, ntest = len(ref) // ch, len(test) // ch
|
||||
lags = range(-max_lag, max_lag + 1) if max_lag else [0]
|
||||
if max_lag > 64:
|
||||
# coarse cross-correlation on the first channel to find candidate lags, then refine
|
||||
cands = []
|
||||
m = min(nref, 1 << 15)
|
||||
seg = [ref[i * ch] for i in range(skip, min(nref, skip + m))]
|
||||
for lag in range(-max_lag, max_lag + 1):
|
||||
acc = 0.0
|
||||
for i in range(0, len(seg), 7):
|
||||
j = skip + i + lag
|
||||
if 0 <= j < ntest:
|
||||
acc += seg[i] * test[j * ch]
|
||||
cands.append((acc, lag))
|
||||
cands.sort(reverse=True)
|
||||
lags = sorted(set(l for _, l in cands[:3]))
|
||||
for lag in lags:
|
||||
sig = err = 0.0
|
||||
for i in range(skip, nref):
|
||||
j = i + lag
|
||||
if j < 0 or j >= ntest:
|
||||
continue
|
||||
for c in range(ch):
|
||||
a = ref[i * ch + c]
|
||||
e = a - test[j * ch + c]
|
||||
sig += a * a
|
||||
err += e * e
|
||||
s = 200.0 if err == 0 else (10 * math.log10(sig / err) if sig > 0 else -200.0)
|
||||
if s > best[0]:
|
||||
best = (s, lag)
|
||||
return best
|
||||
|
||||
|
||||
def luau_bin():
|
||||
p = shutil.which("luau")
|
||||
if p:
|
||||
return p
|
||||
return subprocess.run(["nix", "shell", "nixpkgs#luau", "-c", "sh", "-c", "command -v luau"], capture_output=True, check=True,
|
||||
text=True).stdout.strip()
|
||||
|
||||
|
||||
def luau(ctx, code):
|
||||
d = os.path.join(ROOT, "tests", "gen")
|
||||
os.makedirs(d, exist_ok=True)
|
||||
fd, path = tempfile.mkstemp(prefix="_run_", suffix=".luau", dir=d)
|
||||
try:
|
||||
with os.fdopen(fd, "w") as f:
|
||||
f.write(code)
|
||||
r = subprocess.run([luau_bin(), "--codegen", "-O2", path], cwd=ROOT, capture_output=True)
|
||||
if r.returncode != 0:
|
||||
raise RuntimeError("luau failed:\n" + r.stderr.decode(errors="replace") + r.stdout.decode(errors="replace")[-2000:])
|
||||
out = r.stdout
|
||||
return out[:-1] if out.endswith(b"\n") else out
|
||||
finally:
|
||||
os.unlink(path)
|
||||
Reference in new issue
Block a user