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
@@ -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
|
||||
Reference in new issue
Block a user