From dcdf8377535ee144a5c95e280db71a20806616fa Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:25:18 -0500 Subject: [PATCH] ws-m4a: codecs/Mdct (MDCT / IMDCT / DCT-IV for any N divisible by 4 over a mixed-radix FFT; sine / KBD / Vorbis windows), shared with the Vorbis / Opus encoders --- src/Formats/codecs/Mdct/Fft.luau | 211 ++++++++++++++++++++++++++++++ src/Formats/codecs/Mdct/init.luau | 203 ++++++++++++++++++++++++++++ tests/codecs/mdct.luau | 134 +++++++++++++++++++ 3 files changed, 548 insertions(+) create mode 100644 src/Formats/codecs/Mdct/Fft.luau create mode 100644 src/Formats/codecs/Mdct/init.luau create mode 100644 tests/codecs/mdct.luau diff --git a/src/Formats/codecs/Mdct/Fft.luau b/src/Formats/codecs/Mdct/Fft.luau new file mode 100644 index 0000000..b4900df --- /dev/null +++ b/src/Formats/codecs/Mdct/Fft.luau @@ -0,0 +1,211 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Mdct/Fft: mixed-radix complex FFT of any size (radix 4, 2, 3, 5 butterflies, a generic odd-radix pass for +-- other primes), self-sorting Stockham passes ping-ponging between the data and a scratch array (the FFTPACK / +-- pocketfft pass structure, written from the textbook decimation-in-frequency derivation; no third-party code). +-- Data are separate real / imaginary arrays, 1-based. Never throws. +local Fft = {} + +export type Plan = { + n: number, + factors: { number }, + -- per pass: twiddles exp(-2 pi i u i l1 / n) for u = 1 .. p - 1, i = 0 .. ido - 1 at [(u - 1) * ido + i + 1] + twr: { { number } }, + twi: { { number } }, + -- per pass, generic odd radix: exp(-2 pi i k / p) for k = 0 .. p - 1 + rr: { { number } }, + ri: { { number } }, + sre: { number }, -- scratch + sim: { number }, +} + +local cos, sin, pi = math.cos, math.sin, math.pi + +-- new(n) -> Plan | nil (n < 1 or not an integer) +function Fft.new(n: number): Plan? + if type(n) ~= "number" or n < 1 or n % 1 ~= 0 or n > 2 ^ 24 then + return nil + end + local factors = {} + local m = n + while m % 4 == 0 do + table.insert(factors, 4) + m //= 4 + end + while m % 2 == 0 do + table.insert(factors, 2) + m //= 2 + end + local f = 3 + while m > 1 do + while m % f == 0 do + table.insert(factors, f) + m //= f + end + f += 2 + if f * f > m and m > 1 then + table.insert(factors, m) + m = 1 + end + end + local twr, twi, rr, ri = {}, {}, {}, {} + local l1 = 1 + for k, p in factors do + local ido = n // (l1 * p) + local tr, ti = table.create((p - 1) * ido, 0), table.create((p - 1) * ido, 0) + for u = 1, p - 1 do + for i = 0, ido - 1 do + local a = -2 * pi * u * i * l1 / n + tr[(u - 1) * ido + i + 1] = cos(a) + ti[(u - 1) * ido + i + 1] = sin(a) + end + end + twr[k], twi[k] = tr, ti + local cr, ci = table.create(p, 0), table.create(p, 0) + for j = 0, p - 1 do + cr[j + 1] = cos(-2 * pi * j / p) + ci[j + 1] = sin(-2 * pi * j / p) + end + rr[k], ri[k] = cr, ci + l1 *= p + end + return { + n = n, + factors = factors, + twr = twr, + twi = twi, + rr = rr, + ri = ri, + sre = table.create(n, 0), + sim = table.create(n, 0), + } +end + +-- one pass of radix p: cc (i, v, k) = src[1 + i + ido * (v + p * k)] -> ch (i, k, u) = dst[1 + i + ido * (k + l1 * u)] +local function pass(p: number, ido: number, l1: number, ar: { number }, ai: { number }, br: { number }, bi: { number }, tr: { number }, ti: { number }, cr: { number }, ci: { number }) + local lp = ido * l1 + if p == 4 then + for k = 0, l1 - 1 do + for i = 0, ido - 1 do + local s = 1 + i + ido * 4 * k + local a0r, a0i = ar[s], ai[s] + local a1r, a1i = ar[s + ido], ai[s + ido] + local a2r, a2i = ar[s + 2 * ido], ai[s + 2 * ido] + local a3r, a3i = ar[s + 3 * ido], ai[s + 3 * ido] + local t0r, t0i = a0r + a2r, a0i + a2i + local t1r, t1i = a0r - a2r, a0i - a2i + local t2r, t2i = a1r + a3r, a1i + a3i + local t3r, t3i = a1r - a3r, a1i - a3i + local d = 1 + i + ido * k + br[d], bi[d] = t0r + t2r, t0i + t2i + local y1r, y1i = t1r + t3i, t1i - t3r + local y2r, y2i = t0r - t2r, t0i - t2i + local y3r, y3i = t1r - t3i, t1i + t3r + if i == 0 then + br[d + lp], bi[d + lp] = y1r, y1i + br[d + 2 * lp], bi[d + 2 * lp] = y2r, y2i + br[d + 3 * lp], bi[d + 3 * lp] = y3r, y3i + else + local w1r, w1i = tr[i + 1], ti[i + 1] + local w2r, w2i = tr[ido + i + 1], ti[ido + i + 1] + local w3r, w3i = tr[2 * ido + i + 1], ti[2 * ido + i + 1] + br[d + lp], bi[d + lp] = y1r * w1r - y1i * w1i, y1r * w1i + y1i * w1r + br[d + 2 * lp], bi[d + 2 * lp] = y2r * w2r - y2i * w2i, y2r * w2i + y2i * w2r + br[d + 3 * lp], bi[d + 3 * lp] = y3r * w3r - y3i * w3i, y3r * w3i + y3i * w3r + end + end + end + elseif p == 2 then + for k = 0, l1 - 1 do + for i = 0, ido - 1 do + local s = 1 + i + ido * 2 * k + local a0r, a0i = ar[s], ai[s] + local a1r, a1i = ar[s + ido], ai[s + ido] + local d = 1 + i + ido * k + br[d], bi[d] = a0r + a1r, a0i + a1i + local yr, yi = a0r - a1r, a0i - a1i + if i == 0 then + br[d + lp], bi[d + lp] = yr, yi + else + local wr, wi = tr[i + 1], ti[i + 1] + br[d + lp], bi[d + lp] = yr * wr - yi * wi, yr * wi + yi * wr + end + end + end + elseif p == 3 then + local c = 0.86602540378443864676 -- sin(pi / 3) + for k = 0, l1 - 1 do + for i = 0, ido - 1 do + local s = 1 + i + ido * 3 * k + local a0r, a0i = ar[s], ai[s] + local a1r, a1i = ar[s + ido], ai[s + ido] + local a2r, a2i = ar[s + 2 * ido], ai[s + 2 * ido] + local tr_, ti_ = a1r + a2r, a1i + a2i + local sr, si = a1r - a2r, a1i - a2i + local d = 1 + i + ido * k + br[d], bi[d] = a0r + tr_, a0i + ti_ + local mr, mi = a0r - 0.5 * tr_, a0i - 0.5 * ti_ + local y1r, y1i = mr + c * si, mi - c * sr + local y2r, y2i = mr - c * si, mi + c * sr + if i == 0 then + br[d + lp], bi[d + lp] = y1r, y1i + br[d + 2 * lp], bi[d + 2 * lp] = y2r, y2i + else + local w1r, w1i = tr[i + 1], ti[i + 1] + local w2r, w2i = tr[ido + i + 1], ti[ido + i + 1] + br[d + lp], bi[d + lp] = y1r * w1r - y1i * w1i, y1r * w1i + y1i * w1r + br[d + 2 * lp], bi[d + 2 * lp] = y2r * w2r - y2i * w2i, y2r * w2i + y2i * w2r + end + end + end + else + -- generic radix: y_u = sum_v a_v exp(-2 pi i u v / p), then the twiddle + for k = 0, l1 - 1 do + for i = 0, ido - 1 do + local s = 1 + i + ido * p * k + local d = 1 + i + ido * k + for u = 0, p - 1 do + local yr, yi = 0, 0 + local j = 0 + for v = 0, p - 1 do + local xr, xi = ar[s + v * ido], ai[s + v * ido] + local wr, wi = cr[j + 1], ci[j + 1] + yr += xr * wr - xi * wi + yi += xr * wi + xi * wr + j += u + if j >= p then + j -= p + end + end + if u > 0 and i > 0 then + local wr, wi = tr[(u - 1) * ido + i + 1], ti[(u - 1) * ido + i + 1] + yr, yi = yr * wr - yi * wi, yr * wi + yi * wr + end + br[d + u * lp], bi[d + u * lp] = yr, yi + end + end + end + end +end + +-- forward(plan, re, im): in-place forward DFT X[k] = sum x[j] exp(-2 pi i j k / n) of re[1..n], im[1..n]. +-- The inverse (without the 1 / n) is forward(plan, im, re). +function Fft.forward(plan: Plan, re: { number }, im: { number }) + local n = plan.n + local ar, ai, br, bi = re, im, plan.sre, plan.sim + local l1 = 1 + for k, p in plan.factors do + local ido = n // (l1 * p) + pass(p, ido, l1, ar, ai, br, bi, plan.twr[k], plan.twi[k], plan.rr[k], plan.ri[k]) + ar, ai, br, bi = br, bi, ar, ai + l1 *= p + end + if ar ~= re then + for j = 1, n do + re[j], im[j] = ar[j], ai[j] + end + end +end + +return Fft diff --git a/src/Formats/codecs/Mdct/init.luau b/src/Formats/codecs/Mdct/init.luau new file mode 100644 index 0000000..316bc21 --- /dev/null +++ b/src/Formats/codecs/Mdct/init.luau @@ -0,0 +1,203 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point +-- complex FFT (codecs/Mdct/Fft, mixed radix: AAC 2048 / 256, Vorbis 64 .. 8192, CELT 1920 / 240 / ...), plus the +-- DCT-IV, a plain FFT and the sine / KBD / Vorbis windows. Shared by AAC, Vorbis and Opus (decoders and encoders). +-- Written from the textbook definitions (MDCT = DCT-IV of the folded input; DCT-IV through a half-size complex FFT +-- with pre / post twiddles); no third-party code. +-- +-- X[k] = sum_{j=0}^{N-1} x[j] cos(2 pi / N (j + 1/2 + N/4) (k + 1/2)) forward, k = 0 .. N/2 - 1 +-- y[j] = sum_{k=0}^{N/2-1} X[k] cos(2 pi / N (j + 1/2 + N/4) (k + 1/2)) inverse, j = 0 .. N - 1 +-- +-- Both are unnormalised (times `scale`, default 1): windowed forward + inverse + overlap-add with a Princen-Bradley +-- window gives the input times N / 4 (AAC: the spec IMDCT is inverse(..., 2 / N), its MDCT has a factor 2). Arrays +-- are Luau arrays; `xi` / `yi` are the 1-based index of element 0, coefficient arrays may be strided (CELT +-- interleaves its short blocks). +-- +-- local Mdct = require("@formats/codecs/Mdct") +-- local plan = Mdct.new(2048) -- nil when N is not a multiple of 4 +-- Mdct.forward(plan, x, 1, X, 1) -- 2048 samples -> 1024 coefficients +-- Mdct.inverse(plan, X, 1, 1, y, 1, 2 / 2048) -- 1024 coefficients -> 2048 samples +-- local w = Mdct.window("sine", 2048) -- or "kbd" (alpha), "vorbis": N values +-- +-- Never throws: bad sizes return nil from new(); the transforms trust the plan and the array ranges (the caller +-- sizes them). +local Fft = require("@formats/codecs/Mdct/Fft") + +local cos, sin, pi, sqrt = math.cos, math.sin, math.pi, math.sqrt + +local Mdct = {} +Mdct.Fft = Fft + +export type Plan = { + n: number, -- window length N + m: number, -- coefficients N / 2 + fft: Fft.Plan, -- N / 4 points + twc: { number }, -- cos / sin (pi (p + 1/8) / M), p = 0 .. N/4 - 1 + tws: { number }, + re: { number }, -- scratch + im: { number }, + c: { number }, -- DCT-IV output scratch (M) +} + +-- new(N) -> Plan | nil +function Mdct.new(n: number): Plan? + if type(n) ~= "number" or n < 4 or n % 4 ~= 0 or n > 2 ^ 24 then + return nil + end + local m = n // 2 + local q = n // 4 + local fft = Fft.new(q) + if not fft then + return nil + end + local twc, tws = table.create(q, 0), table.create(q, 0) + for p = 0, q - 1 do + local a = pi * (p + 0.125) / m + twc[p + 1], tws[p + 1] = cos(a), sin(a) + end + return { + n = n, + m = m, + fft = fft, + twc = twc, + tws = tws, + re = table.create(q, 0), + im = table.create(q, 0), + c = table.create(m, 0), + } +end + +-- the DCT-IV of the M values u (already in plan.re / plan.im as the pre-twiddled pairs) into out[oi + k * os] +local function dct4Post(plan: Plan, out: { number }, oi: number, os: number, scale: number) + local q, m = plan.n // 4, plan.m + local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws + Fft.forward(plan.fft, re, im) + for k = 0, q - 1 do + local c, s = twc[k + 1], tws[k + 1] + local tr, ti = re[k + 1], im[k + 1] + out[oi + 2 * k * os] = (tr * c + ti * s) * scale + out[oi + (m - 1 - 2 * k) * os] = -(ti * c - tr * s) * scale + end +end + +-- dct4(plan, u, ui, us, out, oi, os, scale?): C[k] = sum_{n=0}^{M-1} u[n] cos(pi / M (n + 1/2) (k + 1/2)) for the +-- plan's M = N / 2 (its own inverse up to 2 / M) +function Mdct.dct4(plan: Plan, u: { number }, ui: number, us: number, out: { number }, oi: number, os: number, scale: number?) + local q, m = plan.n // 4, plan.m + local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws + for p = 0, q - 1 do + local a, b = u[ui + 2 * p * us], u[ui + (m - 1 - 2 * p) * us] + local c, s = twc[p + 1], tws[p + 1] + re[p + 1] = a * c + b * s + im[p + 1] = b * c - a * s + end + dct4Post(plan, out, oi, os, scale or 1) +end + +-- forward(plan, x, xi, X, Xi, Xs?, scale?): N samples x[xi ..] -> N / 2 coefficients X[Xi + k * Xs] +function Mdct.forward(plan: Plan, x: { number }, xi: number, out: { number }, oi: number, os: number?, scale: number?) + local q, m = plan.n // 4, plan.m + local h = m // 2 -- N / 4 + local re, im, twc, tws = plan.re, plan.im, plan.twc, plan.tws + -- fold: u[j] = -x[3M/2 - 1 - j] - x[3M/2 + j] (j < M/2), x[j - M/2] - x[3M/2 - 1 - j] (j >= M/2) + local b3 = xi + 3 * h + for p = 0, q - 1 do + local j = 2 * p + local a + if j < h then + a = -x[b3 - 1 - j] - x[b3 + j] + else + a = x[xi + j - h] - x[b3 - 1 - j] + end + j = m - 1 - 2 * p + local b + if j < h then + b = -x[b3 - 1 - j] - x[b3 + j] + else + b = x[xi + j - h] - x[b3 - 1 - j] + end + local c, s = twc[p + 1], tws[p + 1] + re[p + 1] = a * c + b * s + im[p + 1] = b * c - a * s + end + dct4Post(plan, out, oi, os or 1, scale or 1) +end + +-- inverse(plan, X, Xi, Xs?, y, yi, scale?): N / 2 coefficients X[Xi + k * Xs] -> N samples y[yi ..] (no window) +function Mdct.inverse(plan: Plan, inp: { number }, ii: number, is: number?, y: { number }, yi: number, scale: number?) + local m = plan.m + local h = m // 2 + local c = plan.c + Mdct.dct4(plan, inp, ii, is or 1, c, 1, 1, scale) + -- unfold: y = (C2, -C2 reversed, -C1 reversed, -C1) + for j = 0, h - 1 do + y[yi + j] = c[h + j + 1] + y[yi + h + j] = -c[m - j] + y[yi + m + j] = -c[h - j] + y[yi + 3 * h + j] = -c[j + 1] + end +end + +-- ------------------------------------------------------------------------------------------------ windows +local function besselI0(x: number): number + local sum, term = 1, 1 + local k = 1 + while k < 200 do + term *= (x / (2 * k)) ^ 2 + sum += term + if term < sum * 1e-17 then + break + end + k += 1 + end + return sum +end +Mdct.besselI0 = besselI0 + +-- window(kind, N, alpha?) -> N values: "sine" sin(pi (n + 1/2) / N); "kbd" Kaiser-Bessel-derived (alpha: AAC uses 4 +-- for long, 6 for short windows); "vorbis" sin(pi / 2 sin^2(pi (n + 1/2) / N)). All satisfy w[n]^2 + w[n + N/2]^2 = 1. +function Mdct.window(kind: string, n: number, alpha: number?): { number }? + if type(n) ~= "number" or n < 2 or n % 2 ~= 0 then + return nil + end + local w = table.create(n, 0) + if kind == "sine" then + for i = 0, n - 1 do + w[i + 1] = sin(pi * (i + 0.5) / n) + end + elseif kind == "vorbis" then + for i = 0, n - 1 do + local s = sin(pi * (i + 0.5) / n) + w[i + 1] = sin(pi / 2 * s * s) + end + elseif kind == "kbd" then + local half = n // 2 + local a = alpha or 4 + local kais = table.create(half + 1, 0) + local total = 0 + for i = 0, half do + local r = 2 * i / half - 1 + kais[i + 1] = besselI0(pi * a * sqrt(math.max(0, 1 - r * r))) + total += kais[i + 1] + end + local acc = 0 + for i = 0, half - 1 do + acc += kais[i + 1] + local v = sqrt(acc / total) + w[i + 1] = v + w[n - i] = v + end + else + return nil + end + return w +end + +-- fft(n) -> an Fft plan (Fft.forward(plan, re, im) transforms in place) +function Mdct.fft(n: number): Fft.Plan? + return Fft.new(n) +end + +return Mdct diff --git a/tests/codecs/mdct.luau b/tests/codecs/mdct.luau new file mode 100644 index 0000000..82d0e25 --- /dev/null +++ b/tests/codecs/mdct.luau @@ -0,0 +1,134 @@ +-- codecs/Mdct tests: the FFT against a direct DFT for mixed-radix sizes, the forward / inverse MDCT and the DCT-IV +-- against their O(N^2) definitions (AAC, Vorbis and CELT sizes), perfect reconstruction (TDAC) with the sine, KBD and +-- Vorbis windows, window power complementarity, 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 cos, sin, pi = math.cos, math.sin, math.pi + +local function noise(n: number): { number } + local a = table.create(n, 0) + for i = 1, n do + a[i] = rand(20001) / 10000 - 1 + end + return a +end + +-- FFT vs DFT +for _, n in { 1, 2, 3, 4, 5, 6, 7, 8, 12, 15, 16, 30, 49, 60, 64, 120, 240, 480, 77 } do + local plan = Mdct.fft(n) + t:check(plan, "fft plan " .. n) + local re, im = noise(n), noise(n) + local wr, wi = table.create(n, 0), table.create(n, 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 += re[j + 1] * cos(a) - im[j + 1] * sin(a) + si += re[j + 1] * sin(a) + im[j + 1] * cos(a) + end + wr[k + 1], wi[k + 1] = sr, si + end + Mdct.Fft.forward(plan :: any, re, im) + local err = 0 + for k = 1, n do + err = math.max(err, math.abs(re[k] - wr[k]), math.abs(im[k] - wi[k])) + end + t:check(err < 1e-9 * n, string.format("fft %d: max error %g", n, err)) +end + +-- MDCT / IMDCT vs the definitions +local maxErr = 0 +for _, n in { 4, 8, 16, 64, 240, 256, 480, 1920, 2048 } do + local plan = Mdct.new(n) :: Mdct.Plan + t:check(plan, "mdct plan " .. n) + local m = n // 2 + local x = noise(n) + local X = table.create(m, 0) + Mdct.forward(plan, x, 1, X, 1) + local Y = noise(m) + local y = table.create(n, 0) + Mdct.inverse(plan, Y, 1, 1, y, 1) + local step = if n > 500 then 37 else 1 -- spot-check the big sizes + local ef, ei = 0, 0 + for k = 0, m - 1, step do + local s = 0 + for j = 0, n - 1 do + s += x[j + 1] * cos(2 * pi / n * (j + 0.5 + n / 4) * (k + 0.5)) + end + ef = math.max(ef, math.abs(s - X[k + 1])) + end + for j = 0, n - 1, step do + local s = 0 + for k = 0, m - 1 do + s += Y[k + 1] * cos(2 * pi / n * (j + 0.5 + n / 4) * (k + 0.5)) + end + ei = math.max(ei, math.abs(s - y[j + 1])) + end + t:check(ef < 1e-9 * n and ei < 1e-9 * n, string.format("mdct %d: forward error %g, inverse error %g", n, ef, ei)) + maxErr = math.max(maxErr, ef, ei) + -- strided coefficients + offsets + scale + local X2 = table.create(m * 3 + 5, 0) + Mdct.forward(plan, x, 1, X2, 3, 3, 0.5) + local ok = true + for k = 0, m - 1 do + ok = ok and math.abs(X2[3 + 3 * k] - 0.5 * X[k + 1]) < 1e-9 + end + t:check(ok, "mdct " .. n .. ": strided / scaled forward") +end +t:note("mdct vs definition: max error %.3g", maxErr) + +-- TDAC: windowed forward + inverse + overlap-add reproduces the signal +for _, kind in { "sine", "kbd", "vorbis" } do + for _, n in { 256, 2048, 240 } do + local w = Mdct.window(kind, n, if n == 256 then 6 else 4) :: { number } + local m = n // 2 + local plan = Mdct.new(n) :: Mdct.Plan + local pc = 0 + for i = 1, m do + pc = math.max(pc, math.abs(w[i] ^ 2 + w[i + m] ^ 2 - 1)) + end + t:check(pc < 1e-12, kind .. " " .. n .. ": power complementary") + local frames = 6 + local sig = noise(m * (frames + 1)) + local out = table.create(m * (frames + 1), 0) + local buf, X, y = table.create(n, 0), table.create(m, 0), table.create(n, 0) + for f = 0, frames - 1 do + for i = 1, n do + buf[i] = sig[f * m + i] * w[i] + end + Mdct.forward(plan, buf, 1, X, 1) + Mdct.inverse(plan, X, 1, 1, y, 1, 4 / n) + for i = 1, n do + out[f * m + i] += y[i] * w[i] + end + end + local e = 0 + for i = m + 1, m * frames do + e = math.max(e, math.abs(out[i] - sig[i])) + end + t:check(e < 1e-9, string.format("%s %d: reconstruction error %g", kind, n, e)) + end +end + +-- DCT-IV is its own inverse (times 2 / M) +do + local plan = Mdct.new(512) :: Mdct.Plan + local u = noise(256) + local c, back = table.create(256, 0), table.create(256, 0) + Mdct.dct4(plan, u, 1, 1, c, 1, 1) + Mdct.dct4(plan, c, 1, 1, back, 1, 1, 2 / 256) + local e = 0 + for i = 1, 256 do + e = math.max(e, math.abs(back[i] - u[i])) + end + t:check(e < 1e-10, "dct4 involution: " .. e) +end + +-- bad sizes +t:check(Mdct.new(6) == nil and Mdct.new(0) == nil and Mdct.new(-8) == nil and Mdct.new(8.5) == nil and Mdct.new("x" :: any) == nil, "bad mdct sizes") +t:check(Mdct.fft(0) == nil and Mdct.window("nope", 8) == nil and Mdct.window("sine", 7) == nil, "bad fft sizes / windows") + +t:done()