From dcdf8377535ee144a5c95e280db71a20806616fa Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:25:18 -0500 Subject: [PATCH 1/7] 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() From 859a96ea79fc9e97db2902cd049223508329d363 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:25:23 -0500 Subject: [PATCH 2/7] ws-m4a: regenerate docs/FORMATS.md --- docs/FORMATS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 181230b..4a451fa 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -10,3 +10,4 @@ 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 MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point From 064af84d63d290a385b63f69049a659a94a9438b Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:37:32 -0500 Subject: [PATCH 3/7] ws-m4a: containers/IsoBmff (box tree, demux: stsd entries + codec configs, stts/ctts/stsc/stsz/stz2/stco/co64/stss, elst, fragments; HEIF/AVIF items; iTunes tags read/write; progressive muxer), tested packet-for-packet against ffprobe --- src/Formats/containers/IsoBmff/Box.luau | 193 +++++ src/Formats/containers/IsoBmff/Demux.luau | 848 ++++++++++++++++++++++ src/Formats/containers/IsoBmff/Meta.luau | 526 ++++++++++++++ src/Formats/containers/IsoBmff/Mux.luau | 519 +++++++++++++ src/Formats/containers/IsoBmff/init.luau | 188 +++++ tests/containers/isobmff.luau | 241 ++++++ tools/fixtures/isobmff.py | 89 +++ 7 files changed, 2604 insertions(+) create mode 100644 src/Formats/containers/IsoBmff/Box.luau create mode 100644 src/Formats/containers/IsoBmff/Demux.luau create mode 100644 src/Formats/containers/IsoBmff/Meta.luau create mode 100644 src/Formats/containers/IsoBmff/Mux.luau create mode 100644 src/Formats/containers/IsoBmff/init.luau create mode 100644 tests/containers/isobmff.luau create mode 100644 tools/fixtures/isobmff.py diff --git a/src/Formats/containers/IsoBmff/Box.luau b/src/Formats/containers/IsoBmff/Box.luau new file mode 100644 index 0000000..769d22e --- /dev/null +++ b/src/Formats/containers/IsoBmff/Box.luau @@ -0,0 +1,193 @@ +--!strict +-- containers/IsoBmff/Box: the box tree of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 4.2): 32-bit, 64-bit +-- (size 1) and to-the-end (size 0) sizes, uuid boxes, full-box version / flags, and the recursion into the container +-- boxes (moov / trak / mdia / minf / stbl / udta / meta / ilst items / moof / traf / iprp / ipco / iref / dinf / ...). +-- Sample descriptions (stsd) are left to the demuxer, which knows the sample entry layouts. Never throws. +local Err = require("@formats/core/Err") + +local readu8, readu32, readstring = buffer.readu8, buffer.readu32, buffer.readstring +local byteswap = bit32.byteswap + +local Box = {} + +export type Box = { + type: string, -- four characters ("moov", "\169nam", ...); "uuid" boxes also have `uuid` + start: number, -- absolute offset of the box in the buffer + size: number, -- the whole box, header included + data: number, -- absolute offset of the payload (after size / type / largesize / uuid) + stop: number, -- absolute offset just past the box (start + size, clamped to the parent) + uuid: string?, + children: { Box }?, -- container boxes + truncated: boolean?, -- the box claims more bytes than its parent has (clamped) +} + +-- plain container boxes: their payload is a list of boxes +local CONTAINERS = { + moov = true, trak = true, mdia = true, minf = true, stbl = true, dinf = true, edts = true, udta = true, + mvex = true, moof = true, traf = true, mfra = true, tref = true, iprp = true, ipco = true, sinf = true, + schi = true, wave = true, gmhd = true, tapt = true, ilst = true, clip = true, matt = true, rinf = true, + strk = true, strd = true, grpl = true, meco = true, mere = true, +} +-- full boxes (version + flags) whose payload is then a list of boxes, after `skip` more bytes +local FULL_CONTAINERS: { [string]: number } = { meta = 0, iref = 0, dref = 4 } +Box.CONTAINERS = CONTAINERS + +local function be32(b: buffer, o: number): number + return byteswap(readu32(b, o)) +end +Box.be32 = be32 + +-- the ilst item boxes ("\169nam", "trkn", "----", ...) contain data / mean / name boxes +local function isIlstItem(parentType: string?): boolean + return parentType == "ilst" +end + +-- header(buf, p, limit) -> Box (without children) | nil, Err +function Box.header(b: buffer, p: number, limit: number): (Box?, Err.Err?) + if p + 8 > limit then + return nil, Err.new(Err.TRUNCATED, "box header runs past the end", p) + end + local size = be32(b, p) + local typ = readstring(b, p + 4, 4) + local data = p + 8 + if size == 1 then + if p + 16 > limit then + return nil, Err.new(Err.TRUNCATED, "64-bit box size runs past the end", p) + end + size = be32(b, p + 8) * 4294967296 + be32(b, p + 12) + data = p + 16 + elseif size == 0 then + size = limit - p + end + local uuid: string? = nil + if typ == "uuid" then + if data + 16 > limit then + return nil, Err.new(Err.TRUNCATED, "uuid runs past the end", p) + end + uuid = readstring(b, data, 16) + data += 16 + end + if size < data - p then + return nil, Err.new(Err.CORRUPT, string.format("box '%s' size %d is smaller than its header", typ, size), p) + end + local stop = p + size + local truncated: boolean? = nil + if stop > limit then + stop = limit + truncated = true + end + return { type = typ, start = p, size = size, data = data, stop = stop, uuid = uuid, children = nil, truncated = truncated }, nil +end + +-- list(buf, p, limit, parentType?, depth?) -> { Box } (a run of sibling boxes, containers parsed recursively). A +-- broken box ends the list (its siblings so far are kept); the second value is the first error met, if any. +function Box.list(b: buffer, p: number, limit: number, parentType: string?, depth: number?): ({ Box }, Err.Err?) + local d = depth or 0 + local out: { Box } = {} + local firstErr: Err.Err? = nil + if d > 32 then + return out, Err.new(Err.CORRUPT, "boxes nested too deep", p) + end + while p + 8 <= limit do + local box, err = Box.header(b, p, limit) + if not box then + firstErr = firstErr or err + break + end + if box.truncated then + firstErr = firstErr or Err.new(Err.TRUNCATED, "box '" .. box.type .. "' runs past the end", p) + end + local t = box.type + local kids: { Box }? = nil + local kerr: Err.Err? = nil + if CONTAINERS[t] or isIlstItem(parentType) then + kids, kerr = Box.list(b, box.data, box.stop, t, d + 1) + elseif FULL_CONTAINERS[t] then + local q = box.data + 4 + FULL_CONTAINERS[t] + -- QuickTime writes udta/meta as a plain container: its first child box follows directly + if t == "meta" and box.data + 8 <= box.stop and readstring(b, box.data + 4, 4) == "hdlr" then + q = box.data + end + if q <= box.stop then + kids, kerr = Box.list(b, q, box.stop, t, d + 1) + end + elseif t == "iinf" then + if box.data + 4 <= box.stop then + local v = readu8(b, box.data) + local q = box.data + 4 + (if v == 0 then 2 else 4) + if q <= box.stop then + kids, kerr = Box.list(b, q, box.stop, t, d + 1) + end + end + end + box.children = kids + if kerr then + firstErr = firstErr or kerr + end + table.insert(out, box) + if box.stop <= p then + break + end + p = box.stop + end + return out, firstErr +end + +-- child(box, type) -> the first child of that type +function Box.child(box: Box?, typ: string): Box? + if not box or not box.children then + return nil + end + for _, c in box.children :: { Box } do + if c.type == typ then + return c + end + end + return nil +end + +-- children(box, type) -> every child of that type +function Box.childrenOf(box: Box?, typ: string): { Box } + local out = {} + if box and box.children then + for _, c in box.children :: { Box } do + if c.type == typ then + table.insert(out, c) + end + end + end + return out +end + +-- path(boxes or box, "moov/trak/mdia") -> the first box along the path +function Box.path(root: any, path: string): Box? + local cur: any = root + for part in string.gmatch(path, "[^/]+") do + if cur == nil then + return nil + end + local list = if cur.children ~= nil or cur.type ~= nil then cur.children else cur + local found = nil + if list then + for _, c in list do + if c.type == part then + found = c + break + end + end + end + cur = found + end + return cur +end + +-- version / flags of a full box +function Box.fullHeader(b: buffer, box: Box): (number, number) + if box.data + 4 > box.stop then + return -1, 0 + end + local v = be32(b, box.data) + return bit32.rshift(v, 24), bit32.band(v, 0xFFFFFF) +end + +return Box diff --git a/src/Formats/containers/IsoBmff/Demux.luau b/src/Formats/containers/IsoBmff/Demux.luau new file mode 100644 index 0000000..6a5a4cb --- /dev/null +++ b/src/Formats/containers/IsoBmff/Demux.luau @@ -0,0 +1,848 @@ +--!strict +-- containers/IsoBmff/Demux: tracks and sample tables of an ISO BMFF / QuickTime file (ISO/IEC 14496-12 8.3 - 8.8): +-- tkhd / mdhd / hdlr, sample descriptions (audio v0 / QuickTime v1 / v2, video, other) with the codec configuration +-- (esds DecoderSpecificInfo, alac, dOps, dfLa, avcC, hvcC, av1C, vpcC, dac3, ...), stts / ctts / stsc / stsz / stz2 / +-- stco / co64 / stss, edit lists (elst), and fragmented files (mvex / trex, moof / traf / tfhd / tfdt / trun). +-- The per-sample tables are columnar arrays (offsets / sizes / dts / durations / cts / sync), offsets absolute in the +-- reader's buffer. Never throws. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Box = require("@formats/containers/IsoBmff/Box") + +local readstring = buffer.readstring + +local Demux = {} + +export type Edit = { duration: number, mediaTime: number, rate: number } -- duration in movie ticks, mediaTime in media ticks (-1 = empty) + +-- a track: Types.Track (id, kind, codec, timescale, duration, width, height, sampleRate, channels, config) plus the +-- sample tables and the ISO facts +export type Track = { + id: number, + kind: "video" | "audio" | "subtitle" | "data", + codec: string, -- "aac", "alac", "mp3", "opus", "flac", "pcm", "h264", "hevc", "av1", "vp8", "vp9", "mpeg4", "mjpeg", "ac3", "eac3", "tx3g", ... or the entry fourcc + entry: string, -- the sample entry fourcc ("mp4a", "alac", "avc1", ...) + handler: string, -- hdlr type ("soun", "vide", "subt", "text", "pict", ...) + timescale: number, + duration: number, -- seconds (media duration; the edit list may shorten it) + mediaDuration: number, -- ticks + language: string?, -- ISO 639-2 ("und", "eng", ...) + width: number?, + height: number?, + sampleRate: number?, + channels: number?, + bitsPerSample: number?, + config: buffer?, -- codec configuration (AudioSpecificConfig, ALAC cookie, dOps, avcC, ...) + objectType: number?, -- esds objectTypeIndication + pcm: { bits: number, float: boolean, little: boolean }?, + entryBoxes: { Box.Box }, -- the sample entry's child boxes (esds, btrt, colr, pasp, ...) + edits: { Edit }?, + skip: number, -- media ticks to drop at the start (the first edit's media time: AAC priming) + delay: number, -- movie ticks of an initial empty edit + playDuration: number?, -- media ticks the edit list plays (nil: all) + -- samples + sampleCount: number, + offsets: { number }, -- absolute offsets in the buffer + sizes: { number }, + dts: { number }, -- decode times in ticks + durations: { number }, + cts: { number }?, -- composition offsets (pts = dts + cts) when the track has ctts / trun offsets + sync: { [number]: boolean }?, -- sync samples (nil: every sample is a sync sample) + sampleDescription: { number }?, -- stsd index per sample when there are several entries + [string]: any, +} + +export type Options = { maxSamples: number? } + +local HANDLER_KIND: { [string]: "video" | "audio" | "subtitle" | "data" } = { + soun = "audio", vide = "video", pict = "video", auxv = "video", subt = "subtitle", text = "subtitle", + sbtl = "subtitle", clcp = "subtitle", +} +local CODEC: { [string]: string } = { + mp4a = "aac", alac = "alac", Opus = "opus", fLaC = "flac", [".mp3"] = "mp3", ["ac-3"] = "ac3", ["ec-3"] = "eac3", + lpcm = "pcm", sowt = "pcm", twos = "pcm", ["raw "] = "pcm", in24 = "pcm", in32 = "pcm", fl32 = "pcm", fl64 = "pcm", + ipcm = "pcm", fpcm = "pcm", ulaw = "ulaw", alaw = "alaw", samr = "amr", sawb = "amrwb", + avc1 = "h264", avc3 = "h264", hvc1 = "hevc", hev1 = "hevc", av01 = "av1", vp08 = "vp8", vp09 = "vp9", + mp4v = "mpeg4", jpeg = "mjpeg", mjpa = "mjpeg", mjpb = "mjpeg", png = "png", ["s263"] = "h263", ["mp1v"] = "mpeg1", + ["mp2v"] = "mpeg2", tx3g = "tx3g", wvtt = "webvtt", stpp = "ttml", c608 = "cea608", text = "text", +} +-- esds objectTypeIndication -> codec +local OTI: { [number]: string } = { + [0x40] = "aac", [0x66] = "aac", [0x67] = "aac", [0x68] = "aac", [0x69] = "mp3", [0x6B] = "mp3", [0x6A] = "mpeg1", + [0x60] = "mpeg2", [0x61] = "mpeg2", [0x20] = "mpeg4", [0x21] = "h264", [0x6C] = "mjpeg", [0xA5] = "ac3", + [0xA6] = "eac3", [0xAD] = "opus", [0xDD] = "vorbis", +} +-- the box holding each video / audio codec's configuration +local CONFIG_BOX = { "avcC", "hvcC", "av1C", "vpcC", "dOps", "dfLa", "dac3", "dec3", "d263", "glbl" } +local FULL_CONFIG: { [string]: boolean } = { vpcC = true, dfLa = true, alac = true } + +local function payload(b: buffer, box: Box.Box, skip: number?): buffer + local o = box.data + (skip or 0) + local n = math.max(0, box.stop - o) + local out = buffer.create(n) + if n > 0 then + buffer.copy(out, 0, b, o, n) + end + return out +end + +local function reader(b: buffer, box: Box.Box): Bytes.Reader + return Bytes.reader(b, box.data, box.stop - box.data) +end + +-- expandable descriptor length (ISO 14496-1 8.3.3) +local function descLen(r: Bytes.Reader): number + local n = 0 + for _ = 1, 4 do + local c = r:u8() + n = n * 128 + bit32.band(c, 127) + if c < 128 then + break + end + end + return n +end + +-- esds -> objectTypeIndication, DecoderSpecificInfo, avg bitrate +function Demux.esds(b: buffer, box: Box.Box): (number?, buffer?, number?) + local r = reader(b, box) + r:skip(4) -- version / flags + if r:u8() ~= 3 then + return nil, nil, nil + end + descLen(r) + r:skip(2) -- ES_ID + local flags = r:u8() + if bit32.band(flags, 0x80) ~= 0 then + r:skip(2) + end + if bit32.band(flags, 0x40) ~= 0 then + r:skip(r:u8()) + end + if bit32.band(flags, 0x20) ~= 0 then + r:skip(2) + end + if r:u8() ~= 4 then + return nil, nil, nil + end + local dlen = descLen(r) + local dstart = r.pos + local oti = r:u8() + r:skip(1 + 3 + 4) -- streamType, bufferSize, maxBitrate + local avg = r:u32be() + local dsi: buffer? = nil + if r.pos < dstart + dlen and r:u8() == 5 then + local n = descLen(r) + if n > 0 and r:need(n) then + dsi = r:bytes(n) + end + end + if r.err then + return oti, nil, nil + end + return oti, dsi, avg +end + +-- the sample entry `e` of a track with handler `handler`: fills the codec facts into t +local function sampleEntry(b: buffer, e: Box.Box, handler: string, t: Track) + local r = reader(b, e) + r:skip(6) + r:skip(2) -- data reference index + local typ = e.type + t.entry = typ + t.codec = CODEC[typ] or typ + local kind = t.kind + local childStart + if kind == "audio" then + local version = r:u16be() + r:skip(2 + 4) -- revision, vendor + local channels = r:u16be() + local bits = r:u16be() + r:skip(4) -- compression id, packet size + local rate = r:u32be() / 65536 + if version == 1 then + r:skip(16) + elseif version == 2 then + r:skip(4) + rate = r:f64be() + channels = r:u32be() + r:skip(4) + bits = r:u32be() + local lpcmFlags = r:u32be() + r:skip(8) + if typ == "lpcm" then + t.pcm = { + bits = bits, + float = bit32.band(lpcmFlags, 1) ~= 0, + little = bit32.band(lpcmFlags, 2) == 0, + } + end + end + t.channels, t.sampleRate, t.bitsPerSample = channels, rate, bits + if not t.pcm and t.codec == "pcm" then + local B: { [string]: number } = { sowt = 16, twos = 16, ["raw "] = 8, in24 = 24, in32 = 32, fl32 = 32, fl64 = 64 } + t.pcm = { + bits = B[typ] or bits, + float = typ == "fl32" or typ == "fl64", + little = typ == "sowt", + } + end + childStart = r.pos + elseif kind == "video" then + r:skip(16) + t.width = r:u16be() + t.height = r:u16be() + r:skip(4 + 4 + 4 + 2 + 32 + 2 + 2) + childStart = r.pos + else + childStart = r.pos + end + if r.err then + t.entryBoxes = {} + return + end + local kids = Box.list(b, childStart, e.stop, typ) + t.entryBoxes = kids + -- QuickTime puts the codec boxes inside 'wave' + local all = table.clone(kids) + local wave = Box.child({ type = "", start = 0, size = 0, data = 0, stop = 0, children = kids } :: any, "wave") + if wave and wave.children then + for _, c in wave.children :: { Box.Box } do + table.insert(all, c) + end + end + local holder = { type = "", start = 0, size = 0, data = 0, stop = 0, children = all } :: any + local esds = Box.child(holder, "esds") + if esds then + local oti, dsi, avg = Demux.esds(b, esds) + t.objectType = oti + if oti and OTI[oti] then + t.codec = OTI[oti] + end + t.config = dsi + if avg and avg > 0 then + t.bitrate = avg + end + end + if typ == "alac" then + local a = Box.child(holder, "alac") + if a then + t.config = payload(b, a, 4) + end + end + for _, name in CONFIG_BOX do + local c = Box.child(holder, name) + if c then + t.config = payload(b, c, if FULL_CONFIG[name] then 4 else 0) + break + end + end +end + +-- media handler / header / sample tables of one trak -> Track | nil, Err +local function track(b: buffer, trak: Box.Box, movieTimescale: number, trex: { [number]: any }, o: Options): (Track?, Err.Err?) + local tkhd = Box.child(trak, "tkhd") + local mdia = Box.child(trak, "mdia") + if not tkhd or not mdia then + return nil, Err.new(Err.CORRUPT, "trak without tkhd / mdia", trak.start) + end + local t: Track = { + id = 0, kind = "data", codec = "", entry = "", handler = "", timescale = 1, duration = 0, mediaDuration = 0, + entryBoxes = {}, skip = 0, delay = 0, sampleCount = 0, offsets = {}, sizes = {}, dts = {}, durations = {}, + } + do + local r = reader(b, tkhd) + local v = r:u8() + r:skip(3) + if v == 1 then + r:skip(16) + t.id = r:u32be() + r:skip(4 + 8) + else + r:skip(8) + t.id = r:u32be() + r:skip(4 + 4) + end + r:skip(8 + 2 + 2 + 2 + 2 + 36) + local w, h = r:u32be() / 65536, r:u32be() / 65536 + if r.err then + return nil, r.err + end + if w > 0 and h > 0 then + t.width, t.height = math.floor(w), math.floor(h) + end + end + local mdhd = Box.child(mdia, "mdhd") + if mdhd then + local r = reader(b, mdhd) + local v = r:u8() + r:skip(3) + if v == 1 then + r:skip(16) + t.timescale = r:u32be() + t.mediaDuration = r:u64be() + else + r:skip(8) + t.timescale = r:u32be() + t.mediaDuration = r:u32be() + end + local lang = r:u16be() + if not r.err and lang ~= 0 and lang ~= 0x7FFF then + t.language = string.char( + 96 + bit32.band(bit32.rshift(lang, 10), 31), + 96 + bit32.band(bit32.rshift(lang, 5), 31), + 96 + bit32.band(lang, 31) + ) + end + if t.timescale == 0 then + t.timescale = 1 + end + end + local hdlr = Box.child(mdia, "hdlr") + if hdlr and hdlr.data + 12 <= hdlr.stop then + t.handler = readstring(b, hdlr.data + 8, 4) + end + t.kind = HANDLER_KIND[t.handler] or "data" + local stbl = Box.path(mdia, "minf/stbl") + if not stbl then + return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " has no sample table", mdia.start) + end + -- sample descriptions + local stsd = Box.child(stbl, "stsd") + if stsd and stsd.data + 8 <= stsd.stop then + local entries = Box.list(b, stsd.data + 8, stsd.stop, "stsd") + if entries[1] then + sampleEntry(b, entries[1], t.handler, t) + end + t.sampleEntries = entries + end + -- edit list + local elst = Box.path(trak, "edts/elst") + if elst then + local r = reader(b, elst) + local v = r:u8() + r:skip(3) + local n = r:u32be() + if n <= (elst.stop - elst.data) // 12 then + local edits = {} + for _ = 1, n do + local dur, mt + if v == 1 then + dur, mt = r:u64be(), r:i64be() + else + dur, mt = r:u32be(), r:i32be() + end + local rate = r:i32be() / 65536 + if r.err then + break + end + table.insert(edits, { duration = dur, mediaTime = mt, rate = rate }) + end + t.edits = edits + local play = 0 + local started = false + for _, ed in edits do + if ed.mediaTime == -1 then + if not started then + t.delay += ed.duration + end + else + if not started then + t.skip = ed.mediaTime + started = true + end + play += ed.duration * t.timescale / math.max(1, movieTimescale) + end + end + if started and play > 0 then + t.playDuration = math.floor(play + 0.5) + end + end + end + -- sample sizes + local maxSamples = o.maxSamples or 2 ^ 25 + local sizes = t.sizes + local count = 0 + local stsz = Box.child(stbl, "stsz") + local stz2 = Box.child(stbl, "stz2") + if stsz then + local r = reader(b, stsz) + r:skip(4) + local fixed = r:u32be() + count = r:u32be() + if r.err then + return nil, r.err + end + if count > maxSamples then + return nil, Err.new(Err.LIMIT, string.format("track %d has %d samples (limit %d)", t.id, count, maxSamples), stsz.start) + end + if fixed ~= 0 then + for i = 1, count do + sizes[i] = fixed + end + else + if count * 4 > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "stsz table runs past its box", stsz.start) + end + for i = 1, count do + sizes[i] = r:u32be() + end + end + elseif stz2 then + local r = reader(b, stz2) + r:skip(4 + 3) + local fieldSize = r:u8() + count = r:u32be() + if r.err then + return nil, r.err + end + if fieldSize ~= 4 and fieldSize ~= 8 and fieldSize ~= 16 then + return nil, Err.new(Err.CORRUPT, "bad stz2 field size " .. fieldSize, stz2.start) + end + if count * fieldSize / 8 > r:remaining() + 1 then + return nil, Err.new(Err.TRUNCATED, "stz2 table runs past its box", stz2.start) + end + for i = 1, count do + if fieldSize == 16 then + sizes[i] = r:u16be() + elseif fieldSize == 8 then + sizes[i] = r:u8() + else + local byte = r:peekU8() + if i % 2 == 1 then + sizes[i] = bit32.rshift(math.max(byte, 0), 4) + else + sizes[i] = bit32.band(math.max(byte, 0), 15) + r:skip(1) + end + end + end + end + -- decode times + local dts, durs = t.dts, t.durations + local stts = Box.child(stbl, "stts") + if stts and count > 0 then + local r = reader(b, stts) + r:skip(4) + local n = r:u32be() + if n * 8 > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "stts table runs past its box", stts.start) + end + local i, time = 1, 0 + for _ = 1, n do + local c, d = r:u32be(), r:u32be() + for _ = 1, c do + if i > count then + break + end + dts[i], durs[i] = time, d + time += d + i += 1 + end + end + -- fewer stts entries than samples: repeat the last duration + local last = if i > 1 then durs[i - 1] else 0 + while i <= count do + dts[i], durs[i] = time, last + time += last + i += 1 + end + else + for i = 1, count do + dts[i], durs[i] = 0, 0 + end + end + -- composition offsets + local ctts = Box.child(stbl, "ctts") + if ctts and count > 0 then + local r = reader(b, ctts) + local v = r:u8() + r:skip(3) + local n = r:u32be() + if n * 8 <= r:remaining() then + local cts = table.create(count, 0) + local i = 1 + for _ = 1, n do + local c = r:u32be() + local off = if v == 1 then r:i32be() else r:u32be() + if v == 0 and off >= 2147483648 then + off -= 4294967296 -- writers put negative offsets in version 0 too + end + for _ = 1, c do + if i > count then + break + end + cts[i] = off + i += 1 + end + end + t.cts = cts + end + end + -- sync samples + local stss = Box.child(stbl, "stss") + if stss then + local r = reader(b, stss) + r:skip(4) + local n = r:u32be() + if n * 4 <= r:remaining() then + local sync = {} + for _ = 1, n do + sync[r:u32be()] = true + end + t.sync = sync + end + end + -- chunk offsets + sample-to-chunk -> sample offsets + local stco = Box.child(stbl, "stco") + local co64 = Box.child(stbl, "co64") + local chunks: { number } = {} + if stco or co64 then + local box = (stco or co64) :: Box.Box + local r = reader(b, box) + r:skip(4) + local n = r:u32be() + local w = if co64 then 8 else 4 + if n * w > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "chunk offset table runs past its box", box.start) + end + for i = 1, n do + chunks[i] = if co64 then r:u64be() else r:u32be() + end + end + local stsc = Box.child(stbl, "stsc") + local offsets = t.offsets + if count > 0 then + if not stsc or #chunks == 0 then + return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " has samples but no stsc / stco", stbl.start) + end + local r = reader(b, stsc) + r:skip(4) + local n = r:u32be() + if n * 12 > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "stsc table runs past its box", stsc.start) + end + local first, per, desc = {}, {}, {} + for k = 1, n do + first[k], per[k], desc[k] = r:u32be(), r:u32be(), r:u32be() + end + local sdi: { number }? = nil + if n > 0 then + for k = 1, n do + if desc[k] ~= desc[1] then + sdi = table.create(count, 1) + end + end + end + local i = 1 + local base = 0 -- added by the caller (the file's offset in the buffer) + for k = 1, n do + local c0 = first[k] + local c1 = if k < n then first[k + 1] - 1 else #chunks + if c0 < 1 then + return nil, Err.new(Err.CORRUPT, "stsc first chunk 0", stsc.start) + end + for c = c0, math.min(c1, #chunks) do + local off = chunks[c] + base + for _ = 1, per[k] do + if i > count then + break + end + offsets[i] = off + if sdi then + sdi[i] = desc[k] + end + off += sizes[i] + i += 1 + end + if i > count then + break + end + end + if i > count then + break + end + end + if i <= count then + return nil, Err.new(Err.CORRUPT, string.format("track %d: the chunks hold %d of %d samples", t.id, i - 1, count), stsc.start) + end + t.sampleDescription = sdi + end + t.sampleCount = count + -- QuickTime PCM: one "sample" per sample frame (constant size, duration 1). Regroup into packets of up to 1024 + -- frames within each chunk (as ffmpeg does), so a packet is a useful amount of audio. + if t.kind == "audio" and count > 1 and not t.cts and not t.sync then + local fixed = sizes[1] + local uniform = fixed > 0 + for i = 1, count do + if sizes[i] ~= fixed or durs[i] ~= 1 then + uniform = false + break + end + end + if uniform then + local no, ns, nd, nu = {}, {}, {}, {} + local i = 1 + while i <= count do + local k = 1 + while k < 1024 and i + k <= count and offsets[i + k] == offsets[i] + k * fixed do + k += 1 + end + table.insert(no, offsets[i]) + table.insert(ns, k * fixed) + table.insert(nd, dts[i]) + table.insert(nu, k) + i += k + end + t.offsets, t.sizes, t.dts, t.durations = no, ns, nd, nu + t.sampleCount = #no + t.frameSize = fixed + t.sampleDescription = nil + end + end + -- fragment defaults + t.trex = trex[t.id] + return t, nil +end + +-- the movie fragments (moof) after the moov: appends their samples to the tracks +local function fragments(b: buffer, fileBase: number, top: { Box.Box }, byId: { [number]: Track }, o: Options): Err.Err? + local maxSamples = o.maxSamples or 2 ^ 25 + for _, moof in top do + if moof.type ~= "moof" then + continue + end + local moofStart = moof.start - fileBase -- file offsets (r.base is added at the end) + local prevEnd = moofStart + for _, traf in Box.childrenOf(moof, "traf") do + local tfhd = Box.child(traf, "tfhd") + if not tfhd then + continue + end + local r = reader(b, tfhd) + r:skip(1) + local flags = r:u24be() + local id = r:u32be() + local t = byId[id] + if r.err or not t then + continue + end + local trex = t.trex or {} + local base + if bit32.band(flags, 0x1) ~= 0 then + base = r:u64be() + elseif bit32.band(flags, 0x20000) ~= 0 then + base = moofStart + else + base = prevEnd + end + if bit32.band(flags, 0x2) ~= 0 then + r:skip(4) + end + local defDur = if bit32.band(flags, 0x8) ~= 0 then r:u32be() else (trex.duration or 0) + local defSize = if bit32.band(flags, 0x10) ~= 0 then r:u32be() else (trex.size or 0) + local defFlags = if bit32.band(flags, 0x20) ~= 0 then r:u32be() else (trex.flags or 0) + if r.err then + return r.err + end + local n0 = t.sampleCount + local time = if n0 > 0 then t.dts[n0] + t.durations[n0] else 0 + local tfdt = Box.child(traf, "tfdt") + if tfdt then + local q = reader(b, tfdt) + local v = q:u8() + q:skip(3) + local bt = if v == 1 then q:u64be() else q:u32be() + if not q.err then + time = bt + end + end + local dataPos = base + for _, trun in Box.childrenOf(traf, "trun") do + local q = reader(b, trun) + local v = q:u8() + local tf = q:u24be() + local n = q:u32be() + if q.err then + return q.err + end + if t.sampleCount + n > maxSamples then + return Err.new(Err.LIMIT, "too many fragment samples", trun.start) + end + if bit32.band(tf, 0x1) ~= 0 then + dataPos = base + q:i32be() + end + local firstFlags = if bit32.band(tf, 0x4) ~= 0 then q:u32be() else nil + local per = 0 + for _, bit in { 0x100, 0x200, 0x400, 0x800 } do + if bit32.band(tf, bit) ~= 0 then + per += 4 + end + end + if n * per > q:remaining() then + return Err.new(Err.TRUNCATED, "trun table runs past its box", trun.start) + end + for k = 1, n do + local dur = if bit32.band(tf, 0x100) ~= 0 then q:u32be() else defDur + local size = if bit32.band(tf, 0x200) ~= 0 then q:u32be() else defSize + local sf = if bit32.band(tf, 0x400) ~= 0 then q:u32be() else (if k == 1 and firstFlags then firstFlags else defFlags) + local cto = 0 + if bit32.band(tf, 0x800) ~= 0 then + cto = if v == 1 then q:i32be() else q:u32be() + end + local i = t.sampleCount + 1 + t.sampleCount = i + t.offsets[i] = dataPos + t.sizes[i] = size + t.dts[i] = time + t.durations[i] = dur + if cto ~= 0 or t.cts then + if not t.cts then + t.cts = table.create(i - 1, 0) + end + (t.cts :: { number })[i] = cto + end + -- sample_is_non_sync_sample (bit 16) + local nonSync = bit32.band(sf, 0x10000) ~= 0 + if nonSync then + if not t.sync then + local s = {} + for j = 1, i - 1 do + s[j] = true + end + t.sync = s + end + elseif t.sync then + (t.sync :: any)[i] = true + end + time += dur + dataPos += size + end + prevEnd = dataPos + end + end + end + return nil +end + +export type Movie = { + brand: string?, + minor: number?, + compatible: { string }, + timescale: number, + duration: number, -- seconds + tracks: { Track }, + boxes: { Box.Box }, + moov: Box.Box?, + fragmented: boolean, +} + +-- parse(r, opts) -> Movie | nil, Err: the box tree, ftyp, mvhd and every track (fragments included) +function Demux.parse(r: Bytes.Reader, opts: Options?): (Movie?, Err.Err?) + local o = opts or {} + local b = r.buf + local top, terr = Box.list(b, r.base, r.limit) + if #top == 0 then + return nil, terr or Err.new(Err.CORRUPT, "no boxes", r.base) + end + local m: Movie = { compatible = {}, timescale = 1000, duration = 0, tracks = {}, boxes = top, fragmented = false } + local ftyp = Box.child({ children = top } :: any, "ftyp") + if ftyp and ftyp.data + 8 <= ftyp.stop then + m.brand = readstring(b, ftyp.data, 4) + m.minor = Box.be32(b, ftyp.data + 4) + local p = ftyp.data + 8 + while p + 4 <= ftyp.stop do + table.insert(m.compatible, readstring(b, p, 4)) + p += 4 + end + end + local moov = Box.child({ children = top } :: any, "moov") + m.moov = moov + if not moov then + return m, nil -- an image file (HEIF / AVIF) or a fragment: no tracks + end + local mvhd = Box.child(moov, "mvhd") + local movieDuration = 0 + if mvhd then + local q = reader(b, mvhd) + local v = q:u8() + q:skip(3) + if v == 1 then + q:skip(16) + m.timescale = q:u32be() + movieDuration = q:u64be() + else + q:skip(8) + m.timescale = q:u32be() + movieDuration = q:u32be() + end + if q.err or m.timescale == 0 then + m.timescale = 1000 + end + end + local trex = {} + local mvex = Box.child(moov, "mvex") + if mvex then + m.fragmented = true + for _, x in Box.childrenOf(mvex, "trex") do + local q = reader(b, x) + q:skip(4) + local id = q:u32be() + q:skip(4) + local d = { duration = q:u32be(), size = q:u32be(), flags = q:u32be() } + if not q.err then + trex[id] = d + end + end + end + local byId = {} + for _, trak in Box.childrenOf(moov, "trak") do + local t, err = track(b, trak, m.timescale, trex, o) + if not t then + return nil, err + end + table.insert(m.tracks, t) + byId[t.id] = t + end + if m.fragmented then + local ferr = fragments(b, r.base, top, byId, o) + if ferr then + return nil, ferr + end + end + -- durations; drop samples outside the buffer (a truncated file) but keep what is there + for _, t in m.tracks do + local n = t.sampleCount + local ticks = t.mediaDuration + if n > 0 then + ticks = math.max(ticks, t.dts[n] + t.durations[n]) + end + t.mediaDuration = ticks + t.duration = ticks / t.timescale + for i = 1, n do + local off = t.offsets[i] + if off < 0 or off + t.sizes[i] > r.limit - r.base then + t.sampleCount = i - 1 + t.truncated = true + break + end + end + -- the tables hold file offsets; make them buffer offsets + local base = r.base + if base ~= 0 then + local offs = t.offsets + for i = 1, t.sampleCount do + offs[i] += base + end + end + end + m.duration = movieDuration / m.timescale + if m.duration == 0 then + for _, t in m.tracks do + m.duration = math.max(m.duration, t.duration) + end + end + return m, nil +end + +return Demux diff --git a/src/Formats/containers/IsoBmff/Meta.luau b/src/Formats/containers/IsoBmff/Meta.luau new file mode 100644 index 0000000..a7c44ca --- /dev/null +++ b/src/Formats/containers/IsoBmff/Meta.luau @@ -0,0 +1,526 @@ +--!strict +-- containers/IsoBmff/Meta: the metadata boxes. HEIF / AVIF items (ISO/IEC 23008-12: pitm, iinf / infe, iloc +-- versions 0 - 2, iref, iprp / ipco / ipma, idat; the common properties ispe / pixi / colr / irot / imir / clap / auxC +-- decoded, codec configurations av1C / hvcC / avcC kept raw) and the iTunes tags (udta / meta / ilst: text, trkn / +-- disk, tmpo / cpil, gnre, covr pictures, '----' freeform), plus the ilst writer used by the muxer. +-- Never throws. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Box = require("@formats/containers/IsoBmff/Box") + +local readstring = buffer.readstring + +local Meta = {} + +local function reader(b: buffer, box: Box.Box): Bytes.Reader + return Bytes.reader(b, box.data, box.stop - box.data) +end + +local function uint(r: Bytes.Reader, size: number): number + if size == 0 then + return 0 + elseif size == 4 then + return r:u32be() + elseif size == 8 then + return r:u64be() + elseif size == 2 then + return r:u16be() + elseif size == 1 then + return r:u8() + end + r:fail(Err.CORRUPT, "bad iloc field size " .. size) + return 0 +end + +-- ------------------------------------------------------------------------------------------------ HEIF items +export type Property = { type: string, box: Box.Box, [string]: any } +export type Item = { + id: number, + type: string, -- "av01", "hvc1", "grid", "Exif", "mime", ... + name: string, + contentType: string?, + hidden: boolean, + construction: number, -- iloc construction method (0 file offset, 1 idat, 2 item) + baseOffset: number, + extents: { { offset: number, length: number } }, + properties: { Property }, -- in ipma order + essential: { [number]: boolean }, -- by index into properties + refs: { [string]: { number } }, -- iref type -> item ids (dimg, thmb, auxl, cdsc, ...) +} +export type Items = { + primary: number?, + items: { [number]: Item }, + order: { number }, -- item ids in iinf order + idat: Box.Box?, + properties: { Property }, -- ipco, in order +} + +local function property(b: buffer, box: Box.Box): Property + local p: Property = { type = box.type, box = box } + local r = reader(b, box) + local t = box.type + if t == "ispe" then + r:skip(4) + p.width, p.height = r:u32be(), r:u32be() + elseif t == "pixi" then + r:skip(4) + local n = r:u8() + local bits = {} + for i = 1, math.min(n, 16) do + bits[i] = r:u8() + end + p.bits = bits + elseif t == "colr" then + local ct = r:string(4) + p.colourType = ct + if ct == "nclx" then + p.primaries, p.transfer, p.matrix = r:u16be(), r:u16be(), r:u16be() + p.fullRange = bit32.band(r:u8(), 0x80) ~= 0 + elseif ct == "rICC" or ct == "prof" then + p.icc = r:bytes(r:remaining()) + end + elseif t == "irot" then + p.angle = bit32.band(r:u8(), 3) * 90 + elseif t == "imir" then + p.axis = bit32.band(r:u8(), 1) + elseif t == "clap" then + local function frac(): number + local n, d = r:i32be(), r:u32be() + return if d == 0 then 0 else n / d + end + p.width, p.height, p.horizOff, p.vertOff = frac(), frac(), frac(), frac() + elseif t == "auxC" then + r:skip(4) + p.auxType = r:cstring() + else + local n = box.stop - box.data + local cfg = buffer.create(math.max(0, n)) + if n > 0 then + buffer.copy(cfg, 0, b, box.data, n) + end + p.config = cfg + end + return p +end + +-- items(buf, meta) -> Items | nil, Err (meta: a top-level 'meta' box) +function Meta.items(b: buffer, meta: Box.Box): (Items?, Err.Err?) + local out: Items = { items = {}, order = {}, properties = {} } + local pitm = Box.child(meta, "pitm") + if pitm then + local r = reader(b, pitm) + local v = r:u8() + r:skip(3) + out.primary = if v == 0 then r:u16be() else r:u32be() + end + local iinf = Box.child(meta, "iinf") + if iinf then + for _, infe in Box.childrenOf(iinf, "infe") do + local r = reader(b, infe) + local v = r:u8() + local flags = r:u24be() + local it: Item = { + id = 0, type = "", name = "", hidden = bit32.band(flags, 1) ~= 0, construction = 0, baseOffset = 0, + extents = {}, properties = {}, essential = {}, refs = {}, + } + if v >= 2 then + it.id = if v == 2 then r:u16be() else r:u32be() + r:skip(2) + it.type = r:string(4) + it.name = r:cstring() + if it.type == "mime" and r:remaining() > 0 then + it.contentType = r:cstring() + end + else + it.id = r:u16be() + r:skip(2) + it.name = r:cstring() + it.contentType = r:cstring() + it.type = "mime" + end + if r.err and it.id == 0 then + return nil, r.err + end + out.items[it.id] = it + table.insert(out.order, it.id) + end + end + local iloc = Box.child(meta, "iloc") + if iloc then + local r = reader(b, iloc) + local v = r:u8() + r:skip(3) + local a, c = r:u8(), r:u8() + local offSize, lenSize, baseSize = bit32.rshift(a, 4), bit32.band(a, 15), bit32.rshift(c, 4) + local idxSize = if v >= 1 then bit32.band(c, 15) else 0 + local n = if v < 2 then r:u16be() else r:u32be() + if r.err then + return nil, r.err + end + for _ = 1, n do + local id = if v < 2 then r:u16be() else r:u32be() + local method = 0 + if v >= 1 then + method = bit32.band(r:u16be(), 15) + end + r:skip(2) -- data reference index + local base = uint(r, baseSize) + local ne = r:u16be() + if r.err then + return nil, r.err + end + if ne * (offSize + lenSize + idxSize) > r:remaining() then + return nil, Err.new(Err.TRUNCATED, "iloc extents run past the box", iloc.start) + end + local extents = {} + for k = 1, ne do + if idxSize > 0 then + uint(r, idxSize) + end + extents[k] = { offset = base + uint(r, offSize), length = uint(r, lenSize) } + end + if r.err then + return nil, r.err + end + local it = out.items[id] + if not it then + it = { + id = id, type = "", name = "", hidden = false, construction = 0, baseOffset = 0, extents = {}, + properties = {}, essential = {}, refs = {}, + } + out.items[id] = it + table.insert(out.order, id) + end + it.construction, it.baseOffset, it.extents = method, base, extents + end + end + local iref = Box.child(meta, "iref") + if iref then + local v = Box.fullHeader(b, iref) + for _, ref in (iref.children or {}) :: { Box.Box } do + local r = reader(b, ref) + local from = if v == 0 then r:u16be() else r:u32be() + local n = r:u16be() + local to = {} + for k = 1, n do + to[k] = if v == 0 then r:u16be() else r:u32be() + end + local it = out.items[from] + if it and not r.err then + it.refs[ref.type] = to + end + end + end + local ipco = Box.path(meta, "iprp/ipco") + if ipco and ipco.children then + for i, pb in ipco.children :: { Box.Box } do + out.properties[i] = property(b, pb) + end + end + local ipma = Box.path(meta, "iprp/ipma") + if ipma then + local r = reader(b, ipma) + local v = r:u8() + local flags = r:u24be() + local n = r:u32be() + for _ = 1, n do + if r.err then + break + end + local id = if v < 1 then r:u16be() else r:u32be() + local na = r:u8() + local it = out.items[id] + for _ = 1, na do + local idx, ess + if bit32.band(flags, 1) ~= 0 then + local x = r:u16be() + idx, ess = bit32.band(x, 0x7FFF), x >= 0x8000 + else + local x = r:u8() + idx, ess = bit32.band(x, 0x7F), x >= 0x80 + end + local p = out.properties[idx] + if it and p and not r.err then + table.insert(it.properties, p) + if ess then + it.essential[#it.properties] = true + end + end + end + end + end + out.idat = Box.child(meta, "idat") + return out, nil +end + +-- itemData(buf, base, limit, items, id) -> buffer | nil, Err: the item's bytes (extents concatenated); base / limit +-- bound the file in the buffer +function Meta.itemData(b: buffer, base: number, limit: number, items: Items, id: number): (buffer?, Err.Err?) + local it = items.items[id] + if not it then + return nil, Err.new(Err.CORRUPT, "no item " .. id) + end + local origin, stop + if it.construction == 0 then + origin, stop = base, limit + elseif it.construction == 1 then + local idat = items.idat + if not idat then + return nil, Err.new(Err.CORRUPT, "item " .. id .. " is in a missing idat") + end + origin, stop = idat.data, idat.stop + else + return nil, Err.new(Err.UNSUPPORTED, "item construction method " .. it.construction) + end + local total = 0 + for _, e in it.extents do + local len = e.length + if len == 0 then -- the whole rest of the file + len = stop - origin - e.offset + end + if e.offset < 0 or len < 0 or origin + e.offset + len > stop then + return nil, Err.new(Err.TRUNCATED, "item " .. id .. " runs past the end") + end + total += len + end + if total > 2 ^ 30 then + return nil, Err.new(Err.LIMIT, "item " .. id .. " is too big") + end + local out = buffer.create(total) + local p = 0 + for _, e in it.extents do + local len = if e.length == 0 then stop - origin - e.offset else e.length + buffer.copy(out, p, b, origin + e.offset, len) + p += len + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ iTunes tags +-- ilst item -> standard tag name +local TAG: { [string]: string } = { + ["\169nam"] = "title", ["\169ART"] = "artist", aART = "albumartist", ["\169alb"] = "album", ["\169day"] = "date", + ["\169gen"] = "genre", ["\169cmt"] = "comment", ["\169wrt"] = "composer", ["\169too"] = "encoder", + ["\169lyr"] = "lyrics", ["\169grp"] = "grouping", cprt = "copyright", desc = "description", ldes = "longdescription", + sonm = "titlesort", soar = "artistsort", soal = "albumsort", soaa = "albumartistsort", soco = "composersort", + tvsh = "show", ["\169st3"] = "subtitle", ["\169wrk"] = "work", ["\169mvn"] = "movement", purd = "purchasedate", + ["\169pub"] = "publisher", ["\169xyz"] = "location", +} +local TAG_ATOM: { [string]: string } = {} +for atom, name in TAG do + TAG_ATOM[name] = atom +end +Meta.TAG = TAG +Meta.TAG_ATOM = TAG_ATOM + +-- the ID3v1 genres gnre indexes (1-based in gnre) +local GENRES = { + "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge", "Hip-Hop", "Jazz", "Metal", "New Age", + "Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative", "Ska", + "Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk", "Fusion", + "Trance", "Classical", "Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise", "AlternRock", + "Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop", "Instrumental Rock", "Ethnic", "Gothic", + "Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock", "Comedy", "Cult", + "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret", "New Wave", + "Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka", "Retro", + "Musical", "Rock & Roll", "Hard Rock", +} + +export type Picture = { mime: string, data: buffer } + +-- tags(buf, ilst) -> Tags, { Picture } +function Meta.tags(b: buffer, ilst: Box.Box?): ({ [string]: string }, { Picture }) + local tags: { [string]: string } = {} + local pics: { Picture } = {} + if not ilst or not ilst.children then + return tags, pics + end + for _, item in ilst.children :: { Box.Box } do + local typ = item.type + local freeName: string? = nil + if typ == "----" then + local nm = Box.child(item, "name") + if nm and nm.data + 4 <= nm.stop then + freeName = readstring(b, nm.data + 4, nm.stop - nm.data - 4) + end + end + for _, d in Box.childrenOf(item, "data") do + if d.data + 8 > d.stop then + continue + end + local kind = bit32.band(Box.be32(b, d.data), 0xFFFFFF) + local p, n = d.data + 8, d.stop - d.data - 8 + if typ == "trkn" or typ == "disk" then + if n >= 6 then + local num = Box.be32(b, p) % 65536 + local total = Box.be32(b, p + 2) % 65536 + local key = if typ == "trkn" then "track" else "disc" + if num > 0 then + tags[key] = tostring(num) + end + if total > 0 then + tags[key .. "total"] = tostring(total) + end + end + elseif typ == "gnre" then + if n >= 2 then + local g = GENRES[Box.be32(b, p - 2) % 65536] + if g and not tags.genre then + tags.genre = g + end + end + elseif typ == "tmpo" then + if n >= 2 then + tags.bpm = tostring(Box.be32(b, p - 2) % 65536) + end + elseif typ == "cpil" or typ == "pgap" then + if n >= 1 then + tags[if typ == "cpil" then "compilation" else "gapless"] = tostring(buffer.readu8(b, p)) + end + elseif typ == "covr" then + local mime = if kind == 14 then "image/png" elseif kind == 27 then "image/bmp" else "image/jpeg" + local data = buffer.create(n) + buffer.copy(data, 0, b, p, n) + table.insert(pics, { mime = mime, data = data }) + elseif kind == 1 or kind == 0 then + local s = readstring(b, p, n) + local key = freeName or TAG[typ] or typ + if typ == "\169gen" or not tags[key] then + tags[key] = s + end + end + end + end + return tags, pics +end + +-- ------------------------------------------------------------------------------------------------ ilst writer +local function box(w: Bytes.Writer, typ: string, body: (Bytes.Writer) -> ()) + local start = w:tell() + w:u32be(0) + w:string(typ) + body(w) + w:setU32be(start, w:tell() - start) +end +Meta.box = box + +local function dataBox(w: Bytes.Writer, kind: number, value: string | buffer) + box(w, "data", function() + w:u32be(kind) + w:u32be(0) + if type(value) == "string" then + w:string(value) + else + w:bytes(value) + end + end) +end + +local function num(s: string?): number + local v = tonumber(s or "") + if not v then + return 0 + end + return math.clamp(math.floor(v), 0, 65535) +end + +-- writeIlst(w, tags, pictures?): an ilst box with the tags (standard names -> iTunes atoms; unknown names -> '----' +-- freeform com.apple.iTunes items) and cover pictures +function Meta.writeIlst(w: Bytes.Writer, tags: { [string]: string }, pictures: { Picture }?) + box(w, "ilst", function() + local keys = {} + for k in tags do + table.insert(keys, k) + end + table.sort(keys) + local done: { [string]: boolean } = {} + for _, k in keys do + local v = tags[k] + if type(v) ~= "string" or done[k] then + continue + end + if k == "track" or k == "tracktotal" or k == "disc" or k == "disctotal" then + local base = if k == "track" or k == "tracktotal" then "track" else "disc" + if done[base] then + continue + end + done[base] = true + local atom = if base == "track" then "trkn" else "disk" + local n, total = num(tags[base]), num(tags[base .. "total"]) + box(w, atom, function() + box(w, "data", function() + w:u32be(0) + w:u32be(0) + w:u16be(0) + w:u16be(n) + w:u16be(total) + if atom == "trkn" then + w:u16be(0) + end + end) + end) + elseif k == "bpm" then + box(w, "tmpo", function() + box(w, "data", function() + w:u32be(21) + w:u32be(0) + w:u16be(num(v)) + end) + end) + elseif k == "compilation" or k == "gapless" then + box(w, if k == "compilation" then "cpil" else "pgap", function() + box(w, "data", function() + w:u32be(21) + w:u32be(0) + w:u8(if num(v) ~= 0 then 1 else 0) + end) + end) + elseif TAG_ATOM[k] then + box(w, TAG_ATOM[k], function() + dataBox(w, 1, v) + end) + else + box(w, "----", function() + box(w, "mean", function() + w:u32be(0) + w:string("com.apple.iTunes") + end) + box(w, "name", function() + w:u32be(0) + w:string(k) + end) + dataBox(w, 1, v) + end) + end + done[k] = true + end + if pictures and #pictures > 0 then + box(w, "covr", function() + for _, p in pictures do + dataBox(w, if p.mime == "image/png" then 14 elseif p.mime == "image/bmp" then 27 else 13, p.data) + end + end) + end + end) +end + +-- writeUdta(w, tags, pictures?): udta / meta (hdlr mdir) / ilst +function Meta.writeUdta(w: Bytes.Writer, tags: { [string]: string }, pictures: { Picture }?) + box(w, "udta", function() + box(w, "meta", function() + w:u32be(0) + box(w, "hdlr", function() + w:u32be(0) + w:u32be(0) + w:string("mdir") + w:string("appl") + w:u32be(0) + w:u32be(0) + w:u8(0) + end) + Meta.writeIlst(w, tags, pictures) + end) + end) +end + +return Meta diff --git a/src/Formats/containers/IsoBmff/Mux.luau b/src/Formats/containers/IsoBmff/Mux.luau new file mode 100644 index 0000000..299cc44 --- /dev/null +++ b/src/Formats/containers/IsoBmff/Mux.luau @@ -0,0 +1,519 @@ +--!strict +-- containers/IsoBmff/Mux: writes a progressive (non-fragmented) ISO BMFF / MP4 / M4A file: ftyp, moov (mvhd, one trak +-- per track with tkhd / edts / mdia / mdhd / hdlr / minf / [sv]mhd / dinf / stbl), the samples interleaved in chunks +-- in one mdat, and udta / meta / ilst tags. moov goes first ("fast start"); co64 replaces stco past 4 GB. Sample +-- entries: audio (mp4a + esds, alac, Opus + dOps, fLaC + dfLa, ...) and video (avc1 / hvc1 / av01 / vp09 / ... + +-- their configuration box), plus any raw child boxes. Never throws: bad specs return nil, Err.ARG. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Meta = require("@formats/containers/IsoBmff/Meta") + +local Mux = {} + +export type MuxTrack = { + kind: "audio" | "video" | "subtitle" | "data", + entry: string, -- sample entry fourcc: "alac", "mp4a", "Opus", "fLaC", "avc1", "hvc1", "av01", "vp09", ... + timescale: number, -- ticks per second (audio: the sample rate) + samples: { buffer }?, -- one buffer per sample, or + data: buffer?, -- the samples back to back, with + sizes: { number }?, -- their sizes + durations: { number } | number, -- ticks per sample (or one constant) + cts: { number }?, -- composition offsets (video with B-frames) + sync: { [number]: boolean }?, -- sync samples (nil: all) + sampleRate: number?, + channels: number?, + bitsPerSample: number?, -- default 16 + width: number?, + height: number?, + config: buffer?, -- the codec configuration, written as the entry's configuration box + configBox: string?, -- its box type (default by entry: esds, alac, dOps, dfLa, avcC, hvcC, av1C, vpcC) + objectType: number?, -- esds objectTypeIndication (default 0x40, AAC) + bitrate: number?, -- esds average bitrate + boxes: { { type: string, data: buffer } }?, -- extra sample entry child boxes (raw payloads) + language: string?, -- ISO 639-2, default "und" + name: string?, -- hdlr name + skip: number?, -- media ticks to skip at the start (edit list media time: AAC priming) + playDuration: number?, -- media ticks to play (edit list) +} +export type MuxSpec = { + brand: string?, -- default "isom" + minor: number?, + compatible: { string }?, + timescale: number?, -- movie timescale, default 1000 + tracks: { MuxTrack }, + tags: { [string]: string }?, + pictures: { Meta.Picture }?, + chunkDuration: number?, -- seconds of samples per chunk, default 1 +} + +local DEFAULT_CONFIG_BOX: { [string]: string } = { + mp4a = "esds", mp4v = "esds", alac = "alac", Opus = "dOps", fLaC = "dfLa", avc1 = "avcC", avc3 = "avcC", + hvc1 = "hvcC", hev1 = "hvcC", av01 = "av1C", vp08 = "vpcC", vp09 = "vpcC", ["ac-3"] = "dac3", ["ec-3"] = "dec3", +} +local FULL_BOX: { [string]: boolean } = { alac = true, dfLa = true, vpcC = true } +local HANDLER = { audio = "soun", video = "vide", subtitle = "sbtl", data = "meta" } + +local box = Meta.box + +local function lang(s: string?): number + local l = s or "und" + if #l ~= 3 then + l = "und" + end + local v = 0 + for i = 1, 3 do + v = v * 32 + bit32.band(string.byte(l, i) - 96, 31) + end + return v +end + +local function descriptor(w: Bytes.Writer, tag: number, body: (Bytes.Writer) -> ()) + local inner = Bytes.writer(64) + body(inner) + local n = inner:tell() + w:u8(tag) + -- 4-byte expandable length (the common iTunes / ffmpeg form) + w:u8(0x80 + bit32.band(bit32.rshift(n, 21), 127)) + w:u8(0x80 + bit32.band(bit32.rshift(n, 14), 127)) + w:u8(0x80 + bit32.band(bit32.rshift(n, 7), 127)) + w:u8(bit32.band(n, 127)) + w:bytes(inner.buf, 0, n) +end + +local function esds(w: Bytes.Writer, t: MuxTrack) + box(w, "esds", function() + w:u32be(0) + descriptor(w, 3, function(d) + d:u16be(0) -- ES_ID + d:u8(0) + descriptor(d, 4, function(c) + c:u8(t.objectType or 0x40) + c:u8(if t.kind == "video" then 0x11 else 0x15) -- streamType << 2 | upStream 0 | reserved 1 + c:u24be(0) + c:u32be(t.bitrate or 0) + c:u32be(t.bitrate or 0) + if t.config then + descriptor(c, 5, function(s) + s:bytes(t.config :: buffer) + end) + end + end) + descriptor(d, 6, function(s) + s:u8(2) + end) + end) + end) +end + +local function sampleEntry(w: Bytes.Writer, t: MuxTrack) + box(w, t.entry, function() + w:fill(0, 6) + w:u16be(1) -- data reference index + if t.kind == "audio" then + w:u16be(0) -- version + w:u16be(0) + w:u32be(0) + w:u16be(t.channels or 2) + w:u16be(t.bitsPerSample or 16) + w:u16be(0) + w:u16be(0) + local sr = t.sampleRate or t.timescale + w:u32be(if sr < 65536 then sr * 65536 else 0) + elseif t.kind == "video" then + w:fill(0, 16) + w:u16be(t.width or 0) + w:u16be(t.height or 0) + w:u32be(0x00480000) + w:u32be(0x00480000) + w:u32be(0) + w:u16be(1) -- frame count + w:fill(0, 32) -- compressor name + w:u16be(0x18) + w:i16be(-1) + end + local cb = t.configBox or DEFAULT_CONFIG_BOX[t.entry] + if t.config and cb then + if cb == "esds" then + esds(w, t) + else + box(w, cb, function() + if FULL_BOX[cb] then + w:u32be(0) + end + w:bytes(t.config :: buffer) + end) + end + end + for _, x in t.boxes or {} do + box(w, x.type, function() + w:bytes(x.data) + end) + end + end) +end + +type Chunk = { track: number, first: number, count: number, time: number, offset: number } + +-- runs of equal values: { { count, value } } +local function runs(n: number, value: (number) -> number): { { number } } + local out = {} + for i = 1, n do + local v = value(i) + local last = out[#out] + if last and last[2] == v then + last[1] += 1 + else + table.insert(out, { 1, v }) + end + end + return out +end + +type Prepared = { + t: MuxTrack, + n: number, + sizes: { number }, + dur: (number) -> number, + total: number, -- media ticks + chunks: { Chunk }, + sample: (number) -> (buffer, number), -- buffer, offset +} + +local function moov(w: Bytes.Writer, spec: MuxSpec, prep: { Prepared }, co64: boolean) + local mts = spec.timescale or 1000 + local function toMovie(p: Prepared, ticks: number): number + return math.floor(ticks * mts / p.t.timescale + 0.5) + end + local movieDur = 0 + for _, p in prep do + local play = p.t.playDuration or (p.total - (p.t.skip or 0)) + movieDur = math.max(movieDur, toMovie(p, play)) + end + box(w, "moov", function() + box(w, "mvhd", function() + w:u32be(0) + w:u32be(0) + w:u32be(0) + w:u32be(mts) + w:u32be(movieDur) + w:u32be(0x00010000) + w:u16be(0x0100) + w:fill(0, 10) + for _, v in { 0x00010000, 0, 0, 0, 0x00010000, 0, 0, 0, 0x40000000 } do + w:u32be(v) + end + w:fill(0, 24) + w:u32be(#prep + 1) + end) + for id, p in prep do + local t = p.t + local play = t.playDuration or (p.total - (t.skip or 0)) + box(w, "trak", function() + box(w, "tkhd", function() + w:u32be(3) -- enabled, in movie + w:u32be(0) + w:u32be(0) + w:u32be(id) + w:u32be(0) + w:u32be(toMovie(p, play)) + w:fill(0, 8) + w:u16be(0) + w:u16be(0) + w:u16be(if t.kind == "audio" then 0x0100 else 0) + w:u16be(0) + for _, v in { 0x00010000, 0, 0, 0, 0x00010000, 0, 0, 0, 0x40000000 } do + w:u32be(v) + end + w:u32be((t.width or 0) * 65536) + w:u32be((t.height or 0) * 65536) + end) + if t.skip or t.playDuration then + box(w, "edts", function() + box(w, "elst", function() + w:u32be(0) + w:u32be(1) + w:u32be(toMovie(p, play)) + w:u32be(t.skip or 0) + w:u32be(0x00010000) + end) + end) + end + box(w, "mdia", function() + box(w, "mdhd", function() + w:u32be(0) + w:u32be(0) + w:u32be(0) + w:u32be(t.timescale) + w:u32be(p.total) + w:u16be(lang(t.language)) + w:u16be(0) + end) + box(w, "hdlr", function() + w:u32be(0) + w:u32be(0) + w:string(HANDLER[t.kind] or "meta") + w:fill(0, 12) + w:cstring(t.name or (if t.kind == "audio" then "SoundHandler" elseif t.kind == "video" then "VideoHandler" else "DataHandler")) + end) + box(w, "minf", function() + if t.kind == "audio" then + box(w, "smhd", function() + w:u32be(0) + w:u32be(0) + end) + elseif t.kind == "video" then + box(w, "vmhd", function() + w:u32be(1) + w:fill(0, 8) + end) + else + box(w, "nmhd", function() + w:u32be(0) + end) + end + box(w, "dinf", function() + box(w, "dref", function() + w:u32be(0) + w:u32be(1) + box(w, "url ", function() + w:u32be(1) -- self-contained + end) + end) + end) + box(w, "stbl", function() + box(w, "stsd", function() + w:u32be(0) + w:u32be(1) + sampleEntry(w, t) + end) + local stts = runs(p.n, p.dur) + box(w, "stts", function() + w:u32be(0) + w:u32be(#stts) + for _, r in stts do + w:u32be(r[1]) + w:u32be(r[2]) + end + end) + local cts = t.cts + if cts then + local cr = runs(p.n, function(i) + return cts[i] or 0 + end) + box(w, "ctts", function() + w:u32be(0x01000000) -- version 1: signed offsets + w:u32be(#cr) + for _, r in cr do + w:u32be(r[1]) + w:i32be(r[2]) + end + end) + end + local sync = t.sync + if sync then + local list = {} + for i = 1, p.n do + if sync[i] then + table.insert(list, i) + end + end + box(w, "stss", function() + w:u32be(0) + w:u32be(#list) + for _, i in list do + w:u32be(i) + end + end) + end + local stsc = runs(#p.chunks, function(i) + return p.chunks[i].count + end) + box(w, "stsc", function() + w:u32be(0) + w:u32be(#stsc) + local c = 1 + for _, r in stsc do + w:u32be(c) + w:u32be(r[2]) + w:u32be(1) + c += r[1] + end + end) + box(w, "stsz", function() + w:u32be(0) + local fixed = p.sizes[1] or 0 + for i = 2, p.n do + if p.sizes[i] ~= fixed then + fixed = -1 + break + end + end + if fixed >= 0 and p.n > 0 then + w:u32be(fixed) + w:u32be(p.n) + else + w:u32be(0) + w:u32be(p.n) + for i = 1, p.n do + w:u32be(p.sizes[i]) + end + end + end) + box(w, if co64 then "co64" else "stco", function() + w:u32be(0) + w:u32be(#p.chunks) + for _, c in p.chunks do + if co64 then + w:u64be(c.offset) + else + w:u32be(c.offset) + end + end + end) + end) + end) + end) + end) + end + if spec.tags and next(spec.tags) or spec.pictures and #spec.pictures > 0 then + Meta.writeUdta(w, spec.tags or {}, spec.pictures) + end + end) +end + +-- mux(spec) -> buffer | nil, Err +function Mux.mux(spec: MuxSpec): (buffer?, Err.Err?) + if type(spec) ~= "table" or type(spec.tracks) ~= "table" or #spec.tracks == 0 then + return nil, Err.new(Err.ARG, "mux: expected { tracks = { ... } }") + end + local prep: { Prepared } = {} + local all: { Chunk } = {} + for k, t in spec.tracks do + if type(t) ~= "table" or type(t.entry) ~= "string" or #t.entry ~= 4 or type(t.timescale) ~= "number" or t.timescale <= 0 then + return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs a 4-character entry and a timescale") + end + if not HANDLER[t.kind] then + return nil, Err.new(Err.ARG, "mux: track " .. k .. ": bad kind " .. tostring(t.kind)) + end + local n, sizes, sample + if t.samples then + local list = t.samples + n = #list + sizes = table.create(n, 0) + for i = 1, n do + if type(list[i]) ~= "buffer" then + return nil, Err.new(Err.ARG, "mux: track " .. k .. ": sample " .. i .. " is not a buffer") + end + sizes[i] = buffer.len(list[i]) + end + sample = function(i: number): (buffer, number) + return list[i], 0 + end + elseif t.data and t.sizes then + n = #t.sizes + sizes = t.sizes + local starts = table.create(n, 0) + local o = 0 + for i = 1, n do + starts[i] = o + o += sizes[i] + end + if o > buffer.len(t.data) then + return nil, Err.new(Err.ARG, "mux: track " .. k .. ": sizes exceed the data") + end + local data = t.data + sample = function(i: number): (buffer, number) + return data, starts[i] + end + else + return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs samples or data + sizes") + end + local durs = t.durations + local dur + if type(durs) == "number" then + dur = function(_: number): number + return durs + end + elseif type(durs) == "table" then + dur = function(i: number): number + return durs[i] or 0 + end + else + return nil, Err.new(Err.ARG, "mux: track " .. k .. " needs durations") + end + local total = 0 + local chunks: { Chunk } = {} + local per = (spec.chunkDuration or 1) * t.timescale + local cur: Chunk? = nil + for i = 1, n do + if not cur or total - cur.time >= per then + cur = { track = k, first = i, count = 0, time = total, offset = 0 } + table.insert(chunks, cur :: Chunk) + table.insert(all, cur :: Chunk) + end + (cur :: Chunk).count += 1 + total += dur(i) + end + prep[k] = { t = t, n = n, sizes = sizes, dur = dur, total = total, chunks = chunks, sample = sample } + end + -- interleave the chunks by time + table.sort(all, function(a: Chunk, b: Chunk): boolean + local ta = a.time / prep[a.track].t.timescale + local tb = b.time / prep[b.track].t.timescale + if ta ~= tb then + return ta < tb + end + if a.track ~= b.track then + return a.track < b.track + end + return a.first < b.first + end) + local mdatSize = 0 + for _, c in all do + local p = prep[c.track] + for i = c.first, c.first + c.count - 1 do + mdatSize += p.sizes[i] + end + end + local co64 = mdatSize > 4294967295 - 2 ^ 24 + -- ftyp + local w = Bytes.writer(mdatSize + 4096) + box(w, "ftyp", function() + w:string(spec.brand or "isom") + w:u32be(spec.minor or 0x200) + for _, c in spec.compatible or { spec.brand or "isom", "iso2", "mp41" } do + w:string(string.sub(c .. " ", 1, 4)) + end + end) + -- moov twice: the first pass measures it, the second has the real chunk offsets + local probe = Bytes.writer(4096) + moov(probe, spec, prep, co64) + local mdatHeader = if mdatSize + 8 > 4294967295 then 16 else 8 + local o = w:tell() + probe:tell() + mdatHeader + for _, c in all do + c.offset = o + local p = prep[c.track] + for i = c.first, c.first + c.count - 1 do + o += p.sizes[i] + end + end + moov(w, spec, prep, co64) + if mdatHeader == 16 then + w:u32be(1) + w:string("mdat") + w:u64be(mdatSize + 16) + else + w:u32be(mdatSize + 8) + w:string("mdat") + end + for _, c in all do + local p = prep[c.track] + for i = c.first, c.first + c.count - 1 do + local b, off = p.sample(i) + w:bytes(b, off, p.sizes[i]) + end + end + return w:finish(), nil +end + +return Mux diff --git a/src/Formats/containers/IsoBmff/init.luau b/src/Formats/containers/IsoBmff/init.luau new file mode 100644 index 0000000..dab62b9 --- /dev/null +++ b/src/Formats/containers/IsoBmff/init.luau @@ -0,0 +1,188 @@ +--!strict +-- containers/IsoBmff: ISO base media file format (ISO/IEC 14496-12) and its relatives: MP4 / M4A / M4V / MOV (QuickTime) +-- / 3GP, fragmented MP4 (moof), HEIF / AVIF items (ISO/IEC 23008-12), iTunes tags. A container (layer 2): m4a, mp4, +-- mov, heif, avif build on it. Written from the specifications; no third-party code. +-- +-- local IsoBmff = require("@formats/containers/IsoBmff") +-- local movie, err = IsoBmff.parse(r) -- ftyp brand, tracks (Demux.Track: codec, config, sample tables) +-- local dmx = IsoBmff.demux(r) -- Types.Demuxer: tracks, duration, packets(trackId?), seek(s) +-- local tags, pictures = IsoBmff.tags(r, movie) -- moov/udta/meta/ilst (or a top-level meta) +-- local items = IsoBmff.items(r, movie) -- HEIF / AVIF: primary item, items, properties, refs +-- local data = IsoBmff.itemData(r, items, id) -- an item's bytes +-- local file = IsoBmff.mux({ brand = "M4A ", tracks = { { kind = "audio", entry = "alac", ... } }, tags = ... }) +-- +-- Sample offsets in tracks are absolute offsets into r.buf (r may cover part of a bigger buffer). Supports: 32 / 64-bit +-- boxes, stsz / stz2, stco / co64, ctts v0 / v1, stss, elst v0 / v1, QuickTime sound descriptions v1 / v2 and 'wave', +-- fragments with trex defaults / tfdt / data offsets. Not supported: external data references (dref urls), +-- encrypted tracks (sinf / senc are left to the caller), fragmented writing. Never throws. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Box = require("@formats/containers/IsoBmff/Box") +local Demux = require("@formats/containers/IsoBmff/Demux") +local Meta = require("@formats/containers/IsoBmff/Meta") +local Mux = require("@formats/containers/IsoBmff/Mux") + +local IsoBmff = {} +IsoBmff.Box = Box +IsoBmff.Demux = Demux +IsoBmff.Meta = Meta + +export type Track = Demux.Track +export type Movie = Demux.Movie +export type Items = Meta.Items +export type Item = Meta.Item +export type MuxSpec = Mux.MuxSpec +export type MuxTrack = Mux.MuxTrack +export type Picture = Meta.Picture + +local TOP: { [string]: boolean } = { + ftyp = true, moov = true, mdat = true, free = true, skip = true, wide = true, pnot = true, moof = true, + styp = true, sidx = true, meta = true, uuid = true, PICT = true, +} + +-- sniff(r) -> brand ("M4A ", "isom", "qt ", "avif", "heic", ...) or "" when the file starts with another top-level box, +-- nil when it is not an ISO BMFF file +function IsoBmff.sniff(r: Bytes.Reader): string? + local head = r:peek(12) + if #head < 8 then + return nil + end + local typ = string.sub(head, 5, 8) + if typ == "ftyp" then + return if #head >= 12 then string.sub(head, 9, 12) else "" + end + if TOP[typ] then + local size = string.byte(head, 1) * 16777216 + string.byte(head, 2) * 65536 + string.byte(head, 3) * 256 + string.byte(head, 4) + if size == 1 or size == 0 or size >= 8 then + return "" + end + end + return nil +end + +-- parse(r, opts?) -> Movie | nil, Err +function IsoBmff.parse(r: Bytes.Reader, opts: Demux.Options?): (Movie?, Err.Err?) + return Demux.parse(r, opts) +end + +-- tags(r, movie) -> Tags, { Picture }: iTunes tags from moov/udta/meta/ilst (or moov/meta/ilst, or a top-level meta) +function IsoBmff.tags(r: Bytes.Reader, movie: Movie): ({ [string]: string }, { Picture }) + local ilst = Box.path(movie.boxes, "moov/udta/meta/ilst") or Box.path(movie.boxes, "moov/meta/ilst") or Box.path(movie.boxes, "meta/ilst") + return Meta.tags(r.buf, ilst) +end + +-- items(r, movie) -> Items | nil, Err (the top-level meta box of a HEIF / AVIF file) +function IsoBmff.items(r: Bytes.Reader, movie: Movie): (Items?, Err.Err?) + local meta = Box.path(movie.boxes, "meta") + if not meta then + return nil, Err.new(Err.CORRUPT, "no top-level meta box") + end + return Meta.items(r.buf, meta) +end + +-- itemData(r, items, id) -> buffer | nil, Err +function IsoBmff.itemData(r: Bytes.Reader, items: Items, id: number): (buffer?, Err.Err?) + return Meta.itemData(r.buf, r.base, r.limit, items, id) +end + +-- sample(r, track, i) -> a copy of sample i (1-based) +function IsoBmff.sample(r: Bytes.Reader, t: Track, i: number): buffer? + if i < 1 or i > t.sampleCount then + return nil + end + local n = t.sizes[i] + local out = buffer.create(n) + buffer.copy(out, 0, r.buf, t.offsets[i], n) + return out +end + +-- demux(r, opts?) -> Types.Demuxer (tracks, duration, packets(trackId?), seek(seconds)) | nil, Err. Packets carry pts / +-- dts / duration in their track's timescale ticks and a copy of the sample bytes. +function IsoBmff.demux(r: Bytes.Reader, opts: Demux.Options?): (any, Err.Err?) + local movie, err = Demux.parse(r, opts) + if not movie then + return nil, err + end + local cursor: { [number]: number } = {} + local byId: { [number]: Track } = {} + for _, t in movie.tracks do + cursor[t.id] = 1 + byId[t.id] = t + end + local dmx = { tracks = movie.tracks, duration = movie.duration, movie = movie } + local function packet(t: Track, i: number): any + local dts = t.dts[i] + local cts = t.cts + return { + track = t.id, + dts = dts, + pts = dts + (if cts then cts[i] or 0 else 0), + duration = t.durations[i], + keyframe = t.sync == nil or (t.sync :: any)[i] == true, + data = IsoBmff.sample(r, t, i), + index = i, + } + end + function dmx.packets(_self: any, trackId: number?): () -> any + return function(): any + if trackId then + local t = byId[trackId] + if not t then + return nil + end + local i = cursor[trackId] + if i > t.sampleCount then + return nil + end + cursor[trackId] = i + 1 + return packet(t, i) + end + -- all tracks in file order + local best: Track? = nil + local bestOff = math.huge + for _, t in movie.tracks do + local i = cursor[t.id] + if i <= t.sampleCount and t.offsets[i] < bestOff then + best, bestOff = t, t.offsets[i] + end + end + if not best then + return nil + end + local i = cursor[best.id] + cursor[best.id] = i + 1 + return packet(best, i) + end + end + -- seek(seconds): every track to its last sync sample at or before the time + function dmx.seek(_self: any, seconds: number) + for _, t in movie.tracks do + local target = seconds * t.timescale + local lo, hi = 1, t.sampleCount + local found = 1 + while lo <= hi do + local mid = (lo + hi) // 2 + if t.dts[mid] <= target then + found = mid + lo = mid + 1 + else + hi = mid - 1 + end + end + if t.sync then + while found > 1 and not (t.sync :: any)[found] do + found -= 1 + end + end + cursor[t.id] = found + end + end + return dmx, nil +end + +-- mux(spec) -> buffer | nil, Err (see containers/IsoBmff/Mux) +function IsoBmff.mux(spec: MuxSpec): (buffer?, Err.Err?) + return Mux.mux(spec) +end + +return IsoBmff diff --git a/tests/containers/isobmff.luau b/tests/containers/isobmff.luau new file mode 100644 index 0000000..f05280e --- /dev/null +++ b/tests/containers/isobmff.luau @@ -0,0 +1,241 @@ +-- containers/IsoBmff tests: ffmpeg / MP4Box files (H.264 + AAC with B-frames, fast start, QuickTime MJPEG + PCM, HEVC, +-- fragmented by ffmpeg and MP4Box, stz2 + co64, ALAC) demuxed packet for packet against ffprobe (-ignore_editlist); +-- track facts and codec configurations; iTunes tags and cover art; AVIF items (libavif, plain and with alpha); the +-- muxer round-trips through the demuxer (sizes, times, cts, sync, tags, 64-bit sizes); a sub-range reader; the fuzz +-- no-throw pass. Fixtures: tools/fixtures/isobmff.py. +local T = require("@tests/T") +local IsoBmff = require("@formats/containers/IsoBmff") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Fx = require("@tests/gen/isobmff") + +local t = T.suite("isobmff") + +local CODEC = { h264 = "h264", aac = "aac", mjpeg = "mjpeg", pcm_s16be = "pcm", hevc = "hevc", alac = "alac" } + +local function reader(s: string, pad: number?): Bytes.Reader + if pad then + local b = buffer.create(#s + pad * 2) + buffer.writestring(b, pad, s) + return Bytes.reader(b, pad, #s) + end + return Bytes.reader(buffer.fromstring(s)) +end + +-- every fixture against ffprobe +for _, c in Fx.cases do + for _, pad in { 0, 5 } do + local r = reader(c.data, if pad > 0 then pad else nil) + local label = c.name .. (if pad > 0 then " (sub-range)" else "") + t:check(IsoBmff.sniff(r) ~= nil, label .. ": sniff") + local dmx, err = IsoBmff.demux(r) + t:check(dmx, label .. ": " .. tostring(err)) + t:eq(#dmx.tracks, #c.streams, label .. ": track count") + for i, s in c.streams do + local tr = dmx.tracks[i] + t:eq(tr.kind, s.kind, label .. ": track " .. i .. " kind") + t:eq(tr.codec, CODEC[s.codec] or s.codec, label .. ": track " .. i .. " codec") + t:eq(tr.timescale, s.timescale, label .. ": timescale") + if s.width then + t:check(tr.width == s.width and tr.height == s.height, label .. ": video size") + end + if s.sampleRate then + t:check(tr.sampleRate == s.sampleRate and tr.channels == s.channels, label .. ": audio format") + end + if s.extradata > 0 and s.codec ~= "alac" then + t:eq(if tr.config then buffer.len(tr.config) else 0, s.extradata, label .. ": codec config size") + end + end + -- packets in file order + local n, bad = 0, nil + local base = r.base + for p in dmx:packets() do + n += 1 + local want = c.packets[n] + if not want then + bad = bad or ("extra packet " .. n) + break + end + local tr = dmx.tracks[want.stream] + if p.track ~= tr.id then + bad = bad or ("packet " .. n .. " track") + end + local off = tr.offsets[p.index] + if off - base ~= want.pos or buffer.len(p.data) ~= want.size or p.dts ~= want.dts or p.pts ~= want.pts or p.keyframe ~= want.key then + bad = bad or string.format("packet %d: pos %d/%d size %d/%d dts %d/%d pts %d/%d key %s/%s", n, off - base, want.pos, buffer.len(p.data), want.size, p.dts, want.dts, p.pts, want.pts, tostring(p.keyframe), tostring(want.key)) + end + end + t:check(bad == nil, label .. ": " .. tostring(bad)) + t:eq(n, #c.packets, label .. ": packet count") + if pad == 0 then + t:note("%s: %d tracks, %d packets match ffprobe", c.name, #c.streams, n) + end + end +end + +-- per-track packets, seek +do + local c = Fx.cases[1] + local dmx = IsoBmff.demux(reader(c.data)) + local v = dmx.tracks[1] + local count = 0 + for p in dmx:packets(v.id) do + count += 1 + t:eq(p.track, v.id, "per-track packets") + end + t:eq(count, v.sampleCount, "per-track packet count") + dmx:seek(0.75) + local p = dmx:packets(v.id)() + t:check(p and p.keyframe and p.dts / v.timescale <= 0.75, "seek lands on a keyframe before the time") + t:check(v.skip >= 0 and v.edits ~= nil, "edit list parsed") +end + +-- tags and cover +do + local r = reader(Fx.tagged.data) + local movie = IsoBmff.parse(r) :: IsoBmff.Movie + local tags, pics = IsoBmff.tags(r, movie) + for k, v in Fx.tagged.tags do + t:eq(tags[k], v, "tag " .. k) + end + t:check(tags.encoder ~= nil, "encoder tag") + t:eq(#pics, 1, "one cover") + t:eq(pics[1] and buffer.len(pics[1].data), Fx.tagged.cover, "cover bytes") + t:eq(pics[1] and pics[1].mime, "image/png", "cover mime") +end + +-- AVIF items +for _, c in Fx.avif do + local r = reader(c.data) + t:check(IsoBmff.sniff(r) == "avif", c.name .. ": brand") + local movie = IsoBmff.parse(r) :: IsoBmff.Movie + t:check(movie and #movie.tracks == 0, c.name .. ": no tracks") + local items, err = IsoBmff.items(r, movie) + t:check(items, c.name .. ": items: " .. tostring(err)) + local prim = items.items[items.primary] + t:check(prim and prim.type == "av01", c.name .. ": primary item is av01") + local ispe, av1C + for _, p in prim.properties do + if p.type == "ispe" then + ispe = p + elseif p.type == "av1C" then + av1C = p + end + end + t:check(ispe and ispe.width == c.width and ispe.height == c.height, c.name .. ": ispe") + t:check(av1C and av1C.config and buffer.readu8(av1C.config, 0) == 0x81, c.name .. ": av1C marker / version") + local data = IsoBmff.itemData(r, items, items.primary :: number) + t:check(data and buffer.len(data) > 10, c.name .. ": item data") + -- an AV1 OBU stream: the first OBU is a sequence header (type 1) or a temporal delimiter (2) + local obu = data and bit32.band(bit32.rshift(buffer.readu8(data, 0), 3), 15) + t:check(obu == 1 or obu == 2, c.name .. ": AV1 OBU stream") + local auxl = nil + for _, id in items.order do + local it = items.items[id] + if it.refs.auxl then + auxl = it + end + end + t:eq(auxl ~= nil, c.alpha, c.name .. ": alpha auxiliary item") +end + +-- the muxer: round trip through the demuxer +do + local rand = T.rng(5) + local function sample(n: number): buffer + local b = buffer.create(n) + for i = 0, n - 1 do + buffer.writeu8(b, i, rand(256)) + end + return b + end + local aud, vid = {}, {} + for i = 1, 90 do + aud[i] = sample(50 + rand(200)) + end + for i = 1, 30 do + vid[i] = sample(100 + rand(900)) + end + local cts = {} + local sync = {} + for i = 1, 30 do + cts[i] = (i % 3) * 512 + sync[i] = i % 10 == 1 + end + local cfg = buffer.fromstring("\x12\x10") + local file, err = IsoBmff.mux({ + brand = "mp42", + compatible = { "mp42", "isom" }, + tracks = { + { kind = "video", entry = "avc1", timescale = 15360, samples = vid, durations = 512, cts = cts, sync = sync, width = 64, height = 48, config = buffer.fromstring("\1\100\0\10\255") }, + { kind = "audio", entry = "mp4a", timescale = 44100, samples = aud, durations = 1024, sampleRate = 44100, channels = 2, config = cfg, skip = 1024, playDuration = 44100 * 2 }, + }, + tags = { title = "Mux Test", artist = "Me", track = "2", tracktotal = "9", custom = "free form", bpm = "120" }, + pictures = { { mime = "image/jpeg", data = buffer.fromstring("\255\216\255\217") } }, + chunkDuration = 0.25, + }) + t:check(file, "mux: " .. tostring(err)) + local r = Bytes.reader(file :: buffer) + local dmx = IsoBmff.demux(r) + t:check(dmx and #dmx.tracks == 2, "mux: demux our file") + local v, a = dmx.tracks[1], dmx.tracks[2] + t:check(v.codec == "h264" and v.width == 64 and v.height == 48 and v.config and buffer.len(v.config) == 5, "mux: video track") + t:check(a.codec == "aac" and a.sampleRate == 44100 and a.channels == 2 and a.config and buffer.tostring(a.config) == "\x12\x10", "mux: audio track + esds") + t:check(a.skip == 1024 and a.playDuration == 88200, "mux: edit list") + local ok = true + for i = 1, 30 do + local s = IsoBmff.sample(r, v, i) :: buffer + ok = ok and buffer.tostring(s) == buffer.tostring(vid[i]) and v.dts[i] == (i - 1) * 512 and (v.cts :: any)[i] == cts[i] and ((v.sync :: any)[i] == true) == sync[i] + end + t:check(ok, "mux: video samples, times, cts, sync") + ok = true + for i = 1, 90 do + ok = ok and buffer.tostring(IsoBmff.sample(r, a, i) :: buffer) == buffer.tostring(aud[i]) and a.durations[i] == 1024 + end + t:check(ok, "mux: audio samples") + -- interleaved: offsets alternate between the tracks + t:check(v.offsets[30] > a.offsets[1] and a.offsets[90] > v.offsets[1], "mux: interleaved chunks") + local tags, pics = IsoBmff.tags(r, dmx.movie) + t:check(tags.title == "Mux Test" and tags.artist == "Me" and tags.track == "2" and tags.tracktotal == "9" and tags.custom == "free form" and tags.bpm == "120", "mux: tags round trip") + t:check(#pics == 1 and buffer.len(pics[1].data) == 4, "mux: cover round trip") + t:note("mux: %d bytes, crc %08x", buffer.len(file :: buffer), Crc32.of(file :: buffer)) + -- data + sizes form, bad specs + local f2 = IsoBmff.mux({ tracks = { { kind = "audio", entry = "alac", timescale = 8000, data = buffer.create(30), sizes = { 10, 10, 10 }, durations = { 4096, 4096, 100 }, config = buffer.create(24) } } }) + local d2 = IsoBmff.demux(Bytes.reader(f2 :: buffer)) + t:check(d2 and d2.tracks[1].codec == "alac" and d2.tracks[1].sampleCount == 3 and d2.tracks[1].durations[3] == 100 and buffer.len(d2.tracks[1].config) == 24, "mux: data + sizes, alac cookie") + for _, bad in { {}, { tracks = {} }, { tracks = { { kind = "audio", entry = "toolong", timescale = 1, samples = {}, durations = 1 } } }, { tracks = { { kind = "x", entry = "abcd", timescale = 1, samples = {}, durations = 1 } } }, { tracks = { { kind = "audio", entry = "abcd", timescale = 1 } } } } do + local f, e = IsoBmff.mux(bad :: any) + t:check(f == nil and e and e.code == "ARG", "mux: bad spec -> ARG") + end +end + +-- fuzz +do + local samples = {} + for _, c in Fx.cases do + table.insert(samples, string.sub(c.data, 1, 6000)) + table.insert(samples, c.data) + end + for _, c in Fx.avif do + table.insert(samples, c.data) + end + t:fuzz("demux", function(b: buffer) + local r = Bytes.reader(b) + local dmx = IsoBmff.demux(r) + if dmx then + for p in dmx:packets() do + local _ = p + end + IsoBmff.tags(r, dmx.movie) + local items = IsoBmff.items(r, dmx.movie) + if items then + for _, id in items.order do + IsoBmff.itemData(r, items, id) + end + end + end + return dmx + end, samples, { mutations = 12 }) +end + +t:done() diff --git a/tools/fixtures/isobmff.py b/tools/fixtures/isobmff.py new file mode 100644 index 0000000..4239ca6 --- /dev/null +++ b/tools/fixtures/isobmff.py @@ -0,0 +1,89 @@ +# containers/IsoBmff fixtures (tools/fixtures.py): small files from ffmpeg / MP4Box / avifenc (nix) with ffprobe's +# packet lists as the reference. +# tests/gen/isobmff.luau { cases = { { name, data, streams = { { codec, kind, timescale, width?, height?, +# sampleRate?, channels?, extradata }, ... }, packets = { { stream, pos, size, dts, pts, key }, +# ... } } }, tagged = { data, tags, cover }, avif = { { name, data, width, height, alpha } } } +import json, os, shutil, subprocess, tempfile + +PKGS = ["ffmpeg", "gpac", "libavif"] + + +def sh(ctx, script, cwd): + return ctx.nix(PKGS, ["sh", "-c", "cd '%s' && %s" % (cwd, script)]) + + +def probe(ctx, path, cwd): + out = sh(ctx, "ffprobe -v error -ignore_editlist 1 -show_streams -show_packets -of json '%s'" % path, cwd) + j = json.loads(out) + streams = [] + for s in j["streams"]: + kind = s["codec_type"] + if kind == "video" and s.get("disposition", {}).get("attached_pic"): + continue + tb = s["time_base"].split("/") + e = {"codec": s["codec_name"], "kind": kind, "timescale": int(tb[1]), "index": s["index"], + "extradata": int(s.get("extradata_size", 0))} + if kind == "video": + e["width"], e["height"] = s["width"], s["height"] + if kind == "audio": + e["sampleRate"], e["channels"] = int(s["sample_rate"]), s["channels"] + streams.append(e) + index = {s["index"]: i + 1 for i, s in enumerate(streams)} + packets = [] + for p in j["packets"]: + if p["stream_index"] not in index: + continue + packets.append({"stream": index[p["stream_index"]], "pos": int(p["pos"]), "size": int(p["size"]), + "dts": int(p["dts"]), "pts": int(p["pts"]), "key": "K" in p["flags"]}) + for s in streams: + del s["index"] + return streams, packets + + +def generate(ctx): + d = tempfile.mkdtemp(prefix="isobmff-fx-") + try: + src_v = "-f lavfi -i testsrc=size=64x48:rate=10 -t 1.2" + src_a = "-f lavfi -i sine=frequency=440:sample_rate=44100 -t 1.0" + steps = [ + ("h264_aac.mp4", "ffmpeg -v error %s %s -c:v libx264 -bf 2 -g 5 -pix_fmt yuv420p -c:a aac -b:a 64k -ac 2 h264_aac.mp4" % (src_v, src_a)), + ("faststart.mp4", "ffmpeg -v error -i h264_aac.mp4 -c copy -movflags +faststart faststart.mp4"), + ("mjpeg_pcm.mov", "ffmpeg -v error %s %s -c:v mjpeg -c:a pcm_s16be mjpeg_pcm.mov" % (src_v, src_a)), + ("hevc.mp4", "ffmpeg -v error %s -c:v libx265 -x265-params log-level=none -tag:v hvc1 hevc.mp4" % src_v), + ("frag.mp4", "ffmpeg -v error -i h264_aac.mp4 -c copy -movflags frag_keyframe+empty_moov+default_base_moof frag.mp4"), + ("mp4box_frag.mp4", "MP4Box -quiet -frag 300 -out mp4box_frag.mp4 h264_aac.mp4 >/dev/null 2>&1"), + ("stz2_co64.mp4", "MP4Box -quiet -add h264_aac.mp4#video -add h264_aac.mp4#audio:stz2 -co64 -new stz2_co64.mp4 >/dev/null 2>&1"), + ("alac.m4a", "ffmpeg -v error %s -c:a alac alac.m4a" % src_a), + ] + cases = [] + for name, cmd in steps: + sh(ctx, cmd, d) + streams, packets = probe(ctx, name, d) + with open(os.path.join(d, name), "rb") as f: + data = f.read() + cases.append({"name": name, "data": data, "streams": streams, "packets": packets}) + # tags + cover + sh(ctx, "ffmpeg -v error -f lavfi -i color=red:size=8x8 -frames:v 1 -update 1 cover.png", d) + tags = {"title": "Test Title", "artist": "Some Artist", "album": "An Album", "date": "2024", + "genre": "Electronic", "comment": "a comment", "composer": "Composer X", "album_artist": "AA"} + meta = " ".join("-metadata %s='%s'" % (k, v) for k, v in tags.items()) + sh(ctx, "ffmpeg -v error %s -i cover.png -map 0 -map 1 -c:a aac -b:a 48k -c:v png -disposition:v attached_pic -t 1 %s -metadata track=3/12 -metadata disc=1/2 tagged.m4a" % (src_a, meta), d) + with open(os.path.join(d, "tagged.m4a"), "rb") as f: + tagged = f.read() + with open(os.path.join(d, "cover.png"), "rb") as f: + cover = f.read() + want = {"title": "Test Title", "artist": "Some Artist", "album": "An Album", "date": "2024", + "genre": "Electronic", "comment": "a comment", "composer": "Composer X", "albumartist": "AA", + "track": "3", "tracktotal": "12", "disc": "1", "disctotal": "2"} + # AVIF stills (libavif): plain and with alpha + avif = [] + sh(ctx, "ffmpeg -v error -f lavfi -i testsrc=size=40x24 -frames:v 1 still.png && " + "ffmpeg -v error -f lavfi -i 'testsrc=size=40x24,format=rgba,geq=r=r(X\\,Y):a=X*6' -frames:v 1 alpha.png", d) + for name, png, alpha in (("still.avif", "still.png", False), ("alpha.avif", "alpha.png", True)): + sh(ctx, "avifenc -q 60 -s 10 %s %s >/dev/null" % (png, name), d) + with open(os.path.join(d, name), "rb") as f: + avif.append({"name": name, "data": f.read(), "width": 40, "height": 24, "alpha": alpha}) + ctx.emit("isobmff", {"cases": cases, "tagged": {"data": tagged, "tags": want, "cover": len(cover)}, + "avif": avif}) + finally: + shutil.rmtree(d, ignore_errors=True) From 83d43f6c6d97f5064f6ffba77a798e9145653896 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:03:04 -0500 Subject: [PATCH 4/7] ws-m4a: codecs/Aac (AAC-LC decoder: ASC / PCE / ADTS, all tools, SBR/PS extension hook), codecs/Alac (decoder + encoder), audio/m4a (AAC + ALAC read, ALAC write, tags, gapless, seek), audio/aac (ADTS), audio/caf (lpcm/alac/aac/ulaw/alaw read, lpcm/alac write); fixtures checked by ffmpeg / fdkaac / MP4Box --- docs/FORMATS.md | 5 + licenses/NOTICE.md | 2 + src/Formats/Registry.luau | 36 ++ src/Formats/audio/aac/init.luau | 277 +++++++++ src/Formats/audio/caf/init.luau | 746 +++++++++++++++++++++++ src/Formats/audio/m4a/init.luau | 439 ++++++++++++++ src/Formats/codecs/Aac/Decode.luau | 903 ++++++++++++++++++++++++++++ src/Formats/codecs/Aac/Tables.luau | 335 +++++++++++ src/Formats/codecs/Aac/init.luau | 336 +++++++++++ src/Formats/codecs/Alac/Decode.luau | 427 +++++++++++++ src/Formats/codecs/Alac/Encode.luau | 427 +++++++++++++ src/Formats/codecs/Alac/init.luau | 251 ++++++++ tests/audio/_encode_cases.luau | 12 + tests/audio/_signal.luau | 42 ++ tests/audio/aac.luau | 117 ++++ tests/audio/caf.luau | 177 ++++++ tests/audio/m4a.luau | 218 +++++++ tests/codecs/aac.luau | 182 ++++++ tests/codecs/alac.luau | 181 ++++++ tools/fixtures/_m4a_encode.luau | 31 + tools/fixtures/_m4a_signal.py | 41 ++ tools/fixtures/m4a.py | 195 ++++++ 22 files changed, 5380 insertions(+) create mode 100644 src/Formats/audio/aac/init.luau create mode 100644 src/Formats/audio/caf/init.luau create mode 100644 src/Formats/audio/m4a/init.luau create mode 100644 src/Formats/codecs/Aac/Decode.luau create mode 100644 src/Formats/codecs/Aac/Tables.luau create mode 100644 src/Formats/codecs/Aac/init.luau create mode 100644 src/Formats/codecs/Alac/Decode.luau create mode 100644 src/Formats/codecs/Alac/Encode.luau create mode 100644 src/Formats/codecs/Alac/init.luau create mode 100644 tests/audio/_encode_cases.luau create mode 100644 tests/audio/_signal.luau create mode 100644 tests/audio/aac.luau create mode 100644 tests/audio/caf.luau create mode 100644 tests/audio/m4a.luau create mode 100644 tests/codecs/aac.luau create mode 100644 tests/codecs/alac.luau create mode 100644 tools/fixtures/_m4a_encode.luau create mode 100644 tools/fixtures/_m4a_signal.py create mode 100644 tools/fixtures/m4a.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 4a451fa..4e93b14 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,8 +6,13 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| | image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | +| audio | aac | .aac .adts | yes | - | codecs: "aac", streaming: true | `tests/audio/aac.luau` | +| audio | caf | .caf .caff | yes | yes | codecs: "pcm", "alac", "aac", "ulaw", "alaw", encodeCodecs: "pcm", "alac", tags: true, streaming: true | `tests/audio/caf.luau` | +| audio | m4a | .m4a .m4b .m4r .aac.mp4 | yes | yes | codecs: "aac", "alac", encodeCodecs: "alac", tags: true, streaming: true | `tests/audio/m4a.luau` | Codecs (layer 1, shared by formats; not loadable on their own): +- codecs/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program +- codecs/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1). - codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. - codecs/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index 5d28e73..7e67528 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -4,6 +4,8 @@ |---|---|---| | `src/Formats/codecs/Deflate/` (Inflate, init), `src/Formats/core/Crc32.luau`, `src/Formats/core/Adler32.luau`, `src/Formats/core/Huffman.luau` (table builder) | deflate-luau 1.0.0 (same author), written from RFC 1950-1952 | no licence chosen yet; no third-party code: [deflate-luau-NOTICE.txt](deflate-luau-NOTICE.txt) | | `src/Formats/image/png/` (init, Decode) | png-luau 1.0.0 (same author), written from the PNG specification | no licence chosen yet; no third-party code | +| `src/Formats/codecs/Aac/Tables.luau` | the Huffman codebooks, scalefactor band offsets and TNS limits of ISO/IEC 14496-3 (Annex 4.A), transcribed mechanically from FFmpeg's `libavcodec/aactab.c` (tables of the standard only; no FFmpeg code) | FFmpeg is LGPL-2.1-or-later; the tables are the standard's data | +| `src/Formats/codecs/Aac/`, `codecs/Alac/`, `codecs/Mdct/`, `containers/IsoBmff/`, `audio/m4a`, `audio/aac`, `audio/caf` | written for this library from ISO/IEC 14496-3 / 14496-12 / 23008-12, Apple's ALAC and CAF specifications | no third-party code | | `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ba09f70..7c810a6 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -26,6 +26,42 @@ local list: { Entry } = { return require("@formats/image/png") end, }, + { + name = "aac", + category = "audio", + path = "audio/aac", + extensions = { "aac", "adts" }, + mime = { "audio/aac", "audio/aacp", "audio/x-aac" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac" }, + caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true }, + load = function() + return require("@formats/audio/aac") + end, + }, + { + name = "caf", + category = "audio", + path = "audio/caf", + extensions = { "caf", "caff" }, + mime = { "audio/x-caf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac" }, + caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true }, + load = function() + return require("@formats/audio/caf") + end, + }, + { + name = "m4a", + category = "audio", + path = "audio/m4a", + extensions = { "m4a", "m4b", "m4r", "aac.mp4" }, + mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac" }, + caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true }, + load = function() + return require("@formats/audio/m4a") + end, + }, } return list diff --git a/src/Formats/audio/aac/init.luau b/src/Formats/audio/aac/init.luau new file mode 100644 index 0000000..6c3e45d --- /dev/null +++ b/src/Formats/audio/aac/init.luau @@ -0,0 +1,277 @@ +--!strict +-- audio/aac: raw AAC in ADTS framing (ISO/IEC 13818-7 / 14496-3 1.A.3), the .aac files encoders and radio streams +-- write. Supports: reading AAC-LC through codecs/Aac (1 - 8 channels, every rate, multi-block frames, CRC-protected +-- headers skipped), a leading ID3v2 tag (skipped; its text frames become tags), resync after garbage, seeking (by +-- frame), HE-AAC streams play their AAC-LC core. Not supported: writing (AAC encoding is out of scope), ADIF, LATM. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Aac = require("@formats/codecs/Aac") + +-- ------------------------------------------------------------------------------------------------ contract +local AacFormat = { + name = "aac", + category = "audio", + extensions = { "aac", "adts" }, + mime = { "audio/aac", "audio/aacp", "audio/x-aac" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac" }, + caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxFrames: number?, -- refuse streams with more ADTS frames (default 2^22) +} + +-- ------------------------------------------------------------------------------------------------ constants +local readu8 = buffer.readu8 + +-- the size of an ID3v2 tag at p (0 if none) +local function id3Size(b: buffer, p: number, limit: number): number + if p + 10 > limit or buffer.readstring(b, p, 3) ~= "ID3" then + return 0 + end + local s = 0 + for i = 6, 9 do + s = s * 128 + bit32.band(readu8(b, p + i), 127) + end + local footer = if bit32.band(readu8(b, p + 5), 0x10) ~= 0 then 10 else 0 + return 10 + s + footer +end + +-- a few ID3v2.3 / 2.4 text frames -> tags +local ID3_TAGS: { [string]: string } = { + TIT2 = "title", TPE1 = "artist", TALB = "album", TYER = "date", TDRC = "date", TCON = "genre", TRCK = "track", + COMM = "comment", TCOM = "composer", TPE2 = "albumartist", +} +local function id3Tags(b: buffer, p: number, size: number): Types.Tags + local tags: Types.Tags = {} + local ver = readu8(b, p + 3) + if ver < 3 then + return tags + end + local q, stop = p + 10, p + size + while q + 10 <= stop do + local id = buffer.readstring(b, q, 4) + if not string.match(id, "^[A-Z0-9][A-Z0-9][A-Z0-9][A-Z0-9]$") then + break + end + local n = 0 + for i = 4, 7 do + n = if ver == 4 then n * 128 + bit32.band(readu8(b, q + i), 127) else n * 256 + readu8(b, q + i) + end + if n < 1 or q + 10 + n > stop then + break + end + local key = ID3_TAGS[id] + local enc = readu8(b, q + 10) + if key and (enc == 0 or enc == 3) then + local s = buffer.readstring(b, q + 11, n - 1) + if id == "COMM" and #s > 3 then + s = string.sub(s, 4) + local z = string.find(s, "\0", 1, true) + if z then + s = string.sub(s, z + 1) + end + end + s = (string.gsub(s, "%z+$", "")) + tags[key] = s + end + q += 10 + n + end + return tags +end + +-- ------------------------------------------------------------------------------------------------ sniff +function AacFormat.sniff(r: Bytes.Reader): number + local b, p, limit = r.buf, r.pos, r.limit + p += id3Size(b, p, limit) + local h = Aac.adts(b, p, limit) + if not h then + return 0 + end + -- a second header right after the first makes it certain + local h2 = Aac.adts(b, p + h.frameSize, limit) + if h2 and h2.sfIndex == h.sfIndex and h2.channelConfig == h.channelConfig then + return 0.9 + end + return if p + h.frameSize >= limit then 0.7 else 0.4 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the frame index: offsets of every ADTS frame (resyncing over garbage) +local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number }, Aac.Adts?, Err.Err?) + local b, limit = r.buf, r.limit + local p = r.base + id3Size(b, r.base, limit) + local offs, sizes = {}, {} + local first: Aac.Adts? = nil + while p + 7 <= limit do + local h = Aac.adts(b, p, limit) + if h and first and (h.sfIndex ~= first.sfIndex or h.channelConfig ~= first.channelConfig) then + h = nil -- a false sync inside the data + end + if not h then + p += 1 + continue + end + if p + h.frameSize > limit then + break -- a truncated last frame + end + if not first then + first = h + end + if h.blocks ~= 1 then + return offs, sizes, first, Err.new(Err.UNSUPPORTED, "ADTS frames with " .. h.blocks .. " raw data blocks", p) + end + table.insert(offs, p + h.headerSize) + table.insert(sizes, h.frameSize - h.headerSize) + if #offs > maxFrames then + return offs, sizes, first, Err.new(Err.LIMIT, "more than " .. maxFrames .. " frames") + end + p += h.frameSize + end + return offs, sizes, first, nil +end + +function AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local o = opts or {} + local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22) + if ierr then + return nil, ierr + end + if not first then + return nil, Err.new(Err.CORRUPT, "no ADTS frame", r.base) + end + local h = first :: Aac.Adts + if h.objectType ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, "ADTS profile " .. h.objectType .. " (only AAC-LC)") + end + if h.channelConfig == 0 then + return nil, Err.new(Err.UNSUPPORTED, "ADTS with a program config element (channel configuration 0)") + end + local channels = ({ 1, 2, 3, 4, 5, 6, 8 })[h.channelConfig] :: number + local dec, derr = Aac.decoder({ sfIndex = h.sfIndex, channels = channels, channelConfig = h.channelConfig }) + if not dec then + return nil, derr + end + local d = dec :: Aac.Decoder + local sr = d.sampleRate + local nframes = #offs + local total = nframes * 1024 + local bytes = 0 + for _, s in sizes do + bytes += s + end + local id3 = id3Size(r.buf, r.base, r.limit) + local tags = if id3 > 0 then id3Tags(r.buf, r.base, id3) else {} + local buf = r.buf + local nextFrame = 1 + local pendPos, pendN = 0, 0 + local drop = 0 + local pos = 0 + local failed: Err.Err? = nil + local out: any = { + sampleRate = sr, + channels = channels, + frames = total, + duration = total / sr, + bitrate = if total > 0 then math.floor(bytes * 8 * sr / total) else 0, + tags = tags, + codec = "aac", + error = nil, + } + local function fill(): boolean + while true do + if nextFrame > nframes then + return false + end + local i = nextFrame + nextFrame += 1 + local n, e = d:decode(buf, offs[i], sizes[i]) + if not n then + failed = e + out.error = e + return false + end + if drop >= n then + drop -= n + else + pendPos, pendN = drop, n + drop = 0 + return true + end + end + end + function out.read(_self: any, n: number, ob: buffer?): (buffer, number) + local want = math.max(0, math.floor(n)) + local need = want * channels * 4 + local res = if ob and buffer.len(ob) >= need then ob else buffer.create(need) + local got = 0 + local writef32 = buffer.writef32 + while got < want do + if pendPos >= pendN then + if failed or not fill() then + break + end + end + local take = math.min(want - got, pendN - pendPos) + local src = d.pcm + local q = got * channels * 4 + local s = pendPos * channels + for k = 1, take * channels do + writef32(res, q, src[s + k]) + q += 4 + end + pendPos += take + got += take + end + pos += got + return res, got + end + function out.seek(_self: any, seconds: number) + local target = math.clamp(math.floor(seconds * sr + 0.5), 0, total) + local f = target // 1024 -- frame holding the target (0-based) + local start = math.max(0, f - 1) -- one frame of pre-roll for the overlap + d:reset() + nextFrame = start + 1 + drop = target - start * 1024 + pendPos, pendN = 0, 0 + failed = nil + pos = target + end + function out.position(_self: any): number + return pos / sr + end + if nframes > 0 and not fill() and failed then + return nil, failed + end + return out, nil +end + +function AacFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = AacFormat.open(r, opts) + if not dec then + return nil, err + end + local d: any = dec + local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames) + local done = 0 + while done < d.frames do + local b, n = d:read(math.min(65536, d.frames - done)) + if n == 0 then + break + end + buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4) + done += n + end + if d.error then + return nil, d.error + end + audio.tags = d.tags + audio.meta.source = { format = "aac", codec = "aac", bitrate = d.bitrate } + return audio, nil +end + +return AacFormat diff --git a/src/Formats/audio/caf/init.luau b/src/Formats/audio/caf/init.luau new file mode 100644 index 0000000..f602434 --- /dev/null +++ b/src/Formats/audio/caf/init.luau @@ -0,0 +1,746 @@ +--!strict +-- audio/caf: Apple Core Audio Format (CAF 1.0, Apple's "Core Audio Format Specification"). Supports reading linear +-- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/Alac), AAC-LC (codecs/Aac, +-- kuki esds), mu-law and A-law; the packet table (pakt) with priming / remainder trimming, a data chunk of unknown +-- size (-1), info chunk tags; seeking. Writing linear PCM (16 / 24-bit big endian, 32-bit float) and ALAC (16 / 20 / +-- 24-bit) with info tags. Not supported: IMA4, other compressed formats (UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Aac = require("@formats/codecs/Aac") +local Alac = require("@formats/codecs/Alac") + +-- ------------------------------------------------------------------------------------------------ contract +local Caf = { + name = "caf", + category = "audio", + extensions = { "caf", "caff" }, + mime = { "audio/x-caf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac" }, + caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxPackets: number?, -- packet table limit (default 2^24) +} +export type EncodeOptions = { + codec: ("pcm" | "alac")?, -- default "alac" + bitDepth: number?, -- pcm: 16 (default), 24, 32 (float); alac: 16 (default), 20, 24 + tags: Types.Tags?, -- default: the audio's tags +} + +-- ------------------------------------------------------------------------------------------------ constants +local INFO_TAGS: { [string]: string } = { + title = "title", artist = "artist", album = "album", year = "date", genre = "genre", ["track number"] = "track", + comments = "comment", composer = "composer", copyright = "copyright", lyricist = "lyricist", + ["encoding application"] = "encoder", ["recorded date"] = "recorded", tempo = "bpm", +} +local TAG_INFO: { [string]: string } = {} +for k, v in INFO_TAGS do + TAG_INFO[v] = k +end + +-- mu-law / A-law -> linear 16-bit +local ULAW, ALAW = table.create(256, 0), table.create(256, 0) +for i = 0, 255 do + local u = 255 - i + local t = (bit32.band(u, 15) * 8 + 132) * 2 ^ bit32.band(bit32.rshift(u, 4), 7) + ULAW[i + 1] = if bit32.band(u, 128) ~= 0 then 132 - t else t - 132 + local a = bit32.bxor(i, 0x55) + local seg = bit32.band(bit32.rshift(a, 4), 7) + local m = bit32.band(a, 15) * 16 + 8 + if seg > 0 then + m = (m + 256) * 2 ^ (seg - 1) + end + ALAW[i + 1] = if bit32.band(a, 128) ~= 0 then m else -m +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Caf.sniff(r: Bytes.Reader): number + local h = r:peek(8) + if #h == 8 and string.sub(h, 1, 4) == "caff" and string.byte(h, 5) == 0 and string.byte(h, 6) == 1 then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Desc = { rate: number, format: string, flags: number, bytesPerPacket: number, framesPerPacket: number, channels: number, bits: number } +type Parsed = { + desc: Desc, + dataStart: number, -- absolute offset of the audio data + dataEnd: number, + cookie: buffer?, + packets: { number }?, -- sizes (pakt) + packetFrames: { number }?, + priming: number, + remainder: number, + validFrames: number?, + tags: Types.Tags, +} + +-- the esds payload in a kuki (version / flags, then the ES_Descriptor) -> the DecoderSpecificInfo +local function esdsConfig(b: buffer): buffer? + local r = Bytes.reader(b) + if r:peekU8() ~= 3 then + r:skip(4) -- the esds atom's version / flags + end + local function len(): number + local n = 0 + for _ = 1, 4 do + local c = r:u8() + n = n * 128 + bit32.band(c, 127) + if c < 128 then + break + end + end + return n + end + while not r:eof() and not r.err do + local tag = r:u8() + local n = len() + if tag == 3 then + r:skip(2) + local f = r:u8() + if bit32.band(f, 0x80) ~= 0 then + r:skip(2) + end + if bit32.band(f, 0x40) ~= 0 then + r:skip(r:u8()) + end + if bit32.band(f, 0x20) ~= 0 then + r:skip(2) + end + elseif tag == 4 then + r:skip(13) + elseif tag == 5 then + if n > 0 and r:need(n) then + return r:bytes(n) + end + return nil + else + r:skip(n) + end + end + return nil +end + +local function vlq(r: Bytes.Reader): number + local v = 0 + for _ = 1, 8 do + local c = r:u8() + v = v * 128 + bit32.band(c, 127) + if c < 128 then + return v + end + end + r:fail(Err.CORRUPT, "bad packet table entry") + return 0 +end + +local function parse(r: Bytes.Reader, o: DecodeOptions): (Parsed?, Err.Err?) + if Caf.sniff(r) == 0 then + return nil, Err.new(Err.CORRUPT, "not a CAF file", r.base) + end + r:seek(8) + local p: Parsed = { desc = nil :: any, dataStart = 0, dataEnd = 0, priming = 0, remainder = 0, tags = {} } + local haveData = false + while r:remaining() >= 12 do + local typ = r:string(4) + local size = r:i64be() + local start = r.pos + if size == -1 and typ == "data" then + size = r.limit - start + end + if size < 0 then + return nil, Err.new(Err.CORRUPT, "bad chunk size", start - 12) + end + local stop = start + size + if stop > r.limit then + if typ ~= "data" then + return nil, Err.new(Err.TRUNCATED, "chunk '" .. typ .. "' runs past the end", start - 12) + end + stop = r.limit -- a truncated data chunk: play what is there + end + local c = Bytes.reader(r.buf, start, stop - start) + if typ == "desc" then + p.desc = { + rate = c:f64be(), + format = c:string(4), + flags = c:u32be(), + bytesPerPacket = c:u32be(), + framesPerPacket = c:u32be(), + channels = c:u32be(), + bits = c:u32be(), + } + if c.err then + return nil, c.err + end + elseif typ == "data" then + p.dataStart = start + 4 -- edit count + p.dataEnd = stop + haveData = true + elseif typ == "kuki" then + p.cookie = c:bytes(stop - start) + elseif typ == "pakt" then + local n = c:i64be() + p.validFrames = c:i64be() + p.priming = c:i32be() + p.remainder = c:i32be() + if c.err then + return nil, c.err + end + if n < 0 or n > (o.maxPackets or 2 ^ 24) or n > c:remaining() then + return nil, Err.new(Err.LIMIT, "packet table of " .. n .. " entries", start) + end + local d = p.desc + if not d then + return nil, Err.new(Err.CORRUPT, "pakt before desc", start) + end + local sizes, frames = table.create(n, 0), nil + if d.framesPerPacket == 0 then + frames = table.create(n, 0) + end + for i = 1, n do + sizes[i] = if d.bytesPerPacket == 0 then vlq(c) else d.bytesPerPacket + if frames then + frames[i] = vlq(c) + end + end + if c.err then + return nil, c.err + end + p.packets, p.packetFrames = sizes, frames + elseif typ == "info" then + local n = c:u32be() + for _ = 1, math.min(n, 1000) do + local k = c:cstring() + local v = c:cstring() + if c.err then + break + end + p.tags[INFO_TAGS[string.lower(k)] or k] = v + end + end + r.pos = stop + if typ == "data" and stop >= r.limit then + break + end + end + if not p.desc then + return nil, Err.new(Err.CORRUPT, "no desc chunk", r.base) + end + if not haveData then + return nil, Err.new(Err.CORRUPT, "no data chunk", r.base) + end + local d = p.desc + if d.channels < 1 or d.channels > 64 or d.rate <= 0 or d.rate ~= d.rate or d.rate > 1e7 then + return nil, Err.new(Err.CORRUPT, "bad stream description") + end + return p, nil +end + +-- the packet decoder: decode(i) -> frames into pcm (interleaved floats) | nil, Err +type Source = { + channels: number, + rate: number, + packetCount: number, + packetFrames: (number) -> number, + decode: (number) -> (number?, Err.Err?), + pcm: { number }, + reset: () -> (), + codec: string, + bits: number?, +} + +local function source(r: Bytes.Reader, p: Parsed): (Source?, Err.Err?) + local d = p.desc + local b = r.buf + local ch = d.channels + local fmt = d.format + if fmt == "lpcm" or fmt == "ulaw" or fmt == "alaw" then + local bits = if fmt == "lpcm" then d.bits else 8 + local float = fmt == "lpcm" and bit32.band(d.flags, 1) ~= 0 + local little = fmt == "lpcm" and bit32.band(d.flags, 2) ~= 0 + local bpf = d.bytesPerPacket + if bpf == 0 then + bpf = ch * (bits // 8) + end + if not (bits == 8 or bits == 16 or bits == 24 or bits == 32 or (bits == 64 and float)) or (float and bits < 32) then + return nil, Err.new(Err.UNSUPPORTED, "linear PCM with " .. bits .. " bits") + end + local bps = bits // 8 + if bpf < ch * bps then + return nil, Err.new(Err.CORRUPT, "bytes per packet smaller than a frame") + end + local total = (p.dataEnd - p.dataStart) // bpf + local per = 1024 + local pcm = table.create(per * ch, 0) + local scale = 1 / 2 ^ (bits - 1) + local readu8, readi8 = buffer.readu8, buffer.readi8 + local src: Source = { + channels = ch, + rate = d.rate, + packetCount = (total + per - 1) // per, + packetFrames = function(i: number): number + return math.min(per, total - (i - 1) * per) + end, + pcm = pcm, + reset = function() end, + codec = if fmt == "lpcm" then "pcm" else fmt, + bits = bits, + decode = function(i: number): (number?, Err.Err?) + local f0 = (i - 1) * per + local n = math.min(per, total - f0) + local k = 1 + for f = f0, f0 + n - 1 do + local q = p.dataStart + f * bpf + for _ = 1, ch do + local v + if fmt == "ulaw" then + v = ULAW[readu8(b, q) + 1] / 32768 + elseif fmt == "alaw" then + v = ALAW[readu8(b, q) + 1] / 32768 + elseif float then + if bits == 32 then + v = if little then buffer.readf32(b, q) else Bytes.reader(b, q, 4):f32be() + else + v = if little then buffer.readf64(b, q) else Bytes.reader(b, q, 8):f64be() + end + elseif bits == 8 then + v = readi8(b, q) * scale + elseif bits == 16 then + v = if little then buffer.readi16(b, q) else readi8(b, q) * 256 + readu8(b, q + 1) + v *= scale + elseif bits == 24 then + if little then + v = readi8(b, q + 2) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q) + else + v = readi8(b, q) * 65536 + readu8(b, q + 1) * 256 + readu8(b, q + 2) + end + v *= scale + else + if little then + v = buffer.readi32(b, q) + else + v = readi8(b, q) * 16777216 + readu8(b, q + 1) * 65536 + readu8(b, q + 2) * 256 + readu8(b, q + 3) + end + v *= scale + end + pcm[k] = v + k += 1 + q += bps + end + end + return n, nil + end, + } + return src, nil + end + -- packetised codecs + local sizes = p.packets + if not sizes then + if d.bytesPerPacket > 0 then + local n = (p.dataEnd - p.dataStart) // d.bytesPerPacket + sizes = table.create(n, d.bytesPerPacket) + else + return nil, Err.new(Err.CORRUPT, "compressed CAF without a packet table") + end + end + local offsets = table.create(#sizes, 0) + local o = p.dataStart + for i, s in sizes :: { number } do + offsets[i] = o + o += s + if o > p.dataEnd then + -- a truncated file: keep the whole packets + offsets[i] = nil :: any + sizes = table.move(sizes :: { number }, 1, i - 1, 1, {}) + break + end + end + local count = #(sizes :: { number }) + local fpp = d.framesPerPacket + local pf = p.packetFrames + local function framesOf(i: number): number + return if pf then pf[i] else fpp + end + local cookie = p.cookie + if fmt == "alac" then + if not cookie then + return nil, Err.new(Err.CORRUPT, "ALAC without a magic cookie") + end + local cfg, err = Alac.config(cookie :: buffer) + if not cfg then + return nil, err + end + local dec = Alac.decoder(cfg) + local pcm = table.create(cfg.frameLength * cfg.channels, 0) + local scale = 1 / 2 ^ (cfg.bitDepth - 1) + return { + channels = cfg.channels, + rate = d.rate, + packetCount = count, + packetFrames = framesOf, + pcm = pcm, + reset = function() end, + codec = "alac", + bits = cfg.bitDepth, + decode = function(i: number): (number?, Err.Err?) + local n, e = dec:decode(b, offsets[i], (sizes :: { number })[i]) + if not n then + return nil, e + end + local src = dec.pcm + for k = 1, n * cfg.channels do + pcm[k] = src[k] * scale + end + return n, nil + end, + }, nil + elseif fmt == "aac " then + local asc = if cookie then esdsConfig(cookie :: buffer) else nil + if not asc then + return nil, Err.new(Err.CORRUPT, "AAC without an esds magic cookie") + end + local dec, err = Aac.decoder(asc :: buffer) + if not dec then + return nil, err + end + local ad = dec :: Aac.Decoder + return { + channels = ad.channels, + rate = d.rate, + packetCount = count, + packetFrames = framesOf, + pcm = ad.pcm, + reset = function() + ad:reset() + end, + codec = "aac", + decode = function(i: number): (number?, Err.Err?) + return ad:decode(b, offsets[i], (sizes :: { number })[i]) + end, + }, nil + end + return nil, Err.new(Err.UNSUPPORTED, "CAF format '" .. fmt .. "'") +end + +function Caf.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local p, err = parse(r, opts or {}) + if not p then + return nil, err + end + local s, serr = source(r, p :: Parsed) + if not s then + return nil, serr + end + local src = s :: Source + local ch, rate = src.channels, src.rate + local starts = table.create(src.packetCount + 1, 0) + local total = 0 + for i = 1, src.packetCount do + starts[i] = total + total += src.packetFrames(i) + end + starts[src.packetCount + 1] = total + local skip = math.max(0, p.priming) + local stopAt = total + if p.validFrames and p.validFrames >= 0 then + stopAt = math.min(total, skip + p.validFrames) + elseif p.remainder > 0 then + stopAt = math.max(skip, total - p.remainder) + end + local frames = math.max(0, stopAt - skip) + local nextPacket = 1 + local decoded = 0 + local pendPos, pendN = 0, 0 + local dropUntil = skip + local pos = 0 + local failed: Err.Err? = nil + local dec: any = { + sampleRate = rate, + channels = ch, + frames = frames, + duration = frames / rate, + bitrate = if frames > 0 then math.floor((p.dataEnd - p.dataStart) * 8 * rate / frames) else 0, + tags = p.tags, + codec = src.codec, + bitsPerSample = src.bits, + error = nil, + } + local function fill(): boolean + while true do + if nextPacket > src.packetCount or decoded >= stopAt then + return false + end + local i = nextPacket + nextPacket += 1 + local start = starts[i] + local n, e = src.decode(i) + if not n then + failed = e + dec.error = e + return false + end + decoded = start + n + local a = math.max(start, dropUntil) + local b = math.min(decoded, stopAt) + if b > a then + pendPos, pendN = a - start, b - start + return true + end + end + end + function dec.read(_self: any, n: number, out: buffer?): (buffer, number) + local want = math.max(0, math.floor(n)) + local need = want * ch * 4 + local ob = if out and buffer.len(out) >= need then out else buffer.create(need) + local got = 0 + local writef32 = buffer.writef32 + while got < want do + if pendPos >= pendN then + if failed or not fill() then + break + end + end + local take = math.min(want - got, pendN - pendPos) + local q = got * ch * 4 + local sidx = pendPos * ch + local pcm = src.pcm + for k = 1, take * ch do + writef32(ob, q, pcm[sidx + k]) + q += 4 + end + pendPos += take + got += take + end + pos += got + return ob, got + end + function dec.seek(_self: any, seconds: number) + local target = math.clamp(math.floor(seconds * rate + 0.5), 0, frames) + skip + local lo, hi, found = 1, src.packetCount, 1 + while lo <= hi do + local mid = (lo + hi) // 2 + if starts[mid] <= target then + found = mid + lo = mid + 1 + else + hi = mid - 1 + end + end + if src.codec == "aac" then + found = math.max(1, found - 1) + end + src.reset() + nextPacket = found + decoded = starts[found] + dropUntil = target + pendPos, pendN = 0, 0 + failed = nil + pos = target - skip + end + function dec.position(_self: any): number + return pos / rate + end + if src.packetCount > 0 and frames > 0 and not fill() and failed then + return nil, failed + end + return dec, nil +end + +function Caf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = Caf.open(r, opts) + if not dec then + return nil, err + end + local d: any = dec + local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames) + local done = 0 + while done < d.frames do + local b, n = d:read(math.min(65536, d.frames - done)) + if n == 0 then + break + end + buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4) + done += n + end + if d.error then + return nil, d.error + end + audio.tags = d.tags + audio.meta.source = { format = "caf", codec = d.codec, bitsPerSample = d.bitsPerSample } + return audio, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function chunk(w: Bytes.Writer, typ: string, size: number) + w:string(typ) + w:i64be(size) +end + +-- encode(audio | decoder, opts?) -> buffer | nil, Err +function Caf.encode(value: any, opts: EncodeOptions?): (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") + end + local codec = o.codec or "alac" + if codec ~= "alac" and codec ~= "pcm" then + return nil, Err.new(Err.ARG, "codec must be 'alac' or 'pcm'") + end + local sr, ch = value.sampleRate, value.channels + local depth = o.bitDepth or 16 + if codec == "pcm" and depth ~= 16 and depth ~= 24 and depth ~= 32 then + return nil, Err.new(Err.ARG, "pcm bitDepth 16, 24 or 32 (float)") + end + if ch < 1 or ch > 64 or sr <= 0 then + return nil, Err.new(Err.ARG, "bad sample rate / channels") + end + -- the source frames + local isAudio = value.kind == "audio" and type(value.samples) == "buffer" + if not isAudio and type(value.read) ~= "function" then + return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") + end + if isAudio and buffer.len(value.samples) < value.frames * ch * 4 then + return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels") + end + local done = 0 + local chunkBuf: buffer? = nil + local function nextBlock(n: number): (buffer?, number, number) + if isAudio then + local k = math.min(n, value.frames - done) + local base = done * ch * 4 + done += k + return value.samples, base, k + end + local b, got = value:read(n, chunkBuf) + chunkBuf = b + done += got + return b, 0, got + end + local readf32 = buffer.readf32 + local data = Bytes.writer(65536) + local sizes: { number } = {} + local enc: Alac.Encoder? = nil + if codec == "alac" then + local e, err = Alac.encoder({ sampleRate = math.floor(sr), channels = ch, bitDepth = depth }) + if not e then + return nil, err + end + enc = e + local ints = table.create(4096 * ch, 0) + local peak = 2 ^ (depth - 1) + while true do + local b, base, n = nextBlock(4096) + if not b or n <= 0 then + break + end + for i = 0, n * ch - 1 do + local v = math.floor(readf32(b, base + i * 4) * peak + 0.5) + ints[i + 1] = math.clamp(v, -peak, peak - 1) + end + local pkt, perr = (e :: Alac.Encoder):encode(ints, 1, n) + if not pkt then + return nil, perr + end + data:bytes(pkt) + table.insert(sizes, buffer.len(pkt)) + end + else + local peak = 2 ^ (depth - 1) + while true do + local b, base, n = nextBlock(4096) + if not b or n <= 0 then + break + end + for i = 0, n * ch - 1 do + local f = readf32(b, base + i * 4) + if depth == 32 then + data:f32be(f) + else + local v = math.clamp(math.floor(f * peak + 0.5), -peak, peak - 1) + if depth == 16 then + data:u16be(v % 65536) + else + data:u24be(v % 16777216) + end + end + end + end + end + local frames = done + local w = Bytes.writer(data:tell() + 1024) + w:string("caff") + w:u16be(1) + w:u16be(0) + chunk(w, "desc", 32) + w:f64be(sr) + if codec == "alac" then + w:string("alac") + w:u32be(({ [16] = 1, [20] = 2, [24] = 3, [32] = 4 })[depth] or 1) + w:u32be(0) + w:u32be(4096) + w:u32be(ch) + w:u32be(0) + else + w:string("lpcm") + w:u32be(if depth == 32 then 1 else 0) -- float / big-endian integer + w:u32be(ch * depth // 8) + w:u32be(1) + w:u32be(ch) + w:u32be(depth) + end + local tags = o.tags or value.tags or {} + local keys = {} + for k, v in tags do + if type(v) == "string" then + table.insert(keys, k) + end + end + table.sort(keys) + if #keys > 0 then + local info = Bytes.writer(256) + info:u32be(#keys) + for _, k in keys do + info:cstring(TAG_INFO[k] or k) + info:cstring(tags[k]) + end + chunk(w, "info", info:tell()) + w:bytes(info.buf, 0, info:tell()) + end + if enc then + local cookie = Alac.cookie(enc.config) + chunk(w, "kuki", buffer.len(cookie)) + w:bytes(cookie) + local pk = Bytes.writer(64 + #sizes * 2) + pk:i64be(#sizes) + pk:i64be(frames) + pk:u32be(0) + pk:u32be(#sizes * 4096 - frames) + for _, s in sizes do + -- BER variable-length integer + local bytes = { s % 128 } + local v = s // 128 + while v > 0 do + table.insert(bytes, 1, 128 + v % 128) + v //= 128 + end + for _, x in bytes do + pk:u8(x) + end + end + chunk(w, "pakt", pk:tell()) + w:bytes(pk.buf, 0, pk:tell()) + end + chunk(w, "data", data:tell() + 4) + w:u32be(0) -- edit count + w:bytes(data.buf, 0, data:tell()) + return w:finish(), nil +end + +return Caf diff --git a/src/Formats/audio/m4a/init.luau b/src/Formats/audio/m4a/init.luau new file mode 100644 index 0000000..39e9589 --- /dev/null +++ b/src/Formats/audio/m4a/init.luau @@ -0,0 +1,439 @@ +--!strict +-- audio/m4a: MPEG-4 audio files (M4A / M4B / MP4 / MOV audio tracks) through containers/IsoBmff. Supports: reading +-- AAC-LC (codecs/Aac; HE-AAC files play their AAC-LC core at the core rate) and ALAC (codecs/Alac) tracks, gapless +-- trimming through the edit list (encoder priming / padding), seeking, iTunes tags and cover art (dec.pictures); +-- writing ALAC (16 / 20 / 24-bit, 1 - 8 channels) with tags and cover art. Not supported: writing AAC, other codecs +-- inside MP4 (MP3 / Opus / FLAC / AC-3: UNSUPPORTED), encrypted files. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local IsoBmff = require("@formats/containers/IsoBmff") +local Aac = require("@formats/codecs/Aac") +local Alac = require("@formats/codecs/Alac") + +-- ------------------------------------------------------------------------------------------------ contract +local M4a = { + name = "m4a", + category = "audio", + extensions = { "m4a", "m4b", "m4r", "aac.mp4" }, + mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac" }, + caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + track: number?, -- the track id to play (default: the first AAC / ALAC track) + gapless: boolean?, -- apply the edit list (default true) + maxSamples: number?, -- sample table limit (default 2^25) +} +export type EncodeOptions = { + bitDepth: number?, -- 16 (default), 20 or 24 + frameLength: number?, -- samples per packet, default 4096 + tags: Types.Tags?, -- default: the audio's tags + pictures: { { mime: string, data: buffer } }?, -- cover art (default: audio.meta.pictures) +} + +-- ------------------------------------------------------------------------------------------------ constants +local AUDIO_BRANDS: { [string]: number } = { ["M4A "] = 1, ["M4B "] = 1, ["M4P "] = 1, ["M4V "] = 0.3 } + +-- ------------------------------------------------------------------------------------------------ sniff +function M4a.sniff(r: Bytes.Reader): number + local brand = IsoBmff.sniff(r) + if brand == nil then + return 0 + end + if AUDIO_BRANDS[brand] then + return AUDIO_BRANDS[brand] + end + if brand == "avif" or brand == "avis" or brand == "heic" or brand == "heix" or brand == "mif1" or brand == "msf1" or brand == "crx " then + return 0 + end + return 0.4 -- an MP4 / MOV that may hold audio; a video format claims it more strongly +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the packet decoder of a track: decode(buf, off, len) -> frames | nil, Err; pcm: interleaved floats +type PacketDecoder = { + channels: number, + sampleRate: number, + frameSize: number, + pcm: { number }, + decode: (buf: buffer, off: number, len: number) -> (number?, Err.Err?), + reset: () -> (), +} + +local function packetDecoder(t: IsoBmff.Track): (PacketDecoder?, Err.Err?) + if not t.config then + return nil, Err.new(Err.CORRUPT, "track " .. t.id .. " (" .. t.codec .. ") has no codec configuration") + end + if t.codec == "alac" then + local cfg, err = Alac.config(t.config :: buffer) + if not cfg then + return nil, err + end + local dec = Alac.decoder(cfg) + local pcm = table.create(cfg.frameLength * cfg.channels, 0) + local scale = 1 / 2 ^ (cfg.bitDepth - 1) + local pd: PacketDecoder = { + channels = cfg.channels, + sampleRate = if cfg.sampleRate > 0 then cfg.sampleRate else (t.sampleRate or 44100), + frameSize = cfg.frameLength, + pcm = pcm, + decode = function(buf: buffer, off: number, len: number): (number?, Err.Err?) + local n, e = dec:decode(buf, off, len) + if not n then + return nil, e + end + local src = dec.pcm + for i = 1, n * cfg.channels do + pcm[i] = src[i] * scale + end + return n, nil + end, + reset = function() end, + } + return pd, nil + elseif t.codec == "aac" then + local dec, err = Aac.decoder(t.config :: buffer) + if not dec then + return nil, err + end + local d = dec :: Aac.Decoder + local pd: PacketDecoder = { + channels = d.channels, + sampleRate = d.sampleRate, + frameSize = d.frameLength, + pcm = d.pcm, + decode = function(buf: buffer, off: number, len: number): (number?, Err.Err?) + return d:decode(buf, off, len) + end, + reset = function() + d:reset() + end, + } + return pd, nil + end + return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. t.codec .. " in MP4") +end + +-- open(r, opts?) -> Types.Decoder | nil, Err +function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?) + local o = opts or {} + local movie, err = IsoBmff.parse(r, { maxSamples = o.maxSamples }) + if not movie then + return nil, err + end + local track: IsoBmff.Track? = nil + local other: IsoBmff.Track? = nil + for _, t in movie.tracks do + if t.kind == "audio" then + if o.track and t.id ~= o.track then + continue + end + if t.codec == "aac" or t.codec == "alac" then + track = t + break + end + other = other or t + end + end + if not track then + if other then + return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. other.codec .. " in MP4") + end + return nil, Err.new(Err.CORRUPT, "no audio track") + end + local t = track :: IsoBmff.Track + local pd, perr = packetDecoder(t) + if not pd then + return nil, perr + end + local p = pd :: PacketDecoder + local channels, sr = p.channels, p.sampleRate + -- media ticks -> sample frames + local tickScale = sr / t.timescale + local gapless = o.gapless ~= false + local skip = if gapless then math.floor(t.skip * tickScale + 0.5) else 0 + local total = 0 + for i = 1, t.sampleCount do + total += t.durations[i] + end + total = math.floor(total * tickScale + 0.5) + if gapless and t.playDuration then + total = math.min(total, skip + math.floor(t.playDuration * tickScale + 0.5)) + end + local tags, pictures = IsoBmff.tags(r, movie) + -- iTunes gapless info (fdkaac, iTunes) when there is no edit list: " 0 ..." (hex) + local smpb = tags.iTunSMPB + if gapless and not t.edits and smpb then + local f = {} + for w in string.gmatch(smpb, "%x+") do + table.insert(f, tonumber(w, 16)) + end + if #f >= 4 and f[2] and f[4] and f[4] > 0 and f[2] + f[4] <= total then + skip = f[2] + total = f[2] + f[4] + end + end + local frames = math.max(0, total - skip) + local buf = r.buf + -- streaming state + local nextPacket = 1 + local decoded = 0 -- frames produced by the packets decoded so far (before trimming) + local pend, pendPos, pendN = p.pcm, 0, 0 -- the current packet: frames pendPos .. pendN - 1 not yet returned + local dropUntil = skip -- absolute frame index of the first frame to return + local stopAt = total + local pos = 0 -- frames returned + local failed: Err.Err? = nil + + local dec: any = { + sampleRate = sr, + channels = channels, + frames = frames, + duration = frames / sr, + bitrate = if movie.duration > 0 then math.floor((r.limit - r.base) * 8 / math.max(frames / sr, 1e-9)) else 0, + tags = tags, + pictures = pictures, + codec = t.codec, + track = t, + movie = movie, + error = nil, + } + if t.bitrate then + dec.bitrate = t.bitrate + end + + -- decode the next packet into pend; false at the end / on an error + local function fill(): boolean + while true do + if nextPacket > t.sampleCount or decoded >= stopAt then + return false + end + local i = nextPacket + nextPacket += 1 + local start = decoded + local n, e = p.decode(buf, t.offsets[i], t.sizes[i]) + if not n then + failed = e + dec.error = e + return false + end + decoded += n + -- the part of this packet inside [dropUntil, stopAt) + local a = math.max(start, dropUntil) + local b = math.min(decoded, stopAt) + if b > a then + pendPos = a - start + pendN = b - start + return true + end + end + end + + function dec.read(_self: any, n: number, out: buffer?): (buffer, number) + local want = math.max(0, math.floor(n)) + local need = want * channels * 4 + local ob = if out and buffer.len(out) >= need then out else buffer.create(need) + local got = 0 + local writef32 = buffer.writef32 + while got < want do + if pendPos >= pendN then + if failed or not fill() then + break + end + end + local take = math.min(want - got, pendN - pendPos) + local src = pend + local o = got * channels * 4 + local s = pendPos * channels + for k = 1, take * channels do + writef32(ob, o, src[s + k]) + o += 4 + end + pendPos += take + got += take + end + pos += got + return ob, got + end + + function dec.seek(_self: any, seconds: number) + local target = math.clamp(math.floor(seconds * sr + 0.5), 0, frames) + skip -- absolute frame + -- the last packet starting at or before the target, minus one for the codec's overlap (AAC) + local ticks = target / tickScale + local lo, hi, found = 1, t.sampleCount, 1 + while lo <= hi do + local mid = (lo + hi) // 2 + if t.dts[mid] <= ticks then + found = mid + lo = mid + 1 + else + hi = mid - 1 + end + end + local startPacket = if t.codec == "aac" then math.max(1, found - 1) else found + p.reset() + nextPacket = startPacket + decoded = math.floor((t.dts[startPacket] or 0) * tickScale + 0.5) + dropUntil = math.max(target, skip) + pendPos, pendN = 0, 0 + failed = nil + pos = target - skip + end + + function dec.position(_self: any): number + return pos / sr + end + + -- prime: surface a broken first packet as an open error + if t.sampleCount > 0 and frames > 0 then + if not fill() and failed then + return nil, failed + end + end + return dec, nil +end + +-- decode(r, opts?) -> Types.Audio | nil, Err (the whole stream, tags, cover pictures in meta.pictures) +function M4a.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?) + local dec, err = M4a.open(r, opts) + if not dec then + return nil, err + end + local d: any = dec + local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames) + local done = 0 + local chunk = buffer.create(65536 * d.channels * 4) + while done < d.frames do + local b, n = d:read(math.min(65536, d.frames - done), chunk) + if n == 0 then + break + end + buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4) + done += n + end + if d.error then + return nil, d.error + end + if done < d.frames then + local short = buffer.create(done * d.channels * 4) + buffer.copy(short, 0, audio.samples, 0, buffer.len(short)) + audio.samples = short + audio.frames = done + end + audio.tags = d.tags + audio.meta.source = { format = "m4a", codec = d.codec, bitsPerSample = d.track.bitsPerSample, brand = d.movie.brand } + if #d.pictures > 0 then + audio.meta.pictures = d.pictures + end + return audio, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(audio | decoder, opts?) -> buffer | nil, Err: an ALAC M4A +function M4a.encode(value: any, opts: EncodeOptions?): (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") + end + local sr, ch = value.sampleRate, value.channels + local enc, eerr = Alac.encoder({ sampleRate = sr, channels = ch, bitDepth = o.bitDepth or 16, frameLength = o.frameLength }) + if not enc then + return nil, eerr + end + local e = enc :: Alac.Encoder + local depth = e.config.bitDepth + local fl = e.config.frameLength + local peak = 2 ^ (depth - 1) + local packets: { buffer } = {} + local durations: { number } = {} + local ints = table.create(fl * ch, 0) + local floor = math.floor + local readf32 = buffer.readf32 + -- frames from an Audio buffer or a streaming Decoder + local src: buffer, srcFrames = nil :: any, 0 + local isAudio = value.kind == "audio" and type(value.samples) == "buffer" + if isAudio then + src, srcFrames = value.samples, value.frames + if buffer.len(src) < srcFrames * ch * 4 then + return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels") + end + elseif type(value.read) ~= "function" then + return nil, Err.new(Err.ARG, "expected an Audio or a Decoder") + end + local done = 0 + local chunk: buffer? = nil + while true do + local n, b, base + if isAudio then + n = math.min(fl, srcFrames - done) + b, base = src, done * ch * 4 + else + local got + b, got = value:read(fl, chunk) + chunk = b + n, base = got, 0 + end + if n <= 0 then + break + end + for i = 0, n * ch - 1 do + local v = floor(readf32(b, base + i * 4) * peak + 0.5) + if v >= peak then + v = peak - 1 + elseif v < -peak then + v = -peak + end + ints[i + 1] = v + end + local pkt, perr = e:encode(ints, 1, n) + if not pkt then + return nil, perr + end + table.insert(packets, pkt) + table.insert(durations, n) + done += n + if isAudio and done >= srcFrames then + break + end + end + local tags = o.tags or value.tags or {} + local pictures = o.pictures or (value.meta and value.meta.pictures) or nil + local timescale = if sr < 65536 then sr else 0 + local file, merr = IsoBmff.mux({ + brand = "M4A ", + minor = 0, + compatible = { "M4A ", "mp42", "isom" }, + timescale = 1000, + tracks = { + { + kind = "audio", + entry = "alac", + timescale = if timescale > 0 then timescale else 48000, + samples = packets, + durations = if timescale > 0 then durations else (function() + local d = {} + for i, v in durations do + d[i] = math.floor(v * 48000 / sr + 0.5) + end + return d + end)(), + sampleRate = sr, + channels = ch, + bitsPerSample = depth, + config = Alac.cookie(e.config), + }, + }, + tags = tags, + pictures = pictures, + }) + if not file then + return nil, merr + end + return file, nil +end + +return M4a diff --git a/src/Formats/codecs/Aac/Decode.luau b/src/Formats/codecs/Aac/Decode.luau new file mode 100644 index 0000000..ce4a88b --- /dev/null +++ b/src/Formats/codecs/Aac/Decode.luau @@ -0,0 +1,903 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Aac/Decode: the AAC-LC raw_data_block decoder (ISO/IEC 14496-3 subpart 4): SCE / CPE / LFE / DSE / PCE / +-- FIL / END elements, ics_info with window grouping, section data, scalefactors (with noise energies and intensity +-- positions), pulse data, TNS, the eleven spectral codebooks with escapes, dequantisation, M/S and intensity stereo, +-- perceptual noise substitution (FFmpeg's LCG so the noise matches it), the filterbank (sine / KBD windows, the four +-- window sequences, IMDCT through codecs/Mdct, overlap-add). FIL extension payloads (SBR / PS) are reported to a hook +-- and otherwise skipped. Written from the standard; no third-party code. Never throws: returns nil, message. +local Mdct = require("@formats/codecs/Mdct") +local Tables = require("@formats/codecs/Aac/Tables") + +local readu32, byteswap, lshift, rshift, band = buffer.readu32, bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band +local floor, sqrt, abs = math.floor, math.sqrt, math.abs + +local Decode = {} + +local ONLY_LONG, LONG_START, EIGHT_SHORT, LONG_STOP = 0, 1, 2, 3 +local ZERO_HCB, ESC_HCB, NOISE_HCB, INTENSITY_HCB2, INTENSITY_HCB = 0, 11, 13, 14, 15 + +-- ------------------------------------------------------------------------------------------------ bit reader +-- one packet at a time: module-level cursor over a zero-padded copy (a frame decode never yields) +local B: buffer = buffer.create(16) +local BP = 0 -- bit position +local BL = 0 -- bit limit +local OVER = false + +local function getBits(n: number): number -- 1 .. 25 + local p = BP + BP = p + n + if p > BL then + OVER = true + return 0 + end + return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n) +end +local function peekBits(n: number): number + local p = BP + if p > BL then + return 0 + end + return rshift(lshift(byteswap(readu32(B, rshift(p, 3))), band(p, 7)), 32 - n) +end +local function getLong(n: number): number + if n > 24 then + local hi = getBits(n - 16) + return hi * 65536 + getBits(16) + end + return getBits(n) +end + +-- ------------------------------------------------------------------------------------------------ Huffman +local PEEK = 10 +type Book = { tab: { number }, map: { [number]: number }, maxLen: number } + +local function book(codes: { number }, bits: { number }): Book + local tab = table.create(2 ^ PEEK, 0) + local map = {} + local maxLen = 0 + for s = 1, #codes do + local c, l = codes[s], bits[s] + maxLen = math.max(maxLen, l) + if l <= PEEK then + local shift = 2 ^ (PEEK - l) + for k = 0, shift - 1 do + tab[c * shift + k + 1] = (s - 1) * 32 + l + end + else + map[l * 2 ^ 20 + c] = s - 1 + end + end + return { tab = tab, map = map, maxLen = maxLen } +end + +local SF_BOOK = book(Tables.SF_CODES, Tables.SF_BITS) +local SPEC_BOOK: { Book } = {} +for i = 1, 11 do + SPEC_BOOK[i] = book(Tables.SPEC_CODES[i], Tables.SPEC_BITS[i]) +end + +-- the next symbol of a book, -1 for an invalid code +local function huff(bk: Book): number + local e = bk.tab[peekBits(PEEK) + 1] + if e > 0 then + BP += band(e, 31) + return rshift(e, 5) + end + -- a code longer than PEEK bits + local code = getBits(PEEK) + local map = bk.map + for l = PEEK + 1, bk.maxLen do + code = code * 2 + getBits(1) + local s = map[l * 1048576 + code] + if s then + return s + end + end + return -1 +end + +-- per codebook: dimension, unsigned, modulus, offset +local DIM = { 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2 } +local UNSIGNED = { false, false, true, true, false, false, true, true, true, true, true } +local MOD = { 3, 3, 3, 3, 9, 9, 8, 8, 13, 13, 17 } +local OFF = { 1, 1, 0, 0, 4, 4, 0, 0, 0, 0, 0 } + +-- |q|^(4/3) +local POW43 = table.create(8192, 0) +for i = 0, 8191 do + POW43[i + 1] = i ^ (4 / 3) +end + +-- ------------------------------------------------------------------------------------------------ windows +local SINE_LONG = Mdct.window("sine", 2048) :: { number } +local KBD_LONG = Mdct.window("kbd", 2048, 4) :: { number } +local SINE_SHORT = Mdct.window("sine", 256) :: { number } +local KBD_SHORT = Mdct.window("kbd", 256, 6) :: { number } +local PLAN_LONG = Mdct.new(2048) :: Mdct.Plan +local PLAN_SHORT = Mdct.new(256) :: Mdct.Plan + +-- ------------------------------------------------------------------------------------------------ state +export type Channel = { + spec: { number }, -- 1024 dequantised coefficients (8 x 128 for short windows) + overlap: { number }, -- 1024 samples carried to the next frame + prevShape: number, + -- this frame's ics + windowSequence: number, + windowShape: number, + maxSfb: number, + numGroups: number, + groupLen: { number }, + bandType: { number }, -- [g * maxSfb + sfb + 1] + sf: { number }, + -- tns + tnsFilters: { { number } }, -- per window: { length, order, direction, coefs ... } flattened per filter +} + +export type State = { + sfIndex: number, + channels: number, -- configured channels (0: as found) + frameLength: number, + ch: { Channel }, + pcm: { number }, -- interleaved output floats + random: number, -- PNS generator state + time: { number }, -- 2048 IMDCT scratch + frame: { number }, -- 2048 windowed frame scratch + short: { number }, -- 256 scratch + onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?, + extensions: number, -- extension payloads seen (SBR / PS / ...) + sbr: boolean, -- an SBR payload was seen + map: { number }?, -- element channel order -> output channel (1-based) +} + +local function newChannel(): Channel + return { + spec = table.create(1024, 0), + overlap = table.create(1024, 0), + prevShape = 0, + windowSequence = 0, + windowShape = 0, + maxSfb = 0, + numGroups = 1, + groupLen = { 1, 0, 0, 0, 0, 0, 0, 0 }, + bandType = table.create(8 * 64, 0), + sf = table.create(8 * 64, 0), + tnsFilters = {}, + } +end +Decode.newChannel = newChannel + +-- ------------------------------------------------------------------------------------------------ ics +local function icsInfo(st: State, c: Channel): string? + if getBits(1) ~= 0 then + return "reserved ics bit set" + end + c.windowSequence = getBits(2) + c.windowShape = getBits(1) + if c.windowSequence == EIGHT_SHORT then + c.maxSfb = getBits(4) + local grouping = getBits(7) + local ng = 1 + local gl = c.groupLen + gl[1] = 1 + for w = 1, 7 do + if band(grouping, 2 ^ (6 - (w - 1))) ~= 0 then + gl[ng] += 1 + else + ng += 1 + gl[ng] = 1 + end + end + c.numGroups = ng + if c.maxSfb > Tables.NUM_SWB_SHORT[st.sfIndex + 1] then + return "max_sfb over the short band count" + end + else + c.maxSfb = getBits(6) + c.numGroups = 1 + c.groupLen[1] = 1 + if getBits(1) ~= 0 then + return "prediction (AAC Main / LTP) is not supported" + end + if c.maxSfb > Tables.NUM_SWB_LONG[st.sfIndex + 1] then + return "max_sfb over the long band count" + end + end + return nil +end + +local function sectionData(c: Channel): string? + local long = c.windowSequence ~= EIGHT_SHORT + local bits = if long then 5 else 3 + local esc = 2 ^ bits - 1 + local maxSfb = c.maxSfb + local bt = c.bandType + for g = 0, c.numGroups - 1 do + local k = 0 + while k < maxSfb do + local cb = getBits(4) + if cb == 12 then + return "reserved codebook 12" + end + local len = 0 + while true do + local inc = getBits(bits) + len += inc + if inc ~= esc then + break + end + if OVER then + return "section data runs past the end" + end + end + if k + len > maxSfb then + return "section runs past max_sfb" + end + for s = k, k + len - 1 do + bt[g * maxSfb + s + 1] = cb + end + k += len + if OVER then + return "section data runs past the end" + end + end + end + return nil +end + +local function scaleFactors(c: Channel, globalGain: number): string? + local sfv = globalGain + local noise = globalGain - 90 + local is = 0 + local firstNoise = true + local maxSfb = c.maxSfb + local bt, sf = c.bandType, c.sf + for g = 0, c.numGroups - 1 do + for s = 0, maxSfb - 1 do + local i = g * maxSfb + s + 1 + local cb = bt[i] + if cb == ZERO_HCB then + sf[i] = 0 + elseif cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then + local d = huff(SF_BOOK) + if d < 0 then + return "bad scalefactor code" + end + is += d - 60 + sf[i] = math.clamp(is, -155, 100) + elseif cb == NOISE_HCB then + if firstNoise then + noise += getBits(9) - 256 + firstNoise = false + else + local d = huff(SF_BOOK) + if d < 0 then + return "bad scalefactor code" + end + noise += d - 60 + end + sf[i] = math.clamp(noise, -100, 155) + else + local d = huff(SF_BOOK) + if d < 0 then + return "bad scalefactor code" + end + sfv += d - 60 + if sfv < 0 or sfv > 255 then + return "scalefactor out of range" + end + sf[i] = sfv + end + end + end + return nil +end + +local function tnsData(st: State, c: Channel): string? + local short = c.windowSequence == EIGHT_SHORT + local nw = if short then 8 else 1 + local filters = {} + for w = 1, nw do + local list = {} + local nFilt = getBits(if short then 1 else 2) + if nFilt > 0 then + local coefRes = getBits(1) + for _ = 1, nFilt do + local length = getBits(if short then 4 else 6) + local order = getBits(if short then 3 else 5) + local f = { length, order, 0 } + if order > (if short then 7 else 12) then + return "TNS order too high" + end + if order > 0 then + f[3] = getBits(1) + local compress = getBits(1) + local resBits = coefRes + 3 + local nb = resBits - compress + local iq = ((2 ^ (resBits - 1)) - 0.5) / (math.pi / 2) + local iqm = ((2 ^ (resBits - 1)) + 0.5) / (math.pi / 2) + local tmp = table.create(order, 0) + for k = 1, order do + local v = getBits(nb) + if v >= 2 ^ (nb - 1) then + v -= 2 ^ nb + end + tmp[k] = math.sin(v / (if v >= 0 then iq else iqm)) + end + -- parcor -> LPC + local a = table.create(order + 1, 0) + local b = table.create(order + 1, 0) + a[1] = 1 + for m = 1, order do + for i = 1, m - 1 do + b[i + 1] = a[i + 1] + tmp[m] * a[m - i + 1] + end + for i = 1, m - 1 do + a[i + 1] = b[i + 1] + end + a[m + 1] = tmp[m] + end + for k = 1, order do + f[3 + k] = a[k + 1] + end + end + table.insert(list, f) + end + end + filters[w] = list + end + c.tnsFilters = filters + local _ = st + return nil +end + +local function applyTns(st: State, c: Channel) + local short = c.windowSequence == EIGHT_SHORT + local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] + local numSwb = if short then Tables.NUM_SWB_SHORT[st.sfIndex + 1] else Tables.NUM_SWB_LONG[st.sfIndex + 1] + local maxBands = if short then Tables.TNS_MAX_BANDS_SHORT[st.sfIndex + 1] else Tables.TNS_MAX_BANDS_LONG[st.sfIndex + 1] + local mmm = math.min(maxBands, c.maxSfb) + if mmm == 0 then + return + end + local spec = c.spec + for w, list in c.tnsFilters do + local bottom = numSwb + for _, f in list do + local top = bottom + bottom = math.max(0, top - f[1]) + local order = f[2] + if order > 0 then + local start = swb[math.min(bottom, mmm) + 1] + local stop = swb[math.min(top, mmm) + 1] + local size = stop - start + if size > 0 then + local inc = 1 + local p = (w - 1) * 128 + start + 1 + if f[3] == 1 then + inc = -1 + p = (w - 1) * 128 + stop + end + for m = 0, size - 1 do + local y = spec[p] + local lim = if m < order then m else order + for i = 1, lim do + y -= spec[p - i * inc] * f[3 + i] + end + spec[p] = y + p += inc + end + end + end + end + end +end + +-- the spectral data of one channel, dequantised into c.spec (also pulses, noise, intensity zeros) +local function spectralData(st: State, c: Channel, pulses: { number }?): string? + local short = c.windowSequence == EIGHT_SHORT + local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] + local spec = c.spec + for i = 1, 1024 do + spec[i] = 0 + end + local maxSfb = c.maxSfb + local bt, sf = c.bandType, c.sf + local win = 0 + for g = 0, c.numGroups - 1 do + local glen = c.groupLen[g + 1] + for s = 0, maxSfb - 1 do + local idx = g * maxSfb + s + 1 + local cb = bt[idx] + local lo, hi = swb[s + 1], swb[s + 2] + local width = hi - lo + if cb == ZERO_HCB or cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then + -- zeros (intensity bands are filled from the other channel later) + continue + elseif cb == NOISE_HCB then + local scale = 2 ^ (0.25 * sf[idx]) + for w = 0, glen - 1 do + local base = (win + w) * 128 + lo + local energy = 0 + local r = st.random + for k = 1, width do + r = (r * 1664525 + 1013904223) % 4294967296 + local v = if r >= 2147483648 then r - 4294967296 else r + spec[base + k] = v + energy += v * v + end + st.random = r + local m = if energy > 0 then scale / sqrt(energy) else 0 + for k = 1, width do + spec[base + k] *= m + end + end + continue + end + local bk = SPEC_BOOK[cb] + local dim, uns, mod, off = DIM[cb], UNSIGNED[cb], MOD[cb], OFF[cb] + local gain = 2 ^ (0.25 * (sf[idx] - 100)) + for w = 0, glen - 1 do + local base = (win + w) * 128 + lo + local k = 0 + while k < width do + local sym = huff(bk) + if sym < 0 then + return "bad spectral code" + end + -- unpack the symbol into dim values (first value most significant) + local vals1, vals2, vals3, vals4 + if dim == 4 then + vals4 = sym % mod - off + sym = (sym - (sym % mod)) / mod + vals3 = sym % mod - off + sym = (sym - (sym % mod)) / mod + vals2 = sym % mod - off + sym = (sym - (sym % mod)) / mod + vals1 = sym % mod - off + else + vals2 = sym % mod - off + vals1 = (sym - (sym % mod)) / mod - off + end + if uns then + if vals1 ~= 0 and getBits(1) == 1 then + vals1 = -vals1 + end + if vals2 ~= 0 and getBits(1) == 1 then + vals2 = -vals2 + end + if dim == 4 then + if vals3 ~= 0 and getBits(1) == 1 then + vals3 = -vals3 + end + if vals4 ~= 0 and getBits(1) == 1 then + vals4 = -vals4 + end + end + if cb == ESC_HCB then + for e = 1, 2 do + local v = if e == 1 then vals1 else vals2 + if v == 16 or v == -16 then + local n = 0 + while getBits(1) == 1 do + n += 1 + if n > 8 or OVER then + return "bad escape" + end + end + local esc = 2 ^ (n + 4) + getBits(n + 4) + if v < 0 then + esc = -esc + end + if e == 1 then + vals1 = esc + else + vals2 = esc + end + end + end + end + end + local p = base + k + 1 + spec[p] = vals1 + spec[p + 1] = vals2 + if dim == 4 then + spec[p + 2] = vals3 + spec[p + 3] = vals4 + end + k += dim + end + if OVER then + return "spectral data runs past the end" + end + end + -- dequantise (pulses are added to the quantised values first: long windows only, applied below) + if not pulses then + for w = 0, glen - 1 do + local base = (win + w) * 128 + lo + for k = 1, width do + local q = spec[base + k] + if q ~= 0 then + local aq = if q < 0 then -q else q + local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain + spec[base + k] = if q < 0 then -v else v + end + end + end + end + end + win += glen + end + if pulses then + -- long window: add the pulses to the quantised values, then dequantise every band + for i = 1, #pulses, 2 do + local pos = pulses[i] + 1 + if pos <= 1024 then + local q = spec[pos] + spec[pos] = if q > 0 then q + pulses[i + 1] else q - pulses[i + 1] + end + end + for s = 0, maxSfb - 1 do + local idx = s + 1 + local cb = bt[idx] + if cb ~= ZERO_HCB and cb < NOISE_HCB then + local gain = 2 ^ (0.25 * (sf[idx] - 100)) + for k = swb[s + 1] + 1, swb[s + 2] do + local q = spec[k] + if q ~= 0 then + local aq = if q < 0 then -q else q + local v = (POW43[aq + 1] or aq ^ (4 / 3)) * gain + spec[k] = if q < 0 then -v else v + end + end + end + end + end + return nil +end + +-- individual_channel_stream +local function ics(st: State, c: Channel, commonWindow: boolean): string? + local globalGain = getBits(8) + if not commonWindow then + local e = icsInfo(st, c) + if e then + return e + end + end + local e = sectionData(c) + if e then + return e + end + e = scaleFactors(c, globalGain) + if e then + return e + end + local pulses: { number }? = nil + if getBits(1) == 1 then + if c.windowSequence == EIGHT_SHORT then + return "pulse data in a short window" + end + local n = getBits(2) + 1 + local startSfb = getBits(6) + if startSfb >= Tables.NUM_SWB_LONG[st.sfIndex + 1] then + return "bad pulse start band" + end + local pos = Tables.SWB_LONG[st.sfIndex + 1][startSfb + 1] + local list = {} + for _ = 1, n do + pos += getBits(5) + table.insert(list, pos) + table.insert(list, getBits(4)) + end + pulses = list + end + c.tnsFilters = {} + if getBits(1) == 1 then + e = tnsData(st, c) + if e then + return e + end + end + if getBits(1) == 1 then + return "gain control (AAC SSR) is not supported" + end + if OVER then + return "channel stream runs past the end" + end + return spectralData(st, c, pulses) +end + +-- ------------------------------------------------------------------------------------------------ stereo +local function msStereo(st: State, l: Channel, r: Channel, mask: { number }) + local short = l.windowSequence == EIGHT_SHORT + local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] + local maxSfb = l.maxSfb + local a, b = l.spec, r.spec + local win = 0 + for g = 0, l.numGroups - 1 do + local glen = l.groupLen[g + 1] + for s = 0, maxSfb - 1 do + local idx = g * maxSfb + s + 1 + if mask[idx] == 1 and l.bandType[idx] < NOISE_HCB and r.bandType[idx] < NOISE_HCB then + for w = 0, glen - 1 do + local base = (win + w) * 128 + for k = base + swb[s + 1] + 1, base + swb[s + 2] do + local m, sd = a[k], b[k] + a[k], b[k] = m + sd, m - sd + end + end + end + end + win += glen + end +end + +local function intensity(st: State, l: Channel, r: Channel, mask: { number }, msPresent: number) + local short = r.windowSequence == EIGHT_SHORT + local swb = if short then Tables.SWB_SHORT[st.sfIndex + 1] else Tables.SWB_LONG[st.sfIndex + 1] + local maxSfb = r.maxSfb + local a, b = l.spec, r.spec + local win = 0 + for g = 0, r.numGroups - 1 do + local glen = r.groupLen[g + 1] + for s = 0, maxSfb - 1 do + local idx = g * maxSfb + s + 1 + local cb = r.bandType[idx] + if cb == INTENSITY_HCB or cb == INTENSITY_HCB2 then + local sign = if cb == INTENSITY_HCB then 1 else -1 + if msPresent ~= 0 and mask[idx] == 1 then + sign = -sign + end + local scale = sign * 0.5 ^ (0.25 * r.sf[idx]) + for w = 0, glen - 1 do + local base = (win + w) * 128 + for k = base + swb[s + 1] + 1, base + swb[s + 2] do + b[k] = a[k] * scale + end + end + end + end + win += glen + end +end + +-- ------------------------------------------------------------------------------------------------ filterbank +local function filterbank(st: State, c: Channel, out: { number }, stride: number, offset: number) + local seq, shape, prev = c.windowSequence, c.windowShape, c.prevShape + local spec, overlap = c.spec, c.overlap + local frame = st.frame + local scale = 1 / 32768 + if seq == EIGHT_SHORT then + for i = 1, 2048 do + frame[i] = 0 + end + local tmp = st.short + local rise0 = if prev == 1 then KBD_SHORT else SINE_SHORT + local wcur = if shape == 1 then KBD_SHORT else SINE_SHORT + for w = 0, 7 do + Mdct.inverse(PLAN_SHORT, spec, w * 128 + 1, 1, tmp, 1, 2 / 256) + local rise = if w == 0 then rise0 else wcur + local base = 448 + w * 128 + for n = 1, 128 do + frame[base + n] += tmp[n] * rise[n] + frame[base + 128 + n] += tmp[128 + n] * wcur[128 + n] + end + end + else + local t = st.time + Mdct.inverse(PLAN_LONG, spec, 1, 1, t, 1, 2 / 2048) + -- left half + if seq == LONG_STOP then + local rise = if prev == 1 then KBD_SHORT else SINE_SHORT + for n = 1, 448 do + frame[n] = 0 + end + for n = 1, 128 do + frame[448 + n] = t[448 + n] * rise[n] + end + for n = 577, 1024 do + frame[n] = t[n] + end + else + local rise = if prev == 1 then KBD_LONG else SINE_LONG + for n = 1, 1024 do + frame[n] = t[n] * rise[n] + end + end + -- right half + if seq == LONG_START then + local fall = if shape == 1 then KBD_SHORT else SINE_SHORT + for n = 1025, 1472 do + frame[n] = t[n] + end + for n = 1, 128 do + frame[1472 + n] = t[1472 + n] * fall[128 + n] + end + for n = 1601, 2048 do + frame[n] = 0 + end + else + local fall = if shape == 1 then KBD_LONG else SINE_LONG + for n = 1025, 2048 do + frame[n] = t[n] * fall[n] + end + end + end + local p = offset + for n = 1, 1024 do + out[p] = (frame[n] + overlap[n]) * scale + overlap[n] = frame[1024 + n] + p += stride + end + c.prevShape = shape +end + +-- ------------------------------------------------------------------------------------------------ frame +-- frame(st, buf, off, len) -> channels decoded | nil, message. Output: st.pcm, 1024 frames interleaved. +function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?) + if buffer.len(B) < len + 16 then + B = buffer.create(len + 256) + end + buffer.copy(B, 0, buf, off, len) + buffer.fill(B, len, 0, 16) + BP, BL, OVER = 0, len * 8, false + local chans = st.ch + local nextCh = 1 + local order: { Channel } = {} + local lastElement = -1 + while true do + if BP + 3 > BL then + break -- tolerate a missing END + end + local id = getBits(3) + if id == 7 then + break + end + if id == 0 or id == 3 then -- SCE / LFE + getBits(4) + local c = chans[nextCh] + if not c then + c = newChannel() + chans[nextCh] = c + end + local e = ics(st, c, false) + if e then + return nil, e + end + applyTns(st, c) + table.insert(order, c) + nextCh += 1 + lastElement = id + elseif id == 1 then -- CPE + getBits(4) + local l, r = chans[nextCh], chans[nextCh + 1] + if not l then + l = newChannel() + chans[nextCh] = l + end + if not r then + r = newChannel() + chans[nextCh + 1] = r + end + local common = getBits(1) == 1 + local msPresent = 0 + local mask = table.create(8 * 64, 0) + if common then + local e = icsInfo(st, l) + if e then + return nil, e + end + r.windowSequence, r.windowShape, r.maxSfb, r.numGroups = l.windowSequence, l.windowShape, l.maxSfb, l.numGroups + for i = 1, 8 do + r.groupLen[i] = l.groupLen[i] + end + msPresent = getBits(2) + if msPresent == 1 then + for i = 1, l.numGroups * l.maxSfb do + mask[i] = getBits(1) + end + elseif msPresent == 2 then + for i = 1, l.numGroups * l.maxSfb do + mask[i] = 1 + end + elseif msPresent == 3 then + return nil, "reserved ms_mask_present" + end + end + local e = ics(st, l, common) + if e then + return nil, e + end + e = ics(st, r, common) + if e then + return nil, e + end + if common and msPresent ~= 0 then + msStereo(st, l, r, mask) + end + if common then + intensity(st, l, r, mask, msPresent) + end + applyTns(st, l) + applyTns(st, r) + table.insert(order, l) + table.insert(order, r) + nextCh += 2 + lastElement = id + elseif id == 2 then + return nil, "coupling channel elements are not supported" + elseif id == 4 then -- DSE + getBits(4) + local align = getBits(1) + local count = getBits(8) + if count == 255 then + count += getBits(8) + end + if align == 1 then + BP = (BP + 7) // 8 * 8 + end + BP += count * 8 + elseif id == 5 then -- PCE: skipped here (parsed from the configuration) + return nil, "program config element inside the stream is not supported" + elseif id == 6 then -- FIL + local count = getBits(4) + if count == 15 then + count += getBits(8) - 1 + end + if count > 0 then + local start = BP + local kind = getBits(4) + if kind == 13 or kind == 14 then -- EXT_SBR_DATA / EXT_SBR_DATA_CRC + st.sbr = true + end + st.extensions += 1 + local hook = st.onExtension + if hook then + hook(kind, lastElement, B, start, count * 8) + end + BP = start + count * 8 + end + end + if OVER or BP > BL then + return nil, "frame runs past the end" + end + if nextCh > 9 then + return nil, "more than 8 channels" + end + end + local n = #order + if n == 0 then + return 0, nil + end + local pcm = st.pcm + local map = st.map + for i, c in order do + local o = if map and map[i] then map[i] else i + filterbank(st, c, pcm, n, o) + end + return n, nil +end + +function Decode.state(sfIndex: number): State + return { + sfIndex = sfIndex, + channels = 0, + frameLength = 1024, + ch = {}, + pcm = table.create(1024 * 8, 0), + random = 0x1f2e3d4c, + time = table.create(2048, 0), + frame = table.create(2048, 0), + short = table.create(256, 0), + onExtension = nil, + extensions = 0, + sbr = false, + map = nil, + } +end + +local _ = abs +local _2 = floor +return Decode diff --git a/src/Formats/codecs/Aac/Tables.luau b/src/Formats/codecs/Aac/Tables.luau new file mode 100644 index 0000000..65305fb --- /dev/null +++ b/src/Formats/codecs/Aac/Tables.luau @@ -0,0 +1,335 @@ +--!strict +-- codecs/Aac/Tables: the AAC-LC tables of ISO/IEC 14496-3 (subpart 4, Annex 4.A): the scalefactor and the eleven +-- spectral Huffman codebooks (code, length per symbol), the scalefactor band offsets per sampling rate (1024 and 128 +-- lines) and the TNS band limits. Transcribed from FFmpeg libavcodec/aactab.c (tables of the standard, no code; +-- see licenses/NOTICE.md). Generated; do not edit. +local Tables = {} + +Tables.SF_CODES = { + 262120, 262118, 262119, 262117, 524277, 524273, 524269, 524278, 524270, 524271, 524272, 524284, 524285, 524287, 524286, 524279, + 524280, 524283, 524281, 262116, 524282, 262115, 131055, 131056, 65525, 131054, 65522, 65523, 65524, 65521, 32758, 32759, + 16377, 16373, 16375, 16371, 16374, 16370, 8183, 8181, 4089, 4087, 4086, 2041, 4084, 2040, 1017, 1015, + 1013, 504, 503, 250, 248, 246, 121, 58, 56, 26, 11, 4, 0, 10, 12, 27, + 57, 59, 120, 122, 247, 249, 502, 505, 1012, 1014, 1016, 2037, 2036, 2038, 2039, 4085, + 4088, 8180, 8182, 8184, 16376, 16372, 65520, 32756, 65526, 32757, 262114, 524249, 524250, 524251, 524252, 524253, + 524254, 524248, 524242, 524243, 524244, 524245, 524246, 524274, 524255, 524263, 524264, 524265, 524266, 524267, 524262, 524256, + 524257, 524258, 524259, 524260, 524261, 524247, 524268, 524276, 524275, +} + +Tables.SF_BITS = { + 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 18, 19, 18, 17, 17, 16, 17, 16, 16, 16, 16, + 15, 15, 14, 14, 14, 14, 14, 14, 13, 13, 12, 12, 12, 11, 12, 11, 10, 10, 10, 9, 9, 8, 8, 8, 7, 6, 6, 5, 4, 3, + 1, 4, 4, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 16, 15, 16, 15, + 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, + 19, +} + +Tables.SPEC_CODES = { + { + 2040, 497, 2045, 1013, 104, 1008, 2039, 492, 2037, 1009, 114, 1012, 116, 17, 118, 491, + 108, 1014, 2044, 481, 2033, 496, 97, 502, 2034, 490, 2043, 498, 105, 493, 119, 23, + 111, 486, 100, 485, 103, 21, 98, 18, 0, 20, 101, 22, 109, 489, 99, 484, + 107, 19, 113, 483, 112, 499, 2046, 487, 2035, 495, 96, 494, 2032, 482, 2042, 1011, + 106, 488, 117, 16, 115, 500, 110, 1015, 2038, 480, 2041, 1010, 102, 501, 2047, 503, + 2036, + }, + { + 499, 111, 509, 235, 35, 234, 503, 232, 506, 242, 45, 112, 32, 6, 43, 110, + 40, 233, 505, 102, 248, 231, 27, 241, 500, 107, 501, 236, 42, 108, 44, 10, + 39, 103, 26, 245, 36, 8, 31, 9, 0, 7, 29, 11, 48, 239, 28, 100, + 30, 12, 41, 243, 47, 240, 508, 113, 498, 244, 33, 230, 247, 104, 504, 238, + 34, 101, 49, 2, 38, 237, 37, 106, 507, 114, 510, 105, 46, 246, 511, 109, + 502, + }, + { + 0, 9, 239, 11, 25, 240, 491, 486, 1010, 10, 53, 495, 52, 55, 489, 493, + 487, 1011, 494, 1005, 8186, 492, 498, 2041, 2040, 1016, 4088, 8, 56, 1014, 54, 117, + 1009, 1003, 1004, 4084, 24, 118, 2036, 57, 116, 1007, 499, 500, 2038, 488, 1002, 8188, + 242, 497, 4091, 1013, 2035, 4092, 238, 1015, 32766, 496, 2037, 32765, 8187, 16378, 65535, 241, + 1008, 16380, 490, 1006, 16379, 4086, 4090, 32764, 2034, 4085, 65534, 1012, 2039, 32763, 4087, 4089, + 32762, + }, + { + 7, 22, 246, 24, 8, 239, 495, 243, 2040, 25, 23, 237, 21, 1, 226, 240, + 112, 1008, 494, 241, 2042, 238, 228, 1010, 2038, 1007, 2045, 5, 20, 242, 9, 4, + 229, 244, 232, 1012, 6, 2, 231, 3, 0, 107, 227, 105, 499, 235, 230, 1014, + 110, 106, 500, 1004, 496, 1017, 245, 236, 2043, 234, 111, 1015, 2041, 1011, 4095, 233, + 109, 1016, 108, 104, 501, 1006, 498, 2036, 2039, 1009, 4094, 1005, 497, 2037, 2046, 1013, + 2044, + }, + { + 8191, 4087, 2036, 2024, 1009, 2030, 2041, 4088, 8189, 4093, 2033, 1000, 488, 240, 492, 1006, + 2034, 4090, 4084, 1007, 498, 232, 112, 236, 496, 1002, 2035, 2027, 491, 234, 26, 8, + 25, 238, 495, 2029, 1008, 242, 115, 11, 0, 10, 113, 243, 2025, 2031, 494, 239, + 24, 9, 27, 235, 489, 2028, 2038, 1003, 499, 237, 114, 233, 497, 1005, 2039, 4086, + 2032, 1001, 493, 241, 490, 1004, 2040, 4089, 8188, 4092, 4085, 2026, 1011, 1010, 2037, 4091, + 8190, + }, + { + 2046, 1021, 497, 491, 500, 490, 496, 1020, 2045, 1014, 485, 234, 108, 113, 104, 240, + 486, 1015, 499, 239, 50, 39, 40, 38, 49, 235, 503, 488, 111, 46, 8, 4, + 6, 41, 107, 494, 495, 114, 45, 2, 0, 3, 47, 115, 506, 487, 110, 43, + 7, 1, 5, 44, 109, 492, 505, 238, 48, 36, 42, 37, 51, 236, 498, 1016, + 484, 237, 106, 112, 105, 116, 241, 1018, 2047, 1017, 502, 493, 504, 489, 501, 1019, + 2044, + }, + { + 0, 5, 55, 116, 242, 491, 1005, 2039, 4, 12, 53, 113, 236, 238, 494, 501, + 54, 52, 114, 234, 241, 489, 499, 1013, 115, 112, 235, 240, 497, 496, 1004, 1018, + 243, 237, 488, 495, 1007, 1009, 1017, 2043, 493, 239, 490, 498, 1011, 1016, 2041, 2044, + 1006, 492, 500, 1012, 1015, 2040, 4093, 4094, 2038, 1008, 1010, 1014, 2042, 2045, 4092, 4095, + }, + { + 14, 5, 16, 48, 111, 241, 506, 1022, 3, 0, 4, 18, 44, 106, 117, 248, + 15, 2, 6, 20, 46, 105, 114, 245, 47, 17, 19, 42, 50, 108, 236, 250, + 113, 43, 45, 49, 109, 112, 242, 505, 239, 104, 51, 107, 110, 238, 249, 1020, + 504, 116, 115, 237, 240, 246, 502, 509, 1021, 243, 244, 247, 503, 507, 508, 1023, + }, + { + 0, 5, 55, 231, 478, 974, 985, 1992, 1997, 4040, 4061, 8164, 8172, 4, 12, 53, + 114, 234, 237, 482, 977, 979, 992, 2008, 4047, 4053, 54, 52, 113, 232, 236, 481, + 975, 989, 987, 2000, 4039, 4052, 4068, 230, 112, 233, 477, 483, 978, 988, 1996, 1994, + 2014, 4056, 4074, 8155, 479, 235, 476, 486, 981, 990, 1995, 2013, 2012, 4045, 4066, 4071, + 8161, 976, 480, 484, 982, 1989, 2001, 2011, 4050, 2016, 4057, 4075, 8163, 8169, 1988, 485, + 983, 1990, 1999, 2010, 4043, 4058, 4067, 4073, 8166, 8179, 8183, 2003, 984, 993, 2004, 2009, + 4051, 4062, 8157, 8153, 8162, 8170, 8177, 8182, 2002, 980, 986, 1991, 2007, 2018, 4046, 4059, + 8152, 8174, 16368, 8180, 16370, 2017, 991, 1993, 2006, 4042, 4048, 4069, 4070, 8171, 8175, 16371, + 16372, 16373, 4064, 1998, 2005, 4038, 4049, 4065, 8160, 8168, 8176, 16369, 16376, 16374, 32764, 4072, + 2015, 4041, 4055, 4060, 8156, 8159, 8173, 8181, 16377, 16379, 32765, 32766, 8167, 4044, 4054, 4063, + 8158, 8154, 8165, 8178, 16378, 16375, 16380, 16381, 32767, + }, + { + 34, 8, 29, 38, 95, 211, 463, 976, 983, 1005, 2032, 2038, 4093, 7, 0, 1, + 9, 32, 84, 96, 213, 220, 468, 973, 990, 2023, 28, 2, 6, 12, 30, 40, + 91, 205, 217, 462, 476, 985, 1009, 37, 11, 10, 13, 36, 87, 97, 204, 221, + 460, 478, 979, 999, 93, 33, 31, 35, 39, 89, 100, 216, 223, 466, 482, 989, + 1006, 209, 85, 41, 86, 88, 98, 206, 224, 226, 474, 980, 995, 2027, 457, 94, + 90, 92, 99, 202, 218, 455, 458, 480, 987, 1000, 2028, 483, 210, 203, 208, 215, + 219, 454, 469, 472, 970, 986, 2026, 2033, 481, 212, 207, 214, 222, 225, 464, 470, + 977, 981, 1010, 2030, 2043, 1001, 461, 456, 459, 465, 471, 479, 975, 992, 1007, 2022, + 2040, 4090, 1003, 477, 467, 473, 475, 978, 972, 988, 1002, 2029, 2035, 2041, 4089, 2034, + 974, 484, 971, 984, 982, 994, 997, 2024, 2036, 2037, 2039, 4091, 2042, 1004, 991, 993, + 996, 998, 1008, 2025, 2031, 4088, 4094, 4092, 4095, + }, + { + 0, 6, 25, 61, 156, 198, 423, 912, 962, 991, 2022, 2035, 4091, 2028, 4090, 4094, + 910, 5, 1, 8, 20, 55, 66, 146, 175, 401, 421, 437, 926, 960, 930, 973, + 2006, 174, 23, 7, 9, 24, 57, 64, 142, 163, 184, 409, 428, 449, 945, 918, + 958, 970, 157, 60, 21, 22, 26, 59, 68, 145, 165, 190, 406, 430, 441, 929, + 913, 933, 981, 148, 154, 54, 56, 58, 65, 140, 155, 176, 195, 414, 427, 444, + 927, 911, 937, 975, 147, 191, 62, 63, 67, 69, 158, 167, 185, 404, 418, 442, + 451, 934, 935, 955, 980, 159, 416, 143, 141, 144, 152, 166, 182, 196, 415, 431, + 447, 921, 959, 948, 969, 999, 168, 438, 171, 164, 170, 178, 194, 197, 408, 420, + 440, 908, 932, 964, 966, 989, 1000, 173, 943, 402, 189, 188, 398, 407, 410, 419, + 433, 909, 920, 951, 979, 977, 987, 2013, 180, 990, 425, 411, 412, 417, 426, 429, + 435, 907, 946, 952, 974, 993, 992, 2002, 2021, 183, 2019, 443, 424, 422, 432, 434, + 439, 923, 922, 954, 949, 982, 2007, 996, 2008, 2026, 186, 2024, 928, 445, 436, 906, + 452, 914, 938, 944, 956, 983, 2004, 2012, 2011, 2005, 2032, 193, 2043, 968, 931, 917, + 925, 940, 942, 965, 984, 994, 998, 2020, 2023, 2016, 2025, 2039, 400, 2034, 915, 446, + 448, 916, 919, 941, 963, 961, 978, 2010, 2009, 2015, 2027, 2036, 2042, 405, 2040, 957, + 924, 939, 936, 947, 953, 976, 995, 997, 2018, 2014, 2029, 2033, 2041, 2044, 403, 4093, + 988, 950, 967, 972, 971, 985, 986, 2003, 2017, 2030, 2031, 2037, 2038, 4092, 4095, 413, + 450, 181, 161, 150, 151, 149, 153, 160, 162, 172, 169, 177, 179, 187, 192, 399, + 4, + }, +} + +Tables.SPEC_BITS = { + { + 11, 9, 11, 10, 7, 10, 11, 9, 11, 10, 7, 10, 7, 5, 7, 9, 7, 10, 11, 9, 11, 9, 7, 9, 11, 9, 11, 9, 7, 9, + 7, 5, 7, 9, 7, 9, 7, 5, 7, 5, 1, 5, 7, 5, 7, 9, 7, 9, 7, 5, 7, 9, 7, 9, 11, 9, 11, 9, 7, 9, + 11, 9, 11, 10, 7, 9, 7, 5, 7, 9, 7, 10, 11, 9, 11, 10, 7, 9, 11, 9, 11, + }, + { + 9, 7, 9, 8, 6, 8, 9, 8, 9, 8, 6, 7, 6, 5, 6, 7, 6, 8, 9, 7, 8, 8, 6, 8, 9, 7, 9, 8, 6, 7, + 6, 5, 6, 7, 6, 8, 6, 5, 6, 5, 3, 5, 6, 5, 6, 8, 6, 7, 6, 5, 6, 8, 6, 8, 9, 7, 9, 8, 6, 8, + 8, 7, 9, 8, 6, 7, 6, 4, 6, 8, 6, 7, 9, 7, 9, 7, 6, 8, 9, 7, 9, + }, + { + 1, 4, 8, 4, 5, 8, 9, 9, 10, 4, 6, 9, 6, 6, 9, 9, 9, 10, 9, 10, 13, 9, 9, 11, 11, 10, 12, 4, 6, 10, + 6, 7, 10, 10, 10, 12, 5, 7, 11, 6, 7, 10, 9, 9, 11, 9, 10, 13, 8, 9, 12, 10, 11, 12, 8, 10, 15, 9, 11, 15, + 13, 14, 16, 8, 10, 14, 9, 10, 14, 12, 12, 15, 11, 12, 16, 10, 11, 15, 12, 12, 15, + }, + { + 4, 5, 8, 5, 4, 8, 9, 8, 11, 5, 5, 8, 5, 4, 8, 8, 7, 10, 9, 8, 11, 8, 8, 10, 11, 10, 11, 4, 5, 8, + 4, 4, 8, 8, 8, 10, 4, 4, 8, 4, 4, 7, 8, 7, 9, 8, 8, 10, 7, 7, 9, 10, 9, 10, 8, 8, 11, 8, 7, 10, + 11, 10, 12, 8, 7, 10, 7, 7, 9, 10, 9, 11, 11, 10, 12, 10, 9, 11, 11, 10, 11, + }, + { + 13, 12, 11, 11, 10, 11, 11, 12, 13, 12, 11, 10, 9, 8, 9, 10, 11, 12, 12, 10, 9, 8, 7, 8, 9, 10, 11, 11, 9, 8, + 5, 4, 5, 8, 9, 11, 10, 8, 7, 4, 1, 4, 7, 8, 11, 11, 9, 8, 5, 4, 5, 8, 9, 11, 11, 10, 9, 8, 7, 8, + 9, 10, 11, 12, 11, 10, 9, 8, 9, 10, 11, 12, 13, 12, 12, 11, 10, 10, 11, 12, 13, + }, + { + 11, 10, 9, 9, 9, 9, 9, 10, 11, 10, 9, 8, 7, 7, 7, 8, 9, 10, 9, 8, 6, 6, 6, 6, 6, 8, 9, 9, 7, 6, + 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 8, 6, 6, 6, 6, + 6, 8, 9, 10, 9, 8, 7, 7, 7, 7, 8, 10, 11, 10, 9, 9, 9, 9, 9, 10, 11, + }, + { + 1, 3, 6, 7, 8, 9, 10, 11, 3, 4, 6, 7, 8, 8, 9, 9, 6, 6, 7, 8, 8, 9, 9, 10, 7, 7, 8, 8, 9, 9, + 10, 10, 8, 8, 9, 9, 10, 10, 10, 11, 9, 8, 9, 9, 10, 10, 11, 11, 10, 9, 9, 10, 10, 11, 12, 12, 11, 10, 10, 10, + 11, 11, 12, 12, + }, + { + 5, 4, 5, 6, 7, 8, 9, 10, 4, 3, 4, 5, 6, 7, 7, 8, 5, 4, 4, 5, 6, 7, 7, 8, 6, 5, 5, 6, 6, 7, + 8, 8, 7, 6, 6, 6, 7, 7, 8, 9, 8, 7, 6, 7, 7, 8, 8, 10, 9, 7, 7, 8, 8, 8, 9, 9, 10, 8, 8, 8, + 9, 9, 9, 10, + }, + { + 1, 3, 6, 8, 9, 10, 10, 11, 11, 12, 12, 13, 13, 3, 4, 6, 7, 8, 8, 9, 10, 10, 10, 11, 12, 12, 6, 6, 7, 8, + 8, 9, 10, 10, 10, 11, 12, 12, 12, 8, 7, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 9, 8, 9, 9, 10, 10, 11, 11, + 11, 12, 12, 12, 13, 10, 9, 9, 10, 11, 11, 11, 12, 11, 12, 12, 13, 13, 11, 9, 10, 11, 11, 11, 12, 12, 12, 12, 13, 13, + 13, 11, 10, 10, 11, 11, 12, 12, 13, 13, 13, 13, 13, 13, 11, 10, 10, 11, 11, 11, 12, 12, 13, 13, 14, 13, 14, 11, 10, 11, + 11, 12, 12, 12, 12, 13, 13, 14, 14, 14, 12, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 12, 11, 12, 12, 12, 13, 13, + 13, 13, 14, 14, 15, 15, 13, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, + }, + { + 6, 5, 6, 6, 7, 8, 9, 10, 10, 10, 11, 11, 12, 5, 4, 4, 5, 6, 7, 7, 8, 8, 9, 10, 10, 11, 6, 4, 5, 5, + 6, 6, 7, 8, 8, 9, 9, 10, 10, 6, 5, 5, 5, 6, 7, 7, 8, 8, 9, 9, 10, 10, 7, 6, 6, 6, 6, 7, 7, 8, + 8, 9, 9, 10, 10, 8, 7, 6, 7, 7, 7, 8, 8, 8, 9, 10, 10, 11, 9, 7, 7, 7, 7, 8, 8, 9, 9, 9, 10, 10, + 11, 9, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 9, 8, 8, 8, 8, 8, 9, 9, 10, 10, 10, 11, 11, 10, 9, 9, + 9, 9, 9, 9, 10, 10, 10, 11, 11, 12, 10, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 12, 11, 10, 9, 10, 10, 10, 10, + 10, 11, 11, 11, 11, 12, 11, 10, 10, 10, 10, 10, 10, 11, 11, 12, 12, 12, 12, + }, + { + 4, 5, 6, 7, 8, 8, 9, 10, 10, 10, 11, 11, 12, 11, 12, 12, 10, 5, 4, 5, 6, 7, 7, 8, 8, 9, 9, 9, 10, 10, + 10, 10, 11, 8, 6, 5, 5, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 7, 6, 6, 6, 7, 7, 8, 8, 8, + 9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, + 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 8, 9, + 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 10, 8, 10, 9, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, + 10, 11, 8, 10, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 8, 11, 9, 9, 9, 9, 9, 9, 10, 10, 10, + 10, 10, 11, 10, 11, 11, 8, 11, 10, 9, 9, 10, 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 8, 11, 10, 10, 10, 10, 10, + 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 9, 11, 10, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 11, 10, + 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 12, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 12, + 12, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 5, + }, +} + +Tables.SWB_LONG = { + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, + 108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, + 960, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, + 108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, + 960, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 100, + 112, 124, 140, 156, 172, 192, 216, 240, 268, 304, 344, 384, 424, 464, 504, 544, 584, 624, 664, 704, + 744, 784, 824, 864, 904, 944, 984, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, + 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, + 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, + 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, + 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, + 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, + 672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108, + 116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552, + 600, 652, 704, 768, 832, 896, 960, 1024, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108, + 116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552, + 600, 652, 704, 768, 832, 896, 960, 1024, + }, + { + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, + 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, + 832, 896, 960, 1024, + }, + { + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, + 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, + 832, 896, 960, 1024, + }, + { + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, + 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, + 832, 896, 960, 1024, + }, + { + 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252, + 268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944, + 1024, + }, + { + 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252, + 268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944, + 1024, + }, +} + +Tables.SWB_SHORT = { + { + 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, + }, + { + 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, + }, + { + 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, + }, + { + 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128, + }, + { + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128, + }, +} + +Tables.NUM_SWB_LONG = { + 41, 41, 47, 49, 49, 51, 47, 47, 43, 43, 43, 40, 40, +} + +Tables.NUM_SWB_SHORT = { + 12, 12, 12, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, +} + +Tables.TNS_MAX_BANDS_LONG = { + 31, 31, 34, 40, 42, 51, 46, 46, 42, 42, 42, 39, 39, +} + +Tables.TNS_MAX_BANDS_SHORT = { + 9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +} + +return Tables + diff --git a/src/Formats/codecs/Aac/init.luau b/src/Formats/codecs/Aac/init.luau new file mode 100644 index 0000000..c7e5e0b --- /dev/null +++ b/src/Formats/codecs/Aac/init.luau @@ -0,0 +1,336 @@ +--!strict +-- codecs/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program +-- config element, explicit and backward-compatible SBR signalling), ADTS headers, and raw_data_block decoding +-- (codecs/Aac/Decode). A codec (layer 1): audio/m4a, audio/aac (ADTS), and later MP4 / MKV / MPEG-TS video build on it. +-- Written from the standard (tables: codecs/Aac/Tables); no third-party code. +-- Supports: AAC-LC (object type 2) 1 - 8 channels, all sampling rates, long / short / start / stop windows, sine and KBD +-- windows, M/S, intensity stereo, PNS, TNS, pulses. HE-AAC (SBR, PS: object types 5 / 29, or implicit SBR payloads) +-- decodes its AAC-LC core at the core rate; `decoder.onExtension` receives every FIL extension payload (the hook for a +-- later SBR / PS module), `decoder.sbr` says whether one was seen. Not supported: AAC Main prediction, LTP, SSR gain +-- control, coupling channels, 960-sample frames, ER / USAC object types (UNSUPPORTED). +-- +-- local Aac = require("@formats/codecs/Aac") +-- local dec, err = Aac.decoder(asc) -- an AudioSpecificConfig (buffer) or { objectType, sfIndex, channels } +-- local frames, err = dec:decode(buf, offset, length) -- one raw_data_block -> dec.pcm (frames * channels floats) +-- local h = Aac.adts(buf, offset, limit) -- an ADTS header: { headerSize, frameSize, objectType, sfIndex, ... } +-- +-- Never throws: bad data returns nil, Err. +local Err = require("@formats/core/Err") +local Bits = require("@formats/core/Bits") +local Decode = require("@formats/codecs/Aac/Decode") + +local Aac = {} + +Aac.RATES = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 } +local CONFIG_CHANNELS = { 1, 2, 3, 4, 5, 6, 8 } +-- element order (AAC: C, L, R, ...) -> WAV order (L, R, C, LFE, ...) for channel configurations 3 .. 7 +local CONFIG_MAP: { [number]: { number } } = { + [3] = { 3, 1, 2 }, + [4] = { 3, 1, 2, 4 }, + [5] = { 3, 1, 2, 4, 5 }, + [6] = { 3, 1, 2, 5, 6, 4 }, + [7] = { 3, 7, 8, 1, 2, 5, 6, 4 }, +} + +export type Config = { + objectType: number, -- 2 = AAC-LC (the core object type when SBR / PS is signalled) + sfIndex: number, + sampleRate: number, -- the core rate + channelConfig: number, + channels: number, + sbr: boolean, -- SBR signalled (explicitly or backward-compatibly) + ps: boolean, + extensionRate: number?, -- the SBR output rate + frameLength: number, +} + +local function rateIndex(rate: number): number + -- the nearest standard rate (ISO 14496-3 table 4.82 mapping for explicit frequencies) + local best, bi = math.huge, 4 + for i, r in Aac.RATES do + if math.abs(r - rate) < best then + best, bi = math.abs(r - rate), i - 1 + end + end + return bi +end + +local function objectType(br: Bits.BitReader): number + local t = br:read(5) + if t == 31 then + t = 32 + br:read(6) + end + return t +end + +local function frequency(br: Bits.BitReader): (number, number) + local i = br:read(4) + if i == 15 then + local f = br:read(24) + return rateIndex(f), f + end + return i, Aac.RATES[i + 1] or 0 +end + +-- pce(br) -> channels (program_config_element) +local function pce(br: Bits.BitReader): number + br:read(4 + 2 + 4) + local front, side, back = br:read(4), br:read(4), br:read(4) + local lfe, assoc, cc = br:read(2), br:read(3), br:read(4) + if br:read(1) == 1 then + br:read(4) + end + if br:read(1) == 1 then + br:read(4) + end + if br:read(1) == 1 then + br:read(3) + end + local channels = 0 + for _ = 1, front + side + back do + channels += if br:read(1) == 1 then 2 else 1 + br:read(4) + end + channels += lfe + br:skip(lfe * 4 + assoc * 4 + cc * 5) + br:align() + br:skip(br:read(8) * 8) + return channels +end + +-- config(asc) -> Config | nil, Err: parse an AudioSpecificConfig +function Aac.config(asc: buffer): (Config?, Err.Err?) + if type(asc) ~= "buffer" or buffer.len(asc) < 2 then + return nil, Err.new(Err.TRUNCATED, "AudioSpecificConfig is shorter than 2 bytes") + end + local br = Bits.msbReader(asc) + local aot = objectType(br) + local sfi, rate = frequency(br) + local chcfg = br:read(4) + local sbr, ps = false, false + local extRate: number? = nil + if aot == 5 or aot == 29 then + sbr = true + ps = aot == 29 + local _, er = frequency(br) + extRate = er + aot = objectType(br) + if aot == 22 then + br:read(4) + end + end + if aot ~= 2 and aot ~= 1 and aot ~= 4 then + if aot == 0 or br.err then + return nil, Err.new(Err.CORRUPT, "bad AudioSpecificConfig") + end + return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. aot .. " (only AAC-LC)") + end + if aot ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, if aot == 1 then "AAC Main" else "AAC LTP") + end + -- GASpecificConfig + local frameLengthFlag = br:read(1) + if br:read(1) == 1 then + br:read(14) + end + local ext = br:read(1) + local channels = CONFIG_CHANNELS[chcfg] or 0 + if chcfg == 0 then + channels = pce(br) + elseif chcfg > 7 then + return nil, Err.new(Err.UNSUPPORTED, "channel configuration " .. chcfg) + end + if ext == 1 then + br:read(1) -- extensionFlag3 + end + -- backward-compatible SBR signalling + if not sbr and br:bitsLeft() >= 16 then + if br:read(11) == 0x2b7 then + local et = objectType(br) + if et == 5 and br:read(1) == 1 then + sbr = true + local _, er = frequency(br) + extRate = er + if br:bitsLeft() >= 12 and br:read(11) == 0x548 then + ps = br:read(1) == 1 + end + end + end + end + if br.err and channels == 0 then + return nil, br.err + end + if sfi > 12 or rate <= 0 then + return nil, Err.new(Err.CORRUPT, "bad sampling frequency index " .. sfi) + end + if frameLengthFlag == 1 then + return nil, Err.new(Err.UNSUPPORTED, "960-sample AAC frames") + end + if channels < 1 or channels > 8 then + return nil, Err.new(Err.UNSUPPORTED, channels .. " channels") + end + return { + objectType = aot, + sfIndex = sfi, + sampleRate = rate, + channelConfig = chcfg, + channels = channels, + sbr = sbr, + ps = ps, + extensionRate = extRate, + frameLength = 1024, + }, nil +end + +-- asc(objectType, sfIndex, channelConfig) -> a 2-byte AudioSpecificConfig +function Aac.asc(aot: number, sfIndex: number, channelConfig: number): buffer + local b = buffer.create(2) + local v = aot * 2048 + sfIndex * 128 + channelConfig * 8 + buffer.writeu8(b, 0, bit32.rshift(v, 8)) + buffer.writeu8(b, 1, bit32.band(v, 255)) + return b +end + +export type Adts = { + headerSize: number, -- 7, or 9 with a CRC + frameSize: number, -- the whole frame, header included + objectType: number, + sfIndex: number, + sampleRate: number, + channelConfig: number, + blocks: number, -- raw_data_blocks in the frame (1 .. 4) + protected: boolean, +} + +-- adts(buf, offset, limit) -> Adts | nil (not a valid header at offset) +function Aac.adts(b: buffer, o: number, limit: number): Adts? + if o < 0 or o + 7 > limit or o + 7 > buffer.len(b) then + return nil + end + local b0, b1, b2, b3, b4, b5, b6 = buffer.readu8(b, o), buffer.readu8(b, o + 1), buffer.readu8(b, o + 2), buffer.readu8(b, o + 3), buffer.readu8(b, o + 4), buffer.readu8(b, o + 5), buffer.readu8(b, o + 6) + if b0 ~= 0xFF or bit32.band(b1, 0xF6) ~= 0xF0 then -- sync, layer 0 + return nil + end + local protected = bit32.band(b1, 1) == 0 + local profile = bit32.rshift(b2, 6) + local sfi = bit32.band(bit32.rshift(b2, 2), 15) + local ch = bit32.band(b2, 1) * 4 + bit32.rshift(b3, 6) + local size = bit32.band(b3, 3) * 2048 + b4 * 8 + bit32.rshift(b5, 5) + local blocks = bit32.band(b6, 3) + 1 + local hs = if protected then 9 else 7 + if sfi > 12 or size < hs then + return nil + end + return { + headerSize = hs, + frameSize = size, + objectType = profile + 1, + sfIndex = sfi, + sampleRate = Aac.RATES[sfi + 1], + channelConfig = ch, + blocks = blocks, + protected = protected, + } +end + +-- ------------------------------------------------------------------------------------------------ decoder +export type Decoder = { + config: Config, + channels: number, + sampleRate: number, + frameLength: number, + pcm: { number }, -- the last frame: 1024 * channels interleaved floats (-1 .. 1), WAV channel order + sbr: boolean, -- SBR payloads seen in the stream (implicit signalling) or signalled + onExtension: ((kind: number, element: number, buf: buffer, bitPos: number, bits: number) -> ())?, + decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?), + reset: (self: Decoder) -> (), + state: Decode.State, +} + +local function decode(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?) + local o = offset or 0 + local n = length or (buffer.len(buf) - o) + if type(buf) ~= "buffer" or o < 0 or n < 0 or o + n > buffer.len(buf) then + return nil, Err.new(Err.ARG, "packet range out of the buffer") + end + local st = self.state + st.onExtension = self.onExtension + local chans, msg = Decode.frame(st, buf, o, n) + if not chans then + return nil, Err.new(Err.CORRUPT, msg or "bad frame", o) + end + if st.sbr then + self.sbr = true + end + if chans == 0 then + -- an empty frame (only fill elements): silence + for i = 1, 1024 * self.channels do + st.pcm[i] = 0 + end + return 1024, nil + end + if chans ~= self.channels then + return nil, Err.new(Err.CORRUPT, string.format("frame has %d channels, the configuration %d", chans, self.channels), o) + end + return 1024, nil +end + +local function reset(self: Decoder) + for _, c in self.state.ch do + for i = 1, 1024 do + c.overlap[i] = 0 + end + c.prevShape = 0 + end +end + +-- decoder(asc | { objectType?, sfIndex, channels }) -> Decoder | nil, Err +function Aac.decoder(asc: any): (Decoder?, Err.Err?) + local cfg: Config + if type(asc) == "buffer" then + local c, err = Aac.config(asc) + if not c then + return nil, err + end + cfg = c + elseif type(asc) == "table" and type(asc.sfIndex) == "number" and type(asc.channels) == "number" then + local sfi = asc.sfIndex + if sfi < 0 or sfi > 12 or asc.channels < 1 or asc.channels > 8 then + return nil, Err.new(Err.ARG, "bad sampling index / channels") + end + if (asc.objectType or 2) ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, "AAC object type " .. asc.objectType .. " (only AAC-LC)") + end + cfg = { + objectType = 2, + sfIndex = sfi, + sampleRate = Aac.RATES[sfi + 1], + channelConfig = asc.channelConfig or asc.channels, + channels = asc.channels, + sbr = false, + ps = false, + frameLength = 1024, + } + else + return nil, Err.new(Err.ARG, "decoder: expected an AudioSpecificConfig buffer") + end + local st = Decode.state(cfg.sfIndex) + st.channels = cfg.channels + if cfg.channelConfig >= 3 then + st.map = CONFIG_MAP[cfg.channelConfig] + end + return { + config = cfg, + channels = cfg.channels, + sampleRate = cfg.sampleRate, + frameLength = 1024, + pcm = st.pcm, + sbr = cfg.sbr, + onExtension = nil, + decode = decode, + reset = reset, + state = st, + }, nil +end + +return Aac diff --git a/src/Formats/codecs/Alac/Decode.luau b/src/Formats/codecs/Alac/Decode.luau new file mode 100644 index 0000000..932d7e7 --- /dev/null +++ b/src/Formats/codecs/Alac/Decode.luau @@ -0,0 +1,427 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Alac/Decode: the ALAC frame decoder: elements SCE / CPE / LFE / DSE / FIL / END, the adaptive Golomb-Rice +-- residuals with zero runs, the adaptive FIR predictor (orders 0, 31 and 1 .. 30), stereo unmixing, shifted low bytes, +-- uncompressed (escape) frames, 16 / 20 / 24 / 32-bit samples. Written from the ALAC format as published by Apple +-- (ALACDecoder / ag_dec / dp_dec, Apache 2.0; behaviour, not code). Never throws: returns nil, message. +local readu32, readu8 = buffer.readu32, buffer.readu8 +local byteswap, lshift, rshift, band, countlz, bnot = bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band, bit32.countlz, bit32.bnot +local floor = math.floor + +local Decode = {} + +export type State = { + frameLength: number, + bitDepth: number, + pb: number, + mb: number, + kb: number, + channels: number, + maxRun: number, + scratch: buffer, -- the packet + 16 zero bytes (reads past the end are safe; the overrun is checked) + pred: { { number } }, -- per element channel (0, 1): residuals / predictor output + mix: { { number } }, + shift: { number }, + out: { number }, -- interleaved output samples (integers), frames * channels +} + +local POW = table.create(64, 0) +for i = 0, 63 do + POW[i + 1] = 2 ^ i +end + +-- bit reader over st.scratch: pos = bit position. bits(n) for n <= 25. +local function bitsAt(b: buffer, pos: number, n: number): number + local w = byteswap(readu32(b, rshift(pos, 3))) + return rshift(lshift(w, band(pos, 7)), 32 - n) +end + +local function signExtend(v: number, bits: number): number + local m = POW[bits + 1] + v = v % m + if v >= m / 2 then + v -= m + end + return v +end + +-- the adaptive Golomb-Rice value: unary prefix (escape after 9 ones: `bps` raw bits), then k bits +local function scalar(b: buffer, pos: number, k: number, m: number, bps: number): (number, number) + local w = lshift(byteswap(readu32(b, rshift(pos, 3))), band(pos, 7)) + local pre = countlz(bnot(w)) + if pre >= 9 then + pos += 9 + local v + if bps > 25 then + v = bitsAt(b, pos, bps - 16) * 65536 + bitsAt(b, pos + bps - 16, 16) + else + v = bitsAt(b, pos, bps) + end + return v, pos + bps + end + pos += pre + 1 + if k == 1 then + return pre, pos + end + local v = bitsAt(b, pos, k) + local x = pre * m + if v > 1 then + return x + v - 1, pos + k + end + return x, pos + k - 1 +end + +-- residuals: n values into out[1..n]; returns the new bit position or -1 +local function rice(b: buffer, pos: number, limit: number, out: { number }, n: number, bps: number, mult: number, st: State): number + local history = st.mb + local kb = st.kb + local signMod = 0 + local i = 1 + while i <= n do + if pos > limit then + return -1 -- each value reads at most 41 bits past here: inside the 16 padding bytes + end + local k = 31 - countlz(floor(history / 512) + 3) + if k > kb then + k = kb + end + local x + x, pos = scalar(b, pos, k, POW[k + 1] - 1, bps) + x += signMod + signMod = 0 + out[i] = if x % 2 == 0 then x / 2 else -(x + 1) / 2 + if x > 0xFFFF then + history = 0xFFFF + else + history += x * mult - floor(history * mult / 512) + end + if history < 128 and i < n then + if pos > limit then + return -1 + end + local lg = if history > 0 then 31 - countlz(history) else 0 + k = 7 - lg + floor((history + 16) / 64) + if k > kb then + k = kb + end + local run + run, pos = scalar(b, pos, k, POW[k + 1] - 1, 16) + if run > 0 then + if run > n - i then + return -1 + end + for j = i + 1, i + run do + out[j] = 0 + end + i += run + end + if run < 0xFFFF then + signMod = 1 -- the next value is not 0 (unless the run hit its maximum) + end + history = 0 + end + i += 1 + end + return pos +end + +-- the adaptive FIR predictor: err[1..n] -> out[1..n] (may be the same array); coefs adapt in place +local function predict(err: { number }, out: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number) + out[1] = err[1] + if n <= 1 then + return + end + if order == 0 then + if out ~= err then + for i = 2, n do + out[i] = err[i] + end + end + return + end + if order == 31 then + for i = 2, n do + out[i] = signExtend(out[i - 1] + err[i], bps) + end + return + end + local i = 2 + while i <= order + 1 and i <= n do + out[i] = signExtend(out[i - 1] + err[i], bps) + i += 1 + end + local half = if quant > 0 then POW[quant] else 0 + local qd = POW[quant + 1] + -- coefs[1] multiplies the most recent sample + while i <= n do + local d = out[i - order - 1] + local val = 0 + for j = 1, order do + val += (out[i - j] - d) * coefs[j] + end + val = floor((val + half) / qd) + local e = err[i] + out[i] = signExtend(val + d + e, bps) + if e ~= 0 then + local es = if e > 0 then 1 else -1 + -- adapt from the oldest sample to the newest while the error keeps its sign + for j = order, 1, -1 do + if e * es <= 0 then + break + end + local v = d - out[i - j] + local sgn = if v > 0 then es elseif v < 0 then -es else 0 + coefs[j] -= sgn + e -= floor(v * sgn / qd) * (order - j + 1) + end + end + i += 1 + end +end + +-- decode(st, buf, off, len) -> frames | nil, message. Samples land interleaved in st.out (integers), channels in the +-- ALAC element order. +function Decode.frame(st: State, buf: buffer, off: number, len: number): (number?, string?) + if len <= 0 then + return nil, "empty packet" + end + local b = st.scratch + if buffer.len(b) < len + 16 then + b = buffer.create(len + 64) + st.scratch = b + end + buffer.copy(b, 0, buf, off, len) + buffer.fill(b, len, 0, 16) + local limit = len * 8 + local pos = 0 + local channels = st.channels + local ch = 0 -- next output channel + local frames = -1 + local out = st.out + while true do + if pos + 3 > limit then + return nil, "frame runs past the end" + end + local tag = bitsAt(b, pos, 3) + pos += 3 + if tag == 7 then -- END + break + elseif tag == 0 or tag == 1 or tag == 3 then -- SCE / CPE / LFE + local nch = if tag == 1 then 2 else 1 + if ch + nch > channels then + return nil, "more channels than the configuration" + end + pos += 4 -- element instance tag + if bitsAt(b, pos, 12) ~= 0 then + return nil, "bad element header" + end + pos += 12 + local h = bitsAt(b, pos, 4) + pos += 4 + local partial = rshift(h, 3) + local shiftBytes = band(rshift(h, 1), 3) + local escape = band(h, 1) + if shiftBytes == 3 then + return nil, "bad shift" + end + local n = st.frameLength + if partial == 1 then + n = bitsAt(b, pos, 16) * 65536 + bitsAt(b, pos + 16, 16) + pos += 32 + end + if n < 1 or n > st.frameLength then + return nil, "bad frame length " .. n + end + if frames >= 0 and n ~= frames then + return nil, "elements of different lengths" + end + frames = n + if #out < n * channels then + for k = #out + 1, n * channels do + out[k] = 0 + end + end + local shift = shiftBytes * 8 + local bps = st.bitDepth - shift + nch - 1 + if bps > 32 or bps < 1 then + return nil, "bad sample size" + end + if pos > limit then + return nil, "frame runs past the end" + end + local mixBits, mixRes = 0, 0 + local p0, p1 = st.pred[1], st.pred[2] + local m0, m1 = st.mix[1], st.mix[2] + local shiftBuf = st.shift + if escape == 0 then + mixBits = bitsAt(b, pos, 8) + mixRes = bitsAt(b, pos + 8, 8) + pos += 16 + if mixRes >= 128 then + mixRes -= 256 + end + local mode, denShift, pbFactor, order = {}, {}, {}, {} + local coefs = { {}, {} } + for c = 1, nch do + local x = bitsAt(b, pos, 8) + local y = bitsAt(b, pos + 8, 8) + pos += 16 + mode[c], denShift[c] = rshift(x, 4), band(x, 15) + pbFactor[c], order[c] = rshift(y, 5), band(y, 31) + if pos + order[c] * 16 > limit then + return nil, "frame runs past the end" + end + for j = 1, order[c] do + local v = bitsAt(b, pos, 16) + pos += 16 + coefs[c][j] = if v >= 32768 then v - 65536 else v + end + end + if pos > limit then + return nil, "frame runs past the end" + end + local shiftPos = pos + if shift > 0 then + pos += shift * n * nch + end + for c = 1, nch do + local p = if c == 1 then p0 else p1 + local mb = if c == 1 then m0 else m1 + pos = rice(b, pos, limit, p, n, bps, floor(st.pb * pbFactor[c] / 4), st) + if pos < 0 or pos > limit then + return nil, "bad residuals" + end + if mode[c] == 15 then + predict(p, p, n, bps, {}, 31, 0) + elseif mode[c] ~= 0 then + return nil, "unknown prediction mode " .. mode[c] + end + predict(p, mb, n, bps, coefs[c], order[c], denShift[c]) + end + if shift > 0 then + local sp = shiftPos + for i = 1, n * nch do + shiftBuf[i] = bitsAt(b, sp, shift) + sp += shift + end + end + else + -- uncompressed: interleaved samples of bitDepth bits + local bits = st.bitDepth + if pos + n * nch * bits > limit then + return nil, "frame runs past the end" + end + for i = 1, n do + for c = 1, nch do + local v + if bits > 25 then + v = bitsAt(b, pos, bits - 16) * 65536 + bitsAt(b, pos + bits - 16, 16) + else + v = bitsAt(b, pos, bits) + end + pos += bits + v = signExtend(v, bits) + if c == 1 then + m0[i] = v + else + m1[i] = v + end + end + end + shift = 0 + end + -- unmix + shifted bytes -> interleaved output + local sm = POW[shift + 1] + if nch == 2 then + local den = POW[mixBits + 1] + for i = 1, n do + local u, v = m0[i], m1[i] + local l, r + if mixRes ~= 0 then + l = u + v - floor(mixRes * v / den) + r = l - v + else + l, r = u, v + end + if shift > 0 then + l = l * sm + shiftBuf[2 * i - 1] + r = r * sm + shiftBuf[2 * i] + end + local o = (i - 1) * channels + ch + 1 + out[o] = l + out[o + 1] = r + end + else + for i = 1, n do + local v = m0[i] + if shift > 0 then + v = v * sm + shiftBuf[i] + end + out[(i - 1) * channels + ch + 1] = v + end + end + ch += nch + elseif tag == 4 then -- DSE + pos += 4 + local align = bitsAt(b, pos, 1) + local count = bitsAt(b, pos + 1, 8) + pos += 9 + if count == 255 then + count += bitsAt(b, pos, 8) + pos += 8 + end + if align == 1 then + pos = (pos + 7) // 8 * 8 + end + pos += count * 8 + elseif tag == 6 then -- FIL + local count = bitsAt(b, pos, 4) + pos += 4 + if count == 15 then + count += bitsAt(b, pos, 8) - 1 + pos += 8 + end + pos += count * 8 + else + return nil, "unsupported element " .. tag + end + if pos > limit then + return nil, "frame runs past the end" + end + end + if frames < 0 then + return 0, nil + end + if ch < channels then + -- missing channels: silence + for i = 1, frames do + for c = ch + 1, channels do + out[(i - 1) * channels + c] = 0 + end + end + end + return frames, nil +end + +-- the scratch state for a configuration +function Decode.state(cfg: any): State + local n = cfg.frameLength + return { + frameLength = n, + bitDepth = cfg.bitDepth, + pb = cfg.pb, + mb = cfg.mb, + kb = cfg.kb, + channels = cfg.channels, + maxRun = cfg.maxRun, + scratch = buffer.create(math.max(64, cfg.maxFrameBytes or 0) + 64), + pred = { table.create(n, 0), table.create(n, 0) }, + mix = { table.create(n, 0), table.create(n, 0) }, + shift = table.create(n * 2, 0), + out = table.create(n * cfg.channels, 0), + } +end + +local _ = readu8 +return Decode diff --git a/src/Formats/codecs/Alac/Encode.luau b/src/Formats/codecs/Alac/Encode.luau new file mode 100644 index 0000000..4309bd5 --- /dev/null +++ b/src/Formats/codecs/Alac/Encode.luau @@ -0,0 +1,427 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Alac/Encode: an ALAC frame encoder: per element (SCE / CPE) the stereo mix (mixBits 2, the best mixRes of +-- 0 .. 4 by first-difference energy), per channel LPC coefficients (Levinson-Durbin on a windowed autocorrelation, +-- orders 4 and 8 tried, quantised with denShift 9), residuals through the same adaptive FIR the decoder runs, the +-- adaptive Golomb-Rice code with zero runs; an uncompressed (escape) frame when that is smaller. 16 / 20 / 24-bit +-- input. Written for this library from the ALAC format; no third-party code. Never throws. +local band, rshift, bor, lshift, countlz = bit32.band, bit32.rshift, bit32.bor, bit32.lshift, bit32.countlz +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local floor, abs = math.floor, math.abs + +local Encode = {} + +local POW = table.create(64, 0) +for i = 0, 63 do + POW[i + 1] = 2 ^ i +end + +local DENSHIFT = 9 +local PB_FACTOR = 4 + +export type State = { + frameLength: number, + bitDepth: number, + pb: number, + mb: number, + kb: number, + channels: number, + out: buffer, -- packet scratch + pos: number, -- bit position in out + cap: number, -- bits available + u: { number }, + v: { number }, + err: { number }, + work: { number }, +} + +-- ------------------------------------------------------------------------------------------------ bit writer +local function put(st: State, v: number, n: number) + local pos = st.pos + if pos + n > st.cap then + st.pos = st.cap + 1 -- overflow: the caller falls back to an uncompressed frame + return + end + local b = st.out + while n > 0 do + local byte = rshift(pos, 3) + local free = 8 - band(pos, 7) + local take = if n < free then n else free + local bits = band(rshift(v, n - take), POW[take + 1] - 1) + writeu8(b, byte, bor(readu8(b, byte), lshift(bits, free - take))) + pos += take + n -= take + end + st.pos = pos +end + +local function putBig(st: State, v: number, n: number) + if n > 24 then + local lo = v % 65536 + put(st, (v - lo) / 65536, n - 16) + put(st, lo, 16) + else + put(st, v, n) + end +end + +-- ------------------------------------------------------------------------------------------------ rice code +local function signExtend(v: number, bits: number): number + local m = POW[bits + 1] + v = v % m + if v >= m / 2 then + v -= m + end + return v +end + +-- the bits of one scalar (no writing) +local function scalarBits(x: number, k: number, m: number, bps: number): number + local pre = if k == 1 then x else floor(x / m) + if pre >= 9 then + return 9 + bps + end + if k == 1 then + return pre + 1 + end + local r = x - pre * m + return pre + 1 + (if r == 0 then k - 1 else k) +end + +local function scalar(st: State, x: number, k: number, m: number, bps: number) + local pre = if k == 1 then x else floor(x / m) + if pre >= 9 then + put(st, 511, 9) + putBig(st, x, bps) + return + end + -- pre ones and a zero + put(st, POW[pre + 2] - 2, pre + 1) + if k ~= 1 then + local r = x - pre * m + if r == 0 then + put(st, 0, k - 1) + else + put(st, r + 1, k) + end + end +end + +-- code the residuals e[1..n] (write = false: just count the bits) +local function rice(st: State, e: { number }, n: number, bps: number, mult: number, write: boolean): number + local history = st.mb + local kb = st.kb + local signMod = 0 + local bits = 0 + local i = 1 + while i <= n do + local k = 31 - countlz(floor(history / 512) + 3) + if k > kb then + k = kb + end + local v = e[i] + local zz = if v >= 0 then 2 * v else -2 * v - 1 + local x = zz - signMod + signMod = 0 + local m = POW[k + 1] - 1 + if write then + scalar(st, x, k, m, bps) + else + bits += scalarBits(x, k, m, bps) + end + if zz > 0xFFFF then -- the decoder adapts on the value with its sign modifier added back + history = 0xFFFF + else + history += zz * mult - floor(history * mult / 512) + end + if history < 128 and i < n then + local lg = if history > 0 then 31 - countlz(history) else 0 + k = 7 - lg + floor((history + 16) / 64) + if k > kb then + k = kb + end + local run = 0 + while i + run < n and e[i + run + 1] == 0 and run < 0xFFFF do + run += 1 + end + m = POW[k + 1] - 1 + if write then + scalar(st, run, k, m, 16) + else + bits += scalarBits(run, k, m, 16) + end + i += run + if run < 0xFFFF then + signMod = 1 + end + history = 0 + end + i += 1 + end + return bits +end + +-- ------------------------------------------------------------------------------------------------ prediction +-- residuals of x[1..n] under the decoder's adaptive FIR starting from coefs (adapted in place, like the decoder) +local function residuals(x: { number }, e: { number }, n: number, bps: number, coefs: { number }, order: number, quant: number) + e[1] = x[1] + if n <= 1 then + return + end + local i = 2 + while i <= order + 1 and i <= n do + e[i] = signExtend(x[i] - x[i - 1], bps) + i += 1 + end + local half = POW[quant] + local qd = POW[quant + 1] + while i <= n do + local d = x[i - order - 1] + local val = 0 + for j = 1, order do + val += (x[i - j] - d) * coefs[j] + end + val = floor((val + half) / qd) + local r = signExtend(x[i] - val - d, bps) + e[i] = r + if r ~= 0 then + local es = if r > 0 then 1 else -1 + for j = order, 1, -1 do + if r * es <= 0 then + break + end + local v = d - x[i - j] + local sgn = if v > 0 then es elseif v < 0 then -es else 0 + coefs[j] -= sgn + r -= floor(v * sgn / qd) * (order - j + 1) + end + end + i += 1 + end +end + +-- LPC coefficients of x[1..n] for the given order (Levinson-Durbin on a Welch-windowed autocorrelation), quantised +local function lpc(x: { number }, n: number, order: number, work: { number }): { number } + local ac = table.create(order + 1, 0) + for i = 1, n do + local t = (2 * (i - 1) - (n - 1)) / (n + 1) + work[i] = x[i] * (1 - t * t) + end + for lag = 0, order do + local s = 0 + for i = lag + 1, n do + s += work[i] * work[i - lag] + end + ac[lag + 1] = s + end + local coefs = table.create(order, 0) + if ac[1] <= 0 then + return coefs + end + ac[1] *= 1.0001 -- a little white noise: keeps the recursion stable + local a = table.create(order + 1, 0) + local tmp = table.create(order + 1, 0) + local errv = ac[1] + for i = 1, order do + local acc = ac[i + 1] + for j = 1, i - 1 do + acc -= a[j] * ac[i - j + 1] + end + local kc = acc / errv + for j = 1, i - 1 do + tmp[j] = a[j] - kc * a[i - j] + end + for j = 1, i - 1 do + a[j] = tmp[j] + end + a[i] = kc + errv *= (1 - kc * kc) + if errv <= 0 then + break + end + end + local scale = POW[DENSHIFT + 1] + for j = 1, order do + coefs[j] = math.clamp(floor(a[j] * scale + 0.5), -32768, 32767) + end + return coefs +end + +-- choose order / coefficients for one channel: returns order, coefs (as transmitted), bits +local function analyse(st: State, x: { number }, n: number, bps: number): (number, { number }, number) + local mult = floor(st.pb * PB_FACTOR / 4) + local bestOrder, bestCoefs, bestBits = 0, {}, math.huge + for _, order in { 4, 8 } do + if order >= n then + continue + end + local coefs = lpc(x, n, order, st.work) + local trial = table.clone(coefs) + residuals(x, st.err, n, bps, trial, order, DENSHIFT) + local bits = rice(st, st.err, n, bps, mult, false) + order * 16 + if bits < bestBits then + bestOrder, bestCoefs, bestBits = order, coefs, bits + end + end + if bestBits == math.huge then + -- tiny frames: first-order prediction (order 31 is only a decoder mode; order 0 = no prediction) + for i = 1, n do + st.err[i] = x[i] + end + return 0, {}, rice(st, st.err, n, bps, mult, false) + end + return bestOrder, bestCoefs, bestBits +end + +-- ------------------------------------------------------------------------------------------------ frame +-- frame(st, samples, first, frames, map) -> buffer: samples interleaved (integers, WAV channel order) from index +-- `first`; map[k] = the input channel (1-based) of ALAC channel k; elements: list of 1 / 2 channel counts +function Encode.frame(st: State, samples: { number }, first: number, frames: number, map: { number }, elements: { number }): buffer + local channels, depth = st.channels, st.bitDepth + local n = frames + local partial = n ~= st.frameLength + local rawBits = n * channels * depth + local need = rawBits + 64 * #elements + 64 + if st.cap < need + 8 * 32 * 2 * #elements * 16 then + local bytes = (need + 8 * 32 * 2 * #elements * 16) // 8 + 16 + st.out = buffer.create(bytes) + st.cap = bytes * 8 + end + buffer.fill(st.out, 0, 0) + st.pos = 0 + local u, v = st.u, st.v + local mult = floor(st.pb * PB_FACTOR / 4) + local compressed = true + local ch = 1 + for _, nch in elements do + local a, b = map[ch], map[ch + 1] + local bps = depth + nch - 1 + local mixRes = 0 + if nch == 2 then + -- the mix with the smallest first-difference energy + local best = math.huge + for res = 0, 4 do + local cost = 0 + local pu, pv = 0, 0 + for i = 0, n - 1 do + local l = samples[first + i * channels + a - 1] + local r = samples[first + i * channels + b - 1] + local uu, vv + if res == 0 then + uu, vv = l, r + else + uu, vv = floor((res * l + (4 - res) * r) / 4), l - r + end + cost += abs(uu - pu) + abs(vv - pv) + pu, pv = uu, vv + end + if cost < best then + best, mixRes = cost, res + end + end + for i = 1, n do + local l = samples[first + (i - 1) * channels + a - 1] + local r = samples[first + (i - 1) * channels + b - 1] + if mixRes == 0 then + u[i], v[i] = l, r + else + u[i], v[i] = floor((mixRes * l + (4 - mixRes) * r) / 4), l - r + end + end + else + for i = 1, n do + u[i] = samples[first + (i - 1) * channels + a - 1] + end + end + -- header + put(st, if nch == 2 then 1 else 0, 3) + put(st, 0, 4) + put(st, 0, 12) + put(st, if partial then 1 else 0, 1) + put(st, 0, 2) + put(st, 0, 1) + if partial then + putBig(st, n, 32) + end + put(st, if mixRes == 0 then 0 else 2, 8) + put(st, mixRes, 8) + local orders, coefsList = {}, {} + for c = 1, nch do + local x = if c == 1 then u else v + local order, coefs = analyse(st, x, n, bps) + orders[c], coefsList[c] = order, coefs + put(st, 0 * 16 + DENSHIFT, 8) -- mode 0, denShift + put(st, PB_FACTOR * 32 + order, 8) + for j = 1, order do + put(st, coefs[j] % 65536, 16) + end + end + for c = 1, nch do + local x = if c == 1 then u else v + local order = orders[c] + if order == 0 then + for i = 1, n do + st.err[i] = x[i] + end + else + residuals(x, st.err, n, bps, table.clone(coefsList[c]), order, DENSHIFT) + end + rice(st, st.err, n, bps, mult, true) + end + ch += nch + if st.pos > rawBits + 64 * #elements then + compressed = false + break + end + end + if not compressed then + -- uncompressed frame + buffer.fill(st.out, 0, 0) + st.pos = 0 + ch = 1 + for _, nch in elements do + put(st, if nch == 2 then 1 else 0, 3) + put(st, 0, 4) + put(st, 0, 12) + put(st, if partial then 1 else 0, 1) + put(st, 0, 2) + put(st, 1, 1) + if partial then + putBig(st, n, 32) + end + for i = 0, n - 1 do + for c = 0, nch - 1 do + putBig(st, samples[first + i * channels + map[ch + c] - 1] % POW[depth + 1], depth) + end + end + ch += nch + end + end + put(st, 7, 3) -- END + local bytes = (st.pos + 7) // 8 + local pkt = buffer.create(bytes) + buffer.copy(pkt, 0, st.out, 0, bytes) + return pkt +end + +function Encode.state(cfg: any): State + local n = cfg.frameLength + return { + frameLength = n, + bitDepth = cfg.bitDepth, + pb = cfg.pb, + mb = cfg.mb, + kb = cfg.kb, + channels = cfg.channels, + out = buffer.create(16), + pos = 0, + cap = 0, + u = table.create(n, 0), + v = table.create(n, 0), + err = table.create(n, 0), + work = table.create(n, 0), + } +end + +return Encode diff --git a/src/Formats/codecs/Alac/init.luau b/src/Formats/codecs/Alac/init.luau new file mode 100644 index 0000000..7af082b --- /dev/null +++ b/src/Formats/codecs/Alac/init.luau @@ -0,0 +1,251 @@ +--!strict +-- codecs/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1). +-- Written from the ALAC format as Apple published it (ALACSpecificConfig, the element syntax, adaptive Golomb-Rice +-- residuals, the adaptive FIR predictor); no third-party code. 1 - 8 channels, 16 / 20 / 24 / 32-bit decode, 16 / 20 / +-- 24-bit encode. Channels come out (and go in) in WAV order (ALAC stores C L R ... for 3+ channels). +-- +-- local Alac = require("@formats/codecs/Alac") +-- local cfg, err = Alac.config(cookie) -- the 24-byte ALACSpecificConfig (frma / alac atoms skipped) +-- local dec = Alac.decoder(cfg) +-- local frames, err = dec:decode(buf, offset, length) -- one packet -> dec.pcm (interleaved integers, WAV order) +-- local enc = Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 }) +-- local packet = enc:encode(samples, first, frames) -- interleaved integers -> one packet (frames <= 4096) +-- local cookie = Alac.cookie(enc.config) -- after encoding: maxFrameBytes / avgBitRate filled +-- +-- Never throws: bad data returns nil, Err (CORRUPT / TRUNCATED / UNSUPPORTED), bad arguments Err.ARG. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Decode = require("@formats/codecs/Alac/Decode") +local Encode = require("@formats/codecs/Alac/Encode") + +local Alac = {} + +export type Config = { + frameLength: number, -- samples per packet (4096) + compatibleVersion: number, + bitDepth: number, + pb: number, -- 40 + mb: number, -- 10 + kb: number, -- 14 + channels: number, + maxRun: number, -- 255 + maxFrameBytes: number, + avgBitRate: number, + sampleRate: number, +} + +-- ALAC channel k (1-based) -> WAV channel (1-based), per channel count +local TO_WAV: { { number } } = { + { 1 }, + { 1, 2 }, + { 3, 1, 2 }, + { 3, 1, 2, 4 }, + { 3, 1, 2, 4, 5 }, + { 3, 1, 2, 5, 6, 4 }, + { 3, 1, 2, 5, 6, 7, 4 }, + { 3, 7, 8, 1, 2, 5, 6, 4 }, +} +-- the element layout (channels per element) the encoder writes +local ELEMENTS: { { number } } = { + { 1 }, + { 2 }, + { 1, 2 }, + { 1, 2, 1 }, + { 1, 2, 2 }, + { 1, 2, 2, 1 }, + { 1, 2, 2, 1, 1 }, + { 1, 2, 2, 2, 1 }, +} +Alac.TO_WAV = TO_WAV + +-- config(buf, offset?, length?) -> Config | nil, Err +function Alac.config(buf: buffer, offset: number?, length: number?): (Config?, Err.Err?) + local r = Bytes.reader(buf, offset, length) + -- a QuickTime 'wave' payload may hold frma + alac atoms ahead of the cookie + for _ = 1, 2 do + local typ = r:peek(4, 4) + if typ == "frma" then + r:skip(12) + elseif typ == "alac" then + r:skip(12) + end + end + if r:remaining() < 24 then + return nil, Err.new(Err.TRUNCATED, "ALAC configuration is shorter than 24 bytes") + end + local c: Config = { + frameLength = r:u32be(), + compatibleVersion = r:u8(), + bitDepth = r:u8(), + pb = r:u8(), + mb = r:u8(), + kb = r:u8(), + channels = r:u8(), + maxRun = r:u16be(), + maxFrameBytes = r:u32be(), + avgBitRate = r:u32be(), + sampleRate = r:u32be(), + } + if c.compatibleVersion ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "ALAC version " .. c.compatibleVersion) + end + if c.frameLength < 1 or c.frameLength > 65536 then + return nil, Err.new(Err.CORRUPT, "bad ALAC frame length " .. c.frameLength) + end + if c.bitDepth ~= 16 and c.bitDepth ~= 20 and c.bitDepth ~= 24 and c.bitDepth ~= 32 then + return nil, Err.new(Err.UNSUPPORTED, "ALAC bit depth " .. c.bitDepth) + end + if c.channels < 1 or c.channels > 8 then + return nil, Err.new(Err.UNSUPPORTED, "ALAC with " .. c.channels .. " channels") + end + if c.kb < 1 or c.kb > 24 then + return nil, Err.new(Err.CORRUPT, "bad ALAC rice limit " .. c.kb) + end + return c, nil +end + +-- cookie(cfg) -> the 24-byte ALACSpecificConfig +function Alac.cookie(c: Config): buffer + local w = Bytes.writer(24) + w:u32be(c.frameLength) + w:u8(0) + w:u8(c.bitDepth) + w:u8(c.pb) + w:u8(c.mb) + w:u8(c.kb) + w:u8(c.channels) + w:u16be(c.maxRun) + w:u32be(c.maxFrameBytes) + w:u32be(c.avgBitRate) + w:u32be(c.sampleRate) + return w:finish() +end + +-- ------------------------------------------------------------------------------------------------ decoder +export type Decoder = { + config: Config, + pcm: { number }, -- the last packet's samples, interleaved, WAV order (integers of config.bitDepth bits) + decode: (self: Decoder, buf: buffer, offset: number?, length: number?) -> (number?, Err.Err?), + state: Decode.State, +} + +local function decode(self: Decoder, buf: buffer, offset: number?, length: number?): (number?, Err.Err?) + local o = offset or 0 + local n = length or (buffer.len(buf) - o) + if o < 0 or n < 0 or o + n > buffer.len(buf) then + return nil, Err.new(Err.ARG, "packet range out of the buffer") + end + local frames, msg = Decode.frame(self.state, buf, o, n) + if not frames then + return nil, Err.new(Err.CORRUPT, msg or "bad packet", o) + end + local ch = self.config.channels + local src, dst = self.state.out, self.pcm + if ch <= 2 then + for i = 1, frames * ch do + dst[i] = src[i] + end + else + local map = TO_WAV[ch] + for f = 0, frames - 1 do + local base = f * ch + for k = 1, ch do + dst[base + map[k]] = src[base + k] + end + end + end + return frames, nil +end + +-- decoder(cfg) -> Decoder +function Alac.decoder(cfg: Config): Decoder + return { + config = cfg, + pcm = table.create(cfg.frameLength * cfg.channels, 0), + decode = decode, + state = Decode.state(cfg), + } +end + +-- ------------------------------------------------------------------------------------------------ encoder +export type Encoder = { + config: Config, + encode: (self: Encoder, samples: { number }, first: number, frames: number) -> (buffer?, Err.Err?), + state: Encode.State, + bytes: number, + frames: number, +} + +local function encode(self: Encoder, samples: { number }, first: number, frames: number): (buffer?, Err.Err?) + local cfg = self.config + if type(samples) ~= "table" or frames < 1 or frames > cfg.frameLength or frames % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encode: 1 .. " .. cfg.frameLength .. " frames of interleaved integer samples") + end + if first < 1 or first + frames * cfg.channels - 1 > #samples then + return nil, Err.new(Err.ARG, "encode: the samples end early") + end + local ch = cfg.channels + local pkt = Encode.frame(self.state, samples, first, frames, TO_WAV[ch], ELEMENTS[ch]) + local n = buffer.len(pkt) + self.bytes += n + self.frames += frames + if n > cfg.maxFrameBytes then + cfg.maxFrameBytes = n + end + if self.frames > 0 then + cfg.avgBitRate = math.floor(self.bytes * 8 * cfg.sampleRate / self.frames) + end + return pkt, nil +end + +export type EncoderOptions = { + sampleRate: number, + channels: number, -- 1 .. 8 + bitDepth: number?, -- 16 (default), 20 or 24 + frameLength: number?, -- default 4096 +} + +-- encoder(opts) -> Encoder | nil, Err +function Alac.encoder(opts: EncoderOptions): (Encoder?, Err.Err?) + if type(opts) ~= "table" then + return nil, Err.new(Err.ARG, "encoder: expected options") + end + local depth = opts.bitDepth or 16 + local ch = opts.channels + if depth ~= 16 and depth ~= 20 and depth ~= 24 then + return nil, Err.new(Err.ARG, "encoder: bitDepth 16, 20 or 24") + end + if type(ch) ~= "number" or ch < 1 or ch > 8 or ch % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encoder: 1 .. 8 channels") + end + local sr = opts.sampleRate + if type(sr) ~= "number" or sr < 1 or sr % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encoder: bad sampleRate") + end + local fl = opts.frameLength or 4096 + if fl < 16 or fl > 16384 or fl % 1 ~= 0 then + return nil, Err.new(Err.ARG, "encoder: frameLength 16 .. 16384") + end + local cfg: Config = { + frameLength = fl, + compatibleVersion = 0, + bitDepth = depth, + pb = 40, + mb = 10, + kb = 14, + channels = ch, + maxRun = 255, + maxFrameBytes = 0, + avgBitRate = 0, + sampleRate = sr, + } + return { + config = cfg, + encode = encode, + state = Encode.state(cfg), + bytes = 0, + frames = 0, + }, nil +end + +return Alac diff --git a/tests/audio/_encode_cases.luau b/tests/audio/_encode_cases.luau new file mode 100644 index 0000000..1e7bd23 --- /dev/null +++ b/tests/audio/_encode_cases.luau @@ -0,0 +1,12 @@ +-- tests/audio/_encode_cases: the files our ALAC / CAF writers produce for the reference check (tools/fixtures/m4a.py +-- runs tools/fixtures/_m4a_encode.luau over them; tests/audio/m4a.luau and caf.luau re-encode and compare). +return { + { name = "ours_alac16_stereo", container = "m4a", rate = 44100, frames = 4096 * 3 + 1234, channels = 2, bits = 16, seed = 1, tags = { title = "Our Title \u{e9}", artist = "formats-luau", album = "Tests", track = "5", tracktotal = "10", date = "2026", genre = "Test", comment = "round trip" } }, + { name = "ours_alac16_mono", container = "m4a", rate = 22050, frames = 5000, channels = 1, bits = 16, seed = 2 }, + { name = "ours_alac24_stereo", container = "m4a", rate = 48000, frames = 9000, channels = 2, bits = 24, seed = 3 }, + { name = "ours_alac16_6ch", container = "m4a", rate = 48000, frames = 4500, channels = 6, bits = 16, seed = 4 }, + { name = "ours_alac20_stereo", container = "m4a", rate = 96000, frames = 3000, channels = 2, bits = 20, seed = 5 }, + { name = "ours_caf_alac16", container = "caf", codec = "alac", rate = 44100, frames = 7000, channels = 2, bits = 16, seed = 6 }, + { name = "ours_caf_pcm16", container = "caf", codec = "pcm", rate = 44100, frames = 3000, channels = 2, bits = 16, seed = 7 }, + { name = "ours_caf_pcm24", container = "caf", codec = "pcm", rate = 48000, frames = 2000, channels = 1, bits = 24, seed = 8 }, +} diff --git a/tests/audio/_signal.luau b/tests/audio/_signal.luau new file mode 100644 index 0000000..4986a7e --- /dev/null +++ b/tests/audio/_signal.luau @@ -0,0 +1,42 @@ +-- tests/audio/_signal: the deterministic integer test signal of tools/fixtures/_m4a_signal.py (the same numbers), as +-- an interleaved integer array and as a Types.Audio (f32, exact for up to 24 bits). Used by the m4a / caf tests and the +-- fixture-time encoder runs (tools/fixtures/_m4a_encode.luau). +local Types = require("@formats/Types") + +local Signal = {} + +function Signal.ints(frames: number, channels: number, bits: number, seed: number): { number } + local s = seed + local peak = 2 ^ (bits - 1) - 1 + local out = table.create(frames * channels, 0) + local k = 1 + for i = 0, frames - 1 do + for c = 0, channels - 1 do + s = (s * 48271) % 2147483647 + local p1 = 97 + 31 * c + local tri = math.abs((i % p1) * 2 - p1) * 2 - p1 + local v = tri * (peak // (4 * p1)) + local p2 = 1500 + 200 * c + v += if (i // p2) % 2 == 0 then peak // 6 else -(peak // 6) + v += ((s // 65536) % 4096 - 2048) * (peak // 65536 + 1) + if i % 7001 < 3 then + v += peak // 2 + end + out[k] = math.clamp(v, -peak - 1, peak) + k += 1 + end + end + return out +end + +function Signal.audio(rate: number, frames: number, channels: number, bits: number, seed: number): Types.Audio + local ints = Signal.ints(frames, channels, bits, seed) + local a = Types.Audio.new(rate, channels, frames) + local scale = 1 / 2 ^ (bits - 1) + for i, v in ints do + buffer.writef32(a.samples, (i - 1) * 4, v * scale) + end + return a +end + +return Signal diff --git a/tests/audio/aac.luau b/tests/audio/aac.luau new file mode 100644 index 0000000..360d39a --- /dev/null +++ b/tests/audio/aac.luau @@ -0,0 +1,117 @@ +-- audio/aac tests: ADTS streams from ffmpeg and fdkaac (stereo, mono 32 kHz) against ffmpeg's float decode (SNR, +-- length); an HE-AAC ADTS stream plays its core; a leading ID3v2 tag (skipped, text frames as tags) and garbage before +-- the first frame (resync); a truncated last frame; streaming + seek; sniff; errors; the fuzz no-throw pass. +-- Fixtures: tools/fixtures/m4a.py. +local T = require("@tests/T") +local AacF = require("@formats/audio/aac") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/m4a_aac") +local He = require("@tests/gen/m4a_he") + +local t = T.suite("aac") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +local function snr(a: any, ref: string, skip: number?): number + local off = (skip or 0) * a.channels + local n = math.min(a.frames * a.channels - off, #ref // 4) + local rb = buffer.fromstring(ref) + local sig, err = 0, 0 + for i = 0, n - 1 do + local r = buffer.readf32(rb, i * 4) + local d = buffer.readf32(a.samples, (off + i) * 4) - r + sig += r * r + err += d * d + end + return if err == 0 then math.huge else 10 * math.log10(sig / err) +end + +t:eq(AacF.name, "aac", "name") +t:check(AacF.caps.decode and not AacF.caps.encode and AacF.encode == nil, "caps: decode only") + +local first +for _, c in Fx do + if c.container ~= "adts" then + continue + end + first = first or c + local r = reader(c.data) + t:check(AacF.sniff(r) >= 0.9, c.name .. ": sniff") + local a, err = AacF.decode(r) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": frames (ADTS keeps the priming)") + local s = snr(a, c.ref) + t:check(s > 90, string.format("%s: SNR %.1f dB", c.name, s)) + t:note("%s: %d ch %d Hz, %d frames, SNR %.1f dB vs ffmpeg", c.name, c.channels, c.rate, a.frames, s) +end + +-- HE-AAC ADTS: the core +for _, c in He do + if string.sub(c.name, -4) == ".aac" then + local a, err = AacF.decode(reader(c.data)) + t:check(a and a.sampleRate == c.rate // 2 and a.frames > 0, c.name .. ": core decode: " .. tostring(err)) + end +end + +-- ID3v2 in front + garbage, truncated tail +do + local function frame(id: string, text: string): string + local body = "\3" .. text + local n = #body + return id .. string.char(0, 0, n // 128, n % 128) .. "\0\0" .. body + end + local frames = frame("TIT2", "Adts Title") .. frame("TPE1", "Someone") + local n = #frames + local id3 = "ID3\4\0\0" .. string.char(0, 0, n // 128, n % 128) .. frames + local data = id3 .. "\0\1\2garbage" .. first.data + local a, err = AacF.decode(reader(data)) + t:check(a, "id3 + garbage: " .. tostring(err)) + t:check(a.tags.title == "Adts Title" and a.tags.artist == "Someone", "id3 tags") + t:eq(a.frames, first.frames, "id3 + garbage: same frames") + t:check(snr(a, first.ref) > 90, "id3 + garbage: same audio") + local cut = AacF.decode(reader(string.sub(first.data, 1, #first.data - 5))) :: any + t:check(cut and cut.frames == first.frames - 1024, "truncated last frame dropped") +end + +-- streaming + seek +do + local whole = AacF.decode(reader(first.data)) :: any + local dec = AacF.open(reader(first.data)) :: any + for _, at in { 0.3, 0.0, 0.5123 } do + dec:seek(at) + local b, n = dec:read(600) + local f0 = math.floor(at * whole.sampleRate + 0.5) + local maxd = 0 + for i = 0, n * whole.channels - 1 do + maxd = math.max(maxd, math.abs(buffer.readf32(b, i * 4) - buffer.readf32(whole.samples, (f0 * whole.channels + i) * 4))) + end + -- (the stream has no PNS: noise substitution would draw different noise after a seek) + t:check(n == 600 and maxd < 1e-6, string.format("seek %.3f s (max diff %g)", at, maxd)) + end +end + +-- errors +do + t:eq(AacF.sniff(reader("RIFF....WAVE")), 0, "sniff a WAV") + local _, e = AacF.decode(reader(string.rep("\0", 100))) + t:check(e and e.code == Err.CORRUPT, "no frames: " .. tostring(e)) +end + +-- fuzz +do + local samples = {} + for _, c in Fx do + if c.container == "adts" then + table.insert(samples, string.sub(c.data, 1, 6000)) + end + end + t:fuzz("decode", function(b: buffer) + return AacF.decode(Bytes.reader(b)) + end, samples, { mutations = 30 }) +end + +t:done() diff --git a/tests/audio/caf.luau b/tests/audio/caf.luau new file mode 100644 index 0000000..c0f40ff --- /dev/null +++ b/tests/audio/caf.luau @@ -0,0 +1,177 @@ +-- audio/caf tests: ALAC CAF from ffmpeg bit-exact; AAC CAF (ffmpeg's ADTS frames wrapped by the fixture) against +-- ffmpeg's float decode; our CAF writer (PCM 16 / 24-bit, ALAC; re-encoded here and compared with the bytes ffmpeg +-- decoded bit-exactly); PCM layouts (little / big endian, float) through our writer + a hand-built header; info tags; +-- seek; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/m4a.py. +local T = require("@tests/T") +local Caf = require("@formats/audio/caf") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Signal = require("@tests/audio/_signal") +local Cases = require("@tests/audio/_encode_cases") +local Alac = require("@tests/gen/m4a_alac") +local Aac = require("@tests/gen/m4a_aac") +local Ours = require("@tests/gen/m4a_ours") + +local t = T.suite("caf") + +local function reader(s: string | buffer): Bytes.Reader + return Bytes.reader(if type(s) == "string" then buffer.fromstring(s) else s) +end + +local function intCrc(a: any, bits: number): number + local n = a.frames * a.channels + local b = buffer.create(n * 4) + local scale = 2 ^ (bits - 1) + for i = 0, n - 1 do + buffer.writei32(b, i * 4, math.floor(buffer.readf32(a.samples, i * 4) * scale + 0.5)) + end + return Crc32.of(b) +end + +t:eq(Caf.name, "caf", "name") +t:check(Caf.caps.decode and Caf.caps.encode, "caps") + +for _, c in Alac do + if c.container == "caf" then + local r = reader(c.data) + t:eq(Caf.sniff(r), 1, c.name .. ": sniff") + local a, err = Caf.decode(r) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.channels == c.channels and a.sampleRate == c.rate and a.frames == c.frames, c.name .. ": format / length (pakt)") + t:eq(intCrc(a, c.bits), c.crc, c.name .. ": bit-exact") + end +end + +for _, c in Aac do + if c.container == "caf" then + local a, err = Caf.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:eq(a.frames, c.frames, c.name .. ": frames") + local rb = buffer.fromstring(c.ref) + local sig, e = 0, 0 + for i = 0, a.frames * a.channels - 1 do + local r = buffer.readf32(rb, i * 4) + sig += r * r + e += (buffer.readf32(a.samples, i * 4) - r) ^ 2 + end + local snr = if e == 0 then math.huge else 10 * math.log10(sig / e) + t:check(snr > 90, string.format("%s: SNR %.1f dB", c.name, snr)) + t:note("%s: SNR %.1f dB vs ffmpeg", c.name, snr) + end +end + +-- our writer: the bytes ffmpeg validated +do + local byName = {} + for _, o in Ours do + byName[o.name] = o + end + for _, c in Cases do + if c.container ~= "caf" then + continue + end + local o = byName[c.name] + t:check(o and o.ffmpeg, c.name .. ": ffmpeg decoded it bit-exactly") + local a = Signal.audio(c.rate, c.frames, c.channels, c.bits, c.seed) + local file = Caf.encode(a, { codec = c.codec, bitDepth = c.bits }) :: buffer + t:eq(string.format("%08x", Crc32.of(file)), string.format("%08x", o.crc), c.name .. ": the validated bytes") + local back = Caf.decode(reader(file)) :: any + t:check(back and back.frames == c.frames, c.name .. ": our length") + local ints = Signal.ints(c.frames, c.channels, c.bits, c.seed) + local ok = true + local scale = 2 ^ (c.bits - 1) + for i = 1, #ints do + ok = ok and math.floor(buffer.readf32(back.samples, (i - 1) * 4) * scale + 0.5) == ints[i] + end + t:check(ok, c.name .. ": round trip") + end +end + +-- float PCM, tags, a decoder as the source, a hand-built little-endian header +do + local a = Signal.audio(32000, 3000, 3, 16, 12) + a.tags = { title = "Caf Title", artist = "A", date = "1999", comment = "c", custom = "x" } + local file = Caf.encode(a, { codec = "pcm", bitDepth = 32 }) :: buffer + local back = Caf.decode(reader(file)) :: any + t:check(back.frames == 3000 and buffer.tostring(back.samples) == buffer.tostring(a.samples), "float PCM round trip") + for k, v in a.tags do + t:eq(back.tags[k], v, "tag " .. k) + end + local dec = Caf.open(reader(file)) :: any + local again = Caf.encode(dec, { codec = "alac" }) :: buffer + local b2 = Caf.decode(reader(again)) :: any + t:check(b2.frames == 3000 and buffer.tostring(b2.samples) == buffer.tostring(a.samples), "ALAC from a streaming decoder") + -- little-endian 24-bit integer PCM, data chunk of unknown size (-1) + local w = Bytes.writer(64) + w:string("caff") + w:u16be(1) + w:u16be(0) + w:string("desc") + w:u64be(32) + w:f64be(8000) + w:string("lpcm") + w:u32be(2) + w:u32be(3) + w:u32be(1) + w:u32be(1) + w:u32be(24) + w:string("data") + w:u32be(0xFFFFFFFF) + w:u32be(0xFFFFFFFF) + w:u32be(0) + for _, v in { 0, 4194304, -4194304, 8388607, -8388608 } do + w:u24le(v % 16777216) + end + local le = Caf.decode(Bytes.reader(w:finish())) :: any + t:check(le and le.frames == 5, "24-bit LE, data size -1") + t:check(le and math.abs(buffer.readf32(le.samples, 4) - 0.5) < 1e-7 and math.abs(buffer.readf32(le.samples, 16) + 1) < 1e-7, "24-bit LE values") +end + +-- seek +do + local c = Alac[#Alac] + local whole = Caf.decode(reader(c.data)) :: any + local dec = Caf.open(reader(c.data)) :: any + for _, at in { 0.1, 0.0, 0.15 } do + dec:seek(at) + local b, n = dec:read(400) + local f0 = math.floor(at * whole.sampleRate + 0.5) + local same = n == 400 + for i = 0, n * whole.channels - 1 do + same = same and buffer.readf32(b, i * 4) == buffer.readf32(whole.samples, (f0 * whole.channels + i) * 4) + end + t:check(same, string.format("seek %.2f s", at)) + end +end + +-- errors +do + t:eq(Caf.sniff(reader("caff\0\2\0\0")), 0, "sniff: wrong version") + local _, e = Caf.decode(reader("caff\0\1\0\0")) + t:check(e and e.code == Err.CORRUPT, "no desc: " .. tostring(e)) + local _, e2 = Caf.encode(Signal.audio(8000, 10, 1, 16, 1), { codec = "mp3" } :: any) + t:check(e2 and e2.code == Err.ARG, "bad codec: " .. tostring(e2)) +end + +-- fuzz +do + local samples = {} + for _, c in Alac do + if c.container == "caf" then + table.insert(samples, string.sub(c.data, 1, 9000)) + end + end + for _, c in Aac do + if c.container == "caf" then + table.insert(samples, string.sub(c.data, 1, 6000)) + end + end + local pcm = Caf.encode(Signal.audio(8000, 300, 2, 16, 3), { codec = "pcm" }) :: buffer + table.insert(samples, buffer.tostring(pcm)) + t:fuzz("decode", function(b: buffer) + return Caf.decode(Bytes.reader(b)) + end, samples, { mutations = 30 }) +end + +t:done() diff --git a/tests/audio/m4a.luau b/tests/audio/m4a.luau new file mode 100644 index 0000000..273f71e --- /dev/null +++ b/tests/audio/m4a.luau @@ -0,0 +1,218 @@ +-- audio/m4a tests: ALAC files from ffmpeg decode bit-exactly (16 / 24-bit, mono / stereo / 5.1, partial frames); +-- AAC-LC files from ffmpeg and fdkaac (stereo / mono / 5.1, 8 - 96 kHz, PNS / intensity / M/S / TNS) against ffmpeg's +-- float decode (SNR, gapless length through the edit list); HE-AAC / HE-AACv2 play their core; our ALAC writer +-- (re-encoded here, compared with the bytes ffmpeg decoded bit-exactly and MP4Box accepted in the fixture step); tags +-- and cover art round trips; streaming reads, seeking; the contract; the fuzz no-throw pass. +-- Fixtures: tools/fixtures/m4a.py. +local T = require("@tests/T") +local M4a = require("@formats/audio/m4a") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Signal = require("@tests/audio/_signal") +local Cases = require("@tests/audio/_encode_cases") +local Alac = require("@tests/gen/m4a_alac") +local Aac = require("@tests/gen/m4a_aac") +local He = require("@tests/gen/m4a_he") +local Ours = require("@tests/gen/m4a_ours") + +local t = T.suite("m4a") + +local function reader(s: string | buffer): Bytes.Reader + return Bytes.reader(if type(s) == "string" then buffer.fromstring(s) else s) +end + +-- the integers of a decoded Audio (exact for <= 24-bit sources), CRC-32 as little-endian int32 +local function intCrc(a: any, bits: number): number + local n = a.frames * a.channels + local b = buffer.create(n * 4) + local scale = 2 ^ (bits - 1) + for i = 0, n - 1 do + buffer.writei32(b, i * 4, math.floor(buffer.readf32(a.samples, i * 4) * scale + 0.5)) + end + return Crc32.of(b) +end + +local function snr(a: any, ref: string): (number, number) + local n = math.min(a.frames * a.channels, #ref // 4) + local rb = buffer.fromstring(ref) + local sig, err = 0, 0 + for i = 0, n - 1 do + local r = buffer.readf32(rb, i * 4) + local d = buffer.readf32(a.samples, i * 4) - r + sig += r * r + err += d * d + end + if err == 0 then + return math.huge, n + end + return 10 * math.log10(sig / err), n +end + +-- the contract +t:eq(M4a.name, "m4a", "name") +t:eq(M4a.category, "audio", "category") +t:check(M4a.caps.decode and M4a.caps.encode, "caps") + +-- ALAC from ffmpeg: bit-exact +for _, c in Alac do + if c.container ~= "m4a" then + continue + end + local r = reader(c.data) + t:check(M4a.sniff(r) == 1, c.name .. ": sniff") + local a, err = M4a.decode(r) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": frames") + t:eq(intCrc(a, c.bits), c.crc, c.name .. ": samples bit-exact") + t:eq(a.meta.source.codec, "alac", c.name .. ": codec") +end +t:note("%d ffmpeg ALAC files decode bit-exactly", #Alac - 1) + +-- AAC: against ffmpeg's float decode +local worst = math.huge +for _, c in Aac do + if c.container ~= "m4a" then + continue + end + local a, err = M4a.decode(reader(c.data)) + t:check(a, c.name .. ": " .. tostring(err)) + t:check(a.channels == c.channels and a.sampleRate == c.rate, c.name .. ": format") + t:eq(a.frames, c.frames, c.name .. ": gapless length") + local s = snr(a, c.ref) + worst = math.min(worst, s) + t:check(s > 90, string.format("%s: SNR %.1f dB vs ffmpeg", c.name, s)) + t:note("%s: %d ch %d Hz, %d frames, SNR %.1f dB vs ffmpeg", c.name, c.channels, c.rate, a.frames, s) +end + +-- HE-AAC: the AAC-LC core at half the rate, SBR seen +for _, c in He do + if string.sub(c.name, -4) ~= ".m4a" then + continue + end + local dec, err = M4a.open(reader(c.data)) + t:check(dec, c.name .. ": " .. tostring(err)) + t:eq(dec.sampleRate, c.rate // 2, c.name .. ": core rate") + local b, n = dec:read(8192) + local e = 0 + for i = 0, n * dec.channels - 1 do + e += buffer.readf32(b, i * 4) ^ 2 + end + t:check(n == 8192 and e > 1, c.name .. ": the core decodes (energy " .. e .. ")") +end + +-- our ALAC writer: the bytes ffmpeg validated +do + local byName = {} + for _, o in Ours do + byName[o.name] = o + end + for _, c in Cases do + if c.container ~= "m4a" then + continue + end + local o = byName[c.name] + t:check(o and o.ffmpeg and o.mp4box and o.codec == "alac", c.name .. ": ffmpeg decoded it bit-exactly, MP4Box read it") + t:eq(o.frames, c.frames, c.name .. ": ffmpeg's length") + local a = Signal.audio(c.rate, c.frames, c.channels, c.bits, c.seed) + a.tags = c.tags or {} + local file, err = M4a.encode(a, { bitDepth = c.bits }) + t:check(file, c.name .. ": encode: " .. tostring(err)) + t:eq(string.format("%08x", Crc32.of(file :: buffer)), string.format("%08x", o.crc), c.name .. ": the validated bytes") + -- and our own decoder gets the integers back + local back = M4a.decode(Bytes.reader(file :: buffer)) :: any + local ints = Signal.ints(c.frames, c.channels, c.bits, c.seed) + local ok = back.frames == c.frames + local scale = 2 ^ (c.bits - 1) + for i = 1, #ints, 7 do + ok = ok and math.floor(buffer.readf32(back.samples, (i - 1) * 4) * scale + 0.5) == ints[i] + end + t:check(ok, c.name .. ": round trip") + if c.tags then + for k, v in c.tags do + t:eq(back.tags[k], v, c.name .. ": tag " .. k) + end + t:eq(o.tags.title, c.tags.title, c.name .. ": ffprobe title") + t:eq(o.tags.track, c.tags.track .. "/" .. c.tags.tracktotal, c.name .. ": ffprobe track") + t:eq(o.tags.artist, c.tags.artist, c.name .. ": ffprobe artist") + end + t:note("%s: %d bytes (%.0f%% of PCM)", c.name, buffer.len(file :: buffer), 100 * buffer.len(file :: buffer) / (c.frames * c.channels * c.bits / 8)) + end +end + +-- cover art + streaming a decoder into the encoder +do + local a = Signal.audio(44100, 5000, 2, 16, 9) + a.meta.pictures = { { mime = "image/png", data = buffer.fromstring("\137PNG fake") } } + a.tags = { title = "Pic" } + local file = M4a.encode(a) :: buffer + local back = M4a.decode(Bytes.reader(file)) :: any + t:check(back.meta.pictures and #back.meta.pictures == 1 and back.meta.pictures[1].mime == "image/png", "cover art round trip") + local dec = M4a.open(Bytes.reader(file)) :: any + local again = M4a.encode(dec) :: buffer + local back2 = M4a.decode(Bytes.reader(again)) :: any + t:check(back2.frames == 5000 and buffer.tostring(back2.samples) == buffer.tostring(back.samples), "encode from a streaming decoder") + local _, e = M4a.encode({} :: any) + t:check(e and e.code == Err.ARG, "encode of a non-audio returns Err.ARG") + local _, e2 = M4a.encode(a, { bitDepth = 12 }) + t:check(e2 and e2.code == Err.ARG, "bad bitDepth returns Err.ARG") +end + +-- streaming + seek (AAC without PNS: its noise is random, so a seek changes it; and ALAC) +for _, c in { Aac[1], Alac[1] } do + local whole = M4a.decode(reader(c.data)) :: any + local dec = M4a.open(reader(c.data)) :: any + t:eq(dec.frames, whole.frames, c.name .. ": decoder frames") + -- read in odd chunks + local got, out = 0, buffer.create(whole.frames * whole.channels * 4) + while true do + local b, n = dec:read(777) + if n == 0 then + break + end + buffer.copy(out, got * whole.channels * 4, b, 0, n * whole.channels * 4) + got += n + end + t:check(got == whole.frames and buffer.tostring(out) == buffer.tostring(whole.samples), c.name .. ": chunked reads equal the whole decode") + for _, at in { 0.1, 0.0, 0.05 } do + dec:seek(at) + local b, n = dec:read(500) + local f0 = math.floor(at * whole.sampleRate + 0.5) + local maxd = 0 + for i = 0, n * whole.channels - 1 do + maxd = math.max(maxd, math.abs(buffer.readf32(b, i * 4) - buffer.readf32(whole.samples, (f0 * whole.channels + i) * 4))) + end + t:check(n == 500 and maxd < 1e-6, string.format("%s: seek %.2f s (max diff %g)", c.name, at, maxd)) + t:check(math.abs(dec:position() - (f0 + 500) / whole.sampleRate) < 1e-9, c.name .. ": position after seek") + end +end + +-- errors +do + local _, e = M4a.decode(reader("\0\0\0\8ftypM4A ")) + t:check(e ~= nil, "a lone ftyp: " .. tostring(e)) + local _, e2 = M4a.decode(reader("hello world, not an mp4")) + t:check(e2 ~= nil and Err.is(e2), "junk: " .. tostring(e2)) + t:eq(M4a.sniff(reader("hello")), 0, "sniff junk") +end + +-- fuzz +do + local samples = {} + for i, c in Alac do + if c.container == "m4a" and i <= 2 then + table.insert(samples, string.sub(c.data, 1, 12000)) + end + end + for i, c in Aac do + if c.container == "m4a" and i <= 2 then + table.insert(samples, string.sub(c.data, 1, 9000)) + end + end + t:fuzz("decode", function(b: buffer) + return M4a.decode(Bytes.reader(b)) + end, samples, { mutations = 25 }) +end + +t:done() diff --git a/tests/codecs/aac.luau b/tests/codecs/aac.luau new file mode 100644 index 0000000..b340bd4 --- /dev/null +++ b/tests/codecs/aac.luau @@ -0,0 +1,182 @@ +-- codecs/Aac tests: AudioSpecificConfig parsing (every fixture's esds, explicit SBR / PS signalling from fdkaac, +-- crafted configs: PCE channel counts, 960-sample frames, Main / LTP object types), ADTS headers, raw frames decoded +-- straight from ADTS against ffmpeg's float decode, the FIL extension hook on HE-AAC (implicit SBR), reset, errors, +-- the fuzz no-throw pass on raw frames. Fixtures: tools/fixtures/m4a.py. +local T = require("@tests/T") +local Aac = require("@formats/codecs/Aac") +local IsoBmff = require("@formats/containers/IsoBmff") +local Bytes = require("@formats/core/Bytes") +local Bits = require("@formats/core/Bits") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/m4a_aac") +local He = require("@tests/gen/m4a_he") + +local t = T.suite("aac-codec") + +-- ADTS frames of a stream: { offset, size } of the raw blocks +local function frames(data: buffer): ({ { number } }, Aac.Adts?) + local out, p, first = {}, 0, nil + while true do + local h = Aac.adts(data, p, buffer.len(data)) + if not h or p + h.frameSize > buffer.len(data) then + break + end + first = first or h + table.insert(out, { p + h.headerSize, h.frameSize - h.headerSize }) + p += h.frameSize + end + return out, first +end + +-- ASCs from the M4A fixtures +for _, c in Fx do + if c.container == "m4a" then + local r = Bytes.reader(buffer.fromstring(c.data)) + local movie = IsoBmff.parse(r) :: IsoBmff.Movie + local cfg, err = Aac.config(movie.tracks[1].config :: buffer) + t:check(cfg, c.name .. ": " .. tostring(err)) + t:check(cfg.objectType == 2 and cfg.sampleRate == c.rate and cfg.channels == c.channels and not cfg.sbr, c.name .. ": AAC-LC config") + end +end +for _, c in He do + if string.sub(c.name, -4) == ".m4a" then + local r = Bytes.reader(buffer.fromstring(c.data)) + local movie = IsoBmff.parse(r) :: IsoBmff.Movie + local cfg, err = Aac.config(movie.tracks[1].config :: buffer) + t:check(cfg, c.name .. ": " .. tostring(err)) + t:check(cfg.sbr and cfg.sampleRate == c.rate // 2 and cfg.extensionRate == c.rate, c.name .. ": SBR signalled, core at half rate") + t:eq(cfg.ps, c.ps, c.name .. ": PS signalled") + end +end + +-- crafted configs +do + local asc = Aac.asc(2, 4, 2) + local cfg = Aac.config(asc) :: Aac.Config + t:check(cfg and cfg.sampleRate == 44100 and cfg.channels == 2, "asc(2, 44.1 kHz, stereo)") + local _, e1 = Aac.config(Aac.asc(1, 4, 2)) + t:check(e1 and e1.code == Err.UNSUPPORTED, "AAC Main: " .. tostring(e1)) + local _, e2 = Aac.config(Aac.asc(23, 4, 2)) + t:check(e2 and e2.code == Err.UNSUPPORTED, "ER AAC LD") + local b960 = Aac.asc(2, 3, 1) + buffer.writeu8(b960, 1, bit32.bor(buffer.readu8(b960, 1), 4)) -- frameLengthFlag + local _, e3 = Aac.config(b960) + t:check(e3 and e3.code == Err.UNSUPPORTED, "960-sample frames") + -- channel configuration 0 with a PCE: front C (SCE) + L/R (CPE), back L/R (CPE), one LFE = 6 channels + local bw = Bits.msbWriter() + bw:write(2, 5) + bw:write(3, 4) + bw:write(0, 4) + bw:write(0, 3) -- GASpecificConfig flags + bw:write(0, 4) -- PCE: tag + bw:write(1, 2) + bw:write(3, 4) + bw:write(2, 4) -- front + bw:write(0, 4) -- side + bw:write(1, 4) -- back + bw:write(1, 2) -- lfe + bw:write(0, 3) + bw:write(0, 4) + bw:write(0, 3) -- mixdowns + bw:write(0, 5) + bw:write(16 + 1, 5) -- front: SCE 0, CPE 1 + bw:write(16 + 2, 5) -- back: CPE 2 + bw:write(0, 4) -- lfe tag + bw:align() + bw:write(0, 8) -- comment + local pcfg, perr = Aac.config(bw:finish()) + t:check(pcfg and pcfg.channels == 6 and pcfg.channelConfig == 0, "PCE: 6 channels: " .. tostring(perr)) + local _, e4 = Aac.decoder("nope" :: any) + t:check(e4 and e4.code == Err.ARG, "decoder of a string") +end + +-- ADTS headers + raw frames against ffmpeg +for _, c in Fx do + if c.container ~= "adts" then + continue + end + local data = buffer.fromstring(c.data) + local list, h = frames(data) + t:check(h and h.objectType == 2 and h.sampleRate == c.rate, c.name .. ": ADTS header") + local dec = Aac.decoder({ sfIndex = (h :: Aac.Adts).sfIndex, channels = c.channels }) :: Aac.Decoder + local ref = buffer.fromstring(c.ref) + local sig, err = 0, 0 + local o = 0 + for _, f in list do + local n, e = dec:decode(data, f[1], f[2]) + t:check(n == 1024, c.name .. ": frame: " .. tostring(e)) + for k = 1, 1024 * c.channels do + local r = buffer.readf32(ref, o) + sig += r * r + err += (dec.pcm[k] - r) ^ 2 + o += 4 + end + end + local snr = 10 * math.log10(sig / math.max(err, 1e-30)) + t:check(snr > 90, string.format("%s: SNR %.1f dB", c.name, snr)) + t:note("%s: %d raw frames, SNR %.1f dB vs ffmpeg", c.name, #list, snr) + -- reset: decoding again from the start gives the same first frames + dec:reset() + dec:decode(data, list[1][1], list[1][2]) + local again = table.clone(dec.pcm) + local dec2 = Aac.decoder({ sfIndex = (h :: Aac.Adts).sfIndex, channels = c.channels }) :: Aac.Decoder + dec2:decode(data, list[1][1], list[1][2]) + local same = true + for k = 1, 1024 * c.channels do + same = same and again[k] == dec2.pcm[k] + end + t:check(same, c.name .. ": reset clears the overlap") +end + +-- the extension hook on HE-AAC (implicit SBR in ADTS) +for _, c in He do + if string.sub(c.name, -4) == ".aac" then + local data = buffer.fromstring(c.data) + local list, h = frames(data) + local dec = Aac.decoder({ sfIndex = (h :: Aac.Adts).sfIndex, channels = 2 }) :: Aac.Decoder + local seen, bits = 0, 0 + dec.onExtension = function(kind: number, _element: number, _buf: buffer, _pos: number, n: number) + if kind == 13 or kind == 14 then + seen += 1 + bits += n + end + end + for _, f in list do + dec:decode(data, f[1], f[2]) + end + t:check(seen == #list and dec.sbr, string.format("%s: an SBR payload per frame (%d of %d, %d bits)", c.name, seen, #list, bits)) + end +end + +-- errors +do + local dec = Aac.decoder(Aac.asc(2, 4, 2)) :: Aac.Decoder + local _, e = dec:decode(buffer.fromstring("\x20\x00\x00\x00\x00")) + t:check(e and e.code == Err.CORRUPT, "garbage frame: " .. tostring(e)) + local _, e2 = dec:decode(buffer.create(4), 3, 10) + t:check(e2 and e2.code == Err.ARG, "range out of the buffer") + t:check(Aac.adts(buffer.fromstring("\255\241"), 0, 2) == nil, "short ADTS header") +end + +-- fuzz raw frames (stereo with every tool, mono, 5.1) +do + local pick = {} + for _, c in Fx do + if c.container == "adts" then + local data = buffer.fromstring(c.data) + local list, h = frames(data) + local f = list[math.min(#list, 9)] + local raw = buffer.create(f[2]) + buffer.copy(raw, 0, data, f[1], f[2]) + table.insert(pick, { raw, (h :: Aac.Adts).sfIndex, c.channels }) + end + end + for _, p in pick do + local dec = Aac.decoder({ sfIndex = p[2], channels = p[3] }) :: Aac.Decoder + t:fuzz("raw frame " .. p[3] .. " ch", function(b: buffer) + return dec:decode(b) + end, { p[1] }, { mutations = 60, garbage = 100 }) + end +end + +t:done() diff --git a/tests/codecs/alac.luau b/tests/codecs/alac.luau new file mode 100644 index 0000000..8dff395 --- /dev/null +++ b/tests/codecs/alac.luau @@ -0,0 +1,181 @@ +-- codecs/Alac tests: encoder -> decoder round trips over silence (zero runs), full-scale noise (uncompressed frames), +-- tones, steps, 1 - 8 channels, 16 / 20 / 24 bits, partial and tiny frames, custom frame lengths; ffmpeg's ALAC +-- packets (through containers/IsoBmff) decode to the source integers; the magic cookie (plain, behind frma / alac atoms, +-- bad versions / depths); errors; the fuzz no-throw pass on packets. Fixtures: tools/fixtures/m4a.py. +local T = require("@tests/T") +local Alac = require("@formats/codecs/Alac") +local IsoBmff = require("@formats/containers/IsoBmff") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/m4a_alac") + +local t = T.suite("alac") +local rand = T.rng(42) + +local function roundTrip(label: string, ch: number, bits: number, frames: number, gen: (number, number) -> number, fl: number?) + local enc = Alac.encoder({ sampleRate = 44100, channels = ch, bitDepth = bits, frameLength = fl }) :: Alac.Encoder + t:check(enc, label .. ": encoder") + local per = enc.config.frameLength + local src = table.create(frames * ch, 0) + for i = 0, frames - 1 do + for c = 1, ch do + src[i * ch + c] = gen(i, c) + end + end + local packets = {} + local bytes = 0 + local f = 0 + while f < frames do + local n = math.min(per, frames - f) + local p, err = enc:encode(src, f * ch + 1, n) + t:check(p, label .. ": encode: " .. tostring(err)) + table.insert(packets, { p, n }) + bytes += buffer.len(p :: buffer) + f += n + end + local cfg = Alac.config(Alac.cookie(enc.config)) :: Alac.Config + t:check(cfg and cfg.maxFrameBytes >= 1 and cfg.channels == ch and cfg.bitDepth == bits, label .. ": cookie") + local dec = Alac.decoder(cfg) + local ok = true + local at = 0 + for _, pk in packets do + local n, err = dec:decode(pk[1]) + if n ~= pk[2] then + ok = false + t:check(false, label .. ": decode: " .. tostring(err)) + break + end + for k = 1, n * ch do + if dec.pcm[k] ~= src[at * ch + k] then + ok = false + end + end + at += n + end + t:check(ok, label .. ": round trip") + return bytes / (frames * ch * bits / 8) +end + +local peakOf = function(bits: number): number + return 2 ^ (bits - 1) +end + +for _, bits in { 16, 20, 24 } do + local pk = peakOf(bits) + for _, ch in { 1, 2, 3, 6, 8 } do + local r1 = roundTrip(string.format("tone %d-bit %d ch", bits, ch), ch, bits, 9000, function(i, c) + return math.floor(math.sin(i * 0.031 * c) * (pk * 0.6) + math.sin(i * 0.0071) * pk * 0.2) + end) + if ch == 2 then + t:note("%d-bit stereo tone: %.0f%% of PCM", bits, r1 * 100) + end + end + roundTrip(bits .. "-bit silence (zero runs)", 2, bits, 10000, function() + return 0 + end) + local r = roundTrip(bits .. "-bit full-scale noise (escape frames)", 2, bits, 5000, function() + return rand(2 ^ bits) - pk + end) + t:check(r < 1.01, bits .. "-bit noise stays near PCM size") + roundTrip(bits .. "-bit extremes", 1, bits, 600, function(i) + return if i % 2 == 0 then pk - 1 else -pk + end) + roundTrip(bits .. "-bit sparse clicks (zero runs + values)", 2, bits, 7000, function(i, c) + return if i % 997 == c then pk // 3 else 0 + end) +end +for _, n in { 1, 2, 3, 5, 9, 17, 4095 } do + roundTrip("partial frame of " .. n, 2, 16, n, function(i, c) + return (i * 37 + c * 1000) % 3000 - 1500 + end) +end +roundTrip("frame length 1024", 2, 16, 5000, function(i) + return math.floor(math.sin(i * 0.05) * 10000) +end, 1024) +roundTrip("identical channels", 2, 16, 5000, function(i) + return math.floor(math.sin(i * 0.02) * 20000) +end) + +-- ffmpeg's packets +for _, c in Fx do + if c.container == "m4a" then + local r = Bytes.reader(buffer.fromstring(c.data)) + local movie = IsoBmff.parse(r) :: IsoBmff.Movie + local tr = movie.tracks[1] + local cfg = Alac.config(tr.config :: buffer) :: Alac.Config + t:check(cfg and cfg.bitDepth == c.bits and cfg.channels == c.channels, c.name .. ": cookie") + local dec = Alac.decoder(cfg) + local out = buffer.create(c.frames * c.channels * 4) + local o = 0 + for i = 1, tr.sampleCount do + local n, err = dec:decode(r.buf, tr.offsets[i], tr.sizes[i]) + t:check(n, c.name .. ": packet " .. i .. ": " .. tostring(err)) + for k = 1, (n :: number) * c.channels do + buffer.writei32(out, o, dec.pcm[k]) + o += 4 + end + end + t:eq(Crc32.of(out), c.crc, c.name .. ": ffmpeg's packets decode to the source") + end +end + +-- the cookie behind QuickTime atoms, bad cookies +do + local enc = Alac.encoder({ sampleRate = 48000, channels = 2 }) :: Alac.Encoder + local plain = Alac.cookie(enc.config) + local w = Bytes.writer(64) + w:u32be(12) + w:string("frma") + w:string("alac") + w:u32be(36) + w:string("alac") + w:u32be(0) + w:bytes(plain) + local cfg = Alac.config(w:finish()) + t:check(cfg and cfg.sampleRate == 48000 and cfg.frameLength == 4096, "cookie behind frma / alac atoms") + local bad = buffer.fromstring(buffer.tostring(plain)) + buffer.writeu8(bad, 5, 12) + local _, e = Alac.config(bad) + t:check(e and e.code == Err.UNSUPPORTED, "12-bit cookie: " .. tostring(e)) + local _, e2 = Alac.config(buffer.create(10)) + t:check(e2 and e2.code == Err.TRUNCATED, "short cookie") + local _, e3 = Alac.encoder({ sampleRate = 44100, channels = 9 }) + t:check(e3 and e3.code == Err.ARG, "9 channels") + local _, e4 = enc:encode({ 1, 2 }, 1, 5) + t:check(e4 and e4.code == Err.ARG, "too few samples") + local dec = Alac.decoder(cfg :: Alac.Config) + local _, e5 = dec:decode(buffer.fromstring("\1\255\255\255")) + t:check(e5 and e5.code == Err.CORRUPT, "bad packet: " .. tostring(e5)) +end + +-- fuzz the packet decoder +do + local enc = Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 }) :: Alac.Encoder + local src = table.create(2 * 3000, 0) + for i = 1, #src do + src[i] = math.floor(math.sin(i * 0.01) * 8000) + rand(64) + end + local samples = {} + table.insert(samples, (enc:encode(src, 1, 3000))) + for i = 1, #src do + src[i] = if i % 300 < 3 then 5000 else 0 + end + table.insert(samples, (enc:encode(src, 1, 3000))) + local dec = Alac.decoder(enc.config) + local enc24 = Alac.encoder({ sampleRate = 44100, channels = 1, bitDepth = 24 }) :: Alac.Encoder + local dec24 = Alac.decoder(enc24.config) + local s24 = table.create(2000, 0) + for i = 1, 2000 do + s24[i] = rand(2 ^ 24) - 2 ^ 23 + end + local p24 = enc24:encode(s24, 1, 2000) :: buffer + t:fuzz("decode packet", function(b: buffer) + return dec:decode(b) + end, samples, { mutations = 40 }) + t:fuzz("decode 24-bit escape packet", function(b: buffer) + return dec24:decode(b) + end, { p24 }, { mutations = 20, garbage = 50 }) +end + +t:done() diff --git a/tools/fixtures/_m4a_encode.luau b/tools/fixtures/_m4a_encode.luau new file mode 100644 index 0000000..8a42eb5 --- /dev/null +++ b/tools/fixtures/_m4a_encode.luau @@ -0,0 +1,31 @@ +-- tools/fixtures/_m4a_encode: run by tools/fixtures/m4a.py (luau, from the repo root) so the reference tools can check +-- our writers: encodes the test signal (tests/audio/_signal) to ALAC M4A (audio/m4a) and ALAC / PCM CAF (audio/caf) +-- and prints " " lines. The tests re-encode and compare the CRC with the file ffmpeg validated. +local Signal = require("@tests/audio/_signal") +local M4a = require("@formats/audio/m4a") +local Caf = require("@formats/audio/caf") + +local function hex(b: buffer): string + local t = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + t[i + 1] = string.format("%02x", buffer.readu8(b, i)) + end + return table.concat(t) +end + +local Cases = require("@tests/audio/_encode_cases") +for _, c in Cases do + local a = Signal.audio(c.rate, c.frames, c.channels, c.bits, c.seed) + a.tags = c.tags or {} + local out, err + if c.container == "caf" then + out, err = Caf.encode(a, { codec = c.codec, bitDepth = c.bits }) + else + out, err = M4a.encode(a, { bitDepth = c.bits }) + end + if not out then + print(c.name .. " ERROR " .. tostring(err)) + else + print(c.name .. " " .. hex(out)) + end +end diff --git a/tools/fixtures/_m4a_signal.py b/tools/fixtures/_m4a_signal.py new file mode 100644 index 0000000..7eb72ed --- /dev/null +++ b/tools/fixtures/_m4a_signal.py @@ -0,0 +1,41 @@ +# The deterministic integer test signal shared by tools/fixtures/m4a.py, tools/fixtures/caf.py and the Luau side +# (tests/audio/_signal.luau computes the same numbers): triangle + square + MINSTD noise (exact in doubles) + clicks, per channel. +import struct + + +def signal(frames, channels, bits, seed): + s = seed + peak = 2 ** (bits - 1) - 1 + out = [] + for i in range(frames): + for c in range(channels): + s = (s * 48271) % 2147483647 + p1 = 97 + 31 * c + tri = abs((i % p1) * 2 - p1) * 2 - p1 + v = tri * (peak // (4 * p1)) + p2 = 1500 + 200 * c + v += (peak // 6) if (i // p2) % 2 == 0 else -(peak // 6) + v += ((s // 65536) % 4096 - 2048) * (peak // 65536 + 1) + if i % 7001 < 3: + v += peak // 2 + out.append(max(-peak - 1, min(peak, v))) + return out + + +def pack(samples, bits, big=False): + e = ">" if big else "<" + if bits == 16: + return struct.pack(e + "%dh" % len(samples), *samples) + if bits == 24: + b = bytearray() + for v in samples: + x = struct.pack("> 5) + frames.append(adts[p + hs:p + size]) + sfi, ch, aot = (b2 >> 2) & 15, ((b2 & 1) << 2) | (b3 >> 6), (b2 >> 6) + 1 + p += size + rate = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350][sfi] + asc = struct.pack(">H", (aot << 11) | (sfi << 7) | (ch << 3)) + dsi = b"\x05" + bytes([len(asc)]) + asc + dcd = b"\x04" + bytes([13 + len(dsi)]) + bytes([0x40, 0x15, 0, 0, 0]) + struct.pack(">II", 0, 0) + dsi + esd = b"\x03" + bytes([3 + len(dcd) + 3]) + b"\x00\x00\x00" + dcd + b"\x06\x01\x02" + + def ber(n): + out = [n & 127] + n >>= 7 + while n: + out.insert(0, 128 | (n & 127)) + n >>= 7 + return bytes(out) + + def chunk(t, body): + return t + struct.pack(">q", len(body)) + body + + desc = struct.pack(">d4sIIIII", rate, b"aac ", 2, 0, 1024, ch, 0) + pakt = struct.pack(">qqii", len(frames), len(frames) * 1024, 0, 0) + b"".join(ber(len(f)) for f in frames) + data = b"\x00\x00\x00\x00" + b"".join(frames) + return b"caff\x00\x01\x00\x00" + chunk(b"desc", desc) + chunk(b"kuki", b"\x00\x00\x00\x00" + esd) + chunk(b"pakt", pakt) + chunk(b"data", data) + + +def generate(ctx): + d = tempfile.mkdtemp(prefix="m4a-fx-") + try: + # --- ALAC from ffmpeg: lossless, the decode must equal the source integers + alac = [] + for name, frames, ch, rate, bits, container in ( + ("alac16_stereo.m4a", 10000, 2, 44100, 16, "m4a"), + ("alac16_mono.m4a", 4097, 1, 8000, 16, "m4a"), + ("alac24_stereo.m4a", 6000, 2, 96000, 24, "m4a"), + ("alac16_6ch.m4a", 5000, 6, 48000, 16, "m4a"), + ("alac16_stereo.caf", 9000, 2, 44100, 16, "caf"), + ): + ints = signal(frames, ch, bits, 11 + frames) + with open(os.path.join(d, "in.wav"), "wb") as f: + f.write(wav(ints, ch, rate, bits)) + fmt = "-sample_fmt s32p" if bits == 24 else "" + run(ctx, "ffmpeg -v error -y -i in.wav -c:a alac %s %s" % (fmt, name), d) + with open(os.path.join(d, name), "rb") as f: + data = f.read() + alac.append({"name": name, "data": data, "container": container, "channels": ch, "rate": rate, + "bits": bits, "frames": frames, "crc": crc_ints(ints)}) + ctx.emit("m4a_alac", alac) + + # --- AAC from ffmpeg / faac: our decode against ffmpeg's float decode + aac = [] + specs = ( + # name, frames, channels, rate, encoder command (in.wav -> name) + ("aac_stereo_128k.m4a", 60000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 128k -aac_pns 0 %s"), + ("aac_mono_22k.m4a", 30000, 1, 22050, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 48k %s"), + ("aac_51_48k.m4a", 30000, 6, 48000, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 256k %s"), + ("aac_tools_40k.m4a", 50000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 40k -aac_pns 1 -aac_is 1 -aac_ms 1 -aac_tns 1 %s"), + ("aac_8k_mono.m4a", 12000, 1, 8000, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 16k %s"), + ("aac_96k.m4a", 30000, 2, 96000, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 192k %s"), + ("aac_stereo.aac", 40000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 96k -aac_pns 0 -f adts %s"), + ("fdk_stereo.aac", 40000, 2, 44100, "fdkaac -S -b 96000 -f 2 -o %s in.wav"), + ("fdk_mono_32k.aac", 20000, 1, 32000, "fdkaac -S -b 48000 -f 2 -o %s in.wav"), + ("fdk_stereo.m4a", 40000, 2, 48000, "fdkaac -S -b 128000 -o %s in.wav"), + ("aac_stereo.caf", 30000, 2, 44100, "ffmpeg -v error -y -i in.wav -c:a aac -b:a 96k -f adts %s.adts"), + ) + for name, frames, ch, rate, cmd in specs: + ints = music(frames, ch, rate, frames + ch) + with open(os.path.join(d, "in.wav"), "wb") as f: + f.write(wav(ints, ch, rate, 16)) + run(ctx, cmd % name, d) + if name.endswith(".caf"): + # ffmpeg cannot write AAC in CAF: wrap its ADTS frames ourselves (desc, kuki esds, pakt, data) + with open(os.path.join(d, name + ".adts"), "rb") as f: + adts = f.read() + with open(os.path.join(d, name), "wb") as f: + f.write(adts_to_caf(adts)) + with open(os.path.join(d, name), "rb") as f: + data = f.read() + ref = run(ctx, "ffmpeg -v error -i %s -f f32le -c:a pcm_f32le -" % name, d) + container = "caf" if name.endswith(".caf") else ("adts" if name.endswith(".aac") else "m4a") + aac.append({"name": name, "data": data, "container": container, "channels": ch, "rate": rate, + "frames": len(ref) // (4 * ch), "ref": ref}) + ctx.emit("m4a_aac", aac) + # HE-AAC (SBR) and HE-AACv2 (SBR + PS) from fdkaac: we decode the AAC-LC core at the core rate + he = [] + for name, frames, ch, rate, prof, br in (("he_aac.m4a", 48000, 2, 44100, 5, 48000), ("he_aac_v2.m4a", 48000, 2, 44100, 29, 32000), ("he_aac.aac", 48000, 2, 44100, 5, 48000)): + ints = music(frames, ch, rate, 99) + with open(os.path.join(d, "in.wav"), "wb") as f: + f.write(wav(ints, ch, rate, 16)) + run(ctx, "fdkaac -S -p %d -b %d %s -o %s in.wav" % (prof, br, "-f 2" if name.endswith(".aac") else "", name), d) + with open(os.path.join(d, name), "rb") as f: + he.append({"name": name, "data": f.read(), "rate": rate, "ps": prof == 29}) + ctx.emit("m4a_he", he) + + # --- our writers, checked by ffmpeg / ffprobe / MP4Box + luau = os.environ.get("LUAU") or shutil.which("luau") + if luau: + out = subprocess.run([luau, "tools/fixtures/_m4a_encode.luau"], capture_output=True, check=True, cwd=ctx.root).stdout + else: + out = ctx.nix("luau", ["luau", os.path.join(ctx.root, "tools/fixtures/_m4a_encode.luau")]) + ours = [] + meta = { + # name -> frames, channels, bits, seed (tests/audio/_encode_cases.luau) + "ours_alac16_stereo": (4096 * 3 + 1234, 2, 16, 1), "ours_alac16_mono": (5000, 1, 16, 2), + "ours_alac24_stereo": (9000, 2, 24, 3), "ours_alac16_6ch": (4500, 6, 16, 4), + "ours_alac20_stereo": (3000, 2, 20, 5), "ours_caf_alac16": (7000, 2, 16, 6), + "ours_caf_pcm16": (3000, 2, 16, 7), "ours_caf_pcm24": (2000, 1, 24, 8), + } + for line in out.decode().split("\n"): + if not line.strip(): + continue + name, hx = line.split(" ", 1) + if hx.startswith("ERROR"): + raise RuntimeError("m4a fixtures: our encoder failed on %s: %s" % (name, hx)) + data = bytes.fromhex(hx) + ext = "caf" if "caf" in name else "m4a" + path = name + "." + ext + with open(os.path.join(d, path), "wb") as f: + f.write(data) + frames, ch, bits, seed = meta[name] + ints = signal(frames, ch, bits, seed) + wide = bits > 16 + want = pack([v << (32 - bits) for v in ints] if wide else ints, 32 if wide else 16) + got = run(ctx, "ffmpeg -v error -i %s -f %s -" % (path, "s32le" if wide else "s16le"), d) + fbytes = (4 if wide else 2) * ch + # ffmpeg's CAF reader drops the pakt remainder from a partial last ALAC packet (also on its own files): + # accept its output when it is an exact prefix of ours + ok = got == want or (ext == "caf" and len(got) > 0 and want.startswith(got)) + probe = json.loads(run(ctx, "ffprobe -v error -show_format -show_streams -of json %s" % path, d)) + tags = {k.lower(): v for k, v in probe["format"].get("tags", {}).items()} + mp4box = True + if ext == "m4a": + try: + run(ctx, "MP4Box -info %s >/dev/null 2>&1" % path, d) + except subprocess.CalledProcessError: + mp4box = False + ours.append({"name": name, "crc": zlib.crc32(data), "ffmpeg": ok, "frames": len(got) // fbytes, + "tags": tags, "mp4box": mp4box, + "codec": probe["streams"][0]["codec_name"]}) + ctx.emit("m4a_ours", ours) + finally: + shutil.rmtree(d, ignore_errors=True) From a7ed692156bd420c37539aedb737eb0f12643b75 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:04:03 -0500 Subject: [PATCH 5/7] ws-m4a: bench lines (AAC-LC / ALAC decode, ALAC encode, MDCT; bench.sh also builds the m4a fixtures); m4a decoder bitrate from the sample sizes --- src/Formats/audio/m4a/init.luau | 8 ++++--- tools/bench.luau | 39 +++++++++++++++++++++++++++++++++ tools/bench.sh | 2 +- 3 files changed, 45 insertions(+), 4 deletions(-) diff --git a/src/Formats/audio/m4a/init.luau b/src/Formats/audio/m4a/init.luau index 39e9589..5962197 100644 --- a/src/Formats/audio/m4a/init.luau +++ b/src/Formats/audio/m4a/init.luau @@ -194,7 +194,7 @@ function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E channels = channels, frames = frames, duration = frames / sr, - bitrate = if movie.duration > 0 then math.floor((r.limit - r.base) * 8 / math.max(frames / sr, 1e-9)) else 0, + bitrate = 0, tags = tags, pictures = pictures, codec = t.codec, @@ -202,9 +202,11 @@ function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E movie = movie, error = nil, } - if t.bitrate then - dec.bitrate = t.bitrate + local bytes = 0 + for i = 1, t.sampleCount do + bytes += t.sizes[i] end + dec.bitrate = if frames > 0 then math.floor(bytes * 8 * sr / frames) else (t.bitrate or 0) -- decode the next packet into pend; false at the end / on an error local function fill(): boolean diff --git a/tools/bench.luau b/tools/bench.luau index 9f6aef7..6519e45 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -56,3 +56,42 @@ do Png.encode(img) end) end + +-- ws-m4a: AAC-LC / ALAC decode and ALAC encode (MB/s of 16-bit PCM equivalent: frames * channels * 2), MDCT +do + local M4a = require("@formats/audio/m4a") + local Alac = require("@formats/codecs/Alac") + local Mdct = require("@formats/codecs/Mdct") + local MA = require("@tests/gen/m4a_aac") + local ML = require("@tests/gen/m4a_alac") + local aac = buffer.fromstring(MA[1].data) + local a = assert(M4a.decode(Bytes.reader(aac))) + bench("aac-lc decode (m4a, stereo)", 3, a.frames * a.channels * 2, function() + M4a.decode(Bytes.reader(aac)) + end) + local alac = buffer.fromstring(ML[1].data) + local l = assert(M4a.decode(Bytes.reader(alac))) + bench("alac decode (m4a, stereo 16)", 3, l.frames * l.channels * 2, function() + M4a.decode(Bytes.reader(alac)) + end) + local enc = assert(Alac.encoder({ sampleRate = 44100, channels = 2, bitDepth = 16 })) + local ints = table.create(a.frames * 2, 0) + for i = 1, a.frames * 2 do + ints[i] = math.floor(buffer.readf32(a.samples, (i - 1) * 4) * 32767) + end + bench("alac encode (stereo 16)", 2, a.frames * 2 * 2, function() + local f = 0 + while f < a.frames do + local n = math.min(4096, a.frames - f) + enc:encode(ints, f * 2 + 1, n) + f += n + end + end) + local plan = assert(Mdct.new(2048)) + local x, X = table.create(2048, 0.5), table.create(1024, 0) + bench("mdct 2048 x 1000 (forward)", 3, 1000 * 2048 * 4, function() + for _ = 1, 1000 do + Mdct.forward(plan, x, 1, X, 1) + end + end) +end diff --git a/tools/bench.sh b/tools/bench.sh index c5dea4a..6a99db6 100644 --- a/tools/bench.sh +++ b/tools/bench.sh @@ -3,7 +3,7 @@ cd "$(dirname "$0")/.." || exit 1 LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')} LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')} -python3 -I tools/fixtures.py deflate png > /dev/null || exit 1 +python3 -I tools/fixtures.py deflate png m4a > /dev/null || exit 1 python3 -I tools/build.py luajit > /dev/null || exit 1 "$LUAU" --codegen -O2 tools/bench.luau "$LUAJIT" -e 'package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path' build/luajit/tools/bench.lua From 84d45c81900a0147ed87c58913cda9129194e598 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:22:52 -0500 Subject: [PATCH 6/7] ws-m4a: CELT-only Opus encoder in audio/opus (RangeEncoder + CeltEncoder ported from the libopus 1.6 encoder paths to mirror the absorbed decoder: 20 ms full-band CBR, mono and mid/side stereo, silence frames; Encode: Ogg Opus with OpusHead/OpusTags, end trimming, 48 kHz resampling); checked by opusdec / opusinfo / ffmpeg; Opus.caps.encode = true (opus test updated), deps += codecs/Mdct --- docs/FORMATS.md | 2 +- licenses/NOTICE.md | 1 + src/Formats/Registry.luau | 4 +- src/Formats/audio/opus/CeltEncoder.luau | 1078 ++++++++++++++++++++++ src/Formats/audio/opus/Encode.luau | 181 ++++ src/Formats/audio/opus/RangeEncoder.luau | 252 +++++ src/Formats/audio/opus/init.luau | 18 +- tests/audio/_opus_cases.luau | 42 + tests/audio/opus.luau | 2 +- tests/audio/opus_encode.luau | 114 +++ tools/bench.luau | 10 + tools/fixtures/_opus_encode.luau | 17 + tools/fixtures/opus_celt.py | 48 + 13 files changed, 1761 insertions(+), 8 deletions(-) create mode 100644 src/Formats/audio/opus/CeltEncoder.luau create mode 100644 src/Formats/audio/opus/Encode.luau create mode 100644 src/Formats/audio/opus/RangeEncoder.luau create mode 100644 tests/audio/_opus_cases.luau create mode 100644 tests/audio/opus_encode.luau create mode 100644 tools/fixtures/_opus_encode.luau create mode 100644 tools/fixtures/opus_celt.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index a1b8835..56ef2f2 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -12,7 +12,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | flac | .flac .oga | yes | - | streaming: true, depths: 4, 8, 12, 16, 20, 24, 32, ogg: true, seek: true | `tests/audio/flac.luau` | | audio | m4a | .m4a .m4b .m4r .aac.mp4 | yes | yes | codecs: "aac", "alac", encodeCodecs: "alac", tags: true, streaming: true | `tests/audio/m4a.luau` | | audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | - | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` | -| audio | opus | .opus | yes | - | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000 | `tests/audio/opus.luau` | +| audio | opus | .opus | yes | yes | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000, encodeModes: "celt" | `tests/audio/opus.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | | archive | zip | .zip .wsz | yes | yes | methods: "store", "deflate", zip64: true | `tests/archive/zip.luau` | | playlist | m3u | .m3u .m3u8 | yes | yes | hls: true | `tests/playlist/m3u.luau` | diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index f3a49b2..b1c5c7b 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -16,6 +16,7 @@ | `src/Formats/playlist/` (m3u, pls; xspf is new), `src/Formats/codecs/Url/`, `src/Formats/codecs/Text/` | playlist-luau 3fc7fd3 (same author), written from RFC 3986 / RFC 8216 | no licence chosen yet; no third-party code | | `src/Formats/codecs/Aac/Tables.luau` | the Huffman codebooks, scalefactor band offsets and TNS limits of ISO/IEC 14496-3 (Annex 4.A), transcribed mechanically from FFmpeg's `libavcodec/aactab.c` (tables of the standard only; no FFmpeg code) | FFmpeg is LGPL-2.1-or-later; the tables are the standard's data | | `src/Formats/codecs/Aac/`, `codecs/Alac/`, `codecs/Mdct/`, `containers/IsoBmff/`, `audio/m4a`, `audio/aac`, `audio/caf` | written for this library from ISO/IEC 14496-3 / 14496-12 / 23008-12, Apple's ALAC and CAF specifications | no third-party code | +| `src/Formats/audio/opus/CeltEncoder.luau`, `src/Formats/audio/opus/RangeEncoder.luau` | the encoder side of libopus 1.6 (celt_encoder.c, entenc.c, quant_bands.c, laplace.c, rate.c, bands.c, vq.c, cwrs.c), ported to mirror the absorbed decoder; analysis simplified (ws-m4a) | libopus BSD 3-clause: [libopus-BSD.txt](libopus-BSD.txt) | | `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index b20418f..689c4e2 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -104,8 +104,8 @@ local list: { Entry } = { path = "audio/opus", extensions = { "opus" }, mime = { "audio/opus", "audio/ogg" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" }, - caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 } }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" }, + caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" } }, load = function() return require("@formats/audio/opus") end, diff --git a/src/Formats/audio/opus/CeltEncoder.luau b/src/Formats/audio/opus/CeltEncoder.luau new file mode 100644 index 0000000..7c8225a --- /dev/null +++ b/src/Formats/audio/opus/CeltEncoder.luau @@ -0,0 +1,1078 @@ +--!strict +--!native +--!optimize 2 +-- audio/opus/CeltEncoder: a fixed-frame CELT encoder (RFC 6716 section 5.3): 20 ms frames (LM 3), full band, constant +-- bit rate, long MDCTs only (no transient detection), no pitch pre-filter, normal spreading, default allocation trim, +-- mono, or stereo as mid / side per band (the angle, intensity when it has no bits; dual L / R stereo on request). The bitstream side is a port of the libopus 1.6 encoder paths +-- (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 T = require("@formats/audio/opus/CeltTables") +local Mdct = require("@formats/codecs/Mdct") + +local CeltEncoder = {} + +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local min, max, sqrt, floor, cos, log, atan2 = math.min, math.max, math.sqrt, math.floor, math.cos, math.log, math.atan2 +local encBitLogp, encIcdf, encBits, encUint, encEncode, encEncodeBin = RE.bitLogp, RE.icdf, RE.bits, RE.uint, RE.encode, RE.encodeBin +local tell, tellFrac = RE.tell, RE.tellFrac + +local NB_EBANDS = 21 +local OVERLAP = 120 +local SHORT_MDCT = 120 +local BITRES = 3 +local MAX_FINE_BITS = 8 +local FINE_OFFSET = 21 +local QTHETA_OFFSET = 4 +local PREEMPH = 0.85000610 +local LM = 3 -- 20 ms frames +local M = 8 +local N = 960 + +local EB = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100 } +local ALLOC = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0, 0, 0, 0, + 110, 100, 90, 84, 78, 71, 65, 58, 51, 45, 39, 32, 26, 20, 12, 0, 0, 0, 0, 0, 0, + 118, 110, 103, 93, 86, 80, 75, 70, 65, 59, 53, 47, 40, 31, 23, 15, 4, 0, 0, 0, 0, + 126, 119, 112, 104, 95, 89, 83, 78, 72, 66, 60, 54, 47, 39, 32, 25, 17, 12, 1, 0, 0, + 134, 127, 120, 114, 103, 97, 91, 85, 78, 72, 66, 60, 54, 47, 41, 35, 29, 23, 16, 10, 1, + 144, 137, 130, 124, 113, 107, 101, 95, 88, 82, 76, 70, 64, 57, 51, 45, 39, 33, 26, 15, 1, + 152, 145, 138, 132, 123, 117, 111, 105, 98, 92, 86, 80, 74, 67, 61, 55, 49, 43, 36, 20, 1, + 162, 155, 148, 142, 133, 127, 121, 115, 108, 102, 96, 90, 84, 77, 71, 65, 59, 53, 46, 30, 1, + 172, 165, 158, 152, 143, 137, 131, 125, 118, 112, 106, 100, 94, 87, 81, 75, 69, 63, 56, 45, 20, + 200, 200, 200, 200, 200, 200, 200, 200, 198, 193, 188, 183, 178, 173, 168, 163, 158, 153, 148, 129, 104, +} +local NB_ALLOC_VECTORS = 11 +local LOG2_FRAC_TABLE = { 0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37 } +local LOGN = T.logN400 +local CACHE_INDEX = T.cache_index50 +local CACHE_BITS = T.cache_bits50 +local CACHE_CAPS = T.cache_caps50 +local E_PROB = T.e_prob_model +local E_MEANS = { + 6.437500, 6.250000, 5.750000, 5.312500, 5.062500, 4.812500, 4.500000, 4.375000, 4.875000, 4.687500, + 4.562500, 4.437500, 4.875000, 4.625000, 4.312500, 4.500000, 4.375000, 4.625000, 4.750000, 4.437500, + 3.750000, +} +local PRED_COEF = { 29440 / 32768, 26112 / 32768, 21248 / 32768, 16384 / 32768 } +local BETA_COEF = { 30147 / 32768, 22282 / 32768, 12124 / 32768, 6554 / 32768 } +local BETA_INTRA = 4915 / 32768 +local TF_SELECT = { 0, -2, 0, -3, 3, 0, 1, -1 } -- LM 3 +local TRIM_ICDF = { 126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0 } +local SPREAD_ICDF = { 25, 23, 2, 0 } +local SMALL_ENERGY_ICDF = { 2, 1, 0 } +local EXP2_TABLE8 = { 16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048 } +local SPREAD_NORMAL = 2 +local SPREAD_FACTOR = { 15, 10, 5 } + +-- the MDCT window (the decoder's) and plan +local WINDOW = table.create(OVERLAP, 0) +for i = 0, OVERLAP - 1 do + local s = math.sin(0.5 * math.pi * (i + 0.5) / OVERLAP) + WINDOW[i + 1] = math.sin(0.5 * math.pi * s * s) +end +local PLAN = Mdct.new(2 * N) :: Mdct.Plan +-- forward scale matching the decoder's backward MDCT (calibrated against audio/opus/Mdct: tests/audio/opus_encode) +local MDCT_SCALE = 2 / N + +-- PVQ codebook sizes U(n, k), flat: U[n * UK + k + 1] +local UK = 177 +local U = table.create(UK * UK, 0) +U[1] = 1 +for n = 1, UK - 1 do + for k = 1, UK - 1 do + U[n * UK + k + 1] = U[(n - 1) * UK + k + 1] + U[n * UK + k] + U[(n - 1) * UK + k] + end +end +local function pvqU(n: number, k: number): number + return U[n * UK + k + 1] +end + +local function imin(a: number, b: number): number + return if a < b then a else b +end +local function imax(a: number, b: number): number + return if a > b then a else b +end +local function tdiv(a: number, b: number): number + local q = a / b + return if q >= 0 then floor(q) else -floor(-q) +end +local function fracMul16(a: number, b: number): number + return (16384 + a * b) // 32768 +end +local function bitexactCos(x: number): number + local x2 = (4096 + x * x) // 8192 + x2 = (32767 - x2) + fracMul16(x2, (-7651 + fracMul16(x2, (8277 + fracMul16(-626, x2))))) + return 1 + x2 +end +local function bitexactLog2tan(isin: number, icos: number): number + local lc = RE.ilog(icos) + local ls = RE.ilog(isin) + icos = icos * 2 ^ (15 - lc) + isin = isin * 2 ^ (15 - ls) + return (ls - lc) * 2048 + fracMul16(isin, fracMul16(isin, -2597) + 7932) - fracMul16(icos, fracMul16(icos, -2597) + 7932) +end + +-- ------------------------------------------------------------------------------------------------ energy +-- ec_laplace_encode: returns the value actually coded (clamped in the flat tail) +local function laplaceEncode(enc: RE.Enc, value: number, fs: number, decay: number): number + local fl = 0 + local val = value + if val ~= 0 then + local s = if val < 0 then -1 else 0 + val = if val < 0 then -val else val + fl = fs + fs = ((32768 - 32 - fs) * (16384 - decay)) // 32768 -- ec_laplace_get_freq1 + local i = 1 + while fs > 0 and i < val do + fs *= 2 + fl += fs + 2 + fs = (fs * decay) // 32768 + i += 1 + end + if fs == 0 then + local ndiMax = 32768 - fl + 1 - 1 + ndiMax = rshift(ndiMax - s, 1) + local di = imin(val - i, ndiMax - 1) + fl += (2 * di + 1 + s) + fs = imin(1, 32768 - fl) + value = if s ~= 0 then -(i + di) else i + di + else + fs += 1 + if s == 0 then + fl += fs + end + end + end + encEncodeBin(enc, fl, fl + fs, 15) + return value +end + +export type State = { + channels: number, + oldBandE: { number }, -- the decoder's view (2 * 21) + preMem: { number }, + inMem: { { number } }, -- the last OVERLAP pre-emphasised samples per channel + frames: number, + X: { { number } }, -- per channel 960 normalised coefficients + bandLogE: { number }, + bandE: { number }, -- linear band amplitudes (intensity stereo weights) + error: { number }, + work: { number }, + tmp: { number }, + iy: { number }, + remaining: number, + spread: number, + dual: boolean, -- stereo: L / R coded independently (default false: mid / side) +} + +-- new(channels) -> State +function CeltEncoder.new(channels: number): State + local inMem = {} + local X = {} + for c = 1, channels do + inMem[c] = table.create(OVERLAP, 0) + X[c] = table.create(N, 0) + end + return { + channels = channels, + oldBandE = table.create(2 * NB_EBANDS, 0), + preMem = table.create(channels, 0), + inMem = inMem, + frames = 0, + X = X, + bandLogE = table.create(2 * NB_EBANDS, 0), + bandE = table.create(2 * NB_EBANDS, 0), + error = table.create(2 * NB_EBANDS, 0), + work = table.create(2 * N, 0), + tmp = table.create(2 * N, 0), + iy = table.create(256, 0), + remaining = 0, + spread = SPREAD_NORMAL, + dual = false, + } +end + +local function quantCoarseEnergy(st: State, intra: boolean, enc: RE.Enc, C: number, budget: number, nbBytes: number) + local oldE, bandLogE, err = st.oldBandE, st.bandLogE, st.error + local probBase = LM * 84 + (if intra then 42 else 0) + local coef, beta + if intra then + coef, beta = 0, BETA_INTRA + else + coef, beta = PRED_COEF[LM + 1], BETA_COEF[LM + 1] + end + local maxDecay = min(16, nbBytes / 8) + local prev0, prev1 = 0, 0 + for i = 0, NB_EBANDS - 1 do + for c = 0, C - 1 do + local k = c * NB_EBANDS + i + 1 + local x = bandLogE[k] + local e = max(-9, oldE[k]) + local prev = if c == 0 then prev0 else prev1 + local f = x - coef * e - prev + local qi = floor(0.5 + f) + local decayBound = max(-28, oldE[k]) - maxDecay + if qi < 0 and x < decayBound then + qi += tdiv(decayBound - x, 1) + if qi > 0 then + qi = 0 + end + end + local t = tell(enc) + local bitsLeft = budget - t - 3 * C * (NB_EBANDS - i) + if i ~= 0 and bitsLeft < 30 then + if bitsLeft < 24 then + qi = imin(1, qi) + end + if bitsLeft < 16 then + qi = imax(-1, qi) + end + end + if budget - t >= 15 then + local pi = 2 * imin(i, 20) + qi = laplaceEncode(enc, qi, E_PROB[probBase + pi + 1] * 128, E_PROB[probBase + pi + 2] * 64) + elseif budget - t >= 2 then + qi = imax(-1, imin(qi, 1)) + encIcdf(enc, if qi < 0 then 1 else 2 * qi, SMALL_ENERGY_ICDF, 2) + elseif budget - t >= 1 then + qi = imin(0, qi) + encBitLogp(enc, qi ~= 0, 1) + else + qi = -1 + end + err[k] = f - qi + oldE[k] = coef * e + prev + qi + prev = prev + qi - beta * qi + if c == 0 then + prev0 = prev + else + prev1 = prev + end + end + end +end + +local function quantFineEnergy(st: State, fineQuant: { number }, enc: RE.Enc, C: number) + local oldE, err = st.oldBandE, st.error + for i = 0, NB_EBANDS - 1 do + local extra = fineQuant[i + 1] + if extra <= 0 then + continue + end + if tell(enc) + C * extra > enc.storage * 8 then + continue + end + local frac = 2 ^ extra + for c = 0, C - 1 do + local k = c * NB_EBANDS + i + 1 + local q2 = floor((err[k] + 0.5) * frac) + q2 = math.clamp(q2, 0, frac - 1) + encBits(enc, q2, extra) + local offset = (q2 + 0.5) * 2 ^ (14 - extra) * (1 / 16384) - 0.5 + oldE[k] += offset + err[k] -= offset + end + end +end + +local function quantEnergyFinalise(st: State, fineQuant: { number }, finePriority: { number }, bitsLeft: number, enc: RE.Enc, C: number) + local oldE, err = st.oldBandE, st.error + for prio = 0, 1 do + local i = 0 + while i < NB_EBANDS and bitsLeft >= C do + if fineQuant[i + 1] >= MAX_FINE_BITS or finePriority[i + 1] ~= prio then + i += 1 + continue + end + for c = 0, C - 1 do + local k = c * NB_EBANDS + i + 1 + local q2 = if err[k] < 0 then 0 else 1 + encBits(enc, q2, 1) + local offset = (q2 - 0.5) * 2 ^ (14 - fineQuant[i + 1] - 1) * (1 / 16384) + oldE[k] += offset + err[k] -= offset + bitsLeft -= 1 + end + i += 1 + end + end +end + +-- ------------------------------------------------------------------------------------------------ allocation +local function bits2pulses(bandI: number, lm: number, bits: number): number + local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] + local lo, hi = 0, CACHE_BITS[base + 1] + bits -= 1 + for _ = 1, 6 do + local mid = rshift(lo + hi + 1, 1) + if CACHE_BITS[base + mid + 1] >= bits then + hi = mid + else + lo = mid + end + end + local loBits = if lo == 0 then -1 else CACHE_BITS[base + lo + 1] + if bits - loBits <= CACHE_BITS[base + hi + 1] - bits then + return lo + end + return hi +end + +local function pulses2bits(bandI: number, lm: number, pulses: number): number + if pulses == 0 then + return 0 + end + local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] + return CACHE_BITS[base + pulses + 1] + 1 +end + +local function getPulses(i: number): number + if i < 8 then + return i + end + return lshift(8 + band(i, 7), rshift(i, 3) - 1) +end + +-- clt_compute_allocation (encoder side): keeps every band it can, no intensity stereo, dual stereo for C == 2 +local function computeAllocation(offsets: { number }, cap: { number }, allocTrim: number, total: number, + pulses: { number }, ebits: { number }, finePriority: { number }, C: number, enc: RE.Enc, wantDual: boolean) + local start, endb = 0, NB_EBANDS + total = imax(total, 0) + local len = NB_EBANDS + local skipStart = start + local skipRsv = if total >= 8 then 8 else 0 + total -= skipRsv + local intensityRsv, dualStereoRsv = 0, 0 + if C == 2 then + intensityRsv = LOG2_FRAC_TABLE[endb - start + 1] + if intensityRsv > total then + intensityRsv = 0 + else + total -= intensityRsv + dualStereoRsv = if total >= 8 then 8 else 0 + total -= dualStereoRsv + end + end + local bits1, bits2, thresh, trimOffset = {}, {}, {}, {} + for j = start, endb - 1 do + local w = EB[j + 2] - EB[j + 1] + thresh[j + 1] = imax(C * 8, (3 * w * 2 ^ LM * 8) // 16) + trimOffset[j + 1] = (C * w * (allocTrim - 5 - LM) * (endb - j - 1) * 2 ^ (LM + BITRES)) // 64 + if w * 2 ^ LM == 1 then + trimOffset[j + 1] -= C * 8 + end + end + local lo, hi = 1, NB_ALLOC_VECTORS - 1 + repeat + local done = false + local psum = 0 + local mid = rshift(lo + hi, 1) + for j = endb - 1, start, -1 do + local Nw = EB[j + 2] - EB[j + 1] + local bitsj = (C * Nw * ALLOC[mid * len + j + 1] * 2 ^ LM) // 4 + if bitsj > 0 then + bitsj = imax(0, bitsj + trimOffset[j + 1]) + end + bitsj += offsets[j + 1] + if bitsj >= thresh[j + 1] or done then + done = true + psum += imin(bitsj, cap[j + 1]) + elseif bitsj >= C * 8 then + psum += C * 8 + end + end + if psum > total then + hi = mid - 1 + else + lo = mid + 1 + end + until lo > hi + hi = lo + lo -= 1 + for j = start, endb - 1 do + local Nw = EB[j + 2] - EB[j + 1] + local bits1j = (C * Nw * ALLOC[lo * len + j + 1] * 2 ^ LM) // 4 + local bits2j = if hi >= NB_ALLOC_VECTORS then cap[j + 1] else (C * Nw * ALLOC[hi * len + j + 1] * 2 ^ LM) // 4 + if bits1j > 0 then + bits1j = imax(0, bits1j + trimOffset[j + 1]) + end + if bits2j > 0 then + bits2j = imax(0, bits2j + trimOffset[j + 1]) + end + if lo > 0 then + bits1j += offsets[j + 1] + end + bits2j += offsets[j + 1] + if offsets[j + 1] > 0 then + skipStart = j + end + bits2j = imax(0, bits2j - bits1j) + bits1[j + 1] = bits1j + bits2[j + 1] = bits2j + end + -- interp_bits2pulses + local bits = pulses + local allocFloor = C * 8 + local stereo = if C > 1 then 1 else 0 + local logM = LM * 8 + lo, hi = 0, 64 + for _ = 1, 6 do + local mid = rshift(lo + hi, 1) + local psum = 0 + local done = false + for j = endb - 1, start, -1 do + local tmp = bits1[j + 1] + (mid * bits2[j + 1]) // 64 + if tmp >= thresh[j + 1] or done then + done = true + psum += imin(tmp, cap[j + 1]) + elseif tmp >= allocFloor then + psum += allocFloor + end + end + if psum > total then + hi = mid + else + lo = mid + end + end + local psum = 0 + local done = false + for j = endb - 1, start, -1 do + local tmp = bits1[j + 1] + (lo * bits2[j + 1]) // 64 + if tmp < thresh[j + 1] and not done then + if tmp >= allocFloor then + tmp = allocFloor + else + tmp = 0 + end + else + done = true + end + tmp = imin(tmp, cap[j + 1]) + bits[j + 1] = tmp + psum += tmp + end + local codedBands = endb + while true do + local j = codedBands - 1 + if j <= skipStart then + total += skipRsv + break + end + local left = total - psum + local percoeff = left // (EB[codedBands + 1] - EB[start + 1]) + left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff + local rem = imax(left - (EB[j + 1] - EB[start + 1]), 0) + local bandWidth = EB[codedBands + 1] - EB[j + 1] + local bandBits = bits[j + 1] + percoeff * bandWidth + rem + if bandBits >= imax(thresh[j + 1], allocFloor + 8) then + -- keep every band that can be coded: signal "no more skipping" + encBitLogp(enc, true, 1) + break + end + psum -= bits[j + 1] + intensityRsv + if intensityRsv > 0 then + intensityRsv = LOG2_FRAC_TABLE[j - start + 1] + end + psum += intensityRsv + if bandBits >= allocFloor then + psum += allocFloor + bits[j + 1] = allocFloor + else + bits[j + 1] = 0 + end + codedBands -= 1 + end + local intensity, dualStereo = 0, false + if intensityRsv > 0 then + intensity = codedBands -- no intensity stereo + encUint(enc, intensity - start, codedBands + 1 - start) + end + if intensity <= start then + total += dualStereoRsv + dualStereoRsv = 0 + end + if dualStereoRsv > 0 then + dualStereo = wantDual + encBitLogp(enc, dualStereo, 1) + end + local left = total - psum + local percoeff = left // (EB[codedBands + 1] - EB[start + 1]) + left -= (EB[codedBands + 1] - EB[start + 1]) * percoeff + for j = start, codedBands - 1 do + bits[j + 1] += percoeff * (EB[j + 2] - EB[j + 1]) + end + for j = start, codedBands - 1 do + local tmp = imin(left, EB[j + 2] - EB[j + 1]) + bits[j + 1] += tmp + left -= tmp + end + local balance = 0 + local j = start + while j < codedBands do + local N0 = EB[j + 2] - EB[j + 1] + local Nw = N0 * 2 ^ LM + local bit = bits[j + 1] + balance + local excess + if Nw > 1 then + excess = imax(bit - cap[j + 1], 0) + bits[j + 1] = bit - excess + local den = C * Nw + (if C == 2 and Nw > 2 and not dualStereo and j < intensity then 1 else 0) + local NClogN = den * (LOGN[j + 1] + logM) + local offset = (NClogN // 2) - den * FINE_OFFSET + if Nw == 2 then + offset += (den * 8) // 4 + end + if bits[j + 1] + offset < den * 2 * 8 then + offset += NClogN // 4 + elseif bits[j + 1] + offset < den * 3 * 8 then + offset += NClogN // 8 + end + local eb = imax(0, bits[j + 1] + offset + den * 4) + eb = (eb // den) // 8 + if C * eb > (bits[j + 1] // 8) then + eb = (bits[j + 1] // 2 ^ stereo) // 8 + end + eb = imin(eb, MAX_FINE_BITS) + finePriority[j + 1] = if eb * (den * 8) >= bits[j + 1] + offset then 1 else 0 + bits[j + 1] -= C * eb * 8 + ebits[j + 1] = eb + else + excess = imax(0, bit - C * 8) + bits[j + 1] = bit - excess + ebits[j + 1] = 0 + finePriority[j + 1] = 1 + end + if excess > 0 then + local extraFine = imin(excess // 2 ^ (stereo + BITRES), MAX_FINE_BITS - ebits[j + 1]) + ebits[j + 1] += extraFine + local extraBits = extraFine * C * 8 + finePriority[j + 1] = if extraBits >= excess - balance then 1 else 0 + excess -= extraBits + end + balance = excess + j += 1 + end + while j < endb do + ebits[j + 1] = (bits[j + 1] // 2 ^ stereo) // 8 + bits[j + 1] = 0 + finePriority[j + 1] = if ebits[j + 1] < 1 then 1 else 0 + j += 1 + end + return codedBands, balance, intensity, dualStereo +end + +-- ------------------------------------------------------------------------------------------------ PVQ +-- icwrs: the index of the pulse vector iy[1..n] +local function icwrs(n: number, iy: { number }): number + local j = n -- 1-based position of _y[n - 1] + local i = if iy[j] < 0 then 1 else 0 + local k = math.abs(iy[j]) + repeat + j -= 1 + local nn = n - (j - 1) -- _n - j with 0-based j + i += pvqU(nn, k) + k += math.abs(iy[j]) + if iy[j] < 0 then + i += pvqU(nn, k + 1) + end + until j <= 1 + return i +end + +local function expRotation1(X: { number }, xo: number, len: number, stride: number, c: number, s: number) + local ms = -s + local p = xo + 1 + for _ = 0, len - stride - 1 do + local x1 = X[p] + local x2 = X[p + stride] + X[p + stride] = c * x2 + s * x1 + X[p] = c * x1 + ms * x2 + p += 1 + end + p = xo + len - 2 * stride + for _ = len - 2 * stride - 1, 0, -1 do + local x1 = X[p] + local x2 = X[p + stride] + X[p + stride] = c * x2 + s * x1 + X[p] = c * x1 + ms * x2 + p -= 1 + end +end + +-- exp_rotation(X, len, dir = 1, stride, K, spread): the encoder's spreading rotation +local function expRotation(X: { number }, xo: number, len: number, stride: number, K: number, spread: number) + if 2 * K >= len or spread == 0 then + return + end + local factor = SPREAD_FACTOR[spread] + local gain = len / (len + factor * K) + local theta = 0.5 * (gain * gain) + local c = cos(0.5 * math.pi * theta) + local s = cos(0.5 * math.pi * (1 - theta)) + local stride2 = 0 + if len >= 8 * stride then + stride2 = 1 + while (stride2 * stride2 + stride2) * stride + rshift(stride, 2) < len do + stride2 += 1 + end + end + len = len // stride + for i = 0, stride - 1 do + local x = xo + i * len + expRotation1(X, x, len, 1, c, -s) + if stride2 ~= 0 then + expRotation1(X, x, len, stride2, s, -c) + end + end +end + +-- op_pvq_search: the K-pulse vector closest to X[xo + 1 .. xo + n] into iy[1..n] +local function pvqSearch(X: { number }, xo: number, n: number, K: number, iy: { number }, y: { number }, absx: { number }) + local sign = y -- reuse: y holds 2 * |pulses| during the search, signs kept in absx's sign + local xy, yy = 0, 0 + local pulsesLeft = K + for j = 1, n do + local v = X[xo + j] + absx[j] = if v < 0 then -v else v + sign[j] = 0 + iy[j] = 0 + end + if K > rshift(n, 1) then + local sum = 0 + for j = 1, n do + sum += absx[j] + end + if not (sum > 1e-15 and sum < 64) then + absx[1] = 1 + for j = 2, n do + absx[j] = 0 + end + sum = 1 + end + local rcp = (K + 0.8) / sum + for j = 1, n do + local p = floor(rcp * absx[j]) + iy[j] = p + yy += p * p + xy += absx[j] * p + sign[j] = 2 * p + pulsesLeft -= p + end + end + if pulsesLeft > n + 3 then + yy += pulsesLeft * pulsesLeft + pulsesLeft * sign[1] + iy[1] += pulsesLeft + pulsesLeft = 0 + end + for _ = 1, pulsesLeft do + yy += 1 + local best = 1 + local rxy = xy + absx[1] + local bestNum = rxy * rxy + local bestDen = yy + sign[1] + for j = 2, n do + rxy = xy + absx[j] + local num = rxy * rxy + local den = yy + sign[j] + if bestDen * num > den * bestNum then + bestDen, bestNum, best = den, num, j + end + end + xy += absx[best] + yy += sign[best] + sign[best] += 2 + iy[best] += 1 + end + for j = 1, n do + if X[xo + j] < 0 then + iy[j] = -iy[j] + end + end +end + +local SCRATCH_Y = table.create(256, 0) +local SCRATCH_A = table.create(256, 0) +local ROT = table.create(256, 0) + +local function algQuant(st: State, X: { number }, xo: number, n: number, K: number, enc: RE.Enc) + -- rotate a copy (the original band stays for nothing else, but keep it intact) + for j = 1, n do + ROT[j] = X[xo + j] + end + expRotation(ROT, 0, n, 1, K, st.spread) + local iy = st.iy + pvqSearch(ROT, 0, n, K, iy, SCRATCH_Y, SCRATCH_A) + encUint(enc, icwrs(n, iy), pvqU(n, K) + pvqU(n, K + 1)) +end + +-- ------------------------------------------------------------------------------------------------ bands +local function computeQn(n: number, b: number, offset: number, pulseCap: number): number + local N2 = 2 * n - 1 + local qb = tdiv(b + N2 * offset, N2) + qb = imin(b - pulseCap - 32, qb) + qb = imin(64, qb) + if qb < 4 then + return 1 + end + local qn = rshift(EXP2_TABLE8[band(qb, 7) + 1], 14 - rshift(qb, 3)) + return lshift(rshift(qn + 1, 1), 1) +end + +-- quant_partition (encoder, B = 1, mono): returns nothing (no resynthesis) +local function quantPartition(st: State, bandI: number, X: { number }, xo: number, n: number, b: number, lm: number, enc: RE.Enc) + local split = false + if lm ~= -1 and n > 2 then + local base = CACHE_INDEX[(lm + 1) * NB_EBANDS + bandI + 1] + split = b > CACHE_BITS[base + CACHE_BITS[base + 1] + 1] + 12 + end + if split then + n = rshift(n, 1) + local yo = xo + n + lm -= 1 + -- compute_theta (mono split, B0 = 1: triangular pdf) + local pulseCap = LOGN[bandI + 1] + lm * 8 + local offset = (pulseCap // 2) - QTHETA_OFFSET + local qn = computeQn(n, b, offset, pulseCap) + local t0 = tellFrac(enc) + local itheta = 0 + if qn ~= 1 then + local emid, eside = 1e-15, 1e-15 + for j = 1, n do + emid += X[xo + j] * X[xo + j] + eside += X[yo + j] * X[yo + j] + end + local it = floor(0.5 + 16384 * 0.63662 * atan2(sqrt(eside), sqrt(emid))) + itheta = (it * qn + 8192) // 16384 + local h = rshift(qn, 1) + local ft = (h + 1) * (h + 1) + local fs = if itheta <= h then itheta + 1 else qn + 1 - itheta + local fl = if itheta <= h then rshift(itheta * (itheta + 1), 1) else ft - rshift((qn + 1 - itheta) * (qn + 2 - itheta), 1) + encEncode(enc, fl, fl + fs, ft) + itheta = (itheta * 16384) // qn + end + local qalloc = tellFrac(enc) - t0 + b -= qalloc + local delta + if itheta == 0 then + delta = -16384 + elseif itheta == 16384 then + delta = 16384 + else + local imid = bitexactCos(itheta) + local iside = bitexactCos(16384 - itheta) + delta = fracMul16((n - 1) * 128, bitexactLog2tan(iside, imid)) + end + local mbits = imax(0, imin(b, tdiv(b - delta, 2))) + local sbits = b - mbits + st.remaining -= qalloc + local rebalance = st.remaining + if mbits >= sbits then + quantPartition(st, bandI, X, xo, n, mbits, lm, enc) + rebalance = mbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 0 then + sbits += rebalance - 24 + end + quantPartition(st, bandI, X, yo, n, sbits, lm, enc) + else + quantPartition(st, bandI, X, yo, n, sbits, lm, enc) + rebalance = sbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 16384 then + mbits += rebalance - 24 + end + quantPartition(st, bandI, X, xo, n, mbits, lm, enc) + end + else + local q = bits2pulses(bandI, lm, b) + local currBits = pulses2bits(bandI, lm, q) + st.remaining -= currBits + while st.remaining < 0 and q > 0 do + st.remaining += currBits + q -= 1 + currBits = pulses2bits(bandI, lm, q) + st.remaining -= currBits + end + if q ~= 0 then + algQuant(st, X, xo, n, getPulses(q), enc) + end + end +end + +-- quant_band_stereo (encoder, N > 2, B = 1): the mid / side angle (step pdf), then mid and side as mono bands; +-- qn == 1 falls back to intensity stereo (with the inversion bit when there is room) +local function quantBandStereo(st: State, i: number, n: number, xo: number, b: number, enc: RE.Enc) + local L, R = st.X[1], st.X[2] + local pulseCap = LOGN[i + 1] + LM * 8 + local offset = (pulseCap // 2) - QTHETA_OFFSET + local qn = computeQn(n, b, offset, pulseCap) + -- stereo_itheta: the angle between mid and side energies + local emid, eside = 1e-15, 1e-15 + for j = 1, n do + local m = 0.5 * L[xo + j] + 0.5 * R[xo + j] + local sd = 0.5 * L[xo + j] - 0.5 * R[xo + j] + emid += m * m + eside += sd * sd + end + local itheta = floor(0.5 + 16384 * 0.63662 * atan2(sqrt(eside), sqrt(emid))) + local t0 = tellFrac(enc) + local function intensityStereo() + local left, right = st.bandE[i + 1], st.bandE[NB_EBANDS + i + 1] + local norm = 1e-15 + sqrt(1e-15 + left * left + right * right) + local a1, a2 = left / norm, right / norm + for j = 1, n do + L[xo + j] = a1 * L[xo + j] + a2 * R[xo + j] + end + end + if qn ~= 1 then + itheta = (itheta * qn + 8192) // 16384 + local p0 = 3 + local x0 = qn // 2 + local ft = p0 * (x0 + 1) + x0 + if itheta <= x0 then + encEncode(enc, p0 * itheta, p0 * (itheta + 1), ft) + else + encEncode(enc, (itheta - 1 - x0) + (x0 + 1) * p0, (itheta - x0) + (x0 + 1) * p0, ft) + end + itheta = (itheta * 16384) // qn + if itheta == 0 then + intensityStereo() + else + -- stereo_split: mid / side + for j = 1, n do + local l = 0.70710678 * L[xo + j] + local r = 0.70710678 * R[xo + j] + L[xo + j] = l + r + R[xo + j] = r - l + end + end + else + local inv = itheta > 8192 + if inv then + for j = 1, n do + R[xo + j] = -R[xo + j] + end + end + intensityStereo() + if b > 16 and st.remaining > 16 then + encBitLogp(enc, inv, 2) + end + itheta = 0 + end + local qalloc = tellFrac(enc) - t0 + b -= qalloc + local delta + if itheta == 0 then + delta = -16384 + elseif itheta == 16384 then + delta = 16384 + else + local imid = bitexactCos(itheta) + local iside = bitexactCos(16384 - itheta) + delta = fracMul16((n - 1) * 128, bitexactLog2tan(iside, imid)) + end + local mbits = imax(0, imin(b, tdiv(b - delta, 2))) + local sbits = b - mbits + st.remaining -= qalloc + local rebalance = st.remaining + if mbits >= sbits then + quantPartition(st, i, L, xo, n, mbits, LM, enc) + rebalance = mbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 0 then + sbits += rebalance - 24 + end + quantPartition(st, i, R, xo, n, sbits, LM, enc) + else + quantPartition(st, i, R, xo, n, sbits, LM, enc) + rebalance = sbits - (rebalance - st.remaining) + if rebalance > 24 and itheta ~= 16384 then + mbits += rebalance - 24 + end + quantPartition(st, i, L, xo, n, mbits, LM, enc) + end +end + +-- quant_all_bands (encoder): mono, dual stereo or mid / side stereo +local function quantAllBands(st: State, C: number, pulses: { number }, dualStereo: boolean, totalBits: number, + balance: number, enc: RE.Enc, codedBands: number, intensity: number) + for i = 0, NB_EBANDS - 1 do + local xo = M * EB[i + 1] + local nb = M * EB[i + 2] - M * EB[i + 1] + local t = tellFrac(enc) + if i ~= 0 then + balance -= t + end + local remainingBits = totalBits - t - 1 + st.remaining = remainingBits + local b + if i <= codedBands - 1 then + local currBalance = tdiv(balance, imin(3, codedBands - i)) + b = imax(0, imin(16383, imin(remainingBits + 1, pulses[i + 1] + currBalance))) + else + b = 0 + end + if dualStereo and i == intensity then + dualStereo = false + end + if C == 2 and dualStereo then + quantPartition(st, i, st.X[1], xo, nb, b // 2, LM, enc) + quantPartition(st, i, st.X[2], xo, nb, b // 2, LM, enc) + elseif C == 2 then + quantBandStereo(st, i, nb, xo, b, enc) + else + quantPartition(st, i, st.X[1], xo, nb, b, LM, enc) + end + balance += pulses[i + 1] + t + end +end + +-- ------------------------------------------------------------------------------------------------ frame +-- encodeFrame(st, pcm, base, stride, nbBytes) -> buffer: one CELT frame of nbBytes from 960 samples per channel +-- (pcm[base + k * stride + c], floats -1 .. 1, interleaved) +function CeltEncoder.encodeFrame(st: State, pcm: { number }, base: number, stride: number, nbBytes: number): buffer + local C = st.channels + local work, tmp = st.work, st.tmp + local silent = true + -- pre-emphasis, the windowed 1920-sample MDCT input, band energies, normalisation + for c = 1, C do + local inMem = st.inMem[c] + local m = st.preMem[c] + -- tmp[1..1080] = the last 120 pre-emphasised samples + this frame's 960 + for k = 1, OVERLAP do + tmp[k] = inMem[k] + end + for k = 0, N - 1 do + local x = pcm[base + k * stride + c - 1] * 32768 + if x ~= 0 then + silent = false + end + tmp[OVERLAP + k + 1] = x - m + m = PREEMPH * x + end + st.preMem[c] = m + for k = 1, OVERLAP do + inMem[k] = tmp[N + k] + end + local q = 420 -- (2N - (N + OVERLAP)) / 2 zeros at each end + for k = 1, q do + work[k] = 0 + work[2 * N - k + 1] = 0 + end + for k = 1, OVERLAP do + work[q + k] = tmp[k] * WINDOW[k] + work[q + N + k] = tmp[N + k] * WINDOW[OVERLAP - k + 1] + end + for k = OVERLAP + 1, N do + work[q + k] = tmp[k] + end + local X = st.X[c] + Mdct.forward(PLAN, work, 1, X, 1, 1, MDCT_SCALE) + for i = 0, NB_EBANDS - 1 do + local a, z = M * EB[i + 1] + 1, M * EB[i + 2] + local s = 1e-27 + for k = a, z do + s += X[k] * X[k] + end + local E = sqrt(s) + st.bandE[(c - 1) * NB_EBANDS + i + 1] = E + st.bandLogE[(c - 1) * NB_EBANDS + i + 1] = log(E) / log(2) - E_MEANS[i + 1] + local g = 1 / (1e-27 + E) + for k = a, z do + X[k] *= g + end + end + end + local enc = RE.new(nbBytes) + local totalBits = nbBytes * 8 + local oldE = st.oldBandE + -- silence + if silent then + encBitLogp(enc, true, 15) + enc.nbits_total += totalBits - tell(enc) + RE.done(enc) + for i = 1, 2 * NB_EBANDS do + oldE[i] = -28 + end + st.frames += 1 + return enc.buf + end + encBitLogp(enc, false, 15) + if tell(enc) + 16 <= totalBits then + encBitLogp(enc, false, 1) -- no post-filter + end + if tell(enc) + 3 <= totalBits then + encBitLogp(enc, false, 3) -- not transient + end + local intra = st.frames == 0 + if tell(enc) + 3 <= totalBits then + encBitLogp(enc, intra, 3) + else + intra = false + end + if C == 1 then + for i = 1, NB_EBANDS do + oldE[i] = max(oldE[i], oldE[NB_EBANDS + i]) + end + end + quantCoarseEnergy(st, intra, enc, C, totalBits, nbBytes) + -- tf_encode: no changes + do + local budget = totalBits + local tt = tell(enc) + local logp = 4 + if tt + logp + 1 <= budget then + budget -= 1 + end + for _ = 0, NB_EBANDS - 1 do + if tt + logp <= budget then + encBitLogp(enc, false, logp) + tt = tell(enc) + end + logp = 5 + end + -- tf_select is only coded when it changes something: not for LM 3 without changes + local _ = TF_SELECT + end + if tell(enc) + 4 <= totalBits then + encIcdf(enc, st.spread, SPREAD_ICDF, 5) + end + local cap = {} + for i = 0, NB_EBANDS - 1 do + local Nw = (EB[i + 2] - EB[i + 1]) * 2 ^ LM + cap[i + 1] = rshift((CACHE_CAPS[NB_EBANDS * (2 * LM + C - 1) + i + 1] + 64) * C * Nw, 2) + end + local offsets = table.create(NB_EBANDS, 0) + local total8 = totalBits * 8 + local t = tellFrac(enc) + for i = 0, NB_EBANDS - 1 do + if t + 6 * 8 < total8 and 0 < cap[i + 1] then + encBitLogp(enc, false, 6) -- no dynamic allocation boost + t = tellFrac(enc) + end + end + if t + 48 <= total8 then + encIcdf(enc, 5, TRIM_ICDF, 7) + end + local bits = nbBytes * 64 - tellFrac(enc) - 1 + local pulses, fineQuant, finePriority = table.create(NB_EBANDS, 0), table.create(NB_EBANDS, 0), table.create(NB_EBANDS, 0) + local codedBands, balance, intensity, dualStereo = computeAllocation(offsets, cap, 5, bits, pulses, fineQuant, finePriority, C, enc, st.dual) + quantFineEnergy(st, fineQuant, enc, C) + quantAllBands(st, C, pulses, dualStereo, nbBytes * 64, balance, enc, codedBands, intensity) + quantEnergyFinalise(st, fineQuant, finePriority, totalBits - tell(enc), enc, C) + RE.done(enc) + if C == 1 then + for i = 1, NB_EBANDS do + oldE[NB_EBANDS + i] = oldE[i] + end + end + st.frames += 1 + st.lastError = enc.error + return enc.buf +end + +CeltEncoder.FRAME = N +CeltEncoder.DELAY = OVERLAP -- the decoder's output lags the input by the MDCT overlap +return CeltEncoder diff --git a/src/Formats/audio/opus/Encode.luau b/src/Formats/audio/opus/Encode.luau new file mode 100644 index 0000000..13e4c05 --- /dev/null +++ b/src/Formats/audio/opus/Encode.luau @@ -0,0 +1,181 @@ +--!strict +-- 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. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Ogg = require("@formats/containers/Ogg") +local CeltEncoder = require("@formats/audio/opus/CeltEncoder") + +local Encode = {} + +export type Options = { + bitrate: number?, -- bits per second (default 64000 per channel; 6000 .. 510000, constant) + tags: { [string]: string }?, -- default: the audio's tags + vendor: string?, -- OpusTags vendor (default "formats-luau") + 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", +} + +-- 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") + end + local ch = value.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 + if rate < 1000 or rate > 768000 then + return nil, Err.new(Err.ARG, "bad sample rate " .. tostring(rate)) + end + local bitrate = o.bitrate or 64000 * ch + 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") + 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") + 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) + end + local FRAME = CeltEncoder.FRAME + local preSkip = CeltEncoder.DELAY + local packets = (n48 + preSkip + FRAME - 1) // FRAME + -- zero padding to whole frames + for i = n48 * ch + 1, packets * FRAME * ch do + pcm[i] = 0 + end + local bytes = math.clamp(floor(bitrate * FRAME / 48000 / 8), if ch == 2 then 40 else 20, 1275 - 1) + local st = CeltEncoder.new(ch) + local mux = Ogg.muxer({ pageSize = 4096 }) + local s = mux:stream(o.serial or 0x4f707573) + -- OpusHead + local head = Bytes.writer(19) + head:string("OpusHead") + head:u8(1) + head:u8(ch) + head:u16le(preSkip) + head:u32le(floor(rate)) + head:u16le(0) + head:u8(0) + s:packet(head:finish(), 0, { flush = true }) + -- OpusTags + local tags = o.tags or value.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] + tw:u32le(#field) + tw:string(field) + end + s:packet(tw:finish(), 0, { flush = true }) + -- audio + local toc = 31 * 8 + (if ch == 2 then 4 else 0) + for p = 0, packets - 1 do + local frame = CeltEncoder.encodeFrame(st, pcm, p * FRAME * ch + 1, ch, bytes) + local pkt = buffer.create(bytes + 1) + buffer.writeu8(pkt, 0, toc) + buffer.copy(pkt, 1, frame, 0, bytes) + local last = p == packets - 1 + local granule = if last then preSkip + n48 else (p + 1) * FRAME + s:packet(pkt, granule, { eos = last }) + end + return mux:finish(), nil +end + +return Encode diff --git a/src/Formats/audio/opus/RangeEncoder.luau b/src/Formats/audio/opus/RangeEncoder.luau new file mode 100644 index 0000000..13bf3c6 --- /dev/null +++ b/src/Formats/audio/opus/RangeEncoder.luau @@ -0,0 +1,252 @@ +--!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 +-- 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 = {} + +export type Enc = { + buf: buffer, + storage: number, + offs: number, + end_offs: number, + end_window: number, + nend_bits: number, + nbits_total: number, + rng: number, + val: number, + rem: number, + ext: number, + error: number, +} + +local CODE_TOP = 2147483648 -- 1 << 31 +local CODE_BOT = 8388608 -- CODE_TOP >> 8 +local CODE_SHIFT = 23 +local SYM_MAX = 255 + +local countlz = bit32.countlz +local band = bit32.band +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local floor = math.floor + +local function ilog(x: number): number + return 32 - countlz(x) +end +RangeEncoder.ilog = ilog + +-- new(storage) -> Enc over a fresh zeroed buffer of storage bytes +function RangeEncoder.new(storage: number): Enc + return { + buf = buffer.create(math.max(storage, 1)), + storage = storage, + offs = 0, + end_offs = 0, + end_window = 0, + nend_bits = 0, + nbits_total = 33, -- EC_CODE_BITS + 1 + rng = CODE_TOP, + val = 0, + rem = -1, + ext = 0, + error = 0, + } +end + +local function writeByte(e: Enc, v: number) + if e.offs + e.end_offs >= e.storage then + e.error = -1 + return + end + writeu8(e.buf, e.offs, band(v, 255)) + e.offs += 1 +end + +local function writeByteAtEnd(e: Enc, v: number) + if e.offs + e.end_offs >= e.storage then + e.error = -1 + return + end + e.end_offs += 1 + writeu8(e.buf, e.storage - e.end_offs, band(v, 255)) +end + +local function carryOut(e: Enc, c: number) + if c ~= SYM_MAX then + local carry = if c >= 256 then 1 else 0 + if e.rem >= 0 then + writeByte(e, e.rem + carry) + end + if e.ext > 0 then + local sym = band(SYM_MAX + carry, 255) + repeat + writeByte(e, sym) + e.ext -= 1 + until e.ext <= 0 + end + e.rem = band(c, 255) + else + e.ext += 1 + end +end + +local function normalize(e: Enc) + while e.rng <= CODE_BOT do + carryOut(e, floor(e.val / 8388608)) + e.val = (e.val * 256) % CODE_TOP + e.rng *= 256 + e.nbits_total += 8 + end +end + +-- encode(fl, fh, ft): the symbol [fl, fh) of ft +function RangeEncoder.encode(e: Enc, fl: number, fh: number, ft: number) + local r = floor(e.rng / ft) + if fl > 0 then + e.val += e.rng - r * (ft - fl) + e.rng = r * (fh - fl) + else + e.rng -= r * (ft - fh) + end + normalize(e) +end + +-- encodeBin(fl, fh, bits): ft = 2^bits +function RangeEncoder.encodeBin(e: Enc, fl: number, fh: number, bits: number) + local ft = 2 ^ bits + local r = floor(e.rng / ft) + if fl > 0 then + e.val += e.rng - r * (ft - fl) + e.rng = r * (fh - fl) + else + e.rng -= r * (ft - fh) + end + normalize(e) +end + +-- bitLogp(v, logp): a bit whose probability of being 1 is 2^-logp +function RangeEncoder.bitLogp(e: Enc, v: boolean, logp: number) + local r = e.rng + local s = floor(r / 2 ^ logp) + r -= s + if v then + e.val += r + e.rng = s + else + e.rng = r + end + normalize(e) +end + +-- icdf(s, icdf, ftb): symbol s (0-based) of an inverse CDF table (1-based Luau array) with 2^ftb total +function RangeEncoder.icdf(e: Enc, s: number, icdf: { number }, ftb: number) + local r = floor(e.rng / 2 ^ ftb) + if s > 0 then + e.val += e.rng - r * icdf[s] + e.rng = r * (icdf[s] - icdf[s + 1]) + else + e.rng -= r * icdf[s + 1] + end + normalize(e) +end + +-- bits(fl, n): n raw bits (n <= 25), written from the end of the frame +function RangeEncoder.bits(e: Enc, fl: number, n: number) + local window = e.end_window + local used = e.nend_bits + if used + n > 32 then + repeat + writeByteAtEnd(e, window % 256) + window = floor(window / 256) + used -= 8 + until used < 8 + end + window += fl * 2 ^ used + used += n + e.end_window = window + e.nend_bits = used + e.nbits_total += n +end + +-- uint(fl, ft): fl uniformly in [0, ft), ft up to 2^32 +function RangeEncoder.uint(e: Enc, fl: number, ft: number) + ft -= 1 + local ftb = ilog(ft) + if ftb > 8 then + ftb -= 8 + local sh = 2 ^ ftb + local ft1 = floor(ft / sh) + 1 + local hi = floor(fl / sh) + RangeEncoder.encode(e, hi, hi + 1, ft1) + RangeEncoder.bits(e, fl - hi * sh, ftb) + else + RangeEncoder.encode(e, fl, fl + 1, ft + 1) + end +end + +function RangeEncoder.tell(e: Enc): number + return e.nbits_total - ilog(e.rng) +end + +local CORRECTION = { 35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535 } +function RangeEncoder.tellFrac(e: Enc): number + local nbits = e.nbits_total * 8 + local l = ilog(e.rng) + local r = floor(e.rng / 2 ^ (l - 16)) + local b = floor(r / 4096) - 8 + if r > CORRECTION[b + 1] then + b += 1 + end + return nbits - (l * 8 + b) +end + +-- done(): flush; the frame is e.buf (storage bytes) +function RangeEncoder.done(e: Enc) + local l = 32 - ilog(e.rng) + local msk = floor((CODE_TOP - 1) / 2 ^ l) + local stop = floor((e.val + msk) / (msk + 1)) * (msk + 1) + if stop + msk >= e.val + e.rng then + l += 1 + msk = floor(msk / 2) + stop = floor((e.val + msk) / (msk + 1)) * (msk + 1) + end + while l > 0 do + carryOut(e, floor(stop / 8388608)) + stop = (stop * 256) % CODE_TOP + l -= 8 + end + if e.rem >= 0 or e.ext > 0 then + carryOut(e, 0) + end + local window = e.end_window + local used = e.nend_bits + while used >= 8 do + writeByteAtEnd(e, window % 256) + window = floor(window / 256) + used -= 8 + end + if e.error == 0 then + local a, b = e.offs, e.storage - e.end_offs + if b > a then + buffer.fill(e.buf, a, 0, b - a) + end + if used > 0 then + if e.end_offs >= e.storage then + e.error = -1 + else + l = -l + if e.offs + e.end_offs >= e.storage and l < used then + window = window % 2 ^ l + e.error = -1 + end + local p = e.storage - e.end_offs - 1 + writeu8(e.buf, p, bit32.bor(readu8(e.buf, p), window)) + end + end + end +end + +local _ = CODE_SHIFT +return RangeEncoder diff --git a/src/Formats/audio/opus/init.luau b/src/Formats/audio/opus/init.luau index 08852eb..2d80432 100644 --- a/src/Formats/audio/opus/init.luau +++ b/src/Formats/audio/opus/init.luau @@ -5,14 +5,17 @@ -- Supports: decode of every Opus mode / bandwidth / frame size, mono, stereo and surround (optional stereo downmix, -- opts.stereo), pre-skip, end trimming, output gain, OpusTags, sample-accurate seeking (granule bisection + 80 ms -- pre-roll), damaged files (concealment). Output is always 48 kHz f32. --- Not supported: encoding, mapping family 3 (ambisonics projection), chained streams (the first Opus stream is --- decoded), CELT pitch PLC (noise PLC only). +-- Encoding (audio/opus/Encode + CeltEncoder, ws-m4a): a CELT-only fixed-frame encoder (20 ms, full band, constant +-- bit rate, mono or dual stereo; other input rates resampled to 48 kHz) writing Ogg Opus with OpusTags. +-- Not supported: SILK / hybrid encoding, transients / pitch pre-filter in the encoder, mapping family 3 (ambisonics +-- projection), chained streams (the first Opus stream is decoded), CELT pitch PLC (noise PLC only). -- Changes from opus-luau: the injected Ogg demuxer is containers/Ogg; errors are core/Err values; read() takes an -- optional output buffer; decode() fully decodes to an Audio. -- -- local dec, err = Opus.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(n, out?), dec:seek(s), ... -- local audio = Opus.decode(Bytes.reader(buf)) -- a Types.Audio -- Opus.Decoder.new(channels) + Opus.Decoder.decode(st, buf, off, len, pcm, base, maxFrames) -- raw packets +-- local file = Opus.encode(audio, { bitrate = 96000 }) -- Ogg Opus (CELT only) -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") @@ -24,6 +27,7 @@ local Packet = require("@formats/audio/opus/Packet") local RangeDecoder = require("@formats/audio/opus/RangeDecoder") local Celt = require("@formats/audio/opus/Celt") local Silk = require("@formats/audio/opus/Silk") +local Encode = require("@formats/audio/opus/Encode") -- ------------------------------------------------------------------------------------------------ contract local Opus = { @@ -31,8 +35,8 @@ local Opus = { category = "audio", extensions = { "opus" }, mime = { "audio/opus", "audio/ogg" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg" }, - caps = { decode = true, encode = false, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 } }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" }, + caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" } }, } -- ------------------------------------------------------------------------------------------------ types @@ -213,6 +217,12 @@ function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?) return a, nil end +-- ------------------------------------------------------------------------------------------------ encode +-- encode(audio | decoder, opts?) -> Ogg Opus buffer | nil, Err (CELT only; see audio/opus/Encode) +function Opus.encode(value: any, opts: Encode.Options?): (buffer?, Err.Err?) + return Encode.encode(value, opts) +end + -- ------------------------------------------------------------------------------------------------ open local Stream = {} Stream.__index = Stream diff --git a/tests/audio/_opus_cases.luau b/tests/audio/_opus_cases.luau new file mode 100644 index 0000000..1163827 --- /dev/null +++ b/tests/audio/_opus_cases.luau @@ -0,0 +1,42 @@ +-- tests/audio/_opus_cases: the inputs of the CELT encoder reference check (tools/fixtures/opus_celt.py runs +-- tools/fixtures/_opus_encode.luau over them; tests/audio/opus_encode.luau re-encodes and compares): a deterministic +-- music-like signal (chord + vibrato + chirp + clicks + a silent stretch) at a given rate / channel count. +local Types = require("@formats/Types") + +local Cases = {} + +Cases.list = { + { name = "celt_mono_64k", rate = 48000, channels = 1, seconds = 1.5, bitrate = 64000, minSnr = 15 }, + { name = "celt_stereo_128k", rate = 48000, channels = 2, seconds = 1.5, bitrate = 128000, minSnr = 15 }, + { name = "celt_stereo_256k", rate = 48000, channels = 2, seconds = 1, bitrate = 256000, minSnr = 22 }, + { name = "celt_mono_24k", rate = 48000, channels = 1, seconds = 1, bitrate = 24000, minSnr = 8 }, + { name = "celt_44k_stereo_96k", rate = 44100, channels = 2, seconds = 1, bitrate = 96000, minSnr = 0, tags = { title = "Celt \u{e9}", artist = "formats-luau", album = "Opus" } }, + { name = "celt_short", rate = 48000, channels = 1, seconds = 0.01, bitrate = 48000, minSnr = -100 }, +} + +function Cases.signal(c: any): Types.Audio + local n = math.floor(c.seconds * c.rate + 0.5) + local a = Types.Audio.new(c.rate, c.channels, n) + local s = 7 + for i = 0, n - 1 do + local t = i / c.rate + for ch = 0, c.channels - 1 do + s = (s * 48271) % 2147483647 + local v = 0.18 * math.sin(2 * math.pi * 220 * t + 2 * math.sin(2 * math.pi * 5 * t)) + v += 0.12 * math.sin(2 * math.pi * (277.2 + ch * 2) * t) + 0.1 * math.sin(2 * math.pi * 329.6 * t) + v += 0.08 * math.sin(2 * math.pi * (1000 + 3000 * t) * t) + v += 0.01 * (s / 2147483647 - 0.5) + if i % (c.rate // 4) < 30 then + v += 0.4 * (if (i // 5) % 2 == 0 then 1 else -1) + end + if t > 0.6 and t < 0.75 then + v = 0 -- digital silence (the encoder's silence frames) + end + buffer.writef32(a.samples, (i * c.channels + ch) * 4, v) + end + end + a.tags = c.tags or {} + return a +end + +return Cases diff --git a/tests/audio/opus.luau b/tests/audio/opus.luau index c876dce..8403251 100644 --- a/tests/audio/opus.luau +++ b/tests/audio/opus.luau @@ -81,7 +81,7 @@ end -- ------------------------------------------------------------------------------------------------ contract t:eq(Opus.name, "opus", "name") t:eq(Opus.category, "audio", "category") -t:check(Opus.caps.decode and not Opus.caps.encode and Opus.open ~= nil and Opus.decode ~= nil, "caps") +t:check(Opus.caps.decode and Opus.caps.encode and Opus.open ~= nil and Opus.decode ~= nil and Opus.encode ~= nil, "caps (the CELT encoder: tests/audio/opus_encode.luau)") t:eq(Opus.sniff(Bytes.reader(FX.celt_st_128.data)), 1, "sniff an Opus file") t:eq(Opus.sniff(Bytes.reader(buffer.fromstring("OggS" .. string.rep("\0", 40)))), 0, "sniff another Ogg") t:eq(Opus.sniff(Bytes.reader(buffer.create(0))), 0, "sniff nothing") diff --git a/tests/audio/opus_encode.luau b/tests/audio/opus_encode.luau new file mode 100644 index 0000000..c3aeff4 --- /dev/null +++ b/tests/audio/opus_encode.luau @@ -0,0 +1,114 @@ +-- audio/opus encoder tests (the CELT-only writer, ws-m4a; mono and mid / side stereo): our Ogg Opus files (re-encoded here, compared with the bytes +-- checked in the fixture step) decode in libopus' opusdec to the input's exact length (pre-skip + end trimming) with a +-- minimum SNR, opusinfo finds no problem, ffmpeg reads them, OpusTags carry the tags; our decoder agrees with opusdec; +-- resampled 44.1 kHz input; silence frames; streaming input; errors; a fuzz no-throw pass over our files. +-- Fixtures: tools/fixtures/opus_celt.py. +local T = require("@tests/T") +local Opus = require("@formats/audio/opus") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Cases = require("@tests/audio/_opus_cases") +local Fx = require("@tests/gen/opus_celt") + +local t = T.suite("opus-encode") + +t:check(Opus.caps.encode and Opus.encode ~= nil, "caps: encode") + +local byName = {} +for _, f in Fx do + byName[f.name] = f +end + +local function snr(ref: buffer, refBase: number, got: buffer, n: number): number + local s, e = 0, 0 + for i = 0, n - 1 do + local x = buffer.readf32(ref, (refBase + i) * 4) + local d = buffer.readf32(got, (refBase + i) * 4) - x + s += x * x + e += d * d + end + return if e == 0 then math.huge else 10 * math.log10(s / math.max(e, 1e-30)) +end + +local files = {} +for _, c in Cases.list do + local fx = byName[c.name] + t:check(fx, c.name .. ": fixture") + local input = Cases.signal(c) + local file, err = Opus.encode(input, { bitrate = c.bitrate }) + t:check(file, c.name .. ": encode: " .. tostring(err)) + table.insert(files, file) + t:eq(string.format("%08x", Crc32.of(file :: buffer)), string.format("%08x", fx.crc), c.name .. ": the bytes the reference tools checked") + t:check(fx.opusinfo, c.name .. ": opusinfo reports no problem") + t:check(fx.ffmpeg, c.name .. ": ffmpeg decodes it") + local frames48 = math.floor(input.frames * 48000 / c.rate + 0.5) + local ch = c.channels + t:eq(#fx.opusdec // (4 * ch), frames48, c.name .. ": opusdec length = the input's (pre-skip + end trimming)") + t:eq(fx.ffmpegFrames, frames48, c.name .. ": ffmpeg length") + -- our decoder vs opusdec + local ours = Opus.decode(Bytes.reader(file :: buffer)) :: any + t:eq(ours.frames, frames48, c.name .. ": our decoder's length") + local ref = buffer.fromstring(fx.opusdec) + local agree = snr(ref, 0, ours.samples, frames48 * ch) + t:check(agree > 60, string.format("%s: our decoder vs opusdec %.1f dB", c.name, agree)) + -- quality vs the input (48 kHz inputs; skip the edges) + if c.rate == 48000 and frames48 > 4000 then + local s = snr(input.samples, 960 * ch, ref, (frames48 - 1920) * ch) + t:check(s >= c.minSnr, string.format("%s: SNR %.1f dB (minimum %d)", c.name, s, c.minSnr)) + t:note("%s: %d bytes, SNR %.1f dB vs the input, our decoder vs opusdec %.1f dB", c.name, buffer.len(file :: buffer), s, agree) + end + if c.tags then + for k, v in c.tags do + t:eq(fx.comments[k], v, c.name .. ": opusinfo comment " .. k) + t:eq(ours.tags[k], v, c.name .. ": our tag " .. k) + end + end +end + +-- silence frames decode to silence +do + local c = Cases.list[1] + local ref = buffer.fromstring(byName[c.name].opusdec) + local peak = 0 + for i = math.floor(0.62 * 48000), math.floor(0.73 * 48000) do + peak = math.max(peak, math.abs(buffer.readf32(ref, i * 4))) + end + t:check(peak < 1e-3, "digital silence stays silent (peak " .. peak .. ")") +end + +-- a streaming decoder as the input +do + local c = Cases.list[1] + local dec = Opus.open(Bytes.reader(files[1] :: buffer)) :: any + local again, err = Opus.encode(dec, { bitrate = 64000 }) + t:check(again, "encode from a decoder: " .. tostring(err)) + local back = Opus.decode(Bytes.reader(again :: buffer)) :: any + t:eq(back.frames, math.floor(c.seconds * 48000 + 0.5), "re-encoded length") +end + +-- errors +do + local three = Cases.signal({ rate = 48000, channels = 3, seconds = 0.05 }) + local _, e = Opus.encode(three) + t:check(e and e.code == Err.UNSUPPORTED, "3 channels: " .. tostring(e)) + local _, e2 = Opus.encode(Cases.signal(Cases.list[6]), { bitrate = 1000 }) + t:check(e2 and e2.code == Err.ARG, "bitrate too low") + local _, e3 = Opus.encode({} :: any) + t:check(e3 and e3.code == Err.ARG, "not audio") +end + +-- fuzz the decoder over our files +do + local samples = {} + for i, f in files do + if i <= 3 then + table.insert(samples, string.sub(buffer.tostring(f :: buffer), 1, 4000)) + end + end + t:fuzz("decode our files", function(b: buffer) + return Opus.decode(Bytes.reader(b)) + end, samples, { mutations = 10, garbage = 30 }) +end + +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index b2eea5d..1f5ed5f 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -184,3 +184,13 @@ do end end) end +do + local Opus = require("@formats/audio/opus") + local Cases = require("@tests/audio/_opus_cases") + local c = Cases.list[2] + local a = Cases.signal(c) + local dt = bench("opus celt encode 128k (1.5 s st)", 2, a.frames * a.channels * 2, function() + Opus.encode(a, { bitrate = 128000 }) + end) + local _ = dt +end diff --git a/tools/fixtures/_opus_encode.luau b/tools/fixtures/_opus_encode.luau new file mode 100644 index 0000000..a974148 --- /dev/null +++ b/tools/fixtures/_opus_encode.luau @@ -0,0 +1,17 @@ +-- tools/fixtures/_opus_encode: run by tools/fixtures/opus_celt.py (luau, from the repo root): encodes +-- tests/audio/_opus_cases with audio/opus's CELT encoder and prints " " lines for opusdec / ffmpeg. +local Opus = require("@formats/audio/opus") +local Cases = require("@tests/audio/_opus_cases") + +for _, c in Cases.list do + local out, err = Opus.encode(Cases.signal(c), { bitrate = c.bitrate }) + if not out then + print(c.name .. " ERROR " .. tostring(err)) + else + local t = table.create(buffer.len(out)) + for i = 0, buffer.len(out) - 1 do + t[i + 1] = string.format("%02x", buffer.readu8(out, i)) + end + print(c.name .. " " .. table.concat(t)) + end +end diff --git a/tools/fixtures/opus_celt.py b/tools/fixtures/opus_celt.py new file mode 100644 index 0000000..5db280b --- /dev/null +++ b/tools/fixtures/opus_celt.py @@ -0,0 +1,48 @@ +# The CELT encoder reference check (tools/fixtures.py): runs tools/fixtures/_opus_encode.luau (our encoder over +# tests/audio/_opus_cases.luau), then the reference tools through nix: opusdec --float (libopus), opusinfo (stream +# structure), ffmpeg (an independent Ogg / Opus reader). +# tests/gen/opus_celt.luau { { name, crc (of our bytes), opusdec (f32le 48 kHz decode), opusinfo (exit 0), +# ffmpeg (decoded), ffmpegFrames, comments (opusinfo's user comments) } } +import os, re, shutil, subprocess, tempfile, zlib + +INPUTS = ["src/Formats/audio/opus", "src/Formats/codecs/Mdct", "src/Formats/containers/Ogg", + "tests/audio/_opus_cases.luau", "tools/fixtures/_opus_encode.luau"] + + +def generate(ctx): + luau = os.environ.get("LUAU") or shutil.which("luau") + script = os.path.join(ctx.root, "tools/fixtures/_opus_encode.luau") + if luau: + out = subprocess.run([luau, script], capture_output=True, check=True, cwd=ctx.root).stdout + else: + out = ctx.nix("luau", ["luau", script]) + d = tempfile.mkdtemp(prefix="opus-celt-fx-") + try: + cases = [] + for line in out.decode().split("\n"): + if not line.strip(): + continue + name, hx = line.split(" ", 1) + if hx.startswith("ERROR"): + raise RuntimeError("opus_celt fixtures: our encoder failed on %s: %s" % (name, hx)) + data = bytes.fromhex(hx) + path = os.path.join(d, name + ".opus") + with open(path, "wb") as f: + f.write(data) + raw = os.path.join(d, name + ".f32") + ctx.nix("opus-tools", ["opusdec", "--quiet", "--float", "--rate", "48000", path, raw]) + with open(raw, "rb") as f: + pcm = f.read() + info = subprocess.run(["nix", "shell", "nixpkgs#opus-tools", "-c", "opusinfo", path], capture_output=True) + text = info.stdout.decode(errors="replace") + comments = {} + for m in re.finditer(r"^\s*([A-Za-z]+)=(.*)$", text, re.M): + comments[m.group(1).lower()] = m.group(2) + ok = info.returncode == 0 and "WARNING" not in text and "ERROR" not in text.upper().replace("ERRORS", "") + ff = subprocess.run(["nix", "shell", "nixpkgs#ffmpeg", "-c", "ffmpeg", "-v", "error", "-i", path, "-f", "f32le", "-ac", "1", "-"], capture_output=True) + cases.append({"name": name, "crc": zlib.crc32(data), "opusdec": pcm, "opusinfo": ok, + "ffmpeg": ff.returncode == 0 and len(ff.stderr) == 0, "ffmpegFrames": len(ff.stdout) // 4, + "comments": comments}) + ctx.emit("opus_celt", cases) + finally: + shutil.rmtree(d, ignore_errors=True) From 1749b9b9fcdf346dcb33cd2831dc6a16fa214be0 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:23:26 -0500 Subject: [PATCH 7/7] ws-m4a: m4a extensions (m4a, m4b, m4r) --- docs/FORMATS.md | 2 +- src/Formats/Registry.luau | 2 +- src/Formats/audio/m4a/init.luau | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 56ef2f2..db1f367 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -10,7 +10,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | aac | .aac .adts | yes | - | codecs: "aac", streaming: true | `tests/audio/aac.luau` | | audio | caf | .caf .caff | yes | yes | codecs: "pcm", "alac", "aac", "ulaw", "alaw", encodeCodecs: "pcm", "alac", tags: true, streaming: true | `tests/audio/caf.luau` | | audio | flac | .flac .oga | yes | - | streaming: true, depths: 4, 8, 12, 16, 20, 24, 32, ogg: true, seek: true | `tests/audio/flac.luau` | -| audio | m4a | .m4a .m4b .m4r .aac.mp4 | yes | yes | codecs: "aac", "alac", encodeCodecs: "alac", tags: true, streaming: true | `tests/audio/m4a.luau` | +| audio | m4a | .m4a .m4b .m4r | yes | yes | codecs: "aac", "alac", encodeCodecs: "alac", tags: true, streaming: true | `tests/audio/m4a.luau` | | audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | - | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` | | audio | opus | .opus | yes | yes | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000, encodeModes: "celt" | `tests/audio/opus.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 689c4e2..e5e11d2 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -78,7 +78,7 @@ local list: { Entry } = { name = "m4a", category = "audio", path = "audio/m4a", - extensions = { "m4a", "m4b", "m4r", "aac.mp4" }, + extensions = { "m4a", "m4b", "m4r" }, mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" }, deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac" }, caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true }, diff --git a/src/Formats/audio/m4a/init.luau b/src/Formats/audio/m4a/init.luau index 5962197..bf64abb 100644 --- a/src/Formats/audio/m4a/init.luau +++ b/src/Formats/audio/m4a/init.luau @@ -17,7 +17,7 @@ local Alac = require("@formats/codecs/Alac") local M4a = { name = "m4a", category = "audio", - extensions = { "m4a", "m4b", "m4r", "aac.mp4" }, + extensions = { "m4a", "m4b", "m4r" }, mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" }, deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac" }, caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true },